问:
Generate QRCode without Windows-1252
Hi I using to generate QR code BaconQrCode. I have problem with gereate QR code to Google Authenticator.

To generate QR code I use: GoogleAuthenticator

BaconQrCode generate QR code with characters for example:

otpauth%3A%2F%2Ftotp%2FLaravel%3Fsecret%3D3DNLF33LLMG7SN2XXX%26issuer%3Dname.surname%2540mydomain.com

I check and work in Google Authenticator this code:

otpauth://totp/Laravel?secret=3DNLF33LLMG7SN2XXX&issuer=name.surname%40mydomain.com

答:
I change fucntion getQRCodeGoogleUrl:

```<code>public function getQRCodeGoogleUrl($name, $secret, $title = null, $params = array())
{
    $level = !empty($params['level']) && array_search($params['level'], array('L', 'M', 'Q', 'H')) !== false ? $params['level'] : 'M';
    if ($title !== null) {
        $getTitle = $title;
    }
    $urlencoded = "otpauth://totp/$name?secret=$secret&issuer=$getTitle&ecc=$level";
    return $urlencoded;
}
</code>```

and the I use BaconQrCodeGenerator:

```<code>$google_qrCodeUrl = $this->getQRCodeGoogleUrl($title, $secret, $mail);
$qrcode = new BaconQrCodeGenerator;
$qrCodeUrl = $qrcode->size(250)->generate($google_qrCodeUrl);
</code>```

And now work correctly ;)

Title: Generate QRCode without Windows-1252

Body:
I change fucntion getQRCodeGoogleUrl:

public function getQRCodeGoogleUrl($name, $secret, $title = null, $params = array())
{
    $level = !empty($params['level']) && array_search($params['level'], array('L', 'M', 'Q', 'H')) !== false ? $params['level'] : 'M';
    if ($title !== null) {
        $getTitle = $title;
    }
    $urlencoded = "otpauth://totp/$name?secret=$secret&issuer=$getTitle&ecc=$level";
    return $urlencoded;
}

and the I use BaconQrCodeGenerator:

$google_qrCodeUrl = $this->getQRCodeGoogleUrl($title, $secret, $mail);
$qrcode = new BaconQrCodeGenerator;
$qrCodeUrl = $qrcode->size(250)->generate($google_qrCodeUrl);

And now work correctly ;)


来源: stackexchange

问:
ImportError: cannot import name 'RGBColor'
I am trying to import this:

```<code>from colormath.color_objects import RGBColor
</code>```

and I am getting this error:

```<code>ImportError: cannot import name 'RGBColor'
</code>```

I am using Python 3.6 and the library colormath is installed.

答:
RGBColor is a removed class from an old version of colormath.

From the v2.0.1 release notes (2014):

Completely re-worked RGB handling. Each RGB space now has its own
  class, inheriting from BaseRGBColor. Consequently, RGBColor is no
  more. In most cases, you can substitute RGBColor with sRGBColor during
  your upgrade.

And if you check the current documentation, you'll see there is indeed no RGBColor. Try sRGBColor instead.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to import this:

from colormath.color_objects import RGBColor

and I am getting this error:

ImportError: cannot import name 'RGBColor'

I am using Python 3.6 and the library colormath is installed.


问:
How to concatenate strings of a string field in a PostgreSQL 'group by' query?
I am looking for a way to concatenate the strings of a field within a group by query. So for example, I have a table:

ID
COMPANY_ID
EMPLOYEE

1
1
Anna

2
1
Bill

3
2
Carol

4
2
Dave

and I wanted to group by company_id to get something like:

COMPANY_ID
EMPLOYEE

1
Anna, Bill

2
Carol, Dave

There is a built-in function in mySQL to do this group_concat

答:
I found this PostgreSQL documentation helpful: http://www.postgresql.org/docs/8.0/interactive/functions-conditional.html.

In my case, I sought plain SQL to concatenate a field with brackets around it, if the field is not empty.

```<code>select itemid,
  CASE
    itemdescription WHEN '' THEN itemname
    ELSE itemname || ' (' || itemdescription || ')'
  END
from items;
</code>```

OwnerDisplayName: Guy C

LastEditorDisplayName: travis

Body:
I found this PostgreSQL documentation helpful: http://www.postgresql.org/docs/8.0/interactive/functions-conditional.html.

In my case, I sought plain SQL to concatenate a field with brackets around it, if the field is not empty.

select itemid,
  CASE
    itemdescription WHEN '' THEN itemname
    ELSE itemname || ' (' || itemdescription || ')'
  END
from items;

OwnerDisplayName: David

LastEditorDisplayName: David

ContentLicense: CC BY-SA 2.5


问:
Sorting strings in reverse order with backbone.js
I'm trying to sort a Backbone.js collection in reverse order. There are previous replies on how to do this with integers, but none with strings.

```<code>var Chapter  = Backbone.Model;
var chapters = new Backbone.Collection;

chapters.comparator = function(chapter) {
  return chapter.get("title");
};

chapters.add(new Chapter({page: 9, title: "The End"}));
chapters.add(new Chapter({page: 5, title: "The Middle"}));
chapters.add(new Chapter({page: 1, title: "The Beginning"}));

alert(chapters.pluck('title'));
</code>```

The above code sorts the chapters from A -> Z, but how do I write a comparator that sorts it from Z -> A?

答:
You could:

grab the char code for each character in the string,

subtract each value from 0xffff (the maximum return value of string.charCodeAt),

use String.fromCharCode to turn that back into string of "negated" characters

and that will be your sorting key.

```<code>chapters.comparator = function(chapter) {
    return String.fromCharCode.apply(String,
        _.map(chapter.get("title").split(""), function (c) {
            return 0xffff - c.charCodeAt();
        })
    );
}
</code>```

And voila:

```<code>> console.log(chapters.pluck('title'));
["The Middle", "The End", "The Beginning"]
</code>```

Note: if your comparison strings are long (as in 65 kb or more), you may run into trouble (see Matt's comment below). To avoid this, and speed up comparisons a bit, just use a shorter slice of your comparison string. (In the above example, you could go for chapter.get("title").slice(0, 100).split("") instead.) How long a slice you need will depend on your application.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to sort a Backbone.js collection in reverse order. There are previous replies on how to do this with integers, but none with strings.

var Chapter  = Backbone.Model;
var chapters = new Backbone.Collection;

chapters.comparator = function(chapter) {
  return chapter.get("title");
};

chapters.add(new Chapter({page: 9, title: "The End"}));
chapters.add(new Chapter({page: 5, title: "The Middle"}));
chapters.add(new Chapter({page: 1, title: "The Beginning"}));

alert(chapters.pluck('title'));

The above code sorts the chapters from A -> Z, but how do I write a comparator that sorts it from Z -> A?

Body:
You could:

grab the char code for each character in the string,

subtract each value from 0xffff (the maximum return value of string.charCodeAt),

use String.fromCharCode to turn that back into string of "negated" characters

and that will be your sorting key.

chapters.comparator = function(chapter) {
    return String.fromCharCode.apply(String,
        _.map(chapter.get("title").split(""), function (c) {
            return 0xffff - c.charCodeAt();
        })
    );
}

And voila:

> console.log(chapters.pluck('title'));
["The Middle", "The End", "The Beginning"]

Note: if your comparison strings are long (as in 65 kb or more), you may run into trouble (see Matt's comment below). To avoid this, and speed up comparisons a bit, just use a shorter slice of your comparison string. (In the above example, you could go for chapter.get("title").slice(0, 100).split("") instead.) How long a slice you need will depend on your application.


问:
list of buttons on the page. After I get the list I want to check if the button is displayed on the page
I am new to automation testing and I have been trying to figure this out all day. Anyways I want to go the site and get a list of buttons on the page. Than I want to print the list of buttons that are displayed on the page.

```<code>package com.practice;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Buttons {

    public static void main(String[] args) throws InterruptedException {

        System.setProperty("webdriver.chrome.driver",
                "C:\\Users\\Oderint dum metuant\\eclipse-workspace\\JAR FILES\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.toolsqa.com/automation-practice-switch-windows/");

        List <WebElement> buttons = driver.findElements(By.tagName("button"));
        for ( int i=0; i<buttons.size();i++){
            WebElement button = buttons.get(i);
            if(button.isEnabled()){
                System.out.println(buttons);
                }
            }

    }

}
</code>```

This is what I get when I run the code:

[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]

答:
If you want to print the list of button names that are displayed on the page.

Ans. Remove if condition block and change the print statement. Refer below Code:

```<code>List <WebElement> buttons = driver.findElements(By.tagName("button"));

    for ( int i=0; i<buttons.size();i++)
    {
        WebElement button = buttons.get(i);

        System.out.println(button.getText());//It prints all the buttons name displayed on the page

    }
</code>```

2. If you want to print the list of button names which are enabled on the page.

Ans. Keep the if condition block, just change the print statement. Refer below code:

```<code>List <WebElement> buttons = driver.findElements(By.tagName("button"));

        for ( int i=0; i<buttons.size();i++)
        {
            WebElement button = buttons.get(i);

            //System.out.println(button.getText());  //It prints all the buttons name displayed on the page

        if(button.isEnabled())
            {
                System.out.println(button.getText()); //It prints all the buttons name which are enabled on the page

            }
        }
</code>```

Body:
I am new to automation testing and I have been trying to figure this out all day. Anyways I want to go the site and get a list of buttons on the page. Than I want to print the list of buttons that are displayed on the page.

package com.practice;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Buttons {

    public static void main(String[] args) throws InterruptedException {

        System.setProperty("webdriver.chrome.driver",
                "C:\\Users\\Oderint dum metuant\\eclipse-workspace\\JAR FILES\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.toolsqa.com/automation-practice-switch-windows/");

        List <WebElement> buttons = driver.findElements(By.tagName("button"));
        for ( int i=0; i<buttons.size();i++){
            WebElement button = buttons.get(i);
            if(button.isEnabled()){
                System.out.println(buttons);
                }
            }

    }

}

This is what I get when I run the code:

[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]

Body:
If you want to print the list of button names that are displayed on the page.

Ans. Remove if condition block and change the print statement. Refer below Code:

List <WebElement> buttons = driver.findElements(By.tagName("button"));

    for ( int i=0; i<buttons.size();i++)
    {
        WebElement button = buttons.get(i);

        System.out.println(button.getText());//It prints all the buttons name displayed on the page

    }

2. If you want to print the list of button names which are enabled on the page.

Ans. Keep the if condition block, just change the print statement. Refer below code:

List <WebElement> buttons = driver.findElements(By.tagName("button"));

        for ( int i=0; i<buttons.size();i++)
        {
            WebElement button = buttons.get(i);

            //System.out.println(button.getText());  //It prints all the buttons name displayed on the page

        if(button.isEnabled())
            {
                System.out.println(button.getText()); //It prints all the buttons name which are enabled on the page

            }
        }


问:
How to deal with asynchronous methods and IDisposable in C#?
I have some integration tests using xUnit that need to tear down some resources created during the test. To do that, I have implemented IDisposable in the class containing the tests.

The problem is I need to delete resources created during the test using a client that has only an asynchronous interface. But, the Dispose method is synchronous.

I could use .Result or .Wait() to wait for the completion of the asynchronous call, but that may create deadlocks (the issue is well-documented here).

Given I cannot use .Result or .Wait(), what is the proper (and safe) way to call an asynchronous method in a Dispose method?

UPDATE: adding a (simplified) example to show the problem.

```<code>[Collection("IntegrationTests")]
public class SomeIntegrationTests : IDisposable {
    private readonly IClient _client; // SDK client for external API

    public SomeIntegrationTests() {
        // initialize client
    }

    [Fact]
    public async Task Test1() {
        await _client
            .ExecuteAsync(/* a request that creates resources */);

        // some assertions
    }

    public void Dispose() {
        _client
            .ExecuteAsync(/* a request to delete previously created resources */)
            .Wait(); // this may create a deadlock
    }
}
</code>```

答:
I have similar problems, especially XUnit is a problem child here.
I "solved" that with moving all cleanup code into the test, e.g. a try..finally block. It's less elegant, but works more stable and avoid async dispose.
If you have a lot of tests, you could add a method which reduces the boilerplate.

For example:

```<code>        private async Task WithFinalizer(Action<Task> toExecute)
    {

        try
        {
            await toExecute();
        }
        finally
        {
           // cleanup here
        }
    }

    // Usage
    [Fact]
    public async Task TestIt()
    {
        await WithFinalizer(async =>
        {
         // your test
         });
    }
</code>```

Another benefit of this is that, in my experience, cleanup is often highly dependent of the test - providing a custom finalizer for each test is much easier with this technique (add a second action which can be used as a finalizer)

Body:
I have some integration tests using xUnit that need to tear down some resources created during the test. To do that, I have implemented IDisposable in the class containing the tests.

The problem is I need to delete resources created during the test using a client that has only an asynchronous interface. But, the Dispose method is synchronous.

I could use .Result or .Wait() to wait for the completion of the asynchronous call, but that may create deadlocks (the issue is well-documented here).

Given I cannot use .Result or .Wait(), what is the proper (and safe) way to call an asynchronous method in a Dispose method?

UPDATE: adding a (simplified) example to show the problem.

[Collection("IntegrationTests")]
public class SomeIntegrationTests : IDisposable {
    private readonly IClient _client; // SDK client for external API

    public SomeIntegrationTests() {
        // initialize client
    }

    [Fact]
    public async Task Test1() {
        await _client
            .ExecuteAsync(/* a request that creates resources */);

        // some assertions
    }

    public void Dispose() {
        _client
            .ExecuteAsync(/* a request to delete previously created resources */)
            .Wait(); // this may create a deadlock
    }
}

Body:
I have similar problems, especially XUnit is a problem child here.
I "solved" that with moving all cleanup code into the test, e.g. a try..finally block. It's less elegant, but works more stable and avoid async dispose.
If you have a lot of tests, you could add a method which reduces the boilerplate.

For example:

        private async Task WithFinalizer(Action<Task> toExecute)
    {

        try
        {
            await toExecute();
        }
        finally
        {
           // cleanup here
        }
    }

    // Usage
    [Fact]
    public async Task TestIt()
    {
        await WithFinalizer(async =>
        {
         // your test
         });
    }

Another benefit of this is that, in my experience, cleanup is often highly dependent of the test - providing a custom finalizer for each test is much easier with this technique (add a second action which can be used as a finalizer)


问:
Can I generate html code as a string then set that string to be the value of a div in typescript using clarity framework (Angular 7)
I am trying to generate a html code as a string for a Clarity-data-grid using TS then set that string to be the value of a div but the clarity framework won't work unless I actually type the HTML code in the HTML file.

this.component.nativeElement.innerHTML=this.html; -> doing this in TS won't work. But it works if I type everything in (#html below), it will display the table.

```<code>html: string ='';
//Generating the grid
private genGrid(data: string): void {
    let request: Object;
    if(data !== ''){
      request = JSON.parse(data);
      for(let prop in request){
        if(request.hasOwnProperty(prop))
          this.html+='<clr-dg-column [clrDgField]="\''+prop+'\'">'+prop+'</clr-dg-column>';
      }
      for(let prop in request){
        if(request.hasOwnProperty(prop))
          this.html+='<clr-dg-cell>'+prop+'</clr-dg-cell>';
      }
    }
}
this.genGrid(someString);
this.component.nativeElement.innerHTML=this.html;
</code>```

this html code will be generated in my file #html

```<code><div class="card-block" style="padding: 0 10px 10px 10px;"><clr-datagrid><clr-dg-column [clrDgField]="'productId'">productId</clr-dg-column><clr-dg-column [clrDgField]="'productCategoryId'">productCategoryId</clr-dg-column><clr-dg-column [clrDgField]="'productName'">productName</clr-dg-column><clr-dg-column [clrDgField]="'countUnit'">countUnit</clr-dg-column><clr-dg-column [clrDgField]="'manufacturer'">manufacturer</clr-dg-column><clr-dg-column [clrDgField]="'country'">country</clr-dg-column><clr-dg-column [clrDgField]="'description'">description</clr-dg-column><clr-dg-column [clrDgField]="'status'">status</clr-dg-column><clr-dg-column [clrDgField]="'createdDate'">createdDate</clr-dg-column><clr-dg-column [clrDgField]="'createdBy'">createdBy</clr-dg-column><clr-dg-column [clrDgField]="'modifiedBy'">modifiedBy</clr-dg-column><clr-dg-column [clrDgField]="'modifiedDate'">modifiedDate</clr-dg-column><clr-dg-cell>productId</clr-dg-cell><clr-dg-cell>productCategoryId</clr-dg-cell><clr-dg-cell>productName</clr-dg-cell><clr-dg-cell>countUnit</clr-dg-cell><clr-dg-cell>manufacturer</clr-dg-cell><clr-dg-cell>country</clr-dg-cell><clr-dg-cell>description</clr-dg-cell><clr-dg-cell>status</clr-dg-cell><clr-dg-cell>createdDate</clr-dg-cell><clr-dg-cell>createdBy</clr-dg-cell><clr-dg-cell>modifiedBy</clr-dg-cell><clr-dg-cell>modifiedDate</clr-dg-cell>
</code>```

答:
Because this is an Angular library. It works with Angular context, and it needs to be compiled in order to work properly.

Setting it as innerHTML of an element (which, BTW, is a very bad practice in Angular) makes it "final", i.e. it will not be compiled to JS code.

If you want to do that, I suggest you take a look at dynamic components or CDK Portals

Body:
I am trying to generate a html code as a string for a Clarity-data-grid using TS then set that string to be the value of a div but the clarity framework won't work unless I actually type the HTML code in the HTML file.

this.component.nativeElement.innerHTML=this.html; -> doing this in TS won't work. But it works if I type everything in (#html below), it will display the table.

html: string ='';
//Generating the grid
private genGrid(data: string): void {
    let request: Object;
    if(data !== ''){
      request = JSON.parse(data);
      for(let prop in request){
        if(request.hasOwnProperty(prop))
          this.html+='<clr-dg-column [clrDgField]="\''+prop+'\'">'+prop+'</clr-dg-column>';
      }
      for(let prop in request){
        if(request.hasOwnProperty(prop))
          this.html+='<clr-dg-cell>'+prop+'</clr-dg-cell>';
      }
    }
}
this.genGrid(someString);
this.component.nativeElement.innerHTML=this.html;

this html code will be generated in my file #html

<clr-datagrid><clr-dg-column [clrDgField]="'productId'">productId</clr-dg-column><clr-dg-column [clrDgField]="'productCategoryId'">productCategoryId</clr-dg-column><clr-dg-column [clrDgField]="'productName'">productName</clr-dg-column><clr-dg-column [clrDgField]="'countUnit'">countUnit</clr-dg-column><clr-dg-column [clrDgField]="'manufacturer'">manufacturer</clr-dg-column><clr-dg-column [clrDgField]="'country'">country</clr-dg-column><clr-dg-column [clrDgField]="'description'">description</clr-dg-column><clr-dg-column [clrDgField]="'status'">status</clr-dg-column><clr-dg-column [clrDgField]="'createdDate'">createdDate</clr-dg-column><clr-dg-column [clrDgField]="'createdBy'">createdBy</clr-dg-column><clr-dg-column [clrDgField]="'modifiedBy'">modifiedBy</clr-dg-column><clr-dg-column [clrDgField]="'modifiedDate'">modifiedDate</clr-dg-column><clr-dg-cell>productId</clr-dg-cell><clr-dg-cell>productCategoryId</clr-dg-cell><clr-dg-cell>productName</clr-dg-cell><clr-dg-cell>countUnit</clr-dg-cell><clr-dg-cell>manufacturer</clr-dg-cell><clr-dg-cell>country</clr-dg-cell><clr-dg-cell>description</clr-dg-cell><clr-dg-cell>status</clr-dg-cell><clr-dg-cell>createdDate</clr-dg-cell><clr-dg-cell>createdBy</clr-dg-cell><clr-dg-cell>modifiedBy</clr-dg-cell><clr-dg-cell>modifiedDate</clr-dg-cell>


问:
Showing and hiding a fixed element on pre-defined screen widths
I want to hide my element on @media(min-width:576px) and want to show my element on @media(min-width: 768px) as I need to use display: fixed; for my element, but the display: fixed; element is not showing my element.

```<code>@media (min-width : 576px) {
    #content-item { display: none;}
}
@media (min-width : 768px) {
    #content-item { display: fixed;}
}
</code>```

I expect to show my #content-item element and also want to use display: fixed; property

答:
I think you're making a confusion between display and position.
try this.</p>

```<code>@media (min-width : 576px) {
    #content-item { display: none;}
}
@media (min-width : 768px) {
    #content-item {
      display: block;
      position: fixed;
    }
}
</code>```

Body:
I want to hide my element on @media(min-width:576px) and want to show my element on @media(min-width: 768px) as I need to use display: fixed; for my element, but the display: fixed; element is not showing my element.

@media (min-width : 576px) {
    #content-item { display: none;}
}
@media (min-width : 768px) {
    #content-item { display: fixed;}
}

I expect to show my #content-item element and also want to use display: fixed; property

Body:
I think you're making a confusion between display and position.
try this.

@media (min-width : 576px) {
    #content-item { display: none;}
}
@media (min-width : 768px) {
    #content-item {
      display: block;
      position: fixed;
    }
}


问:
How to correctly implement equals(), hashCode() for Tree in Java?
I have a tree structure and I need to override the methods equals/hashCode because I use the check of the expected result in the unit tests.

The problem with tree type structures is that they refer to each other recursively. In particular, parents for children and vice versa.

and if all fields are used in the methods equals/hashCode, then there will be a looping. The question is how to correctly override then in order not to violate the contract.

I will give an example of how I implemented it.

```<code>public class App {
    public static void main(String[] args) {
        Book book1 = new Book(1L, "The catcher in the rye");
        Book book2 = new Book(2L, "Rich Dad Poor Dad");

        BookTree bookTree1 = new BookTree(book1);
        BookTree bookTreeChild1 = new BookTree(book2);
        bookTree1.addChild(bookTreeChild1);

        BookTree bookTree2 = new BookTree(book1);
        BookTree bookTreeChild2 = new BookTree(book2);
        bookTree2.addChild(bookTreeChild2);

        if (!bookTree1.equals(bookTree2)) {
            throw new RuntimeException("Invalid override equals");
        }
    }
}

class Book {
    private Long id;
    private String name;

    public Book(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object object) {
        if (this == object) return true;
        if (object == null || getClass() != object.getClass()) return false;
        Book book = (Book) object;
        return Objects.equals(id, book.id) &&
                Objects.equals(name, book.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }
}

class Tree<T> {
    private List<Tree<T>> children = new ArrayList<>();
    private Tree<T> parent = null;
    private T data;

    public Tree(T data) {
        this.data = data;
    }

    public Tree(T data, Tree<T> parent) {
        this.data = data;
        parent.addChild(this);
    }

    public List<Tree<T>> getChildren() {
        return children;
    }

    public void addChild(Tree<T> child) {
        child.setParent(this);
        this.children.add(child);
    }

    public void addChild(T data) {
        Tree<T> newChild = new Tree<>(data);
        this.addChild(newChild);
    }

    public void removeChildren() {
        this.children = new ArrayList<>();
    }

    public void addChildren(List<Tree<T>> children) {
        for(Tree<T> t : children) {
            t.setParent(this);
        }
        this.children.addAll(children);
    }

    private void setParent(Tree<T> parent) {
        this.parent = parent;
    }

    public Tree<T> getParent() {
        return parent;
    }

    public T getData() {
        return this.data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public boolean isRoot() {
        return (this.parent == null);
    }

    public boolean isLeaf() {
        return this.children.size() == 0;
    }

    public void removeParent() {
        this.parent = null;
    }

    @Override
    public boolean equals(Object object) {
        if (this == object) return true;
        if (object == null || getClass() != object.getClass()) return false;
        Tree<?> tree = (Tree<?>) object;
        return Objects.equals(children, tree.children) &&
                Objects.equals(data, tree.data);
    }

    @Override
    public int hashCode() {
        return Objects.hash(children, data);
    }
}

class BookTree extends Tree<Book> {

    public BookTree(Book data) {
        super(data);
    }

    public BookTree(Book data, Tree<Book> parent) {
        super(data, parent);
    }
}
</code>```

As you can see from my implementation, I use only two fields: "data" and "children".
Accordingly, my question is whether I implemented the methods equals/hashCode correctly?
If wrong, then please show how.

答:
Accordingly, my question is whether I implemented the methods equals/hashCode correctly?

First of all: "what is correct?" ... one could wonder why a Tree should implement equals() and hashCode() in the first place. Especially hashCode() is tricky: the point of that method is (mainly) so you can store the corresponding object in a HashMap/HashSet. But that raises a big red flag: both these classes do not like it, when hashCode() returns different values over time. And that is exactly what your code will be doing: every time you change your tree (adding/removing a node), hashCode() will give a different result.

So we could have a look at what the standard libs do: and there we find JTree ... which doesn't implement both methods! On the other hand, when we look towards AbstractSet (which is the base class for TreeSet), there we find that both methods are implemented and include the members. So both ways seem to be valid.

Coming back to the question: that really depends how you want these two methods to work. Are two trees equal when they have the exact same content (meaning: does the order of children matter)?

Long story short: assuming that you want to ensure that all data is equal, and that all children are equal, and in the same order, then your implementation seems correct.

And yes, that restriction to only check these two attributes makes a lot of sense: when you include the parent link, you immediately get into a recursion that can't be broken.

Finally: you tagged this question with JUnit. This implies that you consider writing tests for your production code. Then these tests should answer your question. Meaning: one approach would be that you sit down and define the contract for these two methods. And then you create a number of test cases that verify all aspects of these contracts. And then your test cases tell you whether your production code meets your contract.

I think that is the crucial point here: there is no universal rule that tells us if/how to implement equals() and hashCode() for a Tree class. You have to look into your requirements if/how to do that. Then you derive tests from that knowledge, which you then you apply in order to verify if a given implementation meets the requirements/contract.

Body:
I have a tree structure and I need to override the methods equals/hashCode because I use the check of the expected result in the unit tests.

The problem with tree type structures is that they refer to each other recursively. In particular, parents for children and vice versa.

and if all fields are used in the methods equals/hashCode, then there will be a looping. The question is how to correctly override then in order not to violate the contract.

I will give an example of how I implemented it.

public class App {
    public static void main(String[] args) {
        Book book1 = new Book(1L, "The catcher in the rye");
        Book book2 = new Book(2L, "Rich Dad Poor Dad");

        BookTree bookTree1 = new BookTree(book1);
        BookTree bookTreeChild1 = new BookTree(book2);
        bookTree1.addChild(bookTreeChild1);

        BookTree bookTree2 = new BookTree(book1);
        BookTree bookTreeChild2 = new BookTree(book2);
        bookTree2.addChild(bookTreeChild2);

        if (!bookTree1.equals(bookTree2)) {
            throw new RuntimeException("Invalid override equals");
        }
    }
}

class Book {
    private Long id;
    private String name;

    public Book(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object object) {
        if (this == object) return true;
        if (object == null || getClass() != object.getClass()) return false;
        Book book = (Book) object;
        return Objects.equals(id, book.id) &&
                Objects.equals(name, book.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }
}

class Tree<T> {
    private List<Tree<T>> children = new ArrayList<>();
    private Tree<T> parent = null;
    private T data;

    public Tree(T data) {
        this.data = data;
    }

    public Tree(T data, Tree<T> parent) {
        this.data = data;
        parent.addChild(this);
    }

    public List<Tree<T>> getChildren() {
        return children;
    }

    public void addChild(Tree<T> child) {
        child.setParent(this);
        this.children.add(child);
    }

    public void addChild(T data) {
        Tree<T> newChild = new Tree<>(data);
        this.addChild(newChild);
    }

    public void removeChildren() {
        this.children = new ArrayList<>();
    }

    public void addChildren(List<Tree<T>> children) {
        for(Tree<T> t : children) {
            t.setParent(this);
        }
        this.children.addAll(children);
    }

    private void setParent(Tree<T> parent) {
        this.parent = parent;
    }

    public Tree<T> getParent() {
        return parent;
    }

    public T getData() {
        return this.data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public boolean isRoot() {
        return (this.parent == null);
    }

    public boolean isLeaf() {
        return this.children.size() == 0;
    }

    public void removeParent() {
        this.parent = null;
    }

    @Override
    public boolean equals(Object object) {
        if (this == object) return true;
        if (object == null || getClass() != object.getClass()) return false;
        Tree<?> tree = (Tree<?>) object;
        return Objects.equals(children, tree.children) &&
                Objects.equals(data, tree.data);
    }

    @Override
    public int hashCode() {
        return Objects.hash(children, data);
    }
}

class BookTree extends Tree<Book> {

    public BookTree(Book data) {
        super(data);
    }

    public BookTree(Book data, Tree<Book> parent) {
        super(data, parent);
    }
}

As you can see from my implementation, I use only two fields: "data" and "children".
Accordingly, my question is whether I implemented the methods equals/hashCode correctly?
If wrong, then please show how.


问:
The app's Info.plist must contain an NSContactsUsageDescription key
I am getting a crash below:

This app has crashed because it attempted to access privacy-sensitive data without a usage description.  The app's Info.plist must contain an NSContactsUsageDescription key with a string value explaining to the user how the app uses this data.

But I have already added the 'Privacy - Contacts Usage Description' key

答: if you are using App test and and App UItest then there would be multple plist files in your project just make it sure you are adding discription in right if plist


问:
Sql Bulk Copy/Insert in C#
I am new to JSON and SQLBulkCopy. I have a JSON formatted POST data that I want to Bulk Copy/Insert in Microsoft SQL using C#.

JSON Format:

```<code>{
    "URLs": [{
        "url_name": "Google",
        "url_address": "http://www.google.com/"
    },
    {
        "url_name": "Yahoo",
        "url_address": "http://www.yahoo.com/"
    },
    {
        "url_name": "FB",
        "url_address": "http://www.fb.com/"
    },
    {
        "url_name": "MegaSearches",
        "url_address": "http://www.megasearches.com/"
    }]
}
</code>```

Classes:

```<code>public class UrlData
{
    public List<Url> URLs {get;set;}
}

public class Url
{
    public string url_address {get;set;}
    public string url_name {get;set;}
}
</code>```

How can I do that efficiently?

答:
Using this below code, you can convert List<YourClassname> to DataTable:-

```<code>List<YourClass> objlist = alldata;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(objlist);
DataTable dt = Newtonsoft.Json.JsonConvert.DeserializeObject<DataTable>(json);
SaveDataInTables(dt, "Table_Name_Of_SQL");
</code>```

Here, I'm assuming that alldata contains list<YourClass> object and you can also do - objlist.Add(objYourClass), then pass sql_TableName and data table in SaveDataInTables method. This method will insert all data in SQL_Table.

```<code>public void SaveDataInTables(DataTable dataTable, string tablename)
{
   if (dataTable.Rows.Count > 0)
   {
       using (SqlConnection con = new SqlConnection("Your_ConnectionString"))
       {
           using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
           {
               sqlBulkCopy.DestinationTableName = tablename;
               con.Open();
               sqlBulkCopy.WriteToServer(dataTable);
               con.Close();
            }
        }
    }
}
</code>```

Hope, these codes help you!!!

Title: Sql Bulk Copy/Insert in C#

Body:
I am new to JSON and SQLBulkCopy. I have a JSON formatted POST data that I want to Bulk Copy/Insert in Microsoft SQL using C#.

JSON Format:

{
    "URLs": [{
        "url_name": "Google",
        "url_address": "http://www.google.com/"
    },
    {
        "url_name": "Yahoo",
        "url_address": "http://www.yahoo.com/"
    },
    {
        "url_name": "FB",
        "url_address": "http://www.fb.com/"
    },
    {
        "url_name": "MegaSearches",
        "url_address": "http://www.megasearches.com/"
    }]
}

Classes:

public class UrlData
{
    public List<Url> URLs {get;set;}
}

public class Url
{
    public string url_address {get;set;}
    public string url_name {get;set;}
}

How can I do that efficiently?

Body:
Using this below code, you can convert List<YourClassname> to DataTable:-

List<YourClass> objlist = alldata;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(objlist);
DataTable dt = Newtonsoft.Json.JsonConvert.DeserializeObject<DataTable>(json);
SaveDataInTables(dt, "Table_Name_Of_SQL");

Here, I'm assuming that alldata contains list<YourClass> object and you can also do - objlist.Add(objYourClass), then pass sql_TableName and data table in SaveDataInTables method. This method will insert all data in SQL_Table.

public void SaveDataInTables(DataTable dataTable, string tablename)
{
   if (dataTable.Rows.Count > 0)
   {
       using (SqlConnection con = new SqlConnection("Your_ConnectionString"))
       {
           using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
           {
               sqlBulkCopy.DestinationTableName = tablename;
               con.Open();
               sqlBulkCopy.WriteToServer(dataTable);
               con.Close();
            }
        }
    }
}

Hope, these codes help you!!!


问:
Next greatest number
I'm trying to find the next greatest number from the user input.If the user gives 23 it shows the output as 32.If there is number greater number then it has to print the same given number.But if the user gives 03 it shows 3 but it has to show 30.Because it takes 03 as octal number.How can i change the code to show the correct output as 30?</p>

```<code>public class Main
{
 static void swap(char ar[], int i, int j)
 {
  char temp = ar[i];
  ar[i] = ar[j];
  ar[j] = temp;
 }
 public static void main(String[] args)
 {
   Scanner in = new Scanner(System.in);
   int num = in .nextInt();
   char[] chars = ("" + num).toCharArray();
   int i;
   int n = chars.length;
   for (i = n - 1; i > 0; i--)
   {
    if (chars[i] > chars[i - 1])
     break;
   }
   if (i == 0)
    System.out.println(num);
   else {
    int x = chars[i - 1], min = i;
   for (int j = i + 1; j<n; j++)
   {
    if (chars[j] > x && chars[j]<chars[min])
     min = j;
   }
   swap(chars, i - 1, min);
   Arrays.sort(chars, i, n);
   for (i = 0; i<n; i++)
     System.out.print(chars[i]);
  }
 }
}
</code>```

答:
```<code>public static int findNextGreatestNumber(int[] arr, int k) {
    int delta = Integer.MAX_VALUE;
    int res = 0;

    for (int a : arr) {
        if (a - k > 0 && a - k < delta) {
            delta = a - k;
            res = a;
        }
    }

    return delta == Integer.MAX_VALUE ? k : res;
}
</code>```

Title: Next greatest number

Body:
I'm trying to find the next greatest number from the user input.If the user gives 23 it shows the output as 32.If there is number greater number then it has to print the same given number.But if the user gives 03 it shows 3 but it has to show 30.Because it takes 03 as octal number.How can i change the code to show the correct output as 30?

public class Main
{
 static void swap(char ar[], int i, int j)
 {
  char temp = ar[i];
  ar[i] = ar[j];
  ar[j] = temp;
 }
 public static void main(String[] args)
 {
   Scanner in = new Scanner(System.in);
   int num = in .nextInt();
   char[] chars = ("" + num).toCharArray();
   int i;
   int n = chars.length;
   for (i = n - 1; i > 0; i--)
   {
    if (chars[i] > chars[i - 1])
     break;
   }
   if (i == 0)
    System.out.println(num);
   else {
    int x = chars[i - 1], min = i;
   for (int j = i + 1; j<n; j++)
   {
    if (chars[j] > x && chars[j]<chars[min])
     min = j;
   }
   swap(chars, i - 1, min);
   Arrays.sort(chars, i, n);
   for (i = 0; i<n; i++)
     System.out.print(chars[i]);
  }
 }
}


问:
Can i deploy .car application (synapse-mediator & REST API) on wso2dss?
Sorry for my English and I'm newbie in wso2. I'm using this tutorial https://youtu.be/pa-nXLaCh4I to deploy my .car application on WSO2ESB. All ok, but can I deploy this on WSO2DSS? It's doesn't work for me. Please help.

I have changed only one thing in this tutorial - export composite application project with "Server Role" = "Data Services Server". Then my wso2dss server deploy my .car app without errors, but when I use http/1.1 get request to 'http://localhost:8280/sample/log' my browser says that I can't connect. I have checked localhost 8280 port with nmap and get request that port is closed:

```<code>PORT     STATE  SERVICE
8280/tcp closed synapse-nhttp
</code>```

Then I check "\wso2esb-4.9.0\repository\conf\axis2\axis2.xml" and find element:

```<code><transportReceiver name="http" class="org.apache.synapse.transport.passthru.PassThroughHttpListener"> ...
</code>```

which was uncommented, but in "\wso2dss-3.5.1\repository\conf\axis2\axis2.xml" iIfound element

```<code><!--transportReceiver name="http" class="org.apache.synapse.transport.nhttp.HttpCoreNIOListener"> ...
</code>```

which was commented. I uncomment this element in wso2dss axis2.xml. Then restart server, but get errors like:
java.lang.ClassNotFoundException and server did not start. Then I copy 3 jars in "\wso2dss-3.5.1\repository\components\dropins":

```<code>httpcore-nio_4.3.3.wso2v1.jar
synapse-commons_2.1.3.wso2v11.jar
synapse-nhttp-transport_2.1.3.wso2v11.jar
</code>```

and server started and port 8280 opened:

```<code>PORT     STATE SERVICE
8280/tcp open  synapse-nhttp
</code>```

And at that moment I was stacked. I use http/1.1 get request to to 'http://localhost:8280/sample/log' but get error in browser

```<code>ERR_INCOMPLETE_CHUNKED_ENCODING" 500 Internal Server Error
</code>```

but was excepting empty page and wso2dss server console displays nothing.
I use standart wso2dss-3.5.1 build and developer-studio-eclipse-jee-luna-win64-x86_64-3.8.0

答:
You cannot deploy synapse artifacts to DSS. This product is meant for a different purpose which is, working with data sources and data services. </p>

<p>If you want DSS and ESB functionalities together in a single product, you can install the DSS feature to ESB [1]. Or you can use WSO2 EI [2] which has ESB and DSS combined together. </p>

Body:
Sorry for my English and I'm newbie in wso2. I'm using this tutorial https://youtu.be/pa-nXLaCh4I to deploy my .car application on WSO2ESB. All ok, but can I deploy this on WSO2DSS? It's doesn't work for me. Please help.

I have changed only one thing in this tutorial - export composite application project with "Server Role" = "Data Services Server". Then my wso2dss server deploy my .car app without errors, but when I use http/1.1 get request to 'http://localhost:8280/sample/log' my browser says that I can't connect. I have checked localhost 8280 port with nmap and get request that port is closed:

PORT     STATE  SERVICE
8280/tcp closed synapse-nhttp

Then I check "\wso2esb-4.9.0\repository\conf\axis2\axis2.xml" and find element:

<transportReceiver name="http" class="org.apache.synapse.transport.passthru.PassThroughHttpListener"> ...

which was uncommented, but in "\wso2dss-3.5.1\repository\conf\axis2\axis2.xml" iIfound element

Body:
You cannot deploy synapse artifacts to DSS. This product is meant for a different purpose which is, working with data sources and data services.

If you want DSS and ESB functionalities together in a single product, you can install the DSS feature to ESB [1]. Or you can use WSO2 EI [2] which has ESB and DSS combined together.


问:
Objective-C release is not called explicitly
```<code>NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSString * str = [[NSString alloc] initWithString:@"test"];
[str release];
int i = 999999999;
while(i-- > 0) {}
NSLog(@"%@", str);
[pool drain];
</code>```

Output: test

Why didn't release work?
How can I immediately delete the object from memory?

Xcode Version 4.0 iPhone Application

~SOLVED~

Thank's to all for answers.
I've got a lot of useful information about this question. I'm going to use NSString *str = @"text" instead of NSString *str = [[NSString alloc] initWithString:@"text"];

i've understood that release just "marks" memory as "willing to be freed", but not freeing it immediatly

答:
When you do:

```<code>NSString * str = [[NSString alloc] initWithString:@"test"];
</code>```

This gets optimized into:

```<code>NSString * str = @"test";
</code>```

You can't release a constant string, because it's hardcoded into the application binary.

Proof:

```<code>NSString *s = [NSString alloc];
NSLog(@"%p", s);
s = [s initWithString:@"foo"];
NSLog(@"%p", s);
s = @"foo";
NSLog(@"%p", s);
</code>```

Logs:

```<code>2011-04-12 10:17:45.591 EmptyFoundation[6679:a0f] 0x100116370
2011-04-12 10:17:45.599 EmptyFoundation[6679:a0f] 0x100009270
2011-04-12 10:17:45.604 EmptyFoundation[6679:a0f] 0x100009270
</code>```

You can see that the result of +alloc is different from the result of -initWithString:, and the result of -initWithString: is equivalent to the constant string.  Basically, -initWithString: says "aha, i'm going to be an immutable string, and I'm being given an immutable string! I can just take a shortcut, destroy myself, and return the parameter, and everything will still work the same"

Body:
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSString * str = [[NSString alloc] initWithString:@"test"];
[str release];
int i = 999999999;
while(i-- > 0) {}
NSLog(@"%@", str);
[pool drain];

Output: test

Why didn't release work?
How can I immediately delete the object from memory?

Xcode Version 4.0 iPhone Application

~SOLVED~

Thank's to all for answers.
I've got a lot of useful information about this question. I'm going to use NSString *str = @"text" instead of NSString *str = [[NSString alloc] initWithString:@"text"];

i've understood that release just "marks" memory as "willing to be freed", but not freeing it immediatly

Body:
When you do:

NSString * str = [[NSString alloc] initWithString:@"test"];

This gets optimized into:

NSString * str = @"test";

You can't release a constant string, because it's hardcoded into the application binary.

Proof:

NSString *s = [NSString alloc];
NSLog(@"%p", s);
s = [s initWithString:@"foo"];
NSLog(@"%p", s);
s = @"foo";
NSLog(@"%p", s);

Logs:

2011-04-12 10:17:45.591 EmptyFoundation[6679:a0f] 0x100116370
2011-04-12 10:17:45.599 EmptyFoundation[6679:a0f] 0x100009270
2011-04-12 10:17:45.604 EmptyFoundation[6679:a0f] 0x100009270

You can see that the result of +alloc is different from the result of -initWithString:, and the result of -initWithString: is equivalent to the constant string.  Basically, -initWithString: says "aha, i'm going to be an immutable string, and I'm being given an immutable string! I can just take a shortcut, destroy myself, and return the parameter, and everything will still work the same"


问:
Add Componets to several pages. Error | Ionic 4
I try add to several pages my Header Components (Ionic g component).

My Header componet have a 4 files: html,scss,spec.ts and ts. When I add this component to minimum 2 pages I get this error:

```<code>Error: Type HeaderComponent is part of the declarations of 2 modules: Tab1PageModule and ProductPageModule! Please consider moving HeaderComponent to a higher module that imports Tab1PageModule and ProductPageModule. You can also create a new NgModule that exports and includes HeaderComponent then import that NgModule in Tab1PageModule and ProductPageModule.
</code>```

Its my component look like this:

```<code>import { HeaderComponent } from './../../partials/header/header.component';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Routes, RouterModule } from '@angular/router';

import { IonicModule } from '@ionic/angular';

import { ProductPage } from './product.page';

const routes: Routes = [
  {
    path: '',
    component: ProductPage
  }
];

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    RouterModule.forChild(routes)
  ],

  entryComponents:[HeaderComponent],
  declarations: [ProductPage,HeaderComponent]
})
export class ProductPageModule {}

</code>```

I try several ways too add this component but I still stay on the same point. When add NgModule to component then I get error about directives (is not recognized). When add ComoneModule (from Ionic Library) then my componets shows on all pages but Is two ways binding is not working properly (isn't refresh);

I will be very greatful for help

EDIT
I try create shared model (Header.components.module.ts), but When I use shared module i get error about:

```<code>core.js:15724 ERROR Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'ngIf' since it isn't a known property of 'ion-buttons'.
</code>```

```<code>import { HeaderComponent } from './header.component';
import { NgModule,CUSTOM_ELEMENTS_SCHEMA  } from '@angular/core';
import { IonicModule } from '@ionic/angular';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
@NgModule({

    imports: [CommonModule,
        FormsModule,
        IonicModule,RouterModule],
    declarations: [
        HeaderComponent,

   ],
   exports: [
    HeaderComponent
   ],
   schemas: [
    CUSTOM_ELEMENTS_SCHEMA
  ]
})

export class HeaderComponentsModule {}

</code>```

答:
When declaring a component, it should be declared in one module only. If you want to reuse it, then you should import the said module into another module.

You could create a shared module that contains :

```<code>imports: [MySharedComponent],
exports: [MySharedComponent]
</code>```

And in both Tab1PageModule and ProductPageModule :

```<code>imports: [MySharedModule]
</code>```

Body:
I try add to several pages my Header Components (Ionic g component).

My Header componet have a 4 files: html,scss,spec.ts and ts. When I add this component to minimum 2 pages I get this error:

Error: Type HeaderComponent is part of the declarations of 2 modules: Tab1PageModule and ProductPageModule! Please consider moving HeaderComponent to a higher module that imports Tab1PageModule and ProductPageModule. You can also create a new NgModule that exports and includes HeaderComponent then import that NgModule in Tab1PageModule and ProductPageModule.

Its my component look like this:

import { HeaderComponent } from './../../partials/header/header.component';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Routes, RouterModule } from '@angular/router';

import { IonicModule } from '@ionic/angular';

import { ProductPage } from './product.page';

const routes: Routes = [
  {
    path: '',
    component: ProductPage
  }
];

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    RouterModule.forChild(routes)
  ],

  entryComponents:[HeaderComponent],
  declarations: [ProductPage,HeaderComponent]
})
export class ProductPageModule {}

I try several ways too add this component but I still stay on the same point. When add NgModule to component then I get error about directives (is not recognized). When add ComoneModule (from Ionic Library) then my componets shows on all pages but Is two ways binding is not working properly (isn't refresh);

I will be very greatful for help

EDIT
I try create shared model (Header.components.module.ts), but When I use shared module i get error about:

core.js:15724 ERROR Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'ngIf' since it isn't a known property of 'ion-buttons'.

import { HeaderComponent } from './header.component';
import { NgModule,CUSTOM_ELEMENTS_SCHEMA  } from '@angular/core';
import { IonicModule } from '@ionic/angular';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
@NgModule({

    imports: [CommonModule,
        FormsModule,
        IonicModule,RouterModule],
    declarations: [
        HeaderComponent,

   ],
   exports: [
    HeaderComponent
   ],
   schemas: [
    CUSTOM_ELEMENTS_SCHEMA
  ]
})

export class HeaderComponentsModule {}

Body:
When declaring a component, it should be declared in one module only. If you want to reuse it, then you should import the said module into another module.

You could create a shared module that contains :

imports: [MySharedComponent],
exports: [MySharedComponent]

And in both Tab1PageModule and ProductPageModule :

imports: [MySharedModule]


问:
How to implement a delayed reply/timeout correctly between serverHTTP and a channel?
I have a concept here which I don't know how I should solve correctly with minimum impact on the system in Go.

I'm making a 'print-spooler' where clients can call in on an API (/StartJob) to process printjobs.

Since there is only one printer so the bottleneck is a single worker that processes each job at a time, but clients can pass one job at any given time, it will just queue up and the worker will process each job in the time it takes step by step.

The way I'm doing it is that ServeHTTP pushes the job onto the channel (note here I just pass on the ID it the worker will look up the printdata from that):

```<code>func (gv *GlobalVariables) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    switch r.URL.Path {
    case "/StartJob":
        newPrintJob := QueueElement {jobid: "jobid"}
        gv.printQueue <- newPrintJob
        fmt.Fprintf(w, "instant reply from serveHTTP\r\n")

    default:
        fmt.Fprintf(w, "No such Api")
    }
  }
</code>```

The Worker then just runs all the time and processes any jobs coming in. Real code there is a bit more but in the end it executes an external process:

```<code>  func worker(jobs <-chan QueueElement) {
    for {
        job := <-jobs
        processExec ("START /i /b processAndPrint.exe -"+job.jobid)
      }
</code>```

The thing here is the external process can take time to execute, sometimes its instant but under some circumstances it can take 1 minute to perform the task before it returns.

My problem here is that now in serverHTTP, I write back to the client instantly with no knowledge if the job was the first in line and instantly can be processed, or if it has been queued up and maybe will be seconds away or minutes away before its processed:

```<code>  fmt.Fprintf(w, "instant reply from serveHTTP\r\n")
</code>```

What I would like is to give the client up to 5 seconds to get a reply back if his job was processed within that time, or if not, tell him he needs to call back later to check the status of his job.

I had several approaches in mind:

In my QueueElemnt I pass on the http.ResponseWriter so I'm able to write to the responsewriter (reply back to client) from the Worker. This I can do if I let the serveHTTP sleep as the ResponseWriter will shut down when the go routine exists. So here I would need to wait in serveHTTP and then when its waiting the worker is allowed to write to the ResponseWriter.

The problem with this approach is that if the job is minutes away, the Worker won't write anything to that ResponseWriter, and the serveHTTP wouldn't know if a reply had been sent from the worker.

I could create a channel for each QueueElement so the serveHTTP and not only the worker but the actual job if being processed by the worker are able to communicate to each other.

This approach I haven't tested, but I also worry here that its overkill and heavy on the system as we can have a situation where we have many many many api requests coming in and thereby a big queue that's being processed, so even though I would need to timeout/cancel it after 5 seconds, I think the concept is overkill?

I could maybe pass on a mutexed value in the queueElement that both serveHTTP could check for up to 5 seconds and the queue could check/manipulate but in case a job is finished then the queueElement disappears so this maybe results in conflicts.

I could do a variation of no 1) where I write my own responsewriter and use the flag if something has been written to it already, so the serveHTTP would check for up to 5 seconds on that to check if the Worker already wrote a reply back to the client and in that case exit serveHTTP with no answer, or in case no writes then serveHTTP would write the message back to the client,  a bit along the lines of this.

But none of these I feel are very smooth and I don't want to launch forever amount of go-routines or channels or lock myself into mutuxes everywhere as I don't know the impact of what it has on the system.

Can anyone assist me in a working correct way to implement such a thing? I've been reading page up page down and haven't found a nice and clean way of achieving this.

答:
I would avoid holding the request for a long time because we are not sure when the job will be processed.

One approach I can think of is:

Initially reply from the server as accepted / queued and return job_id.

```<code>{
   "job_id": "1",
   "status": "queued"
}
</code>```

The client can poll(say every 5 seconds) or use long polling to check the status of the job.

When is it running:

```<code>{
   "job_id": "1",
   "status": "processing"
}

</code>```

After completion:

```<code>{
   "job_id": "1",
   "status": "success/failed"
}

</code>```

Body:
I have a concept here which I don't know how I should solve correctly with minimum impact on the system in Go.

I'm making a 'print-spooler' where clients can call in on an API (/StartJob) to process printjobs.

Since there is only one printer so the bottleneck is a single worker that processes each job at a time, but clients can pass one job at any given time, it will just queue up and the worker will process each job in the time it takes step by step.

The way I'm doing it is that ServeHTTP pushes the job onto the channel (note here I just pass on the ID it the worker will look up the printdata from that):

func (gv *GlobalVariables) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    switch r.URL.Path {
    case "/StartJob":
        newPrintJob := QueueElement {jobid: "jobid"}
        gv.printQueue <- newPrintJob
        fmt.Fprintf(w, "instant reply from serveHTTP\r\n")

    default:
        fmt.Fprintf(w, "No such Api")
    }
  }

The Worker then just runs all the time and processes any jobs coming in. Real code there is a bit more but in the end it executes an external process:

  func worker(jobs <-chan QueueElement) {
    for {
        job := <-jobs
        processExec ("START /i /b processAndPrint.exe -"+job.jobid)
      }

The thing here is the external process can take time to execute, sometimes its instant but under some circumstances it can take 1 minute to perform the task before it returns.

My problem here is that now in serverHTTP, I write back to the client instantly with no knowledge if the job was the first in line and instantly can be processed, or if it has been queued up and maybe will be seconds away or minutes away before its processed:

  fmt.Fprintf(w, "instant reply from serveHTTP\r\n")

What I would like is to give the client up to 5 seconds to get a reply back if his job was processed within that time, or if not, tell him he needs to call back later to check the status of his job.

I had several approaches in mind:

In my QueueElemnt I pass on the http.ResponseWriter so I'm able to write to the responsewriter (reply back to client) from the Worker. This I can do if I let the serveHTTP sleep as the ResponseWriter will shut down when the go routine exists. So here I would need to wait in serveHTTP and then when its waiting the worker is allowed to write to the ResponseWriter.

The problem with this approach is that if the job is minutes away, the Worker won't write anything to that ResponseWriter, and the serveHTTP wouldn't know if a reply had been sent from the worker.

I could create a channel for each QueueElement so the serveHTTP and not only the worker but the actual job if being processed by the worker are able to communicate to each other.

This approach I haven't tested, but I also worry here that its overkill and heavy on the system as we can have a situation where we have many many many api requests coming in and thereby a big queue that's being processed, so even though I would need to timeout/cancel it after 5 seconds, I think the concept is overkill?

I could maybe pass on a mutexed value in the queueElement that both serveHTTP could check for up to 5 seconds and the queue could check/manipulate but in case a job is finished then the queueElement disappears so this maybe results in conflicts.

I could do a variation of no 1) where I write my own responsewriter and use the flag if something has been written to it already, so the serveHTTP would check for up to 5 seconds on that to check if the Worker already wrote a reply back to the client and in that case exit serveHTTP with no answer, or in case no writes then serveHTTP would write the message back to the client,  a bit along the lines of this.

But none of these I feel are very smooth and I don't want to launch forever amount of go-routines or channels or lock myself into mutuxes everywhere as I don't know the impact of what it has on the system.

Can anyone assist me in a working correct way to implement such a thing? I've been reading page up page down and haven't found a nice and clean way of achieving this.

Body:
I would avoid holding the request for a long time because we are not sure when the job will be processed.

One approach I can think of is:

Initially reply from the server as accepted / queued and return job_id.

{
   "job_id": "1",
   "status": "queued"
}

The client can poll(say every 5 seconds) or use long polling to check the status of the job.

When is it running:

{
   "job_id": "1",
   "status": "processing"
}

After completion:

{
   "job_id": "1",
   "status": "success/failed"
}


问:
Compare two dataframe columns in same dataframe and return text contained in first column
I have data loaded into a dataframe but cannot figure out how to compare the parsed data against the other column and return only matches.

This seems like it should be easy but I just don't see it. I've tried splitting the values out to compare but here's where I get stuck.

```<code>import pandas as pd

df = pd.DataFrame({ 'col1': [';t9010;',';c1312;',';d1310;c1512;'],
                    'col2': [';t1010;d1010;c1012;',';t1210;d1210;c1312;',';t1310;d1310;c1412;']})

df['col1_split'] = df['col1'].str.split(';')
df['col2_split'] = df['col2'].str.split(';')

# output something like...
df['output'] = [null,';c1312;',';d1310;']

</code>```

I'd expect to see something like -

1st row - return null, as t9010 is not contained in col2_split

2nd row - return c1312, as it is in col2_split

3rd row - return d1310 but not c1512, as only d1310 is in col2_split

lastly, the final text should be returned semicolon delimited and with leading and trailing semicolons i.e. ;t9010; or ;c1312; or ;d1310;c1512; if there is more than one.

答:
You may be can try this method to get all values in col1 if its values are in col2. The method is by splitting string values in each row to a list and then omitting the empty values or length is less than 0 in the list values ([]) first. And then searching the values without empty values in col1 that is matched to the col2 and displaying the output to the output column.

```<code>df = pd.DataFrame({ 'col1': [';t9010;',';c1312;',';d1310;c1512;'],
                    'col2': [';t1010;d1010;c1012;',';t1210;d1210;c1312;',';t1310;d1310;c1412;']})

#splitting & omitting the empty values
df['col1_split']=df.col1.apply(lambda x: list((pd.Series(x.split(';')))[(pd.Series(x.split(';'))).apply(len)>0]))
df['col2_split']=df.col2.apply(lambda x: list((pd.Series(x.split(';')))[(pd.Series(x.split(';'))).apply(len)>0]))

def check(list1, list2):
    res=''
    for i in list1:
        if (i in list2): res += ';'+str(i)
    #semicolon cover at the end of string in each row
    if len(res)>0: res+=';'
    return res

df['output']=df.apply(lambda x: check(x.col1_split, x.col2_split), axis=1)
df
</code>```

Output:

Hope this can help you.

Body:
I have data loaded into a dataframe but cannot figure out how to compare the parsed data against the other column and return only matches.

This seems like it should be easy but I just don't see it. I've tried splitting the values out to compare but here's where I get stuck.

import pandas as pd

df = pd.DataFrame({ 'col1': [';t9010;',';c1312;',';d1310;c1512;'],
                    'col2': [';t1010;d1010;c1012;',';t1210;d1210;c1312;',';t1310;d1310;c1412;']})

df['col1_split'] = df['col1'].str.split(';')
df['col2_split'] = df['col2'].str.split(';')

# output something like...
df['output'] = [null,';c1312;',';d1310;']

I'd expect to see something like -

1st row - return null, as t9010 is not contained in col2_split

2nd row - return c1312, as it is in col2_split

3rd row - return d1310 but not c1512, as only d1310 is in col2_split

lastly, the final text should be returned semicolon delimited and with leading and trailing semicolons i.e. ;t9010; or ;c1312; or ;d1310;c1512; if there is more than one.

Body:
You may be can try this method to get all values in col1 if its values are in col2. The method is by splitting string values in each row to a list and then omitting the empty values or length is less than 0 in the list values ([]) first. And then searching the values without empty values in col1 that is matched to the col2 and displaying the output to the output column.

df = pd.DataFrame({ 'col1': [';t9010;',';c1312;',';d1310;c1512;'],
                    'col2': [';t1010;d1010;c1012;',';t1210;d1210;c1312;',';t1310;d1310;c1412;']})

#splitting & omitting the empty values
df['col1_split']=df.col1.apply(lambda x: list((pd.Series(x.split(';')))[(pd.Series(x.split(';'))).apply(len)>0]))
df['col2_split']=df.col2.apply(lambda x: list((pd.Series(x.split(';')))[(pd.Series(x.split(';'))).apply(len)>0]))

def check(list1, list2):
    res=''
    for i in list1:
        if (i in list2): res += ';'+str(i)
    #semicolon cover at the end of string in each row
    if len(res)>0: res+=';'
    return res

df['output']=df.apply(lambda x: check(x.col1_split, x.col2_split), axis=1)
df

Output:

Hope this can help you.


答:
You are reading the numbers from standard input as integers.  Try reading them as strings instead:

   Scanner in = new Scanner(System.in);
   String num = in.nextLine();
   char[] chars = num.toCharArray();
```

Title: Next greatest number


问:
How to build React checkbox tree
I'm trying to work with a checkbox tree component like this: https://www.npmjs.com/package/react-checkbox-tree, except I'm storing the items that I have selected in Redux.  Moreover, the only items that I'm actually storing are the leaf nodes in the tree.  So for example, I'd have the full options data which would be used to render the tree:

```<code>const fam = {
  cuz2: {
    name: 'cuz2',
    children: {
      cuzKid2: {
        name: 'cuzKid2',
        children: {
        }
      }
    }
  },
  grandpa: {
    name: 'grandpa',
    children: {
      dad: {
        name: 'dad',
        children: {
          me: {
           name: 'me',
           children: {}
          },
          sis: {
           name: 'sis',
           children: {}
          }
        }
      },
      aunt: {
        name: 'aunt',
        children: {
          cuz: {
            name: 'cuz',
            children: {
              name: 'cuzkid',
              children: {}
            }
          }
        }
    }
  }
}
</code>```

and a separate object that stores the items selected.  The following would be the only items that would appear if every checkbox was checked:

```<code>const selected = {
 cuz2: true,
 me: true,
 sis: true,
 cuz: true
}
</code>```

I seem to be struggling with this method for having the UI determine which boxes to have fully, partially, or un-checked based on the selected object.  I was wondering if anyone can recommend another strategy of accomplishing this.

答:
So I have used react-checkbox-tree but I have customised a bit the icons in order to use another icons library.

Check my example on sandbox:

Title: How to build React checkbox tree

Body:
I'm trying to work with a checkbox tree component like this: https://www.npmjs.com/package/react-checkbox-tree, except I'm storing the items that I have selected in Redux.  Moreover, the only items that I'm actually storing are the leaf nodes in the tree.  So for example, I'd have the full options data which would be used to render the tree:

const fam = {
  cuz2: {
    name: 'cuz2',
    children: {
      cuzKid2: {
        name: 'cuzKid2',
        children: {
        }
      }
    }
  },
  grandpa: {
    name: 'grandpa',
    children: {
      dad: {
        name: 'dad',
        children: {
          me: {
           name: 'me',
           children: {}
          },
          sis: {
           name: 'sis',
           children: {}
          }
        }
      },
      aunt: {
        name: 'aunt',
        children: {
          cuz: {
            name: 'cuz',
            children: {
              name: 'cuzkid',
              children: {}
            }
          }
        }
    }
  }
}

and a separate object that stores the items selected.  The following would be the only items that would appear if every checkbox was checked:

const selected = {
 cuz2: true,
 me: true,
 sis: true,
 cuz: true
}

I seem to be struggling with this method for having the UI determine which boxes to have fully, partially, or un-checked based on the selected object.  I was wondering if anyone can recommend another strategy of accomplishing this.


问:
Regex To Alter Date String
I'm somewhat new to python, and for this assignment we were asked to used a single regular expression to solve each prompt. I've finished prompts A-C, but now I'm stuck on prompt D.
Here's the prompt:

d.  A  substitution,  using  a  regular  expression,  that  converts a date  in  either  the  format  “May 29, 2019”  or  “May 29 2019”  to  “29 May 19”.

A valid  date  format  to  match  has  these elements:
•The  month  must  be  the  common  three  letter  month  abbreviation  beginning  with  a  capital  letter followed by two lower case letters:  Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec.

•The day may be one or two digits. It is not necessary to check for a valid day and dates with leading zeros are acceptable such as 03.
•The year is exactly four digits.

•The month and day are separated by one or more spaces. The day and year are also separated by  one  or  more  spaces  but  an  optional  comma  immediately  after  the  day  is  permitted  (no  spaces between the day and comma are permitted)

What I'm stuck on: I'm not sure what to put in the r"..." statement (refer to code), with what I have now I get an error "re.error: bad escape \w at position 0", if we could fix the error or find an another way to do it while maintaining the substr = r"..." I would really appreciate it! Thank you!

Note:
--my re.compile code works just fine, before I messed with the substring to change the output, it accepted the case. It just didn't convert it as I had not written the conversion string yet.
--At the moment how im processing dates isn't very conventional, i plan on working on that after getting something that works.

Code:

```<code>import re

d = re.compile(r"^((Jan)\s+[1-31],\s+\d{4})$|"
               r"^((Jan)\s+[1-31]\s+\d{4})$|"
               r"^((Feb)\s+[1-28],\s+\d{4})$|"
               r"^((Feb)\s+[1-28]\s+\d{4})$|"
               r"^((Feb)\s+[1-29],\s+\d{4})$|" #ask prof about leap years
               r"^((Feb)\s+[1-29]\s+\d{4})$|"  #ask prof about leap years
               r"^((Mar)\s+[1-31],\s+\d{4})$|"
               r"^((Mar)\s+[1-31]\s+\d{4})$|"
               r"^((Apr)\s+[1-30],\s+\d{4})$|"
               r"^((Apr)\s+[1-30]\s+\d{4})$|"
               r"^((May)\s+[1-31],\s+\d{4})$|"
               r"^((May)\s+[1-31]\s+\d{4})$|"
               r"^((Jun)\s+[1-30],\s+\d{4})$|"
               r"^((Jun)\s+[1-30]\s+\d{4})$|"
               r"^((Jul)\s+[1-31],\s+\d{4})$|"
               r"^((Jul)\s+[1-31]\s+\d{4})$|"
               r"^((Aug)\s+[1-31],\s+\d{4})$|"
               r"^((Aug)\s+[1-31]\s+\d{4})$|"
               r"^((Sep)\s+[1-30],\s+\d{4})$|"
               r"^((Sep)\s+[1-30]\s+\d{4})$|"
               r"^((Oct)\s+[1-31],\s+\d{4})$|"
               r"^((Oct)\s+[1-31]\s+\d{4})$|"
               r"^((Nov)\s+[1-30],\s+\d{4})$|"
               r"^((Nov)\s+[1-30]\s+\d{4})$|"
               r"^((Dec)\s+[1-31],\s+\d{4})$|"
               r"^((Dec)\s+[1-31]\s+\d{4})$")

subStr = r"\w\s\d{1,2}\s\d{4}"

print("----Part d tests that match (and should change):")
print(d.sub(subStr, "May 29, 2019"))

print("----Part d tests that match (and should remain unchanged):")
print(d.sub(subStr, "May 29 19"))

</code>```

Expected output:

```<code>----Part d tests that match (and should change):
May 29 19
----Part d tests that match (and should remain unchanged):
May 29 19
</code>```

Actual output(if i left the substring blank, and how it currently is):

```<code>Blank:
----Part d tests that match (and should change):
May 29, 2019
----Part d tests that match (and should remain unchanged):
May 29 19

--------------------------------
Current:
----Part d tests that match (and should change):
    this = chr(ESCAPES[this][1])
KeyError: '\\w'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/Xavier/PycharmProjects/hw7/hw7.py", line 101, in <module>
    print(d.sub(subStr, "May 29, 2019"))
  File "C:\Users\Xavier\AppData\Local\Programs\Python\Python37\lib\re.py", line 309, in _subx
    template = _compile_repl(template, pattern)
  File "C:\Users\Xavier\AppData\Local\Programs\Python\Python37\lib\re.py", line 300, in _compile_repl
    return sre_parse.parse_template(repl, pattern)
  File "C:\Users\Xavier\AppData\Local\Programs\Python\Python37\lib\sre_parse.py", line 1024, in parse_template
    raise s.error('bad escape %s' % this, len(this))
re.error: bad escape \w at position 0

</code>```

答:
Hints:

(Jan|Feb|Mar) matches and captures the month...extend that for all months.

Square brackets match a single character...[1-31] is effectively [123]...the range 1-3 or 1 (redundant). [0-9] or just \d matches any single digit. The requirements said the date does not need to be validated, so \d{1,2} (match 1 or two digits) should be legal.

? is used for 0 or 1 match so ,? is an optional comma.

4-digit year, but only capture last two: \d{2}(\d{2}).

You should have three capture groups in the match string.  \n where n is the group number inserts what was captured, so the replacement is just r'\2 \1 \3'.

Title: Regex To Alter Date String

Body:
I'm somewhat new to python, and for this assignment we were asked to used a single regular expression to solve each prompt. I've finished prompts A-C, but now I'm stuck on prompt D.
Here's the prompt:

d.  A  substitution,  using  a  regular  expression,  that  converts a date  in  either  the  format  “May 29, 2019”  or  “May 29 2019”  to  “29 May 19”.

A valid  date  format  to  match  has  these elements:
•The  month  must  be  the  common  three  letter  month  abbreviation  beginning  with  a  capital  letter followed by two lower case letters:  Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec.

•The day may be one or two digits. It is not necessary to check for a valid day and dates with leading zeros are acceptable such as 03.
•The year is exactly four digits.

•The month and day are separated by one or more spaces. The day and year are also separated by  one  or  more  spaces  but  an  optional  comma  immediately  after  the  day  is  permitted  (no  spaces between the day and comma are permitted)

What I'm stuck on: I'm not sure what to put in the r"..." statement (refer to code), with what I have now I get an error "re.error: bad escape \w at position 0", if we could fix the error or find an another way to do it while maintaining the substr = r"..." I would really appreciate it! Thank you!

Note:
--my re.compile code works just fine, before I messed with the substring to change the output, it accepted the case. It just didn't convert it as I had not written the conversion string yet.
--At the moment how im processing dates isn't very conventional, i plan on working on that after getting something that works.

Code:

import re

d = re.compile(r"^((Jan)\s+[1-31],\s+\d{4})$|"
               r"^((Jan)\s+[1-31]\s+\d{4})$|"
               r"^((Feb)\s+[1-28],\s+\d{4})$|"
               r"^((Feb)\s+[1-28]\s+\d{4})$|"
               r"^((Feb)\s+[1-29],\s+\d{4})$|" #ask prof about leap years
               r"^((Feb)\s+[1-29]\s+\d{4})$|"  #ask prof about leap years
               r"^((Mar)\s+[1-31],\s+\d{4})$|"
               r"^((Mar)\s+[1-31]\s+\d{4})$|"
               r"^((Apr)\s+[1-30],\s+\d{4})$|"
               r"^((Apr)\s+[1-30]\s+\d{4})$|"
               r"^((May)\s+[1-31],\s+\d{4})$|"
               r"^((May)\s+[1-31]\s+\d{4})$|"
               r"^((Jun)\s+[1-30],\s+\d{4})$|"
               r"^((Jun)\s+[1-30]\s+\d{4})$|"
               r"^((Jul)\s+[1-31],\s+\d{4})$|"
               r"^((Jul)\s+[1-31]\s+\d{4})$|"
               r"^((Aug)\s+[1-31],\s+\d{4})$|"
               r"^((Aug)\s+[1-31]\s+\d{4})$|"
               r"^((Sep)\s+[1-30],\s+\d{4})$|"
               r"^((Sep)\s+[1-30]\s+\d{4})$|"
               r"^((Oct)\s+[1-31],\s+\d{4})$|"
               r"^((Oct)\s+[1-31]\s+\d{4})$|"
               r"^((Nov)\s+[1-30],\s+\d{4})$|"
               r"^((Nov)\s+[1-30]\s+\d{4})$|"
               r"^((Dec)\s+[1-31],\s+\d{4})$|"
               r"^((Dec)\s+[1-31]\s+\d{4})$")

subStr = r"\w\s\d{1,2}\s\d{4}"

print("----Part d tests that match (and should change):")
print(d.sub(subStr, "May 29, 2019"))

print("----Part d tests that match (and should remain unchanged):")
print(d.sub(subStr, "May 29 19"))

Expected output:

----Part d tests that match (and should change):
May 29 19
----Part d tests that match (and should remain unchanged):
May 29 19

Actual output(if i left the substring blank, and how it currently is):

Blank:
----Part d tests that match (and should change):
May 29, 2019
----Part d tests that match (and should remain unchanged):
May 29 19

--------------------------------
Current:
----Part d tests that match (and should change):
    this = chr(ESCAPES[this][1])
KeyError: '\\w'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/Xavier/PycharmProjects/hw7/hw7.py", line 101, in <module>
    print(d.sub(subStr, "May 29, 2019"))
  File "C:\Users\Xavier\AppData\Local\Programs\Python\Python37\lib\re.py", line 309, in _subx
    template = _compile_repl(template, pattern)
  File "C:\Users\Xavier\AppData\Local\Programs\Python\Python37\lib\re.py", line 300, in _compile_repl
    return sre_parse.parse_template(repl, pattern)
  File "C:\Users\Xavier\AppData\Local\Programs\Python\Python37\lib\sre_parse.py", line 1024, in parse_template
    raise s.error('bad escape %s' % this, len(this))
re.error: bad escape \w at position 0


问:
Selenium Duplicate Elements marked with ==$0
How to handle duplicate elements in selenium, where duplicate elements comes marked with ==$0 ?

Go to www.google.com and search for google search button, I have tried iterator and creating list, but, is this correct way of handling ==$0

```<code>driver.findElements(By.xpath("//input[@aria-label='Google Search']"));
</code>```

I want to select second element.

答:
$0 - $4

The $0, $1, $2, $3 and $4 are the historical reference to the last five DOM elements inspected within the Elements panel of google-chrome-devtools or the last five JavaScript heap objects selected in the Profiles panel. $0 returns the most recently selected element or JavaScript object, $1 returns the second most recently selected one, and so on.

In your usecase, you have inspected the Google Search button through the Elements panel. So in the Console drawer, $0 has been evaluated and displays the same element as:

A bit more information about your usecase would have helped us to answer your question in a better way. However every element within the HTML DOM can be identified uniquely using either css-selectors or xpath.

If your usecase is to Google Search any particular term/phrase, you can use the following solution:

```<code>WebElement searchField = driver.findElement(By.name("q"));
searchField.sendKeys("user3245610");
searchField.sendKeys("Keys.RETURN");
</code>```

You can find a detailed relevant discussion in How to click a random link from google search results through Selenium and Python

Body:
How to handle duplicate elements in selenium, where duplicate elements comes marked with ==$0 ?

Go to www.google.com and search for google search button, I have tried iterator and creating list, but, is this correct way of handling ==$0

driver.findElements(By.xpath("//input[@aria-label='Google Search']"));

I want to select second element.

Body:
$0 - $4

The $0, $1, $2, $3 and $4 are the historical reference to the last five DOM elements inspected within the Elements panel of google-chrome-devtools or the last five JavaScript heap objects selected in the Profiles panel. $0 returns the most recently selected element or JavaScript object, $1 returns the second most recently selected one, and so on.

In your usecase, you have inspected the Google Search button through the Elements panel. So in the Console drawer, $0 has been evaluated and displays the same element as:

A bit more information about your usecase would have helped us to answer your question in a better way. However every element within the HTML DOM can be identified uniquely using either css-selectors or xpath.

If your usecase is to Google Search any particular term/phrase, you can use the following solution:

WebElement searchField = driver.findElement(By.name("q"));
searchField.sendKeys("user3245610");
searchField.sendKeys("Keys.RETURN");

You can find a detailed relevant discussion in How to click a random link from google search results through Selenium and Python


答:
If using regex is not mandatory, I would instead use pandas.to_datetime or time.strptime:

pandas

```<code>import pandas as pd

s = "Jun 29, 2019"

try:
   print(pd.to_datetime(s).strftime('%d %b %Y'))

except ValueError:
   print('unrecognized time format!')
</code>```

%b means abbreviation of the month, see the docs for a complete list.

time

or if you don't have pandas installed, use the built-in library time:

```<code>import time

out = None
for pattern in ['%b %d, %Y', '%b %d %Y']:
    try:
        out = time.strftime('%d %b %Y', time.strptime(s, pattern))
    except ValueError:
        continue

if out is None:
    print('Error: Could not read the time')

</code>```

regex

If you do have to use regex for this, you need to replace [1-31]
with e.g. (?:[12]\d|3[01]|\d), see regex tester.

and then you're using re.sub wrongly. You would want to insert capturing groups in the first big regex and then use \1, \2, ... in the replacement string to put them back in, so no \w

Edit

And the only way I can think of using regex and checking for dates would be

```<code>(?:(Jan|Mar|May|Jul|Aug|Oct|Dec) (3[01]|[12]\d|\d)|(Apr|Jun|Sep|Nov) (30|[12]\d|\d)|(Feb) (2[0-9]|[1]\d|\d)),? (\d{4})
</code>```

and using

```<code>subStr = '\1\3\5 \2\4\6 \7'
</code>```

which is incredibly ugly, and does not treat leap years.

Title: Regex To Alter Date String

Body:
If using regex is not mandatory, I would instead use pandas.to_datetime or time.strptime:

pandas

import pandas as pd

s = "Jun 29, 2019"

try:
   print(pd.to_datetime(s).strftime('%d %b %Y'))

except ValueError:
   print('unrecognized time format!')

%b means abbreviation of the month, see the docs for a complete list.

time

or if you don't have pandas installed, use the built-in library time:

import time

out = None
for pattern in ['%b %d, %Y', '%b %d %Y']:
    try:
        out = time.strftime('%d %b %Y', time.strptime(s, pattern))
    except ValueError:
        continue

if out is None:
    print('Error: Could not read the time')

regex

If you do have to use regex for this, you need to replace [1-31]
with e.g. (?:[12]\d|3[01]|\d), see regex tester.

and then you're using re.sub wrongly. You would want to insert capturing groups in the first big regex and then use \1, \2, ... in the replacement string to put them back in, so no \w

Edit

And the only way I can think of using regex and checking for dates would be

(?:(Jan|Mar|May|Jul|Aug|Oct|Dec) (3[01]|[12]\d|\d)|(Apr|Jun|Sep|Nov) (30|[12]\d|\d)|(Feb) (2[0-9]|[1]\d|\d)),? (\d{4})

and using

subStr = '\1\3\5 \2\4\6 \7'

which is incredibly ugly, and does not treat leap years.


问:
How to wait for multiple conditions on invisibility_of_element_located using Selenium through Python
I want to wait for the element to disappear on Selenium, but at the same time I must ensure that all the elements are gone. Right now, it is something like this:

```<code>element = WebDriverWait(driver, 30).until(
    expected_conditions.element_to_be_clickable((By.XPATH, xpath))
)
is_clickable = WebDriverWait(driver, 30).until(
    expected_conditions.invisibility_of_element_located((By.XPATH, layovers[0]))
)
is_clickable_2 = WebDriverWait(driver, 30).until(
    expected_conditions.invisibility_of_element_located((By.XPATH, layovers[1]))
)

if is_clickable and is_clickable_2:
    element.click()
</code>```

And there are more than two elements on the layovers list, which store xpaths as str.

In this case, can I make all of them into a single function that checks the invisibility of the elements, instead of repeating them? (I mean, make the WebDriverWait takes only one call, and not define another wrapper function.)

答:
First thing first :

the moment you write WebDriverWait(driver, 30), an object of web driver wait (Explicit wait) will be created.

Instead you can do something like this :

```<code>wait = WebDriverWait(driver,10)
</code>```

and you can use the reference variable wait as many times as you want in the same class.

You can create a method which will take webdriverwait reference and along with that you can pass xpath or locator as per your requirement.

```<code>def my_method(wait, xpath):
wait.until(
    expected_conditions.invisibility_of_element_located((By.XPATH, layovers[0]))
</code>```

Hope this helps.

Body:
I want to wait for the element to disappear on Selenium, but at the same time I must ensure that all the elements are gone. Right now, it is something like this:

element = WebDriverWait(driver, 30).until(
    expected_conditions.element_to_be_clickable((By.XPATH, xpath))
)
is_clickable = WebDriverWait(driver, 30).until(
    expected_conditions.invisibility_of_element_located((By.XPATH, layovers[0]))
)
is_clickable_2 = WebDriverWait(driver, 30).until(
    expected_conditions.invisibility_of_element_located((By.XPATH, layovers[1]))
)

if is_clickable and is_clickable_2:
    element.click()

And there are more than two elements on the layovers list, which store xpaths as str.

In this case, can I make all of them into a single function that checks the invisibility of the elements, instead of repeating them? (I mean, make the WebDriverWait takes only one call, and not define another wrapper function.)

Body:
First thing first :

the moment you write WebDriverWait(driver, 30), an object of web driver wait (Explicit wait) will be created.

Instead you can do something like this :

wait = WebDriverWait(driver,10)

and you can use the reference variable wait as many times as you want in the same class.

You can create a method which will take webdriverwait reference and along with that you can pass xpath or locator as per your requirement.

def my_method(wait, xpath):
wait.until(
    expected_conditions.invisibility_of_element_located((By.XPATH, layovers[0]))

Hope this helps.


问:
How can I force BigQuery to autodetect schema with all strings?
Is there a way to use --autodect in BigQuery forcing all new fields to be treated as strings?

The issue is the following: I have a csv file separated by \t and where all fields are quoted like this '67.4'. Now, if I simply provide a schema, then the bq load breaks for reasons I cannot understand. If I do bq load --autodect it works fine, but the values are still quoted. Now, I tried to do

```<code>bq load --autodetect --quote="'" --max_bad_records=10000
--field_delimiter="\t" --source_format=CSV
repo:abc.2017 gs://abc/abc_2017-*.csv.gz
</code>```

But it now breaks wih

```<code>- gs://abc/abc_2017-04-16.csv.gz: Error while reading data,
error message: Could not parse '67.4' as int for field
int64_field_35 (position 35) starting at location 2138722
</code>```

Here's one row, fields again are separated by tabs:

'333933353332333633383339333033333337'    '31373335434633'    'pre'           'E' '1' '333933383335333833393333333333383338'  '2017-02-01
  05:13:59' '29'        '333733333330333033323339333933313335333333303333333433393336'      '333333353331333933363338333033373333333833323338333733323330'                                          '3333343234313434'  'R' 'LC'    '100'   '-70.2' '-31.34'            'HSFC310'   'WOMT24I'   '146'   '1'     '05'

Ideas?

答:
Auto detect schema samples up to the first 100 rows so if the column contains all integer for up to the first 100 rows then the data type will be integer. The purpose of --qoute flag is to enclose the column with the specified value.

Example:

```<code>Sample csv data:
col1, col2
1, "2"
</code>```

If you don't specify the --quote then by default it will be ". The data type for col2 will be Integer and the value will be 2.

If you specify the --quote other than the default " then it will enclose the data with that value. Example: --quote="'", col2 will be String type and data value will be "2" (the double quotes itself will be part of the data value)

As of now you can't force auto-detect schema to make all your columns to be of certain datatype, otherwise, it wouldn't be auto-detect after all. You may want to file a feature request to add another flag for bq load (and even in the UI) to make certain columns to be of certain data type (e.g. I want to make column # 1, 2, 15, 100, xxx to be String or All columns should be String/Integer/Numeric, etc...).

Body:
Is there a way to use --autodect in BigQuery forcing all new fields to be treated as strings?

The issue is the following: I have a csv file separated by \t and where all fields are quoted like this '67.4'. Now, if I simply provide a schema, then the bq load breaks for reasons I cannot understand. If I do bq load --autodect it works fine, but the values are still quoted. Now, I tried to do

bq load --autodetect --quote="'" --max_bad_records=10000
--field_delimiter="\t" --source_format=CSV
repo:abc.2017 gs://abc/abc_2017-*.csv.gz

But it now breaks wih

- gs://abc/abc_2017-04-16.csv.gz: Error while reading data,
error message: Could not parse '67.4' as int for field
int64_field_35 (position 35) starting at location 2138722

Here's one row, fields again are separated by tabs:

'333933353332333633383339333033333337'    '31373335434633'    'pre'           'E' '1' '333933383335333833393333333333383338'  '2017-02-01
  05:13:59' '29'        '333733333330333033323339333933313335333333303333333433393336'      '333333353331333933363338333033373333333833323338333733323330'                                          '3333343234313434'  'R' 'LC'    '100'   '-70.2' '-31.34'            'HSFC310'   'WOMT24I'   '146'   '1'     '05'

Ideas?

Body:
Auto detect schema samples up to the first 100 rows so if the column contains all integer for up to the first 100 rows then the data type will be integer. The purpose of --qoute flag is to enclose the column with the specified value.

Example:

Sample csv data:
col1, col2
1, "2"

If you don't specify the --quote then by default it will be ". The data type for col2 will be Integer and the value will be 2.

If you specify the --quote other than the default " then it will enclose the data with that value. Example: --quote="'", col2 will be String type and data value will be "2" (the double quotes itself will be part of the data value)

As of now you can't force auto-detect schema to make all your columns to be of certain datatype, otherwise, it wouldn't be auto-detect after all. You may want to file a feature request to add another flag for bq load (and even in the UI) to make certain columns to be of certain data type (e.g. I want to make column # 1, 2, 15, 100, xxx to be String or All columns should be String/Integer/Numeric, etc...).


问:
Get Referer URL in Spring MVC
How can I get the referer URL in Spring MVC Controller?</p>

答:
In Spring MVC 3 you can get it from request, as @BalusC already said:

```<code>public ModelAndView doSomething(final HttpServletRequest request) {
    final String referer = request.getHeader("referer");
    ...
}
</code>```

but there also exists special annotation @RequestHeader which allow to simplify your code to

```<code>public ModelAndView doSomething(@RequestHeader(value = "referer", required = false) final String referer) {
    ...
}
</code>```

Title: Get Referer URL in Spring MVC

Body:
In Spring MVC 3 you can get it from request, as @BalusC already said:

public ModelAndView doSomething(final HttpServletRequest request) {
    final String referer = request.getHeader("referer");
    ...
}

but there also exists special annotation @RequestHeader which allow to simplify your code to

public ModelAndView doSomething(@RequestHeader(value = "referer", required = false) final String referer) {
    ...
}