问:
Is it possible to create signalR streaming connection in web worker
I am using Angular 8 and singalR for image streaming from the server.

I noticed that streaming slow down my UI rendering.
I want whole streaming part to move to Web Worker and only valuable content send from Web Worker to UI tread.

I do not have code example since I am not sure if my idea even possible.

Can anyone give me some tips, or post, since I do not find anything about web workers and web socket (signalR) connection in them.

答:
After some researching I finally finished this.
This is possible, and there is couple tips for it:

https://angular.io/guide/web-worker
Create web worker, ng generate webWorker  , is command for that and Angular will set up enviroment for you.
If you do that without this command, there is additional work to do. Please check documentation for it.

Install @microsoft/signalr library, not @aspnet/signalr. I had problem to establish connection in web worker with @aspnet/signalr.

Then from my component I called worker to establish connection:

public establishConnectionToStreamingHub() {
  if (!this.streamingWorker) {
    this.streamingWorker = new Worker('./streaming-data.worker', { type: 'module' });

    this.streamingWorker.postMessage(<StreamingWorkerRequest>{
      action: StreamingWorkerAction.EstablishConnection,
      baseHref: this.href
    });

    this.streamingWorker.onmessage = this.onWorkerMessage;
  }
}

// listen for streaming response from worker.
// I created interface here for message type.
// If message is success I notified listener about it, if message is error handling should be added here.

private onWorkerMessage = (message) => {
  const response = message.data as StreamingWorkerResponse;
  if (response.type === ResponseMessageType.StreamingSuccessResult) {
    this.streamingDataNotify(response.data);
  }
}

```
<p>This is my streaming worker file.
The main point here is that I have one class for connection and streaming.
First time I get message to the worker I check message type if message is 'StreamingWorkerAction.EstablishConnection'.
If it is I create new class instance and establish connection to the hub in class constructor. I send worker instace to the class also.
After it for all streaming request class object is in charge of.</p>
```import { StreamingWorkerAction,
  StreamingWorkerRequest,
  StreamingWorkerResponse,
  ResponseMessageType
} from './streaming-worker.model';

export class StreamingClass {
  private hubConnection: HubConnection;

  private workerInstance;
  private href = '';

  private streamingSubscription: ISubscription<Data>;

  constructor(data: StreamingWorkerRequest) {
    this.href = data.baseHref;
    this.workerInstance = data.workerInstance;

    this.connectHub().subscribe(result => {
      console.log('Streaming connection established.')
    }, error => {
      this.workerInstance.postMessage(<StreamingWorkerResponse>{
        type: ResponseMessageType.ConnectingError,
        error: error
      });
    });

    this.workerInstance.onmessage = (event) => {
      const requestData = event.data as StreamingWorkerRequest;
      if (requestData.action === StreamingWorkerAction.StartStreaming) {
        this.clearCurrentSubscription();
        this.streamingSubscription = this.startStreaming(streamingId);
      }
    };
  }

  private clearCurrentSubscription() {
    if (this.streamingSubscription) {
      this.streamingSubscription.dispose();
    }
  }

  private startStreaming(streamingId: string): ISubscription<StreamingData> {
    return this.hubConnection.stream<StreamingData>('Stream', streamingId).subscribe({
      next: data => {
        this.workerInstance.postMessage(<StreamingWorkerResponse>{
          type: ResponseMessageType.StreamingSuccessResult,
          data: data
        });
      },
      complete: () => {
        console.log('complete');
      },
      error: error => {
        this.workerInstance.postMessage(<StreamingWorkerResponse>{
          type: ResponseMessageType.StreamingError,
          error: error
        });
      }
    });
  }

  private connectHub(): Observable<boolean> {
    this.hubConnection = new HubConnectionBuilder()
       .withUrl(this.href + '/api/hub/pathToTheHub')
       .withAutomaticReconnect()
       .build();
  }

}

// web worker event listener
addEventListener('message', event => {
  const requestData = event.data as StreamingWorkerRequest;

  if (requestData.action === StreamingWorkerAction.EstablishConnection) {
    requestData.workerInstance = self;
    const streamingClass = new StreamingClass(requestData);
  }
});
```
<p><strong>Update: 02-09-2020</strong></p>
<p>On npm site for @microsoft/signalr library: https://www.npmjs.com/package/@microsoft/signalr</p>
<p>I noticed this:</p>
<blockquote>
<p>To use the client in a webworker, copy *.js files from the dist/webworker > >folder to your script folder include on your webworker using the importScripts >function. Note that webworker SignalR hub connection supports only absolute path >to a SignalR hub.</p>
</blockquote>
<p>After it i found webworker folder in my node modules: \node_modules@microsoft\signalr\dist\webworker</p>
<p>and copied file signalr.js to assets folder on path: assets/scripts/signalr.js.</p>
<p>Then in my worker file I imported script like this:</p>
```import * as signalR from '../../../../assets/scripts/signalr.js';
```
<p>And in worker file replaced all old signalR import to new one from webworker script.
For example those lines:</p>
```private hubConnection: HubConnection;
private streamingSubscription: ISubscription<MetaModule>;

this.hubConnection = new HubConnectionBuilder()
       .withUrl(this.href + '/api/hub/pathToTheHub')
       .withAutomaticReconnect()
       .build();
```
<p>are changed to:</p>
```private hubConnection: signalR.HubConnection;
private streamingSubscription: signalR.ISubscription<MetaModule>;

this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl(this.href + '/api/hub/pathToTheHub')
      .withAutomaticReconnect()
      .build();
```

After those updates our streaming process works significantly faster.

Body:
After some researching I finally finished this.
This is possible, and there is couple tips for it:

https://angular.io/guide/web-worker
Create web worker, ng generate webWorker  , is command for that and Angular will set up enviroment for you.
If you do that without this command, there is additional work to do. Please check documentation for it.

Install @microsoft/signalr library, not @aspnet/signalr. I had problem to establish connection in web worker with @aspnet/signalr.

Then from my component I called worker to establish connection:

public establishConnectionToStreamingHub() {
  if (!this.streamingWorker) {
    this.streamingWorker = new Worker('./streaming-data.worker', { type: 'module' });

    this.streamingWorker.postMessage(<StreamingWorkerRequest>{
      action: StreamingWorkerAction.EstablishConnection,
      baseHref: this.href
    });

    this.streamingWorker.onmessage = this.onWorkerMessage;
  }
}

// listen for streaming response from worker.
// I created interface here for message type.
// If message is success I notified listener about it, if message is error handling should be added here.

private onWorkerMessage = (message) => {
  const response = message.data as StreamingWorkerResponse;
  if (response.type === ResponseMessageType.StreamingSuccessResult) {
    this.streamingDataNotify(response.data);
  }
}

This is my streaming worker file.
The main point here is that I have one class for connection and streaming.
First time I get message to the worker I check message type if message is 'StreamingWorkerAction.EstablishConnection'.
If it is I create new class instance and establish connection to the hub in class constructor. I send worker instace to the class also.
After it for all streaming request class object is in charge of.

import { StreamingWorkerAction,
  StreamingWorkerRequest,
  StreamingWorkerResponse,
  ResponseMessageType
} from './streaming-worker.model';

export class StreamingClass {
  private hubConnection: HubConnection;

  private workerInstance;
  private href = '';

  private streamingSubscription: ISubscription<Data>;

  constructor(data: StreamingWorkerRequest) {
    this.href = data.baseHref;
    this.workerInstance = data.workerInstance;

    this.connectHub().subscribe(result => {
      console.log('Streaming connection established.')
    }, error => {
      this.workerInstance.postMessage(<StreamingWorkerResponse>{
        type: ResponseMessageType.ConnectingError,
        error: error
      });
    });

    this.workerInstance.onmessage = (event) => {
      const requestData = event.data as StreamingWorkerRequest;
      if (requestData.action === StreamingWorkerAction.StartStreaming) {
        this.clearCurrentSubscription();
        this.streamingSubscription = this.startStreaming(streamingId);
      }
    };
  }

  private clearCurrentSubscription() {
    if (this.streamingSubscription) {
      this.streamingSubscription.dispose();
    }
  }

  private startStreaming(streamingId: string): ISubscription<StreamingData> {
    return this.hubConnection.stream<StreamingData>('Stream', streamingId).subscribe({
      next: data => {
        this.workerInstance.postMessage(<StreamingWorkerResponse>{
          type: ResponseMessageType.StreamingSuccessResult,
          data: data
        });
      },
      complete: () => {
        console.log('complete');
      },
      error: error => {
        this.workerInstance.postMessage(<StreamingWorkerResponse>{
          type: ResponseMessageType.StreamingError,
          error: error
        });
      }
    });
  }

  private connectHub(): Observable<boolean> {
    this.hubConnection = new HubConnectionBuilder()
       .withUrl(this.href + '/api/hub/pathToTheHub')
       .withAutomaticReconnect()
       .build();
  }

}

// web worker event listener
addEventListener('message', event => {
  const requestData = event.data as StreamingWorkerRequest;

  if (requestData.action === StreamingWorkerAction.EstablishConnection) {
    requestData.workerInstance = self;
    const streamingClass = new StreamingClass(requestData);
  }
});

Update: 02-09-2020

On npm site for @microsoft/signalr library: https://www.npmjs.com/package/@microsoft/signalr

I noticed this:

To use the client in a webworker, copy *.js files from the dist/webworker > >folder to your script folder include on your webworker using the importScripts >function. Note that webworker SignalR hub connection supports only absolute path >to a SignalR hub.

After it i found webworker folder in my node modules: \node_modules@microsoft\signalr\dist\webworker

and copied file signalr.js to assets folder on path: assets/scripts/signalr.js.

Then in my worker file I imported script like this:

import * as signalR from '../../../../assets/scripts/signalr.js';

And in worker file replaced all old signalR import to new one from webworker script.
For example those lines:

private hubConnection: HubConnection;
private streamingSubscription: ISubscription<MetaModule>;

this.hubConnection = new HubConnectionBuilder()
       .withUrl(this.href + '/api/hub/pathToTheHub')
       .withAutomaticReconnect()
       .build();

are changed to:

private hubConnection: signalR.HubConnection;
private streamingSubscription: signalR.ISubscription<MetaModule>;

this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl(this.href + '/api/hub/pathToTheHub')
      .withAutomaticReconnect()
      .build();

After those updates our streaming process works significantly faster.


来源: stackexchange

问:
How to retrieve Table structure from sqlite3 (.db ) database using python
I am trying to get table structure using python from sqlite3 (.db) database. for that I am using the below code, but it is giving syntax error any help?</p>
```<code>import sqlite3
conn = sqlite3.connect('Db-IMDB.db')
cursor = conn.cursor()
cursor.execute('DESCRIBE Movie')
</code>```

答:
It's not MySQL, but sqlite3. In Python API you can retrieve information on table from this statement:   </p>

```<code>table_info = cursor.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to get table structure using python from sqlite3 (.db) database. for that I am using the below code, but it is giving syntax error any help?

import sqlite3
conn = sqlite3.connect('Db-IMDB.db')
cursor = conn.cursor()
cursor.execute('DESCRIBE Movie')

Body:
It's not MySQL, but sqlite3. In Python API you can retrieve information on table from this statement:

table_info = cursor.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()


问:
How to query registry values skipping the PS* ones
When querying the registry value names like this:

```<code>Get-ItemProperty HKCU:\Software\Microsoft\Osk
</code>```

You get a whole bunch of extra values.

```<code>PSPath            : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software\Microsoft\Osk
PSParentPath      : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software\Microsoft
PSChildName       : Osk
PSDrive           : HKCU
PSProvider        : Microsoft.PowerShell.Core\Registry
WindowLeft        : 100
WindowTop         : 100
WindowWidth       : 828
WindowHeight      : 236
ClickSound        : 1
Mode              : 1
HoverPeriod       : 1000
ScanInterval      : 1000
UseDevice         : 1
UseMouse          : 0
UseKB             : 1
ScanKey           : 32
UseTextPrediction : 1
InsertSpace       : 1
ShowNumPad        : 0
</code>```

What I want is only the value names (WindowLeft, ...)

How can I do that?

Edit: string matches don't cut it. I do want legitimate registry value names to be included.

Example (could have done similar things with reg query hklm /v PS* /s or reg query hkcu /v PS* /s

```<code>reg add "HKCU\Software\BeSharp.net\Test" /v "Foo" /t REG_SZ /d "Bar" /f
reg add "HKCU\Software\BeSharp.net\Test" /v "Bar" /t REG_SZ /d "Foo" /f

reg add "HKCU\Software\BeSharp.net\Test" /v "PSPath" /t REG_SZ /d "Foo" /f
reg add "HKCU\Software\BeSharp.net\Test" /v "PSParentPath" /t REG_SZ /d "Foo" /f
reg add "HKCU\Software\BeSharp.net\Test" /v "PSChildName" /t REG_SZ /d "Foo" /f
reg add "HKCU\Software\BeSharp.net\Test" /v "PSDrive" /t REG_SZ /d "Foo" /f
reg add "HKCU\Software\BeSharp.net\Test" /v "PSProvider" /t REG_SZ /d "Foo" /f

reg add "HKCU\Software\BeSharp.net\Test" /v "1" /t REG_SZ /d "PSPath" /f
reg add "HKCU\Software\BeSharp.net\Test" /v "2" /t REG_SZ /d "PSParentPath" /f
reg add "HKCU\Software\BeSharp.net\Test" /v "3" /t REG_SZ /d "PSChildName" /f
reg add "HKCU\Software\BeSharp.net\Test" /v "4" /t REG_SZ /d "PSDrive" /f
reg add "HKCU\Software\BeSharp.net\Test" /v "5" /t REG_SZ /d "PSProvider" /f

reg query "HKCU\Software\BeSharp.net\Test"
</code>```

You can delete the above demo data with this:

```<code>reg delete "HKCU\Software\BeSharp.net\Test"
</code>```

The reg query "HKCU\Software\BeSharp.net\Test" returns this:

```<code>HKEY_CURRENT_USER\Software\BeSharp.net\Test
    Foo    REG_SZ    Bar
    Bar    REG_SZ    Foo
    PSPath    REG_SZ    Foo
    PSParentPath    REG_SZ    Foo
    PSChildName    REG_SZ    Foo
    PSDrive    REG_SZ    Foo
    PSProvider    REG_SZ    Foo
    1    REG_SZ    PSPath
    2    REG_SZ    PSParentPath
    3    REG_SZ    PSChildName
    4    REG_SZ    PSDrive
    5    REG_SZ    PSProvider
</code>```

But the PowerShell Get-ItemProperty "HKCU:\Software\BeSharp.net\Test" returns this, overwriting the PS* values in the registry:

```<code>PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software\BeSharp.net\Test
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software\BeSharp.net
PSChildName  : Test
PSDrive      : HKCU
PSProvider   : Microsoft.PowerShell.Core\Registry
Foo          : Bar
Bar          : Foo
1            : PSPath
2            : PSParentPath
3            : PSChildName
4            : PSDrive
5            : PSProvider
</code>```

And adding a Select clause skips all PS* values, even if they came from the registry: PowerShell Get-ItemProperty "HKCU:\Software\BeSharp.net\Test" ^| Select * -Exclude PS*:

```<code>Foo : Bar
Bar : Foo
1   : PSPath
2   : PSParentPath
3   : PSChildName
4   : PSDrive
5   : PSProvider
</code>```

So: skip PS* values like PSPath, PSParentPath, PSChildName, PSDrive and PSProvider (are there more?) when they are not in the registry, but include them when they are in the registry.

Bonus: Only list the names (not the values).

答:
I know this is truly old, but here's a function I added to my Profile to facilitate registry exploration:

```<code>Function Get-KeyProperty  {
Param(
    [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
    [ValidateScript( {(Resolve-Path $_).Provider.Name -Like 'Registry'} )]
    [String[]]
    $Path,
    [String[]]
    $Name=@("*")
)
Process {
    $Name.ForEach({ (Get-Item $Path).Property -like $_}).ForEach({
        Begin {$Hash = @{}}
        Process { $Hash += @{ $_ = (Get-Item $Path).GetValue($_)} }
        End {[PSCustomObject]$Hash}
    })
}}
</code>```

Examples:

```<code>PS C:\> set-alias gkp Get-KeyProperty
>>
>> $USF = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\'
>>
>> $TestPSNames = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\DummyWithPSNames\'
>>
PS C:\> gkp $TestPSNames
Hello PSPath
----- ------
World Not the real PS Path

PS C:\>>gkp $USF -Name p*,S*

Start Menu : C:\Users\keith\AppData\Roaming\Microsoft\Windows\Start Menu
SendTo     : C:\Users\keith\AppData\Roaming\Microsoft\Windows\SendTo
Startup    : C:\Users\keith\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
PrintHood  : C:\Users\keith\AppData\Roaming\Microsoft\Windows\Printer Shortcuts
Personal   : C:\Users\keith\Documents
Programs   : C:\Users\keith\AppData\Roaming\Microsoft\Windows\Start Menu\Programs

PS C:\>>$USF, $TestPSNames | gkp -Name S*,PS*,H* | fl

SendTo     : C:\Users\keith\AppData\Roaming\Microsoft\Windows\SendTo
Startup    : C:\Users\keith\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Start Menu : C:\Users\keith\AppData\Roaming\Microsoft\Windows\Start Menu
History    : C:\Users\keith\AppData\Local\Microsoft\Windows\History

PSPath : Not the real PS Path
Hello  : World
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When querying the registry value names like this:

Get-ItemProperty HKCU:\Software\Microsoft\Osk

You get a whole bunch of extra values.

PSPath            : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software\Microsoft\Osk
PSParentPath      : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software\Microsoft
PSChildName       : Osk
PSDrive           : HKCU
PSProvider        : Microsoft.PowerShell.Core\Registry
WindowLeft        : 100
WindowTop         : 100
WindowWidth       : 828
WindowHeight      : 236
ClickSound        : 1
Mode              : 1
HoverPeriod       : 1000
ScanInterval      : 1000
UseDevice         : 1
UseMouse          : 0
UseKB             : 1
ScanKey           : 32
UseTextPrediction : 1
InsertSpace       : 1
ShowNumPad        : 0

What I want is only the value names (WindowLeft, ...)

How can I do that?

Edit: string matches don't cut it. I do want legitimate registry value names to be included.

Example (could have done similar things with reg query hklm /v PS* /s or reg query hkcu /v PS* /s

reg add "HKCU\Software\BeSharp.net\Test" /v "Foo" /t REG_SZ /d "Bar" /f
reg add "HKCU\Software\BeSharp.net\Test" /v "Bar" /t REG_SZ /d "Foo" /f

reg add "HKCU\Software\BeSharp.net\Test" /v "PSPath" /t REG_SZ /d "Foo" /f
reg add "HKCU\Software\BeSharp.net\Test" /v "PSParentPath" /t REG_SZ /d "Foo" /f
reg add "HKCU\Software\BeSharp.net\Test" /v "PSChildName" /t REG_SZ /d "Foo" /f
reg add "HKCU\Software\BeSharp.net\Test" /v "PSDrive" /t REG_SZ /d "Foo" /f
reg add "HKCU\Software\BeSharp.net\Test" /v "PSProvider" /t REG_SZ /d "Foo" /f

reg add "HKCU\Software\BeSharp.net\Test" /v "1" /t REG_SZ /d "PSPath" /f
reg add "HKCU\Software\BeSharp.net\Test" /v "2" /t REG_SZ /d "PSParentPath" /f
reg add "HKCU\Software\BeSharp.net\Test" /v "3" /t REG_SZ /d "PSChildName" /f
reg add "HKCU\Software\BeSharp.net\Test" /v "4" /t REG_SZ /d "PSDrive" /f
reg add "HKCU\Software\BeSharp.net\Test" /v "5" /t REG_SZ /d "PSProvider" /f

reg query "HKCU\Software\BeSharp.net\Test"

You can delete the above demo data with this:

reg delete "HKCU\Software\BeSharp.net\Test"

The reg query "HKCU\Software\BeSharp.net\Test" returns this:

HKEY_CURRENT_USER\Software\BeSharp.net\Test
    Foo    REG_SZ    Bar
    Bar    REG_SZ    Foo
    PSPath    REG_SZ    Foo
    PSParentPath    REG_SZ    Foo
    PSChildName    REG_SZ    Foo
    PSDrive    REG_SZ    Foo
    PSProvider    REG_SZ    Foo
    1    REG_SZ    PSPath
    2    REG_SZ    PSParentPath
    3    REG_SZ    PSChildName
    4    REG_SZ    PSDrive
    5    REG_SZ    PSProvider

But the PowerShell Get-ItemProperty "HKCU:\Software\BeSharp.net\Test" returns this, overwriting the PS* values in the registry:

PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software\BeSharp.net\Test
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software\BeSharp.net
PSChildName  : Test
PSDrive      : HKCU
PSProvider   : Microsoft.PowerShell.Core\Registry
Foo          : Bar
Bar          : Foo
1            : PSPath
2            : PSParentPath
3            : PSChildName
4            : PSDrive
5            : PSProvider

And adding a Select clause skips all PS* values, even if they came from the registry: PowerShell Get-ItemProperty "HKCU:\Software\BeSharp.net\Test" ^| Select * -Exclude PS*:

Foo : Bar
Bar : Foo
1   : PSPath
2   : PSParentPath
3   : PSChildName
4   : PSDrive
5   : PSProvider

So: skip PS* values like PSPath, PSParentPath, PSChildName, PSDrive and PSProvider (are there more?) when they are not in the registry, but include them when they are in the registry.

Bonus: Only list the names (not the values).

Body:
I know this is truly old, but here's a function I added to my Profile to facilitate registry exploration:

Function Get-KeyProperty  {
Param(
    [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
    [ValidateScript( {(Resolve-Path $_).Provider.Name -Like 'Registry'} )]
    [String[]]
    $Path,
    [String[]]
    $Name=@("*")
)
Process {
    $Name.ForEach({ (Get-Item $Path).Property -like $_}).ForEach({
        Begin {$Hash = @{}}
        Process { $Hash += @{ $_ = (Get-Item $Path).GetValue($_)} }
        End {[PSCustomObject]$Hash}
    })
}}

Examples:

PS C:\> set-alias gkp Get-KeyProperty
>>
>> $USF = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\'
>>
>> $TestPSNames = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\DummyWithPSNames\'
>>
PS C:\> gkp $TestPSNames
Hello PSPath
----- ------
World Not the real PS Path

PS C:\>>gkp $USF -Name p*,S*

Start Menu : C:\Users\keith\AppData\Roaming\Microsoft\Windows\Start Menu
SendTo     : C:\Users\keith\AppData\Roaming\Microsoft\Windows\SendTo
Startup    : C:\Users\keith\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
PrintHood  : C:\Users\keith\AppData\Roaming\Microsoft\Windows\Printer Shortcuts
Personal   : C:\Users\keith\Documents
Programs   : C:\Users\keith\AppData\Roaming\Microsoft\Windows\Start Menu\Programs

PS C:\>>$USF, $TestPSNames | gkp -Name S*,PS*,H* | fl

SendTo     : C:\Users\keith\AppData\Roaming\Microsoft\Windows\SendTo
Startup    : C:\Users\keith\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Start Menu : C:\Users\keith\AppData\Roaming\Microsoft\Windows\Start Menu
History    : C:\Users\keith\AppData\Local\Microsoft\Windows\History

PSPath : Not the real PS Path
Hello  : World


问:
Is there a way to disable MotionLayout visiblity changes animation?
In my MotionScene I have transition which lasts for several seconds. In ConstraintSet I have a view that is invisible that I want to make visible when the transition is done. But I don't want to animate the view going from Visibility.GONE to Visibility.VISIBLE. Is there a way to stop that?

If needed I can provide code, but it's not that complex. It's just a transition with two ConstraintSet-s, this View is in both sets in starting set it's visibility="visible", and in ending set it's visibility = "gone"

Does anybody have any suggestions?

EDIT: I should note that I did put
    android:animateLayoutChanges="false" in root layout of the activity that uses this MotionScene.

答:
If i understand your problem, you can use alpha animation like this;</p>

```<code>AlphaAnimation animation1 = new AlphaAnimation(1f, 0.3f);
animation1.setDuration(1000);
animation1.setFillAfter(true);
yourView.startAnimation(animation1);
</code>```

Body:
If i understand your problem, you can use alpha animation like this;

AlphaAnimation animation1 = new AlphaAnimation(1f, 0.3f);
animation1.setDuration(1000);
animation1.setFillAfter(true);
yourView.startAnimation(animation1);


问:
Problem when trying to overwrite the row color with a custom class with Bootstrap 3
I am trying to apply custom colors on a bootstrap vue table.

I'd like to apply a custom color to the row with the inactive class.

This is what I've tried so far but without any success (this code is within a VueJS component):

```<code><style scoped>
    table tbody tr td {
        padding: 20px;
    }
    .inactive{
        background: #038a0a !important;
    }
</style>
</code>```

Thanks for the help guys !

答:
Seems like its working fine when i try it with Bootstrap

new Vue({
  el: '#app',

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code><style scoped>
    table tbody tr td {
        padding: 120px;
        background-color:"red"
    }
    .inactive{
        background: #038a0a !important;
    }
</style></code>```

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

      #
      First
      Last
      Handle

      1
      Mark
      Otto
      @mdo

      2
      Jacob
      Thornton
      @fat

      3
      Larry
      the Bird
      @twitter

```

Body:
I am trying to apply custom colors on a bootstrap vue table.

I'd like to apply a custom color to the row with the inactive class.

This is what I've tried so far but without any success (this code is within a VueJS component):

Thanks for the help guys !

Body:
Seems like its working fine when i try it with Bootstrap

new Vue({
  el: '#app',

})

<style scoped>
    table tbody tr td {
        padding: 120px;
        background-color:"red"
    }
    .inactive{
        background: #038a0a !important;
    }
</style>

<script src="https://unpkg.com/vue"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

<div id="app">
  <table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">First</th>
      <th scope="col">Last</th>
      <th scope="col">Handle</th>
    </tr>
  </thead>
  <tbody>
    <tr class="inactive">
      <th scope="row">1</th>
      <td>Mark</td>
      <td>Otto</td>
      <td>@mdo</td>
    </tr>
    <tr>
      <th scope="row">2</th>
      <td>Jacob</td>
      <td>Thornton</td>
      <td>@fat</td>
    </tr>
    <tr>
      <th scope="row">3</th>
      <td>Larry</td>
      <td>the Bird</td>
      <td>@twitter</td>
    </tr>
  </tbody>
</table>
</div>


问:
How to connect Flask API endpoints to React app
I have an API made on Flask that has several endpoints. I am trying to use data from these end points to display a chart on my front end that shows the data to the user.

The following are my exact requirements:

Implement one or more types of charts that can be used to effectively visualize data supplied from the API endpoints. Users should be able to pick different metrics to visualize and compare with others.

My Flask API:

```<code>import os
from flask import Flask, jsonify, session, request
import sqlalchemy
import time
from functools import wraps

# web app
app = Flask(__name__)
app.secret_key = 'super_secure_key_that_should_be_in_.env'

# database engine
engine = sqlalchemy.create_engine(os.getenv('SQL_URI'))

def rate_limit(**limit_kwargs):
    def decorator(function):
        @wraps(function)
        def wrapper(*args, **kwargs):
            limit = limit_kwargs['limit'] if 'limit' in limit_kwargs else 5
            seconds = limit_kwargs['window'] if 'window' in limit_kwargs else 60
            session_key = 'rate_limit_' + str(request.url_rule)
            if session_key not in session:
                session[session_key] = []

            window: list = session[session_key]
            if len(window) < limit:
                window.append(int(time.time()))
                session[session_key] = window
                return function(*args, **kwargs)

            if time.time() - window[0] < seconds:
                return jsonify(error='Rate limit exceeded'), 429

            window.pop(0)
            window.append(int(time.time()))
            session[session_key] = window
            return function(*args, **kwargs)
        return wrapper
    return decorator

@app.route('/')
@rate_limit()
def index():
    return 'Welcome '

@app.route('/events/hourly')
@rate_limit(limit=3, window=20)
def events_hourly():
    return queryHelper('''
        SELECT date, hour, events
        FROM public.hourly_events
        ORDER BY date, hour
        LIMIT 168;
    ''')

@app.route('/events/daily')
@rate_limit(limit=2)
def events_daily():
    return queryHelper('''
        SELECT date, SUM(events) AS events
        FROM public.hourly_events
        GROUP BY date
        ORDER BY date
        LIMIT 7;
    ''')

@app.route('/stats/hourly')
@rate_limit(limit=3, window=20)
def stats_hourly():
    return queryHelper('''
        SELECT date, hour, impressions, clicks, revenue
        FROM public.hourly_stats
        ORDER BY date, hour
        LIMIT 168;
    ''')

@app.route('/stats/daily')
@rate_limit(limit=2)
def stats_daily():
    return queryHelper('''
        SELECT date,
            SUM(impressions) AS impressions,
            SUM(clicks) AS clicks,
            SUM(revenue) AS revenue
        FROM public.hourly_stats
        GROUP BY date
        ORDER BY date
        LIMIT 7;
    ''')

@app.route('/poi')
@rate_limit(limit=3)
def poi():
    return queryHelper('''
        SELECT *
        FROM public.poi;
    ''')

def queryHelper(query):
    with engine.connect() as conn:
        result = conn.execute(query).fetchall()
        return jsonify([dict(row.items()) for row in result])
</code>```

My React App.js:

```<code>import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';

import DailyEvents from "./Components/DailyEvents";

class App extends Component {
    render() {
        return (
            <div className="App">
                <header className= "App-header">
                    <img src={logo} className="App-logo" alt="logo" />
                    <h1 className="App-title"> Welcome to React</h1>
                </header>
                <DailyEvents />
            </div>
        );
    }
}

export default App;
</code>```

My Components/DailyEvents.js:

```<code>import React, { Component } from 'react';
import axios from 'axios';

class App extends Component {
  state = {
    dates: []
  }
    componentDidMount() {
    axios.get('api_url_or_localhost/events/daily')
    .then(res => res.json())
    .then((data) => {
      this.setState({ dates: data })
    })
    .catch(console.log)
  }
}

export default App;
</code>```

I keep getting a TypeError that instance.render is not a function.

What I am trying to do is use my Flask API endpoints to visualize the data on the front-end.

答:
try using axios  :
https://alligator.io/react/axios-react/

it should look like this :

axios.get('put the query address')
      .then(response => {
        process your response
      })```

Body:
I have an API made on Flask that has several endpoints. I am trying to use data from these end points to display a chart on my front end that shows the data to the user.

The following are my exact requirements:

Implement one or more types of charts that can be used to effectively visualize data supplied from the API endpoints. Users should be able to pick different metrics to visualize and compare with others.

My Flask API:

import os
from flask import Flask, jsonify, session, request
import sqlalchemy
import time
from functools import wraps

# web app
app = Flask(__name__)
app.secret_key = 'super_secure_key_that_should_be_in_.env'

# database engine
engine = sqlalchemy.create_engine(os.getenv('SQL_URI'))

def rate_limit(**limit_kwargs):
    def decorator(function):
        @wraps(function)
        def wrapper(*args, **kwargs):
            limit = limit_kwargs['limit'] if 'limit' in limit_kwargs else 5
            seconds = limit_kwargs['window'] if 'window' in limit_kwargs else 60
            session_key = 'rate_limit_' + str(request.url_rule)
            if session_key not in session:
                session[session_key] = []

            window: list = session[session_key]
            if len(window) < limit:
                window.append(int(time.time()))
                session[session_key] = window
                return function(*args, **kwargs)

            if time.time() - window[0] < seconds:
                return jsonify(error='Rate limit exceeded'), 429

            window.pop(0)
            window.append(int(time.time()))
            session[session_key] = window
            return function(*args, **kwargs)
        return wrapper
    return decorator

@app.route('/')
@rate_limit()
def index():
    return 'Welcome '

@app.route('/events/hourly')
@rate_limit(limit=3, window=20)
def events_hourly():
    return queryHelper('''
        SELECT date, hour, events
        FROM public.hourly_events
        ORDER BY date, hour
        LIMIT 168;
    ''')

@app.route('/events/daily')
@rate_limit(limit=2)
def events_daily():
    return queryHelper('''
        SELECT date, SUM(events) AS events
        FROM public.hourly_events
        GROUP BY date
        ORDER BY date
        LIMIT 7;
    ''')

@app.route('/stats/hourly')
@rate_limit(limit=3, window=20)
def stats_hourly():
    return queryHelper('''
        SELECT date, hour, impressions, clicks, revenue
        FROM public.hourly_stats
        ORDER BY date, hour
        LIMIT 168;
    ''')

@app.route('/stats/daily')
@rate_limit(limit=2)
def stats_daily():
    return queryHelper('''
        SELECT date,
            SUM(impressions) AS impressions,
            SUM(clicks) AS clicks,
            SUM(revenue) AS revenue
        FROM public.hourly_stats
        GROUP BY date
        ORDER BY date
        LIMIT 7;
    ''')

@app.route('/poi')
@rate_limit(limit=3)
def poi():
    return queryHelper('''
        SELECT *
        FROM public.poi;
    ''')

def queryHelper(query):
    with engine.connect() as conn:
        result = conn.execute(query).fetchall()
        return jsonify([dict(row.items()) for row in result])

My React App.js:

import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';

import DailyEvents from "./Components/DailyEvents";

class App extends Component {
    render() {
        return (

 Welcome to React

                <DailyEvents />

        );
    }
}

export default App;

My Components/DailyEvents.js:

import React, { Component } from 'react';
import axios from 'axios';

class App extends Component {
  state = {
    dates: []
  }
    componentDidMount() {
    axios.get('api_url_or_localhost/events/daily')
    .then(res => res.json())
    .then((data) => {
      this.setState({ dates: data })
    })
    .catch(console.log)
  }
}

export default App;

I keep getting a TypeError that instance.render is not a function.

What I am trying to do is use my Flask API endpoints to visualize the data on the front-end.


问:
Unable to turn factor into numeric
I took in an open access data, but I'm unable to convert column 5 to 50 to numeric.

```<code>file_url <- "https://genelab-data.ndc.nasa.gov/genelab/static/media/dataset/GLDS-138_metabolomics_mx%20367428_NASA_bacteria%20cells_09-2017_submit%20.csv?version=1"
dst1 = 'GLDS-138_metabolomics_mx 367428_NASA_bacteria cells_09-2017_submit.csv'
download.file(file_url, dst1)
Bdata <- read.csv(dst1, stringsAsFactors = FALSE)

Bdata <- t(Bdata)
Bdata <- Bdata[-c(2:7, 114:118),]
Bdata <- Bdata[,-c(1,2,6,8)]
Bdata[1,1:4] <- Bdata[2,1:4]
Bdata <- Bdata[-c(2),]

columnName <- Bdata[1,]
rowName    <- Bdata[,1]
colnames(Bdata) <- columnName
rownames(Bdata) <- rowName
Bdata <- Bdata[-1 ,]
Bdata <- as.data.frame(Bdata)

Bdata[,5:50] <- as.numeric(as.character(Bdata[,5:50]))
</code>```

I've tried numerous method, most of which either coerces NAs or changes the information.

Anyone know how to solve this?

答:
You can try the following code</p>

```<code>Bdata[,5:50]<- `class<-`(as.matrix(Bdata[,5:50]),"numeric")
</code>```

Title: Unable to turn factor into numeric

Body:
I took in an open access data, but I'm unable to convert column 5 to 50 to numeric.

file_url <- "https://genelab-data.ndc.nasa.gov/genelab/static/media/dataset/GLDS-138_metabolomics_mx%20367428_NASA_bacteria%20cells_09-2017_submit%20.csv?version=1"
dst1 = 'GLDS-138_metabolomics_mx 367428_NASA_bacteria cells_09-2017_submit.csv'
download.file(file_url, dst1)
Bdata <- read.csv(dst1, stringsAsFactors = FALSE)

Bdata <- t(Bdata)
Bdata <- Bdata[-c(2:7, 114:118),]
Bdata <- Bdata[,-c(1,2,6,8)]
Bdata[1,1:4] <- Bdata[2,1:4]
Bdata <- Bdata[-c(2),]

columnName <- Bdata[1,]
rowName    <- Bdata[,1]
colnames(Bdata) <- columnName
rownames(Bdata) <- rowName
Bdata <- Bdata[-1 ,]
Bdata <- as.data.frame(Bdata)

Bdata[,5:50] <- as.numeric(as.character(Bdata[,5:50]))

I've tried numerous method, most of which either coerces NAs or changes the information.

Anyone know how to solve this?

Body:
You can try the following code

Bdata[,5:50]<- `class<-`(as.matrix(Bdata[,5:50]),"numeric")


问:
How do I get Bootstrap popovers to work in FullCalendar 4?
I'm using Google calendar data in FullCalendar 4 and everything is displaying fine, but I'm having trouble figuring out how to use bootstrap popovers for events on hover. I've tried a bunch of different things I found online, but it all either throws JSON errors or does nothing at all (probably because most of it is for previous versions).

```<code>        var calendarEl = document.getElementById('calendar');

        var calendar = new FullCalendar.Calendar(calendarEl, {
            plugins: [ 'dayGrid', 'timeGrid', 'list', 'bootstrap', 'googleCalendar' ],
            themeSystem: 'bootstrap',
            googleCalendarApiKey: 'xxxxxxx',

            events: {
                googleCalendarId: 'xxxxxxx'
            },

            eventRender: function(event, element) {
                $(element).popover({
                    title: event.title,
                    placement:'top',
                    html:true,
                    trigger : 'hover',
                    animation : 'false',
                    content: event.description,
                    container:'body'
                }).popover('show');
            },

            height: 650,
            header: {
                left: 'title',
                center: '',
                right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek prevYear,prev,next,nextYear'
            }
        });

        calendar.render();
</code>```

This particular eventRender function doesn't throw any errors, but it doesn't do anything either. The only thing happening on mouseover is the addition of fc-allow-mouse-resize to the anchor tag in the particular event. What am I missing?

SOLUTION (removed event.description from popover content)

```<code>            var calendarEl = document.getElementById('calendar');

            var calendar = new FullCalendar.Calendar(calendarEl, {
                plugins: [ 'dayGrid', 'timeGrid', 'list', 'bootstrap', 'googleCalendar'],
                themeSystem: 'bootstrap',
                googleCalendarApiKey: 'xxxxxxx',

                events: {
                    googleCalendarId: 'xxxxxxx'
                },

                eventRender: function(info) {
                    var start = info.event.start;
                    var end = info.event.end;
                    var startTime;
                    var endTime;

                    if (!start) {
                        startTime = '';
                    } else {
                        startTime = start;
                    }

                    if (!end) {
                        endDate = '';
                    } else {
                        endTime = end;
                    }

                    var title = info.event.title;
                    var location = "at " + info.event.extendedProps.location;
                    if (!info.event.extendedProps.location) {
                        location = '';
                    }

                    $(info.el).popover({
                        title: title,
                        placement:'top',
                        trigger : 'hover',
                        content: startTime + " to " + endTime + " " + location,
                        container:'body'
                    }).popover('show');
                },

                eventClick: function(info) {
                    info.jsEvent.preventDefault(); // don't let the browser navigate
                    if (info.event.url) {
                        window.open(info.event.url);
                    }
                },

                height: 650,
                header: {
                    left: 'title',
                    center: '',
                    right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek prevYear,prev,next,nextYear'
                }
            });

            calendar.render();
</code>```

答:
I had same problem and this worked like charm. Thanks.

Just a small add: endDate should be endTime in the code part below

```<code>if (!end) {
    endDate = '';
} else {
    endTime = end;
}
</code>```

Btw I found it easier to write it as:

```<code>var endTime  = (!end) ? '' : end;
</code>```

I would like to add something for Date Format. Maybe somebody can find it useful.
I used:

```<code>var end = info.event.end.toLocaleString('fr-FR');
</code>```

even more specialized:

```<code>var end = info.event.end.toLocaleString('fr-FR',{
                day: '2-digit',
                month: 'short',
                hour: '2-digit',
                minute: '2-digit'
            });
</code>```

Body:
I'm using Google calendar data in FullCalendar 4 and everything is displaying fine, but I'm having trouble figuring out how to use bootstrap popovers for events on hover. I've tried a bunch of different things I found online, but it all either throws JSON errors or does nothing at all (probably because most of it is for previous versions).

        var calendarEl = document.getElementById('calendar');

        var calendar = new FullCalendar.Calendar(calendarEl, {
            plugins: [ 'dayGrid', 'timeGrid', 'list', 'bootstrap', 'googleCalendar' ],
            themeSystem: 'bootstrap',
            googleCalendarApiKey: 'xxxxxxx',

            events: {
                googleCalendarId: 'xxxxxxx'
            },

            eventRender: function(event, element) {
                $(element).popover({
                    title: event.title,
                    placement:'top',
                    html:true,
                    trigger : 'hover',
                    animation : 'false',
                    content: event.description,
                    container:'body'
                }).popover('show');
            },

            height: 650,
            header: {
                left: 'title',
                center: '',
                right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek prevYear,prev,next,nextYear'
            }
        });

        calendar.render();

This particular eventRender function doesn't throw any errors, but it doesn't do anything either. The only thing happening on mouseover is the addition of fc-allow-mouse-resize to the anchor tag in the particular event. What am I missing?

SOLUTION (removed event.description from popover content)

            var calendarEl = document.getElementById('calendar');

            var calendar = new FullCalendar.Calendar(calendarEl, {
                plugins: [ 'dayGrid', 'timeGrid', 'list', 'bootstrap', 'googleCalendar'],
                themeSystem: 'bootstrap',
                googleCalendarApiKey: 'xxxxxxx',

                events: {
                    googleCalendarId: 'xxxxxxx'
                },

                eventRender: function(info) {
                    var start = info.event.start;
                    var end = info.event.end;
                    var startTime;
                    var endTime;

                    if (!start) {
                        startTime = '';
                    } else {
                        startTime = start;
                    }

                    if (!end) {
                        endDate = '';
                    } else {
                        endTime = end;
                    }

                    var title = info.event.title;
                    var location = "at " + info.event.extendedProps.location;
                    if (!info.event.extendedProps.location) {
                        location = '';
                    }

                    $(info.el).popover({
                        title: title,
                        placement:'top',
                        trigger : 'hover',
                        content: startTime + " to " + endTime + " " + location,
                        container:'body'
                    }).popover('show');
                },

                eventClick: function(info) {
                    info.jsEvent.preventDefault(); // don't let the browser navigate
                    if (info.event.url) {
                        window.open(info.event.url);
                    }
                },

                height: 650,
                header: {
                    left: 'title',
                    center: '',
                    right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek prevYear,prev,next,nextYear'
                }
            });

            calendar.render();

Body:
I had same problem and this worked like charm. Thanks.

Just a small add: endDate should be endTime in the code part below

if (!end) {
    endDate = '';
} else {
    endTime = end;
}

Btw I found it easier to write it as:

var endTime  = (!end) ? '' : end;

I would like to add something for Date Format. Maybe somebody can find it useful.
I used:

var end = info.event.end.toLocaleString('fr-FR');

even more specialized:

var end = info.event.end.toLocaleString('fr-FR',{
                day: '2-digit',
                month: 'short',
                hour: '2-digit',
                minute: '2-digit'
            });


问:
Searching through keys dictionary
How can i search through a bunch of keys in a Dictionary with a for loop or something like it and see if there is any key with the same first three string values as another string. the following example isnt Code at all but it is basicly the result i whant. </p>

```<code>Key1(3932030)
Key2(4201230)
Key3(5209872)

ArrayWithKeys(3930000,4200000,5200000)

Dictionary searchForkeys(ArrayWithKeys[i])

keyFound(3932030)
</code>```

答:
First, Get substring to search and then use it to find keys inside dictionary object.

string[] keyArray = new string[]{ "3930000", "4200000" , "5200000"};

string substringToSearch ;

foreach(string inputKey in keyArray)
{
    substringToSearch = inputKey.Length >= 3 ? inputKey.Substring(0, 3) : inputKey;

    if(dictionaryObject.Keys.Any(x => x.StartsWith(substringToSearch)))
    {
        // below is the key matched with inputKey
        dictionaryObject.Where(x => x.Key.StartsWith(substringToSearch)).First().Value;
    }
}
```

<p><strong>EDIT</strong><br>
Using only for loop</p>

<pre class="lang-cs prettyprint-override"><code>string substringToSearch = inputKey.Length >= 3 ? inputKey.Substring(0, 3) : inputKey;

for(int i; i < dictionaryObject.Keys.Count; i++)
{
    if( dictionaryObject.ElementAt(i).Key.StartsWith(substringToSearch) )
    {
        // key matched with inputKey
        // below is key
        string keyStr = dictionaryObject.ElementAt(i).Key;
    }
}
</code>```

Title: Searching through keys dictionary

Body:
How can i search through a bunch of keys in a Dictionary with a for loop or something like it and see if there is any key with the same first three string values as another string. the following example isnt Code at all but it is basicly the result i whant.

Key1(3932030)
Key2(4201230)
Key3(5209872)

ArrayWithKeys(3930000,4200000,5200000)

Dictionary searchForkeys(ArrayWithKeys[i])

keyFound(3932030)

Body:
First, Get substring to search and then use it to find keys inside dictionary object.

string[] keyArray = new string[]{ "3930000", "4200000" , "5200000"};

string substringToSearch ;

foreach(string inputKey in keyArray)
{
    substringToSearch = inputKey.Length >= 3 ? inputKey.Substring(0, 3) : inputKey;

    if(dictionaryObject.Keys.Any(x => x.StartsWith(substringToSearch)))
    {
        // below is the key matched with inputKey
        dictionaryObject.Where(x => x.Key.StartsWith(substringToSearch)).First().Value;
    }
}

EDIT

Using only for loop

string substringToSearch = inputKey.Length >= 3 ? inputKey.Substring(0, 3) : inputKey;

for(int i; i < dictionaryObject.Keys.Count; i++)
{
    if( dictionaryObject.ElementAt(i).Key.StartsWith(substringToSearch) )
    {
        // key matched with inputKey
        // below is key
        string keyStr = dictionaryObject.ElementAt(i).Key;
    }
}


问:
OUTER/CROSS APPLY Subquery without FROM clause
Most online documentation or tutorials discussing OUTER|CROSS APPLY describe something like:

```<code>SELECT columns
FROM table OUTER|CROSS APPLY (SELECT … FROM …);
</code>```

The subquery is normally a full SELECT … FROM … query.

I must have read somewhere that the subquery doesn’t need a FROM  in which case the columns appear to come from the main query:

```<code>SELECT columns
FROM table OUTER|CROSS APPLY (SELECT … );
</code>```

because I have used it routinely as a method to pre-calculate columns.

The question is what is really happening if the FROM is omitted from the sub query? Is it short for something else? I found that it does not mean the same as from the main table.

I have a sample here: http://sqlfiddle.com/#!18/0188f7/4/1

答:
First consider

```<code>SELECT o.name, o.type
FROM sys.objects o
</code>```

Now consider

```<code>SELECT o.name, (SELECT o.type) AS type
FROM sys.objects o
</code>```

A SELECT without a FROM is as though selecting from an imaginary single row table. The above doesn't change the results the scalar subquery just acts as a correlated sub query and uses the value from the outer query.

APPLY behaves in the same way. References to columns from the outer query are just passed in as correlated parameters. So this is the same as

```<code>SELECT o.name, ca.type
FROM sys.objects o
CROSS APPLY (SELECT o.type) AS ca
</code>```

But APPLY in general is more capable than a scalar subquery in the SELECT (in that it can act to expand a row out or remove rows from the result)

Body:
Most online documentation or tutorials discussing OUTER|CROSS APPLY describe something like:

SELECT columns
FROM table OUTER|CROSS APPLY (SELECT … FROM …);

The subquery is normally a full SELECT … FROM … query.

I must have read somewhere that the subquery doesn’t need a FROM  in which case the columns appear to come from the main query:

SELECT columns
FROM table OUTER|CROSS APPLY (SELECT … );

because I have used it routinely as a method to pre-calculate columns.

The question is what is really happening if the FROM is omitted from the sub query? Is it short for something else? I found that it does not mean the same as from the main table.

I have a sample here: http://sqlfiddle.com/#!18/0188f7/4/1

Body:
First consider

SELECT o.name, o.type
FROM sys.objects o

Now consider

SELECT o.name, (SELECT o.type) AS type
FROM sys.objects o

A SELECT without a FROM is as though selecting from an imaginary single row table. The above doesn't change the results the scalar subquery just acts as a correlated sub query and uses the value from the outer query.

APPLY behaves in the same way. References to columns from the outer query are just passed in as correlated parameters. So this is the same as

SELECT o.name, ca.type
FROM sys.objects o
CROSS APPLY (SELECT o.type) AS ca

But APPLY in general is more capable than a scalar subquery in the SELECT (in that it can act to expand a row out or remove rows from the result)


问:
How to active number between 2 dates
I have the following schema:

```<code>name | hire_date                   | last_date                   | active
n1   | January 20, 2018, 12:00 AM  |                             | true
n2   | October 1, 2018, 12:00 AM   | February 18, 2020, 12:00 AM | false
n3   | October 15, 2018, 12:00 AM  |                             | true
n4   | January 12 2019, 12:00 AM   |                             | true
n5   | February 12, 2019, 12:00 AM |                             | true
n6   | December 12, 2019, 12:00 AM | January 15, 2020, 12:00 AM  | false
n7   | February 17, 2020, 12:00 AM |                             | true
</code>```

I need to extract the monthly count of the total number of active employees.

I am trying it with join the table with itself, and get a count of rows, but not sure how to proceed:

```<code>select
-- ot1.name, ot2.name, ot1.hire_date, ot2.hire_date, ot1.last_date, ot2.last_date,
date_trunc('month', ot1.hire_date) AS hire_dates, count(ot1.hire_date)
from ops_teammates ot1
 join ops_teammates ot2 ON ot1.hire_date >= ot2.hire_date
 group by hire_dates
order by ot1.hire_date, ot2.hire_date;
</code>```

How can I get the count like

```<code>Jan 2018, 1
Oct 2018, 3
Jan 2019, 4
Feb 2019, 5
Dec 2019, 6
Jan 2020, 5
Feb 2020, 5
</code>```

答:
You could use union all and aggregation::

```<code>select month_start, sum(cnt),
       sum(sum(cnt)) over (order by month_start) as running_cnt
from (
    select 1 cnt, date_trunc('month', hire_date) month_start from ops_teammates
    union all
    select -1, date_trunc('month', last_date) + interval '1 month' from ops_teammates  where last_date is not null
)
group by month_start
order by month_start
</code>```

Title: How to active number between 2 dates

Body:
I have the following schema:

name | hire_date                   | last_date                   | active
n1   | January 20, 2018, 12:00 AM  |                             | true
n2   | October 1, 2018, 12:00 AM   | February 18, 2020, 12:00 AM | false
n3   | October 15, 2018, 12:00 AM  |                             | true
n4   | January 12 2019, 12:00 AM   |                             | true
n5   | February 12, 2019, 12:00 AM |                             | true
n6   | December 12, 2019, 12:00 AM | January 15, 2020, 12:00 AM  | false
n7   | February 17, 2020, 12:00 AM |                             | true

I need to extract the monthly count of the total number of active employees.

I am trying it with join the table with itself, and get a count of rows, but not sure how to proceed:

select
-- ot1.name, ot2.name, ot1.hire_date, ot2.hire_date, ot1.last_date, ot2.last_date,
date_trunc('month', ot1.hire_date) AS hire_dates, count(ot1.hire_date)
from ops_teammates ot1
 join ops_teammates ot2 ON ot1.hire_date >= ot2.hire_date
 group by hire_dates
order by ot1.hire_date, ot2.hire_date;

How can I get the count like

Jan 2018, 1
Oct 2018, 3
Jan 2019, 4
Feb 2019, 5
Dec 2019, 6
Jan 2020, 5
Feb 2020, 5

Body:
You could use union all and aggregation::

select month_start, sum(cnt),
       sum(sum(cnt)) over (order by month_start) as running_cnt
from (
    select 1 cnt, date_trunc('month', hire_date) month_start from ops_teammates
    union all
    select -1, date_trunc('month', last_date) + interval '1 month' from ops_teammates  where last_date is not null
)
group by month_start
order by month_start


问:
Tensorflow Lite GPU support for python
Anyone know if Tensorflow Lite has GPU support for Python? I've seen guides for Android and iOS, but I haven't come across anything about Python. If tensorflow-gpu is installed and tensorflow.lite.python.interpreter is imported, will GPU be used automatically?

答: According to this thread, it is not.</p>

Title: Tensorflow Lite GPU support for python

Body: According to this thread, it is not.


问:
How to upload files to a Django Model that are created on the fly?
Here's an example:

Suppose a user, let's say 'Avi' is using my web app. Avi uploads a file (say and .xls/.xlsx) to my web app. I use django-storages to upload the files to either S3 or Azure. The problem arises when I create a dataframe from the uploaded file. When I export the dataframe, it does not get uploaded but rather gets exported to the location of the project.

Current Solution:
I use azure, boto3 api for converting the dataframe to a stream of bytes and then uploading to the corresponding container or s3 bucket.

Is there a easier way where I could pass the newly created dataframe through a serializer so it gets uploaded to the respective location?

答:
After some digging and searching all over the internet. I've found a better solution to the existing one. I'll try to put down a detailed snippet!
Using SimpleUploadedFile which is a part of django.core.files.uploadedfile solves most of the problem and makes the code much easier to read.

Here's a snippet:

```<code># Other imports
from django.core.files.uploadedfile import SimpleUploadedFile
import pandas as pd
import io

df = pd.DataFrame()
# Do something with dataframe
# After processing the dataframe do the following
output_stream = io.BytesIO()
df.to_excel(output_stream, index=False)
output_file = SimpleUploadedFile('sample.xlsx', output_stream.getvalue())
data = { 'record_type': 'OUTPUT_FILE', 'record':output_file }
record_serializer = RecordSerializer(data=data)
if record_serializer.is_valid():
    record_serializer.save()
    # Display data from the serializer/ Return serialized data
else:
    # Return an exception or error from the serializer
</code>```

Do let me know if it works for any of you who've tried this.
Also, since you're passing the file as a param to the serialzer, no matter if you're using default local storage or configures S3, Azure etc using django-storages, the file will be uploaded to your corresponding location without the hassle of calling the API to upload files created by python/django every now and then.

Body:
After some digging and searching all over the internet. I've found a better solution to the existing one. I'll try to put down a detailed snippet!
Using SimpleUploadedFile which is a part of django.core.files.uploadedfile solves most of the problem and makes the code much easier to read.

Here's a snippet:

# Other imports
from django.core.files.uploadedfile import SimpleUploadedFile
import pandas as pd
import io

df = pd.DataFrame()
# Do something with dataframe
# After processing the dataframe do the following
output_stream = io.BytesIO()
df.to_excel(output_stream, index=False)
output_file = SimpleUploadedFile('sample.xlsx', output_stream.getvalue())
data = { 'record_type': 'OUTPUT_FILE', 'record':output_file }
record_serializer = RecordSerializer(data=data)
if record_serializer.is_valid():
    record_serializer.save()
    # Display data from the serializer/ Return serialized data
else:
    # Return an exception or error from the serializer

Do let me know if it works for any of you who've tried this.
Also, since you're passing the file as a param to the serialzer, no matter if you're using default local storage or configures S3, Azure etc using django-storages, the file will be uploaded to your corresponding location without the hassle of calling the API to upload files created by python/django every now and then.


问:
Endless replicaset connection error with spring data support and mongodb
I'm working in a apps where I'm using mongodb with replicaset.

In my replicaset I've 2 db servers and 1 arbiter. I'm creating my mongo object as follows

```<code>List<ServerAddress> servers = new ArrayList<ServerAddress>();
servers.add( new ServerAddress( "192.168.1.42", 27017 ) );
servers.add( new ServerAddress( "192.168.1.187", 27017 ) );
servers.add( new ServerAddress( "192.168.1.189", 27017 ) ); //Arbiter

MongoOptions mongoOptions = new MongoOptions();
mongoOptions.autoConnectRetry = true;
mongo = new Mongo(servers, mongoOptions);
mongo.slaveOk();
</code>```

When all the servers are up then there are no problems but when any one of the server goes down the system starts to through endless error messages as shown below

```<code>May 17, 2011 11:24:19 AM com.mongodb.ReplicaSetStatus$Node update
SEVERE: can't update node: 192.168.1.42:27017
java.io.IOException: couldn't connect to [/192.168.1.42:27017] bc:java.net.ConnectException: Connection refused: connect
    at com.mongodb.DBPort._open(DBPort.java:206)
    at com.mongodb.DBPort.go(DBPort.java:94)
    at com.mongodb.DBPort.go(DBPort.java:75)
    at com.mongodb.DBPort.findOne(DBPort.java:129)
    at com.mongodb.DBPort.runCommand(DBPort.java:138)
    at com.mongodb.ReplicaSetStatus$Node.update(ReplicaSetStatus.java:149)
    at com.mongodb.ReplicaSetStatus.updateAll(ReplicaSetStatus.java:314)
    at com.mongodb.ReplicaSetStatus$Updater.run(ReplicaSetStatus.java:263)
</code>```

Can you help me to resolve this?

Since I'm using a replica set, if one server is down isn't suppose to use the new primary and ignore the older primary?

Please find the below images to check the replica set status

All servers up and 192.168.1.42 is the primary server

192.168.1.42 is down(manually teminated) and 192.168.1.187 is the new primary(The errors happens now)

192.168.1.42 is up again and actings as a secondary server(error goes off)

UPDATED:
The database works even if the error messages get logged. Is there a mechanism to reduce/suppress the error messages?

答:
This is a logging issue. It is now a warning, instead of an error.

The 2.6 driver (due out later this week) will be less verbose with logging for this. This is not an error but just a warning that that node is down when the background thread checks on the status of the replicaset members. You can use the current version in master if you want to test now: http://github.com/mongodb/mongo-java-driver

http://github.com/mongodb/mongo-java-driver/commit/ee7543a4f7cc26618cf78eab2a18bd33b3e101cc

Body:
I'm working in a apps where I'm using mongodb with replicaset.

In my replicaset I've 2 db servers and 1 arbiter. I'm creating my mongo object as follows

List<ServerAddress> servers = new ArrayList<ServerAddress>();
servers.add( new ServerAddress( "192.168.1.42", 27017 ) );
servers.add( new ServerAddress( "192.168.1.187", 27017 ) );
servers.add( new ServerAddress( "192.168.1.189", 27017 ) ); //Arbiter

MongoOptions mongoOptions = new MongoOptions();
mongoOptions.autoConnectRetry = true;
mongo = new Mongo(servers, mongoOptions);
mongo.slaveOk();

When all the servers are up then there are no problems but when any one of the server goes down the system starts to through endless error messages as shown below

May 17, 2011 11:24:19 AM com.mongodb.ReplicaSetStatus$Node update
SEVERE: can't update node: 192.168.1.42:27017
java.io.IOException: couldn't connect to [/192.168.1.42:27017] bc:java.net.ConnectException: Connection refused: connect
    at com.mongodb.DBPort._open(DBPort.java:206)
    at com.mongodb.DBPort.go(DBPort.java:94)
    at com.mongodb.DBPort.go(DBPort.java:75)
    at com.mongodb.DBPort.findOne(DBPort.java:129)
    at com.mongodb.DBPort.runCommand(DBPort.java:138)
    at com.mongodb.ReplicaSetStatus$Node.update(ReplicaSetStatus.java:149)
    at com.mongodb.ReplicaSetStatus.updateAll(ReplicaSetStatus.java:314)
    at com.mongodb.ReplicaSetStatus$Updater.run(ReplicaSetStatus.java:263)

Can you help me to resolve this?

Since I'm using a replica set, if one server is down isn't suppose to use the new primary and ignore the older primary?

Please find the below images to check the replica set status

All servers up and 192.168.1.42 is the primary server

192.168.1.42 is down(manually teminated) and 192.168.1.187 is the new primary(The errors happens now)

192.168.1.42 is up again and actings as a secondary server(error goes off)

UPDATED:
The database works even if the error messages get logged. Is there a mechanism to reduce/suppress the error messages?


问:
How to create a gcp instance from a custom image?
In AWS I will create an AMI, copy to other regions and make them all public. My customers can then choose from Community AMIs.

I have been trying to replicate this workflow in GCP and I found that GCP does not have an option of community images. And you cannot make it 'public' either. But you can use gcloud compute images export command to export an image to an external file and upload it to a bucket.

But how to use this to create an instance? I checked console to 'create VM Instance' but it does not have an option to upload or choose from drive. Only public and custom images already in your account.

答:
To share custom image publicly.

Make custom image public using below command

```<code>gcloud compute images add-iam-policy-binding [image-name] \
    --member='allAuthenticatedUsers' \
    --role='roles/compute.imageUser'
</code>```

Get public URL of custom image

```<code>gcloud compute images list --uri | grep [image-name]
</code>```

It will be in https://www.googleapis.com/compute/v1/projects/[project-name]/global/images/[image-name] format

Create VM using public image URL

```<code>gcloud beta compute instances create instance-1 --zone=us-central1-a \
--machine-type=n1-standard-1 --subnet=default \
--image=https://www.googleapis.com/compute/v1/projects/[project-name]/global/images/[image-name] \
--boot-disk-size=10GB --boot-disk-device-name=instance-1
</code>```

For details, gcp manage images here

Body:
To share custom image publicly.

Make custom image public using below command

gcloud compute images add-iam-policy-binding [image-name] \
    --member='allAuthenticatedUsers' \
    --role='roles/compute.imageUser'

Get public URL of custom image

gcloud compute images list --uri | grep [image-name]

It will be in https://www.googleapis.com/compute/v1/projects/[project-name]/global/images/[image-name] format

Create VM using public image URL

gcloud beta compute instances create instance-1 --zone=us-central1-a \
--machine-type=n1-standard-1 --subnet=default \
--image=https://www.googleapis.com/compute/v1/projects/[project-name]/global/images/[image-name] \
--boot-disk-size=10GB --boot-disk-device-name=instance-1

For details, gcp manage images here


问:
How does DiffEqFlux.sciml_train work for Neural ODEs in Julia?
I have a ganeral question about how Neural ODE Nets are trained in Julia. Are data points being sampled from the tspan on which the Nural ODE is defined and on them the parameter updates computed? In other words is there some shuffling and batching happening during training or is the loss computed over all data points in the tspan?</p>

答:
I found an answer about what Julia is doing here: https://github.com/JuliaDiffEq/DiffEqFlux.jl/blob/master/src/train.jl . </p>

```<code>    "Optimizes the `loss(θ,curdata...)` function with respect to the parameter vector
`θ` iterating over the `data`. By default the data iterator is empty, i.e.
`loss(θ)` is used. The first output of the loss function is considered the loss.
Extra outputs are passed to the callback."
</code>```

<p>I think that to do batching one needs to sample datapoints and then run Flux.train on them in a loop, giving as input the batch data points. </p>

Body:
I found an answer about what Julia is doing here: https://github.com/JuliaDiffEq/DiffEqFlux.jl/blob/master/src/train.jl .

    "Optimizes the `loss(θ,curdata...)` function with respect to the parameter vector
`θ` iterating over the `data`. By default the data iterator is empty, i.e.
`loss(θ)` is used. The first output of the loss function is considered the loss.
Extra outputs are passed to the callback."

I think that to do batching one needs to sample datapoints and then run Flux.train on them in a loop, giving as input the batch data points.


问:
Read a variable name in Javascript from Flask
I am passing variable from Flask to JavaScript using the method render_template.

I followed this post: Passing variables from flask to javascript, but it is not working for me

Here is my code:

```<code>@app.route('/')
def index():
    return render_template('index.html')

@app.route('/debug')
def index_debug():
    return render_template('index.html', debug=True)
</code>```

I would like to read it from a JavaScript file. I tried using this method:

this is my html file:

```<code><head>
    <script type="text/javascript">
        var debugMode = {{ debug }};
    </script>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js" crossorigin="anonymous"></script>
    <script src="/static/index.js"></script>
</head>
</code>```

But when i try accessing this variable in my index.js. the variable debugMode  is undefined.

答:
Try this

```<code><head>
 <script type="text/javascript">
    window.debugMode = {{ debug }};
 </script>
 <script src="/static/index.js"></script>
</head>
</code>```

If you want to read a variable from HTML in JS you ought to declare this var in window scope and read in JS file like this.

```<code>const myNewVar = window.debugMode
</code>```

Body:
I am passing variable from Flask to JavaScript using the method render_template.

I followed this post: Passing variables from flask to javascript, but it is not working for me

Here is my code:

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/debug')
def index_debug():
    return render_template('index.html', debug=True)

I would like to read it from a JavaScript file. I tried using this method:

this is my html file:

But when i try accessing this variable in my index.js. the variable debugMode  is undefined.

Body:
Try this

<head>
 <script type="text/javascript">
    window.debugMode = {{ debug }};
 </script>
 <script src="/static/index.js"></script>
</head>

If you want to read a variable from HTML in JS you ought to declare this var in window scope and read in JS file like this.

const myNewVar = window.debugMode


问:
Shinydashboard box() masked by graphics package in Shiny
I am trying to create boxes for my shiny app but I believe the box() function from shinydashboard is being masked by the box() function from graphics package.

Here is a very simple reproduction of my problem with a screenshot of what my box looks like. I've included the packages that I use in my actual shinyapp in case that is important, but they aren't used in this reproduction. I have tried running it with shinydashboard::box() but that didn't work either.

```<code>library(shiny)
library(shinydashboard)
library(flexdashboard)
library(dplyr)

server <- shinyServer(function(input, output){
 })

ui <- shinyUI(
    fluidPage(
        titlePanel("title panel"),
        sidebarLayout(
            sidebarPanel("Sidebar"),
            mainPanel(
                shinydashboard::box(title = "Box Fail.", status = "primary", background = "red")
            )) ))

shinyApp(ui = ui, server = server)

``
[![shiny screenshot][1]][1]

  [1]: https://i.stack.imgur.com/a17d2.png
</code>```

答:
You can use the useShinydashboard() from shinyWidgets package

Description

Allow to use functions from 'shinydashboard' into a
  classic 'shiny' app, specifically valueBox, infoBox and box.

```<code>library(shiny)
library(shinydashboard)
library(flexdashboard)
library(dplyr)
library(shinyWidgets)

server <- shinyServer(function(input, output){})

ui <- shinyUI(
  fluidPage(
    useShinydashboard(),
    titlePanel("title panel"),
    sidebarLayout(
      sidebarPanel("Sidebar"),
      mainPanel(
        shinydashboard::box(title = "Box Fail.", status = "primary", background = "red")
      )) ))

shinyApp(ui = ui, server = server)
</code>```

Body:
I am trying to create boxes for my shiny app but I believe the box() function from shinydashboard is being masked by the box() function from graphics package.

Here is a very simple reproduction of my problem with a screenshot of what my box looks like. I've included the packages that I use in my actual shinyapp in case that is important, but they aren't used in this reproduction. I have tried running it with shinydashboard::box() but that didn't work either.

library(shiny)
library(shinydashboard)
library(flexdashboard)
library(dplyr)

server <- shinyServer(function(input, output){
 })

ui <- shinyUI(
    fluidPage(
        titlePanel("title panel"),
        sidebarLayout(
            sidebarPanel("Sidebar"),
            mainPanel(
                shinydashboard::box(title = "Box Fail.", status = "primary", background = "red")
            )) ))

shinyApp(ui = ui, server = server)

``
[![shiny screenshot][1]][1]

  [1]: https://i.stack.imgur.com/a17d2.png

Body:
You can use the useShinydashboard() from shinyWidgets package

Description

Allow to use functions from 'shinydashboard' into a
  classic 'shiny' app, specifically valueBox, infoBox and box.

library(shiny)
library(shinydashboard)
library(flexdashboard)
library(dplyr)
library(shinyWidgets)

server <- shinyServer(function(input, output){})

ui <- shinyUI(
  fluidPage(
    useShinydashboard(),
    titlePanel("title panel"),
    sidebarLayout(
      sidebarPanel("Sidebar"),
      mainPanel(
        shinydashboard::box(title = "Box Fail.", status = "primary", background = "red")
      )) ))

shinyApp(ui = ui, server = server)


问:
powershell psobject nested with same reference. from json
I'm having difficulty accessing the nested part of a psobject.
I've used

```<code>$response = Invoke-RestMethod
</code>```

to pull back information from an application.
$response then contains a json file.

I've santized the json file but this is the general format.

```<code>Response:{
    "total":  2,
    "items":  [
                  {
                      "id":  1,
                      "name":  "127.0.0.1",
                      "properties":  [
                                               {
                                                   "name":  "var1",
                                                   "value":  "10"
                                               },
                                               {
                                                   "name":  "var2",
                                                   "value":  "20"
                                               },
                                               {
                                                   "name":  "var3",
                                                   "value":  "30"
                                               },
                                               {
                                                   "name":  "var4",
                                                   "value":  "40"
                                               }
                                            ]
                  },
                  {
                      "id":  2,
                      "name":  "10.2.2.2",
                      "properties":  [
                                               {
                                                   "name":  "var1",
                                                   "value":  "100"
                                               },
                                               {
                                                   "name":  "var2",
                                                   "value":  "200"
                                               },
                                               {
                                                   "name":  "var3",
                                                   "value":  "300"
                                               },
                                               {
                                                   "name":  "var4",
                                                   "value":  "400"
                                               },
                                               {
                                                   "name":  "var5",
                                                   "value":  "500"
                                               }
                                            ]
                  },
              ],
    "searchId":  null,
    "isMin":  false
}
</code>```

I can easily access the id and name directly under the items layer using a simple for loop

```<code>for ( $index = 0; $index -lt $data.Items.count; $index++)
{
    $id=$data.Items.id[$index]
    $name=$data.Items.name[$index]
}
</code>```

but i can't find out how to reference the stuff under the properties section.

This is some of the stuff i've tried

```<code>    $var1 = Select-Object -ExpandProperty  $data.Items.properties[$index]
    $var1 = $data.Items.properties[$index] | Select-Object -expand name
    $var1 = $data.Items.properties[$index] | Select -property *
</code>```

Some of it gets close, but only returns one of the name entries and not all.

答:
It is important where you apply the index. Applying the index at the very end of your
expression works in some cases, but not quite in the way, that you might expect.
Lets have a closer look at what you are exactly doing:

```<code>$id = $data.Items.id[0]
</code>```

$data.Items.id returns an array of all ids of all "Items" elements:

```<code>PS> $data.Items.id

1
2
</code>```

With $data.Items.id[0] you address the first element of that array, which is the value
that you want.

Now compare that to the following:

```<code>$id = $data.Items[0].id
</code>```

$data.Items returns an array of all "Items" elements:

```<code>PS> $data.Items

id name      properties
-- ----      ----------
 1 127.0.0.1 {@{name=var1; value=10}, @{name=var2; value=20}, @{name=var3; value=30}, @{name=var4; value=40}}
 2 10.2.2.2  {@{name=var1; value=100}, @{name=var2; value=200}, @{name=var3; value=300}, @{name=var4; value=400....}
</code>```

With $data.Items[0] you address the the first element of the array:

```<code>PS> $data.Items[0]

id name      properties
-- ----      ----------
 1 127.0.0.1 {@{name=var1; value=10}, @{name=var2; value=20}, @{name=var3; value=30}, @{name=var4; value=40}}
</code>```

And with $data.Items[0].id you address the the first element of the array and select only
the content of it`s id-property.

The benefit of addressing a single object first before expanding its properties will be clear once you have properties, that contain more than a single value. Compare the following output:

```<code>PS> $data.Items.properties[0]

name value
---- -----
var1 10
</code>```

```<code>PS> $data.Items[0].properties

name value
---- -----
var1 10
var2 20
var3 30
var4 40
</code>```

As you said in the comments, you would further want to change the value of one particular
property. I suggest you narrow the properties down by using Where-Object:

```<code>PS> $var2 = $data.Items[0].properties | Where-Object Name -eq 'var2'
PS> $var2.value = 25
PS> $data.Items[0].properties

name value
---- -----
var1 10
var2 25   <---
var3 30
var4 40
</code>```

Body:
I'm having difficulty accessing the nested part of a psobject.
I've used

$response = Invoke-RestMethod

to pull back information from an application.
$response then contains a json file.

I've santized the json file but this is the general format.

Response:{
    "total":  2,
    "items":  [
                  {
                      "id":  1,
                      "name":  "127.0.0.1",
                      "properties":  [
                                               {
                                                   "name":  "var1",
                                                   "value":  "10"
                                               },
                                               {
                                                   "name":  "var2",
                                                   "value":  "20"
                                               },
                                               {
                                                   "name":  "var3",
                                                   "value":  "30"
                                               },
                                               {
                                                   "name":  "var4",
                                                   "value":  "40"
                                               }
                                            ]
                  },
                  {
                      "id":  2,
                      "name":  "10.2.2.2",
                      "properties":  [
                                               {
                                                   "name":  "var1",
                                                   "value":  "100"
                                               },
                                               {
                                                   "name":  "var2",
                                                   "value":  "200"
                                               },
                                               {
                                                   "name":  "var3",
                                                   "value":  "300"
                                               },
                                               {
                                                   "name":  "var4",
                                                   "value":  "400"
                                               },
                                               {
                                                   "name":  "var5",
                                                   "value":  "500"
                                               }
                                            ]
                  },
              ],
    "searchId":  null,
    "isMin":  false
}

I can easily access the id and name directly under the items layer using a simple for loop

for ( $index = 0; $index -lt $data.Items.count; $index++)
{
    $id=$data.Items.id[$index]
    $name=$data.Items.name[$index]
}

but i can't find out how to reference the stuff under the properties section.

This is some of the stuff i've tried

    $var1 = Select-Object -ExpandProperty  $data.Items.properties[$index]
    $var1 = $data.Items.properties[$index] | Select-Object -expand name
    $var1 = $data.Items.properties[$index] | Select -property *

Some of it gets close, but only returns one of the name entries and not all.

Body:
It is important where you apply the index. Applying the index at the very end of your
expression works in some cases, but not quite in the way, that you might expect.
Lets have a closer look at what you are exactly doing:

$id = $data.Items.id[0]

$data.Items.id returns an array of all ids of all "Items" elements:

PS> $data.Items.id

1
2

With $data.Items.id[0] you address the first element of that array, which is the value
that you want.

Now compare that to the following:

$id = $data.Items[0].id

$data.Items returns an array of all "Items" elements:

PS> $data.Items

id name      properties
-- ----      ----------
 1 127.0.0.1 {@{name=var1; value=10}, @{name=var2; value=20}, @{name=var3; value=30}, @{name=var4; value=40}}
 2 10.2.2.2  {@{name=var1; value=100}, @{name=var2; value=200}, @{name=var3; value=300}, @{name=var4; value=400....}

With $data.Items[0] you address the the first element of the array:

PS> $data.Items[0]

id name      properties
-- ----      ----------
 1 127.0.0.1 {@{name=var1; value=10}, @{name=var2; value=20}, @{name=var3; value=30}, @{name=var4; value=40}}

And with $data.Items[0].id you address the the first element of the array and select only
the content of it`s id-property.

The benefit of addressing a single object first before expanding its properties will be clear once you have properties, that contain more than a single value. Compare the following output:

PS> $data.Items.properties[0]

name value
---- -----
var1 10

PS> $data.Items[0].properties

name value
---- -----
var1 10
var2 20
var3 30
var4 40

As you said in the comments, you would further want to change the value of one particular
property. I suggest you narrow the properties down by using Where-Object:

PS> $var2 = $data.Items[0].properties | Where-Object Name -eq 'var2'
PS> $var2.value = 25
PS> $data.Items[0].properties

name value
---- -----
var1 10
var2 25   <---
var3 30
var4 40


问:
'-[Page compare:] unrecognized selector sent to instance' in CoreData
EDIT: Page is one of my entities

EIDT2: I'm always running with '-com.apple.CoreData.ConcurrencyDebug 1' and I've got no concurrency issues reported by that

I've stared to see a crash that I have no clue how to solve. I can't find when it was introduced it seems to come from CoreData. And also it's not 100% reproducible.

How can I track it down better? Is it me?

```<code> Fatal Exception: NSInvalidArgumentException
-[Page compare:]: unrecognized selector sent to instance 0x281c640a0
</code>```

With the following stack-trace:

```<code>Fatal Exception: NSInvalidArgumentException
0  CoreFoundation                 0x192cc896c __exceptionPreprocess
1  libobjc.A.dylib                0x1929e1028 objc_exception_throw
2  CoreFoundation                 0x192bc6dcc -[NSOrderedSet initWithSet:copyItems:]
3  CoreFoundation                 0x192ccd048 ___forwarding___
4  CoreFoundation                 0x192ccf3a0 _CF_forwarding_prep_0
5  Foundation                     0x1930afc3c _NSCompareObject
6  CoreData                       0x197670e24 +[NSFetchedResultsController(PrivateMethods) _insertIndexForObject:inArray:lowIdx:highIdx:sortDescriptors:]
7  CoreData                       0x197671034 -[NSFetchedResultsController(PrivateMethods) _updateFetchedObjectsWithInsertChange:]
8  CoreData                       0x19766b73c -[NSFetchedResultsController(PrivateMethods) _updateFetchedObjectsWithInsertedObjects:deletedObjects:updatedObjects:]
9  CoreData                       0x19779829c __82-[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:]_block_invoke
10 CoreData                       0x197757aac developerSubmittedBlockToNSManagedObjectContextPerform
11 CoreData                       0x1976221c4 -[NSManagedObjectContext performBlockAndWait:]
12 CoreData                       0x19762b81c -[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:]
13 Foundation                     0x19309306c __57-[NSNotificationCenter addObserver:selector:name:object:]_block_invoke_2
14 CoreFoundation                 0x192c2099c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__
15 CoreFoundation                 0x192c209ec ___CFXRegistrationPost1_block_invoke
16 CoreFoundation                 0x192c1fce4 _CFXRegistrationPost1
17 CoreFoundation                 0x192c1f97c ___CFXNotificationPost_block_invoke
18 CoreFoundation                 0x192b98910 -[_CFXNotificationRegistrar find:object:observer:enumerator:]
19 CoreFoundation                 0x192c1f2ac _CFXNotificationPost
20 Foundation                     0x192f81bfc -[NSNotificationCenter postNotificationName:object:userInfo:]
21 CoreData                       0x1976329dc -[NSManagedObjectContext(_NSInternalNotificationHandling) _postContextDidMergeChangesNotificationWithUserInfo:]
22 CoreData                       0x19762b6b4 -[NSManagedObjectContext(_NSInternalChangeProcessing) _createAndPostChangeNotification:deletions:updates:refreshes:deferrals:wasMerge:]
23 CoreData                       0x197635e00 -[NSManagedObjectContext(_NSInternalChangeProcessing) _postRefreshedObjectsNotificationAndClearList]
24 CoreData                       0x19762a4fc -[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:]
25 CoreData                       0x197631f1c -[NSManagedObjectContext _mergeChangesFromDidSaveDictionary:usingObjectIDs:]
26 CoreData                       0x19763228c -[NSManagedObjectContext mergeChangesFromContextDidSaveNotification:]
27 CoreData                       0x197757aac developerSubmittedBlockToNSManagedObjectContextPerform
28 libdispatch.dylib              0x19296dfd8 _dispatch_client_callout
29 libdispatch.dylib              0x192979cc8 _dispatch_main_queue_callback_4CF
30 CoreFoundation                 0x192c43cc8 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__
31 CoreFoundation                 0x192c3ea24 __CFRunLoopRun
32 CoreFoundation                 0x192c3df40 CFRunLoopRunSpecific
33 GraphicsServices               0x19cebb534 GSEventRunModal
34 UIKitCore                      0x196db6a60 UIApplicationMain
35 Calendarly                     0x1005812fc main + 29 (AppDelegate.swift:29)
36 libdyld.dylib                  0x192abce18 start
</code>```

I think I've found it! As a last sorting-resort, I wanted to sort by primary-key and added this:

And it seems like that didn't work.. Because the crash happens when the names and years are the same, thus it's using: NSSortDescriptor(key: "self", ascending: true)

5   Foundation                     0x1b8d8bc34 _NSCompareObject + 64 (NSSortDescriptor.m:275) in another crash I got from a the crash, which gave me the file as well (NSSortDescriptor.m), which got me thinking more...

答:
Shortly after I posted the question I got another crash report which had the file-names in it as well (not just functions).

Which was:

5   Foundation                     0x1b8d8bc34 _NSCompareObject + 64 (NSSortDescriptor.m:275

This lead me to believe it had something to do with NSSortDescriptor, and surely I added some sorting on self some time ago to keep a consistent order between items that had the same "name" and "year".

Interestingly the crash just occurred when inserting objects and not when loading up the collectionView.

I've actually found the post that led me to do this (though I must have missed the warning):

https://stackoverflow.com/a/52881564/897465

Body:
EDIT: Page is one of my entities

EIDT2: I'm always running with '-com.apple.CoreData.ConcurrencyDebug 1' and I've got no concurrency issues reported by that

I've stared to see a crash that I have no clue how to solve. I can't find when it was introduced it seems to come from CoreData. And also it's not 100% reproducible.

How can I track it down better? Is it me?

 Fatal Exception: NSInvalidArgumentException
-[Page compare:]: unrecognized selector sent to instance 0x281c640a0

With the following stack-trace:

Fatal Exception: NSInvalidArgumentException
0  CoreFoundation                 0x192cc896c __exceptionPreprocess
1  libobjc.A.dylib                0x1929e1028 objc_exception_throw
2  CoreFoundation                 0x192bc6dcc -[NSOrderedSet initWithSet:copyItems:]
3  CoreFoundation                 0x192ccd048 ___forwarding___
4  CoreFoundation                 0x192ccf3a0 _CF_forwarding_prep_0
5  Foundation                     0x1930afc3c _NSCompareObject
6  CoreData                       0x197670e24 +[NSFetchedResultsController(PrivateMethods) _insertIndexForObject:inArray:lowIdx:highIdx:sortDescriptors:]
7  CoreData                       0x197671034 -[NSFetchedResultsController(PrivateMethods) _updateFetchedObjectsWithInsertChange:]
8  CoreData                       0x19766b73c -[NSFetchedResultsController(PrivateMethods) _updateFetchedObjectsWithInsertedObjects:deletedObjects:updatedObjects:]
9  CoreData                       0x19779829c __82-[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:]_block_invoke
10 CoreData                       0x197757aac developerSubmittedBlockToNSManagedObjectContextPerform
11 CoreData                       0x1976221c4 -[NSManagedObjectContext performBlockAndWait:]
12 CoreData                       0x19762b81c -[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:]
13 Foundation                     0x19309306c __57-[NSNotificationCenter addObserver:selector:name:object:]_block_invoke_2
14 CoreFoundation                 0x192c2099c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__
15 CoreFoundation                 0x192c209ec ___CFXRegistrationPost1_block_invoke
16 CoreFoundation                 0x192c1fce4 _CFXRegistrationPost1
17 CoreFoundation                 0x192c1f97c ___CFXNotificationPost_block_invoke
18 CoreFoundation                 0x192b98910 -[_CFXNotificationRegistrar find:object:observer:enumerator:]
19 CoreFoundation                 0x192c1f2ac _CFXNotificationPost
20 Foundation                     0x192f81bfc -[NSNotificationCenter postNotificationName:object:userInfo:]
21 CoreData                       0x1976329dc -[NSManagedObjectContext(_NSInternalNotificationHandling) _postContextDidMergeChangesNotificationWithUserInfo:]
22 CoreData                       0x19762b6b4 -[NSManagedObjectContext(_NSInternalChangeProcessing) _createAndPostChangeNotification:deletions:updates:refreshes:deferrals:wasMerge:]
23 CoreData                       0x197635e00 -[NSManagedObjectContext(_NSInternalChangeProcessing) _postRefreshedObjectsNotificationAndClearList]
24 CoreData                       0x19762a4fc -[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:]
25 CoreData                       0x197631f1c -[NSManagedObjectContext _mergeChangesFromDidSaveDictionary:usingObjectIDs:]
26 CoreData                       0x19763228c -[NSManagedObjectContext mergeChangesFromContextDidSaveNotification:]
27 CoreData                       0x197757aac developerSubmittedBlockToNSManagedObjectContextPerform
28 libdispatch.dylib              0x19296dfd8 _dispatch_client_callout
29 libdispatch.dylib              0x192979cc8 _dispatch_main_queue_callback_4CF
30 CoreFoundation                 0x192c43cc8 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__
31 CoreFoundation                 0x192c3ea24 __CFRunLoopRun
32 CoreFoundation                 0x192c3df40 CFRunLoopRunSpecific
33 GraphicsServices               0x19cebb534 GSEventRunModal
34 UIKitCore                      0x196db6a60 UIApplicationMain
35 Calendarly                     0x1005812fc main + 29 (AppDelegate.swift:29)
36 libdyld.dylib                  0x192abce18 start

I think I've found it! As a last sorting-resort, I wanted to sort by primary-key and added this:

And it seems like that didn't work.. Because the crash happens when the names and years are the same, thus it's using: NSSortDescriptor(key: "self", ascending: true)

5   Foundation                     0x1b8d8bc34 _NSCompareObject + 64 (NSSortDescriptor.m:275) in another crash I got from a the crash, which gave me the file as well (NSSortDescriptor.m), which got me thinking more...


问:
Left alignment of last line of flex cells
I've made a table-like flex structure, that looks pretty nice and has adaptive number of cells, but when last row isn't full - it stretches remaining cells to full size, which looks unshapely.

https://jsfiddle.net/zzmaster/6uw4gm3t/3/
(you need to enlarge results area to maximum in order to see this)

Logically, justify-content: flex-start; should fix this, but it doesn't.

Is there any way to turn remained cells back to their's place?

答:
You can fix with remove flex: 1 1 0px CSS style. Replace below code with your current code.

```<code>ul.text {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}

ul.text li {
  min-width: 300px;
  display: inline-flex;
}
</code>```

Body:
You can fix with remove flex: 1 1 0px CSS style. Replace below code with your current code.

ul.text {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}

ul.text li {
  min-width: 300px;
  display: inline-flex;
}


问:
Regular expression for remove metadata
I trying to create a application with use some Entity Framework and some old DataSets but I only have a dynamic connection string using entity and need remove metadata at runtime to create a connection string to my database. Anyone know a way to remove all metadata from Entity Framework Connection

I have this

```<code>metadata=res://*/Models.SiteModel.csdl|res://*/Models.SiteModel.ssdl|res://*/Models.SiteModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=(local);Initial Catalog=MyDB;Persist Security Info=True;User ID=sa;Password=P@ssw0rd;MultipleActiveResultSets=True"
</code>```

and need only this:

```<code>Data Source=(local);Initial Catalog=MyDB;Persist Security Info=True;User ID=sa;Password=P@ssw0rd;MultipleActiveResultSets=True
</code>```

答: A better property to use is builder.ProviderConnectionString rather than stripping the Metadata from the builder to get build.ConnectiongString.

Title: Regular expression for remove metadata

Body:
I trying to create a application with use some Entity Framework and some old DataSets but I only have a dynamic connection string using entity and need remove metadata at runtime to create a connection string to my database. Anyone know a way to remove all metadata from Entity Framework Connection

I have this

metadata=res://*/Models.SiteModel.csdl|res://*/Models.SiteModel.ssdl|res://*/Models.SiteModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=(local);Initial Catalog=MyDB;Persist Security Info=True;User ID=sa;Password=P@ssw0rd;MultipleActiveResultSets=True"

and need only this:

Data Source=(local);Initial Catalog=MyDB;Persist Security Info=True;User ID=sa;Password=P@ssw0rd;MultipleActiveResultSets=True