问:
How do I pass the objectID of a document inside of a MongoDB Collection in a URL?
I am learning how to use databases. I am working on making a simple CRUD application that stores contact information, displays said contact information and allows the user to delete contacts. I am trying to pass an objectID as a parameter inside of the URL. This is how I am attempting to do so:

```<code><a href="/contacts/list/<%= this._id %>">Delete</a>
</code>```

I am then trying to send this objectID to a separate page.

```<code>router.get('/contacts/list/:id', function(req, res){
    res.send(req.params.id);
});
</code>```

If anyone can guide me in the right direction it would be much appretiated.

答:
By the time you get it to code it will be a string, ObjectId() is not a supported type of JSON, it's from BSON which is MongoDB specific. So when you query database, internally drivers would convert ObjectId() to string & present it to you. You can pass it wherever you want as like string & when you query/delete a document using that you need to convert string from ObjectId() to match with type of _id field in database.

mongodb Driver :

```<code>const ObjectId = require('mongodb').ObjectId;
const id = new ObjectId(objectIdSring);
</code>```

mongoose :

```<code>const mongoose = require('mongoose');
const id = mongoose.Types.ObjectId(objectIdSring);
</code>```

Note : You don't need to do that conversion by yourself when using .findByIdAndDelete() function provided by mongoose - which actually takes in a string & internally it would convert to ObjectId(). Not only this it has few other functions similar to this, you can check for functions with syntax : .findById*****.

Body:
I am learning how to use databases. I am working on making a simple CRUD application that stores contact information, displays said contact information and allows the user to delete contacts. I am trying to pass an objectID as a parameter inside of the URL. This is how I am attempting to do so:

<a href="/contacts/list/<%= this._id %>">Delete

I am then trying to send this objectID to a separate page.

router.get('/contacts/list/:id', function(req, res){
    res.send(req.params.id);
});

If anyone can guide me in the right direction it would be much appretiated.

Body:
By the time you get it to code it will be a string, ObjectId() is not a supported type of JSON, it's from BSON which is MongoDB specific. So when you query database, internally drivers would convert ObjectId() to string & present it to you. You can pass it wherever you want as like string & when you query/delete a document using that you need to convert string from ObjectId() to match with type of _id field in database.

mongodb Driver :

const ObjectId = require('mongodb').ObjectId;
const id = new ObjectId(objectIdSring);

mongoose :

const mongoose = require('mongoose');
const id = mongoose.Types.ObjectId(objectIdSring);

Note : You don't need to do that conversion by yourself when using .findByIdAndDelete() function provided by mongoose - which actually takes in a string & internally it would convert to ObjectId(). Not only this it has few other functions similar to this, you can check for functions with syntax : .findById*****.


来源: stackexchange

问:
How to parse a custom key/value pair string into a JSON object in Azure Data Explorer?
I needed to parse a string of properties to a JSON object. Here is the input format:

"var1=[val1] & var2=[val2] & var3=[val3] & var4=[val4]"

And the desired output:

{
   "var1": "val1",
   "var2": "val2",
   "var3": "val3",
   "var4": "val4"
}
```

I have the answer, see below...

答:
an alternative method would be using extract_all(), then 'converting' the array into a property bad using pack() and make_bag():

```<code>print str = "var1=[val1] & var2=[val2] & var3=[val3] & var4=[val4]"
| project Properties = extract_all(@"(?P<key>\w+)?=\[(?P<value>.*?)\]", dynamic(["key","value"]), str)
| mv-apply Properties on (
    summarize make_bag(pack(tostring(Properties[0]), Properties[1]))
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I needed to parse a string of properties to a JSON object. Here is the input format:

"var1=[val1] & var2=[val2] & var3=[val3] & var4=[val4]"

And the desired output:

{
   "var1": "val1",
   "var2": "val2",
   "var3": "val3",
   "var4": "val4"
}

I have the answer, see below...

Body:
an alternative method would be using extract_all(), then 'converting' the array into a property bad using pack() and make_bag():

print str = "var1=[val1] & var2=[val2] & var3=[val3] & var4=[val4]"
| project Properties = extract_all(@"(?P<key>\w+)?=\[(?P<value>.*?)\]", dynamic(["key","value"]), str)
| mv-apply Properties on (
    summarize make_bag(pack(tostring(Properties[0]), Properties[1]))
)


问:
NIFI custom processor error - can not upload template
Good day,

I'm trying to upload nifi template and getting this kind of error:

org.apache.nifi.processors.kite.ConvertAvroSchema is not known to this NiFi instance

I suppose that my Nifi Instance misses some component - but where can I get it and where on file system I need to add missing file?

I'm little bit confused.

Thanks!

答:
As stated here, since 1.10.0 kite-nar was taken out of the default binaries because of space limitations.
You can get it here. </p>


问:
How to write byte(s) to a file in C++?
I have created a bitset using std::bitset<8> bits which is equivalent to 00000000 i.e., 1 byte.
I have output file defined as std::ofstream outfile("./compressed", std::ofstream::out | std::ofstream::binary) but when I write the bits using outfile << bits, the content of outfile becomes 00000000 but the size of file is 8 bytes. (each bit of bits end up taking 1 byte in the file). Is there any way to truly write byte to a file? For example if I write 11010001 then this should be written as a byte and the file size should be 1 byte not 8 bytes. I am writing a code for Huffman encoder and I am not able to find a way to write the encoded bytes to the output compressed file.

答:
The issue is operator<< is the text encoding method, even if you've specified std::ofstream::binary. You can use put to write a single binary character or write to output multiple characters. Note that you are responsible for the conversion of data to its char representation.

```<code>std::bitset<8> bits = foo();
std::ofstream outfile("compressed", std::ofstream::out | std::ofstream::binary);

// In reality, your conversion code is probably more complicated than this
char repr = bits.to_ulong();

// Use scoped sentries to output with put/write
{
    std::ofstream::sentry sentry(outfile);
    if (sentry)
    {
        outfile.put(repr);                  // <- Option 1
        outfile.write(&repr, sizeof repr);  // <- Option 2
    }
}
</code>```

Title: How to write byte(s) to a file in C++?

Body:
The issue is operator<< is the text encoding method, even if you've specified std::ofstream::binary. You can use put to write a single binary character or write to output multiple characters. Note that you are responsible for the conversion of data to its char representation.

std::bitset<8> bits = foo();
std::ofstream outfile("compressed", std::ofstream::out | std::ofstream::binary);

// In reality, your conversion code is probably more complicated than this
char repr = bits.to_ulong();

// Use scoped sentries to output with put/write
{
    std::ofstream::sentry sentry(outfile);
    if (sentry)
    {
        outfile.put(repr);                  // <- Option 1
        outfile.write(&repr, sizeof repr);  // <- Option 2
    }
}


问:
Vb.Net MS Publisher Strings Array To TextBox Problem
I am creating a Simple Publisher Application in which I need to insert texts in different textbox from an array of strings .I have coded it like this .

```<code>    Dim texts(40) As String 'Array of strings to be inserted

    shpTextBox = appPub.ActiveDocument.Pages(pageIndex).Shapes.AddTextbox _
          (Orientation:=PbTextOrientation.pbTextOrientationHorizontal, _
          Left:=pbShape.Left - 20, Top:=pbShape.Top, _
          Width:=72, Height:=18)

                'add text
                shpTextBox.TextFrame.TextRange.Text = texts(Index)'Problem here , Only First array value is populating to very first text box , rest are empty strings.

                Index = Index + 1
</code>```

Now It only populates first text box with the first string in the array (For 0th index) and rest textboxes contains empty strings ,though texts array has values.

Any help would be highly appreciated .

Thanks.

答: Changed the code to C# and its working fine now...!!</p>

ContentLicense: CC BY-SA 3.0

Body:
I am creating a Simple Publisher Application in which I need to insert texts in different textbox from an array of strings .I have coded it like this .

    Dim texts(40) As String 'Array of strings to be inserted

    shpTextBox = appPub.ActiveDocument.Pages(pageIndex).Shapes.AddTextbox _
          (Orientation:=PbTextOrientation.pbTextOrientationHorizontal, _
          Left:=pbShape.Left - 20, Top:=pbShape.Top, _
          Width:=72, Height:=18)

                'add text
                shpTextBox.TextFrame.TextRange.Text = texts(Index)'Problem here , Only First array value is populating to very first text box , rest are empty strings.

                Index = Index + 1

Now It only populates first text box with the first string in the array (For 0th index) and rest textboxes contains empty strings ,though texts array has values.

Any help would be highly appreciated .

Thanks.


问:
Implementing VirtualTreeView TVTDefaultAccessibleProvider in C++ Builder
When using VirtualStringTree to add accessibility support it is required to include the unit VirtualTrees.Accessibility in the uses section. This works in Delphi.

The equivalent of this in C++ Builder would be to include the #include "VirtualTrees.Accessibility.hpp". But including the include file doesn't have any effect.

I've traced the problem to the VirtualTrees.Accessibility.pas file and it executes a few lines of code to register the default accessibility provider in Delphi while this code is absent from the hpp file. So including the hpp does include the class but not the code which registers the provider.

The code in question (at the end of VirtualTrees.Accessibility.pas is this):

var
  DefaultAccessibleProvider: TVTDefaultAccessibleProvider;
  DefaultAccessibleItemProvider: TVTDefaultAccessibleItemProvider;
  MultiColumnAccessibleProvider: TVTMultiColumnAccessibleItemProvider;

initialization
  if DefaultAccessibleProvider = nil then
  begin
    DefaultAccessibleProvider := TVTDefaultAccessibleProvider.Create;
    GetAccessibilityFactory.RegisterAccessibleProvider(DefaultAccessibleProvider);
  end;
  if DefaultAccessibleItemProvider = nil then
  begin
    DefaultAccessibleItemProvider := TVTDefaultAccessibleItemProvider.Create;
    GetAccessibilityFactory.RegisterAccessibleProvider(DefaultAccessibleItemProvider);
  end;
  if MultiColumnAccessibleProvider = nil then
  begin
    MultiColumnAccessibleProvider := TVTMultiColumnAccessibleItemProvider.Create;
    GetAccessibilityFactory.RegisterAccessibleProvider(MultiColumnAccessibleProvider);
  end;
finalization
  GetAccessibilityFactory.UnRegisterAccessibleProvider(MultiColumnAccessibleProvider);
  MultiColumnAccessibleProvider := nil;
  GetAccessibilityFactory.UnRegisterAccessibleProvider(DefaultAccessibleItemProvider);
  DefaultAccessibleItemProvider := nil;
  GetAccessibilityFactory.UnRegisterAccessibleProvider(DefaultAccessibleProvider);
  DefaultAccessibleProvider := nil;

end.
```

My question - how do I translate or use the above so I can have accessibility support from C++ Builder as well after including the VirtualTrees.Accessibility.hpp file? A translation of the above into C++ would be very appreciated.

答:
Based on research from this link and answer by Remy Lebeau:

The initialization part is not called

And the opened issue on VirtualTree GitHub:

https://github.com/Virtual-TreeView/Virtual-TreeView/issues/951

I am sharing a solution here, how this might be achieved by either one of the following:

Method A

By calling:

TVirtualTreeAccessibility::RegisterDefaultAccessibleProviders();

somewhere in the cpp file, as suggested by Joachim Marder

Method B

By adding:

#pragma link "VirtualTrees.Accessibility"

in the cpp source file

Method C

By adding something like:

{$HPPEMIT '#pragma link "VirtualTrees.Accessibility"'}

in the VirtualTrees.Accessibility.pas source code

Body:
When using VirtualStringTree to add accessibility support it is required to include the unit VirtualTrees.Accessibility in the uses section. This works in Delphi.

The equivalent of this in C++ Builder would be to include the #include "VirtualTrees.Accessibility.hpp". But including the include file doesn't have any effect.

I've traced the problem to the VirtualTrees.Accessibility.pas file and it executes a few lines of code to register the default accessibility provider in Delphi while this code is absent from the hpp file. So including the hpp does include the class but not the code which registers the provider.

The code in question (at the end of VirtualTrees.Accessibility.pas is this):

var
  DefaultAccessibleProvider: TVTDefaultAccessibleProvider;
  DefaultAccessibleItemProvider: TVTDefaultAccessibleItemProvider;
  MultiColumnAccessibleProvider: TVTMultiColumnAccessibleItemProvider;

initialization
  if DefaultAccessibleProvider = nil then
  begin
    DefaultAccessibleProvider := TVTDefaultAccessibleProvider.Create;
    GetAccessibilityFactory.RegisterAccessibleProvider(DefaultAccessibleProvider);
  end;
  if DefaultAccessibleItemProvider = nil then
  begin
    DefaultAccessibleItemProvider := TVTDefaultAccessibleItemProvider.Create;
    GetAccessibilityFactory.RegisterAccessibleProvider(DefaultAccessibleItemProvider);
  end;
  if MultiColumnAccessibleProvider = nil then
  begin
    MultiColumnAccessibleProvider := TVTMultiColumnAccessibleItemProvider.Create;
    GetAccessibilityFactory.RegisterAccessibleProvider(MultiColumnAccessibleProvider);
  end;
finalization
  GetAccessibilityFactory.UnRegisterAccessibleProvider(MultiColumnAccessibleProvider);
  MultiColumnAccessibleProvider := nil;
  GetAccessibilityFactory.UnRegisterAccessibleProvider(DefaultAccessibleItemProvider);
  DefaultAccessibleItemProvider := nil;
  GetAccessibilityFactory.UnRegisterAccessibleProvider(DefaultAccessibleProvider);
  DefaultAccessibleProvider := nil;

end.

My question - how do I translate or use the above so I can have accessibility support from C++ Builder as well after including the VirtualTrees.Accessibility.hpp file? A translation of the above into C++ would be very appreciated.


问:
Implicitly expose members of a class property
I wonder if it's possible to access public members of a property of an object without specifying the name of the property.

Exemple :

```<code>// Bar.cs
public class Bar {
    public bool SomeMethod() {

    }
}

// Container.cs
public class Container<T> {
    public T Content;
}

// Anywhere.cs
Container<Bar> container;

// Is there a way to access Bar properties and method directly like this ?
container.SomeMethod();
// Instead of:
container.Content.SomeMethod();
</code>```

答:
The possible option here is to apply a generic constraint to the Container<T> class using where keyword

public class Bar
{
    public void SomeMethod()
    {
    }
}

public class Container<T> where T : Bar
{
    public T Content;

    public void SomeMethod()
    {
        Content?.SomeMethod();
    }
}
```

<p>Generic types are resolved at runtime, so you can't know what is the type <code>T</code> exactly and does it have <code>SomeMethod()</code> or not. You can create a base class or interface to use it as constraint instead of using <code>where T : Bar</code>.</p>

<p>Another option is cast <code>Content</code> to the concrete type (or use a reflection even), but you lose all benefits of generic types</p>

<pre class="lang-cs prettyprint-override"><code>public void SomeMethod()
{
    if (Content is Bar bar)
    {
        bar.SomeMethod();
    }
}
</code>```

Body:
I wonder if it's possible to access public members of a property of an object without specifying the name of the property.

Exemple :

// Bar.cs
public class Bar {
    public bool SomeMethod() {

    }
}

// Container.cs
public class Container<T> {
    public T Content;
}

// Anywhere.cs
Container<Bar> container;

// Is there a way to access Bar properties and method directly like this ?
container.SomeMethod();
// Instead of:
container.Content.SomeMethod();

Body:
The possible option here is to apply a generic constraint to the Container<T> class using where keyword

public class Bar
{
    public void SomeMethod()
    {
    }
}

public class Container<T> where T : Bar
{
    public T Content;

    public void SomeMethod()
    {
        Content?.SomeMethod();
    }
}

Generic types are resolved at runtime, so you can't know what is the type T exactly and does it have SomeMethod() or not. You can create a base class or interface to use it as constraint instead of using where T : Bar.

Another option is cast Content to the concrete type (or use a reflection even), but you lose all benefits of generic types

public void SomeMethod()
{
    if (Content is Bar bar)
    {
        bar.SomeMethod();
    }
}


问:
Travis CI not sending Jacoco reports to SonarCloud
I have a Spring Boot project repository on Github with Travis CI integrated. Currently Travis CI is configured to build the project for commits and Pull requests, which works fine.

Next, I want to send a Jacoco report to SonarCloud. I have followed the wiki on Travis but when I look at SoundCloud project nothing is shown. Following is my configuration:

Authentication token for SonarCloud account: I have generated it on SonarCloud and set it in Travis -> Environment Variables -> SONAR_TOKEN.

.travis.yml

```<code>script:
  - mvn install -P test
  - mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent org.jacoco:jacoco-maven-plugin:report package sonar:sonar

addons:
  sonarcloud:
    organization: "my_organization_name_on_SonarCloud"
</code>```

Project's src/main/resources/sonar-project.properties

```<code>sonar.projectKey=my_project_key_on_SonarCloud
sonar.projectName=my_project_name
sonar.projectVersion=0.0.1
sonar.sources=.
</code>```

Jacoco-maven-plugin

```<code><plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.3</version>
    <executions>
        <execution>
            <id>default-prepare-agent</id>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
            </execution>
        <execution>
            <id>default-report</id>
            <phase>prepare-package</phase>
            <goals>
                <goal>report</goal>
            </goals>
        </execution>
    </executions>
</plugin>
</code>```

Following are the Travis CI Job logs

```<code>Setting environment variables from repository settings
$ export SONAR_TOKEN=[secure]
SonarCloud addon
addon hash: de356982c12b370c7bfe9c5317053863
Preparing SonarQube Scanner CLI
Archive:  /home/travis/.sonarscanner/sonar-scanner.zip
inflating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/bin/sonar-scanner-debug.bat
inflating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/bin/sonar-runner.bat
inflating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/bin/sonar-scanner.bat
inflating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/bin/sonar-runner
inflating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/bin/sonar-scanner
inflating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/bin/sonar-scanner-debug
creating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/conf/
inflating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/conf/sonar-scanner.properties
creating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/lib/
inflating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/lib/sonar-scanner-cli-3.0.3.778.jar
$ export SONAR_SCANNER_HOME=${TRAVIS_HOME}/.sonarscanner/sonar-scanner-3.0.3.778
Not installing SonarSource build-wrapper because it's a Java or Javascript project
Preparing SonarQube Scanner parameters0.00s
$
The command "" exited with 0.
</code>```

Can somebody point out what I am missing here?

Thanks in advance.

答:
script:
- mvn clean install -B
- mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent install sonar:sonar -Dsonar.projectKey=...

sudo: required
addons:
  sonarcloud:
    organization: ...
    token:
      secure: $SONAR_TOKEN

Could you try like above

Body:
I have a Spring Boot project repository on Github with Travis CI integrated. Currently Travis CI is configured to build the project for commits and Pull requests, which works fine.

Next, I want to send a Jacoco report to SonarCloud. I have followed the wiki on Travis but when I look at SoundCloud project nothing is shown. Following is my configuration:

Authentication token for SonarCloud account: I have generated it on SonarCloud and set it in Travis -> Environment Variables -> SONAR_TOKEN.

.travis.yml

script:
  - mvn install -P test
  - mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent org.jacoco:jacoco-maven-plugin:report package sonar:sonar

addons:
  sonarcloud:
    organization: "my_organization_name_on_SonarCloud"

Project's src/main/resources/sonar-project.properties

sonar.projectKey=my_project_key_on_SonarCloud
sonar.projectName=my_project_name
sonar.projectVersion=0.0.1
sonar.sources=.

Jacoco-maven-plugin

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.3</version>
    <executions>
        <execution>
            <id>default-prepare-agent</id>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
            </execution>
        <execution>
            <id>default-report</id>
            <phase>prepare-package</phase>
            <goals>
                <goal>report</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Following are the Travis CI Job logs

Setting environment variables from repository settings
$ export SONAR_TOKEN=[secure]
SonarCloud addon
addon hash: de356982c12b370c7bfe9c5317053863
Preparing SonarQube Scanner CLI
Archive:  /home/travis/.sonarscanner/sonar-scanner.zip
inflating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/bin/sonar-scanner-debug.bat
inflating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/bin/sonar-runner.bat
inflating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/bin/sonar-scanner.bat
inflating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/bin/sonar-runner
inflating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/bin/sonar-scanner
inflating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/bin/sonar-scanner-debug
creating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/conf/
inflating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/conf/sonar-scanner.properties
creating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/lib/
inflating: /home/travis/.sonarscanner/sonar-scanner-3.0.3.778/lib/sonar-scanner-cli-3.0.3.778.jar
$ export SONAR_SCANNER_HOME=${TRAVIS_HOME}/.sonarscanner/sonar-scanner-3.0.3.778
Not installing SonarSource build-wrapper because it's a Java or Javascript project
Preparing SonarQube Scanner parameters0.00s
$
The command "" exited with 0.

Can somebody point out what I am missing here?

Thanks in advance.


问:
Access Error: 'Export$ is not a valid name.'
I've been working with an Access DB for months now, and for some reason today my import is throwing a strange error. On importing using a saved import, Access gives me the error:

```<code>"Export$" is not a valid name. Make sure it does not include invalid characters or punctuation and that it is not too long.
</code>```

My import is a Excel file of roughly 350,000 rows, 12 columns. Every week I run this import with a new weekly Excel file and have never seen this error before. I don't believe I have any invalid names in my column titles ($Export exists nowhere in my sheet.)

How can I fix this or find what row is throwing the error?

EDIT:

The worksheet that is throwing the error is named "WP Items", is reference at C:/SK/WP Items.xlsx. The import draws from the name, which is the same as it is every week - so that confuses me further.

There is no VBA involved here, just running a saved import.

答: Had the same problem.  Every month for 10 year's I import the same file with updated data... I just figured out this problem with trial and error.  On the import file, one of the header row names inadvertently had a space in front of the column name. I deleted the space & its FIXED.</p>

Body:
I've been working with an Access DB for months now, and for some reason today my import is throwing a strange error. On importing using a saved import, Access gives me the error:

"Export$" is not a valid name. Make sure it does not include invalid characters or punctuation and that it is not too long.

My import is a Excel file of roughly 350,000 rows, 12 columns. Every week I run this import with a new weekly Excel file and have never seen this error before. I don't believe I have any invalid names in my column titles ($Export exists nowhere in my sheet.)

How can I fix this or find what row is throwing the error?

EDIT:

The worksheet that is throwing the error is named "WP Items", is reference at C:/SK/WP Items.xlsx. The import draws from the name, which is the same as it is every week - so that confuses me further.

There is no VBA involved here, just running a saved import.


问:
methods for comparing strings with numbers
I have been doing some string problems.
The problem now is to check if a  ip is valid or not.
for example 255.6.13.4.
The ip is stored in a string.Now i have to check whether the numbers lie between 0 to 255.
Is there any way to split the ip and compare with numbers or any other way around it.
thanks in advance</p>

答:
Use stringstreams and std::getline(), it has a delimiter parameter.

Link to live sample

#include <iostream>
#include <sstream>
#include <vector>

int main()
{
    std::string str = "123.231.0.43";

    std::stringstream test(str);
    std::string temp;
    int temp_int;
    std::vector<int> addr_elements; //int vector, you can use a string vector if you prefer

    while (std::getline(test, temp, '.')) //split by delimiter '.'
    {

        std::stringstream ssint(temp);
        ssint >> temp_int;     //string to int
        addr_elements.push_back(temp_int); //now you have a vector of integers
    }

    for(int i : addr_elements){ //test print the vector
        std::cout << i << " ";
    }
}
```


问:
delete file other than particular extension file format
i have a lot of different type of files in one folder. i need to delete the files but except the pdf file.
I tried to display the pdf file only. but i need to delete the other than pdf files</p>

```<code>ls -1 | xargs file | grep 'PDF document,' | sed 's/:.*//'
</code>```

答:
You could do the following - I've used echo rm instead of rm for safety:

```<code>for i in *
do
    [ x"$(file --mime-type -b "$i")" != xapplication/pdf ] && echo rm "$i"
done
</code>```

The --mime-type -b options to file make the output of file easier to deal with in a script.

Body:
i have a lot of different type of files in one folder. i need to delete the files but except the pdf file.
I tried to display the pdf file only. but i need to delete the other than pdf files

ls -1 | xargs file | grep 'PDF document,' | sed 's/:.*//'

Body:
You could do the following - I've used echo rm instead of rm for safety:

for i in *
do
    [ x"$(file --mime-type -b "$i")" != xapplication/pdf ] && echo rm "$i"
done

The --mime-type -b options to file make the output of file easier to deal with in a script.


问:
Backtracking Sudoku only sort of works in Python 3
I'm struggling to make this work. It gets a few digits right, but I don't know where the problem is. I've read various other codes and while I understand how they work, I don't know where the problem with my code is. I've tried multiple things and this is the closest I've come.

```<code>board = [
    [0, 9, 0,   0, 0, 0,   0, 1, 0],
    [8, 0, 4,   0, 2, 0,   3, 0, 7],
    [0, 6, 0,   9, 0, 7,   0, 2, 0],

    [0, 0, 5,   0, 3, 0,  1, 0, 0],
    [0, 7, 0,   5, 0, 1,  0, 3, 0],
    [0, 0, 3,   0, 9, 0,  8, 0, 0],

    [0, 2, 0,   8, 0, 5,   0, 6, 0],
    [1, 0, 7,   0, 6, 0,   4, 0, 9],
    [0, 3, 0,   0, 0, 0,   0, 8, 0],
]

def p(board):
    for i in board:
        print(i)

def find(board):
    for row in range(9):
        for col in range(9):
            if board[row][col] == 0:
                return row, col
    return 1

def check_horizontal(board, row, number):
    for i in range(0, 9):
        if board[row][i] == number:
            return False
    return True

def check_vertical(board, col, number):
    for i in range(0, 9):
        if board[i][col] == number:
            return False
    return True

def check_sqaure(board, row, col, number):
    a = int(row / 3)
    b = int(col / 3)
    for i in range(a * 3, a * 3 + 3):
        for j in range(b * 3, b * 3 + 3):
            if board[i][j] == number:
                return False
    return True

def check_all(board, row, col, number):
    if check_horizontal(board, row, number) and check_vertical(board, col, number) and check_sqaure(board, row, col,number):
        return True

def play(board):
    if find(board) == 1:
        return 1
    row, col = find(board)
    for i in range(1, 10):
        if check_all(board, row, col, i):
            board[row][col] = i
            if play(board) == 1:
                return board
            else:
                if check_all(board, row, col,board[row][col] + 1):
                    board[row][col] = board[row][col] + 1
play(board)
p(board)
</code>```

and this is the output:

```<code>[7, 9, 2, 3, 4, 8, 6, 1, 5]
[8, 5, 4, 6, 2, 0, 3, 0, 7]
[0, 6, 0, 9, 0, 7, 0, 2, 0]
[0, 0, 5, 0, 3, 0, 1, 0, 0]
[0, 7, 0, 5, 0, 1, 0, 3, 0]
[0, 0, 3, 0, 9, 0, 8, 0, 0]
[0, 2, 0, 8, 0, 5, 0, 6, 0]
[1, 0, 7, 0, 6, 0, 4, 0, 9]
[0, 3, 0, 0, 0, 0, 0, 8, 0]
</code>```

The correct result would be:

```<code>    [7, 9, 2,   3, 5, 4,    6, 1, 8]
    [8, 5, 4,   1, 2, 6,    3, 9, 7]
    [3, 6, 1,   9, 8, 7,    5, 2, 4]

    [9, 4, 5,   6, 3, 8,    1, 7, 2]
    [2, 7, 8,   5, 4, 1,    9, 3, 6]
    [6, 1, 3,   7, 9, 2,    8, 4, 5]

    [4, 2, 9,   8, 1, 5,    7, 6, 3]
    [1, 8, 7,   2, 6, 3,    4, 5, 9]
    [5, 3, 6,   4, 7, 9,    2, 8, 1]
</code>```

答:
I see a couple issues with your play function.

The first issue is that you're not backtracking properly. Backtracking means you need to mark the space on the board you've been testing as unknown when you give up on the current partial solution. You currently have some strange code that tries to jump ahead if the recursion didn't find a solution. I think you should remove these lines:

```<code>else:
    if check_all(board, row, col,board[row][col] + 1):
        board[row][col] = board[row][col] + 1
</code>```

Instead, you need to reset if the loop fails to find any solution. So put this at the end of the code, outside the loop:

```<code>board[row][col] = 0
</code>```

The other issue is that you've got some mixed up logic about what the return value should be from play. In the base case, you're returning the sentinel value 1, and your later recursive code checks for this. But the later code will return board instead of the sentinel value if it thinks it got a solution from the recursion. You need to pick one of those and be consistent with it! The other side of this is that you're relying upon the default return value of None to indicate a failure when you fall off the end of the function. You should probably be explicit about that return value, by adding return None.

Here's how I'd do it, returning the board:

```<code>def play(board):
    if find(board) == 1:
        return board            # first change, return the board here!
    row, col = find(board)
    for i in range(1, 10):
        if check_all(board, row, col, i):
            board[row][col] = i
            if play(board) is not None: # second change, check for a non-None value, not == 1
                return board
    board[row][col] = 0         # third change, do proper backtracking (replaced three lines)
    return None                 # fourth change, be explicit about our return value on failure
</code>```

There's still a small wart where you call find twice, but it doesn't make the code wrong, just a bit slower than necessary. You could improve it by changing the first few lines:

```<code>coords = find(board)
if coords == 1:
    return board
row, col = coords
</code>```

I'd also prefer to use None as the sentinel for a failed find, but that's more an issue of taste than anything genuinely wrong or inefficient.

Body:
I'm struggling to make this work. It gets a few digits right, but I don't know where the problem is. I've read various other codes and while I understand how they work, I don't know where the problem with my code is. I've tried multiple things and this is the closest I've come.

board = [
    [0, 9, 0,   0, 0, 0,   0, 1, 0],
    [8, 0, 4,   0, 2, 0,   3, 0, 7],
    [0, 6, 0,   9, 0, 7,   0, 2, 0],

    [0, 0, 5,   0, 3, 0,  1, 0, 0],
    [0, 7, 0,   5, 0, 1,  0, 3, 0],
    [0, 0, 3,   0, 9, 0,  8, 0, 0],

    [0, 2, 0,   8, 0, 5,   0, 6, 0],
    [1, 0, 7,   0, 6, 0,   4, 0, 9],
    [0, 3, 0,   0, 0, 0,   0, 8, 0],
]

def p(board):
    for i in board:
        print(i)

def find(board):
    for row in range(9):
        for col in range(9):
            if board[row][col] == 0:
                return row, col
    return 1

def check_horizontal(board, row, number):
    for i in range(0, 9):
        if board[row][i] == number:
            return False
    return True

def check_vertical(board, col, number):
    for i in range(0, 9):
        if board[i][col] == number:
            return False
    return True

def check_sqaure(board, row, col, number):
    a = int(row / 3)
    b = int(col / 3)
    for i in range(a * 3, a * 3 + 3):
        for j in range(b * 3, b * 3 + 3):
            if board[i][j] == number:
                return False
    return True

def check_all(board, row, col, number):
    if check_horizontal(board, row, number) and check_vertical(board, col, number) and check_sqaure(board, row, col,number):
        return True

def play(board):
    if find(board) == 1:
        return 1
    row, col = find(board)
    for i in range(1, 10):
        if check_all(board, row, col, i):
            board[row][col] = i
            if play(board) == 1:
                return board
            else:
                if check_all(board, row, col,board[row][col] + 1):
                    board[row][col] = board[row][col] + 1
play(board)
p(board)

and this is the output:

[7, 9, 2, 3, 4, 8, 6, 1, 5]
[8, 5, 4, 6, 2, 0, 3, 0, 7]
[0, 6, 0, 9, 0, 7, 0, 2, 0]
[0, 0, 5, 0, 3, 0, 1, 0, 0]
[0, 7, 0, 5, 0, 1, 0, 3, 0]
[0, 0, 3, 0, 9, 0, 8, 0, 0]
[0, 2, 0, 8, 0, 5, 0, 6, 0]
[1, 0, 7, 0, 6, 0, 4, 0, 9]
[0, 3, 0, 0, 0, 0, 0, 8, 0]

The correct result would be:

    [7, 9, 2,   3, 5, 4,    6, 1, 8]
    [8, 5, 4,   1, 2, 6,    3, 9, 7]
    [3, 6, 1,   9, 8, 7,    5, 2, 4]

    [9, 4, 5,   6, 3, 8,    1, 7, 2]
    [2, 7, 8,   5, 4, 1,    9, 3, 6]
    [6, 1, 3,   7, 9, 2,    8, 4, 5]

    [4, 2, 9,   8, 1, 5,    7, 6, 3]
    [1, 8, 7,   2, 6, 3,    4, 5, 9]
    [5, 3, 6,   4, 7, 9,    2, 8, 1]

Body:
I see a couple issues with your play function.

The first issue is that you're not backtracking properly. Backtracking means you need to mark the space on the board you've been testing as unknown when you give up on the current partial solution. You currently have some strange code that tries to jump ahead if the recursion didn't find a solution. I think you should remove these lines:

else:
    if check_all(board, row, col,board[row][col] + 1):
        board[row][col] = board[row][col] + 1

Instead, you need to reset if the loop fails to find any solution. So put this at the end of the code, outside the loop:

board[row][col] = 0

The other issue is that you've got some mixed up logic about what the return value should be from play. In the base case, you're returning the sentinel value 1, and your later recursive code checks for this. But the later code will return board instead of the sentinel value if it thinks it got a solution from the recursion. You need to pick one of those and be consistent with it! The other side of this is that you're relying upon the default return value of None to indicate a failure when you fall off the end of the function. You should probably be explicit about that return value, by adding return None.

Here's how I'd do it, returning the board:

def play(board):
    if find(board) == 1:
        return board            # first change, return the board here!
    row, col = find(board)
    for i in range(1, 10):
        if check_all(board, row, col, i):
            board[row][col] = i
            if play(board) is not None: # second change, check for a non-None value, not == 1
                return board
    board[row][col] = 0         # third change, do proper backtracking (replaced three lines)
    return None                 # fourth change, be explicit about our return value on failure

There's still a small wart where you call find twice, but it doesn't make the code wrong, just a bit slower than necessary. You could improve it by changing the first few lines:

coords = find(board)
if coords == 1:
    return board
row, col = coords

I'd also prefer to use None as the sentinel for a failed find, but that's more an issue of taste than anything genuinely wrong or inefficient.


问:
Can someone explain me this while loop what means?
```<code>while (a = b)
   ;
</code>```

I know that it will probably not be anything so complex but I don't understand what it will become

答:
If b=0 then it will not an infinite loop. Otherwise, it will be an infinite loop.
Here, the value of b assigned in a. Hope you got it.</p>

Body:
while (a = b)
   ;

I know that it will probably not be anything so complex but I don't understand what it will become


问:
How to get the date value from DaterRangePicker?
I'm new to React and I've come across 'react suite' which I'm currently using for the DateRangePicker component.

However, I'm struggling to get the start date and end date in a format that is suitable. At the moment I can print in the console the object which looks like this:

Essentially what I would like to do is to print the date in the following format YYYY/MM/DD.

I can imagine that this is probably something straightforward to do, however, I'm struggling to find an appropriate way to do this so any help is appreciated!

My code:

```<code>handleSelect(range) {
        console.log(range)
    }

    render() {
        return (
            <div className="menu">
                <DateRangePicker
                    onChange = {this.handleSelect}
                />
            </div>
        )
    }
</code>```

答:
That library uses JavaScript Dates.

When stringified, e.g. because they are logged, they look the way you see them in the console.

You can either format it by hand, by accessing the components you're interested in via their getters, or use a more sophisticated library that does the heavy lifting for you, e.g. moment.js.

Body:
I'm new to React and I've come across 'react suite' which I'm currently using for the DateRangePicker component.

However, I'm struggling to get the start date and end date in a format that is suitable. At the moment I can print in the console the object which looks like this:

Essentially what I would like to do is to print the date in the following format YYYY/MM/DD.

I can imagine that this is probably something straightforward to do, however, I'm struggling to find an appropriate way to do this so any help is appreciated!

My code:

handleSelect(range) {
        console.log(range)
    }

    render() {
        return (

                <DateRangePicker
                    onChange = {this.handleSelect}
                />

        )
    }


问:
PHP array combinations
I have an array of 7 numbers (1,2,3,4,5,6,7) and I want to choose 5 of the numbers like

(1,2,3,4,5), (1,2,3,4,6), (1,2,3,4,7).

Note that (1,2,3,4,5) is equal to (4,5,3,1,2), so only one of those should be included in the output.

I would like to know if there is a function in PHP or any algorithm that can do this ?
I have no idea where to start from.
Can you help me ?

I want all the combinations of 7 given numbers ( they are taken from an array ) put into 5 slots, disregarding order.

答:
New solution which optimizes speed and memory for combining algorithm

Mindset: generate combinations K numbers of Array of numbers. New solution will use K 'for' statements. One 'for' One number.
Such as: $K = 5 mean that 5 of 'for' statements is used

```<code>$total = count($array);
$i0 = -1;
for ($i1 = $i0 + 1; $i1 < $total; $i1++) {
    for ($i2 = $i1 + 1; $i2 < $total; $i2++) {
        for ($i3 = $i2 + 1; $i3 < $total; $i3++) {
            for ($i4 = $i3 + 1; $i4 < $total; $i4++) {
                for ($i5 = $i4 + 1; $i5 < $total; $i5++) {
                    $record = array();
                    for ($i = 1; $i <= $k; $i++) {
                        $t = "i$i";
                        $record[] = $array[$$t];
                    }
                    $callback($record);
                }
            }
        }
    }
}
</code>```

And detail of code that generated the real code that will be execute by eval() function

```<code>function combine($array, $k, $callback)
{
    $total = count($array);
    $init = '
        $i0 = -1;
    ';
    $sample = '
        for($i{current} = $i{previous} + 1; $i{current} < $total; $i{current}++ ) {
            {body}
        }
    ';

    $do = '
        $record = array();
        for ($i = 1; $i <= $k; $i++) {
            $t = "i$i";
            $record[] = $array[$$t];
        }
        $callback($record);
    ';
    $for = '';
    for ($i = $k; $i >= 1; $i--) {
        switch ($i) {
            case $k:
                $for = str_replace(['{current}', '{previous}', '{body}'], [$i, $i - 1, $do], $sample);
                break;
            case 1:
                $for = $init . str_replace(['{current}', '{previous}', '{body}'], [$i, $i - 1, $for], $sample);
                break;
            default:
                $for = str_replace(['{current}', '{previous}', '{body}'], [$i, $i - 1, $for], $sample);
                break;
        }
    }

    // execute
    eval($for);
}
</code>```

How to combine K numbers of Array

```<code>$k = 5;
$array = array(1, 2, 3, 4, 5, 6, 7);
$callback = function ($record) {
    echo implode($record) . "\n";
};
combine($array, $k, $callback);
</code>```

Title: PHP array combinations

Body:
New solution which optimizes speed and memory for combining algorithm

Mindset: generate combinations K numbers of Array of numbers. New solution will use K 'for' statements. One 'for' One number.
Such as: $K = 5 mean that 5 of 'for' statements is used

$total = count($array);
$i0 = -1;
for ($i1 = $i0 + 1; $i1 < $total; $i1++) {
    for ($i2 = $i1 + 1; $i2 < $total; $i2++) {
        for ($i3 = $i2 + 1; $i3 < $total; $i3++) {
            for ($i4 = $i3 + 1; $i4 < $total; $i4++) {
                for ($i5 = $i4 + 1; $i5 < $total; $i5++) {
                    $record = array();
                    for ($i = 1; $i <= $k; $i++) {
                        $t = "i$i";
                        $record[] = $array[$$t];
                    }
                    $callback($record);
                }
            }
        }
    }
}

And detail of code that generated the real code that will be execute by eval() function

function combine($array, $k, $callback)
{
    $total = count($array);
    $init = '
        $i0 = -1;
    ';
    $sample = '
        for($i{current} = $i{previous} + 1; $i{current} < $total; $i{current}++ ) {
            {body}
        }
    ';

    $do = '
        $record = array();
        for ($i = 1; $i <= $k; $i++) {
            $t = "i$i";
            $record[] = $array[$$t];
        }
        $callback($record);
    ';
    $for = '';
    for ($i = $k; $i >= 1; $i--) {
        switch ($i) {
            case $k:
                $for = str_replace(['{current}', '{previous}', '{body}'], [$i, $i - 1, $do], $sample);
                break;
            case 1:
                $for = $init . str_replace(['{current}', '{previous}', '{body}'], [$i, $i - 1, $for], $sample);
                break;
            default:
                $for = str_replace(['{current}', '{previous}', '{body}'], [$i, $i - 1, $for], $sample);
                break;
        }
    }

    // execute
    eval($for);
}

How to combine K numbers of Array

$k = 5;
$array = array(1, 2, 3, 4, 5, 6, 7);
$callback = function ($record) {
    echo implode($record) . "\n";
};
combine($array, $k, $callback);


问:
Laravel - logging "route not found"
I do not see any log output when a route is not found.  I am running laravel in development mode and I can see this error when hitting a route that does not exist.

```<code>"message": "",
"exception":
"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
"file":
"/var/www/html/Customer_Interface/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php",
"line": 179,
</code>```

However, it does not show any activity storage/logs.  Is there anyway to catch this exception and log it there?

答:
Laravel by default doesn't report these:

//src/Illuminate/Foundation/Exceptions/Handler.php

/**
     * A list of the internal exception types that should not be reported.
     *
     * @var array
     */
    protected $internalDontReport = [
        AuthenticationException::class,
        AuthorizationException::class,
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        SuspiciousOperationException::class,
        TokenMismatchException::class,
        ValidationException::class,
    ];
```
<p>Now, you can in <code>app/Exceptions/Handler.php</code> you can have that array imported then remove the <code>HttpException</code> and <code>ModelNotFoundException</code>, or whichever Exception you want like so</p>
<pre class="lang-php prettyprint-override"><code>
    ...
    // app/Exceptions/Handler.php

    protected $internalDontReport = [
        AuthenticationException::class,
        AuthorizationException::class,
        // HttpException::class,
        HttpResponseException::class,
        // ModelNotFoundException::class,
        SuspiciousOperationException::class,
        TokenMismatchException::class,
        ValidationException::class,
    ];
    ...
</code>```

ModelNotFoundException is when you have a route like route::get('/articles/{article}','ArticleController@single');

and have that assigned in the controller as function single(Article $article) and $article is not found.

Pick what to keep and what to comment out.

Second approach is to do this in the report method in the same Handler.php file

 /**
     * Report or log an exception.
     *
     * @param \Exception $exception
     *
     * @return void
     * @throws Exception
     */
    public function report(Exception $exception)
    {

        # Report 404
        if ($exception instanceof NotFoundHttpException || $exception instanceof ModelNotFoundException) {
             # Log as warning
             Log::warning('Your message');
             # Or Log as info
             Log::info($exception);
             // ...
        }
        ....
     }
```

You can find more about loggin in this Laravel Logging
And Laravel Errors

Hope this answers your question!

Title: Laravel - logging "route not found"

Body:
I do not see any log output when a route is not found.  I am running laravel in development mode and I can see this error when hitting a route that does not exist.

"message": "",
"exception":
"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
"file":
"/var/www/html/Customer_Interface/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php",
"line": 179,

However, it does not show any activity storage/logs.  Is there anyway to catch this exception and log it there?

Body:
Laravel by default doesn't report these:

//src/Illuminate/Foundation/Exceptions/Handler.php

/**
     * A list of the internal exception types that should not be reported.
     *
     * @var array
     */
    protected $internalDontReport = [
        AuthenticationException::class,
        AuthorizationException::class,
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        SuspiciousOperationException::class,
        TokenMismatchException::class,
        ValidationException::class,
    ];

Now, you can in app/Exceptions/Handler.php you can have that array imported then remove the HttpException and ModelNotFoundException, or whichever Exception you want like so

    ...
    // app/Exceptions/Handler.php

    protected $internalDontReport = [
        AuthenticationException::class,
        AuthorizationException::class,
        // HttpException::class,
        HttpResponseException::class,
        // ModelNotFoundException::class,
        SuspiciousOperationException::class,
        TokenMismatchException::class,
        ValidationException::class,
    ];
    ...

ModelNotFoundException is when you have a route like route::get('/articles/{article}','ArticleController@single');

and have that assigned in the controller as function single(Article $article) and $article is not found.

Pick what to keep and what to comment out.

Second approach is to do this in the report method in the same Handler.php file

 /**
     * Report or log an exception.
     *
     * @param \Exception $exception
     *
     * @return void
     * @throws Exception
     */
    public function report(Exception $exception)
    {

        # Report 404
        if ($exception instanceof NotFoundHttpException || $exception instanceof ModelNotFoundException) {
             # Log as warning
             Log::warning('Your message');
             # Or Log as info
             Log::info($exception);
             // ...
        }
        ....
     }

You can find more about loggin in this Laravel Logging
And Laravel Errors

Hope this answers your question!


问:
Converting String array to java.util.List
How do I convert a String array to a java.util.List?

答:
```<code>List<String> strings = Arrays.asList(new String[]{"one", "two", "three"});
</code>```

This is a list view of the array, the list is partly unmodifiable, you can't add or delete elements. But the time complexity is O(1).

If you want a modifiable a List:

```<code>List<String> strings =
     new ArrayList<String>(Arrays.asList(new String[]{"one", "two", "three"}));
</code>```

This will copy all elements from the source array into a new list (complexity: O(n))

Body:
List<String> strings = Arrays.asList(new String[]{"one", "two", "three"});

This is a list view of the array, the list is partly unmodifiable, you can't add or delete elements. But the time complexity is O(1).

If you want a modifiable a List:

List<String> strings =
     new ArrayList<String>(Arrays.asList(new String[]{"one", "two", "three"}));

This will copy all elements from the source array into a new list (complexity: O(n))


问:
Spring Security for web service without roles and authorities
I have a REST web service built on Spring Boot. For authentication I use Spring Security and Basic Authentication and I am new to this. Do I have to use Roles and Authorities for my solution?

I only want the user of the web service to state user name and password credentials. I don't have any users in a database or elsewhere.

In my WebSecurityConfigurerAdapter configuration I now have .authorities("ROLE_USER"); in the end of my configureGlobal method, following examples on the internet. I would like to skip that so that the class would look like this:

```<code>@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("username").password(passwordEncoder().encode("password"));
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .anyRequest().authenticated().and().httpBasic();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
</code>```

I found I can not do that. I works if I use .roles("USER") instead. But I do not want to handle neither authorities nor roles, just a user name and a password.
Why do I need this or how can I skip this?

I am greatful for any light you can shed on this matter (authentication and Spring Security) to a novice.

答:
If you use inMemoryAuthentication you normally provide the roles via roles("...")

InMemoryAuthentication does not work with null as GrantedAuthorities. So not calling roles(...) causes an BeanCreationException

But nothing prevents you from providing an empty list...  like:

@Configuration
class SecurityConfig extends WebSecurityConfigurerAdapter {

    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("username")
                .password(passwordEncoder().encode("password"))
                .roles(); // <--- leave roles empty
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .anyRequest().authenticated().and().httpBasic();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
```

<p>Note: Don't think you need <code>@EnableWebSecurity</code> or use <code>configureGlobal</code> ...</p>

<hr>

<p>Or you can always choose to create your own custom AuthenticationProvider.</p>

<p>Configuration of a custom AuthenticationProvider:</p>

<pre class="lang-java prettyprint-override"><code>    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider());
    }

    @Bean
    public AuthenticationProvider authProvider() {
        return new CustomAuthenticationProvider();
    }

</code>```

Body:
I have a REST web service built on Spring Boot. For authentication I use Spring Security and Basic Authentication and I am new to this. Do I have to use Roles and Authorities for my solution?

I only want the user of the web service to state user name and password credentials. I don't have any users in a database or elsewhere.

In my WebSecurityConfigurerAdapter configuration I now have .authorities("ROLE_USER"); in the end of my configureGlobal method, following examples on the internet. I would like to skip that so that the class would look like this:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("username").password(passwordEncoder().encode("password"));
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .anyRequest().authenticated().and().httpBasic();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

I found I can not do that. I works if I use .roles("USER") instead. But I do not want to handle neither authorities nor roles, just a user name and a password.
Why do I need this or how can I skip this?

I am greatful for any light you can shed on this matter (authentication and Spring Security) to a novice.

Body:
If you use inMemoryAuthentication you normally provide the roles via roles("...")

InMemoryAuthentication does not work with null as GrantedAuthorities. So not calling roles(...) causes an BeanCreationException

But nothing prevents you from providing an empty list...  like:

@Configuration
class SecurityConfig extends WebSecurityConfigurerAdapter {

    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("username")
                .password(passwordEncoder().encode("password"))
                .roles(); // <--- leave roles empty
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .anyRequest().authenticated().and().httpBasic();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

Note: Don't think you need @EnableWebSecurity or use configureGlobal ...

Or you can always choose to create your own custom AuthenticationProvider.

Configuration of a custom AuthenticationProvider:

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider());
    }

    @Bean
    public AuthenticationProvider authProvider() {
        return new CustomAuthenticationProvider();
    }


问:
Organize numbers in group ascending
Sorry for the mess, I´ll start from the beginning. I want this tibble:

A tibble: 20 x 2

```<code>  ID NAME
   <dbl> <chr>
 1     1 aa
 2     1 bb
 3     1 cc
 4     2 dd
 5     2 ee
 6     2 ff
 7     3 gg
 8     3 hh
 9     3 ii
10     4 jj
11     4 kk
12     4 ll
13     5 mm
14     5 nn
15     5 oo
16     6 pp
17     7 qq
18     8 rr
19     9 ss
20    10 tt
</code>```

Organized in this manner:

A tibble: 20 x 2

```<code>  ID NAME
   <dbl> <chr>
 1     1 aa
 2     2 dd
 3     3 gg
 4     4 jj
 5     5 mm
 6     6 pp
 7     7 qq
 8     8 rr
 9     9 ss
10    10 tt
11     1 bb
12     2 ee
13     3 hh
14     4 kk
15     5 nn
16     1 cc
17     2 ff
18     3 hh
19     4 ll
20     5 oo
</code>```

That is the first '1' followed by the first '2' and so on..

Thanks for all answers but I think my example was perhaps a bit misleading.

Best regards,

H

答:
Here, the 'NAME' seems to be ordered in a specific order.  In that case, convert to factor, with levels specified in that custom order and pass it on to arrange and then do the order with 'ID'

```<code>library(dplyr)
df1 %>%
    arrange(factor(NAME, levels = c("xx", "zz", "yy")), ID)
#   ID NAME
#1   1   xx
#2   2   xx
#3   3   xx
#4   4   xx
#5   5   xx
#6   6   xx
#7   7   xx
#8   8   xx
#9   9   xx
#10 10   xx
#11  1   zz
#12  2   zz
#13  3   zz
#14  4   zz
#15  5   zz
#16  1   yy
#17  2   yy
#18  3   yy
#19  4   yy
#20  5   yy
</code>```

Or as per @zx8574 post, if it is the order of occurrence of values in 'NAME', either use the factor approach mentioned in his post or another way is match

```<code>df1 %>%
     arrange(match(NAME, unique(NAME)), ID)
</code>```

Update

Based on the updated data, we could reorder based on the sequence grouped by 'ID'

```<code>library(data.table)
df2 %>%
     arrange(rowid(ID))
#   ID NAME
#1   1   aa
#2   2   dd
#3   3   gg
#4   4   jj
#5   5   mm
#6   6   pp
#7   7   qq
#8   8   rr
#9   9   ss
#10 10   tt
#11  1   bb
#12  2   ee
#13  3   hh
#14  4   kk
#15  5   nn
#16  1   cc
#17  2   ff
#18  3   ii
#19  4   ll
#20  5   oo
</code>```

Or using data.table

```<code>setDT(df2)[order(rowid(ID))]
</code>```

data

```<code>df1 <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L,
4L, 4L, 5L, 5L, 5L, 6L, 7L, 8L, 9L, 10L), NAME = c("xx", "zz",
"yy", "xx", "zz", "yy", "xx", "zz", "yy", "xx", "zz", "yy", "xx",
"zz", "yy", "xx", "xx", "xx", "xx", "xx")), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20"))

df2 <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L,
4L, 4L, 5L, 5L, 5L, 6L, 7L, 8L, 9L, 10L), NAME = c("aa", "bb",
"cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj", "kk", "ll", "mm",
"nn", "oo", "pp", "qq", "rr", "ss", "tt")), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20"))
</code>```

Title: Organize numbers in group ascending

Body:
Sorry for the mess, I´ll start from the beginning. I want this tibble:

A tibble: 20 x 2

  ID NAME
   <dbl> <chr>
 1     1 aa
 2     1 bb
 3     1 cc
 4     2 dd
 5     2 ee
 6     2 ff
 7     3 gg
 8     3 hh
 9     3 ii
10     4 jj
11     4 kk
12     4 ll
13     5 mm
14     5 nn
15     5 oo
16     6 pp
17     7 qq
18     8 rr
19     9 ss
20    10 tt

Organized in this manner:

A tibble: 20 x 2

  ID NAME
   <dbl> <chr>
 1     1 aa
 2     2 dd
 3     3 gg
 4     4 jj
 5     5 mm
 6     6 pp
 7     7 qq
 8     8 rr
 9     9 ss
10    10 tt
11     1 bb
12     2 ee
13     3 hh
14     4 kk
15     5 nn
16     1 cc
17     2 ff
18     3 hh
19     4 ll
20     5 oo

That is the first '1' followed by the first '2' and so on..

Thanks for all answers but I think my example was perhaps a bit misleading.

Best regards,

H

Body:
Here, the 'NAME' seems to be ordered in a specific order.  In that case, convert to factor, with levels specified in that custom order and pass it on to arrange and then do the order with 'ID'

library(dplyr)
df1 %>%
    arrange(factor(NAME, levels = c("xx", "zz", "yy")), ID)
#   ID NAME
#1   1   xx
#2   2   xx
#3   3   xx
#4   4   xx
#5   5   xx
#6   6   xx
#7   7   xx
#8   8   xx
#9   9   xx
#10 10   xx
#11  1   zz
#12  2   zz
#13  3   zz
#14  4   zz
#15  5   zz
#16  1   yy
#17  2   yy
#18  3   yy
#19  4   yy
#20  5   yy

Or as per @zx8574 post, if it is the order of occurrence of values in 'NAME', either use the factor approach mentioned in his post or another way is match

df1 %>%
     arrange(match(NAME, unique(NAME)), ID)

Update

Based on the updated data, we could reorder based on the sequence grouped by 'ID'

library(data.table)
df2 %>%
     arrange(rowid(ID))
#   ID NAME
#1   1   aa
#2   2   dd
#3   3   gg
#4   4   jj
#5   5   mm
#6   6   pp
#7   7   qq
#8   8   rr
#9   9   ss
#10 10   tt
#11  1   bb
#12  2   ee
#13  3   hh
#14  4   kk
#15  5   nn
#16  1   cc
#17  2   ff
#18  3   ii
#19  4   ll
#20  5   oo

Or using data.table

setDT(df2)[order(rowid(ID))]

data

df1 <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L,
4L, 4L, 5L, 5L, 5L, 6L, 7L, 8L, 9L, 10L), NAME = c("xx", "zz",
"yy", "xx", "zz", "yy", "xx", "zz", "yy", "xx", "zz", "yy", "xx",
"zz", "yy", "xx", "xx", "xx", "xx", "xx")), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20"))

df2 <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L,
4L, 4L, 5L, 5L, 5L, 6L, 7L, 8L, 9L, 10L), NAME = c("aa", "bb",
"cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj", "kk", "ll", "mm",
"nn", "oo", "pp", "qq", "rr", "ss", "tt")), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20"))


问:
Get currently pressed keys in inspector
I am currently building a simple shortcuts system for my Unity project.

At the moment I am inserting the shortcuts in the inspector by string, for example: "Control+Alt+A". but writing it every time is too annoying.

So I thought about creating a custom editor for it, where the textbox would be filled automatically with the keys the user presses. Unfortunately the only way I found about getting this info is with the OnSceneGUI function, but it requires the scene window to have focus, and if the shortcut is defined in Unity it would fire.

To sum up, How can I read the currently pressed keys and display them with an editor script¿

Edit: this link almost does what I need, but it detects only one key (no combinations), and the Shift key isn't detected at all

答:
Depends a lot on how you store and check the hotkeys later but you could create a custom EditorWindow pop-up.

First I would store my shortcut e.g. like

```<code>[Serializable]
public struct ShortCut
{
    public bool Ctrl;
    public bool Alt;
    public bool Shift;

    public KeyCode Key;

    public ShortCut(KeyCode key, bool ctrl, bool alt, bool shift)
    {
        Key = key;
        Ctrl = ctrl;
        Alt = alt;
        Shift = shift;
    }

    public override string ToString()
    {
        var builder = new StringBuilder();
        if (Ctrl) builder.Append("CTRL + ");
        if (Alt) builder.Append("ALT + ");
        if (Shift) builder.Append("SHIFT + ");

        builder.Append(Key.ToString());

        return builder.ToString();
    }

    public bool IsDown => IsCtrlDown && IsAltDown && IsShiftDown && Input.GetKeyDown(Key);

    private bool IsCtrlDown => !Ctrl || Input.GetKey(KeyCode.RightControl) || Input.GetKey(KeyCode.LeftControl);
    private bool IsAltDown => !Alt || Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt);
    private bool IsShiftDown => !Shift || Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);
}
</code>```

You can wait for it in a script like e.g.

```<code>public class ShortCutTester : MonoBehaviour
{
    // This youc an now call via the context menu of the someShortCut field in the Inspector
    [ContextMenuItem("Set Shortcut", nameof(SetSomeShortCut))]
    public ShortCut someShortCut;

    private void SetSomeShortCut()
    {
        ShortKeyDialog.ShowDialog(someShortCut, result =>
        {
            // mark as dirty and provide undo/redo funcztionality
            Undo.RecordObject(this, "Change someShortCut");
            someShortCut = result;
        });
    }

    private void Update()
    {
        if (someShortCut.IsDown)
        {
            Debug.Log("Hello!");
        }
    }

    #if UNITY_EDITOR
    // in order to catch all editor own key events on runtime
    // you will still get the warning "You have to exit playmode in order to save"
    // but at least this makes the Hello print anyway. Couldn't figure out how to catch the key completely before Unity handles it
    private void OnGUI()
    {
        var e = Event.current;
        e.Use();
    }
    #endif
}
</code>```

and set it via a popup dialog

```<code>public class ShortKeyDialog : EditorWindow
{
    private ShortCut keys;
    private ShortCut newKeys;
    private Action<ShortCut> callback;
    private bool changed;

    public static void ShowDialog( ShortCut currentShortcut, Action<ShortCut> onDone)
    {
        var dialog = GetWindow<ShortKeyDialog>();
        dialog.keys = currentShortcut;
        dialog.newKeys = currentShortcut;
        dialog.callback = onDone;
        dialog.minSize = new Vector2(300, 200);
        dialog.position = new Rect(Screen.width / 2f + 150, Screen.height / 2f + 100, 300, 200);
        dialog.ShowModalUtility();
    }

    private void OnGUI()
    {
        //Get pressed keys
        var e = Event.current;
        if (e?.isKey == true)
        {
            switch (e.type)
            {
                case EventType.KeyDown:
                    switch (e.keyCode)
                    {
                        // Here you will need all allowed keycodes
                        case KeyCode.A:
                        case KeyCode.B:
                        case KeyCode.C:
                        case KeyCode.D:
                        case KeyCode.E:
                        case KeyCode.F:
                        case KeyCode.G:
                        case KeyCode.H:
                        case KeyCode.I:
                        case KeyCode.J:
                        case KeyCode.K:
                        case KeyCode.L:
                        case KeyCode.M:
                        case KeyCode.N:
                        case KeyCode.O:
                        case KeyCode.P:
                        case KeyCode.Q:
                        case KeyCode.R:
                        case KeyCode.S:
                        case KeyCode.T:
                        case KeyCode.U:
                        case KeyCode.V:
                        case KeyCode.W:
                        case KeyCode.X:
                        case KeyCode.Y:
                        case KeyCode.Z:
                        case KeyCode.F1:
                        case KeyCode.F2:
                        case KeyCode.F3:
                        case KeyCode.F4:
                        case KeyCode.F5:
                        case KeyCode.F6:
                        case KeyCode.F7:
                        case KeyCode.F8:
                        case KeyCode.F9:
                        case KeyCode.F10:
                        case KeyCode.F11:
                        case KeyCode.F12:
                        case KeyCode.F13:
                        case KeyCode.F14:
                        case KeyCode.F15:
                        case KeyCode.Comma:
                        case KeyCode.Plus:
                        case KeyCode.Minus:
                        case KeyCode.Period:
                            // etc depends on your needs I guess
                            changed = true;
                            newKeys = new ShortCut (e.keyCode, e.control, e.alt, e.shift);

                            // Refresh the EditorWindow
                            Repaint();
                            break;
                    }
                    break;
            }

            // Use all key presses so nothing else handles them
            // e.g. also not the Unity editor itself like e.g. for CTRL + S
            e.Use();
        }

        EditorGUILayout.LabelField("Current Shortcut");
        EditorGUILayout.HelpBox(keys.ToString(), MessageType.None);

        EditorGUILayout.Space();

        EditorGUILayout.LabelField("Press buttons to assign a new shortcut", EditorStyles.textArea);

        EditorGUILayout.HelpBox(newKeys.ToString(), MessageType.None);

        EditorGUILayout.Space();

        EditorGUILayout.BeginHorizontal();
        {
            if (GUILayout.Button("Cancel"))
            {
                Close();
            }
            EditorGUI.BeginDisabledGroup(!changed);
            {
                if (GUILayout.Button("Save"))
                {
                    callback?.Invoke(newKeys);
                    Close();
                }
            }
            EditorGUI.EndDisabledGroup();
        }
        EditorGUILayout.EndHorizontal();
    }
}
</code>```

Please note: Typed on smartphone so no chance to test and correct things currently but I hope the idea gets clear

Will test and update asap when back on a PC

Title: Get currently pressed keys in inspector

Body:
Depends a lot on how you store and check the hotkeys later but you could create a custom EditorWindow pop-up.

First I would store my shortcut e.g. like

[Serializable]
public struct ShortCut
{
    public bool Ctrl;
    public bool Alt;
    public bool Shift;

    public KeyCode Key;

    public ShortCut(KeyCode key, bool ctrl, bool alt, bool shift)
    {
        Key = key;
        Ctrl = ctrl;
        Alt = alt;
        Shift = shift;
    }

    public override string ToString()
    {
        var builder = new StringBuilder();
        if (Ctrl) builder.Append("CTRL + ");
        if (Alt) builder.Append("ALT + ");
        if (Shift) builder.Append("SHIFT + ");

        builder.Append(Key.ToString());

        return builder.ToString();
    }

    public bool IsDown => IsCtrlDown && IsAltDown && IsShiftDown && Input.GetKeyDown(Key);

    private bool IsCtrlDown => !Ctrl || Input.GetKey(KeyCode.RightControl) || Input.GetKey(KeyCode.LeftControl);
    private bool IsAltDown => !Alt || Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt);
    private bool IsShiftDown => !Shift || Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);
}

You can wait for it in a script like e.g.

public class ShortCutTester : MonoBehaviour
{
    // This youc an now call via the context menu of the someShortCut field in the Inspector
    [ContextMenuItem("Set Shortcut", nameof(SetSomeShortCut))]
    public ShortCut someShortCut;

    private void SetSomeShortCut()
    {
        ShortKeyDialog.ShowDialog(someShortCut, result =>
        {
            // mark as dirty and provide undo/redo funcztionality
            Undo.RecordObject(this, "Change someShortCut");
            someShortCut = result;
        });
    }

    private void Update()
    {
        if (someShortCut.IsDown)
        {
            Debug.Log("Hello!");
        }
    }

    #if UNITY_EDITOR
    // in order to catch all editor own key events on runtime
    // you will still get the warning "You have to exit playmode in order to save"
    // but at least this makes the Hello print anyway. Couldn't figure out how to catch the key completely before Unity handles it
    private void OnGUI()
    {
        var e = Event.current;
        e.Use();
    }
    #endif
}

and set it via a popup dialog

public class ShortKeyDialog : EditorWindow
{
    private ShortCut keys;
    private ShortCut newKeys;
    private Action<ShortCut> callback;
    private bool changed;

    public static void ShowDialog( ShortCut currentShortcut, Action<ShortCut> onDone)
    {
        var dialog = GetWindow<ShortKeyDialog>();
        dialog.keys = currentShortcut;
        dialog.newKeys = currentShortcut;
        dialog.callback = onDone;
        dialog.minSize = new Vector2(300, 200);
        dialog.position = new Rect(Screen.width / 2f + 150, Screen.height / 2f + 100, 300, 200);
        dialog.ShowModalUtility();
    }

    private void OnGUI()
    {
        //Get pressed keys
        var e = Event.current;
        if (e?.isKey == true)
        {
            switch (e.type)
            {
                case EventType.KeyDown:
                    switch (e.keyCode)
                    {
                        // Here you will need all allowed keycodes
                        case KeyCode.A:
                        case KeyCode.B:
                        case KeyCode.C:
                        case KeyCode.D:
                        case KeyCode.E:
                        case KeyCode.F:
                        case KeyCode.G:
                        case KeyCode.H:
                        case KeyCode.I:
                        case KeyCode.J:
                        case KeyCode.K:
                        case KeyCode.L:
                        case KeyCode.M:
                        case KeyCode.N:
                        case KeyCode.O:
                        case KeyCode.P:
                        case KeyCode.Q:
                        case KeyCode.R:
                        case KeyCode.S:
                        case KeyCode.T:
                        case KeyCode.U:
                        case KeyCode.V:
                        case KeyCode.W:
                        case KeyCode.X:
                        case KeyCode.Y:
                        case KeyCode.Z:
                        case KeyCode.F1:
                        case KeyCode.F2:
                        case KeyCode.F3:
                        case KeyCode.F4:
                        case KeyCode.F5:
                        case KeyCode.F6:
                        case KeyCode.F7:
                        case KeyCode.F8:
                        case KeyCode.F9:
                        case KeyCode.F10:
                        case KeyCode.F11:
                        case KeyCode.F12:
                        case KeyCode.F13:
                        case KeyCode.F14:
                        case KeyCode.F15:
                        case KeyCode.Comma:
                        case KeyCode.Plus:
                        case KeyCode.Minus:
                        case KeyCode.Period:
                            // etc depends on your needs I guess
                            changed = true;
                            newKeys = new ShortCut (e.keyCode, e.control, e.alt, e.shift);

                            // Refresh the EditorWindow
                            Repaint();
                            break;
                    }
                    break;
            }

            // Use all key presses so nothing else handles them
            // e.g. also not the Unity editor itself like e.g. for CTRL + S
            e.Use();
        }

        EditorGUILayout.LabelField("Current Shortcut");
        EditorGUILayout.HelpBox(keys.ToString(), MessageType.None);

        EditorGUILayout.Space();

        EditorGUILayout.LabelField("Press buttons to assign a new shortcut", EditorStyles.textArea);

        EditorGUILayout.HelpBox(newKeys.ToString(), MessageType.None);

        EditorGUILayout.Space();

        EditorGUILayout.BeginHorizontal();
        {
            if (GUILayout.Button("Cancel"))
            {
                Close();
            }
            EditorGUI.BeginDisabledGroup(!changed);
            {
                if (GUILayout.Button("Save"))
                {
                    callback?.Invoke(newKeys);
                    Close();
                }
            }
            EditorGUI.EndDisabledGroup();
        }
        EditorGUILayout.EndHorizontal();
    }
}

Please note: Typed on smartphone so no chance to test and correct things currently but I hope the idea gets clear

Will test and update asap when back on a PC


问:
How to unzip a file in Ruby on Rails?
I'm uploading a file to the server in Ruby on Rails

Normally, it's a text file and I save it in the model as a 'file' field in a Submission ActiveRecord with other fields such as title of submission.. etc.

However, the user can also submit a zip file. In this case the zipfile should unzipped and for each file in the zip a new Submission should be created with the same text fields, but current file.

How can I accomplish this?

I looked at unzip examples on the net, but most use a directory to unzip the files to. I'm not sure if I need that as in the current create method of SubmissionsController, a file object is received and I presume the path to save the file to is automatically generated when the Submission save method is called. So I was thinking that maybe I should unzip the zipfile in memory to get an array of file objects and then create a new Submission with each file object but same fields and then let ActiveRecord generate the file paths for each one when it saves them to the database.
I might be wrong here, because I'm kind of new to Rails and Ruby.

答:
Worked for me:

```<code>gem install rubyzip
</code>```

main.rb

require 'zip'

def extract_zip(file, destination)
  FileUtils.mkdir_p(destination)

  Zip::File.open(file) do |zip_file|
    zip_file.each do |f|
      fpath = File.join(destination, f.name)
      FileUtils.mkdir_p(File.dirname(fpath))
      zip_file.extract(f, fpath) unless File.exist?(fpath)
    end
  end
end

extract_zip('file.zip', 'tmp')
```

Title: How to unzip a file in Ruby on Rails?

Body:
Worked for me:

gem install rubyzip

main.rb

require 'zip'

def extract_zip(file, destination)
  FileUtils.mkdir_p(destination)

  Zip::File.open(file) do |zip_file|
    zip_file.each do |f|
      fpath = File.join(destination, f.name)
      FileUtils.mkdir_p(File.dirname(fpath))
      zip_file.extract(f, fpath) unless File.exist?(fpath)
    end
  end
end

extract_zip('file.zip', 'tmp')


问:
PHP: How to loop and skip over database tables without corresponding data in another table?
I'm relatively new to PHP and still learning, and I recognize that this is a rookie question, but I'd love and appreciate any help that you can provide.

I'm currently working on coding a website that uses PHP and MySQL to pull and organize data from both a "courses" and "categories" database table.  Each row in the "courses" table is associated with a particular course category through the column "category_id," which is linked to the relevant "id" column in the "categories" table.

So, for example, if category 3 in the "categories" table is "Music" and a particular course is on music, that course's "category_id" column value will be set to "3" in the "courses" table. (I hope that I explained all of that appropriately; my apologies if it's unclear).

I'd like to display all of the course category names that currently contain courses, and also display all of the course names within each of those categories underneath each category name.  So, for example:

Music: (1) Rock, (2) Jazz

Painting: (1) Watercolor, (2) Acrylic

Here is the code that I'm using to do this.  I'm using an MVC framework in which I've passed all of the data from both the "courses" and "categories" tables into this view as the associative arrays $categories and $courses.

```<code><?php foreach ($categories as $category) : ?>

    <h4><?php echo ($category['name']); ?></h4>

    <?php foreach ($courses as $course) {

        if ($course['category_id'] == $category['id']) : ?>
            <p><?php echo ($course['name']); ?></p>
        <?php endif;
    }

endforeach; ?>
</code>```

The problem that I'm running into is that I have category rows in my "categories" table for which I don't currently yet have any corresponding courses in the "courses" table.  As I build out the website, this will change, but for now and for organization sake I don't want to delete those rows from the "categories" table.

So now, given the above code, I'm outputting a list of categories and courses that looks like this:

Dance:

Sculpture:

Music: (1) Rock, (2) Jazz

Painting: (1) Watercolor, (2) Acrylic

So finally, my question: how would I go about looping through each of the categories, and only displaying the category name if there are corresponding courses associated with that category_id in the "courses" table? (In reference to the example above, to skip over and not display the "Dance" and "Sculpture" categories because there aren't yet any courses associated with those categories).

Again, my apologies if anything above is unclear, and I very much appreciate anyone's help!

Best,
Josh

答:
you can use something like this to select categories only with record in courses

```<code>select * from categories inner join courses where categories.id=courses.category_id group by categories.id
</code>```

for better understanding
https://www.w3schools.com/sql/sql_join_inner.asp

Body:
I'm relatively new to PHP and still learning, and I recognize that this is a rookie question, but I'd love and appreciate any help that you can provide.

I'm currently working on coding a website that uses PHP and MySQL to pull and organize data from both a "courses" and "categories" database table.  Each row in the "courses" table is associated with a particular course category through the column "category_id," which is linked to the relevant "id" column in the "categories" table.

So, for example, if category 3 in the "categories" table is "Music" and a particular course is on music, that course's "category_id" column value will be set to "3" in the "courses" table. (I hope that I explained all of that appropriately; my apologies if it's unclear).

I'd like to display all of the course category names that currently contain courses, and also display all of the course names within each of those categories underneath each category name.  So, for example:

Music: (1) Rock, (2) Jazz

Painting: (1) Watercolor, (2) Acrylic

Here is the code that I'm using to do this.  I'm using an MVC framework in which I've passed all of the data from both the "courses" and "categories" tables into this view as the associative arrays $categories and $courses.

<?php foreach ($categories as $category) : ?>

<?php echo ($category['name']); ?>

    <?php foreach ($courses as $course) {

        if ($course['category_id'] == $category['id']) : ?>

<?php echo ($course['name']); ?>

        <?php endif;
    }

endforeach; ?>

The problem that I'm running into is that I have category rows in my "categories" table for which I don't currently yet have any corresponding courses in the "courses" table.  As I build out the website, this will change, but for now and for organization sake I don't want to delete those rows from the "categories" table.

So now, given the above code, I'm outputting a list of categories and courses that looks like this:

Dance:

Sculpture:

Music: (1) Rock, (2) Jazz

Painting: (1) Watercolor, (2) Acrylic

So finally, my question: how would I go about looping through each of the categories, and only displaying the category name if there are corresponding courses associated with that category_id in the "courses" table? (In reference to the example above, to skip over and not display the "Dance" and "Sculpture" categories because there aren't yet any courses associated with those categories).

Again, my apologies if anything above is unclear, and I very much appreciate anyone's help!

Best,
Josh

Body:
you can use something like this to select categories only with record in courses

select * from categories inner join courses where categories.id=courses.category_id group by categories.id

for better understanding
https://www.w3schools.com/sql/sql_join_inner.asp


问:
How to copy/write particular row using apache poi
I know i am missing the main function here. I want to copy/ write only particular row from my source excel to destination excel using apache POI.

eg. My source excel has 10 rows. I need only 5th row to be copied to my destination excel.

My class,

```<code>public class Test1 {
    public static void main(String[] args) throws Exception{
        File srcFile=new File("C:\\Test\\Read.xlsx");
        FileInputStream fis=new FileInputStream(srcFile);

        XSSFWorkbook wb=new XSSFWorkbook(fis);
        XSSFSheet sheet1=wb.getSheetAt(0);

        File desFile=new File("C:\\Test\\Write.xlsx");
        FileOutputStream fout=new FileOutputStream(desFile);

        wb.write(fout);

        wb.close();
    }
}
</code>```

答:
As per the Apache POI docs, you can use the XSSFSheet.getRow(int) method to get a row at a specific index.

```<code>// 5th row
Row row = sheet.getRow(4);
</code>```

To add this row to a new workbook, you'll have to iterate through each cell in the row object and set the value of cells in the new workbook to these values. An example can be found here.

Body:
I know i am missing the main function here. I want to copy/ write only particular row from my source excel to destination excel using apache POI.

eg. My source excel has 10 rows. I need only 5th row to be copied to my destination excel.

My class,

public class Test1 {
    public static void main(String[] args) throws Exception{
        File srcFile=new File("C:\\Test\\Read.xlsx");
        FileInputStream fis=new FileInputStream(srcFile);

        XSSFWorkbook wb=new XSSFWorkbook(fis);
        XSSFSheet sheet1=wb.getSheetAt(0);

        File desFile=new File("C:\\Test\\Write.xlsx");
        FileOutputStream fout=new FileOutputStream(desFile);

        wb.write(fout);

        wb.close();
    }
}

Body:
As per the Apache POI docs, you can use the XSSFSheet.getRow(int) method to get a row at a specific index.

// 5th row
Row row = sheet.getRow(4);

To add this row to a new workbook, you'll have to iterate through each cell in the row object and set the value of cells in the new workbook to these values. An example can be found here.


问:
React JS with Redux: How to pass e.target.value from one component to another
I have an input select that generated a value using an onChange method. However, I am trying to pass the selected value from this component to another component. This is how my code looks like now:

```<code> <Input type="select" name="selectInput" value={this.state.completeTask} onChange=.
 {this.handleChangeCompleteTask} >
        <option value="" disabled> Select Reason</option>
        <option value="Task Completed"> Task Completed</option>
        <option value="Task in Progress"> Task in Progress</option>
 </Input>
</code>```

The handleChangeCompleteTask is:

```<code>handleChangeCompleteTask = (e) => {
    this.setState({ completeTask: e.target.value });
};
</code>```

I also have an initial state for completeTask as:

```<code>   state = {
        completeTask: ''
    };
</code>```

The question is how can I pass completeTask current state as in this.state.nonCompletionReason and pass it to a different function in a different component.

The other component has a function that handles tasks as in:

```<code>handleTasks = (tasks) => {
 this.props.tasks(tasks)
}
</code>```

I would like to pass the

答: You will want to pass state.completeTask into the props of the other component like this: <OtherComponent completeTask={this.state.completeTask} />. Then the OtherComponent will have access via this.props.completeTask.

Body:
I have an input select that generated a value using an onChange method. However, I am trying to pass the selected value from this component to another component. This is how my code looks like now:

 <Input type="select" name="selectInput" value={this.state.completeTask} onChange=.
 {this.handleChangeCompleteTask} >
        <option value="" disabled> Select Reason</option>
        <option value="Task Completed"> Task Completed</option>
        <option value="Task in Progress"> Task in Progress</option>
 </Input>

The handleChangeCompleteTask is:

handleChangeCompleteTask = (e) => {
    this.setState({ completeTask: e.target.value });
};

I also have an initial state for completeTask as:

   state = {
        completeTask: ''
    };

The question is how can I pass completeTask current state as in this.state.nonCompletionReason and pass it to a different function in a different component.

The other component has a function that handles tasks as in:

handleTasks = (tasks) => {
 this.props.tasks(tasks)
}

I would like to pass the


问:
How to convert a .pptx to .pdf using Python
I have been looking  to convert a .pptx file to a .pdf file through a Python script for several hours but nothing seems to be working.

What I have tried: I have tried 1) this script which calls windows32.client, and 2) unoconv, but none of them seem to be working for me.

Problems encountered: Using script from first option throws up an error (com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024894), None)), whereas in second option Python can't seem to recognize unoconv even after installing it using pip.

I also saw some recommended Pandoc, but I can't understand how to use it for Python.

Versions I am using: Python 2.7.9, Windows 8.1

答:
I was working with this solution but I needed to search all .pptx, .ppt,  and then turn them all to .pdf (python 3.7.5). Hope it works...

```<code>import os
import win32com.client

ppttoPDF = 32

for root, dirs, files in os.walk(r'your directory here'):
    for f in files:

        if f.endswith(".pptx"):
            try:
                print(f)
                in_file=os.path.join(root,f)
                powerpoint = win32com.client.Dispatch("Powerpoint.Application")
                deck = powerpoint.Presentations.Open(in_file)
                deck.SaveAs(os.path.join(root,f[:-5]), ppttoPDF) # formatType = 32 for ppt to pdf
                deck.Close()
                powerpoint.Quit()
                print('done')
                os.remove(os.path.join(root,f))
                pass
            except:
                print('could not open')
                # os.remove(os.path.join(root,f))
        elif f.endswith(".ppt"):
            try:
                print(f)
                in_file=os.path.join(root,f)
                powerpoint = win32com.client.Dispatch("Powerpoint.Application")
                deck = powerpoint.Presentations.Open(in_file)
                deck.SaveAs(os.path.join(root,f[:-4]), ppttoPDF) # formatType = 32 for ppt to pdf
                deck.Close()
                powerpoint.Quit()
                print('done')
                os.remove(os.path.join(root,f))
                pass
            except:
                print('could not open')
                # os.remove(os.path.join(root,f))
        else:
            pass
</code>```

The try and except was for those documents I couldn't read and won't exit the code until the last document. And I would recommend doing each type of format aside: first .pptx and then .ppt (or viceversa).

Body:
I was working with this solution but I needed to search all .pptx, .ppt,  and then turn them all to .pdf (python 3.7.5). Hope it works...

import os
import win32com.client

ppttoPDF = 32

for root, dirs, files in os.walk(r'your directory here'):
    for f in files:

        if f.endswith(".pptx"):
            try:
                print(f)
                in_file=os.path.join(root,f)
                powerpoint = win32com.client.Dispatch("Powerpoint.Application")
                deck = powerpoint.Presentations.Open(in_file)
                deck.SaveAs(os.path.join(root,f[:-5]), ppttoPDF) # formatType = 32 for ppt to pdf
                deck.Close()
                powerpoint.Quit()
                print('done')
                os.remove(os.path.join(root,f))
                pass
            except:
                print('could not open')
                # os.remove(os.path.join(root,f))
        elif f.endswith(".ppt"):
            try:
                print(f)
                in_file=os.path.join(root,f)
                powerpoint = win32com.client.Dispatch("Powerpoint.Application")
                deck = powerpoint.Presentations.Open(in_file)
                deck.SaveAs(os.path.join(root,f[:-4]), ppttoPDF) # formatType = 32 for ppt to pdf
                deck.Close()
                powerpoint.Quit()
                print('done')
                os.remove(os.path.join(root,f))
                pass
            except:
                print('could not open')
                # os.remove(os.path.join(root,f))
        else:
            pass

The try and except was for those documents I couldn't read and won't exit the code until the last document. And I would recommend doing each type of format aside: first .pptx and then .ppt (or viceversa).


问:
Duplicate lines of code consecutively with Pycharm
I am currently creating a script which has approximately 100 lines of code. Within PyCharm, I am interested in duplicating each line of code consecutively throughout the script. An example demonstrating the desired output is shown below.

```<code># Current Code

print("Hello World")
print("I enjoy python")
print("Stack Overflow is amazing")

# Desired Output

print("Hello World")
print("Hello World")
print("Hello World")
print("I enjoy python")
print("I enjoy python")
print("I enjoy python")
print("Stack Overflow is amazing")
print("Stack Overflow is amazing")
print("Stack Overflow is amazing")
</code>```

As this is only a sample with 3 original lines of code, I simply created duplicates of the code by copying and pasting each line. In projects which contain over 100 lines of code, this would be impractical. How can I do this in PyCharm without copying and pasting line by line?

-Thanks

答:
If you want to do it in PyCharm you can use regex replace:

^(.*)$ replace by $1\n$1\n$1:

But if you wont to do it using python script you can do something like this:

with open('input.py') as f_input:
    with open('output.py', 'w') as f_output:
        f_output.writelines(sum([[x] * 3 for x in f_input], []))
```

Body:
I am currently creating a script which has approximately 100 lines of code. Within PyCharm, I am interested in duplicating each line of code consecutively throughout the script. An example demonstrating the desired output is shown below.

# Current Code

print("Hello World")
print("I enjoy python")
print("Stack Overflow is amazing")

# Desired Output

print("Hello World")
print("Hello World")
print("Hello World")
print("I enjoy python")
print("I enjoy python")
print("I enjoy python")
print("Stack Overflow is amazing")
print("Stack Overflow is amazing")
print("Stack Overflow is amazing")

As this is only a sample with 3 original lines of code, I simply created duplicates of the code by copying and pasting each line. In projects which contain over 100 lines of code, this would be impractical. How can I do this in PyCharm without copying and pasting line by line?

-Thanks