问:
Stopped maven install
I am testing a spring boot project with it default pom.xml like that.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
</project>
```

<p>When I am trying to run the command <code>mvn clean install</code> the below two exceptions ProjectBuildingException and UnresolvableModelException appeared like below</p>

<pre class="lang-none prettyprint-override"><code>[INFO] Scanning for projects...
Downloading from central: https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-parent/2.2.4.RELEASE/spring-boot-starter-parent-2.2.4.RELEASE.pom
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[FATAL] Non-resolvable parent POM for com.example:demo:0.0.1-SNAPSHOT: Could not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom:2.2.4.RELEASE from/to central (https://repo.maven.apache.org/maven2): Transfer failed for https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-parent/2.2.4.RELEASE/spring-boot-starter-parent-2.2.4.RELEASE.pom and 'parent.relativePath' points at no local POM @ line 5, column 10
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project com.example:demo:0.0.1-SNAPSHOT (C:\Users\User\Desktop\demo\pom.xml) has 1 error
[ERROR]     Non-resolvable parent POM for com.example:demo:0.0.1-SNAPSHOT: Could not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom:2.2.4.RELEASE from/to central (https://repo.maven.apache.org/maven2): Transfer failed for https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-parent/2.2.4.RELEASE/spring-boot-starter-parent-2.2.4.RELEASE.pom and 'parent.relativePath' points at no local POM @ line 5, column 10: Connect to repo.maven.apache.org:443 [repo.maven.apache.org/151.101.240.215] failed: Connection timed out: connect -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException
</code>```

答: The original log shows that the attempt to connect to https://repo.maven.apache.org/maven2 timed out. This is a, presumably temporary, network problem. </p>

Title: Stopped maven install

Body:
I am testing a spring boot project with it default pom.xml like that.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
</project>

When I am trying to run the command mvn clean install the below two exceptions ProjectBuildingException and UnresolvableModelException appeared like below

[INFO] Scanning for projects...
Downloading from central: https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-parent/2.2.4.RELEASE/spring-boot-starter-parent-2.2.4.RELEASE.pom
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[FATAL] Non-resolvable parent POM for com.example:demo:0.0.1-SNAPSHOT: Could not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom:2.2.4.RELEASE from/to central (https://repo.maven.apache.org/maven2): Transfer failed for https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-parent/2.2.4.RELEASE/spring-boot-starter-parent-2.2.4.RELEASE.pom and 'parent.relativePath' points at no local POM @ line 5, column 10
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project com.example:demo:0.0.1-SNAPSHOT (C:\Users\User\Desktop\demo\pom.xml) has 1 error
[ERROR]     Non-resolvable parent POM for com.example:demo:0.0.1-SNAPSHOT: Could not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom:2.2.4.RELEASE from/to central (https://repo.maven.apache.org/maven2): Transfer failed for https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-parent/2.2.4.RELEASE/spring-boot-starter-parent-2.2.4.RELEASE.pom and 'parent.relativePath' points at no local POM @ line 5, column 10: Connect to repo.maven.apache.org:443 [repo.maven.apache.org/151.101.240.215] failed: Connection timed out: connect -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException


来源: stackexchange

问:
Alternative to using `display:none` on different devices to stop functions firing
I'm currently using CSS media queries to hide things via display:none; for desktop and mobile. While this works fine for minor things I have a dashboard that has a large amount of functionality depending on the device.

At the moment using display:none means that the functions still fire and this puts huge strain on our hosting environment. It's currently taking 16s to load!

Is there an alternate way to only serve the content depending on the device? This way I can stop the desktop functions firing on mobile and vice versa.

Ideally a way of doing it in PHP would be ideal.

答:
I've tried:

```<code><?php if ( wp_is_mobile() ) { ?>
</code>```

This works really well as it stops ALL the functions firing and I can control whether the desktop of mobile function should fire.

ContentLicense: CC BY-SA 4.0

Body:
I've tried:

<?php if ( wp_is_mobile() ) { ?>

This works really well as it stops ALL the functions firing and I can control whether the desktop of mobile function should fire.


问:
Pass two parameters to ng model - Typescript
I'm newbie with angular8.

I have the following template:

```<code><label class="pr-1 selectLabel" [title]="'alphOrder' | translate">{{'alphOrder' | translate}}</label>
<ng-select class="w-25 p-3" placeholder="Select" [items]="(sortingField | async)?.alphOrder" [clearable]="false" [(ngModel)]="HERE" (change)="sortBy('titles', HERE)" [searchable]="false">
</ng-select>
</code>```

On the first line I passed a key to [title] with the translate function.

I would like to do the same thing on the second line with [(ng-model)], with the difference of passing two parameters.

Then I would like to pass the same parameters to the sortBy function.

In both circumstances the parameters must have the translate function.
I would like to understand how to write such a thing, since I never know how to behave with the template syntax...!

答:
I turn the problem around according to your needs.

If you don't have too many elements, you could do something like that in the template (considering that on all the json files of the languages you have put all the same keys):

```<code><ng-select (change)="sortBy(selection)" [(ngModel)]="selection" class="w-25 p-3" placeholder="Select" [clearable]="false" [searchable]="false">
    <ng-option>{{'author' | translate}}</ng-option>
    <ng-option>{{'title' | translate}}</ng-option>
    <ng-option>{{'date' | translate}}</ng-option>

    <!-- and you can continue to unwind elements if there are not too many ... -->

</ng-select>
</code>```

And that's about the template.

As for the component ts file, you can trigger the selected element like this:

```<code>export class myComponent {

    public val: string;

    sortBy(val) {
        console.log("Dropdown selection:", val);

        // do whatever you want with the translatable element
    }
}
</code>```

Body:
I'm newbie with angular8.

I have the following template:

{{'alphOrder' | translate}}
<ng-select class="w-25 p-3" placeholder="Select" [items]="(sortingField | async)?.alphOrder" [clearable]="false" [(ngModel)]="HERE" (change)="sortBy('titles', HERE)" [searchable]="false">
</ng-select>

On the first line I passed a key to [title] with the translate function.

I would like to do the same thing on the second line with [(ng-model)], with the difference of passing two parameters.

Then I would like to pass the same parameters to the sortBy function.

In both circumstances the parameters must have the translate function.
I would like to understand how to write such a thing, since I never know how to behave with the template syntax...!

Body:
I turn the problem around according to your needs.

If you don't have too many elements, you could do something like that in the template (considering that on all the json files of the languages you have put all the same keys):

<ng-select (change)="sortBy(selection)" [(ngModel)]="selection" class="w-25 p-3" placeholder="Select" [clearable]="false" [searchable]="false">
    <ng-option>{{'author' | translate}}</ng-option>
    <ng-option>{{'title' | translate}}</ng-option>
    <ng-option>{{'date' | translate}}</ng-option>

    <!-- and you can continue to unwind elements if there are not too many ... -->

</ng-select>

And that's about the template.

As for the component ts file, you can trigger the selected element like this:

export class myComponent {

    public val: string;

    sortBy(val) {
        console.log("Dropdown selection:", val);

        // do whatever you want with the translatable element
    }
}


问:
Initializer Element is not a constant->Objective C
I am getting "Initializer Element is not a constant" error for the following declaration.</p>

```<code>struct EBD_HEADER
{
    char   x;
    int Key;
    char Number;
    int ID;
    int Version;
}EBD_HEAD;

struct EBD_TRAILER
{
    int Crc_0;
    int Crc_1;
    int  Etx;
}EBD_TRAIL;

static const int EBD_HEADER_SIZE  = sizeof(EBD_HEAD);

static const int EBD_TRAILER_SIZE = sizeof(EBD_TRAIL);

static const int RMH_ENCODED_MSG_OVERHEAD = EBD_HEADER_SIZE +
EBD_TRAILER_SIZE; //**error:Intializer Element is not a constant**
</code>```

答:
static const int in C declares a variable of type int whose value can be assumed (when optimising) not to change. It doesn’t declare a constant, unlike in C++.

If you want integer constants in plain C, you can either use macros as the previous answer suggests, or use an enum instead.  Note that you are allowed to use anonymous enums; e.g.

```<code>enum {
  EBD_HEADER_SIZE = sizeof (EBD_HEAD),
  EBD_TRAILER_SIZE = sizeof (EBD_TRAIL),
  RMH_ENCODED_MSG_OVERHEAD = sizeof (EBD_HEAD) + sizeof (EBD_TRAIL)
};
</code>```

Note that using enum for this purpose is not without its problems; you can only declare constants of integral type this way, and if you decide to use a named enum (either via a tag or via typedef), it’s worth noting that some compilers will choose different sizes or alignments for your type according to the number and values of its member constants.

Obviously, using #define also has a few drawbacks, not least the well-known problems of accidental multiple evaluation of side-effects and operator precedence.

ContentLicense: CC BY-SA 3.0

Body:
I am getting "Initializer Element is not a constant" error for the following declaration.

struct EBD_HEADER
{
    char   x;
    int Key;
    char Number;
    int ID;
    int Version;
}EBD_HEAD;

struct EBD_TRAILER
{
    int Crc_0;
    int Crc_1;
    int  Etx;
}EBD_TRAIL;

static const int EBD_HEADER_SIZE  = sizeof(EBD_HEAD);

static const int EBD_TRAILER_SIZE = sizeof(EBD_TRAIL);

static const int RMH_ENCODED_MSG_OVERHEAD = EBD_HEADER_SIZE +
EBD_TRAILER_SIZE; //**error:Intializer Element is not a constant**

Body:
static const int in C declares a variable of type int whose value can be assumed (when optimising) not to change. It doesn’t declare a constant, unlike in C++.

If you want integer constants in plain C, you can either use macros as the previous answer suggests, or use an enum instead.  Note that you are allowed to use anonymous enums; e.g.

enum {
  EBD_HEADER_SIZE = sizeof (EBD_HEAD),
  EBD_TRAILER_SIZE = sizeof (EBD_TRAIL),
  RMH_ENCODED_MSG_OVERHEAD = sizeof (EBD_HEAD) + sizeof (EBD_TRAIL)
};

Note that using enum for this purpose is not without its problems; you can only declare constants of integral type this way, and if you decide to use a named enum (either via a tag or via typedef), it’s worth noting that some compilers will choose different sizes or alignments for your type according to the number and values of its member constants.

Obviously, using #define also has a few drawbacks, not least the well-known problems of accidental multiple evaluation of side-effects and operator precedence.


答:
Your problem is that you are deleting the items while reading the table. Every time you delete an item, the table is shorter, so you eventually get a list index out of range error.

You could do it this way instead:

```<code>tablica = [[[row for i in range(len(item))] for row in item if row[1] != 0] for item in tablica]
</code>```

Title: Delete list from the list matrix - Python

Body:
I created sorted matrix with ID/ Odometers/ Date. I really need to delete all list where 0 value is on the second position.
I prepared a function and loop but unfortunately I have still below error. I doubt that del [] method is used correctly ?

in zero_clear, if tablica[i][1] == 0: ****

tablica = [
            [
            [21091705,  0,'30.06.2019'],
            [21091705,  0,'29.06.2019'],
            [21091705,  653842,'29.06.2019'],
            [21091705,  641701,'28.06.2019'],
            [21091705,  642000,'27.06.2019'],
            [21091705,  0,'25.06.2019'],
            [21091705,  642030,'25.06.2019'],
            [21091705,  642030,'25.06.2019'],
            [21091705,  637030,'25.06.2019'],
            [21091705,  0,'25.06.2019'],
            [21091705,  0,'17.05.2019'],
            [21091705,  641256,'25.06.2019']
            ],
            [
            [21091703,  487000,'30.06.2019'],
            [21091703,  461524,'29.06.2019'],
            [21091703,  0,'29.06.2019'],
            [21091703,  0,'28.06.2019'],
            [21091703,  427701,'28.06.2019'],
            [21091703,  429000,'27.06.2019']
            ],
            [
            [21091701,  421077,'30.06.2019'],
            [21091701,  453777,'29.06.2019'],
            [21091701,  0,'29.06.2019'],
            [21091701,  427701,'28.06.2019'],
            [21091701,  433123,'27.06.2019']
            ],
            [
            [21091704,  491000,'30.06.2019'],
            [21091704,  0,'29.06.2019'],
            [21091704,  474542,'29.06.2019'],
            [21091704,  427701,'28.06.2019'],
            [21091704,  427701,'28.06.2019'],
            [21091704,  0,'27.06.2019']
            ]
            ]

def zero_clear(tablica):

    for i in range(len(tablica)):

        if tablica[i][1] == 0:
            del tablica[i]

    return tablica

for item in tablica:
    zero_clear(item)

Body:
Your problem is that you are deleting the items while reading the table. Every time you delete an item, the table is shorter, so you eventually get a list index out of range error.

You could do it this way instead:

tablica = [[[row for i in range(len(item))] for row in item if row[1] != 0] for item in tablica]


问:
Is there any Protractor HTTP Mock library available for non angular applications?
Protractor-http-mock requires angular synchronization so this library can not be used to mock protractor tests for non-angular applications. Can anyone suggest which library will be a best suite to mock non-angular (REACT) application with protractor?</p>

答:
There is a protractor plugin called ng-apimock. The ng here does not stand for angular. This is a generic npm package that can be used as a mock server for testing. Protractor offers the plugin that can be configured and used with ng-apimock to create API mocks for non angular applications. Here is the link for you to check it out:
https://www.npmjs.com/package/ng-apimock</p>


问:
How to import my python file in another file in visual studio code
I am using python/selenium in visual studio code. I am trying to import my another python class driverScript which resides in executionEngine module and in the file DriverScript. I have imported as below:

```<code>import driverScript from executionEngine.DriverScript
</code>```

It is producing error:

```<code>Traceback (most recent call last):
  File "c:/Selenium/Selenium-Python Framework/RK_Practice/Tests/mainTest.py", line 5, in <module>
  from executionEngine.DriverScript import driverScript
ModuleNotFoundError: No module named 'executionEngine'
</code>```

How can I import correctly? Your help is very much appreciated.

答: Depends on where executionEngine is supposed to come from. If it's from a package installable via a package manager such as pip or Anaconda, looks like it's not properly installed. If you installed it yourself, you probably need to add the directory containing executionEngine to your PYTHONPATH, so the Python interpreter can find it. This can be done in the VSCode environment files. See the PYTHONPATH section in https://code.visualstudio.com/docs/python/environments

Body:
I am using python/selenium in visual studio code. I am trying to import my another python class driverScript which resides in executionEngine module and in the file DriverScript. I have imported as below:

import driverScript from executionEngine.DriverScript

It is producing error:

Traceback (most recent call last):
  File "c:/Selenium/Selenium-Python Framework/RK_Practice/Tests/mainTest.py", line 5, in <module>
  from executionEngine.DriverScript import driverScript
ModuleNotFoundError: No module named 'executionEngine'

How can I import correctly? Your help is very much appreciated.


问:
How to store and retrieve nested JSON array in laravel 6
I am trying to retrieve the data saved as json in mysql. My migration looks like below:

```<code>Schema::create('items', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name')->nullable();
        $table->json('add_ons')->nullable();
        $table->timestamps();
    });
</code>```

I have tried saving the below JSON from postman and it saved perfectly.

```<code>{
    "itemName": "chicken",
    "addons": {
        "required": false,
        "min": 2,
        "max": 3,
        "data": [
            {
                "name": "sauces",
                "type": [
                    {
                        "name": "white sauce",
                        "type": [
                            {
                                "name": "whiteOne",
                                "price": 10
                            },
                            {
                                "name": "whiteTwo",
                                "price": 20
                            }
                        ]
                    },
                    {
                        "name": "red sauce",
                        "price": 10
                    }
                ]
            }
        ]
    }
}
</code>```

Now, I trying to retrieve the price of 'whiteOne' under 'white sauce' and getting nothing other than null or laravel error response.

I have tried

```<code>Item::whereJsonContains('add_ons->data->name','sauces')->get()
Item::whereJsonContains('add_ons->data->name','sauces')->find(16)
</code>```

After saving the 'add_ons' column has below data:

```<code>{
  "required": false,
  "min": 2,
  "max": 3,
  "data": [
    {
      "name": "sauces",
      "type": [
        {
          "name": "white sauce",
          "type": [
            {
              "name": "whiteOne",
              "price": 10
            },
            {
              "name": "whiteTwo",
              "price": 20
            }
          ]
        },
        {
          "name": "red sauce",
          "price": 10
        }
      ]
    }
  ]
}
</code>```

Can anyone help me ?

答:
I used this function to get the value of the index.

```<code>public function search($array, $key, $value) {
        // RecursiveArrayIterator to traverse an
        // unknown amount of sub arrays within
        // the outer array.
        $arrIt = new \RecursiveArrayIterator($array);

        // RecursiveIteratorIterator used to iterate
        // through recursive iterators
        $it = new \RecursiveIteratorIterator($arrIt);

        foreach ($it as $sub) {

            // Current active sub iterator
            $subArray = $it->getSubIterator();

            if ($subArray[$key] === $value) {
                //$result[] = iterator_to_array($subArray);
                $result = iterator_to_array($subArray);
             }
        }
        return $result;
    }
</code>```

Now when I pass the values in the function I get the appropriate values.

```<code>$item = Item::where('id','=',16)->first();
$res = $this->search($item->add_ons['data'], 'name', 'whiteTwo');
echo $res["name"]." - ".$res['price'] ."<br>";
</code>```

Body:
I am trying to retrieve the data saved as json in mysql. My migration looks like below:

Schema::create('items', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name')->nullable();
        $table->json('add_ons')->nullable();
        $table->timestamps();
    });

I have tried saving the below JSON from postman and it saved perfectly.

{
    "itemName": "chicken",
    "addons": {
        "required": false,
        "min": 2,
        "max": 3,
        "data": [
            {
                "name": "sauces",
                "type": [
                    {
                        "name": "white sauce",
                        "type": [
                            {
                                "name": "whiteOne",
                                "price": 10
                            },
                            {
                                "name": "whiteTwo",
                                "price": 20
                            }
                        ]
                    },
                    {
                        "name": "red sauce",
                        "price": 10
                    }
                ]
            }
        ]
    }
}

Now, I trying to retrieve the price of 'whiteOne' under 'white sauce' and getting nothing other than null or laravel error response.

I have tried

Item::whereJsonContains('add_ons->data->name','sauces')->get()
Item::whereJsonContains('add_ons->data->name','sauces')->find(16)

After saving the 'add_ons' column has below data:

{
  "required": false,
  "min": 2,
  "max": 3,
  "data": [
    {
      "name": "sauces",
      "type": [
        {
          "name": "white sauce",
          "type": [
            {
              "name": "whiteOne",
              "price": 10
            },
            {
              "name": "whiteTwo",
              "price": 20
            }
          ]
        },
        {
          "name": "red sauce",
          "price": 10
        }
      ]
    }
  ]
}

Can anyone help me ?

Body:
I used this function to get the value of the index.

public function search($array, $key, $value) {
        // RecursiveArrayIterator to traverse an
        // unknown amount of sub arrays within
        // the outer array.
        $arrIt = new \RecursiveArrayIterator($array);

        // RecursiveIteratorIterator used to iterate
        // through recursive iterators
        $it = new \RecursiveIteratorIterator($arrIt);

        foreach ($it as $sub) {

            // Current active sub iterator
            $subArray = $it->getSubIterator();

            if ($subArray[$key] === $value) {
                //$result[] = iterator_to_array($subArray);
                $result = iterator_to_array($subArray);
             }
        }
        return $result;
    }

Now when I pass the values in the function I get the appropriate values.

$item = Item::where('id','=',16)->first();
$res = $this->search($item->add_ons['data'], 'name', 'whiteTwo');
echo $res["name"]." - ".$res['price'] ."<br>";


问:
Could not handle request: /api/identity/recovery/v0.9/recover-password WSO2 Identity Server 5.3.0
I'm trying to use password recovery in WSO2 IS 5.3.0, I've updated my configuration follow this guidance https://docs.wso2.com/display/IS530/Password+Recovery ..

The error when I call this recovery password API

curl -X POST -H "Authorization: Basic YWRtaW46YWRtaW4=" -H
  "Content-Type: application/json" -d '{"user": {"username":
  "kim","realm": "PRIMARY","tenant-domain":"carbon.super"},"properties":
  []}'
  "https://localhost:9443/api/identity/recovery/v0.9/recover-password?type=email&notify=true"

The error that i got is :

```<code>ERROR {org.wso2.carbon.tomcat.ext.valves.CompositeValve} -  Could not handle request: /api/identity/recovery/v0.9/recover-password
java.lang.NullPointerException
    at org.wso2.carbon.identity.auth.valve.AuthenticationValve.handleErrorResponse(AuthenticationValve.java:103)
    at org.wso2.carbon.identity.auth.valve.AuthenticationValve.invoke(AuthenticationValve.java:93)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:99)
    at org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
    at org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:57)
    at org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:62)
    at org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:159)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
    at org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:57)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1770)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1729)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
</code>```

Is there any suggestion about this error?

答:
This seems to be a known issue in IS-5.3.0

https://wso2.org/jira/browse/IDENTITY-5944

Use a IS-5.4.0 or higher version. Otherwise, you can find the fix for this issue in the given URL. [1]

[1].https://github.com/wso2-extensions/identity-carbon-auth-rest/pull/44/files

Body:
I'm trying to use password recovery in WSO2 IS 5.3.0, I've updated my configuration follow this guidance https://docs.wso2.com/display/IS530/Password+Recovery ..

The error when I call this recovery password API

curl -X POST -H "Authorization: Basic YWRtaW46YWRtaW4=" -H
  "Content-Type: application/json" -d '{"user": {"username":
  "kim","realm": "PRIMARY","tenant-domain":"carbon.super"},"properties":
  []}'
  "https://localhost:9443/api/identity/recovery/v0.9/recover-password?type=email&notify=true"

The error that i got is :

ERROR {org.wso2.carbon.tomcat.ext.valves.CompositeValve} -  Could not handle request: /api/identity/recovery/v0.9/recover-password
java.lang.NullPointerException
    at org.wso2.carbon.identity.auth.valve.AuthenticationValve.handleErrorResponse(AuthenticationValve.java:103)
    at org.wso2.carbon.identity.auth.valve.AuthenticationValve.invoke(AuthenticationValve.java:93)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:99)
    at org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
    at org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:57)
    at org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:62)
    at org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:159)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
    at org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:57)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1770)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1729)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

Is there any suggestion about this error?


问:
How to keep Windows Service running after computer is restarted?
I have this Windows Service (using SqlDependency) that sends me an e-mail everytime it is started and everytime a new row is inserted on my Sales table (the database has Service Broker enabled).
I also write a log file to register when the service is started, the data is inserted to the table, if the e-mail was successfully sent and when the service is stoped.

When I started the service manually, it worked just fine.

Then I turned my PC off and on again and inserted data on my table
in the database, but nothing happened (no e-mail sent and no
register in my log file).

I restarted the service manually and it worked fine again.

Turned the PC off and on again and nothing heppened again.

I made some research and changed the initialization type to Automatic
and tried again. And nothing happened again.

I changed the initialization type to Automatic Delayed and tried
again. But it didn't work too, even 1 hour after I turned the PC on.

Now I manually restarted the service and the log file registered that
the service stoped and started, I received the email that the service
started and, after I inserted data in my database table, both log
register and email message worked just fine.

Everytime it didn't work, I checked the services manager in Windows and it was marked as "Running".

I don't know if I need to configure something different in my code or in my service properties.
Has anybody ever had this issue?

EDIT

I modified my service and included a timer, so every minute passed it writes the time in my log text file. After I restarted my PC, the log file continued to register the time every minute, but did not register the insert I made in my database table.

My guess is that the service might be losing the database connection when the PC is restarted, so the SqlDependency cannot detect the changes. Does it make any sense?

答:
Your service depends on SQL Server, but your service is probably starting before SQL Server has been started, or finished starting. This may be causing your SqlDependency to fail.

You can mark your service as being dependent on SQL Server, which means:

Windows won't attempt to start your service until SQL Server has started and is ready, and

Starting your service will cause Windows to start SQL Server before it starts your service

This can be achieved on the command-line with the sc command (which will need to be run at an administrative command prompt). If your SQL Server instance is named MSSQLSERVER and your service is named MyService the command would look like this:

sc config MyService depend= MSSQLSERVER
```

Note: The space after = and before MSSQLSERVER matters. The detailed syntax can be found on learn.microsoft.com.

Once this command has run successfully, this is what you'll see when looking at the properties of your service in Control Panel > Administrative Tools > Services:

Body:
Your service depends on SQL Server, but your service is probably starting before SQL Server has been started, or finished starting. This may be causing your SqlDependency to fail.

You can mark your service as being dependent on SQL Server, which means:

Windows won't attempt to start your service until SQL Server has started and is ready, and

Starting your service will cause Windows to start SQL Server before it starts your service

This can be achieved on the command-line with the sc command (which will need to be run at an administrative command prompt). If your SQL Server instance is named MSSQLSERVER and your service is named MyService the command would look like this:

sc config MyService depend= MSSQLSERVER

Note: The space after = and before MSSQLSERVER matters. The detailed syntax can be found on learn.microsoft.com.

Once this command has run successfully, this is what you'll see when looking at the properties of your service in Control Panel > Administrative Tools > Services:


问:
Java sort string both alphabetically and keep ASCII order
The list is: Arrays.asList("Za", "ab", "AB", "Sa", "1ab", "Ab", "!Ab");

If I use stream().sorted() then the order is: !Ab 1ab AB Ab Za ab --> Za should not be in front of ab.

If I use sorted(String.CASE_INSENSITIVE_ORDER) then the order is !Ab 1ab ab AB Ab Za --> This time, AB is behind ab.

Is there any way to combine the two rules so we have list sorted alphabetically and uppercase is greater than lower case?

Added Example: 1AB - A0B - AbD - aBD - abd1 - ZAB
Sorted alphabetically (Z is  never in front of a) and Number >  Uppercase > Lowercase (AbD > aBD)

答:
The problem is that ab and AB are equal; hence themselves are unordered in the result.
So add a normal comparison, as capitals come before small letters.

```<code>list.stream()
    .sorted(String.CASE_INSENSITIVE_ORDER
            .thenComparing(Comparator.naturalOrder()))
</code>```

After comment

```<code>list.stream()
    .sorted(String.CASE_INSENSITIVE_ORDER
            .thenComparing(Comparator.reverseOrder()))
</code>```

Body:
The problem is that ab and AB are equal; hence themselves are unordered in the result.
So add a normal comparison, as capitals come before small letters.

list.stream()
    .sorted(String.CASE_INSENSITIVE_ORDER
            .thenComparing(Comparator.naturalOrder()))

After comment

list.stream()
    .sorted(String.CASE_INSENSITIVE_ORDER
            .thenComparing(Comparator.reverseOrder()))


问:
How to change a variable UITextView after clicking the button?
I create UITextView with a random tag and text, but it is created with one variable, is it possible to update the variable after creation UITextView (by clicking the add button)? Maybe add a random number to it, for example newText1, newText2.. etc.

So that the next UITextView is already created with a new variable?

P.S Sorry, if the question is silly, I just recently started to study Swift

```<code>@IBOutlet weak var addTextButton: UIButton!
@IBOutlet weak var StoriesView: UIView!

var newText = UITextView()

override func viewDidLoad() {
        super.viewDidLoad()
}

@IBAction func addTextButton(_ sender: Any) {

        let maxNumber = 10000
        let i = Int(arc4random_uniform(UInt32(maxNumber)))

        newText = UITextView(frame: CGRect(x: self.StoriesView.frame.origin.x + 40, y: self.StoriesView.frame.origin.y + 40, width: 380, height: 80))
         self.StoriesView.addSubview(newText)

         newText.font = UIFont(name: "Verdana", size: 11)
         newText.text = "TAP TO EDIT #\(i)"
         newText.sizeToFit()
         newText.textColor = UIColor.black
         newText.backgroundColor = UIColor.clear
         newText.tag = i

         newText.isEditable = true
         newText.isSelectable = true
         newText.isUserInteractionEnabled = true
         newText.allowsEditingTextAttributes = true
         newText.translatesAutoresizingMaskIntoConstraints = true

         newText.enablesReturnKeyAutomatically = true

         newText.delegate = self
       }
</code>```

UPD:

```<code>let fontToolbar = UIToolbar(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
        fontToolbar.barStyle = .default
        fontToolbar.items = [
            UIBarButtonItem(title: "Green", style: .plain, target: self, action: #selector(greenColor)),
             UIBarButtonItem(title: "Blue", style: .plain, target: self, action: #selector(blueColor)),
             UIBarButtonItem(title: "Red", style: .plain, target: self, action: #selector(redColor)),
        UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
        UIBarButtonItem(title: "Close Keyboard", style: .plain, target: self, action: #selector(dismissKeyboard))]
        fontToolbar.sizeToFit()
        newText.inputAccessoryView = fontToolbar
</code>```

in the toolBar above the keyboard I have buttons, here we change the color

```<code>@objc func redColor() {
        newText.textColor = UIColor.red}

    @objc func blueColor() {
        newText.textColor = UIColor.blue}

    @objc func greenColor() {
        newText.textColor = UIColor.green}
</code>```

So the color changes only in the newly created UITextView

答:
I have modified your code a bit to have new UITextView object with button click

```<code>import UIKit

class ScannerViewController: UIViewController, UITextViewDelegate {

  @IBOutlet weak var StoriesView: UIView!
  @IBOutlet weak var addTextButton: UIButton!
  var yposition: CGFloat!
  var textFieldTag: [Int]! = []

    override func viewDidLoad() {
    super.viewDidLoad()
    yposition = 20
  }

  @IBAction func addTextButton(_ sender: Any) {

    let xposition = self.StoriesView.frame.origin.x
    let maxNumber = 10000
    let i = Int(arc4random_uniform(UInt32(maxNumber)))
    textFieldTag.append(i)

    let newText = UITextView(frame: CGRect(x: xposition , y: yposition , width: 380, height: 40))
    self.StoriesView.addSubview(newText)

    newText.font = UIFont(name: "Verdana", size: 11)
    newText.text = "TAP TO EDIT #\(i)"
    newText.sizeToFit()
    newText.textColor = UIColor.black
    newText.backgroundColor = UIColor.yellow
    newText.tag = i

    newText.isEditable = true
    newText.isSelectable = true
    newText.isUserInteractionEnabled = true
    newText.allowsEditingTextAttributes = true
    newText.translatesAutoresizingMaskIntoConstraints = true

    newText.enablesReturnKeyAutomatically = true
    newText.delegate = self

    yposition = yposition + 45
  }

  @IBAction func accessTextFields(_ sender: Any) {

    //access all text fields
    for tag in textFieldTag {
      if let textField = self.StoriesView.viewWithTag(tag) as? UITextView {
        //change properties here
        textField.backgroundColor = .cyan
      }
    }

    //access specific text fields
    if let textField = self.StoriesView.viewWithTag(textFieldTag.first!) as? UITextView {
      //change properties here
      textField.backgroundColor = .orange
    }

    if let textField = self.StoriesView.viewWithTag(textFieldTag[textFieldTag.count - 1]) as? UITextView {
      //change properties here
      textField.backgroundColor = .green
    }
  }
}
</code>```

It will have an output as this!!

Body:
I create UITextView with a random tag and text, but it is created with one variable, is it possible to update the variable after creation UITextView (by clicking the add button)? Maybe add a random number to it, for example newText1, newText2.. etc.

So that the next UITextView is already created with a new variable?

P.S Sorry, if the question is silly, I just recently started to study Swift

@IBOutlet weak var addTextButton: UIButton!
@IBOutlet weak var StoriesView: UIView!

var newText = UITextView()

override func viewDidLoad() {
        super.viewDidLoad()
}

@IBAction func addTextButton(_ sender: Any) {

        let maxNumber = 10000
        let i = Int(arc4random_uniform(UInt32(maxNumber)))

        newText = UITextView(frame: CGRect(x: self.StoriesView.frame.origin.x + 40, y: self.StoriesView.frame.origin.y + 40, width: 380, height: 80))
         self.StoriesView.addSubview(newText)

         newText.font = UIFont(name: "Verdana", size: 11)
         newText.text = "TAP TO EDIT #\(i)"
         newText.sizeToFit()
         newText.textColor = UIColor.black
         newText.backgroundColor = UIColor.clear
         newText.tag = i

         newText.isEditable = true
         newText.isSelectable = true
         newText.isUserInteractionEnabled = true
         newText.allowsEditingTextAttributes = true
         newText.translatesAutoresizingMaskIntoConstraints = true

         newText.enablesReturnKeyAutomatically = true

         newText.delegate = self
       }

UPD:

let fontToolbar = UIToolbar(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
        fontToolbar.barStyle = .default
        fontToolbar.items = [
            UIBarButtonItem(title: "Green", style: .plain, target: self, action: #selector(greenColor)),
             UIBarButtonItem(title: "Blue", style: .plain, target: self, action: #selector(blueColor)),
             UIBarButtonItem(title: "Red", style: .plain, target: self, action: #selector(redColor)),
        UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
        UIBarButtonItem(title: "Close Keyboard", style: .plain, target: self, action: #selector(dismissKeyboard))]
        fontToolbar.sizeToFit()
        newText.inputAccessoryView = fontToolbar

in the toolBar above the keyboard I have buttons, here we change the color

@objc func redColor() {
        newText.textColor = UIColor.red}

    @objc func blueColor() {
        newText.textColor = UIColor.blue}

    @objc func greenColor() {
        newText.textColor = UIColor.green}

So the color changes only in the newly created UITextView

Body:
I have modified your code a bit to have new UITextView object with button click

import UIKit

class ScannerViewController: UIViewController, UITextViewDelegate {

  @IBOutlet weak var StoriesView: UIView!
  @IBOutlet weak var addTextButton: UIButton!
  var yposition: CGFloat!
  var textFieldTag: [Int]! = []

    override func viewDidLoad() {
    super.viewDidLoad()
    yposition = 20
  }

  @IBAction func addTextButton(_ sender: Any) {

    let xposition = self.StoriesView.frame.origin.x
    let maxNumber = 10000
    let i = Int(arc4random_uniform(UInt32(maxNumber)))
    textFieldTag.append(i)

    let newText = UITextView(frame: CGRect(x: xposition , y: yposition , width: 380, height: 40))
    self.StoriesView.addSubview(newText)

    newText.font = UIFont(name: "Verdana", size: 11)
    newText.text = "TAP TO EDIT #\(i)"
    newText.sizeToFit()
    newText.textColor = UIColor.black
    newText.backgroundColor = UIColor.yellow
    newText.tag = i

    newText.isEditable = true
    newText.isSelectable = true
    newText.isUserInteractionEnabled = true
    newText.allowsEditingTextAttributes = true
    newText.translatesAutoresizingMaskIntoConstraints = true

    newText.enablesReturnKeyAutomatically = true
    newText.delegate = self

    yposition = yposition + 45
  }

  @IBAction func accessTextFields(_ sender: Any) {

    //access all text fields
    for tag in textFieldTag {
      if let textField = self.StoriesView.viewWithTag(tag) as? UITextView {
        //change properties here
        textField.backgroundColor = .cyan
      }
    }

    //access specific text fields
    if let textField = self.StoriesView.viewWithTag(textFieldTag.first!) as? UITextView {
      //change properties here
      textField.backgroundColor = .orange
    }

    if let textField = self.StoriesView.viewWithTag(textFieldTag[textFieldTag.count - 1]) as? UITextView {
      //change properties here
      textField.backgroundColor = .green
    }
  }
}

It will have an output as this!!


问:
Comparing a bit to a boolean
Say I have a set of flags, encoded in a uint16_t flags. For example, AMAZING_FLAG = 0x02.
Now, I have a function. This function needs to check if I want to change the flag, because if I want to do that, I need to write to flash. And that is expensive. Therefore, I want a check which tells me if flags & AMAZING_FLAG is equal to doSet. This is the first idea:

```<code>setAmazingFlag(bool doSet)
{
    if ((flags & AMAZING_FLAG) != (doSet ? AMAZING_FLAG : 0)) {
        // Really expensive thing
        // Update flags
    }
}
</code>```

This is not an intuitive if statement.
I feel like there should be a better way, something like:

```<code>if ((flags & AMAZING_FLAG) != doSet){

}
</code>```

But this does not actually work, true seems to be equal to 0x01.

So, is there a neat way to compare a bit to a boolean?

答:
You need to convert the bit mask to a boolean statement, which in C is equivalent to values 0 or 1.

(flags & AMAZING_FLAG) != 0. The most common way.

!!(flags & AMAZING_FLAG). Somewhat common, also OK to use, but a bit cryptic.

(bool)(flags & AMAZING_FLAG). Modern C way from C99 and beyond only.

Take any of the above alternatives, then compare it with your boolean using != or ==.

Title: Comparing a bit to a boolean

Body:
Say I have a set of flags, encoded in a uint16_t flags. For example, AMAZING_FLAG = 0x02.
Now, I have a function. This function needs to check if I want to change the flag, because if I want to do that, I need to write to flash. And that is expensive. Therefore, I want a check which tells me if flags & AMAZING_FLAG is equal to doSet. This is the first idea:

setAmazingFlag(bool doSet)
{
    if ((flags & AMAZING_FLAG) != (doSet ? AMAZING_FLAG : 0)) {
        // Really expensive thing
        // Update flags
    }
}

This is not an intuitive if statement.
I feel like there should be a better way, something like:

if ((flags & AMAZING_FLAG) != doSet){

}

But this does not actually work, true seems to be equal to 0x01.

So, is there a neat way to compare a bit to a boolean?


问:
When porting python 2.5 to 3.X, how can I replace "from <module> import *"?
I've got a python 2.5 package with the following structure:

Config.py contains the following line:

```<code>from CommonDefines import *
</code>```

Runnning this code in 3.7 gives the following exception:

File "../../.\ConfigLib\Config.py", line 7, in
      from CommonDefines import * ModuleNotFoundError: No module named 'CommonDefines'

Replacing that line with:

```<code>from .CommonDefines import *
</code>```

... works in 3.7 but gives the following error in 2.5:

SyntaxError: 'import *' not allowed with 'from .'

Is there a way to write this line so that works in both 2.5 and 3.X?

EDIT:

The following doesn't work, since the second import triggers a syntax error in 2.5

```<code>try:
    from CommonDefines import *
except:
    from .CommonDefines import *
</code>```

SyntaxError: 'import *' not allowed with 'from .'

答:
I would just use a proper name-by-name import, but this can be done in a hacky way, for your personal use, using exec:

```<code>try:
    from CommonDefines import *
except ModuleNotFoundError:
    exec('from .CommonDefines import *')
</code>```

You can even swap them and catch the SyntaxError.

Body:
I've got a python 2.5 package with the following structure:

Config.py contains the following line:

from CommonDefines import *

Runnning this code in 3.7 gives the following exception:

File "../../.\ConfigLib\Config.py", line 7, in
      from CommonDefines import * ModuleNotFoundError: No module named 'CommonDefines'

Replacing that line with:

from .CommonDefines import *

... works in 3.7 but gives the following error in 2.5:

SyntaxError: 'import *' not allowed with 'from .'

Is there a way to write this line so that works in both 2.5 and 3.X?

EDIT:

The following doesn't work, since the second import triggers a syntax error in 2.5

try:
    from CommonDefines import *
except:
    from .CommonDefines import *

SyntaxError: 'import *' not allowed with 'from .'

Body:
I would just use a proper name-by-name import, but this can be done in a hacky way, for your personal use, using exec:

try:
    from CommonDefines import *
except ModuleNotFoundError:
    exec('from .CommonDefines import *')

You can even swap them and catch the SyntaxError.


问:
Detecting "ended" event in Blackberry website after playing video
We develop a video website for blackberry. When the user click in a video thumb we redirect him to the video file and the native video player is launched. When the video completes or the user press the Back button it come backs to the site. Its there any way to detect when the video has finished? or maybe when the user goes back to the page?

FYI: we cannot use html5!

Thanks

答: Listen for blur and focus events on the window itself.


问:
Test with many variables: I looking for quick method to introduce each variable in the test
I have some data and I need to compare the average but I am looking for quick method to introduce each sample in the test.

```<code>from scipy import stats

my_variables = ["a","b","c"]
my_variables[0] = [1,2,3]
my_variables[1] = [0,1,2]
my_variables[2] = [2,3,4]

Kruskal_Wallis_test= stats.kruskal(my_variables[0], my_variables[1], my_variables[2])
</code>```

Would be it possible doing something like this?

```<code>Kruskal_Wallis_test= stats.kruskal(my_variables)
</code>```

答:
What about this:

```<code>Kruskal_Wallis_test = stats.kruskal(*my_variables)
</code>```

It uses * to unpack the list.

Body:
I have some data and I need to compare the average but I am looking for quick method to introduce each sample in the test.

from scipy import stats

my_variables = ["a","b","c"]
my_variables[0] = [1,2,3]
my_variables[1] = [0,1,2]
my_variables[2] = [2,3,4]

Kruskal_Wallis_test= stats.kruskal(my_variables[0], my_variables[1], my_variables[2])

Would be it possible doing something like this?

Kruskal_Wallis_test= stats.kruskal(my_variables)

Body:
What about this:

Kruskal_Wallis_test = stats.kruskal(*my_variables)

It uses * to unpack the list.


问:
How to direct the output of a process to stdout and pipe to another process in bash?
How to direct the output of a process to stdout and pipe to another process in bash?

I am using bash shell in mac

I have two python programs generate.py and sum.py

generate.py prints integers to stdout.

when run using python3 generate.py it generates

```<code>1
2
3
4
...
...
</code>```

sum.py just consumes the output of generate.py and keeps the counter and once the generate.py is done sum.py outputs the final value.

however when I run using the following bash command

python3 generate.py >&2 | python3 sum.py I cannot see the output of python3 sum.py

but if I do this python3 generate.py | python3 sum.py I can see the result from sum.py is printed to stdout but I dont see the output from generate.py in stdout.

so what I am looking is to see the output of both generate.py and sum.py while piping the data between them. any idea?

答:
You can do it this way

```<code>python3 generate.py | tee /dev/stderr | python3 sum.py
</code>```

But both "/dev/stderr" and "/dev/tty" are special "device file" and we should avoid using it this way.

This is easier to illustrate with an example. If we construct a chained command with pipeline, the normal expectation is, the whole chained pipeline will behave like a single coherent command (whole pipeline takes input form stdin, and write all output to stdout, and errors goes to stderr).

If I append "|wc -l" at the end (counting number of lines), it will expect it return the number of line for both "generate.py" and "sum.py".

But it will not work this way.

```<code>python3 generate.py | tee /dev/stderr | python3 sum.py | wc -l
</code>```

The wc output will only be "1", which refers to the single line from "sum.py".

About "/dev/tty", it is referring to a "controlling terminal" device file. You can refers to this for more information. But in essence this is not a "device file" which should be used to generate output

Body:
How to direct the output of a process to stdout and pipe to another process in bash?

I am using bash shell in mac

I have two python programs generate.py and sum.py

generate.py prints integers to stdout.

when run using python3 generate.py it generates

1
2
3
4
...
...

sum.py just consumes the output of generate.py and keeps the counter and once the generate.py is done sum.py outputs the final value.

however when I run using the following bash command

python3 generate.py >&2 | python3 sum.py I cannot see the output of python3 sum.py

but if I do this python3 generate.py | python3 sum.py I can see the result from sum.py is printed to stdout but I dont see the output from generate.py in stdout.

so what I am looking is to see the output of both generate.py and sum.py while piping the data between them. any idea?

Body:
You can do it this way

python3 generate.py | tee /dev/stderr | python3 sum.py

But both "/dev/stderr" and "/dev/tty" are special "device file" and we should avoid using it this way.

This is easier to illustrate with an example. If we construct a chained command with pipeline, the normal expectation is, the whole chained pipeline will behave like a single coherent command (whole pipeline takes input form stdin, and write all output to stdout, and errors goes to stderr).

If I append "|wc -l" at the end (counting number of lines), it will expect it return the number of line for both "generate.py" and "sum.py".

But it will not work this way.

python3 generate.py | tee /dev/stderr | python3 sum.py | wc -l

The wc output will only be "1", which refers to the single line from "sum.py".

About "/dev/tty", it is referring to a "controlling terminal" device file. You can refers to this for more information. But in essence this is not a "device file" which should be used to generate output


问:
Get the first value from a DataGridViewRow without selecting the entire row
I have a DataGridView, I want the user to be able to select any value in it and when a button is pressed it should show the first value from that row.

```<code>private void Button_Click(object sender, EventArgs e)
{
     MessageBox.Show(Datagridview.SelectedRows[0].Cells[0].Value.ToString());
}
</code>```

This of course gives an error seeing there is no row selected.

So how can I get the selected row from the selected cell to use in a way that I am able to get the value from the first cell of the row?

The only "solutions" I can find online involve forcing the user to be only able to select the entire row, not cell.

答:
you can keep cell seclection and use the row of CurrentCell

```<code>private void Button_Click(object sender, EventArgs e)
{
     var current = Datagridview.CurrentCell;
     if (current == null) return;
     MessageBox.Show(Datagridview.Rows[current.RowIndex].Cells[0].Value.ToString());
     // or with indexer:
     // MessageBox.Show(Datagridview[0, current.RowIndex].Value.ToString());
}
</code>```

Body:
I have a DataGridView, I want the user to be able to select any value in it and when a button is pressed it should show the first value from that row.

private void Button_Click(object sender, EventArgs e)
{
     MessageBox.Show(Datagridview.SelectedRows[0].Cells[0].Value.ToString());
}

This of course gives an error seeing there is no row selected.

So how can I get the selected row from the selected cell to use in a way that I am able to get the value from the first cell of the row?

The only "solutions" I can find online involve forcing the user to be only able to select the entire row, not cell.

Body:
you can keep cell seclection and use the row of CurrentCell

private void Button_Click(object sender, EventArgs e)
{
     var current = Datagridview.CurrentCell;
     if (current == null) return;
     MessageBox.Show(Datagridview.Rows[current.RowIndex].Cells[0].Value.ToString());
     // or with indexer:
     // MessageBox.Show(Datagridview[0, current.RowIndex].Value.ToString());
}


问:
How to send AWS SES email to same domain that is verified
I have setup Amazon Simple Email Service account on one my my domains. Lets say it example.com

I am not able to send emails to that same domain I have verified.

meaning sending email from noreply@example.com to myemail@example.com is not happening.

I even tried in AWS console's send test email but couldn't send the email.

I couldn't find in AWS SES documentation saying we can't send emails to same domain.

Can we send emails to same domain in AWS SES? If not is it documented in AWS SES?
If yes how can I send them?

答:
I don't see in AWS SES documentation that it doesn't support sending to the same domain name.

I finally got to know that the domain I'm using is configured with Office 365 email provider, the admin have configured Spam filters such a way that it doesn't even enter user's inbox if they recognized it to be sending automated emails from same domain.

Conclusion: its not an issue from Amazon AWS SES but in-house spam filtering.


问:
Does git rebase and or git merge create filed with conflicts marked up?
After I got message about existing conflicts, I found that files with conflicts contain marks like

```<code><<<<<<<<<<<<<<<
</code>```

or

```<code>>>>>>>>>>>>>>>>
</code>```

Is this correct? What is the name of this file format?

答: Conflict marks <<<<, ==== and >>>> could be a result of a conflict in many git commands: rebase, merge, cherry-pick, apply. The result is still a text file and you can open it in any text editor. E.g, I usually use vim instead of mergetool.

Body:
After I got message about existing conflicts, I found that files with conflicts contain marks like

<<<<<<<<<<<<<<<

or

>>>>>>>>>>>>>>>

Is this correct? What is the name of this file format?


问:
how to stop old pact files being merged with new ones, without having to rely on my colleagues knowing to clean the target/pacts folder?
Pact merges pacts at the file level, this is great for merging pacts from multiple tests, but not so great when you want to modify and re-run a test without cleaning the target/pacts folder.

The default junit run config in intellij doesn't clean the target folder before running the tests; I know I can use maven clean/remove the files manually, but this means anyone else who runs these tests locally needs to know to run them a specific way.

I want to merge pacts from multiple tests so I don't want to turn off merging.
I tried implementing a before method that deletes files from the pact folder if they exist, but it was janky.

I'm considering setting the pact folder to a temporary directory that removes itself after the tests are run, but that might interfere with pushing new pacts to the broker, and I don't want to remove the folder too soon/often and end up with missing pacts. Also it's useful to be able to see the files at the end, so auto-removing them isn't ideal.

Is there a nice way to stop old pacts merging with new ones, without relying on people to just know they need to remove old pact files before running a modified test?

答:
Why is it an actual problem for you? As in, yes, the pact file is temporarily bigger than it should be, but what is the actual impact?

You shouldn't be publishing from your local machine anyway, that is a CI concern (I usually restrict by not providing write credentials to local environments) so if all you need is to be able to rerun a unit test then I wouldn't worry.

Alternatively, if you are all using the same IDE you could create an IDE specific config and check it in to the repo that cleans the dir before any target / test is run.


问:
How to define a protocol that specializes a generic protocol, so that it can be used in type declarations?
I'm an Android developer learning iOS development and I'm facing this issue that is trivial with Kotlin/Java interfaces, but I can't get through it with Swift protocols.

Say we have this protocol:

protocol ValueStore {
  associatedtype Value
  var value: Value? { get set }
}
```

<p>In Kotlin/Java, if I want to use a generic abstraction to define a variable type, I just use a generic interface with type parameter:</p>

```val stringStore: ValueStore<String>
```

<p>Since this is not possible in Swift, I tried to create a specialized sub-protocol that defines the associated type:</p>

<pre class="lang-swift prettyprint-override"><code>protocol StringStore: ValueStore where Value == String { }
</code>```

with the intent to use the latter like this:

let stringStore: StringStore
```

The above declaration is what I'm trying to achieve. Yet the compiler tells me Protocol 'StringStore' can only be used as a generic constraint because it has Self or associated type requirements.

Although in type declarations I can use a specialized generic concrete implementation, i.e. UserDefaultsValueStore<String>, this is against the dependency inversion principle.

Is it possible to specialize a protocol with associated type and still maintaining the level of abstraction?

答:
If I understand the question correctly... Try this:

```<code>protocol ValueStoreType {
  associatedtype Value
  var value: Value? { get set }
}

struct ValueStore<T>: ValueStoreType {
  var value: T?
}
</code>```

Then you will be able to do:

```<code>var stringStore: ValueStore<String>
</code>```

Body:
I'm an Android developer learning iOS development and I'm facing this issue that is trivial with Kotlin/Java interfaces, but I can't get through it with Swift protocols.

Say we have this protocol:

protocol ValueStore {
  associatedtype Value
  var value: Value? { get set }
}

In Kotlin/Java, if I want to use a generic abstraction to define a variable type, I just use a generic interface with type parameter:

val stringStore: ValueStore<String>

Since this is not possible in Swift, I tried to create a specialized sub-protocol that defines the associated type:

protocol StringStore: ValueStore where Value == String { }

with the intent to use the latter like this:

let stringStore: StringStore

The above declaration is what I'm trying to achieve. Yet the compiler tells me Protocol 'StringStore' can only be used as a generic constraint because it has Self or associated type requirements.

Although in type declarations I can use a specialized generic concrete implementation, i.e. UserDefaultsValueStore<String>, this is against the dependency inversion principle.

Is it possible to specialize a protocol with associated type and still maintaining the level of abstraction?

Body:
If I understand the question correctly... Try this:

protocol ValueStoreType {
  associatedtype Value
  var value: Value? { get set }
}

struct ValueStore<T>: ValueStoreType {
  var value: T?
}

Then you will be able to do:

var stringStore: ValueStore<String>


问:
How to get which route called a component
I am using react-route-dom, I want to implement this config:

```<code><Route exact path='/test/:id' component={MyComponent}/>
<Route exact path='/test2/:id' component={MyComponent}/>
</code>```

then in MyComponent, I want to make something different depending on which route is calling it.

```<code>const MyComponent = ({info: {param}, info2: {param1, param2}}) => {

  return (
    <div>

    </div>

  )
}

MyComponent.propTypes = {
  info: PropTypes.object.isRequired,
  info2: PropTypes.object.isRequired,
};

const mapStateToProps = (state) => ({
  info: state.info,
  info2: state.info2
});

export default connect(mapStateToProps, {})(MyComponent);
</code>```

How can I get the test or test2 params?

答: You can get access to the entire path using props.location</p>

Body:
I am using react-route-dom, I want to implement this config:

<Route exact path='/test/:id' component={MyComponent}/>
<Route exact path='/test2/:id' component={MyComponent}/>

then in MyComponent, I want to make something different depending on which route is calling it.

const MyComponent = ({info: {param}, info2: {param1, param2}}) => {

  return (

  )
}

MyComponent.propTypes = {
  info: PropTypes.object.isRequired,
  info2: PropTypes.object.isRequired,
};

const mapStateToProps = (state) => ({
  info: state.info,
  info2: state.info2
});

export default connect(mapStateToProps, {})(MyComponent);

How can I get the test or test2 params?


问:
Are all cold observables unicast and all hot observables multicast?
I am reading the documentation about multicasting saying:

In RxJS observables are cold, or unicast by default. These operators can make an observable hot, or multicast, allowing side-effects to be shared among multiple subscribers.

I wonder whether all cold observables are unicast and all hot are multicast, or whether there can be any exceptional cases.

答:
In the link provided by @lagoman (which I've read multiple times but still missed that point) I found some interesting explanation about hot-multicast relationship:

² Hot observables are usually multicast, but they could be listening to a producer that only supports one listener at a time. The grounds for calling it “multicast” at that point are a little fuzzy.


问:
How should i catch and handle 406 error in VUEJS
I have a route where i send to the api the day and h to verify in database if there is an opening in a schedule, if is not the api is sending 406. And i'm getting in console 406 error.
How should i handle that error to have a clean console? </p>

答:
You can simply wrap an api call into try-catch and simply don't to do anything with e in catch part.

```<code>try { ... you code here ... } catch(e){}
</code>```

Body:
You can simply wrap an api call into try-catch and simply don't to do anything with e in catch part.

try { ... you code here ... } catch(e){}


问:
Angular 8 Polling Using Observables
Hey i am upgrading my Project from angular 5 to angular 8. This is the code i was using for polling. </p>

```<code> Observable.interval(this.intervalTime).timeout(600000)
                .takeWhile(() => this.alive)
                .subscribe(i => {
                    this.timeOutValue++;
                    //fun();
                });
</code>```

<p>fun() is setting alive as true or false. But now in angular 8 interval is not defined. Will someone please help me for workaround.  </p>

答:
Use the interval function from 'rxjs' and perform your operations in a pipe.

```<code>import { interval } from 'rxjs';
import { timeout, takeWhile } from 'rxjs/operators';

class MyClass {
  private intervalTime: number;
  private alive: Subject<any> = new Subject<any>();
  private timeOutValue = 0;

  myPollingMethod() {
    interval(this.intervalTime).pipe(
      timeout(600000),
      takeWhile(() => this.alive)
    ).subscribe(i => {
      this.timeOutValue++;
      //fun();
    });
  }
}
</code>```

Title: Angular 8 Polling Using Observables

Body:
Hey i am upgrading my Project from angular 5 to angular 8. This is the code i was using for polling.

 Observable.interval(this.intervalTime).timeout(600000)
                .takeWhile(() => this.alive)
                .subscribe(i => {
                    this.timeOutValue++;
                    //fun();
                });

fun() is setting alive as true or false. But now in angular 8 interval is not defined. Will someone please help me for workaround.

Body:
Use the interval function from 'rxjs' and perform your operations in a pipe.

import { interval } from 'rxjs';
import { timeout, takeWhile } from 'rxjs/operators';

class MyClass {
  private intervalTime: number;
  private alive: Subject<any> = new Subject<any>();
  private timeOutValue = 0;

  myPollingMethod() {
    interval(this.intervalTime).pipe(
      timeout(600000),
      takeWhile(() => this.alive)
    ).subscribe(i => {
      this.timeOutValue++;
      //fun();
    });
  }
}


问:
How to update a record using sequelize for node?
I'm creating a RESTful API with NodeJS, express, express-resource, and Sequelize that is used to manage datasets stored in a MySQL database.

I'm trying to figure out how to properly update a record using Sequelize.

I create a model:

```<code>module.exports = function (sequelize, DataTypes) {
  return sequelize.define('Locale', {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true
    },
    locale: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        len: 2
      }
    },
    visible: {
      type: DataTypes.BOOLEAN,
      defaultValue: 1
    }
  })
}
</code>```

Then, in my resource controller, I define an update action.

In here I want to be able to update the record where the id matches a req.params variable.

First I build a model and then I use the updateAttributes method to update the record.

```<code>const Sequelize = require('sequelize')
const { dbconfig } = require('../config.js')

// Initialize database connection
const sequelize = new Sequelize(dbconfig.database, dbconfig.username, dbconfig.password)

// Locale model
const Locales = sequelize.import(__dirname + './models/Locale')

// Create schema if necessary
Locales.sync()

/**
 * PUT /locale/:id
 */

exports.update = function (req, res) {
  if (req.body.name) {
    const loc = Locales.build()

    loc.updateAttributes({
      locale: req.body.name
    })
      .on('success', id => {
        res.json({
          success: true
        }, 200)
      })
      .on('failure', error => {
        throw new Error(error)
      })
  }
  else
    throw new Error('Data not provided')
}
</code>```

Now, this does not actually produce an update query as I would expect.

Instead, an insert query is executed:

```<code>INSERT INTO `Locales`(`id`, `locale`, `createdAt`, `updatedAt`, `visible`)
VALUES ('1', 'us', '2011-11-16 05:26:09', '2011-11-16 05:26:15', 1)
</code>```

So my question is: What is the proper way to update a record using Sequelize ORM?

答:
If you're here looking for a way to increment a specific field value in a model...

This worked for me as of sequelize@5.21.3

User.increment("field", {by: 1, where: {id: 1});

REF: https://github.com/sequelize/sequelize/issues/7268

Body:
I'm creating a RESTful API with NodeJS, express, express-resource, and Sequelize that is used to manage datasets stored in a MySQL database.

I'm trying to figure out how to properly update a record using Sequelize.

I create a model:

module.exports = function (sequelize, DataTypes) {
  return sequelize.define('Locale', {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true
    },
    locale: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        len: 2
      }
    },
    visible: {
      type: DataTypes.BOOLEAN,
      defaultValue: 1
    }
  })
}

Then, in my resource controller, I define an update action.

In here I want to be able to update the record where the id matches a req.params variable.

First I build a model and then I use the updateAttributes method to update the record.

const Sequelize = require('sequelize')
const { dbconfig } = require('../config.js')

// Initialize database connection
const sequelize = new Sequelize(dbconfig.database, dbconfig.username, dbconfig.password)

// Locale model
const Locales = sequelize.import(__dirname + './models/Locale')

// Create schema if necessary
Locales.sync()

/**
 * PUT /locale/:id
 */

exports.update = function (req, res) {
  if (req.body.name) {
    const loc = Locales.build()

    loc.updateAttributes({
      locale: req.body.name
    })
      .on('success', id => {
        res.json({
          success: true
        }, 200)
      })
      .on('failure', error => {
        throw new Error(error)
      })
  }
  else
    throw new Error('Data not provided')
}

Now, this does not actually produce an update query as I would expect.

Instead, an insert query is executed:

INSERT INTO `Locales`(`id`, `locale`, `createdAt`, `updatedAt`, `visible`)
VALUES ('1', 'us', '2011-11-16 05:26:09', '2011-11-16 05:26:15', 1)

So my question is: What is the proper way to update a record using Sequelize ORM?


问:
cs50 Pset4 problem with blurring an image
Have been stuck at this problem for awhile now and I'm very confused as to why my code isn't compiling as it's supposed to. Im supposed to average out the value of colors of pixel number 5 with its surrounding pixel such that the resulting image will look blurred. Here is my code:

```<code>    // Blur image
    // 1 | 2 | 3
    // -   -   -
    // 4 | 5 | 6
    // -   -   -
    // 7 | 8 | 9
    //assuming i is 5
    void blur(int height, int width, RGBTRIPLE image[height][width])
    {
        RGBTRIPLE copy[height][width];
        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                copy[i][j] = image[i][j];
            }
        }
        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                int red = 0;
                int green = 0;
                int blue = 0;
                float counter = 0;

                // 5
                red += copy[i][j].rgbtRed;
                green += copy[i][j].rgbtGreen;
                blue += copy[i][j].rgbtBlue;
                counter++;

                //1
                if (i - 1 > -1 && j - 1 > -1)
                {
                    red += copy[i - 1][j].rgbtRed;
                    green += copy[i - 1][j].rgbtGreen;
                    blue += copy[i - 1][j].rgbtBlue;
                    counter++;
                }
                // 2
                if (i - 1 > -1)
                {
                    red += copy[i - 1][j].rgbtRed;
                    green += copy[i - 1][j].rgbtGreen;
                    blue += copy[i - 1][j].rgbtBlue;
                    counter++;
                }
                // 3
                if (i - 1 > -1 && j + 1 < height)
                {
                    red += copy[i - 1][j + 1].rgbtRed;
                    green += copy[i - 1][j + 1].rgbtGreen;
                    blue += copy[i - 1][j + 1].rgbtBlue;
                    counter++;
                }
                // 4
                if (j - 1 > -1)
                {
                    red += copy[i][j - 1].rgbtRed;
                    green += copy[i][j - 1].rgbtGreen;
                    blue += copy[i][j - 1].rgbtBlue;
                    counter++;
                }
                // 6
                if (j + 1 < width)
                {
                    red += copy[i][j + 1].rgbtRed;
                    green += copy[i][j + 1].rgbtGreen;
                    blue += copy[i][j + 1].rgbtBlue;
                    counter++;
                }
                // 7
                if (i + 1 < height && j - 1 > -1)
                {
                    red += copy[i + 1][j - 1].rgbtRed;
                    green += copy[i + 1][j - 1].rgbtGreen;
                    blue += copy[i + 1][j - 1].rgbtBlue;
                    counter++;
                }
                // 8
                if (i + 1 < height)
                {
                    red += copy[i + 1][j].rgbtRed;
                    green += copy[i + 1][j].rgbtGreen;
                    blue += copy[i + 1][j].rgbtBlue;
                    counter++;
                }
                // 9
                if (i + 1 < height && j + 1 < width)
                {
                    red += copy[i + 1][j + 1].rgbtRed;
                    green += copy[i + 1][j + 1].rgbtGreen;
                    blue += copy[i + 1][j + 1].rgbtBlue;
                    counter++;
                }

                image[i][j].rgbtRed = round(red/counter);
                image[i][j].rgbtGreen = round(green/counter);
                image[i][j].rgbtBlue = round(blue/counter);
            }
        }
        return;
    }
</code>```

I check the start with the center pixel and check for the existence of surrounding pixels and average the value of the center pixel using the values of its surrounding pixels accordingly. My code compiles fine and it seems to be working when I run it. When I try to run debug50; all the values add up when I was doing some manual testing. However when i tried implementing Check50, this error message shows up

```<code>expected "127 140 149\n", not "130 143 153\n"
Log
testing with sample 3x3 image
first row: (10, 20, 30), (40, 50, 60), (70, 80, 90)
second row: (110, 130, 140), (120, 140, 150), (130, 150, 160)
third row: (200, 210, 220), (220, 230, 240), (240, 250, 255)
running ./testing 3 0...
checking for output "127 140 149\n"...

Expected Output:
127 140 149
Actual Output:
130 143 153
</code>```

Not too sure what went wrong with my code. Any advice would be much appreciated!

答:
```<code>                //1
                if (i - 1 > -1 && j - 1 > -1)
                {
                    red += copy[i - 1][j].rgbtRed;
                    green += copy[i - 1][j].rgbtGreen;
                    blue += copy[i - 1][j].rgbtBlue;
                    counter++;
                }
</code>```

You have used 'j', while it should have been 'j - 1' instead. It should be this:

```<code>                //1
                if (i - 1 > -1 && j - 1 > -1)
                {
                    red += copy[i - 1][j - 1].rgbtRed;
                    green += copy[i - 1][j - 1].rgbtGreen;
                    blue += copy[i - 1][j - 1].rgbtBlue;
                    counter++;
                }
</code>```

Body:
Have been stuck at this problem for awhile now and I'm very confused as to why my code isn't compiling as it's supposed to. Im supposed to average out the value of colors of pixel number 5 with its surrounding pixel such that the resulting image will look blurred. Here is my code:

    // Blur image
    // 1 | 2 | 3
    // -   -   -
    // 4 | 5 | 6
    // -   -   -
    // 7 | 8 | 9
    //assuming i is 5
    void blur(int height, int width, RGBTRIPLE image[height][width])
    {
        RGBTRIPLE copy[height][width];
        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                copy[i][j] = image[i][j];
            }
        }
        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                int red = 0;
                int green = 0;
                int blue = 0;
                float counter = 0;

                // 5
                red += copy[i][j].rgbtRed;
                green += copy[i][j].rgbtGreen;
                blue += copy[i][j].rgbtBlue;
                counter++;

                //1
                if (i - 1 > -1 && j - 1 > -1)
                {
                    red += copy[i - 1][j].rgbtRed;
                    green += copy[i - 1][j].rgbtGreen;
                    blue += copy[i - 1][j].rgbtBlue;
                    counter++;
                }
                // 2
                if (i - 1 > -1)
                {
                    red += copy[i - 1][j].rgbtRed;
                    green += copy[i - 1][j].rgbtGreen;
                    blue += copy[i - 1][j].rgbtBlue;
                    counter++;
                }
                // 3
                if (i - 1 > -1 && j + 1 < height)
                {
                    red += copy[i - 1][j + 1].rgbtRed;
                    green += copy[i - 1][j + 1].rgbtGreen;
                    blue += copy[i - 1][j + 1].rgbtBlue;
                    counter++;
                }
                // 4
                if (j - 1 > -1)
                {
                    red += copy[i][j - 1].rgbtRed;
                    green += copy[i][j - 1].rgbtGreen;
                    blue += copy[i][j - 1].rgbtBlue;
                    counter++;
                }
                // 6
                if (j + 1 < width)
                {
                    red += copy[i][j + 1].rgbtRed;
                    green += copy[i][j + 1].rgbtGreen;
                    blue += copy[i][j + 1].rgbtBlue;
                    counter++;
                }
                // 7
                if (i + 1 < height && j - 1 > -1)
                {
                    red += copy[i + 1][j - 1].rgbtRed;
                    green += copy[i + 1][j - 1].rgbtGreen;
                    blue += copy[i + 1][j - 1].rgbtBlue;
                    counter++;
                }
                // 8
                if (i + 1 < height)
                {
                    red += copy[i + 1][j].rgbtRed;
                    green += copy[i + 1][j].rgbtGreen;
                    blue += copy[i + 1][j].rgbtBlue;
                    counter++;
                }
                // 9
                if (i + 1 < height && j + 1 < width)
                {
                    red += copy[i + 1][j + 1].rgbtRed;
                    green += copy[i + 1][j + 1].rgbtGreen;
                    blue += copy[i + 1][j + 1].rgbtBlue;
                    counter++;
                }

                image[i][j].rgbtRed = round(red/counter);
                image[i][j].rgbtGreen = round(green/counter);
                image[i][j].rgbtBlue = round(blue/counter);
            }
        }
        return;
    }

I check the start with the center pixel and check for the existence of surrounding pixels and average the value of the center pixel using the values of its surrounding pixels accordingly. My code compiles fine and it seems to be working when I run it. When I try to run debug50; all the values add up when I was doing some manual testing. However when i tried implementing Check50, this error message shows up

expected "127 140 149\n", not "130 143 153\n"
Log
testing with sample 3x3 image
first row: (10, 20, 30), (40, 50, 60), (70, 80, 90)
second row: (110, 130, 140), (120, 140, 150), (130, 150, 160)
third row: (200, 210, 220), (220, 230, 240), (240, 250, 255)
running ./testing 3 0...
checking for output "127 140 149\n"...

Expected Output:
127 140 149
Actual Output:
130 143 153

Not too sure what went wrong with my code. Any advice would be much appreciated!

Body:
                //1
                if (i - 1 > -1 && j - 1 > -1)
                {
                    red += copy[i - 1][j].rgbtRed;
                    green += copy[i - 1][j].rgbtGreen;
                    blue += copy[i - 1][j].rgbtBlue;
                    counter++;
                }

You have used 'j', while it should have been 'j - 1' instead. It should be this:

                //1
                if (i - 1 > -1 && j - 1 > -1)
                {
                    red += copy[i - 1][j - 1].rgbtRed;
                    green += copy[i - 1][j - 1].rgbtGreen;
                    blue += copy[i - 1][j - 1].rgbtBlue;
                    counter++;
                }


问:
Laravel Deployment : PHP Error Unable to load dynamic library 'pdo_pgsql'
I want to deploy my laravel app in ubuntu server 18 LTS. So I have install nginx postgres php. But when i try to do php artisan migrate I have this returned error :

This is the errror (a picture beacose of comande line)
.

So I have verify different thing :
First I can access to my data base in localhost with the postgres user.
The laravel app work while database not be required.

In php.ini I have uncomment extention=pdo-pgsql; and extention=pgsql

I have install the php postgres sql extension with this command sudo apt-get install php7.2-pgsql

And this is my .env settings for database in laravel :

```<code>DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5433
DB_DATABASE=THERY //I have already create the database
DB_USERNAME=postgres
DB_PASSWORD=postgres

</code>```

答:
So for my problem they have two solution plus a bonus

If the problem come from php and you don't want to reinstall all you can follow this topic here in ask ubuntu
and use this two command :

```<code>sudo apt-get --purge remove php-common

sudo apt-get install php-common php-pgsql php-cli
</code>```

If you want to correctly install php for laravel with postgresql you can use this comandes:

```<code>#php install comande
sudo apt-get install php-fpm openssl php-common php-curl php-json php-mbstring php-xml php-zip php-pgsql

#make sure to uncomment extension=pdo_pgsql
sudo nano /etc/php/7.2/fpm/php.ini

#restart fpm service to apply settings
sudo systemctl restar php7.2-fpm
</code>```

Finally if you have an [SQLSTATE 08006 error] check if the port in .env file in your laravel app correspond to the listened port in your server (form me the used port is 5432 and not 5433)

Body:
I want to deploy my laravel app in ubuntu server 18 LTS. So I have install nginx postgres php. But when i try to do php artisan migrate I have this returned error :

This is the errror (a picture beacose of comande line)
.

So I have verify different thing :
First I can access to my data base in localhost with the postgres user.
The laravel app work while database not be required.

In php.ini I have uncomment extention=pdo-pgsql; and extention=pgsql

I have install the php postgres sql extension with this command sudo apt-get install php7.2-pgsql

And this is my .env settings for database in laravel :

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5433
DB_DATABASE=THERY //I have already create the database
DB_USERNAME=postgres
DB_PASSWORD=postgres

Body:
So for my problem they have two solution plus a bonus

If the problem come from php and you don't want to reinstall all you can follow this topic here in ask ubuntu
and use this two command :

sudo apt-get --purge remove php-common

sudo apt-get install php-common php-pgsql php-cli

If you want to correctly install php for laravel with postgresql you can use this comandes:

#php install comande
sudo apt-get install php-fpm openssl php-common php-curl php-json php-mbstring php-xml php-zip php-pgsql

#make sure to uncomment extension=pdo_pgsql
sudo nano /etc/php/7.2/fpm/php.ini

#restart fpm service to apply settings
sudo systemctl restar php7.2-fpm

Finally if you have an [SQLSTATE 08006 error] check if the port in .env file in your laravel app correspond to the listened port in your server (form me the used port is 5432 and not 5433)


问:
Eclipse not updating dependency JARs in web deployment
In eclipse, I have a project, say ProjectA, which is a dynamic web module. ProjectB is a library used by ProjectA. I have added ProjectB to ProjectA's web deployment assembly, with the deploy path /WEB-INF/lib/ProjectB.jar.

When I deploy ProjectA onto a Tomcat v6.0 server, everything works fine. However, if I make any changes to ProjectB, no matter what I do, these changes don't seem to be picked up by the deployment.

I have tried the following options Project->Clean... from the main menu, and Clean Module Work Directory... from the server's context menu, but neither works. The only thing that seems to work is deleting the Project, then re-importing it into Eclipse.

Any ideas would be greatly appreciated!

Thanks

答: You could check that ProjectB has to be exported as a dependency to ProjectA (Project Properties -> Java Build Path -> Order and Export). This may solve your problem. But since I usually work with an EAR file myself, I may be mistaken.</p>


问:
Read-only monitoring
So im trying to make a read only filesystem monitoring for all my centos servers. At first it seemed easy but then i ran into a conflict. Basicly i made a script to check and zabbix to monitor the outcome but each server has 1 Read only mount that stops me from getting the correct data.

```<code>#!/bin/bash

if cat /proc/mounts | grep RO  | grep "\srw" > /dev/null
    then
            echo 1
    else
            echo 0

fi
</code>```

So this script will check for read only mounts perfectly but the outcome for "cat /proc/mounts" will allways result in "tmpfs /sys/fs/cgroup tmpfs ro,seclabel,nosuid,nodev,noexec,mode=755 0 0" meaning the monitoring will allways tell me i have an readonly mount. Does anyone know how to make script skip this or has even a better way to monitor readonly ?

答: Try filtering out tmpfs using: | grep -v tmpfs

Title: Read-only monitoring

Body:
So im trying to make a read only filesystem monitoring for all my centos servers. At first it seemed easy but then i ran into a conflict. Basicly i made a script to check and zabbix to monitor the outcome but each server has 1 Read only mount that stops me from getting the correct data.

#!/bin/bash

if cat /proc/mounts | grep RO  | grep "\srw" > /dev/null
    then
            echo 1
    else
            echo 0

fi

So this script will check for read only mounts perfectly but the outcome for "cat /proc/mounts" will allways result in "tmpfs /sys/fs/cgroup tmpfs ro,seclabel,nosuid,nodev,noexec,mode=755 0 0" meaning the monitoring will allways tell me i have an readonly mount. Does anyone know how to make script skip this or has even a better way to monitor readonly ?


Title: Apply timestamp convert to date to multiple columns in Python

Body:
I want to convert two timestamp columns start_date and end_date to normal date columns:

   id     start_date       end_date
0   1  1578448800000  1583632800000
1   2  1582164000000  1582250400000
2   3  1582509600000  1582596000000
3   4  1583373600000  1588557600000
4   5  1582509600000  1582596000000
5   6  1582164000000  1582250400000
6   7  1581040800000  1586224800000
7   8  1582423200000  1582509600000
8   9  1583287200000  1583373600000

The following code works for one timestamp, but how could I apply it to those two columns?
Thanks for your kind helps.

import datetime
timestamp = datetime.datetime.fromtimestamp(1500000000)
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))

Output:

2017-07-14 10:40:00

I also try with pd.to_datetime(df['start_date']/1000).apply(lambda x: x.date()) which give a incorrect result.

0    1970-01-01
1    1970-01-01
2    1970-01-01
3    1970-01-01
4    1970-01-01
5    1970-01-01
6    1970-01-01
7    1970-01-01
8    1970-01-01

Body:
Use DataFrame.apply with list of columns names and to_datetime with parameter unit='ms':

cols = ['start_date', 'end_date']
df[cols] = df[cols].apply(pd.to_datetime, unit='ms')
print (df)
   id          start_date            end_date
0   1 2020-01-08 02:00:00 2020-03-08 02:00:00
1   2 2020-02-20 02:00:00 2020-02-21 02:00:00
2   3 2020-02-24 02:00:00 2020-02-25 02:00:00
3   4 2020-03-05 02:00:00 2020-05-04 02:00:00
4   5 2020-02-24 02:00:00 2020-02-25 02:00:00
5   6 2020-02-20 02:00:00 2020-02-21 02:00:00
6   7 2020-02-07 02:00:00 2020-04-07 02:00:00
7   8 2020-02-23 02:00:00 2020-02-24 02:00:00
8   9 2020-03-04 02:00:00 2020-03-05 02:00:00

EDIT: For dates add lambda function with Series.dt.date:

cols = ['start_date', 'end_date']
df[cols] = df[cols].apply(lambda x: pd.to_datetime(x, unit='ms').dt.date)
print (df)
   id  start_date    end_date
0   1  2020-01-08  2020-03-08
1   2  2020-02-20  2020-02-21
2   3  2020-02-24  2020-02-25
3   4  2020-03-05  2020-05-04
4   5  2020-02-24  2020-02-25
5   6  2020-02-20  2020-02-21
6   7  2020-02-07  2020-04-07
7   8  2020-02-23  2020-02-24
8   9  2020-03-04  2020-03-05

Or convert each column separately:

df['start_date'] = pd.to_datetime(df['start_date'], unit='ms')
df['end_date'] = pd.to_datetime(df['end_date'], unit='ms')
print (df)
   id          start_date            end_date
0   1 2020-01-08 02:00:00 2020-03-08 02:00:00
1   2 2020-02-20 02:00:00 2020-02-21 02:00:00
2   3 2020-02-24 02:00:00 2020-02-25 02:00:00
3   4 2020-03-05 02:00:00 2020-05-04 02:00:00
4   5 2020-02-24 02:00:00 2020-02-25 02:00:00
5   6 2020-02-20 02:00:00 2020-02-21 02:00:00
6   7 2020-02-07 02:00:00 2020-04-07 02:00:00
7   8 2020-02-23 02:00:00 2020-02-24 02:00:00
8   9 2020-03-04 02:00:00 2020-03-05 02:00:00

And for dates:

df['start_date'] = pd.to_datetime(df['start_date'], unit='ms').dt.date
df['end_date'] = pd.to_datetime(df['end_date'], unit='ms').dt.date


问:
How to create custom styles for ng-select
How to reimplement css for

```<code>&.ng-select-focused {
    &:not(.ng-select-opened) > .ng-select-container {
        border-color: $ng-select-highlight;
        box-shadow: $ng-select-box-shadow;
    }
}
</code>```

In official documentation said you have to add class="custom" and than you can implement your own styles, so I've tried this:

```<code>.ng-select.custom {
    &.ng-select-focused {
        &:not(.ng-select-opened) > .ng-select-container {
            border-color: red;
        }
      }
  }
</code>```

but there is no effect. Did I do something wrong?

答:
Try to add : :host ::ng-deep

Example 1 :

```<code>:host ::ng-deep .ng-select.custom {
    &.ng-select-focused {
        &:not(.ng-select-opened) > .ng-select-container {
            border-color: red;
        }
      }
  }
</code>```

Example 2 :

```<code>.ng-select.custom ::ng-deep .ng-select-focused {
  &:not(.ng-select-opened) > .ng-select-container {
    border-color: red;
  }
 }
</code>```

Body:
How to reimplement css for

&.ng-select-focused {
    &:not(.ng-select-opened) > .ng-select-container {
        border-color: $ng-select-highlight;
        box-shadow: $ng-select-box-shadow;
    }
}

In official documentation said you have to add class="custom" and than you can implement your own styles, so I've tried this:

.ng-select.custom {
    &.ng-select-focused {
        &:not(.ng-select-opened) > .ng-select-container {
            border-color: red;
        }
      }
  }

but there is no effect. Did I do something wrong?

Body:
Try to add : :host ::ng-deep

Example 1 :

:host ::ng-deep .ng-select.custom {
    &.ng-select-focused {
        &:not(.ng-select-opened) > .ng-select-container {
            border-color: red;
        }
      }
  }

Example 2 :

.ng-select.custom ::ng-deep .ng-select-focused {
  &:not(.ng-select-opened) > .ng-select-container {
    border-color: red;
  }
 }


问:
Looking for a Macro/VBA Code that removes alternate duplicates
I need a VBA that can help me run through a list in one column and perform the following steps:

Identify every alternate duplicate

Delete the alternate duplicate

Shift the content up, getting rid of the blank cells

The sheet contains only one column.

Example:

Apple

Orange

Strawberry

Apple

Strawberry

Kiwi

Apple

Apple

I would need No. 4, 5 and 8 removed.

I hope that this makes sense.

Thanks a ton :)

答:
Try something like this:</p>

```<code>Sub test()

    Dim i As Long, LastRow As Long

    With ThisWorkbook.Worksheets("Sheet1")

    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        For i = LastRow To 2 Step -1
            If WorksheetFunction.CountIf(.Range("A1:A" & LastRow), .Range("A" & i).Value) > 1 Then
                .Rows(i).EntireRow.Delete
            End If
        Next i

    End With

End Sub
</code>```

Body:
Try something like this:

Sub test()

    Dim i As Long, LastRow As Long

    With ThisWorkbook.Worksheets("Sheet1")

    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        For i = LastRow To 2 Step -1
            If WorksheetFunction.CountIf(.Range("A1:A" & LastRow), .Range("A" & i).Value) > 1 Then
                .Rows(i).EntireRow.Delete
            End If
        Next i

    End With

End Sub


问:
Retrieve the contents of cookies using Java
I need to retrieve the properties of the cookies stored upon visiting a web page. Specifically,

Name

Host

Expiration Date

Is there a library that I can use?

EDIT: I apologize for the lack of detail..
I am employing Selenium to retrieve the WEB page. Asserting the presence of the cookie (and ultimately deleting it) is present in Selenium's native functionality. Reading the contents, however, is something I was hoping to do...

答:
Here is an excellent resource I stumbled upon, using the java.net API -
http://www.hccp.org/java-net-cookie-how-to.html</p>


问:
ERROR 1049 (42000): Unknown database 'mydatabasename'
I am trying to restore database from .sql file , i have created the database in phpmyadmin and also using the create if not exist command in the .sql file which i am restoring to the database and both names of database are same in phpmyadmin and .sql file which is"mydatabase".

Here is the command which i am using to restore database.

```<code>mysql -uroot -pmypassword mydatabase<mydatabase.sql;
</code>```

When i execute the above command i am getting the following error, i have also given all the permission to the user upon this database.

```<code>ERROR 1049 (42000): Unknown database 'mydatabasename'
</code>```

答:
I found these lines in one of the .sql files

"To connect with a manager that does not use port 3306, you must specify the port number:

```<code>$mysqli = new mysqli('127.0.0.0.1','user','password','database','3307');
</code>```

or, in procedural terms:

```<code>$mysqli = mysqli_connect('127.0.0.0.1','user','password','database','3307');"
</code>```

It resolved the error for me . So i will suggest must use port number while making connection to server to resolve the error 1049(unknown database).

Body:
I am trying to restore database from .sql file , i have created the database in phpmyadmin and also using the create if not exist command in the .sql file which i am restoring to the database and both names of database are same in phpmyadmin and .sql file which is"mydatabase".

Here is the command which i am using to restore database.

mysql -uroot -pmypassword mydatabase<mydatabase.sql;

When i execute the above command i am getting the following error, i have also given all the permission to the user upon this database.

ERROR 1049 (42000): Unknown database 'mydatabasename'

Body:
I found these lines in one of the .sql files

"To connect with a manager that does not use port 3306, you must specify the port number:

$mysqli = new mysqli('127.0.0.0.1','user','password','database','3307');

or, in procedural terms:

$mysqli = mysqli_connect('127.0.0.0.1','user','password','database','3307');"

It resolved the error for me . So i will suggest must use port number while making connection to server to resolve the error 1049(unknown database).