问:
How can I create a Class file and JAR file without main function?
How can I create the class file and jar file for this coding, when I compile this program its not working because there is no main function in the program. And also I am trying in command prompt but I don't know how to set the classpath? please help me
My Coding is here</p>

```<code>public class NewLogFields implements ILogNotify
{
    public void onLog(Level level, String comment, IMediaStream stream, String category,String event, int status, String context) {
        if (category.equals(WMSLoggerIDs.CAT_session) && event.equals(WMSLoggerIDs.EVT_destroy))
        {
            Long csBytes = (Long)WMSLoggerFactory.getGlobalLogValue(WMSLogger IDs.FD_cs_bytes);
            Long scBytes = (Long)WMSLoggerFactory.getGlobalLogValue(WMSLogger IDs.FD_sc_bytes);
            System.out.println("disconnect: csBytes:"+csBytes+" scBytes:"+scBytes);
        }
    }
}
</code>```

答:
create the class file using the compiler: javac NewLogFileds.java
create the jar file using the jar command: jar cvf stuff.jar NewLogFileds.class

You are correct that the program needs a main() function in order to run.
add:

public static void main(String args[]) {
         // code here
}

With that you could run the code with or without the jar:

java NewLogFields
or
java -cp stuff.jar NewLogFields

There are ways of creating a MANIFEST file that tells java which class to run from the jar making the last line more simple.

Body:
How can I create the class file and jar file for this coding, when I compile this program its not working because there is no main function in the program. And also I am trying in command prompt but I don't know how to set the classpath? please help me
My Coding is here

public class NewLogFields implements ILogNotify
{
    public void onLog(Level level, String comment, IMediaStream stream, String category,String event, int status, String context) {
        if (category.equals(WMSLoggerIDs.CAT_session) && event.equals(WMSLoggerIDs.EVT_destroy))
        {
            Long csBytes = (Long)WMSLoggerFactory.getGlobalLogValue(WMSLogger IDs.FD_cs_bytes);
            Long scBytes = (Long)WMSLoggerFactory.getGlobalLogValue(WMSLogger IDs.FD_sc_bytes);
            System.out.println("disconnect: csBytes:"+csBytes+" scBytes:"+scBytes);
        }
    }
}


来源: stackexchange

问:
How to center object with CSS transform scale
I'm trying to implement a zoom in/out functionality, just like you would have on a document editor like google docs or any word processor application. The problem I'm having is that I cannot keep the "document" centered and also be able to scroll all of its parts into view. Here is a small demonstration of the problem: https://codepen.io/liviu_vasut/pen/dyGbwwO

document.getElementById('objectToScale').style.transform = "scale(3)";```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 5px;
  width: 300px;
  height: 200px;
  border: 1px solid #000000;
  left: 0px;
  top: 0px;
  margin: 10px;
  overflow: auto;
}

.object {
  position: relative;
  width: 120px;
  height: 120px;
  display: inline-block;
  background-color: grey;
  border-radius: 25px;
  padding: 5px;
  transform-origin: center;
  transform: scale(1);
}</code>```

x

```

Thanks for your time.

答:
Actually, use the transform-origin: 0 0; and manually set the scrollbar to the center:

var scaled = false;

function toggleScale() {
  [...document.getElementsByClassName('object')].forEach(e => {
    e.classList.toggle('scaled');
    e.parentElement.scrollTop = (e.parentElement.scrollHeight - e.parentElement.clientHeight) / 2;
    e.parentElement.scrollLeft = (e.parentElement.scrollWidth - e.parentElement.clientWidth) / 2;
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}

.container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 5px;
  width: 300px;
  height: 200px;
  border: 1px solid #000000;
  left: 0px;
  top: 0px;
  margin: 10px;
  overflow: auto;
}

.object {
  position: relative;
  width: 120px;
  height: 120px;
  display: inline-block;
  background-color: grey;
  border-radius: 25px;
  padding: 5px;
  transform-origin: 0 0;
}

.scaled {
  transform: scale(3);
}</code>```

<input type="button" onClick="toggleScale()" value="Toggle Scale" />

cannot see the entire object when scaled

```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to implement a zoom in/out functionality, just like you would have on a document editor like google docs or any word processor application. The problem I'm having is that I cannot keep the "document" centered and also be able to scroll all of its parts into view. Here is a small demonstration of the problem: https://codepen.io/liviu_vasut/pen/dyGbwwO

document.getElementById('objectToScale').style.transform = "scale(3)";

.container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 5px;
  width: 300px;
  height: 200px;
  border: 1px solid #000000;
  left: 0px;
  top: 0px;
  margin: 10px;
  overflow: auto;
}

.object {
  position: relative;
  width: 120px;
  height: 120px;
  display: inline-block;
  background-color: grey;
  border-radius: 25px;
  padding: 5px;
  transform-origin: center;
  transform: scale(1);
}

x

Thanks for your time.

Body:
Actually, use the transform-origin: 0 0; and manually set the scrollbar to the center:

var scaled = false;

function toggleScale() {
  [...document.getElementsByClassName('object')].forEach(e => {
    e.classList.toggle('scaled');
    e.parentElement.scrollTop = (e.parentElement.scrollHeight - e.parentElement.clientHeight) / 2;
    e.parentElement.scrollLeft = (e.parentElement.scrollWidth - e.parentElement.clientWidth) / 2;
  });
}

* {
  box-sizing: border-box;
}

.container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 5px;
  width: 300px;
  height: 200px;
  border: 1px solid #000000;
  left: 0px;
  top: 0px;
  margin: 10px;
  overflow: auto;
}

.object {
  position: relative;
  width: 120px;
  height: 120px;
  display: inline-block;
  background-color: grey;
  border-radius: 25px;
  padding: 5px;
  transform-origin: 0 0;
}

.scaled {
  transform: scale(3);
}

<input type="button" onClick="toggleScale()" value="Toggle Scale" />

<div class="container">
   <div class="object">cannot see the entire object when scaled</div>
</div>


问:
How do I declare a function with optional parameters in C#
I want to write a class for creating Excel files from Datagridviews. I want to add a bottom line with Subtotals for selected columns and the number of those columns change from 1 to 3.
I want my function work like this

```<code>exportToExcel(string title, DataGridView dgv, int colId1, int colId2, int colId3); //for with 3 sub total

//Example:
exportToExcel("Some Title",mygridview, 3);  //for 1 sub total
exportToExcel("Another Titme", othergridview, 5,6,7); //for 3 sub totals
</code>```

Do I have to create functions for different variations or is there a way to make 2nd and 3rd column numbers optional ?

答:
You can use list in the last parameter.

```<code>void exportToExcel(string str, object obj, List<int> subtotal){
//Based on Count - Logic Here
}
</code>```

On Calling,

```<code>exportToExcel("Some Title",mygridview, new List<int>{3, 4, 5});
</code>```

Body:
I want to write a class for creating Excel files from Datagridviews. I want to add a bottom line with Subtotals for selected columns and the number of those columns change from 1 to 3.
I want my function work like this

exportToExcel(string title, DataGridView dgv, int colId1, int colId2, int colId3); //for with 3 sub total

//Example:
exportToExcel("Some Title",mygridview, 3);  //for 1 sub total
exportToExcel("Another Titme", othergridview, 5,6,7); //for 3 sub totals

Do I have to create functions for different variations or is there a way to make 2nd and 3rd column numbers optional ?

Body:
You can use list in the last parameter.

void exportToExcel(string str, object obj, List<int> subtotal){
//Based on Count - Logic Here
}

On Calling,

exportToExcel("Some Title",mygridview, new List<int>{3, 4, 5});


问:
Using Images uploaded on Strapi on Nuxt front end
Below is my API data exposed from strapi.

http://myjson.com/1fgx71

I have a column post_content which is a markdown, I have uploaded image there using WYSIWYG editor. Now images uploaded has path of

```<code>/uploads/f8d87d8b6b1e41fe9ecd965078c57dc1.png
</code>```

This is the path on my Strapi server which has port of 1337.

Now on my Nuxt app I try to show this content using VueShowDown, obviously it gives error as file not found because Nuxt runs on port 3000, and there is no file present on Nuxt directory, file is stored on strapi server.

In such cases how do I show the image, which is stored on Strapi on my front end.

Thank you.

答:
hi you can create a computed variable and replace all '/uploads/' strings before show in template like:</p>
```<code>data() {
    return {
        strapi_url: 'https://url-from-your-strapi.com'
    }
}, computed: {
    changed_post_content: function () {
        return post_content.split('/uploads/').join(`${this.strapi_url}/uploads/` );
    }
},
</code>```

Body:
Below is my API data exposed from strapi.

http://myjson.com/1fgx71

I have a column post_content which is a markdown, I have uploaded image there using WYSIWYG editor. Now images uploaded has path of

/uploads/f8d87d8b6b1e41fe9ecd965078c57dc1.png

This is the path on my Strapi server which has port of 1337.

Now on my Nuxt app I try to show this content using VueShowDown, obviously it gives error as file not found because Nuxt runs on port 3000, and there is no file present on Nuxt directory, file is stored on strapi server.

In such cases how do I show the image, which is stored on Strapi on my front end.

Thank you.

Body:
hi you can create a computed variable and replace all '/uploads/' strings before show in template like:

data() {
    return {
        strapi_url: 'https://url-from-your-strapi.com'
    }
}, computed: {
    changed_post_content: function () {
        return post_content.split('/uploads/').join(`${this.strapi_url}/uploads/` );
    }
},


问:
What would I do with Azure Releases when I have a WPF application?
Would there be a purpose of Azure Releases if I'm just building a WPF application?  </p>

<p>In Azure Builds I can just use a Copy task to copy the output files to a drop location, right?  </p>

答:
What would I do with Azure Releases when I have a WPF application?

Indeed, we could just use a Copy task to copy the output files to a drop location when we build/deploy the WPF application.

However, if we have to deploy the WPF application to multiple stages/machines, in this case, we may need add one more copy task to copy the output files. In addition, if the situation of each stages/machines is different, we may not be able to use only the copy task to complete the deployment. Now, we could use the Azure Release with multiple stages, like Dev, Test, Product and so on. one stage corresponds to an environment or machine, and each environment or machine can be set individually.

On the other hand, if we use a copy task to copy the output files to deploy the WPF application, WPF application will be deployed to the target machine every time when we enable CI. Obviously, not every modification we want to deploy to the target machine. So, we need a release pipeline to separate our build and deploy.

Hope this helps.

Body:
Would there be a purpose of Azure Releases if I'm just building a WPF application?

In Azure Builds I can just use a Copy task to copy the output files to a drop location, right?


问:
How do I run an arbitrary shell command from Deno?
I want to run any arbitrary bash command from Deno, like I would with a child_process in Node. Is that possible in Deno?

答:
Deno 1.28.0 added a new API to run a shell command: Deno.Command (--allow-run permission required)

let cmd = new Deno.Command("echo", { args: ["hello world"] });
let { code, stdout, stderr } = await cmd.output();
// stdout & stderr are a Uint8Array
console.log(new TextDecoder().decode(stdout)); // hello world
```
<p>More advanced usage:</p>
<pre class="lang-js prettyprint-override"><code>const command = new Deno.Command(Deno.execPath(), {
  args: [
    "eval",
    "console.log('Hello World')",
  ],
  stdin: "piped",
  stdout: "piped",
});
const child = command.spawn();

// open a file and pipe the subprocess output to it.
child.stdout.pipeTo(
  Deno.openSync("output", { write: true, create: true }).writable,
);

// manually close stdin
child.stdin.close();
const status = await child.status;

const s = await c.status;
console.log(s);
</code>```

This API replaced the deprecated Deno.run

OLD ANSWER:

In order to run a shell command, you have to use Deno.run, which requires --allow-run permissions.

There's an ongoing discussion to use --allow-all instead for running a subprocess

The following will output to stdout.

// --allow-run
const process = Deno.run({
  cmd: ["echo", "hello world"]
});

// Close to release Deno's resources associated with the process.
// The process will continue to run after close(). To wait for it to
// finish `await process.status()` or `await process.output()`.
process.close();
```
<hr />
<p>If you want to store the output, you'll have to set <code>stdout/stderr</code> to <code>"piped"</code></p>
<pre class="lang-js prettyprint-override"><code>const process = Deno.run({
  cmd: ["echo", "hello world"],
  stdout: "piped",
  stderr: "piped"
});

const output = await process.output() // "piped" must be set
const outStr = new TextDecoder().decode(output);

/*
const error = await p.stderrOutput();
const errorStr = new TextDecoder().decode(error);
*/

process.close();
</code>```

Body:
Deno 1.28.0 added a new API to run a shell command: Deno.Command (--allow-run permission required)

let cmd = new Deno.Command("echo", { args: ["hello world"] });
let { code, stdout, stderr } = await cmd.output();
// stdout & stderr are a Uint8Array
console.log(new TextDecoder().decode(stdout)); // hello world

More advanced usage:

const command = new Deno.Command(Deno.execPath(), {
  args: [
    "eval",
    "console.log('Hello World')",
  ],
  stdin: "piped",
  stdout: "piped",
});
const child = command.spawn();

// open a file and pipe the subprocess output to it.
child.stdout.pipeTo(
  Deno.openSync("output", { write: true, create: true }).writable,
);

// manually close stdin
child.stdin.close();
const status = await child.status;

const s = await c.status;
console.log(s);

This API replaced the deprecated Deno.run

OLD ANSWER:

In order to run a shell command, you have to use Deno.run, which requires --allow-run permissions.

There's an ongoing discussion to use --allow-all instead for running a subprocess

The following will output to stdout.

// --allow-run
const process = Deno.run({
  cmd: ["echo", "hello world"]
});

// Close to release Deno's resources associated with the process.
// The process will continue to run after close(). To wait for it to
// finish `await process.status()` or `await process.output()`.
process.close();

If you want to store the output, you'll have to set stdout/stderr to "piped"

const process = Deno.run({
  cmd: ["echo", "hello world"],
  stdout: "piped",
  stderr: "piped"
});

const output = await process.output() // "piped" must be set
const outStr = new TextDecoder().decode(output);

/*
const error = await p.stderrOutput();
const errorStr = new TextDecoder().decode(error);
*/

process.close();


问:
How to import entire folder to another?
This is what my folder looks like (both folders have empty __init__.py file:

```<code>.
├── Filter
│   ├── __init__.py
│   └── stp.py
└── Time
    ├── __init__.py
    └── event.py
</code>```

In event.py I currently have (which works):

```<code>from Filter.stp import *
</code>```

But I want to change it to (import entire folder since I have many more files in reality):

```<code>import Filter
</code>```

How can I do that?

答:
this may not be the best solution.

You need to import all the files in the directory in the __init__.py foder. but since you have many files in the directory, so you can't import them manually.

therefore we must edit __ini__.py programmatically:

```<code>import sy
path = "relative path to dir"
files = os.listdir(path ) # i am assuming you only have the .py files you want to import
 files.pop('__init__.py')
import_file = open (path + '__init__.py', 'w+')
for f in files:
    import_file.write("import " + f.strip(".py") + "\n" )
import_file.close()
</code>```

I can't run the code right now, so it may not be perfect.

Title: How to import entire folder to another?

Body:
This is what my folder looks like (both folders have empty __init__.py file:

.
├── Filter
│   ├── __init__.py
│   └── stp.py
└── Time
    ├── __init__.py
    └── event.py

In event.py I currently have (which works):

from Filter.stp import *

But I want to change it to (import entire folder since I have many more files in reality):

import Filter

How can I do that?

Body:
this may not be the best solution.

You need to import all the files in the directory in the __init__.py foder. but since you have many files in the directory, so you can't import them manually.

therefore we must edit __ini__.py programmatically:

import sy
path = "relative path to dir"
files = os.listdir(path ) # i am assuming you only have the .py files you want to import
 files.pop('__init__.py')
import_file = open (path + '__init__.py', 'w+')
for f in files:
    import_file.write("import " + f.strip(".py") + "\n" )
import_file.close()

I can't run the code right now, so it may not be perfect.


问:
Why is my Symfony 5 local server showing the HTTP request as text instead of a rendered page?
I just wanted to try out Symfony 5 for my own education, so I followed the instructions here.

symfony check:requirements shows that I have the requirements needed to run the application (I'm running Windows 10 with php 7.3.4 running via php-cgi.exe)

I created the project by running symfony new my_project_name then, as per the instructions, cd into the project directory and run symfony server:start

The command line output says

[OK] Web server listening

        The Web server is using PHP CGI 7.3.4

        https://127.0.0.1:8000

But when I open the local IP address at port 8000 in my browser, I see an HTTP request as raw text, not the expected welcome page or even a 404 page.

Can anyone advise as to why the standard Symfony 5 startup instructions would not be producing the expected output and whether there's something more I need to configure to get the expected output?

答:
I had the same problem as you, but after running those commands the problem was solved:

```<code>$ symfony composer req profiler --dev
$ symfony composer req logger
</code>```

and
    $ symfony composer req debug --dev

I think it's just a composer issue.

Body:
I had the same problem as you, but after running those commands the problem was solved:

$ symfony composer req profiler --dev
$ symfony composer req logger

and
    $ symfony composer req debug --dev

I think it's just a composer issue.


问:
Property injection in to Web Api controller using Autofac
I'm trying to set a property on an System.Web.Http.ApiController to a value of a resolved IServerPackageRepository. The controller runs in a HttpSelfHostServer and the DependencyResolver has been set to AutofacWebApiDependencyResolver. Here is the code from the Autofac.Module.Load method

```<code>...

builder.RegisterType<ServerPackageRepository>()
    .As<IServerPackageRepository>()
    .SingleInstance()
    .WithParameter("path", this.StoragePath);

builder.RegisterApiControllers(Assembly.GetExecutingAssembly())
    .PropertiesAutowired();
</code>```

The ApiController controller itself has a property of type

```<code>public IServerPackageRepository Repository { get; set; }
</code>```

but is never resolved.

I am trying to do it this way because ApiController won't take nothing but default constructors. Any suggestions on how to do this the correct way using Autofac?

答:
An alternative would be to directly wire your dependency to the property like so:</p>

```<code>var repo = new ServerPackageRepository(path: this.StoragePath);

builder.RegisterInstance(repo)
    .SingleInstance();

builder.RegisterApiControllers(Assembly.GetExecutingAssembly())
    .WithProperty("Repository", repo)
    .PropertiesAutowired();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to set a property on an System.Web.Http.ApiController to a value of a resolved IServerPackageRepository. The controller runs in a HttpSelfHostServer and the DependencyResolver has been set to AutofacWebApiDependencyResolver. Here is the code from the Autofac.Module.Load method

...

builder.RegisterType<ServerPackageRepository>()
    .As<IServerPackageRepository>()
    .SingleInstance()
    .WithParameter("path", this.StoragePath);

builder.RegisterApiControllers(Assembly.GetExecutingAssembly())
    .PropertiesAutowired();

The ApiController controller itself has a property of type

public IServerPackageRepository Repository { get; set; }

but is never resolved.

I am trying to do it this way because ApiController won't take nothing but default constructors. Any suggestions on how to do this the correct way using Autofac?

Body:
An alternative would be to directly wire your dependency to the property like so:

var repo = new ServerPackageRepository(path: this.StoragePath);

builder.RegisterInstance(repo)
    .SingleInstance();

builder.RegisterApiControllers(Assembly.GetExecutingAssembly())
    .WithProperty("Repository", repo)
    .PropertiesAutowired();


问:
com.amazonaws.services.gluejobexecutor.model.VersionMismatchException
Exactly like in this AWS forum question I was running 2 Jobs concurrently. The Job was configured with Max concurrency: 10 but when executing job.commit() I receive this error message:

```<code>py4j.protocol.Py4JJavaError: An error occurred while calling z:com.amazonaws.services.glue.util.Job.commit.
: com.amazonaws.services.gluejobexecutor.model.VersionMismatchException:
Continuation update failed due to version mismatch. Expected version 6 but found version 7
(Service: AWSGlueJobExecutor; Status Code: 400; Error Code: VersionMismatchException; Request ID: 123)
</code>```

The two Jobs read different portions of data.

But I can't understand what's the problem here and how to deal with it. Anyone can help?

答:
Reporting @bgiannini's answer in this other AWS forum question, it looks like that the "version" was referring to job bookmarking.

If multiple instances of the same job are running simultaneously (i.e. max concurrency > 1) and using bookmarks, when job run 1 runs job.init() it gets a version and job.commit() seems to expect a certain value (+1 to version for every job.commit that is executed I guess?). If job run 2 started at the same time and got the same initial version from job.init(), then submits job.commit() before job 1 does, job 1 doesn't increment to the version it expected to.

Actually I was running the 2 Jobs with Job bookmark: Enable. Indeed when disabling bookmarking, looks to be working for me.

I understand it might not be the best solution but it can be a good compromise.

Body:
Exactly like in this AWS forum question I was running 2 Jobs concurrently. The Job was configured with Max concurrency: 10 but when executing job.commit() I receive this error message:

py4j.protocol.Py4JJavaError: An error occurred while calling z:com.amazonaws.services.glue.util.Job.commit.
: com.amazonaws.services.gluejobexecutor.model.VersionMismatchException:
Continuation update failed due to version mismatch. Expected version 6 but found version 7
(Service: AWSGlueJobExecutor; Status Code: 400; Error Code: VersionMismatchException; Request ID: 123)

The two Jobs read different portions of data.

But I can't understand what's the problem here and how to deal with it. Anyone can help?


问:
Javascript invalid label error
I am sorry if this question is a repeat of someother. I have looked into some of them but they don't answer my particular question.

I get an "invalid label" error where I am printing my alert statement in the code below:

```<code>    $(document).ready(
    function(){
        if( $('map#map').length > 0 ){
            //alert('found a map!');
            $('map#map area').each($area,
                function(i, val){
                    alert('Found: ' + val ):
                }
            );
        }
    }
);
</code>```

I get the same error is I do the following: alert('Found: ' + $(this) );

Can anyone tell me why this is happening, please?

ps: the elements I am attempting to read are as follows:

```<code><map id="map" name="imgmap20116293122">
<area alt="" coords="11,76,97,127" href="" shape="rect" target="" title="" />
<area alt="" coords="12,28,96,74" href="" shape="rect" target="" title="" />
<area alt="" coords="100,28,160,73" href="" shape="rect" target="" title="" />
<area alt="" coords="162,28,221,73" href="" shape="rect" target="" title="" />
<area alt="" coords="502,239,549,282" href="" shape="rect" target="" title="" />
<area alt="" coords="473,284,554,330" href="" shape="rect" target="" title="" /-->
</code>```

答:
You have a colon at the end of the statement. Change that to a semicolon.

Also, you have an extra parameter $area in the each method, which is not supported. If you remove that, the code will run.

Title: Javascript invalid label error

Body:
I am sorry if this question is a repeat of someother. I have looked into some of them but they don't answer my particular question.

I get an "invalid label" error where I am printing my alert statement in the code below:

    $(document).ready(
    function(){
        if( $('map#map').length > 0 ){
            //alert('found a map!');
            $('map#map area').each($area,
                function(i, val){
                    alert('Found: ' + val ):
                }
            );
        }
    }
);

I get the same error is I do the following: alert('Found: ' + $(this) );

Can anyone tell me why this is happening, please?

ps: the elements I am attempting to read are as follows:

<map id="map" name="imgmap20116293122">
<area alt="" coords="11,76,97,127" href="" shape="rect" target="" title="" />
<area alt="" coords="12,28,96,74" href="" shape="rect" target="" title="" />
<area alt="" coords="100,28,160,73" href="" shape="rect" target="" title="" />
<area alt="" coords="162,28,221,73" href="" shape="rect" target="" title="" />
<area alt="" coords="502,239,549,282" href="" shape="rect" target="" title="" />
<area alt="" coords="473,284,554,330" href="" shape="rect" target="" title="" /-->


问:
group_by, get most frequent and second most frequent
I have the following dataset:

```<code>a   b

1   a
1   a
1   a
1   none
2   none
2   none
2   b
3   a
3   c
3   c
3   d
4   a
</code>```

I want to get the most frequent value in b for any a and the second most frequent value of b for any a. in case two values in b have the same frequency I m indifferent about any of the two being considered the "first" or the "second".

in this case the expected output would be:

d2:

```<code>a    first    second
1    a        none
2    none     b
3    c        a(or d, doesn't matter)
4    a        NA
</code>```

as you can see a=4 has just one value in b, thus I expect a NA in the output column "second" as there is no second most frequent value.

data:

```<code>a <- c(1,1,1,1,2,2,2,3,3,3,3,4)
b<- c("a","a", "a", "none", "none", "none", "b", "a", "c" , "c",  "d","a")
d <-  data.frame(a,b)
</code>```

what I tried at the moment is the following

```<code>d1 <-  d %>% group_by(a) %>% summarize ( first =names(which.max(table(b)))  , second= names(which.max(table(b)[-which.max(table(b))] )))
</code>```

but it doesn't work properly, any idea on how to do this?

答:
You can count number of rows for a and b combination and for each value of a select 1st and 2nd value in summarise.

```<code>library(dplyr)
 d %>%
  count(a, b, sort = TRUE) %>%
  group_by(a) %>%
  summarise(first = b[1],second = b[2])

# A tibble: 4 x 3
#      a first second
#  <dbl> <chr> <chr>
#1     1 a     none
#2     2 none  b
#3     3 c     a
#4     4 a     NA
</code>```

Body:
I have the following dataset:

a   b

1   a
1   a
1   a
1   none
2   none
2   none
2   b
3   a
3   c
3   c
3   d
4   a

I want to get the most frequent value in b for any a and the second most frequent value of b for any a. in case two values in b have the same frequency I m indifferent about any of the two being considered the "first" or the "second".

in this case the expected output would be:

d2:

a    first    second
1    a        none
2    none     b
3    c        a(or d, doesn't matter)
4    a        NA

as you can see a=4 has just one value in b, thus I expect a NA in the output column "second" as there is no second most frequent value.

data:

a <- c(1,1,1,1,2,2,2,3,3,3,3,4)
b<- c("a","a", "a", "none", "none", "none", "b", "a", "c" , "c",  "d","a")
d <-  data.frame(a,b)

what I tried at the moment is the following

d1 <-  d %>% group_by(a) %>% summarize ( first =names(which.max(table(b)))  , second= names(which.max(table(b)[-which.max(table(b))] )))

but it doesn't work properly, any idea on how to do this?

Body:
You can count number of rows for a and b combination and for each value of a select 1st and 2nd value in summarise.

library(dplyr)
 d %>%
  count(a, b, sort = TRUE) %>%
  group_by(a) %>%
  summarise(first = b[1],second = b[2])

# A tibble: 4 x 3
#      a first second
#  <dbl> <chr> <chr>
#1     1 a     none
#2     2 none  b
#3     3 c     a
#4     4 a     NA


问:
How to add url prefix for server api with traefik?
I'm using traefik v2 as gateway. I have a frontend container running with host https://some.site.com which powered by traefik.

Now I have a micro-service server with multi services and all of them are listening on 80 port. I want to serve the backend server on path https://some.site.com/api/service1, https://some.site.com/api/service2 ...

I have tried traefik.http.routers.service1.rule=(Host(some.site.com) && PathPrefix(/api/service1)) but not worked and traefik.http.middlewares.add-api.addprefix.prefix=/api/service1 not worked too;

How can I implement this?

答:
Can you post your services' docker-compose configuration?
If you use middlewares, you may need to specify the service. Like</p>

```<code>traefik.http.routers.service1.middlewares=add-api
traefik.http.middlewares.add-api.addprefix.prefix=/api/service1
</code>```

Body:
Can you post your services' docker-compose configuration?
If you use middlewares, you may need to specify the service. Like

traefik.http.routers.service1.middlewares=add-api
traefik.http.middlewares.add-api.addprefix.prefix=/api/service1


问:
Should I make the method virtual or abstract?
I have an abstract class that does its own internal validation. It has another method that allows subclasses to do additional validation checks. Currently, I've made the method abstract.

```<code>protected abstract bool ValidateFurther();
</code>```

However, I'm seeing quite a number of subclasses being forced to override it just to return true. I'm considering to make the method virtual.

```<code>protected virtual bool ValidateFurther() => true;
</code>```

Is it bad to assume that validation is going to be fine in the abstract class? I'm worried that subclasses may not notice it and ended up not overriding it even when it is needed. Which is the more suitable approach here?

答:
The short answer

If this class' (and all of its derived class') purpose does not always necessitate validation, then you should go with virtual, otherwise abstract.

In other words, is validation a cornerstone of this class' purpose? (yes = abstract, no = virtual)

I suspect that virtual is the better approach here, but not for the reason you're thinking it is. The rest of this answer elaborates on why your reasoning isn't the deciding factor here, and what actually is the deciding factor.

Your reasoning

I'm seeing quite a number of subclasses being forced to override it just to return true.

I suspect you're succumbing to the programmer's reflex: "I see this repeated and must write code to avoid this repetition!"

While that is generally a good approach, it can also be misapplied when you start applying this to things that happen to be the same rather than expressing the same functional purpose.

The example I tend to use to address that point is the following:

```<code>public class Book
{
    public string Title { get; set; }
    public DateTime CreatedOn { get; set; }
}

public class EmployeeJob
{
    public string Title { get; set; }
    public DateTime CreatedOn { get; set; }
}
</code>```

There is definitely value to abstracting the CreatedOn property, as these entities are both audited data entities. The CreatedOn property is part of that audited entity, and its existence in both Book and EmployeeJob stems from these classes both being audited entities.

If a change is made to audited entities (e.g. they no longer track creation date), then that change needs to automatically persist to all audited entities. When you use shared logic, that automatically happens.

But does Title need to be abstracted into a shared logic? No. There is no functional overlap here. Yes, these properties have the same name and type, but they share no common logic whatsoever. They just happen to be equal to each other right now, but they are not tied to one another.

If a change is made to one Title property (e.g. it now becomes a Guid FK to a table of job titles), that change doesn't automatically reflect on the other (e.g. a book title would still just be a string). Implementing these Title properties using shared logic would actually cause a problem down the line instead of solve one.

In short: sometimes programmers seek more patterns than they need. Or if you allow me to quote Jurassic Park...

The deciding factor

I'm considering to make the method virtual.

Whether you make it abstract or virtual depends on one specific considerations (not DRY, as addressed above): Do you wish to provide a default implementation, or would you prefer to enforce that every consumer (i.e. derived class) evaluate the implementation of this method for themselves?

Neither of these are objectively better than the other, it's a matter of which fits best for you current scenario.

I'm seeing quite a number of subclasses being forced to override it just to return true.

I infer from this that you're essentially skipping validation in these classes, so in this case I would opt for the virtual approach since this class' (and all of its derived class') purpose does not always necessitate validation (again, that is my interpretation based on your explanation).

In other words, is validation a cornerstone of this class' purpose? (yes = abstract, no = virtual). You didn't specify your class or its purpose so I can't make that final call.

Body:
I have an abstract class that does its own internal validation. It has another method that allows subclasses to do additional validation checks. Currently, I've made the method abstract.

protected abstract bool ValidateFurther();

However, I'm seeing quite a number of subclasses being forced to override it just to return true. I'm considering to make the method virtual.

protected virtual bool ValidateFurther() => true;

Is it bad to assume that validation is going to be fine in the abstract class? I'm worried that subclasses may not notice it and ended up not overriding it even when it is needed. Which is the more suitable approach here?

Body:
The short answer

If this class' (and all of its derived class') purpose does not always necessitate validation, then you should go with virtual, otherwise abstract.

In other words, is validation a cornerstone of this class' purpose? (yes = abstract, no = virtual)

I suspect that virtual is the better approach here, but not for the reason you're thinking it is. The rest of this answer elaborates on why your reasoning isn't the deciding factor here, and what actually is the deciding factor.

Your reasoning

I'm seeing quite a number of subclasses being forced to override it just to return true.

I suspect you're succumbing to the programmer's reflex: "I see this repeated and must write code to avoid this repetition!"

While that is generally a good approach, it can also be misapplied when you start applying this to things that happen to be the same rather than expressing the same functional purpose.

The example I tend to use to address that point is the following:

public class Book
{
    public string Title { get; set; }
    public DateTime CreatedOn { get; set; }
}

public class EmployeeJob
{
    public string Title { get; set; }
    public DateTime CreatedOn { get; set; }
}

There is definitely value to abstracting the CreatedOn property, as these entities are both audited data entities. The CreatedOn property is part of that audited entity, and its existence in both Book and EmployeeJob stems from these classes both being audited entities.

If a change is made to audited entities (e.g. they no longer track creation date), then that change needs to automatically persist to all audited entities. When you use shared logic, that automatically happens.

But does Title need to be abstracted into a shared logic? No. There is no functional overlap here. Yes, these properties have the same name and type, but they share no common logic whatsoever. They just happen to be equal to each other right now, but they are not tied to one another.

If a change is made to one Title property (e.g. it now becomes a Guid FK to a table of job titles), that change doesn't automatically reflect on the other (e.g. a book title would still just be a string). Implementing these Title properties using shared logic would actually cause a problem down the line instead of solve one.

In short: sometimes programmers seek more patterns than they need. Or if you allow me to quote Jurassic Park...

The deciding factor

I'm considering to make the method virtual.

Whether you make it abstract or virtual depends on one specific considerations (not DRY, as addressed above): Do you wish to provide a default implementation, or would you prefer to enforce that every consumer (i.e. derived class) evaluate the implementation of this method for themselves?

Neither of these are objectively better than the other, it's a matter of which fits best for you current scenario.

I'm seeing quite a number of subclasses being forced to override it just to return true.

I infer from this that you're essentially skipping validation in these classes, so in this case I would opt for the virtual approach since this class' (and all of its derived class') purpose does not always necessitate validation (again, that is my interpretation based on your explanation).

In other words, is validation a cornerstone of this class' purpose? (yes = abstract, no = virtual). You didn't specify your class or its purpose so I can't make that final call.


问:
Indexing a scripting language in Eclipse
I am writing an Eclipse plugin for a 2D game engine (<http://www.ksatechnologyhq.com:1357/>) that has its own scripting language. I want to index all scripts in AIGE projects, so I can fill content assist lists with functions from other files (like Eclipse does with Java). How is this done? </p>

<p>(By the way, here is the only documentation on the syntax on said language and the extensions I want to use are AHLSL and HLSL.)</p>

答:
UA (like Help) uses Apache Lucene to index all of its content to allow for searches.  Aside from looking at the org.eclipse.help code, see also http://en.wikipedia.org/wiki/Lucene and http://darksleep.com/lucene/.  Eclipse SDK ships with 3 org.apache.lucene bundles.

AFAIK JDT maintains an AST (Abstract Syntax Tree) model.  The editor keeps its model up to date, and so at any given point has access to, say, all the methods that can be called for that object.  If I find out more I'll add an edit.

PW

Body:
I am writing an Eclipse plugin for a 2D game engine (<http://www.ksatechnologyhq.com:1357/>) that has its own scripting language. I want to index all scripts in AIGE projects, so I can fill content assist lists with functions from other files (like Eclipse does with Java). How is this done?

(By the way, here is the only documentation on the syntax on said language and the extensions I want to use are AHLSL and HLSL.)


问:
How to make a share able link in laravel to public
i have a laravel project where you can enter only using email and password this project create customer invoices and sometimes admin wants to share invoice using wtsapp and email how we can create link that can be public without email and password?
here is blade code example</p>

```<code><thead>
    <tr  class="header" id="myHeader">
        <th style="width: 20px">#</th>
        <th>Customer</th>
        <th>Units</th>
        <th>Total</th>
        <th>Sub Total</th>
        <th>Recieved</th>
        <th>Balance</th>
        <th>Advance</th>
        @if(Auth::user()->role < 3)
            <th>A Benefit</th>
            <th>Actual Ben</th>
        @endif
        <th>C Benefit</th>
        <th>S Price</th>
        <th>Date</th>
        <th>Action</th>
    </tr>
</thead>

@if ( $invoice->received_amount < $invoice->subtotal  )
    <td style="color: red" data-changein="subtotal">{{ $invoice->amount }}</td>
@elseif ( $invoice->received_amount > $invoice->subtotal && $invoice->amount_left > 0  )
    <td style="color: #CC9A2E" data-changein="subtotal">{{ $invoice->amount }}</td>
@endif
</code>```

答:
Simply remove the invoice route from your route group which has auth middleware and that should work.

Your route could be like yourapp.com/invoice/{invoice_id}. The only issue with this is anyone could read the content of invoice if they know the invoice id. Things could get worse if you are using increment id. You might want to consider using a hashed_id column to prevent this from happening.

Body:
i have a laravel project where you can enter only using email and password this project create customer invoices and sometimes admin wants to share invoice using wtsapp and email how we can create link that can be public without email and password?
here is blade code example

        #
        Customer
        Units
        Total
        Sub Total
        Recieved
        Balance
        Advance
        @if(Auth::user()->role < 3)
            A Benefit
            Actual Ben
        @endif
        C Benefit
        S Price
        Date
        Action

@if ( $invoice->received_amount < $invoice->subtotal  )
    {{ $invoice->amount }}
@elseif ( $invoice->received_amount > $invoice->subtotal && $invoice->amount_left > 0  )
    {{ $invoice->amount }}
@endif


问:
Blurry text after using CSS transform: scale(); in Chrome
Seems like there has been a recent update to Google Chrome that causes blurry text after doing a transform: scale(). Specifically I'm doing this:

@-webkit-keyframes bounceIn {
  0% {
    opacity: 0;
    -webkit-transform: scale(.3);
  }

  50% {
    opacity: 1;
    -webkit-transform: scale(1.05);
  }

  70% {
    -webkit-transform: scale(.9);
  }

  100% {
    -webkit-transform: scale(1);
  }
}
```

If you visit http://rourkery.com in Chrome, you should see the problem on the main text area. It didn't used to do this and it doesn't seem to effect other webkit browsers (like Safari). There were some other posts about people experiencing a similar issue with 3d transforms, but can't find anything about 2d transforms like this.

Any ideas would be appreciated, thanks!

答:
Just to add to the fix craze, putting {border:1px solid #???} around the badly looking object fixes the issue for me.
In case you have a stable background colour, consider this too.
This is so dumb noone thought about mentioning I guess, eh eh.</p>

Body:
Seems like there has been a recent update to Google Chrome that causes blurry text after doing a transform: scale(). Specifically I'm doing this:

@-webkit-keyframes bounceIn {
  0% {
    opacity: 0;
    -webkit-transform: scale(.3);
  }

  50% {
    opacity: 1;
    -webkit-transform: scale(1.05);
  }

  70% {
    -webkit-transform: scale(.9);
  }

  100% {
    -webkit-transform: scale(1);
  }
}

If you visit http://rourkery.com in Chrome, you should see the problem on the main text area. It didn't used to do this and it doesn't seem to effect other webkit browsers (like Safari). There were some other posts about people experiencing a similar issue with 3d transforms, but can't find anything about 2d transforms like this.

Any ideas would be appreciated, thanks!


问:
Pyinstaller does not work on an image show python application? What am I doing wrong?
I have this imsple code for testing:

```<code>#!/usr/bin/env python3
import cv2
import sys
import os

if getattr(sys, 'frozen', False):
    app_path = sys.MEIPASS
else:
    app_path = os.path.dirname(os.path.abspath(__file__))

img = cv2.imread('sammy_noise.jpg')
cv2.imshow('It works?', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Just an image show.

And I want to make this script work with double click.
I installed pypinstaller. And I ran this in the terminal:

```<code>pyinstaller --onefile --add-data="sammy_noise.jpg:." test.py
</code>```

The build is successfully but when I try to double click the exe file in the dist folder nothing happens. What am I doing wrong?

答:
I think you should try this way:

pyinstaller --onefile --add-data=sammy_noise.jpg;. test.py

Body:
I have this imsple code for testing:

#!/usr/bin/env python3
import cv2
import sys
import os

if getattr(sys, 'frozen', False):
    app_path = sys.MEIPASS
else:
    app_path = os.path.dirname(os.path.abspath(__file__))

img = cv2.imread('sammy_noise.jpg')
cv2.imshow('It works?', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Just an image show.

And I want to make this script work with double click.
I installed pypinstaller. And I ran this in the terminal:

pyinstaller --onefile --add-data="sammy_noise.jpg:." test.py

The build is successfully but when I try to double click the exe file in the dist folder nothing happens. What am I doing wrong?


问:
Difference between subroutine , co-routine , function and thread?
I have been reading the Art of Programming, vol 1, for the past 2 days.

There is a topic about subroutine and coroutine.
I am confused. I can't understand when the book says that coroutines are initialised later after main(), unlike subroutines. Furthermore, the invoked coroutine becomes a subroutine for a calling coroutine.

I tried researching over previously asked question on here, where I came to know notions of functions and thread too, in the same context.
The book gives an example about a coroutine using the MIX computer model.
Can I get any simple pseudocode, using an example about coroutines and other terminologies in the context of today's high level languages?

So, a related question: How to differ a subroutine, coroutine, function and thread?

答:
from python docs,

Coroutines are a more generalized form of subroutines. Subroutines are entered at one point and exited at another point. Coroutines can be entered, exited, and resumed at many different points. They can be implemented with the async def statement.


问:
How do I declare a function with optional parameters in C#
I want to write a class for creating Excel files from Datagridviews. I want to add a bottom line with Subtotals for selected columns and the number of those columns change from 1 to 3.
I want my function work like this

```<code>exportToExcel(string title, DataGridView dgv, int colId1, int colId2, int colId3); //for with 3 sub total

//Example:
exportToExcel("Some Title",mygridview, 3);  //for 1 sub total
exportToExcel("Another Titme", othergridview, 5,6,7); //for 3 sub totals
</code>```

Do I have to create functions for different variations or is there a way to make 2nd and 3rd column numbers optional ?

答:
You can assign default values to the optional parameter, only one thing you need to keep in mind is your optional parameters should define at the end of parameter list, after the required parameters.

```<code>public void ExportToExcel(string title, DataGridView dgv, int colId1, int colId2 = 0, int colId3 = 0)
{

   //Your business logic
}
</code>```

You can call it like,

```<code>ExportToExcel("Excel work book", dgvObj, 1); //Value of colId1 = 1, colId2 = 0 and colId3 = 0
ExportToExcel("Excel work book", dgvObj, 1, 2); //Value of colId1 = 1, colId2 = 2 and colId3 = 0
ExportToExcel("Excel work book", dgvObj, 1, 2, 3); //Value of colId1 = 1, colId2 = 2 and colId3 = 3
</code>```

You can use params int[] colIds to avoid multiple method parameters.

```<code>public void ExportToExcel(string title, DataGridView dgv, params int[] colIds)
{
   //You can access n parameters using index like colIds[0], colIds[1], colIds[2]
   //Your business logic
}
</code>```

Body:
I want to write a class for creating Excel files from Datagridviews. I want to add a bottom line with Subtotals for selected columns and the number of those columns change from 1 to 3.
I want my function work like this

exportToExcel(string title, DataGridView dgv, int colId1, int colId2, int colId3); //for with 3 sub total

//Example:
exportToExcel("Some Title",mygridview, 3);  //for 1 sub total
exportToExcel("Another Titme", othergridview, 5,6,7); //for 3 sub totals

Do I have to create functions for different variations or is there a way to make 2nd and 3rd column numbers optional ?

Body:
You can assign default values to the optional parameter, only one thing you need to keep in mind is your optional parameters should define at the end of parameter list, after the required parameters.

public void ExportToExcel(string title, DataGridView dgv, int colId1, int colId2 = 0, int colId3 = 0)
{

   //Your business logic
}

You can call it like,

ExportToExcel("Excel work book", dgvObj, 1); //Value of colId1 = 1, colId2 = 0 and colId3 = 0
ExportToExcel("Excel work book", dgvObj, 1, 2); //Value of colId1 = 1, colId2 = 2 and colId3 = 0
ExportToExcel("Excel work book", dgvObj, 1, 2, 3); //Value of colId1 = 1, colId2 = 2 and colId3 = 3

You can use params int[] colIds to avoid multiple method parameters.

public void ExportToExcel(string title, DataGridView dgv, params int[] colIds)
{
   //You can access n parameters using index like colIds[0], colIds[1], colIds[2]
   //Your business logic
}


问:
Why is the time complexity of performing n union find (union by size) operations O(n log n)?
In Tree based Implementation of Union Find operation, each element is stored in a node, which contains a pointer to a set name. A node v whose set pointer points back to v is also a set name. Each set is a tree, rooted at a node with a self-referencing set pointer.

To perform a union, we simply make the root of one tree point to the root of the other. To perform a find, we follow set name pointers from the starting node until reaching a node whose set name pointer refers back to itself.

In Union by size -> When performing a union, we make the root of smaller tree
point to the root of the larger. This implies O(n log n) time for
performing n union find operations. Each time we follow a pointer, we are going to a subtree of size at most double the size of the previous subtree. Thus, we will follow at most O(log n) pointers for any find.

I do not understand how for each union operation, Find operation is always O(log n). Can someone please explain how the worst case complexity is actually computed?

答:
We need to prove that maximum height of trees is log(N) where N is the number of items in UF (1)

In the base case, all trees have a height of 0. (1) of course satisfied

Now assuming all the trees satisfy (1) we need to prove that joining any 2 trees with i, j (i <= j) nodes will create a new tree with maximum height is log(i + j)(2):

Because the joining 2 trees procedure gets root node of the smaller tree and attach it to the root node of the bigger one so the height of the new tree will be:

```<code>max(log(j), 1 + log(i)) = max(log(j), log(2i)) <= log(i + j) => (2) proved
</code>```

log(j): height of new tree is still the height of the bigger tree

1 + log(i): when height of 2 trees are the same

See the picture below for more details:

Ref: book Algorithms

Body:
We need to prove that maximum height of trees is log(N) where N is the number of items in UF (1)

In the base case, all trees have a height of 0. (1) of course satisfied

Now assuming all the trees satisfy (1) we need to prove that joining any 2 trees with i, j (i <= j) nodes will create a new tree with maximum height is log(i + j)(2):

Because the joining 2 trees procedure gets root node of the smaller tree and attach it to the root node of the bigger one so the height of the new tree will be:

max(log(j), 1 + log(i)) = max(log(j), log(2i)) <= log(i + j) => (2) proved

log(j): height of new tree is still the height of the bigger tree

1 + log(i): when height of 2 trees are the same

See the picture below for more details:

Ref: book Algorithms


问:
Sabre API and .NET Framework
I've been tasked with upgrading our Sabre client to use the new API, we are transitioning away from "OTA_TravelItineraryReadLLSRQ" and need to use https://developer.sabre.com/docs/soap_apis/management/itinerary/Get_Itinerary (the deadline is June 30th 2020)

What is the suggested developer route I should take for this? Does a c# API client exist somewhere that I can take advantage of? Or a WSDL file?

I am very new to Sabre API and any assistance to point me into the right direction would be greatly appreciated.

答:
1) All the Sabre WSDL documentation is available on their developer portal:-
https://developer.sabre.com/docs/soap_apis/management/itinerary/Get_Itinerary/resources . Assuming that you have access to the same.

2) Verify the request and response using a tool like SoapUI. Import the WSDLs and you can make modifications as needed.

3) Do a compare of the existing API responses with the new one and perform a field mapping as per your data requirements. Make sure that all required fields are being returned. This is the key exercise. You would need to understand the data fields and the purpose of each.

4) Sabre provides sample API code for some of the API’s. It may not be exactly the same but you can refer to the same to get an idea:-https://developer.sabre.com/solutions/sample-code

5) Here is a link for resolving some common issues when importing WSDL's as web references in a .NET project:- https://developer.sabre.com/solutions/known-dotnet-bugs

6) It is important that you periodically plan your migration to an updated version of an API. All legacy versions for an API are now available to existing customers—this guarantees that you have access to legacy documentation as you version-up your application to the latest features and functionality. View the Product Catalog to find the most recent version of your APIs and also get the retirement schedule. Here is a link for the same:-
https://developer.sabre.com/guides/travel-agency/reference/api-versioning

Title: Sabre API and .NET Framework


问:
Unable to log in with python selenium
I am trying to log in to my university Moodle account using Selenium and headless chrome.

I have managed to locate the "username" and "password" elements and I am pretty sure I fill them in the correct way.
the problem is when I click submit on the form objects (or manually click the submit button) it appears that the page won't acknowledge the data that was given.

the site is:
https://moodle2.cs.huji.ac.il/nu19/

and my code:

```<code>chromeBrow = selenium.webdriver.Chrome(chrome_options=opt)
chromeBrow.get(loginPage)

# login

nameObj = chromeBrow.find_element_by_id('login_username')
nameObj.clear()
nameObj.send_keys(userName)

passObj = chromeBrow.find_element_by_id('login_password')
passObj.clear()
passObj.send_keys(userPass)

wait = WebDriverWait(chromeBrow, 1000)

submit = wait.until(EC.presence_of_all_elements_located((By.ID, "loginbtn")))
passObj.submit()
</code>```

I have tried using the WebDriverWait as suggested here, but I'm still logged out after the submission.

Thanks!

答:
At the last line, you should use:

```<code>    submit.click()
</code>```

Instead of:

```<code>    passObj.submit()
</code>```

??

Title: Unable to log in with python selenium

Body:
I am trying to log in to my university Moodle account using Selenium and headless chrome.

I have managed to locate the "username" and "password" elements and I am pretty sure I fill them in the correct way.
the problem is when I click submit on the form objects (or manually click the submit button) it appears that the page won't acknowledge the data that was given.

the site is:
https://moodle2.cs.huji.ac.il/nu19/

and my code:

chromeBrow = selenium.webdriver.Chrome(chrome_options=opt)
chromeBrow.get(loginPage)

# login

nameObj = chromeBrow.find_element_by_id('login_username')
nameObj.clear()
nameObj.send_keys(userName)

passObj = chromeBrow.find_element_by_id('login_password')
passObj.clear()
passObj.send_keys(userPass)

wait = WebDriverWait(chromeBrow, 1000)

submit = wait.until(EC.presence_of_all_elements_located((By.ID, "loginbtn")))
passObj.submit()

I have tried using the WebDriverWait as suggested here, but I'm still logged out after the submission.

Thanks!

Body:
At the last line, you should use:

    submit.click()

Instead of:

    passObj.submit()

??


问:
Vaadin img in a VerticalLaout
Second Question,

I use IntelliJIdEA and Vaadin Designer, i add a img to a VerticalLayout out an tryed to have the Img as a kind of a Header, but it will not appear on the localhost side.

the image is created from the Designer

```<code>@Id("img")
    private Image img;

</code>```

And i ve tryed to connect

```<code> Image i = new Image("frontend/turkey-5201498_1920.jpg", "Alternative image text");
        i.setSizeFull();
        img.add(i);

</code>```

Doesnt worked, i´ve connected a button Clicklistener this was working

i place the jpg in the project folder /folder/file.jpg

Thank you for the help in front !

答:
Where you should place your static files and how you refer to them depends a little on what tools you have in your chain. If you are using the default recommended stack with Spring boot, then your image should be in /src/main/resources/META-INF/resources/img/turkey-5201498_1920.jpg and you should refer to it as new Image("img/turkey-5201498_1920.jpg", "Alternative image text")

For non-Spring Boot apps, and for more details, check this awesome reply in another Stack Overflow question. https://stackoverflow.com/a/57553974/64095

Title: Vaadin img in a VerticalLaout

Body:
Second Question,

I use IntelliJIdEA and Vaadin Designer, i add a img to a VerticalLayout out an tryed to have the Img as a kind of a Header, but it will not appear on the localhost side.

the image is created from the Designer

@Id("img")
    private Image img;

And i ve tryed to connect

 Image i = new Image("frontend/turkey-5201498_1920.jpg", "Alternative image text");
        i.setSizeFull();
        img.add(i);

Doesnt worked, i´ve connected a button Clicklistener this was working

i place the jpg in the project folder /folder/file.jpg

Thank you for the help in front !


问:
"PT" Formatted time string in python
I'm receiving a string which is formatted in the following way: "PTXMYS" Where X is the amount of minutes and Y is the amount of seconds.

I'd like to turn that string into an int which presents the amount of seconds in total.
I tried using datetime and other stuff and it just won't work for me, I read online that this formatting is standard for iso8601 so it's weird for me that it doesn't really work.

String example:

```<code>x="PT4M13S"
</code>```

答:
there is a third-party library that can parse these strings, isodate:

```<code>import isodate
isodate.parse_duration("PT4M13S")
# datetime.timedelta(seconds=253)
isodate.parse_duration("PT4M13S").total_seconds()
# 253.0
</code>```

And for completeness, there is an option to do this with datetime's strptime and timedelta's total_seconds():

```<code>from datetime import datetime, timedelta
# parse minute and second to datetime object:
t = datetime.strptime("PT4M13S","PT%MM%SS")
# convert to timedelta to get the total seconds
td = timedelta(minutes=t.minute, seconds=t.second)
td.total_seconds()
# 253
</code>```

Title: "PT" Formatted time string in python

Body:
I'm receiving a string which is formatted in the following way: "PTXMYS" Where X is the amount of minutes and Y is the amount of seconds.

I'd like to turn that string into an int which presents the amount of seconds in total.
I tried using datetime and other stuff and it just won't work for me, I read online that this formatting is standard for iso8601 so it's weird for me that it doesn't really work.

String example:

x="PT4M13S"

Body:
there is a third-party library that can parse these strings, isodate:

import isodate
isodate.parse_duration("PT4M13S")
# datetime.timedelta(seconds=253)
isodate.parse_duration("PT4M13S").total_seconds()
# 253.0

And for completeness, there is an option to do this with datetime's strptime and timedelta's total_seconds():

from datetime import datetime, timedelta
# parse minute and second to datetime object:
t = datetime.strptime("PT4M13S","PT%MM%SS")
# convert to timedelta to get the total seconds
td = timedelta(minutes=t.minute, seconds=t.second)
td.total_seconds()
# 253


问:
Validation using Yup to check array length --> error if length === 1
I have the following object:

```<code>{
    array: [1]
}
</code>```

And the following code:

```<code>myArray: Yup.array().of(
    Yup.object().shape({
        name: Yup.string().max(255).required().label('Name')
    })
)
</code>```

Now I check the name is required, I need to check if myArray has length === 1 to return an error.

答:
You could use mixed.test(options: object) if you just want to test length === 1:

```<code>myArray: array()
  .of(
    object().shape({
      name: string()
        .max(255)
        .required()
        .label("Name")
    })
  )
  .test({
    message: 'The error message if length === 1',
    test: arr => arr.length !== 1,
  })
</code>```

Demo:

And array.min(limit: number | Ref, message?: string | function) if you want to test length === 0 | 1 :

```<code>myArray: Yup.array()
  .of(
    Yup.object().shape({
      name:Yup.string()
        .max(255)
        .required()
        .label('Name')
      })
  )
  .min(2, 'The error message if length === 0 | 1')
</code>```

Demo:

Body:
I have the following object:

{
    array: [1]
}

And the following code:

myArray: Yup.array().of(
    Yup.object().shape({
        name: Yup.string().max(255).required().label('Name')
    })
)

Now I check the name is required, I need to check if myArray has length === 1 to return an error.

Body:
You could use mixed.test(options: object) if you just want to test length === 1:

myArray: array()
  .of(
    object().shape({
      name: string()
        .max(255)
        .required()
        .label("Name")
    })
  )
  .test({
    message: 'The error message if length === 1',
    test: arr => arr.length !== 1,
  })

Demo:

And array.min(limit: number | Ref, message?: string | function) if you want to test length === 0 | 1 :

myArray: Yup.array()
  .of(
    Yup.object().shape({
      name:Yup.string()
        .max(255)
        .required()
        .label('Name')
      })
  )
  .min(2, 'The error message if length === 0 | 1')

Demo:


问:
React field onChange not firing when value gets inserted programatically (hooks, not classes)

I'm writing an app (from full stack open) which will search through countries, and display country information if only one country is selected.
The application works well when a human uses it, however, if more than 1 country is displayed, I want the user to be able to click a 'show' button next to the country name, and display the country information for the given country.

 I figured I could just create a function that changes the search field's value, and set the value to the given country's name.

My problem is, that the onChange on the input doesn't fire when it gets filled out programmatically.

I've tried create a new hook just for the input field, but I couldn't get that to work either.
How can I go about making my onChange trigger when the field is filled programmatically?

I want to do this in the function toggleShowCountry

Code:

```<code>
import React, {useState, useEffect} from 'react';

import axios from 'axios';

function App() {

  const [countries, setCountries] = useState([]);
  const [search, setSearch] = useState(countries);
  const [inputField, setInputField] = useState("");

  const fetchCountries = () => {
    axios
    .get('https://restcountries.eu/rest/v2/all')
    .then(response => {
      setCountries(response.data);
    });
  };
  useEffect(fetchCountries, []);

  const handleSearch = (e) => {
    e.preventDefault();
    const searchField = document.querySelector('#searchCountry').value;

      setSearch(Object.values(countries).filter(country =>
        country.name.toLowerCase().includes(searchField.toLowerCase())))

  }

  const toggleShowCountry = (props) => {

    const searchField = document.querySelector('#searchCountry');
    searchField.value = props;

  }

  return (
    <div>
      <h2>Search countries</h2>
      <Search handleSearch={handleSearch} />
      <Display countries={search} toggleShowCountry={toggleShowCountry} />
    </div>
  )
}

const Display = (props) => {

  const countries = props.countries;
  let filteredCountries = countries.map(country => country);

  if (countries.length > 10){
    return(
      <>
        <p>Too many matches, specify another filter.</p>
      </>
    )
  } else if (countries.length === 1){
    return (
      <>
      {filteredCountries.map(country =>
        <div key={country}>
          <ShowCountry country={country} key={country} />

        </div>
      )}

      </>
    )
  } else {
    return (
      <>

        {filteredCountries.map(country =>
          <ul key={country.name}>
            <FilteredCountries country={country} key={country.name} toggleShowCountry={props.toggleShowCountry}/>
          </ul>
        )}
      </>
    )
  }
}

const FilteredCountries = (props) => {
  const country = props.country;
  return (
    <>
      <li>{country.name} <button onClick={() => props.toggleShowCountry(country.name)}>Show</button></li>
    </>
  )
}

const ShowCountry = ({country}) => {

  return (
    <>
      <h2>{country.name}</h2>
      <p>Capital: {country.capital}</p>
      <p>Population: {country.population}</p>

      <h3><strong>Languages</strong></h3>
      <ul>
        {country.languages.map(language =>
          <li key={language.name}>{language.name}</li>
        )}
      </ul>
      <img src={country.flag} alt="flag" width="100px"/>
    </>
  )
}

const Search = (props) => {
  return (
    <div>
      <form>
        <div>
          <label htmlFor="countries">Enter country </label>
          <input name="countries" id="searchCountry" onChange={props.handleSearch} />
        </div>
      </form>
    </div>
  )
}

export default App;
</code>```

答: The input onChange event handler only gets called when the input loses focus which means that it won't get called unless you force the input to lose focus or call the onChange result manually. Like Denis Stukalov showed. :)

Body:
I'm writing an app (from full stack open) which will search through countries, and display country information if only one country is selected.
The application works well when a human uses it, however, if more than 1 country is displayed, I want the user to be able to click a 'show' button next to the country name, and display the country information for the given country.

 I figured I could just create a function that changes the search field's value, and set the value to the given country's name.

My problem is, that the onChange on the input doesn't fire when it gets filled out programmatically.

I've tried create a new hook just for the input field, but I couldn't get that to work either.
How can I go about making my onChange trigger when the field is filled programmatically?

I want to do this in the function toggleShowCountry

Code:

import React, {useState, useEffect} from 'react';

import axios from 'axios';

function App() {

  const [countries, setCountries] = useState([]);
  const [search, setSearch] = useState(countries);
  const [inputField, setInputField] = useState("");

  const fetchCountries = () => {
    axios
    .get('https://restcountries.eu/rest/v2/all')
    .then(response => {
      setCountries(response.data);
    });
  };
  useEffect(fetchCountries, []);

  const handleSearch = (e) => {
    e.preventDefault();
    const searchField = document.querySelector('#searchCountry').value;

      setSearch(Object.values(countries).filter(country =>
        country.name.toLowerCase().includes(searchField.toLowerCase())))

  }

  const toggleShowCountry = (props) => {

    const searchField = document.querySelector('#searchCountry');
    searchField.value = props;

  }

  return (

Search countries

      <Search handleSearch={handleSearch} />
      <Display countries={search} toggleShowCountry={toggleShowCountry} />

  )
}

const Display = (props) => {

  const countries = props.countries;
  let filteredCountries = countries.map(country => country);

  if (countries.length > 10){
    return(
      <>

Too many matches, specify another filter.

      </>
    )
  } else if (countries.length === 1){
    return (
      <>
      {filteredCountries.map(country =>

          <ShowCountry country={country} key={country} />

      )}

      </>
    )
  } else {
    return (
      <>

        {filteredCountries.map(country =>

            <FilteredCountries country={country} key={country.name} toggleShowCountry={props.toggleShowCountry}/>

        )}
      </>
    )
  }
}

const FilteredCountries = (props) => {
  const country = props.country;
  return (
    <>

{country.name} <button onClick={() => props.toggleShowCountry(country.name)}>Show</button>

    </>
  )
}

const ShowCountry = ({country}) => {

  return (
    <>

{country.name}

Capital: {country.capital}

Population: {country.population}

Languages

        {country.languages.map(language =>

{language.name}

        )}

    </>
  )
}

const Search = (props) => {
  return (

      <form>

          Enter country
          <input name="countries" id="searchCountry" onChange={props.handleSearch} />

      </form>

  )
}

export default App;


问:
JOOQ, Unknown column 'ideas_service.parent_section.id' in 'on clause' when joining multiple tables
So I have five tables I am trying to get back in one query

```<code>parent_section(id, gate_id)

Assessment_Question(id,parent_section_id)

Assessment_question_multi_choice_option(id, question_id)

Assessment_answer_Group(id, entity_id)

Assessment_Answer(id,assessment_question_id, assessment_answer_Group_id)
</code>```

I am trying to list all questions

Error is Unknown column 'ideas_service.parent_section.id' in 'on clause'

Here is my query

```<code>        dsl.select()
        .from(PARENT_SECTION,ASSESSMENT_ANSWER_GROUP)
        .join(ASSESSMENT_QUESTION)
        .on(PARENT_SECTION.ID.eq(ASSESSMENT_QUESTION.PARENT_SECTION_ID))
        .leftJoin(ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION)
        .on(
            ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION.ASSESSMENT_QUESTION_ID.eq(
                ASSESSMENT_QUESTION.ID))
        .join(ASSESSMENT_ANSWER)
        .on(ASSESSMENT_ANSWER_GROUP.ID.eq(ASSESSMENT_ANSWER.ASSESSMENT_ANSWER_GROUP_ID))
        .where(PARENT_SECTION.GATE_ID.eq(gateId))
        .fetch()
</code>```

Previously when I was only trying to query the table for three tables, parent_Section_assessment_question and assessment_question_multi_choice, my query was like this and it worked

```<code>    var queryResult =
    dsl.select()
        .from(PARENT_SECTION)
        .join(ASSESSMENT_QUESTION)
        .on(PARENT_SECTION.ID.eq(ASSESSMENT_QUESTION.PARENT_SECTION_ID))
        .leftJoin(ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION)
        .on(
            ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION.ASSESSMENT_QUESTION_ID.eq(
                ASSESSMENT_QUESTION.ID))
        .where(PARENT_SECTION.GATE_ID.eq(gateId))
        .fetch()
</code>```

How should I modify the working query to also list a join between a assessment_Answer_Group( where assessment_answer_Group.entity_id = x) on the questions assessment_answer.answer_group_id

To clarify on the joining structure

I am doing an inner join between parent_section and assessment_Question and a left join between assessment_question and assessment_multi_choice_option

The join between answer_group and assessment_answer is separate from those three tables, it should be where assessment_answer_group.entity_id = x and join on assessment_Answer.answer_Group_id = assessment_answer_Grorup.id

edit: After akinas comments my query is now this, it finds the assessment_answer_group but it does not find any assessment_answers

```<code>    var queryResult =
    dsl.select()
      //below line is cross join with an always true join coniditon
        .from(PARENT_SECTION.join(ASSESSMENT_ANSWER_GROUP).on(true))
        .join(ASSESSMENT_QUESTION)
        .on(PARENT_SECTION.ID.eq(ASSESSMENT_QUESTION.PARENT_SECTION_ID))
        .leftJoin(ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION)
        .on(
            ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION.ASSESSMENT_QUESTION_ID.eq(
                ASSESSMENT_QUESTION.ID))
        .join(ASSESSMENT_ANSWER)
        .on(ASSESSMENT_ANSWER_GROUP.ID.eq(ASSESSMENT_ANSWER.ASSESSMENT_ANSWER_GROUP_ID))
        .where(PARENT_SECTION.GATE_ID.eq(gateId))
</code>```

答:
Why are you getting the syntax error

The reason why you're getting this error:

Error is Unknown column 'ideas_service.parent_section.id' in 'on clause'

Is because you're joining ASSESSMENT_QUESTION to ASSESSMENT_ANSWER_GROUP, not to PARENT_SECTION in your jOOQ query:

dsl.select()
   .from(PARENT_SECTION,ASSESSMENT_ANSWER_GROUP)
   .join(ASSESSMENT_QUESTION)
   .on(PARENT_SECTION.ID.eq(ASSESSMENT_QUESTION.PARENT_SECTION_ID))
   // ...
```

<p>As others have pointed out in the comments, you're mixing comma separated from lists with ANSI JOIN syntax. This is hardly ever recommended, both in SQL, or in jOOQ. In jOOQ, your above query corresponds to this SQL:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT *
FROM PARENT_SECTION, (
  ASSESSMENT_ANSWER_GROUP
    JOIN ASSESSMENT_QUESTION
      ON PARENT_SECTION.ID = ASSESSMENT_QUESTION.PARENT_ID
  )
..
</code>```

As you can see, the join expression doesn't make any sense because you're joining two tables using a predicate that references a table that is not in scope. I recently wrote a blog post that might help understanding SQL JOIN syntax by adding such parentheses. I think the parentheses definitely help here.

Here's my advice on getting joins right:

Never mix table lists with ANSI joins, it's usually just trouble (although, it can be useful in edge cases). If you need outer joins, you cannot use table lists in most SQL dialects (except for Oracle), so you need ANSI joins anyway. Stick to them.

Be careful of mixing outer joins with inner joins. Joins are operators, and it's important to be aware of their associativity

Cartesian products

But you have another problem. You cannot easily join several to-many relationships in SQL, or you'll get cartesian products. Meaning:

A PARENT_SECTION can have many ASSESSMENT_QUESTION, which can have many ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION. These are 2 levels of to-many relationships, which will duplicate the PARENT_SECTION per ASSESSMENT_QUESTION and again the ASSESSMENT_QUESTION per ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION. This repeated duplication is OK, because you're going down one branch of your join tree.

However, an ASSESSMENT_QUESTION also has several ASSESSMENT_ANSWER, because that's another to-many relationship. This is causing problems.

So, you'll end up with a cartesian product between ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION and ASSESSMENT_ANSWER, as you're traversing two separate to-many branches of your join tree, which is definitely not what you want.

While your 5-join query might eventually be right syntactically, it will still be wrong semantically!

Getting it right

You will have to resort to using either XML/JSON (available from jOOQ 3.14), or run (at least) 2 queries:

// Query 1 producing ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION
dsl.select()
   .from(PARENT_SECTION)
   .join(ASSESSMENT_QUESTION)
     .on(ASSESSMENT_QUESTION.PARENT_SECTION_ID.eq(PARENT_SECTION.ID))
   .leftJoin(ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION)
     .on(ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION.ASSESSMENT_QUESTION_ID
       .eq(ASSESSMENT_QUESTION.ID))
   .where(PARENT_SECTION.GATE_ID.eq(gateId))
   .fetch();

// Query 2 producing ASSESSMENT_ANSWER and ASSESSMENT_ANSWER_GROUP
dsl.select()
   .from(ASSESSMENT_ANSWER)
   .join(ASSESSMENT_ANSWER_GROUP)
     .on(ASSESSMENT_ANSWER_GROUP.ID.eq(ASSESSMENT_ANSWER.ASSESSMENT_ANSWER_GROUP_ID))
   .where(ASSESSMENT_ANSWER.ASSESSMENT_QUESTION_ID.in(
     select(ASSESSMENT_QUESTION.ID)
     .from(ASSESSMENT_QUESTION)
     .join(PARENT_SECTION)
     .on(ASSESSMENT_QUESTION.PARENT_SECTION_ID.eq(PARENT_SECTION.ID))
     .where(PARENT_SECTION.GATE_ID.eq(gateId))
   ))
   .fetch();
```

<p>You can then assemble the results together in your client. Notice the second query doesn't need to join <code>PARENT_SECTION</code> and <code>ASSESSMENT_QUESTION</code> anymore. A semi join (implemented using the <code>IN</code> predicate) will suffice</p>

<h3>Using implicit joins</h3>

<p>jOOQ supports implicit joins for to-one relationships. The above Query 2 could also be written like this, which is perhaps a bit simpler (although I do recommend you study "real" joins first):</p>

<pre class="lang-java prettyprint-override"><code>dsl.select()
   .from(ASSESSMENT_ANSWER)
   .join(ASSESSMENT_ANSWER_GROUP)
     .on(ASSESSMENT_ANSWER_GROUP.ID.eq(ASSESSMENT_ANSWER.ASSESSMENT_ANSWER_GROUP_ID))
   .where(ASSESSMENT_ANSWER.assessmentQuestion().parentSection().GATE_ID.eq(gateId))
   .fetch();
</code>```

Body:
So I have five tables I am trying to get back in one query

parent_section(id, gate_id)

Assessment_Question(id,parent_section_id)

Assessment_question_multi_choice_option(id, question_id)

Assessment_answer_Group(id, entity_id)

Assessment_Answer(id,assessment_question_id, assessment_answer_Group_id)

I am trying to list all questions

Error is Unknown column 'ideas_service.parent_section.id' in 'on clause'

Here is my query

        dsl.select()
        .from(PARENT_SECTION,ASSESSMENT_ANSWER_GROUP)
        .join(ASSESSMENT_QUESTION)
        .on(PARENT_SECTION.ID.eq(ASSESSMENT_QUESTION.PARENT_SECTION_ID))
        .leftJoin(ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION)
        .on(
            ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION.ASSESSMENT_QUESTION_ID.eq(
                ASSESSMENT_QUESTION.ID))
        .join(ASSESSMENT_ANSWER)
        .on(ASSESSMENT_ANSWER_GROUP.ID.eq(ASSESSMENT_ANSWER.ASSESSMENT_ANSWER_GROUP_ID))
        .where(PARENT_SECTION.GATE_ID.eq(gateId))
        .fetch()

Previously when I was only trying to query the table for three tables, parent_Section_assessment_question and assessment_question_multi_choice, my query was like this and it worked

    var queryResult =
    dsl.select()
        .from(PARENT_SECTION)
        .join(ASSESSMENT_QUESTION)
        .on(PARENT_SECTION.ID.eq(ASSESSMENT_QUESTION.PARENT_SECTION_ID))
        .leftJoin(ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION)
        .on(
            ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION.ASSESSMENT_QUESTION_ID.eq(
                ASSESSMENT_QUESTION.ID))
        .where(PARENT_SECTION.GATE_ID.eq(gateId))
        .fetch()

How should I modify the working query to also list a join between a assessment_Answer_Group( where assessment_answer_Group.entity_id = x) on the questions assessment_answer.answer_group_id

To clarify on the joining structure

I am doing an inner join between parent_section and assessment_Question and a left join between assessment_question and assessment_multi_choice_option

The join between answer_group and assessment_answer is separate from those three tables, it should be where assessment_answer_group.entity_id = x and join on assessment_Answer.answer_Group_id = assessment_answer_Grorup.id

edit: After akinas comments my query is now this, it finds the assessment_answer_group but it does not find any assessment_answers

    var queryResult =
    dsl.select()
      //below line is cross join with an always true join coniditon
        .from(PARENT_SECTION.join(ASSESSMENT_ANSWER_GROUP).on(true))
        .join(ASSESSMENT_QUESTION)
        .on(PARENT_SECTION.ID.eq(ASSESSMENT_QUESTION.PARENT_SECTION_ID))
        .leftJoin(ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION)
        .on(
            ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION.ASSESSMENT_QUESTION_ID.eq(
                ASSESSMENT_QUESTION.ID))
        .join(ASSESSMENT_ANSWER)
        .on(ASSESSMENT_ANSWER_GROUP.ID.eq(ASSESSMENT_ANSWER.ASSESSMENT_ANSWER_GROUP_ID))
        .where(PARENT_SECTION.GATE_ID.eq(gateId))

Body:
Why are you getting the syntax error

The reason why you're getting this error:

Error is Unknown column 'ideas_service.parent_section.id' in 'on clause'

Is because you're joining ASSESSMENT_QUESTION to ASSESSMENT_ANSWER_GROUP, not to PARENT_SECTION in your jOOQ query:

dsl.select()
   .from(PARENT_SECTION,ASSESSMENT_ANSWER_GROUP)
   .join(ASSESSMENT_QUESTION)
   .on(PARENT_SECTION.ID.eq(ASSESSMENT_QUESTION.PARENT_SECTION_ID))
   // ...

As others have pointed out in the comments, you're mixing comma separated from lists with ANSI JOIN syntax. This is hardly ever recommended, both in SQL, or in jOOQ. In jOOQ, your above query corresponds to this SQL:

SELECT *
FROM PARENT_SECTION, (
  ASSESSMENT_ANSWER_GROUP
    JOIN ASSESSMENT_QUESTION
      ON PARENT_SECTION.ID = ASSESSMENT_QUESTION.PARENT_ID
  )
..

As you can see, the join expression doesn't make any sense because you're joining two tables using a predicate that references a table that is not in scope. I recently wrote a blog post that might help understanding SQL JOIN syntax by adding such parentheses. I think the parentheses definitely help here.

Here's my advice on getting joins right:

Never mix table lists with ANSI joins, it's usually just trouble (although, it can be useful in edge cases). If you need outer joins, you cannot use table lists in most SQL dialects (except for Oracle), so you need ANSI joins anyway. Stick to them.

Be careful of mixing outer joins with inner joins. Joins are operators, and it's important to be aware of their associativity

Cartesian products

But you have another problem. You cannot easily join several to-many relationships in SQL, or you'll get cartesian products. Meaning:

A PARENT_SECTION can have many ASSESSMENT_QUESTION, which can have many ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION. These are 2 levels of to-many relationships, which will duplicate the PARENT_SECTION per ASSESSMENT_QUESTION and again the ASSESSMENT_QUESTION per ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION. This repeated duplication is OK, because you're going down one branch of your join tree.

However, an ASSESSMENT_QUESTION also has several ASSESSMENT_ANSWER, because that's another to-many relationship. This is causing problems.

So, you'll end up with a cartesian product between ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION and ASSESSMENT_ANSWER, as you're traversing two separate to-many branches of your join tree, which is definitely not what you want.

While your 5-join query might eventually be right syntactically, it will still be wrong semantically!

Getting it right

You will have to resort to using either XML/JSON (available from jOOQ 3.14), or run (at least) 2 queries:

// Query 1 producing ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION
dsl.select()
   .from(PARENT_SECTION)
   .join(ASSESSMENT_QUESTION)
     .on(ASSESSMENT_QUESTION.PARENT_SECTION_ID.eq(PARENT_SECTION.ID))
   .leftJoin(ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION)
     .on(ASSESSMENT_QUESTION_MULTI_CHOICE_OPTION.ASSESSMENT_QUESTION_ID
       .eq(ASSESSMENT_QUESTION.ID))
   .where(PARENT_SECTION.GATE_ID.eq(gateId))
   .fetch();

// Query 2 producing ASSESSMENT_ANSWER and ASSESSMENT_ANSWER_GROUP
dsl.select()
   .from(ASSESSMENT_ANSWER)
   .join(ASSESSMENT_ANSWER_GROUP)
     .on(ASSESSMENT_ANSWER_GROUP.ID.eq(ASSESSMENT_ANSWER.ASSESSMENT_ANSWER_GROUP_ID))
   .where(ASSESSMENT_ANSWER.ASSESSMENT_QUESTION_ID.in(
     select(ASSESSMENT_QUESTION.ID)
     .from(ASSESSMENT_QUESTION)
     .join(PARENT_SECTION)
     .on(ASSESSMENT_QUESTION.PARENT_SECTION_ID.eq(PARENT_SECTION.ID))
     .where(PARENT_SECTION.GATE_ID.eq(gateId))
   ))
   .fetch();

You can then assemble the results together in your client. Notice the second query doesn't need to join PARENT_SECTION and ASSESSMENT_QUESTION anymore. A semi join (implemented using the IN predicate) will suffice

Using implicit joins

jOOQ supports implicit joins for to-one relationships. The above Query 2 could also be written like this, which is perhaps a bit simpler (although I do recommend you study "real" joins first):

dsl.select()
   .from(ASSESSMENT_ANSWER)
   .join(ASSESSMENT_ANSWER_GROUP)
     .on(ASSESSMENT_ANSWER_GROUP.ID.eq(ASSESSMENT_ANSWER.ASSESSMENT_ANSWER_GROUP_ID))
   .where(ASSESSMENT_ANSWER.assessmentQuestion().parentSection().GATE_ID.eq(gateId))
   .fetch();


问:
Using Sharp to compress image size without changing aspect ratio of the image
I have an aws image file and Iam compressing the image using sharp , but after compressing, the file size is increasing hugely . In my case I have an image size of 6.5MB , which after compressing it is becoming 19.5MB.

The following is my code :

```<code>const width = parseInt(image.height);
const height = parseInt(image.width);

var getObjectParams = {
  Bucket: BUCKET,
  Key: FILE_NAME
}

  s3.getObject(getObjectParams).promise()
    .then(data => {
      sharp(data.Body)
       .resize(width, height)
        .ignoreAspectRatio()
        .toFormat('png')
        .toBuffer()
        .then((buffer) => {
         ........
         ........
    }
</code>```

I have even tried using .max() ,

```<code> sharp(data.Body)
 .withoutEnlargement()
 .resize(width, height)
 .toFormat('png')
 .toBuffer()
</code>```

The same issue , file size is increasing . In my case the image aspect ratio should be maintained. Any suggestions would be appreciated. Thanks

答:
This is a common problem with Sharp but yet this is a nice & amazing package. Read the Sharp documentation for png.

If you need to play around with;
options.quality, options.colours, options.dither to compress a significant amount of any PNG image and according to its doc,

requires libvips compiled with support for libimagequant

So you need the help of libimagequant to achieve your goal.
According to the site, libimagequant is a Small, portable C library for high-quality conversion of RGBA images to 8-bit indexed-color (palette) images.

Instead you can use this NPM PACKAGE called imagemin and I am sure it uses the same method to compress PNG images. With a small piece of code as below, you can reduce the size of PNG.

```<code>const files = await imagemin(['images/*.{png}'], {
    destination: 'build/images',
        plugins: [
            imageminJpegtran(),
            imageminPngquant({
                quality: [0.6, 0.8]
            })
        ]
});
</code>```

Play around with quality: [0.6, 0.8] like quality: [0.2, 0.2] to reduce the size and you can pass a single image file like const files = await imagemin(['fileName.png']

Body:
I have an aws image file and Iam compressing the image using sharp , but after compressing, the file size is increasing hugely . In my case I have an image size of 6.5MB , which after compressing it is becoming 19.5MB.

The following is my code :

const width = parseInt(image.height);
const height = parseInt(image.width);

var getObjectParams = {
  Bucket: BUCKET,
  Key: FILE_NAME
}

  s3.getObject(getObjectParams).promise()
    .then(data => {
      sharp(data.Body)
       .resize(width, height)
        .ignoreAspectRatio()
        .toFormat('png')
        .toBuffer()
        .then((buffer) => {
         ........
         ........
    }

I have even tried using .max() ,

 sharp(data.Body)
 .withoutEnlargement()
 .resize(width, height)
 .toFormat('png')
 .toBuffer()

The same issue , file size is increasing . In my case the image aspect ratio should be maintained. Any suggestions would be appreciated. Thanks

Body:
This is a common problem with Sharp but yet this is a nice & amazing package. Read the Sharp documentation for png.

If you need to play around with;
options.quality, options.colours, options.dither to compress a significant amount of any PNG image and according to its doc,

requires libvips compiled with support for libimagequant

So you need the help of libimagequant to achieve your goal.
According to the site, libimagequant is a Small, portable C library for high-quality conversion of RGBA images to 8-bit indexed-color (palette) images.

Instead you can use this NPM PACKAGE called imagemin and I am sure it uses the same method to compress PNG images. With a small piece of code as below, you can reduce the size of PNG.

const files = await imagemin(['images/*.{png}'], {
    destination: 'build/images',
        plugins: [
            imageminJpegtran(),
            imageminPngquant({
                quality: [0.6, 0.8]
            })
        ]
});

Play around with quality: [0.6, 0.8] like quality: [0.2, 0.2] to reduce the size and you can pass a single image file like const files = await imagemin(['fileName.png']


问:
File sharing in Python
I have 4 computers in a network. I am curios if anyone know how i can i make python to look for some files in different folders from the network or if i can create a mount point that include some folders from different computers. The reason is that i am running a script that needs to open some daemons on different computer. For instance i have the following folders from which i need to run:

```<code>/temp on 10.18.2.25
/opt on 10.18.2.35
/var-temp on 10.18.4.12
/spam on 10.18.2.17
</code>```

I am using the command os.system('exec .....') to launch it , but only works for the current directory.

答:
It sounds like you don't merely want to execute files stored on different machines on one machine, but on the machines they're stored on. Mounting won't help with that.

You'd need a daemon already running on the target, and tell it over the network to execute a file. xinetd is a common one.

Title: File sharing in Python

Body:
I have 4 computers in a network. I am curios if anyone know how i can i make python to look for some files in different folders from the network or if i can create a mount point that include some folders from different computers. The reason is that i am running a script that needs to open some daemons on different computer. For instance i have the following folders from which i need to run:

/temp on 10.18.2.25
/opt on 10.18.2.35
/var-temp on 10.18.4.12
/spam on 10.18.2.17

I am using the command os.system('exec .....') to launch it , but only works for the current directory.