问:
How to use openssl passwd command from the openssl library?

I would like to know if the openssl library include a function for openssl passwd command ?

For example I would like to create a hashed password using sha512 with a custom salt, corresponding command is openssl passwd -6 -salt xxxx password.
I search in the documentation but I didn't find anything, always talking about the command but not about the library.

Thanks in advance

答:
There is no one function in the library, if you want to know what the command is doing, it points you to it in the help:

-5
  -6

Use the SHA256 / SHA512 based algorithms defined by Ulrich Drepper.
  See https://www.akkadia.org/drepper/SHA-crypt.txt.

So it's using the openssl library to implement the SHA512 algorithm by Ulrich Drepper.

You can check out the source code here to see how it's done.  Look for the shacrypt function which is implementing the Ulrich Drepper algorithm using the openssl library.


来源: stackexchange

问:
Angular karma testing: TypeError: Cannot read property 'path' of null
I am trying run some tests on Angular Karma on an angular component to determine the route.

The component is structured like this

```<code>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-basic-form',
  templateUrl: './basic-form.component.html',
  styleUrls: ['./basic-form.component.less'],
})
export class BasicFormComponent implements OnInit {
  constructor(
    public activatedRoute: ActivatedRoute,
  ) {}

  ngOnInit() {
    if(this.activatedRoute.snapshot.routeConfig.path === 'basic-form/:date'){ // route with date
     let date = this.route.snapshot.paramMap.get('date'); // get the date
   } else {
    // no worries, just use the latest date, and this component can be used on multiple routes
   }
 }
</code>```

In my test file I have

```<code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { BasicFormComponent } from './basic-form.component';

describe('BasicFormComponent', () => {
  let component: BasicFormComponent;
  let fixture: ComponentFixture<BasicFormComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ BasicFormComponent ],
      imports: [DemoMaterialModule, ReactiveFormsModule, FormsModule, HttpClientTestingModule,  RouterTestingModule.withRoutes([])],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
      providers: [
      ]

    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BasicFormComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component.activatedRoute.snapshot.routeConfig.path).toBeTruthy(); // why is this not working?
  });

});
</code>```

The errors I am getting is

BasicFormComponent should create TypeError: Cannot read property
  'path' of null TypeError: Cannot read property 'snapshot' of undefined

Why won't it import the activatedRoute module?

I am trying to get my head wrapped testing, which seems to be a dark art.

Any guidance will be appreciated.

答:
Thanks to @Gérôme Grignon for pointing me to the right direction. </p>

<p>The answer in removing the errors is below, take note in the providers, there is the use value settings. No more errors. </p>

```<code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { BasicFormComponent } from './basic-form.component';

describe('BasicFormComponent', () => {
  let component: BasicFormComponent;
  let fixture: ComponentFixture<BasicFormComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ BasicFormComponent ],
      imports: [DemoMaterialModule, ReactiveFormsModule, FormsModule, HttpClientTestingModule,  RouterTestingModule.withRoutes([])],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
      providers: [ BasicFormComponent, {
          provide: ActivatedRoute,
          useValue: {snapshot: {params: {'date': ''}, routeConfig: {'path': 'basic-form-edit/:date'}}}
      }]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BasicFormComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component.activatedRoute.snapshot.routeConfig.path).toBeTruthy(); // why is this not working?
  });
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying run some tests on Angular Karma on an angular component to determine the route.

The component is structured like this

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-basic-form',
  templateUrl: './basic-form.component.html',
  styleUrls: ['./basic-form.component.less'],
})
export class BasicFormComponent implements OnInit {
  constructor(
    public activatedRoute: ActivatedRoute,
  ) {}

  ngOnInit() {
    if(this.activatedRoute.snapshot.routeConfig.path === 'basic-form/:date'){ // route with date
     let date = this.route.snapshot.paramMap.get('date'); // get the date
   } else {
    // no worries, just use the latest date, and this component can be used on multiple routes
   }
 }

In my test file I have

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { BasicFormComponent } from './basic-form.component';

describe('BasicFormComponent', () => {
  let component: BasicFormComponent;
  let fixture: ComponentFixture<BasicFormComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ BasicFormComponent ],
      imports: [DemoMaterialModule, ReactiveFormsModule, FormsModule, HttpClientTestingModule,  RouterTestingModule.withRoutes([])],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
      providers: [
      ]

    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BasicFormComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component.activatedRoute.snapshot.routeConfig.path).toBeTruthy(); // why is this not working?
  });

});

The errors I am getting is

BasicFormComponent should create TypeError: Cannot read property
  'path' of null TypeError: Cannot read property 'snapshot' of undefined

Why won't it import the activatedRoute module?

I am trying to get my head wrapped testing, which seems to be a dark art.

Any guidance will be appreciated.

Body:
Thanks to @Gérôme Grignon for pointing me to the right direction.

The answer in removing the errors is below, take note in the providers, there is the use value settings. No more errors.

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { BasicFormComponent } from './basic-form.component';

describe('BasicFormComponent', () => {
  let component: BasicFormComponent;
  let fixture: ComponentFixture<BasicFormComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ BasicFormComponent ],
      imports: [DemoMaterialModule, ReactiveFormsModule, FormsModule, HttpClientTestingModule,  RouterTestingModule.withRoutes([])],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
      providers: [ BasicFormComponent, {
          provide: ActivatedRoute,
          useValue: {snapshot: {params: {'date': ''}, routeConfig: {'path': 'basic-form-edit/:date'}}}
      }]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BasicFormComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component.activatedRoute.snapshot.routeConfig.path).toBeTruthy(); // why is this not working?
  });
});


问:
How to check if string contains chars which are not in a list?
I have a question. How do I check if a python string contains chars which are not in a given list?

Here is the list (set):

set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._")
```

答:
You want to test whether the characters in the string are not a subset of the given set of characters. That is straightforward in Python because the <= operator tests if one set is a subset of another.

import string

# don't use a mutable set for this purpose
GIVEN = frozenset(string.ascii_letters + string.digits + '-._')

def uses_other_chars(s, given=GIVEN):
    return not set(s) <= given
```

<p>Examples:</p>

<pre class="lang-py prettyprint-override"><code>>>> uses_other_chars('abc')
False
>>> uses_other_chars('Hello!')
True
</code>```

Body:
You want to test whether the characters in the string are not a subset of the given set of characters. That is straightforward in Python because the <= operator tests if one set is a subset of another.

import string

# don't use a mutable set for this purpose
GIVEN = frozenset(string.ascii_letters + string.digits + '-._')

def uses_other_chars(s, given=GIVEN):
    return not set(s) <= given

Examples:

>>> uses_other_chars('abc')
False
>>> uses_other_chars('Hello!')
True


问:
How to check when the network is unavailable in iOS 13?
I have added some logic to handle the network is not unavailable but I have a hard time to trigger the error handler. I am using URLError networkUnavailableReason is it the right one?</p>

```<code>DataService.shared.GetMyData(completion: {(result) in
    DispatchQueue.main.async {
        switch result {
            case .success(let data):

                break
            case .failure(let error):
                print(error)
                if let error = error as? URLError, error.networkUnavailableReason == .constrained  {

                    self.showAlert()
                }

                break;
        }
    }
})
</code>```

答:
You can use NWPathMonitor, which is a network monitor, to check if the network is available. I used one like this, by creating a struct for it :

```<code>// make sure to import Network in your file when you do this
struct NetworkMonitor {
    static let monitor = NWPathMonitor()
    static var connection = true
}
</code>```

Then used it like this, wherever you want to start monitoring:

```<code>NetworkMonitor.monitor.pathUpdateHandler = { path in
               if path.status == .satisfied {
                    print("connection successful")
                    NetworkMonitor.connection = true
                    // then respond to successful connection here, I used a notification and this connection bool
              } else {
                    print("no connection")
                    NetworkMonitor.connection = false
                    // respond to lack of connection here
               }
          }

          let queue = DispatchQueue(label: "Monitor")
          NetworkMonitor.monitor.start(queue: queue)
</code>```

Body:
I have added some logic to handle the network is not unavailable but I have a hard time to trigger the error handler. I am using URLError networkUnavailableReason is it the right one?

DataService.shared.GetMyData(completion: {(result) in
    DispatchQueue.main.async {
        switch result {
            case .success(let data):

                break
            case .failure(let error):
                print(error)
                if let error = error as? URLError, error.networkUnavailableReason == .constrained  {

                    self.showAlert()
                }

                break;
        }
    }
})

Body:
You can use NWPathMonitor, which is a network monitor, to check if the network is available. I used one like this, by creating a struct for it :

// make sure to import Network in your file when you do this
struct NetworkMonitor {
    static let monitor = NWPathMonitor()
    static var connection = true
}

Then used it like this, wherever you want to start monitoring:

NetworkMonitor.monitor.pathUpdateHandler = { path in
               if path.status == .satisfied {
                    print("connection successful")
                    NetworkMonitor.connection = true
                    // then respond to successful connection here, I used a notification and this connection bool
              } else {
                    print("no connection")
                    NetworkMonitor.connection = false
                    // respond to lack of connection here
               }
          }

          let queue = DispatchQueue(label: "Monitor")
          NetworkMonitor.monitor.start(queue: queue)


问:
Why Crashlytics is asking for missing DSYM file every time?
I am using Crashlytics in my app everything working fine. even Crashlytics is also working good.

But the problem is that whenever I am creating a new build for our app
  its again showing missing DSYM File upload new.

Is there any solution for this?

In fabric Document, I found this. but I did not understand this.

can anyone explain to me how to resolve this issue?

https://docs.fabric.io/apple/crashlytics/advanced-setup.html

答:
This error means that some dSYM files are missing. The recommended approach is to constantly upload dSYM files to Crashlytics.

Now that Crashlytics is integrated in Firebase, the documentation has slightly changed: https://firebase.google.com/docs/crashlytics/get-deobfuscated-reports-new-sdk

Integrate Crashlytics : pod 'Firebase/Crashlytics'

Add a Run Script Phase :
find "${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}" -name "*.dSYM" | xargs -I \{\} $PODS_ROOT/FirebaseCrashlytics/upload-symbols -gsp ${SRCROOT}/GoogleService-Info.plist -p ios \{\}

In case you don't want to upload dSYM files each time you debug build your app : https://support.crashlytics.com/knowledgebase/articles/118559-can-i-make-the-dsym-uploading-only-on-release-buil


问:
Scipy Spatial Distance Sub-module rejects Numpy Array
I have a dataframe named, "df", with 4 columns. Three columns are independent variables: x1, x2, and x3. And, the other variable, y, is the dependent variable

I would like to calculate the distance, "pdist" between the dependent variable and each of the dependent variables, so I first converted each column to a numpy array as follows:

```<code>y = df[["y"]].values
x1 = df[["x1"]].values
x2 = df[["x2"]].values
x3 = df[["x3"]].values
</code>```

When I feed these arrays through this coding pipeline I got from Github:

```<code>import numpy as np
from scipy.spatial.distance import pdist

def distance_correlation(Xval, Yval, pval=True, nruns=500):

    X, Y = np.atleast_1d(Xval),np.atleast_1d(Yval)
    if np.prod(X.shape) == len(X):X = X[:, None]
    if np.prod(Y.shape) == len(Y):Y = Y[:, None]
    X, Y = np.atleast_2d(X),np.atleast_2d(Y)
    n = X.shape[0]
    if Y.shape[0] != X.shape[0]:raise ValueError('Number of samples must match')
    a, b = squareform(pdist(X)),squareform(pdist(Y))
    A = a - a.mean(axis=0)[None, :] - a.mean(axis=1)[:, None] + a.mean()
    B = b - b.mean(axis=0)[None, :] - b.mean(axis=1)[:, None] + b.mean()
    dcov2_xy = (A * B).sum() / float(n * n)
    dcov2_xx = (A * A).sum() / float(n * n)
    dcov2_yy = (B * B).sum() / float(n * n)
    dcor = np.sqrt(dcov2_xy) / np.sqrt(np.sqrt(dcov2_xx) * np.sqrt(dcov2_yy))
    if pval:
        greater = 0
        for i in range(nruns):
            Y_r = copy.copy(Yval)
            np.random.shuffle(Y_r)
            if distcorr(Xval, Y_r, pval=False) > dcor:
                greater += 1
        return (dcor, greater / float(nruns))
    else:
        return dcor

distance_correlation(x1, y, pval=True, nruns=500)
</code>```

I get this error:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-32-c720c9df4e97> in <module>
----> 1 distance_correlation(bop_sp500, price, pval=True, nruns=500)

<ipython-input-17-e0b3aea12c32> in distance_correlation(Xval, Yval, pval, nruns)
      9     n = X.shape[0]
     10     if Y.shape[0] != X.shape[0]:raise ValueError('Number of samples must match')
---> 11     a, b = squareform(pdist(X)),squareform(pdist(Y))
     12     A = a - a.mean(axis=0)[None, :] - a.mean(axis=1)[:, None] + a.mean()
     13     B = b - b.mean(axis=0)[None, :] - b.mean(axis=1)[:, None] + b.mean()

~\Anaconda3\lib\site-packages\scipy\spatial\distance.py in pdist(X, metric, *args, **kwargs)
   1997     s = X.shape
   1998     if len(s) != 2:
-> 1999         raise ValueError('A 2-dimensional array must be passed.')
   2000
   2001     m, n = s

ValueError: A 2-dimensional array must be passed..
</code>```

Could anyone identify where I am going wrong? I know the error originates from the manner in which I created my numpy arrays. But, I have no clues on fixing it.

Please explain it with examples that use my variable definitions. I am new to Python

答:
Ok, so I finally managed to figure out the cause of the problem I faced:

The Numpy array that was being fed into the helper function was a 2d array.

While the helper function required a "Numpy vector"; i.e. a 1d Numpy array.

The best way to create it is to use the numpy.ravel() function. Hence, for my datasets, the code would be as follows (I have broken down the steps for simplicity):

```<code># Create Arrays
y = df[["y"]].values
x1 = df[["x1"]].values
x2 = df[["x2"]].values
x3 = df[["x3"]].values

# Ravel Them
y = y.ravel()
x1 = x1.ravel()
x2 = x2.ravel()
x3 = x3.ravel()
</code>```

Body:
I have a dataframe named, "df", with 4 columns. Three columns are independent variables: x1, x2, and x3. And, the other variable, y, is the dependent variable

I would like to calculate the distance, "pdist" between the dependent variable and each of the dependent variables, so I first converted each column to a numpy array as follows:

y = df[["y"]].values
x1 = df[["x1"]].values
x2 = df[["x2"]].values
x3 = df[["x3"]].values

When I feed these arrays through this coding pipeline I got from Github:

import numpy as np
from scipy.spatial.distance import pdist

def distance_correlation(Xval, Yval, pval=True, nruns=500):

    X, Y = np.atleast_1d(Xval),np.atleast_1d(Yval)
    if np.prod(X.shape) == len(X):X = X[:, None]
    if np.prod(Y.shape) == len(Y):Y = Y[:, None]
    X, Y = np.atleast_2d(X),np.atleast_2d(Y)
    n = X.shape[0]
    if Y.shape[0] != X.shape[0]:raise ValueError('Number of samples must match')
    a, b = squareform(pdist(X)),squareform(pdist(Y))
    A = a - a.mean(axis=0)[None, :] - a.mean(axis=1)[:, None] + a.mean()
    B = b - b.mean(axis=0)[None, :] - b.mean(axis=1)[:, None] + b.mean()
    dcov2_xy = (A * B).sum() / float(n * n)
    dcov2_xx = (A * A).sum() / float(n * n)
    dcov2_yy = (B * B).sum() / float(n * n)
    dcor = np.sqrt(dcov2_xy) / np.sqrt(np.sqrt(dcov2_xx) * np.sqrt(dcov2_yy))
    if pval:
        greater = 0
        for i in range(nruns):
            Y_r = copy.copy(Yval)
            np.random.shuffle(Y_r)
            if distcorr(Xval, Y_r, pval=False) > dcor:
                greater += 1
        return (dcor, greater / float(nruns))
    else:
        return dcor

distance_correlation(x1, y, pval=True, nruns=500)

I get this error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-32-c720c9df4e97> in <module>
----> 1 distance_correlation(bop_sp500, price, pval=True, nruns=500)

<ipython-input-17-e0b3aea12c32> in distance_correlation(Xval, Yval, pval, nruns)
      9     n = X.shape[0]
     10     if Y.shape[0] != X.shape[0]:raise ValueError('Number of samples must match')
---> 11     a, b = squareform(pdist(X)),squareform(pdist(Y))
     12     A = a - a.mean(axis=0)[None, :] - a.mean(axis=1)[:, None] + a.mean()
     13     B = b - b.mean(axis=0)[None, :] - b.mean(axis=1)[:, None] + b.mean()

~\Anaconda3\lib\site-packages\scipy\spatial\distance.py in pdist(X, metric, *args, **kwargs)
   1997     s = X.shape
   1998     if len(s) != 2:
-> 1999         raise ValueError('A 2-dimensional array must be passed.')
   2000
   2001     m, n = s

ValueError: A 2-dimensional array must be passed..

Could anyone identify where I am going wrong? I know the error originates from the manner in which I created my numpy arrays. But, I have no clues on fixing it.

Please explain it with examples that use my variable definitions. I am new to Python

Body:
Ok, so I finally managed to figure out the cause of the problem I faced:

The Numpy array that was being fed into the helper function was a 2d array.

While the helper function required a "Numpy vector"; i.e. a 1d Numpy array.

The best way to create it is to use the numpy.ravel() function. Hence, for my datasets, the code would be as follows (I have broken down the steps for simplicity):

# Create Arrays
y = df[["y"]].values
x1 = df[["x1"]].values
x2 = df[["x2"]].values
x3 = df[["x3"]].values

# Ravel Them
y = y.ravel()
x1 = x1.ravel()
x2 = x2.ravel()
x3 = x3.ravel()


问:
Java Code to read file is not compiling on VS code editor
```<code>
import java.util.Scanner;
import java.io.*;
/*
 * PROJECT I: ReadData.java
 *
 * A sample code which demonstrates how to read data from an ASCII file using
 * the Scanner
 */

public class ReadData {

  public static void main(String[] args) {

    double x,y,rad;
    int lineCount = 0;

    //Initialise the max and minimum to something sensible
    double maxX = Double.MIN_VALUE;
    double minX = Double.MAX_VALUE;
    double maxY = Double.MIN_VALUE;
    double minY = Double.MAX_VALUE;
 try {
        File file = new File("C:\\Users\\Yakov\\Desktop\\Study stuff\\MA117\\Project 1.data");
      Scanner scanner = new Scanner(new BufferedReader(new FileReader(file)));

      while(scanner.hasNext()) {

        //Read the three valies on each line of the file
        x = scanner.nextDouble();
        y = scanner.nextDouble();
        rad = scanner.nextDouble();

        //Increment the linecounter.
        lineCount++;

        // Find max, min for x and y coords
        if (x > maxX) {
          maxX = x;
        }
        if (y > maxY) {
          maxY = y;
        }
        if (x < minX) {
            minX = x;
        }
        if (y < minY) {
          minY = y;
        }

      }
    } catch(Exception e) {
      System.err.println("An error has occured. See below for details");
      e.printStackTrace();
    }

    System.out.println("Information about the data:");
    System.out.println("  Number of lines in file: " + lineCount);

    System.out.format("  Max x-coord: %10.9f\n", maxX);
    System.out.format("  Min x-coord: %10.9f\n", minX);
    System.out.format("  Max y-coord: %10.9f\n", maxY);
    System.out.format("  Min y-coord: %10.9f\n", minY);

  }

}

</code>```

I'm trying to run this Java code in VS code editor. It is a sample code which is supposed to be able to run, which is provided on the internet. How do I make this run? Is there maybe a problem in this code? The file I have inserted in is real( it exists) , so I dont see any reason this code is not running. I am using windows. Any idea how to fix this? The error is "Exception in thread "main" java.lang.Error: Unresolved compilation problem:

```<code>    at ReadData.main(ReadData (1).java:24)"
</code>```

Edit: import of scanner is not the problem

答: You don't have an import for Scanner - it's under java.util and you only have java.io.*

Body:
import java.util.Scanner;
import java.io.*;
/*
 * PROJECT I: ReadData.java
 *
 * A sample code which demonstrates how to read data from an ASCII file using
 * the Scanner
 */

public class ReadData {

  public static void main(String[] args) {

    double x,y,rad;
    int lineCount = 0;

    //Initialise the max and minimum to something sensible
    double maxX = Double.MIN_VALUE;
    double minX = Double.MAX_VALUE;
    double maxY = Double.MIN_VALUE;
    double minY = Double.MAX_VALUE;
 try {
        File file = new File("C:\\Users\\Yakov\\Desktop\\Study stuff\\MA117\\Project 1.data");
      Scanner scanner = new Scanner(new BufferedReader(new FileReader(file)));

      while(scanner.hasNext()) {

        //Read the three valies on each line of the file
        x = scanner.nextDouble();
        y = scanner.nextDouble();
        rad = scanner.nextDouble();

        //Increment the linecounter.
        lineCount++;

        // Find max, min for x and y coords
        if (x > maxX) {
          maxX = x;
        }
        if (y > maxY) {
          maxY = y;
        }
        if (x < minX) {
            minX = x;
        }
        if (y < minY) {
          minY = y;
        }

      }
    } catch(Exception e) {
      System.err.println("An error has occured. See below for details");
      e.printStackTrace();
    }

    System.out.println("Information about the data:");
    System.out.println("  Number of lines in file: " + lineCount);

    System.out.format("  Max x-coord: %10.9f\n", maxX);
    System.out.format("  Min x-coord: %10.9f\n", minX);
    System.out.format("  Max y-coord: %10.9f\n", maxY);
    System.out.format("  Min y-coord: %10.9f\n", minY);

  }

}

I'm trying to run this Java code in VS code editor. It is a sample code which is supposed to be able to run, which is provided on the internet. How do I make this run? Is there maybe a problem in this code? The file I have inserted in is real( it exists) , so I dont see any reason this code is not running. I am using windows. Any idea how to fix this? The error is "Exception in thread "main" java.lang.Error: Unresolved compilation problem:

    at ReadData.main(ReadData (1).java:24)"

Edit: import of scanner is not the problem


问:
cannot set checked of undefined (saving checkboxs w/ localStorage)
I am saving my checkbox states with localStorage, then re-rendering them later (when button is clicked) the below seems to be working for the most part; except it's erroring in my load function with 'cannot set checked of undefined'.

Note my checkboxes don't come from standard HTML mark-up they are dynamically invoked with javascript - perhaps there's a better way then using input.checked?

```<code>function checkSaver() {
  user = JSON.parse(localStorage.getItem(user));

  var inputs = document.querySelectorAll('input[type="checkbox"]');
  user.userAchkData = [];

  inputs.forEach(function(input){
    user.userAchkData.push({ id: input.id, checked: input.checked });
  });

  localStorage.setItem(username, JSON.stringify(user));
  console.log(JSON.stringify(user));

}
</code>```

```<code>function load_() {
  // get saved latest checkbox states, recheck
  user = JSON.parse(localStorage.getItem(user));
  var inputs = user.userAchkData;

  inputs.forEach(function(input){
    document.getElementById(input.id).checked = input.checked; // erroring here, cannot set checked of undefined
  });
</code>```

Full error: (although it is actually checking the boxes?) Derives from after the = sign above. Any pointers?

Uncaught TypeError: Cannot set property 'checked' of null
    at eval (eventHandlers.js:339)
    at Array.forEach ()
    at load_ (eventHandlers.js:338)

答:
the problem is that you are not checking that the variable is correctly set.

try with this:

```<code>function load_() {
  // get saved latest checkbox states, recheck
  // but first lets define a default value.
  const defaultData = { userAchkData: [] };
  const localStorageData = JSON.parse(localStorage.getItem(user));
  let user = localStorageData || defaultData;
  let inputs = user.userAchkData;

  inputs.forEach(function(input){
    document.getElementById(input.id).checked = input.checked; // erroring here, cannot set checked of undefined
  });
</code>```

same applies for the save function.

```<code>function checkSaver() {
  const defaultData = { userAchkData: [] };
  const localStorageData = JSON.parse(localStorage.getItem(user));
  let user = localStorageData || defaultData;

  let inputs = document.querySelectorAll('input[type="checkbox"]');
  user.userAchkData = [];

  inputs.forEach(function(input){
    user.userAchkData.push({ id: input.id, checked: input.checked });
  });

  localStorage.setItem(username, JSON.stringify(user));
  console.log(JSON.stringify(user));

}
</code>```

Body:
I am saving my checkbox states with localStorage, then re-rendering them later (when button is clicked) the below seems to be working for the most part; except it's erroring in my load function with 'cannot set checked of undefined'.

Note my checkboxes don't come from standard HTML mark-up they are dynamically invoked with javascript - perhaps there's a better way then using input.checked?

function checkSaver() {
  user = JSON.parse(localStorage.getItem(user));

  var inputs = document.querySelectorAll('input[type="checkbox"]');
  user.userAchkData = [];

  inputs.forEach(function(input){
    user.userAchkData.push({ id: input.id, checked: input.checked });
  });

  localStorage.setItem(username, JSON.stringify(user));
  console.log(JSON.stringify(user));

}

function load_() {
  // get saved latest checkbox states, recheck
  user = JSON.parse(localStorage.getItem(user));
  var inputs = user.userAchkData;

  inputs.forEach(function(input){
    document.getElementById(input.id).checked = input.checked; // erroring here, cannot set checked of undefined
  });

Full error: (although it is actually checking the boxes?) Derives from after the = sign above. Any pointers?

Uncaught TypeError: Cannot set property 'checked' of null
    at eval (eventHandlers.js:339)
    at Array.forEach ()
    at load_ (eventHandlers.js:338)

Body:
the problem is that you are not checking that the variable is correctly set.

try with this:

function load_() {
  // get saved latest checkbox states, recheck
  // but first lets define a default value.
  const defaultData = { userAchkData: [] };
  const localStorageData = JSON.parse(localStorage.getItem(user));
  let user = localStorageData || defaultData;
  let inputs = user.userAchkData;

  inputs.forEach(function(input){
    document.getElementById(input.id).checked = input.checked; // erroring here, cannot set checked of undefined
  });

same applies for the save function.

function checkSaver() {
  const defaultData = { userAchkData: [] };
  const localStorageData = JSON.parse(localStorage.getItem(user));
  let user = localStorageData || defaultData;

  let inputs = document.querySelectorAll('input[type="checkbox"]');
  user.userAchkData = [];

  inputs.forEach(function(input){
    user.userAchkData.push({ id: input.id, checked: input.checked });
  });

  localStorage.setItem(username, JSON.stringify(user));
  console.log(JSON.stringify(user));

}


问:
How to insert values to a nested array
I am having one report array of objects which is used to show report data on the dashboard as below,

```<code>    report = [
              {id: "id01", code: "C001", name: "apples", type: "fruits", intime:[], quantity:[]},
              {id: "id01", code: "C001", name: "grapes", type: "fruits", intime:[], quantity:[]},
              {id: "id01", code: "C002", name: "apples", type: "fruits", intime:[], quantity:[]},
              {id: "id01", code: "C002", name: "grapes", type: "fruits", intime:[], quantity:[]}
             ]
</code>```

And below array as input,

```<code>record = [
    {code: "C001",
    records :[{intime: "15:32:12", apples: "30", grapes: "80"},
            {intime: "15:32:13", apples: "34", grapes: "50"}]
    },
    {code: "C002",
    records :[{intime: "15:32:12", apples: "56", grapes: "100"},
            {intime: "15:32:13", apples: "75", grapes: "38"}]
    },
]
</code>```

I want to put these values to arrays of report array as per matching condition so that report array should look like,

```<code>report = [
  {id: "id01", code: "C001", name: "apples", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[30,34]},
  {id: "id01", code: "C001", name: "grapes", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[80,50]},
  {id: "id01", code: "C002", name: "apples", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[56,75]},
  {id: "id01", code: "C002", name: "grapes", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[100,38]}
]
</code>```

I think , this can be achieved through array filter method in loop but that method does not seems efficient when record array is big in size.  Please suggest me some better and efficient way to put values in such way.

答:
```<code>_.each(report, rep => {
    let code = rep.code;
    let name = rep.name;
    _.each(record, rec => {
        if(rec.code === code) {
            let recs = rec.records;
            _.each(recs, re => {
                rep.intime.push(re.intime);
                rep.quantity.push(re[name]);
            });
        }
    });
});
</code>```

<p>You could utilize the 'underscore' module for JavaScript in this scenario. First I start with an each loop that iterates over each object in the report array. Then we can store the code and the name keys associated with that object. We can then iterate over each record and if the codes are equal we can iterate over that particular object. We can then iterate over each of the records and store the intime and then the fruit quantity based on the fruit name associated with the report object that we are currently iterating over. We then push those values to the intime and quantity arrays associated with that report object. </p>

Title: How to insert values to a nested array

Body:
I am having one report array of objects which is used to show report data on the dashboard as below,

    report = [
              {id: "id01", code: "C001", name: "apples", type: "fruits", intime:[], quantity:[]},
              {id: "id01", code: "C001", name: "grapes", type: "fruits", intime:[], quantity:[]},
              {id: "id01", code: "C002", name: "apples", type: "fruits", intime:[], quantity:[]},
              {id: "id01", code: "C002", name: "grapes", type: "fruits", intime:[], quantity:[]}
             ]

And below array as input,

record = [
    {code: "C001",
    records :[{intime: "15:32:12", apples: "30", grapes: "80"},
            {intime: "15:32:13", apples: "34", grapes: "50"}]
    },
    {code: "C002",
    records :[{intime: "15:32:12", apples: "56", grapes: "100"},
            {intime: "15:32:13", apples: "75", grapes: "38"}]
    },
]

I want to put these values to arrays of report array as per matching condition so that report array should look like,

report = [
  {id: "id01", code: "C001", name: "apples", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[30,34]},
  {id: "id01", code: "C001", name: "grapes", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[80,50]},
  {id: "id01", code: "C002", name: "apples", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[56,75]},
  {id: "id01", code: "C002", name: "grapes", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[100,38]}
]

I think , this can be achieved through array filter method in loop but that method does not seems efficient when record array is big in size.  Please suggest me some better and efficient way to put values in such way.

Body:
_.each(report, rep => {
    let code = rep.code;
    let name = rep.name;
    _.each(record, rec => {
        if(rec.code === code) {
            let recs = rec.records;
            _.each(recs, re => {
                rep.intime.push(re.intime);
                rep.quantity.push(re[name]);
            });
        }
    });
});

You could utilize the 'underscore' module for JavaScript in this scenario. First I start with an each loop that iterates over each object in the report array. Then we can store the code and the name keys associated with that object. We can then iterate over each record and if the codes are equal we can iterate over that particular object. We can then iterate over each of the records and store the intime and then the fruit quantity based on the fruit name associated with the report object that we are currently iterating over. We then push those values to the intime and quantity arrays associated with that report object.


问:
JavaScript click event listener on class
I'm currently trying to write some JavaScript to get the attribute of the class that has been clicked. I know that to do this the correct way, I should use an event listener.
My code is as follows:

```<code>var classname = document.getElementsByClassName("classname");

var myFunction = function() {
    var attribute = this.getAttribute("data-myattribute");
    alert(attribute);
};

classname.addEventListener('click', myFunction(), false);
</code>```

I was expecting to get an alert box every time I clicked on one of the classes to tell me the attribute but unfortunately this does not work. Can anyone help please?

(Note - I can quite easily do this in jQuery but I would NOT like to use it)

答:
With modern JavaScript it can be done like this:

const divs = document.querySelectorAll('.a');

divs.forEach(el => el.addEventListener('click', event => {
  console.log(event.target.getAttribute("data-el"));
}));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Example</title>
  <style>
    .a {
      background-color:red;
      height: 33px;
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      cursor: pointer;
    }

    .b {
      background-color:#00AA00;
      height: 50px;
      display: flex;
      align-items: center;
      margin-bottom: 10px;
    }
  </style>
</head>
<body>
  <div class="a" data-el="1">1</div>
  <div class="b" data-el="no-click-handler">2</div>
  <div class="a" data-el="3">11</div>
</body>
</html></code>```

Gets all elements by class name

Loops over all elements with using forEach

Attach an event listener on each element

Uses event.target to retrieve more information for specific element

ContentLicense: CC BY-SA 3.0

Body:
I'm currently trying to write some JavaScript to get the attribute of the class that has been clicked. I know that to do this the correct way, I should use an event listener.
My code is as follows:

var classname = document.getElementsByClassName("classname");

var myFunction = function() {
    var attribute = this.getAttribute("data-myattribute");
    alert(attribute);
};

classname.addEventListener('click', myFunction(), false);

I was expecting to get an alert box every time I clicked on one of the classes to tell me the attribute but unfortunately this does not work. Can anyone help please?

(Note - I can quite easily do this in jQuery but I would NOT like to use it)

Body:
With modern JavaScript it can be done like this:

const divs = document.querySelectorAll('.a');

divs.forEach(el => el.addEventListener('click', event => {
  console.log(event.target.getAttribute("data-el"));
}));

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Example</title>
  <style>
    .a {
      background-color:red;
      height: 33px;
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      cursor: pointer;
    }

    .b {
      background-color:#00AA00;
      height: 50px;
      display: flex;
      align-items: center;
      margin-bottom: 10px;
    }
  </style>
</head>
<body>
  <div class="a" data-el="1">1</div>
  <div class="b" data-el="no-click-handler">2</div>
  <div class="a" data-el="3">11</div>
</body>
</html>

Gets all elements by class name

Loops over all elements with using forEach

Attach an event listener on each element

Uses event.target to retrieve more information for specific element


问:
In R, image processing loop takes an order of magnitude longer to process after ~50 iterations
EDIT: changed the image names from Image1-Image11 to Image50-Image60 for clarity.

EDIT2: Solved by adding a garbage collection command after removing the image file in each loop iteration. Code is updated.

I have 400+ jpeg images in a folder. I'm trying write a script to: read each image, identify some text in the image, and then write the file name and that text into a data frame.

When I run the script below, the first ~50 iterations print a time of .1-.3 seconds. Then, for a few iterations, the iteration will take 1-3 seconds. Then, this bumps up to 1-5 minutes, after which I kill the script.

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

fileList3 = list.files(path = filePath)

printJobXRes = data.frame(
                          jobName = as.character(),
                          xRes = as.numeric(),
                          stringsAsFactors = FALSE
                          )
i = 0

for (fileName in fileList3){
  img = paste0(filePath, '/', fileName, '_TestImage.jpg')
  start_time = Sys.time()
  temp.xRes = image_read(img, strip = T) %>%
    image_rotate(270) %>%
    image_crop('90x150+1750') %>%
    image_negate %>%
    image_convert(type = 'Bilevel') %>%
    image_ocr %>%
    as.numeric

  stop_time = Sys.time()
  i = i+1
  print(paste(fileName,'first attempt, item #', i))
  print(stop_time-start_time)

  temp.df3 = data.frame(
    jobName = fileName,
    xRes = temp.xRes,
    stringsAsFactors = FALSE
    )
  printJobXRes = rbind(printJobXRes, temp.df3)
  rm(temp.xRes)
  rm(temp.df3)
  rm(img)
  gc() #This solved the issue
}
</code>```

Here's a couple lines of the output:

```<code>#Images 1-49 process in .1-.3 seconds each
[1] "Image50.jpg first attempt, item # 50"
Time difference of 0.2320111 secs
[1] "Image51.jpg first attempt, item # 51"
Time difference of 0.213742 secs
[1] "Image52.jpg first attempt, item # 52"
Time difference of 0.2536581 secs
[1] "Image53.jpg first attempt, item # 53"
Time difference of 1.253844 secs
[1] "Image54.jpg first attempt, item # 54"
Time difference of 1.149764 secs
[1] "Image55.jpg first attempt, item # 55"
Time difference of 1.171134 secs
[1] "Image56.jpg first attempt, item # 56"
Time difference of 1.397093 secs
[1] "Image57.jpg first attempt, item # 57"
Time difference of 1.201915 secs
[1] "Image58.jpg first attempt, item # 58"
Time difference of 1.455768 secs
[1] "Image59.jpg first attempt, item # 59"
Time difference of 1.618744 secs
[1] "Image60.jpg first attempt, item # 60"
Time difference of 4.527751 mins
</code>```

Can anyone offer suggestions as to why the loop doesn't continue to take ~.1-.3 seconds? All jpgs are roughly the same size, resolution, and all generated from the same source.

答: I was able to solve my issue based on Mark's suggestion. I was removing the image file from memory in each loop iteration, but the freed up memory was never realized by R. I added a garbage collection command (gc()) into the loop to fix this issue, and the loop then ran as expected. </p>

Body:
EDIT: changed the image names from Image1-Image11 to Image50-Image60 for clarity.

EDIT2: Solved by adding a garbage collection command after removing the image file in each loop iteration. Code is updated.

I have 400+ jpeg images in a folder. I'm trying write a script to: read each image, identify some text in the image, and then write the file name and that text into a data frame.

When I run the script below, the first ~50 iterations print a time of .1-.3 seconds. Then, for a few iterations, the iteration will take 1-3 seconds. Then, this bumps up to 1-5 minutes, after which I kill the script.

library(dplyr)
library(magick)

fileList3 = list.files(path = filePath)

printJobXRes = data.frame(
                          jobName = as.character(),
                          xRes = as.numeric(),
                          stringsAsFactors = FALSE
                          )
i = 0

for (fileName in fileList3){
  img = paste0(filePath, '/', fileName, '_TestImage.jpg')
  start_time = Sys.time()
  temp.xRes = image_read(img, strip = T) %>%
    image_rotate(270) %>%
    image_crop('90x150+1750') %>%
    image_negate %>%
    image_convert(type = 'Bilevel') %>%
    image_ocr %>%
    as.numeric

  stop_time = Sys.time()
  i = i+1
  print(paste(fileName,'first attempt, item #', i))
  print(stop_time-start_time)

  temp.df3 = data.frame(
    jobName = fileName,
    xRes = temp.xRes,
    stringsAsFactors = FALSE
    )
  printJobXRes = rbind(printJobXRes, temp.df3)
  rm(temp.xRes)
  rm(temp.df3)
  rm(img)
  gc() #This solved the issue
}

Here's a couple lines of the output:

#Images 1-49 process in .1-.3 seconds each
[1] "Image50.jpg first attempt, item # 50"
Time difference of 0.2320111 secs
[1] "Image51.jpg first attempt, item # 51"
Time difference of 0.213742 secs
[1] "Image52.jpg first attempt, item # 52"
Time difference of 0.2536581 secs
[1] "Image53.jpg first attempt, item # 53"
Time difference of 1.253844 secs
[1] "Image54.jpg first attempt, item # 54"
Time difference of 1.149764 secs
[1] "Image55.jpg first attempt, item # 55"
Time difference of 1.171134 secs
[1] "Image56.jpg first attempt, item # 56"
Time difference of 1.397093 secs
[1] "Image57.jpg first attempt, item # 57"
Time difference of 1.201915 secs
[1] "Image58.jpg first attempt, item # 58"
Time difference of 1.455768 secs
[1] "Image59.jpg first attempt, item # 59"
Time difference of 1.618744 secs
[1] "Image60.jpg first attempt, item # 60"
Time difference of 4.527751 mins

Can anyone offer suggestions as to why the loop doesn't continue to take ~.1-.3 seconds? All jpgs are roughly the same size, resolution, and all generated from the same source.


问:
Is there alternative to get middle element from array using Ramda?
I tried this code and it produces me wanted result:

```<code>const {
  __,
  compose,
  converge,
  divide,
  identity,
  length,
  prop
} = require("ramda");

const div2 = divide(__, 2);
const lengthDiv2 = compose(Math.floor, div2, length);
const midElement = converge(prop, [lengthDiv2, identity]);

console.log(midElement([1, 5, 4]); //5
</code>```

But I dont know is there another way to get property from array, particularly some other implementation of midElement function?

答:
You can create midElement by chaining R.nth and lengthDiv2 because according to R.chain documentation (and @ScottSauyet):

If second argument is a function, chain(f, g)(x) is equivalent to
  f(g(x), x).

In this case g is lengthDiv2, f is R.nth, and x is the array. So, the result would be R.nth(lengthDiv2(array), array), which will return the middle item.

const { compose, flip, divide, length, chain, nth } = R;

const div2 = flip(divide)(2); // create the function using flip
const lengthDiv2 = compose(Math.floor, div2, length);
const midElement = chain(nth, lengthDiv2); // chain R.nth and lengthDiv2

console.log(midElement([1, 5, 4])); //5```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script></code>```

Body:
I tried this code and it produces me wanted result:

const {
  __,
  compose,
  converge,
  divide,
  identity,
  length,
  prop
} = require("ramda");

const div2 = divide(__, 2);
const lengthDiv2 = compose(Math.floor, div2, length);
const midElement = converge(prop, [lengthDiv2, identity]);

console.log(midElement([1, 5, 4]); //5

But I dont know is there another way to get property from array, particularly some other implementation of midElement function?

Body:
You can create midElement by chaining R.nth and lengthDiv2 because according to R.chain documentation (and @ScottSauyet):

If second argument is a function, chain(f, g)(x) is equivalent to
  f(g(x), x).

In this case g is lengthDiv2, f is R.nth, and x is the array. So, the result would be R.nth(lengthDiv2(array), array), which will return the middle item.

const { compose, flip, divide, length, chain, nth } = R;

const div2 = flip(divide)(2); // create the function using flip
const lengthDiv2 = compose(Math.floor, div2, length);
const midElement = chain(nth, lengthDiv2); // chain R.nth and lengthDiv2

console.log(midElement([1, 5, 4])); //5

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>


问:
Why is more memory allocated than expected?
I'm playing around with BenchmarkDotNet and its MemoryDiagnoser feature.

Considering the following benchmark:

```<code>[Benchmark]
public void Dummy()
{
   var buffer = new byte[1];
}
</code>```

I expect it to allocate exactly 1 byte.

But the benchmark result shows that a total of 32 bytes were allocated. How come? I find this quite misleading.

```<code>| Method |     Mean |     Error |    StdDev |   Median | Ratio | Rank |  Gen 0 | Gen 1 | Gen 2 | Allocated |
|------- |---------:|----------:|----------:|---------:|------:|-----:|-------:|------:|------:|----------:|
|  Dummy | 4.486 ns | 0.1762 ns | 0.5196 ns | 4.650 ns |  1.00 |    1 | 0.0038 |     - |     - |      32 B |

                                                                                why not 1 byte? ^^^^
</code>```

答: You're not allocating a byte. You're allocating a byte array. Array is a reference type and all reference type instances come with a bit of overhead. So the total size of any array is bigger than the size of the elements. Adam's answer has a nice break down of the details.

Body:
I'm playing around with BenchmarkDotNet and its MemoryDiagnoser feature.

Considering the following benchmark:

[Benchmark]
public void Dummy()
{
   var buffer = new byte[1];
}

I expect it to allocate exactly 1 byte.

But the benchmark result shows that a total of 32 bytes were allocated. How come? I find this quite misleading.

| Method |     Mean |     Error |    StdDev |   Median | Ratio | Rank |  Gen 0 | Gen 1 | Gen 2 | Allocated |
|------- |---------:|----------:|----------:|---------:|------:|-----:|-------:|------:|------:|----------:|
|  Dummy | 4.486 ns | 0.1762 ns | 0.5196 ns | 4.650 ns |  1.00 |    1 | 0.0038 |     - |     - |      32 B |

                                                                                why not 1 byte? ^^^^


问:
Setting unique constraint for a table field in ABAP
How to add constraint for a field in a table that should only contain unique values in ABAP?</p>

答:
Setting the the field as a table key ?

as far as i know, there is no "Unique" flag for table field. If you really need such a check, you could code a control into the event (ie sm30 / Environnement / Modify / Events) before the data is writed to the DB.

regards


问:
SELECT INTO a temporary table then drop on commit
I'd like to SELECT INTO a temporary table and drop the temporary table on commit.

I can do

```<code>BEGIN;
SELECT
foo, bar
INTO TEMPORARY TABLE foo_table
FROM bar_table
COMMIT;
</code>```

but the temporary table persists for the lifetime of the session.

I can create the temporary table separately:

```<code>BEGIN;
CREATE TEMPORARY TABLE foo_table
(foo varchar, bar int)
ON COMMIT DROP;
SELECT foo, bar
INTO foo_table
FROM bar_table;
COMMIT;
</code>```

but it's not as nice, because I need to specify the column names and types of the temporary table myself.

Is it possible to do ON COMMIT DROP with INTO TEMPORARY TABLE?

答:
Use (the recommended) create table as syntax:

```<code>create temporary table foo_table
  on commit drop
as
SELECT foo, bar
FROM bar_table;
</code>```

Body:
I'd like to SELECT INTO a temporary table and drop the temporary table on commit.

I can do

BEGIN;
SELECT
foo, bar
INTO TEMPORARY TABLE foo_table
FROM bar_table
COMMIT;

but the temporary table persists for the lifetime of the session.

I can create the temporary table separately:

BEGIN;
CREATE TEMPORARY TABLE foo_table
(foo varchar, bar int)
ON COMMIT DROP;
SELECT foo, bar
INTO foo_table
FROM bar_table;
COMMIT;

but it's not as nice, because I need to specify the column names and types of the temporary table myself.

Is it possible to do ON COMMIT DROP with INTO TEMPORARY TABLE?

Body:
Use (the recommended) create table as syntax:

create temporary table foo_table
  on commit drop
as
SELECT foo, bar
FROM bar_table;


问:
Set Jackson Timezone for Date deserialization
I'm using Jackson (via Spring MVC Annotations) to deserialize a field into a java.util.Date from JSON. The POST looks like - {"enrollDate":"2011-09-28T00:00:00.000Z"}, but when the Object is created by Spring & Jackson it sets the date as "2011-09-27 20:00:00".

How can I set the proper timezone in Jackson?
Or if that is not the problem, how do I send EST from the JSON message?

Javascript/jQuery:

```<code>var personDataView = { enrollDate : new Date($("#enrollDate").val()),
                       //...other members
                      };

$.postJSON('/some/path/', personDataView, function(data){
    //... handle the response here

});
</code>```

JSON Message:

{"enrollDate":"2011-09-28T00:00:00.000Z"}

Spring Controller:

```<code>@RequestMapping(value="/", method=RequestMethod.POST)
public @ResponseBody String saveProfile(@RequestBody personDataView persondataView, HttpServletRequest request)
{
        //...dataView has a java.util.Date enrollDate field
        //...other code
}
</code>```

答:
For anyone struggling with this problem in the now (Feb 2020), the following Medium post was crucial to overcoming it for us.

https://medium.com/@ttulka/spring-http-message-converters-customizing-770814eb2b55

In our case, the app uses @EnableWebMvc and would break if removed so, the section on 'The Life without Spring Boot' was critical. Here's what ended up solving this for us. It allows us to still consume and produce JSON and XML as well as format our datetime during serialization to suit the app's needs.

```<code>@Configuration
@ComponentScan("com.company.branch")
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(0, new MappingJackson2XmlHttpMessageConverter(
                new Jackson2ObjectMapperBuilder()
                        .defaultUseWrapper(false)
                        .createXmlMapper(true)
                        .simpleDateFormat("yyyy-mm-dd'T'HH:mm:ss'Z'")
                        .build()
        ));
    converters.add(1, new MappingJackson2HttpMessageConverter(
                new Jackson2ObjectMapperBuilder()
                        .build()
        ));
    }
}
</code>```

Body:
I'm using Jackson (via Spring MVC Annotations) to deserialize a field into a java.util.Date from JSON. The POST looks like - {"enrollDate":"2011-09-28T00:00:00.000Z"}, but when the Object is created by Spring & Jackson it sets the date as "2011-09-27 20:00:00".

How can I set the proper timezone in Jackson?
Or if that is not the problem, how do I send EST from the JSON message?

Javascript/jQuery:

var personDataView = { enrollDate : new Date($("#enrollDate").val()),
                       //...other members
                      };

$.postJSON('/some/path/', personDataView, function(data){
    //... handle the response here

});

JSON Message:

{"enrollDate":"2011-09-28T00:00:00.000Z"}

Spring Controller:

@RequestMapping(value="/", method=RequestMethod.POST)
public @ResponseBody String saveProfile(@RequestBody personDataView persondataView, HttpServletRequest request)
{
        //...dataView has a java.util.Date enrollDate field
        //...other code
}

Body:
For anyone struggling with this problem in the now (Feb 2020), the following Medium post was crucial to overcoming it for us.

https://medium.com/@ttulka/spring-http-message-converters-customizing-770814eb2b55

In our case, the app uses @EnableWebMvc and would break if removed so, the section on 'The Life without Spring Boot' was critical. Here's what ended up solving this for us. It allows us to still consume and produce JSON and XML as well as format our datetime during serialization to suit the app's needs.

@Configuration
@ComponentScan("com.company.branch")
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(0, new MappingJackson2XmlHttpMessageConverter(
                new Jackson2ObjectMapperBuilder()
                        .defaultUseWrapper(false)
                        .createXmlMapper(true)
                        .simpleDateFormat("yyyy-mm-dd'T'HH:mm:ss'Z'")
                        .build()
        ));
    converters.add(1, new MappingJackson2HttpMessageConverter(
                new Jackson2ObjectMapperBuilder()
                        .build()
        ));
    }
}


问:
How to Read GZIP csv from S3 directly into pandas dataframe
I'm writing an airflow job to read a gzipped file from s3.

First I get the key for the object, which works fine

```<code>obj = self.s3_hook.get_key(key, bucket_name=self.s3_bucket)
</code>```

obj looks fine, something like this:

```<code>path/to/file/data_1.csv.gz
</code>```

Now I want to read the contents into a pandas dataframe. I've tried a number of things but this is my current iteration:

```<code>import pandas as pd
df = pd.read_csv(obj['Body'], compression='gzip')
</code>```

This returns the following error:

```<code>TypeError: 's3.Object' object is not subscriptable
</code>```

What am I doing wrong? i feel like I need to do something with StringIO or BytesIO...I was able to read it in as bytes, but thought there was a more straight forward way to get to a dataframe

Just in case it matters, one row of the data looks like this when I unzip and open in CSV:

```<code> 9671211|ddc9979d5ff90a4714fec7290657c90f|2138|2018-01-30 00:00:12|2018-01-30 00:00:16.069048|42b32863522dbe52e963034bb0aa68b6|1909705|8803795|collect|\\N|0||0||0|
</code>```

答:
figured it out:</p>

```<code>obj = self.s3_hook.get_key(key, bucket_name=self.s3_bucket)
df = pd.read_csv(obj.get()['Body'], compression='gzip', header = None, sep = '|')
</code>```

Body:
I'm writing an airflow job to read a gzipped file from s3.

First I get the key for the object, which works fine

obj = self.s3_hook.get_key(key, bucket_name=self.s3_bucket)

obj looks fine, something like this:

path/to/file/data_1.csv.gz

Now I want to read the contents into a pandas dataframe. I've tried a number of things but this is my current iteration:

import pandas as pd
df = pd.read_csv(obj['Body'], compression='gzip')

This returns the following error:

TypeError: 's3.Object' object is not subscriptable

What am I doing wrong? i feel like I need to do something with StringIO or BytesIO...I was able to read it in as bytes, but thought there was a more straight forward way to get to a dataframe

Just in case it matters, one row of the data looks like this when I unzip and open in CSV:

 9671211|ddc9979d5ff90a4714fec7290657c90f|2138|2018-01-30 00:00:12|2018-01-30 00:00:16.069048|42b32863522dbe52e963034bb0aa68b6|1909705|8803795|collect|\\N|0||0||0|

Body:
figured it out:

obj = self.s3_hook.get_key(key, bucket_name=self.s3_bucket)
df = pd.read_csv(obj.get()['Body'], compression='gzip', header = None, sep = '|')


问:
Write cleaned BS4 data to csv file
```<code>from selenium import webdriver

from bs4 import BeautifulSoup

import csv

chrome_path = r"C:\Users\chromedriver_win32\chromedriver.exe"

driver = webdriver.Chrome(chrome_path)

driver.get('http://www.yell.com')

search = driver.find_element_by_id("search_keyword")

search.send_keys("plumbers")

place = driver.find_element_by_id("search_location")

place.send_keys("London")

driver.find_element_by_xpath("""//*[@id="searchBoxForm"]/fieldset/div[1]/div[3]/button""").click()

soup = BeautifulSoup(driver.page_source, 'html.parser')

for names in soup.find_all("span", {"class": "businessCapsule--name"}):
    print(names.text)

Output = soup.find_all("span", {"class": "businessCapsule--name"})

with open('comple16.csv', 'w') as csv_file:
    csv.register_dialect('custom', delimiter='\n', quoting=csv.QUOTE_NONE, escapechar='\\')
    writer = csv.writer(csv_file, 'custom')
    row = Output
    writer.writerow(row)
</code>```

Currently the code is producing this in the csv file = class": "businessCapsule-- (scraped text)

I would like to only print the scraped text into the CSV file (without the tags)

Please help.

答:
After:

```<code>Output = soup.find_all("span", {"class": "businessCapsule--name"})
</code>```

add:

```<code>Output = [row.text for row in Output]
</code>```

in order to extract text from SPAN fields.

Title: Write cleaned BS4 data to csv file

Body:
from selenium import webdriver

from bs4 import BeautifulSoup

import csv

chrome_path = r"C:\Users\chromedriver_win32\chromedriver.exe"

driver = webdriver.Chrome(chrome_path)

driver.get('http://www.yell.com')

search = driver.find_element_by_id("search_keyword")

search.send_keys("plumbers")

place = driver.find_element_by_id("search_location")

place.send_keys("London")

driver.find_element_by_xpath("""//*[@id="searchBoxForm"]/fieldset/div[1]/div[3]/button""").click()

soup = BeautifulSoup(driver.page_source, 'html.parser')

for names in soup.find_all("span", {"class": "businessCapsule--name"}):
    print(names.text)

Output = soup.find_all("span", {"class": "businessCapsule--name"})

with open('comple16.csv', 'w') as csv_file:
    csv.register_dialect('custom', delimiter='\n', quoting=csv.QUOTE_NONE, escapechar='\\')
    writer = csv.writer(csv_file, 'custom')
    row = Output
    writer.writerow(row)

Currently the code is producing this in the csv file = class": "businessCapsule-- (scraped text)

I would like to only print the scraped text into the CSV file (without the tags)

Please help.

Body:
After:

Output = soup.find_all("span", {"class": "businessCapsule--name"})

add:

Output = [row.text for row in Output]

in order to extract text from SPAN fields.


问:
How to Replace a PHP File With an Existing PHP File
So currently I have two PHP files, they are identical. There is a function that updates the current file being used to add data and also a clear function. I want the clear function on the first file to replace itself with the content of the second. </p>

答:
You can use __FILE__ to get the pathname of the current file, and overwrite this with the second file.

```<code>copy("/path/to/second/file.php", __FILE__);
</code>```

Body:
You can use __FILE__ to get the pathname of the current file, and overwrite this with the second file.

copy("/path/to/second/file.php", __FILE__);


答:
from selenium import webdriver

from bs4 import BeautifulSoup`

import csv

chrome_path = r"C:\Users\chromedriver_win32\chromedriver.exe"

driver = webdriver.Chrome(chrome_path)

driver.get('http://www.yell.com')

search = driver.find_element_by_id("search_keyword")

search.send_keys("plumbers")

place = driver.find_element_by_id("search_location")

place.send_keys("London")

driver.find_element_by_xpath("""//*[@id="searchBoxForm"]/fieldset/div[1]/div[3]/button""").click()

soup = BeautifulSoup(driver.page_source, 'html.parser')

Output = []
for names in soup.find_all("span", {"class": "businessCapsule--name"}):
    Output.append(names.text)

with open('comple16.csv', 'w') as csv_file:
    csv.register_dialect('custom', delimiter='\n', quoting=csv.QUOTE_NONE, escapechar='\\')
    writer = csv.writer(csv_file, 'custom')
    row = Output
    writer.writerow(row)
```

Title: Write cleaned BS4 data to csv file


问:
Validate SSL certificates with Python
I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc.  We use our own internal corporate Certificate Authority for these sites, so we have the public key of the CA to verify the certificates against.

Python by default just accepts and uses SSL certificates when using HTTPS, so even if a certificate is invalid, Python libraries such as urllib2 and Twisted will just happily use the certificate.

How do I verify a certificate in Python?

答:
Jython DOES carry out certificate verification by default, so using standard library modules, e.g. httplib.HTTPSConnection, etc, with jython will verify certificates and give exceptions for failures, i.e. mismatched identities, expired certs, etc.

In fact, you have to do some extra work to get jython to behave like cpython, i.e. to get jython to NOT verify certs.

I have written a blog post on how to disable certificate checking on jython, because it can be useful in testing phases, etc.

Installing an all-trusting security provider on java and jython.

http://jython.xhaus.com/installing-an-all-trusting-security-provider-on-java-and-jython/

Title: Validate SSL certificates with Python


问:
How to return matches and non matches when comparing two ranges/arrays
I'm attempting to return a count of the total number of matching and non-matching entries in a set of two ranges.

I'm trying to avoid looping over the array twice like this:

```<code>#expected output:
#inside: 421 | outside: 55

constant_range = 240..960
sample_range   = 540..1015
sample_range_a = sample_range.to_a

def generate_range
  inside = sample_range_a.select { |val| constant_range.include?(val) }.count
  outside = sample_range_a.select { |val| !constant_range.include?(val) }.count
end

# I was thinking of a counter, but thought that would be even more ineffective
def generate_range
  a = 0
  b = 0
  sample_range_a.select { |val| constant_range.include?(val) ? a++ : b++ }
end
</code>```

答:
You can use - (difference) in Ruby:

constant_range = (240..960).to_a
sample_range   = (540..1015).to_a

puts (sample_range - constant_range).count # 55
```

Body:
I'm attempting to return a count of the total number of matching and non-matching entries in a set of two ranges.

I'm trying to avoid looping over the array twice like this:

#expected output:
#inside: 421 | outside: 55

constant_range = 240..960
sample_range   = 540..1015
sample_range_a = sample_range.to_a

def generate_range
  inside = sample_range_a.select { |val| constant_range.include?(val) }.count
  outside = sample_range_a.select { |val| !constant_range.include?(val) }.count
end

# I was thinking of a counter, but thought that would be even more ineffective
def generate_range
  a = 0
  b = 0
  sample_range_a.select { |val| constant_range.include?(val) ? a++ : b++ }
end


问:
Pythonic way of looping through a list/dict of regex patterns and extracting string
As someone who has written everything in R for years, I'm still unsure if I'm handling iteration/list comprehensions the best way in python. As an example, let's say I have the string:

```<code>string = "Imported as of 1 Jan 2020"
</code>```

And I want to build a date object from the string, where my patterns are stored to a named list in R, or dict in python as follows:

```<code>dates_r =  list(
    day = '[0-9]{1,2}(?=\\s+)',
    month = '(\\w+)(?=(\\s)[0-9]{4})',
    year = '[0-9]{4}$'
)

dates_py = {
    'day':r'[0-9]{1,2}(?=\s+)',
    'month':r'(\w+)(?=(\s)[0-9]{4})',
    'year':r'[0-9]{4}$'
}
</code>```

In R I can simply:

```<code>> dates_out_r <- mapply(stringi::stri_extract_all_regex, pattern = dates_r, str = string, simplify = F)
> dates_out_r
$day
[1] "1"

$month
[1] "Jan"

$year
[1] "2020"
</code>```

Is there a better way than what I am currently doing in python?

```<code>dates_py = {
    'day': r'[0-9]{1,2}(?=\s+)',
    'month': r'(\w+)(?=(\s)[0-9]{4})',
    'year': r'[0-9]{4}$'
}

dates_out = {}

for key, value in dates_py.items():
    rgx = re.compile(value)
    dates_out[key] = re.search(rgx, date_str)[0]
dates_out
{'day': '1', 'month': 'February', 'year': '2020'}
</code>```

答:
u can use dict comprehension

its essetially the same as for loop, but shorter

```<code>d = {k: re.search(regex, string)[0] for k, regex in dates_py.items()}
</code>```

there is also kind of equivalent of mapply, but looks pretty ugly (at least in my implementation)

```<code>dict(map(lambda k, regex: (k, re.search(regex, string)[0]), dates_py.keys(), dates_py.values()))
</code>```

also note, that case re.search(...) is None isnt handled, handling will add event more code, which is not cool for one-liner

Body:
As someone who has written everything in R for years, I'm still unsure if I'm handling iteration/list comprehensions the best way in python. As an example, let's say I have the string:

string = "Imported as of 1 Jan 2020"

And I want to build a date object from the string, where my patterns are stored to a named list in R, or dict in python as follows:

dates_r =  list(
    day = '[0-9]{1,2}(?=\\s+)',
    month = '(\\w+)(?=(\\s)[0-9]{4})',
    year = '[0-9]{4}$'
)

dates_py = {
    'day':r'[0-9]{1,2}(?=\s+)',
    'month':r'(\w+)(?=(\s)[0-9]{4})',
    'year':r'[0-9]{4}$'
}

In R I can simply:

> dates_out_r <- mapply(stringi::stri_extract_all_regex, pattern = dates_r, str = string, simplify = F)
> dates_out_r
$day
[1] "1"

$month
[1] "Jan"

$year
[1] "2020"

Is there a better way than what I am currently doing in python?

dates_py = {
    'day': r'[0-9]{1,2}(?=\s+)',
    'month': r'(\w+)(?=(\s)[0-9]{4})',
    'year': r'[0-9]{4}$'
}

dates_out = {}

for key, value in dates_py.items():
    rgx = re.compile(value)
    dates_out[key] = re.search(rgx, date_str)[0]
dates_out
{'day': '1', 'month': 'February', 'year': '2020'}

Body:
u can use dict comprehension

its essetially the same as for loop, but shorter

d = {k: re.search(regex, string)[0] for k, regex in dates_py.items()}

there is also kind of equivalent of mapply, but looks pretty ugly (at least in my implementation)

dict(map(lambda k, regex: (k, re.search(regex, string)[0]), dates_py.keys(), dates_py.values()))

also note, that case re.search(...) is None isnt handled, handling will add event more code, which is not cool for one-liner


问:
How to angular route for sub modules?
I have a dashboard module in my angular application. And my app.module.ts is like following.

```<code>@NgModule({
  declarations: [
    AppComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    DashboardModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

And app-routing.module.ts is

```<code>const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

And dashboard.route.ts is

```<code>const dashboardRoutes: Routes = [
    { path: 'dashboard', component: DashboardComponent }
]

@NgModule({
    imports: [RouterModule.forChild(dashboardRoutes)],
    exports: [RouterModule]
})
export class DashboardRouteModuel {}
</code>```

But the applciaiton is routing to PageNotFoundComponent always.

答:
Change order of imports AppRoutingModule and DashboardModule like following.</p>

```<code>@NgModule({
  declarations: [
    AppComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule,
    DashboardModule,
    AppRoutingModule,

  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Title: How to angular route for sub modules?

Body:
I have a dashboard module in my angular application. And my app.module.ts is like following.

@NgModule({
  declarations: [
    AppComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    DashboardModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

And app-routing.module.ts is

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

And dashboard.route.ts is

const dashboardRoutes: Routes = [
    { path: 'dashboard', component: DashboardComponent }
]

@NgModule({
    imports: [RouterModule.forChild(dashboardRoutes)],
    exports: [RouterModule]
})
export class DashboardRouteModuel {}

But the applciaiton is routing to PageNotFoundComponent always.

Body:
Change order of imports AppRoutingModule and DashboardModule like following.

@NgModule({
  declarations: [
    AppComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule,
    DashboardModule,
    AppRoutingModule,

  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


问:
Reading and parsing xml file in Spring Project
I want to parse xml file in spring project. Can anyone provide direction for this?

This xml file will be used to load various fields which are required to be validated for each jsf page.

I want to use this xml to be read through document build factory or any generic function present in the spring

```<code>DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
</code>```

I want to validate a page for specific values which are defined in this xml. So I need to parse this xml file as we do in simple java program using DocumentBuilderFactory

答:
The question is much too vague, many different scenarios are possible.

However, I thing you should take a look at the Chapter 14. Marshalling XML using O/X Mappers from the Spring reference. Perhaps you will find the answer there.

Ah, more info in the Question. So the XML contains properties, although it is not in the Java properties XML format.

OK, then I guess I'd write a BeanPostProcessor that uses Commons / Config under the hood to read the properties from XML. You should probably copy what the PropertyPlaceholderConfigurer does, to a certain extent.

Body:
I want to parse xml file in spring project. Can anyone provide direction for this?

This xml file will be used to load various fields which are required to be validated for each jsf page.

I want to use this xml to be read through document build factory or any generic function present in the spring

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);

I want to validate a page for specific values which are defined in this xml. So I need to parse this xml file as we do in simple java program using DocumentBuilderFactory


问:
Left Function Compile Error: Argument not optional (VBA)
I am trying to do a few things with this subroutine.
First i need to insert a row after every 18th row
Then i need to insert a string in column A based on the string in the above row (i.e. 17th row in the first iteration).
Finally i need to insert a string in column B of the ith row again based on the previously established string.

So in Layman's terms, row 17 will say 120F_CASH
i want to find "_ " and take the characters in the string from the left of the "_ ", then in row 18 i want to put 120F & "_MULTI_STRAT" in column A
in column B of row 18, i want to insert "SSELECT PERF.IMST.INDEX WITH ENTITY = " & "120F" & "AND WITH CATEGORY1 = ""01"""

here's my code:

```<code>Option Explicit

Sub InsertRowEveryXrows()
Dim r As Long, lr As Long
Dim code As String

lr = Range("A" & Rows.Count).End(xlUp).Row
    For r = 18 To lr Step 18
        Rows(r).Insert Shift:=xlDown
        Set code = Left(Range(Cells(r - 1, "A"), InStr(1, "_", Cells(r, "A")) - 1))
        Cells(r, "A") = code & "_MULTI_STRAT"
        Cells(r, "B") = "SSELECT PERF.IMST.INDEX WITH ENTITY = " & code & "AND WITH CATEGORY1 = ""01"""
    Next r
End Sub
</code>```

i am getting a compile error: Wrong number of arguments or invalid property assignments on this line:

Set code = Left(Range(Cells(r - 1, "A"), InStr(1, "_", Cells(r, "A"))
  - 1))

the string's location is in row 17 (r-1) in column A & the number of characters is found by looking for "_"

What am i missing?
*fyi i had to add a space after the underscore for it to show up properly here, however, there SHOULD NOT be a space after the underscore.

答:
You could use something like so

```<code>Function Pop_String(strInput As String, strDelim As String, Optional lngInstance = 1)

Dim aTemp() As String

aTemp = Split(strInput, strDelim, lngInstance + 1)

Pop_String = aTemp(lngInstance - 1)

End Function
</code>```

Calling like so

Pop_String("a-b-c-d-e-f","-",4) returns d
Pop_String("a-b-c-d-e-f","-",2) returns b

I would add some error checking too, the default (without 3rd argument) is the first section, so

Pop_String("test-string","-") would return test and
Pop_String("test-string","-",2) would return string.

Body:
I am trying to do a few things with this subroutine.
First i need to insert a row after every 18th row
Then i need to insert a string in column A based on the string in the above row (i.e. 17th row in the first iteration).
Finally i need to insert a string in column B of the ith row again based on the previously established string.

So in Layman's terms, row 17 will say 120F_CASH
i want to find "_ " and take the characters in the string from the left of the "_ ", then in row 18 i want to put 120F & "_MULTI_STRAT" in column A
in column B of row 18, i want to insert "SSELECT PERF.IMST.INDEX WITH ENTITY = " & "120F" & "AND WITH CATEGORY1 = ""01"""

here's my code:

Option Explicit

Sub InsertRowEveryXrows()
Dim r As Long, lr As Long
Dim code As String

lr = Range("A" & Rows.Count).End(xlUp).Row
    For r = 18 To lr Step 18
        Rows(r).Insert Shift:=xlDown
        Set code = Left(Range(Cells(r - 1, "A"), InStr(1, "_", Cells(r, "A")) - 1))
        Cells(r, "A") = code & "_MULTI_STRAT"
        Cells(r, "B") = "SSELECT PERF.IMST.INDEX WITH ENTITY = " & code & "AND WITH CATEGORY1 = ""01"""
    Next r
End Sub

i am getting a compile error: Wrong number of arguments or invalid property assignments on this line:

Set code = Left(Range(Cells(r - 1, "A"), InStr(1, "_", Cells(r, "A"))
  - 1))

the string's location is in row 17 (r-1) in column A & the number of characters is found by looking for "_"

What am i missing?
*fyi i had to add a space after the underscore for it to show up properly here, however, there SHOULD NOT be a space after the underscore.

Body:
You could use something like so

Function Pop_String(strInput As String, strDelim As String, Optional lngInstance = 1)

Dim aTemp() As String

aTemp = Split(strInput, strDelim, lngInstance + 1)

Pop_String = aTemp(lngInstance - 1)

End Function

Calling like so

Pop_String("a-b-c-d-e-f","-",4) returns d
Pop_String("a-b-c-d-e-f","-",2) returns b

I would add some error checking too, the default (without 3rd argument) is the first section, so

Pop_String("test-string","-") would return test and
Pop_String("test-string","-",2) would return string.


问:
Oracle Toad SQL queries leading to inconsistent id counts
I'm using Oracle Toad with SQL commands in the editor window.

I created two new tables (PIDS1 and PIDS2) that contain only one column of ID numbers from two related tables.

I had expected that PIDS2 would contain a superset of the ID's in PIDS1. When I tried to identify the ID's in PIDS2 that are not in PIDS1, I got started on a wild goose chase.

Let's say that it is a given that there is something unexpected going on with the data in my tables. But I cannot make any sense of the two simplified queries described below. The numbers are inconsistent. Can someone explain what is going on?

```<code>-- PIDS1 IS A SINGLE-COLUMN TABLE THAT CONTAINS 1638061 DISTINCT ID'S
-- PIDS2 IS A SINGLE-COLUMN TABLE THAT CONTAINS 3510272 DISTINCT ID'S

SELECT COUNT(T2.ID)
    FROM PIDS2 T2
    WHERE T2.ID NOT IN (
        SELECT T1.ID
        FROM PIDS1 T1);

-- RESULT IS ZERO!
-- WTF? PIDS2 HAS MORE ID'S THAN PIDS1!

SELECT COUNT(T1.ID)
    FROM PIDS1 T1
    WHERE T1.ID NOT IN (
        SELECT T2.ID
        FROM PIDS2 T2);

-- RESULT IS 786690
-- WHERE DID THAT NUMBER COME FROM? LOOKS ARBITRARY
</code>```

答:
Never use NOT IN with a subquery.  If any of the values returned by the subquery are NULL, then all rows are filtered out.

For this reason, I always advise NOT EXISTS:

```<code>SELECT T2.ID
FROM PIDS2 T2
WHERE NOT EXISTS (SELECT 1 FROM PIDS1 T1 WHERE t1.ID = T2.ID);
</code>```

Of course, you can also add WHERE t1.ID IS NOT NULL to the NOT IN version.  In my experience, you'll forget it at some inopportune time in the future.  Just use NOT EXISTS.

Body:
I'm using Oracle Toad with SQL commands in the editor window.

I created two new tables (PIDS1 and PIDS2) that contain only one column of ID numbers from two related tables.

I had expected that PIDS2 would contain a superset of the ID's in PIDS1. When I tried to identify the ID's in PIDS2 that are not in PIDS1, I got started on a wild goose chase.

Let's say that it is a given that there is something unexpected going on with the data in my tables. But I cannot make any sense of the two simplified queries described below. The numbers are inconsistent. Can someone explain what is going on?

-- PIDS1 IS A SINGLE-COLUMN TABLE THAT CONTAINS 1638061 DISTINCT ID'S
-- PIDS2 IS A SINGLE-COLUMN TABLE THAT CONTAINS 3510272 DISTINCT ID'S

SELECT COUNT(T2.ID)
    FROM PIDS2 T2
    WHERE T2.ID NOT IN (
        SELECT T1.ID
        FROM PIDS1 T1);

-- RESULT IS ZERO!
-- WTF? PIDS2 HAS MORE ID'S THAN PIDS1!

SELECT COUNT(T1.ID)
    FROM PIDS1 T1
    WHERE T1.ID NOT IN (
        SELECT T2.ID
        FROM PIDS2 T2);

-- RESULT IS 786690
-- WHERE DID THAT NUMBER COME FROM? LOOKS ARBITRARY

Body:
Never use NOT IN with a subquery.  If any of the values returned by the subquery are NULL, then all rows are filtered out.

For this reason, I always advise NOT EXISTS:

SELECT T2.ID
FROM PIDS2 T2
WHERE NOT EXISTS (SELECT 1 FROM PIDS1 T1 WHERE t1.ID = T2.ID);

Of course, you can also add WHERE t1.ID IS NOT NULL to the NOT IN version.  In my experience, you'll forget it at some inopportune time in the future.  Just use NOT EXISTS.


问:
Three.js, unexpected position shift when scaling object
I'm trying to create a zoom box, so far I managed to translate the cursor positions from locale to world coordinates and create a box object around the cursor with the right uvs.

Here is the fiddle of my attempt :  https://jsfiddle.net/2ynfedvk/2/

Without scaling the box is perfectly centered around the cursor, but if you toggle the scaling checkbox to set the scale zoomMesh.scale.set(1.5, 1.5, 1), the box position shift the further you move the cursor from the scene center.

Am I messing any CSS like "transform origin" for three.js to center the scale around the object, is this the right approach the get this kind of zoom effect ?

I'm new to three.js and 3d in general, so thanks for any help.

答:
When you scale your mesh with 1.5, it means that apply transform matrix that scales values of vertices.

The issue comes from changing of vertices. Vertices are in local space of the mesh. And when you set the left-top vertex of the square, for example, to [10, 10, 0] and then apply .scale.set(1.5, 1.5, 1) to the mesh, then the coordinate of vertex became [15, 15, 0]. The same to all the other 3 vertices. And that's why the center of the square does not match at 1.5 times from the center of the picture to mouse pointer.

So, an option is not to scale a mesh, but change the size of the square.

I changed your fiddle a bit, so maybe it will be more explanatory:

const
  [width, height] = [500, 300],
  canvas = document.querySelector('canvas'),
  scaleCheckBox = document.querySelector('input')
;

console.log(scaleCheckBox)

canvas.width = width;
canvas.height = height;

const
  scene = new THREE.Scene(),
  renderer = new THREE.WebGLRenderer({canvas}),
  camDistance = 5,
  camFov = (2 * Math.atan( height / ( 2 * camDistance ) ) * ( 180 / Math.PI )),
  camera = new THREE.PerspectiveCamera(camFov, width/height, 0.1, 1000 )
;

camera.position.z = camDistance;

const
  texture = new THREE.TextureLoader().load( "https://picsum.photos/500/300" ),
  imageMaterial = new THREE.MeshBasicMaterial( { map: texture , side : 0 } )
;

texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.format = THREE.RGBFormat;

const
  planeGeometry = new THREE.PlaneGeometry( width, height ),
  planeMesh = new THREE.Mesh( planeGeometry, imageMaterial )
;

const
  zoomGeometry = new THREE.BufferGeometry(),
  zoomMaterial = new THREE.MeshBasicMaterial( { map: texture , side : 0 } ),
  zoomMesh = new THREE.Mesh( zoomGeometry, zoomMaterial )
;

zoomMaterial.color.set(0xff0000);

zoomGeometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array([
  0, 0, 0,
  0, 0, 0,
  0, 0, 0,
  0, 0, 0
]), 3));

zoomGeometry.setIndex([
  0, 1, 2,
  2, 1, 3
]);

scene.add( planeMesh );
scene.add( zoomMesh );

var zoom = 1.;

function setZoomBox(e){

  const
    size = 50 * zoom,
    x = e.clientX - (size/2),
    y = -(e.clientY - height) - (size/2),
    coords = [
      x,
      y,
      x + size,
      y + size
    ]
  ;

  const [x1, y1, x2, y2] = [
    coords[0] - (width/2),
    coords[1] - (height/2),
    coords[2] - (width/2),
    coords[3] - (height/2)
  ];

  zoomGeometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array([
    x1, y1, 0,
    x2, y1, 0,
    x1, y2, 0,
    x2, y2, 0
  ]), 3));

  const [u1, v1, u2, v2] = [
    coords[0]/width,
    coords[1]/height,
    coords[2]/width,
    coords[3]/height
  ]

  zoomGeometry.setAttribute('uv',
  new THREE.BufferAttribute(new Float32Array([
    u1, v1,
    u2, v1,
    u1, v2,

    u2, v2,
    u1, v1,
    u1, v2
  ]), 2));

}

function setScale(e){
  //zoomMesh.scale.set(...(scaleCheckBox.checked ? [1.5, 1.5, 1] : [1, 1, 1]));
  zoom = scaleCheckBox.checked ? 1.5 : 1 ;

}

function render(){

  renderer.render(scene, camera);

  requestAnimationFrame(render);
}

render();

canvas.addEventListener('mousemove', setZoomBox);
scaleCheckBox.addEventListener('change', setScale);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
    margin: 0;
    height: 100%;
}

body{
    background: #333;
    color: #FFF;
    font: bold 16px arial;
}

canvas{

}</code>```

<canvas></canvas>

Toggle scale <input type="checkbox" />
```

Body:
When you scale your mesh with 1.5, it means that apply transform matrix that scales values of vertices.

The issue comes from changing of vertices. Vertices are in local space of the mesh. And when you set the left-top vertex of the square, for example, to [10, 10, 0] and then apply .scale.set(1.5, 1.5, 1) to the mesh, then the coordinate of vertex became [15, 15, 0]. The same to all the other 3 vertices. And that's why the center of the square does not match at 1.5 times from the center of the picture to mouse pointer.

So, an option is not to scale a mesh, but change the size of the square.

I changed your fiddle a bit, so maybe it will be more explanatory:

const
  [width, height] = [500, 300],
  canvas = document.querySelector('canvas'),
  scaleCheckBox = document.querySelector('input')
;

console.log(scaleCheckBox)

canvas.width = width;
canvas.height = height;

const
  scene = new THREE.Scene(),
  renderer = new THREE.WebGLRenderer({canvas}),
  camDistance = 5,
  camFov = (2 * Math.atan( height / ( 2 * camDistance ) ) * ( 180 / Math.PI )),
  camera = new THREE.PerspectiveCamera(camFov, width/height, 0.1, 1000 )
;

camera.position.z = camDistance;

const
  texture = new THREE.TextureLoader().load( "https://picsum.photos/500/300" ),
  imageMaterial = new THREE.MeshBasicMaterial( { map: texture , side : 0 } )
;

texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.format = THREE.RGBFormat;

const
  planeGeometry = new THREE.PlaneGeometry( width, height ),
  planeMesh = new THREE.Mesh( planeGeometry, imageMaterial )
;

const
  zoomGeometry = new THREE.BufferGeometry(),
  zoomMaterial = new THREE.MeshBasicMaterial( { map: texture , side : 0 } ),
  zoomMesh = new THREE.Mesh( zoomGeometry, zoomMaterial )
;

zoomMaterial.color.set(0xff0000);

zoomGeometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array([
  0, 0, 0,
  0, 0, 0,
  0, 0, 0,
  0, 0, 0
]), 3));

zoomGeometry.setIndex([
  0, 1, 2,
  2, 1, 3
]);

scene.add( planeMesh );
scene.add( zoomMesh );

var zoom = 1.;

function setZoomBox(e){

  const
    size = 50 * zoom,
    x = e.clientX - (size/2),
    y = -(e.clientY - height) - (size/2),
    coords = [
      x,
      y,
      x + size,
      y + size
    ]
  ;

  const [x1, y1, x2, y2] = [
    coords[0] - (width/2),
    coords[1] - (height/2),
    coords[2] - (width/2),
    coords[3] - (height/2)
  ];

  zoomGeometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array([
    x1, y1, 0,
    x2, y1, 0,
    x1, y2, 0,
    x2, y2, 0
  ]), 3));

  const [u1, v1, u2, v2] = [
    coords[0]/width,
    coords[1]/height,
    coords[2]/width,
    coords[3]/height
  ]

  zoomGeometry.setAttribute('uv',
  new THREE.BufferAttribute(new Float32Array([
    u1, v1,
    u2, v1,
    u1, v2,

    u2, v2,
    u1, v1,
    u1, v2
  ]), 2));

}

function setScale(e){
  //zoomMesh.scale.set(...(scaleCheckBox.checked ? [1.5, 1.5, 1] : [1, 1, 1]));
  zoom = scaleCheckBox.checked ? 1.5 : 1 ;

}

function render(){

  renderer.render(scene, camera);

  requestAnimationFrame(render);
}

render();

canvas.addEventListener('mousemove', setZoomBox);
scaleCheckBox.addEventListener('change', setScale);

html, body {
    margin: 0;
    height: 100%;
}

body{
    background: #333;
    color: #FFF;
    font: bold 16px arial;
}

canvas{

}

<script src="https://threejs.org/build/three.min.js"></script>

<canvas></canvas>
<div>Toggle scale <input type="checkbox" /></div>


问:
Use Old .net dll inside Modern .net application
I have a .net dll file called PcapNet.dll this file is a wrapper around C++ WanPacket.dll library.

But PcapNet.dll built with .net3.5,
every time I reference it in modern .net application eg, .net 4.7

Shows me this message:

System.IO.FileLoadException: 'Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.'

Then I added

```<code><supportedRuntime version="v2.0" sku=".NETFramework,Version=v2.0"/>
</code>```

to App.config.

And This shows me the next message:

System.IO.FileLoadException: 'Could not load file or assembly 'PcapNet.dll' or one of its dependencies. A dynamic link library (DLL) initialization routine failed. (Exception from HRESULT: 0x8007045A)'

Then I Changed TargetFrameWork to 3.5. And Now Everything worked correctly. And I Can use it.

But this is a big problem I can not stick with .net 3.5 I need 4.7 because I will use it in wpf application.

So how can i use this legacy library 3.5 with modern .net 4.7.

Notice: I do not have the source code of this library, I can only access the dll.

答:
Using

<startup useLegacyV2RuntimeActivationPolicy="true">
```

Solved The Problem.

Body:
I have a .net dll file called PcapNet.dll this file is a wrapper around C++ WanPacket.dll library.

But PcapNet.dll built with .net3.5,
every time I reference it in modern .net application eg, .net 4.7

Shows me this message:

System.IO.FileLoadException: 'Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.'

Then I added

<supportedRuntime version="v2.0" sku=".NETFramework,Version=v2.0"/>

to App.config.

And This shows me the next message:

System.IO.FileLoadException: 'Could not load file or assembly 'PcapNet.dll' or one of its dependencies. A dynamic link library (DLL) initialization routine failed. (Exception from HRESULT: 0x8007045A)'

Then I Changed TargetFrameWork to 3.5. And Now Everything worked correctly. And I Can use it.

But this is a big problem I can not stick with .net 3.5 I need 4.7 because I will use it in wpf application.

So how can i use this legacy library 3.5 with modern .net 4.7.

Notice: I do not have the source code of this library, I can only access the dll.

Body:
Using

<startup useLegacyV2RuntimeActivationPolicy="true">

Solved The Problem.


问:
PHP performance and redundancy
I have a section in my site where I do need to count the number of comments for a specific post.I actually already built a function for retrieving all the data in the comments DB table (function getComments).

the comments DB table structure is : id(PK) | authorId | datetime | postId | text

Now, since I just need to count them (the comments),I was wondering if,in term of server resources/redundancy is better to use :

```<code>$comments=new Comment();
$comments->getComments();
echo count($comments);
</code>```

Or I'm better build another function (apart from 'getComments')like :

```<code>function countComments($postid)
{
  //count comments per post
}
</code>```

thanks

Luca

答: I always would prefer to use a separate function which uses MySQL to count the posts. Because if you just need the count you would not have to request the whole rowset, which increases performance and saves resources.</p>

Title: PHP performance and redundancy

Body:
I have a section in my site where I do need to count the number of comments for a specific post.I actually already built a function for retrieving all the data in the comments DB table (function getComments).

the comments DB table structure is : id(PK) | authorId | datetime | postId | text

Now, since I just need to count them (the comments),I was wondering if,in term of server resources/redundancy is better to use :

$comments=new Comment();
$comments->getComments();
echo count($comments);

Or I'm better build another function (apart from 'getComments')like :

function countComments($postid)
{
  //count comments per post
}

thanks

Luca


问:
Relocation of option and answer key
I want to prepare questions for my students. There are questions in the school's database. The table is as follows:

```<code>| id | qcontent                                                                     | o1  | o2   | o3  |
|----|------------------------------------------------------------------------------|-----|------|-----|
| 1  | Lorem Ipsum is simply dummy text of the printing and typesetting industry.   | ab  | ba   | ce  |
| 2  | Lorem Ipsum has been the industry's standard dummy text ever since the 1500s | ce  | sas  | de  |
| 3  | Contrary to popular belief, Lorem Ipsum is not simply random text.           | ase | sded | def |
</code>```

The correct answers are the o1 option.

```<code><?php

foreach($employee as $element) {

    echo $element->id . ". question: " .$element->qcontent . "<br>";
    echo "A) " .$element->o1. "<br>";
    echo "B) " .$element->o2. "<br>";
    echo "C) " .$element->o3. "<br>";
    echo "D) " .$element->o4. "<br>";
    echo "E) " .$element->o5. "<br>";

}

echo "<hr>";
echo "Answers:";

foreach($employee as $element) {

    echo $element->id. " - " .$element->o1. "<br>";

}
</code>```

When I print the questions, all the right answers are option-A.
How can we generate the location of the questions and the answer key?

答:
I would put the answers into an array and shuffle it. Then I would store the correct answer in an answer_key for output at the end.</p>

```<code><?php

foreach($employee as $element) {
    echo $element->id . ". question: " .$element->qcontent . "<br>";

    // put answers in an array
    $answers[0] = $element->01;
    $answers[1] = $element->02;
    $answers[2] = $element->03;
    $answers[3] = $element->04;
    $answers[4] = $element->05;

    // randomize answers
    shuffle($answers);
    echo "A) " .$answers[0]. "<br>";
    echo "B) " .$answers[1]. "<br>";
    echo "C) " .$answers[2]. "<br>";
    echo "D) " .$answers[3]. "<br>";
    echo "E) " .$answers[4]. "<br>";

   // add answer to answer key
   $answer_key[$element->id] = array_slice(array('A', 'B', 'C', 'D', 'E'), array_search($element->01, $answers), 1);
}

echo "<hr>";
echo "Answers:";

foreach($employee as $element) {

    // Output the correct answers
    echo $element->id. " - " .implode(answer_key[$element->id]). "<br>";

}
</code>```

Title: Relocation of option and answer key

Body:
I want to prepare questions for my students. There are questions in the school's database. The table is as follows:

| id | qcontent                                                                     | o1  | o2   | o3  |
|----|------------------------------------------------------------------------------|-----|------|-----|
| 1  | Lorem Ipsum is simply dummy text of the printing and typesetting industry.   | ab  | ba   | ce  |
| 2  | Lorem Ipsum has been the industry's standard dummy text ever since the 1500s | ce  | sas  | de  |
| 3  | Contrary to popular belief, Lorem Ipsum is not simply random text.           | ase | sded | def |

The correct answers are the o1 option.

<?php

foreach($employee as $element) {

    echo $element->id . ". question: " .$element->qcontent . "
";
    echo "A) " .$element->o1. "
";
    echo "B) " .$element->o2. "
";
    echo "C) " .$element->o3. "
";
    echo "D) " .$element->o4. "
";
    echo "E) " .$element->o5. "
";

}

echo "
";
echo "Answers:";

foreach($employee as $element) {

    echo $element->id. " - " .$element->o1. "
";

}

When I print the questions, all the right answers are option-A.
How can we generate the location of the questions and the answer key?

Body:
I would put the answers into an array and shuffle it. Then I would store the correct answer in an answer_key for output at the end.

<?php

foreach($employee as $element) {
    echo $element->id . ". question: " .$element->qcontent . "<br>";

    // put answers in an array
    $answers[0] = $element->01;
    $answers[1] = $element->02;
    $answers[2] = $element->03;
    $answers[3] = $element->04;
    $answers[4] = $element->05;

    // randomize answers
    shuffle($answers);
    echo "A) " .$answers[0]. "<br>";
    echo "B) " .$answers[1]. "<br>";
    echo "C) " .$answers[2]. "<br>";
    echo "D) " .$answers[3]. "<br>";
    echo "E) " .$answers[4]. "<br>";

   // add answer to answer key
   $answer_key[$element->id] = array_slice(array('A', 'B', 'C', 'D', 'E'), array_search($element->01, $answers), 1);
}

echo "<hr>";
echo "Answers:";

foreach($employee as $element) {

    // Output the correct answers
    echo $element->id. " - " .implode(answer_key[$element->id]). "<br>";

}