问:
React Router V6 - Redirect inside Route Component
I have the following code from the V5 Documentation:

```<code>    <Route exact path="/">
      {loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
    </Route>
</code>```

I know that I have Navigate instead of Redirect in V6, but Navigate seems not to work the exact same way:

```<code>    <Route></Route>
      {loggedIn ? <Navigate to="/dashboard" /> : <PublicHomePage />}
    </Route>

Uncaught Error: [Navigate] is not a <Route> component.
</code>```

How can I archieve this with React Router V6?

答:
Try

```<code> <Route path="/" element={ <Navigate to="/dashboard" /> } />
</code>```

Because Route return the element for a path, so for the path '/', return Navigate for redirect

Body:
I have the following code from the V5 Documentation:

    <Route exact path="/">
      {loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
    </Route>

I know that I have Navigate instead of Redirect in V6, but Navigate seems not to work the exact same way:

    <Route></Route>
      {loggedIn ? <Navigate to="/dashboard" /> : <PublicHomePage />}
    </Route>

Uncaught Error: [Navigate] is not a <Route> component.

How can I archieve this with React Router V6?

Body:
Try

 <Route path="/" element={ <Navigate to="/dashboard" /> } />

Because Route return the element for a path, so for the path '/', return Navigate for redirect


来源: stackexchange

问:
Is there a way to disable Click options from prompting via a global flag?
I'm using click to implement a command-line interface in Python. Click has a feature that can prompt for a value if one isn't specified. Like so:

@click.command()
@click.option('--name', prompt=True)
def hello(name):
    click.echo(f"Hello {name}!")
```

This is great when a CLI is being used interactively, but prompting during a non-interactive run is bad (can hang a shell script, for example). I'd like to add a -q flag that would globally disable prompting for every other option.

Is there a straightforward way to do this?

答:
If a -q flag is not a hard requirement, and the goal is to basically override the prompting behavior for automation purposes, a typical solution is to get the option values from environment variables. I think this is a much simpler solution than my other answer which does implement the -q flag.

https://click.palletsprojects.com/en/8.0.x/options/#values-from-environment-variables

A very useful feature of Click is the ability to accept parameters from environment variables in addition to regular parameters. This allows tools to be automated much easier. For instance, you might want to pass a configuration file with a --config parameter but also support exporting a TOOL_CONFIG=hello.cfg key-value pair for a nicer development experience.

...

To enable this feature, the auto_envvar_prefix parameter needs to be passed to the script that is invoked. Each command and parameter is then added as an uppercase underscore-separated variable. If you have a subcommand called run taking an option called reload and the prefix is WEB, then the variable is WEB_RUN_RELOAD.

```<code>import click

@click.group()
def cli():
    pass

@cli.command()
@click.option("--name", prompt=True, show_envvar=True)
def cmd1(name):
    click.echo(f"Hello {name}!")

if __name__ == "__main__":
    cli(auto_envvar_prefix="NON_INTERACTIVE")
</code>```

$ python cli.py cmd1 --help
Usage: cli.py cmd1 [OPTIONS]

Options:
  --name TEXT  [env var: NON_INTERACTIVE_CMD1_NAME]
  --help       Show this message and exit.

$ python cli.py cmd1
Name: abc
Hello abc!

$ python cli.py cmd1 --name=xyz
Hello xyz!

$ export NON_INTERACTIVE_CMD1_NAME=xyz
$ python cli.py cmd1
Hello xyz!

$ unset NON_INTERACTIVE_CMD1_NAME
$ python cli.py cmd1
Name: abc
Hello abc!
```
<p>Rather than a <code>-q</code> that you need to handle within your CLI code, you instead implement it from whichever system is automating or running your CLI. You can then create different <em>.env</em> files for the different sets of default values, and then read them in as needed (or not, if you want to use the CLI interactively):</p>
<pre class="lang-none prettyprint-override"><code>$ cat defaults.env
NON_INTERACTIVE_CMD1_NAME=XYZ
NON_INTERACTIVE_CMD2_VERSION=1.0.0
NON_INTERACTIVE_CMD3_PORT=3000

$ cat automate.sh
#!/usr/bin/env bash

# https://stackoverflow.com/a/45971167/2745495
set -a
source defaults.env
set +a

python cli.py cmd1

$ ./automate.sh
Hello XYZ!

$ python cli.py cmd1
Name: xyz
Hello xyz!
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using click to implement a command-line interface in Python. Click has a feature that can prompt for a value if one isn't specified. Like so:

@click.command()
@click.option('--name', prompt=True)
def hello(name):
    click.echo(f"Hello {name}!")

This is great when a CLI is being used interactively, but prompting during a non-interactive run is bad (can hang a shell script, for example). I'd like to add a -q flag that would globally disable prompting for every other option.

Is there a straightforward way to do this?

Body:
If a -q flag is not a hard requirement, and the goal is to basically override the prompting behavior for automation purposes, a typical solution is to get the option values from environment variables. I think this is a much simpler solution than my other answer which does implement the -q flag.

https://click.palletsprojects.com/en/8.0.x/options/#values-from-environment-variables

A very useful feature of Click is the ability to accept parameters from environment variables in addition to regular parameters. This allows tools to be automated much easier. For instance, you might want to pass a configuration file with a --config parameter but also support exporting a TOOL_CONFIG=hello.cfg key-value pair for a nicer development experience.

...

To enable this feature, the auto_envvar_prefix parameter needs to be passed to the script that is invoked. Each command and parameter is then added as an uppercase underscore-separated variable. If you have a subcommand called run taking an option called reload and the prefix is WEB, then the variable is WEB_RUN_RELOAD.

import click

@click.group()
def cli():
    pass

@cli.command()
@click.option("--name", prompt=True, show_envvar=True)
def cmd1(name):
    click.echo(f"Hello {name}!")

if __name__ == "__main__":
    cli(auto_envvar_prefix="NON_INTERACTIVE")

$ python cli.py cmd1 --help
Usage: cli.py cmd1 [OPTIONS]

Options:
  --name TEXT  [env var: NON_INTERACTIVE_CMD1_NAME]
  --help       Show this message and exit.

$ python cli.py cmd1
Name: abc
Hello abc!

$ python cli.py cmd1 --name=xyz
Hello xyz!

$ export NON_INTERACTIVE_CMD1_NAME=xyz
$ python cli.py cmd1
Hello xyz!

$ unset NON_INTERACTIVE_CMD1_NAME
$ python cli.py cmd1
Name: abc
Hello abc!

Rather than a -q that you need to handle within your CLI code, you instead implement it from whichever system is automating or running your CLI. You can then create different .env files for the different sets of default values, and then read them in as needed (or not, if you want to use the CLI interactively):

$ cat defaults.env
NON_INTERACTIVE_CMD1_NAME=XYZ
NON_INTERACTIVE_CMD2_VERSION=1.0.0
NON_INTERACTIVE_CMD3_PORT=3000

$ cat automate.sh
#!/usr/bin/env bash

# https://stackoverflow.com/a/45971167/2745495
set -a
source defaults.env
set +a

python cli.py cmd1

$ ./automate.sh
Hello XYZ!

$ python cli.py cmd1
Name: xyz
Hello xyz!


问:
Can AVPlayerViewController be customized via Storyboard or must it be done via adding subviews?
I am using AVPlayerViewController/AVPlayer to play mp3s. I would like to be able to add an image and a textView when the player kicks off.  I've sort of been able to do this by adding subviews but I can't get the textView to scroll.  I was thinking that maybe I could just use Storyboard and drag an AVPlayerViewController into it and customize it there like a regular viewController ...but that doesn't seem possible because Xcode has crashed a few times when I've tried this. Is it even possible (or advisable) to try adding an imageView and/or textView via Storyboard somehow, or do I have to use subviews?

If it's subviews, how can I get my textView to scroll (I have another post asking about that)? The code that I have currently (without having AVPlayerViewController on the Storyboard) is:

```<code>let url = URL(string:mystream)
    let player = AVPlayer(url: url!)

    let controller = AVPlayerViewController()

    controller.player = player
    controller.view.frame = self.view.frame

    controller.contentOverlayView!.backgroundColor = UIColor(red: 148/255, green: 148/255, blue: 184/255, alpha: 1)

    //.. view
    var myView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height))

    //.. imageView
    var imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 325, height: 325))
    imageView.image = myImage
    imageView.contentMode = .scaleAspectFit
    imageView.translatesAutoresizingMaskIntoConstraints = false

    //.. textView
    var myTextView = UITextView(frame: CGRect(x: 0, y: 0, width: 350, height: 600))
    //myTextView.text = currentList
    myTextView.text = "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda. "
    myTextView.font = UIFont(name: "Chalkboard SE", size: 18)
    myTextView.textColor = UIColor.yellow
    myTextView.backgroundColor = UIColor.gray

    //..
    myTextView.contentMode = .scaleAspectFit

    myTextView.isScrollEnabled = true
    myTextView.isUserInteractionEnabled = true
    myTextView.isEditable = true
    myTextView.isSelectable = true
    myTextView.bounces = true
    myTextView.showsVerticalScrollIndicator = true
    myTextView.showsHorizontalScrollIndicator = true
    myTextView.contentSize = CGSize(width: 700, height: 700)

    myTextView.translatesAutoresizingMaskIntoConstraints = false

    myView.addSubview(imageView)
    myView.addSubview(myTextView)

    controller.contentOverlayView?.addSubview(myView)

    //.. @@@@@@@@@
    imageView.topAnchor.constraint(equalTo: myView.safeAreaLayoutGuide.topAnchor, constant: 50).isActive = true
    imageView.centerXAnchor.constraint(equalTo: myView.centerXAnchor, constant: 0).isActive = true
    imageView.widthAnchor.constraint(equalToConstant: 325).isActive = true
    imageView.heightAnchor.constraint(equalToConstant: 325).isActive = true

    myTextView.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 15).isActive = true
    myTextView.centerXAnchor.constraint(equalTo: myView.centerXAnchor, constant: 0).isActive = true
    myTextView.widthAnchor.constraint(equalToConstant: 325).isActive = true
    myTextView.heightAnchor.constraint(equalToConstant: 200).isActive = true

    //.. @@@@@@@@@

    present(controller, animated: true) {
            player.play()
    }
</code>```

Here is what the current player presents as... I need to be able to scroll the text...

答:
The short answer as of now, it is not possible to work and customize AVPlayerViewController in your storyboard.

You probably added a UIViewController in your storyboard and set the class of the UIViewController to AVPlayerViewController and probably the AVPlayerViewController's implementation is not prepared to handle this.

For now, you cannot add an AVPlayerViewController to the storyboard and move the controls around or add your subviews.

The closest thing you can do to working with a view in storyboard is to subclass AVPlayerViewController

```<code>class CustomAVPlayerController: AVPlayerViewController
{
 // your implementation
}
</code>```

And you can work with this in your storyboard provided you implement required init?(coder: NSCoder)

However, tread this path with caution as Apple recommends against subclassing AVPlayerViewController.

Overview

A player view controller makes it simple to add media
playback capabilities to your app that match the styling and features
of the native system players. Using this object also means that your
app automatically adopts the new features and styling of future
operating system releases.

I would say use this only if you have to do some basic work like detecting orientation changes, add some colors to views etc and not to mess around with subviews and controls.

If you only work with MP3s you can get away with playing your audio using an AVPlayer in a normal UIViewController rather AVPlayerViewController and this is what I did for one of the apps I developed - Reliable Radio

Here is an example of a UI I was able to achieve:

The pro of the above approach is that you can customize the view as you like, the con of that approach is you have to develop all the controls like play, forward, rewind, volume, scrubber etc

Here is an idea on how to achieve that

So it's a choice on what you are willing to compromise:

Not much UI customization but all the controls for free - AVPlayerViewController

Full UI control but develop your own controls - AVPlayer contained in a custom UIViewController

I will also answer your second question shortly about the UITextView scroll issue with a solution that is somewhere halfway between 1 and 2 above

Body:
I am using AVPlayerViewController/AVPlayer to play mp3s. I would like to be able to add an image and a textView when the player kicks off.  I've sort of been able to do this by adding subviews but I can't get the textView to scroll.  I was thinking that maybe I could just use Storyboard and drag an AVPlayerViewController into it and customize it there like a regular viewController ...but that doesn't seem possible because Xcode has crashed a few times when I've tried this. Is it even possible (or advisable) to try adding an imageView and/or textView via Storyboard somehow, or do I have to use subviews?

If it's subviews, how can I get my textView to scroll (I have another post asking about that)? The code that I have currently (without having AVPlayerViewController on the Storyboard) is:

let url = URL(string:mystream)
    let player = AVPlayer(url: url!)

    let controller = AVPlayerViewController()

    controller.player = player
    controller.view.frame = self.view.frame

    controller.contentOverlayView!.backgroundColor = UIColor(red: 148/255, green: 148/255, blue: 184/255, alpha: 1)

    //.. view
    var myView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height))

    //.. imageView
    var imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 325, height: 325))
    imageView.image = myImage
    imageView.contentMode = .scaleAspectFit
    imageView.translatesAutoresizingMaskIntoConstraints = false

    //.. textView
    var myTextView = UITextView(frame: CGRect(x: 0, y: 0, width: 350, height: 600))
    //myTextView.text = currentList
    myTextView.text = "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda. "
    myTextView.font = UIFont(name: "Chalkboard SE", size: 18)
    myTextView.textColor = UIColor.yellow
    myTextView.backgroundColor = UIColor.gray

    //..
    myTextView.contentMode = .scaleAspectFit

    myTextView.isScrollEnabled = true
    myTextView.isUserInteractionEnabled = true
    myTextView.isEditable = true
    myTextView.isSelectable = true
    myTextView.bounces = true
    myTextView.showsVerticalScrollIndicator = true
    myTextView.showsHorizontalScrollIndicator = true
    myTextView.contentSize = CGSize(width: 700, height: 700)

    myTextView.translatesAutoresizingMaskIntoConstraints = false

    myView.addSubview(imageView)
    myView.addSubview(myTextView)

    controller.contentOverlayView?.addSubview(myView)

    //.. @@@@@@@@@
    imageView.topAnchor.constraint(equalTo: myView.safeAreaLayoutGuide.topAnchor, constant: 50).isActive = true
    imageView.centerXAnchor.constraint(equalTo: myView.centerXAnchor, constant: 0).isActive = true
    imageView.widthAnchor.constraint(equalToConstant: 325).isActive = true
    imageView.heightAnchor.constraint(equalToConstant: 325).isActive = true

    myTextView.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 15).isActive = true
    myTextView.centerXAnchor.constraint(equalTo: myView.centerXAnchor, constant: 0).isActive = true
    myTextView.widthAnchor.constraint(equalToConstant: 325).isActive = true
    myTextView.heightAnchor.constraint(equalToConstant: 200).isActive = true

    //.. @@@@@@@@@

    present(controller, animated: true) {
            player.play()
    }

Here is what the current player presents as... I need to be able to scroll the text...

Body:
The short answer as of now, it is not possible to work and customize AVPlayerViewController in your storyboard.

You probably added a UIViewController in your storyboard and set the class of the UIViewController to AVPlayerViewController and probably the AVPlayerViewController's implementation is not prepared to handle this.

For now, you cannot add an AVPlayerViewController to the storyboard and move the controls around or add your subviews.

The closest thing you can do to working with a view in storyboard is to subclass AVPlayerViewController

class CustomAVPlayerController: AVPlayerViewController
{
 // your implementation
}

And you can work with this in your storyboard provided you implement required init?(coder: NSCoder)

However, tread this path with caution as Apple recommends against subclassing AVPlayerViewController.

Overview

A player view controller makes it simple to add media
playback capabilities to your app that match the styling and features
of the native system players. Using this object also means that your
app automatically adopts the new features and styling of future
operating system releases.

I would say use this only if you have to do some basic work like detecting orientation changes, add some colors to views etc and not to mess around with subviews and controls.

If you only work with MP3s you can get away with playing your audio using an AVPlayer in a normal UIViewController rather AVPlayerViewController and this is what I did for one of the apps I developed - Reliable Radio

Here is an example of a UI I was able to achieve:

The pro of the above approach is that you can customize the view as you like, the con of that approach is you have to develop all the controls like play, forward, rewind, volume, scrubber etc

Here is an idea on how to achieve that

So it's a choice on what you are willing to compromise:

Not much UI customization but all the controls for free - AVPlayerViewController

Full UI control but develop your own controls - AVPlayer contained in a custom UIViewController

I will also answer your second question shortly about the UITextView scroll issue with a solution that is somewhere halfway between 1 and 2 above


问:
Python - mapping dictionary keys to string integers avoiding duplicates
I need to create a dictionary in order to do some mapping, like so:

```<code>mapping = {x: x.split('_')[0] for x in G}
</code>```

which returns:

```<code>{'0_cerebellum': '0', '1_cerebellum': '1', '0_cortex': '0', '1_cortex': '1'}
</code>```

but this will get me duplicates and I need unique string ints as values.

Now, once the split class 'cerebellum' reaches its last 'n' string index ('1' here), how do I keep mapping starting from n+1, n+2 (and so on) values for split class 'cortex', ending up with:

```<code>{'0_cerebellum': '0', '1_cerebellum': '1', '0_cortex': '2', '1_cortex': '3'}
</code>```

答:
use enumerate():

>>> l = ['test', 'foo', 'None', 'Bar']
>>> enumerate(l)
<enumerate object at 0x00000258DE241340>
>>> list(enumerate(l))
[(0, 'test'), (1, 'foo'), (2, 'None'), (3, 'Bar')]
```
<p>this is your finally code:</p>
<pre class="lang-py prettyprint-override"><code>mapping = {x: str(i) for i, x in enumerate(G)}
</code>```

Body:
I need to create a dictionary in order to do some mapping, like so:

mapping = {x: x.split('_')[0] for x in G}

which returns:

{'0_cerebellum': '0', '1_cerebellum': '1', '0_cortex': '0', '1_cortex': '1'}

but this will get me duplicates and I need unique string ints as values.

Now, once the split class 'cerebellum' reaches its last 'n' string index ('1' here), how do I keep mapping starting from n+1, n+2 (and so on) values for split class 'cortex', ending up with:

{'0_cerebellum': '0', '1_cerebellum': '1', '0_cortex': '2', '1_cortex': '3'}

Body:
use enumerate():

>>> l = ['test', 'foo', 'None', 'Bar']
>>> enumerate(l)
<enumerate object at 0x00000258DE241340>
>>> list(enumerate(l))
[(0, 'test'), (1, 'foo'), (2, 'None'), (3, 'Bar')]

this is your finally code:

mapping = {x: str(i) for i, x in enumerate(G)}


问:
How to join values in 2 columns with 1 column? - SQL
Suppose I have 2 tables like:

```<code>table_a
student teacher
A       Z
B       Z
C       Z

table_b
id  person
1   A
2   B
3   C
4   Z

</code>```

I'm looking for an output of:

```<code>table_c
student_id  teacher_id
1           4
2           4
3           4
</code>```

I've been trying to solve this for a while, but can't figure out a simple method and believe I'm overthinking this. I'm confused how it's possible to join values in student and teacher with the person to get my output. I usually attach code that I've tried to my posts but am honestly drawing blanks here.

答:
You can try to use two correlated-subqueries to make it.</p>
```<code>SELECT (SELECT b.id  FROM table_b b WHERE b.person = a.student LIMIT 1) student_id,
       (SELECT b.id  FROM table_b b WHERE b.person = a.teacher LIMIT 1) teacher_id
FROM table_a  a
</code>```

Body:
Suppose I have 2 tables like:

table_a
student teacher
A       Z
B       Z
C       Z

table_b
id  person
1   A
2   B
3   C
4   Z

I'm looking for an output of:

table_c
student_id  teacher_id
1           4
2           4
3           4

I've been trying to solve this for a while, but can't figure out a simple method and believe I'm overthinking this. I'm confused how it's possible to join values in student and teacher with the person to get my output. I usually attach code that I've tried to my posts but am honestly drawing blanks here.

Body:
You can try to use two correlated-subqueries to make it.

SELECT (SELECT b.id  FROM table_b b WHERE b.person = a.student LIMIT 1) student_id,
       (SELECT b.id  FROM table_b b WHERE b.person = a.teacher LIMIT 1) teacher_id
FROM table_a  a


问:
How to copy data to clipboard in C#
How can I copy a string (e.g "hello") to the System Clipboard in C#, so next time I press CTRL+V I'll get "hello"?

答:
If you don't want to set the thread as STAThread, use Clipboard.SetDataObject(object sthhere):

```<code>Clipboard.SetDataObject("Yay! No more STA thread!");
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to copy data to clipboard in C#

Body:
If you don't want to set the thread as STAThread, use Clipboard.SetDataObject(object sthhere):

Clipboard.SetDataObject("Yay! No more STA thread!");


问:
Access Lambda Arguments with Groovy and Spock Argument Capture
I am trying to unit test a Java class with a method containing a lambda function. I am using Groovy and Spock for the test. For proprietary reasons I can't show the original code.

The Java method looks like this:

class ExampleClass {
  AsyncHandler asynHandler;
  Component componet;

  Component getComponent() {
    return component;
  }

  void exampleMethod(String input) {
    byte[] data = input.getBytes();

    getComponent().doCall(builder ->
      builder
        .setName(name)
        .data(data)
        .build()).whenCompleteAsync(asyncHandler);
  }
}
```
<p>Where <code>component#doCall</code> has the following signature:</p>
```CompletableFuture<Response> doCall(Consumer<Request> request) {
  // do some stuff
}
```
<p>The groovy test looks like this:</p>
<pre class="lang-java prettyprint-override"><code>class Spec extends Specification {
  def mockComponent = Mock(Component)

  @Subject
  def sut = new TestableExampleClass(mockComponent)

  def 'a test'() {
    when:
    sut.exampleMethod('teststring')

    then:
    1 * componentMock.doCall(_ as Consumer<Request>) >> { args ->
      assert args[0].args$2.asUtf8String() == 'teststring'
      return new CompletableFuture()
    }
  }

  class TestableExampleClass extends ExampleClass {
    def component

    TestableExampleClass(Component component) {
      this.component = component;
    }

    @Override
    getComponent() {
      return component
    }
  }
}
</code>```

The captured argument, args, shows up as follows in the debug window if I place a breakpoint on the assert line:

```<code>args = {Arrays$ArrayList@1234} size = 1
  > 0 = {Component$lambda}
    > args$1 = {TestableExampleClass}
    > args$2 = {bytes[]}
</code>```

There are two points confusing me:

When I try to cast the captured argument args[0] as either ExampleClass or TestableExampleClass it throws a GroovyCastException. I believe this is because it is expecting Component$Lambda, but I am not sure how to cast this.

Accessing the data property using args[0].args$2, doesn't seem like a clean way to do it. This is likely linked to the casting issue mentioned above. But is there a better way to do this, such as with args[0].data?

Even if direct answers can't be given, a pointer to some documentation or article would be helpful. My search results discussed Groovy closures and Java lambdas comparisons separately, but not about using lambdas in closures.

答:
Why you should not do what you are trying

This invasive kind of testing is a nightmare! Sorry for my strong wording, but I want to make it clear that you should not over-specify tests like this, asserting on private final fields of lambda expressions. Why would it even be important what goes into the lambda? Simply verify the result. In order to do a verification like this, you

need to know internals of how lambdas are implemented in Java,

those implementation details have to stay unchanged across Java versions and

the implementations even have to be the same across JVM types like Oracle Hotspot, OpenJ9 etc.

Otherwise, your tests break quickly. And why would you care how a method internally computes its result? A method should be tested like a black box, only in rare cases should you use interaction testing,where it is absolutely crucial in order to make sure that certain interactions between objects occur in a certain way (e.g. in order to verify a publish-subscribe design pattern).

How you can do it anyway (dont!!!)

Having said all that, just assuming for a minute that it does actually make sense to test like that (which it really does not!), a hint: Instead of accessing the field args$2, you can also access the declared field with index 1. Accessing by name is also possible, of course. anyway, you have to reflect on the lambda's class, get the declared field(s) you are interested in, make them accessible (remember, they are private final) and then assert on their respective contents. You could also filter by field type in order to be less sensitive to their order (not shown here).

Besides, I do not understand why you create a TestableExampleClass instead of using the original.

In this example, I am using explicit types instead of just def in order to make it easier to understand what the code does:

    then:
    1 * mockComponent.doCall(_ as Consumer<Request>) >> { args ->
      Consumer<Request> requestConsumer = args[0]
      Field nameField = requestConsumer.class.declaredFields[1]
//    Field nameField = requestConsumer.class.getDeclaredField('arg$2')
      nameField.accessible = true
      byte[] nameBytes = nameField.get(requestConsumer)
      assert new String(nameBytes, Charset.forName("UTF-8")) == 'teststring'
      return new CompletableFuture()
    }
```
<p>Or, in order to avoid the explicit <code>assert</code> in favour of a Spock-style condition:</p>
<pre class="lang-java prettyprint-override"><code>  def 'a test'() {
    given:
    String name

    when:
    sut.exampleMethod('teststring')

    then:
    1 * mockComponent.doCall(_ as Consumer<Request>) >> { args ->
      Consumer<Request> requestConsumer = args[0]
      Field nameField = requestConsumer.class.declaredFields[1]
//    Field nameField = requestConsumer.class.getDeclaredField('arg$2')
      nameField.accessible = true
      byte[] nameBytes = nameField.get(requestConsumer)
      name = new String(nameBytes, Charset.forName("UTF-8"))
      return new CompletableFuture()
    }
    name == 'teststring'
  }
</code>```

Body:
I am trying to unit test a Java class with a method containing a lambda function. I am using Groovy and Spock for the test. For proprietary reasons I can't show the original code.

The Java method looks like this:

class ExampleClass {
  AsyncHandler asynHandler;
  Component componet;

  Component getComponent() {
    return component;
  }

  void exampleMethod(String input) {
    byte[] data = input.getBytes();

    getComponent().doCall(builder ->
      builder
        .setName(name)
        .data(data)
        .build()).whenCompleteAsync(asyncHandler);
  }
}

Where component#doCall has the following signature:

CompletableFuture<Response> doCall(Consumer<Request> request) {
  // do some stuff
}

The groovy test looks like this:

class Spec extends Specification {
  def mockComponent = Mock(Component)

  @Subject
  def sut = new TestableExampleClass(mockComponent)

  def 'a test'() {
    when:
    sut.exampleMethod('teststring')

    then:
    1 * componentMock.doCall(_ as Consumer<Request>) >> { args ->
      assert args[0].args$2.asUtf8String() == 'teststring'
      return new CompletableFuture()
    }
  }

  class TestableExampleClass extends ExampleClass {
    def component

    TestableExampleClass(Component component) {
      this.component = component;
    }

    @Override
    getComponent() {
      return component
    }
  }
}

The captured argument, args, shows up as follows in the debug window if I place a breakpoint on the assert line:

args = {Arrays$ArrayList@1234} size = 1
  > 0 = {Component$lambda}
    > args$1 = {TestableExampleClass}
    > args$2 = {bytes[]}

There are two points confusing me:

When I try to cast the captured argument args[0] as either ExampleClass or TestableExampleClass it throws a GroovyCastException. I believe this is because it is expecting Component$Lambda, but I am not sure how to cast this.

Accessing the data property using args[0].args$2, doesn't seem like a clean way to do it. This is likely linked to the casting issue mentioned above. But is there a better way to do this, such as with args[0].data?

Even if direct answers can't be given, a pointer to some documentation or article would be helpful. My search results discussed Groovy closures and Java lambdas comparisons separately, but not about using lambdas in closures.

Body:
Why you should not do what you are trying

This invasive kind of testing is a nightmare! Sorry for my strong wording, but I want to make it clear that you should not over-specify tests like this, asserting on private final fields of lambda expressions. Why would it even be important what goes into the lambda? Simply verify the result. In order to do a verification like this, you

need to know internals of how lambdas are implemented in Java,

those implementation details have to stay unchanged across Java versions and

the implementations even have to be the same across JVM types like Oracle Hotspot, OpenJ9 etc.

Otherwise, your tests break quickly. And why would you care how a method internally computes its result? A method should be tested like a black box, only in rare cases should you use interaction testing,where it is absolutely crucial in order to make sure that certain interactions between objects occur in a certain way (e.g. in order to verify a publish-subscribe design pattern).

How you can do it anyway (dont!!!)

Having said all that, just assuming for a minute that it does actually make sense to test like that (which it really does not!), a hint: Instead of accessing the field args$2, you can also access the declared field with index 1. Accessing by name is also possible, of course. anyway, you have to reflect on the lambda's class, get the declared field(s) you are interested in, make them accessible (remember, they are private final) and then assert on their respective contents. You could also filter by field type in order to be less sensitive to their order (not shown here).

Besides, I do not understand why you create a TestableExampleClass instead of using the original.

In this example, I am using explicit types instead of just def in order to make it easier to understand what the code does:

    then:
    1 * mockComponent.doCall(_ as Consumer<Request>) >> { args ->
      Consumer<Request> requestConsumer = args[0]
      Field nameField = requestConsumer.class.declaredFields[1]
//    Field nameField = requestConsumer.class.getDeclaredField('arg$2')
      nameField.accessible = true
      byte[] nameBytes = nameField.get(requestConsumer)
      assert new String(nameBytes, Charset.forName("UTF-8")) == 'teststring'
      return new CompletableFuture()
    }

Or, in order to avoid the explicit assert in favour of a Spock-style condition:

  def 'a test'() {
    given:
    String name

    when:
    sut.exampleMethod('teststring')

    then:
    1 * mockComponent.doCall(_ as Consumer<Request>) >> { args ->
      Consumer<Request> requestConsumer = args[0]
      Field nameField = requestConsumer.class.declaredFields[1]
//    Field nameField = requestConsumer.class.getDeclaredField('arg$2')
      nameField.accessible = true
      byte[] nameBytes = nameField.get(requestConsumer)
      name = new String(nameBytes, Charset.forName("UTF-8"))
      return new CompletableFuture()
    }
    name == 'teststring'
  }


问:
Converting HTML in PHP File to PDF File
I have a php file which queries a database and then writes and updates the html accordingly.

I have a button on this page "Export As PDF"..I am trying to convert this page to a pdf using HTML2FPDF, but I get the following error:

```<code>FPDF error: Unable to create output file: Entry Report
</code>```

I suspect the problem is because I am passing a php file instead of a html file:

```<code><?php
require('html2fpdf.php');

if(isset($_POST['link'])){
  $url = $_POST['link'];
  $nm = $_POST['nm'];
  convert($url, $nm);
}

function convert($link, $name){
  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $fp = fopen($link,"r");
  $strContent = fread($fp, filesize($link));
  fclose($fp);
  $pdf->WriteHTML($strContent);
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}
?>
</code>```

Does anyone know how I can get around this? perhaps by either converting php to html then html to pdf...

Or is there a direct way to convert a php file into a pdf file...

EDIT: OK so the problem was that I didn't allow public write permissions. Upon changing this, I managed it to create the pdf file...The problem is this....the pdf file is blank...

I know this has something to do with the fact that I am passing a php page which is probably empty when it is being passed...How do I capture the html content within the html so the pdf output isn't blank?

Here is the php page:

```<code><?php

function connect() {
  $dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
  mysql_select_db("PDS", $dbh);
  return $dbh;
}

session_start();

if(isset($_SESSION['username'])){
  if(isset($_POST['entryId'])){
    //do something
    $dbh = connect();
    $ide = $_POST['entryId'];
    $usertab = $_POST['usertable'];
    $answertable = $usertab . "Answers";
    $entrytable = $usertab . "Entries";
    $query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());

    if($query){
      //set variables

      $sectionOne = array();
      $sectionTwo = array();
      $sectionThree = array();
      $sectionFour = array();
      $sectionFive = array();
      while($row=mysql_fetch_assoc($query)){
    $date = $row['date'];
    $section = $row['sectionId'];
    switch($section){
    case '1':
      $sectionOne[] = $row;
      break;
    case '2':
      $sectionTwo[] = $row;
      break;
    case '3':
      $sectionThree[] = $row;
      break;
        case '4':
      $sectionFour[] = $row;
      break;
        case '5':
      $sectionFive[] = $row;
      break;
        default:
      break;
    }
      }
    }else{
      //error - sql failed
    }
  }

?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
   <head>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
   <script src = "jQuery.js"></script>
   <script>
   $(document).ready(function(){
       $("#export").click(function(e){
       //post to html2pdfconverter.php
       $("#link").val("Testers/viewentryreport.php");
       $("#nm").val("Entry Report.pdf");
       $("form#sendanswers").submit();
       });
   });
  </script>
  <title>Personal Diary System - Entry Report - <?php echo($date); ?></title>
  </head>
  <body>
  <h1>Entry Report - <?php echo($date); ?></h1>
  <div id = "buttons">
  <form id = "sendanswers" name = "sendanswers" action="Testers/html2pdfconverter.php" method="post">
  <input type = "hidden" name = "link" id = "link" value = "">
  <input type = "hidden" name = "nm" id = "nm" value = "">
  <input type = "button" name = "export" id = "export" value = "Export As PDF"/>
  </form>
  </div>
  <h3>Biological Information</h3>
  <?php
      $i = 0;
      foreach($sectionOne as &$value){
    if($i == 1 || $i == 3){
      $image = "assets/urine".$i.".png";
      echo("<br/>");
      echo($value['question']." <br/> "."<img src = \"$image\"/>");
      echo("<br/>");
    }else{
      echo($value['question'].' : '.$value['answer']);
    }
    echo("<br/>");
    $i++;
      }
  ?>
  <h3>Fatigue and Recovery</h3>
  <?php
      foreach($sectionTwo as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("<br/>");
      }
  ?>
  <h3>Illness and Injury</h3>
  <?php
      foreach($sectionThree as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("<br/>");
      }
  ?>
  <h3>Training Sessions</h3>
  <?php
      foreach($sectionFour as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("<br/>");
      }
  ?>
  <h3>General Feedback</h3>
  <?php
     if(count($sectionFive)>0){
      foreach($sectionFive as &$value){
    echo($value['question'].' : '.$value['answer']);
      }
     }else{
       $sectionFive = "User didn't leave any feedback";
       echo("User didn't leave any feedback");
     }
     echo("<br/>");
  ?>
  </body>
</html>
<?php
}
?>
</code>```

and html2pdfconverter.php

```<code><?php
require('html2fpdf.php');

if(isset($_POST['link'])){
  $url = $_POST['link'];
  $nm = $_POST['nm'];
  convert($url, $nm);
}

function convert($link, $name){
  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $fp = fopen($link,"r");
  $strContent = fread($fp, filesize($link));
  fclose($fp);
  $pdf->WriteHTML($strContent);
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}
?>
</code>```

EDIT @TIMFERRIS

I changed my convert function to this based on @TimeFerris' answer:

```<code>function convert($link, $name){

  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $content = file_get_contents( $link ); //shorter than what you did
  ob_start();
  echo $content;
  $pdf->WriteHTML( ob_get_contents() );
  ob_end_clean();
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}
</code>```

The PDF file is created but still blank

答:
I recently done this by using TCPDF. TCPDF is a further developed version of FPDF.

See this link for an expample regarding converting to PDF. Also, here you can find more examples. Example 61 could also come in quite handy.

Sample code which TCPDF uses:

```<code>$html = '<h1>HTML Example</h1>
<div style="text-align:center">IMAGES<br />
<img src="../images/logo_example.png" alt="test alt attribute" width="100" height="100" border="0" /><img src="../images/tiger.ai" alt="test alt attribute" width="100" height="100" border="0" /><img src="../images/logo_example.jpg" alt="test alt attribute" width="100" height="100" border="0" />
</div>';

// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');
</code>```

Title: Converting HTML in PHP File to PDF File

Body:
I have a php file which queries a database and then writes and updates the html accordingly.

I have a button on this page "Export As PDF"..I am trying to convert this page to a pdf using HTML2FPDF, but I get the following error:

FPDF error: Unable to create output file: Entry Report

I suspect the problem is because I am passing a php file instead of a html file:

<?php
require('html2fpdf.php');

if(isset($_POST['link'])){
  $url = $_POST['link'];
  $nm = $_POST['nm'];
  convert($url, $nm);
}

function convert($link, $name){
  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $fp = fopen($link,"r");
  $strContent = fread($fp, filesize($link));
  fclose($fp);
  $pdf->WriteHTML($strContent);
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}
?>

Does anyone know how I can get around this? perhaps by either converting php to html then html to pdf...

Or is there a direct way to convert a php file into a pdf file...

EDIT: OK so the problem was that I didn't allow public write permissions. Upon changing this, I managed it to create the pdf file...The problem is this....the pdf file is blank...

I know this has something to do with the fact that I am passing a php page which is probably empty when it is being passed...How do I capture the html content within the html so the pdf output isn't blank?

Here is the php page:

<?php

function connect() {
  $dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
  mysql_select_db("PDS", $dbh);
  return $dbh;
}

session_start();

if(isset($_SESSION['username'])){
  if(isset($_POST['entryId'])){
    //do something
    $dbh = connect();
    $ide = $_POST['entryId'];
    $usertab = $_POST['usertable'];
    $answertable = $usertab . "Answers";
    $entrytable = $usertab . "Entries";
    $query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());

    if($query){
      //set variables

      $sectionOne = array();
      $sectionTwo = array();
      $sectionThree = array();
      $sectionFour = array();
      $sectionFive = array();
      while($row=mysql_fetch_assoc($query)){
    $date = $row['date'];
    $section = $row['sectionId'];
    switch($section){
    case '1':
      $sectionOne[] = $row;
      break;
    case '2':
      $sectionTwo[] = $row;
      break;
    case '3':
      $sectionThree[] = $row;
      break;
        case '4':
      $sectionFour[] = $row;
      break;
        case '5':
      $sectionFive[] = $row;
      break;
        default:
      break;
    }
      }
    }else{
      //error - sql failed
    }
  }

?>

   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

  <title>Personal Diary System - Entry Report - <?php echo($date); ?></title>

Entry Report - <?php echo($date); ?>

  <form id = "sendanswers" name = "sendanswers" action="Testers/html2pdfconverter.php" method="post">
  <input type = "hidden" name = "link" id = "link" value = "">
  <input type = "hidden" name = "nm" id = "nm" value = "">
  <input type = "button" name = "export" id = "export" value = "Export As PDF"/>
  </form>

Biological Information

  <?php
      $i = 0;
      foreach($sectionOne as &$value){
    if($i == 1 || $i == 3){
      $image = "assets/urine".$i.".png";
      echo("
");
      echo($value['question']."
 "."");
      echo("
");
    }else{
      echo($value['question'].' : '.$value['answer']);
    }
    echo("
");
    $i++;
      }
  ?>

Fatigue and Recovery

  <?php
      foreach($sectionTwo as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("
");
      }
  ?>

Illness and Injury

  <?php
      foreach($sectionThree as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("
");
      }
  ?>

Training Sessions

  <?php
      foreach($sectionFour as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("
");
      }
  ?>

General Feedback

  <?php
     if(count($sectionFive)>0){
      foreach($sectionFive as &$value){
    echo($value['question'].' : '.$value['answer']);
      }
     }else{
       $sectionFive = "User didn't leave any feedback";
       echo("User didn't leave any feedback");
     }
     echo("
");
  ?>

<?php
}
?>

and html2pdfconverter.php

<?php
require('html2fpdf.php');

if(isset($_POST['link'])){
  $url = $_POST['link'];
  $nm = $_POST['nm'];
  convert($url, $nm);
}

function convert($link, $name){
  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $fp = fopen($link,"r");
  $strContent = fread($fp, filesize($link));
  fclose($fp);
  $pdf->WriteHTML($strContent);
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}
?>

EDIT @TIMFERRIS

I changed my convert function to this based on @TimeFerris' answer:

function convert($link, $name){

  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $content = file_get_contents( $link ); //shorter than what you did
  ob_start();
  echo $content;
  $pdf->WriteHTML( ob_get_contents() );
  ob_end_clean();
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}

The PDF file is created but still blank

Body:
I recently done this by using TCPDF. TCPDF is a further developed version of FPDF.

See this link for an expample regarding converting to PDF. Also, here you can find more examples. Example 61 could also come in quite handy.

Sample code which TCPDF uses:

$html = '<h1>HTML Example</h1>
<div style="text-align:center">IMAGES<br />
<img src="../images/logo_example.png" alt="test alt attribute" width="100" height="100" border="0" /><img src="../images/tiger.ai" alt="test alt attribute" width="100" height="100" border="0" /><img src="../images/logo_example.jpg" alt="test alt attribute" width="100" height="100" border="0" />
</div>';

// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');


答:
As I understand, this should get your result, using enumerate.

```<code>G = ['0_cerebellum', '1_cerebellum', '0_cortex', '1_cortex']
mapping = {key: str(uniqueNum) for uniqueNum,key in enumerate(G)}
</code>```

Output:

```<code>{'0_cerebellum': '0', '1_cerebellum': '1', '0_cortex': '2', '1_cortex': '3'}
</code>```

Title: Python - mapping dictionary keys to string integers avoiding duplicates

Body:
As I understand, this should get your result, using enumerate.

G = ['0_cerebellum', '1_cerebellum', '0_cortex', '1_cortex']
mapping = {key: str(uniqueNum) for uniqueNum,key in enumerate(G)}

Output:

{'0_cerebellum': '0', '1_cerebellum': '1', '0_cortex': '2', '1_cortex': '3'}


问:
I need to web scrap a particular value from a page which is contained in a table
I want to scrap net sales value for Dec 2021 that is contained in a table from a webpage. I am using simple beautifulsoup module.I have included the python code I am using for extracting some of the other values.I want to extract the value 9644.8. The code for the webpage is give below

        PARTICULARS
        Dec 2020
        Mar 2021
        Jun 2021
        Sep 2021
        Dec 2021

        Net Sales <svg
                class="svg-inline--fa fa-info-circle fa-w-16" aria-hidden="true" focusable="false" data-prefix="fas"
                data-icon="info-circle" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"
                data-fa-i2svg=""><path fill="currentColor"
                                       d="M256 8C119.043 8 8 119.083 8 256c0 136.997 111.043 248 248 248s248-111.003 248-248C504 119.083 392.957 8 256 8zm0 110c23.196 0 42 18.804 42 42s-18.804 42-42 42-42-18.804-42-42 18.804-42 42-42zm56 254c0 6.627-5.373 12-12 12h-88c-6.627 0-12-5.373-12-12v-24c0-6.627 5.373-12 12-12h12v-64h-12c-6.627 0-12-5.373-12-12v-24c0-6.627 5.373-12 12-12h64c6.627 0 12 5.373 12 12v100h12c6.627 0 12 5.373 12 12v24z"></path></svg>

            10,824.40

            9,530.90

            9,088.20

            9,321.50

            9,644.80

```
<pre class="lang-py prettyprint-override"><code>import pandas as pd
from bs4 import BeautifulSoup
import requests
a=input("Enter symbol of the company\n")
url="https://ticker.finology.in/company/"+a
print(url)
response=requests.get(url)
soup=BeautifulSoup(response.text,'html.parser')
CP = soup.find("div", {"id":"mainContent_clsprice"}).find("span", {"class": "Number"}).getText()
</code>```

The ticker I am using is IDEA

Body:
I want to scrap net sales value for Dec 2021 that is contained in a table from a webpage. I am using simple beautifulsoup module.I have included the python code I am using for extracting some of the other values.I want to extract the value 9644.8. The code for the webpage is give below

        PARTICULARS
        Dec 2020
        Mar 2021
        Jun 2021
        Sep 2021
        Dec 2021

        Net Sales <svg
                class="svg-inline--fa fa-info-circle fa-w-16" aria-hidden="true" focusable="false" data-prefix="fas"
                data-icon="info-circle" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"
                data-fa-i2svg=""><path fill="currentColor"
                                       d="M256 8C119.043 8 8 119.083 8 256c0 136.997 111.043 248 248 248s248-111.003 248-248C504 119.083 392.957 8 256 8zm0 110c23.196 0 42 18.804 42 42s-18.804 42-42 42-42-18.804-42-42 18.804-42 42-42zm56 254c0 6.627-5.373 12-12 12h-88c-6.627 0-12-5.373-12-12v-24c0-6.627 5.373-12 12-12h12v-64h-12c-6.627 0-12-5.373-12-12v-24c0-6.627 5.373-12 12-12h64c6.627 0 12 5.373 12 12v100h12c6.627 0 12 5.373 12 12v24z"></path></svg>

            10,824.40

            9,530.90

            9,088.20

            9,321.50

            9,644.80

import pandas as pd
from bs4 import BeautifulSoup
import requests
a=input("Enter symbol of the company\n")
url="https://ticker.finology.in/company/"+a
print(url)
response=requests.get(url)
soup=BeautifulSoup(response.text,'html.parser')
CP = soup.find("div", {"id":"mainContent_clsprice"}).find("span", {"class": "Number"}).getText()

The ticker I am using is IDEA

Body:
You can pass the URL directly to pandas.read_html() which will return a list of dataframes of tables found.

>>> dfs = pd.read_html('https://ticker.finology.in/company/idea')
>>> dfs[1]
          PARTICULARS  Dec 2020  Mar 2021  Jun 2021  Sep 2021  Dec 2021
0           Net Sales  10824.40   9530.90   9088.20    9321.5    9644.8
1   Total Expenditure   6717.40   5296.20   5529.30    5672.9    5995.2
2    Operating Profit   4107.00   4234.70   3558.90    3648.6    3649.6
3        Other Income     36.30     31.10     29.20      22.8      25.2
4            Interest   4782.60   4711.00   5223.20    5112.8    5324.7
5        Depreciation   5638.90   5629.50   5831.90    5743.8    5550.5
6   Exceptional Items   -439.50   -972.60     51.30      13.5      11.6
7   Profit Before Tax  -6717.70  -7047.30  -7415.70   -7171.7   -7188.8
8                 Tax      0.00    -20.80      0.00       0.0       0.0
9    Profit After Tax  -6717.70  -7026.50  -7415.70   -7171.7   -7188.8
10  Adjusted EPS (Rs)     -2.34     -2.45     -2.58      -2.5      -2.5


问:
why does nullish coalescing executing two parts?
I have a method:

```<code>const objT2 = {
  calcAge(year) {
    console.log(2022 - year);
  },
};
</code>```

but when I use the nullish coalescing both parts is being executed.

```<code>objT2.calcAge(1990) ?? console.log(`method not found`);
//output => 32    method not found
</code>```

答: first you are calling calcAge method with 1990. so by calling it, the method gets executed objT2.calcAge(1990). this calculated 2022 - 1990 which is 32 and then logs it to the console. then this method returns undefined which gets evaluated as the left hand operand of the ?? operator. As this operator sees the left hand side is returning a nullish value (null or undefined), it goes on to execute the right hand side which logs method not found as well.

Body:
I have a method:

const objT2 = {
  calcAge(year) {
    console.log(2022 - year);
  },
};

but when I use the nullish coalescing both parts is being executed.

objT2.calcAge(1990) ?? console.log(`method not found`);
//output => 32    method not found


问:
How does this nested loop output a list separated into 3 sections with 3 words in each section?
I'm very new to C#. I was curious on how this block of code printed out 3 separate lines with the 3 words in the arrays. Could someone explain how it works?

```<code>using System;

namespace MyFirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {

            String[,] parkingLot = {{ "Mustang", "F-150", "Explorer" }, { "Corvette", "Camaro", "Silverado" }, { "Corolla", "Camry", "Rav4" }};

            for(int i = 0; i < parkingLot.GetLength(0); i++)
            {
                for (int j = 0; j < parkingLot.GetLength(1); j++)
                {
                    Console.Write(parkingLot[i, j] + " ");
                }
                Console.WriteLine();
            }

            Console.ReadKey();
        }
    }
}```
```

答:
The GetLength() method returns the size of the dimension passed in:

Gets a 32-bit integer that represents the number of elements in the
specified dimension of the Array.

Notice the first call gets passed a zero:

```<code>parkingLot.GetLength(0)
</code>```

This returns the number of ROWS in the 2D array.

The second call is passed a one:

```<code>parkingLot.GetLength(1)
</code>```

Which tells you the number of COLUMNS in the 2D array.

Perhaps this example will illustrate the concept better:

```<code>String[,] parkingLot = {
  { "a", "b", "c" },
  { "1", "2", "3" },
  { "red", "green", "blue" },
  { "cat", "dog", "fish"},
  { "A1", "B2", "C3"}
};

for(int row = 0; row < parkingLot.GetLength(0); row++) // 5 rows
{
  for (int col = 0; col < parkingLot.GetLength(1); col++) // 3 columns
  {
    Console.Write(parkingLot[row, col] + " ");
  }
  Console.WriteLine();
}
</code>```

Output:

```<code>a b c
1 2 3
red green blue
cat dog fish
A1 B2 C3
</code>```

Body:
I'm very new to C#. I was curious on how this block of code printed out 3 separate lines with the 3 words in the arrays. Could someone explain how it works?

using System;

namespace MyFirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {

            String[,] parkingLot = {{ "Mustang", "F-150", "Explorer" }, { "Corvette", "Camaro", "Silverado" }, { "Corolla", "Camry", "Rav4" }};

            for(int i = 0; i < parkingLot.GetLength(0); i++)
            {
                for (int j = 0; j < parkingLot.GetLength(1); j++)
                {
                    Console.Write(parkingLot[i, j] + " ");
                }
                Console.WriteLine();
            }

            Console.ReadKey();
        }
    }
}```

Body:
The GetLength() method returns the size of the dimension passed in:

Gets a 32-bit integer that represents the number of elements in the
specified dimension of the Array.

Notice the first call gets passed a zero:

parkingLot.GetLength(0)

This returns the number of ROWS in the 2D array.

The second call is passed a one:

parkingLot.GetLength(1)

Which tells you the number of COLUMNS in the 2D array.

Perhaps this example will illustrate the concept better:

String[,] parkingLot = {
  { "a", "b", "c" },
  { "1", "2", "3" },
  { "red", "green", "blue" },
  { "cat", "dog", "fish"},
  { "A1", "B2", "C3"}
};

for(int row = 0; row < parkingLot.GetLength(0); row++) // 5 rows
{
  for (int col = 0; col < parkingLot.GetLength(1); col++) // 3 columns
  {
    Console.Write(parkingLot[row, col] + " ");
  }
  Console.WriteLine();
}

Output:

a b c
1 2 3
red green blue
cat dog fish
A1 B2 C3


问:
How to upload image to server with image picker react native
I want to upload image and upload to server. how can i get a file and can read in server?

```<code>const takePhotoFromLibraryProfile = () => {
    ImagePicker.openPicker({
      width: 200,
      height: 200,
      cropping: true,
    }).then(image => {
      setImageProfile(image.path);
    });
  };
</code>```

and this my axios post

```<code>axios({
      crossDomain: true,
      method: 'post',
      url: 'url',
      data: {
        userId: dataProfile.id,
        pictures: imageProfile,
      },
      validateStatus: false,
    })
      .then((response, status) => {
        console.log(response);
        setSuccessModal(response.status);
      })
      .catch(function (error) {
        console.log(error);
        // need handling error
      });
  };
</code>```

i got the respon and also false but in develop web can upload the image. Thank you

答:
To upload images to files to web servers, We cannot send it in the data property of Axios or fetch.

To Upload files or image, we have to convert the data into form data. And then we can send the form data to the webserver with the help of the Axios or fetch.

For Example:

```<code>const formData = new FormData()
formData.append('userId', dataProfile.id)
formData.append('pictures', {
    uri: user.profilePicture,
    type: 'image/jpeg',
    name: 'photo.jpg'
})

axios({
    method: 'post',
    url: 'url',
    data: formData,
  })
    .then((response, status) => {
      console.log(response);
      setSuccessModal(response.status);
    })
    .catch(function (error) {
      console.log(error);
      // need handling error
    });
};
</code>```

Body:
I want to upload image and upload to server. how can i get a file and can read in server?

const takePhotoFromLibraryProfile = () => {
    ImagePicker.openPicker({
      width: 200,
      height: 200,
      cropping: true,
    }).then(image => {
      setImageProfile(image.path);
    });
  };

and this my axios post

axios({
      crossDomain: true,
      method: 'post',
      url: 'url',
      data: {
        userId: dataProfile.id,
        pictures: imageProfile,
      },
      validateStatus: false,
    })
      .then((response, status) => {
        console.log(response);
        setSuccessModal(response.status);
      })
      .catch(function (error) {
        console.log(error);
        // need handling error
      });
  };

i got the respon and also false but in develop web can upload the image. Thank you

Body:
To upload images to files to web servers, We cannot send it in the data property of Axios or fetch.

To Upload files or image, we have to convert the data into form data. And then we can send the form data to the webserver with the help of the Axios or fetch.

For Example:

const formData = new FormData()
formData.append('userId', dataProfile.id)
formData.append('pictures', {
    uri: user.profilePicture,
    type: 'image/jpeg',
    name: 'photo.jpg'
})

axios({
    method: 'post',
    url: 'url',
    data: formData,
  })
    .then((response, status) => {
      console.log(response);
      setSuccessModal(response.status);
    })
    .catch(function (error) {
      console.log(error);
      // need handling error
    });
};


问:
I am trying to get retrive data from mongodb but not getting expected output
DB Data -

```<code>[{
    title: "Vivo X50",
    category: "mobile",
    amount: 35000

},
{
    title: "Samsung M32",
    category: "mobile",
    amount: 18000

},
{
    title: "Lenovo 15E253",
    category: "laptop",
    amount: 85000

},
{
    title: "Dell XPS 15R",
    category: "laptop",
    amount: 115000
}]
</code>```

Expected Output:

```<code>[{
    category: "mobile",
    qty: 2,
    totalAmount: 53000
},
{
    category: "laptop",
    qty: 2,
    totalAmount: 200000
}]
</code>```

Code I am running (Using mongoose)

```<code>let products = await Product.aggregate([
    {
      $project: { _id: 0, category: 1, amount: 1 },
    },
    {
      $group: {
        _id: "$category",
        qty: { $sum: 1 },
        totalAmount: { $sum: "$amount" },
      },
    },
  ]);
</code>```

Result I am Getting.

```<code>[
{
"_id": "laptop",
"count": 2,
"totalSum": 200000
},
{
"_id": "mobile",
"count": 2,
"totalSum": 53000
}
]
</code>```

As you can clearly see that I am able to get correct data but I want correct name also category instead of _id. Please help me with that. Thanks in advance

答:
You can use the following query to get your expected output. cheers~

await Product.aggregate([
  {
    $group: {
      _id: "$category",
      qty: {
        $sum: 1
      },
      totalAmount: {
        $sum: "$amount"
      },

    },

  },
  {
    $addFields: {
      category: "$_id"
    }
  },
  {
    $project: {
      _id: 0
    },

  }
])```

Body:
DB Data -

[{
    title: "Vivo X50",
    category: "mobile",
    amount: 35000

},
{
    title: "Samsung M32",
    category: "mobile",
    amount: 18000

},
{
    title: "Lenovo 15E253",
    category: "laptop",
    amount: 85000

},
{
    title: "Dell XPS 15R",
    category: "laptop",
    amount: 115000
}]

Expected Output:

[{
    category: "mobile",
    qty: 2,
    totalAmount: 53000
},
{
    category: "laptop",
    qty: 2,
    totalAmount: 200000
}]

Code I am running (Using mongoose)

let products = await Product.aggregate([
    {
      $project: { _id: 0, category: 1, amount: 1 },
    },
    {
      $group: {
        _id: "$category",
        qty: { $sum: 1 },
        totalAmount: { $sum: "$amount" },
      },
    },
  ]);

Result I am Getting.

[
{
"_id": "laptop",
"count": 2,
"totalSum": 200000
},
{
"_id": "mobile",
"count": 2,
"totalSum": 53000
}
]

As you can clearly see that I am able to get correct data but I want correct name also category instead of _id. Please help me with that. Thanks in advance


问:
grab a argument as regex pattern inside a shell script
This is simple script to run ls with filter :

```<code>sh myscript.sh ".pyc"
</code>```

myscript.sh :

```<code>echo "---------------------------"
for i in `ls | grep '.*\.pyc'`; do
    echo "$i"
done
</code>```

it will do 'ls' and only show *.pyc. Now i want to put that pattern in the argument :

```<code>sh myscript.sh ".pyc"
</code>```

and modify the script :

```<code>echo "---------------------------"
for i in `ls | grep '.*\$1'`; do
    echo "$i"
done
</code>```

But this doesn't work. it returns empty result. How to properly insert that $1 in the regex while inside the shell script ?

答:
Replace everything with this: printf '%s\n' *"$1".

Or alternatively just run one of printf '%s\n' *.pyc, ls *.pyc, ls -d *.pyc, etc.

You probably want *.pyc (a shell glob/wildcard which expands to all files ending .pyc), as opposed to using grep.

Body:
This is simple script to run ls with filter :

sh myscript.sh ".pyc"

myscript.sh :

echo "---------------------------"
for i in `ls | grep '.*\.pyc'`; do
    echo "$i"
done

it will do 'ls' and only show *.pyc. Now i want to put that pattern in the argument :

sh myscript.sh ".pyc"

and modify the script :

echo "---------------------------"
for i in `ls | grep '.*\$1'`; do
    echo "$i"
done

But this doesn't work. it returns empty result. How to properly insert that $1 in the regex while inside the shell script ?


问:
Can I selectively (force) inline a function?
In the book Clean Code (and a couple of others I have come across and read) it is suggested to keep the functions small and break them up if they become large. It also suggests that functions should do one thing and one thing only.

In Optimizing software in C++ Agner Fog states that he does not like the rule of breaking up a function just because it crosses a certain threshold of a number of lines. He states that this results in unnecessary jumps which degrade performance.

First off, I understand that it will not matter if the code I am working on is not in a tight loop and that the functions are heavy so that the time it takes to call them is dwarfed by the time the code in the function takes to execute. But let's assume that I am working with functions that are, most of the time, used by other objects/functions and are performing relatively trivial tasks. These functions follow the suggestions listed in the first paragraph (that is, perform one single function and are small/comprehensible). Then I start programming a performance critical function that utilizes these other functions in a tight loop and is essentially a frame function. Lastly, assume that in-lining them has a benefit for the performance critical function but no benefit whatsoever to any other function (yes, I have profiled this, albeit with a lot of copying and pasting which I want to avoid).

Immediately, one can say that tag the function inline and let the compiler choose. But what if I don't want all those functions to be in a `.inl file or exposed in the header? In my current situation, the performance critical functions and the other functions it uses are all in the same source file.

To sum it up, can I selectively (force) inline a function(s) for a single function so that the end code behaves like it is one big function instead of several calls to other functions.

答:
There is nothing that prevents you to put inline in a static function in a .cpp file.

Some compilers have the option to force an inline function, see e.g. the GCC attribute((always_inline)) and a ton of options to fine tune the inlining optimizations (see -minline-* parameters).

My recommendation is to use inline or even better static inline wherever you see fit, and let the compiler decide. They usually do it pretty well.


问:
AsyncStorage.getItem returns wired value
I am using Context/Asyncstorage for state management.
I store the data which returned from server to the Asyncstorage.

```<code>getData.then(
    res => AsyncStorage.setItem('user', JSON.stringify(res.data))
)
</code>```

And I set the global state named user in Global provider like below.

```<code>const [userState, userDispatch] = useReducer(
   user, userInitialState,
   async () => {
      const storedUserData = await AsyncStorage.getItem('user');
      return storedUserData != null ? JSON.parse(storedUserData) : userInitialState;
   },
);
</code>```

and Here is get the userState on other component

```<code>const SomeComponent = () => {
   const {userState} = useContext(GlobalContext);

   useEffect ( () => {
      console.log(userState.name);   // undefined
      console.log(userState._W.name);   // sammie (correct)
   }, [])

   return <View></View>
}

</code>```

The problem is first console state return undefined because the userState looks like this

```<code>{
   "_U": 0,
   "_V": 1,
   "_W": {
      "name": "sammie",
      "email": "sammie@test.com",
      "phone": "123123123"
   },
   "_X": 0,
}
</code>```

Expected value is

```<code>{
   "_U": 0,
   "_V": 0,
   "_W": 0,
   "_X": 0,
   "name": "sammie",
   "email": "sammie@test.com",
   "phone": "123123123"
}
</code>```

I tried with other state for the test. and when I set the state in useEffect hook like below, it returns like as above.

```<code>   useEffect ( () => {
      storeTheme('light')(themeDispatch);   // store the light mode to the global theme state
   }, [])
</code>```

This theme state's data structure did not changed like as above.
I am absolutely wired about this. Please give me some advice what I am wrong.

Thanks for any advise.

答:
const [userState, userDispatch] = useReducer(
   user, userInitialState,
   async () => {
      const storedUserData = await AsyncStorage.getItem('user');
      console.log(storedUserData);
      return storedUserData != null ? JSON.parse(storedUserData) : userInitialState;
   },
);```

Try logging the same as above and check the output. I feel like maybe the api team sent you the object this way.

Body:
I am using Context/Asyncstorage for state management.
I store the data which returned from server to the Asyncstorage.

getData.then(
    res => AsyncStorage.setItem('user', JSON.stringify(res.data))
)

And I set the global state named user in Global provider like below.

const [userState, userDispatch] = useReducer(
   user, userInitialState,
   async () => {
      const storedUserData = await AsyncStorage.getItem('user');
      return storedUserData != null ? JSON.parse(storedUserData) : userInitialState;
   },
);

and Here is get the userState on other component

const SomeComponent = () => {
   const {userState} = useContext(GlobalContext);

   useEffect ( () => {
      console.log(userState.name);   // undefined
      console.log(userState._W.name);   // sammie (correct)
   }, [])

   return <View></View>
}

The problem is first console state return undefined because the userState looks like this

{
   "_U": 0,
   "_V": 1,
   "_W": {
      "name": "sammie",
      "email": "sammie@test.com",
      "phone": "123123123"
   },
   "_X": 0,
}

Expected value is

{
   "_U": 0,
   "_V": 0,
   "_W": 0,
   "_X": 0,
   "name": "sammie",
   "email": "sammie@test.com",
   "phone": "123123123"
}

I tried with other state for the test. and when I set the state in useEffect hook like below, it returns like as above.

   useEffect ( () => {
      storeTheme('light')(themeDispatch);   // store the light mode to the global theme state
   }, [])

This theme state's data structure did not changed like as above.
I am absolutely wired about this. Please give me some advice what I am wrong.

Thanks for any advise.

Body:
const [userState, userDispatch] = useReducer(
   user, userInitialState,
   async () => {
      const storedUserData = await AsyncStorage.getItem('user');
      console.log(storedUserData);
      return storedUserData != null ? JSON.parse(storedUserData) : userInitialState;
   },
);

Try logging the same as above and check the output. I feel like maybe the api team sent you the object this way.


问:
How do I map http_path in zipkin to AWS XRay request URL
I send my traces to Zipkin and I can tell I am setting the HTTP Path

But it does not map to XRay's Request URL.

Where can I do the mapping?

I am using the following images as per my answer on integrating Spring Cloud Sleuth with Amazon X-Ray

amazon/aws-xray-daemon:latest

ghcr.io/openzipkin/zipkin-aws:latest

Looking through the code, I am using HttpTracing from ZipKin brave libraries I am presuming that's what it is using to populate the data.

Digging around some more there seems to be an openzipkin/zipkin-aws#58 which sort of describes the issue

答:
Looking through the code I may just need to alter the default tracing to add the additional details.  Adding the following bean will make it configure to contain the necessary details.</p>
```<code>@Bean
public HttpTracing httpTracing(Tracing tracing) {

    return HttpTracing.newBuilder(tracing)
        .serverRequestParser(
            (req, context, span) -> {
                HttpRequestParser.DEFAULT.parse(req, context, span);
                HttpTags.URL.tag(req, context, span);
            }
        )
        .serverResponseParser(
            ((response, context, span) -> {
                HttpResponseParser.DEFAULT.parse(response, context, span);
                HttpTags.STATUS_CODE.tag(response, span);
            })
        )
        .clientRequestParser(
            (req, context, span) -> {
                HttpRequestParser.DEFAULT.parse(req, context, span);
                HttpTags.URL.tag(req, context, span); // add the url in addition to defaults
            }
        )
        .clientResponseParser(
            ((response, context, span) -> {
                HttpResponseParser.DEFAULT.parse(response, context, span);
                HttpTags.STATUS_CODE.tag(response, span);
            })
        )
        .build();

}
</code>```

Body:
Looking through the code I may just need to alter the default tracing to add the additional details.  Adding the following bean will make it configure to contain the necessary details.

@Bean
public HttpTracing httpTracing(Tracing tracing) {

    return HttpTracing.newBuilder(tracing)
        .serverRequestParser(
            (req, context, span) -> {
                HttpRequestParser.DEFAULT.parse(req, context, span);
                HttpTags.URL.tag(req, context, span);
            }
        )
        .serverResponseParser(
            ((response, context, span) -> {
                HttpResponseParser.DEFAULT.parse(response, context, span);
                HttpTags.STATUS_CODE.tag(response, span);
            })
        )
        .clientRequestParser(
            (req, context, span) -> {
                HttpRequestParser.DEFAULT.parse(req, context, span);
                HttpTags.URL.tag(req, context, span); // add the url in addition to defaults
            }
        )
        .clientResponseParser(
            ((response, context, span) -> {
                HttpResponseParser.DEFAULT.parse(response, context, span);
                HttpTags.STATUS_CODE.tag(response, span);
            })
        )
        .build();

}


问:
How to use let in an HTML template?
I'm trying to do something which should be simple:
I would like to execute a function in an *ngFor. The function returns an object. I would like to set the object in a kind of "let" statement, so I can use its property in the HTML:</p>

```<code><div *ngFor="let productGroup of getproductGroupBySomeVariable(variable)">
            <!-- This is where I need to set a variable with the output of
             the getProductBySomeProperty function-->
      <div *ngLet="'{{getProductBySomeProperty(productGroup.someproperty)}}'
              as  myVar" class="ui-g">
              <!-- Here I want to use and display the properties of the
                object created by the function above-->
            <span>{{myVar.property1}} </span>
            <span>{{myVar.property2}} </span> etc....
      </div>
</div>
</code>```

答:
I'm the author of https://www.npmjs.com/package/ng-let

source code of the directive: https://github.com/nigrosimone/ng-let/blob/main/projects/ng-let/src/lib/ng-let.directive.ts

```<code>import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

interface NgLetContext<T> {
    ngLet: T;
    $implicit: T;
}

@Directive({
    // tslint:disable-next-line: directive-selector
    selector: '[ngLet]'
})
export class NgLetDirective<T> {

    private context: NgLetContext<T | null> = { ngLet: null, $implicit: null };
    private hasView: boolean = false;

    // eslint-disable-next-line no-unused-vars
    constructor(private viewContainer: ViewContainerRef, private templateRef: TemplateRef<NgLetContext<T>>) { }

    @Input()
    set ngLet(value: T) {
        this.context.$implicit = this.context.ngLet = value;
        if (!this.hasView) {
            this.viewContainer.createEmbeddedView(this.templateRef, this.context);
            this.hasView = true;
        }
    }

    /** @internal */
    public static ngLetUseIfTypeGuard: void;

    /**
     * Assert the correct type of the expression bound to the `NgLet` input within the template.
     *
     * The presence of this static field is a signal to the Ivy template type check compiler that
     * when the `NgLet` structural directive renders its template, the type of the expression bound
     * to `NgLet` should be narrowed in some way. For `NgLet`, the binding expression itself is used to
     * narrow its type, which allows the strictNullChecks feature of TypeScript to work with `NgLet`.
     */
    static ngTemplateGuard_ngLet: 'binding';

    /**
     * Asserts the correct type of the context for the template that `NgLet` will render.
     *
     * The presence of this method is a signal to the Ivy template type-check compiler that the
     * `NgLet` structural directive renders its template with a specific context type.
     */
    static ngTemplateContextGuard<T>(dir: NgLetDirective<T>, ctx: any): ctx is NgLetContext<Exclude<T, false | 0 | '' | null | undefined>> {
        return true;
    }
}
</code>```

Usage:

```<code>import { Component } from '@angular/core';
import { defer, Observable, timer } from 'rxjs';

@Component({
  selector: 'app-root',
  template: `
  <ng-container *ngLet="timer$ | async as time"> <!-- single subscription -->
    <div>
      1: {{ time }}
    </div>
    <div>
      2: {{ time }}
    </div>
  </ng-container>
  `,
})
export class AppComponent {
  timer$: Observable<number> = defer(() => timer(3000, 1000));
}
</code>```

Title: How to use let in an HTML template?

Body:
I'm trying to do something which should be simple:
I would like to execute a function in an *ngFor. The function returns an object. I would like to set the object in a kind of "let" statement, so I can use its property in the HTML:

            {{myVar.property1}}
            {{myVar.property2}}  etc....

Body:
I'm the author of https://www.npmjs.com/package/ng-let

source code of the directive: https://github.com/nigrosimone/ng-let/blob/main/projects/ng-let/src/lib/ng-let.directive.ts

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

interface NgLetContext<T> {
    ngLet: T;
    $implicit: T;
}

@Directive({
    // tslint:disable-next-line: directive-selector
    selector: '[ngLet]'
})
export class NgLetDirective<T> {

    private context: NgLetContext<T | null> = { ngLet: null, $implicit: null };
    private hasView: boolean = false;

    // eslint-disable-next-line no-unused-vars
    constructor(private viewContainer: ViewContainerRef, private templateRef: TemplateRef<NgLetContext<T>>) { }

    @Input()
    set ngLet(value: T) {
        this.context.$implicit = this.context.ngLet = value;
        if (!this.hasView) {
            this.viewContainer.createEmbeddedView(this.templateRef, this.context);
            this.hasView = true;
        }
    }

    /** @internal */
    public static ngLetUseIfTypeGuard: void;

    /**
     * Assert the correct type of the expression bound to the `NgLet` input within the template.
     *
     * The presence of this static field is a signal to the Ivy template type check compiler that
     * when the `NgLet` structural directive renders its template, the type of the expression bound
     * to `NgLet` should be narrowed in some way. For `NgLet`, the binding expression itself is used to
     * narrow its type, which allows the strictNullChecks feature of TypeScript to work with `NgLet`.
     */
    static ngTemplateGuard_ngLet: 'binding';

    /**
     * Asserts the correct type of the context for the template that `NgLet` will render.
     *
     * The presence of this method is a signal to the Ivy template type-check compiler that the
     * `NgLet` structural directive renders its template with a specific context type.
     */
    static ngTemplateContextGuard<T>(dir: NgLetDirective<T>, ctx: any): ctx is NgLetContext<Exclude<T, false | 0 | '' | null | undefined>> {
        return true;
    }
}

Usage:

import { Component } from '@angular/core';
import { defer, Observable, timer } from 'rxjs';

@Component({
  selector: 'app-root',
  template: `
  <ng-container *ngLet="timer$ | async as time"> <!-- single subscription -->
    <div>
      1: {{ time }}
    </div>
    <div>
      2: {{ time }}
    </div>
  </ng-container>
  `,
})
export class AppComponent {
  timer$: Observable<number> = defer(() => timer(3000, 1000));
}


问:
React Router V6 - Redirect inside Route Component
I have the following code from the V5 Documentation:

```<code>    <Route exact path="/">
      {loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
    </Route>
</code>```

I know that I have Navigate instead of Redirect in V6, but Navigate seems not to work the exact same way:

```<code>    <Route></Route>
      {loggedIn ? <Navigate to="/dashboard" /> : <PublicHomePage />}
    </Route>

Uncaught Error: [Navigate] is not a <Route> component.
</code>```

How can I archieve this with React Router V6?

答:
V5

```<code><Route exact path="/">
  ...
</Route>
</code>```

V6

```<code><Route path="/" element={...}/>
</code>```

Body:
I have the following code from the V5 Documentation:

    <Route exact path="/">
      {loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
    </Route>

I know that I have Navigate instead of Redirect in V6, but Navigate seems not to work the exact same way:

    <Route></Route>
      {loggedIn ? <Navigate to="/dashboard" /> : <PublicHomePage />}
    </Route>

Uncaught Error: [Navigate] is not a <Route> component.

How can I archieve this with React Router V6?

Body:
V5

<Route exact path="/">
  ...
</Route>

V6

<Route path="/" element={...}/>


答:
In react-router v6 <Route> it's the only component that's able to be child of <Routes>:

So change this logic:

```<code><Route>
    {loggedIn ? <Navigate to="/dashboard" /> : <PublicHomePage />}
</Route>
</code>```

to this:

```<code><Route path="/" element={loggedIn ? <Navigate to="/dashboard" /> : PublicHomePage}
</code>```

You can also checkout this article: Private Route in react-router v6

Title: React Router V6 - Redirect inside Route Component

Body:
In react-router v6 <Route> it's the only component that's able to be child of <Routes>:

So change this logic:

<Route>
    {loggedIn ? <Navigate to="/dashboard" /> : <PublicHomePage />}
</Route>

to this:

<Route path="/" element={loggedIn ? <Navigate to="/dashboard" /> : PublicHomePage}

You can also checkout this article: Private Route in react-router v6


问:
How many users and push messages can MQTT handle or RSMB can handle?
Right now i am doing an RnD about push for Android and first i am working on:
MQTT using RSMB

question is for how many clients can it handle? i heard only 1032, in that case this is not good for my app. (if it is configurable how?)

after this ill dive into C2DM.

答:
There are different ways of scaling an MQTT-based infrastructure and the bridging model is important.

RSMB is an IBM alphaWorks technology and does not provide a license for production use. The production / supported version, IBM WebSphere MQ Telemetry Daemon for Devices, is considerably more scalable (the IBM performance reports for WMQ Telemetry on Linux demonstrate at least 100,000 concurrently-connected clients sending 256 byte messages see http://www-01.ibm.com/support/docview.wss?uid=swg24027711).


问:
How do I factor out a unit conversion in python
If there is an answer somewhere else, please just link it. I looked for hours.

Problem

Write a function so that the main program below can be replaced by the simpler code that calls function mph_and_minutes_to_miles(). Original main program:

```<code>miles_per_hour = float(input())
minutes_traveled = float(input())
hours_traveled = minutes_traveled / 60.0
miles_traveled = hours_traveled * miles_per_hour

print('Miles: {:f}'.format(miles_traveled))
</code>```

Sample output with inputs: 70.0 100.0
Miles: 116.666667

MY CODE

```<code>def mph_and_minutes_to_miles(miles_per_hour, minutes_traveled):
    miles_per_hour = float(input())
    hours_traveled = minutes_traveled / 60
    miles_traveled = hours_traveled * miles_per_hour
    return hours_traveled

miles_per_hour = float(input())
minutes_traveled = float(input())

print('Miles: {:f}'.format(mph_and_minutes_to_miles(miles_per_hour, minutes_traveled)))
</code>```

OUTPUTS

Testing with inputs: 70.0 100.0

Output differs. See highlights below.

Your output
Miles: 1.666667

Expected output
Miles: 116.666667

答:
```<code>def mph_and_minutes_to_miles(miles_per_hour, minutes_traveled):
    hours_traveled = minutes_traveled / 60
    return hours_traveled * miles_per_hour

miles_per_hour = float(input())
minutes_traveled = float(input())

print('Miles: {:f}'.format(mph_and_minutes_to_miles(miles_per_hour, minutes_traveled)))
</code>```

Body:
If there is an answer somewhere else, please just link it. I looked for hours.

Problem

Write a function so that the main program below can be replaced by the simpler code that calls function mph_and_minutes_to_miles(). Original main program:

miles_per_hour = float(input())
minutes_traveled = float(input())
hours_traveled = minutes_traveled / 60.0
miles_traveled = hours_traveled * miles_per_hour

print('Miles: {:f}'.format(miles_traveled))

Sample output with inputs: 70.0 100.0
Miles: 116.666667

MY CODE

def mph_and_minutes_to_miles(miles_per_hour, minutes_traveled):
    miles_per_hour = float(input())
    hours_traveled = minutes_traveled / 60
    miles_traveled = hours_traveled * miles_per_hour
    return hours_traveled

miles_per_hour = float(input())
minutes_traveled = float(input())

print('Miles: {:f}'.format(mph_and_minutes_to_miles(miles_per_hour, minutes_traveled)))

OUTPUTS

Testing with inputs: 70.0 100.0

Output differs. See highlights below.

Your output
Miles: 1.666667

Expected output
Miles: 116.666667


问:
Tkinter, ignore certain lines from a tcl file?
Basically, I just want to remove the mouse scrollwheel binding for scrolling in ttk.Treeview widget. And I found that a specific line in the file found in

```<code>Python.framework/Versions/3.9/lib/tk8.6/ttk/treeview.tcl
</code>```

is responsible for it, that if removed, disables the mouse scrollwheel for scrolling the view:

```<code>ttk::copyBindings TtkScrollable Treeview
</code>```

However, I don't want to affect the built-in files.
My only solution was to create py2app bundle and delete the same line from the treeview.tcl inside the bundle. But is there a direct way to do this inside a script.py file without affecting the tcl file?

答:
You don't have to modify the original code. Tkinter's event handling mechanism is very robust. It's easy to prevent the default bindings from running, bind binding a function that returns the string "break". Returning "break" will prevent any other handlers in the widget's binding tags from being invoked.

Here's a short contrived example:

```<code>import tkinter as tk
from tkinter import ttk

root = tk.Tk()

tree = ttk.Treeview(root)
tree.pack(side="top", fill="both", expand=True)
for i in range(20):
    tree.insert("", "end", text=f"Item #{i+1}")

tree.bind("<MouseWheel>", lambda event: "break")
root.mainloop()
</code>```

Note if you're on an x11 based system you might have to disable the bindings for <Button-4> and <Button-5> instead of <MouseWheel>.

Body:
Basically, I just want to remove the mouse scrollwheel binding for scrolling in ttk.Treeview widget. And I found that a specific line in the file found in

Python.framework/Versions/3.9/lib/tk8.6/ttk/treeview.tcl

is responsible for it, that if removed, disables the mouse scrollwheel for scrolling the view:

ttk::copyBindings TtkScrollable Treeview

However, I don't want to affect the built-in files.
My only solution was to create py2app bundle and delete the same line from the treeview.tcl inside the bundle. But is there a direct way to do this inside a script.py file without affecting the tcl file?

Body:
You don't have to modify the original code. Tkinter's event handling mechanism is very robust. It's easy to prevent the default bindings from running, bind binding a function that returns the string "break". Returning "break" will prevent any other handlers in the widget's binding tags from being invoked.

Here's a short contrived example:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

tree = ttk.Treeview(root)
tree.pack(side="top", fill="both", expand=True)
for i in range(20):
    tree.insert("", "end", text=f"Item #{i+1}")

tree.bind("<MouseWheel>", lambda event: "break")
root.mainloop()

Note if you're on an x11 based system you might have to disable the bindings for <Button-4> and <Button-5> instead of <MouseWheel>.


问:
Apache error: AH01276: Cannot serve directory /var/www/html/: No matching Directory
I'm using Centos7, Apache, and Laravel 5.8.
I have made a vHost using apache, and place the Laravel direcoty:
The directory was exist and permitable.
This is the vHost configuration.

```<code><VirtualHost segara.id:80>
    ServerName segara.id
    ServerAlias segara.id
    DocumentRoot /var/www/html/live/segara/public

    <Directory /var/www/html/live/segara/public>
        DirectoryIndex index.html index.php
        Options Indexes FollowSymLinks Includes ExecCGI
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog "| /usr/sbin/rotatelogs -l -n 5 /var/www/html/live/segara/storage/logs/http/http-errors.log 86400"
    CustomLog "| /usr/sbin/rotatelogs -l -n 5 /var/www/html/live/segara/storage/logs/http/http-requests.log 86400" combined

</VirtualHost>
</code>```

The problem was:
When I accessed segara.id, the web display as Apache Tesing 123

What should I do?

Thanks

答:
If in your server only serving one web,
I think you can try to change your config on:

```<code><VirtualHost segara.id:80>
</code>```

to be:

```<code><VirtualHost *:80>
</code>```

Then try again

CMIIW

Thank you

Body:
I'm using Centos7, Apache, and Laravel 5.8.
I have made a vHost using apache, and place the Laravel direcoty:
The directory was exist and permitable.
This is the vHost configuration.

<VirtualHost segara.id:80>
    ServerName segara.id
    ServerAlias segara.id
    DocumentRoot /var/www/html/live/segara/public

    <Directory /var/www/html/live/segara/public>
        DirectoryIndex index.html index.php
        Options Indexes FollowSymLinks Includes ExecCGI
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog "| /usr/sbin/rotatelogs -l -n 5 /var/www/html/live/segara/storage/logs/http/http-errors.log 86400"
    CustomLog "| /usr/sbin/rotatelogs -l -n 5 /var/www/html/live/segara/storage/logs/http/http-requests.log 86400" combined

</VirtualHost>

The problem was:
When I accessed segara.id, the web display as Apache Tesing 123

What should I do?

Thanks

Body:
If in your server only serving one web,
I think you can try to change your config on:

<VirtualHost segara.id:80>

to be:

<VirtualHost *:80>

Then try again

CMIIW

Thank you


问:
git cherry-pick a commit, the commit updated later, how to get latest
I cherry-pick a commit from another person's branch. Later the user updated his commit(maybe by squash), so the commit SHA changed. How do I cherry-pick to get latest commit?</p>

答:
Like most things in Git, there are many different ways to accomplish this. Yet there are multiple factors that could change the answer, including the current state of your branch, what you wish your branch to look like afterwards.

Based on larsks' suggestion:

You could git reset your repository to before you cherry-picked the earlier version of the commit, then just cherry-pick the new version.

And your response:

yeah that's a workaround. I'm wondering if there is way that doesn't require rebase, drop commit.

I'm going to assume you have more commits after the commit you already cherry-picked, otherwise you would simply do larsks' suggestion as written. In this case perhaps the simplest solution is to revert the original and repick the new one:

```<code>git revert <commit-id-on-your-branch-of-original-cherry-picked-commit>
git cherry-pick <new-id-of-commit-on-other-branch>
</code>```

Now you might be done, or if you're willing to rewrite your branch you could interactive rebase and squash those 2 new commits up into the previous cherry-picked commit. This would preserve your original order.

Along the same lines, but without requiring an interactive rebase, you could also do:

```<code># Assumptions:
#   Your current branch: "my-branch"
#   Original cherry-picked commit on your branch: <picked-commit-id>
#   New commit to cherry-pick from other branch <new-commit-id-to-pick>

# setup
git switch my-branch # checkout your branch
git branch my-branch-copy # make a temporary copy of your branch

# rebuild your branch
git reset --hard <picked-commit-id>~1 # reset to commit before the picked commit
git cherry-pick <new-commit-id-to-pick>
git cherry-pick <picked-commit-id>..my-branch-copy # rewrite your branch
</code>```

Body:
Like most things in Git, there are many different ways to accomplish this. Yet there are multiple factors that could change the answer, including the current state of your branch, what you wish your branch to look like afterwards.

Based on larsks' suggestion:

You could git reset your repository to before you cherry-picked the earlier version of the commit, then just cherry-pick the new version.

And your response:

yeah that's a workaround. I'm wondering if there is way that doesn't require rebase, drop commit.

I'm going to assume you have more commits after the commit you already cherry-picked, otherwise you would simply do larsks' suggestion as written. In this case perhaps the simplest solution is to revert the original and repick the new one:

git revert <commit-id-on-your-branch-of-original-cherry-picked-commit>
git cherry-pick <new-id-of-commit-on-other-branch>

Now you might be done, or if you're willing to rewrite your branch you could interactive rebase and squash those 2 new commits up into the previous cherry-picked commit. This would preserve your original order.

Along the same lines, but without requiring an interactive rebase, you could also do:

# Assumptions:
#   Your current branch: "my-branch"
#   Original cherry-picked commit on your branch: <picked-commit-id>
#   New commit to cherry-pick from other branch <new-commit-id-to-pick>

# setup
git switch my-branch # checkout your branch
git branch my-branch-copy # make a temporary copy of your branch

# rebuild your branch
git reset --hard <picked-commit-id>~1 # reset to commit before the picked commit
git cherry-pick <new-commit-id-to-pick>
git cherry-pick <picked-commit-id>..my-branch-copy # rewrite your branch