问:
"Enter-PSSession -Session", block the calling process until user types "exit"
I'm having a problem with using New-PSSession in combination with "Enter-PSSession -session". Namely, that there's no way to block the calling process until the user types "exit" in the interactive PSSession.  Here's a code example:

```<code>$s = New-PSSession -computer "remotecomputer1"
Invoke-Command -Session $s -ScriptBlock {
    dir | out-host
    # Setup misc stuff needed for
    # Enter-PSSesion
}
Enter-PSSesion -Session $s
#
# at this point there are 2 threads running...
# one thread for the main script, and
# the other for PSSession
#
# Wait-PSSession -Session $s <== THE MISSING
#  COMMAND THAT IS NONE EXISTENT IN POWERSHELL
#
# Now the main thread falls-though and
# doesn't  wait!!!!! because there's
# no command to stop this????
write-host "Shouldn't get here" `
    + "until user types 'exit'" `
    + "in `Enter-PSsession -Session`"
</code>```

Why this matters?  Because what happens if I call this from WSL:

```<code>$ powershell.exe -File MyRemoting.ps1
</code>```

It kills the interactive session because it doesn't block the main thread until the interactive session remoting session finishes.

答:
tl;dr

What you're seeing is a bug (see bottom section).

There is currently only a suboptimal workaround for your use case:

You can call Enter-PSSession via the Powershell CLI (powershell.exe) with -NoExit in order to force an interactive remote session to be entered synchronously from a script; since you won't be able to pass the session object directly to the CLI call[1], you'll have to retrieve the session via Get-PSSession, by computer name and self-chosen session name.

However, note that this CLI-based workaround has an unpleasant side effect: you need to submit exit twice in order to return control to the caller; first to exit the remote session, and again to exit the CLI call's enclosing local session.

# Create the remote session indirectly, in a *disconnected* state,
# by submitting the session-initialization commands via Invoke-Command:
$computerName = 'remotecomputer1'  # remote target computer.
$sessionName = "example_$pid"      # self-chosen session name.
$null = Invoke-Command -InDisconnectedSession -ComputerName $computerName -SessionName $sessionName -ScriptBlock {
    # Set up misc. stuff.
    $foo = 'bar' # Set sample variable.
}

# Work around the bug: force entering the remote session
# *synchronously* via the CLI.
# !! IMPORTANT: YOU'LL NEED to submit `exit` TWICE
# !!            TO EXIT THE REMOTE SESSION.
powershell.exe -NoExit -NoProfile {
  param($ComputerName, $SessionName)
  # Retrieve the preconfigured session from the remote computer.
  $session = Get-PSSession -ComputerName $ComputerName -Name $SessionName
  # Synchronously enter the session interactively.
  # Note:
  #  * In order for Enter-PSSession to succeed, the session must be
  #    in the *disconnected* state, which we've ensured above.
  #  * You may get the following warning, which you can ignore:
  #       "You have entered a session that is busy running a command or script and output will be displayed in the console.
  #        You can wait for the running command to finish or cancel
  #        it and get an input prompt by pressing Ctrl-C."
  # If you submit $foo interactively, 'bar' should be reported,
  # conforming use of the preconfigured session.
  Enter-PSSession -Session $session
} -Args $computerName, $sessionName

# As desired, this command now executes only after the remote
# session (and its transient wrapper session) have exited.
Write-Host @'
Should only get here after the user has typed 'exit'
*twice* in the remote session.
'@
```
<hr />
<p>What you're seeing is <strong>a <em>bug</em> in <code>Enter-PSSession</code></strong> - see GitHub issue #16350 - present up to at least PowerShell (Core) 7.2.1:</p>
<p><strong><code>Enter-PSSession</code> should <em>always</em> block, in that it should enter an  <em>interactive</em> remote session that shouldn't exit and therefore shouldn't return control to the caller <em>until the user interactively terminates the remote session</em></strong>, typically by submitting <code>exit</code> or the equivalent <code>Exit-PSSession</code>.</p>
<p>This currently only works when <code>Enter-PSSession</code> is called directly <em>directly from the prompt</em> of a (local) interactive PowerShell session.</p>
<p>In other words: <strong><code>Enter-PSSession</code> is currently broken when you call it <em>from a script</em> and/or <em>via the CLI</em></strong> (<code>pwsh</code> for PowerShell (Core) 7+, <code>powershell.exe</code> for Windows PowerShell):</p>
<p>Entering the remote session is then unexpectedly <em>deferred</em>, and <em>local execution of the remaining commands in the script file / passed to the <code>-Command</code> (<code>-c</code>) CLI parameter continues right away</em>. In the case of the CLI, the deferred remote session is effectively never entered:</p>
<ul>
<li><p>If you call a script file containing <code>Enter-PSSession</code> from inside a (local) PowerShell session, the remote session is then unexpectedly not entered until <em>after the script has finished</em>.</p>
<ul>
<li><p>You can simulate this scenario via script <em>block</em> as follows; note: requires running from an <em>elevated</em> session, and requires your machine to be set up for PowerShell remoting:</p>
<pre class="lang-sh prettyprint-override"><code># !! With the bug present, 'ConsoleHost' prints *first*
# !! - implying *local* execution - and only *then*
# !! is the interactive remote session entered.
& { Enter-PSSession -ComputerName .; $Host.Name }
</code>```

If you call via the CLI, a remote interactive session is never even entered:

If you call powershell.exe - whether or not the last command is exit - or pwsh.exe with exit as the last command, the entire PowerShell process exits after all commands have executed locally and returns control to the caller; in other words: the interactive remote session is never entered.

If you call pwsh.exe without an explicit exit statement, the CLI call hangs after local command execution, and even Ctrl-C doesn't help.

Example (again, run from an elevated session, and make sure that your machine is set up for PowerShell remoting):

# !! With the bug present, 'ConsoleHost' prints *right away*
# !! - implying *local* execution - and then *returns*, i.e.
# !! the interactive *remote* session is never entered.
powershell -c 'Enter-PSSession -ComputerName .; $Host.Name; exit'
```

As discussed and shown in the code in the top section, a suboptimal workaround is to use -NoExit to ensure that the session is entered, but at the expense of having exit twice.

[1] Even though calling the PowerShell CLI from inside PowerShell with a script block { ... } tries to pass objects and not just strings via the -Args parameter, the objects undergo serialization and deserialization, which can result in loss of type fidelity. Indeed, in the case at hand, the deserialized form of what originally was a [System.Management.Automation.Runspaces.PSSession] instance (created by New-PSSession) is not recognized by Enter-PSSession's -Session parameter.

Body:
I'm having a problem with using New-PSSession in combination with "Enter-PSSession -session". Namely, that there's no way to block the calling process until the user types "exit" in the interactive PSSession.  Here's a code example:

$s = New-PSSession -computer "remotecomputer1"
Invoke-Command -Session $s -ScriptBlock {
    dir | out-host
    # Setup misc stuff needed for
    # Enter-PSSesion
}
Enter-PSSesion -Session $s
#
# at this point there are 2 threads running...
# one thread for the main script, and
# the other for PSSession
#
# Wait-PSSession -Session $s <== THE MISSING
#  COMMAND THAT IS NONE EXISTENT IN POWERSHELL
#
# Now the main thread falls-though and
# doesn't  wait!!!!! because there's
# no command to stop this????
write-host "Shouldn't get here" `
    + "until user types 'exit'" `
    + "in `Enter-PSsession -Session`"

Why this matters?  Because what happens if I call this from WSL:

$ powershell.exe -File MyRemoting.ps1

It kills the interactive session because it doesn't block the main thread until the interactive session remoting session finishes.

Body:
tl;dr

What you're seeing is a bug (see bottom section).

There is currently only a suboptimal workaround for your use case:

You can call Enter-PSSession via the Powershell CLI (powershell.exe) with -NoExit in order to force an interactive remote session to be entered synchronously from a script; since you won't be able to pass the session object directly to the CLI call[1], you'll have to retrieve the session via Get-PSSession, by computer name and self-chosen session name.

However, note that this CLI-based workaround has an unpleasant side effect: you need to submit exit twice in order to return control to the caller; first to exit the remote session, and again to exit the CLI call's enclosing local session.

# Create the remote session indirectly, in a *disconnected* state,
# by submitting the session-initialization commands via Invoke-Command:
$computerName = 'remotecomputer1'  # remote target computer.
$sessionName = "example_$pid"      # self-chosen session name.
$null = Invoke-Command -InDisconnectedSession -ComputerName $computerName -SessionName $sessionName -ScriptBlock {
    # Set up misc. stuff.
    $foo = 'bar' # Set sample variable.
}

# Work around the bug: force entering the remote session
# *synchronously* via the CLI.
# !! IMPORTANT: YOU'LL NEED to submit `exit` TWICE
# !!            TO EXIT THE REMOTE SESSION.
powershell.exe -NoExit -NoProfile {
  param($ComputerName, $SessionName)
  # Retrieve the preconfigured session from the remote computer.
  $session = Get-PSSession -ComputerName $ComputerName -Name $SessionName
  # Synchronously enter the session interactively.
  # Note:
  #  * In order for Enter-PSSession to succeed, the session must be
  #    in the *disconnected* state, which we've ensured above.
  #  * You may get the following warning, which you can ignore:
  #       "You have entered a session that is busy running a command or script and output will be displayed in the console.
  #        You can wait for the running command to finish or cancel
  #        it and get an input prompt by pressing Ctrl-C."
  # If you submit $foo interactively, 'bar' should be reported,
  # conforming use of the preconfigured session.
  Enter-PSSession -Session $session
} -Args $computerName, $sessionName

# As desired, this command now executes only after the remote
# session (and its transient wrapper session) have exited.
Write-Host @'
Should only get here after the user has typed 'exit'
*twice* in the remote session.
'@

What you're seeing is a bug in Enter-PSSession - see GitHub issue #16350 - present up to at least PowerShell (Core) 7.2.1:

Enter-PSSession should always block, in that it should enter an  interactive remote session that shouldn't exit and therefore shouldn't return control to the caller until the user interactively terminates the remote session, typically by submitting exit or the equivalent Exit-PSSession.

This currently only works when Enter-PSSession is called directly directly from the prompt of a (local) interactive PowerShell session.

In other words: Enter-PSSession is currently broken when you call it from a script and/or via the CLI (pwsh for PowerShell (Core) 7+, powershell.exe for Windows PowerShell):

Entering the remote session is then unexpectedly deferred, and local execution of the remaining commands in the script file / passed to the -Command (-c) CLI parameter continues right away. In the case of the CLI, the deferred remote session is effectively never entered:

If you call a script file containing Enter-PSSession from inside a (local) PowerShell session, the remote session is then unexpectedly not entered until after the script has finished.

You can simulate this scenario via script block as follows; note: requires running from an elevated session, and requires your machine to be set up for PowerShell remoting:

# !! With the bug present, 'ConsoleHost' prints *first*
# !! - implying *local* execution - and only *then*
# !! is the interactive remote session entered.
& { Enter-PSSession -ComputerName .; $Host.Name }

If you call via the CLI, a remote interactive session is never even entered:

If you call powershell.exe - whether or not the last command is exit - or pwsh.exe with exit as the last command, the entire PowerShell process exits after all commands have executed locally and returns control to the caller; in other words: the interactive remote session is never entered.

If you call pwsh.exe without an explicit exit statement, the CLI call hangs after local command execution, and even Ctrl-C doesn't help.

Example (again, run from an elevated session, and make sure that your machine is set up for PowerShell remoting):

# !! With the bug present, 'ConsoleHost' prints *right away*
# !! - implying *local* execution - and then *returns*, i.e.
# !! the interactive *remote* session is never entered.
powershell -c 'Enter-PSSession -ComputerName .; $Host.Name; exit'

As discussed and shown in the code in the top section, a suboptimal workaround is to use -NoExit to ensure that the session is entered, but at the expense of having exit twice.

[1] Even though calling the PowerShell CLI from inside PowerShell with a script block { ... } tries to pass objects and not just strings via the -Args parameter, the objects undergo serialization and deserialization, which can result in loss of type fidelity. Indeed, in the case at hand, the deserialized form of what originally was a [System.Management.Automation.Runspaces.PSSession] instance (created by New-PSSession) is not recognized by Enter-PSSession's -Session parameter.


来源: stackexchange

问:
How to hide certain texts retrieved from Strings.xml
I have an English teaching app where the users are given some sentences with their Turkish equivalents. I retrieve the data from Strings.xml as follows:

<.b>Possession (Aitlik)\n\nhave
        (sahip olmak)\npossess (sahip olmak)\nown (sahip olmak)\nbelong (ait olmak)\nconsist (-den meydana gelmek)\nlack (eksik olmak)\ninvolve
        (içermek)\n\n<.b>Emotions (Duygular)\n\nlike (sevmek)\ndislike (sevmemek)\nprefer (tercih etmek)\nappreciate (takdir etmek)\nneed
        (ihtiyacı olmak)\nwish (istemek, dilemek)\nhope (ummak)\nvalue (değer vermek)\nadore (hayran olmak)\nfear (korkmak)\nsurprise (şaşırtmak)\nenvy
        (kıskanmak)\nhate (nefret etmek)\nlove (sevmek)\n\n
    ...
```
<p>If the user wishes, I'd like to hide the translations of the words. Is there a way to do it? So far, I tried separating the example sentences from their translations and hiding the translations from the code:</p>
<pre class="lang-xml prettyprint-override"><code><string name=header_one>"<.b>Possession</b>"</string>
<string name=header_one_translation>"<.b>Aitlik</b>"</string>
</code>```

binding.hideTranslationsButton.setOnClickListener {
            binding.headerOneTranslation.isGone = true
            binding.translationOne.isGone = true
            binding.translationTwo.isGone = true
            binding.translationThree.isGone = true
            binding.translationFour.isGone = true
            binding.translationFive.isGone = true
            binding.translationSix.isGone = true
            ...
        }
```

but it took too much time and it feels like my code has gotten messier considering I have 50 other grammar topics like this (I put dots intentionally --> <.b>).

答:
Maybe think about reordering your layouts.

Dunno what your structure is.

```<code><LinearLayout id=root>
   <LinearLayout id=english>
       <LinearLayout id=sentence1/>
       <LinearLayout id=sentence2/>
   </LinearLayout>
   <LinearLayout id=turkish>
       <LinearLayout id=translate1/>
       <LinearLayout id=translate2/>
   </LinearLayout>
</LinearLayout>
</code>```

and now you hide the turkish layout.

ContentLicense: CC BY-SA 4.0

Body:
I have an English teaching app where the users are given some sentences with their Turkish equivalents. I retrieve the data from Strings.xml as follows:

<.b>Possession (Aitlik)\n\nhave
        (sahip olmak)\npossess (sahip olmak)\nown (sahip olmak)\nbelong (ait olmak)\nconsist (-den meydana gelmek)\nlack (eksik olmak)\ninvolve
        (içermek)\n\n<.b>Emotions (Duygular)\n\nlike (sevmek)\ndislike (sevmemek)\nprefer (tercih etmek)\nappreciate (takdir etmek)\nneed
        (ihtiyacı olmak)\nwish (istemek, dilemek)\nhope (ummak)\nvalue (değer vermek)\nadore (hayran olmak)\nfear (korkmak)\nsurprise (şaşırtmak)\nenvy
        (kıskanmak)\nhate (nefret etmek)\nlove (sevmek)\n\n
    ...

If the user wishes, I'd like to hide the translations of the words. Is there a way to do it? So far, I tried separating the example sentences from their translations and hiding the translations from the code:

<string name=header_one>"<.b>Possession"</string>
<string name=header_one_translation>"<.b>Aitlik"</string>

binding.hideTranslationsButton.setOnClickListener {
            binding.headerOneTranslation.isGone = true
            binding.translationOne.isGone = true
            binding.translationTwo.isGone = true
            binding.translationThree.isGone = true
            binding.translationFour.isGone = true
            binding.translationFive.isGone = true
            binding.translationSix.isGone = true
            ...
        }

but it took too much time and it feels like my code has gotten messier considering I have 50 other grammar topics like this (I put dots intentionally --> <.b>).

Body:
Maybe think about reordering your layouts.

Dunno what your structure is.

<LinearLayout id=root>
   <LinearLayout id=english>
       <LinearLayout id=sentence1/>
       <LinearLayout id=sentence2/>
   </LinearLayout>
   <LinearLayout id=turkish>
       <LinearLayout id=translate1/>
       <LinearLayout id=translate2/>
   </LinearLayout>
</LinearLayout>

and now you hide the turkish layout.


问:
How do I hide an option in react-select
Basically i have two dropdowns. based on a value selected in one dropdown I want to hdie certain options in another dropdown. </p>

<p>I tried adding a className parameter to the option object along with label and value params and tried setting the display of all options with the above className to none but it did not set the className of the option to the one i specified. </p>

```<code>[{'label':'x','value':'y',className:'hide'}]
.hide{
display:none
}
</code>```

答:
According to https://react-select.com/props

filterOption

Custom method to filter whether an option should be displayed in the menu

You just need to use filterOption

For example if you want to hide an option with value="hiddenOption" you need :

```<code><Select filterOption={(option) => option.value !== "hiddenOption"} />
</code>```

Title: How do I hide an option in react-select

Body:
Basically i have two dropdowns. based on a value selected in one dropdown I want to hdie certain options in another dropdown.

I tried adding a className parameter to the option object along with label and value params and tried setting the display of all options with the above className to none but it did not set the className of the option to the one i specified.

[{'label':'x','value':'y',className:'hide'}]
.hide{
display:none
}

Body:
According to https://react-select.com/props

filterOption

Custom method to filter whether an option should be displayed in the menu

You just need to use filterOption

For example if you want to hide an option with value="hiddenOption" you need :

<Select filterOption={(option) => option.value !== "hiddenOption"} />


问:
check if first two letter (digits) in a ip adress is '41' with PHP?
I use PHP:s ['REMOTE_ADDR'] to fetch the users ip.

I want to see if that ip starts with a 41.

```<code>$usr_ip = $_SERVER['REMOTE_ADDR'];
</code>```

Then I want to match, and if it starts with 41, then die()

I don't know how to do the matching.

答: What about substr()?</p>

ContentLicense: CC BY-SA 3.0

Body:
I use PHP:s ['REMOTE_ADDR'] to fetch the users ip.

I want to see if that ip starts with a 41.

$usr_ip = $_SERVER['REMOTE_ADDR'];

Then I want to match, and if it starts with 41, then die()

I don't know how to do the matching.

Body: What about substr()?


问:
SQL query for grouping by (project, environment) and finding the newest entry for each combination?
I have a table with data that looks like the following

```<code>project  | environment | timestamp
----------------------------------------
project1 | dev         | 1644515845
project1 | dev         | 1644513211
project1 | qa          | 1644515542
project2 | dev         | 1644513692
project2 | qa          | 1644514822
</code>```

There are multiple projects and each project has multiple environments. There are multiple timestamps associated with each (project, environment) pair which correspond to the last time changes were made to the project.

Is there a query to group by (project, environment) and get the the entry with the newest timestamp for each combination of (project, environment)?

Something like

```<code>SELECT c.project, c.environment, c.timestamp
FROM c
GROUP BY c.project, c.environment, c.timestamp
ORDER BY c.timestamp
</code>```

But it should only return one entry (the newest) for each (project, environment) tuple. My database is in a Cosmo DB if that makes a difference.

This is my expected output

```<code>project  | environment | timestamp
----------------------------------------
project1 | dev         | 1644515845
project1 | qa          | 1644515542
project2 | dev         | 1644513692
project2 | qa          | 1644514822
</code>```

答:
You remove the timestamp from the group and selcet the MAX of thetomestamo

```<code>SELECT `project`, `environment`, MAX(`timestamp`)
FROM
c
GROUP BY `project`, `environment`
</code>```

here os a mysql sample to show that it works https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=86353790b7f73f766df01997255bdeb3

Body:
I have a table with data that looks like the following

project  | environment | timestamp
----------------------------------------
project1 | dev         | 1644515845
project1 | dev         | 1644513211
project1 | qa          | 1644515542
project2 | dev         | 1644513692
project2 | qa          | 1644514822

There are multiple projects and each project has multiple environments. There are multiple timestamps associated with each (project, environment) pair which correspond to the last time changes were made to the project.

Is there a query to group by (project, environment) and get the the entry with the newest timestamp for each combination of (project, environment)?

Something like

SELECT c.project, c.environment, c.timestamp
FROM c
GROUP BY c.project, c.environment, c.timestamp
ORDER BY c.timestamp

But it should only return one entry (the newest) for each (project, environment) tuple. My database is in a Cosmo DB if that makes a difference.

This is my expected output

project  | environment | timestamp
----------------------------------------
project1 | dev         | 1644515845
project1 | qa          | 1644515542
project2 | dev         | 1644513692
project2 | qa          | 1644514822

Body:
You remove the timestamp from the group and selcet the MAX of thetomestamo

SELECT `project`, `environment`, MAX(`timestamp`)
FROM
c
GROUP BY `project`, `environment`

here os a mysql sample to show that it works https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=86353790b7f73f766df01997255bdeb3


问:
Activate conda environment without conda
Suppose I have a conda environment folder but no conda nor requirements file. Is there a way to use the environment, i.e. to activate or extract requirements, without installing conda?</p>

答:
Basic Pip exporting

Let's assume the environment is /path/to/env, with a /path/to/env/bin/python installed. If one only wants the Python packages, and pip is installed, then probably sufficient to do:

/path/to/env/bin/python -s -m pip list --format=freeze > requirements.txt
```

Note the -s flag insulates the site module from include packages in a user site (e.g., ~/.local/lib/pythonX.Y/site-packages/); if you want those included for some reason, then drop the flag.

Mimicking Conda activation

More diligently, one could simulate a basic activation by

Prepending environment's bin/ to PATH; and

Running any activation shell scripts (found in etc/conda/activate.d/); note that sometimes there are no such scripts and that folder doesn't exist.

Then exporting could be done with python -s -m pip list --format=freeze.

In most cases, I wouldn't expect a difference here, but I include it for completeness. We can't rule out that a package might be out there that manipulates environment variables via activation scripts in such a way that  pip list output is changed. Not saying I've seen this, only that it's possible.

Body:
Basic Pip exporting

Let's assume the environment is /path/to/env, with a /path/to/env/bin/python installed. If one only wants the Python packages, and pip is installed, then probably sufficient to do:

/path/to/env/bin/python -s -m pip list --format=freeze > requirements.txt

Note the -s flag insulates the site module from include packages in a user site (e.g., ~/.local/lib/pythonX.Y/site-packages/); if you want those included for some reason, then drop the flag.

Mimicking Conda activation

More diligently, one could simulate a basic activation by

Prepending environment's bin/ to PATH; and

Running any activation shell scripts (found in etc/conda/activate.d/); note that sometimes there are no such scripts and that folder doesn't exist.

Then exporting could be done with python -s -m pip list --format=freeze.

In most cases, I wouldn't expect a difference here, but I include it for completeness. We can't rule out that a package might be out there that manipulates environment variables via activation scripts in such a way that  pip list output is changed. Not saying I've seen this, only that it's possible.


问:
Swift map from array of objects to array of async functions and await them all
I've just updated to Xcode 13.2.1 and now have access to async await and I'm trying to find places I can "convert" from Combine over to async await.

I want to achieve the following...

Given a type like...

```<code>struct Person {
  let name: String

  func fetchAvatar(completion: @escaping (UIImage?) -> Void) {
    // fetch the image from the web and pass it into the completion.
  }
}
</code>```

I currently have a function like this...

```<code>func fetchAllTheAvatars(people: [Person], completion: ([UIImage]) -> Void) {
  Publisher.MergeMany(
    people.map { person in
      Future<UIImage?, Never> { promise in
        person.fetchAvatar { promise(.success($0)) }
      }
    }
  )
  .compactMap { $0 }
  .collect()
  .sink { completion($0) }
  .store(in: &cancellables )
}
</code>```

Now... it looks to me like this could be a good candidate for moving to using async await and AsyncSequence maybe...?!? It doesn't have to be ideal though, I just want to get a feel of how to use them. I'm used to async await in JS and TS and this just seems a little bit different. :D

I added a wrapper function to my Person...

```<code>func fetchAvatar() async -> UIImage? {
  await withCheckedContinuation { continuation in
    fetchAvatar { image in
      continuation.resume(returning: image)
    }
  }
}
</code>```

But now I'm stuck on how to update my fetchAllTheAvatars function.

```<code>func fetchAllTheAvatars(people: [Person]) async -> [UIImage] {
  people.map { ...???... }
}
</code>```

Everywhere I have seen online seems to use for await line in url.lines { ... } but I don't yet have an AsyncSequence. I need to somehow "convert" my non-async array of Person into an AsyncSequence of () -> Image?.

Is that possible? Am I going about this entirely the wrong way?

Thanks

答:
The standard pattern is TaskGroup. Add your tasks for the individual images, and then await in a for loop, map, or, in this case, reduce:

func fetchAllTheAvatars(people: [Person]) async -> [Person.ID: UIImage] {
    await withTaskGroup(of: (Person.ID, UIImage?).self) { group in
        for person in people {
            group.addTask { await (person.id, person.fetchAvatar()) }
        }

        return await group.reduce(into: [:]) { dictionary, result in
            if let image = result.1 {
                dictionary[result.0] = image
            }
        }
    }
}
```
<p>Note, because the order is not guaranteed and because some of your <code>Person</code> may not return an image, my implementation returns an efficient, order-independent, structure (i.e., a dictionary).</p>
<p>Needless to say, the above assumes that you make <code>Person</code> conform to <code>Identifiable</code>:</p>
<pre class="lang-swift prettyprint-override"><code>struct Person: Identifiable {
    let id = UUID()
    let name: String

    func fetchAvatar() async -> UIImage? { … }
}
</code>```

Body:
I've just updated to Xcode 13.2.1 and now have access to async await and I'm trying to find places I can "convert" from Combine over to async await.

I want to achieve the following...

Given a type like...

struct Person {
  let name: String

  func fetchAvatar(completion: @escaping (UIImage?) -> Void) {
    // fetch the image from the web and pass it into the completion.
  }
}

I currently have a function like this...

func fetchAllTheAvatars(people: [Person], completion: ([UIImage]) -> Void) {
  Publisher.MergeMany(
    people.map { person in
      Future<UIImage?, Never> { promise in
        person.fetchAvatar { promise(.success($0)) }
      }
    }
  )
  .compactMap { $0 }
  .collect()
  .sink { completion($0) }
  .store(in: &cancellables )
}

Now... it looks to me like this could be a good candidate for moving to using async await and AsyncSequence maybe...?!? It doesn't have to be ideal though, I just want to get a feel of how to use them. I'm used to async await in JS and TS and this just seems a little bit different. :D

I added a wrapper function to my Person...

func fetchAvatar() async -> UIImage? {
  await withCheckedContinuation { continuation in
    fetchAvatar { image in
      continuation.resume(returning: image)
    }
  }
}

But now I'm stuck on how to update my fetchAllTheAvatars function.

func fetchAllTheAvatars(people: [Person]) async -> [UIImage] {
  people.map { ...???... }
}

Everywhere I have seen online seems to use for await line in url.lines { ... } but I don't yet have an AsyncSequence. I need to somehow "convert" my non-async array of Person into an AsyncSequence of () -> Image?.

Is that possible? Am I going about this entirely the wrong way?

Thanks

Body:
The standard pattern is TaskGroup. Add your tasks for the individual images, and then await in a for loop, map, or, in this case, reduce:

func fetchAllTheAvatars(people: [Person]) async -> [Person.ID: UIImage] {
    await withTaskGroup(of: (Person.ID, UIImage?).self) { group in
        for person in people {
            group.addTask { await (person.id, person.fetchAvatar()) }
        }

        return await group.reduce(into: [:]) { dictionary, result in
            if let image = result.1 {
                dictionary[result.0] = image
            }
        }
    }
}

Note, because the order is not guaranteed and because some of your Person may not return an image, my implementation returns an efficient, order-independent, structure (i.e., a dictionary).

Needless to say, the above assumes that you make Person conform to Identifiable:

struct Person: Identifiable {
    let id = UUID()
    let name: String

    func fetchAvatar() async -> UIImage? { … }
}


问:
Deeplink empty String Argument
I'm using the Jetpack Navigation as a navigation solution in my app.

I'm facing an inconsistent behaviour when using the generated safe args as opposed to the deeplink strategy.

Say I have following navigation graph:

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    app:startDestination="@+id/home_dest">

    <fragment
        android:id="@+id/home_dest"
        android:name="com.example.android.codelabs.navigation.HomeFragment"
        android:label="@string/home"
        tools:layout="@layout/home_fragment" >
        <action
            android:id="@+id/action_home_dest_to_deeplink_dest"
            app:destination="@id/deeplink_dest" />
    </fragment>

    <fragment
        android:id="@+id/deeplink_dest"
        android:name="com.example.android.codelabs.navigation.DeepLinkFragment"
        android:label="@string/deeplink"
        tools:layout="@layout/deeplink_fragment">

        <argument
            android:name="myarg"
            app:argType="string" />

        <deepLink app:uri="example://my-deelink-frag?myArg={myarg}" />
    </fragment>
</navigation>
```
<p>I have defined 2 ways to navigate to the <code>DeepLinkFragment</code>:</p>
<ul>
<li>Navigation action with id <code>action_home_dest_to_deeplink_dest</code></li>
<li>A deeplink <code>example://my-deelink-frag?myArg={myarg}</code></li>
</ul>
<p>In the <code>DeepLinkFragment</code> I'm using the <code>navArgs()</code> function to de-serialize the incoming <code>Bundle</code> and show a simple <code>Toast</code> message.</p>
<pre class="lang-kotlin prettyprint-override"><code>class DeepLinkFragment : Fragment() {

    private val args : DeepLinkFragmentArgs by navArgs()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Toast.makeText(requireContext(), args.myarg, Toast.LENGTH_SHORT).show()
    }
}
</code>```

When navigating with the generated safe args I can sent an empty string as the value for myArg.
No problem.

findNavController().navigate(HomeFragmentDirections.actionHomeDestToDeeplinkDest(""))
```
<p>However, when navigating with an empty string as argument via the deeplink way:</p>
<pre class="lang-kotlin prettyprint-override"><code>val arg = ""
findNavController().navigate("example://my-deelink-frag?myArg=${arg}".toUri())
</code>```

I get following stacktrace:

```<code> Caused by: java.lang.IllegalArgumentException: Required argument "myarg" is missing and does not have an android:defaultValue
    at com.example.android.codelabs.navigation.DeepLinkFragmentArgs$Companion.fromBundle(DeepLinkFragmentArgs.kt:29)
    at com.example.android.codelabs.navigation.DeepLinkFragmentArgs.fromBundle(Unknown Source:2)
    at java.lang.reflect.Method.invoke(Native Method)
    at androidx.navigation.NavArgsLazy.getValue(NavArgsLazy.kt:52)
    at androidx.navigation.NavArgsLazy.getValue(NavArgsLazy.kt:34)
    at com.example.android.codelabs.navigation.DeepLinkFragment.getArgs(DeepLinkFragment.kt:30)
    at com.example.android.codelabs.navigation.DeepLinkFragment.onViewCreated(DeepLinkFragment.kt:34)
    at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2987)
    at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:546)
    at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
    at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
    at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2106)
    at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
    at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:524)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:233)
    at android.app.ActivityThread.main(ActivityThread.java:8068)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:631)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:978)
</code>```

Which is coming from the generated DeeplinkFragmentArgs code

public data class DeepLinkFragmentArgs(
  public val myarg: String = ""
) : NavArgs {
  public fun toBundle(): Bundle {
    val result = Bundle()
    result.putString("myarg", this.myarg)
    return result
  }

  public companion object {
    @JvmStatic
    public fun fromBundle(bundle: Bundle): DeepLinkFragmentArgs {
      bundle.setClassLoader(DeepLinkFragmentArgs::class.java.classLoader)
      val __myarg : String?
      if (bundle.containsKey("myarg")) {
        __myarg = bundle.getString("myarg")
        if (__myarg == null) {
          throw IllegalArgumentException("Argument \"myarg\" is marked as non-null but was passed a null value.")
        }
      } else {
        __myarg = ""
      }
      return DeepLinkFragmentArgs(__myarg)
    }
  }
}
```
<blockquote>
<p>Looking at the code it seems as if an empty string is making the <code>bundle.getString("myarg")</code> return <code>null</code> instead of the empty string?!</p>
</blockquote>
<p>As a <em>fix</em> I could add the <code>android:defaultValue</code>.<br />
However I don't think is the right solution.</p>
<pre class="lang-xml prettyprint-override"><code><argument
    android:name="myarg"
    android:defaultValue=""
    app:argType="string" />
</code>```

Is this a known limitation when using deeplinks?

答:
One probably cannot pass an empty string as argument; for string one would usually  pass "@null" as default value (which also requires a nullable field); but it could as well be string "default", if you don't want to use any null values. If something may appear inconsistent, you may not have referenced the default nav-graph XML in AndroidManifest.xml, which merely defines the entry-point for the deep-linking. Also, version 2.5.0-alpha01 may be required, in order to build with the current AGP 7.1.1. There's no right or wrong, but it's convenient to let the NavController handle that - and generating code is preferred, over writing code.

At least in common HTTP, %02%03 would be an empty query-string parameter (yet untested).

Title: Deeplink empty String Argument

Body:
I'm using the Jetpack Navigation as a navigation solution in my app.

I'm facing an inconsistent behaviour when using the generated safe args as opposed to the deeplink strategy.

Say I have following navigation graph:

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    app:startDestination="@+id/home_dest">

    <fragment
        android:id="@+id/home_dest"
        android:name="com.example.android.codelabs.navigation.HomeFragment"
        android:label="@string/home"
        tools:layout="@layout/home_fragment" >
        <action
            android:id="@+id/action_home_dest_to_deeplink_dest"
            app:destination="@id/deeplink_dest" />
    </fragment>

    <fragment
        android:id="@+id/deeplink_dest"
        android:name="com.example.android.codelabs.navigation.DeepLinkFragment"
        android:label="@string/deeplink"
        tools:layout="@layout/deeplink_fragment">

        <argument
            android:name="myarg"
            app:argType="string" />

        <deepLink app:uri="example://my-deelink-frag?myArg={myarg}" />
    </fragment>
</navigation>

I have defined 2 ways to navigate to the DeepLinkFragment:

Navigation action with id action_home_dest_to_deeplink_dest

A deeplink example://my-deelink-frag?myArg={myarg}

In the DeepLinkFragment I'm using the navArgs() function to de-serialize the incoming Bundle and show a simple Toast message.

class DeepLinkFragment : Fragment() {

    private val args : DeepLinkFragmentArgs by navArgs()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Toast.makeText(requireContext(), args.myarg, Toast.LENGTH_SHORT).show()
    }
}

When navigating with the generated safe args I can sent an empty string as the value for myArg.
No problem.

findNavController().navigate(HomeFragmentDirections.actionHomeDestToDeeplinkDest(""))

However, when navigating with an empty string as argument via the deeplink way:

val arg = ""
findNavController().navigate("example://my-deelink-frag?myArg=${arg}".toUri())

I get following stacktrace:

 Caused by: java.lang.IllegalArgumentException: Required argument "myarg" is missing and does not have an android:defaultValue
    at com.example.android.codelabs.navigation.DeepLinkFragmentArgs$Companion.fromBundle(DeepLinkFragmentArgs.kt:29)
    at com.example.android.codelabs.navigation.DeepLinkFragmentArgs.fromBundle(Unknown Source:2)
    at java.lang.reflect.Method.invoke(Native Method)
    at androidx.navigation.NavArgsLazy.getValue(NavArgsLazy.kt:52)
    at androidx.navigation.NavArgsLazy.getValue(NavArgsLazy.kt:34)
    at com.example.android.codelabs.navigation.DeepLinkFragment.getArgs(DeepLinkFragment.kt:30)
    at com.example.android.codelabs.navigation.DeepLinkFragment.onViewCreated(DeepLinkFragment.kt:34)
    at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2987)
    at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:546)
    at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
    at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
    at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2106)
    at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
    at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:524)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:233)
    at android.app.ActivityThread.main(ActivityThread.java:8068)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:631)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:978)

Which is coming from the generated DeeplinkFragmentArgs code

public data class DeepLinkFragmentArgs(
  public val myarg: String = ""
) : NavArgs {
  public fun toBundle(): Bundle {
    val result = Bundle()
    result.putString("myarg", this.myarg)
    return result
  }

  public companion object {
    @JvmStatic
    public fun fromBundle(bundle: Bundle): DeepLinkFragmentArgs {
      bundle.setClassLoader(DeepLinkFragmentArgs::class.java.classLoader)
      val __myarg : String?
      if (bundle.containsKey("myarg")) {
        __myarg = bundle.getString("myarg")
        if (__myarg == null) {
          throw IllegalArgumentException("Argument \"myarg\" is marked as non-null but was passed a null value.")
        }
      } else {
        __myarg = ""
      }
      return DeepLinkFragmentArgs(__myarg)
    }
  }
}

Looking at the code it seems as if an empty string is making the bundle.getString("myarg") return null instead of the empty string?!

As a fix I could add the android:defaultValue.

However I don't think is the right solution.

<argument
    android:name="myarg"
    android:defaultValue=""
    app:argType="string" />

Is this a known limitation when using deeplinks?


问:
Android newbie - debugging app on physical device
I was trying to debug my code on a physical device instead of an emulator. In order to do this after a series of steps I finally plugged in my device only to see that "Samsung_Android" and "CDC serial" drivers are missing.

It seems very odd for these drivers to be missing. What am I doing wrong, any suggestions ?

Thanks in advance for your help.

答: You need to install the usb drivers for ADB. For samsung, you need to install kies, located here. Also, if you have problems there are some stack overflow related questions, like this one.</p>


答:
my $dt = Date.today.DateTime;

$dt.clone: formatter => { .yyyy-mm-dd ~ q{ } ~ .hh-mm-ss }\
andthen $_, *.later(:5minute) ... * eqv $dt.later(:1day)
andthen .rotor: 2 => -1
andthen .map: *.join(q{, }).put
```

Body:
How to generate a DateTime range by step of 5 minutes? The following is the output:

2022-02-13 00:00:00, 2022-02-13 00:05:00
2022-02-13 00:05:00, 2022-02-13 00:10:00
2022-02-13 00:10:00, 2022-02-13 00:15:00
2022-02-13 00:15:00, 2022-02-13 00:20:00
...
2022-02-13 23:45:00, 2022-02-13 23:50:00
2022-02-13 23:50:00, 2022-02-13 23:55:00
2022-02-13 23:55:00, 2022-02-14 00:00:00


问:
jQuery UI Autocomplete Formatting for Multiple Elements
I have the jQuery UI Autocomplete setup to my liking and working perfectly, but there is one fatal flaw.  In my autocomplete I use a custom display like this example.  I have something very similar built but with on exception...

The only difference is that I have multiple autocomplete elements of the same class on that one page.  Only the first element shows the extra data line, the rest only show the basic autocomplete.

I can get the desired result by just iterating all of those class elements and calling the autocomplete on them, but I was hoping there was a better way of calling it once and having it "just work".

Here's how I'm adding the extra line:

```<code>.data( 'autocomplete' )._renderItem = function( ul, item ) {
  return $( '<li></li>' )
  .data( 'item.autocomplete', item )
  .append( '<a>' + item.label + '<br/><small>' + item.desc + '<small></a>' )
  .appendTo( ul );
};
</code>```

I should note that I'm not getting any console exceptions at all.

答:
I had the same issue as sshefer and I got the best solution for it:

Change the ```.autocomplete( "instance" )._renderItem = function( ul, item )```
by

```<code>$( ".input_class" ).each(function(){
    $( this ).autocomplete( "instance" )._renderItem = function( ul, item )...
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have the jQuery UI Autocomplete setup to my liking and working perfectly, but there is one fatal flaw.  In my autocomplete I use a custom display like this example.  I have something very similar built but with on exception...

The only difference is that I have multiple autocomplete elements of the same class on that one page.  Only the first element shows the extra data line, the rest only show the basic autocomplete.

I can get the desired result by just iterating all of those class elements and calling the autocomplete on them, but I was hoping there was a better way of calling it once and having it "just work".

Here's how I'm adding the extra line:

.data( 'autocomplete' )._renderItem = function( ul, item ) {
  return $( '

' )
  .data( 'item.autocomplete', item )
  .append( '' + item.label + '
' + item.desc + '' )
  .appendTo( ul );
};

I should note that I'm not getting any console exceptions at all.

Body:
I had the same issue as sshefer and I got the best solution for it:

Change the
.autocomplete( "instance" )._renderItem = function( ul, item )

by

$( ".input_class" ).each(function(){
    $( this ).autocomplete( "instance" )._renderItem = function( ul, item )...
});


问:
Newest update (9 Feb 2022) by Samsung for the Galaxy Watch4 is crashing my watch face - what to do?
Yesterday Samsung published an update for the Galaxy Watch4. Since then I am being flooded by users' emails saying that my watch face is crashing and is unusable. The crash happens when the watch switches between normal and ambient mode.

According to some articles published today (https://www.xda-developers.com/galaxy-watch-4-update-breaking-watch-faces) the WatchFaceService.Engine is not supported any longer or broken in the new update.

What is confusing, is that while my watch face crashes, other watch faces simply don't get updated in ambient mode, because apparently onTimeTick() is not being called. But I still cannot figure out how to avoid the crash. The debug information only says "java.lang.RuntimeException: eglCreateWindowSurface failed", but does not point to any line in my code:

```<code>2022-02-11 11:21:55.612 4652-4652/com.xxxx.mywatchface E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.xxxx.mywatchface, PID: 4652
java.lang.RuntimeException: eglCreateWindowSurface failed
    at android.support.wearable.watchface.Gles2WatchFaceService$Engine.createWindowSurface(Gles2WatchFaceService.java:202)
    at android.support.wearable.watchface.Gles2WatchFaceService$Engine.onSurfaceChanged(Gles2WatchFaceService.java:300)
    at android.service.wallpaper.WallpaperService$Engine.updateSurface(WallpaperService.java:1082)
    at android.service.wallpaper.WallpaperService$Engine.reportVisibility(WallpaperService.java:1296)
    at android.service.wallpaper.WallpaperService$Engine$3.onDisplayChanged(WallpaperService.java:1439)
    at android.hardware.display.DisplayManagerGlobal$DisplayListenerDelegate.handleMessage(DisplayManagerGlobal.java:767)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:246)
    at android.app.ActivityThread.main(ActivityThread.java:7690)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:593)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)
</code>```

Does any body know more about this? Should WatchFaceService not longer be supported, what is the alternative to it?

答:
That's a broken release of a firmware update by Samsung.

I performed a few tests regarding this issue.

My conclusion is that they "blocked" on the firmware layer, the lock request of the CPU - now, a process that requests a CPU lock is ignored.

I am not familiar with the onTimeTick() method of the watch face API, but I guess it requests CPU lock to update the GUI.

According to the documentation, This is how a process claims a CPU lock, and now, after this update, those lines of code gets ignored:

Kotlin Code:

```<code>val pm = getSystemService(POWER_SERVICE) as PowerManager
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "awake")
wl.acquire(
    MainActivityModel.convertDegreesToMilliseconds(rotationValue)
        .toLong()
)
</code>```

Maybe you can find more information or an update about a hotfix here:

https://forum.developer.samsung.com/c/watch-face-studio/49

Body:
Yesterday Samsung published an update for the Galaxy Watch4. Since then I am being flooded by users' emails saying that my watch face is crashing and is unusable. The crash happens when the watch switches between normal and ambient mode.

According to some articles published today (https://www.xda-developers.com/galaxy-watch-4-update-breaking-watch-faces) the WatchFaceService.Engine is not supported any longer or broken in the new update.

What is confusing, is that while my watch face crashes, other watch faces simply don't get updated in ambient mode, because apparently onTimeTick() is not being called. But I still cannot figure out how to avoid the crash. The debug information only says "java.lang.RuntimeException: eglCreateWindowSurface failed", but does not point to any line in my code:

2022-02-11 11:21:55.612 4652-4652/com.xxxx.mywatchface E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.xxxx.mywatchface, PID: 4652
java.lang.RuntimeException: eglCreateWindowSurface failed
    at android.support.wearable.watchface.Gles2WatchFaceService$Engine.createWindowSurface(Gles2WatchFaceService.java:202)
    at android.support.wearable.watchface.Gles2WatchFaceService$Engine.onSurfaceChanged(Gles2WatchFaceService.java:300)
    at android.service.wallpaper.WallpaperService$Engine.updateSurface(WallpaperService.java:1082)
    at android.service.wallpaper.WallpaperService$Engine.reportVisibility(WallpaperService.java:1296)
    at android.service.wallpaper.WallpaperService$Engine$3.onDisplayChanged(WallpaperService.java:1439)
    at android.hardware.display.DisplayManagerGlobal$DisplayListenerDelegate.handleMessage(DisplayManagerGlobal.java:767)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:246)
    at android.app.ActivityThread.main(ActivityThread.java:7690)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:593)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)

Does any body know more about this? Should WatchFaceService not longer be supported, what is the alternative to it?

Body:
That's a broken release of a firmware update by Samsung.

I performed a few tests regarding this issue.

My conclusion is that they "blocked" on the firmware layer, the lock request of the CPU - now, a process that requests a CPU lock is ignored.

I am not familiar with the onTimeTick() method of the watch face API, but I guess it requests CPU lock to update the GUI.

According to the documentation, This is how a process claims a CPU lock, and now, after this update, those lines of code gets ignored:

Kotlin Code:

val pm = getSystemService(POWER_SERVICE) as PowerManager
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "awake")
wl.acquire(
    MainActivityModel.convertDegreesToMilliseconds(rotationValue)
        .toLong()
)

Maybe you can find more information or an update about a hotfix here:

https://forum.developer.samsung.com/c/watch-face-studio/49


问:
How to change truncate characters in UILabel?
When the text of a UILabel gets truncated there are 3 dots inserted by default.
Is it possible to change these characters or disable them?

答:
I would like to provide a more Swifty version of what Fonix provided earlier and using Swift 5 syntax.  Also I decided to write the functions as an extension of UILabel.

```<code>extension UILabel {
    func replaceEllipsis(withString replacement: String, andMaximumWidth width: CGFloat = 0) -> Bool {

        if let labelText = self.text, let font = self.font {
            let origSize = self.frame
            var useWidth = width

            if width <= 0 {
                useWidth = origSize.width // use label width by default if width <= 0
            }

            self.sizeToFit()
            let labelSize = labelText.size(withAttributes: [NSAttributedString.Key.font: font])

            if labelSize.width > useWidth {
                let truncateWidth = useWidth
                let subLength = labelText.count

                var newText = String(labelText[..<labelText.index(labelText.endIndex, offsetBy: -1)])
                newText = String(newText[..<newText.index(labelText.startIndex, offsetBy: getTruncatedStringPoint(splitPoint: subLength,
                                                                                original: labelText,
                                                                                truncatedWidth: truncateWidth,
                                                                                font: font,
                                                                                length: subLength))])
                newText = String.localizedStringWithFormat("%@%@", newText, replacement)
                var count = 0

                while newText.size(withAttributes: [NSAttributedString.Key.font: font]).width > useWidth {
                    count += 1
                    newText = String(labelText[..<labelText.index(labelText.endIndex, offsetBy: -(1 + count))])
                    newText = newText.trimmingCharacters(in: NSCharacterSet.whitespaces)
                    newText = String.localizedStringWithFormat("%@%@", newText, replacement)
                }
                self.text = newText
                self.frame = origSize
                return true
            } else {
                self.frame = origSize
                return false
            }
        } else {
            return false
        }
    }

    private func getTruncatedStringPoint(splitPoint: Int, original: String, truncatedWidth: CGFloat, font: UIFont, length: Int) -> Int {
        let index = original.index(original.startIndex, offsetBy: splitPoint)
        let splitLeft = String(original[..<index])

        let subLength = length / 2

        if subLength <= 0 {
            return splitPoint
        }

        let width = splitLeft.size(withAttributes: [NSAttributedString.Key.font: font]).width

        if width > truncatedWidth {
            return getTruncatedStringPoint(splitPoint: splitPoint - subLength, original: original, truncatedWidth: truncatedWidth, font: font, length: subLength)
        } else if width < truncatedWidth {
            return getTruncatedStringPoint(splitPoint: splitPoint + subLength, original: original, truncatedWidth: truncatedWidth, font: font, length: subLength)
        } else {
            return splitPoint
        }
    }
}
</code>```

It'll be used as follows:

```<code><UILabel>.replaceEllipsis(withString: " ...Read More") // if you want to use the label width
</code>```

Also you can pass a custom width as well if you need to.  I opted for the default width in the above example.

For references on what I used in my refactor, the below StackOverflow links were helpful:

Advanced by refactor

substringToIndex refactor

Body:
I would like to provide a more Swifty version of what Fonix provided earlier and using Swift 5 syntax.  Also I decided to write the functions as an extension of UILabel.

extension UILabel {
    func replaceEllipsis(withString replacement: String, andMaximumWidth width: CGFloat = 0) -> Bool {

        if let labelText = self.text, let font = self.font {
            let origSize = self.frame
            var useWidth = width

            if width <= 0 {
                useWidth = origSize.width // use label width by default if width <= 0
            }

            self.sizeToFit()
            let labelSize = labelText.size(withAttributes: [NSAttributedString.Key.font: font])

            if labelSize.width > useWidth {
                let truncateWidth = useWidth
                let subLength = labelText.count

                var newText = String(labelText[..<labelText.index(labelText.endIndex, offsetBy: -1)])
                newText = String(newText[..<newText.index(labelText.startIndex, offsetBy: getTruncatedStringPoint(splitPoint: subLength,
                                                                                original: labelText,
                                                                                truncatedWidth: truncateWidth,
                                                                                font: font,
                                                                                length: subLength))])
                newText = String.localizedStringWithFormat("%@%@", newText, replacement)
                var count = 0

                while newText.size(withAttributes: [NSAttributedString.Key.font: font]).width > useWidth {
                    count += 1
                    newText = String(labelText[..<labelText.index(labelText.endIndex, offsetBy: -(1 + count))])
                    newText = newText.trimmingCharacters(in: NSCharacterSet.whitespaces)
                    newText = String.localizedStringWithFormat("%@%@", newText, replacement)
                }
                self.text = newText
                self.frame = origSize
                return true
            } else {
                self.frame = origSize
                return false
            }
        } else {
            return false
        }
    }

    private func getTruncatedStringPoint(splitPoint: Int, original: String, truncatedWidth: CGFloat, font: UIFont, length: Int) -> Int {
        let index = original.index(original.startIndex, offsetBy: splitPoint)
        let splitLeft = String(original[..<index])

        let subLength = length / 2

        if subLength <= 0 {
            return splitPoint
        }

        let width = splitLeft.size(withAttributes: [NSAttributedString.Key.font: font]).width

        if width > truncatedWidth {
            return getTruncatedStringPoint(splitPoint: splitPoint - subLength, original: original, truncatedWidth: truncatedWidth, font: font, length: subLength)
        } else if width < truncatedWidth {
            return getTruncatedStringPoint(splitPoint: splitPoint + subLength, original: original, truncatedWidth: truncatedWidth, font: font, length: subLength)
        } else {
            return splitPoint
        }
    }
}

It'll be used as follows:

<UILabel>.replaceEllipsis(withString: " ...Read More") // if you want to use the label width

Also you can pass a custom width as well if you need to.  I opted for the default width in the above example.

For references on what I used in my refactor, the below StackOverflow links were helpful:

Advanced by refactor

substringToIndex refactor


答:
Use substr...</p>

```<code>if (substr($usr_ip, 0, 2) == "41") {
    die('Access denied');
}
</code>```

Title: check if first two letter (digits) in a ip adress is '41' with PHP?

Body:
Use substr...

if (substr($usr_ip, 0, 2) == "41") {
    die('Access denied');
}


问:
Should I reduce not required columns in DFs before join them in Spark?
Is there any sense to reduce not required columns before I join it in Spark data frames?
For example:
DF1 has 10 columns, DF2 has 15 columns, DF3 has 25 columns.
I want to join them, select needed 10 columns and save it in .parquet.

Does it make sense to transform DFs with select only needed columns before the join or Spark engine will optimize the join by itself and will not operate with all 50 columns during the join operation?

答:
Yes, it makes a perfect sense because it reduce the amount of data shuffled between executors. And it's better to make selection of only necessary columns as early as possible - in most cases, if file format allows (Parquet, Delta Lake), Spark will read data only for necessary columns, not for all columns. I.e.:

df1 = spark.read.parquet("file1") \
  .select("col1", "col2", "col3")
df2 = spark.read.parquet("file2") \
  .select("col1", "col5", "col6")
joined = df1.join(df2, "col1")
```


Title: Numpy log2 returning NaN for small values

Body:
I've the following data frame with all positive values

    V1          V2          V3      V4          V5
0  F1H5N4S2  10.751263  0.216574  0.703209  10.674107
1    F2H4N7  12.131079  0.000004  1.883824   0.018118
2     H12N2  11.075072  0.214872  0.000004  10.674107
3      H3N7   1.091061  0.000004  3.503290   0.091797
4    F2H4N5   0.590545  0.000004  1.730215   0.223571

When I'm trying to convert the numerical values to log2 using the following syntax in numpy(np)

log2df = df.apply(lambda x: np.log2(x) if np.issubdtype(x.dtype, np.float) else x)

I'm getting the following data frame with NaNs in place of log2(0.000004). 0.000004 happens to be the smallest value in the dataframe which I imputed.
Can anyone help me solve the problem?
Thanks

    V1          V2          V3      V4          V5
0  F1H5N4S2  3.426434 -2.207070 -0.507974  3.416043
1    F2H4N7  3.600636       NaN  0.913664 -5.786433
2     H12N2  3.469244 -2.218451       NaN  3.416043
3      H3N7  0.125732       NaN  1.808710 -3.445414
4    F2H4N5 -0.759880       NaN  0.790951 -2.161198

Body:
This works fine for me, but avoid using apply. Select the numeric type and apply a vectorial operation:

cols = df.select_dtypes('number').columns

df[cols] = np.log2(df[cols])

output:

         V1        V2         V3         V4        V5
0  F1H5N4S2  3.426434  -2.207068  -0.507975  3.416043
1    F2H4N7  3.600636 -17.931569   0.913664 -5.786432
2     H12N2  3.469244  -2.218451 -17.931569  3.416043
3      H3N7  0.125732 -17.931569   1.808710 -3.445409
4    F2H4N5 -0.759881 -17.931569   0.790951 -2.161195


问:
Compile-time ceiling function, for literals, in C?
I have a C program which involves some floating-point literal that's defined by a macro. And - it just so happens that in a performance-critical part of the code, I need the ceiling of that floating-point number, as an integer (say, an int). Now, if it were an actual literal, then I would just manually take the ceiling and be done with it. But since it's a macro, I can't do that.

Naturally, ceilf(MY_DOUBLE_LITERAL) works, but - it's expensive. (int)(MY_DOUBLE_LITERAL) + 1 will also work... except if the literal is itself an integer, in which case it will be wrong.

So, is there some way - preprocessor macros are fine - to obtain the ceiling of MY_DOUBLE_LITERAL, or alternatively to determine whether it is an integer or not?

Notes:

I cannot perform the ceil() before the performance-critical part of the code, due to constraints I won't go into. Naturally if one can move computation outside of the performance-critical part or loop, that's always best, and thanks goes to @SpyrosK for mentioning that.

C99 preferred.

You may assume the literal is a double, i.e. a decimal number like 123.4 or an exponential-notation like 1.23e4.

答:
If your literal fits nicely within the int representation range, you will often be able to rely on compiler optimizations. clang and gcc, for example, will go as far as simply optimizing ceilf() away when it's provided a literal, so ceifl(MY_DOUBLE_LITERAL) will result in a literal being used and no time wasted at run-time.

If somehow that doesn't work with your compiler, you could use:

```<code>int poor_mans_ceil(double x)
{
    return (int) x + ( ((double)(int) x < x) ? 1 : 0);
}
</code>```

which should be "easier" for a compiler to optimize. You can see this happening on GodBolt.

Having said that - Some compilers in more exotic setting might fail to optimize both ceil() and the function above. Example: NVIDIA's NVCC compiler for CUDA.

Body:
If your literal fits nicely within the int representation range, you will often be able to rely on compiler optimizations. clang and gcc, for example, will go as far as simply optimizing ceilf() away when it's provided a literal, so ceifl(MY_DOUBLE_LITERAL) will result in a literal being used and no time wasted at run-time.

If somehow that doesn't work with your compiler, you could use:

int poor_mans_ceil(double x)
{
    return (int) x + ( ((double)(int) x < x) ? 1 : 0);
}

which should be "easier" for a compiler to optimize. You can see this happening on GodBolt.

Having said that - Some compilers in more exotic setting might fail to optimize both ceil() and the function above. Example: NVIDIA's NVCC compiler for CUDA.


问:
Not able to find the ip address
I am trying to find the static ip address of google.com in cmd prompt with the use of ping command as ping google.com. Instead of showing me the ip address of google, it is giving the following output. Not able to find the google ip address. So, instead of showing the ip address for google.com it is providing 2404:6800:4009:82b::200e. Not able to figure out how to find the ip address. Please help

答:
This is the IPv6, if you want the IPv4 you need to run</p>
```<code>ping google.com -4
</code>```

Title: Not able to find the ip address

Body:
This is the IPv6, if you want the IPv4 you need to run

ping google.com -4


问:
How to open a vagrant file in notepad on windows
This will download a “Vagrant” file, which you need to open with notepad
and add the following line: “config.VM.provision: reload“. It should
resemble the following when completed:enter code here

```<code>         Vagrant.configure("2") do |config|
         config.vm.provision :reload
          config.vm.synced_folder
</code>```

I am so confused on the open with notepad part help!!!!

答:
You don't need to open notepad, you can just use PowerShell to add the text. If you have the file on disk something like this should work:</p>
```<code>$StringToAdd = 'config.VM.provision: reload'
$VagrantFilePath = 'C:\path\Vagrantfile'
$StringToAdd | Add-Content $VagrantFilePath
</code>```

Body:
This will download a “Vagrant” file, which you need to open with notepad
and add the following line: “config.VM.provision: reload“. It should
resemble the following when completed:enter code here

         Vagrant.configure("2") do |config|
         config.vm.provision :reload
          config.vm.synced_folder

I am so confused on the open with notepad part help!!!!

Body:
You don't need to open notepad, you can just use PowerShell to add the text. If you have the file on disk something like this should work:

$StringToAdd = 'config.VM.provision: reload'
$VagrantFilePath = 'C:\path\Vagrantfile'
$StringToAdd | Add-Content $VagrantFilePath


问:
Whenever I try to write code in JavaFX I always get the same error. What am I doing wrong?
Code:

```<code>package learning;

import javafx.application.Application;
import javafx.stage.Stage;

public class One extends Application {

    public static void main (String[] args){
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {

    }
}
</code>```

Error:

```<code>Exception in Application constructor Exception in thread "main"
java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:568)
        at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1071)
Caused by: java.lang.RuntimeException: Unable to construct Application
instance: class learning.One
        at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:893)
        at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:198)
        at java.base/java.lang.Thread.run(Thread.java:833) Caused by:
java.lang.IllegalAccessException: class com.sun.javafx.application.LauncherImpl (in module javafx.graphics) cannot access class learning.One (in module com.example.hoho) because module com.example.hoho does not export learning to module javafx.graphics
        at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:392)
        at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:674)
        at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:489)
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
        at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:805)
        at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:474)
        at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:447)
        at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
        at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:446)
        at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
        at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native
Method)
        at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
        ... 1 more
</code>```

I've downloaded JavaFX and have put it into my project structure already, and since I'm working in Intellij all the example classes that I get when I first open a new project work. However, whenever I try to write my own code this error always comes up. Any help please?

答:
The crucial part is here:

```<code>class com.sun.javafx.application.LauncherImpl (in module javafx.graphics)
cannot access class learning.One (in module com.example.hoho) because
module com.example.hoho does not export learning to module javafx.graphics
</code>```

You will have to add that to your module-info.java.

Body:
Code:

package learning;

import javafx.application.Application;
import javafx.stage.Stage;

public class One extends Application {

    public static void main (String[] args){
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {

    }
}

Error:

Exception in Application constructor Exception in thread "main"
java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:568)
        at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1071)
Caused by: java.lang.RuntimeException: Unable to construct Application
instance: class learning.One
        at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:893)
        at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:198)
        at java.base/java.lang.Thread.run(Thread.java:833) Caused by:
java.lang.IllegalAccessException: class com.sun.javafx.application.LauncherImpl (in module javafx.graphics) cannot access class learning.One (in module com.example.hoho) because module com.example.hoho does not export learning to module javafx.graphics
        at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:392)
        at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:674)
        at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:489)
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
        at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:805)
        at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:474)
        at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:447)
        at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
        at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:446)
        at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
        at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native
Method)
        at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
        ... 1 more

I've downloaded JavaFX and have put it into my project structure already, and since I'm working in Intellij all the example classes that I get when I first open a new project work. However, whenever I try to write my own code this error always comes up. Any help please?

Body:
The crucial part is here:

class com.sun.javafx.application.LauncherImpl (in module javafx.graphics)
cannot access class learning.One (in module com.example.hoho) because
module com.example.hoho does not export learning to module javafx.graphics

You will have to add that to your module-info.java.


问:
what would be the best practice for http request in webapi project with softdelete
I am working on a webapi .Net5 project. I am using SQLserver and EF5 to store my entities. Each of my entities has a property called IsDeleted, which I use for remove(IsDeleted=true) and restore(IsDeleted=false).

I am a bit confused which http request method should I use for my remove/restore endpoints.

I am updating a partial part of my entity (isdeleted), so I was thinking about PATCH

I also don't want to show the client that I am doing soft delete, then for remove, I was thinking about DELETE but I really do not delete any entity from my resources

I was also thinking about PUT, but in both cases, I do not have any request body and therefore it is very rare that a PUT method has not have any body .

I saw in some StackOverflow question and answers that they recommend to use a POST method for restore and DELETE for remove when using the soft delete but did not really understand why.

Anybody knows what would be the correct way of doing that and why?

答:
Using HTTP DELETE to update IsDeleted = true is up to you as the API designer. There's no law saying HTTP DELETE must hard-delete whatever it refers to.

If the client does not know you're soft-deleting the record it'd be entirely appropriate to use DELETE.

I work with a system which has soft-delete, but it is not hidden from the client app / user. So to soft-delete it is either a PUT request to api/some_endpoint/24601 with "status": "ARCHIVED" within the payload, or a POST request to api/some_endpoint/24601/actions with a similar payload. (PATCH may be more appropriate than PUT but the API designers have stuck with PUT throughout.)


问:
Rolling or sliding window iterator?
I need a rolling window (aka sliding window) iterable over a sequence/iterator/generator.  (Default Python iteration could be considered a special case, where the window length is 1.)  I'm currently using the following code. How can I do it more elegantly and/or efficiently?

```<code>def rolling_window(seq, window_size):
    it = iter(seq)
    win = [it.next() for cnt in xrange(window_size)] # First window
    yield win
    for e in it: # Subsequent windows
        win[:-1] = win[1:]
        win[-1] = e
        yield win

if __name__=="__main__":
    for w in rolling_window(xrange(6), 3):
        print w

"""Example output:
   [0, 1, 2]
   [1, 2, 3]
   [2, 3, 4]
   [3, 4, 5]
"""
</code>```

For the specific case of window_size == 2 (i.e., iterating over adjacent, overlapping pairs in a sequence), see also How can I iterate over overlapping (current, next) pairs of values from a list?.

答:
The toolz/cytoolz package has a sliding_window function.</p>
```<code>>>> from cytoolz import sliding_window
>>> list(sliding_window(3, range(6))) # returns [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)]
</code>```

Title: Rolling or sliding window iterator?

Body:
I need a rolling window (aka sliding window) iterable over a sequence/iterator/generator.  (Default Python iteration could be considered a special case, where the window length is 1.)  I'm currently using the following code. How can I do it more elegantly and/or efficiently?

def rolling_window(seq, window_size):
    it = iter(seq)
    win = [it.next() for cnt in xrange(window_size)] # First window
    yield win
    for e in it: # Subsequent windows
        win[:-1] = win[1:]
        win[-1] = e
        yield win

if __name__=="__main__":
    for w in rolling_window(xrange(6), 3):
        print w

"""Example output:
   [0, 1, 2]
   [1, 2, 3]
   [2, 3, 4]
   [3, 4, 5]
"""

For the specific case of window_size == 2 (i.e., iterating over adjacent, overlapping pairs in a sequence), see also How can I iterate over overlapping (current, next) pairs of values from a list?.

Body:
The toolz/cytoolz package has a sliding_window function.

>>> from cytoolz import sliding_window
>>> list(sliding_window(3, range(6))) # returns [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)]


问:
Twitter API request failing when created different ways
I am trying to get to learn programing by replicating the code from a tutorial on the web.

I am puzzled as to why the sending request command in line 21 works and the sending command in line 74 does not work, when is using the same parameters, endpoint and headers.

i’ve tried many options but none of them seem to work, I’ve spent many hours and I am going a bit crazy.

##Update11#####
i’ve commented lines where the start_time and end_time attributes get added, and it seems to work, however I need to set the start time and end time.

Once I commented out the two lines listed below it seems to work, however, I need to stop it in case it uses my entire month allowance.

```<code>params['start_time'] = pre60

params['end_time'] = now
</code>```

Any idea why adding the start_time and end_time to the parameters is not working?

####Update 2######
If I put a debug point in the response command withing the while loop it intermetinly works. Why would adding the break point would make it work some times?

I also added a sleep line before the response, but that doesn’t work.

Any help would be much appreciated.

Many thanks.

```<code>from datetime import datetime, timedelta
import requests
import pandas as pd
import re
#from main import get_data,jprint

# Twitter API configuration parameters

# setup the API request
endpoint = 'https://api.twitter.com/2/tweets/search/recent'
params = {'max_results': '1',
          'query':  '(tesla OR tsla OR elon musk) (lang:en)',
          'tweet.fields':'created_at,lang'
          }
token = ‘asdjklsfdClkjwe23….example'
headers = {'Authorization': "Bearer {}".format(token)}

#Line 20## WHY THIS ONE WORKS? Line 20
response = requests.get(endpoint, headers=headers, params=params)  # send the request
print(response.status_code)  # this one returns 200

dtformat = '%Y-%m-%dT%H:%M:%SZ'  # the date format string required by twitter

def get_data(tweet):
    clean_up_tweet(tweet['text'])
    data = {
        'id': tweet['id'],
        'created_at': tweet['created_at'],
        'text': tweet['text']
    }
    return data

def clean_up_tweet(tweet):
    # Cleanup text from tweets
    whitespace = re.compile(r"\s+")
    web_address = re.compile(r"(?i)http(s):\/\/[a-z0-9.~_\-\/]+")
    tesla = re.compile(r"(?i)@Tesla(?=\b)")
    user = re.compile(r"(?i)@[a-z0-9_]+")

    # we then use the sub method to replace anything matching
    tweet = whitespace.sub(' ', tweet)
    tweet = web_address.sub('', tweet)
    tweet = tesla.sub('Tesla', tweet)
    tweet = user.sub('', tweet)

# we use this function to subtract 60 mins from our datetime string
def time_travel(now, mins):
    now = datetime.strptime(now, dtformat)
    back_in_time = now - timedelta(minutes=mins)
    return back_in_time.strftime(dtformat)

now = datetime.now()  # get the current datetime, this is our starting point
last_week = now - timedelta(days=7)  # datetime one week ago = the finish line
now = now.strftime(dtformat)  # convert now datetime to format for API

df = pd.DataFrame()  # initialize dataframe to store tweets

while True:
    if datetime.strptime(now, dtformat) < last_week:
        # if we have reached 7 days ago, break the loop
        break
    pre60 = time_travel(now, 60)  # get 60 minutes before 'now'
    # assign from and to datetime parameters for the API
    params['start_time'] = pre60
    params['end_time'] = now

    #Line 73##WHY THIS ONE DOES NOT WORK?
    response = requests.get(endpoint, headers=headers, params=params) # send the request
    print(response.status_code) #this one returns 400
    now = pre60  # move the window 60 minutes earlier
    # iteratively append our tweet data to our dataframe

    for tweet in response.json()['data']:
        row = get_data(tweet)  # we defined this function earlier
        df = df.append(row, ignore_index=True)
</code>```

答:
Not sure if this would help you directly, but try using a library instead of direct twitter API's as this would ease complications on your part.

One such library for python is tweepy: https://docs.tweepy.org/en/stable/api.html

Also if you want to extract large number of tweets, then you won't get entire result in one single response. You will have to follow cursor method.

Attached is sample code for the same

```<code>import tweepy
auth = tweepy.OAuth2BearerHandler("YourKey")
api = tweepy.API(auth)
user = api.get_user(screen_name="UserYouWantToUse", include_entities=False)

tweets_df = pd.DataFrame(
    columns=['id', 'text', 'retweet_count', 'favorite_count', 'created_at'])

start_date_tweet = datetime.datetime.now() # this should newer date
end_date_tweet = datetime.datetime(2019, 1, 1)  # this should be older date
twitter_date_format = '%a %b %d %X %z %Y'

def addTweetsInDataFrame(max_id = -1):
    if (max_id == -1):   # This is the first API call, max_id is not required
        tweet_timeline = api.user_timeline(
            user_id=user.id, count=200, exclude_replies=True, trim_user=True, include_rts=False)
    else:   # Cursoring starts, need to pass max_id parameter as well
        tweet_timeline = api.user_timeline(
            user_id=user.id, count=200, exclude_replies=True, trim_user=True, include_rts=False, max_id = max_id)

    max_id_track = math.inf

    for tweet in tweet_timeline:

        tweet_date = datetime.datetime.strptime(tweet._json['created_at'], twitter_date_format)
        tweet_date = tweet_date.replace(tzinfo=None)    # to remove timezone from datetime object

        if (tweet_date > start_date_tweet): # This tweet is newer than required start date
            continue

        if (tweet_date < end_date_tweet):  # crossed the older date limit, all other post would be older than this date
            return

        tweet_dict = dict()
        tweet_dict['id'] = tweet._json['id']
        tweet_dict['text'] = tweet._json['text']
        tweet_dict['retweet_count'] = tweet._json['retweet_count']
        tweet_dict['favorite_count'] = tweet._json['favorite_count']
        tweet_dict['created_at'] = tweet_date

        tweets_df.loc[len(tweets_df.index)] = tweet_dict

        max_id_track = min(max_id_track, tweet._json['id'])

    if (max_id_track != math.inf):  # Cursor is available for next set of data
        time.sleep(2)               # To avoid hitting API limit
        addTweetsInDataFrame(max_id_track-1)

addTweetsInDataFrame()
tweets_df.to_excel("tweets_df.xlsx", index=False) # Saving in excel file
</code>```

Body:
I am trying to get to learn programing by replicating the code from a tutorial on the web.

I am puzzled as to why the sending request command in line 21 works and the sending command in line 74 does not work, when is using the same parameters, endpoint and headers.

i’ve tried many options but none of them seem to work, I’ve spent many hours and I am going a bit crazy.

##Update11#####
i’ve commented lines where the start_time and end_time attributes get added, and it seems to work, however I need to set the start time and end time.

Once I commented out the two lines listed below it seems to work, however, I need to stop it in case it uses my entire month allowance.

params['start_time'] = pre60

params['end_time'] = now

Any idea why adding the start_time and end_time to the parameters is not working?

####Update 2######
If I put a debug point in the response command withing the while loop it intermetinly works. Why would adding the break point would make it work some times?

I also added a sleep line before the response, but that doesn’t work.

Any help would be much appreciated.

Many thanks.

from datetime import datetime, timedelta
import requests
import pandas as pd
import re
#from main import get_data,jprint

# Twitter API configuration parameters

# setup the API request
endpoint = 'https://api.twitter.com/2/tweets/search/recent'
params = {'max_results': '1',
          'query':  '(tesla OR tsla OR elon musk) (lang:en)',
          'tweet.fields':'created_at,lang'
          }
token = ‘asdjklsfdClkjwe23….example'
headers = {'Authorization': "Bearer {}".format(token)}

#Line 20## WHY THIS ONE WORKS? Line 20
response = requests.get(endpoint, headers=headers, params=params)  # send the request
print(response.status_code)  # this one returns 200

dtformat = '%Y-%m-%dT%H:%M:%SZ'  # the date format string required by twitter

def get_data(tweet):
    clean_up_tweet(tweet['text'])
    data = {
        'id': tweet['id'],
        'created_at': tweet['created_at'],
        'text': tweet['text']
    }
    return data

def clean_up_tweet(tweet):
    # Cleanup text from tweets
    whitespace = re.compile(r"\s+")
    web_address = re.compile(r"(?i)http(s):\/\/[a-z0-9.~_\-\/]+")
    tesla = re.compile(r"(?i)@Tesla(?=\b)")
    user = re.compile(r"(?i)@[a-z0-9_]+")

    # we then use the sub method to replace anything matching
    tweet = whitespace.sub(' ', tweet)
    tweet = web_address.sub('', tweet)
    tweet = tesla.sub('Tesla', tweet)
    tweet = user.sub('', tweet)

# we use this function to subtract 60 mins from our datetime string
def time_travel(now, mins):
    now = datetime.strptime(now, dtformat)
    back_in_time = now - timedelta(minutes=mins)
    return back_in_time.strftime(dtformat)

now = datetime.now()  # get the current datetime, this is our starting point
last_week = now - timedelta(days=7)  # datetime one week ago = the finish line
now = now.strftime(dtformat)  # convert now datetime to format for API

df = pd.DataFrame()  # initialize dataframe to store tweets

while True:
    if datetime.strptime(now, dtformat) < last_week:
        # if we have reached 7 days ago, break the loop
        break
    pre60 = time_travel(now, 60)  # get 60 minutes before 'now'
    # assign from and to datetime parameters for the API
    params['start_time'] = pre60
    params['end_time'] = now

    #Line 73##WHY THIS ONE DOES NOT WORK?
    response = requests.get(endpoint, headers=headers, params=params) # send the request
    print(response.status_code) #this one returns 400
    now = pre60  # move the window 60 minutes earlier
    # iteratively append our tweet data to our dataframe

    for tweet in response.json()['data']:
        row = get_data(tweet)  # we defined this function earlier
        df = df.append(row, ignore_index=True)

Body:
Not sure if this would help you directly, but try using a library instead of direct twitter API's as this would ease complications on your part.

One such library for python is tweepy: https://docs.tweepy.org/en/stable/api.html

Also if you want to extract large number of tweets, then you won't get entire result in one single response. You will have to follow cursor method.

Attached is sample code for the same

import tweepy
auth = tweepy.OAuth2BearerHandler("YourKey")
api = tweepy.API(auth)
user = api.get_user(screen_name="UserYouWantToUse", include_entities=False)

tweets_df = pd.DataFrame(
    columns=['id', 'text', 'retweet_count', 'favorite_count', 'created_at'])

start_date_tweet = datetime.datetime.now() # this should newer date
end_date_tweet = datetime.datetime(2019, 1, 1)  # this should be older date
twitter_date_format = '%a %b %d %X %z %Y'

def addTweetsInDataFrame(max_id = -1):
    if (max_id == -1):   # This is the first API call, max_id is not required
        tweet_timeline = api.user_timeline(
            user_id=user.id, count=200, exclude_replies=True, trim_user=True, include_rts=False)
    else:   # Cursoring starts, need to pass max_id parameter as well
        tweet_timeline = api.user_timeline(
            user_id=user.id, count=200, exclude_replies=True, trim_user=True, include_rts=False, max_id = max_id)

    max_id_track = math.inf

    for tweet in tweet_timeline:

        tweet_date = datetime.datetime.strptime(tweet._json['created_at'], twitter_date_format)
        tweet_date = tweet_date.replace(tzinfo=None)    # to remove timezone from datetime object

        if (tweet_date > start_date_tweet): # This tweet is newer than required start date
            continue

        if (tweet_date < end_date_tweet):  # crossed the older date limit, all other post would be older than this date
            return

        tweet_dict = dict()
        tweet_dict['id'] = tweet._json['id']
        tweet_dict['text'] = tweet._json['text']
        tweet_dict['retweet_count'] = tweet._json['retweet_count']
        tweet_dict['favorite_count'] = tweet._json['favorite_count']
        tweet_dict['created_at'] = tweet_date

        tweets_df.loc[len(tweets_df.index)] = tweet_dict

        max_id_track = min(max_id_track, tweet._json['id'])

    if (max_id_track != math.inf):  # Cursor is available for next set of data
        time.sleep(2)               # To avoid hitting API limit
        addTweetsInDataFrame(max_id_track-1)

addTweetsInDataFrame()
tweets_df.to_excel("tweets_df.xlsx", index=False) # Saving in excel file


问:
Inheriting from JavaScript function in C++
I have a following JavaScript base function:

```<code>function Animal { }

Animal.prototype.move = function () {
  //...
}
</code>```

I have also a derived JavaScript function like this:

```<code>function Dog {
  Dog.super_.call(this);
}

util.inherits(Dog, Animal);

Dog.prototype.bark = function () {
  // ...
}
</code>```

Now I would like to create a C++ addon which is exactly the same as the derived
Dog JavaScript function:

```<code>void Dog::Init(Handle<Object> exports, Handle<Object> module) {
  Isolate* isolate = Isolate::GetCurrent();

  Local<Function> require = Local<Function>::Cast(module->Get(
    String::NewFromUtf8(isolate, "require")));

  Local<Value> args[] = {
    String::NewFromUtf8(isolate, "./animal")
  };

  Local<Value> animalModule = require->Call(module, 1, args);

  Local<Function> animalFunc = Local<Function>::Cast(animalModule);

  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
  // tpl->Inherit(animalFunc); // <-- HERE
  tpl->SetClassName(String::NewFromUtf8(isolate, "Dog"));
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  NODE_SET_PROTOTYPE_METHOD(tpl, "bark", Bark);

  constructor.Reset(isolate, tpl->GetFunction());
  exports->Set(String::NewFromUtf8(isolate, "Dog"),
    tpl->GetFunction());
}
</code>```

How can I get a FunctionTemplate from animalFunc / animalModule to be able to inherit from it in tpl function template? Or maybe I should somehow assign animalFunc.prototype to tpl.prototype?

答:
Alas, you can't.

Check this discussion: https://github.com/nodejs/node-addon-api/issues/229

It is the main reason why there is no standard way of inheriting JS classes in C++.

Body:
I have a following JavaScript base function:

function Animal { }

Animal.prototype.move = function () {
  //...
}

I have also a derived JavaScript function like this:

function Dog {
  Dog.super_.call(this);
}

util.inherits(Dog, Animal);

Dog.prototype.bark = function () {
  // ...
}

Now I would like to create a C++ addon which is exactly the same as the derived
Dog JavaScript function:

void Dog::Init(Handle<Object> exports, Handle<Object> module) {
  Isolate* isolate = Isolate::GetCurrent();

  Local<Function> require = Local<Function>::Cast(module->Get(
    String::NewFromUtf8(isolate, "require")));

  Local<Value> args[] = {
    String::NewFromUtf8(isolate, "./animal")
  };

  Local<Value> animalModule = require->Call(module, 1, args);

  Local<Function> animalFunc = Local<Function>::Cast(animalModule);

  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
  // tpl->Inherit(animalFunc); // <-- HERE
  tpl->SetClassName(String::NewFromUtf8(isolate, "Dog"));
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  NODE_SET_PROTOTYPE_METHOD(tpl, "bark", Bark);

  constructor.Reset(isolate, tpl->GetFunction());
  exports->Set(String::NewFromUtf8(isolate, "Dog"),
    tpl->GetFunction());
}

How can I get a FunctionTemplate from animalFunc / animalModule to be able to inherit from it in tpl function template? Or maybe I should somehow assign animalFunc.prototype to tpl.prototype?


问:
How can I use Coalesce with Group_Concat to not return anything vs Empty '' or NULL?
I need to use coalesce other wise I get NULL output if any of the gathered records doesn't have a value in it. Yet when I use Coalesce with (Value, NULL) I end up with results like

```<code>A|B|NULL|D
</code>```

likewise (Value, '')

```<code>A|B|''|D
</code>```

when I am looking for

```<code>A|B|D
</code>```

So how can I tell Mysql 'If some records don't have values till populate the ones that do, and only those ones, with the separator of my choice'?

答:
I'm not sure what your data are but, why don't you try CONCAT_WS with GROUP_CONCAT like:

```<code>select id,group_concat(my_column separator '|')
from (select id, concat_ws('|',col1,col2,col3,col4) as my_column
      from test_tbl
      ) as t1
group by id ;
</code>```

Data examples:

```<code>CREATE TABLE test_tbl(
id int,
col1 varchar(30) ,
col2 varchar(30),
col3 varchar(30),
col4 varchar(30));

insert into test_tbl values
(1,'A','B',NULL,'D'),
(1,'A','B',NULL,'D'),
(2,'A','B','D','C');
</code>```

Result:

```<code>id    group_concat(my_column separator '|')
1    A|B|D|A|B|D
2    A|B|D|C
</code>```

Demo

Body:
I need to use coalesce other wise I get NULL output if any of the gathered records doesn't have a value in it. Yet when I use Coalesce with (Value, NULL) I end up with results like

A|B|NULL|D

likewise (Value, '')

A|B|''|D

when I am looking for

A|B|D

So how can I tell Mysql 'If some records don't have values till populate the ones that do, and only those ones, with the separator of my choice'?

Body:
I'm not sure what your data are but, why don't you try CONCAT_WS with GROUP_CONCAT like:

select id,group_concat(my_column separator '|')
from (select id, concat_ws('|',col1,col2,col3,col4) as my_column
      from test_tbl
      ) as t1
group by id ;

Data examples:

CREATE TABLE test_tbl(
id int,
col1 varchar(30) ,
col2 varchar(30),
col3 varchar(30),
col4 varchar(30));

insert into test_tbl values
(1,'A','B',NULL,'D'),
(1,'A','B',NULL,'D'),
(2,'A','B','D','C');

Result:

id    group_concat(my_column separator '|')
1    A|B|D|A|B|D
2    A|B|D|C

Demo


问:
redirecting to thankyou.aspx page after survey
I am trying to direct after user click on "Finish" on a sharepoint survey. But the following code executes when user click on "Respond to this survey". Any idea what is happening.</p>

```<code><script type="text/javascript">
function redirect()
{
  var inputcCtrls = document.getElementsByTagName("input");
  for(var m=0; m<inputcCtrls.length; m++)
   if(inputcCtrls[m].type=='button'&&inputcCtrls[m].value=='Finish')
     var funcOnClick = inputcCtrls[m].onclick;
         inputcCtrls[m].onclick = window.location = "http://www.google.com/";
}
redirect();
</script>
</code>```

答:
Edit thanks to graham's answer.
Change:

```<code>for(var m=0; m<inputcCtrls.length; m++)
   if(inputcCtrls[m].type=='button'&&inputcCtrls[m].value=='Finish')
     var funcOnClick = inputcCtrls[m].onclick;
         inputcCtrls[m].onclick = window.location = "http://www.google.com/";
</code>```

to

```<code>for(var m=0; m<inputcCtrls.length; m++) {
   if(inputcCtrls[m].type=='button'&&inputcCtrls[m].value=='Finish') {
      var funcOnClick = inputcCtrls[m].onclick;

       inputcCtrls[m].onclick = function () { window.location = "http://www.google.com/" };
   }
}
</code>```

onclick wants a function. This is why I always use parathesis no matter if it's one line or not.

Body:
Edit thanks to graham's answer.
Change:

for(var m=0; m<inputcCtrls.length; m++)
   if(inputcCtrls[m].type=='button'&&inputcCtrls[m].value=='Finish')
     var funcOnClick = inputcCtrls[m].onclick;
         inputcCtrls[m].onclick = window.location = "http://www.google.com/";

to

for(var m=0; m<inputcCtrls.length; m++) {
   if(inputcCtrls[m].type=='button'&&inputcCtrls[m].value=='Finish') {
      var funcOnClick = inputcCtrls[m].onclick;

       inputcCtrls[m].onclick = function () { window.location = "http://www.google.com/" };
   }
}

onclick wants a function. This is why I always use parathesis no matter if it's one line or not.