问:
Android - No Activity found to handle HTTPS CustomTabsIntent
I have an app in production and some users get a weird ActivityNotFoundException about a VIEW https intent. I cannot reproduce it locally on my physical device or emulator. I also assume that every Android has a browser to open URLs by default, am I wrong? (None of the devices that encounter the bug is rooted). Could the problem be because the phone doesn't have chrome?

I use CustomTabsIntent to open the URLs:

```<code>public static void openUrl(final Uri url, final Activity activity) {
        CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
        builder.setToolbarColor(ContextCompat.getColor(activity, R.color.denis_red));
        builder.setCloseButtonIcon(
                BitmapFactory.decodeResource(activity.getResources(),
                        R.drawable.ic_arrow_back_white_24dp));
        builder.setStartAnimations(activity, R.anim.activity_slide_in_right,
                R.anim.activity_slide_out_left);
        builder.setExitAnimations(activity, R.anim.activity_slide_in_left,
                R.anim.activity_slide_out_right);
        builder.build().launchUrl(activity, url);
    }
</code>```

I add some of the stack traces if it can help. Thanks!

1:

```<code>android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=https://redirect.denis.de/... (has extras) }
    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2031)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1686)
    at android.app.Activity.startActivityForResult(Activity.java:4506)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
    at android.app.Activity.startActivity(Activity.java:4825)
    at android.support.v4.content.ContextCompat.startActivity(ContextCompat.java:248)
    at android.support.customtabs.CustomTabsIntent.launchUrl(CustomTabsIntent.java:263)
    at de.boxine.denisapp.util.web.ChromeTabUtil.openUrl(ChromeTabUtil.java:26)
    at de.boxine.denisapp.denis.list.DenisListActivity.onOptionsItemSelected(DenisListActivity.java:82)
    at android.app.Activity.onMenuItemSelected(Activity.java:3469)
    at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:436)
    at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:196)
    at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:109)
    at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:109)
    at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:64)
    at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:204)
    at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:781)
    at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
    at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
    at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
    at android.support.v7.view.menu.MenuPopup.onItemClick(MenuPopup.java:128)
    at android.widget.AdapterView.performItemClick(AdapterView.java:318)
    at android.widget.AbsListView.performItemClick(AbsListView.java:1158)
    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3153)
    at android.widget.AbsListView$3.run(AbsListView.java:4068)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6626)
    at java.lang.reflect.Method.invoke(Method.java)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
</code>```

2:

```<code>android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=https://redirect.denis.de/... (has extras) }
    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1981)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1636)
    at android.app.Activity.startActivityForResult(Activity.java:4762)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
    at android.app.Activity.startActivity(Activity.java:5119)
    at android.support.v4.content.ContextCompat.startActivity(ContextCompat.java:248)
    at android.support.customtabs.CustomTabsIntent.launchUrl(CustomTabsIntent.java:263)
    at de.boxine.denisapp.util.web.ChromeTabUtil.openUrl(ChromeTabUtil.java:26)
    at de.boxine.denisapp.login.LoginActivity.openUrl(LoginActivity.java:205)
    at de.boxine.denisapp.login.LoginPresenter.onPasswordForgetLinkClicked(LoginPresenter.java:93)
    at de.boxine.denisapp.login.LoginActivity.lambda$onCreate$2$LoginActivity(LoginActivity.java:153)
    at de.boxine.denisapp.login.-$$Lambda$LoginActivity$HDjhvwi_2M2aWu9LndZHRP-ar9Q.onClick
    at android.view.View.performClick(View.java:6291)
    at android.view.View$PerformClick.run(View.java:24931)
    at android.os.Handler.handleCallback(Handler.java:808)
    at android.os.Handler.dispatchMessage(Handler.java:101)
    at android.os.Looper.loop(Looper.java:166)
    at android.app.ActivityThread.main(ActivityThread.java:7529)
    at java.lang.reflect.Method.invoke(Method.java)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
</code>```

答:
```<code>String myUrl = "google.com";

if (!myUrl .startsWith("http://") && !myUrl .startsWith("https://")){
myUrl = "http://" + myUrl ;
}

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myUrl ));
startActivity(browserIntent);
</code>```

make sure the url you are trying to open starts with http or https

Body:
I have an app in production and some users get a weird ActivityNotFoundException about a VIEW https intent. I cannot reproduce it locally on my physical device or emulator. I also assume that every Android has a browser to open URLs by default, am I wrong? (None of the devices that encounter the bug is rooted). Could the problem be because the phone doesn't have chrome?

I use CustomTabsIntent to open the URLs:

public static void openUrl(final Uri url, final Activity activity) {
        CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
        builder.setToolbarColor(ContextCompat.getColor(activity, R.color.denis_red));
        builder.setCloseButtonIcon(
                BitmapFactory.decodeResource(activity.getResources(),
                        R.drawable.ic_arrow_back_white_24dp));
        builder.setStartAnimations(activity, R.anim.activity_slide_in_right,
                R.anim.activity_slide_out_left);
        builder.setExitAnimations(activity, R.anim.activity_slide_in_left,
                R.anim.activity_slide_out_right);
        builder.build().launchUrl(activity, url);
    }

I add some of the stack traces if it can help. Thanks!

1:

android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=https://redirect.denis.de/... (has extras) }
    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2031)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1686)
    at android.app.Activity.startActivityForResult(Activity.java:4506)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
    at android.app.Activity.startActivity(Activity.java:4825)
    at android.support.v4.content.ContextCompat.startActivity(ContextCompat.java:248)
    at android.support.customtabs.CustomTabsIntent.launchUrl(CustomTabsIntent.java:263)
    at de.boxine.denisapp.util.web.ChromeTabUtil.openUrl(ChromeTabUtil.java:26)
    at de.boxine.denisapp.denis.list.DenisListActivity.onOptionsItemSelected(DenisListActivity.java:82)
    at android.app.Activity.onMenuItemSelected(Activity.java:3469)
    at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:436)
    at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:196)
    at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:109)
    at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:109)
    at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:64)
    at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:204)
    at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:781)
    at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
    at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
    at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
    at android.support.v7.view.menu.MenuPopup.onItemClick(MenuPopup.java:128)
    at android.widget.AdapterView.performItemClick(AdapterView.java:318)
    at android.widget.AbsListView.performItemClick(AbsListView.java:1158)
    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3153)
    at android.widget.AbsListView$3.run(AbsListView.java:4068)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6626)
    at java.lang.reflect.Method.invoke(Method.java)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)

2:

android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=https://redirect.denis.de/... (has extras) }
    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1981)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1636)
    at android.app.Activity.startActivityForResult(Activity.java:4762)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
    at android.app.Activity.startActivity(Activity.java:5119)
    at android.support.v4.content.ContextCompat.startActivity(ContextCompat.java:248)
    at android.support.customtabs.CustomTabsIntent.launchUrl(CustomTabsIntent.java:263)
    at de.boxine.denisapp.util.web.ChromeTabUtil.openUrl(ChromeTabUtil.java:26)
    at de.boxine.denisapp.login.LoginActivity.openUrl(LoginActivity.java:205)
    at de.boxine.denisapp.login.LoginPresenter.onPasswordForgetLinkClicked(LoginPresenter.java:93)
    at de.boxine.denisapp.login.LoginActivity.lambda$onCreate$2$LoginActivity(LoginActivity.java:153)
    at de.boxine.denisapp.login.-$$Lambda$LoginActivity$HDjhvwi_2M2aWu9LndZHRP-ar9Q.onClick
    at android.view.View.performClick(View.java:6291)
    at android.view.View$PerformClick.run(View.java:24931)
    at android.os.Handler.handleCallback(Handler.java:808)
    at android.os.Handler.dispatchMessage(Handler.java:101)
    at android.os.Looper.loop(Looper.java:166)
    at android.app.ActivityThread.main(ActivityThread.java:7529)
    at java.lang.reflect.Method.invoke(Method.java)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)

Body:
String myUrl = "google.com";

if (!myUrl .startsWith("http://") && !myUrl .startsWith("https://")){
myUrl = "http://" + myUrl ;
}

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myUrl ));
startActivity(browserIntent);

make sure the url you are trying to open starts with http or https


来源: stackexchange

问:
Does TeamCity Multi nodes setup increases the agents number?
Does anyone tried to use TeamCity MultiNodes setup, and know if the agents number grows with each agent?
Normally  Teamcity comes with 3 agents provided by professional edition license.
And if we need more we can buy additional license key.
Now, in case of MultiNode TeamCity setup of 3 nodes, we will have only 3 agetns, or 9 ?</p>

答:
This is the answer JetBrain answer:
In multi-node setup, the main and secondary nodes operate under the same license, so three-node setup would still have 3 agents available in absence of extra license keys.</p>

ContentLicense: CC BY-SA 4.0


问:
"Does not provide an export named 'Tooltip'," even though I can output Tooltip
When this code runs:

```<code>// index.svelte
import Chart, { Tooltip } from 'chart.js/auto.esm';
console.log({ Tooltip });
</code>```

Tooltip is successfully output to the console, but I also get an error (in the browser):

The requested module '/node_modules/.vite/chart_js_auto.js?v=9674d8be' does not provide an export named 'Tooltip'

So SvelteKit is obviously running this code multiple times. Why does it work once, then fail later? How do I get it to work all the time?

I imported 'chart.js/auto.esm' instead of just 'chart.js' because SvelteKit needs ESM modules. I can import { Tooltip } from 'chart.js' and this works locally, but a there's a different build error on Vercel:

SyntaxError: Named export 'Tooltip' not found. The requested module
'chart.js' is a CommonJS module, which may not support all
module.exports as named exports.

答:
This is because when you import from chart.js/auto it registers everything for you and will make it available, but only exports the chart.

If you want to specifically import the Tooltip you will need to import it like so:

import {Tooltip} from 'chart.js'
```

Keep in mind that if you do it like this you will need to import and register every functionality you are using yourself

Body:
When this code runs:

// index.svelte
import Chart, { Tooltip } from 'chart.js/auto.esm';
console.log({ Tooltip });

Tooltip is successfully output to the console, but I also get an error (in the browser):

The requested module '/node_modules/.vite/chart_js_auto.js?v=9674d8be' does not provide an export named 'Tooltip'

So SvelteKit is obviously running this code multiple times. Why does it work once, then fail later? How do I get it to work all the time?

I imported 'chart.js/auto.esm' instead of just 'chart.js' because SvelteKit needs ESM modules. I can import { Tooltip } from 'chart.js' and this works locally, but a there's a different build error on Vercel:

SyntaxError: Named export 'Tooltip' not found. The requested module
'chart.js' is a CommonJS module, which may not support all
module.exports as named exports.

Body:
This is because when you import from chart.js/auto it registers everything for you and will make it available, but only exports the chart.

If you want to specifically import the Tooltip you will need to import it like so:

import {Tooltip} from 'chart.js'

Keep in mind that if you do it like this you will need to import and register every functionality you are using yourself


问:
How to use a loop then calculate the sum of a list?
I need to write a function "sum_reciprocals()" which takes 1 input argument, a positive integer "n", and returns 1 output value, the sum of the reciprocals of all integers from 1 to n (inclusive).
The result should be returned as a floating point number, and rounded to 5 decimal places.

here is my code

```<code>def sum_reciprocals(n):
    x = [1]
    n = 10000
    for i in range(2,n+1):
        x.append(x[i-2]+1/x[i-1])
    sum_reciprocals = round(sum(x))
    return sum_reciprocals
</code>```

But it says that "IndexError: list index out of range" on my fifth line.

答:
Can't really understand what's the point of this

```<code>x.append(x[i - 2] + 1 / x[i - 1])
</code>```

You can just iterate from 1 to n with i and add 1 / i to the total sum, like so

```<code>def sum_reciprocals(n):
    total = 0
    for i in range(1, n + 1):
        total += 1 / i

    return total
</code>```

or using list comprehension with sum() function

```<code>def sum_reciprocals(n):
    return sum([1 / i for i in range(1, n + 1)])
</code>```

or even adding lambda expression to this

```<code> sum_reciprocals = lambda n: sum([1 / i for i in range(1, n + 1)])
</code>```

Although last one will be a violation of PEP 8 E731 Code style standart (but it's good to know you can do that)

Body:
I need to write a function "sum_reciprocals()" which takes 1 input argument, a positive integer "n", and returns 1 output value, the sum of the reciprocals of all integers from 1 to n (inclusive).
The result should be returned as a floating point number, and rounded to 5 decimal places.

here is my code

def sum_reciprocals(n):
    x = [1]
    n = 10000
    for i in range(2,n+1):
        x.append(x[i-2]+1/x[i-1])
    sum_reciprocals = round(sum(x))
    return sum_reciprocals

But it says that "IndexError: list index out of range" on my fifth line.

Body:
Can't really understand what's the point of this

x.append(x[i - 2] + 1 / x[i - 1])

You can just iterate from 1 to n with i and add 1 / i to the total sum, like so

def sum_reciprocals(n):
    total = 0
    for i in range(1, n + 1):
        total += 1 / i

    return total

or using list comprehension with sum() function

def sum_reciprocals(n):
    return sum([1 / i for i in range(1, n + 1)])

or even adding lambda expression to this

 sum_reciprocals = lambda n: sum([1 / i for i in range(1, n + 1)])

Although last one will be a violation of PEP 8 E731 Code style standart (but it's good to know you can do that)


问:
How do I filter query objects by date range in Django?
I've got a field in one model like:

```<code>class Sample(models.Model):
    date = fields.DateField(auto_now=False)
</code>```

Now, I need to filter the objects by a date range.

How do I filter all the objects that have a date between 1-Jan-2011 and 31-Jan-2011?

答:
Model

```<code>date = models.DateField()
</code>```

View

```<code>def get_queryset(self):

    fromDate = self.request.query_params.get('fromDate',None)
    toDate = self.request.query_params.get('toDate',None)
    response  = yourModel.objects.filter(date__gte=fromDate,date__lte=toDate)
    return response
</code>```

Body:
I've got a field in one model like:

class Sample(models.Model):
    date = fields.DateField(auto_now=False)

Now, I need to filter the objects by a date range.

How do I filter all the objects that have a date between 1-Jan-2011 and 31-Jan-2011?

Body:
Model

date = models.DateField()

View

def get_queryset(self):

    fromDate = self.request.query_params.get('fromDate',None)
    toDate = self.request.query_params.get('toDate',None)
    response  = yourModel.objects.filter(date__gte=fromDate,date__lte=toDate)
    return response


问:
how to choose best mechanism for delete logs saved to mongodb
I'm implementing a logger using MongoDB and I'm quite new to the concept.
The logger is supposed to log each request and Its response.
I'm facing the question of using the TTL Index of mongo or just using the query overnight approach.

I think that the first method might bring some overhead by using a background thread and probably rebuilding the index after each deletion but, it frees space as soon as the documents expire and this might be beneficial.
The second approach, on the other hand, does not have this kind of overhead but it frees up space just at the end of each day.

It seems to me that the second approach will suit my case better as it would not be the case that my server just goes on the edge of not having enough disk space, but it will always be the case that we need to reduce the overhead on the server.

I'm wondering if there are some aspects to the subject that I'm missing and also I'm not sure about the applications of the MongoDB TTL.

答:
Just my opinion:

It seems to be best to store logs in monthly , daily or hourly collection depends on your applications write load , and at the end of the day to just drop() the oldest  collections with custom script. From experience TTL indices not working well when there is heavy write load to your collection since they add additional write load based on expiration time.

For example imagine you insert at 06:00h log events with 100k/sec and your TTL index life time is set to 3h , this mean after 3h  at 09:00h you will have those 100k/sec deletes applied to your collection that are also stored in the oplog ...  , solution in such cases is to add more shards , but it become kind of expensive... , far easier is to just drop the exprired collection ...

Moreover depending on your project size for bigger collections to speed up searches you can additionally shard and pre-split the collections based on compound index hashed datetime field(every log contain timestamp) with another field which you will search often and this will allow you scalable search across multiple distributed shards.

Also note mongoDB is a general purpose document database and fulltext search is kind of limited to expensinve regex expressions , so in case you need to do fast raw fulltext search in your logs  some inverse index search engine like elasticsearch on top of your mongoDB backand maybe a good solution to cover this functionality.


问:
How to insert list at specific position into list of lists
I want to know if it is possible to insert a list of floats into a list of lists at a specific position and how to index it or if I should consider using a different datatype (like an array or dictionary) instead:

As an example:

```<code>list_to_insert = [0.7, 0.3, 0.85, -0.1, 0.4]

list_of_lists = [[[], []],
                [[], [], [], [], [], []],
                [[], [], [], [], [], []],
                [[], []]]

=> list_of_lists = [[[], []],
                   [[], [], [], [], [], []],
                   [[], [], [], [], [list_to_insert], []],
                   [[], []]]
</code>```

答:
You can insert in a list of lists like

```<code>list_of_lists[2].insert(4,list_to_insert)
</code>```

However in the output you gave the element isn't inserted rather replaced.
So to get that output

```<code>list_of_lists[2][4]=list_to_insert
</code>```

Body:
I want to know if it is possible to insert a list of floats into a list of lists at a specific position and how to index it or if I should consider using a different datatype (like an array or dictionary) instead:

As an example:

list_to_insert = [0.7, 0.3, 0.85, -0.1, 0.4]

list_of_lists = [[[], []],
                [[], [], [], [], [], []],
                [[], [], [], [], [], []],
                [[], []]]

=> list_of_lists = [[[], []],
                   [[], [], [], [], [], []],
                   [[], [], [], [], [list_to_insert], []],
                   [[], []]]

Body:
You can insert in a list of lists like

list_of_lists[2].insert(4,list_to_insert)

However in the output you gave the element isn't inserted rather replaced.
So to get that output

list_of_lists[2][4]=list_to_insert


问:
How to filter null returning method in stream?
I have a list, it has some method like getSummary(), and this method returns null in some cases. How can I filter to avoid getting the null result?

Here is my code:

```<code>List<Event> items = getEvents(sharedCalendarId, startDateTime, endDateTime, zoneId);

if (CollectionUtils.isNotEmpty(items)) {
    openingHoursDto.setBranches(items.stream()
            .collect(Collectors.groupingBy(Event::getSummary))
            .entrySet()
            .stream()
            .map(e -> {
                LibraryBranchOpeningHoursDto lBOHDto = new LibraryBranchOpeningHoursDto();
                lBOHDto.setName(e.getKey());
                lBOHDto.setDates(getHoursDtoMap(e.getValue(), startDateTime, endDateTime, selfServicePattern, specialHoursColorId, zoneId));
                return lBOHDto;
            })
            .sorted(comparing(LibraryBranchOpeningHoursDto::getName))
            .collect(Collectors.toList()));
    return openingHoursDto;
}
</code>```

答: Or you can use .stream() .filter(Objects::notNull)

Body:
I have a list, it has some method like getSummary(), and this method returns null in some cases. How can I filter to avoid getting the null result?

Here is my code:

List<Event> items = getEvents(sharedCalendarId, startDateTime, endDateTime, zoneId);

if (CollectionUtils.isNotEmpty(items)) {
    openingHoursDto.setBranches(items.stream()
            .collect(Collectors.groupingBy(Event::getSummary))
            .entrySet()
            .stream()
            .map(e -> {
                LibraryBranchOpeningHoursDto lBOHDto = new LibraryBranchOpeningHoursDto();
                lBOHDto.setName(e.getKey());
                lBOHDto.setDates(getHoursDtoMap(e.getValue(), startDateTime, endDateTime, selfServicePattern, specialHoursColorId, zoneId));
                return lBOHDto;
            })
            .sorted(comparing(LibraryBranchOpeningHoursDto::getName))
            .collect(Collectors.toList()));
    return openingHoursDto;
}


问:
How to tell MEF to re-create object?
I'm using mef to create WCF web services. This is how service looks:

```<code>[Export]
    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class MobileService
    {
        [Import]
        public IEmailService EmailService { get; set; }

        [Import]
        public ILoggerService LoggerService { get; set; }

        [Import]
        public IContextManager ContextManager { get; set; }
</code>```

This is how code to retreive service instance looks:

```<code>// Get Service instace via MEF
    public object GetInstance(InstanceContext instanceContext, Message message)
    {
        var lazyInstance = Container.GetExports(ServiceType, null, null).FirstOrDefault();
        var instance = lazyInstance.Value;

        return instance;
    }
</code>```

MEF creates EmailService, LoggerService and this if fine, they live happily while service lives.

Now, ContextManager is different animal. In GetInstance - I really like to "kill" it and re-create. ContextManager studies URL and headers during construction and populates "context". With code like I have - it is created first time and never get's destroyed. How to change this behavior?

Thanks!

答:
You can make the part's creation be "NonShared" by setting it on a PartCreationPolicyAttribute on the exported class, or the RequiredCreationPolicy property of an ImportAttribute.

This will create a new instance of the class with the export every time an import is satisfied.  If this isn't exactly what you want, you may want to look at ExportFactory or scoped containers.  However if you are using the .NET 4 version of MEF, ExportFactory isn't supported and you have to do a lot more work for scoping.  You can get a preview of the next version of MEF at mef.codeplex.com.

ContentLicense: CC BY-SA 3.0

Title: How to tell MEF to re-create object?

Body:
I'm using mef to create WCF web services. This is how service looks:

[Export]
    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class MobileService
    {
        [Import]
        public IEmailService EmailService { get; set; }

        [Import]
        public ILoggerService LoggerService { get; set; }

        [Import]
        public IContextManager ContextManager { get; set; }

This is how code to retreive service instance looks:

// Get Service instace via MEF
    public object GetInstance(InstanceContext instanceContext, Message message)
    {
        var lazyInstance = Container.GetExports(ServiceType, null, null).FirstOrDefault();
        var instance = lazyInstance.Value;

        return instance;
    }

MEF creates EmailService, LoggerService and this if fine, they live happily while service lives.

Now, ContextManager is different animal. In GetInstance - I really like to "kill" it and re-create. ContextManager studies URL and headers during construction and populates "context". With code like I have - it is created first time and never get's destroyed. How to change this behavior?

Thanks!


问:
appInsights.setup().start(); returns an error
I'm using appInsights v2.1.4 in my NodeJs Azure Function.
The app key in provided by the APPINSIGHTS_INSTRUMENTATIONKEY variable in the function configuration.

I have setup a class as such

const appInsights = require('applicationinsights');

class AppInsightsLog {
    error (context, eventName, error) {
        context.log.error(error);

        appInsights.setup().start();
        const client = appInsights.defaultClient;
        client.trackEvent({ name: `Catch error: ${eventName}`, properties: error });
    }

    info (context, eventName, extraInfo = null) {
        context.log.info(eventName);

        appInsights.setup().start();
        const client = appInsights.defaultClient;
        client.trackEvent({ name: `Log info: ${eventName}`, properties: extraInfo });
    }
}

module.exports = { AppInsightsLog };
```
<p>And using it like so</p>
<pre class="lang-js prettyprint-override"><code>/* ... other imports before it ... */
const { AppInsightsLog } = require('../../../utils/AppInsightsLog');
const appInsightsLog = new AppInsightsLog();

class Post {
    async data (context, feedRow) {
        try {
            ...
            appInsightsLog.info(context, `processing feed: ${feedRow.feedtype}`);
            ....
        } catch (error) {
            appInsightsLog.error(context, 'ProcessRawDataQueue', error);
            return { statusCode: 500, body: error.message };
        }
    }
}
</code>```

I'm getting this error:

[Error] TypeError: api_1.createContextKey is not a functionat Object. (D:\home\site\wwwroot\node_modules@opentelemetry\core\build\src\trace\suppress-tracing.js:20:36)at Module._compile (internal/modules/cjs/loader.js:999:30)at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)at Module.load (internal/modules/cjs/loader.js:863:32)at Function.Module._load (internal/modules/cjs/loader.js:708:14)at Module.require (internal/modules/cjs/loader.js:887:19)at Module.patchedRequire [as require] (D:\home\site\wwwroot\node_modules\diagnostic-channel\dist\src\patchRequire.js:15:46)at require (internal/modules/cjs/helpers.js:74:18)at Object. (D:\home\site\wwwroot\node_modules@opentelemetry\core\build\src\baggage\propagation\HttpBaggagePropagator.js:20:28)at Module._compile (internal/modules/cjs/loader.js:999:30)

Any ideas what is wrong?

答:
Just upgrading @azure/storage-blob doesn't neccesarily fix the issue. For me what worked correctly was having these two dependencies with these versions:

    {
      "dependencies": {
        "@azure/storage-blob": "^12.0.1",
        "applicationinsights": "^2.2.1",
      }
    }
```

I guess there is some incompatibility between some versions

Body:
I'm using appInsights v2.1.4 in my NodeJs Azure Function.
The app key in provided by the APPINSIGHTS_INSTRUMENTATIONKEY variable in the function configuration.

I have setup a class as such

const appInsights = require('applicationinsights');

class AppInsightsLog {
    error (context, eventName, error) {
        context.log.error(error);

        appInsights.setup().start();
        const client = appInsights.defaultClient;
        client.trackEvent({ name: `Catch error: ${eventName}`, properties: error });
    }

    info (context, eventName, extraInfo = null) {
        context.log.info(eventName);

        appInsights.setup().start();
        const client = appInsights.defaultClient;
        client.trackEvent({ name: `Log info: ${eventName}`, properties: extraInfo });
    }
}

module.exports = { AppInsightsLog };

And using it like so

/* ... other imports before it ... */
const { AppInsightsLog } = require('../../../utils/AppInsightsLog');
const appInsightsLog = new AppInsightsLog();

class Post {
    async data (context, feedRow) {
        try {
            ...
            appInsightsLog.info(context, `processing feed: ${feedRow.feedtype}`);
            ....
        } catch (error) {
            appInsightsLog.error(context, 'ProcessRawDataQueue', error);
            return { statusCode: 500, body: error.message };
        }
    }
}

I'm getting this error:

[Error] TypeError: api_1.createContextKey is not a functionat Object. (D:\home\site\wwwroot\node_modules@opentelemetry\core\build\src\trace\suppress-tracing.js:20:36)at Module._compile (internal/modules/cjs/loader.js:999:30)at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)at Module.load (internal/modules/cjs/loader.js:863:32)at Function.Module._load (internal/modules/cjs/loader.js:708:14)at Module.require (internal/modules/cjs/loader.js:887:19)at Module.patchedRequire [as require] (D:\home\site\wwwroot\node_modules\diagnostic-channel\dist\src\patchRequire.js:15:46)at require (internal/modules/cjs/helpers.js:74:18)at Object. (D:\home\site\wwwroot\node_modules@opentelemetry\core\build\src\baggage\propagation\HttpBaggagePropagator.js:20:28)at Module._compile (internal/modules/cjs/loader.js:999:30)

Any ideas what is wrong?

Body:
Just upgrading @azure/storage-blob doesn't neccesarily fix the issue. For me what worked correctly was having these two dependencies with these versions:

    {
      "dependencies": {
        "@azure/storage-blob": "^12.0.1",
        "applicationinsights": "^2.2.1",
      }
    }

I guess there is some incompatibility between some versions


问:
Is it necessary to put space after $this keyword in OOP PHP according to PSRs?
I studied PSR-2 and PSR-12 documentations completely but didn't find any explanation regarding whether to put any space after $this keyword.

My exact question is which one of following styles is more correct according to PSRs:

```<code>return $this->name;
</code>```

or

```<code>return $this -> name;
</code>```

sample codes to compare would be as below:

```<code>class Car
{
    public $name;
    public function getName()
    {
        return $this->name; // I've always seen this style (no spaces)
    }
}
</code>```

in comparison with:

```<code>class Car
{
    public $name;
    public function getName()
    {
        return $this -> name; // Includes spaces
    }
}
</code>```

Are both correct? If so, is there a reason to use one over the other?

答:
Both are permitted by the standards.

Having "spaces" around the object operator (->) is not forbidden by any of the PSR standards. And it's legal.

Whitespace around this is not regulated simply because sometimes when writing fluent interfaces it can make sense to separate the chained calls with whitespace. E.g.:

```<code>$foo->bar()
    ->baz()
    ->fizz()
    ->fizzBuzz();
</code>```

And forbidding this would make not particular sense.

While additional language could have been added to account for this and other cases, it wasn't. Maybe it wasn't considered by the commitee, maybe it was considered a given that the common practice of the PHP community would prevail without needing an additional standard. Why they wouldn't add this specific language is not particularly important.

However, your example of using whitespace like this:

```<code>$foo -> bar();
</code>```

Simply difficults reading and provides no advantage. While not illegal, and not against the coding style PSRs, it's simply a bad idea.

Body:
I studied PSR-2 and PSR-12 documentations completely but didn't find any explanation regarding whether to put any space after $this keyword.

My exact question is which one of following styles is more correct according to PSRs:

return $this->name;

or

return $this -> name;

sample codes to compare would be as below:

class Car
{
    public $name;
    public function getName()
    {
        return $this->name; // I've always seen this style (no spaces)
    }
}

in comparison with:

class Car
{
    public $name;
    public function getName()
    {
        return $this -> name; // Includes spaces
    }
}

Are both correct? If so, is there a reason to use one over the other?

Body:
Both are permitted by the standards.

Having "spaces" around the object operator (->) is not forbidden by any of the PSR standards. And it's legal.

Whitespace around this is not regulated simply because sometimes when writing fluent interfaces it can make sense to separate the chained calls with whitespace. E.g.:

$foo->bar()
    ->baz()
    ->fizz()
    ->fizzBuzz();

And forbidding this would make not particular sense.

While additional language could have been added to account for this and other cases, it wasn't. Maybe it wasn't considered by the commitee, maybe it was considered a given that the common practice of the PHP community would prevail without needing an additional standard. Why they wouldn't add this specific language is not particularly important.

However, your example of using whitespace like this:

$foo -> bar();

Simply difficults reading and provides no advantage. While not illegal, and not against the coding style PSRs, it's simply a bad idea.


问:
How do I create a file and write to it?
What's the simplest way to create and write to a (text) file in Java?</p>

答:
Below is the code to write the file and also deleted on exit for help content web page :</p>
```<code>public String writeHelpContent(String filePath, String helpPageContent) throws IOException{
        logger.info("HowToUseRiskOfficeHelpService - writeHelpContent start");
        File file = new File(filePath);
        try(FileWriter fw = new FileWriter(file);){
            file.deleteOnExit();
            if(file.createNewFile()) {
                logger.info("HowToUseRiskOfficeHelpService - file created successfully");
            }else {
                logger.info("HowToUseRiskOfficeHelpService - file already exists");
            }
            fw.write(helpPageContent);
            fw.flush();
        }

        return "Sucessfully write into help page file";
    }
</code>```

Title: How do I create a file and write to it?

Body:
Below is the code to write the file and also deleted on exit for help content web page :

public String writeHelpContent(String filePath, String helpPageContent) throws IOException{
        logger.info("HowToUseRiskOfficeHelpService - writeHelpContent start");
        File file = new File(filePath);
        try(FileWriter fw = new FileWriter(file);){
            file.deleteOnExit();
            if(file.createNewFile()) {
                logger.info("HowToUseRiskOfficeHelpService - file created successfully");
            }else {
                logger.info("HowToUseRiskOfficeHelpService - file already exists");
            }
            fw.write(helpPageContent);
            fw.flush();
        }

        return "Sucessfully write into help page file";
    }


问:
How to name subelements according to BEM?
I have a question regarding BEM (Block Element Modifier) class naming conventions.

What if I need to have 3 nested divs, how should I name the class of the 3rd one?

.one{} //block
.one__two{} //block element
//?```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="one">
  <div class="one__two">

    <!-- How should I rename class "three"? -->
    <div class="three"></div>

  </div>
</div></code>```

I want to rename ".three" to "one__two__three", or "two__three", but I'm not sure that this is right, because as I understand, according to BEM nesting elements inside of elements is not allowed.

答:
Nesting elements is fine; build the structure to your needs. The important thing is to not couple the classnames to your nesting. The classname schema does really only recognize two types of DOM elements: the block itself and the elements of that block; of the latter all are equal regarding the naming schema, no matter how deeply nested in the block.
Here is an example:

    Encabulator
    The turbo shmeerf of all Shmoof

    Lorem ipsum shmeerf of Shmoof quooz bar moof bla bla

    Buy it!

```
<p>And modifiers are added as needed:</p>
<pre class="lang-html prettyprint-override"><code>  <div class="product-card__footer">

      Buy it! 50% off for first-time customers!!!!!! OMG!!!!

  </div>
</code>```

Body:
I have a question regarding BEM (Block Element Modifier) class naming conventions.

What if I need to have 3 nested divs, how should I name the class of the 3rd one?

.one{} //block
.one__two{} //block element
//?

I want to rename ".three" to "one__two__three", or "two__three", but I'm not sure that this is right, because as I understand, according to BEM nesting elements inside of elements is not allowed.

Body:
Nesting elements is fine; build the structure to your needs. The important thing is to not couple the classnames to your nesting. The classname schema does really only recognize two types of DOM elements: the block itself and the elements of that block; of the latter all are equal regarding the naming schema, no matter how deeply nested in the block.
Here is an example:

<div class="product-card">
  <div class="product-card__img-area">
    <img class="product-card__product-picture" src="https://example.com/cabulator.jpg"/>
  </div>
  <div class="product-card__header">
    <span class="product-card__main-headline">Encabulator</span>
    <span class="product-card__sub-headline">The turbo shmeerf of all Shmoof</span>
  </div>
  <div class="product-card__text-body">
    Lorem ipsum shmeerf of Shmoof quooz bar moof bla bla
  </div>
  <div class="product-card__footer">
    <a class="product-card__cta" href="https://example.com/buy.html">Buy it!</a>
  </div>
</div>

And modifiers are added as needed:

  <div class="product-card__footer">
    <a class="product-card__cta product-card__cta--bargain" href="http://exmpl.com/buy">
      Buy it! 50% off for first-time customers!!!!!! OMG!!!!
    </a>
  </div>


问:
How to pass the latitude and longitude values to the ns url as a arguments?
Iam developing one application.In that i use the google api for getting the location information.For that i use the CLLocationManager for getting the location latitude and longitude values.And my pblm is how to pass these latitude and longitude values to nsurl .ANd iam directly given the one location values to the url like below.

```<code> NSURL *URL = [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search           /json?location=40.7143528,-74.0059731&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM"];
</code>```

I write this one in below method for get and pass the latitude and longitude values.

```<code>   - (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
}
</code>```

So please tell me how to pass the newlocation.Coordinates.latitude and newlocation.Coordinates.longitude to that url in that method.

With others suggestions i changed the code like below.

```<code>    - (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{

    NSString *address = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f, %f&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM", newLocation.lattitude, newLocation.longitude];
    NSURL *url = [NSURL URLFromString:address];
}
</code>```

This also gives the error like Exe_Bad_Access when the first line executed.SO please tell me how to write that one.

答:
This will work: </p>

```<code>- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {
    NSString *address = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f, %f&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM", newLocation.coordinate.latitude, newLocation.coordinate.longitude];
    NSURL *url = [NSURL URLFromString:address];
}
</code>```

Body:
Iam developing one application.In that i use the google api for getting the location information.For that i use the CLLocationManager for getting the location latitude and longitude values.And my pblm is how to pass these latitude and longitude values to nsurl .ANd iam directly given the one location values to the url like below.

 NSURL *URL = [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search           /json?location=40.7143528,-74.0059731&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM"];

I write this one in below method for get and pass the latitude and longitude values.

   - (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
}

So please tell me how to pass the newlocation.Coordinates.latitude and newlocation.Coordinates.longitude to that url in that method.

With others suggestions i changed the code like below.

    - (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{

    NSString *address = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f, %f&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM", newLocation.lattitude, newLocation.longitude];
    NSURL *url = [NSURL URLFromString:address];
}

This also gives the error like Exe_Bad_Access when the first line executed.SO please tell me how to write that one.

Body:
This will work:

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {
    NSString *address = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f, %f&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM", newLocation.coordinate.latitude, newLocation.coordinate.longitude];
    NSURL *url = [NSURL URLFromString:address];
}


问:
How to change state without re-rendering in react native
I am making an app which is calling an API repeatedly and changing state, and I have another function which is listening to an event and update some state but I want to update it without re-rendering because it causes some unwanted behaviour to chain of repeatedly API calling,

Any help will be appreciated.

答: If you want to store some data without triggering rerender, use useRef() hook for this instead of useState.


问:
Element not clickable, ElementClickInterceptedException in Selenium
A similar question has been asked many times, and I have gone over many of them, such as Debugging "Element is not clickable at point" error
, Selenium Webdriver - element not clickable error in firefox, ElementClickInterceptedException: Message: element click intercepted:

but haven't been able to solve my problem.

I want to select a subset of car brands from the websites search dropdown menu. Usually I would do it via Selenium's Select, but that doesn't do the trick here.

Here's my code.

```<code>from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.proxy import Proxy, ProxyType
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

ser = Service(executable_path= r'D:\chromedriver.exe')

#Note I have omitted the options that I use (proxy and header).
driver = webdriver.Chrome(service = ser)
driver.get("https://www.autotalli.com/")
time.sleep(5)

# Accepting cookies
driver.find_element(by = By.XPATH, value  = "//button[contains(text(),'Asetuks')]").click()
time.sleep(5)
driver.find_element(by = By.XPATH, value  = "//button[contains(text(),'Tallenna')]").click()
driver.maximize_window()
time.sleep(5)

#selecting parameters from the dropdown menu
element = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "//*[@class = 'mbsc-input-wrap']")))
element.click()

element = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "//*[@data-val = '66-duplicated']")))
element.click()
element = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "//*[@class = 'mbsc-input-wrap']")))
element.click()
element = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "//*[@data-val = '10-duplicated']")))
element.click()
</code>```

What throws me off is that the code works for the 66-duplicated element but not for the 10-duplicated element, and the two are identical in every way. The error I get is

```<code>Exception has occurred: ElementClickInterceptedException
Message: element click intercepted: Element <div role="option" tabindex="-1" aria-selected="false" class="mbsc-sc-itm mbsc-sel-gr-itm  mbsc-btn-e" data-index="2" data-val="10-duplicated" style="height:40px;line-height:40px;">...</div> is not clickable at point (268, 217). Other element would receive the click: <input tabindex="0" type="text" class="mbsc-sel-filter-input mbsc-control" placeholder="Hae">
</code>```

To to solve this, I have tried to use javascript, move to the element and then click and maximize the window - None of which worked.

```<code>#Attempt 1:js:
driver.execute_script("arguments[0].click()", element)

#Attempt 2: moveToElement:

element = driver.find_element(by = By.XPATH, value  = "//*[@data-val = '10-duplicated']")
actions = ActionChains(driver)
actions.move_to_element(element).perform()
element = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "//*[@data-val = '10-duplicated']")))
element.click()
</code>```

I have also tried a combination of these but to no avail.

However,when I put a break point right before the click of element "10-duplicated" and manually scroll and move the mouse to the element, and run the remaining code, it works.

I am quite puzzled here. What's going on and how can this problem be solved?

答:
There are 17 matches for //*[@class = 'mbsc-input-wrap'] locator on that page, but you are opening the same, first match 2 times. That is Merkit droplist.

Now, when selecting //*[@data-val = '66-duplicated'] (Nissan)  from the opened droplist this will work since that option is within the visible options but when Nissan is currently selected //*[@data-val = '10-duplicated'] (BMW) option in not visible, you can not click it directly.

In order to select it now you will have to

Cancel the previous selection of Nissan so that BMW will become initially visible by opening the droplist.

Scroll the droplist

Click the //*[@data-val = '10-duplicated'] with JavaScript - not recommended since this is not what human user can do via GUI.

I will give you a code to make the first approach - cancelling the previous Nissan selection.

I have also made some improvements there.

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.proxy import Proxy, ProxyType
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

ser = Service(executable_path= r'D:\chromedriver.exe')

#Note I have omitted the options that I use (proxy and header).
driver = webdriver.Chrome(service = ser)
driver.get("https://www.autotalli.com/")
wait = WebDriverWait(driver, 20)

time.sleep(5)

# Accepting cookies
driver.find_element(by = By.XPATH, value  = "//button[contains(text(),'Asetuks')]").click()
time.sleep(5)
driver.find_element(by = By.XPATH, value  = "//button[contains(text(),'Tallenna')]").click()
driver.maximize_window()
time.sleep(5)

#selecting parameters from the dropdown menu
wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@class = 'mbsc-input-wrap']"))).click()

wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@data-val = '66-duplicated']"))).click()
#clear the previously selected NIssan option
wait.until(EC.element_to_be_clickable((By.XPATH, "//span[contains(@class,'usedCarsMakeClear clearOption')]"))).click()

wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@class = 'mbsc-input-wrap']"))).click()

wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@data-val = '10-duplicated']"))).click()

```

Body:
A similar question has been asked many times, and I have gone over many of them, such as Debugging "Element is not clickable at point" error
, Selenium Webdriver - element not clickable error in firefox, ElementClickInterceptedException: Message: element click intercepted:

but haven't been able to solve my problem.

I want to select a subset of car brands from the websites search dropdown menu. Usually I would do it via Selenium's Select, but that doesn't do the trick here.

Here's my code.

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.proxy import Proxy, ProxyType
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

ser = Service(executable_path= r'D:\chromedriver.exe')

#Note I have omitted the options that I use (proxy and header).
driver = webdriver.Chrome(service = ser)
driver.get("https://www.autotalli.com/")
time.sleep(5)

# Accepting cookies
driver.find_element(by = By.XPATH, value  = "//button[contains(text(),'Asetuks')]").click()
time.sleep(5)
driver.find_element(by = By.XPATH, value  = "//button[contains(text(),'Tallenna')]").click()
driver.maximize_window()
time.sleep(5)

#selecting parameters from the dropdown menu
element = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "//*[@class = 'mbsc-input-wrap']")))
element.click()

element = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "//*[@data-val = '66-duplicated']")))
element.click()
element = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "//*[@class = 'mbsc-input-wrap']")))
element.click()
element = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "//*[@data-val = '10-duplicated']")))
element.click()

What throws me off is that the code works for the 66-duplicated element but not for the 10-duplicated element, and the two are identical in every way. The error I get is

Exception has occurred: ElementClickInterceptedException
Message: element click intercepted: Element
...
 is not clickable at point (268, 217). Other element would receive the click: <input tabindex="0" type="text" class="mbsc-sel-filter-input mbsc-control" placeholder="Hae">

To to solve this, I have tried to use javascript, move to the element and then click and maximize the window - None of which worked.

#Attempt 1:js:
driver.execute_script("arguments[0].click()", element)

#Attempt 2: moveToElement:

element = driver.find_element(by = By.XPATH, value  = "//*[@data-val = '10-duplicated']")
actions = ActionChains(driver)
actions.move_to_element(element).perform()
element = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "//*[@data-val = '10-duplicated']")))
element.click()

I have also tried a combination of these but to no avail.

However,when I put a break point right before the click of element "10-duplicated" and manually scroll and move the mouse to the element, and run the remaining code, it works.

I am quite puzzled here. What's going on and how can this problem be solved?


问:
Cannot deserialize value of type `java.lang.String` from Array value from mockmvc
```<code>public class ModelDTO implements Serializable {

    private Long id;
    private String datasetName;

    @JsonRawValue
    private String json;
}
</code>```

Post API is working fine from postman or swagger if I send the following body.

```<code>{
  "id": 1,
  "datasetName": "Insurance",
  "json" : "[{\"ClassName\":\"AAAA\",\"Fields\":[[\"cdsa\",\"csa\"],[\"ca\"]]},{\"ClassName\":\"ca\",\"Fields\":[null]}]"
}
</code>```

But MockMVC test case is giving follwing error in Spring boot project

Bad Request: JSON parse error: Unexpected character ('C' (code 67)): was expecting comma to separate Object entries; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('C' (code 67)): was expecting comma to separate Object entries
at [Source: (PushbackInputStream); line: 1, column: 89]

```<code>mockMvc.perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(ModelDTO))).andExpect(status().isCreated());
</code>```

答:
my json were not properly set. it requires backword slash for parsing.
I have added extra two backword slash like '\' and now it is working.

```<code>private static final String DEFAULT_JSON = "\"[{\\\"ClassName\\\":\\\"Health Aditya Birla\\\",\\\"Fields\\\":[[\\\"Insured Person's Details\\\",\\\"Gender\\\",\\\"Member ID\\\"],[\\\"Policy Details\\\",\\\"Insured Person's Details\\\"],[\\\"Premium Certificate\\\"]]},{\\\"ClassName\\\":\\\"Health Care\\\",\\\"Fields\\\":[[\\\"Details of Insured\\\",\\\"Relationship\\\",\\\"Date Of Birth\\\"],[\\\"Mobile No\\\"],[\\\"Gross Premium\\\",\\\"Goods & Services Tax\\\"]]}]\"";
</code>```

I have referred following link to solve this issue.

enter link description here

Body:
public class ModelDTO implements Serializable {

    private Long id;
    private String datasetName;

    @JsonRawValue
    private String json;
}

Post API is working fine from postman or swagger if I send the following body.

{
  "id": 1,
  "datasetName": "Insurance",
  "json" : "[{\"ClassName\":\"AAAA\",\"Fields\":[[\"cdsa\",\"csa\"],[\"ca\"]]},{\"ClassName\":\"ca\",\"Fields\":[null]}]"
}

But MockMVC test case is giving follwing error in Spring boot project

Bad Request: JSON parse error: Unexpected character ('C' (code 67)): was expecting comma to separate Object entries; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('C' (code 67)): was expecting comma to separate Object entries
at [Source: (PushbackInputStream); line: 1, column: 89]

mockMvc.perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(ModelDTO))).andExpect(status().isCreated());

Body:
my json were not properly set. it requires backword slash for parsing.
I have added extra two backword slash like '\' and now it is working.

private static final String DEFAULT_JSON = "\"[{\\\"ClassName\\\":\\\"Health Aditya Birla\\\",\\\"Fields\\\":[[\\\"Insured Person's Details\\\",\\\"Gender\\\",\\\"Member ID\\\"],[\\\"Policy Details\\\",\\\"Insured Person's Details\\\"],[\\\"Premium Certificate\\\"]]},{\\\"ClassName\\\":\\\"Health Care\\\",\\\"Fields\\\":[[\\\"Details of Insured\\\",\\\"Relationship\\\",\\\"Date Of Birth\\\"],[\\\"Mobile No\\\"],[\\\"Gross Premium\\\",\\\"Goods & Services Tax\\\"]]}]\"";

I have referred following link to solve this issue.

enter link description here


问:
Attempting to add a "delete" button to existing "details" view
I am working on a group project that allows users to create, store, edit, and delete notes.

We are able to access the stored notes via a very basic "details" view, and would like to make the "delete" functionality available within that details view without having to create a separate "delete" view.

As of right now, this is how our "details" handler looks in our controller:

```<code>    public String displayNoteDetails(Model model, @RequestParam int id, @RequestParam int userId) {

        Optional<SecretNote> result = noteRepository.findById(id);

        if (result.isEmpty()) {
            model.addAttribute("title", "Invalid Note ID: " + id);
            return "redirect:../";
        } else {
            SecretNote secretNote = result.get();
            model.addAttribute("title", secretNote.getName() + " Details");
            model.addAttribute("secretNote", secretNote);
        }
        return "notes/details";
    }
}
</code>```

I was able to get a "delete" button to show up in the "details" view with the following:

```<code><form th:action="delete" method="post" th:object="${secretNote}">
        <input type="hidden" th:field="${secretNote.id}"/>
        <button type="submit" value="Submit" class="btn btn-danger">Delete</button>
</form>
</code>```

However, when clicking on said "delete" button, it is redirecting to http://localhost:8080/notes/delete, presumably because of how I have the "delete" button set up. I'd like to add code to the displayNoteDetails that would allow me to use noteRepository.deleteById(id); and then redirect to "notes/index" (the user home page that displays all notes).

FWIW, here's how we had the delete handlers when we were planning on doing a separate view:

```<code>@GetMapping("delete")
    public String displayDeleteNoteForm(@RequestParam int id, @RequestParam int userId) {
        noteRepository.deleteById(id);
        return "notes/index";
    }

    @PostMapping("delete")
    public String processDeleteNoteForm(Model model, @RequestParam(required = false) int[] noteIds) {

        if (noteIds !=null) {
            for (int id : noteIds) {
                noteRepository.deleteById(id);
                model.addAttribute("delete");
            }
        }
        return "notes/index";

    }
</code>```

Apologies in advance for formatting. I am clearly a novice.

答:
Replace:

```<code><form th:action="delete" method="post" th:object="${secretNote}">
</code>```

with:

```<code><form th:action="@{/notes/{id}/delete(id=${secretNote.id})}" method="post" th:object="${secretNote}">
</code>```

This will add the id of the note in the action URL of the form.

Body:
I am working on a group project that allows users to create, store, edit, and delete notes.

We are able to access the stored notes via a very basic "details" view, and would like to make the "delete" functionality available within that details view without having to create a separate "delete" view.

As of right now, this is how our "details" handler looks in our controller:

    public String displayNoteDetails(Model model, @RequestParam int id, @RequestParam int userId) {

        Optional<SecretNote> result = noteRepository.findById(id);

        if (result.isEmpty()) {
            model.addAttribute("title", "Invalid Note ID: " + id);
            return "redirect:../";
        } else {
            SecretNote secretNote = result.get();
            model.addAttribute("title", secretNote.getName() + " Details");
            model.addAttribute("secretNote", secretNote);
        }
        return "notes/details";
    }
}

I was able to get a "delete" button to show up in the "details" view with the following:

<form th:action="delete" method="post" th:object="${secretNote}">
        <input type="hidden" th:field="${secretNote.id}"/>
        <button type="submit" value="Submit" class="btn btn-danger">Delete</button>
</form>

However, when clicking on said "delete" button, it is redirecting to http://localhost:8080/notes/delete, presumably because of how I have the "delete" button set up. I'd like to add code to the displayNoteDetails that would allow me to use noteRepository.deleteById(id); and then redirect to "notes/index" (the user home page that displays all notes).

FWIW, here's how we had the delete handlers when we were planning on doing a separate view:

@GetMapping("delete")
    public String displayDeleteNoteForm(@RequestParam int id, @RequestParam int userId) {
        noteRepository.deleteById(id);
        return "notes/index";
    }

    @PostMapping("delete")
    public String processDeleteNoteForm(Model model, @RequestParam(required = false) int[] noteIds) {

        if (noteIds !=null) {
            for (int id : noteIds) {
                noteRepository.deleteById(id);
                model.addAttribute("delete");
            }
        }
        return "notes/index";

    }

Apologies in advance for formatting. I am clearly a novice.

Body:
Replace:

<form th:action="delete" method="post" th:object="${secretNote}">

with:

<form th:action="@{/notes/{id}/delete(id=${secretNote.id})}" method="post" th:object="${secretNote}">

This will add the id of the note in the action URL of the form.


问:
openpyxl set background color for cells
See example imageenter image description hereI would like to fill in these boxes with a coloured background, as they are elements that are append on the excel file, I cannot define the number of the box... Any ideas?

ws.append([datumcleaned,tagesinfo,])

here his the code:

# Writing on a EXCEL FILE
filename = (f"{myPath}/Monatsplan {userfinder} {month} {year}.xlsx")
try:
    wb = load_workbook(filename)
    ws = wb.worksheets[0]  # select first worksheet
except FileNotFoundError:
    headers_row = ['Datum', 'Dienst','Funktion','Von','Bis','Schichtdauer','Bezahlte Zeit']
    wb = Workbook()
    ws = wb.active
    ws.append(headers_row)
wb.save(filename)
ws.append([datumcleaned,tagesinfo,])
wb.save(filename)
wb.close()
```

答:
your best bet is to iterate over existing columns with .iter_cols() and apply background color to the index number -1 of every column since the appended row is the last index:

```<code>for cols in ws.iter_cols():
if cols[-1].value: # need to check the cells have values.
                  # otherwise colors the entire row.
    cols[-1].fill = PatternFill(bgColor="FFC7CE", fill_type="solid")
</code>```

Title: openpyxl set background color for cells

Body:
your best bet is to iterate over existing columns with .iter_cols() and apply background color to the index number -1 of every column since the appended row is the last index:

for cols in ws.iter_cols():
if cols[-1].value: # need to check the cells have values.
                  # otherwise colors the entire row.
    cols[-1].fill = PatternFill(bgColor="FFC7CE", fill_type="solid")


问:
How to completely uninstall .NET from macos
I have installed multiple versions of .NET in my macbook m1 and I want to wipe out all of them so that I can install .NET 6.
Is there a quick way to do it apart from using Terminal?</p>

答: I intalled the latest version of .NET Uninstall Tool and followed the instructions provided by Microsoft. With Mac OSX  Mojave it worked as a charm!</p>


问:
Skipping errors in a loop? (PHP)
I have a loop where the code loops and in every loop it connects to different server and then makes MySQL query. However sometimes one of the loops/queries cannot reach to the end and all the code breaks. Is there a way where if the loop gives error then skip the processes / move to next loop?</p>

答:
This all depends on if you use php's built-in mysql, mysqli or some third party library. But as a general rule I would recommend the following logic.

loop start

connect

check connection ok

check for table that might be missing using SHOW TABLES query or if you have permissions check against the mysql database holding schema information. You could also do this before selecting a db schema to see if you schema exists using SHOW DATABASES.

If table exists do your logic against it and disconnect - otherwise continue to move to the next iteration of the loop

loop end

Depending on the work you do on the table in question you could also suppress any errors from your query using the @ prefix like @mysql_query and then check for number of affected rows. If you do a select you could check your result set to see if you got anything back etc. I don't like the use of @ though and it should be noted that a select from an existing table that was empty and similar situations could result in strange behavior depending on your code. Try/Catch is a nicer approach to handle error control flow. But actually throwing an exception is quite a slow process in comparison and since all the work revolves around connecting to databases all over the place it might not be a good idea to slow it down even more if a lot of exceptions could be thrown by this loop. Also, when using it to skip a step in a loop it can be quite hard for some people to follow the logic. Therefore something like @ could be acceptable here ;)

Title: Skipping errors in a loop? (PHP)


问:
How do you programmatically redact PDF FIles?
Adobe Acrobat has the ability to redact PDF files (that is, actually remove the information, rather than simply drawing a black box on top of it). I would like to use this feature programmatically. To redact using the GUI you select the Mark for Redaction Tool, draw it over the text to be redacted, then Apply Redactions.

Is there any way to do this programmatically, either through AppleScript or some other way?

I know the (X,y) location of the text to be redacted.

Thanks!

答:
Redacting PDFs in general is a pretty complex task.

You can redact PDF pages for free on doXiview (https://doxiview.cib.de) The redact option is located on the right side.

Another approach is programmatically done by CIB pdf toolbox (https://pdftoolbox.cib.de/)


问:
Is there a better/more pythonic way to update dictionaries?
This is a class assignment. I am trying to update the values of multiple dictionary keys simultaneously.

The code is supposed to subtract the 'ingredients' used by the various drinks from the resources dictionary.

I have it working on a drink by drink basis but I feel certain there is more pythonic way to do this. This code only updates for 'cappuccino'

I looked into using the update() method but but not sure how/if it applies.python

```<code>MENU = {
    "espresso": {
        "ingredients": {
            "water": 50,
            "coffee": 18,
        },
        "cost": 1.5,
    },
    "latte": {
        "ingredients": {
            "water": 200,
            "milk": 150,
            "coffee": 24,
        },
        "cost": 2.5,
    },
    "cappuccino": {
        "ingredients": {
            "water": 250,
            "milk": 100,
            "coffee": 24,
        },
        "cost": 3.0,
    }
}

resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
}

#the bracket notation is how I access the values of the different keys in the dictionary.
#For the dict MENU we need to access the deeper levels of the dictionary by using the multiple
#brackets to get to the value of the key. I then subtract the amounts used by the drinks from the resources.`
#this approach works, but I feel like there is a more pythonic approach.

cappuccino_remaining_water = resources['water'] - MENU['cappuccino']['ingredients']['water']
cappuccino_remaining_milk = resources['milk'] - MENU['cappuccino']['ingredients']['milk']
cappuccino_remaining_coffee = resources['coffee'] - MENU['cappuccino']['ingredients']['coffee']

resources['water'] = cappuccino_remaining_water
resources['milk'] = cappuccino_remaining_milk
resources['coffee'] = cappuccino_remaining_coffee

print(resources)
</code>```

答:
You can use a loop to iterate through all the ingredients required for your chosen drink and find the corresponding ingredient in you resources dictionary:

MENU = {
    "espresso": {
        "ingredients": {
            "water": 50,
            "coffee": 18,
        },
        "cost": 1.5,
    },
    "latte": {
        "ingredients": {
            "water": 200,
            "milk": 150,
            "coffee": 24,
        },
        "cost": 2.5,
    },
    "cappuccino": {
        "ingredients": {
            "water": 250,
            "milk": 100,
            "coffee": 24,
        },
        "cost": 3.0,
    }
}

resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
}

drink = 'cappuccino'
for ingredient in MENU[drink]['ingredients']:
    if ingredient in resources:
        resources[ingredient] = resources[ingredient] - MENU[drink]['ingredients'][ingredient]

print(resources)
```
<p>We're updating the <code>resources</code> dictionary by overwriting <code>resources[ingredient]</code> inside the loop, giving us:</p>
<pre class="lang-py prettyprint-override"><code>{'water': 50, 'milk': 100, 'coffee': 76}
</code>```

Body:
This is a class assignment. I am trying to update the values of multiple dictionary keys simultaneously.

The code is supposed to subtract the 'ingredients' used by the various drinks from the resources dictionary.

I have it working on a drink by drink basis but I feel certain there is more pythonic way to do this. This code only updates for 'cappuccino'

I looked into using the update() method but but not sure how/if it applies.python

MENU = {
    "espresso": {
        "ingredients": {
            "water": 50,
            "coffee": 18,
        },
        "cost": 1.5,
    },
    "latte": {
        "ingredients": {
            "water": 200,
            "milk": 150,
            "coffee": 24,
        },
        "cost": 2.5,
    },
    "cappuccino": {
        "ingredients": {
            "water": 250,
            "milk": 100,
            "coffee": 24,
        },
        "cost": 3.0,
    }
}

resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
}

#the bracket notation is how I access the values of the different keys in the dictionary.
#For the dict MENU we need to access the deeper levels of the dictionary by using the multiple
#brackets to get to the value of the key. I then subtract the amounts used by the drinks from the resources.`
#this approach works, but I feel like there is a more pythonic approach.

cappuccino_remaining_water = resources['water'] - MENU['cappuccino']['ingredients']['water']
cappuccino_remaining_milk = resources['milk'] - MENU['cappuccino']['ingredients']['milk']
cappuccino_remaining_coffee = resources['coffee'] - MENU['cappuccino']['ingredients']['coffee']

resources['water'] = cappuccino_remaining_water
resources['milk'] = cappuccino_remaining_milk
resources['coffee'] = cappuccino_remaining_coffee

print(resources)

Body:
You can use a loop to iterate through all the ingredients required for your chosen drink and find the corresponding ingredient in you resources dictionary:

MENU = {
    "espresso": {
        "ingredients": {
            "water": 50,
            "coffee": 18,
        },
        "cost": 1.5,
    },
    "latte": {
        "ingredients": {
            "water": 200,
            "milk": 150,
            "coffee": 24,
        },
        "cost": 2.5,
    },
    "cappuccino": {
        "ingredients": {
            "water": 250,
            "milk": 100,
            "coffee": 24,
        },
        "cost": 3.0,
    }
}

resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
}

drink = 'cappuccino'
for ingredient in MENU[drink]['ingredients']:
    if ingredient in resources:
        resources[ingredient] = resources[ingredient] - MENU[drink]['ingredients'][ingredient]

print(resources)

We're updating the resources dictionary by overwriting resources[ingredient] inside the loop, giving us:

{'water': 50, 'milk': 100, 'coffee': 76}


问:
IE8 Sprite Sheet Backgrounds Disappearing
I am having some issues with these background images I am using for a menu on my app. In IE (7 and 8, maybe 9) the images seem to fall under the background of the item below it, which happens to have a black background. When I check the developer tools it seems that IE8 has created a css3 container to contain the image with z-index -1... I have changed the value in the developer tools to make it appear as normal, but then the text that is supposed to appear over the image disappears.... It is all rather frustrating.

It works fine in all other browsers.

Checkout: http://letswoosh.com

Anyone have any ideas about fixing this? Thanks!!!

答:
When I disable Javascript using IE debugger and reload the webpage the images appear. Also when I load with Javascript enabled I get an exception in IE7 and 8 regarding _e3 is null or not an object. The images disappear afterwards.

It's obvious the images are disappearing due to a Javascript error or incompatibility with IE.


问:
How to modify intervals on matplotlib's qualitative color maps?
```<code>import matplotlib.pyplot as plt
import numpy as np
</code>```

I have a 2D numpy array:

```<code>mock=\
np.array([[0.1,0.2,0.3],
          [0.2,0.3,0.4],
          [0.3,0.4,0.5],
          [0.4,0.5,0.6],
          [0.5,0.6,0.7],
          [0.6,0.7,0.8],
          [0.7,0.8,0.9]])
</code>```

I plot these values using the tab20c colormap, from the so-called "Qualitative" colormaps:

```<code>plt.figure(figsize=(6,6))
im = plt.imshow(mock,cmap = "tab20c", vmin=0, vmax=1)
plt.colorbar(im)
</code>```

How would I go about this if I wanted all the values below a certain value, let's say 0.25 having the same color as 0.25 has, replacing not only the colors in the plot itself, but also in the colorbar? The expected output would be then: all 3 squares in the top left corner to be red, bottom 5 rectangles in the colormap are also all red.

By doing this, I am essentially modifying the interval for the color red in the barchart: instead of showing values in the interval between 0.2 and 0.25 as red, the new version will show everything in the interval between 0 and 0.25 red.

答:
What about using numpy.clip to set the data below 0.25 to 0.25?

```<code>im = plt.imshow(np.clip(mock, 0.25, np.inf), cmap = "tab20c", vmin=0, vmax=1)
</code>```

This seems to be the most straightforward solution to me as it doesn't require to mess with the plotting parameters.

output:

Body:
import matplotlib.pyplot as plt
import numpy as np

I have a 2D numpy array:

mock=\
np.array([[0.1,0.2,0.3],
          [0.2,0.3,0.4],
          [0.3,0.4,0.5],
          [0.4,0.5,0.6],
          [0.5,0.6,0.7],
          [0.6,0.7,0.8],
          [0.7,0.8,0.9]])

I plot these values using the tab20c colormap, from the so-called "Qualitative" colormaps:

plt.figure(figsize=(6,6))
im = plt.imshow(mock,cmap = "tab20c", vmin=0, vmax=1)
plt.colorbar(im)

How would I go about this if I wanted all the values below a certain value, let's say 0.25 having the same color as 0.25 has, replacing not only the colors in the plot itself, but also in the colorbar? The expected output would be then: all 3 squares in the top left corner to be red, bottom 5 rectangles in the colormap are also all red.

By doing this, I am essentially modifying the interval for the color red in the barchart: instead of showing values in the interval between 0.2 and 0.25 as red, the new version will show everything in the interval between 0 and 0.25 red.

Body:
What about using numpy.clip to set the data below 0.25 to 0.25?

im = plt.imshow(np.clip(mock, 0.25, np.inf), cmap = "tab20c", vmin=0, vmax=1)

This seems to be the most straightforward solution to me as it doesn't require to mess with the plotting parameters.

output:


问:
dynamically import class from file and use a function in it
i have this file ./src/commands/test.js:

```<code>export default class {
    run() {
        console.log('test!')
    }
}
</code>```

i am trying to make a command that will get all commands in that folder and call their run function:

```<code>#! /usr/bin/env node

const fs = require('fs')
const folders = [
    './src/commands',
    //'./my_modules/diontron/unity/src/commands',
]

folders.forEach(folder => {
    fs.readdir(folder, (err, files) => {
        files.forEach(file => {
            if (file != 'index.js') {
                let commandClass = require(folder + '/' + file).default
                let command = new commandClass()

                command.run()
            }
        })
    })
})
</code>```

this gives me the error:

```<code>Cannot find module './src/commands/test.js'

</code>```

how do i dynamically go through all files in a folder, require/import them, and use the class function?

答:
You can do it with dynamic import() rather than require. Note that you'll need a package.json in src or src/commands with "type": "module" in it, since test.js uses ESM by Node.js uses CommonJS by default.

This works for me in that setup:

```<code>#! /usr/bin/env node

const fs = require("fs");
const folders = [
    "./src/commands",
    //"./my_modules/diontron/unity/src/commands",
];

folders.forEach(folder => {
    fs.readdir(folder, (err, files) => {
        files.forEach(file => {
            if (file != "index.js") {
                const modFile = folder + "/" + file;
                import(modFile)
                .then(({ default: commandClass }) => {
                    const command = new commandClass();
                    command.run();
                })
                .catch(error => {
                    console.log(`Failed to load module ${modFile}`);
                });
            }
        });
    });
});
</code>```

Although that runs the code in parallel. If you want to run it in series (each waiting for the previous one to complete), you might do this (note the change from "fs" to "fs/promises" at the top):

```<code>#! /usr/bin/env node

const fs = require("fs/promises");
const folders = [
    "./src/commands",
    //"./my_modules/diontron/unity/src/commands",
];

(async () => {
    for (const folder of folders) {
        for (const folder of folders) {
            const files = await fs.readdir(folder);
            for (const file of files) {
                const { default: commandClass } = await import(folder + "/" + file);
                const command = new commandClass();
                command.run();
            }
        }
    }
})()
.catch(error => {
    console.error(error);
});
</code>```

That relies on the script being run from the parent folder of the folders you're searching. If you want to use the current path instead, you should use process.cwd() to get it, then use that to resolve the folders:

```<code>#! /usr/bin/env node

const fs = require("fs");
const path = require("path"); // ***
const folders = [
    "./src/commands",
    //"./my_modules/diontron/unity/src/commands",
];

const currentDir = process.cwd(); // ***

folders.forEach(folder => {
    fs.readdir(folder, (err, files) => {
        const fullFolder = path.join(currentDir, folder); // ***
        files.forEach(file => {
            if (file != "index.js") {
                const modFile = fullFolder + "/" + file; // ***
                import(modFile)
                .then(({ default: commandClass }) => {
                    const command = new commandClass();
                    command.run();
                })
                .catch(error => {
                    console.log(`Failed to load module ${modFile}`);
                });
            }
        });
    });
});
</code>```

Body:
i have this file ./src/commands/test.js:

export default class {
    run() {
        console.log('test!')
    }
}

i am trying to make a command that will get all commands in that folder and call their run function:

#! /usr/bin/env node

const fs = require('fs')
const folders = [
    './src/commands',
    //'./my_modules/diontron/unity/src/commands',
]

folders.forEach(folder => {
    fs.readdir(folder, (err, files) => {
        files.forEach(file => {
            if (file != 'index.js') {
                let commandClass = require(folder + '/' + file).default
                let command = new commandClass()

                command.run()
            }
        })
    })
})

this gives me the error:

Cannot find module './src/commands/test.js'

how do i dynamically go through all files in a folder, require/import them, and use the class function?

Body:
You can do it with dynamic import() rather than require. Note that you'll need a package.json in src or src/commands with "type": "module" in it, since test.js uses ESM by Node.js uses CommonJS by default.

This works for me in that setup:

#! /usr/bin/env node

const fs = require("fs");
const folders = [
    "./src/commands",
    //"./my_modules/diontron/unity/src/commands",
];

folders.forEach(folder => {
    fs.readdir(folder, (err, files) => {
        files.forEach(file => {
            if (file != "index.js") {
                const modFile = folder + "/" + file;
                import(modFile)
                .then(({ default: commandClass }) => {
                    const command = new commandClass();
                    command.run();
                })
                .catch(error => {
                    console.log(`Failed to load module ${modFile}`);
                });
            }
        });
    });
});

Although that runs the code in parallel. If you want to run it in series (each waiting for the previous one to complete), you might do this (note the change from "fs" to "fs/promises" at the top):

#! /usr/bin/env node

const fs = require("fs/promises");
const folders = [
    "./src/commands",
    //"./my_modules/diontron/unity/src/commands",
];

(async () => {
    for (const folder of folders) {
        for (const folder of folders) {
            const files = await fs.readdir(folder);
            for (const file of files) {
                const { default: commandClass } = await import(folder + "/" + file);
                const command = new commandClass();
                command.run();
            }
        }
    }
})()
.catch(error => {
    console.error(error);
});

That relies on the script being run from the parent folder of the folders you're searching. If you want to use the current path instead, you should use process.cwd() to get it, then use that to resolve the folders:

#! /usr/bin/env node

const fs = require("fs");
const path = require("path"); // ***
const folders = [
    "./src/commands",
    //"./my_modules/diontron/unity/src/commands",
];

const currentDir = process.cwd(); // ***

folders.forEach(folder => {
    fs.readdir(folder, (err, files) => {
        const fullFolder = path.join(currentDir, folder); // ***
        files.forEach(file => {
            if (file != "index.js") {
                const modFile = fullFolder + "/" + file; // ***
                import(modFile)
                .then(({ default: commandClass }) => {
                    const command = new commandClass();
                    command.run();
                })
                .catch(error => {
                    console.log(`Failed to load module ${modFile}`);
                });
            }
        });
    });
});


答:
You can adapt an existing colourmap:

```<code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap

tab20c = cm.get_cmap('tab20c', 256)
newcolors = tab20c(np.linspace(0, 1, 256))
red = np.array([1, 0, 0, 1])
newcolors[:int(256/4), :] = red
newcmp = ListedColormap(newcolors)

mock=\
np.array([[0.1,0.2,0.3],
          [0.2,0.3,0.4],
          [0.3,0.4,0.5],
          [0.4,0.5,0.6],
          [0.5,0.6,0.7],
          [0.6,0.7,0.8],
          [0.7,0.8,0.9]])

plt.figure(figsize=(6,6))
im = plt.imshow(mock,cmap = newcmp, vmin=0.0, vmax=1)
plt.colorbar(im)
</code>```

Title: How to modify intervals on matplotlib's qualitative color maps?

Body:
You can adapt an existing colourmap:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap

tab20c = cm.get_cmap('tab20c', 256)
newcolors = tab20c(np.linspace(0, 1, 256))
red = np.array([1, 0, 0, 1])
newcolors[:int(256/4), :] = red
newcmp = ListedColormap(newcolors)

mock=\
np.array([[0.1,0.2,0.3],
          [0.2,0.3,0.4],
          [0.3,0.4,0.5],
          [0.4,0.5,0.6],
          [0.5,0.6,0.7],
          [0.6,0.7,0.8],
          [0.7,0.8,0.9]])

plt.figure(figsize=(6,6))
im = plt.imshow(mock,cmap = newcmp, vmin=0.0, vmax=1)
plt.colorbar(im)


问:
How to set state using useState and do something else as well in onChange in React?
I have a component which includes another component (from headlessui/react) defined as follows:

```<code>export default function MyComponent(props) {
  const [selectedState, setState] = useState('');
  return (
    <div>
      <RadioGroup value={selectedState} onChange={setState}>
      ...
      </RadioGroup>
    </div>
  )
}
</code>```

In the onChange I would like to first call a function which does something and then calls setState. However, nomatter what I try, I can't get this to work.

I've tried:

```<code>onChange={() => {
  doSomethingFirst();
  return setState;
}

onChange={() => {
  doSomethingFirst();
  // This requires an argument and I'm not sure what the argument should be
  setState();
}

// Even this fails
onChange={() => setState;}
</code>```

What do I do to get this working?

答:
This should works.

```<code>export default function MyComponent(props) {
  const [selectedState, setState] = useState('');

  const updateState = (ev)=> {
    doSomethingHere();
    ...
    setState()
  }

  return (
    <div>
      <RadioGroup value={selectedState} onChange={updateState}>
        ...
      </RadioGroup>
    </div>
  );
}
</code>```

ev object passed to updateState function contains <RadioGroup> element. You can inspect it with console.log to see what values it holds.

If you are trying to update the state according to the RadioGroup value, you must be able to read that value inside ev object.

Body:
I have a component which includes another component (from headlessui/react) defined as follows:

export default function MyComponent(props) {
  const [selectedState, setState] = useState('');
  return (

      <RadioGroup value={selectedState} onChange={setState}>
      ...
      </RadioGroup>

  )
}

In the onChange I would like to first call a function which does something and then calls setState. However, nomatter what I try, I can't get this to work.

I've tried:

onChange={() => {
  doSomethingFirst();
  return setState;
}

onChange={() => {
  doSomethingFirst();
  // This requires an argument and I'm not sure what the argument should be
  setState();
}

// Even this fails
onChange={() => setState;}

What do I do to get this working?

Body:
This should works.

export default function MyComponent(props) {
  const [selectedState, setState] = useState('');

  const updateState = (ev)=> {
    doSomethingHere();
    ...
    setState()
  }

  return (
    <div>
      <RadioGroup value={selectedState} onChange={updateState}>
        ...
      </RadioGroup>
    </div>
  );
}

ev object passed to updateState function contains <RadioGroup> element. You can inspect it with console.log to see what values it holds.

If you are trying to update the state according to the RadioGroup value, you must be able to read that value inside ev object.


问:
how do i map over items in an input feild?
I am making a form that sends over the shipping details of a user . I am however finding it difficult to map over the shipping other in an input field that is immutable(read only). I keep getting this in the input field [object, object] in the browser . I want the details of the objects to show instead.

Here is a snippet of the code

```<code><div class="telephone">
                <label for="name"></label>
                <input
                  type="text"
                  name="username"
                  value={items.map((item, id) => (
                    <Payment
                      key={id}
                      name={item.name}
                      price={item.price}
                      itemSize={item.itemSize}
                      count={item.count}
                    />
                  ))}
                  readonly
                />
              </div>
</code>```

答:
HTML input types are expecting text as value and you are passing JSX component to it, that's why it's displaying [Object, object]. Not sure what you want to achieve, but input type='text' need text as value.

https://www.w3schools.com/tags/tag_input.asp

Body:
I am making a form that sends over the shipping details of a user . I am however finding it difficult to map over the shipping other in an input field that is immutable(read only). I keep getting this in the input field [object, object] in the browser . I want the details of the objects to show instead.

Here is a snippet of the code

                <input
                  type="text"
                  name="username"
                  value={items.map((item, id) => (
                    <Payment
                      key={id}
                      name={item.name}
                      price={item.price}
                      itemSize={item.itemSize}
                      count={item.count}
                    />
                  ))}
                  readonly
                />