问:
How to make text boxes appear using jQuery
I am trying to make the corresponding textarea appear when Abnormal is clicked and disappear when Normal is clicked. The problem I am having is that when I click Abnormal for one question it affects both textareas and not the one it corresponds to.

$("[nfield='horizontal_field']").on("change", function() {
  $("[mrbvalue='Normal']").on('change', function() {
    if ($("[mrbvalue='Normal']:checked")) {
      $('[nfield="txt_fieldhori"]').show()
    }
  });

  $("[mrbvalue='Abnormal']").on('change', function() {
    if ($("[mrbvalue='Abnormal']:checked")) {
      $('[nfield="txt_fieldhori"]').hide()
    }
  });
})

$("[nfield='vert_field']").on('change', function() {
  $("[mrbvalue='Normal']").on('change', function() {
    if ($("[mrbvalue='Normal']:checked")) {
      $('[nfield="txt_nooo"]').show()
    }
  });

  $("[mrbvalue='Abnormal']").on('change', function() {
    if ($("[mrbvalue='Abnormal']:checked")) {
      $('[nfield="txt_nooo"]').hide()
    }
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="n-mrb n-choice q" nfield="horizontal_field">
  <div class="mrb-item"><label><input type="radio" name="horizontal_field" mrbvalue="Normal" class="k-valid"> Normal</label></div>
  <div class="mrb-item"><label><input type="radio" name="horizontal_field" mrbvalue="Abnormal" class="k-valid"> Abnormal</label></div>
</div>
<textarea class="n-text comment -EntireLine ee k-valid" nfield="txt_fieldhori" id="tet"></textarea>
<div class="n-mrb n-choice q" nfield="vert_field">
  <div class="mrb-item"><label><input type="radio" name="vert_field" mrbvalue="Normal" class="k-valid"> Normal</label></div>
  <div class="mrb-item"><label><input type="radio" name="vert_field" mrbvalue="Abnormal" class="k-valid"> Abnormal</label></div>
</div>
<textarea class="n-text comment -EntireLine ee k-valid" nfield="txt_nooo" id="te"></textarea></code>```

答:
The issue is because you're selecting all textarea instances when an event occurs on the radio, and you're also unnecessarily nesting the event handlers.

To fix this you can simply hook a single event handler to all radio buttons which toggles the visibility of the related textarea, which can be retrieved using jQuery's DOM traversal methods, based on the selected value.

Also note that your HTML has a lot of invalid non-standard attributes. These either need to be removed or converted to data attributes, for example: data-nfield="txt_fieldhori". In either case you need to ensure you put a value attribute on the radio input elements themselves.

With all that said, try this:

$(":radio").on("change", function() {
  $(this).closest('.n-choice').next('textarea').toggle(this.value === 'Normal');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="n-mrb n-choice q">
  <div class="mrb-item">
    <label>
      <input type="radio" name="horizontal_field" value="Normal" class="k-valid" checked="true">
      Normal
    </label>
  </div>
  <div class="mrb-item">
    <label>
      <input type="radio" name="horizontal_field" value="Abnormal" class="k-valid">
      Abnormal
    </label>
  </div>
</div>
<textarea class="n-text comment -EntireLine ee k-valid" id="tet"></textarea>
<div class="n-mrb n-choice q">
  <div class="mrb-item">
    <label>
      <input type="radio" name="vert_field" value="Normal" class="k-valid" checked="true">
      Normal
    </label>
  </div>
  <div class="mrb-item">
    <label>
      <input type="radio" name="vert_field" value="Abnormal" class="k-valid">
      Abnormal
    </label>
  </div>
</div>
<textarea class="n-text comment -EntireLine ee k-valid"  id="te"></textarea></code>```

Body:
I am trying to make the corresponding textarea appear when Abnormal is clicked and disappear when Normal is clicked. The problem I am having is that when I click Abnormal for one question it affects both textareas and not the one it corresponds to.

$("[nfield='horizontal_field']").on("change", function() {
  $("[mrbvalue='Normal']").on('change', function() {
    if ($("[mrbvalue='Normal']:checked")) {
      $('[nfield="txt_fieldhori"]').show()
    }
  });

  $("[mrbvalue='Abnormal']").on('change', function() {
    if ($("[mrbvalue='Abnormal']:checked")) {
      $('[nfield="txt_fieldhori"]').hide()
    }
  });
})

$("[nfield='vert_field']").on('change', function() {
  $("[mrbvalue='Normal']").on('change', function() {
    if ($("[mrbvalue='Normal']:checked")) {
      $('[nfield="txt_nooo"]').show()
    }
  });

  $("[mrbvalue='Abnormal']").on('change', function() {
    if ($("[mrbvalue='Abnormal']:checked")) {
      $('[nfield="txt_nooo"]').hide()
    }
  })
});

<input type="radio" name="horizontal_field" mrbvalue="Normal" class="k-valid"> Normal

<input type="radio" name="horizontal_field" mrbvalue="Abnormal" class="k-valid"> Abnormal

<textarea class="n-text comment -EntireLine ee k-valid" nfield="txt_fieldhori" id="tet"></textarea>

<input type="radio" name="vert_field" mrbvalue="Normal" class="k-valid"> Normal

<input type="radio" name="vert_field" mrbvalue="Abnormal" class="k-valid"> Abnormal

<textarea class="n-text comment -EntireLine ee k-valid" nfield="txt_nooo" id="te"></textarea>

Body:
The issue is because you're selecting all textarea instances when an event occurs on the radio, and you're also unnecessarily nesting the event handlers.

To fix this you can simply hook a single event handler to all radio buttons which toggles the visibility of the related textarea, which can be retrieved using jQuery's DOM traversal methods, based on the selected value.

Also note that your HTML has a lot of invalid non-standard attributes. These either need to be removed or converted to data attributes, for example: data-nfield="txt_fieldhori". In either case you need to ensure you put a value attribute on the radio input elements themselves.

With all that said, try this:

$(":radio").on("change", function() {
  $(this).closest('.n-choice').next('textarea').toggle(this.value === 'Normal');
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="n-mrb n-choice q">
  <div class="mrb-item">
    <label>
      <input type="radio" name="horizontal_field" value="Normal" class="k-valid" checked="true">
      Normal
    </label>
  </div>
  <div class="mrb-item">
    <label>
      <input type="radio" name="horizontal_field" value="Abnormal" class="k-valid">
      Abnormal
    </label>
  </div>
</div>
<textarea class="n-text comment -EntireLine ee k-valid" id="tet"></textarea>
<div class="n-mrb n-choice q">
  <div class="mrb-item">
    <label>
      <input type="radio" name="vert_field" value="Normal" class="k-valid" checked="true">
      Normal
    </label>
  </div>
  <div class="mrb-item">
    <label>
      <input type="radio" name="vert_field" value="Abnormal" class="k-valid">
      Abnormal
    </label>
  </div>
</div>
<textarea class="n-text comment -EntireLine ee k-valid"  id="te"></textarea>


来源: stackexchange

问:
ESLint: 'cy' is not defined (Cypress)
I've just started using Cypress with my React Typescript project. I've gotten some simple tests to run:

describe('settings page', () => {
  beforeEach(() => {
    cy.visit('http://localhost:3000')
  });
  it('starts in a waiting state, with no settings.', () => {
    cy.contains('Waiting for settings...')
  });
  it('shows settings once settings are received', () => {
    const state = cy.window().its('store').invoke('getState')
    console.log(state) // different question: how do I get this to be the state and not a $Chainer?
  });
});
```

<p>It runs in Cypress just fine. But I get Typescript errors in Webstorm, saying that <code>cy</code> is not defined (a TS and ESlint error) and an error on <code>describe</code> saying <code>all files must be modules when the --isolatedModules flag is provided</code>.</p>

<p>I can make it a JS file instead of a TS file, then I still get <code>cy</code> is not defined.</p>

<p>I've tried <code>import cy from 'cypress'</code> but then I get <code>ParseError: 'import' and 'export' may appear only with 'sourceType: module'</code> which is a whole other can of worms (I'm taking baby steps in writing my tests and haven't had to import anything yet...)</p>

<p><code>/// <reference types="cypress" /></code> <strong>does not work.</strong></p>

<h3>Update (sort of)</h3>

<p>I've followed instructions here and have made a little progress. To my already very full React webpack.config.dev.js I added the recommended code:</p>

<pre class="lang-js prettyprint-override"><code>          { // TODO inserted for cypress https://stackoverflow.com/a/56693706/6826164
            rules: [
              {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/
              }
            ]
          },
</code>```

to the end of the list of rules (just before the file loader).

When I do this as well as setting up the plugins/index file as indicated in the article, the cypress "home screen" runs but when I click to open my tests, it takes very many seconds and then shows lots of errors, starting with

```<code>integration\settings.spec.ts
This occurred while Cypress was compiling and bundling your test code. This is usually caused by:

A missing file or dependency
A syntax error in the file or one of its dependencies
Fix the error in your code and re-run your tests.

./cypress/integration/settings.spec.ts
Module build failed (from ./node_modules/ts-loader/index.js):
Error: TypeScript emitted no output for C:\Users\...\...\front_end\cypress\integration\settings.spec.ts.
 @ multi ./cypress/integration/settings.spec.ts main[0]
</code>```

Followed by, actually, a lot of Typescript output such as this:

```<code>C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx
[tsl] ERROR in C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx(37,41)
      TS2339: Property 'toBeTruthy' does not exist on type 'Assertion'.

C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx
[tsl] ERROR in C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx(41,45)
      TS2339: Property 'toBeDefined' does not exist on type 'Assertion'.
</code>```

Notice that these are now errors for code outside the test files (although perhaps that makes sense). Many of them are for files in which I'm using Jest rather than Cypress, and many errors, as you can see, seem to be related to it inferring an Assertion type on expect that is not Jest, such that it thinks the toEqual matcher is wrong.

All the while, in Webstorm ESLint is still complaining about all my cy and TypeScript is underlining all those Jest assertions mentioned in the output.

This is all with a ts test file. If I rename the file to js, it says the file has no tests.

Any help? I love Cypress but I'm having a hell of a time getting it to work fully!

答:
Just add these lines to your tsconfig.json file for e2e tests:

```<code>"compilerOptions": {
    "types": ["cypress"]
}
</code>```

This adds support for cypress types.

ContentLicense: CC BY-SA 4.0

Title: ESLint: 'cy' is not defined (Cypress)

Body:
I've just started using Cypress with my React Typescript project. I've gotten some simple tests to run:

describe('settings page', () => {
  beforeEach(() => {
    cy.visit('http://localhost:3000')
  });
  it('starts in a waiting state, with no settings.', () => {
    cy.contains('Waiting for settings...')
  });
  it('shows settings once settings are received', () => {
    const state = cy.window().its('store').invoke('getState')
    console.log(state) // different question: how do I get this to be the state and not a $Chainer?
  });
});

It runs in Cypress just fine. But I get Typescript errors in Webstorm, saying that cy is not defined (a TS and ESlint error) and an error on describe saying all files must be modules when the --isolatedModules flag is provided.

I can make it a JS file instead of a TS file, then I still get cy is not defined.

I've tried import cy from 'cypress' but then I get ParseError: 'import' and 'export' may appear only with 'sourceType: module' which is a whole other can of worms (I'm taking baby steps in writing my tests and haven't had to import anything yet...)

/// <reference types="cypress" /> does not work.

Update (sort of)

I've followed instructions here and have made a little progress. To my already very full React webpack.config.dev.js I added the recommended code:

          { // TODO inserted for cypress https://stackoverflow.com/a/56693706/6826164
            rules: [
              {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/
              }
            ]
          },

to the end of the list of rules (just before the file loader).

When I do this as well as setting up the plugins/index file as indicated in the article, the cypress "home screen" runs but when I click to open my tests, it takes very many seconds and then shows lots of errors, starting with

integration\settings.spec.ts
This occurred while Cypress was compiling and bundling your test code. This is usually caused by:

A missing file or dependency
A syntax error in the file or one of its dependencies
Fix the error in your code and re-run your tests.

./cypress/integration/settings.spec.ts
Module build failed (from ./node_modules/ts-loader/index.js):
Error: TypeScript emitted no output for C:\Users\...\...\front_end\cypress\integration\settings.spec.ts.
 @ multi ./cypress/integration/settings.spec.ts main[0]

Followed by, actually, a lot of Typescript output such as this:

C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx
[tsl] ERROR in C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx(37,41)
      TS2339: Property 'toBeTruthy' does not exist on type 'Assertion'.

C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx
[tsl] ERROR in C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx(41,45)
      TS2339: Property 'toBeDefined' does not exist on type 'Assertion'.

Notice that these are now errors for code outside the test files (although perhaps that makes sense). Many of them are for files in which I'm using Jest rather than Cypress, and many errors, as you can see, seem to be related to it inferring an Assertion type on expect that is not Jest, such that it thinks the toEqual matcher is wrong.

All the while, in Webstorm ESLint is still complaining about all my cy and TypeScript is underlining all those Jest assertions mentioned in the output.

This is all with a ts test file. If I rename the file to js, it says the file has no tests.

Any help? I love Cypress but I'm having a hell of a time getting it to work fully!

Body:
Just add these lines to your tsconfig.json file for e2e tests:

"compilerOptions": {
    "types": ["cypress"]
}

This adds support for cypress types.


问:
Python Dropbox Upload - Working With The Response
I am new to interfacing with the Dropbox API and am using Python 3.6

I am uploading large files to my account using the following function called dropboxupload (not my own) .  I simply call it at the end of my code:

```<code>import os
import sys
from tqdm import tqdm
import dropbox

filenameonly = sys.argv[1]
filenamewithextension = sys.argv[2]
fullfilepath = sys.argv[3]

access_token = "removedforsecurity"

def dropboxupload(access_token,file_path,target_path,timeout=3600,chunk_size=150 * 1024 * 1024,):
    dbx = dropbox.Dropbox(access_token, timeout=timeout)
    with open(file_path, "rb") as f:
        file_size = os.path.getsize(file_path)
        chunk_size = 150 * 1024 * 1024
        if file_size <= chunk_size:
            print(dbx.files_upload(f.read(), target_path))
        else:
            with tqdm(total=file_size, desc="Uploaded") as pbar:
                upload_session_start_result = dbx.files_upload_session_start(
                    f.read(chunk_size)
                )
                pbar.update(chunk_size)
                cursor = dropbox.files.UploadSessionCursor(
                    session_id=upload_session_start_result.session_id,
                    offset=f.tell(),
                )
                commit = dropbox.files.CommitInfo(path=target_path)
                while f.tell() < file_size:
                    if (file_size - f.tell()) <= chunk_size:
                        print(
                            dbx.files_upload_session_finish(
                                f.read(chunk_size), cursor, commit
                            )
                        )
                    else:
                        dbx.files_upload_session_append(
                            f.read(chunk_size),
                            cursor.session_id,
                            cursor.offset,
                        )
                        cursor.offset = f.tell()
                    pbar.update(chunk_size)

dropboxupload(access_token, fullfilepath, "/"+filenamewithextension)
</code>```

It works perfectly.

The response that comes back automatically is the FileMetadata; example as follows:

```<code>FileMetadata(name='500.mp4', id='id:a5yk0DAylOAAAAAAAAADbA', client_modified=datetime.datetime(2020, 2, 19, 13, 56, 31), server_modified=datetime.datetime(2020, 2, 19, 13, 56, 31), rev='59eee27d89b134c0970a9', size=512727070, path_lower='/500.mp4', path_display='/500.mp4', parent_shared_folder_id=None, media_info=None, symlink_info=None, sharing_info=None, is_downloadable=True, export_info=None, property_groups=None, has_explicit_shared_members=None, content_hash='e134be9c61057696145fbe4c416d5e62c983649bb756c9e9597d982781a1cb83')
</code>```

What i want to do is capture this response and use the data within it for other means in the next step of my project.

For example i want to take the id and set as a new variable called "data". I have tried doing this with

```<code>data = str(dropbox.files.FileMetadata.id)
print ("THE DATA VARIABLE IS")
print(data)
</code>```

but all that gets printed is....

```<code>THE DATA VARIABLE IS
property object at 0x03A82F60
</code>```

I am obviously capturing the data wrong - please can you help?!

Thanks

答:
I think what you want to do is this:</p>

```<code>data = dropbox.files.FileMetadata.id()
</code>```

Body:
I am new to interfacing with the Dropbox API and am using Python 3.6

I am uploading large files to my account using the following function called dropboxupload (not my own) .  I simply call it at the end of my code:

import os
import sys
from tqdm import tqdm
import dropbox

filenameonly = sys.argv[1]
filenamewithextension = sys.argv[2]
fullfilepath = sys.argv[3]

access_token = "removedforsecurity"

def dropboxupload(access_token,file_path,target_path,timeout=3600,chunk_size=150 * 1024 * 1024,):
    dbx = dropbox.Dropbox(access_token, timeout=timeout)
    with open(file_path, "rb") as f:
        file_size = os.path.getsize(file_path)
        chunk_size = 150 * 1024 * 1024
        if file_size <= chunk_size:
            print(dbx.files_upload(f.read(), target_path))
        else:
            with tqdm(total=file_size, desc="Uploaded") as pbar:
                upload_session_start_result = dbx.files_upload_session_start(
                    f.read(chunk_size)
                )
                pbar.update(chunk_size)
                cursor = dropbox.files.UploadSessionCursor(
                    session_id=upload_session_start_result.session_id,
                    offset=f.tell(),
                )
                commit = dropbox.files.CommitInfo(path=target_path)
                while f.tell() < file_size:
                    if (file_size - f.tell()) <= chunk_size:
                        print(
                            dbx.files_upload_session_finish(
                                f.read(chunk_size), cursor, commit
                            )
                        )
                    else:
                        dbx.files_upload_session_append(
                            f.read(chunk_size),
                            cursor.session_id,
                            cursor.offset,
                        )
                        cursor.offset = f.tell()
                    pbar.update(chunk_size)

dropboxupload(access_token, fullfilepath, "/"+filenamewithextension)

It works perfectly.

The response that comes back automatically is the FileMetadata; example as follows:

FileMetadata(name='500.mp4', id='id:a5yk0DAylOAAAAAAAAADbA', client_modified=datetime.datetime(2020, 2, 19, 13, 56, 31), server_modified=datetime.datetime(2020, 2, 19, 13, 56, 31), rev='59eee27d89b134c0970a9', size=512727070, path_lower='/500.mp4', path_display='/500.mp4', parent_shared_folder_id=None, media_info=None, symlink_info=None, sharing_info=None, is_downloadable=True, export_info=None, property_groups=None, has_explicit_shared_members=None, content_hash='e134be9c61057696145fbe4c416d5e62c983649bb756c9e9597d982781a1cb83')

What i want to do is capture this response and use the data within it for other means in the next step of my project.

For example i want to take the id and set as a new variable called "data". I have tried doing this with

data = str(dropbox.files.FileMetadata.id)
print ("THE DATA VARIABLE IS")
print(data)

but all that gets printed is....

THE DATA VARIABLE IS
property object at 0x03A82F60

I am obviously capturing the data wrong - please can you help?!

Thanks

Body:
I think what you want to do is this:

data = dropbox.files.FileMetadata.id()


问:
How can I make this update query work in PostgreSQL?
I have the following tables:

orientador:

importado:

I' like to run the following query, updating orientador.atividadeorientador with it's respectivelly importado.atividade:

```<code>UPDATE importado
SET atividadeorientador = pco.atividade
FROM importado AS pci
  INNER JOIN orientador AS pco
      ON pco.codinst_o = pci.codinst
      AND pci.codigo = pco.codigo_o
      AND pci.codinst = 237
      AND pci.versao LIKE '002'
      AND pco.atividade > 0;
</code>```

The result updates all the lines with a single value:

What I'm doing wrong?

答:
Don't repeat the table being updated:

```<code>UPDATE importado pci
SET atividadeorientador = pco.atividade
FROM orientador pco
WHERE pco.codinst_o = pci.codinst AND
      pci.codigo = pco.codigo_o AND
      pci.codinst = 237 AND
      pci.versao LIKE '002' AND
      pco.atividade > 0;
</code>```

Your version has two versions of importado, which Postgres interprets as a CROSS JOIN (this is different from the behavior in SQL Server).

Body:
I have the following tables:

orientador:

importado:

I' like to run the following query, updating orientador.atividadeorientador with it's respectivelly importado.atividade:

UPDATE importado
SET atividadeorientador = pco.atividade
FROM importado AS pci
  INNER JOIN orientador AS pco
      ON pco.codinst_o = pci.codinst
      AND pci.codigo = pco.codigo_o
      AND pci.codinst = 237
      AND pci.versao LIKE '002'
      AND pco.atividade > 0;

The result updates all the lines with a single value:

What I'm doing wrong?

Body:
Don't repeat the table being updated:

UPDATE importado pci
SET atividadeorientador = pco.atividade
FROM orientador pco
WHERE pco.codinst_o = pci.codinst AND
      pci.codigo = pco.codigo_o AND
      pci.codinst = 237 AND
      pci.versao LIKE '002' AND
      pco.atividade > 0;

Your version has two versions of importado, which Postgres interprets as a CROSS JOIN (this is different from the behavior in SQL Server).


问:
Replace ISO-Date with normal Date in HTML Document via Widget
my problem is the following . Im using Duda widget Builder to build my own Widgets. In one application there is a Date and by default its depicted as ISO .
Now converting that isnt too hard, I tried the following :

if (document.getElementById("date") !== null) {
  let date = document.getElementById("date").toString();
  let dater = date.substring(0, 10);
  document.getElementById("date").innerHTML.replace(date, dater);
  console.log('Test');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Wrapper shadow">
  <h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div></code>```

Now it doesnt throw any errors and it console.logs the "Test". But the date stays in ISO.

The widget works with jQuery I believe it has something to do with that.
The widget interface where you write down the javascript is encapsulated by this: function(element,data,api){ 'my js code from above'}
Please help.

答:
You can also use Moment.js for format the date you need.

const el = document.querySelector('#date');

const myDateFormat = 'YYYY-MM-DD';
const date = el.textContent;
const newDate = moment(date, myDateFormat).format(myDateFormat);

el.textContent = newDate;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://momentjs.com/downloads/moment.min.js"></script>

<div class="Wrapper shadow">
  <h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div></code>```

Hope to help you and others ^^.

Body:
my problem is the following . Im using Duda widget Builder to build my own Widgets. In one application there is a Date and by default its depicted as ISO .
Now converting that isnt too hard, I tried the following :

if (document.getElementById("date") !== null) {
  let date = document.getElementById("date").toString();
  let dater = date.substring(0, 10);
  document.getElementById("date").innerHTML.replace(date, dater);
  console.log('Test');
}

2020-02-20T14:39:40Z

Now it doesnt throw any errors and it console.logs the "Test". But the date stays in ISO.

The widget works with jQuery I believe it has something to do with that.
The widget interface where you write down the javascript is encapsulated by this: function(element,data,api){ 'my js code from above'}
Please help.

Body:
You can also use Moment.js for format the date you need.

const el = document.querySelector('#date');

const myDateFormat = 'YYYY-MM-DD';
const date = el.textContent;
const newDate = moment(date, myDateFormat).format(myDateFormat);

el.textContent = newDate;

<script src="https://momentjs.com/downloads/moment.min.js"></script>

<div class="Wrapper shadow">
  <h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div>

Hope to help you and others ^^.


问:
Source a virtual environment using python
On the servers I am working on, there is a virtual environment which can be activated using source /bin/virtualenv-activate. I need this virtual environment because of a command line tool which is accessible only there. Let's call it fancytool. What I would like to do is to use fancytool out of a python script and return its output into a python variable. The python script is not initiated in the virtual environment, so I thought of something like this:

```<code>os.system('source /bin/virtualenv-activate')
results = os.popen(fancytool).read()
</code>```

However, this returns:

```<code>sh: 1: source: not found
sh: 1: fancytool: not found
</code>```

If I enter source /bin/virtualenv-activate in the terminal and then fancytool, everything works fine. How can I achieve this also in a python script?

答:
You should add a shebang to the top of the script to activate the env

```<code>#!/path/to/venv/bin/python

# your code here
</code>```

However relying on the knowledge of the venv within your scripts is considered poor practice

Body:
On the servers I am working on, there is a virtual environment which can be activated using source /bin/virtualenv-activate. I need this virtual environment because of a command line tool which is accessible only there. Let's call it fancytool. What I would like to do is to use fancytool out of a python script and return its output into a python variable. The python script is not initiated in the virtual environment, so I thought of something like this:

os.system('source /bin/virtualenv-activate')
results = os.popen(fancytool).read()

However, this returns:

sh: 1: source: not found
sh: 1: fancytool: not found

If I enter source /bin/virtualenv-activate in the terminal and then fancytool, everything works fine. How can I achieve this also in a python script?

Body:
You should add a shebang to the top of the script to activate the env

#!/path/to/venv/bin/python

# your code here

However relying on the knowledge of the venv within your scripts is considered poor practice


问:
How to handle the images efficiently as assets in pubspec.yaml?
So I have my project that has 20 folders and each folder has 10 images, I need to animate the images.

Generally we assign images in flutter like below,

```<code>image1.jpg

asset:
  - assets/images1.jpg
</code>```

So Do I have to assign all these images as assets like above? Or is there any way to handle large set of local images in flutter?

答:
To include all assets under a directory, specify the directory name with the / character at the end:

```<code>flutter:
  assets:
    - assets/
</code>```

Note that only files located directly in the directory are included. To add files located in subdirectories, create an entry per directory.

Source: https://flutter.dev/docs/development/ui/assets-and-images

Body:
So I have my project that has 20 folders and each folder has 10 images, I need to animate the images.

Generally we assign images in flutter like below,

image1.jpg

asset:
  - assets/images1.jpg

So Do I have to assign all these images as assets like above? Or is there any way to handle large set of local images in flutter?

Body:
To include all assets under a directory, specify the directory name with the / character at the end:

flutter:
  assets:
    - assets/

Note that only files located directly in the directory are included. To add files located in subdirectories, create an entry per directory.

Source: https://flutter.dev/docs/development/ui/assets-and-images


问:
Spring security logout handling
According to Spring Security 4.0.0 document:

4.2.4 Logout Handling

The logout element adds support for logging out by navigating to a
  particular URL. The default logout URL is /logout, but you can set it
  to something else using the logout-url attribute. More information on
  other available attributes may be found in the namespace appendix.

However, after following security setting in the doc, the URL /logout doesn't show logout page. Instead, it shows

On the contrary, the URL /login works properly.

The following is my setting:

Spring Framework 4.1.6

Spring Security 4.0.0

Web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>Test8</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/security-config.xml</param-value>
    </context-param>

</web-app>
</code>```

security-config.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security.xsd">
    <http>
        <intercept-url pattern="/**" access="hasRole('USER')" />
        <form-login />
        <logout />
    </http>

    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="aaa" password="111" authorities="ROLE_USER, ROLE_ADMIN" />
                <user name="bbb" password="222" authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>

</beans:beans>
</code>```

答:
With Spring security 4.2.13 I have a managed to make this work by navigating to the logout URL through a form submission (POST method) instead of using a link.

I replaced
">Log out
 with

```<code><form name='f' action='${pageContext.request.contextPath}/logout' method='POST'>
<input name="logout" type="submit" value="Log out" />
<input name="${_csrf.parameterName}" type="hidden"
    value="${_csrf.token}" />
</form>
</code>```

in my view layer, which is a JSP page. This way you will get a button instead of a link.
(In older Spring versions the default logout URL was "/j_spring_security_logout".)

ContentLicense: CC BY-SA 3.0

Title: Spring security logout handling

Body:
According to Spring Security 4.0.0 document:

4.2.4 Logout Handling

The logout element adds support for logging out by navigating to a
  particular URL. The default logout URL is /logout, but you can set it
  to something else using the logout-url attribute. More information on
  other available attributes may be found in the namespace appendix.

However, after following security setting in the doc, the URL /logout doesn't show logout page. Instead, it shows

On the contrary, the URL /login works properly.

The following is my setting:

Spring Framework 4.1.6

Spring Security 4.0.0

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>Test8</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/security-config.xml</param-value>
    </context-param>

</web-app>

security-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security.xsd">
    <http>
        <intercept-url pattern="/**" access="hasRole('USER')" />
        <form-login />
        <logout />
    </http>

    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="aaa" password="111" authorities="ROLE_USER, ROLE_ADMIN" />
                <user name="bbb" password="222" authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>

</beans:beans>

Body:
With Spring security 4.2.13 I have a managed to make this work by navigating to the logout URL through a form submission (POST method) instead of using a link.

I replaced <p><a href="<c:url value='/logout'/>">Log out</a></p> with

<form name='f' action='${pageContext.request.contextPath}/logout' method='POST'>
<input name="logout" type="submit" value="Log out" />
<input name="${_csrf.parameterName}" type="hidden"
    value="${_csrf.token}" />
</form>

in my view layer, which is a JSP page. This way you will get a button instead of a link.
(In older Spring versions the default logout URL was "/j_spring_security_logout".)


问:
inoremap: variable timeoutlen
I have two remaps in my .vimrc for the insert mode:

```<code>inoremap jk <ESC>
inoremap {<CR> {<CR>}
</code>```

The first remap should have a short timeoutlen, whereas the latter should have no timeout at all. Reason: I need a timeout for the first remap, as jk might be used as regular characters. The latter on the other hand is code completion, where a timeout makes no sense.

Is it possible to assign different timeoutlen's for different remaps? Thanks & BR

答:
One way to extend the timeout of your second mapping is to actually only map <CR> and then use an expression to check that it's being typed after a { character.

The behavior is somewhat different from a two-character mapping in that the mapping will also work if you're typing a <CR> after a { that was already there, which might be acceptable to you (or might even be exactly what you wanted.)

Since you're using an expression to do checks, you can do additional checks such as only applying the mapping if you're typing the <CR> at the end of a line (so you avoid it if you're using it to split an existing long line.)

A possible implementation of that would be:

```<code>inoremap <expr> <CR>
    \ col('.') ==# col('$')
    \ && getline('.')[col('.')-2] ==# '{'
    \ ? "\<CR>}\<C-O>O"
    \ : "\<CR>"
</code>```

We're using a ternary operator here to produce a different output based on the condition holding or not. If it doesn't, we simply map back to the keystroke itself, so it keeps working as it usually does in all other contexts.

For the part that inserts a closing curly brace, I also added a CTRL-O O to the end, so after inserting the brace, it will add a new line before it and leave the cursor in an indented column inside the block. I hope you'll find this helpful, but feel free to disregard that part if it's not really what you had in mind.

Title: inoremap: variable timeoutlen

Body:
I have two remaps in my .vimrc for the insert mode:

inoremap jk <ESC>
inoremap {<CR> {<CR>}

The first remap should have a short timeoutlen, whereas the latter should have no timeout at all. Reason: I need a timeout for the first remap, as jk might be used as regular characters. The latter on the other hand is code completion, where a timeout makes no sense.

Is it possible to assign different timeoutlen's for different remaps? Thanks & BR

Body:
One way to extend the timeout of your second mapping is to actually only map <CR> and then use an expression to check that it's being typed after a { character.

The behavior is somewhat different from a two-character mapping in that the mapping will also work if you're typing a <CR> after a { that was already there, which might be acceptable to you (or might even be exactly what you wanted.)

Since you're using an expression to do checks, you can do additional checks such as only applying the mapping if you're typing the <CR> at the end of a line (so you avoid it if you're using it to split an existing long line.)

A possible implementation of that would be:

inoremap <expr> <CR>
    \ col('.') ==# col('$')
    \ && getline('.')[col('.')-2] ==# '{'
    \ ? "\<CR>}\<C-O>O"
    \ : "\<CR>"

We're using a ternary operator here to produce a different output based on the condition holding or not. If it doesn't, we simply map back to the keystroke itself, so it keeps working as it usually does in all other contexts.

For the part that inserts a closing curly brace, I also added a CTRL-O O to the end, so after inserting the brace, it will add a new line before it and leave the cursor in an indented column inside the block. I hope you'll find this helpful, but feel free to disregard that part if it's not really what you had in mind.


问:
How to test the contents of a dropdown list web-component with VueJS, typescript and jest
I'm trying to test the contents of a dropdown list implemented as a web component used in a VueJS application.

Specifically, I want to test if a given dropdown list contains items which are retrieved by an HTTP query (implemented in a vuex store) when the application's created() lifecycle hook is triggered.

The VueJS application is written in typescript and I use Jest as my testing framework.

My Vue component SearchBar.vue that I would like to test:

```<code><template>
    <dropdown-web-component
        label="Applications"
        :options.prop="applications"
    />
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

@Component
export default class SearchBar extends Vue {
    get applications() {
        return this.$typedStore.state.applications;
    }
    created() {
        // the http call is implemented in the vuex store
        this.$store.dispatch(Actions.GetApplications);
    }
}
</code>```

答:
Here is how I made it work:

The SearchBar.spec.ts test for the component:

```<code>import Vuex, { Store } from "vuex";
import { shallowMount, Wrapper } from "@vue/test-utils";
import SearchBar from "@/components/SearchBar.vue";
import { Vue } from "vue/types/vue";

describe('SearchBar', () => {
    let actions: any;
    let store: Store;
    let state: any;

    beforeEach(() => {
        const applications = ['applicationId1', 'applicationId2', 'applicationId3'];

        actions = {
            GET_APPLICATIONS: jest.fn()
        };
        state = {
            applications
        };
        store = new Vuex.Store({
            modules: {
                users: {
                    actions,
                    state
                }
            }
        });
    });

    it('should dispatch the GET_APPLICATIONS vuex store action when created', () => {
        shallowMount(SearchAndFilterBar, { store });

        expect(actions.GET_APPLICATIONS).toHaveBeenCalled();
    });

    describe('Applications dropdown', () => {
        it('should render a dropdown with applications', () => {
            const wrapper = shallowMount(SearchAndFilterBar, {
                store
            });
            const filter: Wrapper<Vue> = wrapper.find('dropdown-web-component');
            // without the cast to any, TS will not be able to find vnode
            expect((filter as any).vnode.data.domProps.options.length).toEqual(3);
        });
    });
});

</code>```

I hope my own answer helps someone out as well as it took me quite some time to figure all of this out.

Body:
I'm trying to test the contents of a dropdown list implemented as a web component used in a VueJS application.

Specifically, I want to test if a given dropdown list contains items which are retrieved by an HTTP query (implemented in a vuex store) when the application's created() lifecycle hook is triggered.

The VueJS application is written in typescript and I use Jest as my testing framework.

My Vue component SearchBar.vue that I would like to test:

<template>
    <dropdown-web-component
        label="Applications"
        :options.prop="applications"
    />
</template>

Body:
Here is how I made it work:

The SearchBar.spec.ts test for the component:

import Vuex, { Store } from "vuex";
import { shallowMount, Wrapper } from "@vue/test-utils";
import SearchBar from "@/components/SearchBar.vue";
import { Vue } from "vue/types/vue";

describe('SearchBar', () => {
    let actions: any;
    let store: Store;
    let state: any;

    beforeEach(() => {
        const applications = ['applicationId1', 'applicationId2', 'applicationId3'];

        actions = {
            GET_APPLICATIONS: jest.fn()
        };
        state = {
            applications
        };
        store = new Vuex.Store({
            modules: {
                users: {
                    actions,
                    state
                }
            }
        });
    });

    it('should dispatch the GET_APPLICATIONS vuex store action when created', () => {
        shallowMount(SearchAndFilterBar, { store });

        expect(actions.GET_APPLICATIONS).toHaveBeenCalled();
    });

    describe('Applications dropdown', () => {
        it('should render a dropdown with applications', () => {
            const wrapper = shallowMount(SearchAndFilterBar, {
                store
            });
            const filter: Wrapper<Vue> = wrapper.find('dropdown-web-component');
            // without the cast to any, TS will not be able to find vnode
            expect((filter as any).vnode.data.domProps.options.length).toEqual(3);
        });
    });
});

I hope my own answer helps someone out as well as it took me quite some time to figure all of this out.


问:
How to use optional command line arguments in a python function?
I want a more compact and scalable way to use command line args to feed a python function, here is what i have:

```<code>def getRelevant (number = 5, sortBy = "Change"):
    number, sortBy = int(number), sortBy
    relevant = ...
    return relevant

if __name__ == "__main__":
    if len(sys.argv) == 3:
        print(getRelevant(sys.argv[1], sys.argv[2]))
    elif len(sys.argv) == 2:
        print(getRelevant(sys.argv[1]))
    else:
        print(getRelevant())
</code>```

It works. But I'm not happy with this conditionals, is there a way to make it simpler?

答:
You can try with argparse or Typer

argparse: https://docs.python.org/3/library/argparse.html

typer: https://typer.tiangolo.com/

Body:
I want a more compact and scalable way to use command line args to feed a python function, here is what i have:

def getRelevant (number = 5, sortBy = "Change"):
    number, sortBy = int(number), sortBy
    relevant = ...
    return relevant

if __name__ == "__main__":
    if len(sys.argv) == 3:
        print(getRelevant(sys.argv[1], sys.argv[2]))
    elif len(sys.argv) == 2:
        print(getRelevant(sys.argv[1]))
    else:
        print(getRelevant())

It works. But I'm not happy with this conditionals, is there a way to make it simpler?


问:
Can Query results be put onto a text field of a form?
Can the results of a query be put into a text box on a form?  I have a form that I would like to put the last "Order Number" (which is a text field) into a textbox on the form.  I have a query written that brings up the last order number -- SELECT Max(SwitchingProcedure.OrderNumber) AS MaxOfOrderNumber FROM SwitchingProcedure-- Can this result be put on a form that is bound to this table.  Is there a better way to do this?</p>

答:
You can also use the DLookup function to retrieve a column value from any specified table or query.

In the control source of your text box, use: =DLookup("[Enter column name from query here]","[Enter name of your query]")

You can also add criteria to the DLookUp to limit the result to a particular row, but your query should only return one row anyway so it's not needed.

Hope this helps.


问:
Best way to wait until prices load completely (such as on comparision websites)
I tried using implicit wait but it did not work somehow and then I also tried explicit wait such as sleep but again it did not work and also not a good practice.
I then looked at fluent wait but because I am using the PageFactory and old version of fluent wait is deprecated, does anyone know how can I implement fluent wait along with PageFactory.

答:
Here you go...</p>

```<code>    public static void waitForElement(WebElement element){
    try {
        Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                .withTimeout(Duration.ofMillis(60000))
                .pollingEvery(Duration.ofMillis(1000))
                .ignoring(NoSuchElementException.class)
                .ignoring(StaleElementReferenceException.class);
        wait.until(ExpectedConditions.elementToBeClickable(element));
        waiting(100);
        //can add further action here
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

Body:
Here you go...

    public static void waitForElement(WebElement element){
    try {
        Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                .withTimeout(Duration.ofMillis(60000))
                .pollingEvery(Duration.ofMillis(1000))
                .ignoring(NoSuchElementException.class)
                .ignoring(StaleElementReferenceException.class);
        wait.until(ExpectedConditions.elementToBeClickable(element));
        waiting(100);
        //can add further action here
    } catch (Exception e) {
        e.printStackTrace();
    }
}


答:
You can create images sub-folder inside assets folder and can directly include/import that folder in pubspec.yaml file like this:</p>

```<code>flutter:
   assets:
    - assets/images/
</code>```

Title: How to handle the images efficiently as assets in pubspec.yaml?

Body:
You can create images sub-folder inside assets folder and can directly include/import that folder in pubspec.yaml file like this:

flutter:
   assets:
    - assets/images/


问:
Wordpress - Add comma to all but last item, remove underscore
I'm using the advanced custom field plugin for Wordpress to show the results of checkboxes. I have what I want working, I just want to tidy up the code and add the following:

Remove the underscore from the social media tag (some kind of stripping out???).

If possible I'd like to show a comma after each "tag" but not if it's the last one.

Here's my test page, they're the blue "tags" under the discipline section.

Here's my code:

```<code>    <?php
$catNames = array( 'branding','creative','development','exhibition','packaging','print','seo','social_media','usability','web','advertising','campaign','content','feasibility','publishing','research','strategy');

foreach($catNames as $name){
    if(in_array($name, get_field('categories') )){
echo '<a href="/tags/design/'.$name.'" title="'.$name.'">'.strtoupper($name).'</a>';
    }
}
?>
</code>```

答:
Well it is pretty basic, you just have to do a loop. I could have write something better with more information... anyway this should do exactly what your code did but in a loop.</p>

```<code><?php
$catNames = array( 'branding','creative','development','exhibition','packaging','print','seo','social_media','usability','web','advertising','campaign','content','feasibility','publishing','research','strategy');

foreach($catNames as $name){
    if(in_array($name, get_field('categories') )){ //I don't know what this is suppose to do
echo '<a href="/tags/design/'.$name.'" title="'.$name.'">'.strtoupper($name).'</a>';
    }
}
?>
</code>```

Body:
I'm using the advanced custom field plugin for Wordpress to show the results of checkboxes. I have what I want working, I just want to tidy up the code and add the following:

Remove the underscore from the social media tag (some kind of stripping out???).

If possible I'd like to show a comma after each "tag" but not if it's the last one.

Here's my test page, they're the blue "tags" under the discipline section.

Here's my code:

    <?php
$catNames = array( 'branding','creative','development','exhibition','packaging','print','seo','social_media','usability','web','advertising','campaign','content','feasibility','publishing','research','strategy');

foreach($catNames as $name){
    if(in_array($name, get_field('categories') )){
echo ''.strtoupper($name).'';
    }
}
?>

Body:
Well it is pretty basic, you just have to do a loop. I could have write something better with more information... anyway this should do exactly what your code did but in a loop.

<?php
$catNames = array( 'branding','creative','development','exhibition','packaging','print','seo','social_media','usability','web','advertising','campaign','content','feasibility','publishing','research','strategy');

foreach($catNames as $name){
    if(in_array($name, get_field('categories') )){ //I don't know what this is suppose to do
echo '<a href="/tags/design/'.$name.'" title="'.$name.'">'.strtoupper($name).'</a>';
    }
}
?>


问:
Prevent all clicks on embedded element
I use embedded tweets in my website, however, I would like to prevent any type of user interaction with these embedded tweets other than showing them to my users. Following the advise here, I wrapped the embed code inside a
 element with the CSS property pointer-events:none, as in the example below, nevertheless, the embedded tweet in the  remains clickable. Any ideas how to mask it with an invisible NON-CLICKABLE layer?

Or hey, ya know, just relax and have fun. https://twitter.com/U53iZEL9O9
— Meg Turney (@megturney) February 19, 2020

```

答:
The code below seems to work using your "twitter-tweet" class rather than the div to specify pointer events:

```<code><head>
<style>
.twitter-tweet{
pointer-events: none;
}
</style>

</head>

<body>
<div class="right" style="display:inline-block;float:left;z-index:2">
  <blockquote class="twitter-tweet">
    <p lang="en" dir="ltr">Or hey, ya know, just relax and have fun. <a href="https://twitter.com/U53iZEL9O9">https://twitter.com/U53iZEL9O9</a></p>— Meg Turney (@megturney) <a href="https://twitter.com/megturney/status/1230141853246402560?ref_src=twsrc%5Etfw">February 19, 2020</a></blockquote>
  <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
</div>
</body>
</code>```

However, when I run the code you've posted, it behaves as specified as well. It seems you may have other code preventing your efforts here. Nonetheless try adding pointer-events: none; to your twitter-tweet class instead.

Title: Prevent all clicks on embedded element

Body:
The code below seems to work using your "twitter-tweet" class rather than the div to specify pointer events:

<head>
<style>
.twitter-tweet{
pointer-events: none;
}
</style>

</head>

<body>
<div class="right" style="display:inline-block;float:left;z-index:2">
  <blockquote class="twitter-tweet">
    <p lang="en" dir="ltr">Or hey, ya know, just relax and have fun. <a href="https://twitter.com/U53iZEL9O9">https://twitter.com/U53iZEL9O9</a></p>&mdash; Meg Turney (@megturney) <a href="https://twitter.com/megturney/status/1230141853246402560?ref_src=twsrc%5Etfw">February 19, 2020</a></blockquote>
  <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
</div>
</body>

However, when I run the code you've posted, it behaves as specified as well. It seems you may have other code preventing your efforts here. Nonetheless try adding pointer-events: none; to your twitter-tweet class instead.


问:
What exactly is represented by the template parameter passed to std::function template?
std::function itself offers a great utility- it provides type erasure in order to generically store / provide access to callables. Its flexibility is great:

```<code>#include <functional>
#include <iostream>

void printer() {
    std::cout << "I print!";
}

int adder(int a, int b) {
    return a + b;
}

int main() {
    std::function<void()> fun1 = printer;       // fun1() calls printer()
    std::function<int(int, int)> fun2 = adder;  // fun2(1, 2) calls adder(1, 2)

    std::function<void()> fun3 = [](){};        // fun3() will do nothing - same for the lambda
    std::function<int(int, int)> fun4 =
            [](int a, int b) { return a + b; }; // fun4(1, 2) will yield the sum
}
</code>```

And, to be honest, everything makes sense. std::function<void()> says that it's a function, which, when called, returns void and takes no (()) arguments. Ditto for std::function<int(int, int)> - when called, it returns an int and requires two ints as its arguments.

While intuitive, I believe I lack fundamental understanding of that exactly is the explicit template parameter. What exactly is void() or int(int, int)? They cannot be function pointers, becasue when I do:

```<code>int main() {
    using type = void();

    type x = printer;
}
</code>```

I get the following warning and an error:

```<code>main.cpp:15:10: warning: declaration of 'void x()' has 'extern' and is initialized
 type x = printer;
      ^
main.cpp:15:14: error: function 'void x()' is initialized like a variable
 type x = printer;
          ^~~~~~~
</code>```

Well, obviously it looks like a variable - I wanted it to be a variable. However, if I wanted a function pointer, I would've had to do:

```<code>using type = void(*)();
</code>```

instead of:

```<code>using type = void();
</code>```

What exactly is the type with omitted *? What exactly is represented by the intuitive explicit template parameters when used with, for example, the std::function?

答:
What exactly is the type with omitted *?

Think about it. A type "followed by" a * means "pointer to that type". If you don't "follow" a type with a *, then the type means just that type. So if you have a function pointer, then it is a pointer to... a function type.

Therefore, types like void() are function types.

Function types are distinct from object types, but they are still types. So you can play most of the type-based games with them that C++ allows. But since they're not object types, you cannot create objects of function type.

Body:
std::function itself offers a great utility- it provides type erasure in order to generically store / provide access to callables. Its flexibility is great:

#include <functional>
#include <iostream>

void printer() {
    std::cout << "I print!";
}

int adder(int a, int b) {
    return a + b;
}

int main() {
    std::function<void()> fun1 = printer;       // fun1() calls printer()
    std::function<int(int, int)> fun2 = adder;  // fun2(1, 2) calls adder(1, 2)

    std::function<void()> fun3 = [](){};        // fun3() will do nothing - same for the lambda
    std::function<int(int, int)> fun4 =
            [](int a, int b) { return a + b; }; // fun4(1, 2) will yield the sum
}

And, to be honest, everything makes sense. std::function<void()> says that it's a function, which, when called, returns void and takes no (()) arguments. Ditto for std::function<int(int, int)> - when called, it returns an int and requires two ints as its arguments.

While intuitive, I believe I lack fundamental understanding of that exactly is the explicit template parameter. What exactly is void() or int(int, int)? They cannot be function pointers, becasue when I do:

int main() {
    using type = void();

    type x = printer;
}

I get the following warning and an error:

main.cpp:15:10: warning: declaration of 'void x()' has 'extern' and is initialized
 type x = printer;
      ^
main.cpp:15:14: error: function 'void x()' is initialized like a variable
 type x = printer;
          ^~~~~~~

Well, obviously it looks like a variable - I wanted it to be a variable. However, if I wanted a function pointer, I would've had to do:

using type = void(*)();

instead of:

using type = void();

What exactly is the type with omitted *? What exactly is represented by the intuitive explicit template parameters when used with, for example, the std::function?


答:
Maybe:</p>

```<code>SELECT percentile_disc(0.5) WITHIN GROUP (ORDER BY lat_count)
FROM (SELECT user_id
    , COUNT(lat) AS lat_count
FROM gps_track
GROUP BY user_id) du;
</code>```

Title: Computing the median of all users in all trips

Body:
Got my hand dirty on GPS trajectory dataset. This data set consists of sequence of the GPS points of trips for users, until the length of trip:

SELECT * FROM gps_track;
+---------+------------------+------------------+
| user_id |       lat        |       lon        |
+---------+------------------+------------------+
| 1       | 39.984702        | 116.318417       |
| 1       | 39.984683        | 116.31845        |
| 1       | 39.984611        | 116.318026       |
| .       | .                | .                |
| 2       | 26.162202        | 119.943787       |
| 2       | 26.161528        | 119.943234       |
| 2       | 26.1619          | 119.943228       |
| .       | .                | .                |
| 3       | 22.8143366666667 | 108.332281666667 |
| 3       | 22.81429         | 108.332256666667 |
| 3       | 22.81432         | 108.332258333333 |
| .       | .                | .                |
| 4       | 32.9239666666667 | 117.386683333333 |
| 4       | 32.9235166666667 | 117.386616666667 |
| 4       | 32.9232833333333 | 117.386683333333 |
| .       | .                | .                |
+---------+------------------+------------------+

I can get the COUNT of GPS points for each user_id 1, 2,3,.. etc.

SELECT distinct user_id
    , COUNT(lat) AS lat_count
FROM gps_track
GROUP BY user_id

How do I then get the median of the number of GPS points in all the trips? Not the median point for each user. Here's the fiddle for sample points from my dataset.

Body:
Maybe:

SELECT percentile_disc(0.5) WITHIN GROUP (ORDER BY lat_count)
FROM (SELECT user_id
    , COUNT(lat) AS lat_count
FROM gps_track
GROUP BY user_id) du;


问:
How can I save files in parallel without automatically increasing the file size?
I have 2 scripts that doing exactly the same.

But one script is producing 3 RData files that weights  82.7 KB, and the other script creating 3 RData files that weights 120 KB.

the first one is without parallel:

```<code>library("plyr")
ddply(.data = iris,
      .variables = "Species",
      ##.parallel=TRUE,##Without parallel
      .fun = function(SpeciesData){

      #Create Simple Model -------------------------------------------------------------
      Model <- lm(formula = "Sepal.Length~Sepal.Width+Petal.Length+Petal.Width",data = SpeciesData)

      #Save The Model -------------------------------------------------------------
       save(Model,
            compress = FALSE,
            file = gsub(x =  "Species.RData",
                        pattern = "Species",
                        replacement = unique(SpeciesData$Species)))

 })
</code>```

The second is with parallel:

```<code>library("plyr")
doSNOW::registerDoSNOW(cl<-snow::makeCluster(3))
ddply(.data = iris,
      .variables = "Species",
      .parallel=TRUE,##With parallel
      .fun = function(SpeciesData){

      #Create Simple Model -------------------------------------------------------------
      Model <- lm(formula = "Sepal.Length~Sepal.Width+Petal.Length+Petal.Width",data = SpeciesData)

      #Save The Model -------------------------------------------------------------
       save(Model,
            compress = FALSE,
            file = gsub(x =  "Species.RData",
                        pattern = "Species",
                        replacement = unique(SpeciesData$Species)))

 })
snow::stopCluster(cl)
</code>```

the second script creates files that weight 42% more.

How can I save files in parallel without automatically increasing the file size?

答:
I have not used ddply to parallelize saving objects, so I guess the file gets much larger because when you save model object, it carrys also some information about the environment from which it is saved.

So using your ddply code above, the sizes I have are:

```<code>sapply(dir(pattern="RData"),file.size)
setosa.RData versicolor.RData  virginica.RData
       36002            36002            36002
</code>```

There are two options, one is to use purrr / furrr:

```<code>library(furrr)
library(purrr)

func = function(SpeciesData){
  Model <- lm(formula = "Sepal.Length~Sepal.Width+Petal.Length+Petal.Width",data = SpeciesData)
  save(Model,
       compress = FALSE,
       file = gsub(x =  "Species.RData",
                   pattern = "Species",
                   replacement = unique(SpeciesData$Species)))
}

split(iris,iris$Species) %>% future_map(func)

sapply(dir(pattern="RData"),file.size)
    setosa.RData versicolor.RData  virginica.RData
           25426            27156            27156
</code>```

Or to use saveRDS (and ddply?) since you only have one object to save:

```<code>ddply(.data = iris,
      .variables = "Species",
      .parallel=TRUE,##With parallel
      .fun = function(SpeciesData){
        Model <- lm(formula = "Sepal.Length~Sepal.Width+Petal.Length+Petal.Width",data = SpeciesData)
        saveRDS(Model,
             gsub(x =  "Species.rds",
                         pattern = "Species",
                         replacement = unique(SpeciesData$Species)))

      })

sapply(dir(pattern="rds"),file.size)
    setosa.rds versicolor.rds  virginica.rds
          6389           6300           6277
</code>```

You will do readRDS instead of load to get the file:

```<code>m1 = readRDS("setosa.rds")
m1
Call:
lm(formula = "Sepal.Length~Sepal.Width+Petal.Length+Petal.Width",
    data = SpeciesData)

Coefficients:
 (Intercept)   Sepal.Width  Petal.Length   Petal.Width
      2.3519        0.6548        0.2376        0.2521
</code>```

We can look at the coefficients in comparison with the rda object:

```<code>m2 = get(load("setosa.RData"))
m2

Call:
lm(formula = "Sepal.Length~Sepal.Width+Petal.Length+Petal.Width",
    data = SpeciesData)

Coefficients:
 (Intercept)   Sepal.Width  Petal.Length   Petal.Width
      2.3519        0.6548        0.2376        0.2521
</code>```

The objects are not identical because of the environment parts, but in terms of prediction or other stuff we normally use it for, it works:

```<code>identical(predict(m1,data.frame(iris[1:10,])),predict(m2,data.frame(iris[1:10,])))
</code>```

Body:
I have 2 scripts that doing exactly the same.

But one script is producing 3 RData files that weights  82.7 KB, and the other script creating 3 RData files that weights 120 KB.

the first one is without parallel:

library("plyr")
ddply(.data = iris,
      .variables = "Species",
      ##.parallel=TRUE,##Without parallel
      .fun = function(SpeciesData){

      #Create Simple Model -------------------------------------------------------------
      Model <- lm(formula = "Sepal.Length~Sepal.Width+Petal.Length+Petal.Width",data = SpeciesData)

      #Save The Model -------------------------------------------------------------
       save(Model,
            compress = FALSE,
            file = gsub(x =  "Species.RData",
                        pattern = "Species",
                        replacement = unique(SpeciesData$Species)))

 })

The second is with parallel:

library("plyr")
doSNOW::registerDoSNOW(cl<-snow::makeCluster(3))
ddply(.data = iris,
      .variables = "Species",
      .parallel=TRUE,##With parallel
      .fun = function(SpeciesData){

      #Create Simple Model -------------------------------------------------------------
      Model <- lm(formula = "Sepal.Length~Sepal.Width+Petal.Length+Petal.Width",data = SpeciesData)

      #Save The Model -------------------------------------------------------------
       save(Model,
            compress = FALSE,
            file = gsub(x =  "Species.RData",
                        pattern = "Species",
                        replacement = unique(SpeciesData$Species)))

 })
snow::stopCluster(cl)

the second script creates files that weight 42% more.

How can I save files in parallel without automatically increasing the file size?

Body:
I have not used ddply to parallelize saving objects, so I guess the file gets much larger because when you save model object, it carrys also some information about the environment from which it is saved.

So using your ddply code above, the sizes I have are:

sapply(dir(pattern="RData"),file.size)
setosa.RData versicolor.RData  virginica.RData
       36002            36002            36002

There are two options, one is to use purrr / furrr:

library(furrr)
library(purrr)

func = function(SpeciesData){
  Model <- lm(formula = "Sepal.Length~Sepal.Width+Petal.Length+Petal.Width",data = SpeciesData)
  save(Model,
       compress = FALSE,
       file = gsub(x =  "Species.RData",
                   pattern = "Species",
                   replacement = unique(SpeciesData$Species)))
}

split(iris,iris$Species) %>% future_map(func)

sapply(dir(pattern="RData"),file.size)
    setosa.RData versicolor.RData  virginica.RData
           25426            27156            27156

Or to use saveRDS (and ddply?) since you only have one object to save:

ddply(.data = iris,
      .variables = "Species",
      .parallel=TRUE,##With parallel
      .fun = function(SpeciesData){
        Model <- lm(formula = "Sepal.Length~Sepal.Width+Petal.Length+Petal.Width",data = SpeciesData)
        saveRDS(Model,
             gsub(x =  "Species.rds",
                         pattern = "Species",
                         replacement = unique(SpeciesData$Species)))

      })

sapply(dir(pattern="rds"),file.size)
    setosa.rds versicolor.rds  virginica.rds
          6389           6300           6277

You will do readRDS instead of load to get the file:

m1 = readRDS("setosa.rds")
m1
Call:
lm(formula = "Sepal.Length~Sepal.Width+Petal.Length+Petal.Width",
    data = SpeciesData)

Coefficients:
 (Intercept)   Sepal.Width  Petal.Length   Petal.Width
      2.3519        0.6548        0.2376        0.2521

We can look at the coefficients in comparison with the rda object:

m2 = get(load("setosa.RData"))
m2

Call:
lm(formula = "Sepal.Length~Sepal.Width+Petal.Length+Petal.Width",
    data = SpeciesData)

Coefficients:
 (Intercept)   Sepal.Width  Petal.Length   Petal.Width
      2.3519        0.6548        0.2376        0.2521

The objects are not identical because of the environment parts, but in terms of prediction or other stuff we normally use it for, it works:

identical(predict(m1,data.frame(iris[1:10,])),predict(m2,data.frame(iris[1:10,])))


问:
redirect user on previous page after successfull task
What should be good way to redirect user after successful action like edit or delete any item, in delete condition we could use $_SERVER['HTTP_REFERER'] but in case of edit, we show first of all edit form and then user clicks update, so if we use same approach user would be redirected to edit page not main page. I hope you got idea about my confusion. thanks.

答:
I advice to never use HTTP_REFERER.

It is possible it isn't set at all.

It can be anything, don't expect your previous page.

I advice an solid solution using (as above mentioned) hidden field, session storage, or simply have a solid routing in your application so you know which route someone took. Pick the best.


问:
Spring JPA 2 nested many to many relationship
I am having a problem with my many to many relationship. Basically, here is what I am trying to do.
I have 2 many to many tables that are nested, as seen on the following image.
Db diagram

When compiling my code, I get the following error:

```<code>Caused by: java.sql.SQLSyntaxErrorException: Unknown column 'weeks0_.employee_project_employee_id' in 'field list'
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-3.4.1.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.1.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:57) ~[hibernate-core-5.4.6.Final.jar:5.4.6.Final]
</code>```

So I understand that I have a problem with the weeks.

here are my entities:

Week:

```<code>package com.achsogo.rpt.entity;

import javax.persistence.*;
import java.util.Set;

@Entity
@Table(name="week")
public class Week {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private int weekNumber;
private int year;

@OneToMany(mappedBy = "week", cascade = CascadeType.ALL, orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<EmployeeProjectWeek> employeeProjects;

public Week() {
}

public Week(int weekNumber, int year) {
    this.weekNumber = weekNumber;
    this.year = year;
} //Getter and Setters
</code>```

Project:

```<code>import javax.persistence.*;
import java.util.*;

@Entity
@Table(name = "project")
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String alias;
private String pspElement;
private int contractValue;
private int plannedCost;
private int plannedHours;
private int assignedHours;
private Date startDate;
private Date endDate;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "project", orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<ProjectAP> projectAPS;
@ManyToOne
private Department department;
@OneToMany(mappedBy = "project", cascade = CascadeType.ALL, orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<EmployeeProject> employees;

//Empty constructor
public Project(){}

//constructor for new project with default names
public Project(String alias){
    this.alias = alias;
}
</code>```

Employee:

```<code>@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private String email;
private int employeeNumber;
private String acronym;
private int availability;
@OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<EmployeeProject> projects;
@ManyToOne
private Department department;
@ManyToOne
private Role role;
</code>```

Table between Project and Employee (with the class to create the ID):

EmployeeProjectID:

```<code>@Embeddable
public class EmployeeProjectId implements Serializable {

private Long projectId;
private Long employeeId;

private EmployeeProjectId(){}

public EmployeeProjectId(Long projectId, Long employeeId){
    this.employeeId = employeeId;
    this.projectId = projectId;
}
</code>```

EmployeeProject: It is here that the weeks are being called (If I am not mistaken)

```<code>@Entity
@Table(name = "project_employee")
public class EmployeeProject {

@EmbeddedId
private EmployeeProjectId id;

@ManyToOne(fetch = FetchType.EAGER)
@MapsId("projectId")
private Project project;

@ManyToOne(fetch = FetchType.EAGER)
@MapsId("employeeId")
private Employee employee;

@Column(name = "amount_time")
private int amountTime = 0;

@Column(name = "is_project_leader")
private boolean isProjectLeader = false;

@OneToMany(mappedBy = "employeeProject", cascade = CascadeType.ALL, orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<EmployeeProjectWeek> weeks;

public EmployeeProject(){}
</code>```

And now the table between Week and Employee Project:

EmployeeProjectWeekId: To create the ID for the nested many to many table:

```<code>@Embeddable
public class EmployeeProjectWeekId implements Serializable {

private EmployeeProjectId employeeProjectId;
private Long weekId;

private EmployeeProjectWeekId(){}
</code>```

And finally the EmployeeProjectweek:

```<code>@Entity
@Table(name="project_employee_week")
public class EmployeeProjectWeek {

@EmbeddedId
private EmployeeProjectWeekId id;

@ManyToOne(fetch = FetchType.EAGER)
@MapsId("weekId")
private Week week;

@ManyToOne(fetch = FetchType.EAGER)
@MapsId("employeeProjectId")
private EmployeeProject employeeProject;

@Column(name="amount_time")
private int amountTime = 0;

@Column(name="is_project_leader")
private boolean isProjectLeader= false;

public EmployeeProjectWeek(Week week, EmployeeProject employeeProject) {
    this.week = week;
    this.employeeProject = employeeProject;
    this.id = new EmployeeProjectWeekId(employeeProject.getId(), week.getId());
}
</code>```

Does anyone has a clue where I have done an error? Thanks in advance for your time!

答:
It was a naming problem. I solved this by dropping all the tables in my DB and having Spring to automatically generate the tables. Now everything works well.

I entered the following lines in my application.properties:

```<code>spring.jpa.hibernate.ddl=true
spring.jpa.hibernate.ddl-auto=update
</code>```

Body:
I am having a problem with my many to many relationship. Basically, here is what I am trying to do.
I have 2 many to many tables that are nested, as seen on the following image.
Db diagram

When compiling my code, I get the following error:

Caused by: java.sql.SQLSyntaxErrorException: Unknown column 'weeks0_.employee_project_employee_id' in 'field list'
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-3.4.1.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.1.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:57) ~[hibernate-core-5.4.6.Final.jar:5.4.6.Final]

So I understand that I have a problem with the weeks.

here are my entities:

Week:

package com.achsogo.rpt.entity;

import javax.persistence.*;
import java.util.Set;

@Entity
@Table(name="week")
public class Week {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private int weekNumber;
private int year;

@OneToMany(mappedBy = "week", cascade = CascadeType.ALL, orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<EmployeeProjectWeek> employeeProjects;

public Week() {
}

public Week(int weekNumber, int year) {
    this.weekNumber = weekNumber;
    this.year = year;
} //Getter and Setters

Project:

import javax.persistence.*;
import java.util.*;

@Entity
@Table(name = "project")
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String alias;
private String pspElement;
private int contractValue;
private int plannedCost;
private int plannedHours;
private int assignedHours;
private Date startDate;
private Date endDate;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "project", orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<ProjectAP> projectAPS;
@ManyToOne
private Department department;
@OneToMany(mappedBy = "project", cascade = CascadeType.ALL, orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<EmployeeProject> employees;

//Empty constructor
public Project(){}

//constructor for new project with default names
public Project(String alias){
    this.alias = alias;
}

Employee:

@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private String email;
private int employeeNumber;
private String acronym;
private int availability;
@OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<EmployeeProject> projects;
@ManyToOne
private Department department;
@ManyToOne
private Role role;

Table between Project and Employee (with the class to create the ID):

EmployeeProjectID:

@Embeddable
public class EmployeeProjectId implements Serializable {

private Long projectId;
private Long employeeId;

private EmployeeProjectId(){}

public EmployeeProjectId(Long projectId, Long employeeId){
    this.employeeId = employeeId;
    this.projectId = projectId;
}

EmployeeProject: It is here that the weeks are being called (If I am not mistaken)

@Entity
@Table(name = "project_employee")
public class EmployeeProject {

@EmbeddedId
private EmployeeProjectId id;

@ManyToOne(fetch = FetchType.EAGER)
@MapsId("projectId")
private Project project;

@ManyToOne(fetch = FetchType.EAGER)
@MapsId("employeeId")
private Employee employee;

@Column(name = "amount_time")
private int amountTime = 0;

@Column(name = "is_project_leader")
private boolean isProjectLeader = false;

@OneToMany(mappedBy = "employeeProject", cascade = CascadeType.ALL, orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<EmployeeProjectWeek> weeks;

public EmployeeProject(){}

And now the table between Week and Employee Project:

EmployeeProjectWeekId: To create the ID for the nested many to many table:

@Embeddable
public class EmployeeProjectWeekId implements Serializable {

private EmployeeProjectId employeeProjectId;
private Long weekId;

private EmployeeProjectWeekId(){}

And finally the EmployeeProjectweek:

@Entity
@Table(name="project_employee_week")
public class EmployeeProjectWeek {

@EmbeddedId
private EmployeeProjectWeekId id;

@ManyToOne(fetch = FetchType.EAGER)
@MapsId("weekId")
private Week week;

@ManyToOne(fetch = FetchType.EAGER)
@MapsId("employeeProjectId")
private EmployeeProject employeeProject;

@Column(name="amount_time")
private int amountTime = 0;

@Column(name="is_project_leader")
private boolean isProjectLeader= false;

public EmployeeProjectWeek(Week week, EmployeeProject employeeProject) {
    this.week = week;
    this.employeeProject = employeeProject;
    this.id = new EmployeeProjectWeekId(employeeProject.getId(), week.getId());
}

Does anyone has a clue where I have done an error? Thanks in advance for your time!

Body:
It was a naming problem. I solved this by dropping all the tables in my DB and having Spring to automatically generate the tables. Now everything works well.

I entered the following lines in my application.properties:

spring.jpa.hibernate.ddl=true
spring.jpa.hibernate.ddl-auto=update


问:
mongoose foreign key problem with node.js
I have 3 collections:

```<code>const LeaveSchema = new mongoose.Schema({
 employee: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }
})
</code>```

```<code>const UserSchema = new mongoose.Schema({
 company: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Company'
    }
})
</code>```

```<code>const CompanySchema = new mongoose.Schema({
 //
})
</code>```

How can i get list of "leaves" of "users" in the same "company"

答:
I find a solution: </p>

```<code>leaves = await Leave.aggregate([
        {
            "$lookup": {
                "from": "users",
                "let": { "companyId": "$employe" },
                "pipeline": [
                    { "$match": { "$expr": { "$eq": ["$_id", "$$companyId"] } } },
                    {
                        "$lookup": {
                            "from": "companies",
                            "let": { "companyId": "$company" },
                            "pipeline": [
                                { "$match": { "_id": new mongoose.Types.ObjectId(company_id),"$expr": { "$eq": ["$_id", "$$companyId"] } } }
                            ],
                            "as": "companies"
                        }
                    },
                    { "$unwind": "$companies" }
                ],
                "as": "users"
            }
        },
        { "$unwind": "$users" }
    ])
</code>```

Body:
I have 3 collections:

const LeaveSchema = new mongoose.Schema({
 employee: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }
})

const UserSchema = new mongoose.Schema({
 company: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Company'
    }
})

const CompanySchema = new mongoose.Schema({
 //
})

How can i get list of "leaves" of "users" in the same "company"

Body:
I find a solution:

leaves = await Leave.aggregate([
        {
            "$lookup": {
                "from": "users",
                "let": { "companyId": "$employe" },
                "pipeline": [
                    { "$match": { "$expr": { "$eq": ["$_id", "$$companyId"] } } },
                    {
                        "$lookup": {
                            "from": "companies",
                            "let": { "companyId": "$company" },
                            "pipeline": [
                                { "$match": { "_id": new mongoose.Types.ObjectId(company_id),"$expr": { "$eq": ["$_id", "$$companyId"] } } }
                            ],
                            "as": "companies"
                        }
                    },
                    { "$unwind": "$companies" }
                ],
                "as": "users"
            }
        },
        { "$unwind": "$users" }
    ])


问:
Check for NULL ggplot object before adding layers in dplyr pipe
I have template plot functions that check whether a data frame has > 0 rows before running:

```<code>library(tidyverse)

plot_fun <- function(df) {
  if (nrow(df) > 0) {
    df %>%
      ggplot(., aes(Sepal.Length, Sepal.Width)) +
      geom_point()
  }
}
</code>```

Then I use this within pipes and add bespoke layers:

```<code>iris %>% plot_fun() + ggtitle("Plot me")
</code>```

However if the data framed piped in has 0 rows I get an error because I am trying to add layers to nothing:

```<code>iris %>%
  filter(Sepal.Length > 1000) %>%
  plot_fun() +
  ggtitle("Plot me")
</code>```

Error in iris %>% filter(Sepal.Length > 1000) %>% plot_fun() +
  ggtitle("Plot me") :    non-numeric argument to binary operator

I can build a check mid pipe to avoid the error:

```<code>iris %>%
  filter(Sepal.Length > 1000) %>%
  plot_fun() %>%
  {
    if (!is.null(.)) {
      . +
        ggtitle("Plot me")
    }
  }
</code>```

That works but that seems clunky. Is it possible to make a function check_df_pipe() or something to stop the pipe if preceding filters remove all data? Or maybe to check if the pipe . is NULL at a point?

```<code>check_df_pipe <- function(x) {
  if(nrow(x) > 0) {
    x
  } else{
    stop("Dont return an error just to exit pipe")
  }
}

iris %>%
  filter(Sepal.Length > 1000) %>%
  check_df_pipe() %>%
  plot_fun() +
  ggtitle("Plot me")
</code>```

Error in check_df_pipe(.) : Dont return an error just to exit pipe

Or any other ideas on how to deal with this? I don't want to add ggtitle("Plot me") into plot_fun because I wan't plot_fun to stay generic.

答:
Option 1: Blank plot

This doesn't directly answer your question, but how about a different approach?  When the dataframe has zero rows, use geom_blank() to create an empty plot.  Adding a title later doesn't return an error.

```<code>plot_fun <- function(df) {
  if (nrow(df) > 0) {
    df %>%
      ggplot(., aes(Sepal.Length, Sepal.Width)) +
      geom_point()
  } else {
    ggplot(data = data.frame()) +
      geom_blank()
  }
}

iris %>%
  filter(Sepal.Length > 1000) %>%
  plot_fun() +
  ggtitle("Plot me")
</code>```

Option 2: Pass layers into a function

You can pass layers as function arguments.  Here's a function that checks whether the plot exists, and then adds the layers only if it does.

```<code>append_layers_maybe <- function(p, l) {
  if(!is.null(p)) {
    p + l
  }
}

iris %>%
  plot_fun() %>%
  append_layers_maybe(facet_wrap(~ Species)) %>%
  append_layers_maybe(ggtitle("Foo"))

iris %>%
  filter(Sepal.Length > 1000) %>%
  plot_fun() %>%
  append_layers_maybe(facet_wrap(~ Species)) %>%
  append_layers_maybe(ggtitle("Plot me"))
</code>```

Body:
I have template plot functions that check whether a data frame has > 0 rows before running:

library(tidyverse)

plot_fun <- function(df) {
  if (nrow(df) > 0) {
    df %>%
      ggplot(., aes(Sepal.Length, Sepal.Width)) +
      geom_point()
  }
}

Then I use this within pipes and add bespoke layers:

iris %>% plot_fun() + ggtitle("Plot me")

However if the data framed piped in has 0 rows I get an error because I am trying to add layers to nothing:

iris %>%
  filter(Sepal.Length > 1000) %>%
  plot_fun() +
  ggtitle("Plot me")

Error in iris %>% filter(Sepal.Length > 1000) %>% plot_fun() +
  ggtitle("Plot me") :    non-numeric argument to binary operator

I can build a check mid pipe to avoid the error:

iris %>%
  filter(Sepal.Length > 1000) %>%
  plot_fun() %>%
  {
    if (!is.null(.)) {
      . +
        ggtitle("Plot me")
    }
  }

That works but that seems clunky. Is it possible to make a function check_df_pipe() or something to stop the pipe if preceding filters remove all data? Or maybe to check if the pipe . is NULL at a point?

check_df_pipe <- function(x) {
  if(nrow(x) > 0) {
    x
  } else{
    stop("Dont return an error just to exit pipe")
  }
}

iris %>%
  filter(Sepal.Length > 1000) %>%
  check_df_pipe() %>%
  plot_fun() +
  ggtitle("Plot me")

Error in check_df_pipe(.) : Dont return an error just to exit pipe

Or any other ideas on how to deal with this? I don't want to add ggtitle("Plot me") into plot_fun because I wan't plot_fun to stay generic.

Body:
Option 1: Blank plot

This doesn't directly answer your question, but how about a different approach?  When the dataframe has zero rows, use geom_blank() to create an empty plot.  Adding a title later doesn't return an error.

plot_fun <- function(df) {
  if (nrow(df) > 0) {
    df %>%
      ggplot(., aes(Sepal.Length, Sepal.Width)) +
      geom_point()
  } else {
    ggplot(data = data.frame()) +
      geom_blank()
  }
}

iris %>%
  filter(Sepal.Length > 1000) %>%
  plot_fun() +
  ggtitle("Plot me")

Option 2: Pass layers into a function

You can pass layers as function arguments.  Here's a function that checks whether the plot exists, and then adds the layers only if it does.

append_layers_maybe <- function(p, l) {
  if(!is.null(p)) {
    p + l
  }
}

iris %>%
  plot_fun() %>%
  append_layers_maybe(facet_wrap(~ Species)) %>%
  append_layers_maybe(ggtitle("Foo"))

iris %>%
  filter(Sepal.Length > 1000) %>%
  plot_fun() %>%
  append_layers_maybe(facet_wrap(~ Species)) %>%
  append_layers_maybe(ggtitle("Plot me"))


问:
Populate a combobox into a Userform with a selection of cells in the active sheet
I just started to use VBA into excel and I'm trying to create a User Form where I select data from the active sheet (the Userform shall be duplicated once I duplicate the sheet where it is included and all the reference  shall be to te active sheet):

the Userform is named "SystemDesignUserForm"

the actual sheet where it is included is named "System Design"

the ComboBox is named "DIAComboBox" and shall list the data included into cells "w6:w33".

I tried with the code:

```<code>DIAComboBox.List = Range("W6:W33").Value
</code>```

and also with

```<code>DIAComboBox.List = ActiveSheet.Range("W6:W33").Value
</code>```

and with:

```<code>DIAComboBox.List = Worksheets("System Design").Range("W6:W33").Value
</code>```

but it doesn't wotk: the combobox appear void.

Do you have any suggestion?

答:
You can try iterating through the range and populate:

```<code>'set worksheet
Dim ws as Worksheet
Set ws = Worksheets("System Design")

'loop through and collect range
    For each c in ws.Range("W6:W33")
        With Me.DIAComboBox
            .AddItem c.Value
        End With
    Next c

    Me.DIAComboBox.SetFocus
</code>```

Hopefully this helps.

Body:
I just started to use VBA into excel and I'm trying to create a User Form where I select data from the active sheet (the Userform shall be duplicated once I duplicate the sheet where it is included and all the reference  shall be to te active sheet):

the Userform is named "SystemDesignUserForm"

the actual sheet where it is included is named "System Design"

the ComboBox is named "DIAComboBox" and shall list the data included into cells "w6:w33".

I tried with the code:

DIAComboBox.List = Range("W6:W33").Value

and also with

DIAComboBox.List = ActiveSheet.Range("W6:W33").Value

and with:

DIAComboBox.List = Worksheets("System Design").Range("W6:W33").Value

but it doesn't wotk: the combobox appear void.

Do you have any suggestion?

Body:
You can try iterating through the range and populate:

'set worksheet
Dim ws as Worksheet
Set ws = Worksheets("System Design")

'loop through and collect range
    For each c in ws.Range("W6:W33")
        With Me.DIAComboBox
            .AddItem c.Value
        End With
    Next c

    Me.DIAComboBox.SetFocus

Hopefully this helps.


答:
df = df.sort_values(by=['name', 'timestamp'], ascending=True)

The by parameter can either be a string or a list of strings, see https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html

Title: Pandas sort sorted indices by datetime

Body:
I have the following dataframe:

               latitude  longitude       timestamp
name
testschip-1   51.822872   4.905615 2019-08-01 00:00:00
testschip-1   51.822876   4.905613 2019-08-01 00:00:57
testschip-1   51.822872   4.905613 2019-08-01 00:00:20
testschip-1   51.822880   4.905627 2019-08-01 00:00:27
testschip-1   51.822872   4.905613 2019-08-01 00:00:09
testschip-1   51.822872   4.905613 2019-08-01 00:00:39
testschip-1   51.822876   4.905613 2019-08-01 00:00:38
testschip-10  51.824749   4.965562 2019-08-01 00:00:56
testschip-10  51.827072   4.952107 2019-08-01 00:00:47
testschip-10  51.826794   4.954065 2019-08-01 00:00:19
testschip-10  51.826702   4.954648 2019-08-01 00:00:08
testschip-11  51.819588   4.962135 2019-08-01 00:00:57
testschip-11  51.819584   4.962165 2019-08-01 00:00:38
testschip-11  51.819588   4.962172 2019-08-01 00:00:08
testschip-11  51.819588   4.962122 2019-08-01 00:00:17

Per name (on the index) I would like to get the timestamp hierachically sorted.
If I do:

df = df.sort_values(by='timestamp',ascending=True)

I sort by time, but I lose my sorted names on the indices. How do I keep my sorted indices and sort these indices by time?


问:
Wrong constant on FragmentStatePagerAdapter constructor
When I extend my adapter with a FragmentStatePagerAdapter and pass the arguments with fragment manager and the constant BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT to the constructor I receive an error on lint with the message "wrong constant".

I've checked on the documentation if the constant is the correct one, and is everything ok compared with my code.

My question is, Why Lint gives me this error if I'm doing this correctly?

My Adapter code:

```<code>class CardBannerAdapter(
    fm: FragmentManager
) : FragmentStatePagerAdapter(
   fm, androidx.fragment.app.FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
) {

}
</code>```

答:
I fixed it by upgrading build tools in project build.gradle</p>

```<code>classpath 'com.android.tools.build:gradle:3.5.3'
</code>```

Body:
When I extend my adapter with a FragmentStatePagerAdapter and pass the arguments with fragment manager and the constant BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT to the constructor I receive an error on lint with the message "wrong constant".

I've checked on the documentation if the constant is the correct one, and is everything ok compared with my code.

My question is, Why Lint gives me this error if I'm doing this correctly?

My Adapter code:

class CardBannerAdapter(
    fm: FragmentManager
) : FragmentStatePagerAdapter(
   fm, androidx.fragment.app.FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
) {

}

Body:
I fixed it by upgrading build tools in project build.gradle

classpath 'com.android.tools.build:gradle:3.5.3'


问:
Which is quicker/more efficient?
Currently learning about efficiency in C++ and wondered about the efficiency of returning parameters in methods.

Imagine a Vector3f class with an add method.

Code One:

```<code>Vector3f Vector3f::add(const Vector3f &rhs) const {
    Vector3f result;
    result.x(x() + rhs.x());
    result.y(y() + rhs.y());
    result.z(z() + rhs.z());
    return result;
}
</code>```

Code Two:

```<code>Vector3f Vector3f::add(const Vector3f &rhs) const {
    return Vector3f(
                x() + rhs.x(),
                y() + rhs.y(),
                z() + rhs.z());
}
</code>```

I know that the second code segment is more efficient, and I was hoping someone could give me a definitive answer as to why. I'm sure it's something to do with temporary objects.

答:
It probably has to do with the return-value optimisation (RVO). Because the second form constructs the object as it returns it, the compiler is allowed to (and usually will) skip the copy-constructor by constructing the object directly in the caller's context.

The first form can also be optimised in similar fashion, but I've often seen compilers optimise the latter and not the former.

Title: Which is quicker/more efficient?

Body:
Currently learning about efficiency in C++ and wondered about the efficiency of returning parameters in methods.

Imagine a Vector3f class with an add method.

Code One:

Vector3f Vector3f::add(const Vector3f &rhs) const {
    Vector3f result;
    result.x(x() + rhs.x());
    result.y(y() + rhs.y());
    result.z(z() + rhs.z());
    return result;
}

Code Two:

Vector3f Vector3f::add(const Vector3f &rhs) const {
    return Vector3f(
                x() + rhs.x(),
                y() + rhs.y(),
                z() + rhs.z());
}

I know that the second code segment is more efficient, and I was hoping someone could give me a definitive answer as to why. I'm sure it's something to do with temporary objects.