问:
Why properties of an XMLHttpRequest object are only printable through console.log()?
```<code>var obj = new XMLHttpRequest();
console.log("Object.keys():",Object.keys(obj));
console.log("Object.getOwnPropertyNames():",Object.getOwnPropertyNames(obj))
console.log("Object.entries():",Object.entries(obj))
console.log("JSON.stringify():",JSON.stringify(obj))

console.log("console.log:"); console.log(obj)
</code>```

output:

Object.keys(): []

  Object.getOwnPropertyNames(): []

  Object.entries(): []

  JSON.stringify(): {}

  console.log:

  XMLHttpRequest {onreadystatechange: null, readyState: 0, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}

How can I create such an object in javascript, whose properties are only printed using console.log(obj), but not returned by any of the above functions?

I have already tried to create objects using constructor function, object.create() (with enumerable:false),  Object.assign(), using getters, instatiating from a class, instatiating from an extended class e.t.c

答:
This has to do with the WhatWG console.log specification:

How the implementation prints args is up to the implementation, but implementations should separate the objects by a space or something similar, as that has become a developer expectation.

The spec leaves the output format very vague and it's up to the implementation to decide what to print.

Body:
var obj = new XMLHttpRequest();
console.log("Object.keys():",Object.keys(obj));
console.log("Object.getOwnPropertyNames():",Object.getOwnPropertyNames(obj))
console.log("Object.entries():",Object.entries(obj))
console.log("JSON.stringify():",JSON.stringify(obj))

console.log("console.log:"); console.log(obj)

output:

Object.keys(): []

  Object.getOwnPropertyNames(): []

  Object.entries(): []

  JSON.stringify(): {}

  console.log:

  XMLHttpRequest {onreadystatechange: null, readyState: 0, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}

How can I create such an object in javascript, whose properties are only printed using console.log(obj), but not returned by any of the above functions?

I have already tried to create objects using constructor function, object.create() (with enumerable:false),  Object.assign(), using getters, instatiating from a class, instatiating from an extended class e.t.c


来源: stackexchange

问:
PS - How to save output to file with colors?
How can I save the terminal output to a PDF file with colors?

I use right now this command:

myCommand that output something with colors to terminal | Out-Printer -Name "Microsoft Print to PDF"

It does create the file, but colors are missing. Any ideas? Tips?

I'm using Windows 10, Powershell

答:
I would heavily suggest using a module for doing that, gives you more control over the output most of the times.

http://www.powertheshell.com/modules/

Get the PDFTools Mod.

```<code>Out-PTSPdf -Name "YourFileName" -Path C:\Users\YourUser\Documents
</code>```

Nevertheless, I doubt that PowerShell actually pipes "colored content" with colors, because it is the PowerShell Engine itself "coloring" according to the syntax. Not sure about that tho.

ContentLicense: CC BY-SA 4.0

Body:
I would heavily suggest using a module for doing that, gives you more control over the output most of the times.

http://www.powertheshell.com/modules/

Get the PDFTools Mod.

Out-PTSPdf -Name "YourFileName" -Path C:\Users\YourUser\Documents

Nevertheless, I doubt that PowerShell actually pipes "colored content" with colors, because it is the PowerShell Engine itself "coloring" according to the syntax. Not sure about that tho.


问:
Conda environment from linux to windows
I am working on an image processing / computer vision / deep learning app which requires the use of old versions for some Python packages.
I am new to the world of machine learning and software,it's been 6 months that I made a career change and I am not aware of the best practices when it comes to python projects that work for different platforms (Windows, Linux, MacOS).
So today, I am working on a linux, I did some conda installs and some pip installs and I am exporting my environment to a .yml file. How to make sure that creating a virtual environment on a Windows Machine using conda and my exported .yml file is going to work with no problems ?</p>

答:
You just have to make sure your .yml file doesn't include platform dependent packages by adding the --from-history flag when creating the file. This exports only packages you intentionally installed.

On Windows conda will take care of the virtual environment by installing dependencies for the specified packages in the .yml file that are Windows compatible.

Title: Conda environment from linux to windows


问:
Error in R - Number of columns of result is not a multiple of vector length (arg 1)
I received this error when I tried running this code in R

```<code>const1 = c(1,1,1,1,1)
const2 = c(1,1,1,1,1)
const3 = c(1,1,1,1,1)
const4 = c(1,1,1,1,1)
const5 = c(1,1,1,1,1)
const6 = c(1,1,1,1,1)
const7 = c(35,16,125,25,40,5)
const8 = c(37,17,130,27,43,7)
const9 = c(39,18,136,29,46,8)
const10 = c(42,19,139,30,50,10)
const11 = c(45,20,144,33,52,11)
f.con <- rbind(const1,const2,const3,const4,const5,const6,const7,const8,const9,const10,const11)
</code>```

Warning message:In rbind(const1, const2, const3, const4, const5, const6, const7,

  number of columns of result is not a multiple of vector length (arg 1)

Body:
I received this error when I tried running this code in R

const1 = c(1,1,1,1,1)
const2 = c(1,1,1,1,1)
const3 = c(1,1,1,1,1)
const4 = c(1,1,1,1,1)
const5 = c(1,1,1,1,1)
const6 = c(1,1,1,1,1)
const7 = c(35,16,125,25,40,5)
const8 = c(37,17,130,27,43,7)
const9 = c(39,18,136,29,46,8)
const10 = c(42,19,139,30,50,10)
const11 = c(45,20,144,33,52,11)
f.con <- rbind(const1,const2,const3,const4,const5,const6,const7,const8,const9,const10,const11)

Warning message:In rbind(const1, const2, const3, const4, const5, const6, const7,

  number of columns of result is not a multiple of vector length (arg 1)

Body:
You can get all the vectors in a list and use sapply to extract data from each.

data <- mget(paste0('const', 1:11))
t(sapply(data, `[`, 1:max(lengths(data))))

#        [,1] [,2] [,3] [,4] [,5] [,6]
#const1     1    1    1    1    1   NA
#const2     1    1    1    1    1   NA
#const3     1    1    1    1    1   NA
#const4     1    1    1    1    1   NA
#const5     1    1    1    1    1   NA
#const6     1    1    1    1    1   NA
#const7    35   16  125   25   40    5
#const8    37   17  130   27   43    7
#const9    39   18  136   29   46    8
#const10   42   19  139   30   50   10
#const11   45   20  144   33   52   11


问:
Why does mysql_query() return TRUE with a SELECT statement?
According to the manual of mysql_query() and to everything I know about this function that I used so many times, it can either return a resource or FALSE if the query is a SELECT. Yet it returns TRUE from time to time.

How can this be? It never ever happened before. Is this a bug in PHP 5.3.2? Does anyone know anything about this?

The code is something like:

```<code>if (!$resource = mysql_query($query, $handle)) {
    throw some exception;
}

var_dump($query);
if ($resource === true && strpos($query, 'SELECT') !== false) {
    throw new Exception('mysql_query() returned TRUE for SELECT');
}
</code>```

It's pretty hard to reproduce, too. It happens only from time to time. I also noticed that it's likely this happens at the same time the server interrupts the connection suddenly, in which case it should return FALSE...

答: Let's look at this the other way, When mysql_query() returns FALSE it means that for what ever reason, the attempt to query has failed. Meaning that even before it got to do you're query something went wrong, as such there has been no effect on the database, or that the query was unable to even get to a point where it could see the database.

ContentLicense: CC BY-SA 3.0

Body:
According to the manual of mysql_query() and to everything I know about this function that I used so many times, it can either return a resource or FALSE if the query is a SELECT. Yet it returns TRUE from time to time.

How can this be? It never ever happened before. Is this a bug in PHP 5.3.2? Does anyone know anything about this?

The code is something like:

if (!$resource = mysql_query($query, $handle)) {
    throw some exception;
}

var_dump($query);
if ($resource === true && strpos($query, 'SELECT') !== false) {
    throw new Exception('mysql_query() returned TRUE for SELECT');
}

It's pretty hard to reproduce, too. It happens only from time to time. I also noticed that it's likely this happens at the same time the server interrupts the connection suddenly, in which case it should return FALSE...


问:
How to call swift native function from react native?
I have a swift class, which i am exposing to react-native, inside that i have a function that is also exposed to react-native. Now when react native calls that function it does a lot of this internally, but after some point of time it returns an object.

Now it will call a specific function that will get the object. I cannot change the parameter to that function. But i have another function, to which i want to return to react native. How can i do it.

```<code>  func AckCallback(response:APIResponse) -> Void
  {
    print(response)

  }
</code>```

for this function I cannot change the paremeter, becaused it had been used a lot of places, But I want to return that response from this function to react-native. If anybody know this issue, please let me know.

```<code>  @objc func sendEvent(_ response: APIResponse, callback: (NSObject) -> ())
-> Void {

    callback( [[
      "responseCode" : "Working",
      ]] as NSObject)

  }
</code>```

I just want to know how to use this sendEvent inside the AckCallback, or is there any other way to send that **

response: APIResponse

**

to react-native.

答:
In iOS Project Create 2 Files

```<code>SwiftComponentManager.swift and SwiftComponentManager.m  create these 2 files.
</code>```

SwiftComponentManager.swift ->

```<code>@objc(SwiftComponentManager)
class SwiftComponentManager: NSObject {

@objc func passValueFromReact(_ value : String) {
    debugPrint(" Print Here \(value)")
 }
}
</code>```

In SwiftComponentManager.m

```<code>#import <Foundation/Foundation.h>

#import "React/RCTBridgeModule.h"
@interface RCT_EXTERN_MODULE(SwiftComponentManager, NSObject)

  RCT_EXTERN_METHOD(passValueFromReact:(NSString *)value) //Here exported your swift function for React Native
@end
</code>```

Here start work in React-Native project

Now How will call this Swift function in React Native.

Import your SwiftComponent in React JS file

```<code>const { SwiftComponentManager } = NativeModules
</code>```

Now call your function with value where you want in JS file

```<code>SwiftComponentManager.passValueFromReact("Hello World")
</code>```

Body:
I have a swift class, which i am exposing to react-native, inside that i have a function that is also exposed to react-native. Now when react native calls that function it does a lot of this internally, but after some point of time it returns an object.

Now it will call a specific function that will get the object. I cannot change the parameter to that function. But i have another function, to which i want to return to react native. How can i do it.

  func AckCallback(response:APIResponse) -> Void
  {
    print(response)

  }

for this function I cannot change the paremeter, becaused it had been used a lot of places, But I want to return that response from this function to react-native. If anybody know this issue, please let me know.

  @objc func sendEvent(_ response: APIResponse, callback: (NSObject) -> ())
-> Void {

    callback( [[
      "responseCode" : "Working",
      ]] as NSObject)

  }

I just want to know how to use this sendEvent inside the AckCallback, or is there any other way to send that **

response: APIResponse

**

to react-native.

Body:
In iOS Project Create 2 Files

SwiftComponentManager.swift and SwiftComponentManager.m  create these 2 files.

SwiftComponentManager.swift ->

@objc(SwiftComponentManager)
class SwiftComponentManager: NSObject {

@objc func passValueFromReact(_ value : String) {
    debugPrint(" Print Here \(value)")
 }
}

In SwiftComponentManager.m

#import <Foundation/Foundation.h>

#import "React/RCTBridgeModule.h"
@interface RCT_EXTERN_MODULE(SwiftComponentManager, NSObject)

  RCT_EXTERN_METHOD(passValueFromReact:(NSString *)value) //Here exported your swift function for React Native
@end

Here start work in React-Native project

Now How will call this Swift function in React Native.

Import your SwiftComponent in React JS file

const { SwiftComponentManager } = NativeModules

Now call your function with value where you want in JS file

SwiftComponentManager.passValueFromReact("Hello World")


问:
Objective-C equivalent to Swift's "Any"
Is there any way that an Objective-C method could operate on primitive parameters without knowing their types? For instance,

```<code>-(Any)returnFirst:(Any)first notSecond:(Any)second  {
  return first;
}
</code>```

This could then be used like:

```<code>int a = [self returnFirst:500 notSecond:1000];
char b = [self returnFirst:'a' notSecond:'b'];
</code>```

答:
In Swift 3, the id type in Objective-C now maps to the Any type in Swift, which describes a value of any type, whether a class, enum, struct, or any other Swift type.

Source: https://developer.apple.com/swift/blog/?id=39

Title: Objective-C equivalent to Swift's "Any"

Body:
Is there any way that an Objective-C method could operate on primitive parameters without knowing their types? For instance,

-(Any)returnFirst:(Any)first notSecond:(Any)second  {
  return first;
}

This could then be used like:

int a = [self returnFirst:500 notSecond:1000];
char b = [self returnFirst:'a' notSecond:'b'];


问:
Sorting list with rules with python
I have a list like this

```<code>['File3', 'File007', 'File3a', 'File10', 'File11', 'File1', 'File4', 'File5', 'File9', 'File8', 'File8b1', 'File8b2', 'File8b11', 'File6']
</code>```

When I sort it with sorted() in python. it will become like this:

```<code>['File007', 'File1', 'File10', 'File11', 'File3', 'File3a', 'File4', 'File5', 'File6', 'File8', 'File8b1', 'File8b11', 'File8b2', 'File9']
</code>```

But what I want is:

```<code>['File1', 'File3', 'File3a', 'File4', 'File5', 'File6', 'File007', 'File8', 'File8b1', 'File8b2', 'File8b11', 'File9', 'File10', 'File11']
</code>```

The number sort it must be:
File1, File2, File3, File10

not like:
File1, File10, File2, File3

if it has 0 digit like this File007, it will count as 7

if it has alphabet after number, like File3a, it will sort like this:
File3, File3a, File3b, ...

is there a ways to add this rules in sorting the list?

答:
There is a way to define you own sorting rules, by passing the key keyword argument to the sorted function. Some code that seems to do exactly what you want could look like this:

```<code>import re

def key_fn(f):
    # the f[4:] part just gets the part of each string after 'File'
    groups = re.match(r'(\d*)(\D*)(\d*)', f[4:]).groups()
    def try_parse_int(x):
        # x should be either an empty string or something we can
        # parse into an int
        try:
            return int(x)
        except ValueError:
            return None
    return try_parse_int(groups[0]), groups[1], try_parse_int(groups[2])

files = ['File3','File007','File3a','File10','File11','File1','File4','File5',
    'File9','File8','File8b1','File8b2','File8b11','File6']

sorted_files = sorted(files, key=key_fn)
</code>```

This supports any amount of digits, followed (optionally) by any amount non-digits, followed (optionally) by any amount of digits again.

Title: Sorting list with rules with python

Body:
I have a list like this

['File3', 'File007', 'File3a', 'File10', 'File11', 'File1', 'File4', 'File5', 'File9', 'File8', 'File8b1', 'File8b2', 'File8b11', 'File6']

When I sort it with sorted() in python. it will become like this:

['File007', 'File1', 'File10', 'File11', 'File3', 'File3a', 'File4', 'File5', 'File6', 'File8', 'File8b1', 'File8b11', 'File8b2', 'File9']

But what I want is:

['File1', 'File3', 'File3a', 'File4', 'File5', 'File6', 'File007', 'File8', 'File8b1', 'File8b2', 'File8b11', 'File9', 'File10', 'File11']

The number sort it must be:
File1, File2, File3, File10

not like:
File1, File10, File2, File3

if it has 0 digit like this File007, it will count as 7

if it has alphabet after number, like File3a, it will sort like this:
File3, File3a, File3b, ...

is there a ways to add this rules in sorting the list?

Body:
There is a way to define you own sorting rules, by passing the key keyword argument to the sorted function. Some code that seems to do exactly what you want could look like this:

import re

def key_fn(f):
    # the f[4:] part just gets the part of each string after 'File'
    groups = re.match(r'(\d*)(\D*)(\d*)', f[4:]).groups()
    def try_parse_int(x):
        # x should be either an empty string or something we can
        # parse into an int
        try:
            return int(x)
        except ValueError:
            return None
    return try_parse_int(groups[0]), groups[1], try_parse_int(groups[2])

files = ['File3','File007','File3a','File10','File11','File1','File4','File5',
    'File9','File8','File8b1','File8b2','File8b11','File6']

sorted_files = sorted(files, key=key_fn)

This supports any amount of digits, followed (optionally) by any amount non-digits, followed (optionally) by any amount of digits again.


问:
Why don't use msg in printing instead of msg[pointer -1]?
It is printing correctly but I have confusion that whenever I write just msg, it gives me Your ?@ and whenever I write msg[option-1], it gives me full message of Your name is bilal. I am not understanding the cause of [option-1]. Why it is used and what is it's function?

```<code>#include <stdio.h>
#define MAX_LEN 256

int main(){
  FILE * fp = fopen("file.txt","r");
  int option;
  char word[MAX_LEN];
  static const char * const msg[] = {
    "Name",
    "Date of Birth",
    "ID Card Number",
    "Phone Number",
    "Address",
    "Account",
    "Fixing Year",
    "Amount" };
      for (option = 1; option <= sizeof(msg)/sizeof(char *); ++option)
      printf("%d. Your %s:\n", option, msg[option-1]);
  fclose(fp);
  return 0;
}
</code>```

答:
The conversion specifier %s is designed to output strings. It expects an argument of the type char *.

The array msg is declared like

```<code>static const char * const msg[] = {
//...
</code>```

that is its elements have the type char *. The array itself used in expressions has the type char **. So it may be supplied to the conversion  specifier %s.

The valid range of indices to access elements of the array is [ 0, sizeod( msg ) / sizeof( char * ) ) while in the loop shown below the index variable is changed from [1, sizeof( msg ) / sizeod( char * ) + 1 ).

That is in this loop

```<code>  for (option = 1; option <= sizeof(msg)/sizeof(char *); ++option)
</code>```

indices start fro 1. So to output correctly an element of the array you have to use the expression option - 1 as an index and the expression msg[option-1] has the required type char * that is expected by the conversion specifier of the call of prontf.

```<code>  printf("%d. Your %s:\n", option, msg[option-1]);
</code>```

That is the selected from the array string is outputted.

Body:
It is printing correctly but I have confusion that whenever I write just msg, it gives me Your ?@ and whenever I write msg[option-1], it gives me full message of Your name is bilal. I am not understanding the cause of [option-1]. Why it is used and what is it's function?

#include <stdio.h>
#define MAX_LEN 256

int main(){
  FILE * fp = fopen("file.txt","r");
  int option;
  char word[MAX_LEN];
  static const char * const msg[] = {
    "Name",
    "Date of Birth",
    "ID Card Number",
    "Phone Number",
    "Address",
    "Account",
    "Fixing Year",
    "Amount" };
      for (option = 1; option <= sizeof(msg)/sizeof(char *); ++option)
      printf("%d. Your %s:\n", option, msg[option-1]);
  fclose(fp);
  return 0;
}

Body:
The conversion specifier %s is designed to output strings. It expects an argument of the type char *.

The array msg is declared like

static const char * const msg[] = {
//...

that is its elements have the type char *. The array itself used in expressions has the type char **. So it may be supplied to the conversion  specifier %s.

The valid range of indices to access elements of the array is [ 0, sizeod( msg ) / sizeof( char * ) ) while in the loop shown below the index variable is changed from [1, sizeof( msg ) / sizeod( char * ) + 1 ).

That is in this loop

  for (option = 1; option <= sizeof(msg)/sizeof(char *); ++option)

indices start fro 1. So to output correctly an element of the array you have to use the expression option - 1 as an index and the expression msg[option-1] has the required type char * that is expected by the conversion specifier of the call of prontf.

  printf("%d. Your %s:\n", option, msg[option-1]);

That is the selected from the array string is outputted.


问:
Return a value inside a function after getting value from firebase storage closure Swift
I have a function which downloads data from firebase:

```<code>func downloadData(path: String) -> Data? {
    let data: Data?

    let storage = Storage.storage()
    storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in

    if let error = error {
        print("\(error)")
    } else {
        data = result
        print("finished")
    }

    return data // <-- this is called before closue ends
}
</code>```

but it is not returning the value from storage closure.
I tried using a dispatch group

```<code> func downloadData(path: String) -> Data? {
     ...
     let group = DispatchGroup()
     group.enter()
     storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in
         ...
         ...
         group.leave()
     }

    group.notify(queue: .main) {
        return data // <-- build time error! the function doesn't return a value
    }
}
</code>```

so I tried a different approach: instead of group.notify() I used:

```<code>group.wait()
</code>```

but it didn't work also. the whole app was frozen and nothing happened

and I tried another one:

```<code>let semaphore = DispatchSemaphore(value: 0)

storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in
    ...
    ...
    semaphore.signal()
}

semaphore.wait()

return data // <-- nothing happens... it is not being executed
</code>```

Any ideas on how to figure this out?

UPDATE

I tried using the completion option but it still didn't wait until it is downloded.

this is my outerFunction:

```<code>    var soundData: Data?
    var imageData: Data?
    downloadData(path: soundPath) { sound in
        soundData = sound

        downloadData(path: imageData) { image in
             imageData = image
        }

    }

    doMoreStuff() // <-- called before completeion blocks executed
</code>```

答:
You can't really do that without some kind of completion closure, because you'd be blocking the thread which calls the function, probably the UI thread.

Another alternative would be to use Apple's new Combine framework and return a Future

```<code>import Combine

func downloadData(path: String) -> Future<Data, Error> {
    return Future<Data, Error> { promise in
        let storage = Storage.storage()
        storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in
            if let error = error {
                promise(.failure(error))
            } else {
                promise(.success(result))
            }

        }
    }
}

var bag = Set<AnyCancellable>()

downloadData(path: "test")
    .subscribe(on: DispatchQueue.main)
    .sink(receiveCompletion: { (res) in
        <#code#>
    }) { (data) in
        <#code#>
    }
.store(in: &bag)
</code>```

Body:
I have a function which downloads data from firebase:

func downloadData(path: String) -> Data? {
    let data: Data?

    let storage = Storage.storage()
    storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in

    if let error = error {
        print("\(error)")
    } else {
        data = result
        print("finished")
    }

    return data // <-- this is called before closue ends
}

but it is not returning the value from storage closure.
I tried using a dispatch group

 func downloadData(path: String) -> Data? {
     ...
     let group = DispatchGroup()
     group.enter()
     storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in
         ...
         ...
         group.leave()
     }

    group.notify(queue: .main) {
        return data // <-- build time error! the function doesn't return a value
    }
}

so I tried a different approach: instead of group.notify() I used:

group.wait()

but it didn't work also. the whole app was frozen and nothing happened

and I tried another one:

let semaphore = DispatchSemaphore(value: 0)

storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in
    ...
    ...
    semaphore.signal()
}

semaphore.wait()

return data // <-- nothing happens... it is not being executed

Any ideas on how to figure this out?

UPDATE

I tried using the completion option but it still didn't wait until it is downloded.

this is my outerFunction:

    var soundData: Data?
    var imageData: Data?
    downloadData(path: soundPath) { sound in
        soundData = sound

        downloadData(path: imageData) { image in
             imageData = image
        }

    }

    doMoreStuff() // <-- called before completeion blocks executed

Body:
You can't really do that without some kind of completion closure, because you'd be blocking the thread which calls the function, probably the UI thread.

Another alternative would be to use Apple's new Combine framework and return a Future

import Combine

func downloadData(path: String) -> Future<Data, Error> {
    return Future<Data, Error> { promise in
        let storage = Storage.storage()
        storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in
            if let error = error {
                promise(.failure(error))
            } else {
                promise(.success(result))
            }

        }
    }
}

var bag = Set<AnyCancellable>()

downloadData(path: "test")
    .subscribe(on: DispatchQueue.main)
    .sink(receiveCompletion: { (res) in
        <#code#>
    }) { (data) in
        <#code#>
    }
.store(in: &bag)


问:
Error 403 - Forbidden while trying npm install
So just like every day I do different projects and install additional modules, today I want to install another module and such an error, reinstall the server and still the same .... [Error]
The error appeared overnight

答:
I found the issue from here: https://github.com/npm/npm/issues/2119#issuecomment-5321857

It's a very common issue in npm. Actually npm is not working good with HTTPS over a proxy. Changing the registry URL from HTTPS to HTTP will fix the problem.

Try this out:

```<code>npm config set registry http://registry.npmjs.org
</code>```

Body:
I found the issue from here: https://github.com/npm/npm/issues/2119#issuecomment-5321857

It's a very common issue in npm. Actually npm is not working good with HTTPS over a proxy. Changing the registry URL from HTTPS to HTTP will fix the problem.

Try this out:

npm config set registry http://registry.npmjs.org


问:
How to configure a fine tuned thread pool for futures?
How large is Scala's thread pool for futures?

My Scala application makes many millions of future {}s and I wonder if there is anything I can do to optimize them by configuring a thread pool.

Thank you.

答:
```<code>class ThreadPoolExecutionContext(val executionContext: ExecutionContext)

object ThreadPoolExecutionContext {

  val executionContextProvider: ThreadPoolExecutionContext = {
    try {
      val executionContextExecutor: ExecutionContextExecutor = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(25))
      new ThreadPoolExecutionContext(executionContextExecutor)
    } catch {
      case exception: Exception => {
        Log.error("Failed to create thread pool", exception)
        throw exception
      }
    }
  }
}
</code>```


问:
Filtering out data based effective and Term Data
I have query contains both start and end date, i would like to filter out data based on two dates. I need only 2019 and higher data either based on start or end date, if you can have a look examples. i need ID 1,2,3,6,7 and 4,5 is not required. We can do based on extract year for both start and end date. but looking for better approach Thanks!</p>

```<code>CREATE TABLE TEMP
(
ID INT,
SDate DATE,
EDate DATE
)

INSERT INTO TEMP
SELECT 1,'01/01/2014', '01/01/2019' FROM DUAL
UNION ALL
SELECT 2,'01/01/2015', '01/01/2020' FROM DUAL
UNION ALL
SELECT 3,'01/01/2019', '12/31/2019' FROM DUAL
UNION ALL
SELECT 4,'01/01/2012', '12/31/2018' FROM DUAL
UNION ALL
SELECT 5,'01/01/2010', '10/01/2016' FROM DUAL
 UNION ALL
SELECT 6,'06/01/2020', '10/01/2020' FROM DUAL
UNION ALL
SELECT 7,'01/01/2021', '03/01/2021' FROM DUAL
</code>```

答:
Something like this? Sounds like what you said, but - you didn't post how you do it now. If that's not "it", what "better" approach do you need and why? I mean, what's wrong with this?

```<code>SQL> select *
  2  from temp
  3  where extract(year from sdate) >= 2019
  4     or extract(year from edate) >= 2019;

        ID SDATE      EDATE
---------- ---------- ----------
         1 01/01/2014 01/01/2019
         2 01/01/2015 01/01/2020
         3 01/01/2019 12/31/2019
         6 06/01/2020 10/01/2020
         7 01/01/2021 03/01/2021

SQL>
</code>```

Body:
I have query contains both start and end date, i would like to filter out data based on two dates. I need only 2019 and higher data either based on start or end date, if you can have a look examples. i need ID 1,2,3,6,7 and 4,5 is not required. We can do based on extract year for both start and end date. but looking for better approach Thanks!

CREATE TABLE TEMP
(
ID INT,
SDate DATE,
EDate DATE
)

INSERT INTO TEMP
SELECT 1,'01/01/2014', '01/01/2019' FROM DUAL
UNION ALL
SELECT 2,'01/01/2015', '01/01/2020' FROM DUAL
UNION ALL
SELECT 3,'01/01/2019', '12/31/2019' FROM DUAL
UNION ALL
SELECT 4,'01/01/2012', '12/31/2018' FROM DUAL
UNION ALL
SELECT 5,'01/01/2010', '10/01/2016' FROM DUAL
 UNION ALL
SELECT 6,'06/01/2020', '10/01/2020' FROM DUAL
UNION ALL
SELECT 7,'01/01/2021', '03/01/2021' FROM DUAL

Body:
Something like this? Sounds like what you said, but - you didn't post how you do it now. If that's not "it", what "better" approach do you need and why? I mean, what's wrong with this?

SQL> select *
  2  from temp
  3  where extract(year from sdate) >= 2019
  4     or extract(year from edate) >= 2019;

        ID SDATE      EDATE
---------- ---------- ----------
         1 01/01/2014 01/01/2019
         2 01/01/2015 01/01/2020
         3 01/01/2019 12/31/2019
         6 06/01/2020 10/01/2020
         7 01/01/2021 03/01/2021

SQL>


问:
Boostrap container overflow and not responsive (always displayed two columns)
I have created a form with two columns. But when I decrease the browser width, two columns are preserved even when their content overflows. I have tried to change the code to plain DIV with container class, specify cols count, set width but it resists.

Here is the codepen: https://codesandbox.io/s/stoic-goldberg-4ugt6

and the source code of the parent container:

```<code><div class="container flex-wrap pt-3 w-75 ml-auto mr-auto mt-auto mb-5">
  <div class="row">
    <div class="col">
      <b-card>
        <SeriesForm />
      </b-card>
    </div>
    <div class="col">
      <b-card :header="captions[1]">
        <SeriesForm :group="forms[1]" />
      </b-card>
    </div>
  </div>
  <div class="row">
    <div class="col text-center p-4">
      <b-button>Analyse</b-button>
    </div>
  </div>
</div>
</code>```

How can I make it two columns when there is enough space and single column otherwise?

答:
The issue isn't with the bootstrap grid itself, the issue is with how your checkboxes are displayed.

You're defining in the .align-nicely class, that your checkbox group must always be 3 columns.
display: grid isn't that smart. So if you tell it to be 3 columns, it will be 3 columns and ignore everything else. This is why your content is overflowing.

So to fix the issue or improve it at least. You have to change how the display: grid columns are handled.

One method would be to use CSS @media queries, to define how many columns there should be at a given screen width. This way you can scale them down as the screen gets smaller.

The below CSS should work if you use  with your current text.

.align-nicely {
  display: grid;
  grid-column-gap: 10px;
  grid-row-gap: 10px;
  grid-template-columns: 1fr 1fr 1fr;
}

@media screen and (max-width: 1350px) {
  .align-nicely {
    grid-template-columns: 1fr 1fr;
  }
}

@media screen and (max-width: 576px) {
  .align-nicely {
    grid-template-columns: 1fr;
  }
}
```

<p>Another solution could be to use the <code>repeat()</code> function combined with <code>minmax()</code>.
This option will be a lot more dynamic than the first one, but will break the alignment across your different groups.</p>

<pre class="lang-css prettyprint-override"><code>.align-nicely {
  display: grid;
  grid-column-gap: 10px;
  grid-row-gap: 10px;
  /*
    The 110px inside minmax(), is how small each column is allowed to get.
    So if there isn't space on the current row for the column to be over 110px,
    it will be moved to a new row. So you will need to adjust this based on your content size.
  */
  grid-template-columns: repeat(auto-fit, minmax(110px, 1fr));
}
</code>```

Body:
I have created a form with two columns. But when I decrease the browser width, two columns are preserved even when their content overflows. I have tried to change the code to plain DIV with container class, specify cols count, set width but it resists.

Here is the codepen: https://codesandbox.io/s/stoic-goldberg-4ugt6

and the source code of the parent container:

        <SeriesForm />

        <SeriesForm :group="forms[1]" />

      Analyse

How can I make it two columns when there is enough space and single column otherwise?

Body:
The issue isn't with the bootstrap grid itself, the issue is with how your checkboxes are displayed.

You're defining in the .align-nicely class, that your checkbox group must always be 3 columns.
display: grid isn't that smart. So if you tell it to be 3 columns, it will be 3 columns and ignore everything else. This is why your content is overflowing.

So to fix the issue or improve it at least. You have to change how the display: grid columns are handled.

One method would be to use CSS @media queries, to define how many columns there should be at a given screen width. This way you can scale them down as the screen gets smaller.

The below CSS should work if you use <b-col xl='6'> with your current text.

.align-nicely {
  display: grid;
  grid-column-gap: 10px;
  grid-row-gap: 10px;
  grid-template-columns: 1fr 1fr 1fr;
}

@media screen and (max-width: 1350px) {
  .align-nicely {
    grid-template-columns: 1fr 1fr;
  }
}

@media screen and (max-width: 576px) {
  .align-nicely {
    grid-template-columns: 1fr;
  }
}

Another solution could be to use the repeat() function combined with minmax().
This option will be a lot more dynamic than the first one, but will break the alignment across your different groups.

.align-nicely {
  display: grid;
  grid-column-gap: 10px;
  grid-row-gap: 10px;
  /*
    The 110px inside minmax(), is how small each column is allowed to get.
    So if there isn't space on the current row for the column to be over 110px,
    it will be moved to a new row. So you will need to adjust this based on your content size.
  */
  grid-template-columns: repeat(auto-fit, minmax(110px, 1fr));
}


问:
How to insert an element at the last position in an array dynamically in C?
I'm a newbie in C and trying to insert a number at the last position in C such that, the size of the array is changed over time.

The first array is like this:

```<code>temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
</code>```

Now how can we insert those values in temp that are != 0 to a new array which has a defined length of 5: tmp

Here's what I'm trying:

```<code>void push(int arr[], int value, int current){
  arr[current] = value;
}

int main(void) {

  int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
  int tmp[5];

  for(int i=0;;i++){
    if(temp[i]) push(tmp, temp[i],sizeof(tmp)/sizeof(tmp[0]));
    // I don't put i < 10 int the loop initialization. Since the tmp's length is just 5

  }
  // I put sizeof(tmp)/sizeof(tmp[0]) there because we want at every time the tmp is inserted a new value,
  // it's length will change (increase by 1).
  // So next loop round, the new value will be added to the last position
  // But I failed to do so

}
</code>```

Current output:

```<code>exited segmentation fault
// I'd be very grateful if someone can also explain for me why this error happens
</code>```

Desired output:

```<code>tmp[5] = {1, 2, 5, 6, 8}
</code>```

答:
The problem is that you are accessing outside of the bounds of temp because you don't specify when to stop in the loop.

For a dynamic array, when you don't know the number of elements before hand, you can use realloc:

```<code>#include <stdio.h>
#include <stdlib.h>

void push(int **arr, size_t *size, int value)
{
    int *ptr = realloc(*arr, sizeof(*ptr) * (*size + 1));

    if (ptr == NULL)
    {
        free(*arr);
        perror("push");
        exit(EXIT_FAILURE);
    }
    ptr[*size] = value;
    *size += 1;
    *arr = ptr;
}

int main(void)
{
    int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
    int *arr = NULL;
    size_t size = 0;

    for (size_t i = 0; i < sizeof temp / sizeof temp[0]; i++)
    {
        if (temp[i])
        {
            push(&arr, &size, temp[i]);
        }
    }
    for (size_t i = 0; i < size; i++)
    {
        printf("%d\n", arr[i]);
    }
    free(arr);
}
</code>```

Notice that even if it ilustrates the use of a growable array, this example is considered bad code, a more robust design will take care of the size and is able to manage the allocation and deallocation by itself:

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int *data;
    size_t size;
}  dyn_array;

dyn_array *create_dyn_array(void)
{
    dyn_array *arr = calloc(1, sizeof *arr);

    if (arr == NULL)
    {
        perror("create_dyn_array");
        exit(EXIT_FAILURE);
    }
    return arr;
}

void destroy_dyn_array(dyn_array *arr)
{
    free(arr->data);
    free(arr);
}

void push_dyn_array(dyn_array *arr, int value)
{
    int *ptr = realloc(arr->data, sizeof(*ptr) * (arr->size + 1));

    if (ptr == NULL)
    {
        destroy_dyn_array(arr);
        perror("push_dyn_array");
        exit(EXIT_FAILURE);
    }
    ptr[arr->size++] = value;
    arr->data = ptr;
}

int main(void)
{
    int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
    dyn_array *arr = create_dyn_array();

    for (size_t i = 0; i < sizeof temp / sizeof temp[0]; i++)
    {
        if (temp[i])
        {
            push_dyn_array(arr, temp[i]);
        }
    }
    for (size_t i = 0; i < arr->size; i++)
    {
        printf("%d\n", arr->data[i]);
    }
    destroy_dyn_array(arr);
}
</code>```

This is better, but still not perfect because we are limited to a fixed type (int), with some extra memory we can adapt our code to support any type (using the generic type void *), as an optimization, the dynamic array grows by a factor of 2 instead of calling realloc on each iteration:

```<code>#include <stdio.h>
#include <stdlib.h>

/* Begin - This API is supposed to be in a header */

typedef struct
{
    void **data;
    size_t room;
    size_t size;
}  dynarray;

dynarray *dynarray_create(void)
{
    dynarray *array = calloc(1, sizeof *array);

    if (array == NULL)
    {
        return NULL;
    }
    array->data = malloc(sizeof(void *));
    if (array->data == NULL)
    {
        free(array);
        return NULL;
    }
    array->room = 1;
    return array;
}

void *dynarray_push(dynarray *array, void *data)
{
    if (data == NULL)
    {
        return NULL;
    }
    if (array->size == array->room)
    {
        array->room *= 2;

        void *ptr = realloc(array->data, array->room * sizeof(void *));

        if (ptr == NULL)
        {
            return NULL;
        }
        array->data = ptr;
    }
    array->data[array->size++] = data;
    return data;
}

void *dynarray_get(dynarray *array, size_t index)
{
    return array->data[index];
}

size_t dynarray_size(dynarray *array)
{
    return array->size;
}

void dynarray_destroy(dynarray *array, void (*func)(void *data))
{
    if (func != NULL)
    {
        for (size_t i = 0; i < array->size; i++)
        {
            func(array->data[i]);
        }
    }
    free(array->data);
    free(array);
}

/* End API */

int main(void)
{
    int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
    dynarray *array = dynarray_create();

    if (array == NULL)
    {
        perror("dynarray_create");
        exit(EXIT_FAILURE);
    }
    for (size_t i = 0; i < sizeof temp / sizeof temp[0]; i++)
    {
        if (temp[i])
        {
            if (dynarray_push(array, &temp[i]) == NULL)
            {
                perror("dynarray_push");
                exit(EXIT_FAILURE);
            }
        }
    }

    size_t size = dynarray_size(array);

    for (size_t i = 0; i < size; i++)
    {
        int *data = dynarray_get(array, i);

        printf("%d\n", *data);
    }
    dynarray_destroy(array, NULL);
}
</code>```

Body:
I'm a newbie in C and trying to insert a number at the last position in C such that, the size of the array is changed over time.

The first array is like this:

temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};

Now how can we insert those values in temp that are != 0 to a new array which has a defined length of 5: tmp

Here's what I'm trying:

void push(int arr[], int value, int current){
  arr[current] = value;
}

int main(void) {

  int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
  int tmp[5];

  for(int i=0;;i++){
    if(temp[i]) push(tmp, temp[i],sizeof(tmp)/sizeof(tmp[0]));
    // I don't put i < 10 int the loop initialization. Since the tmp's length is just 5

  }
  // I put sizeof(tmp)/sizeof(tmp[0]) there because we want at every time the tmp is inserted a new value,
  // it's length will change (increase by 1).
  // So next loop round, the new value will be added to the last position
  // But I failed to do so

}

Current output:

exited segmentation fault
// I'd be very grateful if someone can also explain for me why this error happens

Desired output:

tmp[5] = {1, 2, 5, 6, 8}

Body:
The problem is that you are accessing outside of the bounds of temp because you don't specify when to stop in the loop.

For a dynamic array, when you don't know the number of elements before hand, you can use realloc:

#include <stdio.h>
#include <stdlib.h>

void push(int **arr, size_t *size, int value)
{
    int *ptr = realloc(*arr, sizeof(*ptr) * (*size + 1));

    if (ptr == NULL)
    {
        free(*arr);
        perror("push");
        exit(EXIT_FAILURE);
    }
    ptr[*size] = value;
    *size += 1;
    *arr = ptr;
}

int main(void)
{
    int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
    int *arr = NULL;
    size_t size = 0;

    for (size_t i = 0; i < sizeof temp / sizeof temp[0]; i++)
    {
        if (temp[i])
        {
            push(&arr, &size, temp[i]);
        }
    }
    for (size_t i = 0; i < size; i++)
    {
        printf("%d\n", arr[i]);
    }
    free(arr);
}

Notice that even if it ilustrates the use of a growable array, this example is considered bad code, a more robust design will take care of the size and is able to manage the allocation and deallocation by itself:

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int *data;
    size_t size;
}  dyn_array;

dyn_array *create_dyn_array(void)
{
    dyn_array *arr = calloc(1, sizeof *arr);

    if (arr == NULL)
    {
        perror("create_dyn_array");
        exit(EXIT_FAILURE);
    }
    return arr;
}

void destroy_dyn_array(dyn_array *arr)
{
    free(arr->data);
    free(arr);
}

void push_dyn_array(dyn_array *arr, int value)
{
    int *ptr = realloc(arr->data, sizeof(*ptr) * (arr->size + 1));

    if (ptr == NULL)
    {
        destroy_dyn_array(arr);
        perror("push_dyn_array");
        exit(EXIT_FAILURE);
    }
    ptr[arr->size++] = value;
    arr->data = ptr;
}

int main(void)
{
    int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
    dyn_array *arr = create_dyn_array();

    for (size_t i = 0; i < sizeof temp / sizeof temp[0]; i++)
    {
        if (temp[i])
        {
            push_dyn_array(arr, temp[i]);
        }
    }
    for (size_t i = 0; i < arr->size; i++)
    {
        printf("%d\n", arr->data[i]);
    }
    destroy_dyn_array(arr);
}

This is better, but still not perfect because we are limited to a fixed type (int), with some extra memory we can adapt our code to support any type (using the generic type void *), as an optimization, the dynamic array grows by a factor of 2 instead of calling realloc on each iteration:

#include <stdio.h>
#include <stdlib.h>

/* Begin - This API is supposed to be in a header */

typedef struct
{
    void **data;
    size_t room;
    size_t size;
}  dynarray;

dynarray *dynarray_create(void)
{
    dynarray *array = calloc(1, sizeof *array);

    if (array == NULL)
    {
        return NULL;
    }
    array->data = malloc(sizeof(void *));
    if (array->data == NULL)
    {
        free(array);
        return NULL;
    }
    array->room = 1;
    return array;
}

void *dynarray_push(dynarray *array, void *data)
{
    if (data == NULL)
    {
        return NULL;
    }
    if (array->size == array->room)
    {
        array->room *= 2;

        void *ptr = realloc(array->data, array->room * sizeof(void *));

        if (ptr == NULL)
        {
            return NULL;
        }
        array->data = ptr;
    }
    array->data[array->size++] = data;
    return data;
}

void *dynarray_get(dynarray *array, size_t index)
{
    return array->data[index];
}

size_t dynarray_size(dynarray *array)
{
    return array->size;
}

void dynarray_destroy(dynarray *array, void (*func)(void *data))
{
    if (func != NULL)
    {
        for (size_t i = 0; i < array->size; i++)
        {
            func(array->data[i]);
        }
    }
    free(array->data);
    free(array);
}

/* End API */

int main(void)
{
    int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
    dynarray *array = dynarray_create();

    if (array == NULL)
    {
        perror("dynarray_create");
        exit(EXIT_FAILURE);
    }
    for (size_t i = 0; i < sizeof temp / sizeof temp[0]; i++)
    {
        if (temp[i])
        {
            if (dynarray_push(array, &temp[i]) == NULL)
            {
                perror("dynarray_push");
                exit(EXIT_FAILURE);
            }
        }
    }

    size_t size = dynarray_size(array);

    for (size_t i = 0; i < size; i++)
    {
        int *data = dynarray_get(array, i);

        printf("%d\n", *data);
    }
    dynarray_destroy(array, NULL);
}


问:
How to customize the code-block language of Sphinx?
Consider the below situation:

```<code>.. code-block:: my_lang

    ...

</code>```

If I want to make my_lang as some stuff such as Python, how can I do it?

答:
First, you need to create a script (_ext/mylanglexer.py), and then add on the extensions on the conf.py

(_ext is a convention but not a must.)

_ext/mylanglexer.py

# _ext/mylanglexer.py

from pygments.lexers import get_lexer_by_name  # refer LEXERS
from pygments.lexers._mapping import LEXERS
from pygments.lexers.python import PythonLexer

def setup(app):
    # choose one, both ok
    app.add_lexer('my_lang', get_lexer_by_name('py'))
    # app.add_lexer('my_lang', PythonLexer)
```
<p>conf.py</p>
```# conf.py

extensions = [
    ...
    '_ext.mylanglexer',  # types.ModuleType, they are likely the_module = __import__('sphinx.ext.autodoc')
]
```
<p>at some tutorial the tell you better add <code>sys.path.append(os.path.abspath("./_ext"))</code>
then <code>extensions = ['mylanglexer'] </code></p>
<p>Anyway, as long as you know that is a module, all extensions should be able to be <code>import ...</code>, so if your module is not in the default path, of course, you must append.</p>
<p>Now, it's working!</p>
<hr />
<h1>How does it work</h1>
<p>see the pygements.lexers.<strong>init</strong>.py</p>
```# pygements.lexers.__init__.py

def get_lexer_by_name(_alias, **options):
    ...

    # lookup builtin lexers
    for module_name, name, aliases, _, _ in LEXERS.values():  # <-- Be focus on this line.
        if _alias.lower() in aliases:
            return _lexer_cache[name](**options)  # The class object (module_name+key_name), for example: pygments.lexers.python.PythonLexer(**options)
    # continue with lexers from setuptools entrypoints
    for cls in find_plugin_lexers():

        ...
        return cls(**options)

    raise ClassNotFound('no lexer for alias %r found' % _alias)
```
<p>In which LEXERS is some kind of the following stuff.</p>
```# pygments.lexers._mapping.py

LEXERS = {
    # key_name: module_name, name, aliases: Tuple[str], _, _
    ...
    'ObjectiveCLexer': ('pygments.lexers.objective', 'Objective-C', ('objective-c', 'objectivec', 'obj-c', 'objc'), ('*.m', '*.h'), ('text/x-objective-c',)),
    'ObjectiveCppLexer': ('pygments.lexers.objective', 'Objective-C++', ('objective-c++', 'objectivec++', 'obj-c++', 'objc++'), ('*.mm', '*.hh'), ('text/x-objective-c++',)),
    'ObjectiveJLexer': ('pygments.lexers.javascript', 'Objective-J', ('objective-j', 'objectivej', 'obj-j', 'objj'), ('*.j',), ('text/x-objective-j',)),
    'OcamlLexer': ('pygments.lexers.ml', 'OCaml', ('ocaml',), ('*.ml', '*.mli', '*.mll', '*.mly'), ('text/x-ocaml',)),
    'OctaveLexer': ('pygments.lexers.matlab', 'Octave', ('octave',), ('*.m',), ('text/octave',)),
    'JsonLexer': ('pygments.lexers.data', 'JSON', ('json',), ('*.json', 'Pipfile.lock'), ('application/json',)),
    'PythonLexer': ('pygments.lexers.python', 'Python', ('python', 'py', 'sage', 'python3', 'py3'), ('*.py', '*.pyw', '*.jy', '*.sage', '*.sc', 'SConstruct', 'SConscript', '*.bzl', 'BUCK', 'BUILD', 'BUILD.bazel', 'WORKSPACE', '*.tac'), ('text/x-python', 'application/x-python', 'text/x-python3', 'application/x-python3')),
    ...
}
```

There you know, your _alias in the aliases, then will work!

How can I customize my style?

you can copy and do some modify the Lexer, such as ObjectiveCLexer, JsonLexer ...

finally app.add_lexer('my_lang', YourLexer)  that's kind of the problem.

Body:
Consider the below situation:

.. code-block:: my_lang

    ...

If I want to make my_lang as some stuff such as Python, how can I do it?

Body:
First, you need to create a script (_ext/mylanglexer.py), and then add on the extensions on the conf.py

(_ext is a convention but not a must.)

_ext/mylanglexer.py

# _ext/mylanglexer.py

from pygments.lexers import get_lexer_by_name  # refer LEXERS
from pygments.lexers._mapping import LEXERS
from pygments.lexers.python import PythonLexer

def setup(app):
    # choose one, both ok
    app.add_lexer('my_lang', get_lexer_by_name('py'))
    # app.add_lexer('my_lang', PythonLexer)

conf.py

# conf.py

extensions = [
    ...
    '_ext.mylanglexer',  # types.ModuleType, they are likely the_module = __import__('sphinx.ext.autodoc')
]

at some tutorial the tell you better add sys.path.append(os.path.abspath("./_ext"))
then extensions = ['mylanglexer']

Anyway, as long as you know that is a module, all extensions should be able to be import ..., so if your module is not in the default path, of course, you must append.

Now, it's working!

How does it work

see the pygements.lexers.init.py

# pygements.lexers.__init__.py

def get_lexer_by_name(_alias, **options):
    ...

    # lookup builtin lexers
    for module_name, name, aliases, _, _ in LEXERS.values():  # <-- Be focus on this line.
        if _alias.lower() in aliases:
            return _lexer_cache[name](**options)  # The class object (module_name+key_name), for example: pygments.lexers.python.PythonLexer(**options)
    # continue with lexers from setuptools entrypoints
    for cls in find_plugin_lexers():

        ...
        return cls(**options)

    raise ClassNotFound('no lexer for alias %r found' % _alias)

In which LEXERS is some kind of the following stuff.

# pygments.lexers._mapping.py

LEXERS = {
    # key_name: module_name, name, aliases: Tuple[str], _, _
    ...
    'ObjectiveCLexer': ('pygments.lexers.objective', 'Objective-C', ('objective-c', 'objectivec', 'obj-c', 'objc'), ('*.m', '*.h'), ('text/x-objective-c',)),
    'ObjectiveCppLexer': ('pygments.lexers.objective', 'Objective-C++', ('objective-c++', 'objectivec++', 'obj-c++', 'objc++'), ('*.mm', '*.hh'), ('text/x-objective-c++',)),
    'ObjectiveJLexer': ('pygments.lexers.javascript', 'Objective-J', ('objective-j', 'objectivej', 'obj-j', 'objj'), ('*.j',), ('text/x-objective-j',)),
    'OcamlLexer': ('pygments.lexers.ml', 'OCaml', ('ocaml',), ('*.ml', '*.mli', '*.mll', '*.mly'), ('text/x-ocaml',)),
    'OctaveLexer': ('pygments.lexers.matlab', 'Octave', ('octave',), ('*.m',), ('text/octave',)),
    'JsonLexer': ('pygments.lexers.data', 'JSON', ('json',), ('*.json', 'Pipfile.lock'), ('application/json',)),
    'PythonLexer': ('pygments.lexers.python', 'Python', ('python', 'py', 'sage', 'python3', 'py3'), ('*.py', '*.pyw', '*.jy', '*.sage', '*.sc', 'SConstruct', 'SConscript', '*.bzl', 'BUCK', 'BUILD', 'BUILD.bazel', 'WORKSPACE', '*.tac'), ('text/x-python', 'application/x-python', 'text/x-python3', 'application/x-python3')),
    ...
}

There you know, your _alias in the aliases, then will work!

How can I customize my style?

you can copy and do some modify the Lexer, such as ObjectiveCLexer, JsonLexer ...

finally app.add_lexer('my_lang', YourLexer)  that's kind of the problem.


问:
Pretty printing a list in a tabular format
Using Python 2.4, how do I print a list in a nice tabular format?

My list is in the below format.

```<code>mylist=[(('VAL1', 'VAL2', 'VAL3', 'VAL4', 'VAL5', 'VAL6'), AGGREGATE_VALUE)]
</code>```

I have tried pprint, but it does not print the result in a tabular format.

EDIT : I would like to see the output in the below format:

VAL1        VAL2     VAL3    VAL4    VAL5    VAL6        AGGREGATE_VALUE

This table, should account for variable item lengths and still print with proper indentation.

答:
For arbitrary item count and arbitrary line count you can use:

```<code>print "\n".join (map (lambda (x, y): "%s\t%s" % ("\t".join (x), y), mylist) )
</code>```

For example for input

```<code>mylist = [ ( ('VAL11', 'VAL12', 'VAL13', 'VAL14', 'VAL15', 'VAL16'), 'AGGREGATE_VALUE1'),
     ( ('VAL21', 'VAL22', 'VAL23', 'VAL24', 'VAL25', 'VAL26'), 'AGGREGATE_VALUE2'),
     ( ('VAL31', 'VAL32', 'VAL33', 'VAL34', 'VAL35', 'VAL36'), 'AGGREGATE_VALUE3'),]
</code>```

it yields:

```<code>VAL11   VAL12   VAL13   VAL14   VAL15   VAL16   AGGREGATE_VALUE1
VAL21   VAL22   VAL23   VAL24   VAL25   VAL26   AGGREGATE_VALUE2
VAL31   VAL32   VAL33   VAL34   VAL35   VAL36   AGGREGATE_VALUE3
</code>```

Body:
Using Python 2.4, how do I print a list in a nice tabular format?

My list is in the below format.

mylist=[(('VAL1', 'VAL2', 'VAL3', 'VAL4', 'VAL5', 'VAL6'), AGGREGATE_VALUE)]

I have tried pprint, but it does not print the result in a tabular format.

EDIT : I would like to see the output in the below format:

VAL1        VAL2     VAL3    VAL4    VAL5    VAL6        AGGREGATE_VALUE

This table, should account for variable item lengths and still print with proper indentation.

Body:
For arbitrary item count and arbitrary line count you can use:

print "\n".join (map (lambda (x, y): "%s\t%s" % ("\t".join (x), y), mylist) )

For example for input

mylist = [ ( ('VAL11', 'VAL12', 'VAL13', 'VAL14', 'VAL15', 'VAL16'), 'AGGREGATE_VALUE1'),
     ( ('VAL21', 'VAL22', 'VAL23', 'VAL24', 'VAL25', 'VAL26'), 'AGGREGATE_VALUE2'),
     ( ('VAL31', 'VAL32', 'VAL33', 'VAL34', 'VAL35', 'VAL36'), 'AGGREGATE_VALUE3'),]

it yields:

VAL11   VAL12   VAL13   VAL14   VAL15   VAL16   AGGREGATE_VALUE1
VAL21   VAL22   VAL23   VAL24   VAL25   VAL26   AGGREGATE_VALUE2
VAL31   VAL32   VAL33   VAL34   VAL35   VAL36   AGGREGATE_VALUE3


问:
How to include column values as null even when condition is not met?

Write a query to show ALL building names, their metering company name and meter type for all buildings that do not have postpaid meters.

The image 1 is the result that I should get and image 2 is the results that i am getting:

```<code>USE Ultimate_DataBase
GO

SELECT [Bld_Name], [Elec_company_name], [Mtype_Name]
FROM [dbo].[Metering_Company] A
FULL OUTER JOIN [dbo].[Metering_Type] D
ON A.[MType_ID]= D.MType_ID
FULL OUTER JOIN [dbo].[Building_metering] B
ON A.[Elec_ID]= B.[Elec_ID]
FULL OUTER JOIN [dbo].[Building] C
ON C.[Bld_ID]= B.[Bld_ID]
WHERE [Mtype_Name] != 'POSTPAID'
</code>```

答:
```<code>USE Ultimate_DataBase
GO

SELECT [Bld_Name], [Elec_company_name], [Mtype_Name]
FROM [dbo].[Metering_Company] A
LEFT JOIN [dbo].[Metering_Type] D
ON A.[MType_ID]= D.MType_ID
LEFT JOIN [dbo].[Building_metering] B
ON A.[Elec_ID]= B.[Elec_ID]
LEFT JOIN [dbo].[Building] C
ON C.[Bld_ID]= B.[Bld_ID]
</code>```

Use this

Body:
Write a query to show ALL building names, their metering company name and meter type for all buildings that do not have postpaid meters.

The image 1 is the result that I should get and image 2 is the results that i am getting:

USE Ultimate_DataBase
GO

SELECT [Bld_Name], [Elec_company_name], [Mtype_Name]
FROM [dbo].[Metering_Company] A
FULL OUTER JOIN [dbo].[Metering_Type] D
ON A.[MType_ID]= D.MType_ID
FULL OUTER JOIN [dbo].[Building_metering] B
ON A.[Elec_ID]= B.[Elec_ID]
FULL OUTER JOIN [dbo].[Building] C
ON C.[Bld_ID]= B.[Bld_ID]
WHERE [Mtype_Name] != 'POSTPAID'

Body:
USE Ultimate_DataBase
GO

SELECT [Bld_Name], [Elec_company_name], [Mtype_Name]
FROM [dbo].[Metering_Company] A
LEFT JOIN [dbo].[Metering_Type] D
ON A.[MType_ID]= D.MType_ID
LEFT JOIN [dbo].[Building_metering] B
ON A.[Elec_ID]= B.[Elec_ID]
LEFT JOIN [dbo].[Building] C
ON C.[Bld_ID]= B.[Bld_ID]

Use this


问:
How do you implement a re-try-catch?
Try-catch is meant to help in the exception handling. This means somehow that it will help our system to be more robust: try to recover from an unexpected event.

We suspect something might happen when executing and instruction (sending a message), so it gets enclosed in the try. If that something nearly unexpected happens, we can do something: we write the catch. I don't think we called to just log the exception. I thing the catch block is meant to give us the opportunity of recovering from the error.

Now, let's say we recover from the error because we could fix what was wrong. It could be super nice to do a re-try:

```<code>try{ some_instruction(); }
catch (NearlyUnexpectedException e){
   fix_the_problem();
   retry;
}
</code>```

This would quickly fall in the eternal loop, but let's say that the fix_the_problem returns true, then we retry. Given that there is no such thing in Java, how would YOU solve this problem? What would be your best design code for solving this?

This is like a philosophical question, given that I already know what I'm asking for is not directly supported by Java.

答:
Here is my solution similar to some others can wrap a function, but allows you to get the functions return value, if it suceeds.</p>

```<code>    /**
     * Wraps a function with retry logic allowing exceptions to be caught and retires made.
     *
     * @param function the function to retry
     * @param maxRetries maximum number of retires before failing
     * @param delay time to wait between each retry
     * @param allowedExceptionTypes exception types where if caught a retry will be performed
     * @param <V> return type of the function
     * @return the value returned by the function if successful
     * @throws Exception Either an unexpected exception from the function or a {@link RuntimeException} if maxRetries is exceeded
     */
    @SafeVarargs
    public static <V> V runWithRetriesAndDelay(Callable<V> function, int maxRetries, Duration delay, Class<? extends Exception>... allowedExceptionTypes) throws Exception {
        final Set<Class<? extends Exception>> exceptions = new HashSet<>(Arrays.asList(allowedExceptionTypes));
        for(int i = 1; i <= maxRetries; i++) {
            try {
                return function.call();
            } catch (Exception e) {
                if(exceptions.contains(e.getClass())){
                    // An exception of an expected type
                    System.out.println("Attempt [" + i + "/" + maxRetries + "] Caught exception [" + e.getClass() + "]");
                    // Pause for the delay time
                    Thread.sleep(delay.toMillis());
                }else {
                    // An unexpected exception type
                    throw e;
                }
            }
        }
        throw new RuntimeException(maxRetries + " retries exceeded");
    }
</code>```

Title: How do you implement a re-try-catch?

Body:
Try-catch is meant to help in the exception handling. This means somehow that it will help our system to be more robust: try to recover from an unexpected event.

We suspect something might happen when executing and instruction (sending a message), so it gets enclosed in the try. If that something nearly unexpected happens, we can do something: we write the catch. I don't think we called to just log the exception. I thing the catch block is meant to give us the opportunity of recovering from the error.

Now, let's say we recover from the error because we could fix what was wrong. It could be super nice to do a re-try:

try{ some_instruction(); }
catch (NearlyUnexpectedException e){
   fix_the_problem();
   retry;
}

This would quickly fall in the eternal loop, but let's say that the fix_the_problem returns true, then we retry. Given that there is no such thing in Java, how would YOU solve this problem? What would be your best design code for solving this?

This is like a philosophical question, given that I already know what I'm asking for is not directly supported by Java.

Body:
Here is my solution similar to some others can wrap a function, but allows you to get the functions return value, if it suceeds.

    /**
     * Wraps a function with retry logic allowing exceptions to be caught and retires made.
     *
     * @param function the function to retry
     * @param maxRetries maximum number of retires before failing
     * @param delay time to wait between each retry
     * @param allowedExceptionTypes exception types where if caught a retry will be performed
     * @param <V> return type of the function
     * @return the value returned by the function if successful
     * @throws Exception Either an unexpected exception from the function or a {@link RuntimeException} if maxRetries is exceeded
     */
    @SafeVarargs
    public static <V> V runWithRetriesAndDelay(Callable<V> function, int maxRetries, Duration delay, Class<? extends Exception>... allowedExceptionTypes) throws Exception {
        final Set<Class<? extends Exception>> exceptions = new HashSet<>(Arrays.asList(allowedExceptionTypes));
        for(int i = 1; i <= maxRetries; i++) {
            try {
                return function.call();
            } catch (Exception e) {
                if(exceptions.contains(e.getClass())){
                    // An exception of an expected type
                    System.out.println("Attempt [" + i + "/" + maxRetries + "] Caught exception [" + e.getClass() + "]");
                    // Pause for the delay time
                    Thread.sleep(delay.toMillis());
                }else {
                    // An unexpected exception type
                    throw e;
                }
            }
        }
        throw new RuntimeException(maxRetries + " retries exceeded");
    }


问:
Hive Python UDF with argument
I want to make hive Python UDF take constant arguments in addition to data from columns.

How can this be achieved?

In the example below, I wish hive query below be able to take the argument '10000', and my_udf should be able to parse this argument '10000'

```<code># hive>
ADD FILE my_udf.py;
SELECT TRANSFORM(col1, col2, '10000') USING 'python my_udf.py' AS (udf_output) FROM my_table;
</code>```

and

```<code># my_udf.py
import sys
for line_str in sys.stdin:
    line = line_str.strip().split('\t')
    print(line[2])  # udf outputs the constant argument we inputted: 10000
</code>```

答:
```<code># hive>
ADD FILE my_udf.py;
SELECT TRANSFORM(col1, col2, '10000') USING 'python my_udf.py' AS (udf_output) FROM my_table;
</code>```

TRANSFORM(col1, col2, '10000') is correct after all. I had some other syntax issues elsewhere, which caused me think this syntax didn't work.

Title: Hive Python UDF with argument

Body:
I want to make hive Python UDF take constant arguments in addition to data from columns.

How can this be achieved?

In the example below, I wish hive query below be able to take the argument '10000', and my_udf should be able to parse this argument '10000'

# hive>
ADD FILE my_udf.py;
SELECT TRANSFORM(col1, col2, '10000') USING 'python my_udf.py' AS (udf_output) FROM my_table;

and

# my_udf.py
import sys
for line_str in sys.stdin:
    line = line_str.strip().split('\t')
    print(line[2])  # udf outputs the constant argument we inputted: 10000

Body:
# hive>
ADD FILE my_udf.py;
SELECT TRANSFORM(col1, col2, '10000') USING 'python my_udf.py' AS (udf_output) FROM my_table;

TRANSFORM(col1, col2, '10000') is correct after all. I had some other syntax issues elsewhere, which caused me think this syntax didn't work.


问:
Secure cells in a way that I can only add +1 to them
I have a bunch of cells with numbers in them. I want them to secure them in a way that I can only add +1 to them. Now I do this manually (4 becomes 5 etc.etc.).

Assuming Google Spreadsheets doesn't have nifty up/down arrow for a cell increasing/decreasing +1 / -1, I think I'm supposed to use a script.

Something like this

```<code>function increment() {  SpreadsheetApp.getActiveSheet().getRange("F5").setValue(SpreadsheetApp.getActiveSheet().getRange("F5").getValue() + 1);
}
</code>```

But if I'm using this script (creating numerous drawings (grrr) ), I'm supposed to create x of the same functions? Seems a bit dumb.

This gives me errors

```<code>function increment(mycell) {  SpreadsheetApp.getActiveSheet().getRange(mycell).setValue(SpreadsheetApp.getActiveSheet().getRange(mycell).getValue() + 1);
}
</code>```

Usage: increment(F5)

  Error: function increment(F5) not found.

?

答:
The problem about your approach is the recursion

Sheet formulas are by default recalculated, so should you type into a cell a formula that increments the value in another cell by 1 - once the value increases, this will trigger the formula recalculation and request the value to increase again and so on.

So you cannot implement your idea in this way

Workaround

Create a function that increments the value of the current cell

You bind this function e.g. to a button and trigger execution after you click into the desired cell and clicked on the button

Sample function:

```<code>function increment() {
  SpreadsheetApp.getActiveSheet().getCurrentCell().setValue(SpreadsheetApp.getActiveSheet().getCurrentCell().getValue() + 1);
}
</code>```

To create a button:

Go from the Sheets UI on Insert->Drawing

Draw a shape of your choice and click on Save and close

Click on the three vertical dots in the right upper corner of the drawing

Select Assign script

Type in the name of the function (without ())

Click into the cell the value of which you want to increment

Click onto your drawing to run the script - done!

Body:
I have a bunch of cells with numbers in them. I want them to secure them in a way that I can only add +1 to them. Now I do this manually (4 becomes 5 etc.etc.).

Assuming Google Spreadsheets doesn't have nifty up/down arrow for a cell increasing/decreasing +1 / -1, I think I'm supposed to use a script.

Something like this

function increment() {  SpreadsheetApp.getActiveSheet().getRange("F5").setValue(SpreadsheetApp.getActiveSheet().getRange("F5").getValue() + 1);
}

But if I'm using this script (creating numerous drawings (grrr) ), I'm supposed to create x of the same functions? Seems a bit dumb.

This gives me errors

function increment(mycell) {  SpreadsheetApp.getActiveSheet().getRange(mycell).setValue(SpreadsheetApp.getActiveSheet().getRange(mycell).getValue() + 1);
}

Usage: increment(F5)

  Error: function increment(F5) not found.

?

Body:
The problem about your approach is the recursion

Sheet formulas are by default recalculated, so should you type into a cell a formula that increments the value in another cell by 1 - once the value increases, this will trigger the formula recalculation and request the value to increase again and so on.

So you cannot implement your idea in this way

Workaround

Create a function that increments the value of the current cell

You bind this function e.g. to a button and trigger execution after you click into the desired cell and clicked on the button

Sample function:

function increment() {
  SpreadsheetApp.getActiveSheet().getCurrentCell().setValue(SpreadsheetApp.getActiveSheet().getCurrentCell().getValue() + 1);
}

To create a button:

Go from the Sheets UI on Insert->Drawing

Draw a shape of your choice and click on Save and close

Click on the three vertical dots in the right upper corner of the drawing

Select Assign script

Type in the name of the function (without ())

Click into the cell the value of which you want to increment

Click onto your drawing to run the script - done!


问:
Automatic Semicolon Insertion (ASI) for arrow function expression vs normal function expression

const log = function (x)
{
 console.log(x);
}
[1,2,3,4,5].forEach(num=>log(num))```
</div>
</div>
</p>

<p>This throws error:-</p>

```{
  "message": "Uncaught TypeError: Cannot read property 'forEach' of undefined",
  "filename": "https://stacksnippets.net/js",
  "lineno": 16,
  "colno": 13
}
```

<p>Which is because of lack of semi-colon before the array. So it's misinterpreted as:-</p>

```const log = function (x)
{
    console.log(x);
}[1,2,3,4,5].forEach(num=>log(num))
```

<p>But why does the following work:-</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const log = (x)=>{
 console.log(x)
}
[1,2,3,4,5].forEach(num=>log(num))</code>```

I understand that it's also a function expression as well. Is there an exception for arrow function in ASI? Or am I missing something?

答:
The specification says:

When, as the source text is parsed from left to right, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true: [...]

So for ASI to happen, the syntax may be an invalid production without it. And actually it is:

```<code>  () => {}[0] // syntax error
</code>```

So the Semicolon is needed here. Now why is that a Syntax error, while function () { }[0] is not? Well, the member access is defined as

```<code>  MemberExpression:
    MemberExpression [ Expression ]
    PrimaryExpression
    //...

 PrimaryExpression:
   FunctionExpression
   // no arrow function here
</code>```

Why the Syntax is how it is? I don't know.

Body:
const log = function (x)
{
 console.log(x);
}
[1,2,3,4,5].forEach(num=>log(num))

This throws error:-

{
  "message": "Uncaught TypeError: Cannot read property 'forEach' of undefined",
  "filename": "https://stacksnippets.net/js",
  "lineno": 16,
  "colno": 13
}

Which is because of lack of semi-colon before the array. So it's misinterpreted as:-

const log = function (x)
{
    console.log(x);
}[1,2,3,4,5].forEach(num=>log(num))

But why does the following work:-

const log = (x)=>{
 console.log(x)
}
[1,2,3,4,5].forEach(num=>log(num))

I understand that it's also a function expression as well. Is there an exception for arrow function in ASI? Or am I missing something?

Body:
The specification says:

When, as the source text is parsed from left to right, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true: [...]

So for ASI to happen, the syntax may be an invalid production without it. And actually it is:

  () => {}[0] // syntax error

So the Semicolon is needed here. Now why is that a Syntax error, while function () { }[0] is not? Well, the member access is defined as

  MemberExpression:
    MemberExpression [ Expression ]
    PrimaryExpression
    //...

 PrimaryExpression:
   FunctionExpression
   // no arrow function here

Why the Syntax is how it is? I don't know.


问:
multiple belongs_to for a model
I have this model "Comment" which is given by a model "User" for a given "city" and "department".
While creating the schema for table "comments", I put in columns city_id, department_id and user_id which should act as foreign keys to respective ids in tables cities, departments and users.

```<code>class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :city
  belongs_to :department
end
</code>```

Cities and Departments are independent tables which are populated with reference data (which would be used to populate  in the forms.

When I try to access comment.city.name, I get a "undefined method `name' for nil:NilClass".
Table cities is defined with columns -"id", "name" and "symbol".
What is the root cause of this error?
What else do I need to do ? I have tried even by putting has_many :feedbacks in class City and class Department (even though it should not happen because they are independent of comments). I am missing something basic here, it seems.

Thanks,
Ashish

答:
I think you need a has_many to go with every belongs_to. So each of your classes that comments belong_to (User, City, Department) should have</p>

```<code>has_many :comments
</code>```

Title: multiple belongs_to for a model

Body:
I have this model "Comment" which is given by a model "User" for a given "city" and "department".
While creating the schema for table "comments", I put in columns city_id, department_id and user_id which should act as foreign keys to respective ids in tables cities, departments and users.

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :city
  belongs_to :department
end

Cities and Departments are independent tables which are populated with reference data (which would be used to populate  in the forms.

When I try to access comment.city.name, I get a "undefined method `name' for nil:NilClass".
Table cities is defined with columns -"id", "name" and "symbol".
What is the root cause of this error?
What else do I need to do ? I have tried even by putting has_many :feedbacks in class City and class Department (even though it should not happen because they are independent of comments). I am missing something basic here, it seems.

Thanks,
Ashish

Body:
I think you need a has_many to go with every belongs_to. So each of your classes that comments belong_to (User, City, Department) should have

has_many :comments


问:
Fastest way to convert a string into a Float32Array
How can I convert a string containing floats written out (not stored as JSON or something like that) into a Float32Array? I tried this but it doesn't work:

```<code>var str = "2.3 4.3 3.145";
var arr1 = parseFloat(str);
var arr2 = new Float32Array(arr1);
</code>```

答:
You can split, then map to an array of floats

const str = "2.3 4.3 3.145";
const arr1 = str.split(' ').map(parseFloat);
const arr2 = new Float32Array(arr1);

console.log(arr1);
console.log(arr2);```

Body:
How can I convert a string containing floats written out (not stored as JSON or something like that) into a Float32Array? I tried this but it doesn't work:

var str = "2.3 4.3 3.145";
var arr1 = parseFloat(str);
var arr2 = new Float32Array(arr1);


问:
RegEx to match stuff between parentheses
I'm having a tough time getting this to work. I have a string like:

```<code>something/([0-9])/([a-z])
</code>```

And I need regex or a method of getting each match between the parentheses and return an array of matches like:

```<code>[
  [0-9],
  [a-z]
]
</code>```

The regex I'm using is /\((.+)\)/ which does seem to match the right thing if there is only one set of parenthesis.

How can I get an array like above using any RegExp method in JavaScript? I need to return just that array because the returned items in the array will be looped through to create a URL routing scheme.

Body:
I'm having a tough time getting this to work. I have a string like:

something/([0-9])/([a-z])

And I need regex or a method of getting each match between the parentheses and return an array of matches like:

[
  [0-9],
  [a-z]
]

The regex I'm using is /\((.+)\)/ which does seem to match the right thing if there is only one set of parenthesis.

How can I get an array like above using any RegExp method in JavaScript? I need to return just that array because the returned items in the array will be looped through to create a URL routing scheme.

Body:
Use this expression:

/\(([^()]+)\)/g

e.g:

function()
{
    var mts = "something/([0-9])/([a-z])".match(/\(([^()]+)\)/g );
    alert(mts[0]);
    alert(mts[1]);
}


问:
Selecting records based on different conditions on a column
Below is sample records in 2 tables

Person Table

```<code>Per_Id      +     Per_type
--------------------------------------------
000001            SINGULAR
000002            COLLECTIVE
000003            INSTITUTION
000004            INSTITUTION
000005            SINGULAR
</code>```

Person Char Table

```<code>Per_Id      +     Char_Type        +    Char_Val
-------------------------------------------------------------------------------
000002            STAT_TY               SUSPENSION
000002            STAT                  COMPLETE

000003            STAT_TY               SUSPENSION
000003            STAT                  COMPLETE

000004            STAT_TY               CESSATION
000004            STAT                  COMPLETE

000005            STAT_TY               DEATH
000005            STAT                  PENDING
</code>```

Requirement is that I need to select the persons with following conditions

The person that do not have any entry in the Person Char Table (Working fine)

Person that has entry in the char table but the value of char STAT is not COMPLETE (Working fine)

The person of type INSTITUTION that has char with value SUSPENSION

In the above table person IDs returned from the query are

```<code>000001 (No record in char table)
000005 (The value of STAT char is not COMPLETE)
000003 (Institution person and char value is SUSPENSION)
</code>```

Below is the query in which I need help in the clause for selecting records that satisfies point 3.

```<code>SELECT P.PER_ID,
C.CHAR_VAL, C1.CHAR_VAL
FROM PERSON_TBL P
LEFT OUTER JOIN CHAR_TBL C ON C.PER_ID = P.PER_ID AND C.CHAR_TYPE = 'STAT_TY'
LEFT OUTER JOIN CHAR_TBL C1 ON C1.PER_ID = P.PER_ID AND C1.CHAR_TYPE = 'STAT'
WHERE
1=1
AND NVL(C.CHAR_VAL,' ')  NOT IN ('CESSATION','DEATH')
AND NVL(STCS.SRCH_CHAR_VAL,' ')  NOT IN ('COMPLETE')
AND ***need clause for selecting person of type SINGULAR and with char SUSPENSION***
</code>```

答:
How about exists and not exists:

```<code>select p.*
from person_tbl p
where not exists (select 1
                  from person_char pc
                  where pc.per_id = p.per_id
                 ) or
      exists (select 1
              from person_char pc
              where pc.per_id = p.per_id and
                    pc.char_type = 'STAT' and
                    pc.char_value <> 'COMPLETE'
            ) or
      (p.per_type = 'INSTITUTION' and
       exists (select 1
               from person_char pc
               where pc.per_id = p.per_id and
                     pc.char_type = 'STAT_TY' and
                     pc.char_value = 'SUSPENSION'
             )
      );
</code>```

Body:
Below is sample records in 2 tables

Person Table

Per_Id      +     Per_type
--------------------------------------------
000001            SINGULAR
000002            COLLECTIVE
000003            INSTITUTION
000004            INSTITUTION
000005            SINGULAR

Person Char Table

Per_Id      +     Char_Type        +    Char_Val
-------------------------------------------------------------------------------
000002            STAT_TY               SUSPENSION
000002            STAT                  COMPLETE

000003            STAT_TY               SUSPENSION
000003            STAT                  COMPLETE

000004            STAT_TY               CESSATION
000004            STAT                  COMPLETE

000005            STAT_TY               DEATH
000005            STAT                  PENDING

Requirement is that I need to select the persons with following conditions

The person that do not have any entry in the Person Char Table (Working fine)

Person that has entry in the char table but the value of char STAT is not COMPLETE (Working fine)

The person of type INSTITUTION that has char with value SUSPENSION

In the above table person IDs returned from the query are

000001 (No record in char table)
000005 (The value of STAT char is not COMPLETE)
000003 (Institution person and char value is SUSPENSION)

Below is the query in which I need help in the clause for selecting records that satisfies point 3.

SELECT P.PER_ID,
C.CHAR_VAL, C1.CHAR_VAL
FROM PERSON_TBL P
LEFT OUTER JOIN CHAR_TBL C ON C.PER_ID = P.PER_ID AND C.CHAR_TYPE = 'STAT_TY'
LEFT OUTER JOIN CHAR_TBL C1 ON C1.PER_ID = P.PER_ID AND C1.CHAR_TYPE = 'STAT'
WHERE
1=1
AND NVL(C.CHAR_VAL,' ')  NOT IN ('CESSATION','DEATH')
AND NVL(STCS.SRCH_CHAR_VAL,' ')  NOT IN ('COMPLETE')
AND ***need clause for selecting person of type SINGULAR and with char SUSPENSION***

Body:
How about exists and not exists:

select p.*
from person_tbl p
where not exists (select 1
                  from person_char pc
                  where pc.per_id = p.per_id
                 ) or
      exists (select 1
              from person_char pc
              where pc.per_id = p.per_id and
                    pc.char_type = 'STAT' and
                    pc.char_value <> 'COMPLETE'
            ) or
      (p.per_type = 'INSTITUTION' and
       exists (select 1
               from person_char pc
               where pc.per_id = p.per_id and
                     pc.char_type = 'STAT_TY' and
                     pc.char_value = 'SUSPENSION'
             )
      );


问:
Is there a way to run "tsc -watch" and "npm start" at the same time, with a click of a button/ shortcut on VSCode?
I am new to node.js and typescript, and I was wondering whether there is any way to run those two commands at the same time with the click of a button or command on visual studio code.

Thank you

答:
You can execute a command via a click by clicking on the "npm scripts" tab shown on your left hand side (default)

If you want to execute multiple commands in single click you have to use something like concurrently

open you package.json and edit script

```<code>"script" : {
  "my-script": "concurrently \"tsc-watch\" \"npm start\""
}
</code>```

Body:
You can execute a command via a click by clicking on the "npm scripts" tab shown on your left hand side (default)

If you want to execute multiple commands in single click you have to use something like concurrently

open you package.json and edit script

"script" : {
  "my-script": "concurrently \"tsc-watch\" \"npm start\""
}


问:
Add class to a link when clicking it and remove it when clicking elsewhere
Important: I tried many solutions here and none of them worked for me.

I have a dropdown list, I want to add it a CSS class when I hover or click it, and remove it when click somewhere else.

a.linkOnMouseDropDown:hover /*work fine */
{
  background-color: rgb(220, 234, 255) !important;
  color: rgb(21, 96, 143);
  cursor: pointer;
}

a.linkOnMouseDropDown:focus /*not work*/
{
  background-color: rgb(220, 234, 255);
  color: rgb(21, 96, 143);
}

a.linkOnMouseDropDown:not(:focus) /*not work */
{
  background-color: transparent;
  color: white;
}

a.dropDownOption:hover //work fine
{
  background-color: rgb(25, 99, 112) !important;
  cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class=" nav navbar-nav navbar-right">
  <li appDropdown>
    Manage <span class="caret"></span>
    <ul class="dropdown-menu">
      <li>Save Data</li>
      <li>Fetch Data</li>
    </ul>
  </li>
</ul></code>```

Again:
I need the 'Manage' dropdown will be changed when the user is hovering or click it according to :

```<code>   a.linkOnMouseDropDown:hover
</code>```

And remove it when I click somewhere else.

Many thanks!  :)

答:
I solved the problem, its based on my own directive (Angular):

```<code>@Directive({
    selector:'[appDropdown]'
})
export class DropdownDirective {
    @HostBinding('class.open') isOpen = false;
    @HostListener('document:click', ['$event']) toggleOpen(event: Event)
    {
      this.isOpen = this.elRef.nativeElement.contains(event.target) ? !this.isOpen : false;
      this.headerservice.isDropdownOpen.next(this.isOpen); //I added this line!

    }
    constructor(private elRef: ElementRef,
                private headerservice: HeaderService) {}
}
</code>```

And my Service class:

```<code>export class HeaderService{

    isDropdownOpen = new Subject<boolean>();
}
</code>```

I using a flag, but I also must listen to it all the time, so I added the subject in the Service. Now I listen to it in the header component:

```<code>export class headerComponent implements OnInit,OnDestroy{
    collapsed = true;
    linkPressed = "";
    subscription: Subscription;
    dropdownClicked=false;

    constructor(private headerservice: HeaderService){}

    ngOnInit(): void {
      this.subscription = this.headerservice.isDropdownOpen.subscribe(
        (state: boolean) =>{
          this.dropdownClicked = state;
      }
      );

    }
    ngOnDestroy(): void {
      this.subscription.unsubscribe();
    }
}

<ul class=" nav navbar-nav navbar-right ">
            <li class="" appDropdown>
                <a  class="dropdown-toggle linkOnMouseHover" [ngClass]="{customBackground:dropdownClicked}" role="button">Manage <span class="caret"></span></a>
                <ul class="dropdown-menu">
                    <li><a  class="dropDownOption" >Save Data</a></li>
                    <li><a  class="dropDownOption" >Fetch Data</a></li>
                </ul>
            </li>
        </ul>
</code>```

Conclusion: I had to use my directive flag. However, in the header component, there is another approach as Michael D suggested (instead of using the ngClass):

```<code>@ViewChild('manageButton', {static: false}) manageButton: any;
</code>```

And in the subscribe function:

```<code>if(state == true){
       this.manageButton.nativeElement.classList.add('customBackground');
}else{
       this.manageButton.nativeElement.classList.remove('customBackground');
}
</code>```

Body:
Important: I tried many solutions here and none of them worked for me.

I have a dropdown list, I want to add it a CSS class when I hover or click it, and remove it when click somewhere else.

a.linkOnMouseDropDown:hover /*work fine */
{
  background-color: rgb(220, 234, 255) !important;
  color: rgb(21, 96, 143);
  cursor: pointer;
}

a.linkOnMouseDropDown:focus /*not work*/
{
  background-color: rgb(220, 234, 255);
  color: rgb(21, 96, 143);
}

a.linkOnMouseDropDown:not(:focus) /*not work */
{
  background-color: transparent;
  color: white;
}

a.dropDownOption:hover //work fine
{
  background-color: rgb(25, 99, 112) !important;
  cursor: pointer;
}

    Manage

Save Data

Fetch Data

Again:
I need the 'Manage' dropdown will be changed when the user is hovering or click it according to :

   a.linkOnMouseDropDown:hover

And remove it when I click somewhere else.

Many thanks!  :)

Body:
I solved the problem, its based on my own directive (Angular):

@Directive({
    selector:'[appDropdown]'
})
export class DropdownDirective {
    @HostBinding('class.open') isOpen = false;
    @HostListener('document:click', ['$event']) toggleOpen(event: Event)
    {
      this.isOpen = this.elRef.nativeElement.contains(event.target) ? !this.isOpen : false;
      this.headerservice.isDropdownOpen.next(this.isOpen); //I added this line!

    }
    constructor(private elRef: ElementRef,
                private headerservice: HeaderService) {}
}

And my Service class:

export class HeaderService{

    isDropdownOpen = new Subject<boolean>();
}

I using a flag, but I also must listen to it all the time, so I added the subject in the Service. Now I listen to it in the header component:

export class headerComponent implements OnInit,OnDestroy{
    collapsed = true;
    linkPressed = "";
    subscription: Subscription;
    dropdownClicked=false;

    constructor(private headerservice: HeaderService){}

    ngOnInit(): void {
      this.subscription = this.headerservice.isDropdownOpen.subscribe(
        (state: boolean) =>{
          this.dropdownClicked = state;
      }
      );

    }
    ngOnDestroy(): void {
      this.subscription.unsubscribe();
    }
}

<ul class=" nav navbar-nav navbar-right ">
            <li class="" appDropdown>
                <a  class="dropdown-toggle linkOnMouseHover" [ngClass]="{customBackground:dropdownClicked}" role="button">Manage <span class="caret"></span></a>
                <ul class="dropdown-menu">
                    <li><a  class="dropDownOption" >Save Data</a></li>
                    <li><a  class="dropDownOption" >Fetch Data</a></li>
                </ul>
            </li>
        </ul>

Conclusion: I had to use my directive flag. However, in the header component, there is another approach as Michael D suggested (instead of using the ngClass):

@ViewChild('manageButton', {static: false}) manageButton: any;

And in the subscribe function:

if(state == true){
       this.manageButton.nativeElement.classList.add('customBackground');
}else{
       this.manageButton.nativeElement.classList.remove('customBackground');
}


问:
How to schedule a task with airflow
Unfortunately even after reading the many questions here and the FAQ page of the airflow website, I still don't understand how airflow schedules tasks. I have a very simple example task here:

```<code>from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta

default_args = {
    "depends_on_past": False,
    "start_date": datetime(2020, 5, 29),
    "email_on_failure": False,
    "email_on_retry": False,
    "retries": 1,
    "retry_delay": timedelta(minutes=5),
}

dag = DAG(
    "example_dag_one",
    schedule_interval="30 8 * * *",
    catchup=False,
    default_args=default_args,
)

with dag:

    t1 = BashOperator(task_id="print_hello", bash_command="echo hello", dag=dag)

    t1

</code>```

My naiv view would be that this task would be run on May 29th 08:30. But as the time passes, airflow has not scheduled that task. If I change the cron expression to something like: '* 8 * * *' It will schedule a task every minute.

When I however use the same DAG with a start date of yesterday (so May 28th in that case) the task will be scheduled at 08:30, yet it's execution date is the 28th (even though it ran on May 29th) and the start date in the web ui is May 29th. This is VERY confusing.

What I want from airflow in the end is simple: "Here is python code, run it on this time day". So how could I achieve that. Again let's say I want to schedule a task on 08:30 every day starting tomorrow.

答:
Actually Airflow will wait for the entire scheduling interval (1 day) to be completed, then the execution would start !

So if you want your task to be executed today 2020/ 5/ 29, you should set the start time in a way that the schedule interval finishes. So set the start time to : datetime(2020, 5, 28)

If the schedule interval is 1 week, so the task would be launched 1 week later of the start time and so on ...

Title: How to schedule a task with airflow

Body:
Unfortunately even after reading the many questions here and the FAQ page of the airflow website, I still don't understand how airflow schedules tasks. I have a very simple example task here:

from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta

default_args = {
    "depends_on_past": False,
    "start_date": datetime(2020, 5, 29),
    "email_on_failure": False,
    "email_on_retry": False,
    "retries": 1,
    "retry_delay": timedelta(minutes=5),
}

dag = DAG(
    "example_dag_one",
    schedule_interval="30 8 * * *",
    catchup=False,
    default_args=default_args,
)

with dag:

    t1 = BashOperator(task_id="print_hello", bash_command="echo hello", dag=dag)

    t1

My naiv view would be that this task would be run on May 29th 08:30. But as the time passes, airflow has not scheduled that task. If I change the cron expression to something like: '* 8 * * *' It will schedule a task every minute.

When I however use the same DAG with a start date of yesterday (so May 28th in that case) the task will be scheduled at 08:30, yet it's execution date is the 28th (even though it ran on May 29th) and the start date in the web ui is May 29th. This is VERY confusing.

What I want from airflow in the end is simple: "Here is python code, run it on this time day". So how could I achieve that. Again let's say I want to schedule a task on 08:30 every day starting tomorrow.


答:
```<code>var getMatchingGroups = function(s) {
  var r=/\((.*?)\)/g, a=[], m;
  while (m = r.exec(s)) {
    a.push(m[1]);
  }
  return a;
};

getMatchingGroups("something/([0-9])/([a-z])"); // => ["[0-9]", "[a-z]"]
</code>```

Title: RegEx to match stuff between parentheses


问:
Spark Scala : how to slice an array in array of array
for an array of array:

```<code>val arrarr = Array(Array(0.37,1),Array(145.38,100),Array(149.37,100),Array(149.37,300),Array(119.37,5),Array(144.37,100))
</code>```

For example, if the input value is 149.37, I want to do some sort of indexing to get 300. 149.37 occurs two times in arrarr(Array(149.37,100),Array(149.37,300). I want to return the last value using spark scala.

Can you please help? Thanks!

答:
```<code>val index = arrarr.lastIndexWhere(x => x(0) == input)
val result = arrarr(index)(1)
</code>```

Test it here

Body:
for an array of array:

val arrarr = Array(Array(0.37,1),Array(145.38,100),Array(149.37,100),Array(149.37,300),Array(119.37,5),Array(144.37,100))

For example, if the input value is 149.37, I want to do some sort of indexing to get 300. 149.37 occurs two times in arrarr(Array(149.37,100),Array(149.37,300). I want to return the last value using spark scala.

Can you please help? Thanks!

Body:
val index = arrarr.lastIndexWhere(x => x(0) == input)
val result = arrarr(index)(1)

Test it here


问:
Weird issue with boost 1.69.0 and openmpi 2.1.2
Can someone help me make sense of the following segfault 11 error?</p>

```<code>[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib64/libthread_db.so.1".

Program received signal SIGSEGV, Segmentation fault.
0x00000000004425e0 in boost::system::error_category::equivalent(boost::system::error_code const&, int) const ()
(gdb) where
#0  0x00000000004425e0 in boost::system::error_category::equivalent(boost::system::error_code const&, int) const ()
#1  0x0000000000414a58 in _GLOBAL__sub_I_operations.cpp ()
#2  0x000000000047d40d in __libc_csu_init ()
#3  0x00002aaaab9b24d5 in __libc_start_main (main=0x414730 <main>, argc=1, argv=0x7fffffff9b38, init=0x47d3c0 <__libc_csu_init>, fini=<optimized out>,
    rtld_fini=<optimized out>, stack_end=0x7fffffff9b28) at ../csu/libc-start.c:225
#4  0x0000000000414a90 in _start ()
</code>```

答:
It looks like something might be raising an error before the static data for eg Boost System had been initialized ¹.

The most likely culprit in such a case is global variables with non-trivial constructors.

If the constructors try to do something before start of main it may fall because the relevant library is not yet initialised.

¹ see "Static Initialization Order Fiasco"

Body:
Can someone help me make sense of the following segfault 11 error?

[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib64/libthread_db.so.1".

Program received signal SIGSEGV, Segmentation fault.
0x00000000004425e0 in boost::system::error_category::equivalent(boost::system::error_code const&, int) const ()
(gdb) where
#0  0x00000000004425e0 in boost::system::error_category::equivalent(boost::system::error_code const&, int) const ()
#1  0x0000000000414a58 in _GLOBAL__sub_I_operations.cpp ()
#2  0x000000000047d40d in __libc_csu_init ()
#3  0x00002aaaab9b24d5 in __libc_start_main (main=0x414730 , argc=1, argv=0x7fffffff9b38, init=0x47d3c0 <__libc_csu_init>, fini=<optimized out>,
    rtld_fini=<optimized out>, stack_end=0x7fffffff9b28) at ../csu/libc-start.c:225
#4  0x0000000000414a90 in _start ()