问:
How to invalidate a resource released via a context manager in python?
My question relates to Kazoo/Zookeeper, but more generally it's about allocating a resource and then letting the caller of that resource no they should pause. From Kazoo docs:

It’s highly recommended to add a state listener with add_listener()
  and watch for LOST and SUSPENDED state changes and re-act
  appropriately. In the event that a LOST state occurs, its certain that
  the lock and/or the lease has been lost.

I'm using a context manager to allocate locks:

```<code>@contextmanager
def lock(self, path, identifier):
  lock = zk.Lock(path, identifier)
  lock.acquire()
  yield lock      <--- how to communicate connection loss from client?
  finally:
    lock.release()
</code>```

Used like this:

```<code>with lock('/some_op/') as lck:
  # do something with lock, but pause in case of connection loss?
</code>```

How do you allocate a lock but revoke access in case of connection loss?

here's how Kazoo recommends you implement the connection state listener:

```<code>def my_listener(state):
    if state == KazooState.LOST:
        # Register somewhere that the session was lost
    elif state == KazooState.SUSPENDED:
        # Handle being disconnected from Zookeeper
    else:
        # Handle being connected/reconnected to Zookeeper
</code>```

答:
This may not be the best design, but you can provide a reference to the lock to the body of the with statement:

```<code>@contextmanager
def acquire_lock(self, path, identifier):
  lock = zk.Lock(path, identifier)
  try:
    retry = KazooRetry()
    retry(lock.acquire)
    yield lock
  finally:
    lock.release()

with acquire_lock('/some_op/') as lock:
    ...
    if necessary:
        lock.release()
    ...
</code>```

Specific to your question (I am not familiar with Kazoo), you can define my_listener inside the context manager, where it can close over the lock.

```<code>@contextmanager
def acquire_lock(self, path, identifier):
    lock = zk.Lock(path, identifier)
    def my_listener(state):
        if state == KazooState.LOST:
            lock.release()
        elif state == KazooState.SUSPENDED:
            ...

    try:
        retry = KazooRetry()
    # etc
</code>```

Your context may need to yield the listener, or register it (or whatever you do with listeners) itself, but whatever you do with it, it will have access to the lock you created in the context manager.

Body:
My question relates to Kazoo/Zookeeper, but more generally it's about allocating a resource and then letting the caller of that resource no they should pause. From Kazoo docs:

It’s highly recommended to add a state listener with add_listener()
  and watch for LOST and SUSPENDED state changes and re-act
  appropriately. In the event that a LOST state occurs, its certain that
  the lock and/or the lease has been lost.

I'm using a context manager to allocate locks:

@contextmanager
def lock(self, path, identifier):
  lock = zk.Lock(path, identifier)
  lock.acquire()
  yield lock      <--- how to communicate connection loss from client?
  finally:
    lock.release()

Used like this:

with lock('/some_op/') as lck:
  # do something with lock, but pause in case of connection loss?

How do you allocate a lock but revoke access in case of connection loss?

here's how Kazoo recommends you implement the connection state listener:

def my_listener(state):
    if state == KazooState.LOST:
        # Register somewhere that the session was lost
    elif state == KazooState.SUSPENDED:
        # Handle being disconnected from Zookeeper
    else:
        # Handle being connected/reconnected to Zookeeper

Body:
This may not be the best design, but you can provide a reference to the lock to the body of the with statement:

@contextmanager
def acquire_lock(self, path, identifier):
  lock = zk.Lock(path, identifier)
  try:
    retry = KazooRetry()
    retry(lock.acquire)
    yield lock
  finally:
    lock.release()

with acquire_lock('/some_op/') as lock:
    ...
    if necessary:
        lock.release()
    ...

Specific to your question (I am not familiar with Kazoo), you can define my_listener inside the context manager, where it can close over the lock.

@contextmanager
def acquire_lock(self, path, identifier):
    lock = zk.Lock(path, identifier)
    def my_listener(state):
        if state == KazooState.LOST:
            lock.release()
        elif state == KazooState.SUSPENDED:
            ...

    try:
        retry = KazooRetry()
    # etc

Your context may need to yield the listener, or register it (or whatever you do with listeners) itself, but whatever you do with it, it will have access to the lock you created in the context manager.


来源: stackexchange

问:
How to use peanut package with angular dart to deploy project on github pages?
It throws an error
    pub global activate peanut

Pub installs executables into $HOME/.pub-cache/bin, which is not on your path.
You can fix that by adding this to your shell's config file (.bashrc, .bash_profile, etc.):

export PATH="$PATH":"$HOME/.pub-cache/bin"

Activated peanut 3.2.1.

I have added the following paths to
.bash_profle

```<code>export PATH="$PATH:/Users/tusharrai/development/flutter/bin"
export PATH="$PATH:/Users/tusharrai/development/flutter/.pub-cache/bin"
export PATH="$PATH:/Users/tusharrai/development/flutter/bin/cache/dart-sdk/bin"
export PATH="$PATH:/Users/tusharrai/development/flutter/bin/cache/dart-sdk.pub-cache/bin"
</code>```

答:
I'd avoid adding all of the pasts to your .bash_profile.

Instead, just run flutter pub global run peanut.

ContentLicense: CC BY-SA 4.0

Body:
It throws an error
    pub global activate peanut

Pub installs executables into $HOME/.pub-cache/bin, which is not on your path.
You can fix that by adding this to your shell's config file (.bashrc, .bash_profile, etc.):

export PATH="$PATH":"$HOME/.pub-cache/bin"

Activated peanut 3.2.1.

I have added the following paths to
.bash_profle

export PATH="$PATH:/Users/tusharrai/development/flutter/bin"
export PATH="$PATH:/Users/tusharrai/development/flutter/.pub-cache/bin"
export PATH="$PATH:/Users/tusharrai/development/flutter/bin/cache/dart-sdk/bin"
export PATH="$PATH:/Users/tusharrai/development/flutter/bin/cache/dart-sdk.pub-cache/bin"


问:
Incorrect file upload path in Laravel
I am very beginner in Laravel.

I use Laravel 5.8 in my project.

I use this component: CkEditor + https://github.com/UniSharp/laravel-filemanager .

When uploading files, they get to upload to storage/app. I would like them to be available from the website and located in the folder: public/upload

My lfm.php file:

```<code>return [
    /*
    |--------------------------------------------------------------------------
    | Routing
    |--------------------------------------------------------------------------
     */

    'use_package_routes'       => true,

    // // Use relative paths (without domain)
    // 'relative_paths'           => false,

    /*
    |--------------------------------------------------------------------------
    | Multi-User Mode
    |--------------------------------------------------------------------------
     */

    'allow_multi_user'         => false,

    'allow_share_folder'       => true,

    /*
    |--------------------------------------------------------------------------
    | Folder Names
    |--------------------------------------------------------------------------
     */

    // Flexible way to customize client folders accessibility
    // If you want to customize client folders, publish tag="lfm_handler"
    // Then you can rewrite userField function in App\Handler\ConfigHandler class
    // And set 'user_field' to App\Handler\ConfigHandler::class
    // Ex: The private folder of user will be named as the user id.
    'user_folder_name'         => UniSharp\LaravelFilemanager\Handlers\ConfigHandler::class,
    'base_directory' => 'public',
    'shared_folder_name'       => 'upload',
    'thumb_folder_name'        => 'thumbs',
    'files_folder_name' => 'file',
    'images_folder_name' => 'img',

    'folder_categories'        => [
        'file'  => [
            'folder_name'  => 'upload',
            'startup_view' => 'grid',
            'max_size'     => 50000, // size in KB
            'valid_mime'   => [
                'image/jpeg',
                'image/pjpeg',
                'image/png',
                'image/gif',
                'image/svg+xml',
            ],
        ],
        'image' => [
            'folder_name'  => 'photos',
            'startup_view' => 'list',
            'max_size'     => 50000, // size in KB
            'valid_mime'   => [
                'image/jpeg',
                'image/pjpeg',
                'image/png',
                'image/gif',
                'image/svg+xml',
                'application/pdf',
                'text/plain',
            ],
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Upload / Validation
    |--------------------------------------------------------------------------
     */

    'disk'                     => 'public',

    'rename_file'              => false,

    'alphanumeric_filename'    => false,

    'alphanumeric_directory'   => true,

    'should_validate_size'     => false,

    'should_validate_mime'     => true,

    // permissions to be set when create a new folder or when it creates automatically with thumbnails
    'create_folder_mode'       => 0755,

    // permissions to be set on file upload.
    'create_file_mode'         => 0644,

    // If true, it will attempt to chmod the file after upload
    'should_change_file_mode'  => true,

    // behavior on files with identical name
    // setting it to true cause old file replace with new one
    // setting it to false show `error-file-exist` error and stop upload
    'over_write_on_duplicate'  => false,

    /*
    |--------------------------------------------------------------------------
    | Thumbnail
    |--------------------------------------------------------------------------
     */

    // If true, image thumbnails would be created during upload
    'should_create_thumbnails' => false,

    // Create thumbnails automatically only for listed types.
    'raster_mimetypes'         => [
        'image/jpeg',
        'image/pjpeg',
        'image/png',
    ],

    'thumb_img_width'          => 200,

    'thumb_img_height'         => 200,

    /*
    |--------------------------------------------------------------------------
    | jQuery UI options
    |--------------------------------------------------------------------------
     */

    'resize_aspectRatio'       => false,

    'resize_containment'       => true,

    /*
    |--------------------------------------------------------------------------
    | File Extension Information
    |--------------------------------------------------------------------------
     */

    'file_type_array'          => [
        'pdf'  => 'Adobe Acrobat',
        'doc'  => 'Microsoft Word',
        'docx' => 'Microsoft Word',
        'xls'  => 'Microsoft Excel',
        'xlsx' => 'Microsoft Excel',
        'zip'  => 'Archive',
        'gif'  => 'GIF Image',
        'jpg'  => 'JPEG Image',
        'jpeg' => 'JPEG Image',
        'png'  => 'PNG Image',
        'ppt'  => 'Microsoft PowerPoint',
        'pptx' => 'Microsoft PowerPoint',
    ],

    'file_icon_array'          => [
        'pdf'  => 'fa-file-pdf-o',
        'doc'  => 'fa-file-word-o',
        'docx' => 'fa-file-word-o',
        'xls'  => 'fa-file-excel-o',
        'xlsx' => 'fa-file-excel-o',
        'zip'  => 'fa-file-archive-o',
        'gif'  => 'fa-file-image-o',
        'jpg'  => 'fa-file-image-o',
        'jpeg' => 'fa-file-image-o',
        'png'  => 'fa-file-image-o',
        'ppt'  => 'fa-file-powerpoint-o',
        'pptx' => 'fa-file-powerpoint-o',
    ],

    /*
    |--------------------------------------------------------------------------
    | php.ini override
    |--------------------------------------------------------------------------
    |
    | These values override your php.ini settings before uploading files
    | Set these to false to ingnore and apply your php.ini settings
    |
    | Please note that the 'upload_max_filesize' & 'post_max_size'
    | directives are not supported.
     */
    'php_ini_overrides'        => [
        'memory_limit' => '256M',
    ],
];
</code>```

The traditional upload works correctly (uploads files to the public / upload directory):

```<code>$file->move(public_path($path), $uniqueName . '.' . $extension);
</code>```

How can you fix it?

答:
For that, you need to follow the framework guidelines, its the best practice while you're developing using on it.

For reference, codes example you can find anything in the documentation: https://laravel.com/docs/5.8/filesystem

Edit:

To save in public folder is the same logic, try Storage::disk('public')->put('filename', $file_content); The Storage::disk() method you can point the directory you want to put the file, but this is in the 5.8, I don't know what version what you're using but I guess this is works since 5.2/3, check out and let us know it worked.

Title: Incorrect file upload path in Laravel

Body:
I am very beginner in Laravel.

I use Laravel 5.8 in my project.

I use this component: CkEditor + https://github.com/UniSharp/laravel-filemanager .

When uploading files, they get to upload to storage/app. I would like them to be available from the website and located in the folder: public/upload

My lfm.php file:

return [
    /*
    |--------------------------------------------------------------------------
    | Routing
    |--------------------------------------------------------------------------
     */

    'use_package_routes'       => true,

    // // Use relative paths (without domain)
    // 'relative_paths'           => false,

    /*
    |--------------------------------------------------------------------------
    | Multi-User Mode
    |--------------------------------------------------------------------------
     */

    'allow_multi_user'         => false,

    'allow_share_folder'       => true,

    /*
    |--------------------------------------------------------------------------
    | Folder Names
    |--------------------------------------------------------------------------
     */

    // Flexible way to customize client folders accessibility
    // If you want to customize client folders, publish tag="lfm_handler"
    // Then you can rewrite userField function in App\Handler\ConfigHandler class
    // And set 'user_field' to App\Handler\ConfigHandler::class
    // Ex: The private folder of user will be named as the user id.
    'user_folder_name'         => UniSharp\LaravelFilemanager\Handlers\ConfigHandler::class,
    'base_directory' => 'public',
    'shared_folder_name'       => 'upload',
    'thumb_folder_name'        => 'thumbs',
    'files_folder_name' => 'file',
    'images_folder_name' => 'img',

    'folder_categories'        => [
        'file'  => [
            'folder_name'  => 'upload',
            'startup_view' => 'grid',
            'max_size'     => 50000, // size in KB
            'valid_mime'   => [
                'image/jpeg',
                'image/pjpeg',
                'image/png',
                'image/gif',
                'image/svg+xml',
            ],
        ],
        'image' => [
            'folder_name'  => 'photos',
            'startup_view' => 'list',
            'max_size'     => 50000, // size in KB
            'valid_mime'   => [
                'image/jpeg',
                'image/pjpeg',
                'image/png',
                'image/gif',
                'image/svg+xml',
                'application/pdf',
                'text/plain',
            ],
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Upload / Validation
    |--------------------------------------------------------------------------
     */

    'disk'                     => 'public',

    'rename_file'              => false,

    'alphanumeric_filename'    => false,

    'alphanumeric_directory'   => true,

    'should_validate_size'     => false,

    'should_validate_mime'     => true,

    // permissions to be set when create a new folder or when it creates automatically with thumbnails
    'create_folder_mode'       => 0755,

    // permissions to be set on file upload.
    'create_file_mode'         => 0644,

    // If true, it will attempt to chmod the file after upload
    'should_change_file_mode'  => true,

    // behavior on files with identical name
    // setting it to true cause old file replace with new one
    // setting it to false show `error-file-exist` error and stop upload
    'over_write_on_duplicate'  => false,

    /*
    |--------------------------------------------------------------------------
    | Thumbnail
    |--------------------------------------------------------------------------
     */

    // If true, image thumbnails would be created during upload
    'should_create_thumbnails' => false,

    // Create thumbnails automatically only for listed types.
    'raster_mimetypes'         => [
        'image/jpeg',
        'image/pjpeg',
        'image/png',
    ],

    'thumb_img_width'          => 200,

    'thumb_img_height'         => 200,

    /*
    |--------------------------------------------------------------------------
    | jQuery UI options
    |--------------------------------------------------------------------------
     */

    'resize_aspectRatio'       => false,

    'resize_containment'       => true,

    /*
    |--------------------------------------------------------------------------
    | File Extension Information
    |--------------------------------------------------------------------------
     */

    'file_type_array'          => [
        'pdf'  => 'Adobe Acrobat',
        'doc'  => 'Microsoft Word',
        'docx' => 'Microsoft Word',
        'xls'  => 'Microsoft Excel',
        'xlsx' => 'Microsoft Excel',
        'zip'  => 'Archive',
        'gif'  => 'GIF Image',
        'jpg'  => 'JPEG Image',
        'jpeg' => 'JPEG Image',
        'png'  => 'PNG Image',
        'ppt'  => 'Microsoft PowerPoint',
        'pptx' => 'Microsoft PowerPoint',
    ],

    'file_icon_array'          => [
        'pdf'  => 'fa-file-pdf-o',
        'doc'  => 'fa-file-word-o',
        'docx' => 'fa-file-word-o',
        'xls'  => 'fa-file-excel-o',
        'xlsx' => 'fa-file-excel-o',
        'zip'  => 'fa-file-archive-o',
        'gif'  => 'fa-file-image-o',
        'jpg'  => 'fa-file-image-o',
        'jpeg' => 'fa-file-image-o',
        'png'  => 'fa-file-image-o',
        'ppt'  => 'fa-file-powerpoint-o',
        'pptx' => 'fa-file-powerpoint-o',
    ],

    /*
    |--------------------------------------------------------------------------
    | php.ini override
    |--------------------------------------------------------------------------
    |
    | These values override your php.ini settings before uploading files
    | Set these to false to ingnore and apply your php.ini settings
    |
    | Please note that the 'upload_max_filesize' & 'post_max_size'
    | directives are not supported.
     */
    'php_ini_overrides'        => [
        'memory_limit' => '256M',
    ],
];

The traditional upload works correctly (uploads files to the public / upload directory):

$file->move(public_path($path), $uniqueName . '.' . $extension);

How can you fix it?


问:
Get a hold of a FormControl instance by querying a component's template
I have a custom FormFieldComponent that encapsulates the HTML and error display logic for a form field:

@Component({
  selector: 'field',
  template: `

      {{label}}
      <ng-content></ng-content>

  `
})
export class FormFieldComponent {
  @Input() label: string;  // Field label
  @Input() theControl: FormControl;  // Current form control, required to display errors
}
```

<p>In <code>FormFieldComponent</code>, I need an instance of the FormControl to display errors.</p>

<p>My form then looks like this:</p>

```<form [formGroup]="myForm">
  ...
  <field label="Title" [theControl]="myForm.get('title')">
    <input type="text" formControlName="title">
  </field>
  ...
</form>
```

<p>But I'm not entirely satisfied with the above code. As you can see, I am specifying the field's key in two locations: in the <code>[theControl]</code> input property and in the <code>formControlName</code> directive.</p>

<p>The code would be more concise if I could just write:</p>

```<field label="Title">
  <input type="text" formControlName="title">
</field>
```

<p>Notice how the <code>[theControl]</code> input property is gone. The <code>FieldComponent</code> should be able to get a hold of the FormControl instance it contains, but how?</p>

<p>I have tried using the <code>@ContentChildren</code> decorator to query the component's template for FormControl directives, but it doesn't work:</p>

<pre class="lang-js prettyprint-override"><code>export class FormFieldComponent {
  @ContentChildren(FormControlDirective) theControl: any;
}
</code>```

Another option would be to pass the field's key as an input to FormFieldComponent and then let the component use that key to:

Programmatically apply the formControlName directive to the field it contains.

Get a hold of its parent <form>, access the corresponding FormGroup instance, and extract the FormControl instance from that.

答:
Not sure if things have changed, but I found a seemingly supported way to do this here

Essentially, you can use the @ContentChild decorator and depending on your form control or how you have it linked into your template control, use the proper directive as the selector for the decorator.

For example, if I am projecting an input that uses the case as you have, the [formControl], you are in the same boat as the author of that GitHub ticket.  For me, I was using the 'formGroupName' directive, and as confusing as it was, the correct usage of the directive for that worked out to be @ContentChild(FormControlName) control;

HTH!

ContentLicense: CC BY-SA 3.0

Body:
I have a custom FormFieldComponent that encapsulates the HTML and error display logic for a form field:

@Component({
  selector: 'field',
  template: `

      {{label}}
      <ng-content></ng-content>

  `
})
export class FormFieldComponent {
  @Input() label: string;  // Field label
  @Input() theControl: FormControl;  // Current form control, required to display errors
}

In FormFieldComponent, I need an instance of the FormControl to display errors.

My form then looks like this:

<form [formGroup]="myForm">
  ...
  <field label="Title" [theControl]="myForm.get('title')">
    <input type="text" formControlName="title">
  </field>
  ...
</form>

But I'm not entirely satisfied with the above code. As you can see, I am specifying the field's key in two locations: in the [theControl] input property and in the formControlName directive.

The code would be more concise if I could just write:

<field label="Title">
  <input type="text" formControlName="title">
</field>

Notice how the [theControl] input property is gone. The FieldComponent should be able to get a hold of the FormControl instance it contains, but how?

I have tried using the @ContentChildren decorator to query the component's template for FormControl directives, but it doesn't work:

export class FormFieldComponent {
  @ContentChildren(FormControlDirective) theControl: any;
}

Another option would be to pass the field's key as an input to FormFieldComponent and then let the component use that key to:

Programmatically apply the formControlName directive to the field it contains.

Get a hold of its parent <form>, access the corresponding FormGroup instance, and extract the FormControl instance from that.


问:
How can I simulate SerialPort interactions for testing?
I'm about to start developing a small app (C#) that communicates with a PLC and a testing unit via Serial Ports - this is my first venture into this area.

In essence, I am going to send the PLC a signal to start an operation, and then I am going to wait for the result of that operation from the test unit (which will be independently communicating with the PLC) to return a ASCII string.

Depending on the content of that string, I may want to listen to a signal from the PLC...

It's all new to me, so at the moment, I'm just researching System.IO.Ports.SerialPort; digression: are there third part products out there than simplify interaction with the Serial Port, or are the built-in classes as good as you will get? I'm thinking of ease of use as opposed to better features.

However, it will be a few weeks before the hardware is available for development and testing, so I was wondering how I could simulate communication to/from the serial port so that I can start developing my app?

[I don't yet know how the PLC and the PC are due to communicate - I understand it will be binary rather than text, but at the moment, that is all I know.]

答:
Abstract away your serial port comms behind an interface so that you can code your app against the interface and then test with a 'fake' implementation.  When you've got the hardware for the real thing, you can code up the 'real' implementation of the interface and swap out the fake one.

So for example, you'd have an interface

```<code>public interface ISerialComms
{
    void SendMessage(string message)
}
</code>```

and you'd code your app against that interface using a fake implementation:

```<code>public class FakeSerialComms : ISerialComms
{
    public void SendMessage(string message)
    {
        //some implementation
    }
}
</code>```

Hope that helps!

Body:
Abstract away your serial port comms behind an interface so that you can code your app against the interface and then test with a 'fake' implementation.  When you've got the hardware for the real thing, you can code up the 'real' implementation of the interface and swap out the fake one.

So for example, you'd have an interface

public interface ISerialComms
{
    void SendMessage(string message)
}

and you'd code your app against that interface using a fake implementation:

public class FakeSerialComms : ISerialComms
{
    public void SendMessage(string message)
    {
        //some implementation
    }
}

Hope that helps!


问:
String list multiplication in Python
Beginner question:
If I have 2 lists containing only strings, how do I concatenate them in a third list containing all the elements + each element of one list + each element in the other list? I thought about for loops, but isn't there a more simple way to do it?
Example:

```<code>listone = ['cat', 'dog' ]
listtwo = ['bin', 'sun']

resulting list = ['cat', 'dog', 'bin', 'sun', 'catbin', 'catsun', 'dogbin', 'dogsun', 'catbinsun', 'catsunbin', 'catcat', 'catdog', 'dogbin', 'dogcat']
</code>```

EDIT: Thank you all for replies, but i didn't explain what I want to do well enough.
The number of string in each list should be indefinite, and every word has to be concatenated with every other word, but not only in the form "x + y".
I want also to concatenate it to the other words. Like u = x+y+z

答:
Without importing itertools, you can also use string concatenation when accessing the elements of listone and listtwo like so:

```<code>result = listone + listtwo + [listone[0] + listtwo[0], listone[0] + listtwo[1], listone[1] + listtwo[0], listone[1] + listtwo[1]]
</code>```

Title: String list multiplication in Python

Body:
Beginner question:
If I have 2 lists containing only strings, how do I concatenate them in a third list containing all the elements + each element of one list + each element in the other list? I thought about for loops, but isn't there a more simple way to do it?
Example:

listone = ['cat', 'dog' ]
listtwo = ['bin', 'sun']

resulting list = ['cat', 'dog', 'bin', 'sun', 'catbin', 'catsun', 'dogbin', 'dogsun', 'catbinsun', 'catsunbin', 'catcat', 'catdog', 'dogbin', 'dogcat']

EDIT: Thank you all for replies, but i didn't explain what I want to do well enough.
The number of string in each list should be indefinite, and every word has to be concatenated with every other word, but not only in the form "x + y".
I want also to concatenate it to the other words. Like u = x+y+z

Body:
Without importing itertools, you can also use string concatenation when accessing the elements of listone and listtwo like so:

result = listone + listtwo + [listone[0] + listtwo[0], listone[0] + listtwo[1], listone[1] + listtwo[0], listone[1] + listtwo[1]]


问:
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
When I run

```<code>Get-WmiObject win32_SystemEnclosure -Computer hostname | select serialnumber
</code>```

it works for both local and remote hosts.

When I do this for a list of hosts using

```<code>ForEach ($_ in gc u:\pub\list.txt) {
    Get-WmiObject win32_SystemEnclosure -Computer $_ | select serialnumber | format-table -auto @{Label="Hostname"; Expression={$_}}, @{Label="Service Tag"; Expression={$_.serialnumber}}
}
</code>```

it returns

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

答:
I had same issue, and for me, I was trying to use an IP Address instead of computer name.
Just adding this as one more potential solution for people finding this down the road. </p>

Body:
When I run

Get-WmiObject win32_SystemEnclosure -Computer hostname | select serialnumber

it works for both local and remote hosts.

When I do this for a list of hosts using

ForEach ($_ in gc u:\pub\list.txt) {
    Get-WmiObject win32_SystemEnclosure -Computer $_ | select serialnumber | format-table -auto @{Label="Hostname"; Expression={$_}}, @{Label="Service Tag"; Expression={$_.serialnumber}}
}

it returns

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)


问:
boto3 client NoRegionError: You must specify a region error only sometimes
I have a boto3 client :

```<code>boto3.client('kms')
</code>```

But it happens on new machines, They open and close dynamically.

```<code>    if endpoint is None:
        if region_name is None:
            # Raise a more specific error message that will give
            # better guidance to the user what needs to happen.
            raise NoRegionError()
</code>```

Why is this happening? and why only part of the time?

答:
```<code>os.environ['AWS_DEFAULT_REGION'] = 'your_region_name'
</code>```

In my case sensitivity mattered.

Body:
I have a boto3 client :

boto3.client('kms')

But it happens on new machines, They open and close dynamically.

    if endpoint is None:
        if region_name is None:
            # Raise a more specific error message that will give
            # better guidance to the user what needs to happen.
            raise NoRegionError()

Why is this happening? and why only part of the time?

Body:
os.environ['AWS_DEFAULT_REGION'] = 'your_region_name'

In my case sensitivity mattered.


问:
What's the best way to track unique visits to a page?
I want to log unique visits to a particular page on my site. What is a pretty accurate yet simple way to do this? Simply by IP? Suggestions?

Let me clarify a bit:

I have a list of articles on my site. Every article is actually the same page like article.aspx. However the content is different based on thee article being viewed. I want to track unique views of a particular article.

Thanks!

答: Why not use an analytics package like Google Analytics?</p>

OwnerDisplayName: Micah

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Micah

OwnerDisplayName: webdtc


答:
Or if you want to do it by hand I would do it  this way :

```<code>l = ["a","b"]
l2 = ["c","d"]
l3 = l + l2
print(l3)
for x, y in zip(l,l2):
    l3.append(x+y)
print(l3)
</code>```

I don't know if it's optimal tho.

Title: String list multiplication in Python

Body:
Or if you want to do it by hand I would do it  this way :

l = ["a","b"]
l2 = ["c","d"]
l3 = l + l2
print(l3)
for x, y in zip(l,l2):
    l3.append(x+y)
print(l3)

I don't know if it's optimal tho.


问:
How to send email notification in ibmdatastage with custom body?
I tried to send custom body in data stage notification I don't know how to do that.

I want to send email notification with custom body message in IBM data stage.

答:
Check out the Notfication stage on Sequence level (in a Sequence job).

Alternatively you could run an OS script sending out an email (sendmail) using a Execute Command stage


问:
Pass absolute url path to handlebars view in express
I am trying to just set the canonical meta tag using an express server with handlebars as the templating engine.  I cannot figure out how to get the absolute url path and pass it to the handlebars view.  I was going to create a helper function in handlebars to do so but it would be outside of the req so I don't really know how to get the url or how to go about this.  I would like to set the canonical dynamically and not manually.  Thanks.

Here is my simple server:

```<code>const express = require('express');
const router = require('./routes/router');
const handlebars = require('express-handlebars');
const PORT = process.env.PORT || 5000;
const path = require('path');
const app = express();

var hbs = handlebars.create({
  defaultLayout: 'main',
  helpers: {
    canonical: function() {
      //get absolute url path
    }
  }
});

app.use(express.json());
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');

router(app);

app.listen(PORT, err => {
  if (err) throw err;
  console.log(`ready at http://localhost:${PORT}`);
});
</code>```

答:
You shouldn't need a helper for this.  You can add the value to res.locals and access it via Handlebars.

```<code>app.use("*", function(req, res, next){
    res.locals.absoluteUrl = absoluteUrl; // Note, you'll need to calculate this yourself
    next();
});
</code>```

In Handlebars, you access it as a standard variable:

```<code>{{absoluteUrl}}
</code>```

Body:
I am trying to just set the canonical meta tag using an express server with handlebars as the templating engine.  I cannot figure out how to get the absolute url path and pass it to the handlebars view.  I was going to create a helper function in handlebars to do so but it would be outside of the req so I don't really know how to get the url or how to go about this.  I would like to set the canonical dynamically and not manually.  Thanks.

Here is my simple server:

const express = require('express');
const router = require('./routes/router');
const handlebars = require('express-handlebars');
const PORT = process.env.PORT || 5000;
const path = require('path');
const app = express();

var hbs = handlebars.create({
  defaultLayout: 'main',
  helpers: {
    canonical: function() {
      //get absolute url path
    }
  }
});

app.use(express.json());
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');

router(app);

app.listen(PORT, err => {
  if (err) throw err;
  console.log(`ready at http://localhost:${PORT}`);
});

Body:
You shouldn't need a helper for this.  You can add the value to res.locals and access it via Handlebars.

app.use("*", function(req, res, next){
    res.locals.absoluteUrl = absoluteUrl; // Note, you'll need to calculate this yourself
    next();
});

In Handlebars, you access it as a standard variable:

{{absoluteUrl}}


问:
How to render a React component multiple times but each time with an updated State?
So I am working on a react project. I have a text area where I enter data and then that data is hashed and a Block with the Block number, hashed data and time is rendered on the screen whenever a button is clicked. However, when I enter the data again and hit the button again, it just rerenders the block as block number 2. I want the previous block to remain on screen and a new block to be rendered below the previous block whenever I click the button. How do I solve this? I have tried a lot but nothing seems to work. I am in the learning stages of react so please excuse me if this question seems trivial.

App.js

```<code>import React, {Component} from 'react';
import BlockList from './BlockList.js';
import InputText from './InputText.js';
import Button from './Button.js';

constructor() {
  super();
  console.log('constructor invoked')
  this.state = {
    blockno:0,
    Data:'',
    hash:'',
    showDiv: false

  }

onButtonClick = (event) => {
  console.log('onButtonClick invoked')
  this.setState({blockno: this.state.blockno + 1, showDiv: true})
}

}

render() {

  return(
    <div>
<InputText onSearchChange={this.OnSearchChange}/>
<Button onButtonClick={this.onButtonClick} />
       {
          this.state.showDiv
          ?
            <div>

              <BlockList blockno={this.state.blockno} Data={this.state.Data} />

            </div>
          : ''
        }

    </div>
    );
}

}

export default App;

</code>```

Block.js

```<code>import React from 'react';
import SHA256 from 'sha256-es';

const Block = ({blockno,Data}) => {

        const hashdata = () =>{
            return(
                SHA256.hash(Data)
                );
            }
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = mm + '/' + dd + '/' + yyyy;
return(
<div className="tc ws-pre">
    <h1 className="underline">Block {blockno}</h1>
    <h2>Data: {Data}</h2>
    <h2>Hash: {hashdata()}</h2>
    <h2>Date: {today}</h2>
</div>

        );

}

export default Block
</code>```

BlockList.js

```<code>import React from 'react';
import Block from './Block.js';

const BlockList = ({blockno,Data,isBlockUpdated}) => {

    const BlockItems = () => {
        return(
            <div>
                {console.log('A block item is now returned')}
                <Block blockno={blockno} Data={Data} />
            </div>
            );
    }

return(

<div>

    <BlockItems />

</div>

    );

}

export default BlockList

</code>```

I want to display a new block below the previous one every time I click the button.

答:
As DanBonehill's answer, you need an array to store the blocks

App.js

```<code>constructor() {
  super();
  console.log('constructor invoked')
  this.state = {
    // To store the list of blocks
    blocks: [],

  }
}

onButtonClick = (event) => {
  console.log('onButtonClick invoked')
  let blocks = this.state.blocks

  // Create a new block with current data and time
  blocks.push({data: this.state.Data, time: Date.time()})
  this.setState({blocks})
}

render() {
    // other stuff here
    {
          this.state.blocks.length > 0
          ?
            <div>
              <BlockList blocks={this.state.blocks} />
            </div>
          : ''
        }
}
</code>```

BlockList.js

```<code>const BlockList = ({blocks,Data,isBlockUpdated}) => {
    // other stuff here

    return(
        <div>
            {blocks.map((block, index) => <BlockItem {...block} blockno={index} />)}
        </div>
    );
}
</code>```

Body:
So I am working on a react project. I have a text area where I enter data and then that data is hashed and a Block with the Block number, hashed data and time is rendered on the screen whenever a button is clicked. However, when I enter the data again and hit the button again, it just rerenders the block as block number 2. I want the previous block to remain on screen and a new block to be rendered below the previous block whenever I click the button. How do I solve this? I have tried a lot but nothing seems to work. I am in the learning stages of react so please excuse me if this question seems trivial.

App.js

import React, {Component} from 'react';
import BlockList from './BlockList.js';
import InputText from './InputText.js';
import Button from './Button.js';

constructor() {
  super();
  console.log('constructor invoked')
  this.state = {
    blockno:0,
    Data:'',
    hash:'',
    showDiv: false

  }

onButtonClick = (event) => {
  console.log('onButtonClick invoked')
  this.setState({blockno: this.state.blockno + 1, showDiv: true})
}

}

render() {

  return(

<InputText onSearchChange={this.OnSearchChange}/>
<Button onButtonClick={this.onButtonClick} />
       {
          this.state.showDiv
          ?

              <BlockList blockno={this.state.blockno} Data={this.state.Data} />

          : ''
        }

    );
}

}

export default App;

Block.js

import React from 'react';
import SHA256 from 'sha256-es';

const Block = ({blockno,Data}) => {

        const hashdata = () =>{
            return(
                SHA256.hash(Data)
                );
            }
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = mm + '/' + dd + '/' + yyyy;
return(

Block {blockno}

Data: {Data}

Hash: {hashdata()}

Date: {today}

        );

}

export default Block

BlockList.js

import React from 'react';
import Block from './Block.js';

const BlockList = ({blockno,Data,isBlockUpdated}) => {

    const BlockItems = () => {
        return(

                {console.log('A block item is now returned')}
                <Block blockno={blockno} Data={Data} />

            );
    }

return(

    <BlockItems />

    );

}

export default BlockList

I want to display a new block below the previous one every time I click the button.

Body:
As DanBonehill's answer, you need an array to store the blocks

App.js

constructor() {
  super();
  console.log('constructor invoked')
  this.state = {
    // To store the list of blocks
    blocks: [],

  }
}

onButtonClick = (event) => {
  console.log('onButtonClick invoked')
  let blocks = this.state.blocks

  // Create a new block with current data and time
  blocks.push({data: this.state.Data, time: Date.time()})
  this.setState({blocks})
}

render() {
    // other stuff here
    {
          this.state.blocks.length > 0
          ?
            <div>
              <BlockList blocks={this.state.blocks} />
            </div>
          : ''
        }
}

BlockList.js

const BlockList = ({blocks,Data,isBlockUpdated}) => {
    // other stuff here

    return(
        <div>
            {blocks.map((block, index) => <BlockItem {...block} blockno={index} />)}
        </div>
    );
}


问:
Date object SimpleDateFormat not parsing timestamp string correctly in Java (Android) environment
I'm using the SimpleDateFormat object with the Date object as shown below. The problem lis that the Date object shows the wrong date, which is a few minutes off from the original string. The Date object appears to store the time in  total milliseconds in the debugger.

Any ideas on the problem?

```<code>import java.text.SimpleDateFormat;

import java.util.Date;

Date played_at_local;

dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSSSSZ");

played_at_local = dateFormat.parse("2011-04-11T22:27:18.491726-05:00");

//played_at_local shows "Mon Apr 11 22:35:29 America/Chicago 2011" in debugger
</code>```

答:
Try this, working for me Z should be useed in date, or rmove from Format String

```<code>SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSSSS'Z'");

played_at_local = dateFormat.parse("2011-04-11T22:27:18.491726Z-05:00");
</code>```

Body:
I'm using the SimpleDateFormat object with the Date object as shown below. The problem lis that the Date object shows the wrong date, which is a few minutes off from the original string. The Date object appears to store the time in  total milliseconds in the debugger.

Any ideas on the problem?

import java.text.SimpleDateFormat;

import java.util.Date;

Date played_at_local;

dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSSSSZ");

played_at_local = dateFormat.parse("2011-04-11T22:27:18.491726-05:00");

//played_at_local shows "Mon Apr 11 22:35:29 America/Chicago 2011" in debugger

Body:
Try this, working for me Z should be useed in date, or rmove from Format String

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSSSS'Z'");

played_at_local = dateFormat.parse("2011-04-11T22:27:18.491726Z-05:00");


答:
You can use Cartesian product and join.  Try this:

```<code>import itertools
listone = ['cat', 'dog' ]
listtwo = ['bin', 'sun']
listone + listtwo + list(''.join(e) for e in itertools.product(listone, listtwo))
</code>```

Result:

```<code>['cat', 'dog', 'bin', 'sun', 'catbin', 'catsun', 'dogbin', 'dogsun']
</code>```

Title: String list multiplication in Python

Body:
You can use Cartesian product and join.  Try this:

import itertools
listone = ['cat', 'dog' ]
listtwo = ['bin', 'sun']
listone + listtwo + list(''.join(e) for e in itertools.product(listone, listtwo))

Result:

['cat', 'dog', 'bin', 'sun', 'catbin', 'catsun', 'dogbin', 'dogsun']


问:
Execution time for a method listening from two events at one point of time c#
I have two events which are firing at the same time and calling the same method Method1(). So at one point in time,

that method will be executed two times. And inside that method, I have another method Method2() for which I have to find the execution time.

Right now I have created 2 stopwatches one when method fired from event1 and other for event2 so that they will not block each other and I can also differentiate the execution time of method2 when method1 fired from event1 or event2 and will get the accurate results.

```<code>     public void Method1()
     {
          if(event1)
          {
               Stopwatch timer = new Stopwatch();
               timer1.Start();
               Method2();
               timer1.Stop();
               Console.WriteLine("Time elapsed from event1:
               {0:hh\\:mm\\:ss}", stopwatch.Elapsed);
          }
          else
          {
                Stopwatch timer2 = new Stopwatch();
                timer2.Start();
                Method2();
                timer2.Stop();
                Console.WriteLine("Time elapsed from event2:
                {0:hh\\:mm\\:ss}", stopwatch.Elapsed);
          }
     }
</code>```

Any help so that I can create a common and generic stopwatch implementation that can run the event if one method is executing at some time from different sources and not have to create 2 stopwatches?

答:
You could pass an System.Action as a parameter and a name to apply to the log text.

```<code>public void ExecuteAndMeasureExecutionTime(System.Action methodToExecute, string logName = null)
{
    Stopwatch timer = new Stopwatch();
    timer1.Start();
    methodToExecute();
    timer1.Stop();
    Console.WriteLine("Time elapsed from {0}: {1:hh\\:mm\\:ss}", logName ?? "event", stopwatch.Elapsed);
}
</code>```

Calling code:

```<code>ExecuteAndMeasureExecutionTime(Method1, "Method1");
ExecuteAndMeasureExecutionTime(() => Method2(), "Method2");
</code>```

Body:
I have two events which are firing at the same time and calling the same method Method1(). So at one point in time,

that method will be executed two times. And inside that method, I have another method Method2() for which I have to find the execution time.

Right now I have created 2 stopwatches one when method fired from event1 and other for event2 so that they will not block each other and I can also differentiate the execution time of method2 when method1 fired from event1 or event2 and will get the accurate results.

     public void Method1()
     {
          if(event1)
          {
               Stopwatch timer = new Stopwatch();
               timer1.Start();
               Method2();
               timer1.Stop();
               Console.WriteLine("Time elapsed from event1:
               {0:hh\\:mm\\:ss}", stopwatch.Elapsed);
          }
          else
          {
                Stopwatch timer2 = new Stopwatch();
                timer2.Start();
                Method2();
                timer2.Stop();
                Console.WriteLine("Time elapsed from event2:
                {0:hh\\:mm\\:ss}", stopwatch.Elapsed);
          }
     }

Any help so that I can create a common and generic stopwatch implementation that can run the event if one method is executing at some time from different sources and not have to create 2 stopwatches?

Body:
You could pass an System.Action as a parameter and a name to apply to the log text.

public void ExecuteAndMeasureExecutionTime(System.Action methodToExecute, string logName = null)
{
    Stopwatch timer = new Stopwatch();
    timer1.Start();
    methodToExecute();
    timer1.Stop();
    Console.WriteLine("Time elapsed from {0}: {1:hh\\:mm\\:ss}", logName ?? "event", stopwatch.Elapsed);
}

Calling code:

ExecuteAndMeasureExecutionTime(Method1, "Method1");
ExecuteAndMeasureExecutionTime(() => Method2(), "Method2");


问:
PyTorch: Sigmoid of weights?
I'm new to neural networks/PyTorch. I'm trying to make a net that takes in a vector x, first layer is h_j = w_j^T * x + b_j, output is max_j{h_j}. The only thing is that I want the w_j to be restricted between 0 and 1, by having w_j = S(k*a_j), where S is the sigmoid function, k is some constant, and a_j are the actual weight variables (w_j is just a function of a_j). How do I do this in PyTorch? I can't just use a torch.nn.Linear layer, there has to be something else/additional to add in the sigmoid function on the weights?

Side question, for that last output layer, can I just use torch.max to get the max of the previous layer's outputs? Does that behave nicely, or is there some torch.nn.Max or some pooling stuff that I don't understand that needs to happen?

Thanks!

答:
I am really not sure why would you do that but you can declare a custom layer as below to apply sigmoid to weights. </p>

```<code>class NewLayer(nn.Module):
    def __init__ (self, input_size, output_size):
        super().__init__()
        self.W = nn.Parameter(torch.zeros(input_size, output_size))
        # kaiming initialization (use any other if you like)
        self.W = nn.init.kaiming_normal_(self.W)
        self.b = nn.Parameter(torch.ones(output_size))
    def forward(self, x):
        # applying sigmoid to weights and getting results
        ret = torch.addmm(self.b, x, torch.sigmoid(self.W))
        return ret
</code>```

<p>Once you do this, you can use this as you would use linear layer in your code. </p>

Title: PyTorch: Sigmoid of weights?

Body:
I am really not sure why would you do that but you can declare a custom layer as below to apply sigmoid to weights.

class NewLayer(nn.Module):
    def __init__ (self, input_size, output_size):
        super().__init__()
        self.W = nn.Parameter(torch.zeros(input_size, output_size))
        # kaiming initialization (use any other if you like)
        self.W = nn.init.kaiming_normal_(self.W)
        self.b = nn.Parameter(torch.ones(output_size))
    def forward(self, x):
        # applying sigmoid to weights and getting results
        ret = torch.addmm(self.b, x, torch.sigmoid(self.W))
        return ret

Once you do this, you can use this as you would use linear layer in your code.


问:
Error reading file share paths as arguments
I am receiving the following error when I execute the below script.

Test-Path : A positional parameter cannot be found that accepts
  argument 'input.dat'.

```<code>.\FL.ps1 \\flamingdev\analytics\source\INBOUND   \\flamingdev\analytics\source\OUTBOUND

[CmdletBinding()]
param (
  [string] $SrcFolder,
  [string] $FileListPath
)

$SrcFolder
$FileListPath

IF (Test-Path "$FileListPath"\input.dat) {
Remove-Item "$FileListPath"\input.dat
}

Get-ChildItem -File -Path "$SrcFolder"\Extract* | Select-Object - ExpandProperty Name | Add-Content -Path "$FileListPath"\input.dat
</code>```

答: Thank you, issue was resolved after tweaking the code little bit. Get-ChildItem -File -Path "$SrcFolder","*.csv"</p>

Body:
I am receiving the following error when I execute the below script.

Test-Path : A positional parameter cannot be found that accepts
  argument 'input.dat'.

.\FL.ps1 \\flamingdev\analytics\source\INBOUND   \\flamingdev\analytics\source\OUTBOUND

[CmdletBinding()]
param (
  [string] $SrcFolder,
  [string] $FileListPath
)

$SrcFolder
$FileListPath

IF (Test-Path "$FileListPath"\input.dat) {
Remove-Item "$FileListPath"\input.dat
}

Get-ChildItem -File -Path "$SrcFolder"\Extract* | Select-Object - ExpandProperty Name | Add-Content -Path "$FileListPath"\input.dat


问:
How to extract a subString from android java String?
I tried to extract Sub-String from java string, but failed. i tried like this

```<code>String text = "audios/{any_number} any_audio_name.mp3";
text= text.substring(text.indexOf('/'), text.indexOf('3')-2);
</code>```

Updated

I need String contains only any_audio_name and removing audios/ , any number e.g. {123} and .mp3

For example audios/{211} new school poem.mp3 to new school poem

答:
Use regex seems fit here.

public class MyMain{
    public static void main(String args[]) {
        String line = "audios/any_audio_name.mp3";
        String pattern = "audios\\/(.*)\\.mp3";

        // Create a Pattern object
        Pattern r = Pattern.compile(pattern);

        // Now create matcher object.
        Matcher m = r.matcher(line);

        if (m.find()) {
            System.out.println("Found value: " + m.group(1));
        } else {
            System.out.println("NO MATCH");
        }
    }
}

```

Body:
I tried to extract Sub-String from java string, but failed. i tried like this

String text = "audios/{any_number} any_audio_name.mp3";
text= text.substring(text.indexOf('/'), text.indexOf('3')-2);

Updated

I need String contains only any_audio_name and removing audios/ , any number e.g. {123} and .mp3

For example audios/{211} new school poem.mp3 to new school poem


答:
This should do the job

```<code>In [29]: import itertools
In [30]: listone = ['cat', 'dog' ]
    ...: listtwo = ['bin', 'sun']

In [31]: output = listone + listtwo + [ "".join(items)  for items in list(itertools.product(listone, listtwo))]

In [32]: output
Out[32]: ['cat', 'dog', 'bin', 'sun', 'catbin', 'catsun', 'dogbin', 'dogsun']
</code>```

You also could do it without itertools

```<code>In [33]: output = listone + listtwo + [ item_one+item_two for item_one in listone for item_two in listtwo]

In [34]: output
Out[34]: ['cat', 'dog', 'bin', 'sun', 'catbin', 'catsun', 'dogbin', 'dogsun']
</code>```

Title: String list multiplication in Python

Body:
Beginner question:
If I have 2 lists containing only strings, how do I concatenate them in a third list containing all the elements + each element of one list + each element in the other list? I thought about for loops, but isn't there a more simple way to do it?
Example:

listone = ['cat', 'dog' ]
listtwo = ['bin', 'sun']

resulting list = ['cat', 'dog', 'bin', 'sun', 'catbin', 'catsun', 'dogbin', 'dogsun', 'catbinsun', 'catsunbin', 'catcat', 'catdog', 'dogbin', 'dogcat']

EDIT: Thank you all for replies, but i didn't explain what I want to do well enough.
The number of string in each list should be indefinite, and every word has to be concatenated with every other word, but not only in the form "x + y".
I want also to concatenate it to the other words. Like u = x+y+z

Body:
This should do the job

In [29]: import itertools
In [30]: listone = ['cat', 'dog' ]
    ...: listtwo = ['bin', 'sun']

In [31]: output = listone + listtwo + [ "".join(items)  for items in list(itertools.product(listone, listtwo))]

In [32]: output
Out[32]: ['cat', 'dog', 'bin', 'sun', 'catbin', 'catsun', 'dogbin', 'dogsun']

You also could do it without itertools

In [33]: output = listone + listtwo + [ item_one+item_two for item_one in listone for item_two in listtwo]

In [34]: output
Out[34]: ['cat', 'dog', 'bin', 'sun', 'catbin', 'catsun', 'dogbin', 'dogsun']


问:
Tensorflow giving random answers on a regression problem
I am trying to reproduce a Python exercise with Node.js using Tensorflow.js.

The objective is to simply convert Celsius to Fahrenheit using machine learning.

However, I am a noob with Tensorflow.js and it keeps giving me random answers.

I have tried multiple things like many different shapes.
I have checked that both Python and Node.js have the same models. They both have the following model :

```<code>Layer (type)                 Output shape              Param #
=================================================================
dense_Dense1 (Dense)         [null,1]                  2
=================================================================
Total params: 2
Trainable params: 2
Non-trainable params: 0
</code>```

```<code>const tf = require("@tensorflow/tfjs-node")

function convert(c){
    return (c*1.8)+32 // Convert celsius to fahrenheit
}

var celsius = []
var fahrenheit = []

for (let i = 0; i < 20; i++) {
    var r = 100; // Keeping this only value to ensure that Tf knows the answer I also have tried with 20 different values but doesn't work
    celsius.push([r]) // Shape [20,1]
    fahrenheit.push([convert(r)]) // Push the answer (212) to the fahrenheit array
}

var model = tf.sequential();
model.add(tf.layers.dense({inputShape:[1], units: 1}))

async function trainModel(model, inputs, labels) {
    // Prepare the model for training.
    model.compile({
      optimizer: tf.train.adam(),
      loss: tf.losses.meanSquaredError,
      metrics: ['accuracy'], // Accuracy = 0
    });

    model.summary();

    const epochs = 500;

    return await model.fit(inputs, labels, {
      epochs,
      batchSize: 20,
      verbose: false // Nothing interesting with verbose
    });
  }

c = tf.tensor(celsius)
f = tf.tensor(fahrenheit)

var training = trainModel(model, c, f)

training.then(function(args){
    var prediction = model.predict(tf.tensor([[100]]));
    prediction.print(); // Prints a random number
    console.log("Real answer = "+convert(100))
})

</code>```

The output tensor value is randomly changing every time.
Here is an example :

```<code>Tensor
     [[65.9411697],]
Real answer = 212
</code>```

答:
It seems the main problem is the optimizer. - If trained with an SGD optimizer. the prediction works fine.

```<code>const tf = require("@tensorflow/tfjs-node")
const nr_epochs=500;

function convert(c){
  return (c*1.8)+32 // Convert celsius to fahrenheit
}

let celsius = []
let fahrenheit = []

for (let i = 0; i < 100; i++) {
  var r = 100; // Keeping this only value to ensure that Tf knows the answer
  celsius.push(i) // Shape [20,1]
  fahrenheit.push(convert(i)) // Push the answer (212) to the fahrenheit array
}

const train = async (xy, ys) => {
  const model = tf.sequential();

  model.add(tf.layers.dense({units: 1, inputShape: [1]}));

  model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
  await model.fit(xs,ys,{epochs: nr_epochs})
  return model;
}

const predict =  (model, n) => {
  const predicted =  model.predict(tf.tensor2d([n],[1,1]));
  return predicted;
}

const xs = tf.tensor2d(celsius.slice (0,15), [15,1]);
const ys = tf.tensor2d(fahrenheit.slice (0,15), [15,1]);
(async () => {
  let trained = await train (xs,ys);
  for (let n of [4,6,12]) {
    let predicted = predict (trained, n).dataSync ();
    console.log (`Value: ${n} Predicted: ${predicted [0]}`)
  }
})()
</code>```

Logs:

```<code>Value: 4 Predicted: 38.01055908203125
Value: 6 Predicted: 42.033267974853516
Value: 12 Predicted: 54.101402282714844
</code>```

Body:
I am trying to reproduce a Python exercise with Node.js using Tensorflow.js.

The objective is to simply convert Celsius to Fahrenheit using machine learning.

However, I am a noob with Tensorflow.js and it keeps giving me random answers.

I have tried multiple things like many different shapes.
I have checked that both Python and Node.js have the same models. They both have the following model :

Layer (type)                 Output shape              Param #
=================================================================
dense_Dense1 (Dense)         [null,1]                  2
=================================================================
Total params: 2
Trainable params: 2
Non-trainable params: 0

const tf = require("@tensorflow/tfjs-node")

function convert(c){
    return (c*1.8)+32 // Convert celsius to fahrenheit
}

var celsius = []
var fahrenheit = []

for (let i = 0; i < 20; i++) {
    var r = 100; // Keeping this only value to ensure that Tf knows the answer I also have tried with 20 different values but doesn't work
    celsius.push([r]) // Shape [20,1]
    fahrenheit.push([convert(r)]) // Push the answer (212) to the fahrenheit array
}

var model = tf.sequential();
model.add(tf.layers.dense({inputShape:[1], units: 1}))

async function trainModel(model, inputs, labels) {
    // Prepare the model for training.
    model.compile({
      optimizer: tf.train.adam(),
      loss: tf.losses.meanSquaredError,
      metrics: ['accuracy'], // Accuracy = 0
    });

    model.summary();

    const epochs = 500;

    return await model.fit(inputs, labels, {
      epochs,
      batchSize: 20,
      verbose: false // Nothing interesting with verbose
    });
  }

c = tf.tensor(celsius)
f = tf.tensor(fahrenheit)

var training = trainModel(model, c, f)

training.then(function(args){
    var prediction = model.predict(tf.tensor([[100]]));
    prediction.print(); // Prints a random number
    console.log("Real answer = "+convert(100))
})

The output tensor value is randomly changing every time.
Here is an example :

Tensor
     [[65.9411697],]
Real answer = 212

Body:
It seems the main problem is the optimizer. - If trained with an SGD optimizer. the prediction works fine.

const tf = require("@tensorflow/tfjs-node")
const nr_epochs=500;

function convert(c){
  return (c*1.8)+32 // Convert celsius to fahrenheit
}

let celsius = []
let fahrenheit = []

for (let i = 0; i < 100; i++) {
  var r = 100; // Keeping this only value to ensure that Tf knows the answer
  celsius.push(i) // Shape [20,1]
  fahrenheit.push(convert(i)) // Push the answer (212) to the fahrenheit array
}

const train = async (xy, ys) => {
  const model = tf.sequential();

  model.add(tf.layers.dense({units: 1, inputShape: [1]}));

  model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
  await model.fit(xs,ys,{epochs: nr_epochs})
  return model;
}

const predict =  (model, n) => {
  const predicted =  model.predict(tf.tensor2d([n],[1,1]));
  return predicted;
}

const xs = tf.tensor2d(celsius.slice (0,15), [15,1]);
const ys = tf.tensor2d(fahrenheit.slice (0,15), [15,1]);
(async () => {
  let trained = await train (xs,ys);
  for (let n of [4,6,12]) {
    let predicted = predict (trained, n).dataSync ();
    console.log (`Value: ${n} Predicted: ${predicted [0]}`)
  }
})()

Logs:

Value: 4 Predicted: 38.01055908203125
Value: 6 Predicted: 42.033267974853516
Value: 12 Predicted: 54.101402282714844


问:
Using pointer to a struct to create linked list and Memory allocation in C
I have a concept question I suppose.  When I need to create a linked list, but I am just given a pointer to a struct (and the struct contains some data type and pointer "next").  How would I ensure that I am creating the other links and not just the root node?  I am not using malloc or else this would be more apparent answer. This list is acting as malloc itself.

Thanks in advance!

To Clarify:

There will be single dimension array which will act as a block of memory of fixed sized.  The linked list will then "allocate" by removing a node and putting it into the array or "free" data by removing it from array to add back to list.

example

(struct defined by some data type and pointer)
struct is called node

```<code>node array[10];  //this acts as memory
node* linked_list;  //this gives or removes data to memory (array)
</code>```

答:
I can't be sure if this applies to your particular question, but I do would like to point out something about creating a linked list without using malloc.

It doesn't really matter how you allocate the nodes of the linked list, be it dynamically or statically. What matters is that every node actually exists and the pointers are valid.

For example, we can build a linked list from an array.

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

typedef struct node_t {
    int value;
    struct node_t *next;
} node;

int main() {

    int i;
    node linked_list[10];

    // build the linked list
    for ( i = 0; i < 10; i++ ) {
        linked_list[i].value = i * i;
        linked_list[i].next = ( i < 9 ) ? &linked_list[i+1] : 0;
    }

    // now traverse it
    node *head = &linked_list[0];
    while ( head ) {
        printf( "%d\n", head->value );
        head = head->next;
    }
}
</code>```

EDIT: in order to use an array as the place from which to "allocate" or "free" the linked list nodes, you can augment the node struct with a flag to indicate if the node is being used or not.

```<code>typedef struct node_t {
    char in_use;
    int value;
    struct node_t *next;
} node;
</code>```

EDIT2: let's give it one last try. Below is the function that "allocates" one node from the array (or returns NULL if none is available). Assume linked_list is global.

```<code>node *get_node() {
    int i;
    for ( i = 0; i < 10; i++ )
        if ( !linked_list[i].in_use ) {
            linked_list[i].in_use = true;
            return &linked_list[i];
        }
    return 0;
}
</code>```

EDIT3: if the array is to be used as a memory pool the way to go is John Bode's answer.

Body:
I have a concept question I suppose.  When I need to create a linked list, but I am just given a pointer to a struct (and the struct contains some data type and pointer "next").  How would I ensure that I am creating the other links and not just the root node?  I am not using malloc or else this would be more apparent answer. This list is acting as malloc itself.

Thanks in advance!

To Clarify:

There will be single dimension array which will act as a block of memory of fixed sized.  The linked list will then "allocate" by removing a node and putting it into the array or "free" data by removing it from array to add back to list.

example

(struct defined by some data type and pointer)
struct is called node

node array[10];  //this acts as memory
node* linked_list;  //this gives or removes data to memory (array)

Body:
I can't be sure if this applies to your particular question, but I do would like to point out something about creating a linked list without using malloc.

It doesn't really matter how you allocate the nodes of the linked list, be it dynamically or statically. What matters is that every node actually exists and the pointers are valid.

For example, we can build a linked list from an array.

#include <stdio.h>

typedef struct node_t {
    int value;
    struct node_t *next;
} node;

int main() {

    int i;
    node linked_list[10];

    // build the linked list
    for ( i = 0; i < 10; i++ ) {
        linked_list[i].value = i * i;
        linked_list[i].next = ( i < 9 ) ? &linked_list[i+1] : 0;
    }

    // now traverse it
    node *head = &linked_list[0];
    while ( head ) {
        printf( "%d\n", head->value );
        head = head->next;
    }
}

EDIT: in order to use an array as the place from which to "allocate" or "free" the linked list nodes, you can augment the node struct with a flag to indicate if the node is being used or not.

typedef struct node_t {
    char in_use;
    int value;
    struct node_t *next;
} node;

EDIT2: let's give it one last try. Below is the function that "allocates" one node from the array (or returns NULL if none is available). Assume linked_list is global.

node *get_node() {
    int i;
    for ( i = 0; i < 10; i++ )
        if ( !linked_list[i].in_use ) {
            linked_list[i].in_use = true;
            return &linked_list[i];
        }
    return 0;
}

EDIT3: if the array is to be used as a memory pool the way to go is John Bode's answer.


问:
"Combine" 2 variables to declare a new one?
I am new to coding and I am trying to declare a variable that refers to 2 "combined" previously declared variables as followed :

```<code>var player1 = "Red", player2 = "Blue", player3 = "Green";
var p=1;
var Red = {x: 2, y: 4};
var Blue = {x: 6, y: 2};
var Green = {x: 8, y: 1};

var x = player+p.x; // should be player+1 so "Red" so x=2
var y = player+p.y; // should be y=4

console.log(x);
console.log(y);
</code>```

x and y should be the coordinates of player n°p depending on the color of that player (in this example player n°1).

I hope it's clear enough ! Thanks for your help !

答:
You might be searching for an array of objects:

var players = [
  {
    name: "Red",
    x: 2,
    y: 4
  },
  {
    name: "Blue",
    x: 6,
    y: 2
  },
  {
    name: "Green",
    x: 8,
    y: 1
  }
];

players.forEach((player,index)=>{
  console.log(`Player ${index+1} = ${player.name} position is = x:${player.x},y:${player.y}`);
});```

This way, you can access the element you want by doing: players[index]. And to get its properties, you just need to call it like this: players[index].name for the name.

Body:
I am new to coding and I am trying to declare a variable that refers to 2 "combined" previously declared variables as followed :

var player1 = "Red", player2 = "Blue", player3 = "Green";
var p=1;
var Red = {x: 2, y: 4};
var Blue = {x: 6, y: 2};
var Green = {x: 8, y: 1};

var x = player+p.x; // should be player+1 so "Red" so x=2
var y = player+p.y; // should be y=4

console.log(x);
console.log(y);

x and y should be the coordinates of player n°p depending on the color of that player (in this example player n°1).

I hope it's clear enough ! Thanks for your help !

Body:
You might be searching for an array of objects:

var players = [
  {
    name: "Red",
    x: 2,
    y: 4
  },
  {
    name: "Blue",
    x: 6,
    y: 2
  },
  {
    name: "Green",
    x: 8,
    y: 1
  }
];

players.forEach((player,index)=>{
  console.log(`Player ${index+1} = ${player.name} position is = x:${player.x},y:${player.y}`);
});

This way, you can access the element you want by doing: players[index]. And to get its properties, you just need to call it like this: players[index].name for the name.


问:
Google Searching in R
This question is not so much about how to google search in R (discussed many times before) as much as why it does not always work.

I found this code from another posted question here
That I recall working perfectly. It would produce all the links in the search.

But now it does not work. For some reason the   node is not there anymore when I pull the data into R. But when I actually inspect the html code on Chrome it's there when I am browsing the code. It show's the h3 node in the display inspector but not when it's being downloded.

```<code>library(rvest)
ht <- read_html('https://www.google.co.in/search?q=guitar+repair+workshop')
links <- ht %>% html_nodes(xpath='//h3/a') %>% html_attr('href')
gsub('/url\\?q=','',sapply(strsplit(links[as.vector(grep('url',links))],split='&'),'[',1))
</code>```

I get the following return:

```<code> character(0)
</code>```

The google page display of links depends on your location/preferences. So maybe this is what is causing the issue?

答:
It appears that the format switched very recently, maybe today, and that the //h3 is no longer used. This produces what is intended with one final extraneous result</p>

```<code>    library(rvest)
    ht <- read_html('https://www.google.co.in/search?q=guitar+repair+workshop')
    links <- ht %>% html_nodes(xpath='//a') %>% html_attr('href')
    gsub('/url\\?q=','',sapply(strsplit(links[as.vector(grep('url',links))],split='&'),'[',1))
</code>```

Title: Google Searching in R

Body:
This question is not so much about how to google search in R (discussed many times before) as much as why it does not always work.

I found this code from another posted question here
That I recall working perfectly. It would produce all the links in the search.

But now it does not work. For some reason the   node is not there anymore when I pull the data into R. But when I actually inspect the html code on Chrome it's there when I am browsing the code. It show's the h3 node in the display inspector but not when it's being downloded.

library(rvest)
ht <- read_html('https://www.google.co.in/search?q=guitar+repair+workshop')
links <- ht %>% html_nodes(xpath='//h3/a') %>% html_attr('href')
gsub('/url\\?q=','',sapply(strsplit(links[as.vector(grep('url',links))],split='&'),'[',1))

I get the following return:

 character(0)

The google page display of links depends on your location/preferences. So maybe this is what is causing the issue?

Body:
It appears that the format switched very recently, maybe today, and that the //h3 is no longer used. This produces what is intended with one final extraneous result

    library(rvest)
    ht <- read_html('https://www.google.co.in/search?q=guitar+repair+workshop')
    links <- ht %>% html_nodes(xpath='//a') %>% html_attr('href')
    gsub('/url\\?q=','',sapply(strsplit(links[as.vector(grep('url',links))],split='&'),'[',1))


问:
How to have model method run automatically if field is greater than 12
If my model field hours is more than 12.0 I want end_time to be set automatically without the user having to save or even be in the app. Is there a way to do this in a model method without the user having to save the time entry?

Models.py

```<code>class Entry(models.Model):
    TUID = models.IntegerField()
    start_time = models.DateTimeField()
    end_time = models.DateTimeField(blank=True, null=True, db_index=True)
    seconds_paused = models.PositiveIntegerField(default=0)
    pause_time = models.DateTimeField(blank=True, null=True)
    date_updated = models.DateTimeField(auto_now=True)
    hours = models.DecimalField(max_digits=11, decimal_places=2, default=0)
    pause_time_end = models.DateTimeField(blank=True, null=True)

    def _str_(self):
        return self.TUID

    def timeStop(self):
        if self.hours >= 12:
           self.end_time = timezone.now()
        return self.end_time
</code>```

答:
The question is not entirely clear, but I will assume that what you mean is that when the object is saved, you want to automatically set the end_time if it is not already set.  One option is to do this in a pre_save hook, but I prefer to overwrite the save() method.  Something like this:

```<code>class Entry(models.Model):
    ...
    def save(self, *args, **kwargs):
        if (self.hours >= 12) and not self.end_time:
           self.end_time = timezone.now()
        super().save(*args, **kwargs)
</code>```

Body:
If my model field hours is more than 12.0 I want end_time to be set automatically without the user having to save or even be in the app. Is there a way to do this in a model method without the user having to save the time entry?

Models.py

class Entry(models.Model):
    TUID = models.IntegerField()
    start_time = models.DateTimeField()
    end_time = models.DateTimeField(blank=True, null=True, db_index=True)
    seconds_paused = models.PositiveIntegerField(default=0)
    pause_time = models.DateTimeField(blank=True, null=True)
    date_updated = models.DateTimeField(auto_now=True)
    hours = models.DecimalField(max_digits=11, decimal_places=2, default=0)
    pause_time_end = models.DateTimeField(blank=True, null=True)

    def _str_(self):
        return self.TUID

    def timeStop(self):
        if self.hours >= 12:
           self.end_time = timezone.now()
        return self.end_time

Body:
The question is not entirely clear, but I will assume that what you mean is that when the object is saved, you want to automatically set the end_time if it is not already set.  One option is to do this in a pre_save hook, but I prefer to overwrite the save() method.  Something like this:

class Entry(models.Model):
    ...
    def save(self, *args, **kwargs):
        if (self.hours >= 12) and not self.end_time:
           self.end_time = timezone.now()
        super().save(*args, **kwargs)


问:
Splitting up Data into Rows based on Cell Value
First time here so apologies in advance if I'm asking this incorrectly.

I have a pretty good understanding of excel but I've only ever really used it for some easy to moderate formulas. I'm trying to figure out where to start with a problem I have but I'm not even sure what to search for to find the answer. From what I have been able to find - it should be achievable with either Power Query or a Excel-VBA macro?

I have maybe 400 rows of data on a sheet. I need to separate each row of data based on the values in 4 of the columns.

This is the screenshot I've made with a brief example of what I'm trying to achieve.

The top part of the screenshot is how the data is now. The bottom part is how I want the data to be modified. A new row is created for any fee thats been incurred (base fee for every row, then if they have incurred an order fee then a new row is added, if a priority fee has been incurred then a new row is added etc. If it's '0' then no new row).

If any one has any guidance on how to do this it'd be great. I'm not asking for the solution, but just some tips on what I can research or what I should be learning to accomplish something like this!

答:
Assuming the column headers in your example (Name, Email, Order Date, Order Amount, Currency, Expedite Fee, Currency, Courier Fee, Currency) with the source data in named range with headers Table1, the powerquery code would be below.  </p>

```<code>let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Added Custom" = Table.AddColumn(Source, "Base Fee", each "USD:150"),
#"Merged Columns" = Table.CombineColumns(Table.TransformColumnTypes(#"Added Custom", {{"Order Amount", type text}}, "en-US"),{"Currency", "Order Amount"},Combiner.CombineTextByDelimiter(":", QuoteStyle.None),"Order Amount1"),
#"Merged Columns1" = Table.CombineColumns(Table.TransformColumnTypes(#"Merged Columns", {{"Expedite Fee", type text}}, "en-US"),{"Currency2", "Expedite Fee"},Combiner.CombineTextByDelimiter(":", QuoteStyle.None),"Expedite Fee1"),
#"Merged Columns2" = Table.CombineColumns(Table.TransformColumnTypes(#"Merged Columns1", {{"Courier Fee", type text}}, "en-US"),{"Currency3", "Courier Fee"},Combiner.CombineTextByDelimiter(":", QuoteStyle.None),"Courier Fee1"),
#"Removed Other Columns" = Table.SelectColumns(#"Merged Columns2",{"Name", "Order Amount1", "Expedite Fee1", "Courier Fee1","Base Fee"}),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Removed Other Columns", {"Name"}, "Description", "Value"),
#"Split Column by Delimiter" = Table.SplitColumn(#"Unpivoted Other Columns", "Value", Splitter.SplitTextByDelimiter(":", QuoteStyle.Csv), {"Currency", "Fee"}),
#"Replaced Value" = Table.ReplaceValue(#"Split Column by Delimiter","1","",Replacer.ReplaceText,{"Description"})
in #"Replaced Value"
</code>```

Body:
Assuming the column headers in your example (Name, Email, Order Date, Order Amount, Currency, Expedite Fee, Currency, Courier Fee, Currency) with the source data in named range with headers Table1, the powerquery code would be below.

let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Added Custom" = Table.AddColumn(Source, "Base Fee", each "USD:150"),
#"Merged Columns" = Table.CombineColumns(Table.TransformColumnTypes(#"Added Custom", {{"Order Amount", type text}}, "en-US"),{"Currency", "Order Amount"},Combiner.CombineTextByDelimiter(":", QuoteStyle.None),"Order Amount1"),
#"Merged Columns1" = Table.CombineColumns(Table.TransformColumnTypes(#"Merged Columns", {{"Expedite Fee", type text}}, "en-US"),{"Currency2", "Expedite Fee"},Combiner.CombineTextByDelimiter(":", QuoteStyle.None),"Expedite Fee1"),
#"Merged Columns2" = Table.CombineColumns(Table.TransformColumnTypes(#"Merged Columns1", {{"Courier Fee", type text}}, "en-US"),{"Currency3", "Courier Fee"},Combiner.CombineTextByDelimiter(":", QuoteStyle.None),"Courier Fee1"),
#"Removed Other Columns" = Table.SelectColumns(#"Merged Columns2",{"Name", "Order Amount1", "Expedite Fee1", "Courier Fee1","Base Fee"}),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Removed Other Columns", {"Name"}, "Description", "Value"),
#"Split Column by Delimiter" = Table.SplitColumn(#"Unpivoted Other Columns", "Value", Splitter.SplitTextByDelimiter(":", QuoteStyle.Csv), {"Currency", "Fee"}),
#"Replaced Value" = Table.ReplaceValue(#"Split Column by Delimiter","1","",Replacer.ReplaceText,{"Description"})
in #"Replaced Value"


问:
BigQuery Fails to parse an avro shcema file
I need to create an empty table using avro schema file into Google's big query but fails to do so...

I have composed the following sample schema file

```<code>{
   "namespace": "tutorialspoint.com",
   "type": "record",
   "name": "emp",
   "fields": [
      {"name": "name", "type": "string"},
      {"name": "address", "type": "string"}
   ]
}
</code>```

And the using BigQuery console fails to create a table with the following error:

Error while reading data, error message: The Apache Avro library failed to parse the header with the following error: Invalid data file. Magic does not match: /subrange//bigstore/bigquery-prod-upload-us

答: BigQuery supports loading Avro files, as defined here. There's no formal definition of avro schema file and thus not supported in BigQuery. If you want to create an empty table in BigQuery with schema, you can use a BigQuery JSON schema file.</p>

Body:
I need to create an empty table using avro schema file into Google's big query but fails to do so...

I have composed the following sample schema file

{
   "namespace": "tutorialspoint.com",
   "type": "record",
   "name": "emp",
   "fields": [
      {"name": "name", "type": "string"},
      {"name": "address", "type": "string"}
   ]
}

And the using BigQuery console fails to create a table with the following error:

Error while reading data, error message: The Apache Avro library failed to parse the header with the following error: Invalid data file. Magic does not match: /subrange//bigstore/bigquery-prod-upload-us


问:
Extracting Text Values from XML in SQL
I'm working with SQL data hosted by a 3rd party, and am trying to pull some specific information for reporting. However, some of what I need to parse out is in XML format, and I'm getting stuck. I'm looking for the syntax to pull the text= values only from the XML code.

I believe the code should something like this, but most of the examples I can find online involve simpler XML hierarchy's than what I'm dealing with.

```<code><[columnnameXML].value('(/RelatedValueListBO/Items/RelatedValueListBOItem/text())[1]','varchar(max)')>
</code>```

Fails to pull any results. I've tried declaring the spacenames as well, but again...I only ever end up with NULL values pulled.

Example XML I'm dealing with:

```<code><RelatedValueListBO xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xmlns="http://tempuri.org/RelatedValueListBOSchema.xsd">
    <Items>
        <RelatedValueListBOItem groupKey="Response1" text="Response1" selected="true" />
        <RelatedValueListBOItem groupKey="Response2" text="Response2" selected="true" />
        <RelatedValueListBOItem groupKey="Response3" text="Response3" selected="true" />
    </Items>
</RelatedValueListBO>
</code>```

Ideally I'd like to pull response1; response2; response3 into a single column.  Allowing for the fact that multiple responses may exist. I believe I'm getting stuck with the basic code I've been trying due to the namespaces associated to RelatedValueListBO and the fact that what I want is grouped in groupKey, text, and selected, instead of the value I want just being under the Items node.

答:
You have the namespaces defined in your XML, so you need to define them in the XQuery too.

Fast and dirty method is to replace all namespaces with a "*":

```<code>SELECT @x.value('(/*:RelatedValueListBO/*:Items/*:RelatedValueListBOItem/@text)[1]','varchar(max)')
</code>```

To get all responses in a single column you can use:

```<code>
SELECT
 Item.Col.value('./@text','varchar(max)') X
FROM @x.nodes('/*:RelatedValueListBO/*:Items/*:RelatedValueListBOItem') AS Item(Col)
</code>```

If you need a better performance, you may need to define namespaces properly.

Title: Extracting Text Values from XML in SQL

Body:
I'm working with SQL data hosted by a 3rd party, and am trying to pull some specific information for reporting. However, some of what I need to parse out is in XML format, and I'm getting stuck. I'm looking for the syntax to pull the text= values only from the XML code.

I believe the code should something like this, but most of the examples I can find online involve simpler XML hierarchy's than what I'm dealing with.

<[columnnameXML].value('(/RelatedValueListBO/Items/RelatedValueListBOItem/text())[1]','varchar(max)')>

Fails to pull any results. I've tried declaring the spacenames as well, but again...I only ever end up with NULL values pulled.

Example XML I'm dealing with:

<RelatedValueListBO xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xmlns="http://tempuri.org/RelatedValueListBOSchema.xsd">
    <Items>
        <RelatedValueListBOItem groupKey="Response1" text="Response1" selected="true" />
        <RelatedValueListBOItem groupKey="Response2" text="Response2" selected="true" />
        <RelatedValueListBOItem groupKey="Response3" text="Response3" selected="true" />
    </Items>
</RelatedValueListBO>

Ideally I'd like to pull response1; response2; response3 into a single column.  Allowing for the fact that multiple responses may exist. I believe I'm getting stuck with the basic code I've been trying due to the namespaces associated to RelatedValueListBO and the fact that what I want is grouped in groupKey, text, and selected, instead of the value I want just being under the Items node.

Body:
You have the namespaces defined in your XML, so you need to define them in the XQuery too.

Fast and dirty method is to replace all namespaces with a "*":

SELECT @x.value('(/*:RelatedValueListBO/*:Items/*:RelatedValueListBOItem/@text)[1]','varchar(max)')

To get all responses in a single column you can use:

SELECT
 Item.Col.value('./@text','varchar(max)') X
FROM @x.nodes('/*:RelatedValueListBO/*:Items/*:RelatedValueListBOItem') AS Item(Col)

If you need a better performance, you may need to define namespaces properly.


问:
Problem using function in exported custom module in nodejs
I am new to nodejs and I am trying to export my custom module but it says function is not defined or is not a function.

I have created a module which contains a function to validate the request body using Joi library. Below is what I have done

validator.js

```<code>const Joi = require('joi');

var validateCustomer = function(customer) {
    const schema = {
        name: Joi.string().min(3).required()
    }

    return Joi.validate(customer, schema)
}

module.exports.validator = validateCustomer;
</code>```

customers.js

```<code>const validator = require('../myModules/validator');

router.post('/', async (req, res) => {
    const {error} = validator(req.body);
    if(error) return res.error(404).send(error.details[0].message);
    ...some code
});
</code>```

Please help

答:
Change out

```<code>module.exports.validator = validateCustomer;
</code>```

for

```<code>module.exports = validateCustomer
</code>```

in validator.js.

Body:
I am new to nodejs and I am trying to export my custom module but it says function is not defined or is not a function.

I have created a module which contains a function to validate the request body using Joi library. Below is what I have done

validator.js

const Joi = require('joi');

var validateCustomer = function(customer) {
    const schema = {
        name: Joi.string().min(3).required()
    }

    return Joi.validate(customer, schema)
}

module.exports.validator = validateCustomer;

customers.js

const validator = require('../myModules/validator');

router.post('/', async (req, res) => {
    const {error} = validator(req.body);
    if(error) return res.error(404).send(error.details[0].message);
    ...some code
});

Please help

Body:
Change out

module.exports.validator = validateCustomer;

for

module.exports = validateCustomer

in validator.js.


问:
Separate row selection from row checkbox selection?
Does ag-grid support separating row selection from checked checkboxes?

My users need to select a row (click on it, or keyboard nav) to see further details about the row. Then they need to check the checkbox (or not) to select the row for later export to Excel.

So for example, they'll click every row to see the further details, but only check some of the checkboxes for later export. Is this supported?

If not, what would be a good approach to implement? Add my own checkboxes to the first column?

答:
You can set suppressRowClickSelection to true when you want checkbox selection, and don't want to also select when the row is clicked. If true, rows won't be selected when clicked.

You can read more about this here - https://www.ag-grid.com/javascript-grid-selection/


问:
Angular 6 how to get count of the particular column based on same value from an array of object
I have an array of object and also I am using foreach loop in typescript.Here as per my array it contains 2 columns having value progress:100 and others are less that 100.So here I need to calculate the count of columns having progress:100,for ex here it should be 2.Also I need to get the count of all columns having progress value is less or not 100.for ex here 2.Then I need to append into div.I have tried but its adding not counting.Here is the code below

app.component.html

```<code><div>Progress : 2{{count}}</div><div>completed : 2{{count}}</div>
</code>```

app.component.ts

```<code>declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{

      arrayVal:any;
      currentVal : any;
  title = 'projectchart';
  public array = [{"id":1,"progress":100},{"id":3,"progress":70},{"id":5,"progress":50},{"id":6,"progress":100}];
  ngOnInit(){
     let count=0;
     this.array.forEach((item, index) => {
     console.log(item.progress) ;
     count +=item.progress ;
});
     console.log(count);
  }

}
</code>```

答:
You can use library like underscore, where a function like countBy will do what you want.

In your case:

```<code>_.countBy(array, (item) => item.progress === 100 ? 'completed' : 'progress');
</code>```

the result will be:

{completed: 2, progress: 2}

Body:
I have an array of object and also I am using foreach loop in typescript.Here as per my array it contains 2 columns having value progress:100 and others are less that 100.So here I need to calculate the count of columns having progress:100,for ex here it should be 2.Also I need to get the count of all columns having progress value is less or not 100.for ex here 2.Then I need to append into div.I have tried but its adding not counting.Here is the code below

app.component.html

Progress : 2{{count}}

completed : 2{{count}}

app.component.ts

declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{

      arrayVal:any;
      currentVal : any;
  title = 'projectchart';
  public array = [{"id":1,"progress":100},{"id":3,"progress":70},{"id":5,"progress":50},{"id":6,"progress":100}];
  ngOnInit(){
     let count=0;
     this.array.forEach((item, index) => {
     console.log(item.progress) ;
     count +=item.progress ;
});
     console.log(count);
  }

}

Body:
You can use library like underscore, where a function like countBy will do what you want.

In your case:

_.countBy(array, (item) => item.progress === 100 ? 'completed' : 'progress');

the result will be:

{completed: 2, progress: 2}


问:
What is the attribute that defines the color alpha? XML fusioncharts
I'm trying to make a graph in XML, it's all right, but it shows me at the beginning of the graph a "white" color, I would like to know what is the property that defines that

```<code>Dim strxml = ""
        strxml = strxml & "  <chart caption ='Control en la validación de AS BUILT' xAxisName='ESTADO DE GESTIÓN' yAxisName='Total' rotatevalues='0' valuefontcolor='ffffff' placeValuesInside='1' animation='1' showYAxisValues='1' formatNumberScale='0' labelDisplay='rotate' slantLabels='1' showLabels='1' > "
        strxml = strxml & "  <categories> "
        For i = 0 To dt.Rows.Count - 2
            strxml = strxml & "      <category label='" & dt.Rows(i).Item("estado").ToString() & "'/>"
        Next
        strxml = strxml & "  </categories> "
        'strxml = strxml & "  <dataset color='fa5c05'>"
        strxml = strxml & " <dataset seriesname = 'RF AB' color='84500A'>"
        For i = 0 To dt.Rows.Count - 1
            strxml = strxml & " <set value='" & dt.Rows(i).Item("ab_rf") & "'/>"
        Next
        strxml = strxml & " </dataset>"
        strxml = strxml & " <dataset seriesname = 'FO CONST' >"
        For i = 0 To dt.Rows.Count - 1
            strxml = strxml & " <set value='" & dt.Rows(i).Item("const") & "'/>"
        Next
        strxml = strxml & " </dataset>"
        strxml = strxml & " <dataset seriesname = 'FO FUS. PE' >"
        For i = 0 To dt.Rows.Count - 1
            strxml = strxml & " <set value='" & dt.Rows(i).Item("fus_pe") & "'/>"
        Next
        strxml = strxml & " </dataset>"
        strxml = strxml & " <dataset seriesname = 'FO FUS. PI' >"
        For i = 0 To dt.Rows.Count - 1
            strxml = strxml & " <set value='" & dt.Rows(i).Item("fus_pi") & "'/>"
        Next
        strxml = strxml & " </dataset>"
        strxml = strxml & " <dataset seriesname = 'PI ACTA' >"
        For i = 0 To dt.Rows.Count - 1
            strxml = strxml & " <set value='" & dt.Rows(i).Item("acta") & "'/>"
        Next
        strxml = strxml & " </dataset>"
        strxml = strxml & " </chart> "

        Literal3.Text = FusionCharts.RenderChartHTML("../../FusionCharts/Charts/MSColumn2D.swf", "", strxml, "myNext", "900", "400", False, True, True)
</code>```

it looks like this

Image of graphics

I think the problem could be here

```<code>strxml = strxml & "  <chart caption ='Control en la validación de AS BUILT' xAxisName='ESTADO DE GESTIÓN' yAxisName='Total' rotatevalues='0' valuefontcolor='ffffff' placeValuesInside='1' animation='1' showYAxisValues='1' formatNumberScale='0' labelDisplay='rotate' slantLabels='1' showLabels='1' > "
</code>```

答:
I SOLVED IT :D

I POST THE ANSWER:

I will give the answer for those who need it

need to add the parameter "plotGradientColor" with two single quotes

plotGradientColor=''

the result is:

IMG OF GRAPHICS1

that is for old version of fusioncharts.

For the new version you can use the new parameter:

"usePlotGradientColor": "0"

Good luck to you all

Body:
I'm trying to make a graph in XML, it's all right, but it shows me at the beginning of the graph a "white" color, I would like to know what is the property that defines that

Dim strxml = ""
        strxml = strxml & "  <chart caption ='Control en la validación de AS BUILT' xAxisName='ESTADO DE GESTIÓN' yAxisName='Total' rotatevalues='0' valuefontcolor='ffffff' placeValuesInside='1' animation='1' showYAxisValues='1' formatNumberScale='0' labelDisplay='rotate' slantLabels='1' showLabels='1' > "
        strxml = strxml & "  <categories> "
        For i = 0 To dt.Rows.Count - 2
            strxml = strxml & "      <category label='" & dt.Rows(i).Item("estado").ToString() & "'/>"
        Next
        strxml = strxml & "  </categories> "
        'strxml = strxml & "  <dataset color='fa5c05'>"
        strxml = strxml & " <dataset seriesname = 'RF AB' color='84500A'>"
        For i = 0 To dt.Rows.Count - 1
            strxml = strxml & " <set value='" & dt.Rows(i).Item("ab_rf") & "'/>"
        Next
        strxml = strxml & " </dataset>"
        strxml = strxml & " <dataset seriesname = 'FO CONST' >"
        For i = 0 To dt.Rows.Count - 1
            strxml = strxml & " <set value='" & dt.Rows(i).Item("const") & "'/>"
        Next
        strxml = strxml & " </dataset>"
        strxml = strxml & " <dataset seriesname = 'FO FUS. PE' >"
        For i = 0 To dt.Rows.Count - 1
            strxml = strxml & " <set value='" & dt.Rows(i).Item("fus_pe") & "'/>"
        Next
        strxml = strxml & " </dataset>"
        strxml = strxml & " <dataset seriesname = 'FO FUS. PI' >"
        For i = 0 To dt.Rows.Count - 1
            strxml = strxml & " <set value='" & dt.Rows(i).Item("fus_pi") & "'/>"
        Next
        strxml = strxml & " </dataset>"
        strxml = strxml & " <dataset seriesname = 'PI ACTA' >"
        For i = 0 To dt.Rows.Count - 1
            strxml = strxml & " <set value='" & dt.Rows(i).Item("acta") & "'/>"
        Next
        strxml = strxml & " </dataset>"
        strxml = strxml & " </chart> "

        Literal3.Text = FusionCharts.RenderChartHTML("../../FusionCharts/Charts/MSColumn2D.swf", "", strxml, "myNext", "900", "400", False, True, True)

it looks like this

Image of graphics

I think the problem could be here

strxml = strxml & "  <chart caption ='Control en la validación de AS BUILT' xAxisName='ESTADO DE GESTIÓN' yAxisName='Total' rotatevalues='0' valuefontcolor='ffffff' placeValuesInside='1' animation='1' showYAxisValues='1' formatNumberScale='0' labelDisplay='rotate' slantLabels='1' showLabels='1' > "