问:
Capybara Screenshot formatted
My Capybara-screenshots are looking silly - it does not apply any stylesheets.

and, it seems to make screenshots not exactly after error occurs: by producing a error manually i see different views as opened by the gem.

what do i have to configure?

here is my spec/rails_helper.rb
rails-6.1
and rails s -p 3000 is running alongside the tests

```<code>require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'

require File.expand_path('../config/environment', __dir__)

abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'

require 'capybara/rspec'
require 'capybara-screenshot/rspec'
#Capybara.server = :puma
Capybara.asset_host = "http://localhost:3000/"
Capybara::Screenshot.after_save_html do |path|
  `open #{path}`
end
Capybara::Screenshot.prune_strategy = :keep_last_run

begin
  ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
  puts e.to_s.strip
  exit 1
end
RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = true
  config.infer_spec_type_from_file_location!
  config.filter_rails_from_backtrace!
end
</code>```

Gemfile:

```<code>group :test do
  gem 'capybara', '>= 2.15'
  gem 'selenium-webdriver'
  gem 'webdrivers'
  gem 'capybara-screenshot'
end
group :development, :test do
  gem 'rspec-rails', '~> 3.9'
end
</code>```

on the output-file, the first line ist

```<code><html class="no-js" lang="en"><!--<![endif]--><head><base href='http://localhost:3000/' />
</code>```

so, it seems that capybara-screenshot has checked the csshttps://github.com/mattheworiordan/capybara-screenshot#better-looking-html-screenshots

Thanks for help!

答: Is there a specific reason you're looking at the HTML "screenshots" instead of the jpg screenshots?  The HTML ones will never be fully correct, and really should only be used for verifying HTML structure, not for current values/state. The reason for this is it saves the HTML and attributes, but can't save the JS properties of each element, so it won't save the current state of checkboxes, etc.  The jpg screenshots, on the other hand, are a picture of what the browser actually rendered. As for why the HTML versions wouldn't be loading the CSS, take a look at the source of the file and make sure a <base> element is correctly being injected into the  element of the page.

Title: Capybara Screenshot formatted

Body:
My Capybara-screenshots are looking silly - it does not apply any stylesheets.

and, it seems to make screenshots not exactly after error occurs: by producing a error manually i see different views as opened by the gem.

what do i have to configure?

here is my spec/rails_helper.rb
rails-6.1
and rails s -p 3000 is running alongside the tests

require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'

require File.expand_path('../config/environment', __dir__)

abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'

require 'capybara/rspec'
require 'capybara-screenshot/rspec'
#Capybara.server = :puma
Capybara.asset_host = "http://localhost:3000/"
Capybara::Screenshot.after_save_html do |path|
  `open #{path}`
end
Capybara::Screenshot.prune_strategy = :keep_last_run

begin
  ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
  puts e.to_s.strip
  exit 1
end
RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = true
  config.infer_spec_type_from_file_location!
  config.filter_rails_from_backtrace!
end

Gemfile:

group :test do
  gem 'capybara', '>= 2.15'
  gem 'selenium-webdriver'
  gem 'webdrivers'
  gem 'capybara-screenshot'
end
group :development, :test do
  gem 'rspec-rails', '~> 3.9'
end

on the output-file, the first line ist

<base href='http://localhost:3000/' />

so, it seems that capybara-screenshot has checked the csshttps://github.com/mattheworiordan/capybara-screenshot#better-looking-html-screenshots

Thanks for help!

Body: Is there a specific reason you're looking at the HTML "screenshots" instead of the jpg screenshots?  The HTML ones will never be fully correct, and really should only be used for verifying HTML structure, not for current values/state. The reason for this is it saves the HTML and attributes, but can't save the JS properties of each element, so it won't save the current state of checkboxes, etc.  The jpg screenshots, on the other hand, are a picture of what the browser actually rendered. As for why the HTML versions wouldn't be loading the CSS, take a look at the source of the file and make sure a <base> element is correctly being injected into the <head> element of the page.


来源: stackexchange

问:
Converting a 10 digit Int into Hex and then converting that to values in C
For an exercise in C class, we are given an array of ints which contain 10 digits each:

```<code>unsigned int Array[] = { 1310740313, 1966096717, 2621456717 };
</code>```

We are asked to print out a letter, a value in the 255 range and another value in the 65535 range.

We are using a little endian machine so we have to read from the right. I can figure out the answers by using conversions online but I can't figure it out using C code.

Do I get the hex value, store it, and then do a printf on each byte?

My current code looks like:

```<code>for (int i = 0; i < ArraySize; i++)
{
    printf("%x\n", Array[i]);
}
</code>```

Output:

```<code>4e204f59, 7530414d, 9c40414d
</code>```

How do I convert these to the letter and 2 number?

答:
I think you looking for something like this:

```<code>#include <stdio.h>

unsigned int Array[] = { 1310740313, 1966096717, 2621456717 };

int main()
{
    for (int i = 0; i < 3; i++) {
        printf("%c %d %d\n", Array[i] & 0xff, // last byte as char
                             (Array[i] & 0xff00) >> 8, // second byte as decimal
                             (Array[i] & 0xffff0000) >> 16); // last 2 byte as decimal
    }
    return 0;
}
</code>```

Output

```<code>Y 79 20000
M 65 30000
M 65 40000
</code>```

Basically masking the byte(s) of interests and shifting them to the right place.

ContentLicense: CC BY-SA 4.0

Body:
For an exercise in C class, we are given an array of ints which contain 10 digits each:

unsigned int Array[] = { 1310740313, 1966096717, 2621456717 };

We are asked to print out a letter, a value in the 255 range and another value in the 65535 range.

We are using a little endian machine so we have to read from the right. I can figure out the answers by using conversions online but I can't figure it out using C code.

Do I get the hex value, store it, and then do a printf on each byte?

My current code looks like:

for (int i = 0; i < ArraySize; i++)
{
    printf("%x\n", Array[i]);
}

Output:

4e204f59, 7530414d, 9c40414d

How do I convert these to the letter and 2 number?

Body:
I think you looking for something like this:

#include <stdio.h>

unsigned int Array[] = { 1310740313, 1966096717, 2621456717 };

int main()
{
    for (int i = 0; i < 3; i++) {
        printf("%c %d %d\n", Array[i] & 0xff, // last byte as char
                             (Array[i] & 0xff00) >> 8, // second byte as decimal
                             (Array[i] & 0xffff0000) >> 16); // last 2 byte as decimal
    }
    return 0;
}

Output

Y 79 20000
M 65 30000
M 65 40000

Basically masking the byte(s) of interests and shifting them to the right place.


问:
Files deleted after push in GitHub remote repository
I have my first Git repository that I have created online named myName/python-algorithms.

It was containing many Python scripts. I tried to add a file test.py from my local Ubuntu terminal with the commands:

```<code>git init
git config user.name "myName"
git config user.e-mail "myEmail@myEmail.se"
git add test.py
git commit -m "some init msg"
git remote add origin https://github.com/myname/Python_Algorithms.git
git remote -v
git push -f origin master
</code>```

which deleted all my Python scripts and replaced them with the file test.py on GitHub.

Any idea how I can get back my scripts that were deleted?

答:
Any idea how I can get back my scripts that were deleted?

The main way: Find a backup copy/clone of the original repository (or beg GitHub administrators to find one).

A temporary way: If you have a hash ID showing somewhere in a window or written down somewhere on paper or a whiteboard, and can navigate to the GitHub URL for that commit (e.g., https://github.com/git/git/commit/b9e62f60115c75c5be5de593862925c8b8d7e683 is the URL for one particular commit on GitHub in this particular Git repository for Git), use that to get to the tree object by clicking on "Browse Files", and use that to get to your files.  There is a limited time window during which you can do this; after that, GitHub's maintenance scrubbers will have deleted the commits and they will not be recoverable except via backup copies or other clones.

Remember, what Git stores are commits.  Every commit holds a full and complete snapshot of all of your files, along with some metadata: information about the commit, such as who made it and when.  Every commit has a unique hash ID, so that any Git repository can immediately tell whether it has that commit just by inspecting the hash ID.  If the repository has a commit with that hash ID, it has that commit.

Meanwhile, of course, every repository holds some set of commits.  Your GitHub repository had some set of commits, with your files in them.

When you create a new, empty repository:

```<code>git init
git config user.name "myName"
git config user.e-mail "myEmail@myEmail.se"
</code>```

this new empty repository has no commits at all.  That's not that big a deal since you can then make new commits:

```<code>git add test.py
git commit -m "some init msg"
</code>```

This new repository now has one commit.  Let's draw it.  It has some big ugly hash ID, but let's call it H for "hash":

```<code>H   <-- master
</code>```

Meanwhile, the GitHub repository at https://github.com/myname/Python_Algorithms.git has other commit(s).  Let's assume it has four commits, and call them A, B, C, and D.  Its master holds the hash ID of commit D, which points back to commit C, which points back to B, which points to A, which is the first commit in that repository and hence doesn't point anywhere:

```<code>A <-B <-C <-D   <-- master   (in the Git on GitHub)
</code>```

When you run git push without -f:

```<code>git remote add origin https://github.com/myname/Python_Algorithms.git
git remote -v
</code>```

[and what you didn't do:]

```<code>git push origin master
</code>```

your Git will call up that other Git and offer it your one commit, which you have and they don't.  So far, all is well: they take that one commit and put it in a quarantine area.  Then, your Git says to their Git: Please, if it's OK, use this commit's hash ID to set your branch name master.

Their Git looks in their repository, which has a chain of commits ending at D.  It tries following commit H backwards, to see if that will get it to commit D.  But commit H has no parent: it's a new root commit, like A.  So H doesn't lead back to D, and GitHub responds to your Git: No!  If I overwrite my name master with commit hash H, I'll lose commit D and thereby all earlier commits too!

Alas, you told your Git to git push -f origin master, adding the force flag.  The force flag changes your Git's polite Please, if it is OK request into a command: Set your master!

The Git over on GitHub obeyed.  He set his master to point to H:

```<code>A--B--C--D   [abandoned]

H   <-- master
</code>```

The old commits in the GitHub repository are not accessible by normal Git mechanisms, at this point.  Eventually, their Git maintenance / janitor processing will come around and sweep away the original chain of commits forever.  Until then, access by direct URL through the .../commit/<hash> URL bypasses the normal Git mechanisms, so it can still work.  But all regular Git operations are foiled by the fact that their master now points to commit H and there is no way for their Git to find commit D.

There may be some other clone you, or someone else, made, that contains commit D (and if so it likely has A through C as well, or perhaps it has only A through C as it never got updated after D got added, or whatever).  If you can find such a repository, and can access its commits—by hash ID or by names like master—you can get your files that way, from those commits.  If not ... well, that's why git push --force is dangerous!

Body:
I have my first Git repository that I have created online named myName/python-algorithms.

It was containing many Python scripts. I tried to add a file test.py from my local Ubuntu terminal with the commands:

git init
git config user.name "myName"
git config user.e-mail "myEmail@myEmail.se"
git add test.py
git commit -m "some init msg"
git remote add origin https://github.com/myname/Python_Algorithms.git
git remote -v
git push -f origin master

which deleted all my Python scripts and replaced them with the file test.py on GitHub.

Any idea how I can get back my scripts that were deleted?

Body:
Any idea how I can get back my scripts that were deleted?

The main way: Find a backup copy/clone of the original repository (or beg GitHub administrators to find one).

A temporary way: If you have a hash ID showing somewhere in a window or written down somewhere on paper or a whiteboard, and can navigate to the GitHub URL for that commit (e.g., https://github.com/git/git/commit/b9e62f60115c75c5be5de593862925c8b8d7e683 is the URL for one particular commit on GitHub in this particular Git repository for Git), use that to get to the tree object by clicking on "Browse Files", and use that to get to your files.  There is a limited time window during which you can do this; after that, GitHub's maintenance scrubbers will have deleted the commits and they will not be recoverable except via backup copies or other clones.

Remember, what Git stores are commits.  Every commit holds a full and complete snapshot of all of your files, along with some metadata: information about the commit, such as who made it and when.  Every commit has a unique hash ID, so that any Git repository can immediately tell whether it has that commit just by inspecting the hash ID.  If the repository has a commit with that hash ID, it has that commit.

Meanwhile, of course, every repository holds some set of commits.  Your GitHub repository had some set of commits, with your files in them.

When you create a new, empty repository:

git init
git config user.name "myName"
git config user.e-mail "myEmail@myEmail.se"

this new empty repository has no commits at all.  That's not that big a deal since you can then make new commits:

git add test.py
git commit -m "some init msg"

This new repository now has one commit.  Let's draw it.  It has some big ugly hash ID, but let's call it H for "hash":

H   <-- master

Meanwhile, the GitHub repository at https://github.com/myname/Python_Algorithms.git has other commit(s).  Let's assume it has four commits, and call them A, B, C, and D.  Its master holds the hash ID of commit D, which points back to commit C, which points back to B, which points to A, which is the first commit in that repository and hence doesn't point anywhere:

A <-B <-C <-D   <-- master   (in the Git on GitHub)

When you run git push without -f:

git remote add origin https://github.com/myname/Python_Algorithms.git
git remote -v

[and what you didn't do:]

git push origin master

your Git will call up that other Git and offer it your one commit, which you have and they don't.  So far, all is well: they take that one commit and put it in a quarantine area.  Then, your Git says to their Git: Please, if it's OK, use this commit's hash ID to set your branch name master.

Their Git looks in their repository, which has a chain of commits ending at D.  It tries following commit H backwards, to see if that will get it to commit D.  But commit H has no parent: it's a new root commit, like A.  So H doesn't lead back to D, and GitHub responds to your Git: No!  If I overwrite my name master with commit hash H, I'll lose commit D and thereby all earlier commits too!

Alas, you told your Git to git push -f origin master, adding the force flag.  The force flag changes your Git's polite Please, if it is OK request into a command: Set your master!

The Git over on GitHub obeyed.  He set his master to point to H:

A--B--C--D   [abandoned]

H   <-- master

The old commits in the GitHub repository are not accessible by normal Git mechanisms, at this point.  Eventually, their Git maintenance / janitor processing will come around and sweep away the original chain of commits forever.  Until then, access by direct URL through the .../commit/<hash> URL bypasses the normal Git mechanisms, so it can still work.  But all regular Git operations are foiled by the fact that their master now points to commit H and there is no way for their Git to find commit D.

There may be some other clone you, or someone else, made, that contains commit D (and if so it likely has A through C as well, or perhaps it has only A through C as it never got updated after D got added, or whatever).  If you can find such a repository, and can access its commits—by hash ID or by names like master—you can get your files that way, from those commits.  If not ... well, that's why git push --force is dangerous!


问:
How to authorize in a maven repository using drone.io
So I got a self-hosted instance of drone running on my server alongside a nexus3 repository.
Now I have a java project that should be built, tested and then deployed into the repository every push, which works fine until we get to the deployment part. I found the plugin on the official site for plugins, Maven Auth which is supposed to create a settings.xml based on the configuration, that works (made my pipeline output the contents of the file via cat and showed a valid settings.xml file).
The next step is configured to run

mvn deploy -B -s settings.xml

For some reason, maven doesn't use the username and password provided in the settings.xml (the server always returns an Unauthorized 401 error)

Entire .drone.yml:

```<code>kind: pipeline
name: default
type: docker

steps:
  - name: compile
    image: maven:3-jdk-8
    commands:
      - mvn compile -B -U
    when:
      event:
        - push
  - name: test
    image: maven:3-jdk-8
    commands:
      - mvn test -B
    when:
      event:
        - push
  - name: authenticate
    image: robertstettner/drone-mvn-auth
    settings:
      servers:
        - id: some-id (same in pom.xml distribution repos)
          username: username
          password:
            from_secret: repo_password
  - name: deploy_repo
    image: maven:3-jdk-8
    commands:
      - mvn deploy -B -gs settings.xml
    when:
      event:
        - push
</code>```

Some advice why this doesn't work would be dope! Thanks in advance!

Edit 2:
So I investigated further and installed mitmproxy on my server to analyze the traffic (Client -> Nginx SSL termination proxy -> mitmproxy -> running nexus).

To authorize apparently maven uses a header called "Authorization". And the content is "Basic " + username:password encoded in base64.

Turns out, the content of the Authorization header from the request the drone instance issues is malformed. Decoded it looks like this:

Authorization: Basic USERNAME:[object Object]

instead of

Authorization: Basic USERNAME:password

I am going to try getting around the

```<code>password:
  from_secret: repo_password
</code>```

and hope the settings.xml file is the generated properly

答:
After trying for multiple hours (and failing) trying to get this plugin to work I now decided to use a custom step to create the settings.xml using environment variables.
Just set the secret "repo_username" to the username and the secret "repo_password" to the password and you should be good to go.

  - name: create settings.xml
    image: alpine:latest
    environment:
      REPO_ID: sytm-nexus
      REPO_USERNAME:
        from_secret: repo_username
      REPO_PASSWORD:
        from_secret: repo_password
    commands:
      - echo '<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd"><servers><server><id>'$REPO_ID'</id><username>'$REPO_USERNAME'</username><password>'$REPO_PASSWORD'</password></server></servers></settings>' > settings.xml
```

Edit: As that solution was too hacky for me I created my own drone plugin, which can be found here

Body:
So I got a self-hosted instance of drone running on my server alongside a nexus3 repository.
Now I have a java project that should be built, tested and then deployed into the repository every push, which works fine until we get to the deployment part. I found the plugin on the official site for plugins, Maven Auth which is supposed to create a settings.xml based on the configuration, that works (made my pipeline output the contents of the file via cat and showed a valid settings.xml file).
The next step is configured to run

mvn deploy -B -s settings.xml

For some reason, maven doesn't use the username and password provided in the settings.xml (the server always returns an Unauthorized 401 error)

Entire .drone.yml:

kind: pipeline
name: default
type: docker

steps:
  - name: compile
    image: maven:3-jdk-8
    commands:
      - mvn compile -B -U
    when:
      event:
        - push
  - name: test
    image: maven:3-jdk-8
    commands:
      - mvn test -B
    when:
      event:
        - push
  - name: authenticate
    image: robertstettner/drone-mvn-auth
    settings:
      servers:
        - id: some-id (same in pom.xml distribution repos)
          username: username
          password:
            from_secret: repo_password
  - name: deploy_repo
    image: maven:3-jdk-8
    commands:
      - mvn deploy -B -gs settings.xml
    when:
      event:
        - push

Some advice why this doesn't work would be dope! Thanks in advance!

Edit 2:
So I investigated further and installed mitmproxy on my server to analyze the traffic (Client -> Nginx SSL termination proxy -> mitmproxy -> running nexus).

To authorize apparently maven uses a header called "Authorization". And the content is "Basic " + username:password encoded in base64.

Turns out, the content of the Authorization header from the request the drone instance issues is malformed. Decoded it looks like this:

Authorization: Basic USERNAME:[object Object]

instead of

Authorization: Basic USERNAME:password

I am going to try getting around the

password:
  from_secret: repo_password

and hope the settings.xml file is the generated properly

Body:
After trying for multiple hours (and failing) trying to get this plugin to work I now decided to use a custom step to create the settings.xml using environment variables.
Just set the secret "repo_username" to the username and the secret "repo_password" to the password and you should be good to go.

  - name: create settings.xml
    image: alpine:latest
    environment:
      REPO_ID: sytm-nexus
      REPO_USERNAME:
        from_secret: repo_username
      REPO_PASSWORD:
        from_secret: repo_password
    commands:
      - echo '<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd"><servers><server><id>'$REPO_ID'</id><username>'$REPO_USERNAME'</username><password>'$REPO_PASSWORD'</password></server></servers></settings>' > settings.xml

Edit: As that solution was too hacky for me I created my own drone plugin, which can be found here


问:
css&html nav bar should appear when checkbox is checked
I've tried using the two sibling selectors (~, as in snippet, and +) to make the nav bar appear when the box is checked, but it doesn't work, nor do I know what else to do.

nav {
  left: -100%;
  position: fixed;
}

#check:checked~nav {
  left: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="check"><label for="check"><i class="fas fa-bars"></i></label></div>
<nav>
  <ul>
    <li>Test</li>
    <li>Test</li>
    <li>Test</li>
  </ul>
</nav></code>```

答:
Here is what you code should look like, first you have a none closed
 tag and for + sibling select move the label for the above the checkbox.

nav{
    left: -100%;
    position: fixed;

}

#check:checked + nav{
    left: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="check"><i class="fas fa-bars"></i></label>
<input type="checkbox" id="check">
    <nav>
    <ul><li>Test</li>
        <li>Test</li>
        <li>Test</li>
    </ul>
    </nav></code>```

and if you want to have the same order for the tag change the CSS selector to this:

nav{
    left: -100%;
    position: fixed;
}

#check:checked + label + nav{
    left: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="check">
<label for="check"><i class="fas fa-bars"></i></label>
<nav>
  <ul>
    <li>Test</li>
    <li>Test</li>
    <li>Test</li>
  </ul>
</nav></code>```

Body:
I've tried using the two sibling selectors (~, as in snippet, and +) to make the nav bar appear when the box is checked, but it doesn't work, nor do I know what else to do.

nav {
  left: -100%;
  position: fixed;
}

#check:checked~nav {
  left: 0;
}

<input type="checkbox" id="check">

Test

Test

Test

Body:
Here is what you code should look like, first you have a none closed <div> tag and for + sibling select move the label for the above the checkbox.

nav{
    left: -100%;
    position: fixed;

}

#check:checked + nav{
    left: 0px;
}

<label for="check"><i class="fas fa-bars"></i></label>
<input type="checkbox" id="check">
    <nav>
    <ul><li><a href="">Test</a></li>
        <li><a href="">Test</a></li>
        <li><a href="">Test</a></li>
    </ul>
    </nav>

and if you want to have the same order for the tag change the CSS selector to this:

nav{
    left: -100%;
    position: fixed;
}

#check:checked + label + nav{
    left: 0px;
}

<input type="checkbox" id="check">
<label for="check"><i class="fas fa-bars"></i></label>
<nav>
  <ul>
    <li><a href="">Test</a></li>
    <li><a href="">Test</a></li>
    <li><a href="">Test</a></li>
  </ul>
</nav>


问:
Python not able to save some CLOB xml into xml file
I have this xml saved as CLOB in my oracle database:

```<code><?xml version="1.0" encoding="UTF-8"?>
<DCResponse>
...
</DCResponse>
</code>```

and with this python code I am able to save content into xml file:

```<code>sql = "select extract(xmltype.createxml(xml), '//DCResponse').getStringVal() from table t where id = 2"
for row in cursor.execute(sql):
    print(row[0])
with open("output.xml", "w") as f:
    f.write(row[0])
</code>```

Instead with this xml

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<PIPEDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:XML-PIPE
PIPEDocument.xsd" ReferenceNumber="567862650" CreationDate="20200115155255" Version="1.0"
xmlns="urn:XML-PIPE">
...
</PIPEDocument>
</code>```

I'm not able to extract the content with python. Write() argument must be str, not None.....is result in Python console running this code:

```<code>sql = "select extract(xmltype.createxml(xml), '//PIPEDocument').getStringVal() from table t where id
= 7"
for row in cursor.execute(sql):
    print(row[0])
with open("output.xml", "w") as f:
    f.write(row[0])
</code>```

In my oracle client the output of the below sql query, used in python, is null:

```<code>select extract(xmltype.createxml(xml), '//PIPEDocument').getStringVal() from table t where id = 7;
</code>```

while the xml content is present in my DB:

```<code>select xml from table where id =7
</code>```

Not sure what is the issue, maybe the keyword '//PIPEDocument' in the select query or different encoding between the 2 XML files, but no idea how to fix this.

Please Help
Best Regards
Giancarlo

答:
The problem is that in your second XML document you have namespaces.  The element <PIPEDocument> is in the namespace xmlns="urn:XML-PIPE", and your XPath expression //PIPEDocument' only matches elements <PIPEDocument> in the 'default' namespace.

If you want to use namespaces with the extract function you have to add:

a namespace mapping of a prefix to the namespace URI, using the optional third argument to extract.  This third argument is a string formatted in the same way as xmlns:* attributes in XML documents.  You can't map the default namespace in this way, so xmlns="urn:XML-PIPE" won't work here.  Instead, use a prefix, such as p, or perhaps pipe.

add the prefix to the XPath expression in the second argument to extract.

I made these changes to your code, choosing to use the namespace prefix p.  I also wrapped the entire SQL string in triple-quotes to avoid me having to escape the quotes inside it.  This gave me the following, which returned the desired XML output:

```<code>sql = """select extract(xmltype.createxml(xml), '//p:PIPEDocument', 'xmlns:p="urn:XML-PIPE"').getStringVal() from table t where id = 7"""
for row in cursor.execute(sql):
    print(row[0])
</code>```

Body:
I have this xml saved as CLOB in my oracle database:

<?xml version="1.0" encoding="UTF-8"?>
<DCResponse>
...
</DCResponse>

and with this python code I am able to save content into xml file:

sql = "select extract(xmltype.createxml(xml), '//DCResponse').getStringVal() from table t where id = 2"
for row in cursor.execute(sql):
    print(row[0])
with open("output.xml", "w") as f:
    f.write(row[0])

Instead with this xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<PIPEDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:XML-PIPE
PIPEDocument.xsd" ReferenceNumber="567862650" CreationDate="20200115155255" Version="1.0"
xmlns="urn:XML-PIPE">
...
</PIPEDocument>

I'm not able to extract the content with python. Write() argument must be str, not None.....is result in Python console running this code:

sql = "select extract(xmltype.createxml(xml), '//PIPEDocument').getStringVal() from table t where id
= 7"
for row in cursor.execute(sql):
    print(row[0])
with open("output.xml", "w") as f:
    f.write(row[0])

In my oracle client the output of the below sql query, used in python, is null:

select extract(xmltype.createxml(xml), '//PIPEDocument').getStringVal() from table t where id = 7;

while the xml content is present in my DB:

select xml from table where id =7

Not sure what is the issue, maybe the keyword '//PIPEDocument' in the select query or different encoding between the 2 XML files, but no idea how to fix this.

Please Help
Best Regards
Giancarlo

Body:
The problem is that in your second XML document you have namespaces.  The element <PIPEDocument> is in the namespace xmlns="urn:XML-PIPE", and your XPath expression //PIPEDocument' only matches elements <PIPEDocument> in the 'default' namespace.

If you want to use namespaces with the extract function you have to add:

a namespace mapping of a prefix to the namespace URI, using the optional third argument to extract.  This third argument is a string formatted in the same way as xmlns:* attributes in XML documents.  You can't map the default namespace in this way, so xmlns="urn:XML-PIPE" won't work here.  Instead, use a prefix, such as p, or perhaps pipe.

add the prefix to the XPath expression in the second argument to extract.

I made these changes to your code, choosing to use the namespace prefix p.  I also wrapped the entire SQL string in triple-quotes to avoid me having to escape the quotes inside it.  This gave me the following, which returned the desired XML output:

sql = """select extract(xmltype.createxml(xml), '//p:PIPEDocument', 'xmlns:p="urn:XML-PIPE"').getStringVal() from table t where id = 7"""
for row in cursor.execute(sql):
    print(row[0])


问:
Unable to fetch JSON from Express server using Fetch api
In Express server running on port 8080 I have;

```<code>app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:8081");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
</code>```

Request from port 8081

```<code>fetch('http://localhost:8080/...')
      .then((response) => response.json())
      .then((json) => {
        let jsonStr = JSON.stringify(json);
        console.log(jsonStr)
      })
      .catch((error) => console.log(error))
</code>```

Error I get:

```<code>Access to fetch at 'http://localhost:8080/...' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
</code>```

If I simply manually enter express url on browser I see the JSON I'm trying to fetch.

I have read multiple post to resolve this issue but I still can't seem to be able to resolve it.

How should I fetch to avoid this error?

答:
You're fetching from a different port (8081) and that's why you're getting the CORS error message. Change the Access Control policy as follows:

```<code>  res.header("Access-Control-Allow-Origin", "http://localhost:*");
</code>```

This link can come in handy.

Body:
In Express server running on port 8080 I have;

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:8081");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

Request from port 8081

fetch('http://localhost:8080/...')
      .then((response) => response.json())
      .then((json) => {
        let jsonStr = JSON.stringify(json);
        console.log(jsonStr)
      })
      .catch((error) => console.log(error))

Error I get:

Access to fetch at 'http://localhost:8080/...' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

If I simply manually enter express url on browser I see the JSON I'm trying to fetch.

I have read multiple post to resolve this issue but I still can't seem to be able to resolve it.

How should I fetch to avoid this error?

Body:
You're fetching from a different port (8081) and that's why you're getting the CORS error message. Change the Access Control policy as follows:

  res.header("Access-Control-Allow-Origin", "http://localhost:*");

This link can come in handy.


问:
How to find the length of array within a tuple
I have a tuple of arrays and need to find the length of an array by using the index of the tuple. This tuple is generated from a sparse matrix alternative to numpy where i'm using scipy.sparse.csr_matrix and numpy.unravel_index based on this post

ie:

```<code>>>>T = [(array([0,1,2,3,4,5]),), (array([0,1,2,3,4,5,6,7,8,9]),)]
>>>print(T[1])
(array([0,1,2,3,4,5,6,7,8,9]),)
</code>```

I need to find the length of each array within the tuple for use later. using len() does not work

```<code>>>>len(T[1])
1
</code>```

I am using this within a for loop that iterates through each array using those arrays as an index for other data.

I have searched and searched for how to solve this but found nothing. Please help!

答:
You can try comprehension concept as well,like</p>

```<code>arr_length = [len(i[0]) for i in T]
</code>```

Body:
I have a tuple of arrays and need to find the length of an array by using the index of the tuple. This tuple is generated from a sparse matrix alternative to numpy where i'm using scipy.sparse.csr_matrix and numpy.unravel_index based on this post

ie:

>>>T = [(array([0,1,2,3,4,5]),), (array([0,1,2,3,4,5,6,7,8,9]),)]
>>>print(T[1])
(array([0,1,2,3,4,5,6,7,8,9]),)

I need to find the length of each array within the tuple for use later. using len() does not work

>>>len(T[1])
1

I am using this within a for loop that iterates through each array using those arrays as an index for other data.

I have searched and searched for how to solve this but found nothing. Please help!

Body:
You can try comprehension concept as well,like

arr_length = [len(i[0]) for i in T]


问:
how to use route that is defined in another module
Trying to implement a new module (brought from another of my systems) in an already existing system. Not managing to define the route correctly.
Currently the dashboard routing, for example, is working - I would like the Mycomponent will also be routed.

The MyComponent is defined in MyModule module, not like the all other components which doesn't have their own module.
When I'm clicking on that route path:
path: '/MyComponent', title: 'My component',  icon: '', class: ''
I'm getting the usual:
ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'MyComponent'
Error: Cannot match any routes. URL Segment: 'MyComponent
Lets say that this is my files tree:

```<code>app\app.module.ts
app\app.routing.ts
app\dahshboard\dahshboard.component.ts

app\MyModule\MyModule-routing.module
app\MyModule\MyModule.module.ts
app\MyModule\MyComponent
</code>```

This is the app.module.ts:

```<code>const routes: Routes =[
{
 path: '',
 redirectTo: 'dashboard',
 pathMatch: 'full',
}, {
 path: '',
 component: LayoutComponent,
 children: [{
   path: '',
   loadChildren: './layout.module#LayoutModule'
  }]
 }
];

@NgModule({
 imports: [
  CommonModule,
  BrowserModule,
  RouterModule.forRoot(routes,{
   useHash: true
 })
],...
</code>```

This is the sidebar.component.ts:

```<code>declare interface RouteInfo {
path: string;
title: string;
icon: string;
class: string;
}

export const ROUTES: RouteInfo[] = [

{ path: '/MyComponent', title: 'My component',  icon: '', class: '' },
{ path: '/dashboard', title: 'Dashboard',  icon: 'dashboard', class: '' },
{ path: '/AAA', title: 'AAA',  icon:'AAA', class: '' },
</code>```

This is MyModule.module.ts

```<code>import { MyModuleRoutingModule } from './MyModule-routing.module';
@NgModule({
  declarations: [
    MyComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class MyModule { }
</code>```

This is MyModule-routing.module:

```<code>const routes: Routes = [
{ path: 'MyComponent',  component: MyComponent },
]
@NgModule({
  imports: [RouterModule.forRoot(routes) ],
  exports: [RouterModule]
})
export class MyModuleRoutingModule { }
</code>```

答:
You can add lazy load for myModule ,change your Routes to:
(if you are using angular ver 8 and up it's little bit different check documentation
https://angular.io/guide/lazy-loading-ngmodules)</p>

```<code>const routes: Routes =[
{
 path: '',
 redirectTo: 'dashboard',
 pathMatch: 'full',
}, {
 path: '',
 component: LayoutComponent,
 children: [{
   path: '',
   loadChildren: './layout.module#LayoutModule'
  }]
 },
 {
   path: 'MyComponent',
   loadChildren: './MyModule/mymodule.module#MyModule'
 }

];
</code>```

Body:
Trying to implement a new module (brought from another of my systems) in an already existing system. Not managing to define the route correctly.
Currently the dashboard routing, for example, is working - I would like the Mycomponent will also be routed.

The MyComponent is defined in MyModule module, not like the all other components which doesn't have their own module.
When I'm clicking on that route path:
path: '/MyComponent', title: 'My component',  icon: '', class: ''
I'm getting the usual:
ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'MyComponent'
Error: Cannot match any routes. URL Segment: 'MyComponent
Lets say that this is my files tree:

app\app.module.ts
app\app.routing.ts
app\dahshboard\dahshboard.component.ts

app\MyModule\MyModule-routing.module
app\MyModule\MyModule.module.ts
app\MyModule\MyComponent

This is the app.module.ts:

const routes: Routes =[
{
 path: '',
 redirectTo: 'dashboard',
 pathMatch: 'full',
}, {
 path: '',
 component: LayoutComponent,
 children: [{
   path: '',
   loadChildren: './layout.module#LayoutModule'
  }]
 }
];

@NgModule({
 imports: [
  CommonModule,
  BrowserModule,
  RouterModule.forRoot(routes,{
   useHash: true
 })
],...

This is the sidebar.component.ts:

declare interface RouteInfo {
path: string;
title: string;
icon: string;
class: string;
}

export const ROUTES: RouteInfo[] = [

{ path: '/MyComponent', title: 'My component',  icon: '', class: '' },
{ path: '/dashboard', title: 'Dashboard',  icon: 'dashboard', class: '' },
{ path: '/AAA', title: 'AAA',  icon:'AAA', class: '' },

This is MyModule.module.ts

import { MyModuleRoutingModule } from './MyModule-routing.module';
@NgModule({
  declarations: [
    MyComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class MyModule { }

This is MyModule-routing.module:

const routes: Routes = [
{ path: 'MyComponent',  component: MyComponent },
]
@NgModule({
  imports: [RouterModule.forRoot(routes) ],
  exports: [RouterModule]
})
export class MyModuleRoutingModule { }

Body:
You can add lazy load for myModule ,change your Routes to:
(if you are using angular ver 8 and up it's little bit different check documentation
https://angular.io/guide/lazy-loading-ngmodules)

const routes: Routes =[
{
 path: '',
 redirectTo: 'dashboard',
 pathMatch: 'full',
}, {
 path: '',
 component: LayoutComponent,
 children: [{
   path: '',
   loadChildren: './layout.module#LayoutModule'
  }]
 },
 {
   path: 'MyComponent',
   loadChildren: './MyModule/mymodule.module#MyModule'
 }

];


问:
Implementing Actions on google
What I try to accomplish is let my app be accessible with voice commands on google assistant
I get this error when open App Actions Test tool.
error

actions.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<actions>
    <action intentName="com.example.appname.SHOW_SWITCH_BOARD">
        <fulfillment urlTemplate="https://appname-test-6bc52.firebaseapp.com/{?switchboard}">
            <parameter-mapping
                intentParameter="switchboard.name"
                urlParameter="switchboard" />
        </fulfillment>
    </action>
</actions>
</code>```

答:
It looks like the intentName for your action tag isn't one of the supported built-in Intents.

Currently, you can only use one of the pre-defined Intents to trigger your app. If your app is not in one of the categories that they currently have Intents defined for - you cannot implement App Actions.

Here is an additional video from I/O 2019 discussing App Actions: https://youtu.be/vQALSeGy9aY

Title: Implementing Actions on google

Body:
What I try to accomplish is let my app be accessible with voice commands on google assistant
I get this error when open App Actions Test tool.
error

actions.xml

<?xml version="1.0" encoding="utf-8"?>
<actions>
    <action intentName="com.example.appname.SHOW_SWITCH_BOARD">
        <fulfillment urlTemplate="https://appname-test-6bc52.firebaseapp.com/{?switchboard}">
            <parameter-mapping
                intentParameter="switchboard.name"
                urlParameter="switchboard" />
        </fulfillment>
    </action>
</actions>


问:
How to return an inner type variant reference from an enum without having generics all over the place?
Here are 2 examples that do not compile:

type Common<K, V> = HashMap<K, V>;
type Variant1 = Common<u32, u64>;
type Variant2 = Common<i32, i64>;

enum Stuff {
    V1(Variant1),
    V2(Variant2),
}

impl Stuff {
    fn new(variant1: bool) -> Stuff {
        if variant1 {
            Stuff::V1(Variant1::new())
        } else {
            Stuff::V2(Variant2::new())
        }
    }

    // Example 1
    fn get<K, V>(&self) -> &Common<K, V> {
        match self {
            Stuff::V1(x) => x,
            Stuff::V2(x) => x,
        }
    }

    // Example 2
    fn get_key<K, V>(&self, key: K) -> Option<&V> {
        match self {
            Stuff::V1(x) => x.get(key),
            Stuff::V1(x) => x.get(key),
        }
    }
}
```

<p>playground</p>

<pre class="lang-none prettyprint-override"><code>error[E0308]: mismatched types
  --> src/main.rs:23:29
   |
21 |     fn get<K, V>(&self) -> &Common<K, V> {
   |            - this type parameter
22 |         match self {
23 |             Stuff::V1(x) => x,
   |                             ^ expected type parameter `K`, found `u32`
   |
   = note: expected reference `&std::collections::HashMap<K, V>`
              found reference `&std::collections::HashMap<u32, u64>`
   = help: type parameters must be constrained to match other types
   = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters

error[E0308]: mismatched types
  --> src/main.rs:30:35
   |
28 |     fn get_key<K, V>(&self, key: K) -> &V {
   |                - this type parameter
29 |         match self {
30 |             Stuff::V1(x) => x.get(key),
   |                                   ^^^ expected `&u32`, found type parameter `K`
   |
   = note:   expected reference `&u32`
           found type parameter `K`
   = help: type parameters must be constrained to match other types
   = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters

error[E0308]: mismatched types
  --> src/main.rs:30:29
   |
30 |             Stuff::V1(x) => x.get(key),
   |                             ^^^^^^^^^^ expected `&V`, found enum `std::option::Option`
   |
   = note: expected reference `&V`
                   found enum `std::option::Option<&u64>`

error[E0308]: mismatched types
  --> src/main.rs:31:35
   |
28 |     fn get_key<K, V>(&self, key: K) -> &V {
   |                - this type parameter
...
31 |             Stuff::V1(x) => x.get(key),
   |                                   ^^^ expected `&u32`, found type parameter `K`
   |
   = note:   expected reference `&u32`
           found type parameter `K`
   = help: type parameters must be constrained to match other types
   = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters
</code>```

I would like to have an alternative that would allow me to manipulate (and get things from) the inner type of the variant without having generics all over the place.

As suggested in How can I avoid a ripple effect from changing a concrete struct to generic?, if I can use a Box with a struct instead, it works:

```<code>use std::collections::HashMap;

trait Common<K, V> {
    fn get(&self, key: &K) -> Option<&V>;
}

struct Variant1(HashMap<u32, u64>);
struct Variant2(HashMap<i32, i64>);

impl Common<u32, u64> for Variant1 {
    fn get(&self, key: &u32) -> Option<&u64> {
        self.get(key)
    }
}
impl Common<i32, i64> for Variant2 {
    fn get(&self, key: &i32) -> Option<&i64> {
        self.get(key)
    }
}

struct Stuff<K, V>(Box<dyn Common<K, V>>);

impl<K, V> Stuff<K, V> {
    fn new(variant1: bool) -> Stuff<K, V> {
        if variant1 {
            Stuff(Box::new(Variant1(HashMap::new())))
        } else {
            Stuff(Box::new(Variant2(HashMap::new())))
        }
    }
}

impl<K, V> Common<K, V> for Stuff<K, V> {
    fn get(&self, key: &K) -> Option<&V> {
        self.0.get(key)
    }
}

fn main() {
    let stuff1 = Stuff::new(true);
    let r1 = stuff1.get(&42);
    let stuff2 = Stuff::new(true);
    let r2 = stuff2.get(&42);
}
</code>```

playground

However, because this is no longer an enum, I cannot create the variant under one enum/struct anymore (the code above doesn't compile).

On one hand, I want to be able to create one single struct/enum that holds multiple complicated types (enum), but on the other hand I want to be able to get/access to the underlying object. I can't find a way to do both things.

答:
HashMap<u32, u64> != HashMap<i32, i64>

I know the key and value types are the same size, so the in memory representation will be similar, but rust won't let you cast back and fourth between the two types without using unsafe.

The following example does not use unsafe.

You should note that the examples in this thread are not logically sound because casting between signed and unsigned integers yields incorrect results.

use std::collections::HashMap;

struct Stuff {
    map: HashMap<[u8; 4], [u8; 8]>,
}

impl Stuff {
    fn new() -> Stuff {
        Stuff {
            map: HashMap::new(),
        }
    }

    fn get_u32_u64(&self, key: u32) -> Option<u64> {
        self.map
            .get(&key.to_ne_bytes())
            .cloned()
            .map(u64::from_ne_bytes)
    }

    fn get_i32_u64(&self, key: i32) -> Option<u64> {
        self.map
            .get(&key.to_ne_bytes())
            .cloned()
            .map(u64::from_ne_bytes)
    }

    fn get_u32_i64(&self, key: u32) -> Option<i64> {
        self.map
            .get(&key.to_ne_bytes())
            .cloned()
            .map(i64::from_ne_bytes)
    }

    fn get_i32_i64(&self, key: i32) -> Option<i64> {
        self.map
            .get(&key.to_ne_bytes())
            .cloned()
            .map(i64::from_ne_bytes)
    }
}
```

<p>Here is another alternative using traits.</p>

<pre class="lang-rust prettyprint-override"><code>use std::collections::HashMap;

struct Stuff {
    map: HashMap<[u8; 4], [u8; 8]>,
}

trait StuffKey {
    fn key(self) -> [u8; 4];
}

trait StuffValue {
    fn val(val: [u8; 8]) -> Self;
}

impl Stuff {
    fn new() -> Stuff {
        Stuff {
            map: HashMap::new(),
        }
    }

    fn get<K: StuffKey, V: StuffValue>(&self, key: K) -> Option<V> {
        self.map.get(&key.key()).cloned().map(StuffValue::val)
    }
}

impl StuffKey for i32 {
    fn key(self) -> [u8; 4] {
        self.to_ne_bytes()
    }
}

impl StuffKey for u32 {
    fn key(self) -> [u8; 4] {
        self.to_ne_bytes()
    }
}

impl StuffValue for i64 {
    fn val(val: [u8; 8]) -> Self {
        Self::from_ne_bytes(val)
    }
}

impl StuffValue for u64 {
    fn val(val: [u8; 8]) -> Self {
        Self::from_ne_bytes(val)
    }
}
</code>```

Body:
Here are 2 examples that do not compile:

type Common<K, V> = HashMap<K, V>;
type Variant1 = Common<u32, u64>;
type Variant2 = Common<i32, i64>;

enum Stuff {
    V1(Variant1),
    V2(Variant2),
}

impl Stuff {
    fn new(variant1: bool) -> Stuff {
        if variant1 {
            Stuff::V1(Variant1::new())
        } else {
            Stuff::V2(Variant2::new())
        }
    }

    // Example 1
    fn get<K, V>(&self) -> &Common<K, V> {
        match self {
            Stuff::V1(x) => x,
            Stuff::V2(x) => x,
        }
    }

    // Example 2
    fn get_key<K, V>(&self, key: K) -> Option<&V> {
        match self {
            Stuff::V1(x) => x.get(key),
            Stuff::V1(x) => x.get(key),
        }
    }
}

playground

error[E0308]: mismatched types
  --> src/main.rs:23:29
   |
21 |     fn get<K, V>(&self) -> &Common<K, V> {
   |            - this type parameter
22 |         match self {
23 |             Stuff::V1(x) => x,
   |                             ^ expected type parameter `K`, found `u32`
   |
   = note: expected reference `&std::collections::HashMap<K, V>`
              found reference `&std::collections::HashMap<u32, u64>`
   = help: type parameters must be constrained to match other types
   = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters

error[E0308]: mismatched types
  --> src/main.rs:30:35
   |
28 |     fn get_key<K, V>(&self, key: K) -> &V {
   |                - this type parameter
29 |         match self {
30 |             Stuff::V1(x) => x.get(key),
   |                                   ^^^ expected `&u32`, found type parameter `K`
   |
   = note:   expected reference `&u32`
           found type parameter `K`
   = help: type parameters must be constrained to match other types
   = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters

error[E0308]: mismatched types
  --> src/main.rs:30:29
   |
30 |             Stuff::V1(x) => x.get(key),
   |                             ^^^^^^^^^^ expected `&V`, found enum `std::option::Option`
   |
   = note: expected reference `&V`
                   found enum `std::option::Option<&u64>`

error[E0308]: mismatched types
  --> src/main.rs:31:35
   |
28 |     fn get_key<K, V>(&self, key: K) -> &V {
   |                - this type parameter
...
31 |             Stuff::V1(x) => x.get(key),
   |                                   ^^^ expected `&u32`, found type parameter `K`
   |
   = note:   expected reference `&u32`
           found type parameter `K`
   = help: type parameters must be constrained to match other types
   = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters

I would like to have an alternative that would allow me to manipulate (and get things from) the inner type of the variant without having generics all over the place.

As suggested in How can I avoid a ripple effect from changing a concrete struct to generic?, if I can use a Box with a struct instead, it works:

use std::collections::HashMap;

trait Common<K, V> {
    fn get(&self, key: &K) -> Option<&V>;
}

struct Variant1(HashMap<u32, u64>);
struct Variant2(HashMap<i32, i64>);

impl Common<u32, u64> for Variant1 {
    fn get(&self, key: &u32) -> Option<&u64> {
        self.get(key)
    }
}
impl Common<i32, i64> for Variant2 {
    fn get(&self, key: &i32) -> Option<&i64> {
        self.get(key)
    }
}

struct Stuff<K, V>(Box<dyn Common<K, V>>);

impl<K, V> Stuff<K, V> {
    fn new(variant1: bool) -> Stuff<K, V> {
        if variant1 {
            Stuff(Box::new(Variant1(HashMap::new())))
        } else {
            Stuff(Box::new(Variant2(HashMap::new())))
        }
    }
}

impl<K, V> Common<K, V> for Stuff<K, V> {
    fn get(&self, key: &K) -> Option<&V> {
        self.0.get(key)
    }
}

fn main() {
    let stuff1 = Stuff::new(true);
    let r1 = stuff1.get(&42);
    let stuff2 = Stuff::new(true);
    let r2 = stuff2.get(&42);
}

playground

However, because this is no longer an enum, I cannot create the variant under one enum/struct anymore (the code above doesn't compile).

On one hand, I want to be able to create one single struct/enum that holds multiple complicated types (enum), but on the other hand I want to be able to get/access to the underlying object. I can't find a way to do both things.

Body:
HashMap<u32, u64> != HashMap<i32, i64>

I know the key and value types are the same size, so the in memory representation will be similar, but rust won't let you cast back and fourth between the two types without using unsafe.

The following example does not use unsafe.

You should note that the examples in this thread are not logically sound because casting between signed and unsigned integers yields incorrect results.

use std::collections::HashMap;

struct Stuff {
    map: HashMap<[u8; 4], [u8; 8]>,
}

impl Stuff {
    fn new() -> Stuff {
        Stuff {
            map: HashMap::new(),
        }
    }

    fn get_u32_u64(&self, key: u32) -> Option<u64> {
        self.map
            .get(&key.to_ne_bytes())
            .cloned()
            .map(u64::from_ne_bytes)
    }

    fn get_i32_u64(&self, key: i32) -> Option<u64> {
        self.map
            .get(&key.to_ne_bytes())
            .cloned()
            .map(u64::from_ne_bytes)
    }

    fn get_u32_i64(&self, key: u32) -> Option<i64> {
        self.map
            .get(&key.to_ne_bytes())
            .cloned()
            .map(i64::from_ne_bytes)
    }

    fn get_i32_i64(&self, key: i32) -> Option<i64> {
        self.map
            .get(&key.to_ne_bytes())
            .cloned()
            .map(i64::from_ne_bytes)
    }
}

Here is another alternative using traits.

use std::collections::HashMap;

struct Stuff {
    map: HashMap<[u8; 4], [u8; 8]>,
}

trait StuffKey {
    fn key(self) -> [u8; 4];
}

trait StuffValue {
    fn val(val: [u8; 8]) -> Self;
}

impl Stuff {
    fn new() -> Stuff {
        Stuff {
            map: HashMap::new(),
        }
    }

    fn get<K: StuffKey, V: StuffValue>(&self, key: K) -> Option<V> {
        self.map.get(&key.key()).cloned().map(StuffValue::val)
    }
}

impl StuffKey for i32 {
    fn key(self) -> [u8; 4] {
        self.to_ne_bytes()
    }
}

impl StuffKey for u32 {
    fn key(self) -> [u8; 4] {
        self.to_ne_bytes()
    }
}

impl StuffValue for i64 {
    fn val(val: [u8; 8]) -> Self {
        Self::from_ne_bytes(val)
    }
}

impl StuffValue for u64 {
    fn val(val: [u8; 8]) -> Self {
        Self::from_ne_bytes(val)
    }
}


问:
Powershell: how to split, do math and format
I am looking for a 1-liner that looks something like this:

(gitversion | ConvertFrom-Json).SemVer.split('.') | [string]::Format("{0}.{1}.{2}",$_[0],$_[1] + 1,$_[2]) | git tag $_
```

So, right now I have 0.1.0 and I want a 1 liner that will map it to:
0.2.0

I am sure a guru in PS can make fast work of this

答:
You can read in the entire json, use the Major, Minor and Patch number of the version and update whichever one you are interested in... patch, minor or major.

I am using foreach-object to access all the properties of the json even though there is only one available. 1-liner:

```<code>gitversion | ConvertFrom-Json | % { "$($_.Major).$($_.Minor + 1).$($_.Patch)" } | % { git tag $_ }
</code>```

How can % / ForEach-Object work with multiple repositories

If there is only one repository at the path you are running gitversion, it will always give you one object. (gitversion fails with errors when you run this in directory that doesnt have a git repository.)

I would like to stress that this would work great in your scenario where there is only Major, Minor and Patch version. In cases where the SemVersion is like, "SemVer":"0.1.0", this is fine. But, if your interest is to keep the PreReleaseTag as well in your next version (and not drop the alpha / beta etc tags), you can include the PreReleaseTagWithDash to your output as well. e.g of pre-release tags: "SemVer":"0.1.0-alpha.915"

```<code>gitversion | ConvertFrom-Json | % { "$($_.Major).$($_.Minor + 1).$($_.Patch)$($_.PreReleaseTagWithDash)" } | % { git tag $_ }
</code>```

Sample JSONs of gitversion

From dev or other branches, you can expect variations in semVer that includes pre-release tags.

```<code>{
  "Major":0,
  "Minor":1,
  "Patch":0,
  "PreReleaseTag":"alpha.915",
  "PreReleaseTagWithDash":"-alpha.915",
  "PreReleaseLabel":"alpha",
  "PreReleaseNumber":915,
  "WeightedPreReleaseNumber":915,
  "BuildMetaData":"",
  "BuildMetaDataPadded":"",
  "FullBuildMetaData":"Branch.dev.Sha.888xxx.xxx888",
  "MajorMinorPatch":"0.1.0",
  "SemVer":"0.1.0-alpha.915",
  "LegacySemVer":"0.1.0-alpha915",
  "LegacySemVerPadded":"0.1.0-alpha0915",
  "AssemblySemVer":"0.1.0.0",
  "AssemblySemFileVer":"0.1.0.0",
  "FullSemVer":"0.1.0-alpha.915",
  "InformationalVersion":"0.1.0-alpha.915+Branch.dev.Sha.888xx.xx888",
  "BranchName":"dev",
  "Sha":"888xx.xx888",
  "ShortSha":"7a1152f",
  "NuGetVersionV2":"0.1.0-alpha0915",
  "NuGetVersion":"0.1.0-alpha0915",
  "NuGetPreReleaseTagV2":"alpha0915",
  "NuGetPreReleaseTag":"alpha0915",
  "VersionSourceSha":"88xxx.xx88",
  "CommitsSinceVersionSource":915,
  "CommitsSinceVersionSourcePadded":"0915",
  "CommitDate":"2019-12-06"
}
</code>```

From master branch, you would normally expect a semver = major.minor.patch.

```<code>{
  "Major":0,
  "Minor":1,
  "Patch":0,
  "PreReleaseTag":"",
  "PreReleaseTagWithDash":"",
  "PreReleaseLabel":"",
  "PreReleaseNumber":"",
  "WeightedPreReleaseNumber":"",
  "BuildMetaData":0,
  "BuildMetaDataPadded":"0000",
  "FullBuildMetaData":"0.Branch.master.Sha.9999xxx....xxx999",
  "MajorMinorPatch":"0.1.0",
  "SemVer":"0.1.0",
  "LegacySemVer":"0.1.0",
  "LegacySemVerPadded":"0.1.0",
  "AssemblySemVer":"0.1.0.0",
  "AssemblySemFileVer":"0.1.0.0",
  "FullSemVer":"0.1.0+0",
  "InformationalVersion":"0.1.0+0.Branch.master.Sha.999xxx...xxx999",
  "BranchName":"master",
  "Sha":"86b0be929a84ba7e9b2a463e7dbdc9a3c9325dc1",
  "ShortSha":"86b0be9",
  "NuGetVersionV2":"0.1.0",
  "NuGetVersion":"0.1.0",
  "NuGetPreReleaseTagV2":"",
  "NuGetPreReleaseTag":"",
  "VersionSourceSha":"999xxx...xxx999",
  "CommitsSinceVersionSource":0,
  "CommitsSinceVersionSourcePadded":"0000",
  "CommitDate":"2018-02-18"
}
</code>```

NOTE: I have not tested this with multiple git repositories in one location. This solution will work if there is only repository at the path you are running.

Body:
I am looking for a 1-liner that looks something like this:

(gitversion | ConvertFrom-Json).SemVer.split('.') | [string]::Format("{0}.{1}.{2}",$_[0],$_[1] + 1,$_[2]) | git tag $_

So, right now I have 0.1.0 and I want a 1 liner that will map it to:
0.2.0

I am sure a guru in PS can make fast work of this

Body:
You can read in the entire json, use the Major, Minor and Patch number of the version and update whichever one you are interested in... patch, minor or major.

I am using foreach-object to access all the properties of the json even though there is only one available. 1-liner:

gitversion | ConvertFrom-Json | % { "$($_.Major).$($_.Minor + 1).$($_.Patch)" } | % { git tag $_ }

How can % / ForEach-Object work with multiple repositories

If there is only one repository at the path you are running gitversion, it will always give you one object. (gitversion fails with errors when you run this in directory that doesnt have a git repository.)

I would like to stress that this would work great in your scenario where there is only Major, Minor and Patch version. In cases where the SemVersion is like, "SemVer":"0.1.0", this is fine. But, if your interest is to keep the PreReleaseTag as well in your next version (and not drop the alpha / beta etc tags), you can include the PreReleaseTagWithDash to your output as well. e.g of pre-release tags: "SemVer":"0.1.0-alpha.915"

gitversion | ConvertFrom-Json | % { "$($_.Major).$($_.Minor + 1).$($_.Patch)$($_.PreReleaseTagWithDash)" } | % { git tag $_ }

Sample JSONs of gitversion

From dev or other branches, you can expect variations in semVer that includes pre-release tags.

{
  "Major":0,
  "Minor":1,
  "Patch":0,
  "PreReleaseTag":"alpha.915",
  "PreReleaseTagWithDash":"-alpha.915",
  "PreReleaseLabel":"alpha",
  "PreReleaseNumber":915,
  "WeightedPreReleaseNumber":915,
  "BuildMetaData":"",
  "BuildMetaDataPadded":"",
  "FullBuildMetaData":"Branch.dev.Sha.888xxx.xxx888",
  "MajorMinorPatch":"0.1.0",
  "SemVer":"0.1.0-alpha.915",
  "LegacySemVer":"0.1.0-alpha915",
  "LegacySemVerPadded":"0.1.0-alpha0915",
  "AssemblySemVer":"0.1.0.0",
  "AssemblySemFileVer":"0.1.0.0",
  "FullSemVer":"0.1.0-alpha.915",
  "InformationalVersion":"0.1.0-alpha.915+Branch.dev.Sha.888xx.xx888",
  "BranchName":"dev",
  "Sha":"888xx.xx888",
  "ShortSha":"7a1152f",
  "NuGetVersionV2":"0.1.0-alpha0915",
  "NuGetVersion":"0.1.0-alpha0915",
  "NuGetPreReleaseTagV2":"alpha0915",
  "NuGetPreReleaseTag":"alpha0915",
  "VersionSourceSha":"88xxx.xx88",
  "CommitsSinceVersionSource":915,
  "CommitsSinceVersionSourcePadded":"0915",
  "CommitDate":"2019-12-06"
}

From master branch, you would normally expect a semver = major.minor.patch.

{
  "Major":0,
  "Minor":1,
  "Patch":0,
  "PreReleaseTag":"",
  "PreReleaseTagWithDash":"",
  "PreReleaseLabel":"",
  "PreReleaseNumber":"",
  "WeightedPreReleaseNumber":"",
  "BuildMetaData":0,
  "BuildMetaDataPadded":"0000",
  "FullBuildMetaData":"0.Branch.master.Sha.9999xxx....xxx999",
  "MajorMinorPatch":"0.1.0",
  "SemVer":"0.1.0",
  "LegacySemVer":"0.1.0",
  "LegacySemVerPadded":"0.1.0",
  "AssemblySemVer":"0.1.0.0",
  "AssemblySemFileVer":"0.1.0.0",
  "FullSemVer":"0.1.0+0",
  "InformationalVersion":"0.1.0+0.Branch.master.Sha.999xxx...xxx999",
  "BranchName":"master",
  "Sha":"86b0be929a84ba7e9b2a463e7dbdc9a3c9325dc1",
  "ShortSha":"86b0be9",
  "NuGetVersionV2":"0.1.0",
  "NuGetVersion":"0.1.0",
  "NuGetPreReleaseTagV2":"",
  "NuGetPreReleaseTag":"",
  "VersionSourceSha":"999xxx...xxx999",
  "CommitsSinceVersionSource":0,
  "CommitsSinceVersionSourcePadded":"0000",
  "CommitDate":"2018-02-18"
}

NOTE: I have not tested this with multiple git repositories in one location. This solution will work if there is only repository at the path you are running.


问:
Is the onwheel event triggered by a trackpad scroll
Although it's a basic question, I haven't been able to find an answer. However, since it's such a basic question, not much of an explanation can be provided. Unfortunately, I do not have a laptop that I can use to test this.

```<code>ele.onwheel = function(e) {

}
</code>```

Is the onwheel event triggered by "scrolling" a laptop's trackpad?

答: Yes, it does. Even deltaY is available, but it's value depends on current trackpad or mouse.

Body:
Although it's a basic question, I haven't been able to find an answer. However, since it's such a basic question, not much of an explanation can be provided. Unfortunately, I do not have a laptop that I can use to test this.

ele.onwheel = function(e) {

}

Is the onwheel event triggered by "scrolling" a laptop's trackpad?


问:
Zenject inject plain class into Monobehaviour
I'm trying to inject plain C# class into Mobobehaviour, but an "Unable to resolve 'HeightSystem' while building object with type 'UserDirijible'. Object graph: UserDirijible" exception is thrown.

```<code>namespace Systems {
    public class HeightSystem
    {
...
}
</code>```

```<code>using Zenject;

namespace Systems {
    public class HeightSystemInstaller : MonoInstaller<HeightSystemInstaller>
{
    public override void InstallBindings()
    {
        Container.BindInstance<HeightSystem>(new HeightSystem()).AsSingle();
    }
}
}
</code>```

```<code>//UserDirijible.cs
[Inject]
public Systems.HeightSystem heightSystem;
</code>```

HeightSystemInstaller is attached to empty object in scene. What is may cause this error? Previously, Monobehaviour classes injection was work fine. I was mostly working with Dagger 2 and till now can not find the piece of documentation about injection plain C# classes into Monobehaviours

答: Injected object was not attached to Scene context</p>

Body:
I'm trying to inject plain C# class into Mobobehaviour, but an "Unable to resolve 'HeightSystem' while building object with type 'UserDirijible'. Object graph: UserDirijible" exception is thrown.

namespace Systems {
    public class HeightSystem
    {
...
}

using Zenject;

namespace Systems {
    public class HeightSystemInstaller : MonoInstaller<HeightSystemInstaller>
{
    public override void InstallBindings()
    {
        Container.BindInstance<HeightSystem>(new HeightSystem()).AsSingle();
    }
}
}

//UserDirijible.cs
[Inject]
public Systems.HeightSystem heightSystem;

HeightSystemInstaller is attached to empty object in scene. What is may cause this error? Previously, Monobehaviour classes injection was work fine. I was mostly working with Dagger 2 and till now can not find the piece of documentation about injection plain C# classes into Monobehaviours


问:
Why is this program returning the last word and not the longest word?
Why is this program returning garbage values? I expect the output to be the word 'large', but the value is actually 'rat' - the last word.

#include <iostream>
#include <string>
using namespace std;

std::string LongestWord(std::string sen)
{

    std::string s2, lW;
    for (int i = 0; i < sen.size(); ++i) {

        while (sen[i] != ' ') {
            s2 += sen[i];
            ++i;
        }
        if (s2.size() > lW.size()) {
            lW = ""; lW = s2;
        }

        s2 = "";
    }
    return lW;
}
int main(void)
{

    cout << LongestWord("a cat ate the large rat") << endl;
    return 0;

}
```

答:
Your internal while loop will almost certainly run beyond the end of the given string argument (unless it has a space at the end). Change this internal loop to check for the size of that string, as follows:

        while (i < sen.size() && sen[i] != ' ') {
            s2 += sen[i];
            ++i;
        }
```


问:
What's the preferred method in the community for having python 2.x and 3.x in the same codebase?
I am starting a project in Python 3.x, (I'm quite new to Python) and there exists the possibility that I will need to use say Thrift or any other library that is not yet ported to Python 3.x.

I don't mind about devoting some (substantial) amount of time to convert an external library to Python 3.x if with that others can benefit from that, but I'm curious if there's any preferred way in the Open Source community to deal with this problem.

I have been reading here and there in the python.org site and in some other websites, but I haven't found anything conclusive.  The only thing that I found is that this is a chicken-and-egg problem.

It's out of the question (unless there's no other option) that I ship a dump of a library with my own modifications just to make it 3.x compliant.

Should I...

prepare all the code with __future imports and change here and there appropriately and leave it ready to work with both 2.x and 3.x?  Am I going to find any problem with this, other than the natural resistance of upstream to integrate such amount of changes?

create another branch of the code?  That, to me, should be quite useless, as nobody will maintain that branch except me, probably, and it's a huge duplication effort.

use some type of wrapper that I am not aware of to use those libraries as-is (like using some intermediate bindings in another language) and just create the glue in my code?

Many thanks!

答: I suggest supporting Python 2.x and Python 3.x simultaneously from the same code base, using tox. Check out the Supporting All Versions of Python All The Time With Tox  talk from Pycon 2011.</p>

ContentLicense: CC BY-SA 3.0


问:
Regex: Duration (hours, minutes) in dart
I'm trying to sort a list of data using RegEx. Currently, the code below only checks for hours and minutes.

Example of the output currently:

1:22:00.000000

But I have some data that will also have just minutes  or just hours.

I'm looking to edit this code so it will check for all those possibilities:

Hours

Minutes

Hours and Minutes

```<code>final _regExp = RegExp(r'(?<hours>\d+)h (?<minutes>\d+)m');
Duration _parseDuration(String line) {
  final match = _regExp.firstMatch(line);

  if (match == null) {
    throw Exception('Could not get duration from: $line');
  }

  return Duration(
      hours: int.parse(match.namedGroup('hours')),
      minutes: int.parse(match.namedGroup('minutes')));
}
</code>```

I'm not sure how to do this?

Any help would be appreciated.

答:
I guess this would work. I just added so each group is optional and if any group is not in the input, then use the value 0:</p>

```<code>void main() {
  print(_parseDuration('5h'));      // 5:00:00.000000
  print(_parseDuration('5m'));      // 0:05:00.000000
  print(_parseDuration('10h 50m')); // 10:50:00.000000
}

final _regExp = RegExp(r'((?<hours>\d+)h)?[ ]*((?<minutes>\d+)m)?');
Duration _parseDuration(String line) {
  final match = _regExp.firstMatch(line);

  if (match == null) {
    throw Exception('Could not get duration from: $line');
  }

  return Duration(
      hours: int.parse(match.namedGroup('hours') ?? '0'),
      minutes: int.parse(match.namedGroup('minutes') ?? '0'));
}
</code>```

Body:
I'm trying to sort a list of data using RegEx. Currently, the code below only checks for hours and minutes.

Example of the output currently:

1:22:00.000000

But I have some data that will also have just minutes  or just hours.

I'm looking to edit this code so it will check for all those possibilities:

Hours

Minutes

Hours and Minutes

final _regExp = RegExp(r'(?<hours>\d+)h (?<minutes>\d+)m');
Duration _parseDuration(String line) {
  final match = _regExp.firstMatch(line);

  if (match == null) {
    throw Exception('Could not get duration from: $line');
  }

  return Duration(
      hours: int.parse(match.namedGroup('hours')),
      minutes: int.parse(match.namedGroup('minutes')));
}

I'm not sure how to do this?

Any help would be appreciated.

Body:
I guess this would work. I just added so each group is optional and if any group is not in the input, then use the value 0:

void main() {
  print(_parseDuration('5h'));      // 5:00:00.000000
  print(_parseDuration('5m'));      // 0:05:00.000000
  print(_parseDuration('10h 50m')); // 10:50:00.000000
}

final _regExp = RegExp(r'((?<hours>\d+)h)?[ ]*((?<minutes>\d+)m)?');
Duration _parseDuration(String line) {
  final match = _regExp.firstMatch(line);

  if (match == null) {
    throw Exception('Could not get duration from: $line');
  }

  return Duration(
      hours: int.parse(match.namedGroup('hours') ?? '0'),
      minutes: int.parse(match.namedGroup('minutes') ?? '0'));
}


问:
Register Spring Converter Programmatically in Spring Boot
I want to register a Spring Converter in a Spring Boot project programmatically. In past Spring projects I've done it in XML like this...

```<code><!-- Custom converters to allow automatic binding from Http requests parameters to objects -->
<!-- All converters are annotated w/@Component -->
<bean id="conversionService"
      class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <ref bean="stringToAssessmentConverter" />
        </list>
    </property>
</bean>
</code>```

I'm trying to figure out how to do in Spring Boot's SpringBootServletInitializer

Update: I've made a little progress by passing the StringToAssessmentConverter as an argument to getConversionService, but now I'm getting a "No default constructor found" error for the StringToAssessmentConverter class. I'm not sure why Spring is not seeing the @Autowired constructor.

```<code>@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    ...

    @Bean(name="conversionService")
    public ConversionServiceFactoryBean getConversionService(StringToAssessmentConverter stringToAssessmentConverter) {
        ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();

        Set<Converter> converters = new HashSet<>();

        converters.add(stringToAssessmentConverter);

        bean.setConverters(converters);
        return bean;
    }
}
</code>```

Here's the code for the Converter...

```<code> @Component
 public class StringToAssessmentConverter implements Converter<String, Assessment> {

     private AssessmentService assessmentService;

     @Autowired
     public StringToAssessmentConverter(AssessmentService assessmentService) {
         this.assessmentService = assessmentService;
     }

     public Assessment convert(String source) {
         Long id = Long.valueOf(source);
         try {
             return assessmentService.find(id);
         } catch (SecurityException ex) {
             return null;
         }
     }
 }
</code>```

Full Error

```<code>Failed to execute goal org.springframework.boot:spring-boot-maven-
plugin:1.3.2.RELEASE:run (default-cli) on project yrdstick: An exception
occurred while running. null: InvocationTargetException: Error creating
bean with name
'org.springframework.boot.context.properties.ConfigurationPropertiesBindingPo
stProcessor': Invocation of init method failed; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'conversionService' defined in
me.jpolete.yrdstick.Application: Unsatisfied dependency expressed through
constructor argument with index 0 of type
[me.jpolete.yrdstick.websupport.StringToAssessmentConverter]: : Error
creating bean with name 'stringToAssessmentConverter' defined in file
[/yrdstick/target/classes/me/jpolete/yrdstick/websupport
/StringToAssessmentConverter.class]: Instantiation of bean failed; nested
exception is org.springframework.beans.BeanInstantiationException: Failed
to instantiate
[me.jpolete.yrdstick.websupport.StringToAssessmentConverter]: No default
constructor found; nested exception is java.lang.NoSuchMethodException:
me.jpolete.yrdstick.websupport.StringToAssessmentConverter.<init>();
nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'stringToAssessmentConverter' defined in file [/yrdstick
/dev/yrdstick/target/classes/me/jpolete/yrdstick/websupport
/StringToAssessmentConverter.class]: Instantiation of bean failed; nested
exception is org.springframework.beans.BeanInstantiationException: Failed
to instantiate
[me.jpolete.yrdstick.websupport.StringToAssessmentConverter]: No default
constructor found; nested exception is java.lang.NoSuchMethodException:
me.jpolete.yrdstick.websupport.StringToAssessmentConverter.<init>()
</code>```

答:
**If you are not on Spring Boot, where automatic registration of converters annotated with @Component (and similar stereotype annotations) is performed and you are not in Web Mvc environment :

```<code>@Bean
ConversionService conversionService(){
    ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean();
    Set<Converter<?, ?>> convSet = new HashSet<Converter<?, ?>>();
    convSet.add(new MyConverter()); // or reference bean convSet.add(myConverter());
    factory.setConverters(convSet);
    factory.afterPropertiesSet();
    return factory.getObject();
}
</code>```

Body:
I want to register a Spring Converter in a Spring Boot project programmatically. In past Spring projects I've done it in XML like this...

<bean id="conversionService"
      class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <ref bean="stringToAssessmentConverter" />
        </list>
    </property>
</bean>

I'm trying to figure out how to do in Spring Boot's SpringBootServletInitializer

Update: I've made a little progress by passing the StringToAssessmentConverter as an argument to getConversionService, but now I'm getting a "No default constructor found" error for the StringToAssessmentConverter class. I'm not sure why Spring is not seeing the @Autowired constructor.

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    ...

    @Bean(name="conversionService")
    public ConversionServiceFactoryBean getConversionService(StringToAssessmentConverter stringToAssessmentConverter) {
        ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();

        Set<Converter> converters = new HashSet<>();

        converters.add(stringToAssessmentConverter);

        bean.setConverters(converters);
        return bean;
    }
}

Here's the code for the Converter...

 @Component
 public class StringToAssessmentConverter implements Converter<String, Assessment> {

     private AssessmentService assessmentService;

     @Autowired
     public StringToAssessmentConverter(AssessmentService assessmentService) {
         this.assessmentService = assessmentService;
     }

     public Assessment convert(String source) {
         Long id = Long.valueOf(source);
         try {
             return assessmentService.find(id);
         } catch (SecurityException ex) {
             return null;
         }
     }
 }

Full Error

Failed to execute goal org.springframework.boot:spring-boot-maven-
plugin:1.3.2.RELEASE:run (default-cli) on project yrdstick: An exception
occurred while running. null: InvocationTargetException: Error creating
bean with name
'org.springframework.boot.context.properties.ConfigurationPropertiesBindingPo
stProcessor': Invocation of init method failed; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'conversionService' defined in
me.jpolete.yrdstick.Application: Unsatisfied dependency expressed through
constructor argument with index 0 of type
[me.jpolete.yrdstick.websupport.StringToAssessmentConverter]: : Error
creating bean with name 'stringToAssessmentConverter' defined in file
[/yrdstick/target/classes/me/jpolete/yrdstick/websupport
/StringToAssessmentConverter.class]: Instantiation of bean failed; nested
exception is org.springframework.beans.BeanInstantiationException: Failed
to instantiate
[me.jpolete.yrdstick.websupport.StringToAssessmentConverter]: No default
constructor found; nested exception is java.lang.NoSuchMethodException:
me.jpolete.yrdstick.websupport.StringToAssessmentConverter.<init>();
nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'stringToAssessmentConverter' defined in file [/yrdstick
/dev/yrdstick/target/classes/me/jpolete/yrdstick/websupport
/StringToAssessmentConverter.class]: Instantiation of bean failed; nested
exception is org.springframework.beans.BeanInstantiationException: Failed
to instantiate
[me.jpolete.yrdstick.websupport.StringToAssessmentConverter]: No default
constructor found; nested exception is java.lang.NoSuchMethodException:
me.jpolete.yrdstick.websupport.StringToAssessmentConverter.<init>()

Body:
**If you are not on Spring Boot, where automatic registration of converters annotated with @Component (and similar stereotype annotations) is performed and you are not in Web Mvc environment :

@Bean
ConversionService conversionService(){
    ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean();
    Set<Converter<?, ?>> convSet = new HashSet<Converter<?, ?>>();
    convSet.add(new MyConverter()); // or reference bean convSet.add(myConverter());
    factory.setConverters(convSet);
    factory.afterPropertiesSet();
    return factory.getObject();
}


问:
Is it optimal to connect to Openshift through its REST services or through a CLI script?
I've been writing an Openshift client in Java and wanted to find out if the CLIs internally call the REST services in which case, I can try to use the REST services directly. I'm using Openshift 3.1

I'm connecting to openshift the following way by creating a factory which refers the .conf file. I'm creating the connection from a connection factory. I wanted to know if CLI is optimal or is it a Java client that is.

```<code>final OpenShiftConnectionFactory connectionFactory = new OpenShiftConnectionFactory();

IOpenShiftConnection connection2 = new OpenShiftConnectionFactory()
      .getConnection("domain", "user", "password");
</code>```

PS: If anyone has written any other Openshift client or has an example , if you can give me a short overview on your approach, that's great too.

答:
openshift-java-client is a useful tool to make java openshift client and can save a couple of days. Definitely it's optimal in terms of LOE and rewrite all that stuff unnecessarily. However, make attantion that Openshift CLI wrote on GO, so openshift's CLI should be more optimal in terms of resources usage, but inside it's basically REST client.

In summary, if you prefer java and If you're making CLI (not front-end) and not have high NFRs, I suggest to stay on java and openshift-java-client.

Body:
I've been writing an Openshift client in Java and wanted to find out if the CLIs internally call the REST services in which case, I can try to use the REST services directly. I'm using Openshift 3.1

I'm connecting to openshift the following way by creating a factory which refers the .conf file. I'm creating the connection from a connection factory. I wanted to know if CLI is optimal or is it a Java client that is.

final OpenShiftConnectionFactory connectionFactory = new OpenShiftConnectionFactory();

IOpenShiftConnection connection2 = new OpenShiftConnectionFactory()
      .getConnection("domain", "user", "password");

PS: If anyone has written any other Openshift client or has an example , if you can give me a short overview on your approach, that's great too.


问:
Entity Framework Core: Update() method INSERTs instead of UPDATEs on dependent entity
It seems like EF Core is doing an INSERT instead of an UPDATE, and thus MySQL complains about a duplicate key. However, I am using the Update method on the DbSet and the entities do have primary keys set. This results in a DUPLICATE ENTRY error in MySql.

Running VS 2019, EF Core 3.1.1 and ASP.NET Core 3.1

Model (I do not use Fluent config for relationships, just Convention):

```<code>public class Vehicle
{
    public long Id {get; set; } // PRIMARY KEY, AUTO INCREMENT
    public string RegistrationNumber { get; set; }
    public VehicleSession Session { get; set; }
}

public class VehicleSession
{
    public long VehicleId { get; set; }
    public Vehicle Vehicle { get; set; }
    public string DeviceUuid { get; set; } // PRIMARY KEY
    public string AuthenticationToken { get; set; }
    public string OSName { get; set; }
    public string OSVersion { get; set; }
    public string DeviceModel { get; set; }
}
</code>```

Database:

Table 'vehiclesessions' where the PRIMARY KEY is DeviceUuid and has key 'device2':

Controller:

A request comes in from somewhere. DeviceUuid is fetched from HTTP headers.

```<code>    public async Task<ActionResult<VehicleLoginResponse>> Login(VehicleLogin login)
    {
        Request.Headers.TryGetValue(BaseConstants.DEVICE_UUID, out StringValues deviceUuid);
        Vehicle vehicle = await vehicleService.Authenticate(login.Username, login.Password); // returns a Vehicle by asking dbContet: dbContext.Vehicles.FirstOrDefault(v => v.Username.Equals(username));
        VehicleSession vs = await vehicleService.CreateSession(vehicle, login, deviceUuid);
        // ...
    }
</code>```

Service:

This service creates a new VehicleSession object, assigns it to the Vehicle property, and does an .Update on the Vehicle, so that the new session is saved with it.

```<code>    public async Task<VehicleSession> CreateSession(Vehicle vehicle, VehicleLogin vehicleLogin, string deviceUuid)
    {
        VehicleSession vs = new VehicleSession()
        {
            Vehicle = vehicle,
            AuthenticationToken = someTokenFetchedFromSomewhere,
            DeviceModel = vehicleLogin.DeviceModel,
            DeviceUuid = deviceUuid, // is 'device2'
            OSName = vehicleLogin.OSName,
            OSVersion = vehicleLogin.OSVersion
        };

        vehicle.Session = vs;
        dbContext.Vehicles.Update(vehicle);
        await dbContext.SaveChangesAsync();
        return vs;
    }
</code>```

It doesn't matter if I replace the new VehicleSession and assignment, with just editing an already existing Vehicle.Session, same error:

```<code>    public async Task<VehicleSession> CreateSession(Vehicle vehicle, VehicleLogin vehicleLogin, string deviceUuid)
    {
        if (vehicle.Session == null)
            vehicle.Session = new VehicleSession(); // never executes this line
        vehicle.Session.AuthenticationToken = someTokenFetchedFromSomewhere;

        vehicle.Session.DeviceModel = vehicleLogin.DeviceModel;
        vehicle.Session.DeviceUuid = deviceUuid;
        vehicle.Session.OSName = vehicleLogin.OSName;
        vehicle.Session.OSVersion = vehicleLogin.OSVersion;

        await dbContext.SaveChangesAsync();
        return vehicle.Session;
    }
</code>```

When doing so, I get an error saying:

Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred
  while updating the entries. See the inner exception for details.  --->
  MySql.Data.MySqlClient.MySqlException (0x80004005): Duplicate entry
  'device2' for key 'vehiclesessions.PRIMARY'  --->
  MySql.Data.MySqlClient.MySqlException (0x80004005): Duplicate entry
  'device2' for key 'vehiclesessions.PRIMARY'

The SQL produced:

```<code> Failed executing DbCommand (125ms) [Parameters=[@p0='?' (Size = 95), @p1='?' (Size = 95), @p2='?' (Size = 4000), @p3='?' (Size = 4000), @p4='?' (Size = 4000), @p5='?' (DbType = Int64)], CommandType='Text', CommandTimeout='30']
      INSERT INTO `VehicleSessions` (`DeviceUuid`, `AuthenticationToken`, `DeviceModel`, `OSName`, `OSVersion`, `VehicleId`)
      VALUES (@p0, @p1, @p2, @p3, @p4, @p5);
fail: Microsoft.EntityFrameworkCore.Update[10000]
      An exception occurred in the database while saving changes for context type 'blabla'.
      Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
       ---> MySql.Data.MySqlClient.MySqlException (0x80004005): Duplicate entry 'device2' for key 'vehiclesessions.PRIMARY'
       ---> MySql.Data.MySqlClient.MySqlException (0x80004005): Duplicate entry 'device2' for key 'vehiclesessions.PRIMARY'
</code>```

Why am I getting this error? It seems like an INSERT is done instead of an UPDATE, even though the Vehicle object is fetched from dbContext, passed along and has PRIMARY id set.

答:
So, I think I might have found the issue.

As noted above, I first did a search to retrieve the Vehicle, like this:

Vehicle vehicle = dbContext.Vehicles.FirstOrDefault(v => v.Username.Equals(username));

In this case, the Vehicle.Session, if one existed, was not populated. Later on, I did the update as the code above shows, and it failed as noted above.

But, if I change the fetch code to this:

```<code>Vehicle entityVehicle = dbContext.Vehicles
    .Include(x => x.Session)// <-- NEW!
    .FirstOrDefault(v => v.Username.Equals(username));
</code>```

then it works.

It doesn't matter if I assign the .Session a new VehicleSession(...) or if I change the properties in the existing object. It also doesn't matter if I use dbContext.Vehicles.Update(vehicle); before await dbContext.SaveChangesAsync();, the call to .Update(...) is not needed.

The only thing that made a difference, was to use .Include(...).

My own theory is:

When fetching the object from db, the EF Core "tracker" starts tracking. Property Session is NULL. When Session later is populated, the tracker detects that it was NULL but now is not NULL, thus, it figures that an INSERT is needed.

And then, if you populate the Session on fetch, tracker sees it is there, and should be updated.

Body:
It seems like EF Core is doing an INSERT instead of an UPDATE, and thus MySQL complains about a duplicate key. However, I am using the Update method on the DbSet and the entities do have primary keys set. This results in a DUPLICATE ENTRY error in MySql.

Running VS 2019, EF Core 3.1.1 and ASP.NET Core 3.1

Model (I do not use Fluent config for relationships, just Convention):

public class Vehicle
{
    public long Id {get; set; } // PRIMARY KEY, AUTO INCREMENT
    public string RegistrationNumber { get; set; }
    public VehicleSession Session { get; set; }
}

public class VehicleSession
{
    public long VehicleId { get; set; }
    public Vehicle Vehicle { get; set; }
    public string DeviceUuid { get; set; } // PRIMARY KEY
    public string AuthenticationToken { get; set; }
    public string OSName { get; set; }
    public string OSVersion { get; set; }
    public string DeviceModel { get; set; }
}

Database:

Table 'vehiclesessions' where the PRIMARY KEY is DeviceUuid and has key 'device2':

Controller:

A request comes in from somewhere. DeviceUuid is fetched from HTTP headers.

    public async Task<ActionResult<VehicleLoginResponse>> Login(VehicleLogin login)
    {
        Request.Headers.TryGetValue(BaseConstants.DEVICE_UUID, out StringValues deviceUuid);
        Vehicle vehicle = await vehicleService.Authenticate(login.Username, login.Password); // returns a Vehicle by asking dbContet: dbContext.Vehicles.FirstOrDefault(v => v.Username.Equals(username));
        VehicleSession vs = await vehicleService.CreateSession(vehicle, login, deviceUuid);
        // ...
    }

Service:

This service creates a new VehicleSession object, assigns it to the Vehicle property, and does an .Update on the Vehicle, so that the new session is saved with it.

    public async Task<VehicleSession> CreateSession(Vehicle vehicle, VehicleLogin vehicleLogin, string deviceUuid)
    {
        VehicleSession vs = new VehicleSession()
        {
            Vehicle = vehicle,
            AuthenticationToken = someTokenFetchedFromSomewhere,
            DeviceModel = vehicleLogin.DeviceModel,
            DeviceUuid = deviceUuid, // is 'device2'
            OSName = vehicleLogin.OSName,
            OSVersion = vehicleLogin.OSVersion
        };

        vehicle.Session = vs;
        dbContext.Vehicles.Update(vehicle);
        await dbContext.SaveChangesAsync();
        return vs;
    }

It doesn't matter if I replace the new VehicleSession and assignment, with just editing an already existing Vehicle.Session, same error:

    public async Task<VehicleSession> CreateSession(Vehicle vehicle, VehicleLogin vehicleLogin, string deviceUuid)
    {
        if (vehicle.Session == null)
            vehicle.Session = new VehicleSession(); // never executes this line
        vehicle.Session.AuthenticationToken = someTokenFetchedFromSomewhere;

        vehicle.Session.DeviceModel = vehicleLogin.DeviceModel;
        vehicle.Session.DeviceUuid = deviceUuid;
        vehicle.Session.OSName = vehicleLogin.OSName;
        vehicle.Session.OSVersion = vehicleLogin.OSVersion;

        await dbContext.SaveChangesAsync();
        return vehicle.Session;
    }

When doing so, I get an error saying:

Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred
  while updating the entries. See the inner exception for details.  --->
  MySql.Data.MySqlClient.MySqlException (0x80004005): Duplicate entry
  'device2' for key 'vehiclesessions.PRIMARY'  --->
  MySql.Data.MySqlClient.MySqlException (0x80004005): Duplicate entry
  'device2' for key 'vehiclesessions.PRIMARY'

The SQL produced:

 Failed executing DbCommand (125ms) [Parameters=[@p0='?' (Size = 95), @p1='?' (Size = 95), @p2='?' (Size = 4000), @p3='?' (Size = 4000), @p4='?' (Size = 4000), @p5='?' (DbType = Int64)], CommandType='Text', CommandTimeout='30']
      INSERT INTO `VehicleSessions` (`DeviceUuid`, `AuthenticationToken`, `DeviceModel`, `OSName`, `OSVersion`, `VehicleId`)
      VALUES (@p0, @p1, @p2, @p3, @p4, @p5);
fail: Microsoft.EntityFrameworkCore.Update[10000]
      An exception occurred in the database while saving changes for context type 'blabla'.
      Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
       ---> MySql.Data.MySqlClient.MySqlException (0x80004005): Duplicate entry 'device2' for key 'vehiclesessions.PRIMARY'
       ---> MySql.Data.MySqlClient.MySqlException (0x80004005): Duplicate entry 'device2' for key 'vehiclesessions.PRIMARY'

Why am I getting this error? It seems like an INSERT is done instead of an UPDATE, even though the Vehicle object is fetched from dbContext, passed along and has PRIMARY id set.

Body:
So, I think I might have found the issue.

As noted above, I first did a search to retrieve the Vehicle, like this:

Vehicle vehicle = dbContext.Vehicles.FirstOrDefault(v => v.Username.Equals(username));

In this case, the Vehicle.Session, if one existed, was not populated. Later on, I did the update as the code above shows, and it failed as noted above.

But, if I change the fetch code to this:

Vehicle entityVehicle = dbContext.Vehicles
    .Include(x => x.Session)// <-- NEW!
    .FirstOrDefault(v => v.Username.Equals(username));

then it works.

It doesn't matter if I assign the .Session a new VehicleSession(...) or if I change the properties in the existing object. It also doesn't matter if I use dbContext.Vehicles.Update(vehicle); before await dbContext.SaveChangesAsync();, the call to .Update(...) is not needed.

The only thing that made a difference, was to use .Include(...).

My own theory is:

When fetching the object from db, the EF Core "tracker" starts tracking. Property Session is NULL. When Session later is populated, the tracker detects that it was NULL but now is not NULL, thus, it figures that an INSERT is needed.

And then, if you populate the Session on fetch, tracker sees it is there, and should be updated.


答:
You can use cors to get rid of this;

```<code>const express = require('express')
const cors = require('cors')
const app = express()

app.use(cors())
</code>```

Title: Unable to fetch JSON from Express server using Fetch api

Body:
In Express server running on port 8080 I have;

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:8081");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

Request from port 8081

fetch('http://localhost:8080/...')
      .then((response) => response.json())
      .then((json) => {
        let jsonStr = JSON.stringify(json);
        console.log(jsonStr)
      })
      .catch((error) => console.log(error))

Error I get:

Access to fetch at 'http://localhost:8080/...' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

If I simply manually enter express url on browser I see the JSON I'm trying to fetch.

I have read multiple post to resolve this issue but I still can't seem to be able to resolve it.

How should I fetch to avoid this error?

Body:
You can use cors to get rid of this;

const express = require('express')
const cors = require('cors')
const app = express()

app.use(cors())


问:
How to set Textbox value at page load?
I have to set asp.net TextBox’s value at page load using JQuery.

Can somebody give me example ?

答:
Try this</p>

```<code><script type="text/javascript">
    $(document).ready(function() {
            $("#TextBox1").val("Hello World");
            });
</script>
</code>```

Title: How to set Textbox value at page load?

Body:
Try this

<script type="text/javascript">
    $(document).ready(function() {
            $("#TextBox1").val("Hello World");
            });
</script>