问:
Mock react-dom Jest
I'm trying to mock the react-dom module using Jest

```<code>import React from 'react';
import {configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Link from '../components/DumbComp';
import { shallowToJson } from 'enzyme-to-json';
import { render } from 'react-dom';

configure({ adapter: new Adapter() });

jest.mock('react-dom');
describe('Link',() =>{
it('should render correctly', ()=>{
expect(render).toHaveBeenCalledWith(
  <Link title="mockTitle" url="mockUrl" />, 'element-node'
);
expect(render).toHaveBeenCalledTimes(1);
});
});
</code>```

When I run the test I get the following error:

```<code>Link › should render correctly

expect(jest.fn()).toHaveBeenCalledWith(expected)

Expected mock function to have been called with:
  [<Link title="mockTitle" url="mockUrl" />, "element-node"]
But it was not called.
</code>```

It seems that when I mock the render method it doesn't return anything. How can I correctly mock it?

I'm using this tutorial, see under the "The art of mocking" section.

答:
The accepted answer might be a little out of date. To mock react-dom without side-effects you need to only mock the function you need, which in this case is the render function.

This can be done using Jest's requireActual like so:

```<code>jest.mock('react-dom', () => ({
  ...jest.requireActual('react-dom'),
  render: jest.fn(),
}))
</code>```

Title: Mock react-dom Jest

Body:
I'm trying to mock the react-dom module using Jest

import React from 'react';
import {configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Link from '../components/DumbComp';
import { shallowToJson } from 'enzyme-to-json';
import { render } from 'react-dom';

configure({ adapter: new Adapter() });

jest.mock('react-dom');
describe('Link',() =>{
it('should render correctly', ()=>{
expect(render).toHaveBeenCalledWith(
  <Link title="mockTitle" url="mockUrl" />, 'element-node'
);
expect(render).toHaveBeenCalledTimes(1);
});
});

When I run the test I get the following error:

Link › should render correctly

expect(jest.fn()).toHaveBeenCalledWith(expected)

Expected mock function to have been called with:
  [<Link title="mockTitle" url="mockUrl" />, "element-node"]
But it was not called.

It seems that when I mock the render method it doesn't return anything. How can I correctly mock it?

I'm using this tutorial, see under the "The art of mocking" section.

Body:
The accepted answer might be a little out of date. To mock react-dom without side-effects you need to only mock the function you need, which in this case is the render function.

This can be done using Jest's requireActual like so:

jest.mock('react-dom', () => ({
  ...jest.requireActual('react-dom'),
  render: jest.fn(),
}))


来源: stackexchange

问:
How to scatter chunks of data on cluster nodes without running out of memory
I wrote a code in Python which implements mpi4py to scatter chunks of data across the processors of a cluster. Each processor writes the given chunk of data into a .txt file, then all these .txt files are merged in one.
Everything is working as expected.
However, for very large .txt files, the cluster is complaining about memory:

```<code>mpiexec noticed that process ... rank ... on node ... exited on signal 9 (Killed)
</code>```

I'm trying to set the parameters in the PBS file in a way which avoids this issue. So far, this is not working:

```<code>#!/bin/bash
#PBS -S /bin/bash

## job name and output file
#PBS -N test
#PBS -j oe
#PBS -o job.o
#PBS -V

###########################################################

# USER PARAMETERS

##PBS -l select=16:mpiprocs=1:mem=8000mb

#PBS -l select=4:ncpus=16:mem=4gb
#PBS -l walltime=03:00:00

###########################################################

ulimit -Hn

# number of processes
NPROC=64
echo $NPROC

CURRDIR=$PBS_O_WORKDIR
echo $CURRDIR
cd $CURRDIR

module load anaconda/2019.10
source activate py3

cat $PBS_NODEFILE

echo starting run in current directory $CURRDIR
echo " "
mpiexec -n $NPROC -hostfile $PBS_NODEFILE python $CURRDIR/test.py
echo "finished successfully"

</code>```

Any idea?

答:
MPI uses distributed memory, that is, if you have more data than fits in one process, you spread it over multiple processes, for instance on multiple computers. So "scattering" data often doesn't make sense: it assumes that all this too-much data actually fits on one process. For a true MPI program, your processes all create their own data, or read it from a file, but you never have all data in one place.

So if you're dealing with lots of data, then a scattering approach will of course run out of memory, but it's the wrong way to approach your problem to begin with. Rewrite your program and make it truly distributed memory parallel.

ContentLicense: CC BY-SA 4.0

Body:
I wrote a code in Python which implements mpi4py to scatter chunks of data across the processors of a cluster. Each processor writes the given chunk of data into a .txt file, then all these .txt files are merged in one.
Everything is working as expected.
However, for very large .txt files, the cluster is complaining about memory:

mpiexec noticed that process ... rank ... on node ... exited on signal 9 (Killed)

I'm trying to set the parameters in the PBS file in a way which avoids this issue. So far, this is not working:

#!/bin/bash
#PBS -S /bin/bash

## job name and output file
#PBS -N test
#PBS -j oe
#PBS -o job.o
#PBS -V

###########################################################

# USER PARAMETERS

##PBS -l select=16:mpiprocs=1:mem=8000mb

#PBS -l select=4:ncpus=16:mem=4gb
#PBS -l walltime=03:00:00

###########################################################

ulimit -Hn

# number of processes
NPROC=64
echo $NPROC

CURRDIR=$PBS_O_WORKDIR
echo $CURRDIR
cd $CURRDIR

module load anaconda/2019.10
source activate py3

cat $PBS_NODEFILE

echo starting run in current directory $CURRDIR
echo " "
mpiexec -n $NPROC -hostfile $PBS_NODEFILE python $CURRDIR/test.py
echo "finished successfully"

Any idea?


问:
Javascript: Sort array and return an array of indices that indicates the position of the sorted elements with respect to the original elements
Suppose I have a Javascript array, like so:

```<code>var test = ['b', 'c', 'd', 'a'];
</code>```

I want to sort the array. Obviously, I can just do this to sort the array:

```<code>test.sort(); //Now test is ['a', 'b', 'c', 'd']
</code>```

But what I really want is an array of indices that indicates the position of the sorted elements with respect to the original elements. I'm not quite sure how to phrase this, so maybe that is why I am having trouble figuring out how to do it.

If such a method was called sortIndices(), then what I would want is:

```<code>var indices = test.sortIndices();
//At this point, I want indices to be [3, 0, 1, 2].
</code>```

'a' was at position 3, 'b' was at 0, 'c' was at 1 and 'd' was a 2 in the original array. Hence, [3, 0, 1, 2].

One solution would be to sort a copy of the array, and then cycle through the sorted array and find the position of each element in the original array. But, that feels clunky.

Is there an existing method that does what I want? If not, how would you go about writing a method that does this?

答:
You can use Array.prototype.entries() to pair the items with their indices. You could also use Object.entries() but that would convert the index numbers to strings.

let test = ["b", "c", "d", "a"];

console.log(
  Array.from(test.entries())
    .sort(([_, v], [__, w]) => v.localeCompare(w))
    .map(([i, _]) => i)
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {top:0; max-height: 100% !important}</code>```

Body:
Suppose I have a Javascript array, like so:

var test = ['b', 'c', 'd', 'a'];

I want to sort the array. Obviously, I can just do this to sort the array:

test.sort(); //Now test is ['a', 'b', 'c', 'd']

But what I really want is an array of indices that indicates the position of the sorted elements with respect to the original elements. I'm not quite sure how to phrase this, so maybe that is why I am having trouble figuring out how to do it.

If such a method was called sortIndices(), then what I would want is:

var indices = test.sortIndices();
//At this point, I want indices to be [3, 0, 1, 2].

'a' was at position 3, 'b' was at 0, 'c' was at 1 and 'd' was a 2 in the original array. Hence, [3, 0, 1, 2].

One solution would be to sort a copy of the array, and then cycle through the sorted array and find the position of each element in the original array. But, that feels clunky.

Is there an existing method that does what I want? If not, how would you go about writing a method that does this?

Body:
You can use Array.prototype.entries() to pair the items with their indices. You could also use Object.entries() but that would convert the index numbers to strings.

let test = ["b", "c", "d", "a"];

console.log(
  Array.from(test.entries())
    .sort(([_, v], [__, w]) => v.localeCompare(w))
    .map(([i, _]) => i)
);

.as-console-wrapper {top:0; max-height: 100% !important}


问:
How to add dynamic List to flutter nested map
Need a help!

This is my data from firebase

```<code>{
  "Engineering" : ["EEE", "CSE", "EE"],
  "Marketing" : [ "SEO", "Online Marketing", "Digital Marketing"],
}
</code>```

I am using a nested dropdown to show these data to users, receiving data is something like this

```<code>Map<String, List<String>>
</code>```

after selecting the dropdown, individual selection is something like this-

```<code>String _selectedCategory = "Engineering" ;
String _selectedSkill = "EEE" ;
</code>```

at a time a user can select a category with a skill,

I want to create a dynamic map like this

```<code>{
  "Selected Category 1" : ["Selected Skill 1 from Category 1", "Selected Skill 2 from Category 1", "Selected Skill 3 from Category 1"],
  "Selected Category 2" : [ "Selected Skill 1 from Category 2", "Selected Skill 2 from Category 2", "Selected Skill 3 from Category 2"],
}
</code>```

I tried to achieve this-

```<code>  List<String> addedSkills = [];
  Map<String, List<String>> addedData = {};
</code>```

inside dropdown

```<code>setState((){
   addedSkills.add(_selectedSkill);
   addedData.addAll({_selectedCategory: _addedSkills})
});
</code>```

data is showing like this

```<code>{
  "Selected Category 1" : ["Selected Skill 1 from Category 1", "Selected Skill 2 from
   Category 2", "Selected Skill 3 from Category 2"],

}
</code>```

but I want data something like this

```<code>{
  "Selected Category 1" : ["Selected Skill 1 from Category 1", "Selected Skill 2 from Category 1", "Selected Skill 3 from Category 1"],
  "Selected Category 2" : [ "Selected Skill 1 from Category 2", "Selected Skill 2 from Category 2", "Selected Skill 3 from Category 2"],
}
</code>```

答:
Your output indicates that your _selectedCategory variable is not being upated before this line runs

```<code>addedData.addAll({_selectedCategory: _addedSkills})
</code>```

addAll on a map will add any new key/value pairs and overwrite the value of any existing key. In your case, the value stored under the _selectedCategory key is being overwritten.

You could test this by hard coding a new key

```<code>addedData.addAll({'test_category': _addedSkills})
</code>```

Assuming your addedData map already has at least one key value pair your data will look something like this

```<code>{
  "Selected Category 1" : ["Selected Skill 1 from Category 1", "Selected Skill 2 from Category 1", "Selected Skill 3 from Category 1"],
  "test_category" : ['selected skill'],
}
</code>```

So your issue probably lies in the logic of updating the value of _selectedCategory from what is selected in the dropdown menu. If you need help with that then I suggest sharing that code.

Body:
Need a help!

This is my data from firebase

{
  "Engineering" : ["EEE", "CSE", "EE"],
  "Marketing" : [ "SEO", "Online Marketing", "Digital Marketing"],
}

I am using a nested dropdown to show these data to users, receiving data is something like this

Map<String, List<String>>

after selecting the dropdown, individual selection is something like this-

String _selectedCategory = "Engineering" ;
String _selectedSkill = "EEE" ;

at a time a user can select a category with a skill,

I want to create a dynamic map like this

{
  "Selected Category 1" : ["Selected Skill 1 from Category 1", "Selected Skill 2 from Category 1", "Selected Skill 3 from Category 1"],
  "Selected Category 2" : [ "Selected Skill 1 from Category 2", "Selected Skill 2 from Category 2", "Selected Skill 3 from Category 2"],
}

I tried to achieve this-

  List<String> addedSkills = [];
  Map<String, List<String>> addedData = {};

inside dropdown

setState((){
   addedSkills.add(_selectedSkill);
   addedData.addAll({_selectedCategory: _addedSkills})
});

data is showing like this

{
  "Selected Category 1" : ["Selected Skill 1 from Category 1", "Selected Skill 2 from
   Category 2", "Selected Skill 3 from Category 2"],

}

but I want data something like this

{
  "Selected Category 1" : ["Selected Skill 1 from Category 1", "Selected Skill 2 from Category 1", "Selected Skill 3 from Category 1"],
  "Selected Category 2" : [ "Selected Skill 1 from Category 2", "Selected Skill 2 from Category 2", "Selected Skill 3 from Category 2"],
}

Body:
Your output indicates that your _selectedCategory variable is not being upated before this line runs

addedData.addAll({_selectedCategory: _addedSkills})

addAll on a map will add any new key/value pairs and overwrite the value of any existing key. In your case, the value stored under the _selectedCategory key is being overwritten.

You could test this by hard coding a new key

addedData.addAll({'test_category': _addedSkills})

Assuming your addedData map already has at least one key value pair your data will look something like this

{
  "Selected Category 1" : ["Selected Skill 1 from Category 1", "Selected Skill 2 from Category 1", "Selected Skill 3 from Category 1"],
  "test_category" : ['selected skill'],
}

So your issue probably lies in the logic of updating the value of _selectedCategory from what is selected in the dropdown menu. If you need help with that then I suggest sharing that code.


问:
Get all the names of the applications in a site
I am trying to write a powershell script which gets the names of each application in a website in IIS in order to change the app pool associated with it. I am able to get the website, but I don't see a clear way to fetch each of the names?

Eg. I want to loop through them all: Api, Services, etc.. and then use

```<code>Set-ItemProperty "IIS:\Sites\RootSite\$loopedValue" -Name 'applicationPool' -Value $NewPool
</code>```

I'm trying this:

```<code>Get-WebApplication -Site 'ABC'

Name             Application pool   Protocols    Physical Path
----             ----------------   ---------    -------------
Api              ABC                http         C:\Api
Services         ABC                http         C:\Services
Director         ABC                http         C:\Director
ReportingServer  ABC                http         C:\ReportingServer
</code>```

But there is no way to get the Name from the members of Get-WebApplication.

```<code>Get-WebApplication | Get-Member

   TypeName: Microsoft.IIs.PowerShell.Framework.ConfigurationElement#site#application

Name                     MemberType            Definition
----                     ----------            ----------
ClearLocalData           Method                void ClearLocalData()
Copy                     Method                void Copy(Microsoft.IIs.PowerShell.Framework.ConfigurationElement target, bool recurse)
Delete                   Method                void Delete()
Equals                   Method                bool Equals(System.Object obj), bool IEquatable[ConfigurationElement].Equals(Microsoft.IIs.PowerShell.Framework.Conf...
GetAttribute             Method                Microsoft.IIs.PowerShell.Framework.ConfigurationAttribute GetAttribute(string attributeName)
GetAttributeValue        Method                System.Object GetAttributeValue(string attributeName)
GetChildElement          Method                Microsoft.IIs.PowerShell.Framework.ConfigurationElement GetChildElement(string elementName), Microsoft.IIs.PowerShel...
GetCollection            Method                Microsoft.IIs.PowerShell.Framework.ConfigurationElementCollection GetCollection(string collectionName), Microsoft.II...
GetHashCode              Method                int GetHashCode()
GetMetadata              Method                System.Object GetMetadata(string metadataType)
GetParentElement         Method                Microsoft.IIs.PowerShell.Framework.ConfigurationElement GetParentElement()
GetType                  Method                type GetType()
LoadProperties           Method                void LoadProperties(System.Collections.Generic.Dictionary[string,System.Object] propCollection)
SetAttributeValue        Method                void SetAttributeValue(string attributeName, System.Object value)
SetMetadata              Method                void SetMetadata(string metadataType, System.Object value)
ToPSObject               Method                psobject ToPSObject(Microsoft.IIs.PowerShell.Framework.ConfigurationElement parent)
ToString                 Method                string ToString()
Update                   Method                void Update(Microsoft.IIs.PowerShell.Framework.ConfigurationElement source), bool Update(psobject data)
UpdateCollection         Method                bool UpdateCollection(psobject[] arr)
applicationPool          NoteProperty          string applicationPool=ABC
Collection               NoteProperty          psobject[] Collection=System.Management.Automation.PSObject[]
ConfigurationPathType    NoteProperty          ConfigurationPathNodeType ConfigurationPathType=Location
enabledProtocols         NoteProperty          string enabledProtocols=http
ItemXPath                NoteProperty          string ItemXPath=/system.applicationHost/sites/site[@name='ABC' and @id='1']/application[@path='/API']
Location                 NoteProperty          string Location=
path                     NoteProperty          string path=/ApiDoc
preloadEnabled           NoteProperty          bool preloadEnabled=False
PSPath                   NoteProperty          string PSPath=MACHINE/WEBROOT/APPHOST
serviceAutoStartEnabled  NoteProperty          bool serviceAutoStartEnabled=False
serviceAutoStartProvider NoteProperty          string serviceAutoStartProvider=
virtualDirectoryDefaults NoteProperty          Microsoft.IIs.PowerShell.Framework.ConfigurationElement#application#virtualDirectoryDefaults virtualDirectoryDefault...
Item                     ParameterizedProperty System.Object Item(string attributeName) {get;set;}
Attributes               Property              Microsoft.IIs.PowerShell.Framework.ConfigurationAttributeCollection Attributes {get;}
ChildElements            Property              Microsoft.IIs.PowerShell.Framework.ConfigurationChildElementCollection ChildElements {get;}
ElementTagName           Property              string ElementTagName {get;}
Methods                  Property              Microsoft.IIs.PowerShell.Framework.ConfigurationMethodCollection Methods {get;}
Schema                   Property              Microsoft.IIs.PowerShell.Framework.ConfigurationElementSchema Schema {get;}
PhysicalPath             ScriptProperty        System.Object PhysicalPath {get=$pquery = $this.ItemXPath + "/virtualDirectory[@path='/']/@physicalPath"...
</code>```

I don't really want to parse a string value from the path or PhysicalPath to do this. Is there another way?

答:
An alternative way I came up with was to join the two results from Get-WebSite and Get-WebApplication

```<code>(get-website | select-object @{n='Site'; e={$_.Name}},@{n='Location'; e={$_.PhysicalPath}}) + (get-webapplication | select-object @{n='Site'; e= {$_.GetParentElement().Attributes['name'].value + $_.path }},@{n='Location'; e= {$_.PhysicalPath}})
</code>```

Output:

```<code>Site                          WebType        Location
----                          -------        --------
MEDIA                         WebSite        c:\mir\data
DATA                          WebSite        d:\data
Tu***.M*.A***o.Sa****x.N***e  WebSite        C:\WebSite\Tu***.M*.A***o.Sa****x.N***e
Tu***.***********on.*****ime  WebSite        C:\WebSite\Tu***.***********on.*****ime
Tu***.**.*****.***********ion WebSite        C:\WebSite\Tu***.**.*****.***********ion
Tu***.********.**.****App     WebSite        C:\WEB\Tu***.********.**.****App
Tu***.********.**.****App/api WebApplication C:\Web\Tu***.********.**.****vate
</code>```

Body:
I am trying to write a powershell script which gets the names of each application in a website in IIS in order to change the app pool associated with it. I am able to get the website, but I don't see a clear way to fetch each of the names?

Eg. I want to loop through them all: Api, Services, etc.. and then use

Set-ItemProperty "IIS:\Sites\RootSite\$loopedValue" -Name 'applicationPool' -Value $NewPool

I'm trying this:

Get-WebApplication -Site 'ABC'

Name             Application pool   Protocols    Physical Path
----             ----------------   ---------    -------------
Api              ABC                http         C:\Api
Services         ABC                http         C:\Services
Director         ABC                http         C:\Director
ReportingServer  ABC                http         C:\ReportingServer

But there is no way to get the Name from the members of Get-WebApplication.

Get-WebApplication | Get-Member

   TypeName: Microsoft.IIs.PowerShell.Framework.ConfigurationElement#site#application

Name                     MemberType            Definition
----                     ----------            ----------
ClearLocalData           Method                void ClearLocalData()
Copy                     Method                void Copy(Microsoft.IIs.PowerShell.Framework.ConfigurationElement target, bool recurse)
Delete                   Method                void Delete()
Equals                   Method                bool Equals(System.Object obj), bool IEquatable[ConfigurationElement].Equals(Microsoft.IIs.PowerShell.Framework.Conf...
GetAttribute             Method                Microsoft.IIs.PowerShell.Framework.ConfigurationAttribute GetAttribute(string attributeName)
GetAttributeValue        Method                System.Object GetAttributeValue(string attributeName)
GetChildElement          Method                Microsoft.IIs.PowerShell.Framework.ConfigurationElement GetChildElement(string elementName), Microsoft.IIs.PowerShel...
GetCollection            Method                Microsoft.IIs.PowerShell.Framework.ConfigurationElementCollection GetCollection(string collectionName), Microsoft.II...
GetHashCode              Method                int GetHashCode()
GetMetadata              Method                System.Object GetMetadata(string metadataType)
GetParentElement         Method                Microsoft.IIs.PowerShell.Framework.ConfigurationElement GetParentElement()
GetType                  Method                type GetType()
LoadProperties           Method                void LoadProperties(System.Collections.Generic.Dictionary[string,System.Object] propCollection)
SetAttributeValue        Method                void SetAttributeValue(string attributeName, System.Object value)
SetMetadata              Method                void SetMetadata(string metadataType, System.Object value)
ToPSObject               Method                psobject ToPSObject(Microsoft.IIs.PowerShell.Framework.ConfigurationElement parent)
ToString                 Method                string ToString()
Update                   Method                void Update(Microsoft.IIs.PowerShell.Framework.ConfigurationElement source), bool Update(psobject data)
UpdateCollection         Method                bool UpdateCollection(psobject[] arr)
applicationPool          NoteProperty          string applicationPool=ABC
Collection               NoteProperty          psobject[] Collection=System.Management.Automation.PSObject[]
ConfigurationPathType    NoteProperty          ConfigurationPathNodeType ConfigurationPathType=Location
enabledProtocols         NoteProperty          string enabledProtocols=http
ItemXPath                NoteProperty          string ItemXPath=/system.applicationHost/sites/site[@name='ABC' and @id='1']/application[@path='/API']
Location                 NoteProperty          string Location=
path                     NoteProperty          string path=/ApiDoc
preloadEnabled           NoteProperty          bool preloadEnabled=False
PSPath                   NoteProperty          string PSPath=MACHINE/WEBROOT/APPHOST
serviceAutoStartEnabled  NoteProperty          bool serviceAutoStartEnabled=False
serviceAutoStartProvider NoteProperty          string serviceAutoStartProvider=
virtualDirectoryDefaults NoteProperty          Microsoft.IIs.PowerShell.Framework.ConfigurationElement#application#virtualDirectoryDefaults virtualDirectoryDefault...
Item                     ParameterizedProperty System.Object Item(string attributeName) {get;set;}
Attributes               Property              Microsoft.IIs.PowerShell.Framework.ConfigurationAttributeCollection Attributes {get;}
ChildElements            Property              Microsoft.IIs.PowerShell.Framework.ConfigurationChildElementCollection ChildElements {get;}
ElementTagName           Property              string ElementTagName {get;}
Methods                  Property              Microsoft.IIs.PowerShell.Framework.ConfigurationMethodCollection Methods {get;}
Schema                   Property              Microsoft.IIs.PowerShell.Framework.ConfigurationElementSchema Schema {get;}
PhysicalPath             ScriptProperty        System.Object PhysicalPath {get=$pquery = $this.ItemXPath + "/virtualDirectory[@path='/']/@physicalPath"...

I don't really want to parse a string value from the path or PhysicalPath to do this. Is there another way?

Body:
An alternative way I came up with was to join the two results from Get-WebSite and Get-WebApplication

(get-website | select-object @{n='Site'; e={$_.Name}},@{n='Location'; e={$_.PhysicalPath}}) + (get-webapplication | select-object @{n='Site'; e= {$_.GetParentElement().Attributes['name'].value + $_.path }},@{n='Location'; e= {$_.PhysicalPath}})

Output:

Site                          WebType        Location
----                          -------        --------
MEDIA                         WebSite        c:\mir\data
DATA                          WebSite        d:\data
Tu***.M*.A***o.Sa****x.N***e  WebSite        C:\WebSite\Tu***.M*.A***o.Sa****x.N***e
Tu***.***********on.*****ime  WebSite        C:\WebSite\Tu***.***********on.*****ime
Tu***.**.*****.***********ion WebSite        C:\WebSite\Tu***.**.*****.***********ion
Tu***.********.**.****App     WebSite        C:\WEB\Tu***.********.**.****App
Tu***.********.**.****App/api WebApplication C:\Web\Tu***.********.**.****vate


问:
How to map specific column using GAS?
From @soMario's answer to a certain question, getting the data of specific column can be done like this:

The following will get columns b,d,f,g from the range A:G.

```<code>const rawData = ss.getRange("A:G").getValues().map(([,b,,d,,f,g]) => [b,d,f,g]);
</code>```

How can I get the same, but using getRange(2,1,sheet.getLastRow(),7) instead?

Thank you!

答:
when you getValues() of any range, it is stored as one array of many arrays, which looks like this, structurally for the range A1:G3 :

```<code>[ [ , , , , , , ], [ , , , , , , ], [ , , , , , , ] ]
</code>```

when you want a specific "column", say column 4 of that range, in javascript/appscript it means you want the 4th element of each of the arrays in the array.  When counting from 0, the 4th element is the 3rd "index".

When using the mapping function, each of the elements of the array being mapped is assigned any variable you want.  It is common to use "e".  So for your specific case you would want to do this

```<code>const rawData = ss.getRange("A:G").map(e=>[ e[1], e[3], e[5], e[6] ]);
</code>```

1,3,5 and 6 being the "indices" of columns B,D,F and G when starting to count with A as 0.

However, it's likely that you'll want a filter on your data as well to only return rows where there are values in column A.  If that guess is correct, you can apply a filter before your map like this:

```<code>const rawData = ss.getRange("A:G").filter(e=>e[0]).map(e=>[ e[1], e[3], e[5], e[6] ]);
</code>```

Title: How to map specific column using GAS?

Body:
From @soMario's answer to a certain question, getting the data of specific column can be done like this:

The following will get columns b,d,f,g from the range A:G.

const rawData = ss.getRange("A:G").getValues().map(([,b,,d,,f,g]) => [b,d,f,g]);

How can I get the same, but using getRange(2,1,sheet.getLastRow(),7) instead?

Thank you!

Body:
when you getValues() of any range, it is stored as one array of many arrays, which looks like this, structurally for the range A1:G3 :

[ [ , , , , , , ], [ , , , , , , ], [ , , , , , , ] ]

when you want a specific "column", say column 4 of that range, in javascript/appscript it means you want the 4th element of each of the arrays in the array.  When counting from 0, the 4th element is the 3rd "index".

When using the mapping function, each of the elements of the array being mapped is assigned any variable you want.  It is common to use "e".  So for your specific case you would want to do this

const rawData = ss.getRange("A:G").map(e=>[ e[1], e[3], e[5], e[6] ]);

1,3,5 and 6 being the "indices" of columns B,D,F and G when starting to count with A as 0.

However, it's likely that you'll want a filter on your data as well to only return rows where there are values in column A.  If that guess is correct, you can apply a filter before your map like this:

const rawData = ss.getRange("A:G").filter(e=>e[0]).map(e=>[ e[1], e[3], e[5], e[6] ]);


问:
Nginx with worpress as sub-directory returning 404 in posts
After adding various configurations into the Wordpress subdirectory, I can access without any issues the WP homepage, but I'm still not able to access the posts, returning 404.

www.test.com/blog - WP homepage, works perfectly fine

www.test.com/blog/test-post-for-blog - WP Post, 404

Here is the config:

```<code>server {
  listen 80;
  listen [::]:80;

  server_name www.test.com;

  location ^~ /media {
    alias /var/local/test/static/media;
  }

  location ^~ /icons {
    alias /var/local/test/static/icons;
  }

  location /blog {
    alias /var/www/html;
    index  index.html index.htm index.php;
    try_files $uri $uri/ /blog/index.php?$args /blog/index.php?q=$uri&$args;
    # try_files $uri $uri/ /blog/index.php?q=$uri$args;

    location ~ \.php$ {
      try_files $uri =404;
      include fastcgi_params;
      fastcgi_intercept_errors on;
      fastcgi_index index.php;
      fastcgi_pass blog-test:9000;
      fastcgi_split_path_info ^(/blog)(/.*)$;
      fastcgi_param SCRIPT_FILENAME $request_filename;
      fastcgi_param PATH_INFO $fastcgi_path_info;
    }
  }
}
</code>```

And the log:

```<code>2022/02/09 14:47:25 [error] 32#32: *45 open() "/etc/nginx/html/index.php" failed (2: No such file or directory), client: 10.10.10.10, server: www.test.com, request: "GET /blog/test-post-for-blog/ HTTP/1.1", host: "www.test.com", referrer: "https://www.test.com/blog/"
10.10.10.10 - admin [09/Feb/2022:14:47:25 +0000] "GET /blog/test-post-for-blog/ HTTP/1.1" 404 187 "https://www.test.com/blog/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.87 Safari/537.36"
</code>```

Checking the logs, it seems to look into the wrong place, which is /etc/nginx/html/index.php, but if I add the alias in the php location block, then the homepage will stop working as well, which gets me a bit confused.

Currently, I'm not quite sure if the problem is the alias in the blog block ( nginx recommends not using alias together with try_files, apparently due to a bug ), or anything else. If it is indeed the alias directive, I'll try to add root, together with some rewrite rules to avoid modifying the file structure.

It really took me more than it should to figure it out, and still can not actually understand what might be the issue here.

UPDATE 1 :

This is extremely odd. With the following blog config, separating the php location from the blog, the WP posts are accesible, but not the homepage and admin, returning 404:

```<code>  location /blog {
    alias /var/www/html;
    try_files $uri $uri/ /index.php?$args;
  }

  location ~ \.php$ {
    alias /var/www/html;
    try_files $uri =404;
    include fastcgi_params;
    fastcgi_intercept_errors on;
    fastcgi_index index.php;
    fastcgi_pass blog-test:9000;
    fastcgi_split_path_info ^(/blog)(/.*)$;
    fastcgi_param SCRIPT_FILENAME $request_filename;
    fastcgi_param PATH_INFO $fastcgi_path_info;
  }
</code>```

UPDATE 2 :

Now this works ( the blog and the posts can be accesed ) , but the admin seems to be going into a redirect loop:

```<code>  location /blog {
    alias /var/www/html;
    index index.php;
    try_files $uri $uri/ /blog/index.php?q=$uri&$args;
  }

  location ~ \.php$ {
    alias /var/www/html;
    try_files $uri $uri/ /index.php?$args;
    include fastcgi_params;
    fastcgi_intercept_errors on;
    fastcgi_index index.php;
    fastcgi_pass blog-test:9000;
    fastcgi_param SCRIPT_FILENAME $request_filename;
  }
</code>```

UPDATE 3 & FIX :

This apparently works, but the config seems to be really unpleasant and unoptimised. If I try to nest the php location into the blog block, then the php files will download instead of rendering. If I try to use alias instead of root, some pages will not show resulting in 404. In any case, this seems to be functional:

```<code>  root /var/www/html;
  index index.php;

  location /blog {
    rewrite ^/blog(.*)$ /$1 break;
    try_files $uri $uri/ /blog/index.php?$args;
  }

  location ~ \.php$ {
    rewrite ^/blog(.*)$ $1 break;
    fastcgi_pass blog-test:9000;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_split_path_info ^(/blog)(/.*)$;
    fastcgi_param SCRIPT_FILENAME $request_filename;
    fastcgi_param PATH_INFO $fastcgi_path_info;
  }
</code>```

Body:
After adding various configurations into the Wordpress subdirectory, I can access without any issues the WP homepage, but I'm still not able to access the posts, returning 404.

www.test.com/blog - WP homepage, works perfectly fine

www.test.com/blog/test-post-for-blog - WP Post, 404

Here is the config:

server {
  listen 80;
  listen [::]:80;

  server_name www.test.com;

  location ^~ /media {
    alias /var/local/test/static/media;
  }

  location ^~ /icons {
    alias /var/local/test/static/icons;
  }

  location /blog {
    alias /var/www/html;
    index  index.html index.htm index.php;
    try_files $uri $uri/ /blog/index.php?$args /blog/index.php?q=$uri&$args;
    # try_files $uri $uri/ /blog/index.php?q=$uri$args;

    location ~ \.php$ {
      try_files $uri =404;
      include fastcgi_params;
      fastcgi_intercept_errors on;
      fastcgi_index index.php;
      fastcgi_pass blog-test:9000;
      fastcgi_split_path_info ^(/blog)(/.*)$;
      fastcgi_param SCRIPT_FILENAME $request_filename;
      fastcgi_param PATH_INFO $fastcgi_path_info;
    }
  }
}

And the log:

2022/02/09 14:47:25 [error] 32#32: *45 open() "/etc/nginx/html/index.php" failed (2: No such file or directory), client: 10.10.10.10, server: www.test.com, request: "GET /blog/test-post-for-blog/ HTTP/1.1", host: "www.test.com", referrer: "https://www.test.com/blog/"
10.10.10.10 - admin [09/Feb/2022:14:47:25 +0000] "GET /blog/test-post-for-blog/ HTTP/1.1" 404 187 "https://www.test.com/blog/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.87 Safari/537.36"

Checking the logs, it seems to look into the wrong place, which is /etc/nginx/html/index.php, but if I add the alias in the php location block, then the homepage will stop working as well, which gets me a bit confused.

Currently, I'm not quite sure if the problem is the alias in the blog block ( nginx recommends not using alias together with try_files, apparently due to a bug ), or anything else. If it is indeed the alias directive, I'll try to add root, together with some rewrite rules to avoid modifying the file structure.

It really took me more than it should to figure it out, and still can not actually understand what might be the issue here.

UPDATE 1 :

This is extremely odd. With the following blog config, separating the php location from the blog, the WP posts are accesible, but not the homepage and admin, returning 404:

  location /blog {
    alias /var/www/html;
    try_files $uri $uri/ /index.php?$args;
  }

  location ~ \.php$ {
    alias /var/www/html;
    try_files $uri =404;
    include fastcgi_params;
    fastcgi_intercept_errors on;
    fastcgi_index index.php;
    fastcgi_pass blog-test:9000;
    fastcgi_split_path_info ^(/blog)(/.*)$;
    fastcgi_param SCRIPT_FILENAME $request_filename;
    fastcgi_param PATH_INFO $fastcgi_path_info;
  }

UPDATE 2 :

Now this works ( the blog and the posts can be accesed ) , but the admin seems to be going into a redirect loop:

  location /blog {
    alias /var/www/html;
    index index.php;
    try_files $uri $uri/ /blog/index.php?q=$uri&$args;
  }

  location ~ \.php$ {
    alias /var/www/html;
    try_files $uri $uri/ /index.php?$args;
    include fastcgi_params;
    fastcgi_intercept_errors on;
    fastcgi_index index.php;
    fastcgi_pass blog-test:9000;
    fastcgi_param SCRIPT_FILENAME $request_filename;
  }

UPDATE 3 & FIX :

This apparently works, but the config seems to be really unpleasant and unoptimised. If I try to nest the php location into the blog block, then the php files will download instead of rendering. If I try to use alias instead of root, some pages will not show resulting in 404. In any case, this seems to be functional:

  root /var/www/html;
  index index.php;

  location /blog {
    rewrite ^/blog(.*)$ /$1 break;
    try_files $uri $uri/ /blog/index.php?$args;
  }

  location ~ \.php$ {
    rewrite ^/blog(.*)$ $1 break;
    fastcgi_pass blog-test:9000;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_split_path_info ^(/blog)(/.*)$;
    fastcgi_param SCRIPT_FILENAME $request_filename;
    fastcgi_param PATH_INFO $fastcgi_path_info;
  }


问:
Providing implicit evidence for context bounds on Object
I'm trying to write some abstractions in some Spark Scala code, but running into some issues when using objects. I'm using Spark's Encoder which is used to convert case classes to database schema's here as an example, but I think this question goes for any context bound.

Here is a minimal code example of what I'm trying to do:

```<code>package com.sample.myexample

import org.apache.spark.sql.Encoder
import scala.reflect.runtime.universe.TypeTag

case class MySparkSchema(id: String, value: Double)

abstract class MyTrait[T: TypeTag: Encoder]

object MyObject extends MyTrait[MySparkSchema]
</code>```

Which fails with the following compilation error:

```<code>Unable to find encoder for type com.sample.myexample.MySparkSchema. An implicit Encoder[com.sample.myexample.MySparkSchema] is needed to store com.sample.myexample.MySparkSchema instances in a Dataset. Primitive types (Int, String, etc) and Product types (case classes) are supported by importing spark.implicits._  Support for serializing other types will be added in future releases.
</code>```

I tried defining the implicit evidence in the object like such: (the import statement was suggested by IntelliJ, but it looks a bit weird)

```<code>import com.sample.myexample.MyObject.encoder

object MyObject extends MyTrait[MySparkSchema] {
  implicit val encoder: Encoder[MySparkSchema] = Encoders.product[MySparkSchema]
}
</code>```

Which fails with the error message

```<code>MyTrait.scala:13:25: super constructor cannot be passed a self reference unless parameter is declared by-name
</code>```

One other thing I tried is to convert the object to a class and provide implicit evidence to the constructor:

```<code>class MyObject(implicit evidence: Encoder[MySparkSchema]) extends MyTrait[MySparkSchema]
</code>```

This compiles and works fine, but at the expense of MyObject now being a class instead.

Question: Is it possible to provide implicit evidence for the context bounds when extending a trait? Or does the implicit evidence force me to make a constructor and use class instead?

答:
Your first error almost gives you the solution, you have to import spark.implicits._ for Product types.

You could do this:

```<code>val spark: SparkSession = SparkSession.builder().getOrCreate()
import spark.implicits._
</code>```

Full Example

```<code>package com.sample.myexample

import org.apache.spark.sql.Encoder
import scala.reflect.runtime.universe.TypeTag

case class MySparkSchema(id: String, value: Double)

abstract class MyTrait[T: TypeTag: Encoder]

val spark: SparkSession = SparkSession.builder().getOrCreate()
import spark.implicits._

object MyObject extends MyTrait[MySparkSchema]
</code>```

Body:
I'm trying to write some abstractions in some Spark Scala code, but running into some issues when using objects. I'm using Spark's Encoder which is used to convert case classes to database schema's here as an example, but I think this question goes for any context bound.

Here is a minimal code example of what I'm trying to do:

package com.sample.myexample

import org.apache.spark.sql.Encoder
import scala.reflect.runtime.universe.TypeTag

case class MySparkSchema(id: String, value: Double)

abstract class MyTrait[T: TypeTag: Encoder]

object MyObject extends MyTrait[MySparkSchema]

Which fails with the following compilation error:

Unable to find encoder for type com.sample.myexample.MySparkSchema. An implicit Encoder[com.sample.myexample.MySparkSchema] is needed to store com.sample.myexample.MySparkSchema instances in a Dataset. Primitive types (Int, String, etc) and Product types (case classes) are supported by importing spark.implicits._  Support for serializing other types will be added in future releases.

I tried defining the implicit evidence in the object like such: (the import statement was suggested by IntelliJ, but it looks a bit weird)

import com.sample.myexample.MyObject.encoder

object MyObject extends MyTrait[MySparkSchema] {
  implicit val encoder: Encoder[MySparkSchema] = Encoders.product[MySparkSchema]
}

Which fails with the error message

MyTrait.scala:13:25: super constructor cannot be passed a self reference unless parameter is declared by-name

One other thing I tried is to convert the object to a class and provide implicit evidence to the constructor:

class MyObject(implicit evidence: Encoder[MySparkSchema]) extends MyTrait[MySparkSchema]

This compiles and works fine, but at the expense of MyObject now being a class instead.

Question: Is it possible to provide implicit evidence for the context bounds when extending a trait? Or does the implicit evidence force me to make a constructor and use class instead?

Body:
Your first error almost gives you the solution, you have to import spark.implicits._ for Product types.

You could do this:

val spark: SparkSession = SparkSession.builder().getOrCreate()
import spark.implicits._

Full Example

package com.sample.myexample

import org.apache.spark.sql.Encoder
import scala.reflect.runtime.universe.TypeTag

case class MySparkSchema(id: String, value: Double)

abstract class MyTrait[T: TypeTag: Encoder]

val spark: SparkSession = SparkSession.builder().getOrCreate()
import spark.implicits._

object MyObject extends MyTrait[MySparkSchema]


问:
How do I create a loader that will load in between images when they load in an image slider in react js
I am a beginner in learning  react, I create a project portfolio using image slider, I want to be able to create a loader in between whenever the image load one after the other.
Here is the link to the code
https://github.com/motuncoded/fatah-website/blob/main/src/components/ImageGuitarSlider.js</p>

答:
Unfortunately there is not much info to go on, but you can use a useEffect to achieve this. Here is a generic example you can start off with: In your ImageSilder add a useState for loading and in the useEffect use a promise with a timeout of 1.5 seconds.

```<code>const [loading, setLoading] = useState(false)

useEffect(() => {

    setLoading(true)
    const loadingHandler = () => {
        return new Promise(resolve => {
            setTimeout(() => {
                resolve()
            }, 1500)

        }
    }

    loadingHandler.then(() => setLoading(false))

}, [ticket])
</code>```

Whenever the ticket state is changed it will trigger useEffect (we pass the ticket as a dependency to useEffect) which will set the loading state to true, wait 1.5 seconds and set loading to false. You can use this loading state to display a loading icon, for example, a spinner or loading bar.

This may not be a full solution, based on the info provided in your description, it can be a starting point in what you are looking for.

Body:
Unfortunately there is not much info to go on, but you can use a useEffect to achieve this. Here is a generic example you can start off with: In your ImageSilder add a useState for loading and in the useEffect use a promise with a timeout of 1.5 seconds.

const [loading, setLoading] = useState(false)

useEffect(() => {

    setLoading(true)
    const loadingHandler = () => {
        return new Promise(resolve => {
            setTimeout(() => {
                resolve()
            }, 1500)

        }
    }

    loadingHandler.then(() => setLoading(false))

}, [ticket])

Whenever the ticket state is changed it will trigger useEffect (we pass the ticket as a dependency to useEffect) which will set the loading state to true, wait 1.5 seconds and set loading to false. You can use this loading state to display a loading icon, for example, a spinner or loading bar.

This may not be a full solution, based on the info provided in your description, it can be a starting point in what you are looking for.


问:
ng8 upgrade: ERROR: Unknown version 67 of android
I'm upgrading my angular app from 7.2 to 8.x. And after running the ng update command, the dependencies in the package.json are updated. But when I run ng build I got the following error message:

```<code>ERROR: Unknown version 67 of android
An unhandled exception occurred: Unknown version 67 of android
</code>```

In the log file also find the following line:

```<code>[error] BrowserslistError: Unknown version 67 of android
</code>```

So what's the problem? Where should I debug this issue?

答:
In my case I needed to change the file .browserslistrc to:

```<code>last 1 Chrome version
last 1 Firefox version
last 2 Edge major versions
last 2 Safari major versions
last 2 iOS major versions
Firefox ESR
not IE 11
</code>```

when I only had this content, I got the error: BrowserslistError: Unknown version 92 of android

```<code>last 2 versions
</code>```

Body:
I'm upgrading my angular app from 7.2 to 8.x. And after running the ng update command, the dependencies in the package.json are updated. But when I run ng build I got the following error message:

ERROR: Unknown version 67 of android
An unhandled exception occurred: Unknown version 67 of android

In the log file also find the following line:

[error] BrowserslistError: Unknown version 67 of android

So what's the problem? Where should I debug this issue?

Body:
In my case I needed to change the file .browserslistrc to:

last 1 Chrome version
last 1 Firefox version
last 2 Edge major versions
last 2 Safari major versions
last 2 iOS major versions
Firefox ESR
not IE 11

when I only had this content, I got the error: BrowserslistError: Unknown version 92 of android

last 2 versions


问:
How can I change the hash sign in the url of a page to some other value?
WIth this code </p>

```<code>     <script type="text/javascript">
               window.location.hash="Aboutus";
  </script>
</code>```

<p>,I get url#Aboutus..
I want to change this sign to some other value ..How can I procees?</p>

答:
Try: </p>

```<code>window.location.href += "#Abouts";
alert(location.hash.slice(1)); //Abouts
</code>```

ContentLicense: CC BY-SA 3.0

Body:
WIth this code

,I get url#Aboutus..
I want to change this sign to some other value ..How can I procees?

Body:
Try:

window.location.href += "#Abouts";
alert(location.hash.slice(1)); //Abouts


问:
SQL to compare 2 joins to the same table
I have a table that maps accounts to users. Accounts can have multiple users. User can be in multiple accounts.

```<code>account_id  | user_id
------------+---------
1234          a
1234          b
5678          c
6789          a
</code>```

For example, here user "a" is in accounts 1234 and 6789.

I have another table with account details.

```<code>account_id  | status     | ...
------------+------------+-----
1234          ACTIVE
5678          ACTIVE
6789          SUSPENDED
</code>```

I want to know all the users who are ACTIVE in one account while SUSPENDED in another account. (Any mix, if they're in more than 2 accounts.) In the above example, user "a" is ACTIVE in 1234 and SUSPENDED in 6789.

My attempt started as...

```<code>SELECT user_id FROM mappings
LEFT JOIN account_details AS x ON account_id = x.id AND x.status = 'ACTIVE'
LEFT JOIN account_details AS y ON account_id = y.id AND y.status = 'SUSPENDED'
</code>```

But that seems wrong and I don't know how I'd ensure the 2 joins are linked to the same user. There must be a different way to approach this problem that I'm not seeing.

Thanks for any hints.

答:
Assuming Microsoft SQL Server; it shouldn't be too hard to adapt if you're using a different DBMS:</p>
```<code>SELECT
    id, ...
FROM
    users As u
WHERE
    Exists
    (
        SELECT 1
        FROM mappings As m
        INNER JOIN account_details As a
        ON a.id = m.account_id
        WHERE m.user_id = u.id
        AND a.status = 'ACTIVE'
    )
AND
    Exists
    (
        SELECT 1
        FROM mappings As m
        INNER JOIN account_details As a
        ON a.id = m.account_id
        WHERE m.user_id = u.id
        AND a.status = 'SUSPENDED'
    )
;
</code>```

Body:
I have a table that maps accounts to users. Accounts can have multiple users. User can be in multiple accounts.

account_id  | user_id
------------+---------
1234          a
1234          b
5678          c
6789          a

For example, here user "a" is in accounts 1234 and 6789.

I have another table with account details.

account_id  | status     | ...
------------+------------+-----
1234          ACTIVE
5678          ACTIVE
6789          SUSPENDED

I want to know all the users who are ACTIVE in one account while SUSPENDED in another account. (Any mix, if they're in more than 2 accounts.) In the above example, user "a" is ACTIVE in 1234 and SUSPENDED in 6789.

My attempt started as...

SELECT user_id FROM mappings
LEFT JOIN account_details AS x ON account_id = x.id AND x.status = 'ACTIVE'
LEFT JOIN account_details AS y ON account_id = y.id AND y.status = 'SUSPENDED'

But that seems wrong and I don't know how I'd ensure the 2 joins are linked to the same user. There must be a different way to approach this problem that I'm not seeing.

Thanks for any hints.

Body:
Assuming Microsoft SQL Server; it shouldn't be too hard to adapt if you're using a different DBMS:

SELECT
    id, ...
FROM
    users As u
WHERE
    Exists
    (
        SELECT 1
        FROM mappings As m
        INNER JOIN account_details As a
        ON a.id = m.account_id
        WHERE m.user_id = u.id
        AND a.status = 'ACTIVE'
    )
AND
    Exists
    (
        SELECT 1
        FROM mappings As m
        INNER JOIN account_details As a
        ON a.id = m.account_id
        WHERE m.user_id = u.id
        AND a.status = 'SUSPENDED'
    )
;


问:
How to ignore S3 Bucket Already Owned By You error
I am creating an S3 bucket and DynamoDB table to store shared state and provide locking, respectively, using Terraform in a Gitlab CI pipeline.

The bucket and db table exist on subsequent runs, as expected. But the stage fails in my pipeline due to "Error creating S3 bucket: BucketAlreadyOwnedByYou" error from AWS when I run terraform apply.

```<code>│ Error: Error creating S3 bucket: BucketAlreadyOwnedByYou: Your previous request to create the named bucket succeeded and you already own it.
│   status code: 409, request id: UIGHUK86587686788, host id: 867876IUIUYasdgadsgdfagfdaghfdgfdsfgsdgfdsgdfgsdq8687GJHKHGJK
│
│   with aws_s3_bucket.terraform_state,
│   on main.tf line 5, in resource "aws_s3_bucket" "terraform_state":
│    5: resource "aws_s3_bucket" "terraform_state" {
│
╵
╷
│ Error: error creating DynamoDB Table: ResourceInUseException: Table already exists: uniquestring-shared-state-locks
│
│   with aws_dynamodb_table.terraform_locks,
│   on main.tf line 24, in resource "aws_dynamodb_table" "terraform_locks":
│   24: resource "aws_dynamodb_table" "terraform_locks" {
</code>```

I could potentially write logic into the pipeline yml script, but I must be missing something - running Terraform to apply any modifications, and doing nothing if there are no modifications, is the whole purpose, no?

At this point, I haven't modified anything yet in either the S3 or DB table yet, all I'm doing is re-running the pipeline. Using Terraform v1.1.5.

答: Based on this question and answer, using Terraform to track the Terraform's shared state resources is not a good idea: Initial setup of terraform backend using terraform</p>

Body:
I am creating an S3 bucket and DynamoDB table to store shared state and provide locking, respectively, using Terraform in a Gitlab CI pipeline.

The bucket and db table exist on subsequent runs, as expected. But the stage fails in my pipeline due to "Error creating S3 bucket: BucketAlreadyOwnedByYou" error from AWS when I run terraform apply.

│ Error: Error creating S3 bucket: BucketAlreadyOwnedByYou: Your previous request to create the named bucket succeeded and you already own it.
│   status code: 409, request id: UIGHUK86587686788, host id: 867876IUIUYasdgadsgdfagfdaghfdgfdsfgsdgfdsgdfgsdq8687GJHKHGJK
│
│   with aws_s3_bucket.terraform_state,
│   on main.tf line 5, in resource "aws_s3_bucket" "terraform_state":
│    5: resource "aws_s3_bucket" "terraform_state" {
│
╵
╷
│ Error: error creating DynamoDB Table: ResourceInUseException: Table already exists: uniquestring-shared-state-locks
│
│   with aws_dynamodb_table.terraform_locks,
│   on main.tf line 24, in resource "aws_dynamodb_table" "terraform_locks":
│   24: resource "aws_dynamodb_table" "terraform_locks" {

I could potentially write logic into the pipeline yml script, but I must be missing something - running Terraform to apply any modifications, and doing nothing if there are no modifications, is the whole purpose, no?

At this point, I haven't modified anything yet in either the S3 or DB table yet, all I'm doing is re-running the pipeline. Using Terraform v1.1.5.


问:
Running order of multiple scripts in an HTML document?
I have an HTML page that i ship to the browser and it contains a couple of script tag.

This is my index.html file:

```<code>  <body>
    <div id="app"></div>

    <script src="src/index.js"></script>

    <script>
      window.test = true;
    </script>
  </body>
</html>

</code>```

And this is my src/index.js file:

```<code><script>

const test = () => {
  if (window.test) {
    console.log("wow!");
  }
};

test();
</script>
</code>```

In the HTML file, i define window.test after i run the src/index.js.
src/index.js will only print to the console if window.test is set to true, but that's being set only after, as the second script.

What is the order in which these scripts will run?
Is there a guarantee that window.test will always be set to true "just in time" for the if statement in src/index.js to print wow!?

CodeSandbox:
https://codesandbox.io/s/javascript-forked-utgh8?file=/index.html

答: In JS called from HTML file the order of the scripts are just like their order of writing in this file "always" will be in that order, which means that in your example window.test Will always have a null value in index.js so nothing will be printed in the console

Body:
I have an HTML page that i ship to the browser and it contains a couple of script tag.

This is my index.html file:

And this is my src/index.js file:

In the HTML file, i define window.test after i run the src/index.js.
src/index.js will only print to the console if window.test is set to true, but that's being set only after, as the second script.

What is the order in which these scripts will run?
Is there a guarantee that window.test will always be set to true "just in time" for the if statement in src/index.js to print wow!?

CodeSandbox:
https://codesandbox.io/s/javascript-forked-utgh8?file=/index.html


问:
Splitting a paragraph into an array and animating each contents of the array on button click
```<code><div id="container">
  <button id="button">Click!</button>
</div>
</code>```

JS:

```<code>const container = document.querySelector("#container");
const button = document.querySelector("#button");
button.addEventListener("click", () => {
     let para = document.createElement("p");
     para.textContent = "Text message one. Text message two. Text message three.";
     let strText = para.textContent;
     let splitText = strText.split(".");

     for (let i=0; i<splitText.length;i++) {
     splitText.textContent += "<span>" + splitText[i] + "</span>";
     }
     container.appendChild(splitText[i]);
});
</code>```

I AM STUCK! How can I write my code such that onclicking the button, the array components of the paragraph is shown(animated) on the div one after another ??
I know about the css animation and transition but I just don't know how to apply it here.

答:
Do you mean something like this?

const container = document.querySelector("#container");
const button = document.querySelector("#button");

let idx = 0;
let sentnce = "Text message one. Text message two. Text message three.";
let texts = sentnce.split(".").slice(0, -1);

button.addEventListener("click", () => {
    if (idx < texts.length) {
        let p = document.createElement("p");
        p.textContent = texts[idx];
        container.appendChild(p);
        ++idx;
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
    <button id="button">Click!</button>
</div></code>```

Body:
  <button id="button">Click!</button>

JS:

const container = document.querySelector("#container");
const button = document.querySelector("#button");
button.addEventListener("click", () => {
     let para = document.createElement("p");
     para.textContent = "Text message one. Text message two. Text message three.";
     let strText = para.textContent;
     let splitText = strText.split(".");

     for (let i=0; i<splitText.length;i++) {
     splitText.textContent += "" + splitText[i] + "";
     }
     container.appendChild(splitText[i]);
});

I AM STUCK! How can I write my code such that onclicking the button, the array components of the paragraph is shown(animated) on the div one after another ??
I know about the css animation and transition but I just don't know how to apply it here.

Body:
Do you mean something like this?

const container = document.querySelector("#container");
const button = document.querySelector("#button");

let idx = 0;
let sentnce = "Text message one. Text message two. Text message three.";
let texts = sentnce.split(".").slice(0, -1);

button.addEventListener("click", () => {
    if (idx < texts.length) {
        let p = document.createElement("p");
        p.textContent = texts[idx];
        container.appendChild(p);
        ++idx;
    }
});

<div id="container">
    <button id="button">Click!</button>
</div>


问:
HTTP requests between docker containers
I have created two very simple containers to understand/test HTTP requests between containers, but for some reason, I just can't get my containers communicating. I keep getting GET http://backend:5000/ net::ERR_NAME_NOT_RESOLVED

My first container, a simple react app with no functionality, just gets container name from process.env.REACT_APP_URL, and makes a get request by fetch(http://${url}:5000/).

```<code>import { useState } from "react";

const MyComponent = () => {
  const [message, setmessage] = useState("Hello");

  async function buttonClick() {
    let url = process.env.REACT_APP_URL;

    try {
      let response = await fetch(`http://${url}:5000/`);
      console.log("This is response", response);
      setmessage(response.data);
    } catch (error) {
      console.log("error occured:", error);
    }
  }

  return (
    <>
      <p>{message}</p>
      <button onClick={buttonClick}>Click Me!</button>
    </>
  );
};

export default MyComponent;
</code>```

My second container, again incredibly simple Flask app, with Hello World served in the homepage route, and nothing else.

```<code>from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/")
def hello_world():
    return jsonify("Hello World"), 200

if __name__ == '__main__':
    app.run(host="0.0.0.0")
</code>```

And their corresponding docker files,

```<code>FROM node:17.4.0-alpine

# set working directory
WORKDIR /app

# add `/app/node_modules/.bin` to $PATH
ENV PATH /app/node_modules/.bin:$PATH

# install app dependencies
COPY package.json ./
COPY package-lock.json ./

RUN npm install --silent
RUN npm install react-scripts@3.4.1 -g --silent

# add app
COPY . ./

# start app
CMD ["npm", "start"]
</code>```
```<code>FROM python:3.6.5-alpine

RUN apk update && apk upgrade && apk add gcc musl-dev libc-dev libc6-compat linux-headers build-base git libffi-dev openssl-dev

COPY . .

RUN pip install -r requirements.txt

CMD ["python", "./myfile.py"]
</code>```

Finally, I am using docker-compose to orchestrate these containers:

```<code>version: "3"

services:
  backend:
    build:
      context: ./server
    container_name: backend
    expose:
      - 5000
    ports:
      - 5000:5000

  frontend:
    build:
      context: ./web
    container_name: frontend
    expose:
      - 3000
    ports:
      - 3000:3000
    environment:
      - REACT_APP_URL=backend
    depends_on:
      - "backend"
    links:
      - "backend:backend"
</code>```

My file system is as follows:

```<code>/sample-app
    |_ server
    |_ web
    |_ docker-compose.yml
</code>```

I have been trying to understand what I am doing wrong and I just can't find it. I appreciate any help.

答:
Your frontend communicates with the backend with the exposed port on the host machine (not a container-container communication that needs to happen if the backend container wanted to connect with a DB container). Therefore, the hostname should be localhost not backend.

Try with the following change

  frontend:
    ...
    ...
    environment:
      - REACT_APP_URL=localhost
    ...
    ...
```
<p>You need to convert the response to JSON as well.</p>
```      let response = await fetch(`http://${url}:5000/`);
      response = await response.json();
      console.log("This is response", response);
      setmessage(response.data);
```

Title: HTTP requests between docker containers

Body:
I have created two very simple containers to understand/test HTTP requests between containers, but for some reason, I just can't get my containers communicating. I keep getting GET http://backend:5000/ net::ERR_NAME_NOT_RESOLVED

My first container, a simple react app with no functionality, just gets container name from process.env.REACT_APP_URL, and makes a get request by fetch(http://${url}:5000/).

import { useState } from "react";

const MyComponent = () => {
  const [message, setmessage] = useState("Hello");

  async function buttonClick() {
    let url = process.env.REACT_APP_URL;

    try {
      let response = await fetch(`http://${url}:5000/`);
      console.log("This is response", response);
      setmessage(response.data);
    } catch (error) {
      console.log("error occured:", error);
    }
  }

  return (
    <>

{message}

      <button onClick={buttonClick}>Click Me!</button>
    </>
  );
};

export default MyComponent;

My second container, again incredibly simple Flask app, with Hello World served in the homepage route, and nothing else.

from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/")
def hello_world():
    return jsonify("Hello World"), 200

if __name__ == '__main__':
    app.run(host="0.0.0.0")

And their corresponding docker files,

FROM node:17.4.0-alpine

# set working directory
WORKDIR /app

# add `/app/node_modules/.bin` to $PATH
ENV PATH /app/node_modules/.bin:$PATH

# install app dependencies
COPY package.json ./
COPY package-lock.json ./

RUN npm install --silent
RUN npm install react-scripts@3.4.1 -g --silent

# add app
COPY . ./

# start app
CMD ["npm", "start"]

FROM python:3.6.5-alpine

RUN apk update && apk upgrade && apk add gcc musl-dev libc-dev libc6-compat linux-headers build-base git libffi-dev openssl-dev

COPY . .

RUN pip install -r requirements.txt

CMD ["python", "./myfile.py"]

Finally, I am using docker-compose to orchestrate these containers:

version: "3"

services:
  backend:
    build:
      context: ./server
    container_name: backend
    expose:
      - 5000
    ports:
      - 5000:5000

  frontend:
    build:
      context: ./web
    container_name: frontend
    expose:
      - 3000
    ports:
      - 3000:3000
    environment:
      - REACT_APP_URL=backend
    depends_on:
      - "backend"
    links:
      - "backend:backend"

My file system is as follows:

/sample-app
    |_ server
    |_ web
    |_ docker-compose.yml

I have been trying to understand what I am doing wrong and I just can't find it. I appreciate any help.

Body:
Your frontend communicates with the backend with the exposed port on the host machine (not a container-container communication that needs to happen if the backend container wanted to connect with a DB container). Therefore, the hostname should be localhost not backend.

Try with the following change

  frontend:
    ...
    ...
    environment:
      - REACT_APP_URL=localhost
    ...
    ...

You need to convert the response to JSON as well.

      let response = await fetch(`http://${url}:5000/`);
      response = await response.json();
      console.log("This is response", response);
      setmessage(response.data);


问:
Pagination not iterating over pages
Want to iterate all pages from this url ""url = "https://www.iata.org/en/about/members/airline-list/"" and dump the results in a .csv file.

How could implementing a piece of code to iterate through the pages be included in the current code below?

```<code>import requests
import pandas as pd
from bs4 import BeautifulSoup
from urllib.request import Request

url = 'https://www.iata.org/en/about/members/airline-list/'
req = Request(url , headers = {
                            'accept':'*/*',
                            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36'})

data = []

while True:
    print(url)
    html = requests.get(url)
    soup = BeautifulSoup(html.text, 'html.parser')
    data.append(pd.read_html(soup.select_one('table.datatable').prettify())[0])

    if soup.select_one('span.pagination-link.is-active + div a[href]'):
        url = soup.select_one('span.pagination-link.is-active + div a')['href']
    else:
        break
df = pd.concat(data)
df.to_csv('airline-list.csv',encoding='utf-8-sig',index=False)
</code>```

答:
Try this approach:</p>
```<code>for i in range(1, 30):
    url = f'https://www.iata.org/en/about/members/airline-list/?page={i}&search=&ordering=Alphabetical'
    html = requests.get(url)
    soup = BeautifulSoup(html.text, 'html.parser')
    data.append(pd.read_html(soup.select_one('table.datatable').prettify())[0])
</code>```

Title: Pagination not iterating over pages

Body:
Want to iterate all pages from this url ""url = "https://www.iata.org/en/about/members/airline-list/"" and dump the results in a .csv file.

How could implementing a piece of code to iterate through the pages be included in the current code below?

import requests
import pandas as pd
from bs4 import BeautifulSoup
from urllib.request import Request

url = 'https://www.iata.org/en/about/members/airline-list/'
req = Request(url , headers = {
                            'accept':'*/*',
                            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36'})

data = []

while True:
    print(url)
    html = requests.get(url)
    soup = BeautifulSoup(html.text, 'html.parser')
    data.append(pd.read_html(soup.select_one('table.datatable').prettify())[0])

    if soup.select_one('span.pagination-link.is-active + div a[href]'):
        url = soup.select_one('span.pagination-link.is-active + div a')['href']
    else:
        break
df = pd.concat(data)
df.to_csv('airline-list.csv',encoding='utf-8-sig',index=False)

Body:
Try this approach:

for i in range(1, 30):
    url = f'https://www.iata.org/en/about/members/airline-list/?page={i}&search=&ordering=Alphabetical'
    html = requests.get(url)
    soup = BeautifulSoup(html.text, 'html.parser')
    data.append(pd.read_html(soup.select_one('table.datatable').prettify())[0])


问:
React Native rounded image with a border
I want to create a rounded image with a border. If I add borderColor: 'green', borderWidth:1, border is visible only in top left part of the rounded image.

```<code><TouchableHighlight
          style={[styles.profileImgContainer, { borderColor: 'green', borderWidth:1 }]}
        >
    <Image source={{ uri:"https://www.t-nation.com/system/publishing/articles/10005529/original/6-Reasons-You-Should-Never-Open-a-Gym.png" }} style={styles.profileImg} />
</TouchableHighlight>

export default styles = StyleSheet.create({
  profileImgContainer: {
    marginLeft: 8,
    height: 80,
    width: 80,
    borderRadius: 40,
  },
  profileImg: {
    height: 80,
    width: 80,
    borderRadius: 40,
  },
});
</code>```

答:
If you want to show the image with rounded corner and with resizeMode={'contain'} to show the full image then wrap the image inside a view and then give border radius to the view. it will work

```<code> <View style={styles.carImageHolder}>
                    <Image
                      source={{
                        uri: each?.usercar_details?.car_model?.sized_photo,
                      }}
                      resizeMode={'contain'}
                      style={styles.carImage}
                    />
                  </View>
</code>```

and the style part

```<code>  carImage: {
    width: '100%',
    aspectRatio: 1 / 1,
  },
  carImageHolder: {
    width: '28.3%',
    aspectRatio: 1 / 1,
    backgroundColor: '#d8d8d8',
    borderRadius: 25,
    overflow: 'hidden',
  },
</code>```

Body:
I want to create a rounded image with a border. If I add borderColor: 'green', borderWidth:1, border is visible only in top left part of the rounded image.

<TouchableHighlight
          style={[styles.profileImgContainer, { borderColor: 'green', borderWidth:1 }]}
        >
    <Image source={{ uri:"https://www.t-nation.com/system/publishing/articles/10005529/original/6-Reasons-You-Should-Never-Open-a-Gym.png" }} style={styles.profileImg} />
</TouchableHighlight>

export default styles = StyleSheet.create({
  profileImgContainer: {
    marginLeft: 8,
    height: 80,
    width: 80,
    borderRadius: 40,
  },
  profileImg: {
    height: 80,
    width: 80,
    borderRadius: 40,
  },
});

Body:
If you want to show the image with rounded corner and with resizeMode={'contain'} to show the full image then wrap the image inside a view and then give border radius to the view. it will work

 <View style={styles.carImageHolder}>
                    <Image
                      source={{
                        uri: each?.usercar_details?.car_model?.sized_photo,
                      }}
                      resizeMode={'contain'}
                      style={styles.carImage}
                    />
                  </View>

and the style part

  carImage: {
    width: '100%',
    aspectRatio: 1 / 1,
  },
  carImageHolder: {
    width: '28.3%',
    aspectRatio: 1 / 1,
    backgroundColor: '#d8d8d8',
    borderRadius: 25,
    overflow: 'hidden',
  },


问:
Work Backwards Through URL to Find the First Existing Folder
We have written an API that helps internal users upload and download from SharePoint Online via Excel and other tools. The code is all in C# and we have a 'Browser' UI that allows users to navigate to sites/folder/files by host etc.

We've had some feedback that if a user supplies an invalid folder request, can we work backwords until we find the first valid child folder of the Documents root.

So, as an example, a user provides the URL:

https://example.sharepoint.com/sites/client_XXXXXX_Description/Documents/AdditionalDocuments/CalculationMaterials/CalculationLogging/Job99/

Where both CalculationLogging and Job99 doesn't exist. What I need to do is, starting at Job99, work backwards each level until I find a valid folder, i.e. https://example.sharepoint.com/sites/client_XXXXXX_Description/Documents/AdditionalDocuments/CalculationMaterials/

BUT if its get as far back as Documents, then stop, and tell user they have provided an invalid path.

Here's my code though it feels a bit 'clunky'!

```<code>                // Define new object
            var gc = new GraphClient();
            // Check to see if the item exists
            var exists = await gc.CheckRemoteItemExistsAsync(model.Url);
            // Based on the results of the request
            switch (exists)
            {
                // The path is a valid file
                case "file":
                    // Store the actual filename from the path
                    model.FileName = model.Url.Substring(model.Url.LastIndexOf('/') + 1);
                    // remove the filename from the URL (as we don't use it)
                    model.Url = model.Url.Substring(0, model.Url.LastIndexOf('/') + 1);
                    break;
                // The path is a valid folder
                case "folder":
                    // Append a trailing / if not present
                    if (!model.Url.EndsWith("/")) model.Url += "/";
                    break;
                case null:
                    // Store the first parent folder as we know the existing child doesn't exist
                    var subFolder = model.Url.Substring(0, model.Url.LastIndexOf('/') + 1);
                    var folderLoops = subFolder.Split('/').Length;
                    // ** Where the path starts with http, deduct 2 from the length **
                    if (subFolder.Split('/')[0].StartsWith("http"))
                    {
                        folderLoops -= 2;
                    }
                    // loop through each folder until you find one that is valid
                    for (var i = folderLoops; i > 1; i--)
                    {
                        // If the parent folder is Documents
                        if (subFolder.Split('/')[i] == "Documents")
                        {
                            // Tell user path is invalid
                            MessageBox.Show(
                                string.Format(Resources.PathDoesNotExistsWarningMessage, $"{model.Url}"),
                                Resources.PathDoesNotExistsWarningMessageCaption,
                                MessageBoxButtons.OK);
                            // exit the loop
                            break;
                        }

                        // Check to see if the item exists
                        exists = await gc.CheckRemoteItemExistsAsync(subFolder);
                        // Based on the results of the request
                        switch (exists)
                        {
                            // The path is a valid file
                            case "file":
                            case "folder":
                                break;
                            case null:
                                // Get the parent folder including the trailing /
                                subFolder = subFolder.Substring(0,
                                    subFolder.Substring(0, subFolder.Length - 1).LastIndexOf('/') + 1);
                                continue;
                        }
                    }

                    break;
            }
</code>```

The ** comment (line 4) is to explain I'm deducting 2 as when the path starts with https://, the split function will return https as item 0, and an empty string as item 1.

FYI The function CheckRemoteItemExistsAsync is using Graph API to check whether the path contains a valid DriveItem or not.

答:
Try following :</p>
```<code>            string input = "example.sharepoint.com/sites/client_XXXXXX_Description/Documents/AdditionalDocuments/CalculationMaterials/CalculationLogging/Job99";
            string[] splitURL = input.Split(new char[] {'/'});
            for(int i = splitURL.Length; i > 0; i--)
            {
                string[] URL = splitURL.Take(i).ToArray();
                Console.WriteLine("https://" + string.Join("/",URL));
            }
            Console.ReadLine();
</code>```

Body:
We have written an API that helps internal users upload and download from SharePoint Online via Excel and other tools. The code is all in C# and we have a 'Browser' UI that allows users to navigate to sites/folder/files by host etc.

We've had some feedback that if a user supplies an invalid folder request, can we work backwords until we find the first valid child folder of the Documents root.

So, as an example, a user provides the URL:

https://example.sharepoint.com/sites/client_XXXXXX_Description/Documents/AdditionalDocuments/CalculationMaterials/CalculationLogging/Job99/

Where both CalculationLogging and Job99 doesn't exist. What I need to do is, starting at Job99, work backwards each level until I find a valid folder, i.e. https://example.sharepoint.com/sites/client_XXXXXX_Description/Documents/AdditionalDocuments/CalculationMaterials/

BUT if its get as far back as Documents, then stop, and tell user they have provided an invalid path.

Here's my code though it feels a bit 'clunky'!

                // Define new object
            var gc = new GraphClient();
            // Check to see if the item exists
            var exists = await gc.CheckRemoteItemExistsAsync(model.Url);
            // Based on the results of the request
            switch (exists)
            {
                // The path is a valid file
                case "file":
                    // Store the actual filename from the path
                    model.FileName = model.Url.Substring(model.Url.LastIndexOf('/') + 1);
                    // remove the filename from the URL (as we don't use it)
                    model.Url = model.Url.Substring(0, model.Url.LastIndexOf('/') + 1);
                    break;
                // The path is a valid folder
                case "folder":
                    // Append a trailing / if not present
                    if (!model.Url.EndsWith("/")) model.Url += "/";
                    break;
                case null:
                    // Store the first parent folder as we know the existing child doesn't exist
                    var subFolder = model.Url.Substring(0, model.Url.LastIndexOf('/') + 1);
                    var folderLoops = subFolder.Split('/').Length;
                    // ** Where the path starts with http, deduct 2 from the length **
                    if (subFolder.Split('/')[0].StartsWith("http"))
                    {
                        folderLoops -= 2;
                    }
                    // loop through each folder until you find one that is valid
                    for (var i = folderLoops; i > 1; i--)
                    {
                        // If the parent folder is Documents
                        if (subFolder.Split('/')[i] == "Documents")
                        {
                            // Tell user path is invalid
                            MessageBox.Show(
                                string.Format(Resources.PathDoesNotExistsWarningMessage, $"{model.Url}"),
                                Resources.PathDoesNotExistsWarningMessageCaption,
                                MessageBoxButtons.OK);
                            // exit the loop
                            break;
                        }

                        // Check to see if the item exists
                        exists = await gc.CheckRemoteItemExistsAsync(subFolder);
                        // Based on the results of the request
                        switch (exists)
                        {
                            // The path is a valid file
                            case "file":
                            case "folder":
                                break;
                            case null:
                                // Get the parent folder including the trailing /
                                subFolder = subFolder.Substring(0,
                                    subFolder.Substring(0, subFolder.Length - 1).LastIndexOf('/') + 1);
                                continue;
                        }
                    }

                    break;
            }

The ** comment (line 4) is to explain I'm deducting 2 as when the path starts with https://, the split function will return https as item 0, and an empty string as item 1.

FYI The function CheckRemoteItemExistsAsync is using Graph API to check whether the path contains a valid DriveItem or not.

Body:
Try following :

            string input = "example.sharepoint.com/sites/client_XXXXXX_Description/Documents/AdditionalDocuments/CalculationMaterials/CalculationLogging/Job99";
            string[] splitURL = input.Split(new char[] {'/'});
            for(int i = splitURL.Length; i > 0; i--)
            {
                string[] URL = splitURL.Take(i).ToArray();
                Console.WriteLine("https://" + string.Join("/",URL));
            }
            Console.ReadLine();


问:
Fluentd + azure data explorer cluster
I'm working on fluentd setup in kubernetes. In kubernetes I have a number of applications which are writing some logs into stdout. I can filter, parse, and send logs to azure blob storage. But I want the logs from blob storage to be ingested into azure data explorer cluster. In data explorer cluster I have a database and table which has some schema defined, already. The question is how do I modify event from fluentd in such a way that it's going to meet the table schema? Is it possible at all? Maybe there are some alternative ways of creating such setup?</p>

答:
Yes it is possible to do this. You can ingest data stored in your blob to a custom table on azure data explorer. Refer this link

https://learn.microsoft.com/en-us/azure/data-explorer/ingest-json-formats?tabs=kusto-query-language#ingest-mapped-json-records

The below is an example where i ingest a JSON document stored in blob to a table in ADX

```<code>.ingest into table Events ('https://kustosamplefiles.blob.core.windows.net/jsonsamplefiles/simple.json') with '{"format":"json", "ingestionMappingReference":"FlatEventMapping"}'
</code>```

If the schema is difficult to parse, i would recomment to ingest first to a raw table(Source Table). Then you can have a update policy to move this data into different tables after parsing. You can check this link to understand about Update policy

Title: Fluentd + azure data explorer cluster

Body:
Yes it is possible to do this. You can ingest data stored in your blob to a custom table on azure data explorer. Refer this link

https://learn.microsoft.com/en-us/azure/data-explorer/ingest-json-formats?tabs=kusto-query-language#ingest-mapped-json-records

The below is an example where i ingest a JSON document stored in blob to a table in ADX

.ingest into table Events ('https://kustosamplefiles.blob.core.windows.net/jsonsamplefiles/simple.json') with '{"format":"json", "ingestionMappingReference":"FlatEventMapping"}'

If the schema is difficult to parse, i would recomment to ingest first to a raw table(Source Table). Then you can have a update policy to move this data into different tables after parsing. You can check this link to understand about Update policy


问:
Is there an option to have score of UAC prompt?
I have this script that have goto getPrivileges, and this is useless coz it spams the whole time for UAC, Is there an option to make if you accepted UAC then does 1 thing and if you don't then another?

```<code>@echo off
:init
setlocal DisableDelayedExpansion
set "batchPath=%~0"
for %%k in (%0) do set batchName=%%~nk
set "vbsGetPrivileges=%temp%\OEgetPriv_%batchName%.vbs"
setlocal EnableDelayedExpansion

:checkPrivileges
NET FILE 1>NUL 2>NUL
if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )

:getPrivileges
if '%1'=='ELEV' (echo ELEV & shift /1 & goto gotPrivileges)
echo Set UAC = CreateObject^("Shell.Application"^) > "%vbsGetPrivileges%"
echo args = "ELEV " >> "%vbsGetPrivileges%"
echo For Each strArg in WScript.Arguments >> "%vbsGetPrivileges%"
echo args = args ^& strArg ^& " "  >> "%vbsGetPrivileges%"
echo Next >> "%vbsGetPrivileges%"
echo UAC.ShellExecute "!batchPath!", args, "", "runas", 1 >> "%vbsGetPrivileges%"
"%SystemRoot%\System32\WScript.exe" "%vbsGetPrivileges%" %*
goto getPrivileges
exit /B
</code>```

I would want to have something like this.

```<code>if %UACError% == 0 echo You clicked yes on UAC!
if %UACError% == 1 echo You clicked no on UAC!
</code>```

答:
You shouldn't be doing goto getPrivileges after the launching of the vbs script.

As far as I understand, the content of the vbs script is just relaunching the current batch (!batchPath!) with elevated privileges.

So this relaunching will do :checkPrivileges and go to :gotPrivileges if the elevation was successful, and execute your task requiring elevation.

So for me, you can get rid of your last goto getPrivileges that generates an infinite loop.

To avoid this infinite loop, you can also wait for the vbs script to terminate like this:

```<code>start /WAIT "%SystemRoot%\System32\WScript.exe" "%vbsGetPrivileges%" %*
</code>```

Concerning the result of the UAC, I think the code part inside :checkPrivileges is meant to test just that.

If this does not work, I found another way to check the privileges (here, in french) :

```<code>>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' NEQ '0' ( ...privilege...   ) else (  ...no privilege... )
</code>```

I didn't test it myself, though.

Body:
I have this script that have goto getPrivileges, and this is useless coz it spams the whole time for UAC, Is there an option to make if you accepted UAC then does 1 thing and if you don't then another?

@echo off
:init
setlocal DisableDelayedExpansion
set "batchPath=%~0"
for %%k in (%0) do set batchName=%%~nk
set "vbsGetPrivileges=%temp%\OEgetPriv_%batchName%.vbs"
setlocal EnableDelayedExpansion

:checkPrivileges
NET FILE 1>NUL 2>NUL
if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )

:getPrivileges
if '%1'=='ELEV' (echo ELEV & shift /1 & goto gotPrivileges)
echo Set UAC = CreateObject^("Shell.Application"^) > "%vbsGetPrivileges%"
echo args = "ELEV " >> "%vbsGetPrivileges%"
echo For Each strArg in WScript.Arguments >> "%vbsGetPrivileges%"
echo args = args ^& strArg ^& " "  >> "%vbsGetPrivileges%"
echo Next >> "%vbsGetPrivileges%"
echo UAC.ShellExecute "!batchPath!", args, "", "runas", 1 >> "%vbsGetPrivileges%"
"%SystemRoot%\System32\WScript.exe" "%vbsGetPrivileges%" %*
goto getPrivileges
exit /B

I would want to have something like this.

if %UACError% == 0 echo You clicked yes on UAC!
if %UACError% == 1 echo You clicked no on UAC!

Body:
You shouldn't be doing goto getPrivileges after the launching of the vbs script.

As far as I understand, the content of the vbs script is just relaunching the current batch (!batchPath!) with elevated privileges.

So this relaunching will do :checkPrivileges and go to :gotPrivileges if the elevation was successful, and execute your task requiring elevation.

So for me, you can get rid of your last goto getPrivileges that generates an infinite loop.

To avoid this infinite loop, you can also wait for the vbs script to terminate like this:

start /WAIT "%SystemRoot%\System32\WScript.exe" "%vbsGetPrivileges%" %*

Concerning the result of the UAC, I think the code part inside :checkPrivileges is meant to test just that.

If this does not work, I found another way to check the privileges (here, in french) :

>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' NEQ '0' ( ...privilege...   ) else (  ...no privilege... )

I didn't test it myself, though.