问:
Debug Word VSTO Add-In: Debug Word doc as though it were opened by double-clicking it in explorer
I have a Word VSTO add-in. A tester found a bug that occurs only when the Word document is opened by double-clicking it in Windows File Explorer.

I know how to bring up Word and attach Visual Studio debugger to it afterward.

I know how to use Visual Studio debug settings to start explorer.exe as an external program and have it display its dialog with a specific docx file selected.

I can't figure out how to set up Visual Studio to attach to a Word process that will be running only after I simulate double-clicking a Word doc displayed by explorer.exe

How do I use Visual Studio debug settings to open a Word docx file as though it were double-clicked in the dialog displayed by explorer.exe and then attach to the resultant Word process?

Clarification added: I need my VS debugger to be active at the point in time when the "double-click" opens the Word doc in Word so I can debug code starting with event handlers that are fired right as the doc is opened, e.g., window activate, doc open.

答:
Use the Debugger.Launch method which launches and attaches a debugger to the process in the code of your add-in where you would like to get the debugger to be attached. If a debugger is already attached, nothing happens.

You may find the Attach to running processes with the Visual Studio debugger article helpful.


来源: stackexchange

问:
How to install Laravel Vite?
The Laravel Vite Doc sais to run:

```<code>npx apply laravel:vite --ignore-existing
</code>```

inside your project root to install vite in your laravel project.

When I try to do that in a freshly installed laravel project it shows this:

```<code>zsh:1: command not found: laravel:vite
</code>```

What am I doing wrong?

Using Macos Big Sur with PhpStorm.

答:
That command no longer applies to newly created projects (as of laravel-vite 0.1.27, released a few days ago), and it now results in a different error:

$ npx apply laravel:vite --ignore-existing
[ info ]  Applying preset laravel:vite.
[ error ]  The preset could not be evaluated.
evalmachine.<anonymous>:13
var preset_default = definePreset({
                     ^

ReferenceError: definePreset is not defined
    at evalmachine.<anonymous>:13:22
    at Script.runInContext (node:vm:139:12)
    at Object.runInContext (node:vm:289:6)
    at ModuleImporter.evaluateConfiguration (/Users/tony/src/laravel-vite-demo/example-app/node_modules/apply/dist/Importer/ModuleImporter.js:68:26)
    at ModuleImporter.import (/Users/tony/src/laravel-vite-demo/example-app/node_modules/apply/dist/Importer/ModuleImporter.js:17:27)
    at PresetApplier.run (/Users/tony/src/laravel-vite-demo/example-app/node_modules/apply/dist/Applier/PresetApplier.js:22:87)
    at async CommandLineInterface.apply (/Users/tony/src/laravel-vite-demo/example-app/node_modules/apply/dist/IO/CommandLineInterface.js:57:16)
    at async CommandLineInterface.run (/Users/tony/src/laravel-vite-demo/example-app/node_modules/apply/dist/IO/CommandLineInterface.js:54:16)
```
<p>However, the command shown in the <code>laravel-presets/vite</code> repository (the source repo for the <code>laravel:vite</code> preset) worked for me -- i.e., it augmented the Laravel project with Vite:</p>
<pre class="lang-sh prettyprint-override"><code># Run this command from root of Laravel project
npx @preset/cli apply --debug laravel:vite
</code>```

@preset/cli currently suppresses all output (including errors), so the --debug flag above is important. Since the verbose log is difficult to follow, I recommend redirecting the output to a file, and searching it for the word exception.

Tips

To ensure the preset succeeds, you must have php@8.0 (e.g., from Homebrew) and composer installed and available from the command line. Add the paths to those binaries to your PATH environment variable.

The Vite server must be started separately from the PHP server. Run npm run dev in one terminal; and php artisan serve from another.

ContentLicense: CC BY-SA 4.0

Title: How to install Laravel Vite?

Body:
The Laravel Vite Doc sais to run:

npx apply laravel:vite --ignore-existing

inside your project root to install vite in your laravel project.

When I try to do that in a freshly installed laravel project it shows this:

zsh:1: command not found: laravel:vite

What am I doing wrong?

Using Macos Big Sur with PhpStorm.

Body:
That command no longer applies to newly created projects (as of laravel-vite 0.1.27, released a few days ago), and it now results in a different error:

$ npx apply laravel:vite --ignore-existing
[ info ]  Applying preset laravel:vite.
[ error ]  The preset could not be evaluated.
evalmachine.<anonymous>:13
var preset_default = definePreset({
                     ^

ReferenceError: definePreset is not defined
    at evalmachine.<anonymous>:13:22
    at Script.runInContext (node:vm:139:12)
    at Object.runInContext (node:vm:289:6)
    at ModuleImporter.evaluateConfiguration (/Users/tony/src/laravel-vite-demo/example-app/node_modules/apply/dist/Importer/ModuleImporter.js:68:26)
    at ModuleImporter.import (/Users/tony/src/laravel-vite-demo/example-app/node_modules/apply/dist/Importer/ModuleImporter.js:17:27)
    at PresetApplier.run (/Users/tony/src/laravel-vite-demo/example-app/node_modules/apply/dist/Applier/PresetApplier.js:22:87)
    at async CommandLineInterface.apply (/Users/tony/src/laravel-vite-demo/example-app/node_modules/apply/dist/IO/CommandLineInterface.js:57:16)
    at async CommandLineInterface.run (/Users/tony/src/laravel-vite-demo/example-app/node_modules/apply/dist/IO/CommandLineInterface.js:54:16)

However, the command shown in the laravel-presets/vite repository (the source repo for the laravel:vite preset) worked for me -- i.e., it augmented the Laravel project with Vite:

# Run this command from root of Laravel project
npx @preset/cli apply --debug laravel:vite

@preset/cli currently suppresses all output (including errors), so the --debug flag above is important. Since the verbose log is difficult to follow, I recommend redirecting the output to a file, and searching it for the word exception.

Tips

To ensure the preset succeeds, you must have php@8.0 (e.g., from Homebrew) and composer installed and available from the command line. Add the paths to those binaries to your PATH environment variable.

The Vite server must be started separately from the PHP server. Run npm run dev in one terminal; and php artisan serve from another.


问:
validators for bulk image upload
I have a feature that allows users to upload multiple images. I want to setup a validator to only allow images that are under 3MB.

```<code>def validate_image_bulk(images):

    file_size = images.file.size
    if file_size > settings.MAX_UPLOAD_SIZE:
        raise ValidationError(f'Cover Image {images} is too large 3mb max')
</code>```

How can I get a list of the images being uploaded and validate them at the same time. In a view I could do something like request.FILES.getlist('images') is there something similar like this?

答:
crate an validator.py inside your app:

validator.py

```<code>from django.core.exceptions import ValidationError

def validate_file_size(value):
    filesize = value.size

    if filesize > 3145728:  #3 * 1024 * 1024
       raise ValidationError('The maximum file size that can be uploaded is 3MB')
    else:
      return value
</code>```

your models.py

```<code>from .validator import *
from django.core.validators import FileExtensionValidator #if you also want to use file type Validator

class mymodel(models.Model)
      image = models.ImageField(upload_to='blog/images/',validators=[validate_file_size,FileExtensionValidator( ['png','jpg'] )],blank=True,null=True) #only accept 'png' and 'jpg' image.
</code>```

You can check django documentation for FileExtensionValidator

Title: validators for bulk image upload

Body:
I have a feature that allows users to upload multiple images. I want to setup a validator to only allow images that are under 3MB.

def validate_image_bulk(images):

    file_size = images.file.size
    if file_size > settings.MAX_UPLOAD_SIZE:
        raise ValidationError(f'Cover Image {images} is too large 3mb max')

How can I get a list of the images being uploaded and validate them at the same time. In a view I could do something like request.FILES.getlist('images') is there something similar like this?

Body:
crate an validator.py inside your app:

validator.py

from django.core.exceptions import ValidationError

def validate_file_size(value):
    filesize = value.size

    if filesize > 3145728:  #3 * 1024 * 1024
       raise ValidationError('The maximum file size that can be uploaded is 3MB')
    else:
      return value

your models.py

from .validator import *
from django.core.validators import FileExtensionValidator #if you also want to use file type Validator

class mymodel(models.Model)
      image = models.ImageField(upload_to='blog/images/',validators=[validate_file_size,FileExtensionValidator( ['png','jpg'] )],blank=True,null=True) #only accept 'png' and 'jpg' image.

You can check django documentation for FileExtensionValidator


问:
Search in php from dat file
I'm trying to Search my orderid, This is my code so far:

```<code><?php
$file = 'order.dat';
$searchfor = '177';

// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');

// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
   echo "Found matches:\n";
   echo implode("\n", $matches[0]);
}
else{
   echo "No matches found";
}
</code>```

now for example my order.dat file contains the data

```<code>175|RC456456456|54156456465|109$

176|RC456456456|54156456465|177$

177|RC456456456|54156456465|129$

178|RC456456456|54156456465|129$
</code>```

now when i searchfor 177 i have an result like this:-

```<code>Found matches:
176|RC456456456|54156456465|177$
177|RC456456456|54156456465|129$
</code>```

But i want to search 177 for my 1st string only

I want my result like this, its only match my 1st string not on all 4 variables

```<code>177|RC456456456|54156456465|129$
</code>```

答:
Looks like you want to match only those string that begin with 177. If yes you can change your regex to:

```<code>$pattern = "/^$pattern.*$/m";
</code>```

ContentLicense: CC BY-SA 3.0

Title: Search in php from dat file

Body:
I'm trying to Search my orderid, This is my code so far:

<?php
$file = 'order.dat';
$searchfor = '177';

// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');

// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
   echo "Found matches:\n";
   echo implode("\n", $matches[0]);
}
else{
   echo "No matches found";
}

now for example my order.dat file contains the data

175|RC456456456|54156456465|109$

176|RC456456456|54156456465|177$

177|RC456456456|54156456465|129$

178|RC456456456|54156456465|129$

now when i searchfor 177 i have an result like this:-

Found matches:
176|RC456456456|54156456465|177$
177|RC456456456|54156456465|129$

But i want to search 177 for my 1st string only

I want my result like this, its only match my 1st string not on all 4 variables

177|RC456456456|54156456465|129$

Body:
Looks like you want to match only those string that begin with 177. If yes you can change your regex to:

$pattern = "/^$pattern.*$/m";


问:
Sort dict by multiple keys and with int and None data in python
so I have a dict :

```<code>marker_dict[experiment_id] = {'SM0012AQ': { 'chromosome' : 1, 'linkageGroup':8, 'positionCm' : 45,'qualityStatus' : 'A' },
 'SM0075AQ': { 'chromosome' : 1, 'linkageGroup': 7, 'positionCm' : ,'qualityStatus' : 'A' },
'SM0078BQ': { 'chromosome' : 3, 'linkageGroup': 78, 'positionCm' : 7,'qualityStatus' : 'B' },
'SM0079PQ': { 'chromosome' : 4, 'linkageGroup': , 'positionCm' : 80,'qualityStatus' : 'B' },
'SM0080BQ': { 'chromosome' : , 'linkageGroup': 78, 'positionCm' : 447,'qualityStatus' : 'T' }}
</code>```

I want to sort my dict on 'i.chromosome', 'i.linkageGroup' and 'i.positionCm'

What I am doing :

```<code>marker_list = sorted(marker_dict[experiment_id].values(), key=lambda i: (i.chromosome, i.linkageGroup, i.positionCm))
</code>```

And i got :

```<code>TypeError: '<' not supported between instances of 'Nonetype' and 'int'
</code>```

In python 2, they were doing :

```<code>markerList=sorted(markerDic.values(), key=operator.attrgetter('chromosome','linkageGroup','positionCm'))
</code>```

Could you help me please, I am lost !

答:
Given

t = {'SM0012AQ': { 'chromosome' : 1, 'linkageGroup':8, 'positionCm' : 45,'qualityStatus' : 'A' },
    'SM0075AQ': { 'chromosome' : 1, 'linkageGroup': 7, 'positionCm' : None ,'qualityStatus' : 'A' },
    'SM0078BQ': { 'chromosome' : 3, 'linkageGroup': 78, 'positionCm' : 7,'qualityStatus' : 'B' },
    'SM0079PQ': { 'chromosome' : 4, 'linkageGroup': None, 'positionCm' : 80,'qualityStatus' : 'B' },
    'SM0080BQ': { 'chromosome' : None, 'linkageGroup': 78, 'positionCm' : 447,'qualityStatus' : 'T' }}
```
<p>and the requirement that <code>None</code>s are for <code>int</code>, you can solve it using</p>
<pre class="lang-py prettyprint-override"><code>dict(sorted(t.items(), key=lambda i: (i[1]['chromosome'] if i[1]['chromosome'] is not None else -1, i[1]['linkageGroup'] if i[1]['linkageGroup'] is not None else -1 , i[1]['positionCm'] if i[1]['positionCm'] is not None else -1)))
</code>```

where I've made the assumption that the numbers you have are 0 or positive. If you can also have negatives you need to change the -1 to a very large negative number.

The result:

```<code>{'SM0080BQ': {'chromosome': None,
  'linkageGroup': 78,
  'positionCm': 447,
  'qualityStatus': 'T'},
 'SM0075AQ': {'chromosome': 1,
  'linkageGroup': 7,
  'positionCm': None,
  'qualityStatus': 'A'},
 'SM0012AQ': {'chromosome': 1,
  'linkageGroup': 8,
  'positionCm': 45,
  'qualityStatus': 'A'},
 'SM0078BQ': {'chromosome': 3,
  'linkageGroup': 78,
  'positionCm': 7,
  'qualityStatus': 'B'},
 'SM0079PQ': {'chromosome': 4,
  'linkageGroup': None,
  'positionCm': 80,
  'qualityStatus': 'B'}}
</code>```

Body:
so I have a dict :

marker_dict[experiment_id] = {'SM0012AQ': { 'chromosome' : 1, 'linkageGroup':8, 'positionCm' : 45,'qualityStatus' : 'A' },
 'SM0075AQ': { 'chromosome' : 1, 'linkageGroup': 7, 'positionCm' : ,'qualityStatus' : 'A' },
'SM0078BQ': { 'chromosome' : 3, 'linkageGroup': 78, 'positionCm' : 7,'qualityStatus' : 'B' },
'SM0079PQ': { 'chromosome' : 4, 'linkageGroup': , 'positionCm' : 80,'qualityStatus' : 'B' },
'SM0080BQ': { 'chromosome' : , 'linkageGroup': 78, 'positionCm' : 447,'qualityStatus' : 'T' }}

I want to sort my dict on 'i.chromosome', 'i.linkageGroup' and 'i.positionCm'

What I am doing :

marker_list = sorted(marker_dict[experiment_id].values(), key=lambda i: (i.chromosome, i.linkageGroup, i.positionCm))

And i got :

TypeError: '<' not supported between instances of 'Nonetype' and 'int'

In python 2, they were doing :

markerList=sorted(markerDic.values(), key=operator.attrgetter('chromosome','linkageGroup','positionCm'))

Could you help me please, I am lost !

Body:
Given

t = {'SM0012AQ': { 'chromosome' : 1, 'linkageGroup':8, 'positionCm' : 45,'qualityStatus' : 'A' },
    'SM0075AQ': { 'chromosome' : 1, 'linkageGroup': 7, 'positionCm' : None ,'qualityStatus' : 'A' },
    'SM0078BQ': { 'chromosome' : 3, 'linkageGroup': 78, 'positionCm' : 7,'qualityStatus' : 'B' },
    'SM0079PQ': { 'chromosome' : 4, 'linkageGroup': None, 'positionCm' : 80,'qualityStatus' : 'B' },
    'SM0080BQ': { 'chromosome' : None, 'linkageGroup': 78, 'positionCm' : 447,'qualityStatus' : 'T' }}

and the requirement that Nones are for int, you can solve it using

dict(sorted(t.items(), key=lambda i: (i[1]['chromosome'] if i[1]['chromosome'] is not None else -1, i[1]['linkageGroup'] if i[1]['linkageGroup'] is not None else -1 , i[1]['positionCm'] if i[1]['positionCm'] is not None else -1)))

where I've made the assumption that the numbers you have are 0 or positive. If you can also have negatives you need to change the -1 to a very large negative number.

The result:

{'SM0080BQ': {'chromosome': None,
  'linkageGroup': 78,
  'positionCm': 447,
  'qualityStatus': 'T'},
 'SM0075AQ': {'chromosome': 1,
  'linkageGroup': 7,
  'positionCm': None,
  'qualityStatus': 'A'},
 'SM0012AQ': {'chromosome': 1,
  'linkageGroup': 8,
  'positionCm': 45,
  'qualityStatus': 'A'},
 'SM0078BQ': {'chromosome': 3,
  'linkageGroup': 78,
  'positionCm': 7,
  'qualityStatus': 'B'},
 'SM0079PQ': {'chromosome': 4,
  'linkageGroup': None,
  'positionCm': 80,
  'qualityStatus': 'B'}}


问:
How to stop firebase functions from propagating triggers
I have a Firebase function to decrease the commentCount when a comment is deleted, like this

```<code>export const onArticleCommentDeleted = functions.firestore.document('articles/{articleId}/comments/{uid}').onDelete((snapshot, context) => {
    return db.collection('articles').doc(context.params.articleId).update({
        commentCount: admin.firestore.FieldValue.increment(-1)
    })
})
</code>```

I also have firebase functions to recursively delete comments of an article when it's deleted

```<code>export const onArticleDeleted = functions.firestore.document('articles/{id}').onDelete((snapshot, context) => {
    const commentsRef = db.collection('articles').doc(snapshot.id).collection('comments');
    db.recursiveDelete(commentsRef); // this triggers the onArticleCommentDeleted multiple times
})
</code>```

When I delete an article, the onArticleCommentDeleted is triggered and it tries to update the article that has already been deleted. Of course I can check if the article exists before updating it. But it's really cumbersome and waste of resources.

Are there any ways to avoid from propagating further triggers?

答:
I think the problem arises from the way I make use of the trigger. In general, it's not a good idea to implement an onDelete trigger on a child document updates its own parent. This will surely cause conflict.

Instead, at the client side, I use transaction

```<code>...
runTransaction(async trans => {
    trans.delete(commentRef);
    trans.update(articleRef, {
        commentCount: admin.firestore.FieldValue.increment(-1)
    })
})
</code>```

This makes sure that if one of the operation fails they both fail, and eradicates the triggers. Relying to the client side is not the best idea, but I think we can consider the trade off.

Body:
I have a Firebase function to decrease the commentCount when a comment is deleted, like this

export const onArticleCommentDeleted = functions.firestore.document('articles/{articleId}/comments/{uid}').onDelete((snapshot, context) => {
    return db.collection('articles').doc(context.params.articleId).update({
        commentCount: admin.firestore.FieldValue.increment(-1)
    })
})

I also have firebase functions to recursively delete comments of an article when it's deleted

export const onArticleDeleted = functions.firestore.document('articles/{id}').onDelete((snapshot, context) => {
    const commentsRef = db.collection('articles').doc(snapshot.id).collection('comments');
    db.recursiveDelete(commentsRef); // this triggers the onArticleCommentDeleted multiple times
})

When I delete an article, the onArticleCommentDeleted is triggered and it tries to update the article that has already been deleted. Of course I can check if the article exists before updating it. But it's really cumbersome and waste of resources.

Are there any ways to avoid from propagating further triggers?

Body:
I think the problem arises from the way I make use of the trigger. In general, it's not a good idea to implement an onDelete trigger on a child document updates its own parent. This will surely cause conflict.

Instead, at the client side, I use transaction

...
runTransaction(async trans => {
    trans.delete(commentRef);
    trans.update(articleRef, {
        commentCount: admin.firestore.FieldValue.increment(-1)
    })
})

This makes sure that if one of the operation fails they both fail, and eradicates the triggers. Relying to the client side is not the best idea, but I think we can consider the trade off.


问:
Regex match but do not capture with a ".*"
I have two blocks of code.

```<code><TabItem Header="{materialDesign:PackIcon Kind=Bank, Size=24}"
                     Style="{StaticResource MaterialDesignNavigationRailTabItem}"
                     ToolTip="Example">
</code>```

and

```<code><Button Header="{materialDesign:PackIcon Kind=Bank, Size=24}"
                     Style="{StaticResource MaterialDesignNavigationRailTabItem}"
                     ToolTip="Example">
</code>```

I to select the ToolTip="Example" part and replace it. However, I only want to select the ToolTip that is inside the TabItem block. I can select it with:

```<code>ToolTip\=\"(.*?)\"
</code>```

That selects the one in the Button block as well. I used this StackOverflow Question to try and solve my issue, but I could not figure out how to make it work with a ".*".

So my criteria is:

Must begin with '<TabItem'

Must contain 'ToolTip=".*"'

Must end with ">"

Is what I am trying to achieve possible? If so, how could I achieve this?

答:
```<code><TabItem.*?ToolTip="(.*?)">
</code>```

if you use this regex then you will be able to get the value inside the tooltip as a list you can use them in regex with $1 here $1 will be the value inside the first tooltip and $2 will have the second if there is a second match for this regex

Body:
I have two blocks of code.

<TabItem Header="{materialDesign:PackIcon Kind=Bank, Size=24}"
                     Style="{StaticResource MaterialDesignNavigationRailTabItem}"
                     ToolTip="Example">

and

<Button Header="{materialDesign:PackIcon Kind=Bank, Size=24}"
                     Style="{StaticResource MaterialDesignNavigationRailTabItem}"
                     ToolTip="Example">

I to select the ToolTip="Example" part and replace it. However, I only want to select the ToolTip that is inside the TabItem block. I can select it with:

ToolTip\=\"(.*?)\"

That selects the one in the Button block as well. I used this StackOverflow Question to try and solve my issue, but I could not figure out how to make it work with a ".*".

So my criteria is:

Must begin with '<TabItem'

Must contain 'ToolTip=".*"'

Must end with ">"

Is what I am trying to achieve possible? If so, how could I achieve this?

Body:
<TabItem.*?ToolTip="(.*?)">

if you use this regex then you will be able to get the value inside the tooltip as a list you can use them in regex with $1 here $1 will be the value inside the first tooltip and $2 will have the second if there is a second match for this regex


问:
Single Observer created for every unique Symbol
I am working on a .NET Application which is rendering data from a source (say TCP) to excel using the Excel-DNA Library.
I have given example of LtpObserver which I have created by implementing IExcelObservable. I am creating the Observer using a Excel Function Call (Refer Code) --> "GetLtp".
'Data' referred here is containing a List of LtpObservers and Ltp value.

THE PROBLEM -
When I call the formula in Excel using a symbol say 'X', it creates the Observer (verified via Logging), and the data starts updating. Constructor of observer is called, as well as, callback is received on Subscribe() Method. But, when I call the same formula for 'X in another cell, no new Observer is created, neither a call on subscribe is received.
And upon deletion, of formula from just Cell#1, the Dispose is not called. But upon deleting from both Cell#1 and Cell#2 Dispose is called.

So is there just one observer for every unique symbol in the Excel Workbook? In that case does keeping a list of Observers and updating each of them on OnNext() makes sense? And what about the case when 2 or more formulas are used together in a single cell? How does this work Internally

CODE

```<code>class LtpObserver : IExcelObservable
{
    private List<IExcelObserver> _observerList;
    private string _symbol;
    private Timer _timer;

    public LtpObserver(string symbol)
    {
        Trace.TraceInformation("Constructor Called. New Ltp Observer Loaded for Symbol : " + symbol);
        _symbol = symbol;
        _observerList = new List<IExcelObserver>();
        _timer = new Timer();
        _timer.AutoReset = true;
        _timer.Interval = FeedTimerConstant.ltpFrequency;
        _timer.Elapsed += _timer_Elapsed;

    }

    void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        if (Data != null))
        {
            _timer.Stop();
            Data.LtpObserver = _observerList;
            timer_tick(Data.Ltp);

        }
        else
        {
            timer_tick(0);
        }
    }

    public IDisposable Subscribe(IExcelObserver observer)
    {

        Trace.TraceInformation("LTP Subscription for : " + observer.ToString() + " Symbol : " + _symbol);

        _observerList.Add(observer);
        if (Data != null)
        {
            Data.LtpObserver = _observerList;
            timer_tick(Data.Ltp);
        }
        else
        {
            timer_tick(0);
            _timer.Start();
        }

        return new ActionDisposable(() => {
            Trace.TraceInformation("Un Subscribed for LTP Price :" + _symbol);
            _observerList.Remove(observer);
        });
    }

    void timer_tick(object _now)
    {

        foreach (var obs in _observerList)
            obs.OnNext(_now);
    }
}

-----------------------------------------------------------------------------------------------------------

[ExcelFunction(Name = "GetLtp", IsVolatile = true)]
    public static object GetLtp(string symbol)
    {
        if (String.IsNullOrEmpty(symbol))
        {
            return INVALID_SYMBOL;
        }
        return ExcelAsyncUtil.Observe("GetLtp", symbol, () => new LtpObserver(symbol)
        );
    }

-------------------------------------------------------------------------------------------------------------

    public class Data {

    public decimal Ltp { get; set; }
    public List<IExcelObserver> LtpObserver { get; set; }

    }
</code>```

答:
The behaviour you describe is by design. The first two parameters passed to ExcelAsyncUtil.Observe are normally a string with the function name and an object or array of objects that provide a unique identifier for the IObservable stream.

So the part you describe in "THE PROBLEM" is exactly how it is intended to work. For every unique symbol you have a stream of values, and you can use the same values in multiple places on the sheet without a problem - they will be listening to the same underlying stream. If you have multiple different symbols active, you have multiple streams that you update with whatever mechanism, using the OnNext() calls.

In your code you need not make provision for multiple IObservers that Subscribe to your IObservable. But this detail is specific to the way Excel-DNA will call your IObservable. Excel-DNA will only ever Subscribe once to your IObservable. However, if you wanted to use the same IObservable class in other contexts or in another application, this might not hold an you might get multiple Subscribe calls.

(It would also make more sense to rename LtpObserver to LtpObservable.)

You could add extra information to that list to create separate topics according to the calling cell. This code might be something like this:
(I've removed the IsVolatile=true as that doesn't make sense for a streaming function wrapper like this)

    [ExcelFunction(Name = "GetLtp")]
    public static object GetLtp(string symbol)
    {
        if (String.IsNullOrEmpty(symbol))
        {
            return INVALID_SYMBOL;
        }

        var callerReference = XlCall.Excel(XlCall.xlfCaller);
        var identifiers = new object[] { symbol, callerReference };

        return ExcelAsyncUtil.Observe("GetLtp", identifiers, () => new LtpObserver(symbol, callerReference)
        );
    }
```

But now again you have a unique LtpObserver for the combination of symbol and calling cell. And again each such IObservable will only be subscribed to once by Excel-DNA.

Internally this is implemented using Excel's RTD mechanism. Excel can associate one or more RTD topics with a cell. When the topic value changes, Excel will invalidate the relevant cells, and recalculate them. There is some optimisation inside Excel so that this scales well.

Body:
I am working on a .NET Application which is rendering data from a source (say TCP) to excel using the Excel-DNA Library.
I have given example of LtpObserver which I have created by implementing IExcelObservable. I am creating the Observer using a Excel Function Call (Refer Code) --> "GetLtp".
'Data' referred here is containing a List of LtpObservers and Ltp value.

THE PROBLEM -
When I call the formula in Excel using a symbol say 'X', it creates the Observer (verified via Logging), and the data starts updating. Constructor of observer is called, as well as, callback is received on Subscribe() Method. But, when I call the same formula for 'X in another cell, no new Observer is created, neither a call on subscribe is received.
And upon deletion, of formula from just Cell#1, the Dispose is not called. But upon deleting from both Cell#1 and Cell#2 Dispose is called.

So is there just one observer for every unique symbol in the Excel Workbook? In that case does keeping a list of Observers and updating each of them on OnNext() makes sense? And what about the case when 2 or more formulas are used together in a single cell? How does this work Internally

CODE

class LtpObserver : IExcelObservable
{
    private List<IExcelObserver> _observerList;
    private string _symbol;
    private Timer _timer;

    public LtpObserver(string symbol)
    {
        Trace.TraceInformation("Constructor Called. New Ltp Observer Loaded for Symbol : " + symbol);
        _symbol = symbol;
        _observerList = new List<IExcelObserver>();
        _timer = new Timer();
        _timer.AutoReset = true;
        _timer.Interval = FeedTimerConstant.ltpFrequency;
        _timer.Elapsed += _timer_Elapsed;

    }

    void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        if (Data != null))
        {
            _timer.Stop();
            Data.LtpObserver = _observerList;
            timer_tick(Data.Ltp);

        }
        else
        {
            timer_tick(0);
        }
    }

    public IDisposable Subscribe(IExcelObserver observer)
    {

        Trace.TraceInformation("LTP Subscription for : " + observer.ToString() + " Symbol : " + _symbol);

        _observerList.Add(observer);
        if (Data != null)
        {
            Data.LtpObserver = _observerList;
            timer_tick(Data.Ltp);
        }
        else
        {
            timer_tick(0);
            _timer.Start();
        }

        return new ActionDisposable(() => {
            Trace.TraceInformation("Un Subscribed for LTP Price :" + _symbol);
            _observerList.Remove(observer);
        });
    }

    void timer_tick(object _now)
    {

        foreach (var obs in _observerList)
            obs.OnNext(_now);
    }
}

-----------------------------------------------------------------------------------------------------------

[ExcelFunction(Name = "GetLtp", IsVolatile = true)]
    public static object GetLtp(string symbol)
    {
        if (String.IsNullOrEmpty(symbol))
        {
            return INVALID_SYMBOL;
        }
        return ExcelAsyncUtil.Observe("GetLtp", symbol, () => new LtpObserver(symbol)
        );
    }

-------------------------------------------------------------------------------------------------------------

    public class Data {

    public decimal Ltp { get; set; }
    public List<IExcelObserver> LtpObserver { get; set; }

    }

Body:
The behaviour you describe is by design. The first two parameters passed to ExcelAsyncUtil.Observe are normally a string with the function name and an object or array of objects that provide a unique identifier for the IObservable stream.

So the part you describe in "THE PROBLEM" is exactly how it is intended to work. For every unique symbol you have a stream of values, and you can use the same values in multiple places on the sheet without a problem - they will be listening to the same underlying stream. If you have multiple different symbols active, you have multiple streams that you update with whatever mechanism, using the OnNext() calls.

In your code you need not make provision for multiple IObservers that Subscribe to your IObservable. But this detail is specific to the way Excel-DNA will call your IObservable. Excel-DNA will only ever Subscribe once to your IObservable. However, if you wanted to use the same IObservable class in other contexts or in another application, this might not hold an you might get multiple Subscribe calls.

(It would also make more sense to rename LtpObserver to LtpObservable.)

You could add extra information to that list to create separate topics according to the calling cell. This code might be something like this:
(I've removed the IsVolatile=true as that doesn't make sense for a streaming function wrapper like this)

    [ExcelFunction(Name = "GetLtp")]
    public static object GetLtp(string symbol)
    {
        if (String.IsNullOrEmpty(symbol))
        {
            return INVALID_SYMBOL;
        }

        var callerReference = XlCall.Excel(XlCall.xlfCaller);
        var identifiers = new object[] { symbol, callerReference };

        return ExcelAsyncUtil.Observe("GetLtp", identifiers, () => new LtpObserver(symbol, callerReference)
        );
    }

But now again you have a unique LtpObserver for the combination of symbol and calling cell. And again each such IObservable will only be subscribed to once by Excel-DNA.

Internally this is implemented using Excel's RTD mechanism. Excel can associate one or more RTD topics with a cell. When the topic value changes, Excel will invalidate the relevant cells, and recalculate them. There is some optimisation inside Excel so that this scales well.


答:
```<code>$pattern = "/^$pattern/m"; // your string starts (^) with $pattern (177)
                           // and we dont care what it ends with
</code>```

Title: Search in php from dat file


问:
I have a problem with the iteration loop javascript
I have a problem with the repetition of an error. I need to display the hours at 18, 19, 20, 21, 22 with the minutes, but there is a repetition at 18

let CloseTime = 23;
let TheTimeNow = 20;

let mintes = 20;
let LastMinutes = 60;

let resultMintes = [];
let lastResult = [];

for (TheTimeNow; TheTimeNow <= CloseTime; TheTimeNow++) {
  for (mintes; mintes <= LastMinutes; mintes += 5) {
    resultMintes.push(`${TheTimeNow}:${mintes}`);
  }

  lastResult.push(resultMintes);
}

console.log(lastResult);```

https://codesandbox.io/s/staging-glade-e2msc?file=/src/App.js

答: thats the problem with the inner loop, in the first iteration of outer loop, the value of minutes stays at 60, so the inner loop end immediately in the following iteration, what you need is probably for (mintes = 20; mintes <= LastMinutes; mintes += 5) re-initialize your mintes (you got a u missing but this just spelling not big deal) so the inner loop can restart in every iteration of outer loop

Body:
I have a problem with the repetition of an error. I need to display the hours at 18, 19, 20, 21, 22 with the minutes, but there is a repetition at 18

let CloseTime = 23;
let TheTimeNow = 20;

let mintes = 20;
let LastMinutes = 60;

let resultMintes = [];
let lastResult = [];

for (TheTimeNow; TheTimeNow <= CloseTime; TheTimeNow++) {
  for (mintes; mintes <= LastMinutes; mintes += 5) {
    resultMintes.push(`${TheTimeNow}:${mintes}`);
  }

  lastResult.push(resultMintes);
}

console.log(lastResult);

https://codesandbox.io/s/staging-glade-e2msc?file=/src/App.js


问:
divide a list of positive integers by the length of digits
I would like to divide a list of positive integers by the length of digits.

For example, int_list = [1,3,13,888,1004]
-> [1,3] , [13] , [888] , [1004]

I have implemented below:

def seperate_by_digit(int_list):
    len_set = set()  # track how many digits we have

    int_dict = {}  # key : len of digits  / val : list of integer
    for int_ele in int_list:
        n = len(str(int_ele))
        if n not in len_set:
            int_dict[n] = [int_ele]
            len_set.add(n)
        else:
            sub_int_list = int_dict[n]
            sub_int_list.append(int_ele)
            int_dict[n] = sub_int_list
    return int_dict
```

Is there any better, cleaner way to complete this task?

答:
It's multiple passes, but a way to accomplish this would be to create a set of the lengths of the numbers in lst.

```<code>lst = [1, 3, 13, 888, 1004]

lens = set(len(str(x)) for x in lst)
</code>```

We can then iterate over this set and filter lst for each length.

```<code>grouped = [[x for x in lst if len(str(x)) == l] for l in lens]
</code>```

End result:

```<code>[[1, 3], [13], [888], [1004]]
</code>```

Body:
I would like to divide a list of positive integers by the length of digits.

For example, int_list = [1,3,13,888,1004]
-> [1,3] , [13] , [888] , [1004]

I have implemented below:

def seperate_by_digit(int_list):
    len_set = set()  # track how many digits we have

    int_dict = {}  # key : len of digits  / val : list of integer
    for int_ele in int_list:
        n = len(str(int_ele))
        if n not in len_set:
            int_dict[n] = [int_ele]
            len_set.add(n)
        else:
            sub_int_list = int_dict[n]
            sub_int_list.append(int_ele)
            int_dict[n] = sub_int_list
    return int_dict

Is there any better, cleaner way to complete this task?

Body:
It's multiple passes, but a way to accomplish this would be to create a set of the lengths of the numbers in lst.

lst = [1, 3, 13, 888, 1004]

lens = set(len(str(x)) for x in lst)

We can then iterate over this set and filter lst for each length.

grouped = [[x for x in lst if len(str(x)) == l] for l in lens]

End result:

[[1, 3], [13], [888], [1004]]


问:
Davis.js & scrollTo
I'm using Davis.js and and Ariel Flesler's scrolLTo plugin. I'm trying to have the window scrollTo a div on my page:

```<code>var app = Davis(function () {
          this.get('/products', function (req) {
              $(window).scrollTo( '#products', 800 );
          })
        })

        app.start();
</code>```

This is not working. Any ideas?

答:
Have you made sure that an element with id 'products' is on the page when that route is ran?

It is difficult to try and provide an answer with so little information, do you have a simplified test case that is easy to rerun.

I can't think of any reason why Davis wouldn't work well with scollTo.

Title: Davis.js & scrollTo

Body:
I'm using Davis.js and and Ariel Flesler's scrolLTo plugin. I'm trying to have the window scrollTo a div on my page:

var app = Davis(function () {
          this.get('/products', function (req) {
              $(window).scrollTo( '#products', 800 );
          })
        })

        app.start();

This is not working. Any ideas?


问:
Can I use VBA to update a dataset?
I'm using a vba UserForm to enter in "Vehicle Reg" and choose "Current Status" from a combobox, which currently adds this data to a new line along with a uniqueID, the username, and the time.

I'd like to create a finite list of Vehicle Reg, and use the UserForm to update the Current Status (1 column to the right) with the new value.

Is there a way I can alter what I have to make this work? I am brand new to vba and have been googling for days!
I have a Submit Button, a Reset Button, and on the main spreadsheet I have a macro button that I have attached the "Show Form".

Here's what I have:

```<code>Sub Reset()

    Dim iRow As Long

    iRow = [Counta(Database!A:A)] 'identifying the last row

    With frmForm
         .txtID.Value = ""

        .cmbStatus.Clear

        .cmbStatus.AddItem "Loaded - In"
        .cmbStatus.AddItem "Loaded - Out"
        .cmbStatus.AddItem "Empty - Parked"
        .cmbStatus.AddItem "Empty - On Bay"

        .lstDatabase.ColumnCount = 4
        .lstDatabase.ColumnHeads = True

        If iRow > 1 Then

            .lstDatabase.RowSource = "Database!A2:C" & iRow

        Else

            .lstDatabase.RowSource = "Database!A2:C2"

        End If

    End With
End Sub

Sub Submit()

    Dim sh As Worksheet
    Dim iRow As Long

    Set sh = ThisWorkbook.Sheets("Database")

    iRow = [Counta(Database!A:A)] + 1

    With sh

    .Cells(iRow, 1) = iRow - 1
    .Cells(iRow, 2) = frmForm.txtID.Value
    .Cells(iRow, 3) = frmForm.cmbStatus.Value
    .Cells(iRow, 4) = Application.UserName
    .Cells(iRow, 5) = [Text(Now(), "DD-MM-YYY HH:MM:SS")]

    End With

End Sub

Sub Show_Form()

    Call Reset

    frmForm.Show

End Sub

**And my initialize code:**

    Private Sub UserForm_Initialize()

    With frmForm

        Height = 370
        Width = 645

    End With

End Sub

Private Sub cmdReset_Click()

  Dim msgValue As VbMsgBoxResult

    msgValue = MsgBox("Do you want to reset the form?", vbYesNo + vbInformation, "Confirmation")

    If msgValue = vbNo Then Exit Sub

    Call Reset

End Sub

Private Sub cmdSave_Click()

With Me

    If txtID.Value = "" Then
    MsgBox "Reg Cannot Be Blank", vbOKOnly + vbCritical + vbDefaultButton1, "Reg Blank"

    End If

    Exit Sub

End With

    Dim msgValue As VbMsgBoxResult

    msgValue = MsgBox("Do you want to save?", vbYesNo + vbInformation, "Confirmation")

    If msgValue = vbNo Then Exit Sub

    Call Submit
    Call Reset

    Unload Me

End Sub

Private Sub frmForm_Initialize()

    Call Reset

End Sub
</code>```

Thanks!

答:
Use the lstDatabase_Click() event together with the .ListIndex property to load the form items from the sheet. The Reset de-selects the line. Save without a line selected adds a new record, with line selected updates the existing record.

Option Explicit

Sub Show_Form()
    frmForm.Show
End Sub

Private Sub cmdReset_Click()
    ' unselect line lstdatabase
    With Me
        .txtID.Value = ""
        .cmbStatus = ""
        .lstDatabase.ListIndex = -1
    End With
End Sub

Private Sub UserForm_Initialize()
    With Me
        .Height = 370
        .Width = 645
        .txtID.Value = ""
        .cmbStatus.Clear
        .cmbStatus.AddItem "Loaded - In"
        .cmbStatus.AddItem "Loaded - Out"
        .cmbStatus.AddItem "Empty - Parked"
        .cmbStatus.AddItem "Empty - On Bay"

        .lstDatabase.ColumnCount = 4
        .lstDatabase.ColumnHeads = True
    End With
    LoadDatabase
End Sub

Private Sub cmdSave_Click()

    If txtID.Value = "" Then
        MsgBox "Reg Cannot Be Blank", vbCritical, "Reg Blank"
    ElseIf cmbStatus.Value = "" Then
        MsgBox "Status Cannot Be Blank", vbCritical, "Status Blank"
    ElseIf MsgBox("Do you want to save?", vbYesNo, "Confirmation") = vbYes Then
        Call Submit
        'Unload Me
    End If

End Sub

Sub Submit()

    Dim i As Long, r As Long
    With lstDatabase
        i = .ListIndex
        ' is line selected
        If i >= 0 Then r = .List(i, 0) + 1
    End With

    ' update or add
    With Sheets("Database")
        ' add new find last line
        If r = 0 Then
            r = 1 + .Cells(.Rows.Count, "A").End(xlUp).Row
            .Cells(r, 1) = r - 1
            .Cells(r, 2) = frmForm.txtID.Value
        End If
        ' update
        .Cells(r, 3) = frmForm.cmbStatus.Value
        .Cells(r, 4) = Application.UserName
        .Cells(r, 5) = [Text(Now(), "DD-MM-YYY HH:MM:SS")]
    End With

End Sub

Private Sub lstDatabase_Click()

    Dim i As Long, r As Long
    With lstDatabase
        i = .ListIndex
        If i >= 0 Then
           txtID.Value = .List(i, 1)
           cmbStatus.Text = .List(i, 2)
        End If
    End With

End Sub

Sub LoadDatabase()

   Dim iRow As Long
   With Sheets("Database")
       iRow = .Cells(.Rows.Count, "A").End(xlUp).Row
   End With
   If iRow < 2 Then iRow = 2
   lstDatabase.RowSource = "Database!A2:C" & iRow

End Sub
```

Title: Can I use VBA to update a dataset?

Body:
I'm using a vba UserForm to enter in "Vehicle Reg" and choose "Current Status" from a combobox, which currently adds this data to a new line along with a uniqueID, the username, and the time.

I'd like to create a finite list of Vehicle Reg, and use the UserForm to update the Current Status (1 column to the right) with the new value.

Is there a way I can alter what I have to make this work? I am brand new to vba and have been googling for days!
I have a Submit Button, a Reset Button, and on the main spreadsheet I have a macro button that I have attached the "Show Form".

Here's what I have:

Sub Reset()

    Dim iRow As Long

    iRow = [Counta(Database!A:A)] 'identifying the last row

    With frmForm
         .txtID.Value = ""

        .cmbStatus.Clear

        .cmbStatus.AddItem "Loaded - In"
        .cmbStatus.AddItem "Loaded - Out"
        .cmbStatus.AddItem "Empty - Parked"
        .cmbStatus.AddItem "Empty - On Bay"

        .lstDatabase.ColumnCount = 4
        .lstDatabase.ColumnHeads = True

        If iRow > 1 Then

            .lstDatabase.RowSource = "Database!A2:C" & iRow

        Else

            .lstDatabase.RowSource = "Database!A2:C2"

        End If

    End With
End Sub

Sub Submit()

    Dim sh As Worksheet
    Dim iRow As Long

    Set sh = ThisWorkbook.Sheets("Database")

    iRow = [Counta(Database!A:A)] + 1

    With sh

    .Cells(iRow, 1) = iRow - 1
    .Cells(iRow, 2) = frmForm.txtID.Value
    .Cells(iRow, 3) = frmForm.cmbStatus.Value
    .Cells(iRow, 4) = Application.UserName
    .Cells(iRow, 5) = [Text(Now(), "DD-MM-YYY HH:MM:SS")]

    End With

End Sub

Sub Show_Form()

    Call Reset

    frmForm.Show

End Sub

**And my initialize code:**

    Private Sub UserForm_Initialize()

    With frmForm

        Height = 370
        Width = 645

    End With

End Sub

Private Sub cmdReset_Click()

  Dim msgValue As VbMsgBoxResult

    msgValue = MsgBox("Do you want to reset the form?", vbYesNo + vbInformation, "Confirmation")

    If msgValue = vbNo Then Exit Sub

    Call Reset

End Sub

Private Sub cmdSave_Click()

With Me

    If txtID.Value = "" Then
    MsgBox "Reg Cannot Be Blank", vbOKOnly + vbCritical + vbDefaultButton1, "Reg Blank"

    End If

    Exit Sub

End With

    Dim msgValue As VbMsgBoxResult

    msgValue = MsgBox("Do you want to save?", vbYesNo + vbInformation, "Confirmation")

    If msgValue = vbNo Then Exit Sub

    Call Submit
    Call Reset

    Unload Me

End Sub

Private Sub frmForm_Initialize()

    Call Reset

End Sub

Thanks!


问:
UINavigationController: How to manage Cancel button and back button
Lets say I have two controller A & B... When I'll navigate from A to B then back button on B Controller will be A.

So my problem is... On a button click I have to change backButton to Cancel Button.. and on another back button it should appear backButton A in back button arrow style.

Please suggest.

答:
Do the following,

To SHOW the Cancel button:

```<code>- (void)showCancelButton {

    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(someMethod)];
    [self navigationItem] setLeftBarButtonItem:cancelButton];
    [cancelButton release];
}
</code>```

To HIDE the Cancel button:

```<code>- (void)hideCancelButton {

    [self navigationItem] setLeftBarButtonItem:nil];
}
</code>```

Make sure self.navigationController.navigationItem.hidesBackButton  is NO.

Body:
Do the following,

To SHOW the Cancel button:

- (void)showCancelButton {

    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(someMethod)];
    [self navigationItem] setLeftBarButtonItem:cancelButton];
    [cancelButton release];
}

To HIDE the Cancel button:

- (void)hideCancelButton {

    [self navigationItem] setLeftBarButtonItem:nil];
}

Make sure self.navigationController.navigationItem.hidesBackButton  is NO.


问:
Can the CSS :part pseudo-selector be used to style nested web components?
When creating Web Components with encapsulated styles using Shadow DOM, parts of the shadowed markup can be styled using the ::part pseudo selector (https://developer.mozilla.org/en-US/docs/Web/CSS/::part).

Can the part selector be used to target nested shadow parts?

```<code><custom-element>
  #shadow-root
    <div part="thats-easy"></div>
    <another-custom-element part="proxy-part">
      #shadow-root
        <div part="target-me"></div>
    </another-custom-element>
</custom-element>
</code>```

Current efforts were fruitless:

```<code>another-custom-element::part(target-me) { }
custom-element::part(proxy-part) another-custom-element::part(target-me) { }
custom-element::part(proxy-part another-custom-element::part(target-me)) { }
custom-element::part(proxy-part::part(target-me)) { }
```
```

答:
Nope. It is not possible. It kind a breaks the encapsulation principle. The right way is to use proper theming. That means using a combination of:

```<code>::part - For direct theming of the component
:host-context - for theming based on the context
::slotted - For styling the slotted element inside the styling
</code>```

For more dynamic theming, you can use above styles in combination with Element.matches API. Whatever the class/context that the user of the component has set, you can then change the styling of nested children component.

On a side note, modifying the styling of a decadent component (children of children) is a bad practice even when not using Shadow DOM or Web Components. It will result in a brittle non-maintainable CSS.

Edit Note:

:host-context is not implemented in all browsers and probably never will.

Body:
When creating Web Components with encapsulated styles using Shadow DOM, parts of the shadowed markup can be styled using the ::part pseudo selector (https://developer.mozilla.org/en-US/docs/Web/CSS/::part).

Can the part selector be used to target nested shadow parts?

<custom-element>
  #shadow-root

    <another-custom-element part="proxy-part">
      #shadow-root

    </another-custom-element>
</custom-element>

Current efforts were fruitless:

another-custom-element::part(target-me) { }
custom-element::part(proxy-part) another-custom-element::part(target-me) { }
custom-element::part(proxy-part another-custom-element::part(target-me)) { }
custom-element::part(proxy-part::part(target-me)) { }
```

Body:
Nope. It is not possible. It kind a breaks the encapsulation principle. The right way is to use proper theming. That means using a combination of:

::part - For direct theming of the component
:host-context - for theming based on the context
::slotted - For styling the slotted element inside the styling

For more dynamic theming, you can use above styles in combination with Element.matches API. Whatever the class/context that the user of the component has set, you can then change the styling of nested children component.

On a side note, modifying the styling of a decadent component (children of children) is a bad practice even when not using Shadow DOM or Web Components. It will result in a brittle non-maintainable CSS.

Edit Note:

:host-context is not implemented in all browsers and probably never will.


问:
Making a right triangle by arrays in python using loops and auto filling the arrays
I want to write a program that can help me to calculate some values using python.
The main idea is I want to make a table, which is only half of the cells are having value. (That means I want to make a triangle) So, the triangle I want to make is like this format.

```<code>12345
1234
123
12
1
</code>```

But, things are not that easy. Please see the table below. (Also same as picture 1)

```<code>6.00 6.45 6.80 7.10 7.36 7.56 7.77
6.90 7.20 7.47 7.70 7.88 8.06
7.50 7.75 7.97 8.12 8.30
8.00 8.20 8.33 8.50
8.40 8.50 8.67
8.60 8.80
9.00
</code>```

In the above triangle, each of the rows is make from the previous row by a certain formula. Please refer to the picture 2 and picture 3.

Also, please note that in the above triangle, each of the cells was multiplied by 100. For example, the 6.00 in the upper left corner is 6% (0.06) indeed. << Please do NOT multiplied the figures by 100 in my program, because it is just an accident here for demonstration.

Okay. So, I want to make a program that as long as I input the first row, then the program will calculate and show the remaining rows for me. (That means showing the whole triangle)

Below is my code. Please have a look. I have tried to write a frame, but there are two problems that I encounter.

I don't know how to automatically fill my other arrays(the other rows) base on the first arrays (the first row) that I input in the program.

I keep receiving the error of "IndexError: list index out of range" when I try to run my programme.

Here are my codes

```<code>array1 = [0.06,0.0645,0.068,0.071,0.0736,0.0756,0.0777]         #This is the initial array that I input
array2 = []            #This should be the output after the first iteration, I hope that my programme can auto fill the remaining arrays (including this array) after I run my programme
array3 = []            #This is a blank array waiting for auto fill after I run my program
array4 = []            #This is a blank array waiting for auto fill after I run my program
array5 = []            #This is a blank array waiting for auto fill after I run my program
array6 = []            #This is a blank array waiting for auto fill after I run my program
array7 = []            #This is a blank array waiting for auto fill after I run my program
array8 = []            #This is a blank array waiting for auto fill after I run my program

r = 0  # Set the initial position for the table that I want to make, and this is similar to the x-asis. Please refer to picture 2.
s = 1  # Set the initial position for the table that I want to make, and this is similar to the y-asis. Please refer to picture 2.

def SpotRateForcast(i,j,k):
    global r
    global s

    while (r <= len(k)):                                     # I try to make the first loop here
        s = 1                                                # Reset the value when the first row is completed such that the second loop can work in the second row
        while (s <= len(k)):                                 # this is the second loop to determine when to stop in the each row
            x = ((((1 + k[j - 1])**j) / ((1 + k[i - 1])**i))**(1/(j-i))) - 1  #Calculate the value by the certain formula
            print(("%.4f" % round(x,4)), end=' ,  ')         #Print the value up to 4 decimal places
            s += 1                                           #Record one value is calculated and done
            SpotRateForcast(i,j+1,k)                         #Start to calculate and print the next value
        r += 1                                               # Switch to the next row when the second loop is finished

SpotRateForcast(r,s,array1)                                  #The code to run the program
</code>```

Thank you for reading my question.
I would like to ask someone to finish the programme for me. As you can see, my coding maybe bad because I am a newbie in programming. But I already tried my best to do everything I am able to do.

I do not mind your edit my codes. It is even better if you can write a new codes for me. And I can learn how to write better codes from you.

Lastly, I have one more request. Please add many many comments in the codes you wrote otherwise I may not able to understand what you wrote(I am a beginner). Thank you very much!

答:
You are overthinking it.

If you only need to print a triangle, just print each row in sequence, and for each row print its values in sequence:

```<code>S = [0.06,0.0645,0.068,0.071,0.0736,0.0756,0.0777]

n = len(S)

print(('{:0.4f} ' * n).format(*S))  # print initial line

for i in range(1,n):                # loop over rows
    for j in range(i+1, n+1):       # then over colums
        num = (1 + S[j -1])**j
        den = (1 + S[i - 1])**i
        x = (num/den)**(1/(j - i)) -1       # ok we have f(i, j)
        print('{:0.4f}'.format(x), end=' ') # print it followed with a space
    print('')                       # add a newline after a full row
</code>```

It gives:

```<code>0.0600 0.0645 0.0680 0.0710 0.0736 0.0756 0.0777
0.0690 0.0720 0.0747 0.0770 0.0787 0.0807
0.0750 0.0775 0.0797 0.0812 0.0830
0.0801 0.0821 0.0833 0.0850
0.0841 0.0849 0.0867
0.0857 0.0880
0.0904
</code>```

Now if you want to first build arrays because you will later post-process them, just append each field value to a list for the row, and then append each of those lists to a global list of lists

```<code>S = [0.06,0.0645,0.068,0.071,0.0736,0.0756,0.0777]

n = len(S)

result = [S]                        # add the initial row

for i in range(1,n):                # loop over rows
    row = []                            # prepare a new list for the row
    result.append(row)                  # and append it to result
    for j in range(i+1, n+1):       # then over colums
        num = (1 + S[j -1])**j
        den = (1 + S[i - 1])**i
        x = (num/den)**(1/(j - i)) -1       # ok we have f(i, j)
        row.append(x)               # as a list is modifiable we can append to it
</code>```

Body:
I want to write a program that can help me to calculate some values using python.
The main idea is I want to make a table, which is only half of the cells are having value. (That means I want to make a triangle) So, the triangle I want to make is like this format.

12345
1234
123
12
1

But, things are not that easy. Please see the table below. (Also same as picture 1)

6.00 6.45 6.80 7.10 7.36 7.56 7.77
6.90 7.20 7.47 7.70 7.88 8.06
7.50 7.75 7.97 8.12 8.30
8.00 8.20 8.33 8.50
8.40 8.50 8.67
8.60 8.80
9.00

In the above triangle, each of the rows is make from the previous row by a certain formula. Please refer to the picture 2 and picture 3.

Also, please note that in the above triangle, each of the cells was multiplied by 100. For example, the 6.00 in the upper left corner is 6% (0.06) indeed. << Please do NOT multiplied the figures by 100 in my program, because it is just an accident here for demonstration.

Okay. So, I want to make a program that as long as I input the first row, then the program will calculate and show the remaining rows for me. (That means showing the whole triangle)

Below is my code. Please have a look. I have tried to write a frame, but there are two problems that I encounter.

I don't know how to automatically fill my other arrays(the other rows) base on the first arrays (the first row) that I input in the program.

I keep receiving the error of "IndexError: list index out of range" when I try to run my programme.

Here are my codes

array1 = [0.06,0.0645,0.068,0.071,0.0736,0.0756,0.0777]         #This is the initial array that I input
array2 = []            #This should be the output after the first iteration, I hope that my programme can auto fill the remaining arrays (including this array) after I run my programme
array3 = []            #This is a blank array waiting for auto fill after I run my program
array4 = []            #This is a blank array waiting for auto fill after I run my program
array5 = []            #This is a blank array waiting for auto fill after I run my program
array6 = []            #This is a blank array waiting for auto fill after I run my program
array7 = []            #This is a blank array waiting for auto fill after I run my program
array8 = []            #This is a blank array waiting for auto fill after I run my program

r = 0  # Set the initial position for the table that I want to make, and this is similar to the x-asis. Please refer to picture 2.
s = 1  # Set the initial position for the table that I want to make, and this is similar to the y-asis. Please refer to picture 2.

def SpotRateForcast(i,j,k):
    global r
    global s

    while (r <= len(k)):                                     # I try to make the first loop here
        s = 1                                                # Reset the value when the first row is completed such that the second loop can work in the second row
        while (s <= len(k)):                                 # this is the second loop to determine when to stop in the each row
            x = ((((1 + k[j - 1])**j) / ((1 + k[i - 1])**i))**(1/(j-i))) - 1  #Calculate the value by the certain formula
            print(("%.4f" % round(x,4)), end=' ,  ')         #Print the value up to 4 decimal places
            s += 1                                           #Record one value is calculated and done
            SpotRateForcast(i,j+1,k)                         #Start to calculate and print the next value
        r += 1                                               # Switch to the next row when the second loop is finished

SpotRateForcast(r,s,array1)                                  #The code to run the program

Thank you for reading my question.
I would like to ask someone to finish the programme for me. As you can see, my coding maybe bad because I am a newbie in programming. But I already tried my best to do everything I am able to do.

I do not mind your edit my codes. It is even better if you can write a new codes for me. And I can learn how to write better codes from you.

Lastly, I have one more request. Please add many many comments in the codes you wrote otherwise I may not able to understand what you wrote(I am a beginner). Thank you very much!

Body:
You are overthinking it.

If you only need to print a triangle, just print each row in sequence, and for each row print its values in sequence:

S = [0.06,0.0645,0.068,0.071,0.0736,0.0756,0.0777]

n = len(S)

print(('{:0.4f} ' * n).format(*S))  # print initial line

for i in range(1,n):                # loop over rows
    for j in range(i+1, n+1):       # then over colums
        num = (1 + S[j -1])**j
        den = (1 + S[i - 1])**i
        x = (num/den)**(1/(j - i)) -1       # ok we have f(i, j)
        print('{:0.4f}'.format(x), end=' ') # print it followed with a space
    print('')                       # add a newline after a full row

It gives:

0.0600 0.0645 0.0680 0.0710 0.0736 0.0756 0.0777
0.0690 0.0720 0.0747 0.0770 0.0787 0.0807
0.0750 0.0775 0.0797 0.0812 0.0830
0.0801 0.0821 0.0833 0.0850
0.0841 0.0849 0.0867
0.0857 0.0880
0.0904

Now if you want to first build arrays because you will later post-process them, just append each field value to a list for the row, and then append each of those lists to a global list of lists

S = [0.06,0.0645,0.068,0.071,0.0736,0.0756,0.0777]

n = len(S)

result = [S]                        # add the initial row

for i in range(1,n):                # loop over rows
    row = []                            # prepare a new list for the row
    result.append(row)                  # and append it to result
    for j in range(i+1, n+1):       # then over colums
        num = (1 + S[j -1])**j
        den = (1 + S[i - 1])**i
        x = (num/den)**(1/(j - i)) -1       # ok we have f(i, j)
        row.append(x)               # as a list is modifiable we can append to it


问:
How do I convert multiple columns into one from Binary data?
My data has 3 surveys per year (for 10 years) where 1 represents presence and 0s present absence. The subset looks like this

x <- structure(c(0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1,
                 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1,
                 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1,
                 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1),
               .Dim = c(4L, 3L, 4L))
```

I want to collapse these three columns into one in a way that every row that has 1 in any survey, shows 1 in the final otherwise shows 0.

Body:
My data has 3 surveys per year (for 10 years) where 1 represents presence and 0s present absence. The subset looks like this

x <- structure(c(0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1,
                 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1,
                 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1,
                 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1),
               .Dim = c(4L, 3L, 4L))

I want to collapse these three columns into one in a way that every row that has 1 in any survey, shows 1 in the final otherwise shows 0.

Body:
We could use max

apply(x, c(1, 3), FUN = max)
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]    1    1    1    1
[3,]    0    1    1    1
[4,]    1    1    1    1


答:
http://sandbox.phpcode.eu/g/3fff8.php

```<code>$pattern = "/^$pattern.*?\$/m";
</code>```

instead of

```<code>$pattern = "/^.*|$pattern.*\$/m";
</code>```

Title: Search in php from dat file

Body:
I'm trying to Search my orderid, This is my code so far:

<?php
$file = 'order.dat';
$searchfor = '177';

// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');

// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
   echo "Found matches:\n";
   echo implode("\n", $matches[0]);
}
else{
   echo "No matches found";
}

now for example my order.dat file contains the data

175|RC456456456|54156456465|109$

176|RC456456456|54156456465|177$

177|RC456456456|54156456465|129$

178|RC456456456|54156456465|129$

now when i searchfor 177 i have an result like this:-

Found matches:
176|RC456456456|54156456465|177$
177|RC456456456|54156456465|129$

But i want to search 177 for my 1st string only

I want my result like this, its only match my 1st string not on all 4 variables

177|RC456456456|54156456465|129$

Body:
http://sandbox.phpcode.eu/g/3fff8.php

$pattern = "/^$pattern.*?\$/m";

instead of

$pattern = "/^.*|$pattern.*\$/m";


问:
Get the amount of specifc days in between two dates | in Freemarker
to explain the title or problem of my case.
I want to get the amount of saturdays and sundays in between to dates. For example:
Starting date is: 2022-02-01.                                                                    Ending date is: 2022-02-07.
So in between the dates are two weekend days or one saturday and on sunday.

Is there any way to calculate this or use a given fuction ?

答:
There's nothing built in for that, so you had to expose some Java utility to the template to do that. Or better yet, the data-model should contain the final values to display. Generally if you have to do calculations in the template that's not a good sign.

There's hope that 2.3.32 will be able to do more date/time calculations (because of java.time support). This of course even there will need some coding, but then it will be possible to do it purely in the template language. For now, you have to use Java for this.


问:
How do I join two queries in SQL using UNION ALL operation?
everyone.

This is my first query

```<code>SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.apellidos_Autor DESC ;
</code>```

And this is my second query

```<code>SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.nombres_Autor ASC ;
</code>```

So, I just want to know what do I have to do to join these queries using UNION ALL (and not any JOIN operator). Cz the next is not working for me.

```<code>SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.apellidos_Autor DESC
UNION ALL
SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.nombres_Autor ASC ;
</code>```

Thank u'all, community.
(I really appreciate any kind of feedback).

答:
```<code>SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.apellidos_Autor DESC
union all
SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.nombres_Autor ASC
</code>```

Body:
everyone.

This is my first query

SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.apellidos_Autor DESC ;

And this is my second query

SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.nombres_Autor ASC ;

So, I just want to know what do I have to do to join these queries using UNION ALL (and not any JOIN operator). Cz the next is not working for me.

SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.apellidos_Autor DESC
UNION ALL
SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.nombres_Autor ASC ;

Thank u'all, community.
(I really appreciate any kind of feedback).


问:
Paypal JavaScript SDK with IPN
I am using PayPal JavaScript SDK. Now I want to add Instant Payment Notification (IPN) as I have done with just the quick checkout button.
There I have used it in a form with POST like this:

```<code><form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="notify_url" value="<?php echo $HTTP_DIR."method/paypal/ipn.php"; ?>">
</code>```

How I can use "notify_url" with the JS SDK? I did not find it as a parameter.

Is it enough to set up in the PayPal account where I can set an IPN URL?

答:
IPN is a separate 20 year-old system, not needed for current API-based integrations.  Rather than using IPN with that SDK, change to a server-side create/capture with it. Then you'll have an immediate notification of successful payments, with no need to wait for a separate IPN message that may fail.

See the optional bullet #5 of the 'Add and modify the code' section of Integrate Checkout, which links to a demo code sample. You'll just need to create two routes on your PHP server that return JSON, one to create an order when a button is clicked, and the other to capture it after an approval.

Title: Paypal JavaScript SDK with IPN

Body:
I am using PayPal JavaScript SDK. Now I want to add Instant Payment Notification (IPN) as I have done with just the quick checkout button.
There I have used it in a form with POST like this:

<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="notify_url" value="<?php echo $HTTP_DIR."method/paypal/ipn.php"; ?>">

How I can use "notify_url" with the JS SDK? I did not find it as a parameter.

Is it enough to set up in the PayPal account where I can set an IPN URL?


问:
TDengine arithmetic query operation causing coredump using none numeric operands
I was trying the arithmetic operation using select clause. I found when using numbers as operands the result is looking fine, but none numeric values like string/string or  mix of number/string TDengine core dumps. I was thinking may be the ASCII values could be used in the calculation initially but expecting at least TDengine throws an error. Anyone know if using the none numeric value is the standard way for arithmetic query?

```<code>taos> select 2 + 3.0 from tb;
          2 + 3.0          |
============================
               5.000000000 |
               5.000000000 |
Query OK, 2 row(s) in set (0.014870s)

taos> select 'a' + 'b' from tb;
taos: /root/wz_test/TDengine/src/client/src/tscSQLParser.c:3506: functionCompatibleCheck: Assertion `numOfExpr > 0' failed.
Aborted (core dumped)

taos> select "a" - 1 from db.tb;
taos: /root/wz_test/TDengine/src/client/src/tscSQLParser.c:3506: functionCompatibleCheck: Assertion `numOfExpr > 0' failed.
Aborted (core dumped)
</code>```

答: I think it should be fixed in the later version.</p>

Body:
I was trying the arithmetic operation using select clause. I found when using numbers as operands the result is looking fine, but none numeric values like string/string or  mix of number/string TDengine core dumps. I was thinking may be the ASCII values could be used in the calculation initially but expecting at least TDengine throws an error. Anyone know if using the none numeric value is the standard way for arithmetic query?

taos> select 2 + 3.0 from tb;
          2 + 3.0          |
============================
               5.000000000 |
               5.000000000 |
Query OK, 2 row(s) in set (0.014870s)

taos> select 'a' + 'b' from tb;
taos: /root/wz_test/TDengine/src/client/src/tscSQLParser.c:3506: functionCompatibleCheck: Assertion `numOfExpr > 0' failed.
Aborted (core dumped)

taos> select "a" - 1 from db.tb;
taos: /root/wz_test/TDengine/src/client/src/tscSQLParser.c:3506: functionCompatibleCheck: Assertion `numOfExpr > 0' failed.
Aborted (core dumped)


问:
How to locate multiple widget of same type in widget hierarchy?
I am developing some intregration tests for one of my flutter-web application. I wanted to specifically locate the container(width: 50, height: 50) in the following below widget hierarchy tree considering top to bottom approach.
ParentWidget --> Row --> Text, SizedBox, Row --> Container(), Container(width: 50, height: 50), Container().
Note: Without key approach

I tried to locate using descendant of ParentWidget --> Row --> Row --> with index tried to select the 2nd container, but this isn't working, it fails with error "Bad state: No element".

```<code>import 'package:flutter/material.dart';

class ParentWidget extends StatelessWidget {
  const ParentWidget({Key? key});

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text("Hello World..!!"),
        SizedBox(
          width: 20,
        ),
        Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Container(
              width: 20,
              height: 20,
              color: Colors.red,
            ),
            Container(
              width: 50,
              height: 50,
              color: Colors.red,
            ),
            Container(
              width: 20,
              height: 20,
              color: Colors.red,
            ),
          ],
        ),
      ],
    );
  }
}
</code>```
```<code>final container = tester.widget<Container>(find.descendant(
    of: find.descendant(
        of: find.byType(ParentWidget), matching: find.byType(Row)),
    matching: find.descendant(
        of: find.byType(Row), matching: find.byType(Container).at(1))));
</code>```

答:
To find multiple widgets in a test you can do this:

testWidgets('Test containers', (tester) async {

    await tester.pumpWidget(ParentWidget());

    expect(find.byType(Container), findsNWidgets(3));
  });
```
<p>For more info check https://docs.flutter.dev/cookbook/testing/widget/introduction</p>
<p>Edit:
To test the second Container's width you could do something like this:</p>
<pre class="lang-dart prettyprint-override"><code>//get the second element's widget, index 1, cast it as a container and check it's width
expect((find.byType(Container).evaluate().elementAt(1).widget as Container).constraints?.maxWidth, 50.0);
</code>```

Body:
I am developing some intregration tests for one of my flutter-web application. I wanted to specifically locate the container(width: 50, height: 50) in the following below widget hierarchy tree considering top to bottom approach.
ParentWidget --> Row --> Text, SizedBox, Row --> Container(), Container(width: 50, height: 50), Container().
Note: Without key approach

I tried to locate using descendant of ParentWidget --> Row --> Row --> with index tried to select the 2nd container, but this isn't working, it fails with error "Bad state: No element".

import 'package:flutter/material.dart';

class ParentWidget extends StatelessWidget {
  const ParentWidget({Key? key});

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text("Hello World..!!"),
        SizedBox(
          width: 20,
        ),
        Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Container(
              width: 20,
              height: 20,
              color: Colors.red,
            ),
            Container(
              width: 50,
              height: 50,
              color: Colors.red,
            ),
            Container(
              width: 20,
              height: 20,
              color: Colors.red,
            ),
          ],
        ),
      ],
    );
  }
}

final container = tester.widget<Container>(find.descendant(
    of: find.descendant(
        of: find.byType(ParentWidget), matching: find.byType(Row)),
    matching: find.descendant(
        of: find.byType(Row), matching: find.byType(Container).at(1))));

Body:
To find multiple widgets in a test you can do this:

testWidgets('Test containers', (tester) async {

    await tester.pumpWidget(ParentWidget());

    expect(find.byType(Container), findsNWidgets(3));
  });

For more info check https://docs.flutter.dev/cookbook/testing/widget/introduction

Edit:
To test the second Container's width you could do something like this:

//get the second element's widget, index 1, cast it as a container and check it's width
expect((find.byType(Container).evaluate().elementAt(1).widget as Container).constraints?.maxWidth, 50.0);


问:
How to use apache wicket extensions?
I want to use the AjaxFallbackDefaultDataTable in wicket to view my data but these imports are showing error in eclipse :

```<code>import org.apache.wicket.extensions.ajax.markup.html.repeater.data.table.AjaxFallbackDefaultDataTable;   import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;
</code>```

I guess I should be downloading an extensions jar file from somewhere but I don't know where at, and the Apache wicket website is vague regarding this point.

I am using eclipse with maven plugin and wicket 1.5RC1

答:
You can get the wicket-extensions library from the maven repository.  This site shows assorted versions and allows you to retrieve it by just downloading the jar or by using various build tools including of course maven.

Maven is a good tool for dealing java dependency management, and wicket quickstart is useful for starting wicket projects with a maven setup.

Title: How to use apache wicket extensions?

Body:
I want to use the AjaxFallbackDefaultDataTable in wicket to view my data but these imports are showing error in eclipse :

import org.apache.wicket.extensions.ajax.markup.html.repeater.data.table.AjaxFallbackDefaultDataTable;   import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;

I guess I should be downloading an extensions jar file from somewhere but I don't know where at, and the Apache wicket website is vague regarding this point.

I am using eclipse with maven plugin and wicket 1.5RC1


问:
Why is there no download dSYM button in Testflight for my app?
If I navigate to the Build Metadata section for my app within App Store Connect then the Includes Symbols section just says Yes, there is no blue Download dSYM button there.

The XCode build build options Debug Information Format is set to DWARF with dSYM.

So why is there no dSYM on App Store Connect?

答: In my case the dSYM download link suddenly popped up five days after upload. The migration to the new submission system seems to cause massive delays at the moment.</p>


问:
how Inner join work on two foreign key from single table
I am working on Bus route management system , I made two table first one is Cities and second one is route have following queries

```<code>CREATE TABLE Cities
    (
      ID NUMBER GENERATED ALWAYS AS IDENTITY(START with 1 INCREMENT by 1) PRIMARY KEY,
      Name Varchar(30) not null,
)
CREATE TABLE route
    (
      ID NUMBER GENERATED ALWAYS AS IDENTITY(START with 1 INCREMENT by 1) PRIMARY KEY,
      Name Varchar(30) not null,
      from NUMBER not null,
      to NUMBER NOT NULL,
      CONSTRAINT FROM_id_FK FOREIGN KEY(from) REFERENCES Cities(ID),
      CONSTRAINT TO_id_FK FOREIGN KEY(to) REFERENCES Cities(ID),
)
</code>```

i am joining the table through inner join

```<code>select CITIES.Name
from CITIES
inner join ROUTES on CITIES.ID=ROUTES.ID
</code>```

but it show single column as

```<code>   Name
-----------
</code>```

but i want result as

```<code>    from  |     to
------------------------
</code>```

what is possible way to do this using inner join

答:
Hope is working for you</p>
```<code>select CITIES.Name,ROUTES.from,ROUTES.to
from CITIES inner join ROUTES on CITIES.ID=ROUTES.ID
</code>```

Body:
I am working on Bus route management system , I made two table first one is Cities and second one is route have following queries

CREATE TABLE Cities
    (
      ID NUMBER GENERATED ALWAYS AS IDENTITY(START with 1 INCREMENT by 1) PRIMARY KEY,
      Name Varchar(30) not null,
)
CREATE TABLE route
    (
      ID NUMBER GENERATED ALWAYS AS IDENTITY(START with 1 INCREMENT by 1) PRIMARY KEY,
      Name Varchar(30) not null,
      from NUMBER not null,
      to NUMBER NOT NULL,
      CONSTRAINT FROM_id_FK FOREIGN KEY(from) REFERENCES Cities(ID),
      CONSTRAINT TO_id_FK FOREIGN KEY(to) REFERENCES Cities(ID),
)

i am joining the table through inner join

select CITIES.Name
from CITIES
inner join ROUTES on CITIES.ID=ROUTES.ID

but it show single column as

   Name
-----------

but i want result as

    from  |     to
------------------------

what is possible way to do this using inner join

Body:
Hope is working for you

select CITIES.Name,ROUTES.from,ROUTES.to
from CITIES inner join ROUTES on CITIES.ID=ROUTES.ID


问:
Data structure to select number with probability proportional to its value in less than O(n)
I have a set of numbers, [1, 3, 4, 5, 7]. I want to select a number from the set with a probability proportional to its value:

Number
Probability
%

1
1/20
5

3
3/20
15

4
4/20
20

5
5/20
25

7
7/20
35

However, I want to be able to both update and query this set in less than O(n). Are there any data structures that would help me achieve that?

Preferably in Java, if it exists already

答:
You can get O(log n) amortized querying and updating (including removing/inserting elements) using a Binary Indexed Tree, also known as a Fenwick tree. The idea is to use dynamic resizing, which is the same trick used in variable-size arrays and hash tables to get amortized constant time appends. This also implies that you should be able to get O(log n) worst-case bounds using the method from dynamic arrays of rebuilding a second array on the side, but this makes the code significantly longer.

First, we know that given a list of the partial sums of arr, and a random integer in [0, sum(arr)], we can do this in O(log n) time with a binary search. Specifically, if our random integer is r, we want the index of the rightmost partial sum less than or equal to r.

Now, we'll use the technique from this post of Fenwick trees to maintain and query the partial sums. That post is slightly different from yours: they have a fixed set of n keys, whose weights can be updated, without new insertions or deletions.

A Fenwick tree is an array that allows you to answer queries about partial sums of a 'base' array in O(log n) time per query, and can be built in O(n) time. In particular, you can

Find the the index of the rightmost partial sum of arr less than or equal to r,

Set arr[i] to arr[i]+c for any integer c,

both in O(log n) time.

Start by appending n zeros to arr (it is now half full), and build its Fenwick tree. We can treat 'removing' an element as setting its weight to 0. Inserting an element is done by taking the zero after the rightmost nonzero element in arr as the new element's spot. The removed elements and new elements may eventually cause our array to fill up: if we reach 75% capacity, rebuild our array and Fenwick tree, doubling the array size (pad with zeros on the right) and deleting all the zero-weight elements. If we reach 25% capacity, shrink the array to half size, rebuilding the Fenwick tree as well.

You'll need to maintain arr constantly to be able to rebuild, so all updates must be done on arr and the Fenwick tree. You'll also need a hashmap from array indices to your keys for random selection.

The good part is that you don't need to modify the Fenwick tree internals at all: given a Fenwick tree implementation in Java that supports initialization, array updates and the binary search, you can treat it as a black box. This stops being true if you want worst-case time guarantees: then, you'll need to copy the internal state of the Fenwick tree, piece by piece, which has some complications.


问:
Global scss variables for Angular components without importing them everytime
I do already have SCSS variables defined in src/styles/settings/_variables.scss and I am importing them into src/styles.scss, but still these variables aren't available for every single component.

Is there any way to make a global file which holds all SCSS variables for the rest of my components? Because writing @import in every single component .scss file it is very frustrating, especially if I have many nested components.

I know, there is a lot of similar questions, but it seems like they're all outdated and do not relate to the recent versions of Angular.

I use Angular 7.3 with CLI.

答:
Easily possibe to access sass style(s) from a global file with two steps.

Add folder path of the style files to includePaths array in angular.json file.

Import style file by file-name in any component.

let say your files and folder structures is as follows: src > my-styles-folder > var.scss

angular.json

```<code>"architect": {
  "build": {
    ...
    "options": {
      "stylePreprocessorOptions": {
        "includePaths": [
          "src/my-styles-folder" // add path only, do not include file name
        ]
      },
      "styles": [
        ...
      ]
    }
    ...
  }
}
</code>```

some-component.scss

```<code>@import "var"; // var.scss

mat-toolbar {
  height: $toolbar-height;
}
</code>```

Body:
Easily possibe to access sass style(s) from a global file with two steps.

Add folder path of the style files to includePaths array in angular.json file.

Import style file by file-name in any component.

let say your files and folder structures is as follows: src > my-styles-folder > var.scss

angular.json

"architect": {
  "build": {
    ...
    "options": {
      "stylePreprocessorOptions": {
        "includePaths": [
          "src/my-styles-folder" // add path only, do not include file name
        ]
      },
      "styles": [
        ...
      ]
    }
    ...
  }
}

some-component.scss

@import "var"; // var.scss

mat-toolbar {
  height: $toolbar-height;
}


问:
Question on creating templates in coderush
I am looking to start creating some CR templates to fit with my style of coding (such is the power of coderush).

I tried a dummy one yesterday and made an auto prop with two fields, one for the type and one for the name.

This worked as expected with one flaw...

In coderush when I expand a built in template it sets the cursor to the first field. Mine does not, It sets the cursor at the end of the line

```<code>Private <<Field(Type)>> <<Field(Name)>> {get; set}
</code>```

PS: Does anyone know how to type out those teeny tiny angle brackets that they use?

答:
Those characters « and » are used to denote:

Textcommands: «MyTextCommand»

StringProviders: «?MyStringProvider»

Aliases:: «:MyOtherTemplate»

Text commands are available from a dropdown list just underneath the main expansion window.

All 3 Token types are available from menu items on the expansion box's context menu.

There should be no need to type these characters manually.

That said, I do prefer to be able to do this and have configured a 3rd party tool Autohotkey to autoreplace >> with » and << with « as I type

FWIW the configuration I use is

```<code>:*?:<<::«
:*?:>>::»
</code>```

Body:
I am looking to start creating some CR templates to fit with my style of coding (such is the power of coderush).

I tried a dummy one yesterday and made an auto prop with two fields, one for the type and one for the name.

This worked as expected with one flaw...

In coderush when I expand a built in template it sets the cursor to the first field. Mine does not, It sets the cursor at the end of the line

Private <<Field(Type)>> <<Field(Name)>> {get; set}

PS: Does anyone know how to type out those teeny tiny angle brackets that they use?

Body:
Those characters « and » are used to denote:

Textcommands: «MyTextCommand»

StringProviders: «?MyStringProvider»

Aliases:: «:MyOtherTemplate»

Text commands are available from a dropdown list just underneath the main expansion window.

All 3 Token types are available from menu items on the expansion box's context menu.

There should be no need to type these characters manually.

That said, I do prefer to be able to do this and have configured a 3rd party tool Autohotkey to autoreplace >> with » and << with « as I type

FWIW the configuration I use is

:*?:<<::«
:*?:>>::»


问:
Firebase - Adding database url into config breaks the build
Adding databaseURL into firebase-config.ts breaks the build with the following error
ReferenceError: Cannot access 'signInWithGoogle' before initialization.

NavBar.tsx

```<code>import * as React from 'react';
import AppBar from '@mui/material/AppBar';
import Box from '@mui/material/Box';
import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import MenuIcon from '@mui/icons-material/Menu';
import { useAppSelector } from '@/redux/hooks/hooks';
import { signInWithGoogle, signOut } from '@/firebase-config';

export default function NavBar() {
  const user = useAppSelector(state => state.rootReducer.userSlice.value);
  return (
    <Box sx={{ flexGrow: 1 }} className="">
      <AppBar position="static">
        <Toolbar>
          ----> <Button color="inherit" onClick={user ? signOut : signInWithGoogle}>{user ? "Logout" : "Login"}</Button>
        </Toolbar>
      </AppBar>
    </Box>
  );
}

</code>```

firebase-config.ts

```<code>// Import the functions you need from the SDKs you need
import { getAnalytics } from "firebase/analytics";
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/database';
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "",
  authDomain: "movier-react-ts.firebaseapp.com",
->databaseURL: "https://movier-react-ts-default-rtdb.europe-west1.firebasedatabase.app",
  projectId: "movier-react-ts",
  storageBucket: "movier-react-ts.appspot.com",
  messagingSenderId: "34914144968",
  appId: "1:34914144968:web:8bbf1e4f02beb25c7c4bfd",
  measurementId: "G-9M2EMLFH6Z"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const auth =  firebase.auth();
const provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({ prompt: 'select_account' });
export const signOut = () => auth.signOut();
export const db = firebase.database();
export const signInWithGoogle = () => auth.signInWithPopup(provider);
</code>```

答: Downgrading firebase version to 8.10.0 solved the issue

Body:
Adding databaseURL into firebase-config.ts breaks the build with the following error
ReferenceError: Cannot access 'signInWithGoogle' before initialization.

NavBar.tsx

import * as React from 'react';
import AppBar from '@mui/material/AppBar';
import Box from '@mui/material/Box';
import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import MenuIcon from '@mui/icons-material/Menu';
import { useAppSelector } from '@/redux/hooks/hooks';
import { signInWithGoogle, signOut } from '@/firebase-config';

export default function NavBar() {
  const user = useAppSelector(state => state.rootReducer.userSlice.value);
  return (
    <Box sx={{ flexGrow: 1 }} className="">
      <AppBar position="static">
        <Toolbar>
          ----> <Button color="inherit" onClick={user ? signOut : signInWithGoogle}>{user ? "Logout" : "Login"}</Button>
        </Toolbar>
      </AppBar>
    </Box>
  );
}

firebase-config.ts

// Import the functions you need from the SDKs you need
import { getAnalytics } from "firebase/analytics";
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/database';
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "",
  authDomain: "movier-react-ts.firebaseapp.com",
->databaseURL: "https://movier-react-ts-default-rtdb.europe-west1.firebasedatabase.app",
  projectId: "movier-react-ts",
  storageBucket: "movier-react-ts.appspot.com",
  messagingSenderId: "34914144968",
  appId: "1:34914144968:web:8bbf1e4f02beb25c7c4bfd",
  measurementId: "G-9M2EMLFH6Z"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const auth =  firebase.auth();
const provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({ prompt: 'select_account' });
export const signOut = () => auth.signOut();
export const db = firebase.database();
export const signInWithGoogle = () => auth.signInWithPopup(provider);