问:
How can I use C++ class in Python?
I have implemented a class in C++. I want to use it with Python.
Please suggest step by step method and elaborate each step.
Somthing like this...

```<code>class Test{
     private:
        int n;
     public:
        Test(int k){
            n=k;
        }
        void setInt(int k){
            n = k;
        }
        int getInt(){
            return n;
        }
};
</code>```

Now, in Python

```<code>>>> T1 = Test(12)
>>> T1.getInt()
12
>>> T1.setInt(32)
>>> T1.getInt()
32
</code>```

Please suggest.How can I do this ?
NOTE: I would like to know manual way to do that. I don't want any third party library dependency.

答:
I would suggest you try SWIG or sip (KDE/PyQt).

SWIG link : http://www.swig.org/

SIP link: http://freshmeat.net/projects/python-sip/

These can be used to wrap C++ classes and provide a Pythonic interface to them.

OwnerDisplayName: david makcenzie

ContentLicense: CC BY-SA 2.5

Title: How can I use C++ class in Python?

Body:
I have implemented a class in C++. I want to use it with Python.
Please suggest step by step method and elaborate each step.
Somthing like this...

class Test{
     private:
        int n;
     public:
        Test(int k){
            n=k;
        }
        void setInt(int k){
            n = k;
        }
        int getInt(){
            return n;
        }
};

Now, in Python

>>> T1 = Test(12)
>>> T1.getInt()
12
>>> T1.setInt(32)
>>> T1.getInt()
32

Please suggest.How can I do this ?
NOTE: I would like to know manual way to do that. I don't want any third party library dependency.

LastEditorDisplayName: david makcenzie

OwnerDisplayName: batbrat


来源: stackexchange

问:
How to use CURL/CygWin to send files from local Windows machine to Server?
My goal is to upload a CouchDB document from my Windows machine to a remote server using cygwin/curl.

Here is a tutorial that shows how to do the same on a Mac:
http://net.tutsplus.com/tutorials/getting-started-with-couchdb/

curl -X POST http://127.0.0.1:5984/mycouchshop/ -d @person.json -H "Content-Type: application/json

How can I do the same with Windows & CygWin?

答:
After opening cygwin.

step 1 - CD into the directory that contains the file you would like to post via CURL:

```<code>cd ../
cd /cygdrive/c/Users/[put user name here]/Documents/[more directories here]/
</code>```

Note: The strange part is having to go through the "cygdrive" directory.

step 2 - Use CURL to send the file:

curl -X POST http://mywebsite.com/path/to/directory -d @some_file.extension -H "Content-Type: application/json"

Replace "mywebsite.com...", "some_file.extension" and "application/json" with actual values.

ContentLicense: CC BY-SA 3.0

Body:
After opening cygwin.

step 1 - CD into the directory that contains the file you would like to post via CURL:

cd ../
cd /cygdrive/c/Users/[put user name here]/Documents/[more directories here]/

Note: The strange part is having to go through the "cygdrive" directory.

step 2 - Use CURL to send the file:

curl -X POST http://mywebsite.com/path/to/directory -d @some_file.extension -H "Content-Type: application/json"

Replace "mywebsite.com...", "some_file.extension" and "application/json" with actual values.


问:
Simple example of filtering items in a grid in Vaadin Flow 14
I want to suppress the display of some items in a Grid widget in Vaadin Flow 14.

For example, if the user enters a year in a IntegerField widget, I want the grid to show only items with an associated date before that year. Items with a date on or after that date should disappear. If the user changes the year number, the filtering should be re-applied with fewer or more items displayed appropriately in the grid.

I have seen filters on Grid discussed but cannot wrap my head around the various moving parts. Perhaps someone could show a simple example?

答:
I am going to submit my way of filtering a Grid using a ListDataProvider. The goal of my approach is to be able to add filter fields for any column you want, and that the filters can be combined with each other, and also that each filter value can be changed to something else at any time. With my solution, you will also be able to use other Input Fields than TextField. So can also use ComboBoxes for enums, etc.

The crux is that when you use the setFilter method of the ListDataProvider, any other filter is disregarded so multiple filters wont work simultaneously. But when you use addFilter exclusively you can never change a filter you defined, only add another filter on top of that. You could let the user clear all filters with a button that is dedicated for this but I would like to avoid that.

This is how I avoid this conundrum:
Every time that any filter value changes, I reset the current filter using setFilter. But within that new Filter, I will check the values of ALL filter fields, and not only the value of the field whose value just changed. In other words, I always have only one single filter active, but that filter accounts for all defined filter-values.

Here is the full and working code for a View with a grid (see images below) using the same example as OP's original answer. You can filter this grid by string representation, year, month, or dayOfWeek simultaneously.

```<code>@Route(value = "Test", layout = MainView.class)
public class TestView extends VerticalLayout {
    private Grid<LocalDate> grid;
    private TextField toStringFilter, yearFilter;
    private ComboBox<Month> monthFilter;
    private ComboBox<DayOfWeek> dayOfWeekFilter;

    public TestView() {
        grid = new Grid<>(LocalDate.class, false);
        List< LocalDate > dates = List.of(
                LocalDate.of( 2020 , Month.JANUARY , 23 ) ,
                LocalDate.of( 2019 , Month.FEBRUARY , 24 ) ,
                LocalDate.of( 2022 , Month.MARCH , 25 ) ,
                LocalDate.of( 2011 , Month.APRIL , 26 ) ,
                LocalDate.of( 2022 , Month.APRIL , 23 )
        );
        grid.setItems( new ArrayList< LocalDate >( dates ) );
        grid.addColumn( LocalDate :: toString ).setHeader("String Representation").setKey("tostring");
        grid.addColumn( LocalDate :: getYear ).setHeader("Year").setKey("year");
        grid.addColumn( LocalDate :: getMonth ).setHeader("Month").setKey("month");
        grid.addColumn( LocalDate :: getDayOfWeek ).setHeader("Day Of Week").setKey("dayofweek");

        prepareFilterFields();
        add(grid);
    }

    private void prepareFilterFields() {
        HeaderRow headerRow = grid.appendHeaderRow();

        toStringFilter = gridTextFieldFilter("tostring", headerRow);
        yearFilter = gridTextFieldFilter("year", headerRow);
        monthFilter = gridComboBoxFilter("month", headerRow, Month::toString, Month.values());
        dayOfWeekFilter = gridComboBoxFilter("dayofweek", headerRow, DayOfWeek::toString, DayOfWeek.values());
    }

    private <T> ComboBox<T> gridComboBoxFilter(String columnKey, HeaderRow headerRow, ItemLabelGenerator<T> itemLabelGenerator, T... items) {
        ComboBox<T> filter = new ComboBox<>();
        filter.addValueChangeListener(event -> this.onFilterChange());
        filter.setItemLabelGenerator(itemLabelGenerator);
        filter.setItems(items);
        filter.setWidthFull();
        filter.setClearButtonVisible(true);
        headerRow.getCell(grid.getColumnByKey(columnKey)).setComponent(filter);
        return filter;
    }

    private TextField gridTextFieldFilter(String columnKey, HeaderRow headerRow) {
        TextField filter = new TextField();
        filter.setValueChangeMode(ValueChangeMode.TIMEOUT);
        filter.addValueChangeListener(event -> this.onFilterChange());
        filter.setWidthFull();
        headerRow.getCell(grid.getColumnByKey(columnKey)).setComponent(filter);
        return filter;
    }

    private void onFilterChange(){
        ListDataProvider<LocalDate> listDataProvider = (ListDataProvider<LocalDate>) grid.getDataProvider();
        // Since this will be the only active filter, it needs to account for all values of my filter fields
        listDataProvider.setFilter(item -> {
            boolean toStringFilterMatch = true;
            boolean yearFilterMatch = true;
            boolean monthFilterMatch = true;
            boolean dayOfWeekFilterMatch = true;

            if(!toStringFilter.isEmpty()){
                toStringFilterMatch = item.toString().contains(toStringFilter.getValue());
            }
            if(!yearFilter.isEmpty()){
                yearFilterMatch = String.valueOf(item.getYear()).contains(yearFilter.getValue());
            }
            if(!monthFilter.isEmpty()){
                monthFilterMatch = item.getMonth().equals(monthFilter.getValue());
            }
            if(!dayOfWeekFilter.isEmpty()){
                dayOfWeekFilterMatch = item.getDayOfWeek().equals(dayOfWeekFilter.getValue());
            }

            return toStringFilterMatch && yearFilterMatch && monthFilterMatch && dayOfWeekFilterMatch;
        });
    }
}
</code>```

Unfiltered Grid:

Filtered By Year:

Filtered By Year AND Month:

ContentLicense: CC BY-SA 4.0

Body:
I am going to submit my way of filtering a Grid using a ListDataProvider. The goal of my approach is to be able to add filter fields for any column you want, and that the filters can be combined with each other, and also that each filter value can be changed to something else at any time. With my solution, you will also be able to use other Input Fields than TextField. So can also use ComboBoxes for enums, etc.

The crux is that when you use the setFilter method of the ListDataProvider, any other filter is disregarded so multiple filters wont work simultaneously. But when you use addFilter exclusively you can never change a filter you defined, only add another filter on top of that. You could let the user clear all filters with a button that is dedicated for this but I would like to avoid that.

This is how I avoid this conundrum:
Every time that any filter value changes, I reset the current filter using setFilter. But within that new Filter, I will check the values of ALL filter fields, and not only the value of the field whose value just changed. In other words, I always have only one single filter active, but that filter accounts for all defined filter-values.

Here is the full and working code for a View with a grid (see images below) using the same example as OP's original answer. You can filter this grid by string representation, year, month, or dayOfWeek simultaneously.

@Route(value = "Test", layout = MainView.class)
public class TestView extends VerticalLayout {
    private Grid<LocalDate> grid;
    private TextField toStringFilter, yearFilter;
    private ComboBox<Month> monthFilter;
    private ComboBox<DayOfWeek> dayOfWeekFilter;

    public TestView() {
        grid = new Grid<>(LocalDate.class, false);
        List< LocalDate > dates = List.of(
                LocalDate.of( 2020 , Month.JANUARY , 23 ) ,
                LocalDate.of( 2019 , Month.FEBRUARY , 24 ) ,
                LocalDate.of( 2022 , Month.MARCH , 25 ) ,
                LocalDate.of( 2011 , Month.APRIL , 26 ) ,
                LocalDate.of( 2022 , Month.APRIL , 23 )
        );
        grid.setItems( new ArrayList< LocalDate >( dates ) );
        grid.addColumn( LocalDate :: toString ).setHeader("String Representation").setKey("tostring");
        grid.addColumn( LocalDate :: getYear ).setHeader("Year").setKey("year");
        grid.addColumn( LocalDate :: getMonth ).setHeader("Month").setKey("month");
        grid.addColumn( LocalDate :: getDayOfWeek ).setHeader("Day Of Week").setKey("dayofweek");

        prepareFilterFields();
        add(grid);
    }

    private void prepareFilterFields() {
        HeaderRow headerRow = grid.appendHeaderRow();

        toStringFilter = gridTextFieldFilter("tostring", headerRow);
        yearFilter = gridTextFieldFilter("year", headerRow);
        monthFilter = gridComboBoxFilter("month", headerRow, Month::toString, Month.values());
        dayOfWeekFilter = gridComboBoxFilter("dayofweek", headerRow, DayOfWeek::toString, DayOfWeek.values());
    }

    private <T> ComboBox<T> gridComboBoxFilter(String columnKey, HeaderRow headerRow, ItemLabelGenerator<T> itemLabelGenerator, T... items) {
        ComboBox<T> filter = new ComboBox<>();
        filter.addValueChangeListener(event -> this.onFilterChange());
        filter.setItemLabelGenerator(itemLabelGenerator);
        filter.setItems(items);
        filter.setWidthFull();
        filter.setClearButtonVisible(true);
        headerRow.getCell(grid.getColumnByKey(columnKey)).setComponent(filter);
        return filter;
    }

    private TextField gridTextFieldFilter(String columnKey, HeaderRow headerRow) {
        TextField filter = new TextField();
        filter.setValueChangeMode(ValueChangeMode.TIMEOUT);
        filter.addValueChangeListener(event -> this.onFilterChange());
        filter.setWidthFull();
        headerRow.getCell(grid.getColumnByKey(columnKey)).setComponent(filter);
        return filter;
    }

    private void onFilterChange(){
        ListDataProvider<LocalDate> listDataProvider = (ListDataProvider<LocalDate>) grid.getDataProvider();
        // Since this will be the only active filter, it needs to account for all values of my filter fields
        listDataProvider.setFilter(item -> {
            boolean toStringFilterMatch = true;
            boolean yearFilterMatch = true;
            boolean monthFilterMatch = true;
            boolean dayOfWeekFilterMatch = true;

            if(!toStringFilter.isEmpty()){
                toStringFilterMatch = item.toString().contains(toStringFilter.getValue());
            }
            if(!yearFilter.isEmpty()){
                yearFilterMatch = String.valueOf(item.getYear()).contains(yearFilter.getValue());
            }
            if(!monthFilter.isEmpty()){
                monthFilterMatch = item.getMonth().equals(monthFilter.getValue());
            }
            if(!dayOfWeekFilter.isEmpty()){
                dayOfWeekFilterMatch = item.getDayOfWeek().equals(dayOfWeekFilter.getValue());
            }

            return toStringFilterMatch && yearFilterMatch && monthFilterMatch && dayOfWeekFilterMatch;
        });
    }
}

Unfiltered Grid:

Filtered By Year:

Filtered By Year AND Month:


问:
CosmosDB C# SDK ProyUrl missing
I am working on a containerized micro-services project (docker) in .NET Core targeting Azure. So we are using Azure Cosmos DB, and the C# Cosmos DB SDK (v2.4 since v3 is only in preview) for the CoreSql Api.

During development, I am behind a proxy, so I need to specify the proxy url for everything going outside. It works fine with HttpClientHandler for any HttpClient.

Using Cosmos DB SDK, I however don't see how to set this up on my DocumentClient.

In the Azure Node SDK, I see I could just create a ConnectionPolicy and set the ProxyUrl property for this purpose:
https://learn.microsoft.com/en-us/javascript/api/%40azure/cosmos/connectionpolicy?view=azure-node-latest#proxyurl

However, in the C# variant, no ProxyUrl:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.documents.client.connectionpolicy?view=azure-dotnet

Is there another way to set that?
It is a missing feature in Cosmos DB SDK?
Thanks!
Eric

答:
When using the CosmosDbClient for C#, if on Core 2.2 (unsure about previous versions), you can pass an instance of WebProxy as part of CosmosClientOptions parameter.

example:

```<code>WebProxy proxy = new WebProxy("http://< yourproxy.com >:< port number >", true, new List< string >().ToArray(), new NetworkCredential { Domain = "< domain >", UserName = "< username >", Password = "< password >" });
</code>```

and then

```<code>CosmosClient cosmosClient = new CosmosClient(< EndpointUri >, < PrimaryKey >, new CosmosClientOptions { ConnectionMode = ConnectionMode.Gateway, WebProxy = proxy });
</code>```

Note that when using a Proxy, you will be forced to use ConnectionMode as Gateway.

Title: CosmosDB C# SDK ProyUrl missing

Body:
When using the CosmosDbClient for C#, if on Core 2.2 (unsure about previous versions), you can pass an instance of WebProxy as part of CosmosClientOptions parameter.

example:

WebProxy proxy = new WebProxy("http://< yourproxy.com >:< port number >", true, new List< string >().ToArray(), new NetworkCredential { Domain = "< domain >", UserName = "< username >", Password = "< password >" });

and then

CosmosClient cosmosClient = new CosmosClient(< EndpointUri >, < PrimaryKey >, new CosmosClientOptions { ConnectionMode = ConnectionMode.Gateway, WebProxy = proxy });

Note that when using a Proxy, you will be forced to use ConnectionMode as Gateway.


问:
Customize Xamarin.Forms.Datepicker to pick and visualize multiple Dates
i'm kinda new to the whole wpf/xamarin UI thing and want to start my first mobile app.
So, like the title contains already the topic of this question, i would like to use the standard Xamarin.Forms Datepicker to let the user pick multiple Dates.

I guess it will be pretty easy to submit on the Event for picking a date and put this into an array for the selected Dates.

But how can i visualize all the selected Dates in the Datepicker Dialog? Is there any possability to do this with this Control?

Thanks :)

答:
For your requirement, you could use Calendar. The SfCalendar plugin provide the MultiSelection SelectionMode to do that.

```<code> <syncfusion:SfCalendar
            x:Name="calendar"
            SelectionChanged="calendar_SelectionChanged"
            SelectionMode="MultiSelection" />
</code>```

If you want to get all the list of select dates, you could do that in calendar_SelectionChanged event.

```<code> private void calendar_SelectionChanged(object sender, Syncfusion.SfCalendar.XForms.SelectionChangedEventArgs e)
    {
        var dateAdded = e.DateAdded;
        var dateRemoved = e.DateRemoved;

        if (dateRemoved != null)
        {
            list = dateAdded.Except(dateRemoved).ToList();
        }
        else
        {
            list = dateAdded.ToList();
        }

    }
</code>```

Body:
For your requirement, you could use Calendar. The SfCalendar plugin provide the MultiSelection SelectionMode to do that.

 <syncfusion:SfCalendar
            x:Name="calendar"
            SelectionChanged="calendar_SelectionChanged"
            SelectionMode="MultiSelection" />

If you want to get all the list of select dates, you could do that in calendar_SelectionChanged event.

 private void calendar_SelectionChanged(object sender, Syncfusion.SfCalendar.XForms.SelectionChangedEventArgs e)
    {
        var dateAdded = e.DateAdded;
        var dateRemoved = e.DateRemoved;

        if (dateRemoved != null)
        {
            list = dateAdded.Except(dateRemoved).ToList();
        }
        else
        {
            list = dateAdded.ToList();
        }

    }


问:
How to run ktor application?
I've created a Ktor application with Gradle and I followed the tutorial on https://ktor.io/quickstart/quickstart/gradle.html#initial.

At the end it says:

And then go to Run -> Edit Configurations select the blog.BlogAppKt
  configuration and change its Main class to:
  io.ktor.server.netty.EngineMain

Now when we run the new configuration, the application will start
  again.

I am searching for the option but could not find it:

The gradle file looks as follows:

```<code>plugins {
    application
    kotlin("jvm") version "1.3.61"
}

group = "org.example"
version = "1.0-SNAPSHOT"

val ktor_version = "1.3.0"

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    implementation(kotlin("stdlib-jdk8"))
    compile("io.ktor:ktor-server-netty:$ktor_version")
    compile("io.ktor:ktor-server-core:$ktor_version")
    compile("ch.qos.logback:logback-classic:1.2.3")
    testCompile(group = "junit", name = "junit", version = "4.12")
}

tasks {
    compileKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
    compileTestKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
}

application {
    mainClassName = "io.ktor.server.netty.EngineMain"
}
</code>```

Update

I'v tried following configuration:

But as you can, there is a error message.

What do I have to add to run the Ktor app?

答:
I believe you have encountered a known bug. See the comments starting here.

When you use JDK 9 or later, you would see this stack trace if you run that configuration:

```<code>java.lang.module.ResolutionException: Modules ktor.http.jvm and ktor.server.core export package io.ktor.http to module ktor.http.cio.jvm
    at java.base/java.lang.module.Resolver.resolveFail(Resolver.java:885)
    at java.base/java.lang.module.Resolver.failTwoSuppliers(Resolver.java:797)
    at java.base/java.lang.module.Resolver.checkExportSuppliers(Resolver.java:718)
    at java.base/java.lang.module.Resolver.finish(Resolver.java:362)
    at java.base/java.lang.module.Configuration.<init>(Configuration.java:141)
    at java.base/java.lang.module.Configuration.resolveAndBind(Configuration.java:316)
    at java.base/java.lang.module.ModuleDescriptor$1.resolveAndBind(ModuleDescriptor.java:2693)
    at java.base/jdk.internal.module.ModuleBootstrap.boot(ModuleBootstrap.java:361)
    at java.base/java.lang.ClassLoader.initializeClassLoaders(ClassLoader.java:210)
    at java.base/java.lang.Thread.initialize(Thread.java:428)
    at java.base/java.lang.Thread.<init>(Thread.java:153)
</code>```

If you switch to JDK 8, then you might see an error in the run configuration dialog, but the application will run.

Title: How to run ktor application?

Body:
I've created a Ktor application with Gradle and I followed the tutorial on https://ktor.io/quickstart/quickstart/gradle.html#initial.

At the end it says:

And then go to Run -> Edit Configurations select the blog.BlogAppKt
  configuration and change its Main class to:
  io.ktor.server.netty.EngineMain

Now when we run the new configuration, the application will start
  again.

I am searching for the option but could not find it:

The gradle file looks as follows:

plugins {
    application
    kotlin("jvm") version "1.3.61"
}

group = "org.example"
version = "1.0-SNAPSHOT"

val ktor_version = "1.3.0"

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    implementation(kotlin("stdlib-jdk8"))
    compile("io.ktor:ktor-server-netty:$ktor_version")
    compile("io.ktor:ktor-server-core:$ktor_version")
    compile("ch.qos.logback:logback-classic:1.2.3")
    testCompile(group = "junit", name = "junit", version = "4.12")
}

tasks {
    compileKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
    compileTestKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
}

application {
    mainClassName = "io.ktor.server.netty.EngineMain"
}

Update

I'v tried following configuration:

But as you can, there is a error message.

What do I have to add to run the Ktor app?

Body:
I believe you have encountered a known bug. See the comments starting here.

When you use JDK 9 or later, you would see this stack trace if you run that configuration:

java.lang.module.ResolutionException: Modules ktor.http.jvm and ktor.server.core export package io.ktor.http to module ktor.http.cio.jvm
    at java.base/java.lang.module.Resolver.resolveFail(Resolver.java:885)
    at java.base/java.lang.module.Resolver.failTwoSuppliers(Resolver.java:797)
    at java.base/java.lang.module.Resolver.checkExportSuppliers(Resolver.java:718)
    at java.base/java.lang.module.Resolver.finish(Resolver.java:362)
    at java.base/java.lang.module.Configuration.<init>(Configuration.java:141)
    at java.base/java.lang.module.Configuration.resolveAndBind(Configuration.java:316)
    at java.base/java.lang.module.ModuleDescriptor$1.resolveAndBind(ModuleDescriptor.java:2693)
    at java.base/jdk.internal.module.ModuleBootstrap.boot(ModuleBootstrap.java:361)
    at java.base/java.lang.ClassLoader.initializeClassLoaders(ClassLoader.java:210)
    at java.base/java.lang.Thread.initialize(Thread.java:428)
    at java.base/java.lang.Thread.<init>(Thread.java:153)

If you switch to JDK 8, then you might see an error in the run configuration dialog, but the application will run.


问:
DOM Based XSS Attack and InnerHTML
How would one go about securing the below DOM Based XSS attack?

Specifically, is there a protect() function that will make the below safe?
If no, then is there another solution?
eg: Giving the div an id and then later assigning the element an onclick handler

```<code><?php
function protect()
{
   // For non-DOM XSS attacks, hex-encoding all non-alphanumeric characters
   // with ASCII values less than 256 works (ie: \xHH)
   // But is it possible to augment this function to protect against
   // the below DOM based XSS attack?
}
?>

<body>
  <div id="mydiv"></div>
  <script type="text/javascript">
    var xss = "<?php echo protect($_GET["xss"]) ?>";
    $("#mydiv").html("<div onclick='myfunc(\""+xss+"\")'></div>")
  </script>
</body>
</code>```

I'm hoping for an answer that is not "avoid using innerHTML" or "regex the xss variable to [a-zA-Z0-9]"...ie: is there a more general solution?

Thanks

答:
Expanding on Vineet's reply, here's a set of test-cases to look into:

http://ha.ckers.org/xss.html

Title: DOM Based XSS Attack and InnerHTML

Body:
How would one go about securing the below DOM Based XSS attack?

Specifically, is there a protect() function that will make the below safe?
If no, then is there another solution?
eg: Giving the div an id and then later assigning the element an onclick handler

<?php
function protect()
{
   // For non-DOM XSS attacks, hex-encoding all non-alphanumeric characters
   // with ASCII values less than 256 works (ie: \xHH)
   // But is it possible to augment this function to protect against
   // the below DOM based XSS attack?
}
?>

I'm hoping for an answer that is not "avoid using innerHTML" or "regex the xss variable to [a-zA-Z0-9]"...ie: is there a more general solution?

Thanks


问:
Issue with script to delete the files with particular extension
I have written the following script to delete the files with a particular extension.However, this script delete the file with the extension '.log' or '.txt' or '.css'.

What if the file extension is '.log000123' or '.log1234', so here extension is constant but random numbers are added after the extension. What can be done to delete such files as well through this script?

Any modification in the script or link to any website where such example is covered will be appreciated.

```<code>import os, time, sys

folder_path = "C:\SampleFolder"
file_ends_with = ".log"
how_many_days_old_logs_to_remove = 7

now = time.time()
only_files = []

for file in os.listdir(folder_path):
    file_full_path = os.path.join(folder_path,file)
    if os.path.isfile(file_full_path) and file.endswith(file_ends_with):
        #Delete files older than x days
        if os.stat(file_full_path).st_mtime < now - how_many_days_old_logs_to_remove * 86400:
             os.remove(file_full_path)
             print "\n File Removed : " , file_full_path
</code>```

答:
You can use regular expressions and os.path.splitext:

```<code>import os
import re

file = "myfile.log123"

pattern = ".log(.*)"  # match .log followed by anything
fname, ext = os.path.splitext(file)

# check this condition:
if re.match(pattern, ext):
    # do stuff
</code>```

Body:
I have written the following script to delete the files with a particular extension.However, this script delete the file with the extension '.log' or '.txt' or '.css'.

What if the file extension is '.log000123' or '.log1234', so here extension is constant but random numbers are added after the extension. What can be done to delete such files as well through this script?

Any modification in the script or link to any website where such example is covered will be appreciated.

import os, time, sys

folder_path = "C:\SampleFolder"
file_ends_with = ".log"
how_many_days_old_logs_to_remove = 7

now = time.time()
only_files = []

for file in os.listdir(folder_path):
    file_full_path = os.path.join(folder_path,file)
    if os.path.isfile(file_full_path) and file.endswith(file_ends_with):
        #Delete files older than x days
        if os.stat(file_full_path).st_mtime < now - how_many_days_old_logs_to_remove * 86400:
             os.remove(file_full_path)
             print "\n File Removed : " , file_full_path

Body:
You can use regular expressions and os.path.splitext:

import os
import re

file = "myfile.log123"

pattern = ".log(.*)"  # match .log followed by anything
fname, ext = os.path.splitext(file)

# check this condition:
if re.match(pattern, ext):
    # do stuff


问:
gandi api call from C# returns 400. Its Working Fine from Postman
I have create gandi api code for create domain and for that i have write below code, but it show me 400 bad request error

```<code>public async System.Threading.Tasks.Task<JsonResult> InsertDomain(DomainDetails domainDetails)
{
  HttpResponseMessage response = new HttpResponseMessage();
  try
  {
    var url = "https://api.gandi.net/v5/domain/domains";

    using ( var client = new HttpClient() )
    {
      var json = new JavaScriptSerializer().Serialize(domainDetails);
      HttpContent HttpContent = new StringContent(json, Encoding.UTF8, "application/json");
      var MyHttpClient = new HttpClient();
      MyHttpClient.DefaultRequestHeaders.Add("authorization", GANDI_API_Key);
      response = await MyHttpClient.PostAsync(url, HttpContent);
    }
  }
  catch ( Exception ex )
  {
    throw;
  }
  return Json(new { result = response }, JsonRequestBehavior.AllowGet);
}
</code>```

but when i try to pass same data using postman then it's working fine below code is my postman data

```<code>Body
{
  "fqdn":"dedasdom1906.com",
  "owner":
    {
      "city":"Paris",
      "given":"Alice",
      "family":"Doe",
      "zip":"75001",
      "country":"FR",
      "streetaddr":"5 rue neuve",
      "phone":"+33.123456789",
      "state":"FR-J",
      "type":"0",
      "email":"alice@example.org"
      }
}

Header
authorization : Apikey
Content-Type : application/json
</code>```

答:
I havent worked with this endpoint, but you are missing the return type.

the next thing i would try is to paste json string directly in the StringContent.

please paste the correct string content(rename the variable)

if none of this help you, please give more details.

```<code>client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
</code>```

Body:
I have create gandi api code for create domain and for that i have write below code, but it show me 400 bad request error

public async System.Threading.Tasks.Task<JsonResult> InsertDomain(DomainDetails domainDetails)
{
  HttpResponseMessage response = new HttpResponseMessage();
  try
  {
    var url = "https://api.gandi.net/v5/domain/domains";

    using ( var client = new HttpClient() )
    {
      var json = new JavaScriptSerializer().Serialize(domainDetails);
      HttpContent HttpContent = new StringContent(json, Encoding.UTF8, "application/json");
      var MyHttpClient = new HttpClient();
      MyHttpClient.DefaultRequestHeaders.Add("authorization", GANDI_API_Key);
      response = await MyHttpClient.PostAsync(url, HttpContent);
    }
  }
  catch ( Exception ex )
  {
    throw;
  }
  return Json(new { result = response }, JsonRequestBehavior.AllowGet);
}

but when i try to pass same data using postman then it's working fine below code is my postman data

Body
{
  "fqdn":"dedasdom1906.com",
  "owner":
    {
      "city":"Paris",
      "given":"Alice",
      "family":"Doe",
      "zip":"75001",
      "country":"FR",
      "streetaddr":"5 rue neuve",
      "phone":"+33.123456789",
      "state":"FR-J",
      "type":"0",
      "email":"alice@example.org"
      }
}

Header
authorization : Apikey
Content-Type : application/json

Body:
I havent worked with this endpoint, but you are missing the return type.

the next thing i would try is to paste json string directly in the StringContent.

please paste the correct string content(rename the variable)

if none of this help you, please give more details.

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


问:
TypeError: Can't convert 'bytes' object to str implicitly while creating a bucket using boto client library plugin
Boto client library plugin

This code is used to create a bucket but I couldn't

```<code>import boto
import time

# URI scheme for Cloud Storage.
GOOGLE_STORAGE = 'gs'
# URI scheme for accessing local files.
LOCAL_FILE = 'file'

now = time.time()

CATS_BUCKET = 'cats-%d' % now
DOGS_BUCKET = 'dogs-%d' % now

print(CATS_BUCKET)
print(DOGS_BUCKET)

for name in (CATS_BUCKET, DOGS_BUCKET):
    # Instantiate a BucketStorageUri object.
    uri = boto.storage_uri(name, GOOGLE_STORAGE)
    # create bucket
    try:
        uri.create_bucket()
        print("Successfully created bucket {}".format(name))
    except boto.exception.StorageCreateError as e:
        print("Failed to create bucket: ", e)
</code>```

I have set up the .boto file and when I run this I'm getting error like

```<code>path = '/' + bucket
</code>```

TypeError: Can't convert 'bytes' object to str implicitly

答:
You can try to decode the uri before using it :

```<code>uri.decode('utf-8')
</code>```

Or you can read it already as utf-8 from the beginning with something like that :

```<code>with open(file_path, encoding='utf-8') as file:
  uri = file.read()
</code>```

I honestly think that this issue is related to the encoding. If my suggestion does not work let me know and I will look further into this direction.

EDIT:

You can try also to get the "uri" object like this :

```<code> uri = boto.storage_uri("%s/%s" % (BUCKET_NAME, DOWNLOAD_PATH), 'gs')
</code>```

Body:
Boto client library plugin

This code is used to create a bucket but I couldn't

import boto
import time

# URI scheme for Cloud Storage.
GOOGLE_STORAGE = 'gs'
# URI scheme for accessing local files.
LOCAL_FILE = 'file'

now = time.time()

CATS_BUCKET = 'cats-%d' % now
DOGS_BUCKET = 'dogs-%d' % now

print(CATS_BUCKET)
print(DOGS_BUCKET)

for name in (CATS_BUCKET, DOGS_BUCKET):
    # Instantiate a BucketStorageUri object.
    uri = boto.storage_uri(name, GOOGLE_STORAGE)
    # create bucket
    try:
        uri.create_bucket()
        print("Successfully created bucket {}".format(name))
    except boto.exception.StorageCreateError as e:
        print("Failed to create bucket: ", e)

I have set up the .boto file and when I run this I'm getting error like

path = '/' + bucket

TypeError: Can't convert 'bytes' object to str implicitly

Body:
You can try to decode the uri before using it :

uri.decode('utf-8')

Or you can read it already as utf-8 from the beginning with something like that :

with open(file_path, encoding='utf-8') as file:
  uri = file.read()

I honestly think that this issue is related to the encoding. If my suggestion does not work let me know and I will look further into this direction.

EDIT:

You can try also to get the "uri" object like this :

 uri = boto.storage_uri("%s/%s" % (BUCKET_NAME, DOWNLOAD_PATH), 'gs')


问:
Different screen size layout on Android
I created layouts for each screen. as sw300dp, sw360dp, sw420dp, sw600dp and sw720dp. But there are different screen sizes that support sw-360dp. For example, 1080x1920 and 1080x2280 images change in my changes to sw360. The image is distorted because the two screen sizes are different.

How can I solve this problem?

答:
If you want enforce certain size (which in discouraged, because android devices varies in screen ratios, sizes and densities in large extent, and there always be some device, where image will be distorted) you can add constraint for minimum height, like drawable-sw360dp-h1024dp.
Or simply use proper scaleType for imageview.

Title: Different screen size layout on Android


问:
Is connectionPoolSetting for single mongos instance or the whole cluster?
I am a server-side developer, working on a project which uses a mongo cluster as persistent database.

I have a question for https://mongodb.github.io/mongo-java-driver/3.8/javadoc/com/mongodb/connection/ConnectionPoolSettings.html

It said to a MongoDB server
But what if I have a connectionString like following one

```<code>mongodb://user:pwd@mongos1:port,mongos3:port,mongos3:port,mongos4:port,mongos5:port,mongos6:port/admin?readPreference=secondaryPreferred
</code>```

A mongodb sharded cluster which has 6 mongos instance.

Question:
Is the connectionPoolSetting related to one mongos server? or related to all mongos servers?

E.g. if we have maxSize = 10 in this setting, does it mean single client has max connection pool = 10 for single mongos server (max pool = 60 for my 6 mongos cluster)? Or max connection pool = 10 for the whole cluster no matter how many mongos server we have?

答: max connection pool = 10 means that in the client pool there will be max 10 connections no matter hoe many server are part of your cluster.</p>

Body:
I am a server-side developer, working on a project which uses a mongo cluster as persistent database.

I have a question for https://mongodb.github.io/mongo-java-driver/3.8/javadoc/com/mongodb/connection/ConnectionPoolSettings.html

It said to a MongoDB server
But what if I have a connectionString like following one

mongodb://user:pwd@mongos1:port,mongos3:port,mongos3:port,mongos4:port,mongos5:port,mongos6:port/admin?readPreference=secondaryPreferred

A mongodb sharded cluster which has 6 mongos instance.

Question:
Is the connectionPoolSetting related to one mongos server? or related to all mongos servers?

E.g. if we have maxSize = 10 in this setting, does it mean single client has max connection pool = 10 for single mongos server (max pool = 60 for my 6 mongos cluster)? Or max connection pool = 10 for the whole cluster no matter how many mongos server we have?


答:
Try this :</p>

```<code>import fnmatch
import os

matches = []
folder_path = "C:\SampleFolder"

how_many_days_old_logs_to_remove = 7

now = time.time()

for root, dirnames, filenames in os.walk(folder_path):

    for filename in fnmatch.filter(filenames, '*.log*'):

        if os.stat(filename).st_mtime < now - how_many_days_old_logs_to_remove * 86400:
             os.remove(filename)
             print "\n File Removed : " , file_full_path

        # matches.append(os.path.join(root, filename))

</code>```

Title: Issue with script to delete the files with particular extension

Body:
Try this :

import fnmatch
import os

matches = []
folder_path = "C:\SampleFolder"

how_many_days_old_logs_to_remove = 7

now = time.time()

for root, dirnames, filenames in os.walk(folder_path):

    for filename in fnmatch.filter(filenames, '*.log*'):

        if os.stat(filename).st_mtime < now - how_many_days_old_logs_to_remove * 86400:
             os.remove(filename)
             print "\n File Removed : " , file_full_path

        # matches.append(os.path.join(root, filename))


问:
angular convert number to persian
I want to convert English numbers to Persian number in angular 4:

```<code>persianNumbers = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"];
englishNumbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
price="1000$";
price= this.fixnumber(price,this.persianNumbers,this.englishNumbers);

fixnumber(src,persian,english){
   for(var i=0; i<10; i++)
      {
        var str = /english[i]/gi;
        src = src.replace(str, persian[i]);
      }
    return src;
}
</code>```

It doesn't work.

答:
You should try :

```<code>persianNumbers[i] = englishNumbers[i].toLocaleString('fa')
</code>```

let enNumber = "50000$";
let faNumber = parseInt(enNumber.split('$')[0], 10).toLocaleString('fa-IR') + '$'; //۵۰٬۰۰۰$
console.log(faNumber);```

Title: angular convert number to persian

Body:
I want to convert English numbers to Persian number in angular 4:

persianNumbers = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"];
englishNumbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
price="1000$";
price= this.fixnumber(price,this.persianNumbers,this.englishNumbers);

fixnumber(src,persian,english){
   for(var i=0; i<10; i++)
      {
        var str = /english[i]/gi;
        src = src.replace(str, persian[i]);
      }
    return src;
}

It doesn't work.

Body:
You should try :

persianNumbers[i] = englishNumbers[i].toLocaleString('fa')

let enNumber = "50000$";
let faNumber = parseInt(enNumber.split('$')[0], 10).toLocaleString('fa-IR') + '$'; //۵۰٬۰۰۰$
console.log(faNumber);


问:
Using VBA can I use a Proxy to webscrape using Internet Explorer?
I have searched high and low for an answer to this.  It's something that I feel intuitively should be easily done, but such intuitions are seldom correct...

I am using VBA and Internet Explorer for web-scraping.

```<code>Dim ie As New InternetExplorer
For Each link In URLs
    ie.Navigate, 16386
    Do: DoEvents: Loop Until ie.readyState = 4

Set Doc = ie.document
</code>```

I then use operands such as "getelementsbyclassname", etc, to extract data from the HTML document.
I don't know if this is the best method, but it works, and easily for me.
(I ave fiddled with using XML requests, but found that I often wasn't getting the right response from the website.)

As I am now getting frequently blocked as a "bot" I would like to try using random proxies from a list.
I know that with some objects this is easy by the .setproxy method, but I can't figure out how to do this using ie.

答:
You could refer to this article about setting proxy IP address with VBA. The method is to edit the registry.

First, save the following code as a setIP.vbs file and place it in some path you can easily reach:

```<code>Option Explicit
Dim valUserIn
Dim objShell, RegLocate, RegLocate1
Dim args

set args = Wscript.Arguments
valUserIn = args(0)
Set objShell = WScript.CreateObject("WScript.Shell")
On Error Resume Next
RegLocate = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyServer"
objShell.RegWrite RegLocate,valUserIn,"REG_SZ"
RegLocate = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyEnable"
objShell.RegWrite RegLocate,"1","REG_DWORD"
WScript.Quit
</code>```

Second, execute this script directly from VBA and pass in the IP argument (note to change the ip address and file path to your owns):

```<code>Sub IPproxy()

'give the proxy server IP address
ipAddress = "xxx.xxx.xxx.xxx"

'Call the vbs script to set the new IP address
Shell "wscript the\path\of\your\file\setIP.vbs " & ipAddress, vbNormalFocus

End Sub
</code>```

After that, when you restart IE you can see that the proxy server has been set. You could check this setting to see the effect: Tools-> Internet Options-> Connections-> LAN Settings-> Use a proxy server for your LAN.

Body:
I have searched high and low for an answer to this.  It's something that I feel intuitively should be easily done, but such intuitions are seldom correct...

I am using VBA and Internet Explorer for web-scraping.

Dim ie As New InternetExplorer
For Each link In URLs
    ie.Navigate, 16386
    Do: DoEvents: Loop Until ie.readyState = 4

Set Doc = ie.document

I then use operands such as "getelementsbyclassname", etc, to extract data from the HTML document.
I don't know if this is the best method, but it works, and easily for me.
(I ave fiddled with using XML requests, but found that I often wasn't getting the right response from the website.)

As I am now getting frequently blocked as a "bot" I would like to try using random proxies from a list.
I know that with some objects this is easy by the .setproxy method, but I can't figure out how to do this using ie.

Body:
You could refer to this article about setting proxy IP address with VBA. The method is to edit the registry.

First, save the following code as a setIP.vbs file and place it in some path you can easily reach:

Option Explicit
Dim valUserIn
Dim objShell, RegLocate, RegLocate1
Dim args

set args = Wscript.Arguments
valUserIn = args(0)
Set objShell = WScript.CreateObject("WScript.Shell")
On Error Resume Next
RegLocate = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyServer"
objShell.RegWrite RegLocate,valUserIn,"REG_SZ"
RegLocate = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyEnable"
objShell.RegWrite RegLocate,"1","REG_DWORD"
WScript.Quit

Second, execute this script directly from VBA and pass in the IP argument (note to change the ip address and file path to your owns):

Sub IPproxy()

'give the proxy server IP address
ipAddress = "xxx.xxx.xxx.xxx"

'Call the vbs script to set the new IP address
Shell "wscript the\path\of\your\file\setIP.vbs " & ipAddress, vbNormalFocus

End Sub

After that, when you restart IE you can see that the proxy server has been set. You could check this setting to see the effect: Tools-> Internet Options-> Connections-> LAN Settings-> Use a proxy server for your LAN.


问:
Print a vector with variable number of elements using sprintf
In the following code, I can print all the elements in the vector item separated by a space as

```<code>item = [123 456 789];
sprintf('%d %d %d', item)

ans =

123 456 789
</code>```

How do I go about doing this without having to enter as many %d as the number of elements in item?

答:
The simplest answer is to note that SPRINTF will automatically cycle through all the elements of a vector you give it, so you only have to use one %d, but follow it or lead it with a space. Then you can remove extra white space on the ends using the function STRTRIM. For example:

```<code>>> item = [123 456 789];
>> strtrim(sprintf('%d ',item))

ans =

123 456 789
</code>```

Body:
In the following code, I can print all the elements in the vector item separated by a space as

item = [123 456 789];
sprintf('%d %d %d', item)

ans =

123 456 789

How do I go about doing this without having to enter as many %d as the number of elements in item?

Body:
The simplest answer is to note that SPRINTF will automatically cycle through all the elements of a vector you give it, so you only have to use one %d, but follow it or lead it with a space. Then you can remove extra white space on the ends using the function STRTRIM. For example:

>> item = [123 456 789];
>> strtrim(sprintf('%d ',item))

ans =

123 456 789


问:
Calculate number of filtered Bigrams
Working on Hands on problems on NLP and got stuck in TASK given below.

Below are the statements which are required to be executed in sequence.

I have completed the below steps but the fresco platform is not accepting the solution.

Please let me know what I did wrong in the below code and steps

TASK

1.Import text corpus brown

Extract the list of words associated with text collections belonging to the
news genre. Store the result in the variable news_words.

Convert each word of the list news_words into lower case, and store the
result in lc_news_words.

Compute bigrams of the list lc_news_words, and store it in the variable
lc_news_bigrams.

From lc_news_bigrams, filter bigrams where both words contain only
alphabet characters. Store the result in lc_news_alpha_bigrams.

Extract the list of words associated with the corpus stopwords. Store the
result in stop_words.

Convert each word of the list stop_words into lower case, and store the
result in lc_stop_words.

Filter only the bigrams from lc_news_alpha_bigrams where the words are
not part of lc_stop_words. Store the result in
lc_news_alpha_nonstop_bigrams.

Print the total number of filtered bigrams.

Below is the code which I have done so far. But fresco platform is not accepting the output.

import nltk

import nltk.corpus

from nltk.corpus import brown

from nltk.util import bigrams

from nltk.corpus import stopwords

news_words = brown.words(categories='news')

lc_news_words  = [w.lower() for w in news_words]

lc_news_bigrams = list(nltk.bigrams(lc_news_words))

lc_news_alpha_bigrams = [(word1, word2) for word1, word2 in lc_news_bigrams if (word1.isalpha() and word2.isalpha()) ]

stop_words = stopwords.words('english')

lc_stop_words = [w.lower() for w in stop_words ]

lc_news_alpha_nonstop_bigrams = [ (w1, w2) for w1, w2 in lc_news_alpha_bigrams if (w1.lower() not in lc_stop_words and w2.lower() not in lc_stop_words) ]

len((lc_news_alpha_nonstop_bigrams))
```

答:
```<code>import nltk
from nltk.corpus import brown
from nltk.corpus import stopwords
news_words     = brown.words(categories='news')
lc_news_words  = [l.lower() for l in news_words]
len_news_words = [len(w) for w in lc_news_words]
news_len_bigrams = list(nltk.bigrams(len_news_words))
cfd_news      = nltk.ConditionalFreqDist(news_len_bigrams)
cfd_news.tabulate(conditions=[6,4])

lc_news_bigrams = list(nltk.bigrams(lc_news_words))
lc_news_alpha_bigrams = [(w1,w2) for w1,w2 in lc_news_bigrams if (w1.isalpha() and w2.isalpha())]
stop_words = stopwords.words()
lc_stop_words = [l.lower() for l in stop_words]
lc_news_alpha_nonstop_bigrams = [ (w1, w2) for w1, w2 in lc_news_alpha_bigrams if (w1.lower() not in lc_stop_words and w2.lower() not in lc_stop_words) ]
print(len((lc_news_alpha_nonstop_bigrams)))
</code>```

Final working code - Python 3

Title: Calculate number of filtered Bigrams

Body:
import nltk
from nltk.corpus import brown
from nltk.corpus import stopwords
news_words     = brown.words(categories='news')
lc_news_words  = [l.lower() for l in news_words]
len_news_words = [len(w) for w in lc_news_words]
news_len_bigrams = list(nltk.bigrams(len_news_words))
cfd_news      = nltk.ConditionalFreqDist(news_len_bigrams)
cfd_news.tabulate(conditions=[6,4])

lc_news_bigrams = list(nltk.bigrams(lc_news_words))
lc_news_alpha_bigrams = [(w1,w2) for w1,w2 in lc_news_bigrams if (w1.isalpha() and w2.isalpha())]
stop_words = stopwords.words()
lc_stop_words = [l.lower() for l in stop_words]
lc_news_alpha_nonstop_bigrams = [ (w1, w2) for w1, w2 in lc_news_alpha_bigrams if (w1.lower() not in lc_stop_words and w2.lower() not in lc_stop_words) ]
print(len((lc_news_alpha_nonstop_bigrams)))

Final working code - Python 3