问:
Netbeans not showing Known Archetypes with new Project from Archetype
I have a problem with NetBeans when I try to create a new project, it does not show all options of archetypes to create a project.

I work in Windows 10, and I already have added maven to the user path. It works when i use mvn -v in the Windows console.

答:
I found the solution, the problem is produced because The Central Repository no longer supports insecure communication over plain HTTP and requires that all requests to the repository are encrypted over HTTPS.

To solve this, i have to modify the file "NetbeansLocationPath/java/maven/conf/settings.xml"
and add the next lines in the mirros tags.

```<code>    <mirror>
      <id>other-mirror</id>
      <mirrorOf>central</mirrorOf>
      <name>Other Mirror Repository</name>
      <url>http://insecure.repo1.maven.org/maven2/</url>
    </mirror>
    <mirror>
      <id>internal-repository</id>
      <name>Maven Repository Manager running on https://repo1.maven.org/maven2</name>
      <url>https://repo1.maven.org/maven2</url>
      <mirrorOf>*</mirrorOf>
    </mirror>
  </mirrors>
</code>```

Body:
I found the solution, the problem is produced because The Central Repository no longer supports insecure communication over plain HTTP and requires that all requests to the repository are encrypted over HTTPS.

To solve this, i have to modify the file "NetbeansLocationPath/java/maven/conf/settings.xml"
and add the next lines in the mirros tags.

    <mirror>
      <id>other-mirror</id>
      <mirrorOf>central</mirrorOf>
      <name>Other Mirror Repository</name>
      <url>http://insecure.repo1.maven.org/maven2/</url>
    </mirror>
    <mirror>
      <id>internal-repository</id>
      <name>Maven Repository Manager running on https://repo1.maven.org/maven2</name>
      <url>https://repo1.maven.org/maven2</url>
      <mirrorOf>*</mirrorOf>
    </mirror>
  </mirrors>


来源: stackexchange

问:
Angular Material mat-button does not seem to work inside of *NgFor when working with an array of hardcoded objects
I am been working in Angular for a few years and have came across something odd. I am not sure if this is a weird Angular issue with the version or somehow I just never came across this specific issue. I also tried this in a new Angular application for my own sanity and the issue seems to still persist.

Essentially I created a getter to return a hardcoded array of objects. Then I loop through the objects in the template to show their data as well as create a button for each item. Now when I do not use MatButtonModule mat-button the button will work as expected. However when I use mat-button the button no longer fires.

Now there are some cases where I can get mat-button to work. If instead of using a getter I call locationsTest  in the template the buttons will work. The getter also works if I return the variable locationsTest . Also if I return an array of string or an array of integers from the getter the mat-button will work and the buttons will fire on click. It seems it only happens with a getter returning a hardcoded array of objects.

Why would this be happening? Below is the use case that fails and I am unsure why this would be occurring. When testing below ensure to import MatButtonModule after installing the @angular/material package or else mat-button does nothing.

component.html

```<code><div *ngFor="let location of locations">
  <div>
    <h4>{{ location.name }}</h4>
    <p>{{ location.address }}</p>
    <p>{{ location.city }} </p>
  </div>
</div>

<button mat-button (click)="GoToLocation()">
  Go To Location
</button>
</code>```

component.ts

```<code>let locationsTest = [
    {
      name: "Walmart",
      address: "123 Mcdougal Street W",
      city: "Toronto"
    },
    {
     name: "Barber Shop",
     address: "22 cat Street",
     city: "Toronto"
   }
 ];

public get locations(): any {
  return [
    {
      name: "Walmart",
      address: "123 Mcdougal Street W",
      city: "Toronto"
    },
    {
     name: "Barber Shop",
     address: "22 cat Street",
     city: "Toronto"
   }
 ];
}

public GoToLocation(): void {
  console.log('Going to Location');
}
</code>```

答:
This issue can be caused by multiple different reasons. I would suggest trying the following as a checklist as these always end up being the reasons for me:

Is Angular Material Installed?

I find sometimes we forget to install Angular material and the error is being hidden because of a different error that has yet to be discovered.

Are the modules imported? In this case MatbuttonModule

This is another common one I have came across where we forgot to import the module and therefor Angular does not know what the component or directive is. In this case potentially Angular does not know what the mat-button directive is but the error is silent because of a different error.

(Most common) You used a getter returning a value that updates itself!

This is my most common issue I find when this doesn't work. It is very common when we develop to return mock data. However if you are creating an Observable or BehaviorSubject within a getter or setting a value in general you may be causing Angular to keep triggering lifecycle methods. This would in turn prevent angular functionality from firing as Angular is busy constantly updating.

Example:

```<code>//TS File:
public get userNames(): Observable<Array<string>> {
  public names = new BehaviorSubject<Array<any>>(null);

  let mockNames = [
    'L1ghtk3ira',
    'Thor4Life',
    'OverwatchKing'
  ];

  names.next(mockNames)

  return names.asObservable();
}

/html file
<ng-container *ngIf="userNames | async as listOfUserNames;'>
  <p *ngFor="let userName of listOfUserNames">
    {{ userName  }}
  </p>
</ng-container>
</code>```

This code above seems harmless however what is truly happening when we use this in a template. When our *ngIf (or even if we did async straight in out *ngFor loop) angular gets the data and during that time sets new data. Angular detects this and decides to perform another change detection when the current change detection has finished. When the next change detection happen this issue repeats itself. So even though you see no change on the screen as the data is the same it creates a neverending loop of change detection. Therefor anything inside the for loop such as (click) events can never be fired as Angular is constantly checking and updating itself.

There are two ways to fix this. The fist is simple, we set the value outside of the getter in any way, in my example I chose to just set it as the initial value. change the past TS file to the following:

```<code>public names = new BehaviorSubject<Array<any>>(
  [
    'L1ghtk3ira',
    'Thor4Life',
    'OverwatchKing'
  ]
);

public get userNames(): Observable<Array<string>> {
  return names.asObservable();
}
</code>```

A good rule of thumb to remember with Angular is if you are using a getter in a template never set a value within the getter as it will trigger an endless sea of change detection. Though this should go without saying in general, though mistakes happen.

ContentLicense: CC BY-SA 4.0

Body:
I am been working in Angular for a few years and have came across something odd. I am not sure if this is a weird Angular issue with the version or somehow I just never came across this specific issue. I also tried this in a new Angular application for my own sanity and the issue seems to still persist.

Essentially I created a getter to return a hardcoded array of objects. Then I loop through the objects in the template to show their data as well as create a button for each item. Now when I do not use MatButtonModule mat-button the button will work as expected. However when I use mat-button the button no longer fires.

Now there are some cases where I can get mat-button to work. If instead of using a getter I call locationsTest  in the template the buttons will work. The getter also works if I return the variable locationsTest . Also if I return an array of string or an array of integers from the getter the mat-button will work and the buttons will fire on click. It seems it only happens with a getter returning a hardcoded array of objects.

Why would this be happening? Below is the use case that fails and I am unsure why this would be occurring. When testing below ensure to import MatButtonModule after installing the @angular/material package or else mat-button does nothing.

component.html

{{ location.name }}

{{ location.address }}

{{ location.city }}

<button mat-button (click)="GoToLocation()">
  Go To Location
</button>

component.ts

let locationsTest = [
    {
      name: "Walmart",
      address: "123 Mcdougal Street W",
      city: "Toronto"
    },
    {
     name: "Barber Shop",
     address: "22 cat Street",
     city: "Toronto"
   }
 ];

public get locations(): any {
  return [
    {
      name: "Walmart",
      address: "123 Mcdougal Street W",
      city: "Toronto"
    },
    {
     name: "Barber Shop",
     address: "22 cat Street",
     city: "Toronto"
   }
 ];
}

public GoToLocation(): void {
  console.log('Going to Location');
}

Body:
This issue can be caused by multiple different reasons. I would suggest trying the following as a checklist as these always end up being the reasons for me:

Is Angular Material Installed?

I find sometimes we forget to install Angular material and the error is being hidden because of a different error that has yet to be discovered.

Are the modules imported? In this case MatbuttonModule

This is another common one I have came across where we forgot to import the module and therefor Angular does not know what the component or directive is. In this case potentially Angular does not know what the mat-button directive is but the error is silent because of a different error.

(Most common) You used a getter returning a value that updates itself!

This is my most common issue I find when this doesn't work. It is very common when we develop to return mock data. However if you are creating an Observable or BehaviorSubject within a getter or setting a value in general you may be causing Angular to keep triggering lifecycle methods. This would in turn prevent angular functionality from firing as Angular is busy constantly updating.

Example:

//TS File:
public get userNames(): Observable<Array<string>> {
  public names = new BehaviorSubject<Array<any>>(null);

  let mockNames = [
    'L1ghtk3ira',
    'Thor4Life',
    'OverwatchKing'
  ];

  names.next(mockNames)

  return names.asObservable();
}

/html file
<ng-container *ngIf="userNames | async as listOfUserNames;'>
  <p *ngFor="let userName of listOfUserNames">
    {{ userName  }}
  </p>
</ng-container>

This code above seems harmless however what is truly happening when we use this in a template. When our *ngIf (or even if we did async straight in out *ngFor loop) angular gets the data and during that time sets new data. Angular detects this and decides to perform another change detection when the current change detection has finished. When the next change detection happen this issue repeats itself. So even though you see no change on the screen as the data is the same it creates a neverending loop of change detection. Therefor anything inside the for loop such as (click) events can never be fired as Angular is constantly checking and updating itself.

There are two ways to fix this. The fist is simple, we set the value outside of the getter in any way, in my example I chose to just set it as the initial value. change the past TS file to the following:

public names = new BehaviorSubject<Array<any>>(
  [
    'L1ghtk3ira',
    'Thor4Life',
    'OverwatchKing'
  ]
);

public get userNames(): Observable<Array<string>> {
  return names.asObservable();
}

A good rule of thumb to remember with Angular is if you are using a getter in a template never set a value within the getter as it will trigger an endless sea of change detection. Though this should go without saying in general, though mistakes happen.


问:
Runtime error with Angular 9 and Ivy: Cannot read property 'id' of undefined ; Zone
We have an Angular 8 project with tests.  We are attempting to upgrade to Angular 9 and went through all the steps in https://update.angular.io/#8.0:9.0l3.  This all went smoothly, no issues.  The app compiles with no errors and all of the tests run fine.  We are getting this error at runtime.  When we turn off Ivy, it runs fine so definitely seems related to Ivy.  </p>

```<code>zone-evergreen.js:659 Unhandled Promise rejection: Cannot read property 'id' of undefined ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read property 'id' of undefined
at registerNgModuleType (core.js:35467)
at core.js:35485
at Array.forEach (<anonymous>)
at registerNgModuleType (core.js:35481)
at core.js:35485
at Array.forEach (<anonymous>)
at registerNgModuleType (core.js:35481)
at new NgModuleFactory$1 (core.js:35649)
at compileNgModuleFactory__POST_R3__ (core.js:41403)
at PlatformRef.bootstrapModule (core.js:41768) TypeError: Cannot read property 'id' of undefined
at registerNgModuleType (http://localhost:8080/vendor.js:41436:27)
at http://localhost:8080/vendor.js:41454:14
at Array.forEach (<anonymous>)
at registerNgModuleType (http://localhost:8080/vendor.js:41450:17)
at http://localhost:8080/vendor.js:41454:14
at Array.forEach (<anonymous>)
at registerNgModuleType (http://localhost:8080/vendor.js:41450:17)
at new NgModuleFactory$1 (http://localhost:8080/vendor.js:41602:13)
at compileNgModuleFactory__POST_R3__ (http://localhost:8080/vendor.js:46530:27)
at PlatformRef.bootstrapModule (http://localhost:8080/vendor.js:46859:16)
</code>```

答:
I was finally able to track down the error.  I had to comment out all the imported modules in app.component.ts, app.module.ts and shared.module.ts and add each module back one at a time.  I finally narrowed it down to the include of angular2-recaptcha. That was including a module called ReCaptchaModule.  I'm currently researching how to upgrade or replace that.

Hopefully this is a good troubleshooting tip to others out there.

Body:
We have an Angular 8 project with tests.  We are attempting to upgrade to Angular 9 and went through all the steps in https://update.angular.io/#8.0:9.0l3.  This all went smoothly, no issues.  The app compiles with no errors and all of the tests run fine.  We are getting this error at runtime.  When we turn off Ivy, it runs fine so definitely seems related to Ivy.

zone-evergreen.js:659 Unhandled Promise rejection: Cannot read property 'id' of undefined ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read property 'id' of undefined
at registerNgModuleType (core.js:35467)
at core.js:35485
at Array.forEach (<anonymous>)
at registerNgModuleType (core.js:35481)
at core.js:35485
at Array.forEach (<anonymous>)
at registerNgModuleType (core.js:35481)
at new NgModuleFactory$1 (core.js:35649)
at compileNgModuleFactory__POST_R3__ (core.js:41403)
at PlatformRef.bootstrapModule (core.js:41768) TypeError: Cannot read property 'id' of undefined
at registerNgModuleType (http://localhost:8080/vendor.js:41436:27)
at http://localhost:8080/vendor.js:41454:14
at Array.forEach (<anonymous>)
at registerNgModuleType (http://localhost:8080/vendor.js:41450:17)
at http://localhost:8080/vendor.js:41454:14
at Array.forEach (<anonymous>)
at registerNgModuleType (http://localhost:8080/vendor.js:41450:17)
at new NgModuleFactory$1 (http://localhost:8080/vendor.js:41602:13)
at compileNgModuleFactory__POST_R3__ (http://localhost:8080/vendor.js:46530:27)
at PlatformRef.bootstrapModule (http://localhost:8080/vendor.js:46859:16)


问:
eWay Payment Gateway
I'm trying to implement the recurring web service from eway(australia).How ever I could not get it to work.

I keep on getting the messeage

"The element 'rebillCustomerCreate' in namespace 'http://www.eway.com.au/gateway/rebill/manageRebill' has incomplete content. List of possible elements expected: 'CustomerRef'."

This is the WSDL: https://www.eway.com.au/gateway/rebill/test/manageRebill_test.asmx?wsdl

I am new to SOAP. Trying to implement it in PHP. Can anyone please point out what I did wrong?

Here is my php Code:

```<code><?php
$URL = "https://www.eway.com.au/gateway/rebill/test/manageRebill_test.asmx?wsdl";
$option = array("trace"=>true);
$client = new SOAPClient($URL, $option);
$functions = $client->__getFunctions();
$headeroptions =array('eWAYCustomerID'=>"87654321",'Username'=>"test@eway.com.au","Password"=>"test");
$header = new SOAPHeader('http://www.eway.com.au/gateway/rebill/manageRebill', 'eWAYHeader',$headeroptions);

$bodyoptions = array(
    "customerTitle" => "Mr",
    "customerFirstName" => "firstname",
    "customerLastName" => "lastname",
    "customerAddress" => "address",
    "customerSuburb" => "someniceplace",
    "customerState" => "somenicestate",
    "customerCompany" => "somecompany",
    "customerPostCode" => "411026",
    "customerCountry" => "australia",
    "customerEmail" => "test@eway.com",
    "customerFax" => "123456",
    "customerPhone1" => "123456",
    "customerPhone2" => "123456",
    "customerRef" => "abc123",
    "customerJobDesc" => "Developer",
    "customerComments" => "Make it work",
    "customerURL" => "www.nicesite.com"
);

try{
    $response = $client->__soapCall("CreateRebillCustomer", $bodyoptions,NULL,$header,$outputHeader);
    echo $client->__getLastRequest();
    //$response = $client->CreateRebillCustomer($bodyoptions);
    var_dump($response);
} catch(SOAPFault $e){
    print $e;
}
?>
</code>```

答:
I suggest you to use the library and sample provided by eWay.

Go to this page. Go to "Source Code" tab. The, download PHP source code. There is instruction also.

ContentLicense: CC BY-SA 3.0

Title: eWay Payment Gateway

Body:
I'm trying to implement the recurring web service from eway(australia).How ever I could not get it to work.

I keep on getting the messeage

"The element 'rebillCustomerCreate' in namespace 'http://www.eway.com.au/gateway/rebill/manageRebill' has incomplete content. List of possible elements expected: 'CustomerRef'."

This is the WSDL: https://www.eway.com.au/gateway/rebill/test/manageRebill_test.asmx?wsdl

I am new to SOAP. Trying to implement it in PHP. Can anyone please point out what I did wrong?

Here is my php Code:

<?php
$URL = "https://www.eway.com.au/gateway/rebill/test/manageRebill_test.asmx?wsdl";
$option = array("trace"=>true);
$client = new SOAPClient($URL, $option);
$functions = $client->__getFunctions();
$headeroptions =array('eWAYCustomerID'=>"87654321",'Username'=>"test@eway.com.au","Password"=>"test");
$header = new SOAPHeader('http://www.eway.com.au/gateway/rebill/manageRebill', 'eWAYHeader',$headeroptions);

$bodyoptions = array(
    "customerTitle" => "Mr",
    "customerFirstName" => "firstname",
    "customerLastName" => "lastname",
    "customerAddress" => "address",
    "customerSuburb" => "someniceplace",
    "customerState" => "somenicestate",
    "customerCompany" => "somecompany",
    "customerPostCode" => "411026",
    "customerCountry" => "australia",
    "customerEmail" => "test@eway.com",
    "customerFax" => "123456",
    "customerPhone1" => "123456",
    "customerPhone2" => "123456",
    "customerRef" => "abc123",
    "customerJobDesc" => "Developer",
    "customerComments" => "Make it work",
    "customerURL" => "www.nicesite.com"
);

try{
    $response = $client->__soapCall("CreateRebillCustomer", $bodyoptions,NULL,$header,$outputHeader);
    echo $client->__getLastRequest();
    //$response = $client->CreateRebillCustomer($bodyoptions);
    var_dump($response);
} catch(SOAPFault $e){
    print $e;
}
?>


问:
AI Platform Notebook Always Python 2
I am trying to create a Python 3 Notebook in GCP AI Platform Notebooks but the kernel is always python 2.

After creating a new "Python 3" notebook, the kernel in the top right correctly shows python 3 but ! python --version returns Python 2.7.13 and

```<code>x = 1
f"{x}"
</code>```

throws a SyntaxError. Selecting Python 3 in the top right, restarting the kernel, and restarting the instance does not change the result.

I can see that python 3 is installed from terminal, $ python3 --version -> Python 3.5.3 so the launcher appears to be busted!

I then SSH'ed onto the instance, and ran jupyter notebook (which correctly points to python 3.5)

```<code>zre@intel-20200218:~$ jupyter notebook
[I 17:55:35.993 NotebookApp] JupyterLab extension loaded from /usr/local/lib/python3.5/dist-packages/jupyterlab
[I 17:55:35.993 NotebookApp] JupyterLab application directory is /usr/local/share/jupyter/lab
[I 17:55:36.453 NotebookApp] Serving notebooks from local directory: /home/zre
</code>```

But still hit this behavior:
enter image description here

答:
This happens because of different python version present in system

```<code>ls /usr/bin/python*
</code>```

when you do this you will be seeing a output like this
    /usr/bin/python  /usr/bin/python2  /usr/bin/python2.7  /usr/bin/python3

    /usr/bin/python3.5  /usr/bin/python3.5m  /usr/bin/python3m

Open ~/.bashrc file and add new alias to change your default python executable

```<code>alias python='/usr/bin/python3.5'
. ~/.bashrc
</code>```

Now check your python version

```<code>python --version
</code>```

Title: AI Platform Notebook Always Python 2

Body:
I am trying to create a Python 3 Notebook in GCP AI Platform Notebooks but the kernel is always python 2.

After creating a new "Python 3" notebook, the kernel in the top right correctly shows python 3 but ! python --version returns Python 2.7.13 and

x = 1
f"{x}"

throws a SyntaxError. Selecting Python 3 in the top right, restarting the kernel, and restarting the instance does not change the result.

I can see that python 3 is installed from terminal, $ python3 --version -> Python 3.5.3 so the launcher appears to be busted!

I then SSH'ed onto the instance, and ran jupyter notebook (which correctly points to python 3.5)

zre@intel-20200218:~$ jupyter notebook
[I 17:55:35.993 NotebookApp] JupyterLab extension loaded from /usr/local/lib/python3.5/dist-packages/jupyterlab
[I 17:55:35.993 NotebookApp] JupyterLab application directory is /usr/local/share/jupyter/lab
[I 17:55:36.453 NotebookApp] Serving notebooks from local directory: /home/zre

But still hit this behavior:
enter image description here

Body:
This happens because of different python version present in system

ls /usr/bin/python*

when you do this you will be seeing a output like this
    /usr/bin/python  /usr/bin/python2  /usr/bin/python2.7  /usr/bin/python3

    /usr/bin/python3.5  /usr/bin/python3.5m  /usr/bin/python3m

Open ~/.bashrc file and add new alias to change your default python executable

alias python='/usr/bin/python3.5'
. ~/.bashrc

Now check your python version

python --version


问:
Check which condition in IF statement is true
Is there any method in JavaScript to define which condition inside IF statement is fulfilled?

For example:

```<code>if(a === 1 || b === 2) {
  // do something apart of fulfilled condition
  if(a === 1) {
    // do something
  } else if(b === 2) {
    // do something else
  }
}
</code>```

Code above working as expected but I'm wondering if there is a clever way to do this easier, especially when there will be more conditions.

Thanks for answers.

答:
you can use Boolean algebra:

let a = 1 , b=24;

let binTests = 0;
binTests |= (a===1)?1:0;
binTests |= (b===2)?2:0;

console.log ( (binTests & 1) ? '(a===1) is true ' : '(a===1) is false '  )
console.log ( (binTests & 2) ? '(b===2) is true ' : '(b===2) is false '  ) ```

Body:
Is there any method in JavaScript to define which condition inside IF statement is fulfilled?

For example:

if(a === 1 || b === 2) {
  // do something apart of fulfilled condition
  if(a === 1) {
    // do something
  } else if(b === 2) {
    // do something else
  }
}

Code above working as expected but I'm wondering if there is a clever way to do this easier, especially when there will be more conditions.

Thanks for answers.


问:
OpenCV: augmenting video stream source .png not rendering transparency as expected
I am trying to create my own face filtering augmented reality program in open-cv. The idea is it will map a beaver to the users face. Currently, I am unable to get proper transperency when loading this image with 'cv2.imread(...)'. It looks black in the background, and often shows partially in certain areas that are white. When I open this image in photoshop, I am fully capable of moving this image on top of a background with expected transparency results. I am wondering if the alpha is not getting rendered properly. Here is the relevent code where I am loading the image in.

```<code>import numpy
import cv2

def augment_stream(face: numpy.array, augment: numpy.array) -> numpy.array:
    face_h, face_w, _ = face.shape
    augment_h, augment_w, _ = augment.shape

    scalar = min(face_h / augment_h, face_w / augment_w)
    delta_augment_h = int(scalar * augment_h)
    delta_augment_w = int(scalar * augment_w)

    delta_augment_shape = (delta_augment_w, delta_augment_h)
    resized_augment = cv2.resize(augment, delta_augment_shape)

    augmented_face = face.copy()
    dark_pixels = (resized_augment < 250).all(axis=2)
    offset_x = int((face_w - delta_augment_w) / 2)
    offset_y = int((face_h - delta_augment_h) / 2)

    augmented_face[offset_y: offset_y+delta_augment_h, offset_x: offset_x+delta_augment_w][dark_pixels] = resized_augment[dark_pixels]

    return augmented_face

def main():
    stream = cv2.VideoCapture(0)
    cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
    augment = cv2.imread('assets/normal.png')
    # tmp = cv2.cvtColor(augment, cv2.COLOR_BGR2GRAY)
    # _,alpha = cv2.threshold(tmp,0,255,cv2.THRESH_BINARY)
    # b, g, r = cv2.split(augment)
    # rgba = [b,g,r, alpha]
    # dst = cv2.merge(rgba,4)
    # cv2.imwrite("assets/normal.png", dst)

    while True:
        ret, border = stream.read()
        border_h, border_w, _ = border.shape

        bw = cv2.equalizeHist(cv2.cvtColor(border, cv2.COLOR_BGR2GRAY))

        rects = cascade.detectMultiScale(bw, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)

        for x, y, w, h in rects:
            y0 = int(y - 0.25*h)
            y1 = int(y + 0.75*h)
            x0 = x
            x1 = x + w

            if x0 < 0 or x1 > border_w or y0 < 0 or y1 > border_h:
                continue

            border[y0: y1, x0: x1] = augment_stream(border[y0: y1, x0: x1], augment)

        cv2.imshow('border', border)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    stream.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main()
</code>```

答:
Using example from question overlay a smaller image on a larger image python OpenCv

I reduced it to show only how to put image

use cv2.IMREAD_UNCHANGED to load it as RGBA.

split it to RGB and A

use A to create masks for image and border

use loop to add channels

```<code>import cv2

stream = cv2.VideoCapture(0)

# load RGBA
augment = cv2.imread('image.png', cv2.IMREAD_UNCHANGED) # load RGBA

# make it smaller then frame - only for test
W = 320
H = 240
augment = cv2.resize(augment, (W, H))

# split image and alpha
image   = augment[:,:,0:3]
alpha   = augment[:,:,3]
mask_image  = alpha / 255.0
mask_border = 1.0 - mask_image

# ROI - region of interest
x1 = 200
y1 = 100
x2 = x1 + W
y2 = y1 + H

while True:
    ret, border = stream.read()

    # copy only in some region (ROI) (don't assign to variable) but gives worse result
    #cv2.copyTo(image, alpha, border[y1:y2, x1:x2])

    for c in range(0, 3): # channels RGB
        border[y1:y2, x1:x2, c] = (image[:, :, c]*mask_image + border[y1:y2, x1:x2, c]*mask_border)

    cv2.imshow('border', border)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

stream.release()
cv2.destroyAllWindows()
</code>```

BTW: I tried to use cv2.copyTo(image, mask_image, border) but it gives worse result - maybe mask/alpha needs 3 channels.

It seems it can be done in C/C++ - how to insert a small size image on to a big image

Body:
I am trying to create my own face filtering augmented reality program in open-cv. The idea is it will map a beaver to the users face. Currently, I am unable to get proper transperency when loading this image with 'cv2.imread(...)'. It looks black in the background, and often shows partially in certain areas that are white. When I open this image in photoshop, I am fully capable of moving this image on top of a background with expected transparency results. I am wondering if the alpha is not getting rendered properly. Here is the relevent code where I am loading the image in.

import numpy
import cv2

def augment_stream(face: numpy.array, augment: numpy.array) -> numpy.array:
    face_h, face_w, _ = face.shape
    augment_h, augment_w, _ = augment.shape

    scalar = min(face_h / augment_h, face_w / augment_w)
    delta_augment_h = int(scalar * augment_h)
    delta_augment_w = int(scalar * augment_w)

    delta_augment_shape = (delta_augment_w, delta_augment_h)
    resized_augment = cv2.resize(augment, delta_augment_shape)

    augmented_face = face.copy()
    dark_pixels = (resized_augment < 250).all(axis=2)
    offset_x = int((face_w - delta_augment_w) / 2)
    offset_y = int((face_h - delta_augment_h) / 2)

    augmented_face[offset_y: offset_y+delta_augment_h, offset_x: offset_x+delta_augment_w][dark_pixels] = resized_augment[dark_pixels]

    return augmented_face

def main():
    stream = cv2.VideoCapture(0)
    cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
    augment = cv2.imread('assets/normal.png')
    # tmp = cv2.cvtColor(augment, cv2.COLOR_BGR2GRAY)
    # _,alpha = cv2.threshold(tmp,0,255,cv2.THRESH_BINARY)
    # b, g, r = cv2.split(augment)
    # rgba = [b,g,r, alpha]
    # dst = cv2.merge(rgba,4)
    # cv2.imwrite("assets/normal.png", dst)

    while True:
        ret, border = stream.read()
        border_h, border_w, _ = border.shape

        bw = cv2.equalizeHist(cv2.cvtColor(border, cv2.COLOR_BGR2GRAY))

        rects = cascade.detectMultiScale(bw, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)

        for x, y, w, h in rects:
            y0 = int(y - 0.25*h)
            y1 = int(y + 0.75*h)
            x0 = x
            x1 = x + w

            if x0 < 0 or x1 > border_w or y0 < 0 or y1 > border_h:
                continue

            border[y0: y1, x0: x1] = augment_stream(border[y0: y1, x0: x1], augment)

        cv2.imshow('border', border)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    stream.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main()

Body:
Using example from question overlay a smaller image on a larger image python OpenCv

I reduced it to show only how to put image

use cv2.IMREAD_UNCHANGED to load it as RGBA.

split it to RGB and A

use A to create masks for image and border

use loop to add channels

import cv2

stream = cv2.VideoCapture(0)

# load RGBA
augment = cv2.imread('image.png', cv2.IMREAD_UNCHANGED) # load RGBA

# make it smaller then frame - only for test
W = 320
H = 240
augment = cv2.resize(augment, (W, H))

# split image and alpha
image   = augment[:,:,0:3]
alpha   = augment[:,:,3]
mask_image  = alpha / 255.0
mask_border = 1.0 - mask_image

# ROI - region of interest
x1 = 200
y1 = 100
x2 = x1 + W
y2 = y1 + H

while True:
    ret, border = stream.read()

    # copy only in some region (ROI) (don't assign to variable) but gives worse result
    #cv2.copyTo(image, alpha, border[y1:y2, x1:x2])

    for c in range(0, 3): # channels RGB
        border[y1:y2, x1:x2, c] = (image[:, :, c]*mask_image + border[y1:y2, x1:x2, c]*mask_border)

    cv2.imshow('border', border)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

stream.release()
cv2.destroyAllWindows()

BTW: I tried to use cv2.copyTo(image, mask_image, border) but it gives worse result - maybe mask/alpha needs 3 channels.

It seems it can be done in C/C++ - how to insert a small size image on to a big image


问:
How do I retrieve the data input from a scanner to use in a method?
Basically I have to write a program that uses data that was inputted by the user and put it in a mathematical formula so it spits out an answer. The formula has to be created as a method. This is what I have so far. When I run the code it lets me input a number, but when I do that the program does not output anything and it just finishes running.</p>

```<code>import java.util.Scanner;

public class Namek {
    static int myMethod(int radius) {
        return ((radius * radius) * (22/7));
    }

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter Radius");
        String radius = keyboard.nextLine();

    }

    private static void myMethod() {
    }
</code>```

答:
You need to call the method passing the radius as parameter of the method. You can check https://www.tutorialspoint.com/java/java_methods.htm
,this link to see how to create and call methods with parameters.

I think what you wanted to do is the following:

```<code>import java.util.*;
public class Namek {
        static int myMethod(int radius) {
            return ((radius * radius) * (22/7));
        }
        public static void main(String[] args) {
            Scanner keyboard = new Scanner(System.in);
            System.out.println("Enter Radius");
            int radius = Integer.valueOf(keyboard.nextLine());
            int area = myMethod(radius);
            System.out.println(area);
        }
}
</code>```

Body:
Basically I have to write a program that uses data that was inputted by the user and put it in a mathematical formula so it spits out an answer. The formula has to be created as a method. This is what I have so far. When I run the code it lets me input a number, but when I do that the program does not output anything and it just finishes running.

import java.util.Scanner;

public class Namek {
    static int myMethod(int radius) {
        return ((radius * radius) * (22/7));
    }

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter Radius");
        String radius = keyboard.nextLine();

    }

    private static void myMethod() {
    }

Body:
You need to call the method passing the radius as parameter of the method. You can check https://www.tutorialspoint.com/java/java_methods.htm
,this link to see how to create and call methods with parameters.

I think what you wanted to do is the following:

import java.util.*;
public class Namek {
        static int myMethod(int radius) {
            return ((radius * radius) * (22/7));
        }
        public static void main(String[] args) {
            Scanner keyboard = new Scanner(System.in);
            System.out.println("Enter Radius");
            int radius = Integer.valueOf(keyboard.nextLine());
            int area = myMethod(radius);
            System.out.println(area);
        }
}


问:
Create variable by html button and use it in outside function
Is there any way to make it work?

I´ve read that "let can be only available inside the scope it's declared, like in for loop, on the other hand "var" can be accessed outside the loop for example"

HTML:

let create = document.getElementById("create");
let add = document.getElementById("add");
let cart = document.getElementById("cart");

create.onclick = function(){
  var foo = "foo";
  console.log(foo);
}

add.onclick = function(){
  cart.innerHTML += foo;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <body>
    <button id="create">create</button>
    <button id="add">Add to cart</button>
    <h2 id="cart">Cart: </h2>
  </body>
  <script type="text/javascript" src="test.js"></script>
</html></code>```

答:
You can attach the click event for add inside the show click event handler function by passing the the variable:

let show = document.getElementById("show");
let add = document.getElementById("add");
let cart = document.getElementById("cart");

show.onclick = function(){
  var foo = "foo";
  console.log(foo);
  add.addEventListener('click', function() { addToCart(foo); });
}

function addToCart(f){
  cart.innerHTML += f;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="show">Show</button>
<button id="add">Add to cart</button>
<h2 id="cart">Cart: </h2></code>```

Body:
Is there any way to make it work?

I´ve read that "let can be only available inside the scope it's declared, like in for loop, on the other hand "var" can be accessed outside the loop for example"

HTML:

let create = document.getElementById("create");
let add = document.getElementById("add");
let cart = document.getElementById("cart");

create.onclick = function(){
  var foo = "foo";
  console.log(foo);
}

add.onclick = function(){
  cart.innerHTML += foo;
}

<!DOCTYPE html>

    <button id="create">create</button>
    <button id="add">Add to cart</button>

Cart:

Body:
You can attach the click event for add inside the show click event handler function by passing the the variable:

let show = document.getElementById("show");
let add = document.getElementById("add");
let cart = document.getElementById("cart");

show.onclick = function(){
  var foo = "foo";
  console.log(foo);
  add.addEventListener('click', function() { addToCart(foo); });
}

function addToCart(f){
  cart.innerHTML += f;
}

<button id="show">Show</button>
<button id="add">Add to cart</button>
<h2 id="cart">Cart: </h2>


问:
Using object when out of scope?
I'm working on a school assignment require to create a char LinkedList from user string input based on a menu of options:

Enter new string and store as linked list character of in an LinkedList class.

Get current length from the LinkedList.

Find index of character in this linked list.

Append another LinkedList to this LinkedList.

I have everything working fine, but now I'm stuck at the menu option part.
So let's say I choose option 1 to enter a string, and then I decide to use that object for case 2 and 3 to get the size and find index. That would not work because the object will be destroyed when out of scope. Is there any proper way that I can use to implement this ?

Simple Code Below

```<code>switch(option){
case 1:
 LinkedList ls1(getInput());
 ls1.printList();
 break;
}
case 2:
cout << "Size of LinkedList: " <<ls1.getSize() << endl; //wouldn't work because ls1 got destroyed when out of scope.
}
</code>```

答:
Declare the object outside the switch statement.</p>

```<code> LinkedList ls1(getInput());
 switch(option){
    case 1:
       ls1.printList();
       break;
   case 2:
      cout << "Size of LinkedList: " <<ls1.getSize() << endl;
      break;
   default:
      break;
 }
</code>```

Title: Using object when out of scope?

Body:
I'm working on a school assignment require to create a char LinkedList from user string input based on a menu of options:

Enter new string and store as linked list character of in an LinkedList class.

Get current length from the LinkedList.

Find index of character in this linked list.

Append another LinkedList to this LinkedList.

I have everything working fine, but now I'm stuck at the menu option part.
So let's say I choose option 1 to enter a string, and then I decide to use that object for case 2 and 3 to get the size and find index. That would not work because the object will be destroyed when out of scope. Is there any proper way that I can use to implement this ?

Simple Code Below

switch(option){
case 1:
 LinkedList ls1(getInput());
 ls1.printList();
 break;
}
case 2:
cout << "Size of LinkedList: " <<ls1.getSize() << endl; //wouldn't work because ls1 got destroyed when out of scope.
}

Body:
Declare the object outside the switch statement.

 LinkedList ls1(getInput());
 switch(option){
    case 1:
       ls1.printList();
       break;
   case 2:
      cout << "Size of LinkedList: " <<ls1.getSize() << endl;
      break;
   default:
      break;
 }


问:
How to lock thread correctly with ReentrantLock or Mutex?
I have an acync method with callback:

```<code>myAsyncMethod(params) {
    handleResult(it)
}
</code>```

I need to convert it to sync method (block and return result) like this:

```<code>val result = mySyncMethod(params)
handleResult(result)
</code>```

I can't re-implement it by another way because this method provided by third-party library.

I am trying to use ReentrantLock:

```<code>fun mySyncMethod(params:Type) {
    Log.d("tag", "1")
    val result = null
    val mutex = ReentrantLock()
    myAsyncMethod(params) {
        Log.d("tag", "3")
        result = it
        mutex.unlock()
    }
    Log.d("tag", "2")
    mutex.lock()
    Log.d("tag", "4")
    return result
}

handleResult(mySyncMethod(params))
</code>```

I wait that I should see 1, 2, 3, 4. But I get 1, 2, 4, 3 and null in handleResult. I am trying the same with mutex but with the same result. How to make it works?

P.S. Sure I can use synchronized, but in this case I have to use Object-variable additionally.

答:
Here is my code first. I used a thread instead of your method to test myself.

```<code>fun main() {
    val mutex = ReentrantLock(true)
    val asyncCondition = mutex.newCondition()
    mutex.lock()
    try
    {
        print(1)

        thread {
            mutex.lock()
            try
            {
                print(2)
            }
            finally
            {
                asyncCondition.signalAll()
                mutex.unlock()
            }
        }

        asyncCondition.await()
        print(3)
    }
    finally
    {
        mutex.unlock()
    }
}
</code>```

Java's ReentrnatLock.lock method will block a thread when it is already locked on the only same thread. Since you are trying to lock an async thread from another thread, your code is not working. To block or release another thread, you may use a Condition like my code.

The reason why I am using try..finallystatement everywhere is that if an exception occurred after locking a thread, you are going to meet the infinity loop, so you must be careful about this case.

You may see these references.

Concurrency (ReentrantLock) in different threads

How do java.util.concurrent.locks.Condition work?

Body:
I have an acync method with callback:

myAsyncMethod(params) {
    handleResult(it)
}

I need to convert it to sync method (block and return result) like this:

val result = mySyncMethod(params)
handleResult(result)

I can't re-implement it by another way because this method provided by third-party library.

I am trying to use ReentrantLock:

fun mySyncMethod(params:Type) {
    Log.d("tag", "1")
    val result = null
    val mutex = ReentrantLock()
    myAsyncMethod(params) {
        Log.d("tag", "3")
        result = it
        mutex.unlock()
    }
    Log.d("tag", "2")
    mutex.lock()
    Log.d("tag", "4")
    return result
}

handleResult(mySyncMethod(params))

I wait that I should see 1, 2, 3, 4. But I get 1, 2, 4, 3 and null in handleResult. I am trying the same with mutex but with the same result. How to make it works?

P.S. Sure I can use synchronized, but in this case I have to use Object-variable additionally.

Body:
Here is my code first. I used a thread instead of your method to test myself.

fun main() {
    val mutex = ReentrantLock(true)
    val asyncCondition = mutex.newCondition()
    mutex.lock()
    try
    {
        print(1)

        thread {
            mutex.lock()
            try
            {
                print(2)
            }
            finally
            {
                asyncCondition.signalAll()
                mutex.unlock()
            }
        }

        asyncCondition.await()
        print(3)
    }
    finally
    {
        mutex.unlock()
    }
}

Java's ReentrnatLock.lock method will block a thread when it is already locked on the only same thread. Since you are trying to lock an async thread from another thread, your code is not working. To block or release another thread, you may use a Condition like my code.

The reason why I am using try..finallystatement everywhere is that if an exception occurred after locking a thread, you are going to meet the infinity loop, so you must be careful about this case.

You may see these references.

Concurrency (ReentrantLock) in different threads

How do java.util.concurrent.locks.Condition work?


问:
ggplot - x-axis shows data beyond specified range for longer time periods
Here's some sample data for a company's Net revenue split by two cohorts:

```<code>data <- data.frame(dates = rep(seq(as.Date("2000/1/1"), by = "month", length.out = 48), each = 2),
                   revenue = rep(seq(10000, by = 1000, length.out = 48), each = 2) * rnorm(96, mean = 1, sd = 0.1),
                   cohort = c("Group 1", "Group 2"))
</code>```

I can show one year's worth of data and it returns what I would expect:

```<code>start = "2000-01-01"
end = "2000-12-01"

ggplot(data, aes(fill = cohort, x = dates, y = revenue)) +
    geom_bar(stat = "identity", position = position_dodge(width = NULL)) +
    xlab("Month") +
    ylab("Net Revenue") +
    geom_text(aes(label = round(revenue, 0)), vjust = -0.5, size = 3, position = position_dodge(width = 25)) +
    scale_x_date(date_breaks = "1 month", limits = as.Date(c(start, end))) +
    ggtitle("Monthly Revenue by Group") +
    theme_minimal() +
    theme(axis.text.x = element_text(angle = 60, hjust = 1), plot.title = element_text(hjust = 0.5)) +
    scale_fill_manual(values=c("#00BFC4", "#F8766D"))
</code>```

But if I expand the date range to two years or more and rerun the graph, it shows additional months on both sides of the x-axis despite not displaying any information on the y-axis.

```<code>start = "2000-01-01"
end = "2001-12-01"
#rerun the ggplot code from above
</code>```

Note the non-existant data points for 1999-12-01 and 2002-01-01. Why do these appear and how can I remove them?

答:
I am not sure what exactly the issue is but if you change from "Date" class on x-axis to any other it seems to work as expected. Also filtering the data for the specific range before passing it to ggplot.

For example in this case changing dates to month-year format,

```<code>library(dplyr)
library(ggplot2)

start = as.Date("2000-01-01")
end = as.Date("2001-12-01")
all_fac <- c(outer(month.abb, 2000:2001, paste, sep = "-"))

data %>%
  filter(between(dates, start, end)) %>%
  mutate(dates = factor(format(dates, "%b-%Y"),levels = all_fac)) %>%
  ggplot() + aes(fill = cohort, x = dates, y = revenue) +
  geom_bar(stat = "identity", position = "dodge") +
  xlab("Month") +
  ylab("Net Revenue") +
  geom_text(aes(label = round(revenue, 0))) +
  ggtitle("Monthly Revenue by Group") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 60, hjust = 1), plot.title =
  element_text(hjust = 0.5)) +
  scale_fill_manual(values=c("#00BFC4", "#F8766D"))
</code>```

Please beautify/change the labels on the bars.

Body:
Here's some sample data for a company's Net revenue split by two cohorts:

data <- data.frame(dates = rep(seq(as.Date("2000/1/1"), by = "month", length.out = 48), each = 2),
                   revenue = rep(seq(10000, by = 1000, length.out = 48), each = 2) * rnorm(96, mean = 1, sd = 0.1),
                   cohort = c("Group 1", "Group 2"))

I can show one year's worth of data and it returns what I would expect:

start = "2000-01-01"
end = "2000-12-01"

ggplot(data, aes(fill = cohort, x = dates, y = revenue)) +
    geom_bar(stat = "identity", position = position_dodge(width = NULL)) +
    xlab("Month") +
    ylab("Net Revenue") +
    geom_text(aes(label = round(revenue, 0)), vjust = -0.5, size = 3, position = position_dodge(width = 25)) +
    scale_x_date(date_breaks = "1 month", limits = as.Date(c(start, end))) +
    ggtitle("Monthly Revenue by Group") +
    theme_minimal() +
    theme(axis.text.x = element_text(angle = 60, hjust = 1), plot.title = element_text(hjust = 0.5)) +
    scale_fill_manual(values=c("#00BFC4", "#F8766D"))

But if I expand the date range to two years or more and rerun the graph, it shows additional months on both sides of the x-axis despite not displaying any information on the y-axis.

start = "2000-01-01"
end = "2001-12-01"
#rerun the ggplot code from above

Note the non-existant data points for 1999-12-01 and 2002-01-01. Why do these appear and how can I remove them?

Body:
I am not sure what exactly the issue is but if you change from "Date" class on x-axis to any other it seems to work as expected. Also filtering the data for the specific range before passing it to ggplot.

For example in this case changing dates to month-year format,

library(dplyr)
library(ggplot2)

start = as.Date("2000-01-01")
end = as.Date("2001-12-01")
all_fac <- c(outer(month.abb, 2000:2001, paste, sep = "-"))

data %>%
  filter(between(dates, start, end)) %>%
  mutate(dates = factor(format(dates, "%b-%Y"),levels = all_fac)) %>%
  ggplot() + aes(fill = cohort, x = dates, y = revenue) +
  geom_bar(stat = "identity", position = "dodge") +
  xlab("Month") +
  ylab("Net Revenue") +
  geom_text(aes(label = round(revenue, 0))) +
  ggtitle("Monthly Revenue by Group") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 60, hjust = 1), plot.title =
  element_text(hjust = 0.5)) +
  scale_fill_manual(values=c("#00BFC4", "#F8766D"))

Please beautify/change the labels on the bars.


问:
Access blob storage through azure logic apps
I have Azure blob storage, which contains some CSV files.
My task:

```<code>1. Create a logic app for the blob storage.
2. Retrieve the data from the blob storage.
3. Convert the retrieve file to JSON.
3. Upload that data to an online portal through API.
</code>```

I've tried retrieving the data by "Get blob content" action, but not sure where to see the result. I have just created the logic app, but I'm stuck on what to do next.

答:
For your question about

I've tried retrieving the data by "Get blob content" action, but not sure where to see the result.

When you run the logic app, you can see the content of your csv file in the OUTPUTS, shown as below:

If you want to use an api to upload the data, you just need to do the operation like below screenshot(but it also depends the type of your api's request body) :

Since you mentioned your azure storage blob contains some csv files, so maybe you need to loop the files. You can use "List blobs" action and "For each" action to loop them and then get blob content.

Hope it helps, if you have any further problem, please let me know.

Body:
I have Azure blob storage, which contains some CSV files.
My task:

1. Create a logic app for the blob storage.
2. Retrieve the data from the blob storage.
3. Convert the retrieve file to JSON.
3. Upload that data to an online portal through API.

I've tried retrieving the data by "Get blob content" action, but not sure where to see the result. I have just created the logic app, but I'm stuck on what to do next.


问:
String to new object with parameters
How do i create a new instance of an object from a string?

I want to do this:

```<code>Event event = new Event("hello");
event.setName("nice!");
</code>```

but only having

```<code>String object = "Event";
String object_variable_name = "event";
String object_params = "hello";
</code>```

Is this possible?

答: You can use java.lang.Class's getConstructor isnstead.</p>

Title: String to new object with parameters

Body:
How do i create a new instance of an object from a string?

I want to do this:

Event event = new Event("hello");
event.setName("nice!");

but only having

String object = "Event";
String object_variable_name = "event";
String object_params = "hello";

Is this possible?


问:
WSO2 APIM 3.0.0 REFUSED TO START AFTER EDITING master-datasources.xml file
I installed wso2am-3.0.0 as a service on linux machine and i changed the default database to mysql by editing the master-datasources.xml file. However, when i start the service by running sudo service wso2am-3.0.0 start, I got stucked here as shown below:

```<code>TID: [2020-02-19 00:16:22,738]  INFO {org.wso2.config.mapper.ConfigParser} - Applying Configurations upon new Templates {org.wso2.config.mapper.ConfigParser}
TID: [2020-02-19 00:16:22,739]  WARN {org.wso2.config.mapper.ConfigParser} - Configurations Changed in :repository/conf/datasources/master-datasources.xml {org.wso2.config.mapper.ConfigParser}
TID: [2020-02-19 00:16:22,739]  WARN {org.wso2.config.mapper.ConfigParser} - Configurations Changed in :repository/conf/carbon.xml {org.wso2.config.mapper.ConfigParser}
TID: [2020-02-19 00:16:22,739]  WARN {org.wso2.config.mapper.ConfigParser} - Overriding files in configuration directory /usr/lib/wso2/wso2am/3.0.0 {org.wso2.config.mapper.ConfigParser}
</code>```

And nothing else happens

答:
From API Manager v3.0.0, we have introduced a new configuration model where now you have a deployment.toml to configure. You don't need to touch any xml config files. deployment.toml can be found in repository/conf location. Although you change the configs in xml files, those will be overridden when server starts up.

Please refer how you can change databases to mysql - https://apim.docs.wso2.com/en/3.0.0/InstallAndSetup/SettingUpDatabases/ChangingDefaultDatabases/changing-to-mysql/

Body:
I installed wso2am-3.0.0 as a service on linux machine and i changed the default database to mysql by editing the master-datasources.xml file. However, when i start the service by running sudo service wso2am-3.0.0 start, I got stucked here as shown below:

TID: [2020-02-19 00:16:22,738]  INFO {org.wso2.config.mapper.ConfigParser} - Applying Configurations upon new Templates {org.wso2.config.mapper.ConfigParser}
TID: [2020-02-19 00:16:22,739]  WARN {org.wso2.config.mapper.ConfigParser} - Configurations Changed in :repository/conf/datasources/master-datasources.xml {org.wso2.config.mapper.ConfigParser}
TID: [2020-02-19 00:16:22,739]  WARN {org.wso2.config.mapper.ConfigParser} - Configurations Changed in :repository/conf/carbon.xml {org.wso2.config.mapper.ConfigParser}
TID: [2020-02-19 00:16:22,739]  WARN {org.wso2.config.mapper.ConfigParser} - Overriding files in configuration directory /usr/lib/wso2/wso2am/3.0.0 {org.wso2.config.mapper.ConfigParser}

And nothing else happens


问:
Practice Linux Shell Scripting
My homework assignment is to write a shell script to read a "log.txt" and display its comments line by line. Each line should be prefixed by its line number.

Script I have so far:

```<code>path="/home/user/log.txt"
while i=read -r line
do
   echo "$line"
done < "$log_file"
</code>```

Input file:

```<code>How are you
Where are you
</code>```

Expected output:

```<code>1. How are you
2. Where are you
</code>```

答:
Not a shellscript but some utility/program can do that.

```<code>grep -n . logfile.txt

cat -n logfile.txt

awk '{print NR" "$0}' logfile.txt
</code>```

and many more...

Here is one using bash.

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

n=0

while IFS= read -r line; do
  printf '%d. %s\n' "$n" "$line"
  ((n++))
done < logfile.txt
</code>```

Title: Practice Linux Shell Scripting

Body:
My homework assignment is to write a shell script to read a "log.txt" and display its comments line by line. Each line should be prefixed by its line number.

Script I have so far:

path="/home/user/log.txt"
while i=read -r line
do
   echo "$line"
done < "$log_file"

Input file:

How are you
Where are you

Expected output:

1. How are you
2. Where are you

Body:
Not a shellscript but some utility/program can do that.

grep -n . logfile.txt

cat -n logfile.txt

awk '{print NR" "$0}' logfile.txt

and many more...

Here is one using bash.

#!/usr/bin/env bash

n=0

while IFS= read -r line; do
  printf '%d. %s\n' "$n" "$line"
  ((n++))
done < logfile.txt


问:
SQL migration in Azure Pipelines with transactions
We have a build pipeline running that creates a sql script using dotnet ef migrations script -Idempotent
and this is executed in our release pipeline using the task "Azure SQL Database deployment" using  Invoke-Sqlcmd -ServerInstance "XXXXXXXXX" -Database "XXXXXX" -Username "XXXXXXX"  -Password ******  -Inputfile "XXXXXXXXXX" -ConnectionTimeout 1800

However we would like to run the migration in a transaction, because now, if the migration fail, we end up in a state were the migration is half-completed.

Any ideas?

答:
If you are looking for ways to use EF migrations to generate sql scripte wrapped with transaction, please check this thread which create a MigrationScriptBuilder class inherited from the SqlServerMigrationSqlGenerator.

Below is the code from above thread, you can see the "BEGIN TRAN" and "COMMIT TRAN" around the migrationstatement.

```<code>public class MigrationScriptBuilder : SqlServerMigrationSqlGenerator
{
#if !DEBUG
    protected override void Generate(SqlOperation sqlOperation)
    {
        Statement("GO");

        base.Generate(sqlOperation);

        Statement("GO");
    }

    public override IEnumerable<MigrationStatement> Generate(IEnumerable<MigrationOperation> migrationOperations, string providerManifestToken)
    {
        yield return new MigrationStatement {Sql = "BEGIN TRAN"};

        foreach (var migrationStatement in base.Generate(migrationOperations, providerManifestToken))
        {
            yield return migrationStatement;
        }

        yield return new MigrationStatement {Sql = "COMMIT TRAN"};
    }
#endif
}
</code>```

Body:
If you are looking for ways to use EF migrations to generate sql scripte wrapped with transaction, please check this thread which create a MigrationScriptBuilder class inherited from the SqlServerMigrationSqlGenerator.

Below is the code from above thread, you can see the "BEGIN TRAN" and "COMMIT TRAN" around the migrationstatement.

public class MigrationScriptBuilder : SqlServerMigrationSqlGenerator
{
#if !DEBUG
    protected override void Generate(SqlOperation sqlOperation)
    {
        Statement("GO");

        base.Generate(sqlOperation);

        Statement("GO");
    }

    public override IEnumerable<MigrationStatement> Generate(IEnumerable<MigrationOperation> migrationOperations, string providerManifestToken)
    {
        yield return new MigrationStatement {Sql = "BEGIN TRAN"};

        foreach (var migrationStatement in base.Generate(migrationOperations, providerManifestToken))
        {
            yield return migrationStatement;
        }

        yield return new MigrationStatement {Sql = "COMMIT TRAN"};
    }
#endif
}


问:
AKS - incorrect Pod Status
I have an AKS Cluster with two nodepools. Node pool 1 has 3 nodes, and nodepool 2 has 1 node - all Linux VMs. I noticed that after stopping the VMs and then doing kubectl get pods, the Pods status shows "running" though the VMs are not actually running. How is this possible?

This is the command I tried: kubectl get pods -n development -o=wide

The screenshot is given below. Though VMs are not running, the Pod status shows "running". However, trying to access the app using the Public IP of the service resulted in

ERR_CONNECTION_TIMED_OUT

答: Here is a full thread (https://github.com/kubernetes/kubernetes/issues/55713) on this issue. The problem here is by default the pod waits for 5 minutes before evicting to another node when the current node becomes notReady, but in this case none of the worker nodes are ready and hence pods are not getting evicted. Refer the git issue, there are some suggestions and solutions provided.

Title: AKS - incorrect Pod Status


问:
Python Beautifulsoup img tag parsing
I am using beautifulsoup to parse all img tags which is present in 'www.youtube.com'

The code is

```<code>import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen('http://www.youtube.com/')
soup = BeautifulSoup(page)
tags=soup.findAll('img')
</code>```

But am not getting all img tags.The getting img tags are invalid also.

The img tags which i got after parsing is different from the page source img tags. Some attributes are missing.

I need to get all video img tags in youtube.com

Please help

答:
Try this.</p>

```<code>from simplified_scrapy import SimplifiedDoc, req
url = 'https://www.youtube.com'
html = req.get(url)
doc = SimplifiedDoc(html)
imgs = doc.listImg(url = url)
print([img.url for img in imgs])

imgs = doc.selects('img')
for img in imgs:
  print (img)
  print (doc.absoluteUrl(url,img.src))
</code>```

Title: Python Beautifulsoup img tag parsing

Body:
I am using beautifulsoup to parse all img tags which is present in 'www.youtube.com'

The code is

import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen('http://www.youtube.com/')
soup = BeautifulSoup(page)
tags=soup.findAll('img')

But am not getting all img tags.The getting img tags are invalid also.

The img tags which i got after parsing is different from the page source img tags. Some attributes are missing.

I need to get all video img tags in youtube.com

Please help

Body:
Try this.

from simplified_scrapy import SimplifiedDoc, req
url = 'https://www.youtube.com'
html = req.get(url)
doc = SimplifiedDoc(html)
imgs = doc.listImg(url = url)
print([img.url for img in imgs])

imgs = doc.selects('img')
for img in imgs:
  print (img)
  print (doc.absoluteUrl(url,img.src))


问:
How to reference Timezone (TZ) from a separate column?
I am attempting to assign the correct timezone (TZ) for each observation in my dataset (Attached screenshot). I have successfully been able to mutate the TZ columns (Start_TimeZone) to new columns (Start_TimeZone_New) to represent the "normal" TZ designations (i.e. "America/Los_Angeles"). The issue I am running into, is understanding how to assign this new TZ column to each date/time observation (2nd code snippet). The ultimate goal is to utilize the TZ assignment to calculate the duration between start and end date/time (end date/time not shown).

```<code>```
comp_report_tz %>%
mutate(Start_TimeZone_New = case_when(is.na(Start_TimeZone) ~ "missing",
           Start_TimeZone == "-08:00" ~ "America/Los_Angeles",
           Start_TimeZone == "-07:00" ~ "America/Phoenix",
           Start_TimeZone == "-06:00" ~ "America/Chicago",
           Start_TimeZone == "-05:00" ~ "America/New_York",
                                       TRUE ~ "others")) %>%
mutate(End_TimeZone_New = case_when(is.na(End_TimeZone) ~ "missing",
           Start_TimeZone == "-08:00" ~ "America/Los_Angeles",
           Start_TimeZone == "-07:00" ~ "America/Phoenix",
           Start_TimeZone == "-06:00" ~ "America/Chicago",
           Start_TimeZone == "-05:00" ~ "America/New_York",
                                       TRUE ~ "others"))
```

```
comp_report_adj %>%
mutate(Start_Time_Final = as.POSIXct(comp_report_tz$Start_Date_Time, format = "%m/%d/%y
%I:%M%p", tz=comp_report_adj$Start_TimeZone_New)
```
</code>```

答:
There are some functions in the R package lubridate that might help.

```<code>library(magrittr)
library(lubridate)

assign_tz <- function(dt, tz){
  lubridate::tz(dt) <- tz
  return(dt)
}

tibble::tibble(end = lubridate::now(tz = "America/New_York"), tz_end = "America/New_York",
               start = lubridate::as_datetime("2018-01-01", tz = "America/Chicago"), tz_start = "America/New_York"
               ) %>%
  dplyr::mutate(start_tz = assign_tz(start, tz_start), end_tz = assign_tz(end, tz_end), diff = end_tz - start_tz)

</code>```

Since your Start_Date_Time and your end date times have timezones associated with them, you should be able to calculate the duration as above, by subtracting the start datetime from the end datetime.

Body:
I am attempting to assign the correct timezone (TZ) for each observation in my dataset (Attached screenshot). I have successfully been able to mutate the TZ columns (Start_TimeZone) to new columns (Start_TimeZone_New) to represent the "normal" TZ designations (i.e. "America/Los_Angeles"). The issue I am running into, is understanding how to assign this new TZ column to each date/time observation (2nd code snippet). The ultimate goal is to utilize the TZ assignment to calculate the duration between start and end date/time (end date/time not shown).

```
comp_report_tz %>%
mutate(Start_TimeZone_New = case_when(is.na(Start_TimeZone) ~ "missing",
           Start_TimeZone == "-08:00" ~ "America/Los_Angeles",
           Start_TimeZone == "-07:00" ~ "America/Phoenix",
           Start_TimeZone == "-06:00" ~ "America/Chicago",
           Start_TimeZone == "-05:00" ~ "America/New_York",
                                       TRUE ~ "others")) %>%
mutate(End_TimeZone_New = case_when(is.na(End_TimeZone) ~ "missing",
           Start_TimeZone == "-08:00" ~ "America/Los_Angeles",
           Start_TimeZone == "-07:00" ~ "America/Phoenix",
           Start_TimeZone == "-06:00" ~ "America/Chicago",
           Start_TimeZone == "-05:00" ~ "America/New_York",
                                       TRUE ~ "others"))
```

```
comp_report_adj %>%
mutate(Start_Time_Final = as.POSIXct(comp_report_tz$Start_Date_Time, format = "%m/%d/%y
%I:%M%p", tz=comp_report_adj$Start_TimeZone_New)
```

Body:
There are some functions in the R package lubridate that might help.

library(magrittr)
library(lubridate)

assign_tz <- function(dt, tz){
  lubridate::tz(dt) <- tz
  return(dt)
}

tibble::tibble(end = lubridate::now(tz = "America/New_York"), tz_end = "America/New_York",
               start = lubridate::as_datetime("2018-01-01", tz = "America/Chicago"), tz_start = "America/New_York"
               ) %>%
  dplyr::mutate(start_tz = assign_tz(start, tz_start), end_tz = assign_tz(end, tz_end), diff = end_tz - start_tz)

Since your Start_Date_Time and your end date times have timezones associated with them, you should be able to calculate the duration as above, by subtracting the start datetime from the end datetime.


问:
Twitter Bootstrap - how to detect when media queries starts
which is the fastest and easy way to fire when bootstrap-responsive.css media queries go in action?

go in action = when you resize window to mobile width and site is changed to responsive mobile

hope question is clear

答:
Improving the excellent @falsarella answer, here is a shorter version that works with Bootstrap 4 :

CSS :

```<code>#mq-detector {
    visibility: hidden;
}
</code>```

HTML :

```<code><div id="mq-detector">
    <span data-mq="xs" class="d-block d-sm-none"></span>
    <span data-mq="sm" class="d-none d-sm-block d-md-none"></span>
    <span data-mq="md" class="d-none d-md-block d-lg-none"></span>
    <span data-mq="lg" class="d-none d-lg-block d-xl-none"></span>
    <span data-mq="xl" class="d-none d-xl-block"></span>
</div>
</code>```

JAVASCRIPT :

```<code>//Define function that returns the currently used media query
function getBsMq(){
    var currMq;
    var mqDetector = $('#mq-detector [data-mq]');
    mqDetector.each(function(i){
        if ($(this).is(':visible')) {
            currMq = $(this).attr('data-mq');
        }
    });
    return currMq;
}

//Call the function and get the currently used media query
alert(getBsMq());
</code>```

Body:
Improving the excellent @falsarella answer, here is a shorter version that works with Bootstrap 4 :

CSS :

#mq-detector {
    visibility: hidden;
}

HTML :

<div id="mq-detector">
    <span data-mq="xs" class="d-block d-sm-none"></span>
    <span data-mq="sm" class="d-none d-sm-block d-md-none"></span>
    <span data-mq="md" class="d-none d-md-block d-lg-none"></span>
    <span data-mq="lg" class="d-none d-lg-block d-xl-none"></span>
    <span data-mq="xl" class="d-none d-xl-block"></span>
</div>

JAVASCRIPT :

//Define function that returns the currently used media query
function getBsMq(){
    var currMq;
    var mqDetector = $('#mq-detector [data-mq]');
    mqDetector.each(function(i){
        if ($(this).is(':visible')) {
            currMq = $(this).attr('data-mq');
        }
    });
    return currMq;
}

//Call the function and get the currently used media query
alert(getBsMq());


问:
AcquireTokenSilent for Multiple WebAPI Access tokens using Azure B2C and MSAL.NET
We have a web application which needs authenticated access to several Web APIs. We are using Azure AD B2C for authentication.

I understand you can not include scopes for both resources in one call.

I understand that MSAL is meant to use a refresh token that was cached from the first resource token, to request an access token for the second resource.

```<code>IConfidentialClientApplication cca = MsalAppBuilder.BuildConfidentialClientApplication();
var accounts = await cca.GetAccountsAsync();
AuthenticationResult result = await cca.AcquireTokenSilent(scopeForApi2, accounts.FirstOrDefault())
</code>```

When this call is made, the call doesnt not fail, but the Access Token is null.

Within Azure B2C, the web app, and webapis are registered - and the web app has been granted permission and admin consent to all the scopes from the webapis.

Is this supported using Azure AD B2C and/or MSAL.NET?

We get the first access token for the first resource api successfully:

```<code>app.UseOpenIdConnectAuthentication(
    new OpenIdConnectAuthenticationOptions
    {
        // Generate the metadata address using the tenant and policy information
        MetadataAddress = String.Format(Globals.WellKnownMetadata, Globals.Tenant, Globals.DefaultPolicy),

        // These are standard OpenID Connect parameters, with values pulled from web.config
        ClientId = Globals.ClientId,
        RedirectUri = Globals.RedirectUri,
        PostLogoutRedirectUri = Globals.RedirectUri,

        // Specify the callbacks for each type of notifications
        Notifications = new OpenIdConnectAuthenticationNotifications
        {
            RedirectToIdentityProvider = OnRedirectToIdentityProvider,
            AuthorizationCodeReceived = OnAuthorizationCodeReceived,
            AuthenticationFailed = OnAuthenticationFailed,
        },

        // Specify the claim type that specifies the Name property.
        TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = "name",
            ValidateIssuer = false
        },

        // Specify the scope by appending all of the scopes requested into one string (separated by a blank space)
        Scope = $"openid profile offline_access {Globals.ReadTasksScopeApi1} {Globals.WriteTasksScopeApi1}"
    }
);

</code>```

we get the first access token using the authorizationcode - we receive an access token and refresh token

```<code>IConfidentialClientApplication confidentialClient
     = MsalAppBuilder.BuildConfidentialClientApplication(
        new ClaimsPrincipal(notification.AuthenticationTicket.Identity));

// Upon successful sign in, get & cache a token using MSAL
AuthenticationResult result = await confidentialClient
    .AcquireTokenByAuthorizationCode(Globals.Scopes_Api1, notification.Code)
    .ExecuteAsync();
</code>```

I have also tried adding the "resource" query parameter but it doesnt seem to make any difference:

```<code>var scope = new string[] { Globals.ReadTasksScopeApi2 };

IConfidentialClientApplication cca = MsalAppBuilder.BuildConfidentialClientApplication();
var accounts = await cca.GetAccountsAsync();
AuthenticationResult result = await cca.AcquireTokenSilent(scope, accounts.FirstOrDefault())
.WithExtraQueryParameters(new Dictionary<string, string>
{
   // { "resource", "https://myb2c.onmicrosoft.com/api2" },    // tried appid and guid
    { "resource", "0a6ab6b5-1b88-49fe-a6cf-19f1878d3508" }
})
.ExecuteAsync();
</code>```

Why is the Access Token null for the second call to AcquireTokenSilent on a second resource using Azure AD B2C?

答:
2/19/2020

I have confirmed with Azure support engineer that Azure AD B2C doesn't support such scenario.

Body:
We have a web application which needs authenticated access to several Web APIs. We are using Azure AD B2C for authentication.

I understand you can not include scopes for both resources in one call.

I understand that MSAL is meant to use a refresh token that was cached from the first resource token, to request an access token for the second resource.

IConfidentialClientApplication cca = MsalAppBuilder.BuildConfidentialClientApplication();
var accounts = await cca.GetAccountsAsync();
AuthenticationResult result = await cca.AcquireTokenSilent(scopeForApi2, accounts.FirstOrDefault())

When this call is made, the call doesnt not fail, but the Access Token is null.

Within Azure B2C, the web app, and webapis are registered - and the web app has been granted permission and admin consent to all the scopes from the webapis.

Is this supported using Azure AD B2C and/or MSAL.NET?

We get the first access token for the first resource api successfully:

app.UseOpenIdConnectAuthentication(
    new OpenIdConnectAuthenticationOptions
    {
        // Generate the metadata address using the tenant and policy information
        MetadataAddress = String.Format(Globals.WellKnownMetadata, Globals.Tenant, Globals.DefaultPolicy),

        // These are standard OpenID Connect parameters, with values pulled from web.config
        ClientId = Globals.ClientId,
        RedirectUri = Globals.RedirectUri,
        PostLogoutRedirectUri = Globals.RedirectUri,

        // Specify the callbacks for each type of notifications
        Notifications = new OpenIdConnectAuthenticationNotifications
        {
            RedirectToIdentityProvider = OnRedirectToIdentityProvider,
            AuthorizationCodeReceived = OnAuthorizationCodeReceived,
            AuthenticationFailed = OnAuthenticationFailed,
        },

        // Specify the claim type that specifies the Name property.
        TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = "name",
            ValidateIssuer = false
        },

        // Specify the scope by appending all of the scopes requested into one string (separated by a blank space)
        Scope = $"openid profile offline_access {Globals.ReadTasksScopeApi1} {Globals.WriteTasksScopeApi1}"
    }
);

we get the first access token using the authorizationcode - we receive an access token and refresh token

IConfidentialClientApplication confidentialClient
     = MsalAppBuilder.BuildConfidentialClientApplication(
        new ClaimsPrincipal(notification.AuthenticationTicket.Identity));

// Upon successful sign in, get & cache a token using MSAL
AuthenticationResult result = await confidentialClient
    .AcquireTokenByAuthorizationCode(Globals.Scopes_Api1, notification.Code)
    .ExecuteAsync();

I have also tried adding the "resource" query parameter but it doesnt seem to make any difference:

var scope = new string[] { Globals.ReadTasksScopeApi2 };

IConfidentialClientApplication cca = MsalAppBuilder.BuildConfidentialClientApplication();
var accounts = await cca.GetAccountsAsync();
AuthenticationResult result = await cca.AcquireTokenSilent(scope, accounts.FirstOrDefault())
.WithExtraQueryParameters(new Dictionary<string, string>
{
   // { "resource", "https://myb2c.onmicrosoft.com/api2" },    // tried appid and guid
    { "resource", "0a6ab6b5-1b88-49fe-a6cf-19f1878d3508" }
})
.ExecuteAsync();

Why is the Access Token null for the second call to AcquireTokenSilent on a second resource using Azure AD B2C?


问:
Kotlin map() reuse the same value
I have the following method

```<code>    val dateFormat = SimpleDateFormat("yyyy-MM-dd")
    fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
        val lines = paragraph.split("\n")
        return lines.map { l -> Pair(dateFormat.parse(l.split(" ")[0]), l.split(" ")[1]) }
    }
</code>```

where  l.split(" ") is called twice.

How to write in a smarter way in functional programming style ?

PS 1: I 'm curious for a solution with fold if possible

PS 2 : For readability, the original version was written as

```<code> fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
        val lines = paragraph.split("\n")

        var results = mutableListOf<Pair<Date, String>>()
        for (line in lines) {
            val content = line.split(" ")
            val date: Date = dateFormat.parse(content[0])
            val firstName = content[1]
            results.add(Pair(date,firstName))
        }
        return results
    }
</code>```

答:
I believe there is more functional and optimized way of writing this but here is a basic fold + with example:</p>

```<code>val dateFormat = SimpleDateFormat("yyyy-MM-dd")

fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
   val lines = paragraph.split("\n")

    return lines.fold(listOf<Pair<Date, String>>()) { list, line ->
        with (line.split(" ")) {
            list + Pair(dateFormat.parse(this[0]), this[1])
        }
    }
}
</code>```

Title: Kotlin map() reuse the same value

Body:
I have the following method

    val dateFormat = SimpleDateFormat("yyyy-MM-dd")
    fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
        val lines = paragraph.split("\n")
        return lines.map { l -> Pair(dateFormat.parse(l.split(" ")[0]), l.split(" ")[1]) }
    }

where  l.split(" ") is called twice.

How to write in a smarter way in functional programming style ?

PS 1: I 'm curious for a solution with fold if possible

PS 2 : For readability, the original version was written as

 fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
        val lines = paragraph.split("\n")

        var results = mutableListOf<Pair<Date, String>>()
        for (line in lines) {
            val content = line.split(" ")
            val date: Date = dateFormat.parse(content[0])
            val firstName = content[1]
            results.add(Pair(date,firstName))
        }
        return results
    }

Body:
I believe there is more functional and optimized way of writing this but here is a basic fold + with example:

val dateFormat = SimpleDateFormat("yyyy-MM-dd")

fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
   val lines = paragraph.split("\n")

    return lines.fold(listOf<Pair<Date, String>>()) { list, line ->
        with (line.split(" ")) {
            list + Pair(dateFormat.parse(this[0]), this[1])
        }
    }
}


问:
If cell is 5 long add 0 prefix , else leave as is, loop
We have Serial Numbers that have to be reviewed and some of them are 5 digits long but in the database have a 0 prefix, which of course they don't have in the format we receive. So using bits and pieces of other VBA I've got the below, which loops and changes nothing.

What am I missing/doing wrong?

```<code>Sub SNoReview()

    Dim METER                   As String
    Dim SQL_STRING              As String
    Dim ANSWER                  As String
    Dim CELLADDRESS             As Variant

    Application.ScreenUpdating = True
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Sheets("Sheet1").Activate
    Range("N6").Select

    Do Until IsEmpty(ActiveCell)

        CELLADDRESS = ActiveCell.Address
        METER = ActiveCell.Value

        If Len(METER) = 5 Then
            METER = "0" & (METER)
        Else: METER = (METER)
        End If

        ActiveCell.Offset(1, 0).Select

    Loop

End Sub
</code>```

答:
First acknowledging that @urdearboy has done the hard work here (investigative) ...

In terms of an answer, assuming any data < 6 in length is a numeric or text numeric ... then maybe something like this which converts and formats (from N6 down):

```<code>Option Explicit

Sub SNoReview()

    Dim vSheet As Worksheet
    Dim vCell As Range

    Set vSheet = ThisWorkbook.Worksheets("Sheet1")
    For Each vCell In vSheet.Range("N6:N" & vSheet.Range("N" & vSheet.Rows.Count).End(xlUp).Row)
        If Len(vCell) < 6 Then
            With vCell
                vCell.NumberFormat = "000000"
                vCell = Val(vCell)
            End With
        End If
    Next

End Sub
</code>```

Before

After

Body:
We have Serial Numbers that have to be reviewed and some of them are 5 digits long but in the database have a 0 prefix, which of course they don't have in the format we receive. So using bits and pieces of other VBA I've got the below, which loops and changes nothing.

What am I missing/doing wrong?

Sub SNoReview()

    Dim METER                   As String
    Dim SQL_STRING              As String
    Dim ANSWER                  As String
    Dim CELLADDRESS             As Variant

    Application.ScreenUpdating = True
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Sheets("Sheet1").Activate
    Range("N6").Select

    Do Until IsEmpty(ActiveCell)

        CELLADDRESS = ActiveCell.Address
        METER = ActiveCell.Value

        If Len(METER) = 5 Then
            METER = "0" & (METER)
        Else: METER = (METER)
        End If

        ActiveCell.Offset(1, 0).Select

    Loop

End Sub

Body:
First acknowledging that @urdearboy has done the hard work here (investigative) ...

In terms of an answer, assuming any data < 6 in length is a numeric or text numeric ... then maybe something like this which converts and formats (from N6 down):

Option Explicit

Sub SNoReview()

    Dim vSheet As Worksheet
    Dim vCell As Range

    Set vSheet = ThisWorkbook.Worksheets("Sheet1")
    For Each vCell In vSheet.Range("N6:N" & vSheet.Range("N" & vSheet.Rows.Count).End(xlUp).Row)
        If Len(vCell) < 6 Then
            With vCell
                vCell.NumberFormat = "000000"
                vCell = Val(vCell)
            End With
        End If
    Next

End Sub

Before

After


问:
Univocity - return wrapped record with error context
Say I am parsing a CSV employee file. I have a pojo called Employee and i'm using univocity routines and an iterator.

```<code>Iterator<Employee> iterator = routines.iterate(Employee.class, ...)
</code>```

When an error occurs when parsing a row, I don't want to use the setProcessorErrorHandler() callback. Instead I want to return a generic "Record" or "Item" wrapper which wraps Employee and any error context info if applicable. A bit like how the JTinyCsvParser library's CsvMappingResult object behaves.

Is there an easy way of doing this short of catching for example com.univocity.parsers.common.DataProcessingException?

答: You can but you still need to use the RetryableErrorHandler and from it you must call keepRecord() to prevent the record from being discarded. This way you will get your problematic Employee instance with the information that could be parsed.

Body:
Say I am parsing a CSV employee file. I have a pojo called Employee and i'm using univocity routines and an iterator.

Iterator<Employee> iterator = routines.iterate(Employee.class, ...)

When an error occurs when parsing a row, I don't want to use the setProcessorErrorHandler() callback. Instead I want to return a generic "Record" or "Item" wrapper which wraps Employee and any error context info if applicable. A bit like how the JTinyCsvParser library's CsvMappingResult object behaves.

Is there an easy way of doing this short of catching for example com.univocity.parsers.common.DataProcessingException?


问:
Should I return an array or a collection from a function?
What's the preferred container type when returning multiple objects of the same type from a function?

Is it against good practice to return a simple array (like MyType[]), or should you wrap it in some generic container (like ICollection<MyType>)?

Thanks!

答:
Array is harmful, but ICollection<T> is also harmful.

ICollection<T> cannot guarantee the object will be immutable.

My recommendation is to wrap the returning object with ReadOnlyCollection<T>

OwnerDisplayName: Pwninstein

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: chaowman


问:
GoogleVoice numbers support with Clickatell & TextAnywhere
When I send sms text message to a google voice number from Clickatell or TextAnywhere, I get a failure alert (in the reports) and the message is not sent.

Anybody had experience with that?

答:
Google Voice doesn't support international SMSs, as per their documentation

Some providers, such as BulkSMS have had some success in getting message delivery to GV but the ability of the recipient to reply is not there.

Disclaimer: I work for BulkSMS


问:
Using object when out of scope?
I'm working on a school assignment require to create a char LinkedList from user string input based on a menu of options:

Enter new string and store as linked list character of in an LinkedList class.

Get current length from the LinkedList.

Find index of character in this linked list.

Append another LinkedList to this LinkedList.

I have everything working fine, but now I'm stuck at the menu option part.
So let's say I choose option 1 to enter a string, and then I decide to use that object for case 2 and 3 to get the size and find index. That would not work because the object will be destroyed when out of scope. Is there any proper way that I can use to implement this ?

Simple Code Below

```<code>switch(option){
case 1:
 LinkedList ls1(getInput());
 ls1.printList();
 break;
}
case 2:
cout << "Size of LinkedList: " <<ls1.getSize() << endl; //wouldn't work because ls1 got destroyed when out of scope.
}
</code>```

答:
Try to initiate the object outside the switch statement and after that you could use that object within any switch case.

Example:

```<code>ClassName ObjectName(getInput());
 switch(option){
   case 1: ObjectName.printList();
                 break;
   case 2: cout << "Size of LinkedList: " <<ObjectName.getSize() << endl;
                 break;
   default: break;
 }
</code>```

Title: Using object when out of scope?

Body:
I'm working on a school assignment require to create a char LinkedList from user string input based on a menu of options:

Enter new string and store as linked list character of in an LinkedList class.

Get current length from the LinkedList.

Find index of character in this linked list.

Append another LinkedList to this LinkedList.

I have everything working fine, but now I'm stuck at the menu option part.
So let's say I choose option 1 to enter a string, and then I decide to use that object for case 2 and 3 to get the size and find index. That would not work because the object will be destroyed when out of scope. Is there any proper way that I can use to implement this ?

Simple Code Below

switch(option){
case 1:
 LinkedList ls1(getInput());
 ls1.printList();
 break;
}
case 2:
cout << "Size of LinkedList: " <<ls1.getSize() << endl; //wouldn't work because ls1 got destroyed when out of scope.
}

Body:
Try to initiate the object outside the switch statement and after that you could use that object within any switch case.

Example:

ClassName ObjectName(getInput());
 switch(option){
   case 1: ObjectName.printList();
                 break;
   case 2: cout << "Size of LinkedList: " <<ObjectName.getSize() << endl;
                 break;
   default: break;
 }


问:
Css Increase the height of the div according to the font size
I'm basically going to make an accessibility to increase the font size, but I'm not sure how to achieve this:
basically I need my div to increase in height when the size of my text passes the maximum width something like this:

at the moment if I try this I have this:

passes my maximum width and does not increase in height as a "line break" as in the previous gif
code:

```<code><ContainerNav>
    <Content>
        <Nav>
            <ul>
                <li>
                    <a href="#home">home</a>
                </li>
                <li>
                    <a href="#homex">home2</a>
                </li>
                <li>
                    <a href="#homexv">home3</a>
                </li>
                <li>
                    <a href="#homexv">home4</a>
                </li>
                <li>
                    <a href="#homexv">home5</a>
                </li>
                <li>
                    <a href="#homexv">home6</a>
                </li>
            </ul>
        </Nav>
    </Content>
</ContainerNav>
</code>```

css:

```<code> const flex = props => css`
  display: flex;
  flex-direction: ${props.flexdirection};
`;

const flexAlignCenter = css`
  width: 100%;
  display: flex;
  align-items: center;
  flex-direction: row;
`;

 const mxw80 = css`
  height: 100%;
  margin: 0 auto;
  max-width: 80rem !important;
  width: 80rem !important;
`;

export const ContainerNav = styled.div`
  width: 100%;
  height: 50px;
  background: #8ac926;
  color: white;
  box-shadow: 0 0 5px rgba(18, 23, 39, 0.4);
`;
export const Nav = styled.nav`
  height: auto;
  ${flexAlignCenter}
  & > ul {
    ${flexAlignCenter}
    max-width:500px;
    background: green;
    height: auto;
  }
  & > ul > li {
    margin-right: 20px;
    background: blue;
  }
  & > ul > li > a {
    font-size: 50px;
  }
`;
export const Content = styled.div`
  ${mxw80}
  ${flex}
`;
</code>```

example:

https://codesandbox.io/s/practical-murdock-1pdul

答: If I understood your question correctly, you only have to set the heigth of ContainerNav to auto instead of the fixed height of 50px.

Body:
I'm basically going to make an accessibility to increase the font size, but I'm not sure how to achieve this:
basically I need my div to increase in height when the size of my text passes the maximum width something like this:

at the moment if I try this I have this:

passes my maximum width and does not increase in height as a "line break" as in the previous gif
code:

<ContainerNav>
    <Content>

                    home

                    home2

                    home3

                    home4

                    home5

                    home6

    </Content>
</ContainerNav>

css:

 const flex = props => css`
  display: flex;
  flex-direction: ${props.flexdirection};
`;

const flexAlignCenter = css`
  width: 100%;
  display: flex;
  align-items: center;
  flex-direction: row;
`;

 const mxw80 = css`
  height: 100%;
  margin: 0 auto;
  max-width: 80rem !important;
  width: 80rem !important;
`;

export const ContainerNav = styled.div`
  width: 100%;
  height: 50px;
  background: #8ac926;
  color: white;
  box-shadow: 0 0 5px rgba(18, 23, 39, 0.4);
`;
export const Nav = styled.nav`
  height: auto;
  ${flexAlignCenter}
  & > ul {
    ${flexAlignCenter}
    max-width:500px;
    background: green;
    height: auto;
  }
  & > ul > li {
    margin-right: 20px;
    background: blue;
  }
  & > ul > li > a {
    font-size: 50px;
  }
`;
export const Content = styled.div`
  ${mxw80}
  ${flex}
`;

example:

https://codesandbox.io/s/practical-murdock-1pdul


问:
use JavaScript so that it uses a closure to return the response
I am trying to implement the JavaScript code below so it uses a closure to return the response </p>

```<code>(function() {
    function hello(name, age) {
        return name + ", who is " + age + " years old, says hi!");
    }

    console.log(hello('John', 33));
}();
</code>```

答:
The code you posted is a Self-executing Anonymous Function, not a Closure. In fact there are no closures in your code at all because no variables' scopes cross function boundaries.

If you want to return a value from an SEAF, just add a return statement:

```<code>const message = (function() {
    function hello(name, age) {
        return name + ", who is " + age + " years old, says hi!";
    }

    const result = hello('John', 33);
    console.log( result );
    return result;
}();
</code>```

If you want to export the hello function through the SEAF as a new function without any parameters (because the parameters are captured inside the returned lambda i.e. an example of Partial Application, then do this:

```<code>const hello = (function() {

    function hello(name, age) {
        return name + ", who is " + age + " years old, says hi!";
    }

    return () => hello('John', 33);
}());

console.log( hello() ); // will print  "John, who is 33 years old, says hi!" to the console.
</code>```

Body:
I am trying to implement the JavaScript code below so it uses a closure to return the response

(function() {
    function hello(name, age) {
        return name + ", who is " + age + " years old, says hi!");
    }

    console.log(hello('John', 33));
}();

Body:
The code you posted is a Self-executing Anonymous Function, not a Closure. In fact there are no closures in your code at all because no variables' scopes cross function boundaries.

If you want to return a value from an SEAF, just add a return statement:

const message = (function() {
    function hello(name, age) {
        return name + ", who is " + age + " years old, says hi!";
    }

    const result = hello('John', 33);
    console.log( result );
    return result;
}();

If you want to export the hello function through the SEAF as a new function without any parameters (because the parameters are captured inside the returned lambda i.e. an example of Partial Application, then do this:

const hello = (function() {

    function hello(name, age) {
        return name + ", who is " + age + " years old, says hi!";
    }

    return () => hello('John', 33);
}());

console.log( hello() ); // will print  "John, who is 33 years old, says hi!" to the console.


答:
Try this.

Add a new column with the following SQL query:

```<code>ALTER TABLE myTable ADD newColumn <datatype>
</code>```

Where <datatype> can be something like int, text, longtext, varchar(50) - depending on what you need.

Then update only this column with SQL queries like this:

```<code>UPDATE TABLE myTable SET newColumn = 'Hello this is my data'
</code>```

or if you need to update a specific row (chosen where the column id is 2):

```<code>UPDATE TABLE myTable SET newColumn = 'Hello this is my data' WHERE id = '2'
</code>```

Here's the simple SQL query to copy the data from datenum to newColumn:

```<code>UPDATE myTable SET newColumn = datenum
</code>```

Run that code once (but with your table name and column name of course) and you'll see that the data is copied.

Or if you want to do it with, for example, PHP:

```<code>$rs = mysql_query('SELECT * FROM myTable ORDER BY id ASC');
while ($row = mysql_fetch_array($rs)) {
  $id = $row['id'];
  $new_datenum = $row['datenum'];
  $q = mysql_query('UPDATE myTable SET newColumn = $new_datenum WHERE id = $id');
}
</code>```

This will also copy all the data from datenum to newColumn.

Title: Mysql update data

Body:
UPDATE

+-----+------------------+-------------+
| id  | datenum          | F1_baro_20_ |
+-----+------------------+-------------+
|   1 | 734152.000000000 |     1005.21 |
|   2 | 734152.006944445 |     1005.26 |
+-----+------------------+-------------+

this is my table

And this is my new table

+-----+------------------+-------------+------------+
| id  | datenum          | F1_baro_20_ |new column  |
+-----+------------------+-------------+------------+
|   1 | 734152.000000000 |     1005.21 |            |
|   2 | 734152.006944445 |     1005.26 |            |
+-----+------------------+-------------+------------+

I want to insert data to the 'new_colum' where old_datenum=new_datenum but I don't wan to modify the existing data!

Body:
Try this.

Add a new column with the following SQL query:

ALTER TABLE myTable ADD newColumn <datatype>

Where <datatype> can be something like int, text, longtext, varchar(50) - depending on what you need.

Then update only this column with SQL queries like this:

UPDATE TABLE myTable SET newColumn = 'Hello this is my data'

or if you need to update a specific row (chosen where the column id is 2):

UPDATE TABLE myTable SET newColumn = 'Hello this is my data' WHERE id = '2'

Here's the simple SQL query to copy the data from datenum to newColumn:

UPDATE myTable SET newColumn = datenum

Run that code once (but with your table name and column name of course) and you'll see that the data is copied.

Or if you want to do it with, for example, PHP:

$rs = mysql_query('SELECT * FROM myTable ORDER BY id ASC');
while ($row = mysql_fetch_array($rs)) {
  $id = $row['id'];
  $new_datenum = $row['datenum'];
  $q = mysql_query('UPDATE myTable SET newColumn = $new_datenum WHERE id = $id');
}

This will also copy all the data from datenum to newColumn.


问:
Putting file in same directory as Jupyter notebook
```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

pd.read_csv('the_traits.txt')
</code>```

I am trying to upload a txt document with data into python. It says there is an error and I'm guessing its because it isnt in the same directory? How would I make sure the file is in the same directory?

```<code>FileNotFoundError: [Errno 2] File b'the_traits.txt' does not exist: b'the_traits.txt'
</code>```

答:
open jupyter notebooks and you will see upload button, upload the file from your whichever folder is it there and try it. It will work

or

you also can give absolute path in file that will also do the job for you

Body:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

pd.read_csv('the_traits.txt')

I am trying to upload a txt document with data into python. It says there is an error and I'm guessing its because it isnt in the same directory? How would I make sure the file is in the same directory?

FileNotFoundError: [Errno 2] File b'the_traits.txt' does not exist: b'the_traits.txt'


问:
Detect Single Modifier Key Change in UIKit for Mac (Catalyst)
I am porting an iOS app on MacOS using UIKit for Mac also known as iPad Apps for Mac or Project Catalyst.

The app uses keyCommands from UIKit to detect a single modifier key press:

```<code>UIKeyCommand(input: "", modifierFlags: .shift, action: #selector(singleShift))
</code>```

This code works perfectly on iPad with an external keyboard, I am getting the event fired with every single ⇧ press. However, this does not work on MacOS, although single non-modifier events and modifier + non-modifier combinations work.

How do I achieve the desired behavior and get notified about single modifier key events?

Or maybe I should just give up on UIKeyCommand and try UIGestureRecognizer instead?

答:
This may not be your problem make sure you don't have any keyboard apps or apps that intercept keyboard input running. I had a problem like this when I had Karibeaner-elements installed.

Otherwise, if this is a limitation of catalyst consider wrapping a more stable API from app kit or use UIGestureRecognizer.

Body:
I am porting an iOS app on MacOS using UIKit for Mac also known as iPad Apps for Mac or Project Catalyst.

The app uses keyCommands from UIKit to detect a single modifier key press:

UIKeyCommand(input: "", modifierFlags: .shift, action: #selector(singleShift))

This code works perfectly on iPad with an external keyboard, I am getting the event fired with every single ⇧ press. However, this does not work on MacOS, although single non-modifier events and modifier + non-modifier combinations work.

How do I achieve the desired behavior and get notified about single modifier key events?

Or maybe I should just give up on UIKeyCommand and try UIGestureRecognizer instead?