问:
Swift On Demand Resources Queueing Issue
I'm having what I think is a queueing issue. I've never really understood queueing, so really appreciate any help.

```<code>var ODRtags: Set = ["Soprano", "Alto", "Tenor", "Bass", "KeyCentre"]
...
    func testForChangeRangeMessage() {
        let test = ODRtags.checkIfTagsAvailable()
        if test == false {
                showExerciseDownloadAlert = true
        }
        print ("tests show content downloaded = \(test)")
    }
...
extension Set where Element == String {
    func checkIfTagsAvailable()-> Bool {
        let currentRequest = NSBundleResourceRequest(tags: self)
        var avail = false
        currentRequest.conditionallyBeginAccessingResources { status in
            avail = status
            print ("Donwloaded?? \(status)")
        }
        return avail
    }
}

</code>```

So, ideally what would happen is the first func checks if the ODRs are downloaded, using the extension. If not, it'll make a message pop up asking to download them. The issue is that the
print ("tests show content downloaded = \(test)") prints 'false' first, then the print ("Donwloaded?? \(status)") prints true. So it would seem that the first function is calling the extension function, but then continuing on without waiting for an answer from it. I don't really understand Queueing, but I tried throwing both functions inside DispatchQueue.main.async {, with no change in result.

答:
Thanks!! This is how I ended up solving it.</p>
```<code>var ODRtags: Set = ["Soprano", "Alto", "Tenor", "Bass", "KeyCentre"]
...
    func testForChangeRangeMessage() {
        globalVars.ODRtags.checkIfTagsAvailable(onSucsess: onSucsess, onFailure: onFailure)
    }
    func onSucsess() {
        print ("Content already downloaded")
    }
    func onFailure() {
        print ("Content not downloaded. Prompting now")
        showExerciseDownloadAlert = true
    }
...
extension Set where Element == String {
    func checkIfTagsAvailable(onSucsess: @escaping () -> Void, onFailure: @escaping () -> Void){

        let currentRequest = NSBundleResourceRequest(tags: self)

        currentRequest.conditionallyBeginAccessingResources { status in
            if status == true {
                onSucsess()
                return
            }
            onFailure()
        }
    }
}
</code>```

Body:
I'm having what I think is a queueing issue. I've never really understood queueing, so really appreciate any help.

var ODRtags: Set = ["Soprano", "Alto", "Tenor", "Bass", "KeyCentre"]
...
    func testForChangeRangeMessage() {
        let test = ODRtags.checkIfTagsAvailable()
        if test == false {
                showExerciseDownloadAlert = true
        }
        print ("tests show content downloaded = \(test)")
    }
...
extension Set where Element == String {
    func checkIfTagsAvailable()-> Bool {
        let currentRequest = NSBundleResourceRequest(tags: self)
        var avail = false
        currentRequest.conditionallyBeginAccessingResources { status in
            avail = status
            print ("Donwloaded?? \(status)")
        }
        return avail
    }
}

So, ideally what would happen is the first func checks if the ODRs are downloaded, using the extension. If not, it'll make a message pop up asking to download them. The issue is that the
print ("tests show content downloaded = \(test)") prints 'false' first, then the print ("Donwloaded?? \(status)") prints true. So it would seem that the first function is calling the extension function, but then continuing on without waiting for an answer from it. I don't really understand Queueing, but I tried throwing both functions inside DispatchQueue.main.async {, with no change in result.

Body:
Thanks!! This is how I ended up solving it.

var ODRtags: Set = ["Soprano", "Alto", "Tenor", "Bass", "KeyCentre"]
...
    func testForChangeRangeMessage() {
        globalVars.ODRtags.checkIfTagsAvailable(onSucsess: onSucsess, onFailure: onFailure)
    }
    func onSucsess() {
        print ("Content already downloaded")
    }
    func onFailure() {
        print ("Content not downloaded. Prompting now")
        showExerciseDownloadAlert = true
    }
...
extension Set where Element == String {
    func checkIfTagsAvailable(onSucsess: @escaping () -> Void, onFailure: @escaping () -> Void){

        let currentRequest = NSBundleResourceRequest(tags: self)

        currentRequest.conditionallyBeginAccessingResources { status in
            if status == true {
                onSucsess()
                return
            }
            onFailure()
        }
    }
}


来源: stackexchange

问:
How do I pull a Discord ID and transferring it into a username using Discord.NET?
I'm working on an app in c# and I want it to be able to pull a Discord users ID and transfer it into their Username using Discord.NET so if anyone knows how to do it please respond!!</p>

答:
This should work:

```<code>var user = _client.GetUserAsync("ID").result;
var Username = user.Username + user.Discriminator ;
</code>```

Hope this helped.

ContentLicense: CC BY-SA 4.0

Body:
This should work:

var user = _client.GetUserAsync("ID").result;
var Username = user.Username + user.Discriminator ;

Hope this helped.


问:
Lambda function in Python using dictionaries
I need to convert two functions into lambda versions of the same function, I'll post the code and my attempt that isn't working. This is using dictionaries in Python and mapping pairs and then reducing them. For the actual assignment I'm counting odds/evens and these are mapped to either a 1 or 0 but here I'm just using random numbers. I believe without the errors this is minimum replicable code. Thanks for the help!

I attempted changing one line to this:
mapping = lambda v,k: [(key,val) for key in evenOddDict.items()]

Because it didn't recognize key/val. I'm not sure if something special needs to be done for dictionaries here.

```<code>#mapping function without lambda
#def mapping(key,val):
#    reverse = (val,key)
#    return reverse

#mapping function with lambda
mapping = lambda v,k: [(key,val) for entry in dummydata.items()]

#mapReduce function without lambda
#def mapReduce(key,val):
#    if key not in final_output:
#        final_output[key] = []
#    final_output[key].append(val)

#mapReduce function with lambda
mapReduce = lambda k,v:final_output[k] + v

dummydata = {11:1, 36:0, 53:1, 77:0, 95:1, 22:0, 40:1, 63:0, 85:1, 17:0}

map_output = []
for k,v in dummydata.items():
    tmp = mapping(k,v)
    map_output.append(tmp)

for k, v in map_output:
    mapReduce(k,v)

print("\n\n====================================================")
print("       After mapReduce and Final Output")
print("====================================================\n\n")

for i in range (len(map_output)):
    print(map_output[i])

print("\n\n")

for key in final_output:
    print (key,final_output[key])

print("\n\n")
</code>```

答:
These are equivalent versions of your two functions without lambdas.

mapping = lambda k, v: (v, k)

mapReduce = lambda k, v: final_output.setdefault(k, []).append(v)
```

I'll mention in passing that naming lambdas is apparently somewhat discouraged, and, according to PEP 8:

The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression)

If there's a reason you're doing this besides an assignment's requirement, that would be interesting to share, as the consensus seems to be that there is no benefit to named lambdas over normal functions (and some downsides, such as tracebacks for debugging).

Body:
I need to convert two functions into lambda versions of the same function, I'll post the code and my attempt that isn't working. This is using dictionaries in Python and mapping pairs and then reducing them. For the actual assignment I'm counting odds/evens and these are mapped to either a 1 or 0 but here I'm just using random numbers. I believe without the errors this is minimum replicable code. Thanks for the help!

I attempted changing one line to this:
mapping = lambda v,k: [(key,val) for key in evenOddDict.items()]

Because it didn't recognize key/val. I'm not sure if something special needs to be done for dictionaries here.

#mapping function without lambda
#def mapping(key,val):
#    reverse = (val,key)
#    return reverse

#mapping function with lambda
mapping = lambda v,k: [(key,val) for entry in dummydata.items()]

#mapReduce function without lambda
#def mapReduce(key,val):
#    if key not in final_output:
#        final_output[key] = []
#    final_output[key].append(val)

#mapReduce function with lambda
mapReduce = lambda k,v:final_output[k] + v

dummydata = {11:1, 36:0, 53:1, 77:0, 95:1, 22:0, 40:1, 63:0, 85:1, 17:0}

map_output = []
for k,v in dummydata.items():
    tmp = mapping(k,v)
    map_output.append(tmp)

for k, v in map_output:
    mapReduce(k,v)

print("\n\n====================================================")
print("       After mapReduce and Final Output")
print("====================================================\n\n")

for i in range (len(map_output)):
    print(map_output[i])

print("\n\n")

for key in final_output:
    print (key,final_output[key])

print("\n\n")

Body:
These are equivalent versions of your two functions without lambdas.

mapping = lambda k, v: (v, k)

mapReduce = lambda k, v: final_output.setdefault(k, []).append(v)

I'll mention in passing that naming lambdas is apparently somewhat discouraged, and, according to PEP 8:

The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression)

If there's a reason you're doing this besides an assignment's requirement, that would be interesting to share, as the consensus seems to be that there is no benefit to named lambdas over normal functions (and some downsides, such as tracebacks for debugging).


问:
Why does the AWS fleet provisioning plugin does not create a Greengrass Core device in the cloud?
I am following the documentation in "Set up AWS IoT fleet provisioning for Greengrass core devices" and "Install AWS IoT Greengrass Core software with AWS IoT fleet provisioning" for AWS.

I made sure that I am following it correctly. All policies and roles are attached as described, but at the end I manage to download and install the Greengrass Core software on my Linux device but that does not become visible in the AWS cloud. What I mean by that is that no Greengrass Core Device is created in the cloud, and I have it only locally.

Can someone tell me why that is the case? Or it is not supposed to create it in the cloud? If that is the case, how do I get it to be in the cloud as well so I can deploy components to it?

I used this command to execute the installation:

```<code>sudo -E java -Droot="/greengrass/v2" -Dlog.store=FILE -jar ./GreengrassInstaller/lib/Greengrass.jar --trusted-plugin ./GreengrassInstaller/aws.greengrass.FleetProvisioningByClaim.jar --init-config ./GreengrassInstaller/config.yaml --component-default-user ggc_user:ggc_group --setup-system-service true
</code>```

答:
Yes, once you have started the Greengrass core software, you should see a thing registered, and it should be listed under things in the AWS IoT console and also in the Greengrass core device list.

Check the Greengrass logs on your device. I just finished setting it up, and it works for me.

Body:
I am following the documentation in "Set up AWS IoT fleet provisioning for Greengrass core devices" and "Install AWS IoT Greengrass Core software with AWS IoT fleet provisioning" for AWS.

I made sure that I am following it correctly. All policies and roles are attached as described, but at the end I manage to download and install the Greengrass Core software on my Linux device but that does not become visible in the AWS cloud. What I mean by that is that no Greengrass Core Device is created in the cloud, and I have it only locally.

Can someone tell me why that is the case? Or it is not supposed to create it in the cloud? If that is the case, how do I get it to be in the cloud as well so I can deploy components to it?

I used this command to execute the installation:

sudo -E java -Droot="/greengrass/v2" -Dlog.store=FILE -jar ./GreengrassInstaller/lib/Greengrass.jar --trusted-plugin ./GreengrassInstaller/aws.greengrass.FleetProvisioningByClaim.jar --init-config ./GreengrassInstaller/config.yaml --component-default-user ggc_user:ggc_group --setup-system-service true


问:
SvelteKit Pass Data From Server to Browser
I am trying to pass data from the server to the client to load my app faster and prevent multiple calls to the database.

Via Fetch

SvelteKit is made to do this via the fetch function. This is great if you have an endpoint that allows for custom fetch. But what if you don't?

Firebase is a perfect example of not having a custom fetch function.

Cookies

I would think I could use cookies, but when I set the cookie, it just prints 'undefined' and never gets set.

```

So my code loads correctly, then dissapears when the browser load function is loaded...

Surely there is a functioning way to do this?

J

答:
You need to use a handler that injects the cookie into the server response (because load functions do not expose the request or headers to the browser, they are just used for loading props I believe). Example here: https://github.com/sveltejs/kit/blob/59358960ff2c32d714c47957a2350f459b9ccba8/packages/kit/test/apps/basics/src/hooks.js#L42

https://kit.svelte.dev/docs/hooks#handle

export async function handle({ event, resolve }) {
    event.locals.user = await getUserInformation(event.request.headers.get('cookie'));

    const response = await resolve(event);
    response.headers.set('x-custom-header', 'potato');
    response.headers.append('set-cookie', 'name=SvelteKit; path=/; HttpOnly');

    return response;
}
```

FYI: This functionality was only added 11 days ago in @sveltejs/kit@1.0.0-next.267: https://github.com/sveltejs/kit/pull/3631

Body:
I am trying to pass data from the server to the client to load my app faster and prevent multiple calls to the database.

Via Fetch

SvelteKit is made to do this via the fetch function. This is great if you have an endpoint that allows for custom fetch. But what if you don't?

Firebase is a perfect example of not having a custom fetch function.

Cookies

I would think I could use cookies, but when I set the cookie, it just prints 'undefined' and never gets set.

So my code loads correctly, then dissapears when the browser load function is loaded...

Surely there is a functioning way to do this?

J

Body:
You need to use a handler that injects the cookie into the server response (because load functions do not expose the request or headers to the browser, they are just used for loading props I believe). Example here: https://github.com/sveltejs/kit/blob/59358960ff2c32d714c47957a2350f459b9ccba8/packages/kit/test/apps/basics/src/hooks.js#L42

https://kit.svelte.dev/docs/hooks#handle

export async function handle({ event, resolve }) {
    event.locals.user = await getUserInformation(event.request.headers.get('cookie'));

    const response = await resolve(event);
    response.headers.set('x-custom-header', 'potato');
    response.headers.append('set-cookie', 'name=SvelteKit; path=/; HttpOnly');

    return response;
}

FYI: This functionality was only added 11 days ago in @sveltejs/kit@1.0.0-next.267: https://github.com/sveltejs/kit/pull/3631


问:
Is it possible to use React Material UI, redux and react-form-hook together?
I am exploring several online tutorials to learn how these technologies can be used together to build React TypeScript app.

I have two specific questions:

Is it possible to use these three technologies together? I came across this video which explains react-hook-form with redux but not Material-UI. index.js wraps everything (that is, App component which contains router routes to Step1.js, Step2.js etc.) with react-redux Provider. So, to introduce material-UI, all I have to do is to wrap Material UI components inside react-hook-form Controller in files say Step1.js?

This video says that react-hook-form FormProvider requires useFormContext which is based on react context API. Does this mean that we cannot use redux with FormProvider?

答:
Yes. Material UI is simply for the view layer of your components. Redux is a global state management tool, and react-form-hook is for forms. I don't see why you wouldn't be able to use them together.

Even though the FormProvider uses Context API, you can still have your project's global state in a Redux store. If you do want to use Context API, it's practically the same as Redux, so it's up to you.


问:
get unix style path join in python
While making a wsgi app I am in need of joining route names like /apple,  apple/buy etc.

```<code>    import os
    path = os.path.join("/apple/", "/buy")
    print("route path:", path)

</code>```

Now the problem is it works fine in *nix systems but on dos ones the ouput could become:

```<code>    route path: apple\buy
</code>```

cuz what is wanted was unix style paths like - apple/buy

is their a way that I can always get unix style paths? should I use something other than os module?

答:
os.path is for path operations on the current operating system.
Use urllib.parse.urljoin to join URL paths.

Title: get unix style path join in python

Body:
While making a wsgi app I am in need of joining route names like /apple,  apple/buy etc.

    import os
    path = os.path.join("/apple/", "/buy")
    print("route path:", path)

Now the problem is it works fine in *nix systems but on dos ones the ouput could become:

    route path: apple\buy

cuz what is wanted was unix style paths like - apple/buy

is their a way that I can always get unix style paths? should I use something other than os module?


问:
How do I get this for loop to print
Would any happen to know why I keep getting the error below in my for loop?  Any insight would be greatly appreciated and helpful.</p>
```<code>the_count = [1, 2, 3, 4, 5]
for number in the_count:
print(f"This is count {number}")

NameError                                 Traceback (most recent call last)
<ipython-input-3-e3d6b461f13e> in <module>
----> 1 print(f"This is count {number}")

NameError: name 'number' is not defined
</code>```

答:
Well it should give indentation error but it’s giving name error

the_count = [1, 2, 3, 4, 5]
for number in the_count:
    print(f"This is count {number}")
```

This is how your code should be.

Title: How do I get this for loop to print

Body:
Would any happen to know why I keep getting the error below in my for loop?  Any insight would be greatly appreciated and helpful.

the_count = [1, 2, 3, 4, 5]
for number in the_count:
print(f"This is count {number}")

NameError                                 Traceback (most recent call last)
<ipython-input-3-e3d6b461f13e> in <module>
----> 1 print(f"This is count {number}")

NameError: name 'number' is not defined

Body:
Well it should give indentation error but it’s giving name error

the_count = [1, 2, 3, 4, 5]
for number in the_count:
    print(f"This is count {number}")

This is how your code should be.


问:
HRESULT: 0x800A03EC on Worksheet.range
I am getting HRESULT: 0x800A03EC on Worksheet.range method. Number of rows are more than 70K. Office 2007.

Code:

```<code>Microsoft.Office.Interop.Excel.Range neededRange
    = currentWS.Range[cell.Cells[1, 1], cell.Cells[nRowCount, nColumnCount]];
</code>```

Here my rowcount is more than 65530 . Breaks on this function. I have observed that it breaks only when row count goes more than 65530.

答:
I don't understand the issue. But here is the thing that solved my issue. </p>

<p>Go to Excel Options > Save > Save Files in this format > Select "Excel Workbook(*.xlsx)". Previously, my WorkBooks were opening in [Compatibuility Mode] And now they are opening in normal mode. Range function works fine with that. </p>

ContentLicense: CC BY-SA 3.0

Title: HRESULT: 0x800A03EC on Worksheet.range

Body:
I am getting HRESULT: 0x800A03EC on Worksheet.range method. Number of rows are more than 70K. Office 2007.

Code:

Microsoft.Office.Interop.Excel.Range neededRange
    = currentWS.Range[cell.Cells[1, 1], cell.Cells[nRowCount, nColumnCount]];

Here my rowcount is more than 65530 . Breaks on this function. I have observed that it breaks only when row count goes more than 65530.

Body:
I don't understand the issue. But here is the thing that solved my issue.

Go to Excel Options > Save > Save Files in this format > Select "Excel Workbook(*.xlsx)". Previously, my WorkBooks were opening in [Compatibuility Mode] And now they are opening in normal mode. Range function works fine with that.


答:
Are you running this line by line in a terminal or as a .py file? This code works perfectly if you run it as a python file.

```<code>the_count = [1, 2, 3, 4, 5]
for number in the_count:
    print(f"This is count {number}")
</code>```

Which outputs:

```<code>This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
</code>```

You may run into errors with the for loop if you run this code line by line, since the for loop would be executed fully prior to even reading the print statment.

Title: How do I get this for loop to print

Body:
Are you running this line by line in a terminal or as a .py file? This code works perfectly if you run it as a python file.

the_count = [1, 2, 3, 4, 5]
for number in the_count:
    print(f"This is count {number}")

Which outputs:

This is count 1
This is count 2
This is count 3
This is count 4
This is count 5

You may run into errors with the for loop if you run this code line by line, since the for loop would be executed fully prior to even reading the print statment.


问:
React single selectable component
I'm new to react and I'm trying to make a selection button where only a single item can be selected and it deselects the other items. I have made it as far as selecting an item, but not the deselecting the other items part.

Below is my component code :

```<code>class Diamond extends React.Component {
  constructor(props) {
    super(props);
    this.selectDiamond = this.selectDiamond.bind(this);
    this.state = {selected : false};
  }

  selectDiamond() {
    this.setState( {selected : true} );
  }

  render() {
    if (this.state.selected == true) {
      return (
        <div onClick={this.selectDiamond} className="diamond-selected hover:scale-[105%] duration-300 ">{this.props.text}</div>
      )
    } else {
      return(
        <div onClick={this.selectDiamond} className="diamond-unselected hover:scale-[105%] duration-300 ">{this.props.text}</div>
      )
    }
  }
}
</code>```

and this is how I render it :

```<code><div>
    {["BOY", "GIRL", "BAKLA", "TOMBOY"].map((item, i) => (
        <Diamond key={i} text={item}/>
        )
    )}
</div>
</code>```

I know I need a reference to the <Diamond/>s so I tried something like :

```<code>let diamonds = [];

//and on the constructor method of the component
constructor(props) {
   super(props);
   diamonds.push(this);
}
</code>```

but for some reason when I call diamonds.length it gives me double the number of the created items, and I also do not know what to do from there. I also would like the first item to be selected by default.

答:
I would reccomend using hooks instead of class components.
Here is snippet how it can be done:

```<code>const Diamond = ({ text, setSelected, isSelected }) => {
  return (
    <div
      onClick={setSelected}
      className={`diamond-${
        isSelected ? "" : "un"
      }selected hover:scale-[105%] duration-300`}
    >
      {text}
    </div>
  );
};

const ListDiamonds = () => {
  const [selectedIdx, setSelectedIdx] = useState(null);

  return (
    <div>
      {["BOY", "GIRL", "BAKLA", "TOMBOY"].map((item, i) => (
        <Diamond
          key={i}
          text={item}
          isSelected={selectedIdx === i}
          setSelected={() => setSelectedIdx(i)}
        />
      ))}
    </div>
  );
};
</code>```

I did not test it but in general concept it like that.

Also do not push this from constructor, it is bad practice.
You could read rect lifting state up: https://reactjs.org/docs/lifting-state-up.html
or better with hooks: https://www.freecodecamp.org/news/what-is-lifting-state-up-in-react/

Title: React single selectable component

Body:
I'm new to react and I'm trying to make a selection button where only a single item can be selected and it deselects the other items. I have made it as far as selecting an item, but not the deselecting the other items part.

Below is my component code :

class Diamond extends React.Component {
  constructor(props) {
    super(props);
    this.selectDiamond = this.selectDiamond.bind(this);
    this.state = {selected : false};
  }

  selectDiamond() {
    this.setState( {selected : true} );
  }

  render() {
    if (this.state.selected == true) {
      return (

{this.props.text}

      )
    } else {
      return(

{this.props.text}

      )
    }
  }
}

and this is how I render it :

    {["BOY", "GIRL", "BAKLA", "TOMBOY"].map((item, i) => (
        <Diamond key={i} text={item}/>
        )
    )}

I know I need a reference to the <Diamond/>s so I tried something like :

let diamonds = [];

//and on the constructor method of the component
constructor(props) {
   super(props);
   diamonds.push(this);
}

but for some reason when I call diamonds.length it gives me double the number of the created items, and I also do not know what to do from there. I also would like the first item to be selected by default.

Body:
I would reccomend using hooks instead of class components.
Here is snippet how it can be done:

const Diamond = ({ text, setSelected, isSelected }) => {
  return (
    <div
      onClick={setSelected}
      className={`diamond-${
        isSelected ? "" : "un"
      }selected hover:scale-[105%] duration-300`}
    >
      {text}
    </div>
  );
};

const ListDiamonds = () => {
  const [selectedIdx, setSelectedIdx] = useState(null);

  return (
    <div>
      {["BOY", "GIRL", "BAKLA", "TOMBOY"].map((item, i) => (
        <Diamond
          key={i}
          text={item}
          isSelected={selectedIdx === i}
          setSelected={() => setSelectedIdx(i)}
        />
      ))}
    </div>
  );
};

I did not test it but in general concept it like that.

Also do not push this from constructor, it is bad practice.
You could read rect lifting state up: https://reactjs.org/docs/lifting-state-up.html
or better with hooks: https://www.freecodecamp.org/news/what-is-lifting-state-up-in-react/


问:
Public key credentials are not accessible among subdomains during web authentication
I was able to create public-private key pair using web authentication in the browser for a domain "www.exxample.ba" but i am not able to access the credentials using get() from "www.example.co.in".

Is there any way to get past this limitation like using an extension or something.

答:
The simple answer to your question is no, the API itself fundamentally prevents your use case from being possible.

Digging into it a bit, WebAuthn credentials are bound to an RP ID that is the "effective domain" of a single website. The rules are fairly straightforward:

Credentials bound to RP ID "example.com" can be used to authenticate on https://example.com and https://subdomain.example.com

Credentials bound to "subdomain.example.com" can be used on https://subdomain.example.com but NOT on https://example.com/

Credentials bound to "example.com" CANNOT be used on https://example.org


问:
Can't clone repository: git@gitlab.com: Permission denied (publickey,keyboard-interactive)
I have tried anything I can think of and find online by this point to get it to work but nothing I have tried works.

I am using Windows 10. I already have a repository on GitLab and an SSH-key assigned. And I just want to clone/push/pull the normal stuff.

When I do ssh -Tv git@gitlab.com I get;
Welcome to GitLab, @user!.

But when I try to clone the repo  using
git clone git@gitlab.com:user/my-repo.git
I get;

```<code>git@gitlab.com: Permission denied (publickey,keyboard-interactive).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

This is my config in .ssh, saw some people solving their problem by doing this.

```<code>Host gitlab.com
     User git
     Hostname gitlab.com
     IdentityFile ~/.ssh/id_ed25519
     Preferredauthentications publickey
     TCPKeepAlive yes
     IdentitiesOnly yes
</code>```

I have also tried using the GitLab Personal token with GitLab workflow on vsc and I can see the repo when I use the menu under Git Clone > Clone from GitLab > user/my-repo.
I can also Open remote repo using the GitLab workflow on vsc, and I can see my code.
When  trying to clone the repo using
git clone https://gitlab.com/user/my-repo.git
I get;

```<code>remote: HTTP Basic: Access denied
remote: You must use a personal access token with 'read_repository' or 'write_repository' scope for Git over HTTP.
remote: You can generate one at https://gitlab.com/-/profile/personal_access_tokens
fatal: Authentication failed for 'https://gitlab.com/user/my-repo.git/'
</code>```

I have remade the ssh keys multiple times both rsa and ed25519, I have removed and added a new personal token nothing works.

Does anyone have had the same problems? How did you solve it?
I've seen

I have replaced my username and repo name with user and my-repo.

答:
If using ssh -Tv git@gitlab.com works, but using git clone ssh://git@gitlab.com:foo/bar.git does not, it's likely due to git not using the same ssh program and thus, when ssh is invoked by git, it looks in a different location for your keys.

This is a common misconfiguration on Windows when using git for Windows.

One fix is to set the GIT_SSH environment variable to point to the location of the correct ssh binary or setting your PATH variable such that the correct version of ssh is resolved correctly.

Occasionally, there may be other programs you install that place different versions of git or ssh on PATH for your system. This can interfere with how git works. To know which ones you are currently using run the following commands:

```<code>where git
</code>```
```<code>where ssh
</code>```

In most cases for Windows 10 users, where git should resolve to C:\Program Files\Git\cmd\git.exe and where ssh should resolve to C:\Windows\System32\OpenSSH\ssh.exe

If the where ssh command does NOT resolve to C:\Windows\System32\OpenSSH\ssh.exe (if there are multiple results, it must be the first) and your GIT_SSH environment variable is not set (or is set to some other location) use the following command to fix:

```<code>setx GIT_SSH C:\Windows\System32\OpenSSH\ssh.exe
</code>```

(in some other circumstances, this may resolve your issue, even if where ssh seems correct)

If your where git command resolves to something other than C:\Program Files\Git\cmd\git.exe (if multiple are listed, it should be the first) you'll want to remove the errant entry from your PATH environment variables. (easiest way is to search "environment variables" from the start menu and use the GUI to edit your USER or SYSTEM PATH environment variable). Also make sure you've installed git using the official 64bit installer.

Lastly, ensure that the Windows OpenSSH Authentication Agent service is running. Open "Services" then find "Windows OpenSSH Authentication Agent" and ensure that the service is running. Also make sure your SSH configuration and keys are located under C:\Users\yourusername\.ssh

Between all these steps, you should be able to ensure that git plays nicely with ssh.

An alternative to all of this would be to launch git using "Git Bash" which will self-contains its own git and ssh binaries, and automatically uses your .ssh directory in your user profile home, which should avoid any other environmental issues on your system. However, that may not be convenient because you'll have to open git bash any time you want to use git and your IDE or other programs may not use Git Bash automatically.

Additional references:

Git with SSH on Windows

How to run ssh-add on windows?

Body:
I have tried anything I can think of and find online by this point to get it to work but nothing I have tried works.

I am using Windows 10. I already have a repository on GitLab and an SSH-key assigned. And I just want to clone/push/pull the normal stuff.

When I do ssh -Tv git@gitlab.com I get;
Welcome to GitLab, @user!.

But when I try to clone the repo  using
git clone git@gitlab.com:user/my-repo.git
I get;

git@gitlab.com: Permission denied (publickey,keyboard-interactive).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

This is my config in .ssh, saw some people solving their problem by doing this.

Host gitlab.com
     User git
     Hostname gitlab.com
     IdentityFile ~/.ssh/id_ed25519
     Preferredauthentications publickey
     TCPKeepAlive yes
     IdentitiesOnly yes

I have also tried using the GitLab Personal token with GitLab workflow on vsc and I can see the repo when I use the menu under Git Clone > Clone from GitLab > user/my-repo.
I can also Open remote repo using the GitLab workflow on vsc, and I can see my code.
When  trying to clone the repo using
git clone https://gitlab.com/user/my-repo.git
I get;

remote: HTTP Basic: Access denied
remote: You must use a personal access token with 'read_repository' or 'write_repository' scope for Git over HTTP.
remote: You can generate one at https://gitlab.com/-/profile/personal_access_tokens
fatal: Authentication failed for 'https://gitlab.com/user/my-repo.git/'

I have remade the ssh keys multiple times both rsa and ed25519, I have removed and added a new personal token nothing works.

Does anyone have had the same problems? How did you solve it?
I've seen

I have replaced my username and repo name with user and my-repo.

Body:
If using ssh -Tv git@gitlab.com works, but using git clone ssh://git@gitlab.com:foo/bar.git does not, it's likely due to git not using the same ssh program and thus, when ssh is invoked by git, it looks in a different location for your keys.

This is a common misconfiguration on Windows when using git for Windows.

One fix is to set the GIT_SSH environment variable to point to the location of the correct ssh binary or setting your PATH variable such that the correct version of ssh is resolved correctly.

Occasionally, there may be other programs you install that place different versions of git or ssh on PATH for your system. This can interfere with how git works. To know which ones you are currently using run the following commands:

where git

where ssh

In most cases for Windows 10 users, where git should resolve to C:\Program Files\Git\cmd\git.exe and where ssh should resolve to C:\Windows\System32\OpenSSH\ssh.exe

If the where ssh command does NOT resolve to C:\Windows\System32\OpenSSH\ssh.exe (if there are multiple results, it must be the first) and your GIT_SSH environment variable is not set (or is set to some other location) use the following command to fix:

setx GIT_SSH C:\Windows\System32\OpenSSH\ssh.exe

(in some other circumstances, this may resolve your issue, even if where ssh seems correct)

If your where git command resolves to something other than C:\Program Files\Git\cmd\git.exe (if multiple are listed, it should be the first) you'll want to remove the errant entry from your PATH environment variables. (easiest way is to search "environment variables" from the start menu and use the GUI to edit your USER or SYSTEM PATH environment variable). Also make sure you've installed git using the official 64bit installer.

Lastly, ensure that the Windows OpenSSH Authentication Agent service is running. Open "Services" then find "Windows OpenSSH Authentication Agent" and ensure that the service is running. Also make sure your SSH configuration and keys are located under C:\Users\yourusername\.ssh

Between all these steps, you should be able to ensure that git plays nicely with ssh.

An alternative to all of this would be to launch git using "Git Bash" which will self-contains its own git and ssh binaries, and automatically uses your .ssh directory in your user profile home, which should avoid any other environmental issues on your system. However, that may not be convenient because you'll have to open git bash any time you want to use git and your IDE or other programs may not use Git Bash automatically.

Additional references:

Git with SSH on Windows

How to run ssh-add on windows?


问:
Selenium send_keys doesn't do the same element twice
I'm trying to send keys to Wordle based on the elements in the HTML, and have found that whenever there is a duplicate of a letter it won't press the key twice.

For example, if word = 'Trent' it will only type 'Tren', but if the word was 'Burnt' the whole word would get sent.

This is my current code;

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("https://www.wordleunlimited.com/")

word = "Trent"
letters = []
for letter in word:
    button = "//div[text()='%s']" % letter.lower()
    elem = driver.find_element(By.XPATH, button)
    elem.click()
</code>```

The only workaround I have found for this is to avoid HTML elements altogether and just use the keyboard library. As shown below. Is there anyway to overcome this issue using elements?

```<code>from selenium import webdriver
from keyboard import press
from keyboard import write

driver = webdriver.Chrome()
driver.get("https://www.wordleunlimited.com/")
write(word.lower(), delay = 0.05)
press('enter')
</code>```

答:
You should look at what div[text()=''] does after you select 1 t it makes another div tag with that value.

```<code>"//div[contains(@class,'Game-keyboard-button') and text()='%s']" % letter.lower()
</code>```

you should be targetting the div with a certain class and text.

Body:
I'm trying to send keys to Wordle based on the elements in the HTML, and have found that whenever there is a duplicate of a letter it won't press the key twice.

For example, if word = 'Trent' it will only type 'Tren', but if the word was 'Burnt' the whole word would get sent.

This is my current code;

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("https://www.wordleunlimited.com/")

word = "Trent"
letters = []
for letter in word:
    button = "//div[text()='%s']" % letter.lower()
    elem = driver.find_element(By.XPATH, button)
    elem.click()

The only workaround I have found for this is to avoid HTML elements altogether and just use the keyboard library. As shown below. Is there anyway to overcome this issue using elements?

from selenium import webdriver
from keyboard import press
from keyboard import write

driver = webdriver.Chrome()
driver.get("https://www.wordleunlimited.com/")
write(word.lower(), delay = 0.05)
press('enter')

Body:
You should look at what div[text()=''] does after you select 1 t it makes another div tag with that value.

"//div[contains(@class,'Game-keyboard-button') and text()='%s']" % letter.lower()

you should be targetting the div with a certain class and text.


问:
undefined is not an object (evaluating '_expo.Permission.askAsync')
i don't know what's the problem exactly but when i click on the button to choose image that erreur fire in the console
here's my code </p>

```<code>_checkPermissions = async () => {
    try {
      const { status } = await Permission.askAsync(Permission.CAMERA);
      this.setState({ camera: status });
      const { statusRoll } = await Permission.askAsync(Permission.CAMERA_ROLL);
      this.setState({ cameraRoll: statusRoll });
    } catch (err) {
      console.log(err);
    }
  };
  findNewImage = async () => {
    try {
      this._checkPermissions();
      let result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: "Images",
        allowsEditing: true,
        quality: 1
      });

      if (!result.cancelled) {
        this.setState({
          image: result.uri
        });
      } else {
        console.log("cancel");
      }
    } catch (err) {
     // console.log(err);
    }
  };
</code>```

答:
I know I'm a little late to the party, but I feel it's important to show a way that is currently working (as of 2022) and also askAsync is deprecated ...

Getting image from (native) CAMERA

TL;DR: Even though we want "camera", we will actually use expo-image-picker FOR THE CAMERA (yes, you read right!)

I REPEAT: DO NOT USE expo-camera FOR CAMERA!

REMEMBER: USE ImagePickerExpo.requestCameraPermissionsAsync()
AND ImagePickerExpo.launchCameraAsync()
NOT Camera....!

So install it first: expo install expo-image-picker

Then import everything, from it under 1 alias, I like to use ImagePickerExpo because ImagePicker itself is confusing since it can mean more libraries, + import all needed for this code - you can replace Button with any other button/pressable that supports onPress (to use react-native-elements, you need to install it with yarn add react-native-elements)

Create displaying component

Create a state & setter to save current image source

Create a function that requests the permissions and opens the camera

Return the coponent with button binding onPress on function from 5. and Image that is displayed from the state from 4. but only  when available.

working & tested(so far on android in expo go) code:

```<code>import React, { useState } from 'react';
import { View, Image, Alert, StyleSheet } from 'react-native';
import { Button } from 'react-native-elements';

import * as ImagePickerExpo from 'expo-image-picker';

const MyCameraComponent = () => {
    const [selectedImage, setSelectedImage] = useState(null);

    const openCameraWithPermission = async () => {
        let permissionResult = await ImagePickerExpo.requestCameraPermissionsAsync();

        if (permissionResult.granted === false) {
            Alert.alert("For this to work app needs camera roll permissions...");
            return;
        }

        let cameraResult = await ImagePickerExpo.launchCameraAsync({
            // ...
        });
        console.log(cameraResult);

        if (cameraResult.cancelled === true) {
            return;
        }

        setSelectedImage({ localUri: cameraResult.uri });
    };

    return (
        <View>

            <Button title='Take a photo' onPress={openCameraWithPermission}></Button>

            {(selectedImage !== null) && <Image
                source={{ uri: selectedImage.localUri }}
                style={styles.thumbnail}
            />}

        </View>
    );
}

const styles = StyleSheet.create({
    thumbnail: {
        width: 300,
        height: 300,
        resizeMode: "contain"
    }
});

export default MyCameraComponent;
</code>```

Note that I had to style the Image for it to display, it didn't display to me without proper styling which I find misleading, but I guess that's the react native way...

BTW: This also works in Android emulator (besides expo go in real Android device)

It also works on snack on desktop but only when you choose android (or Web) - https://snack.expo.dev/@jave.web/expo-camera-from-expo-image-picker

Getting image from (native) gallery (not camera)

In case you're wondering how to do the same for gallery, the code is basically the same, you just need a different callback function for the button that uses requestMediaLibraryPermissionsAsync / launchImageLibraryAsync instead of the camera ones.

```<code>let openImagePickerAsync = async () => {
    let permissionResult = await ImagePickerExpo.requestMediaLibraryPermissionsAsync();

    if (permissionResult.granted === false) {
        Alert.alert("For this to work app needs media library/gallery permissions...");
        return;
    }

    let pickerResult = await ImagePickerExpo.launchImageLibraryAsync({
        presentationStyle: 0, // without this iOS was crashing
    });
    console.log(pickerResult);

    if (pickerResult.cancelled === true) {
        return;
    }

    setSelectedImage({ localUri: pickerResult.uri });
}
</code>```

Body:
i don't know what's the problem exactly but when i click on the button to choose image that erreur fire in the console
here's my code

_checkPermissions = async () => {
    try {
      const { status } = await Permission.askAsync(Permission.CAMERA);
      this.setState({ camera: status });
      const { statusRoll } = await Permission.askAsync(Permission.CAMERA_ROLL);
      this.setState({ cameraRoll: statusRoll });
    } catch (err) {
      console.log(err);
    }
  };
  findNewImage = async () => {
    try {
      this._checkPermissions();
      let result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: "Images",
        allowsEditing: true,
        quality: 1
      });

      if (!result.cancelled) {
        this.setState({
          image: result.uri
        });
      } else {
        console.log("cancel");
      }
    } catch (err) {
     // console.log(err);
    }
  };

Body:
I know I'm a little late to the party, but I feel it's important to show a way that is currently working (as of 2022) and also askAsync is deprecated ...

Getting image from (native) CAMERA

TL;DR: Even though we want "camera", we will actually use expo-image-picker FOR THE CAMERA (yes, you read right!)

I REPEAT: DO NOT USE expo-camera FOR CAMERA!

REMEMBER: USE ImagePickerExpo.requestCameraPermissionsAsync()
AND ImagePickerExpo.launchCameraAsync()
NOT Camera....!

So install it first: expo install expo-image-picker

Then import everything, from it under 1 alias, I like to use ImagePickerExpo because ImagePicker itself is confusing since it can mean more libraries, + import all needed for this code - you can replace Button with any other button/pressable that supports onPress (to use react-native-elements, you need to install it with yarn add react-native-elements)

Create displaying component

Create a state & setter to save current image source

Create a function that requests the permissions and opens the camera

Return the coponent with button binding onPress on function from 5. and Image that is displayed from the state from 4. but only  when available.

working & tested(so far on android in expo go) code:

import React, { useState } from 'react';
import { View, Image, Alert, StyleSheet } from 'react-native';
import { Button } from 'react-native-elements';

import * as ImagePickerExpo from 'expo-image-picker';

const MyCameraComponent = () => {
    const [selectedImage, setSelectedImage] = useState(null);

    const openCameraWithPermission = async () => {
        let permissionResult = await ImagePickerExpo.requestCameraPermissionsAsync();

        if (permissionResult.granted === false) {
            Alert.alert("For this to work app needs camera roll permissions...");
            return;
        }

        let cameraResult = await ImagePickerExpo.launchCameraAsync({
            // ...
        });
        console.log(cameraResult);

        if (cameraResult.cancelled === true) {
            return;
        }

        setSelectedImage({ localUri: cameraResult.uri });
    };

    return (
        <View>

            <Button title='Take a photo' onPress={openCameraWithPermission}></Button>

            {(selectedImage !== null) && <Image
                source={{ uri: selectedImage.localUri }}
                style={styles.thumbnail}
            />}

        </View>
    );
}

const styles = StyleSheet.create({
    thumbnail: {
        width: 300,
        height: 300,
        resizeMode: "contain"
    }
});

export default MyCameraComponent;

Note that I had to style the Image for it to display, it didn't display to me without proper styling which I find misleading, but I guess that's the react native way...

BTW: This also works in Android emulator (besides expo go in real Android device)

It also works on snack on desktop but only when you choose android (or Web) - https://snack.expo.dev/@jave.web/expo-camera-from-expo-image-picker

Getting image from (native) gallery (not camera)

In case you're wondering how to do the same for gallery, the code is basically the same, you just need a different callback function for the button that uses requestMediaLibraryPermissionsAsync / launchImageLibraryAsync instead of the camera ones.

let openImagePickerAsync = async () => {
    let permissionResult = await ImagePickerExpo.requestMediaLibraryPermissionsAsync();

    if (permissionResult.granted === false) {
        Alert.alert("For this to work app needs media library/gallery permissions...");
        return;
    }

    let pickerResult = await ImagePickerExpo.launchImageLibraryAsync({
        presentationStyle: 0, // without this iOS was crashing
    });
    console.log(pickerResult);

    if (pickerResult.cancelled === true) {
        return;
    }

    setSelectedImage({ localUri: pickerResult.uri });
}


问:
How do I solve this index out of range issue in python?
I am trying to understand why I get an error that my code is out of range when running it and how to fix this. The tester code to run along side my code can be found here: https://github.com/ikokkari/PythonProblems/blob/main/tester109.py

Here is my code.

```<code>def domino_cycle(tiles):
    indexA = 0
    indexB = 1
    if tiles == []:
        return True
    if tiles[0][0] != tiles[-1][1]:
        return False
    for i in range(len(tiles)-1):
        if i % 2 == 0:
            indexB -= 1
        indexB
        if tiles[indexA][indexB + 1] == tiles[indexA + 1][indexB]:
            indexA += 1
        else:
            return False
    return True
</code>```

答:
Your code produces the expected results for the provided test cases. However, the code you linked generates far more test cases, so it's likely the problem only occurs when a test case is presented that's not covered by those.

Your algorithm seems very convoluted for what is asked. You loop i over the length of tiles - 1, and compute indices to compare in a way that's hard to track.

For any series of tiles, indexA and indexB will have these values in order:

```<code>i = 0: 0, 1 -> 0, 0 -> 1, 0 if tiles [0][1] == tiles [1][0], 0, 0 otherwise
i = 1: 1, 0 -> 2, 0 if tiles [1][1] == tiles[2][0], 1, 0 otherwise
       0, 0 -> 1, 0 if tiles [0][1] == tiles[1][0], 0, 0 otherwise
i = 2: 2, 0 -> 2, -1 -> 3, -1 if tiles [2][0] == tiles[3][-1], 2, -1 otherwise
       1, 0 -> 1, -1 -> 2, -1 if tiles [1][0] == tiles[2][-1], 1, -1 otherwise
       0, 0 -> 0, -1 -> 1, -1 if tiles [0][0] == tiles[1][-1], 0, -1 otherwise
...
i = 6: here indexB can become -2
</code>```

I could write out the whole sequence, but clearly it's possible for indexB to become negative below -2, which would cause the error. Every iteration where i is odd, depending on the tiles, indexB may get lowered, and it is never raised.

For example:

```<code>domino_cycle([(1, 2), (2, 2), (2, 2), (2, 2), (2, 2), (2, 2), (2, 2), (2, 1)])
</code>```

Should return True but tries to access [-3] of a tile, which it obviously doesn't have.

A simpler implementation like this won't have that problem:

```<code>def domino_cycle(tiles):
    return (
        # you check this as well and it helps to avoid errors with the rest
        tiles == [] or
        # the only check that won't be performed by the logic that follows
        (tiles[-1][1] == tiles[0][0] and
        # every 2nd pip value must match the 1st pip value of every paired tile
         all(a[1] == b[0] for a, b in zip(tiles, tiles[1:])))
    )
</code>```

I'm not sure what you were trying to do exactly, as an algorithm, so I can't really provide guidance on how to fix it. You should provide an explanation of your desired logic if you need help fixing your own solution.

If you're not allowed to use zip(), this is more or less the same:

```<code>def domino_cycle(tiles):
    return (
        tiles == [] or
        (tiles[-1][1] == tiles[0][0] and
         all(tiles[i][1] == tiles[i+1][0] for i in range(len(tiles) - 1)))
    )
</code>```

If you're also not allowed to use all() (at this point, you're apparently not learning Python, but basic algorithms), this is the whole thing without:

```<code>def domino_cycle(tiles):
    if tiles == []:
        return True
    if tiles[-1][1] != tiles[0][0]:
        return False
    for i in range(len(tiles) - 1):
        if tiles[i][1] != tiles[i+1][0]:
            return False
    return True
</code>```

You can keep going, without range():

```<code>def domino_cycle(tiles):
    if tiles == []:
        return True
    if tiles[-1][1] != tiles[0][0]:
        return False
    i = 0
    while i < len(tiles) - 1:
        if tiles[i][1] != tiles[i+1][0]:
            return False
        i += 1
    return True
</code>```

That's just a longer way to write the same thing again. But it doesn't answer what was wrong with your algorithm, other than it simply cannot work. It's unclear what you were trying to achieve with the two indices.

Regarding finding the problem, here's your code with a simple debugging print statement, in case your misguided teacher is thinking learning to code with a plain text editor is the best idea:

```<code>def domino_cycle(tiles):
    indexA = 0
    indexB = 1
    if tiles == []:
        return True
    if tiles[0][0] != tiles[-1][1]:
        return False
    for i in range(len(tiles)-1):
        if i % 2 == 0:
            indexB -= 1
        print(f'iteration i=={i}: tiles[{indexA}][{indexB + 1}] == tiles[{indexA + 1}][{indexB}]')
        if tiles[indexA][indexB + 1] == tiles[indexA + 1][indexB]:
            indexA += 1
        else:
            return False
    return True
</code>```

Output on a that failing test case:

iteration i==0: tiles[0][1] == tiles[1][0]
iteration i==1: tiles[1][1] == tiles[2][0]
iteration i==2: tiles[2][0] == tiles[3][-1]
iteration i==3: tiles[3][0] == tiles[4][-1]
iteration i==4: tiles[4][-1] == tiles[5][-2]
iteration i==5: tiles[5][-1] == tiles[6][-2]
iteration i==6: tiles[6][-2] == tiles[7][-3]
```

That's your problem right there.

Body:
I am trying to understand why I get an error that my code is out of range when running it and how to fix this. The tester code to run along side my code can be found here: https://github.com/ikokkari/PythonProblems/blob/main/tester109.py

Here is my code.

def domino_cycle(tiles):
    indexA = 0
    indexB = 1
    if tiles == []:
        return True
    if tiles[0][0] != tiles[-1][1]:
        return False
    for i in range(len(tiles)-1):
        if i % 2 == 0:
            indexB -= 1
        indexB
        if tiles[indexA][indexB + 1] == tiles[indexA + 1][indexB]:
            indexA += 1
        else:
            return False
    return True

Body:
Your code produces the expected results for the provided test cases. However, the code you linked generates far more test cases, so it's likely the problem only occurs when a test case is presented that's not covered by those.

Your algorithm seems very convoluted for what is asked. You loop i over the length of tiles - 1, and compute indices to compare in a way that's hard to track.

For any series of tiles, indexA and indexB will have these values in order:

i = 0: 0, 1 -> 0, 0 -> 1, 0 if tiles [0][1] == tiles [1][0], 0, 0 otherwise
i = 1: 1, 0 -> 2, 0 if tiles [1][1] == tiles[2][0], 1, 0 otherwise
       0, 0 -> 1, 0 if tiles [0][1] == tiles[1][0], 0, 0 otherwise
i = 2: 2, 0 -> 2, -1 -> 3, -1 if tiles [2][0] == tiles[3][-1], 2, -1 otherwise
       1, 0 -> 1, -1 -> 2, -1 if tiles [1][0] == tiles[2][-1], 1, -1 otherwise
       0, 0 -> 0, -1 -> 1, -1 if tiles [0][0] == tiles[1][-1], 0, -1 otherwise
...
i = 6: here indexB can become -2

I could write out the whole sequence, but clearly it's possible for indexB to become negative below -2, which would cause the error. Every iteration where i is odd, depending on the tiles, indexB may get lowered, and it is never raised.

For example:

domino_cycle([(1, 2), (2, 2), (2, 2), (2, 2), (2, 2), (2, 2), (2, 2), (2, 1)])

Should return True but tries to access [-3] of a tile, which it obviously doesn't have.

A simpler implementation like this won't have that problem:

def domino_cycle(tiles):
    return (
        # you check this as well and it helps to avoid errors with the rest
        tiles == [] or
        # the only check that won't be performed by the logic that follows
        (tiles[-1][1] == tiles[0][0] and
        # every 2nd pip value must match the 1st pip value of every paired tile
         all(a[1] == b[0] for a, b in zip(tiles, tiles[1:])))
    )

I'm not sure what you were trying to do exactly, as an algorithm, so I can't really provide guidance on how to fix it. You should provide an explanation of your desired logic if you need help fixing your own solution.

If you're not allowed to use zip(), this is more or less the same:

def domino_cycle(tiles):
    return (
        tiles == [] or
        (tiles[-1][1] == tiles[0][0] and
         all(tiles[i][1] == tiles[i+1][0] for i in range(len(tiles) - 1)))
    )

If you're also not allowed to use all() (at this point, you're apparently not learning Python, but basic algorithms), this is the whole thing without:

def domino_cycle(tiles):
    if tiles == []:
        return True
    if tiles[-1][1] != tiles[0][0]:
        return False
    for i in range(len(tiles) - 1):
        if tiles[i][1] != tiles[i+1][0]:
            return False
    return True

You can keep going, without range():

def domino_cycle(tiles):
    if tiles == []:
        return True
    if tiles[-1][1] != tiles[0][0]:
        return False
    i = 0
    while i < len(tiles) - 1:
        if tiles[i][1] != tiles[i+1][0]:
            return False
        i += 1
    return True

That's just a longer way to write the same thing again. But it doesn't answer what was wrong with your algorithm, other than it simply cannot work. It's unclear what you were trying to achieve with the two indices.

Regarding finding the problem, here's your code with a simple debugging print statement, in case your misguided teacher is thinking learning to code with a plain text editor is the best idea:

def domino_cycle(tiles):
    indexA = 0
    indexB = 1
    if tiles == []:
        return True
    if tiles[0][0] != tiles[-1][1]:
        return False
    for i in range(len(tiles)-1):
        if i % 2 == 0:
            indexB -= 1
        print(f'iteration i=={i}: tiles[{indexA}][{indexB + 1}] == tiles[{indexA + 1}][{indexB}]')
        if tiles[indexA][indexB + 1] == tiles[indexA + 1][indexB]:
            indexA += 1
        else:
            return False
    return True

Output on a that failing test case:

iteration i==0: tiles[0][1] == tiles[1][0]
iteration i==1: tiles[1][1] == tiles[2][0]
iteration i==2: tiles[2][0] == tiles[3][-1]
iteration i==3: tiles[3][0] == tiles[4][-1]
iteration i==4: tiles[4][-1] == tiles[5][-2]
iteration i==5: tiles[5][-1] == tiles[6][-2]
iteration i==6: tiles[6][-2] == tiles[7][-3]

That's your problem right there.


问:
Extract OLE object data in Microsoft Office without OLE application
Is it possible to extract the content of an embedded OLE object in Microsoft Office using VBA/VSTO? I am talking about a situation where the application with which the OLE object was created is not available. In this case some sort of converter application could make use of the raw data.

For instance, in Excel the object is accessible via ActiveSheet.Shapes(x).OLEFormat but I have not found a way to retrieve the raw data of the object.

One way would be to open the native file (Office Open XML/Compound File) and extract the data from there. But maybe there is a simpler approach?

答:
I approached this another way (non-VBA).

Rename the document/spreadsheet to .zip (eg instead of .docx)

Open the .zip and browse the structure to the embedded objects eg \word\embeddings

Edit the .bin file(s) (eg in Notepad++) - you should be able to identify the file extension in the first 10 lines

Now strip all the header/junk from the start of the file - search for ÐÏà¡± and remove everything before/above it

The beginning of the file will now look like this:

Save the file with the extension that you identified above

The file should open and function correctly


答:
Here are a few ways you can print the loop:</p>
```<code># Option 1
the_count = [1, 2, 3, 4, 5]
for x in the_count:
    print('This is count:' + str(x))

# Option 2
the_count = [1, 2, 3, 4, 5]
for x in the_count:
    print(f"This is count {x}")
</code>```

Title: How do I get this for loop to print

Body:
Here are a few ways you can print the loop:

# Option 1
the_count = [1, 2, 3, 4, 5]
for x in the_count:
    print('This is count:' + str(x))

# Option 2
the_count = [1, 2, 3, 4, 5]
for x in the_count:
    print(f"This is count {x}")


问:
Modern apis with FastAPI - Redis Caching
I'm trying to implement the redis caching in my API for the first time it is a simple fastapi application which is using openweather api to query some weather information and my intention is to cache each json response in the redis server. I'hve  made it to work with single key city but with this approach validating query parameters not working with the error handling I put in the place.

caching.py

```<code>import sys
from datetime import timedelta
import json

import redis

from services.openweather_service import get_report

def redis_connect() -> redis.client.Redis:
    try:
        client = redis.Redis(
            host="localhost",
            port=6379,
            db=0,
        )
        ping = client.ping()
        if ping is True:
            return client
    except redis.ConnectionError:
        print("Connection Error!")
        sys.exit(1)

client = redis_connect()

def get_routes_from_cache(key: str) -> str:
    """Data from redis."""

    val = client.get(key)
    return val

def set_routes_to_cache(key: str, value: str) -> bool:
    """Data to redis."""

    state = client.setex(
        key,
        timedelta(hours=24),
        value=value,
    )
    return state

async def route_optima(city: str, state: str, country: str, units=None) -> dict:

    location = {"city": city, "state": state, "country": country, "units": units}

    # First it looks for the data in redis cache
    data = get_routes_from_cache(key=json.dumps(location))
    # print(data)
    # print(type(data))

    # If cache is found then serves the data from cache
    if data is not None:
        data = data.decode("UTF-8")
        data_dict = json.loads(data)
        print(data_dict)
        print(type(data_dict))
        data["cache"] = True
        return data

    else:
        # If cache is not found then sends request to the OpenWeather API
        data = await get_report(city, state, country, units)

        # This block sets saves the respose to redis and serves it directly
        data["cache"] = False
        data = json.dumps(data)
        state = set_routes_to_cache(key=json.dumps(location), value=json.dumps(data))

        if state is True:
            return json.dumps(data)
        return data
</code>```

Then I took a different approach by making the query params location = {"city": city, "state": state, "country": country, "units": units} as a key and the json response as a value but when app try to get the response from the cache here it got weird like right after passing the query params dict into the json.dumps it gives me the bytes object and so I decode it with decode("utf-8") but instead of coming back as a dict it gives me <class 'str'> type object. There I am lost... can anyone help me out here?

weather_api.py

```<code>from typing import Optional
import fastapi
from fastapi import Depends

from models.location import Location
from infrastructure.caching import route_optima
from models.validation_error import ValidationError

router = fastapi.APIRouter()

@router.get("/api/weather/{city}")
async def weather(loc: Location = Depends(), units: Optional[str] = "metric"):
    return await route_optima(loc.city, loc.state, loc.country, units)
</code>```

And if I am using the wrong approach here then please point to the best approach to take here.

答: As you are using Fastapi, it is better to use aioredis to leverage the async functionality.</p>

Body:
I'm trying to implement the redis caching in my API for the first time it is a simple fastapi application which is using openweather api to query some weather information and my intention is to cache each json response in the redis server. I'hve  made it to work with single key city but with this approach validating query parameters not working with the error handling I put in the place.

caching.py

import sys
from datetime import timedelta
import json

import redis

from services.openweather_service import get_report

def redis_connect() -> redis.client.Redis:
    try:
        client = redis.Redis(
            host="localhost",
            port=6379,
            db=0,
        )
        ping = client.ping()
        if ping is True:
            return client
    except redis.ConnectionError:
        print("Connection Error!")
        sys.exit(1)

client = redis_connect()

def get_routes_from_cache(key: str) -> str:
    """Data from redis."""

    val = client.get(key)
    return val

def set_routes_to_cache(key: str, value: str) -> bool:
    """Data to redis."""

    state = client.setex(
        key,
        timedelta(hours=24),
        value=value,
    )
    return state

async def route_optima(city: str, state: str, country: str, units=None) -> dict:

    location = {"city": city, "state": state, "country": country, "units": units}

    # First it looks for the data in redis cache
    data = get_routes_from_cache(key=json.dumps(location))
    # print(data)
    # print(type(data))

    # If cache is found then serves the data from cache
    if data is not None:
        data = data.decode("UTF-8")
        data_dict = json.loads(data)
        print(data_dict)
        print(type(data_dict))
        data["cache"] = True
        return data

    else:
        # If cache is not found then sends request to the OpenWeather API
        data = await get_report(city, state, country, units)

        # This block sets saves the respose to redis and serves it directly
        data["cache"] = False
        data = json.dumps(data)
        state = set_routes_to_cache(key=json.dumps(location), value=json.dumps(data))

        if state is True:
            return json.dumps(data)
        return data

Then I took a different approach by making the query params location = {"city": city, "state": state, "country": country, "units": units} as a key and the json response as a value but when app try to get the response from the cache here it got weird like right after passing the query params dict into the json.dumps it gives me the bytes object and so I decode it with decode("utf-8") but instead of coming back as a dict it gives me <class 'str'> type object. There I am lost... can anyone help me out here?

weather_api.py

from typing import Optional
import fastapi
from fastapi import Depends

from models.location import Location
from infrastructure.caching import route_optima
from models.validation_error import ValidationError

router = fastapi.APIRouter()

@router.get("/api/weather/{city}")
async def weather(loc: Location = Depends(), units: Optional[str] = "metric"):
    return await route_optima(loc.city, loc.state, loc.country, units)

And if I am using the wrong approach here then please point to the best approach to take here.


问:
Is there any disadvantage of marking a variable or constant as private in terms of performance or something?
Is there any disadvantage in terms if performance or something by marking a variable as a private on a class or struct on Swift or view on SwiftUI?

I know about the encapsulation advantage you get when the variable is private, preventing access from other code outside the scope. My concern is about performance.

答: Swift is usually a compiled language (interpreters may exist but they are definitely not common) and once the source code is compiled (which is not something the end user will have to sit through, anyway), there is no performance increase or decrease caused by access control. In fact, after the code has been compiled, there is no such thing as access control--the process is now represented as machine code and it will simply run the way it was written to run. Access control is there for the programmer, not the machine. And in terms of compilation performance, I've yet to come across any literature to suggest a compiler will perform better or worse because of access control.</p>


问:
Stripping the leading zeros but leave a single 0
So let me start of by saying that I'm new to bash so I would appreciate a simple explanation on the answers you give.

I've got the following block of code:

name="Chapter 0000 (sub s2).cbz "

s=$(echo $name | grep -Eo '[0-9]+([.][0-9]+)?' | tr '\n' ' ' | sed 's/^0*//')

echo $s

readarray -d " " -t myarr <<< "$s"

if [[ $(echo "${myarr[0]} < 100 && ${myarr[0]} >= 10" | bc) -ne 0 ]]; then
    myarr[0]="0${myarr[0]}"
elif [[ $(echo "${myarr[0]} < 10" | bc) -ne 0 ]]; then
    myarr[0]="00${myarr[0]}"
fi

newName="Chapter ${myarr[0]}.cbz"

echo $newName
```
<p>which (in this case) would end up spitting out:</p>
``` 2
(standard_in) 1: syntax error
(standard_in) 1: syntax error
Chapter .cbz
```
<p>(I'm fairly certain that the syntax errors are because <code>${myarr[0]}</code> is null when doing the comparisons)</p>
<p>This is not the output I want. I want the code to strip leading 0's but leave a single 0 if its all 0.</p>
<p>So the code to really change would be <code>sed 's/^0*//')</code> but I'm not sure how to change it.</p>
<p>(expected outputs:</p>
```              in   --->   out
1) chapter 8.cbz   ---> Chapter 008.cbz
2) chapter 1.3.cbz   ---> Chapter 001.3.cbz
3) _23 (sec 2).cbz   ---> Chapter 023.cbz
4) chapter 00009.cbz   ---> Chapter 009.cbz
5) chap 0000112.5.cbz   ---> Chapter 112.5.cbz
6) Chapter 0000 (sub s2).cbz   ---> Chapter 000.cbz
```

so far the code I got works for 1- 3 but not the leading 0 cases (4-6))

答:
Here is an awk script that does the trick:

script.awk

```<code>{
  str = "000" gensub("(^[[:digit:]]+\\.?[[:digit:]]*)( \\([^)]+\\))?(\\.cbz)", "\\1", "g", RT);
  str = gensub("(^[[:digit:]]+)([[:digit:]]{3})(.*$)", "\\2\\3", "g", str);
  printf("Chapter %s.cbz\n", str);
}
</code>```

Test input.1.txt

```<code>1) chapter 8.cbz
2) chapter 1.3.cbz
3) _23 (sec 2).cbz
4) chapter 00009.cbz
5) chap 0000112.5.cbz
</code>```

Output:

```<code>awk -f script.awk RS='[[:digit:]]+[\\.]?[[:digit:]]*( \\([^)]+\\))?\\.cbz' input.1.txt
Chapter 008.cbz
Chapter 001.3.cbz
Chapter 023.cbz
Chapter 009.cbz
Chapter 112.5.cbz
</code>```

Body:
So let me start of by saying that I'm new to bash so I would appreciate a simple explanation on the answers you give.

I've got the following block of code:

name="Chapter 0000 (sub s2).cbz "

s=$(echo $name | grep -Eo '[0-9]+([.][0-9]+)?' | tr '\n' ' ' | sed 's/^0*//')

echo $s

readarray -d " " -t myarr <<< "$s"

if [[ $(echo "${myarr[0]} < 100 && ${myarr[0]} >= 10" | bc) -ne 0 ]]; then
    myarr[0]="0${myarr[0]}"
elif [[ $(echo "${myarr[0]} < 10" | bc) -ne 0 ]]; then
    myarr[0]="00${myarr[0]}"
fi

newName="Chapter ${myarr[0]}.cbz"

echo $newName

which (in this case) would end up spitting out:

 2
(standard_in) 1: syntax error
(standard_in) 1: syntax error
Chapter .cbz

(I'm fairly certain that the syntax errors are because ${myarr[0]} is null when doing the comparisons)

This is not the output I want. I want the code to strip leading 0's but leave a single 0 if its all 0.

So the code to really change would be sed 's/^0*//') but I'm not sure how to change it.

(expected outputs:

              in   --->   out
1) chapter 8.cbz   ---> Chapter 008.cbz
2) chapter 1.3.cbz   ---> Chapter 001.3.cbz
3) _23 (sec 2).cbz   ---> Chapter 023.cbz
4) chapter 00009.cbz   ---> Chapter 009.cbz
5) chap 0000112.5.cbz   ---> Chapter 112.5.cbz
6) Chapter 0000 (sub s2).cbz   ---> Chapter 000.cbz

so far the code I got works for 1- 3 but not the leading 0 cases (4-6))

Body:
Here is an awk script that does the trick:

script.awk

{
  str = "000" gensub("(^[[:digit:]]+\\.?[[:digit:]]*)( \\([^)]+\\))?(\\.cbz)", "\\1", "g", RT);
  str = gensub("(^[[:digit:]]+)([[:digit:]]{3})(.*$)", "\\2\\3", "g", str);
  printf("Chapter %s.cbz\n", str);
}

Test input.1.txt

1) chapter 8.cbz
2) chapter 1.3.cbz
3) _23 (sec 2).cbz
4) chapter 00009.cbz
5) chap 0000112.5.cbz

Output:

awk -f script.awk RS='[[:digit:]]+[\\.]?[[:digit:]]*( \\([^)]+\\))?\\.cbz' input.1.txt
Chapter 008.cbz
Chapter 001.3.cbz
Chapter 023.cbz
Chapter 009.cbz
Chapter 112.5.cbz


问:
Is there a function that removes all nonalphanumeric numbers in Fortran?
New to Fortran,been trying to think of a function that replaces all non alphanumeric characters and spaces on a string so that it turns something like [AS:1] to AS1.

Anyone here got a clue how to?

Like I got a trimmer for open spaces to work but I don't know how to make it work for anything that's a non-alphanumeric character.

答:
You would have to write a function to do it. As inspiration, here's a subroutine I recently wrote to do SQL "escaping" of quotes in a string. The key here is having separate indexes for input and output position. Your requirement is even easier - if the character is not alphanumeric or space, don't advance the output length. There are several ways of doing the comparison, an exercise left for the reader.</p>
```<code>subroutine escape (text)
character(*), intent(inout) :: text
character(100) :: newtext
integer i,j
newtext = ' '
j = 1
do i=1,len_trim(text)
    if (text(i:i) == '"') then
        newtext(j:j) = "\"
        j = j + 1
    end if
    newtext(j:j) = text(i:i)
    j = j + 1
end do
text = newtext
end subroutine escape
</code>```

Body:
You would have to write a function to do it. As inspiration, here's a subroutine I recently wrote to do SQL "escaping" of quotes in a string. The key here is having separate indexes for input and output position. Your requirement is even easier - if the character is not alphanumeric or space, don't advance the output length. There are several ways of doing the comparison, an exercise left for the reader.

subroutine escape (text)
character(*), intent(inout) :: text
character(100) :: newtext
integer i,j
newtext = ' '
j = 1
do i=1,len_trim(text)
    if (text(i:i) == '"') then
        newtext(j:j) = "\"
        j = j + 1
    end if
    newtext(j:j) = text(i:i)
    j = j + 1
end do
text = newtext
end subroutine escape


答:
The intrinsic function SCANcan be used for membership searches.

If we have a character char of length-1 and a set set of non-zero size, then we have that SCAN(char, set) returns 1 (0) if char is in (not in) the set. (SCAN will return 0 if the set is of size zero.)

This functions is elemental so, for example, SCAN(char_array, set) returns an indicator for which elements of char_array are in the set.

We also have PACK which returns another array corresponding to a selection mask:

```<code>print*, PACK(char_array, SCAN(char_array,set).eq.1)
</code>```

Which means we can write a subroutine like

```<code>subroutine s(in, out, keep, len)
  integer, intent(in) :: len
  character, intent(in) :: in(len), keep*(*)
  character, intent(out) :: out(len)
  integer :: i

  out = PACK(in, SCAN(in,keep).eq.1, [(' ',i=1,len)])
end subroutine s
</code>```

taking an input character array of size len and returning an output character array of the same size with the elements which are in keep (and trailing elements being blanks).

Naturally, we don't like working with character arrays instead of scalars, so let's provide a nice subroutine using sequence association:

```<code>subroutine strip(in, out, keep)
  character(*), intent(in) :: in, keep
  character(*), intent(out) :: out

  call s(in, out, keep, LEN(in))
end subroutine
</code>```

Complete example:

```<code>module stripping
  implicit none
  private s
contains
  subroutine strip(in, out, keep)
    character(*), intent(in) :: in, keep
    character(*), intent(out) :: out

    call s(in, out, keep, len(in))
  end subroutine strip

  subroutine s(in, out, keep, len)
    integer, intent(in) :: len
    character, intent(in) :: in(len), keep*(*)
    character, intent(out) :: out(len)
    integer :: i

    out = PACK(in, SCAN(in,keep).eq.1, [(' ',i=1,len)])
  end subroutine s

end module stripping

program test
  use stripping, only : strip
  implicit none

  character(10) in, out
  character(*), parameter :: keep="abcd"

  in = "a1b*2sdc]a"
  call strip(in, out, keep)
  print*, TRIM(out)

end program
</code>```

There are doubtless better and clearer ways to do this: this answer mostly serves to have you think about what intrinsic functions there are and how they can be applied. There isn't an intrinsic function to do what you want in one step.

Title: Is there a function that removes all nonalphanumeric numbers in Fortran?

Body:
New to Fortran,been trying to think of a function that replaces all non alphanumeric characters and spaces on a string so that it turns something like [AS:1] to AS1.

Anyone here got a clue how to?

Like I got a trimmer for open spaces to work but I don't know how to make it work for anything that's a non-alphanumeric character.

Body:
The intrinsic function SCANcan be used for membership searches.

If we have a character char of length-1 and a set set of non-zero size, then we have that SCAN(char, set) returns 1 (0) if char is in (not in) the set. (SCAN will return 0 if the set is of size zero.)

This functions is elemental so, for example, SCAN(char_array, set) returns an indicator for which elements of char_array are in the set.

We also have PACK which returns another array corresponding to a selection mask:

print*, PACK(char_array, SCAN(char_array,set).eq.1)

Which means we can write a subroutine like

subroutine s(in, out, keep, len)
  integer, intent(in) :: len
  character, intent(in) :: in(len), keep*(*)
  character, intent(out) :: out(len)
  integer :: i

  out = PACK(in, SCAN(in,keep).eq.1, [(' ',i=1,len)])
end subroutine s

taking an input character array of size len and returning an output character array of the same size with the elements which are in keep (and trailing elements being blanks).

Naturally, we don't like working with character arrays instead of scalars, so let's provide a nice subroutine using sequence association:

subroutine strip(in, out, keep)
  character(*), intent(in) :: in, keep
  character(*), intent(out) :: out

  call s(in, out, keep, LEN(in))
end subroutine

Complete example:

module stripping
  implicit none
  private s
contains
  subroutine strip(in, out, keep)
    character(*), intent(in) :: in, keep
    character(*), intent(out) :: out

    call s(in, out, keep, len(in))
  end subroutine strip

  subroutine s(in, out, keep, len)
    integer, intent(in) :: len
    character, intent(in) :: in(len), keep*(*)
    character, intent(out) :: out(len)
    integer :: i

    out = PACK(in, SCAN(in,keep).eq.1, [(' ',i=1,len)])
  end subroutine s

end module stripping

program test
  use stripping, only : strip
  implicit none

  character(10) in, out
  character(*), parameter :: keep="abcd"

  in = "a1b*2sdc]a"
  call strip(in, out, keep)
  print*, TRIM(out)

end program

There are doubtless better and clearer ways to do this: this answer mostly serves to have you think about what intrinsic functions there are and how they can be applied. There isn't an intrinsic function to do what you want in one step.


问:
How do I account for daylight savings time when retrieving current time in PHP?
When getting the time via PHP script (time()), during Daylight Savings Time it seems to return a time value that is one hour off. Is there any way to get the correct time, accounting for Daylight Savings Time?

答:
time() returns a Unix timestamp and a Unix timestamp is a fixed period of time: number of seconds since the Unix Epoch. It isn't affected by time zones.

Once you have the precise moment, you may want to calculate the local time in a given place:

```<code><?php

$now = time();
echo $now . PHP_EOL;

date_default_timezone_set('Europe/Madrid');
echo date('r', $now) . PHP_EOL;

date_default_timezone_set('Asia/Tokyo');
echo date('r', $now) . PHP_EOL;
</code>```

... will print different local dates for the same timestamp:

```<code>1313683738
Thu, 18 Aug 2011 18:08:58 +0200
Fri, 19 Aug 2011 01:08:58 +0900
</code>```

The same reasoning applies for the opposite operation:

```<code><?php

date_default_timezone_set('Europe/Madrid');
$then = mktime(23, 55, 30, 12, 31, 2000);
echo $then . PHP_EOL;

date_default_timezone_set('Asia/Tokyo');
$then = mktime(23, 55, 30, 12, 31, 2000);
echo $then . PHP_EOL;
</code>```

... will print different timestamps:

```<code>978303330
978274530
</code>```

Body:
time() returns a Unix timestamp and a Unix timestamp is a fixed period of time: number of seconds since the Unix Epoch. It isn't affected by time zones.

Once you have the precise moment, you may want to calculate the local time in a given place:

<?php

$now = time();
echo $now . PHP_EOL;

date_default_timezone_set('Europe/Madrid');
echo date('r', $now) . PHP_EOL;

date_default_timezone_set('Asia/Tokyo');
echo date('r', $now) . PHP_EOL;

... will print different local dates for the same timestamp:

1313683738
Thu, 18 Aug 2011 18:08:58 +0200
Fri, 19 Aug 2011 01:08:58 +0900

The same reasoning applies for the opposite operation:

<?php

date_default_timezone_set('Europe/Madrid');
$then = mktime(23, 55, 30, 12, 31, 2000);
echo $then . PHP_EOL;

date_default_timezone_set('Asia/Tokyo');
$then = mktime(23, 55, 30, 12, 31, 2000);
echo $then . PHP_EOL;

... will print different timestamps:

978303330
978274530


问:
How can I run a node app from the command line?
On RHEL I have put various executable files in ~/.local/bin eg. nvim.appimage. As ~/.local/bin is in my $PATH variable I can call nvim.appimage from any directory which is great.

I want some node apps to be able to be called from any directory, for example ESLint. These are not binaries but are directories with a lot of files and directories inside. Which directory (presumably in $PATH) should they be in so that I as a user but not other users can call them from any of my directories? Also how should they be invoked.

As an example, I have put the cowsay node app into ~/.local/bin I can invoke it like this from any of my directories:

$ node ~/.local/bin/cowsay/node_modules/cowsay/cli.js moo

(I can actually omit node from that command as cli.js has #!bin/bash/env node at the top.)

I would like to be able to invoke cowsay from any of my directories with a simple command eg cowsay

I know that a lot of node apps are not intended to be run from the command line but some are. In particular I am having great difficulty to get neovim with Ale to recognize some node linters like ESLint. Perhaps if I can sort the cowsay issue out I may be able to move on to ESLint with neovim. I am hoping that if I can get ESLint invokable from a location in $PATH it might be usable by neovim / Ale.

答:
Can this achieve what you expected ?

```<code>mkdir ~/.local/nodexe
cd ~/.local/nodexe
ln -fs ../bin/cowsay/node_modules/cowsay/cli.js cowsay
PATH=$PATH:~/.local/nodexe
</code>```

Assuming you have #!bin/bash/env node in cli.js, then you can run by typing cowsay moo

Body:
Can this achieve what you expected ?

mkdir ~/.local/nodexe
cd ~/.local/nodexe
ln -fs ../bin/cowsay/node_modules/cowsay/cli.js cowsay
PATH=$PATH:~/.local/nodexe

Assuming you have #!bin/bash/env node in cli.js, then you can run by typing cowsay moo


问:
Javascript: Copy specified Col through last col and paste down to last row
I'm extremely green to javascript and have pieced together what I need through searching online and watching videos.  I need to set multiple columns in row4, starting from col 18 through to lastcolumn, as the active cells to copy and then pasteformulas down to the last row (if necessary, based on col 4's data).  Code I have below activates (selects) all data from col 18 through last column (as intended) but also through last row (unintended).  Anyone know how to correct this?</p>
```<code>    function CopyFormulasDown() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var sRA4 = ss.getRange(4,1); //First copy is A4 ..this one works as intended
  var lr = ss.getLastRow();
  var lc = ss.getLastColumn();
  var sRR4lc = ss.getRange('R4:'+ lc +'4'); //Trying to select R4 through last col within row4; also tried (4,18+':'+lc), but throws an error: Exception: Cannot convert '18:37' to int.
  var fillDownRangeA4 = ss.getRange(4,1,lr);
  var fillDownRangeR4lc = ss.getRange(4,18,lr,lc);

   // sRA4.activate(); //range cell A4 is copied
    //sRA4.copyTo(fillDownRangeA4);  //copied cell pastes formula down to last row ..WORKS!
    sRR4lc.activate(); //ROW4 COL18 is selected through to last col as intended, but also selects down to last row.... problem is I didn't tell it to select past row 4... not sure how to correct this
   // sRR4lc.copyTo(fillDownRangeR4lc); //commented out for now until I can get just row 4 from col 18 through last col copy to work
};
</code>```

答:
Omgoodness. After typing out the question and posting, I thought of adding the lc to the numofcolumns place instead.  Below is the working code for anyone who's interested:</p>
```<code>  function CopyFormulasDown() {
    var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
    var sRA4 = ss.getRange(4,1); //copy A4
    var lr = ss.getLastRow();
    var lc = ss.getLastColumn();
    var sRR4lc = ss.getRange(4,18,1,lc); //select R4 through last col within row4
    var fillDownRangeA4 = ss.getRange(4,1,lr);
    var fillDownRangeR4lc = ss.getRange(4,18,lr,lc);

      sRA4.activate(); //range cell A4 is copied
      sRA4.copyTo(fillDownRangeA4);  //copied cell pastes formula down to last row ..WORKS!
      sRR4lc.activate(); //ROW4 COL18 is selected through to last col
      sRR4lc.copyTo(fillDownRangeR4lc);
};
</code>```

Body:
I'm extremely green to javascript and have pieced together what I need through searching online and watching videos.  I need to set multiple columns in row4, starting from col 18 through to lastcolumn, as the active cells to copy and then pasteformulas down to the last row (if necessary, based on col 4's data).  Code I have below activates (selects) all data from col 18 through last column (as intended) but also through last row (unintended).  Anyone know how to correct this?

    function CopyFormulasDown() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var sRA4 = ss.getRange(4,1); //First copy is A4 ..this one works as intended
  var lr = ss.getLastRow();
  var lc = ss.getLastColumn();
  var sRR4lc = ss.getRange('R4:'+ lc +'4'); //Trying to select R4 through last col within row4; also tried (4,18+':'+lc), but throws an error: Exception: Cannot convert '18:37' to int.
  var fillDownRangeA4 = ss.getRange(4,1,lr);
  var fillDownRangeR4lc = ss.getRange(4,18,lr,lc);

   // sRA4.activate(); //range cell A4 is copied
    //sRA4.copyTo(fillDownRangeA4);  //copied cell pastes formula down to last row ..WORKS!
    sRR4lc.activate(); //ROW4 COL18 is selected through to last col as intended, but also selects down to last row.... problem is I didn't tell it to select past row 4... not sure how to correct this
   // sRR4lc.copyTo(fillDownRangeR4lc); //commented out for now until I can get just row 4 from col 18 through last col copy to work
};

Body:
Omgoodness. After typing out the question and posting, I thought of adding the lc to the numofcolumns place instead.  Below is the working code for anyone who's interested:

  function CopyFormulasDown() {
    var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
    var sRA4 = ss.getRange(4,1); //copy A4
    var lr = ss.getLastRow();
    var lc = ss.getLastColumn();
    var sRR4lc = ss.getRange(4,18,1,lc); //select R4 through last col within row4
    var fillDownRangeA4 = ss.getRange(4,1,lr);
    var fillDownRangeR4lc = ss.getRange(4,18,lr,lc);

      sRA4.activate(); //range cell A4 is copied
      sRA4.copyTo(fillDownRangeA4);  //copied cell pastes formula down to last row ..WORKS!
      sRR4lc.activate(); //ROW4 COL18 is selected through to last col
      sRR4lc.copyTo(fillDownRangeR4lc);
};


答:
You need to define an external verification procedure that tells if a given character is to be kept or discarded. Then replace the equivalence check typically done in replace routines with this external function.

Here is an implementation that achieves the goal,

```<code>module str_mod
    implicit none
    integer, parameter :: IK = kind(0)
    integer, parameter :: SK = kind("a")
    integer, parameter :: LK = kind(.false.)
contains

    ! Returns `.true.` if it is a desired character.
    function isDesired(char) result(desired)
        character(1, SK), intent(in) :: char
        logical(LK) :: desired
        desired =   (SK_"0" <= char .and. char <= SK_"9") .or. &
                    (SK_"A" <= char .and. char <= SK_"Z") .or. &
                    (SK_"a" <= char .and. char <= SK_"z")
    end function

    function replace(str, isDesired) result(strrep)
        character(*, SK), intent(in)    :: str
        character(:, SK), allocatable   :: strrep
        procedure(logical(LK))          :: isDesired
        integer(IK)                     :: i, counter
        allocate(character(len(str), SK) :: strrep)
        counter = 0_IK
        do i = 1, len(str, kind = IK)
            if (.not. isDesired(str(i:i))) cycle
            counter = counter + 1_IK
            strrep(counter:counter) = str(i:i)
        end do
        strrep = strrep(1:counter)
    end function

end module str_mod

    use str_mod
    print *, replace("Fortran", isDesired)
    print *, replace("(Fortran)", isDesired)
    print *, replace("(Fortran) (Is) [_A_] (GREAT) {language}.", isDesired)
    print *, replace("[AS:1]", isDesired)

end
</code>```

Here is the program output,

```<code> Fortran
 Fortran
 FortranIsAGREATlanguage
 AS1
</code>```

Test it here. Note that this implementation performs two allocations of the output strings, which you could likely avoid by counting the desired characters in str first and then allocating the output string to the proper size and filling it with the identified characters. But any performance gain or difference will likely be negligible in most scenarios. You would likely see better performance benefits if you instead reimplement replace() in the above as a subroutine with str input argument being an allocatable with intent(inout). In such a case, you can avoid an extra copy on exit from the procedure, which can lead to ~25% runtime speedup for small arrays. But again, such performance concerns become relevant only when you call replace() on the order of billions of times.

Body:
You need to define an external verification procedure that tells if a given character is to be kept or discarded. Then replace the equivalence check typically done in replace routines with this external function.

Here is an implementation that achieves the goal,

module str_mod
    implicit none
    integer, parameter :: IK = kind(0)
    integer, parameter :: SK = kind("a")
    integer, parameter :: LK = kind(.false.)
contains

    ! Returns `.true.` if it is a desired character.
    function isDesired(char) result(desired)
        character(1, SK), intent(in) :: char
        logical(LK) :: desired
        desired =   (SK_"0" <= char .and. char <= SK_"9") .or. &
                    (SK_"A" <= char .and. char <= SK_"Z") .or. &
                    (SK_"a" <= char .and. char <= SK_"z")
    end function

    function replace(str, isDesired) result(strrep)
        character(*, SK), intent(in)    :: str
        character(:, SK), allocatable   :: strrep
        procedure(logical(LK))          :: isDesired
        integer(IK)                     :: i, counter
        allocate(character(len(str), SK) :: strrep)
        counter = 0_IK
        do i = 1, len(str, kind = IK)
            if (.not. isDesired(str(i:i))) cycle
            counter = counter + 1_IK
            strrep(counter:counter) = str(i:i)
        end do
        strrep = strrep(1:counter)
    end function

end module str_mod

    use str_mod
    print *, replace("Fortran", isDesired)
    print *, replace("(Fortran)", isDesired)
    print *, replace("(Fortran) (Is) [_A_] (GREAT) {language}.", isDesired)
    print *, replace("[AS:1]", isDesired)

end

Here is the program output,

 Fortran
 Fortran
 FortranIsAGREATlanguage
 AS1

Test it here. Note that this implementation performs two allocations of the output strings, which you could likely avoid by counting the desired characters in str first and then allocating the output string to the proper size and filling it with the identified characters. But any performance gain or difference will likely be negligible in most scenarios. You would likely see better performance benefits if you instead reimplement replace() in the above as a subroutine with str input argument being an allocatable with intent(inout). In such a case, you can avoid an extra copy on exit from the procedure, which can lead to ~25% runtime speedup for small arrays. But again, such performance concerns become relevant only when you call replace() on the order of billions of times.


问:
IntrinsicAttributes props in React Typescript component
Hello I have this message alert:

The type '{ children: string; notify: string; }' cannot be assigned to
type 'IntrinsicAttributes & { notify: any; }'.   Property 'children'
does not exist on type 'IntrinsicAttributes & { notify: any;
}'.ts(2322)

using Card component. This is the first time I get it.

this is the component:

```<code>const Card = (props:{notify:any}) => {

  if (props.notify.length> 0> 0){
    return <IonIcon icon={notifications}  id="iconoHomeCampana">  </IonIcon>

  }else{
    return <IonIcon icon={notificationsOff}  id="iconoHomeCampana">  </IonIcon>
  }
}

export interface newMessage{
  de:string
  ticket:string
}

const App= () => {

  const [notifications, setNotifications] =  useState < newMessage []> ( [])

  useEffect(() => {

  axios.get(url+"chatsinleer/"+props.email).then((resp: { data: any; }) => {
      if (resp.data!="bad"){
        setNotifications(resp.data.map((d: { de: any; ticket: any; }) => ({
          de:d.de,
          ticket:d.ticket,
          })));
      }
    })

  }, []);

return (
      <IonPage >
        <IonHeader>
          <IonToolbar>
            <IonGrid>
              <IonRow id="header">
                <IonCol id="columna" size="1.5"><IonButtons ><IonMenuButton /> </IonButtons></IonCol>
                <IonCol id="columna2" ><Busqueda categorias={categorias} setCategorias={setCategorias} setProveedorBuscadoHook={setProveedorBuscadoHook} setBuscar={setBuscar} /></IonCol>
                <IonCol id="columna3" size="1.5">
                  <Card notify={notifications}>  </Card>
                </IonCol>
              </IonRow>
            </IonGrid>
          </IonToolbar>
        </IonHeader>
    )
}
</code>```

答:
You need to delete space inside <Card notify={notifications}>  </Card>

and use it instead like <Card notify={notifications}></Card> or even better like this:

```<code><Card notify={notifications}/>
</code>```

Problem is that react perceived space as child element;

Here is simple repro which also gave same error:

```<code>const Comp1 = ({ a }: { a: boolean }) => {
  return null;
};

const Comp2 = () => {
  return <Comp1 a={true}> </Comp1>;
};
</code>```

Body:
Hello I have this message alert:

The type '{ children: string; notify: string; }' cannot be assigned to
type 'IntrinsicAttributes & { notify: any; }'.   Property 'children'
does not exist on type 'IntrinsicAttributes & { notify: any;
}'.ts(2322)

using Card component. This is the first time I get it.

this is the component:

const Card = (props:{notify:any}) => {

  if (props.notify.length> 0> 0){
    return <IonIcon icon={notifications}  id="iconoHomeCampana">  </IonIcon>

  }else{
    return <IonIcon icon={notificationsOff}  id="iconoHomeCampana">  </IonIcon>
  }
}

export interface newMessage{
  de:string
  ticket:string
}

const App= () => {

  const [notifications, setNotifications] =  useState < newMessage []> ( [])

  useEffect(() => {

  axios.get(url+"chatsinleer/"+props.email).then((resp: { data: any; }) => {
      if (resp.data!="bad"){
        setNotifications(resp.data.map((d: { de: any; ticket: any; }) => ({
          de:d.de,
          ticket:d.ticket,
          })));
      }
    })

  }, []);

return (
      <IonPage >
        <IonHeader>
          <IonToolbar>
            <IonGrid>
              <IonRow id="header">
                <IonCol id="columna" size="1.5"><IonButtons ><IonMenuButton /> </IonButtons></IonCol>
                <IonCol id="columna2" ><Busqueda categorias={categorias} setCategorias={setCategorias} setProveedorBuscadoHook={setProveedorBuscadoHook} setBuscar={setBuscar} /></IonCol>
                <IonCol id="columna3" size="1.5">
                  <Card notify={notifications}>  </Card>
                </IonCol>
              </IonRow>
            </IonGrid>
          </IonToolbar>
        </IonHeader>
    )
}

Body:
You need to delete space inside <Card notify={notifications}>  </Card>

and use it instead like <Card notify={notifications}></Card> or even better like this:

<Card notify={notifications}/>

Problem is that react perceived space as child element;

Here is simple repro which also gave same error:

const Comp1 = ({ a }: { a: boolean }) => {
  return null;
};

const Comp2 = () => {
  return <Comp1 a={true}> </Comp1>;
};


问:
Write a program that prompts the user for first and last names. The program then prints last name and first
Write a program that prompts the user for first and last names. The program then prints last name and first. If user only enter one name, then give an error message. Please help for my if statement. Many Thanks

```<code>name = str(input("Your first and last names? "))
gap = name.find(" ")
name_length = len(name)
first = name[0:gap]
last = name[gap + 1 : name_length]
if name_length is 2:
    print("Name: ", last.upper(), ", ", first.capitalize(), sep = "")

else:
    print("ERROR: only one name found")
</code>```

And these are what I except:

anGUS snodgrass

Your first and last names? Name: SNODGRASS, Angus

angus

Your first and last names? ERROR: only one name found

答:
```<code>fname = input("Input your First Name : ")

lname = input("Input your Last Name : ")

print ("Hello " + lname + " " + fname)

first_name = input('Please input your first name: ')
last_name = input('Please input your last name: ')
print(last_name + ', ' + first_name)
</code>```

Body:
Write a program that prompts the user for first and last names. The program then prints last name and first. If user only enter one name, then give an error message. Please help for my if statement. Many Thanks

name = str(input("Your first and last names? "))
gap = name.find(" ")
name_length = len(name)
first = name[0:gap]
last = name[gap + 1 : name_length]
if name_length is 2:
    print("Name: ", last.upper(), ", ", first.capitalize(), sep = "")

else:
    print("ERROR: only one name found")

And these are what I except:

anGUS snodgrass

Your first and last names? Name: SNODGRASS, Angus

angus

Your first and last names? ERROR: only one name found