问:
How to normalize a table when I have a key pair type of data
I am making a platform where a trainer will be able to add courses to his profile. But before he adds course there needs to be an application acceptance that needs to be done.

So, I had earlier divided my database into three parts:

users | trainer | course

After a little bit of research, I found that I will have to do database normalization but I am having issues with setting it up.

Now I have trainer table trainer_experience table and trainer_achievements table. Inside trainer experience table I have to save data of the position they wore in and the company name.

My trainer table is this:

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTrainersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('trainers', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id');
            $table->date('date_of_birth');
            $table->integer('mobile_number');
            $table->longText('address');
            $table->string('id_proof');
            $table->string('id_registration_number');
            $table->string('high_school_name');
            $table->string('graduation_college_name');
            $table->string('graduation_course_name');
            $table->string('post_graduation_college_name');
            $table->string('post_graduation_course_name');
            $table->string('phd_field_of_study');
            $table->string('total_duration_of_training');
            $table->integer('no_of_people_trained');
            $table->boolean('paid_training');
            $table->string('training_category');
            $table->string('course_material_ready');
            $table->string('youtube_link')->nullable();
            $table->string('twitter_link')->nullable();
            $table->string('instagram_link')->nullable();
            $table->string('facebook_link')->nullable();
            $table->string('linkedin_link')->nullable();
            $table->string('blog_link')->nullable();
            $table->string('website_link')->nullable();
            $table->string('meetup_group_link')->nullable();
            $table->timestamps();

            $table->index('user_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('trainers');
    }
}

</code>```

How do I store the data so, that I can at least retrieve it in the order they have entered? Do I need to make two different tables? What is the best option that I have?

答:
You have to figure out in the data in trainer_experience and trainer_achievements is reusable or not ?

trainer_experience and trainer_achievements are dependent on each other?

Use Polymorphic relationship for best use.

Body:
I am making a platform where a trainer will be able to add courses to his profile. But before he adds course there needs to be an application acceptance that needs to be done.

So, I had earlier divided my database into three parts:

users | trainer | course

After a little bit of research, I found that I will have to do database normalization but I am having issues with setting it up.

Now I have trainer table trainer_experience table and trainer_achievements table. Inside trainer experience table I have to save data of the position they wore in and the company name.

My trainer table is this:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTrainersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('trainers', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id');
            $table->date('date_of_birth');
            $table->integer('mobile_number');
            $table->longText('address');
            $table->string('id_proof');
            $table->string('id_registration_number');
            $table->string('high_school_name');
            $table->string('graduation_college_name');
            $table->string('graduation_course_name');
            $table->string('post_graduation_college_name');
            $table->string('post_graduation_course_name');
            $table->string('phd_field_of_study');
            $table->string('total_duration_of_training');
            $table->integer('no_of_people_trained');
            $table->boolean('paid_training');
            $table->string('training_category');
            $table->string('course_material_ready');
            $table->string('youtube_link')->nullable();
            $table->string('twitter_link')->nullable();
            $table->string('instagram_link')->nullable();
            $table->string('facebook_link')->nullable();
            $table->string('linkedin_link')->nullable();
            $table->string('blog_link')->nullable();
            $table->string('website_link')->nullable();
            $table->string('meetup_group_link')->nullable();
            $table->timestamps();

            $table->index('user_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('trainers');
    }
}

How do I store the data so, that I can at least retrieve it in the order they have entered? Do I need to make two different tables? What is the best option that I have?


来源: stackexchange

问:
Cancel Grant ALL Request
I run this command

```<code>GRANT ALL PRIVILEGES ON *.* TO 'user'@'host';
</code>```

Now I would cancel this request without revoking the other rights of user database Is that possible?

答: the opposite of your GRANT statement is REVOKE ALL ON <em>.</em> TO 'user'@'host; </p>

ContentLicense: CC BY-SA 4.0

Title: Cancel Grant ALL Request

Body:
I run this command

GRANT ALL PRIVILEGES ON *.* TO 'user'@'host';

Now I would cancel this request without revoking the other rights of user database Is that possible?

Body: the opposite of your GRANT statement is REVOKE ALL ON . TO 'user'@'host;


问:
Get counts of rows for each joined table for each row in the main table
I have three tables in my database. The central table in the star schema is sendings with a PK column called id. Each sending record can have zero or more rows in the tables opens.

```<code>sendings.id = opens.sending_id
</code>```

Similarly, a third table called clicks have the following association to the sending table (one sending can have zero or more clicks):

```<code>sendings.id = clicks.sending_id
</code>```

Both opens and clicks tables have their unique id column, called id.
What I would like to have in one query, is the count of all associated opens and clicks for each sending. The following query does not seem to meet that demand.

```<code>select s.id,
    count(o.id) as open_count,
    count(c.id) as click_count
from sendings s
left join opens o on s.sending_id = o.sending_id
left join clicks c on s.sending_id = c.sending_id
group by s.id;
</code>```

答:
The simple solution is to use count(distinct):

```<code>select s.id,
       count(distinct o.id) as open_count,
       count(distinct c.id) as click_count
from sendings s left join
     opens o
     on s.sending_id = o.sending_id left join
     clicks c
     on s.sending_id = c.sending_id
group by s.id;
</code>```

count() just counts the number of non-NULL values.

In general, a more performance solution is either correlated subqueries or aggregation before the join:

```<code>select s.id, o.open_count, c.click_count
from sendings s left join
     (select o.sending_id, count(*) as open_count
      from opens o
      group by o.sending_id
     ) o
     on s.sending_id = o.sending_id left join
     (select c.sending_id, count(*) as click_count
      from clicks c
      group by c.sending_id
     ) c
     on s.sending_id = c.sending_id;
</code>```

Note that the outer group by is not necessary in this case.

Body:
I have three tables in my database. The central table in the star schema is sendings with a PK column called id. Each sending record can have zero or more rows in the tables opens.

sendings.id = opens.sending_id

Similarly, a third table called clicks have the following association to the sending table (one sending can have zero or more clicks):

sendings.id = clicks.sending_id

Both opens and clicks tables have their unique id column, called id.
What I would like to have in one query, is the count of all associated opens and clicks for each sending. The following query does not seem to meet that demand.

select s.id,
    count(o.id) as open_count,
    count(c.id) as click_count
from sendings s
left join opens o on s.sending_id = o.sending_id
left join clicks c on s.sending_id = c.sending_id
group by s.id;

Body:
The simple solution is to use count(distinct):

select s.id,
       count(distinct o.id) as open_count,
       count(distinct c.id) as click_count
from sendings s left join
     opens o
     on s.sending_id = o.sending_id left join
     clicks c
     on s.sending_id = c.sending_id
group by s.id;

count() just counts the number of non-NULL values.

In general, a more performance solution is either correlated subqueries or aggregation before the join:

select s.id, o.open_count, c.click_count
from sendings s left join
     (select o.sending_id, count(*) as open_count
      from opens o
      group by o.sending_id
     ) o
     on s.sending_id = o.sending_id left join
     (select c.sending_id, count(*) as click_count
      from clicks c
      group by c.sending_id
     ) c
     on s.sending_id = c.sending_id;

Note that the outer group by is not necessary in this case.


问:
Parsing XML Using Python
i'm using Python 2.5 and WinXP.
i am parsing xml file as below:

```<code><Test>
<Default_Config>
  <LINK>{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}</LINK>
  <Lanestat>{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}</Lanestat>
  </Default_Config>
  </Test>
</code>```

however when i print out, the output is as below:

```<code>(None, '{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}')
(None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')
</code>```

Question: How to modify my code so that Link and Lanestat appears instead of None.
tq
Code:

```<code>import elementtree.ElementTree as ET

tree = ET.parse("dict1.xml")
doc = tree.getroot()

for elem in doc.findall('Default_Config/LINK'):
    #print elem.get('LINK'), elem.text
    a=elem.get('LINK'), elem.text
    print a

for elem in doc.findall('Default_Config/Lanestat'):

    #print elem.get('LINK'), elem.text
    a=elem.get('LINK'), elem.text
    print a
</code>```

答:
```<code>import xml.etree.ElementTree as ET

tree = ET.parse("dict1.xml")
doc = tree.getroot()

for elem in doc.findall('Default_Config/LINK'):
    a = elem.tag, elem.text
    print a

for elem in doc.findall('Default_Config/Lanestat'):
    a = elem.tag, elem.text
    print a
</code>```

<p>=></p>

```<code>('LINK', '{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}')
('Lanestat', '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')
</code>```

ContentLicense: CC BY-SA 3.0

Title: Parsing XML Using Python

Body:
i'm using Python 2.5 and WinXP.
i am parsing xml file as below:

<Test>
<Default_Config>
  <LINK>{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}</LINK>
  <Lanestat>{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}</Lanestat>
  </Default_Config>
  </Test>

however when i print out, the output is as below:

(None, '{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}')
(None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')

Question: How to modify my code so that Link and Lanestat appears instead of None.
tq
Code:

import elementtree.ElementTree as ET

tree = ET.parse("dict1.xml")
doc = tree.getroot()

for elem in doc.findall('Default_Config/LINK'):
    #print elem.get('LINK'), elem.text
    a=elem.get('LINK'), elem.text
    print a

for elem in doc.findall('Default_Config/Lanestat'):

    #print elem.get('LINK'), elem.text
    a=elem.get('LINK'), elem.text
    print a

Body:
import xml.etree.ElementTree as ET

tree = ET.parse("dict1.xml")
doc = tree.getroot()

for elem in doc.findall('Default_Config/LINK'):
    a = elem.tag, elem.text
    print a

for elem in doc.findall('Default_Config/Lanestat'):
    a = elem.tag, elem.text
    print a

=>

('LINK', '{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}')
('Lanestat', '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')


问:
RegEx for capturing special chars
I am trying to replace a string using regular expression what i need basically is to convert a code like assignment:

```<code>k*=i
</code>```

into

```<code>k=k+i
</code>```

In my example:

```<code>jregex.Pattern p=new jregex.Pattern("([a-z]|[A-Z])([a-z]|[A-Z]|\\d)*[\\+|\\*|\\-|\\/][=]([a-z]|[A-Z])*([a-z]|[A-Z]|\\d)");
Replacer r= new Replacer(p,"1=$1,2=$2,3=$3,4=$4,5=$5,6=$6,7=$7,8=$8");
String result=r.replace("k*=i");
</code>```

The regex seems to not extract the special chars.

(in this example: +, -, *, /, =)

So what I get as result is:

```<code>1=k,2=,3=,4=i,5=,6=,7=,8=
</code>```

(I can extract only the k & i)

How do I solve this problem?

答:
You could use 3 capturing groups and capturing *+/- in a character class.

```<code>([a-zA-Z])([*+/-])=([a-zA-Z])
</code>```

That will match:

([a-zA-Z]) Capture group 1, match a-z A-Z

([*+/-]) Capture group 2, match * + / -

= Match literally

([a-zA-Z]) Capture group 3, match a-z A-Z

Regex demo | Java demo

And replace with:

```<code>$1=$1$2$3
</code>```

Title: RegEx for capturing special chars

Body:
I am trying to replace a string using regular expression what i need basically is to convert a code like assignment:

k*=i

into

k=k+i

In my example:

jregex.Pattern p=new jregex.Pattern("([a-z]|[A-Z])([a-z]|[A-Z]|\\d)*[\\+|\\*|\\-|\\/][=]([a-z]|[A-Z])*([a-z]|[A-Z]|\\d)");
Replacer r= new Replacer(p,"1=$1,2=$2,3=$3,4=$4,5=$5,6=$6,7=$7,8=$8");
String result=r.replace("k*=i");

The regex seems to not extract the special chars.

(in this example: +, -, *, /, =)

So what I get as result is:

1=k,2=,3=,4=i,5=,6=,7=,8=

(I can extract only the k & i)

How do I solve this problem?

Body:
You could use 3 capturing groups and capturing *+/- in a character class.

([a-zA-Z])([*+/-])=([a-zA-Z])

That will match:

([a-zA-Z]) Capture group 1, match a-z A-Z

([*+/-]) Capture group 2, match * + / -

= Match literally

([a-zA-Z]) Capture group 3, match a-z A-Z

Regex demo | Java demo

And replace with:

$1=$1$2$3


问:
Regex for capturing 4 consecutive numbers in an ID
I need a formula to start at a a certain index and then get the next 4 consecutive numbers.  Using REGEX.  And testing whether they are in the range of 0000-4999.

```<code>^.{6}\d{4}$[0000-4999]
</code>```

This is some code I have tried.  Although I'm still new and don't understand regex.

The outcome needs to be as follows:

ID Number:

```<code>9202204720082
</code>```

Get the following 4 numbers:  4720

Starting at index 7 (presuming indexes starts at 1)

So want to get numbers if indexes 7,8,9, and 10.
This is done to determine the gender in an ID.

答:
Your original expression is just fine, here we can slightly modify it to:

```<code>^.{6}(\d{4}).+$
</code>```

which we are capturing our desired digits in this group (\d{4}).

DEMO

const regex = /^.{6}(\d{4}).+$/gm;
const str = `9202204720082`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}```

RegEx Circuit

jex.im visualizes regular expressions:

Body:
I need a formula to start at a a certain index and then get the next 4 consecutive numbers.  Using REGEX.  And testing whether they are in the range of 0000-4999.

^.{6}\d{4}$[0000-4999]

This is some code I have tried.  Although I'm still new and don't understand regex.

The outcome needs to be as follows:

ID Number:

9202204720082

Get the following 4 numbers:  4720

Starting at index 7 (presuming indexes starts at 1)

So want to get numbers if indexes 7,8,9, and 10.
This is done to determine the gender in an ID.

Body:
Your original expression is just fine, here we can slightly modify it to:

^.{6}(\d{4}).+$

which we are capturing our desired digits in this group (\d{4}).

DEMO

const regex = /^.{6}(\d{4}).+$/gm;
const str = `9202204720082`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

RegEx Circuit

jex.im visualizes regular expressions:


问:
Python to return specific column using list comprehension or apply()
I'm trying to convert R code to Python code and stuck at this point. Can you tell me what is the best way to implement this code snippet in Python?

```<code>only0_0$count =0
for(i in 2:length(only0_0$ID))
{
    only0_0$count[i]=ifelse((only0_0$year[i]-1) %in%
    clientData$Year[clientData$CUSTOMERID %in% only0_0$ID[i]],1,0)
}
</code>```

Background:

Both clientData and only0_0 are DataFrames.

Client Data{columns: year, CustomerID, ...}

only0_0 {columns: year, ID}

ID and CustomerID both represents same thing and are not unique in the corresponding table.

Sort only0_0 by {'ID','year'}

PseudoCode:

In only0_0, create new column 'count' will all zeros.

for loop starting from second observation to last, populate 'count' variable as:

select all 'CustomerID' from clientData where 'ID' in only0_0 matches for a particular row.

e.g. only0_0.ID == 3197

clientData.CustomerID will return all rows id's with customerID=3197

e.g output of last step: rowid(or index in Python) {3,11, 81, 87}

extract corresponding year values from rows id's returned from last step

e.g. output of last step: {2006, 2008, 2009, 2006}

let's say: output of (only0_0.year - 1) == 2008

since 2008 is in {2006, 2008, 2009, 2006}, count = 1

Let me know if it's clear now.

答:
Without knowing what only0_0 and clientData are concretely, it is quite hard, but here are some snippets that should help you:

I assume only0_0 is a pandas.DataFrame and clientData a dictionary, because it does not contain uniform data.

So e.g.

```<code>import pandas as pd
clientData = {'Year': [..., ...], 'CUSTOMERID_transformed': ....}
only0_0 = pd. DataFrame({'count': [1, 2, 3, ...], 'year': [2010, 2012, 2019, ...]})
</code>```

```<code>only0_0.loc[i, 'count'] = 0
for i in range(1, only0_0.shape[0]):    # i.e. skipping the first row
   only0_0.loc[i, 'count'] = 0 if ... else 1

</code>```

or

```<code>... = int(1-bool(...))
</code>```

but I think it is more pythonic to write

```<code>if ...:
    only0_0.loc[i, 'count'] = 0
else:
    only0_0.loc[i, 'count'] = 1
</code>```

Now for the condition, I think it is something composed of

```<code>(only0_0.loc[i, 'year'] - i) in clientData['Year'][...]
</code>```

and

```<code>clientData['CUSTOMERID_transformed'] in only0_0.loc[i, 'ID0_0']
</code>```

EDIT:
Your note suggests rather

```<code>only0_0.loc[i, 'ID0_0'] in clientData['CUSTOMERID_transformed']
</code>```

I hope this helps to get you going.

Body:
I'm trying to convert R code to Python code and stuck at this point. Can you tell me what is the best way to implement this code snippet in Python?

only0_0$count =0
for(i in 2:length(only0_0$ID))
{
    only0_0$count[i]=ifelse((only0_0$year[i]-1) %in%
    clientData$Year[clientData$CUSTOMERID %in% only0_0$ID[i]],1,0)
}

Background:

Both clientData and only0_0 are DataFrames.

Client Data{columns: year, CustomerID, ...}

only0_0 {columns: year, ID}

ID and CustomerID both represents same thing and are not unique in the corresponding table.

Sort only0_0 by {'ID','year'}

PseudoCode:

In only0_0, create new column 'count' will all zeros.

for loop starting from second observation to last, populate 'count' variable as:

select all 'CustomerID' from clientData where 'ID' in only0_0 matches for a particular row.

e.g. only0_0.ID == 3197

clientData.CustomerID will return all rows id's with customerID=3197

e.g output of last step: rowid(or index in Python) {3,11, 81, 87}

extract corresponding year values from rows id's returned from last step

e.g. output of last step: {2006, 2008, 2009, 2006}

let's say: output of (only0_0.year - 1) == 2008

since 2008 is in {2006, 2008, 2009, 2006}, count = 1

Let me know if it's clear now.

Body:
Without knowing what only0_0 and clientData are concretely, it is quite hard, but here are some snippets that should help you:

I assume only0_0 is a pandas.DataFrame and clientData a dictionary, because it does not contain uniform data.

So e.g.

import pandas as pd
clientData = {'Year': [..., ...], 'CUSTOMERID_transformed': ....}
only0_0 = pd. DataFrame({'count': [1, 2, 3, ...], 'year': [2010, 2012, 2019, ...]})

only0_0.loc[i, 'count'] = 0
for i in range(1, only0_0.shape[0]):    # i.e. skipping the first row
   only0_0.loc[i, 'count'] = 0 if ... else 1

or

... = int(1-bool(...))

but I think it is more pythonic to write

if ...:
    only0_0.loc[i, 'count'] = 0
else:
    only0_0.loc[i, 'count'] = 1

Now for the condition, I think it is something composed of

(only0_0.loc[i, 'year'] - i) in clientData['Year'][...]

and

clientData['CUSTOMERID_transformed'] in only0_0.loc[i, 'ID0_0']

EDIT:
Your note suggests rather

only0_0.loc[i, 'ID0_0'] in clientData['CUSTOMERID_transformed']

I hope this helps to get you going.


问:
How to get current timescale?
I'm creating a game that speeds up time scale. I want to pause and resume it with the previous time scale.</p>

```<code>private IEnumerator Speedup()
{
    yield return new WaitForSeconds(10f);
    Time.timeScale+=0.05f;
    StartCoroutine(Speedup());
}
public void pausegame()
{
    Time.timeScale = 0;
}

public void unpausegame()
{
    Time.timeScale = ??;
}
</code>```

答:
Try to store your previous value in a variable (YourVariable = Time.timeScale) then when you resume set the timescale equals to your variable. (Time.timeScale = YourVariable)

I don't know if this is very optimized but it will work I think !

Title: How to get current timescale?

Body:
I'm creating a game that speeds up time scale. I want to pause and resume it with the previous time scale.

private IEnumerator Speedup()
{
    yield return new WaitForSeconds(10f);
    Time.timeScale+=0.05f;
    StartCoroutine(Speedup());
}
public void pausegame()
{
    Time.timeScale = 0;
}

public void unpausegame()
{
    Time.timeScale = ??;
}


问:
How to run a simple JUnit test in eclipse
So here's my code:

```<code>package tests;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

class StatementTester extends TestCase {
    public StatementTester (String name) {
        super(name);
    }

    protected void setUp() {
    }

    protected void tearDown() {
    }

    public void test1() {
        System.out.println("testing");
        assert(true);
    }

    public static Test suite() {
        TestSuite suite= new TestSuite();
        suite.addTest(new StatementTester("test1"));
        return suite;
    }

    public static void main (String[] args) {
        junit.textui.TestRunner.run (suite());
  }
}
</code>```

When I try to run this I get the following error message:

```<code>.E
Time: 0.001
There was 1 error:
1) test1(tests.StatementTester) at tests.StatementTester.main(StatementTester.java:30)

FAILURES!!!
Tests run: 1,  Failures: 0,  Errors: 1
</code>```

I based my code on the example given in Chapter 4 of Martin Fowler's "Refactoring: Improving the design of existing code" (although I simplified it, but the base structure is the same). Also, I run eclipse 3.5.1 and use the JUnit 3 library (don't know how relevant it is, but anyway...)

Can you give me any hints on what I'm doing wrong?

答:
First of all I'd like to say that there is a feature in eclipse that let you run the test without having to declare a main in your test class.

Here is a tutorial that will show you how to do it (with JUnit4) :
http://www.vogella.de/articles/JUnit/article.html

Body:
So here's my code:

package tests;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

class StatementTester extends TestCase {
    public StatementTester (String name) {
        super(name);
    }

    protected void setUp() {
    }

    protected void tearDown() {
    }

    public void test1() {
        System.out.println("testing");
        assert(true);
    }

    public static Test suite() {
        TestSuite suite= new TestSuite();
        suite.addTest(new StatementTester("test1"));
        return suite;
    }

    public static void main (String[] args) {
        junit.textui.TestRunner.run (suite());
  }
}

When I try to run this I get the following error message:

.E
Time: 0.001
There was 1 error:
1) test1(tests.StatementTester) at tests.StatementTester.main(StatementTester.java:30)

FAILURES!!!
Tests run: 1,  Failures: 0,  Errors: 1

I based my code on the example given in Chapter 4 of Martin Fowler's "Refactoring: Improving the design of existing code" (although I simplified it, but the base structure is the same). Also, I run eclipse 3.5.1 and use the JUnit 3 library (don't know how relevant it is, but anyway...)

Can you give me any hints on what I'm doing wrong?


答:
You can use a variable to store the previous scale during pause, and then reassign it in unpause.

```<code>private float _previousScale = 1;

private IEnumerator Speedup()
{
    yield return new WaitForSeconds(10f);
    Time.timeScale += 0.05f;
    StartCoroutine(Speedup());
}

public void pausegame()
{
    _previousScale = Time.timeScale;
    Time.timeScale = 0;
}

public void unpausegame()
{
    Time.timeScale =  _previousScale;
}
</code>```

Further note. I set private float _previousScale = 1; becuase I see an issue incase you call unpausegame before pausegame. If you did not assign it, it will default to 0 and you risk to set Time.timescale to 0 also in unpausegame.

Title: How to get current timescale?

Body:
You can use a variable to store the previous scale during pause, and then reassign it in unpause.

private float _previousScale = 1;

private IEnumerator Speedup()
{
    yield return new WaitForSeconds(10f);
    Time.timeScale += 0.05f;
    StartCoroutine(Speedup());
}

public void pausegame()
{
    _previousScale = Time.timeScale;
    Time.timeScale = 0;
}

public void unpausegame()
{
    Time.timeScale =  _previousScale;
}

Further note. I set private float _previousScale = 1; becuase I see an issue incase you call unpausegame before pausegame. If you did not assign it, it will default to 0 and you risk to set Time.timescale to 0 also in unpausegame.


问:
Multiple tests with pairwise combinations using dplyr/tidyverse
My question is related to this one but a more complex example, in which I would like to statistically compare multiple columns in all combinations, and each of the columns has a different number of samples.

Consider the original data:

```<code># A tibble: 51 x 3
   trial person score
   <chr> <chr>  <dbl>
 1 foo   a      0.266
 2 bar   b      0.372
 3 foo   c      0.573
 4 bar   a      0.908
 5 foo   b      0.202
 6 bar   c      0.898
 7 foo   a      0.945
 8 bar   b      0.661
 9 foo   c      0.629
10 foo   b      0.206
</code>```

For each trial type, I'd like to run a statistical test comparing the scores of each person. So, I need the following test results:

Trial foo, compare all score samples of persons A–B, B–C, C–A

Trial bar, compare all score samples of persons A–B, B–C, C–A

Of course, there are more than two trials, and more than three persons.

Hence, the solution using group_split given in the other question does not work, as it implies always testing agains the first person (in my case), not all pairwise combinations.

So, in the following code, I'm stuck at two points:

library(tidyverse)
#> Registered S3 methods overwritten by 'ggplot2':
#>   method         from
#>   [.quosures     rlang
#>   c.quosures     rlang
#>   print.quosures rlang
library(broom)

set.seed(1)

df = tibble::tibble(
    trial = rep(c("foo", "bar"), 30),
    person = rep(c("a", "b", "c"), 20),
    score = runif(60)
  ) %>%
  filter(score > 0.2)

df %>%
  group_by(person, trial) %>%
  summarize(scores = list(score)) %>%
  spread(person, scores) %>%
  group_split(trial) %>%
  map_df(function(data) {
    data %>%
      summarize_at(vars(b:c), function(x) {
        wilcox.test(.$a, x, paired = FALSE) %>% broom::tidy
      })
  })
#> Error in wilcox.test.default(.$a, x, paired = FALSE): 'x' must be numeric
```

<p><sup>Created on 2019-05-29 by the reprex package (v0.3.0)</sup></p>

<p>The value of <code>x</code> is apparently not just the actual list of scores, but the column vector of scores for a single trial. But I don't know how else to deal with the fact that the number of samples in each person is different.</p>

<p>Also, I still have to manually specify the column names, which would already be a combinatorial nightmare if there were more than, say, four persons.</p>

<p>I can somehow get the combinations as such:</p>

<pre class="lang-r prettyprint-override"><code>df %>%
  group_split(trial) %>%
  map_df(function(data) {
    combinations = expand(tibble(x = unique(data$person), y = unique(data$person)), x, y) %>% filter(x != y)
  })
</code>```

… but that doesn't really help in creating columns for comparison.

What could I do to make this work?

答:
This will allow you to programmatically specify combinations and get around the error you were hitting in wilcox.test().

```<code>combos <- unique(df$person) %>%
  combn(2, simplify = F) %>%
  set_names(map_chr(., ~ paste(., collapse = "_")))

df %>%
  group_split(trial) %>%
  set_names(map_chr(., ~ unique(.$trial))) %>%
  map_df(function(x) {
    map_df(combos, function(y) {
      filter(x, person %in% y) %>%
        wilcox.test(score ~ person, data = .) %>%
        broom::tidy()
    }, .id = "contrast")
  }, .id = "trial")

# A tibble: 6 x 6
  trial contrast statistic p.value method                 alternative
  <chr> <chr>        <dbl>   <dbl> <chr>                  <chr>
1 bar   a_b             34   0.878 Wilcoxon rank sum test two.sided
2 bar   a_c             32   1     Wilcoxon rank sum test two.sided
3 bar   b_c             31   0.959 Wilcoxon rank sum test two.sided
4 foo   a_b             41   1     Wilcoxon rank sum test two.sided
5 foo   a_c             41   1     Wilcoxon rank sum test two.sided
6 foo   b_c             43   0.863 Wilcoxon rank sum test two.sided
</code>```

Since this differs a lot from the pattern you started with, I'm not sure it will work for your real world case, but it works here so I wanted to share.

Body:
My question is related to this one but a more complex example, in which I would like to statistically compare multiple columns in all combinations, and each of the columns has a different number of samples.

Consider the original data:

# A tibble: 51 x 3
   trial person score
   <chr> <chr>  <dbl>
 1 foo   a      0.266
 2 bar   b      0.372
 3 foo   c      0.573
 4 bar   a      0.908
 5 foo   b      0.202
 6 bar   c      0.898
 7 foo   a      0.945
 8 bar   b      0.661
 9 foo   c      0.629
10 foo   b      0.206

For each trial type, I'd like to run a statistical test comparing the scores of each person. So, I need the following test results:

Trial foo, compare all score samples of persons A–B, B–C, C–A

Trial bar, compare all score samples of persons A–B, B–C, C–A

Of course, there are more than two trials, and more than three persons.

Hence, the solution using group_split given in the other question does not work, as it implies always testing agains the first person (in my case), not all pairwise combinations.

So, in the following code, I'm stuck at two points:

library(tidyverse)
#> Registered S3 methods overwritten by 'ggplot2':
#>   method         from
#>   [.quosures     rlang
#>   c.quosures     rlang
#>   print.quosures rlang
library(broom)

set.seed(1)

df = tibble::tibble(
    trial = rep(c("foo", "bar"), 30),
    person = rep(c("a", "b", "c"), 20),
    score = runif(60)
  ) %>%
  filter(score > 0.2)

df %>%
  group_by(person, trial) %>%
  summarize(scores = list(score)) %>%
  spread(person, scores) %>%
  group_split(trial) %>%
  map_df(function(data) {
    data %>%
      summarize_at(vars(b:c), function(x) {
        wilcox.test(.$a, x, paired = FALSE) %>% broom::tidy
      })
  })
#> Error in wilcox.test.default(.$a, x, paired = FALSE): 'x' must be numeric

Created on 2019-05-29 by the reprex package (v0.3.0)

The value of x is apparently not just the actual list of scores, but the column vector of scores for a single trial. But I don't know how else to deal with the fact that the number of samples in each person is different.

Also, I still have to manually specify the column names, which would already be a combinatorial nightmare if there were more than, say, four persons.

I can somehow get the combinations as such:

df %>%
  group_split(trial) %>%
  map_df(function(data) {
    combinations = expand(tibble(x = unique(data$person), y = unique(data$person)), x, y) %>% filter(x != y)
  })

… but that doesn't really help in creating columns for comparison.

What could I do to make this work?

Body:
This will allow you to programmatically specify combinations and get around the error you were hitting in wilcox.test().

combos <- unique(df$person) %>%
  combn(2, simplify = F) %>%
  set_names(map_chr(., ~ paste(., collapse = "_")))

df %>%
  group_split(trial) %>%
  set_names(map_chr(., ~ unique(.$trial))) %>%
  map_df(function(x) {
    map_df(combos, function(y) {
      filter(x, person %in% y) %>%
        wilcox.test(score ~ person, data = .) %>%
        broom::tidy()
    }, .id = "contrast")
  }, .id = "trial")

# A tibble: 6 x 6
  trial contrast statistic p.value method                 alternative
  <chr> <chr>        <dbl>   <dbl> <chr>                  <chr>
1 bar   a_b             34   0.878 Wilcoxon rank sum test two.sided
2 bar   a_c             32   1     Wilcoxon rank sum test two.sided
3 bar   b_c             31   0.959 Wilcoxon rank sum test two.sided
4 foo   a_b             41   1     Wilcoxon rank sum test two.sided
5 foo   a_c             41   1     Wilcoxon rank sum test two.sided
6 foo   b_c             43   0.863 Wilcoxon rank sum test two.sided

Since this differs a lot from the pattern you started with, I'm not sure it will work for your real world case, but it works here so I wanted to share.


问:
Firefox breaks word from slash
Why Firefox is breaking word from / (slash) and - (hyphen) into lines.

Example with / and -

table {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tbody>
    <tr>
      <td>
        LoremipsumdolorsitametconsecteturadipisicingelitLaboredistinctionamdoloresmodiamet/etblanditiisarchitectsundolorem/qnullobcaecatnobilibermollitia/sialiquiodiomagncommodi.

      </td>
    </tr>
  </tbody>
</table></code>```

Example without / and -

table {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tbody>
    <tr>
      <td>
        LoremipsumdolorsitametconsecteturadipisicingelitLaboredistinctionamdoloresmodiametetblanditiisarchitectsundoloremqnullobcaecatnobilibermollitiasialiquiodiomagncommodi.
      </td>
    </tr>
  </tbody>
</table></code>```

Both Examples are working good in other browsers, I have tried overflow-wrap but didn't work.

I'm using Firefox 67.0 (64-bit).

Please open it in Firefox.

答:
You may want to try an HTML code for your forward slash and dash.

For / use /
For - use –```

More info here: https://www.ascii.cl/htmlcodes.htm

Title: Firefox breaks word from slash

Body:
Why Firefox is breaking word from / (slash) and - (hyphen) into lines.

Example with / and -

table {
  width: 100%;
}

        LoremipsumdolorsitametconsecteturadipisicingelitLaboredistinctionamdoloresmodiamet/etblanditiisarchitectsundolorem/qnullobcaecatnobilibermollitia/sialiquiodiomagncommodi.

Example without / and -

table {
  width: 100%;
}

        LoremipsumdolorsitametconsecteturadipisicingelitLaboredistinctionamdoloresmodiametetblanditiisarchitectsundoloremqnullobcaecatnobilibermollitiasialiquiodiomagncommodi.

Both Examples are working good in other browsers, I have tried overflow-wrap but didn't work.

I'm using Firefox 67.0 (64-bit).

Please open it in Firefox.

Body:
You may want to try an HTML code for your forward slash and dash.

For / use &#47;
For - use &#8211;

More info here: https://www.ascii.cl/htmlcodes.htm


问:
Use Play! with a graph-visualization framework that relies on Servlets
I really like Play and it adresses all the problems I had when develpoing web applications. My next project involves calculations on graphs (in this case biological networks) and visualization of large graphs. All the 'backend' stuff is done with the JUNG Graph API, which can be easily integrated in a Play project.

I used to do graph visualization in web applications with yFiles AJAX from yWorks. You will most likely know yWorks if you have ever worked with graphs in Java. yFiles AJAX is basically a JAVA/JavaScript library that offers:

a) Server components that hold the graph model. They mostly extend the extend the Java Servlet API.

b) Client side components that display the graph. This is based on Dojo, which should work in Play.

The components are discribed in detail here: yFiles AJAX dev guide

I know that Play does not use the Servlet API for many good reasons. My question is more general, because I am not that experienced with Play or other frameworks:

Can I use something like yFiles AJAX, which relies on servlets, inside a Play application? Or do I have to stick to a basic JAVA EE project with servlets/jsps?

I hope you understand my question :)

答:
I don't know your API and apparently it heavily relies on servlets everywhere.
I'm not even sure that they provide the code for those server parts...
So in this case, I'm not sure that the servlets are just facade that call backend services. From what I can see in the doc, it doesn't seem to be the case.

Therefore, I think it would be better to keep this module besides Play and not to try to put it into Play, you will spend long time.

Nevertheless, there are some business modules used by the servlets clearly identified in the doc so I think that with some work, it could be modified and become a play module. But how long would it take??? I don't know ;)


问:
I Want to list user task in my django Python view
The task can give one group or can give user list.

If someone login the system. Check task status and group and görevli (list). If a user in list or group in user.group.all Show the filtered list.

I didn't make the filtered query

```<code>    #  todotask = Task.objects.filter(state='to-do').filter(grup__in=request.user.groups.all)

class Task(models.Model):
    class Meta:
        verbose_name = _("Görev")
        verbose_name_plural = _("Görevler")
    STATUSES = (
        ('to-do', _('Yapılacak')),
        ('in_progress', _('Yapılıyor')),
        ('blocked', _('Durduruldu')),
        ('done', _('Tamamlandı')),
        ('dismissed', _('İptal Edildi')),
        ('late', _('Gecikti'))
    )
    PRIORITIES = (
        ('00_low', _('Düşük')),
        ('10_normal', _('Orta')),
        ('20_high', _('Önemli')),
        ('30_critical', _('Çok Önemli')),
        ('40_blocker', _('Engelleyici'))
    )
    title = models.CharField(_("Başlık"), max_length=200)
    partner = models.ForeignKey(Partner, blank=True, null=True, on_delete=models.PROTECT,verbose_name="Dış Ortak")
    proje = models.ForeignKey(Proje, blank=True, null=True, on_delete=models.PROTECT, verbose_name="Proje")
    description = RichTextField("Açıklama", max_length=2000, null=True, blank=True)
    resolution = RichTextField("Sonuç", max_length=2000, null=True, blank=True)
    deadline = models.DateField(_("Teslim Tarihi"), null=True, blank=True, default=datetime.now() + timedelta(days=1))
    grup = models.ForeignKey(Group, related_name='task_assigned', verbose_name=_('Atanan Grup'),
                             on_delete=models.SET_NULL, null=True, blank=True)
    gorevli = models.ManyToManyField(User, verbose_name="Atanan Görevliler", related_name='tasks_assigned', null=True,
                                     blank=True)
    state = models.CharField(_("Durum"), max_length=20, choices=STATUSES, default='to-do')
    priority = models.CharField(_("Öncelik"), max_length=20, choices=PRIORITIES, default='10_normal')
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='users_created', verbose_name=_('created by'),
                                   on_delete=models.SET_NULL, null=True)
    created_at = models.DateTimeField(_("Oluşturulma Zamanı"), auto_now_add=True, editable=False)
    last_modified = models.DateTimeField(_("Son Güncelleme"), auto_now=True, editable=False)
</code>```

This filter must return my list.

```<code>todotask = Task.objects.filter(state='to-do')
</code>```

答:
```<code>   def get_queryset(self, request):
        pusers = []
        liste = []
        projeler = Proje.objects.all()
        for proje in projeler:
            print(proje.title)
            if (proje.grup is not None):
                pusers.append(list(proje.grup.user_set.all()))
            pusers.append(list(proje.gorevli.all()))

            if request.user.username in str(pusers):
                liste.append(proje)
        qs = super().get_queryset(request)
        gsm = list(liste)
        newqs = Proje.objects.filter(id__in=[o.id for o in gsm])
        if request.user.is_superuser:
          return qs
        else:
            return newqs`enter code here`
</code>```

Body:
The task can give one group or can give user list.

If someone login the system. Check task status and group and görevli (list). If a user in list or group in user.group.all Show the filtered list.

I didn't make the filtered query

    #  todotask = Task.objects.filter(state='to-do').filter(grup__in=request.user.groups.all)

class Task(models.Model):
    class Meta:
        verbose_name = _("Görev")
        verbose_name_plural = _("Görevler")
    STATUSES = (
        ('to-do', _('Yapılacak')),
        ('in_progress', _('Yapılıyor')),
        ('blocked', _('Durduruldu')),
        ('done', _('Tamamlandı')),
        ('dismissed', _('İptal Edildi')),
        ('late', _('Gecikti'))
    )
    PRIORITIES = (
        ('00_low', _('Düşük')),
        ('10_normal', _('Orta')),
        ('20_high', _('Önemli')),
        ('30_critical', _('Çok Önemli')),
        ('40_blocker', _('Engelleyici'))
    )
    title = models.CharField(_("Başlık"), max_length=200)
    partner = models.ForeignKey(Partner, blank=True, null=True, on_delete=models.PROTECT,verbose_name="Dış Ortak")
    proje = models.ForeignKey(Proje, blank=True, null=True, on_delete=models.PROTECT, verbose_name="Proje")
    description = RichTextField("Açıklama", max_length=2000, null=True, blank=True)
    resolution = RichTextField("Sonuç", max_length=2000, null=True, blank=True)
    deadline = models.DateField(_("Teslim Tarihi"), null=True, blank=True, default=datetime.now() + timedelta(days=1))
    grup = models.ForeignKey(Group, related_name='task_assigned', verbose_name=_('Atanan Grup'),
                             on_delete=models.SET_NULL, null=True, blank=True)
    gorevli = models.ManyToManyField(User, verbose_name="Atanan Görevliler", related_name='tasks_assigned', null=True,
                                     blank=True)
    state = models.CharField(_("Durum"), max_length=20, choices=STATUSES, default='to-do')
    priority = models.CharField(_("Öncelik"), max_length=20, choices=PRIORITIES, default='10_normal')
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='users_created', verbose_name=_('created by'),
                                   on_delete=models.SET_NULL, null=True)
    created_at = models.DateTimeField(_("Oluşturulma Zamanı"), auto_now_add=True, editable=False)
    last_modified = models.DateTimeField(_("Son Güncelleme"), auto_now=True, editable=False)

This filter must return my list.

todotask = Task.objects.filter(state='to-do')


问:
problem with resetting window repeat clock at c++
problem with resetting window while repeat clock at c++

I tried to reset the time using time, chrono. However, the code execution time continued to increase without initialization.

Hello, I'm a student at the Korea Institute of Technology. Use the translator.
Please excuse me for speaking awkwardly.

I'm designing a program that uses the C++ OpenPose library to measure the right PC user tax.
Basically, we've completed the function of floating a pop-up to provide feedback when your right shoulder or left shoulder is crooked.
However, I would like to issue an alert after a certain second rather than a feedback that is sent in the wrong position.

Time should be measured when the supose function is not executed, but when the user is sitting in the wrong position. Time will be measured from the time when the supose function is executed. An event should occur if the same seat is held for 20 seconds from the wrong seat.

The event will occur after 20 seconds, and if the time is not initialized, it will occur as soon as it is recognized as an incorrect posture. I think it's because of when. If the library breaks from where, it ends with 0 code.

Once I've solved the time-related function, I'm going to ask you a question because I'm having a hard time completing the program.
Thank you.

```<code>while (!userWantsToExit)
        {
 // start frame

std::shared_ptr<std::vector<UserDatum>> datumProcessed;

  if (opWrapper.waitAndPop(datumProcessed))
  {

    userWantsToExit = userOutputClass.display(datumProcessed);
    userOutputClass.printKeypoints(datumProcessed);
....

//string to int

int subShoulder = stoi(rShoulderY) - stoi(lShoulderY);

//clac keypoint values for posedata

if (50 < subShoulder || -50 > subShoulder)
 {

  if (stoi(rShoulderY) < stoi(lShoulderY)) {

    clock_t t_start, t_end;
        int time;
    t_start = clock(); //start clock
    time = t_start / CLOCKS_PER_SEC;
    op::log(time);
    if (time > 20) {
      t_end = clock(); //end clock
      time = (int)(t_end - t_start) / CLOCKS_PER_SEC;
      cv::imshow("SUPOSE", imgLshoulderDown);
      std::string id = "hjw";
      std::string pose = "leftShoulder";
      httpRequestPose(id, pose);
      }
    }
    else if (stoi(rShoulderY) > stoi(lShoulderY)) {
    clock_t t_start, t_end;
    int time;
    t_start = clock(); //start clock
    time = t_start / CLOCKS_PER_SEC;
    op::log(time);
    if (time > 20) {
      cv::imshow("SUPOSE", imgRshoulderDown);
      std::string id = "hjw";
      std::string pose = "rightShoulder";
      httpRequestPose(id, pose);

    }
    t_end = clock();
    time = (int)(t_end - t_start) / CLOCKS_PER_SEC;
     }
     else {
    clock_t t_start, t_end;
    int time;

    t_end = clock();
    time = (int)(t_end - t_start) / CLOCKS_PER_SEC;
     }
  }

 }

else {}

 //op::log("Processed datum could not be emplaced.", op::Priority::High, __LINE__, __FUNCTION__, __FILE__);

}
</code>```

*image

答:
Honestly, it is very hard for me to completely understand your question. However, I was a student and not good at english (even now), i know how struggling it was to find help with google translated paragraphs. Hence, i will make a try.

As I understand, you want to trigger an alert if the shoulder keeps inclining left for more than 20 seconds (same to right incline). Is that correct?

If it is correct, I think the problem is that you keep the variable t_start inside the poseDetect function. It means that everytime the pose is detected the t_start is a new one. The value (t_end - t_start) is always 0. You should declare t_start outside of that function and use a flag to check if it is the first time. I would like to suggest with below pseudo code

```<code>bool isLeftIncline = false;
clock_t startLeft=clock(); //get current time

void poseDetect()
{
    if (50 < subShoulder || -50 > subShoulder){
        if (stoi(rShoulderY) < stoi(lShoulderY)){ // should is inclined to the left
            if(!isLeftIncline){ // the first time
                startLeft=clock(); // get the starting time
                isLeftIncline=true;
                //trigger for the first time here
            }else {  // after the first time
                clock_t current=clock();
                int timeDiff=current-startLeft;
                if(timeDiff>20){ //after 20 second with same pose
                    // issue an alert
                }

                //or trigger alert every nearly 20 seconds
                //if(timeDiff%20<3){
                    //trigger
                //}
            }

        }else {
            // the shoulder no longer inclines to the left
            // reset isLeftIncline time
            isLeftIncline = false;
        }

        // you can apply the same for the right incline here
    }

}
</code>```

Body:
problem with resetting window while repeat clock at c++

I tried to reset the time using time, chrono. However, the code execution time continued to increase without initialization.

Hello, I'm a student at the Korea Institute of Technology. Use the translator.
Please excuse me for speaking awkwardly.

I'm designing a program that uses the C++ OpenPose library to measure the right PC user tax.
Basically, we've completed the function of floating a pop-up to provide feedback when your right shoulder or left shoulder is crooked.
However, I would like to issue an alert after a certain second rather than a feedback that is sent in the wrong position.

Time should be measured when the supose function is not executed, but when the user is sitting in the wrong position. Time will be measured from the time when the supose function is executed. An event should occur if the same seat is held for 20 seconds from the wrong seat.

The event will occur after 20 seconds, and if the time is not initialized, it will occur as soon as it is recognized as an incorrect posture. I think it's because of when. If the library breaks from where, it ends with 0 code.

Once I've solved the time-related function, I'm going to ask you a question because I'm having a hard time completing the program.
Thank you.

while (!userWantsToExit)
        {
 // start frame

std::shared_ptr<std::vector<UserDatum>> datumProcessed;

  if (opWrapper.waitAndPop(datumProcessed))
  {

    userWantsToExit = userOutputClass.display(datumProcessed);
    userOutputClass.printKeypoints(datumProcessed);
....

//string to int

int subShoulder = stoi(rShoulderY) - stoi(lShoulderY);

//clac keypoint values for posedata

if (50 < subShoulder || -50 > subShoulder)
 {

  if (stoi(rShoulderY) < stoi(lShoulderY)) {

    clock_t t_start, t_end;
        int time;
    t_start = clock(); //start clock
    time = t_start / CLOCKS_PER_SEC;
    op::log(time);
    if (time > 20) {
      t_end = clock(); //end clock
      time = (int)(t_end - t_start) / CLOCKS_PER_SEC;
      cv::imshow("SUPOSE", imgLshoulderDown);
      std::string id = "hjw";
      std::string pose = "leftShoulder";
      httpRequestPose(id, pose);
      }
    }
    else if (stoi(rShoulderY) > stoi(lShoulderY)) {
    clock_t t_start, t_end;
    int time;
    t_start = clock(); //start clock
    time = t_start / CLOCKS_PER_SEC;
    op::log(time);
    if (time > 20) {
      cv::imshow("SUPOSE", imgRshoulderDown);
      std::string id = "hjw";
      std::string pose = "rightShoulder";
      httpRequestPose(id, pose);

    }
    t_end = clock();
    time = (int)(t_end - t_start) / CLOCKS_PER_SEC;
     }
     else {
    clock_t t_start, t_end;
    int time;

    t_end = clock();
    time = (int)(t_end - t_start) / CLOCKS_PER_SEC;
     }
  }

 }

else {}

 //op::log("Processed datum could not be emplaced.", op::Priority::High, __LINE__, __FUNCTION__, __FILE__);

}

*image

Body:
Honestly, it is very hard for me to completely understand your question. However, I was a student and not good at english (even now), i know how struggling it was to find help with google translated paragraphs. Hence, i will make a try.

As I understand, you want to trigger an alert if the shoulder keeps inclining left for more than 20 seconds (same to right incline). Is that correct?

If it is correct, I think the problem is that you keep the variable t_start inside the poseDetect function. It means that everytime the pose is detected the t_start is a new one. The value (t_end - t_start) is always 0. You should declare t_start outside of that function and use a flag to check if it is the first time. I would like to suggest with below pseudo code

bool isLeftIncline = false;
clock_t startLeft=clock(); //get current time

void poseDetect()
{
    if (50 < subShoulder || -50 > subShoulder){
        if (stoi(rShoulderY) < stoi(lShoulderY)){ // should is inclined to the left
            if(!isLeftIncline){ // the first time
                startLeft=clock(); // get the starting time
                isLeftIncline=true;
                //trigger for the first time here
            }else {  // after the first time
                clock_t current=clock();
                int timeDiff=current-startLeft;
                if(timeDiff>20){ //after 20 second with same pose
                    // issue an alert
                }

                //or trigger alert every nearly 20 seconds
                //if(timeDiff%20<3){
                    //trigger
                //}
            }

        }else {
            // the shoulder no longer inclines to the left
            // reset isLeftIncline time
            isLeftIncline = false;
        }

        // you can apply the same for the right incline here
    }

}


问:
Spring Data Mongo: Find by array intersection
I use Spring Data DSL to query MongoDB in the following way:

```<code>Page<Member> findByCommunitiesCodeContaining(String code, Pageable pageable);
</code>```

It returns all Members of a community with a given code.

Problem: I need to pass a collection of community codes and return Members that participate in at least one community from the listed codes (where intersection of communities is not empty).

I browsed the Spring Data Mongo documentation but couldn't find a DSL supporting this case.

Question: How do I query records with intersection of collections?

More details. Here is how my structure looks on Java side.

```<code>@Document
public class Member {
    @Id
    private String id;
    private List<Community> communities;
}
</code>```

Community:

```<code>public class Community {
    private String region;
    private String code;
}
</code>```

答:
One option might be to use a regex

```<code>Page<Member> findByCommunitiesCodeRegex(String code, Pageable pageable);
</code>```

The code should be a regex like:

```<code>String code = (code1|code2|code3|....)
</code>```

Hope it helps, I haven't tried it but it is worth trying.

Body:
I use Spring Data DSL to query MongoDB in the following way:

Page<Member> findByCommunitiesCodeContaining(String code, Pageable pageable);

It returns all Members of a community with a given code.

Problem: I need to pass a collection of community codes and return Members that participate in at least one community from the listed codes (where intersection of communities is not empty).

I browsed the Spring Data Mongo documentation but couldn't find a DSL supporting this case.

Question: How do I query records with intersection of collections?

More details. Here is how my structure looks on Java side.

@Document
public class Member {
    @Id
    private String id;
    private List<Community> communities;
}

Community:

public class Community {
    private String region;
    private String code;
}

Body:
One option might be to use a regex

Page<Member> findByCommunitiesCodeRegex(String code, Pageable pageable);

The code should be a regex like:

String code = (code1|code2|code3|....)

Hope it helps, I haven't tried it but it is worth trying.


问:
Correlations between dataframe and list of dataframes in R
I want to calculate correlations between a dataframe and a list of dataframes. Here is my sample:

```<code>library(lubridate)
v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(2,20, length = 10)
v3 = seq(-2,7, length = 10)
v4 = seq(-6,3, length = 10)

df1 = data.frame(Date = v1, Tmax = v2, Tmean = v3, Tmin = v4)

v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(3,21, length = 10)
v3 = seq(-3,8, length = 10)
v4 = seq(-7,4, length = 10)

abc = data.frame(Date = v1, ABC_Tmax = v2, ABC_Tmean = v3, ABC_Tmin = v4)

v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(4,22, length = 10)
v3 = seq(-4,9, length = 10)
v4 = seq(-8,5, length = 10)

def = data.frame(Date = v1, DEF_Tmax = v2, DEF_Tmean = v3, DEF_Tmin = v4)

v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(2,20, length = 10)
v3 = seq(-2,8, length = 10)
v4 = seq(-6,3, length = 10)

ghi = data.frame(Date = v1, GHI_Tmax = v2, GHI_Tmean = v3, GHI_Tmin = v4)

df2 <-list(abc, def, ghi)

names(df2) = c("ABC", "DEF", "GHI")
</code>```

I want to have all correlation coefficients between df1 and df2, but only columnswise.

For example:

df1$Tmax and all df2*Tmax columns

df1$Tmean and all df2*Tmean columns

df1$Tmin and all df2*Tmin columns

I know that I can access all Tmax columns like that:

```<code>lapply(df2, "[[", 2)
</code>```

I know how to calculate the correlation between 2 single values:

```<code>cor.test(df1$Tmax, df2$ABC$ABC_Tmax, method = "spearman")
</code>```

But how can I do it for all columns at once? I tried this, which is not working:

```<code>cor.test(df1$Tmax, lapply(df2, "[[", 2), method = "spearman")
</code>```

Any ideas?

答:
You could use lapply in combination with mapply to apply cor.test and extract a specific value from the test. For example, to get p.value and estimate we can do

```<code>lapply(2:4, function(i)  mapply(function(x, y) {
       a <- cor.test(x, y, method = "spearman")
       c(setNames(a$p.value, "pvalue"), a$estimate)
}, lapply(df2, "[[", i), df1[i]))
</code>```

Body:
I want to calculate correlations between a dataframe and a list of dataframes. Here is my sample:

library(lubridate)
v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(2,20, length = 10)
v3 = seq(-2,7, length = 10)
v4 = seq(-6,3, length = 10)

df1 = data.frame(Date = v1, Tmax = v2, Tmean = v3, Tmin = v4)

v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(3,21, length = 10)
v3 = seq(-3,8, length = 10)
v4 = seq(-7,4, length = 10)

abc = data.frame(Date = v1, ABC_Tmax = v2, ABC_Tmean = v3, ABC_Tmin = v4)

v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(4,22, length = 10)
v3 = seq(-4,9, length = 10)
v4 = seq(-8,5, length = 10)

def = data.frame(Date = v1, DEF_Tmax = v2, DEF_Tmean = v3, DEF_Tmin = v4)

v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(2,20, length = 10)
v3 = seq(-2,8, length = 10)
v4 = seq(-6,3, length = 10)

ghi = data.frame(Date = v1, GHI_Tmax = v2, GHI_Tmean = v3, GHI_Tmin = v4)

df2 <-list(abc, def, ghi)

names(df2) = c("ABC", "DEF", "GHI")

I want to have all correlation coefficients between df1 and df2, but only columnswise.

For example:

df1$Tmax and all df2*Tmax columns

df1$Tmean and all df2*Tmean columns

df1$Tmin and all df2*Tmin columns

I know that I can access all Tmax columns like that:

lapply(df2, "[[", 2)

I know how to calculate the correlation between 2 single values:

cor.test(df1$Tmax, df2$ABC$ABC_Tmax, method = "spearman")

But how can I do it for all columns at once? I tried this, which is not working:

cor.test(df1$Tmax, lapply(df2, "[[", 2), method = "spearman")

Any ideas?

Body:
You could use lapply in combination with mapply to apply cor.test and extract a specific value from the test. For example, to get p.value and estimate we can do

lapply(2:4, function(i)  mapply(function(x, y) {
       a <- cor.test(x, y, method = "spearman")
       c(setNames(a$p.value, "pvalue"), a$estimate)
}, lapply(df2, "[[", i), df1[i]))


问:
Does the qt-thread share the static global variable or not?
I want to know about how to share the static global variable with qt-thread.

I have a one static global pointer test_mem which is shared between qt-thread & main thread.qt-thread with initialize this pointer variable to the starting address of the data memory location which i has to read.then main thread will use the same global variable to read the data from the memory location where this pointer is pointing. But it seems like qt-thread is not sharing the global pointer with main thread.

void run() {
    test_mem = (unsignedchar*)mmap(NULL,lenth,PROT_WRITE|PROT_READ,MAP_SHARED,trigger_fd,offset);
    emit pass_test(&test_mem);
}
```

I want to know about can we share the static global variable between qt-thread & main thread?

答:
Qt and C++ in general share the static variables.

example of use:

//Class where data is stored:

class SharedData {
    static QMutex sMutex;
    static unsigned char* spDataPointer;
    signals: void pass_test(unsigned char** address);
}

//Access from from thread:

SharedData::spDataPointer = (unsignedchar*) mmap(NULL, lenth, PROT_WRITE|PROT_READ, MAP_SHARED, trigger_fd, offset);
emit SharedData::pass_test(&SharedData::spDataPointer);
```

But there is another approach for your implementation.

You don't need to use a shared variable, just use Qt Signals and Slots:

Connect a slot to your pass_test signal by Qt::QueuedConnection.
Like this, when you initialize your pointer, just emit the signal to send it to main-thread. The main-thread will receive your pointer handle it safely.

For more information about QThread show this article.
For more information about Qt Signals and Slots show this article.

Body:
I want to know about how to share the static global variable with qt-thread.

I have a one static global pointer test_mem which is shared between qt-thread & main thread.qt-thread with initialize this pointer variable to the starting address of the data memory location which i has to read.then main thread will use the same global variable to read the data from the memory location where this pointer is pointing. But it seems like qt-thread is not sharing the global pointer with main thread.

void run() {
    test_mem = (unsignedchar*)mmap(NULL,lenth,PROT_WRITE|PROT_READ,MAP_SHARED,trigger_fd,offset);
    emit pass_test(&test_mem);
}

I want to know about can we share the static global variable between qt-thread & main thread?

Body:
Qt and C++ in general share the static variables.

example of use:

//Class where data is stored:

class SharedData {
    static QMutex sMutex;
    static unsigned char* spDataPointer;
    signals: void pass_test(unsigned char** address);
}

//Access from from thread:

SharedData::spDataPointer = (unsignedchar*) mmap(NULL, lenth, PROT_WRITE|PROT_READ, MAP_SHARED, trigger_fd, offset);
emit SharedData::pass_test(&SharedData::spDataPointer);

But there is another approach for your implementation.

You don't need to use a shared variable, just use Qt Signals and Slots:

Connect a slot to your pass_test signal by Qt::QueuedConnection.
Like this, when you initialize your pointer, just emit the signal to send it to main-thread. The main-thread will receive your pointer handle it safely.

For more information about QThread show this article.
For more information about Qt Signals and Slots show this article.


问:
How to Unit Test locale-specific local notifications
I have just added local notifications to my app. These notifications are supposed to fire only if the app Locale's regionCode (i.e. Locale.current.regionCode) is "US" or "CA". I am not interested in the locale's language.

I will also want to write the complementary test case, but once I know how to write one test case, the other will follow naturally.

Therefore, my question is: How can a Locale be injected into the test (see testSuccessfulNotificationDelivery())?

LocalNotificationTests.swift:

```<code>class LocalNotificationTests: XCTestCase {

    let notification1 = LocalNotification(toTriggerInSeconds: 5)
    let notification2 = LocalNotification(toTriggerInSeconds: 6)

    // This object manages LocalNotifications
    // by building them into UNUserNotifications
    // and then scheduling them using UNUserNotificationCenter.
    let notificationManager = NotificationManager()

    func testSuccessfulNotificationDelivery() {

        // setup locale and use it for testing, somehow
        let  = Locale(identifier: "en_CA")

        // The answer to my question would go here.
        // (Inject Locale into the test, somehow?)

        notificationManager.schedule(notifications: [notification1, notification2],
                                     withRegionCode: .regionCode)

        let expectation = self.expectation(description: "notification delivery")

        var deliveredNotifications: [UNNotification]?

        UNUserNotificationCenter.current().getDeliveredNotifications {
            deliveredNotifications = $0
            expectation.fulfill()
        }

        waitForExpectations(timeout: 10, handler: nil)

        XCTAssertEqual(deliveredNotifications?.count, 2)
    }
}
</code>```

Assume default setup() and tearDown().

答:
It could not exactly satisfy your needs but you can check this post.

It seems an important note about changing location style in your test cases.

Once we have executed test in simulator or device it can carry the same language and locale to the next XCUI test case. There is no way to clear the simulator content in between the test cases so it’s good idea to create new scheme for each country and locale

And also you can check Apple Documentation

Body:
I have just added local notifications to my app. These notifications are supposed to fire only if the app Locale's regionCode (i.e. Locale.current.regionCode) is "US" or "CA". I am not interested in the locale's language.

I will also want to write the complementary test case, but once I know how to write one test case, the other will follow naturally.

Therefore, my question is: How can a Locale be injected into the test (see testSuccessfulNotificationDelivery())?

LocalNotificationTests.swift:

class LocalNotificationTests: XCTestCase {

    let notification1 = LocalNotification(toTriggerInSeconds: 5)
    let notification2 = LocalNotification(toTriggerInSeconds: 6)

    // This object manages LocalNotifications
    // by building them into UNUserNotifications
    // and then scheduling them using UNUserNotificationCenter.
    let notificationManager = NotificationManager()

    func testSuccessfulNotificationDelivery() {

        // setup locale and use it for testing, somehow
        let  = Locale(identifier: "en_CA")

        // The answer to my question would go here.
        // (Inject Locale into the test, somehow?)

        notificationManager.schedule(notifications: [notification1, notification2],
                                     withRegionCode: .regionCode)

        let expectation = self.expectation(description: "notification delivery")

        var deliveredNotifications: [UNNotification]?

        UNUserNotificationCenter.current().getDeliveredNotifications {
            deliveredNotifications = $0
            expectation.fulfill()
        }

        waitForExpectations(timeout: 10, handler: nil)

        XCTAssertEqual(deliveredNotifications?.count, 2)
    }
}

Assume default setup() and tearDown().


问:
Overriding OMP_NUM_THREADS from code - for real
All the answers I was able to find so far suggest calling omp_set_num_threads. While it's a proper answer for most cases, it doesn't work for me. Internally, calling omp_set_num_threads causes a creation of per-thread ICV  (or modification, if current thread already has one), and the number of threads is stored there. This means that if there is a different thread, that starts a parallel region, it won't see our new value. So calling omp_set_num_threads != setting OMP_NUM_THREADS env variable.

Is there a way to change global ICV?

Side note - why would I want to to this: I'm working with a library spawns a worker thread for me, so I don't really control it's life-cycle.

Simplest example to reproduce:

export OMP_NUM_THREADS=3

```<code>#include <omp.h>
#include <iostream>
#include <thread>

void job() {
  #pragma omp parallel
  {
    if (omp_get_thread_num() == 0) {
      std::cout << "Num threads:" << omp_get_num_threads() << std::endl;
    }
  };
}

int main () {
  omp_set_num_threads(2);
  #pragma omp parallel
  {
    if (omp_get_thread_num() == 0) {
      std::cout << "Num threads:" << omp_get_num_threads() << std::endl;
    }
  };
  std::thread t(job);
  t.join();
}
</code>```

This produces

```<code>Num threads:2
Num threads:3
</code>```

答:
The problem with what you're trying to achieve is outside of OpenMP's specification.  OpenMP assumes that it's the only programming model in the application process and thus it does know anything about what happens when you create a new thread that also executes OpenMP code.

Specifically, for your problem: the ICV num-threads is a thread-private ICV, that means, that a call to omp_set_num_threads() only affects the ICV stored in the thread that calls omp_set_num_threads().

So, the new std::thread will receive a new copy that initialized from the envionment variable.  You won't be able to change it from the master thread that spawned the new thread.

Body:
All the answers I was able to find so far suggest calling omp_set_num_threads. While it's a proper answer for most cases, it doesn't work for me. Internally, calling omp_set_num_threads causes a creation of per-thread ICV  (or modification, if current thread already has one), and the number of threads is stored there. This means that if there is a different thread, that starts a parallel region, it won't see our new value. So calling omp_set_num_threads != setting OMP_NUM_THREADS env variable.

Is there a way to change global ICV?

Side note - why would I want to to this: I'm working with a library spawns a worker thread for me, so I don't really control it's life-cycle.

Simplest example to reproduce:

export OMP_NUM_THREADS=3

#include <omp.h>
#include <iostream>
#include <thread>

void job() {
  #pragma omp parallel
  {
    if (omp_get_thread_num() == 0) {
      std::cout << "Num threads:" << omp_get_num_threads() << std::endl;
    }
  };
}

int main () {
  omp_set_num_threads(2);
  #pragma omp parallel
  {
    if (omp_get_thread_num() == 0) {
      std::cout << "Num threads:" << omp_get_num_threads() << std::endl;
    }
  };
  std::thread t(job);
  t.join();
}

This produces

Num threads:2
Num threads:3


问:
Is there a R function to order by character or factor of intervals?
After several functions I get a table, which has ordered characters, some starting with "(" or "[" followed by numbers. (intervals, coming from a cut(x) on the data)

What i want to achieve is an order by the startvalue of the invervals, so that (100,124] does not come before (70,100] (see example)
edit: the order of column1 (class) should stay as it is.

well i tried to do it with the order and setorder from data.table but failed so far. I think I need to split the column with strsplit and then order by the first element of it, but that can't be the "best" solution

```<code>test <- data.frame(class = c("class1",   "class1",   "class1",   "class1",   "class2", "class2", "class2", "class2", "class2", "class2", "class2", "class2", "class2"),
                   attr = c("1","2","4","5","(100,124]", "(124,180]" ,"(180,Inf]", "(37,50]" ,  "(5,37]"  ,  "(50,56]"  , "(56,70]"  ,"(70,100]"  ,"[0,5]" ),
                  value = c(415.14,115.13,422.52,37.07,167.40,135.04,67.01,280.03,81.18,237.83,285.62,302.63,3.37))

</code>```

aim:

```<code>class   attr    value
class1  1   415.14
class1  2   115.13
class1  4   422.52
class1  5   37.07
class2  [0,5]   3.37
class2  (5,37]  81.18
class2  (37,50] 280.03
class2  (50,56] 237.83
class2  (56,70] 285.62
class2  (70,100]    302.63
class2  (100,124]   167.40
class2  (124,180]   135.04
class2  (180,Inf]   67.01
</code>```

答:
stringi alternative using the same logic as @G. Grothendieck's solution. It extracts the first sequence of digits in the attr column:

```<code>o2 <- order(test$class, as.numeric(stringi::stri_extract_first_regex(test$attr, "\\d+")))
test[o2, ]

    class      attr     value
1  class1         1  977.0947
2  class1         2  299.9418
3  class1         4 1398.7519
4  class1         5  170.8434
13 class2     [0,5]  299.1390
9  class2    (5,37]  326.5092
8  class2   (37,50]  923.6778
10 class2   (50,56]  734.9950
11 class2   (56,70]  820.7536
12 class2  (70,100]  779.0926
5  class2 (100,124]  308.5136
6  class2 (124,180]  234.6386
7  class2 (180,Inf]  100.1264
</code>```

Body:
After several functions I get a table, which has ordered characters, some starting with "(" or "[" followed by numbers. (intervals, coming from a cut(x) on the data)

What i want to achieve is an order by the startvalue of the invervals, so that (100,124] does not come before (70,100] (see example)
edit: the order of column1 (class) should stay as it is.

well i tried to do it with the order and setorder from data.table but failed so far. I think I need to split the column with strsplit and then order by the first element of it, but that can't be the "best" solution

test <- data.frame(class = c("class1",   "class1",   "class1",   "class1",   "class2", "class2", "class2", "class2", "class2", "class2", "class2", "class2", "class2"),
                   attr = c("1","2","4","5","(100,124]", "(124,180]" ,"(180,Inf]", "(37,50]" ,  "(5,37]"  ,  "(50,56]"  , "(56,70]"  ,"(70,100]"  ,"[0,5]" ),
                  value = c(415.14,115.13,422.52,37.07,167.40,135.04,67.01,280.03,81.18,237.83,285.62,302.63,3.37))

aim:

class   attr    value
class1  1   415.14
class1  2   115.13
class1  4   422.52
class1  5   37.07
class2  [0,5]   3.37
class2  (5,37]  81.18
class2  (37,50] 280.03
class2  (50,56] 237.83
class2  (56,70] 285.62
class2  (70,100]    302.63
class2  (100,124]   167.40
class2  (124,180]   135.04
class2  (180,Inf]   67.01

Body:
stringi alternative using the same logic as @G. Grothendieck's solution. It extracts the first sequence of digits in the attr column:

o2 <- order(test$class, as.numeric(stringi::stri_extract_first_regex(test$attr, "\\d+")))
test[o2, ]

    class      attr     value
1  class1         1  977.0947
2  class1         2  299.9418
3  class1         4 1398.7519
4  class1         5  170.8434
13 class2     [0,5]  299.1390
9  class2    (5,37]  326.5092
8  class2   (37,50]  923.6778
10 class2   (50,56]  734.9950
11 class2   (56,70]  820.7536
12 class2  (70,100]  779.0926
5  class2 (100,124]  308.5136
6  class2 (124,180]  234.6386
7  class2 (180,Inf]  100.1264


问:
Entity Framework problem in new Entity Inheritance
Could someone with some good knowledge answer this question please. Im having a problem with the schema in my Students.aspx page. I have done the walkthrough, but I get an error and I have copied the edmx file from the sample into my application and I still get the error. This is the error:

'EnrollmentDate' is not a member of
  type 'SchoolModel.Person' in the
  currently loaded schemas. Near simple
  identifier, line 6, column 4.

I have also created a new EntityDataSource and I have the same problem. The sample works fine but I can't seem to get the EnrollmentDate and HireDate fields to be part of the 'SchoolModel.Person' Entity. The part which is Upto setting the EntityTypeFilter then I run the app and I get problems

答: It sounds like you're following the example on MSDN. By the end of the example, the fields EnrollmentDate and HireDate are no longer on the SchoolModel.Person class, they're on the subclasses SchoolModel.Instructor and SchoolModel.Student.


问:
Decode Base64 string
I am currently working on a custom SAPUI5 app. I would like to make a service call, which expects the Guid in a different format than it is currently available.

An example:

Available (base64): QvLAUUzUCZbhAAAAjSS2iA==

As it should be (hexadecimal): 42F2C0514CD40996E10000008D24B688

I have not found an online decoder, which could produce the desired result, however, I was able to encode the guid 42F2C0514CD40996E10000008D24B to QvLAUUzUCZbhAAAAjss2iA== with the SAP ABAP standard function module HTTP_BASE64_ENCODE. With the usual online encoders, however, I got a different result.

How can I decode the encoded guid with JavaScript so that it has the desired format?

答:
The string is in hexadecimal format you will have to convert it.

First you convert the string to binary (atob > charCodeAt) and then using the toString(16) you get the hex.

I will not post the code, since its already explained
Decode Base64 to Hexadecimal string with javascript

Title: Decode Base64 string


问:
"How to get 'parent to child' relation with mongodb aggregation"
I have one collection called "location". in this collection all child and parent collection are stores. now I want to create a query who returns me parent to child spaces separated string.

Collection

```<code>businessId: { type: mongoose.Schema.Types.ObjectId, ref: 'admin' },
parentId: { type: mongoose.Schema.Types.ObjectId, ref: 'location' },
name: { type: String },
image: { type: String },
imageManipulation: { type: String },
locationColor: [{ range: { type: String }, color: { type: String } }],
area: {},
settings: {},
status: { type: String, enum: [0, 1], default: 1 },
isChild: { type: String, enum: [0, 1] },
parentPosition: { type: String }
</code>```

In the above collection, you can see parentId field. if the location is a child then it have parentId. if the location is a parent then parentId will null. parent location can N level child location.

Collection Data

```<code>[{
    "_id" : ObjectId("5cee1002a01ad50f5c222982"),
    "status" : "1",
    "name" : "Ground Floor",
    "settings" : {
        "zoom" : "0",
        "positionX" : "0",
        "positionY" : "0",
        "width" : "498",
        "height" : "498"
    },
    "image" : "1559105538977.jpg",
    "businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
    "locationColor" : [],
    "updatedAt" : ISODate("2019-05-29T04:52:18.999Z"),
    "createdAt" : ISODate("2019-05-29T04:52:18.999Z"),
    "__v" : 0
},
{
    "_id" : ObjectId("5cee103ca01ad50f5c222983"),
    "status" : "1",
    "name" : "Kitchen",
    "settings" : {
        "zoom" : "0",
        "positionX" : "0",
        "positionY" : "0",
        "width" : "498",
        "height" : "498"
    },
    "area" : "{\"type\":3,\"points\":[{\"x\":20,\"y\":178},{\"x\":19,\"y\":75},{\"x\":56,\"y\":71},{\"x\":57,\"y\":52},{\"x\":80,\"y\":18},{\"x\":138,\"y\":17},{\"x\":165,\"y\":52},{\"x\":165,\"y\":94},{\"x\":174,\"y\":96},{\"x\":173,\"y\":179}],\"fill\":\"rgba(178,40,40,0.58)\"}",
    "parentId" : ObjectId("5cee1002a01ad50f5c222982"),
    "image" : "1559105596975.jpg",
    "businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
    "locationColor" : [],
    "updatedAt" : ISODate("2019-05-29T04:53:16.990Z"),
    "createdAt" : ISODate("2019-05-29T04:53:16.990Z"),
    "__v" : 0
},
{
    "_id" : ObjectId("5cee1078a01ad50f5c222984"),
    "status" : "1",
    "name" : "Cbot",
    "settings" : {
        "zoom" : "0",
        "positionX" : "0",
        "positionY" : "0",
        "width" : "498",
        "height" : "498"
    },
    "area" : "{\"type\":3,\"points\":[{\"x\":20,\"y\":311},{\"x\":17,\"y\":59},{\"x\":84,\"y\":58},{\"x\":88,\"y\":312}],\"fill\":\"rgba(20,205,123,0.67)\"}",
    "parentId" : ObjectId("5cee103ca01ad50f5c222983"),
    "image" : "1559105656049.jpg",
    "businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
    "locationColor" : [],
    "updatedAt" : ISODate("2019-05-29T04:54:16.070Z"),
    "createdAt" : ISODate("2019-05-29T04:54:16.070Z"),
    "__v" : 0
},
{
    "_id" : ObjectId("5cee10c1a01ad50f5c222985"),
    "status" : "1",
    "name" : "Drower 1",
    "settings" : {
        "zoom" : "5",
        "positionX" : "470",
        "positionY" : "70",
        "width" : "498",
        "height" : "498"
    },
    "area" : "{\"type\":3,\"points\":[{\"x\":21,\"y\":102},{\"x\":81,\"y\":104},{\"x\":79,\"y\":43},{\"x\":21,\"y\":43}],\"fill\":\"rgba(16,77,193,0.5)\"}",
    "parentId" : ObjectId("5cee1078a01ad50f5c222984"),
    "image" : "1559105729881.jpg",
    "businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
    "locationColor" : [],
    "updatedAt" : ISODate("2019-05-29T04:55:29.901Z"),
    "createdAt" : ISODate("2019-05-29T04:55:29.901Z"),
    "__v" : 0
},
{
    "_id" : ObjectId("5cee110ea01ad50f5c222986"),
    "status" : "1",
    "name" : "Drawer 2",
    "settings" : {
        "zoom" : "5",
        "positionX" : "484",
        "positionY" : "103",
        "width" : "498",
        "height" : "498"
    },
    "area" : "{\"type\":1,\"coordinates\":{\"x\":23,\"y\":125,\"width\":58,\"height\":56},\"points\":[{\"x\":23,\"y\":125},{\"x\":81,\"y\":181}],\"fill\":\"rgba(117,37,109,0.74)\"}",
    "parentId" : ObjectId("5cee1078a01ad50f5c222984"),
    "image" : "1559105806551.jpg",
    "businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
    "locationColor" : [],
    "updatedAt" : ISODate("2019-05-29T04:56:46.574Z"),
    "createdAt" : ISODate("2019-05-29T04:56:46.574Z"),
    "__v" : 0
},
{
    "_id" : ObjectId("5cee1148a01ad50f5c222987"),
    "status" : "1",
    "name" : "Drawer 3",
    "settings" : {
        "zoom" : "5",
        "positionX" : "477",
        "positionY" : "94",
        "width" : "498",
        "height" : "498"
    },
    "area" : "{\"type\":3,\"points\":[{\"x\":22,\"y\":205},{\"x\":20,\"y\":290},{\"x\":84,\"y\":288},{\"x\":85,\"y\":205}],\"fill\":\"rgba(164,108,54,0.57)\"}",
    "parentId" : ObjectId("5cee1078a01ad50f5c222984"),
    "image" : "1559105864947.jpg",
    "businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
    "locationColor" : [],
    "updatedAt" : ISODate("2019-05-29T04:57:44.972Z"),
    "createdAt" : ISODate("2019-05-29T04:57:44.972Z"),
    "__v" : 0
},
{
    "_id" : ObjectId("5cee5e683b9f67a9f501f818"),
    "status" : "1",
    "name" : "Washroom",
    "settings" : {
        "zoom" : "5",
        "positionX" : "477",
        "positionY" : "94",
        "width" : "498",
        "height" : "498"
    },
    "area" : "{\"type\":3,\"points\":[{\"x\":22,\"y\":205},{\"x\":20,\"y\":290},{\"x\":84,\"y\":288},{\"x\":85,\"y\":205}],\"fill\":\"rgba(164,108,54,0.57)\"}",
    "parentId" : ObjectId("5cee1002a01ad50f5c222982"),
    "image" : "1559105864947.jpg",
    "businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
    "locationColor" : [],
    "updatedAt" : ISODate("2019-05-29T04:57:44.972Z"),
    "createdAt" : ISODate("2019-05-29T04:57:44.972Z"),
    "__v" : 0
},
{
    "_id" : ObjectId("5cee5f593b9f67a9f501fa01"),
    "status" : "1",
    "name" : "Third Floor",
    "settings" : {
        "zoom" : "0",
        "positionX" : "0",
        "positionY" : "0",
        "width" : "498",
        "height" : "498"
    },
    "image" : "1559105538977123.jpg",
    "businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
    "locationColor" : [],
    "updatedAt" : ISODate("2019-05-29T04:52:18.999Z"),
    "createdAt" : ISODate("2019-05-29T04:52:18.999Z"),
    "__v" : 0
}]
</code>```

Expected result in JSON

```<code>[
        {
            "_id": "5cee1002a01ad50f5c222982",
            "name": "Ground Floor"
        },
        {
            "_id": "5cee103ca01ad50f5c222983",
            "name": "    Kitchen"
        },
        {
            "_id": "5cee1078a01ad50f5c222984",
            "name": "        Cbot"
        },
        {
            "_id": "5cee110ea01ad50f5c222986",
            "name": "            Drawer 2"
        },
        {
            "_id": "5cee1148a01ad50f5c222987",
            "name": "            Drawer 3"
        },
        {
            "_id": "5cee10c1a01ad50f5c222985",
            "name": "            Drower 1"
        },
        {
            "_id": "5cee5e683b9f67a9f501f818",
            "name": "    Washroom"
        },
        {
            "_id": "5cee5f593b9f67a9f501fa01",
            "name": "Third Floor"
        }
    ]
</code>```

答:
I do not think you should let mongodb take care of name formatting. So my solution is about finding how many spaces a certain name needs before, so that js can deal with formatting. This is the query:

```<code>db.collection.aggregate([
    {
        $graphLookup: {
            from: "collection",
            startWith: "$parentId",
            connectFromField: "parentId",
            connectToField: "_id",
            as: "hierarchy"
        }
    },
    {
        $project: {
            "_id": 1,
            "name": 1,
            "hierarchy_size": { $size: "$hierarchy" }
        }
    }
]);
</code>```

With the $graphLookup, the db is building an in memory graph of edges between connectFromField and connectToField. From the graph you only need the depth of your hierarchy, so I computed hierarchy_size. This is the output:

```<code>/* 1 */
{
    "_id" : ObjectId("5cee1002a01ad50f5c222982"),
    "name" : "Ground Floor",
    "hierarchy_size" : 0
}

/* 2 */
{
    "_id" : ObjectId("5cee103ca01ad50f5c222983"),
    "name" : "Kitchen",
    "hierarchy_size" : 1
}

/* 3 */
{
    "_id" : ObjectId("5cee1078a01ad50f5c222984"),
    "name" : "Cbot",
    "hierarchy_size" : 2
}

/* 4 */
{
    "_id" : ObjectId("5cee10c1a01ad50f5c222985"),
    "name" : "Drower 1",
    "hierarchy_size" : 3
}

/* 5 */
{
    "_id" : ObjectId("5cee110ea01ad50f5c222986"),
    "name" : "Drawer 2",
    "hierarchy_size" : 3
}

/* 6 */
{
    "_id" : ObjectId("5cee1148a01ad50f5c222987"),
    "name" : "Drawer 3",
    "hierarchy_size" : 3
}

/* 7 */
{
    "_id" : ObjectId("5cee5e683b9f67a9f501f818"),
    "name" : "Washroom",
    "hierarchy_size" : 1
}

/* 8 */
{
    "_id" : ObjectId("5cee5f593b9f67a9f501fa01"),
    "name" : "Third Floor",
    "hierarchy_size" : 0
}
</code>```

The only problem here might be query performances, but that depends on how much data you need to process. Also consider the memory limit.

Body:
I have one collection called "location". in this collection all child and parent collection are stores. now I want to create a query who returns me parent to child spaces separated string.

Collection

businessId: { type: mongoose.Schema.Types.ObjectId, ref: 'admin' },
parentId: { type: mongoose.Schema.Types.ObjectId, ref: 'location' },
name: { type: String },
image: { type: String },
imageManipulation: { type: String },
locationColor: [{ range: { type: String }, color: { type: String } }],
area: {},
settings: {},
status: { type: String, enum: [0, 1], default: 1 },
isChild: { type: String, enum: [0, 1] },
parentPosition: { type: String }

In the above collection, you can see parentId field. if the location is a child then it have parentId. if the location is a parent then parentId will null. parent location can N level child location.

Collection Data

[{
    "_id" : ObjectId("5cee1002a01ad50f5c222982"),
    "status" : "1",
    "name" : "Ground Floor",
    "settings" : {
        "zoom" : "0",
        "positionX" : "0",
        "positionY" : "0",
        "width" : "498",
        "height" : "498"
    },
    "image" : "1559105538977.jpg",
    "businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
    "locationColor" : [],
    "updatedAt" : ISODate("2019-05-29T04:52:18.999Z"),
    "createdAt" : ISODate("2019-05-29T04:52:18.999Z"),
    "__v" : 0
},
{
    "_id" : ObjectId("5cee103ca01ad50f5c222983"),
    "status" : "1",
    "name" : "Kitchen",
    "settings" : {
        "zoom" : "0",
        "positionX" : "0",
        "positionY" : "0",
        "width" : "498",
        "height" : "498"
    },
    "area" : "{\"type\":3,\"points\":[{\"x\":20,\"y\":178},{\"x\":19,\"y\":75},{\"x\":56,\"y\":71},{\"x\":57,\"y\":52},{\"x\":80,\"y\":18},{\"x\":138,\"y\":17},{\"x\":165,\"y\":52},{\"x\":165,\"y\":94},{\"x\":174,\"y\":96},{\"x\":173,\"y\":179}],\"fill\":\"rgba(178,40,40,0.58)\"}",
    "parentId" : ObjectId("5cee1002a01ad50f5c222982"),
    "image" : "1559105596975.jpg",
    "businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
    "locationColor" : [],
    "updatedAt" : ISODate("2019-05-29T04:53:16.990Z"),
    "createdAt" : ISODate("2019-05-29T04:53:16.990Z"),
    "__v" : 0
},
{
    "_id" : ObjectId("5cee1078a01ad50f5c222984"),
    "status" : "1",
    "name" : "Cbot",
    "settings" : {
        "zoom" : "0",
        "positionX" : "0",
        "positionY" : "0",
        "width" : "498",
        "height" : "498"
    },
    "area" : "{\"type\":3,\"points\":[{\"x\":20,\"y\":311},{\"x\":17,\"y\":59},{\"x\":84,\"y\":58},{\"x\":88,\"y\":312}],\"fill\":\"rgba(20,205,123,0.67)\"}",
    "parentId" : ObjectId("5cee103ca01ad50f5c222983"),
    "image" : "1559105656049.jpg",
    "businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
    "locationColor" : [],
    "updatedAt" : ISODate("2019-05-29T04:54:16.070Z"),
    "createdAt" : ISODate("2019-05-29T04:54:16.070Z"),
    "__v" : 0
},
{
    "_id" : ObjectId("5cee10c1a01ad50f5c222985"),
    "status" : "1",
    "name" : "Drower 1",
    "settings" : {
        "zoom" : "5",
        "positionX" : "470",
        "positionY" : "70",
        "width" : "498",
        "height" : "498"
    },
    "area" : "{\"type\":3,\"points\":[{\"x\":21,\"y\":102},{\"x\":81,\"y\":104},{\"x\":79,\"y\":43},{\"x\":21,\"y\":43}],\"fill\":\"rgba(16,77,193,0.5)\"}",
    "parentId" : ObjectId("5cee1078a01ad50f5c222984"),
    "image" : "1559105729881.jpg",
    "businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
    "locationColor" : [],
    "updatedAt" : ISODate("2019-05-29T04:55:29.901Z"),
    "createdAt" : ISODate("2019-05-29T04:55:29.901Z"),
    "__v" : 0
},
{
    "_id" : ObjectId("5cee110ea01ad50f5c222986"),
    "status" : "1",
    "name" : "Drawer 2",
    "settings" : {
        "zoom" : "5",
        "positionX" : "484",
        "positionY" : "103",
        "width" : "498",
        "height" : "498"
    },
    "area" : "{\"type\":1,\"coordinates\":{\"x\":23,\"y\":125,\"width\":58,\"height\":56},\"points\":[{\"x\":23,\"y\":125},{\"x\":81,\"y\":181}],\"fill\":\"rgba(117,37,109,0.74)\"}",
    "parentId" : ObjectId("5cee1078a01ad50f5c222984"),
    "image" : "1559105806551.jpg",
    "businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
    "locationColor" : [],
    "updatedAt" : ISODate("2019-05-29T04:56:46.574Z"),
    "createdAt" : ISODate("2019-05-29T04:56:46.574Z"),
    "__v" : 0
},
{
    "_id" : ObjectId("5cee1148a01ad50f5c222987"),
    "status" : "1",
    "name" : "Drawer 3",
    "settings" : {
        "zoom" : "5",
        "positionX" : "477",
        "positionY" : "94",
        "width" : "498",
        "height" : "498"
    },
    "area" : "{\"type\":3,\"points\":[{\"x\":22,\"y\":205},{\"x\":20,\"y\":290},{\"x\":84,\"y\":288},{\"x\":85,\"y\":205}],\"fill\":\"rgba(164,108,54,0.57)\"}",
    "parentId" : ObjectId("5cee1078a01ad50f5c222984"),
    "image" : "1559105864947.jpg",
    "businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
    "locationColor" : [],
    "updatedAt" : ISODate("2019-05-29T04:57:44.972Z"),
    "createdAt" : ISODate("2019-05-29T04:57:44.972Z"),
    "__v" : 0
},
{
    "_id" : ObjectId("5cee5e683b9f67a9f501f818"),
    "status" : "1",
    "name" : "Washroom",
    "settings" : {
        "zoom" : "5",
        "positionX" : "477",
        "positionY" : "94",
        "width" : "498",
        "height" : "498"
    },
    "area" : "{\"type\":3,\"points\":[{\"x\":22,\"y\":205},{\"x\":20,\"y\":290},{\"x\":84,\"y\":288},{\"x\":85,\"y\":205}],\"fill\":\"rgba(164,108,54,0.57)\"}",
    "parentId" : ObjectId("5cee1002a01ad50f5c222982"),
    "image" : "1559105864947.jpg",
    "businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
    "locationColor" : [],
    "updatedAt" : ISODate("2019-05-29T04:57:44.972Z"),
    "createdAt" : ISODate("2019-05-29T04:57:44.972Z"),
    "__v" : 0
},
{
    "_id" : ObjectId("5cee5f593b9f67a9f501fa01"),
    "status" : "1",
    "name" : "Third Floor",
    "settings" : {
        "zoom" : "0",
        "positionX" : "0",
        "positionY" : "0",
        "width" : "498",
        "height" : "498"
    },
    "image" : "1559105538977123.jpg",
    "businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
    "locationColor" : [],
    "updatedAt" : ISODate("2019-05-29T04:52:18.999Z"),
    "createdAt" : ISODate("2019-05-29T04:52:18.999Z"),
    "__v" : 0
}]

Expected result in JSON

[
        {
            "_id": "5cee1002a01ad50f5c222982",
            "name": "Ground Floor"
        },
        {
            "_id": "5cee103ca01ad50f5c222983",
            "name": "    Kitchen"
        },
        {
            "_id": "5cee1078a01ad50f5c222984",
            "name": "        Cbot"
        },
        {
            "_id": "5cee110ea01ad50f5c222986",
            "name": "            Drawer 2"
        },
        {
            "_id": "5cee1148a01ad50f5c222987",
            "name": "            Drawer 3"
        },
        {
            "_id": "5cee10c1a01ad50f5c222985",
            "name": "            Drower 1"
        },
        {
            "_id": "5cee5e683b9f67a9f501f818",
            "name": "    Washroom"
        },
        {
            "_id": "5cee5f593b9f67a9f501fa01",
            "name": "Third Floor"
        }
    ]

Body:
I do not think you should let mongodb take care of name formatting. So my solution is about finding how many spaces a certain name needs before, so that js can deal with formatting. This is the query:

db.collection.aggregate([
    {
        $graphLookup: {
            from: "collection",
            startWith: "$parentId",
            connectFromField: "parentId",
            connectToField: "_id",
            as: "hierarchy"
        }
    },
    {
        $project: {
            "_id": 1,
            "name": 1,
            "hierarchy_size": { $size: "$hierarchy" }
        }
    }
]);

With the $graphLookup, the db is building an in memory graph of edges between connectFromField and connectToField. From the graph you only need the depth of your hierarchy, so I computed hierarchy_size. This is the output:

/* 1 */
{
    "_id" : ObjectId("5cee1002a01ad50f5c222982"),
    "name" : "Ground Floor",
    "hierarchy_size" : 0
}

/* 2 */
{
    "_id" : ObjectId("5cee103ca01ad50f5c222983"),
    "name" : "Kitchen",
    "hierarchy_size" : 1
}

/* 3 */
{
    "_id" : ObjectId("5cee1078a01ad50f5c222984"),
    "name" : "Cbot",
    "hierarchy_size" : 2
}

/* 4 */
{
    "_id" : ObjectId("5cee10c1a01ad50f5c222985"),
    "name" : "Drower 1",
    "hierarchy_size" : 3
}

/* 5 */
{
    "_id" : ObjectId("5cee110ea01ad50f5c222986"),
    "name" : "Drawer 2",
    "hierarchy_size" : 3
}

/* 6 */
{
    "_id" : ObjectId("5cee1148a01ad50f5c222987"),
    "name" : "Drawer 3",
    "hierarchy_size" : 3
}

/* 7 */
{
    "_id" : ObjectId("5cee5e683b9f67a9f501f818"),
    "name" : "Washroom",
    "hierarchy_size" : 1
}

/* 8 */
{
    "_id" : ObjectId("5cee5f593b9f67a9f501fa01"),
    "name" : "Third Floor",
    "hierarchy_size" : 0
}

The only problem here might be query performances, but that depends on how much data you need to process. Also consider the memory limit.


问:
Python equivalent code for this CURL command?
Below is my CURL command :

```<code>curl -v -X POST --cert ~/Desktop/cert/hardening.qa.pkcs:0JMQqqksE7Q2 --cert-type p12 https://somewebsite.com/SomeServers/PublishQueue/a.qa.queue.z -d'[{"count":5,"requeue":true,"encoding":"auto","truncate":50000}]'
</code>```

Certificate file is : ~/Desktop/cert/hardening.qa.pkcs
Certificate password : 0JMQqqksE7Q2

I need to write the same code in Python, can someone please help me with requests library. I am not able to figure out how to add --cert and --cert-type in the requests.post

resp = requests.post(url, json = data, cert = (cert_path,cert_pass), verify = False)
```

答:
```<code>import requests

if __name__=='__main__':
    url='https://somewebsite.com/SomeServers/PublishQueue/a.qa.queue.z'
    data=[{"table":"A","count":500},{"table":"B","count":1500}]
    cert_path='~/hardening.qa.pem'
    resp=requests.post(url,json=data,cert=cert_path)
    print(resp.status_code)
    print(resp.text)
    print(resp.headers)
</code>```

The Problem was the certificate was in P12 format, I converted it to .pem file and the above code worked.

Body:
Below is my CURL command :

curl -v -X POST --cert ~/Desktop/cert/hardening.qa.pkcs:0JMQqqksE7Q2 --cert-type p12 https://somewebsite.com/SomeServers/PublishQueue/a.qa.queue.z -d'[{"count":5,"requeue":true,"encoding":"auto","truncate":50000}]'

Certificate file is : ~/Desktop/cert/hardening.qa.pkcs
Certificate password : 0JMQqqksE7Q2

I need to write the same code in Python, can someone please help me with requests library. I am not able to figure out how to add --cert and --cert-type in the requests.post

resp = requests.post(url, json = data, cert = (cert_path,cert_pass), verify = False)

Body:
import requests

if __name__=='__main__':
    url='https://somewebsite.com/SomeServers/PublishQueue/a.qa.queue.z'
    data=[{"table":"A","count":500},{"table":"B","count":1500}]
    cert_path='~/hardening.qa.pem'
    resp=requests.post(url,json=data,cert=cert_path)
    print(resp.status_code)
    print(resp.text)
    print(resp.headers)

The Problem was the certificate was in P12 format, I converted it to .pem file and the above code worked.


问:
horizontal bars with vaadein 8
i very new with Vaadin.

i have a chart with bars veritcally.
i want to geht horizontal bars

i have read here:
https://vaadin.com/docs/v8/charts/java-api/charts-charttypes.html

thats a part of my source (no errors):

```<code>    Chart chart = new Chart(ChartType.BAR);
    Configuration configuration = junkPerMachineChart.getConfiguration();
    configuration.getChart().setType(ChartType.BAR);
    configuration.addSeries(series);
    junkPerMachineChart.setCaption("Stündlicher Verbrauch Mischer");
    getUI().access(() -> junkPerMachineChart.drawChart());
</code>```

i searched inside my junkPerMachineChart for a method like

.setType(ChartType.Vertical);

there is no option like this.

i also searched inside the configuration and found no method like this:

答:
i changed ChartType to COLUMN and the bars are now horizontal</p>

```<code>    Configuration conf = junkPerMachineChart.getConfiguration();
    conf.getChart().setType(ChartType.COLUMN);
</code>```

Title: horizontal bars with vaadein 8

Body:
i very new with Vaadin.

i have a chart with bars veritcally.
i want to geht horizontal bars

i have read here:
https://vaadin.com/docs/v8/charts/java-api/charts-charttypes.html

thats a part of my source (no errors):

    Chart chart = new Chart(ChartType.BAR);
    Configuration configuration = junkPerMachineChart.getConfiguration();
    configuration.getChart().setType(ChartType.BAR);
    configuration.addSeries(series);
    junkPerMachineChart.setCaption("Stündlicher Verbrauch Mischer");
    getUI().access(() -> junkPerMachineChart.drawChart());

i searched inside my junkPerMachineChart for a method like

.setType(ChartType.Vertical);

there is no option like this.

i also searched inside the configuration and found no method like this:

Body:
i changed ChartType to COLUMN and the bars are now horizontal

    Configuration conf = junkPerMachineChart.getConfiguration();
    conf.getChart().setType(ChartType.COLUMN);