问:
How to make pdf file password protected?
I want to make pdf file password protected. I just goolge it for the same and find a good solution given below. It's working fine But it wipe out all the data which is already there in my pdf after i secure pdf using below given code.

Used jar files for this code are:

itextpdf-5.2.1.jar

bcmail-jdk16-1.46.jar

bcprov-jdk16-1.46.jar

bctsp-jdk16-1.46.jar

Code to secure PDF :

```<code>import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Secure_file {
    private static String USER_PASSWORD = "password";
    private static String OWNER_PASSWORD = "secured";
    public static void main(String[] args) throws IOException {
        Document document = new Document();
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E:\\sample.pdf"));
            writer.setEncryption(USER_PASSWORD.getBytes(),OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);
            document.open();
            document.add(new Paragraph("This is Password Protected PDF document."));
            document.close();
            writer.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
</code>```

what changes i need to made in this program ?

答:
example using iText5. If use iText7 is very similar but using another class instead of stampler.

```<code>                PdfReader reader = new PdfReader(dp.getStream());
                File tempFile = File.createTempFile("someFilename", FILE_EXTENSION_PDF);
                tempFile.deleteOnExit();
                FileOutputStream os = new FileOutputStream(tempFile);
                PdfStamper stamper = new PdfStamper(reader, os);

                String pdfPassword = "1234"
                String pdfAdminPassword = "5678"
                stamper.setEncryption(
                        pdfPassword.getBytes(),
                        pdfAdminPassword.getBytes(),
                        PdfWriter.ALLOW_PRINTING,
                        PdfWriter.ENCRYPTION_AES_128);

                reader.close();
                stamper.close();

                InputStream encryptedFileIs = new FileInputStream(tempFile);

</code>```

or apache lib pdfbox

```<code>                PDDocument document = PDDocument.load(dp.getStream());
                AccessPermission ap = new AccessPermission();
                StandardProtectionPolicy spp = new StandardProtectionPolicy("1234", "1234", ap);
                spp.setEncryptionKeyLength(128);
                spp.setPermissions(ap);
                document.protect(spp);

                File tempFile = File.createTempFile("someFilename", FILE_EXTENSION_PDF);
                tempFile.deleteOnExit();
                FileOutputStream os = new FileOutputStream(tempFile);
                document.save(os);
                document.close();
                InputStream encryptedFileIs = new FileInputStream(tempFile);
</code>```

Good luck and happy coding :)

Body:
I want to make pdf file password protected. I just goolge it for the same and find a good solution given below. It's working fine But it wipe out all the data which is already there in my pdf after i secure pdf using below given code.

Used jar files for this code are:

itextpdf-5.2.1.jar

bcmail-jdk16-1.46.jar

bcprov-jdk16-1.46.jar

bctsp-jdk16-1.46.jar

Code to secure PDF :

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Secure_file {
    private static String USER_PASSWORD = "password";
    private static String OWNER_PASSWORD = "secured";
    public static void main(String[] args) throws IOException {
        Document document = new Document();
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E:\\sample.pdf"));
            writer.setEncryption(USER_PASSWORD.getBytes(),OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);
            document.open();
            document.add(new Paragraph("This is Password Protected PDF document."));
            document.close();
            writer.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

what changes i need to made in this program ?

Body:
example using iText5. If use iText7 is very similar but using another class instead of stampler.

                PdfReader reader = new PdfReader(dp.getStream());
                File tempFile = File.createTempFile("someFilename", FILE_EXTENSION_PDF);
                tempFile.deleteOnExit();
                FileOutputStream os = new FileOutputStream(tempFile);
                PdfStamper stamper = new PdfStamper(reader, os);

                String pdfPassword = "1234"
                String pdfAdminPassword = "5678"
                stamper.setEncryption(
                        pdfPassword.getBytes(),
                        pdfAdminPassword.getBytes(),
                        PdfWriter.ALLOW_PRINTING,
                        PdfWriter.ENCRYPTION_AES_128);

                reader.close();
                stamper.close();

                InputStream encryptedFileIs = new FileInputStream(tempFile);

or apache lib pdfbox

                PDDocument document = PDDocument.load(dp.getStream());
                AccessPermission ap = new AccessPermission();
                StandardProtectionPolicy spp = new StandardProtectionPolicy("1234", "1234", ap);
                spp.setEncryptionKeyLength(128);
                spp.setPermissions(ap);
                document.protect(spp);

                File tempFile = File.createTempFile("someFilename", FILE_EXTENSION_PDF);
                tempFile.deleteOnExit();
                FileOutputStream os = new FileOutputStream(tempFile);
                document.save(os);
                document.close();
                InputStream encryptedFileIs = new FileInputStream(tempFile);

Good luck and happy coding :)


来源: stackexchange

问:
AddMessage in batch process for a queue
I want to include a lot of records in a queue of Azure.

I don't want to do it one to one. I would like to create a batch process to know if something went wrong.

Because I need to do a rollback proccess if something went wrong.
For example to run a batch of 50 and if the queue gets the 50 records receive a success.

if something went wrong receive a that information.

I know I can include records in a table in a batch way with this command:

```<code>            cloudTable.ExecuteBatchAsync(tableBatchOperation);
</code>```

And I saw on internet a way to do it batch process for queues.
But I think this post it is related with performance, more than batch process success or not.

Any idea? any magic library?

答:
AFAIK, It’s not possible to send messages in a batch to a storage queue.

Azure Service Bus on the other hand supports this functionality. You might want to look into it if batching is important for you.

ContentLicense: CC BY-SA 4.0

Title: AddMessage in batch process for a queue

Body:
I want to include a lot of records in a queue of Azure.

I don't want to do it one to one. I would like to create a batch process to know if something went wrong.

Because I need to do a rollback proccess if something went wrong.
For example to run a batch of 50 and if the queue gets the 50 records receive a success.

if something went wrong receive a that information.

I know I can include records in a table in a batch way with this command:

            cloudTable.ExecuteBatchAsync(tableBatchOperation);

And I saw on internet a way to do it batch process for queues.
But I think this post it is related with performance, more than batch process success or not.

Any idea? any magic library?


问:
How to configure messages.properties in spring bean annotation?
I am starting a new project with spring 4 and I am confusing how I can map my i18n file: messages.properties..

In spring 3 I was using xml configuration like this:

```<code><bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames" value="messages" />
</bean>
<bean id="i18n" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">
        <list>
            <value>classpath:/..../messages.properties</value>
        </list>
    </property>
    <property name="ignoreResourceNotFound" value="true" />
</bean>
</code>```

And in my jsps files I access it by:

```<code><spring:message code="any key" />
</code>```

In spring 4 I am avoiding to use xml configuration.. I tried the following:

```<code>@Bean
public ResourceBundleMessageSource messageSource() throws Exception {
    ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource();
    resourceBundleMessageSource.setBasename("message.properties");
    return resourceBundleMessageSource;
}

@Bean
public PropertiesFactoryBean propertiesFactoryBean() throws Exception {
    PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
    Resource resource = new ClassPathResource("messages.properties");
    propertiesFactoryBean.setLocation(resource);
    return propertiesFactoryBean;
}
</code>```

That class is annotated with @Configuration, but apparently is missing anything..

When I try to access index.jsp, I receive the following exception:

```<code>org.apache.jasper.JasperException: javax.servlet.ServletException: javax.servlet.jsp.JspTagException: No message found under code 'application.title' for locale 'pt_BR'.
</code>```

Any help is appreciated.

Thanks

答:
You need to put file name for each local language. In your case you need

```<code>messages_BR.properties or messages_pt_BR.properties
</code>```

And all the messages in those files.

ContentLicense: CC BY-SA 3.0

Body:
I am starting a new project with spring 4 and I am confusing how I can map my i18n file: messages.properties..

In spring 3 I was using xml configuration like this:

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames" value="messages" />
</bean>
<bean id="i18n" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">
        <list>
            <value>classpath:/..../messages.properties</value>
        </list>
    </property>
    <property name="ignoreResourceNotFound" value="true" />
</bean>

And in my jsps files I access it by:

<spring:message code="any key" />

In spring 4 I am avoiding to use xml configuration.. I tried the following:

@Bean
public ResourceBundleMessageSource messageSource() throws Exception {
    ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource();
    resourceBundleMessageSource.setBasename("message.properties");
    return resourceBundleMessageSource;
}

@Bean
public PropertiesFactoryBean propertiesFactoryBean() throws Exception {
    PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
    Resource resource = new ClassPathResource("messages.properties");
    propertiesFactoryBean.setLocation(resource);
    return propertiesFactoryBean;
}

That class is annotated with @Configuration, but apparently is missing anything..

When I try to access index.jsp, I receive the following exception:

org.apache.jasper.JasperException: javax.servlet.ServletException: javax.servlet.jsp.JspTagException: No message found under code 'application.title' for locale 'pt_BR'.

Any help is appreciated.

Thanks

Body:
You need to put file name for each local language. In your case you need

messages_BR.properties or messages_pt_BR.properties

And all the messages in those files.


问:
API 29 Mediastore Access
My app creates playlists in the android mediastore. All is well for api's including 28 however, api 29 seems to require additional permissions.
Inserting a new playlist name and id works without issue. When it comes to inserting track id and play order, an access permission exception is thrown.
In verifying the Uri, i found that when resolver.insert for API 29 the exception error is:

```<code>java.lang.SecurityException: myapp_name has no access to content://media/external_primary/audio/media/146
</code>```

The code:

```<code>Uri exturi = MediaStore.Audio.Playlists.Members.getContentUri("external", playlist_id);
// exturi : content://media/external/audio/playlists/227/members

// values : audio_id=146 play_order=0
values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, play_order);
values.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, audio_id);

try {
    resolver.insert(exturi, values);
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

Strange thing is that although inserting a new playlist into Mediastore works but adding tracks (track_id, play order) gives an access permission error

How to resolve this exception error for API 29?

Update Feb 2021:
a small step forward, I am pretty sure I need to get Documenturi for the original uri but still gives me the access error. So the issue does not lie with accessing the tracks but with the uri itself.

```<code>doc_uri = MediaStore.getDocumentUri(context,playlist_members_uri);
java.lang.SecurityException: com.flyingdutchman.newplaylistmanager has no access to content://media/external/audio/playlists/130/members
</code>```

答:
I have implemented the SAF so do not use scopedStorage and have access once the user accepts.
The fact that I can insert new playlist entries clearly shows access to MediaStore, I can also delete these. However trying to add tracks to these playlists does not work for api29. Inserting/deleting a new playlist does not involve any files located on internal or external sdcards as it is simply adding values.

the permissions for both internal and external sdcard:

```<code>2020-07-12 14:39:04.435 11858-11858/com.flyingdutchman.newplaylistmanager E/onCreate:: uriPermission: UriPermission {uri=content://com.android.externalstorage.documents/tree/17F5-240A%3A, modeFlags=3, persistedTime=1594551961263}
2020-07-12 14:39:04.435 11858-11858/com.flyingdutchman.newplaylistmanager E/onCreate:: uriPermission: UriPermission {uri=content://com.android.externalstorage.documents/tree/primary%3A, modeFlags=3, persistedTime=1594551926876}
</code>```

The question now becomes

How do I ensure saf permissions are recognised by the resolver.insert method when inserting/modify tracks into the Media database

Title: API 29 Mediastore Access

Body:
My app creates playlists in the android mediastore. All is well for api's including 28 however, api 29 seems to require additional permissions.
Inserting a new playlist name and id works without issue. When it comes to inserting track id and play order, an access permission exception is thrown.
In verifying the Uri, i found that when resolver.insert for API 29 the exception error is:

java.lang.SecurityException: myapp_name has no access to content://media/external_primary/audio/media/146

The code:

Uri exturi = MediaStore.Audio.Playlists.Members.getContentUri("external", playlist_id);
// exturi : content://media/external/audio/playlists/227/members

// values : audio_id=146 play_order=0
values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, play_order);
values.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, audio_id);

try {
    resolver.insert(exturi, values);
} catch (Exception e) {
    e.printStackTrace();
}

Strange thing is that although inserting a new playlist into Mediastore works but adding tracks (track_id, play order) gives an access permission error

How to resolve this exception error for API 29?

Update Feb 2021:
a small step forward, I am pretty sure I need to get Documenturi for the original uri but still gives me the access error. So the issue does not lie with accessing the tracks but with the uri itself.

doc_uri = MediaStore.getDocumentUri(context,playlist_members_uri);
java.lang.SecurityException: com.flyingdutchman.newplaylistmanager has no access to content://media/external/audio/playlists/130/members

Body:
I have implemented the SAF so do not use scopedStorage and have access once the user accepts.
The fact that I can insert new playlist entries clearly shows access to MediaStore, I can also delete these. However trying to add tracks to these playlists does not work for api29. Inserting/deleting a new playlist does not involve any files located on internal or external sdcards as it is simply adding values.

the permissions for both internal and external sdcard:

2020-07-12 14:39:04.435 11858-11858/com.flyingdutchman.newplaylistmanager E/onCreate:: uriPermission: UriPermission {uri=content://com.android.externalstorage.documents/tree/17F5-240A%3A, modeFlags=3, persistedTime=1594551961263}
2020-07-12 14:39:04.435 11858-11858/com.flyingdutchman.newplaylistmanager E/onCreate:: uriPermission: UriPermission {uri=content://com.android.externalstorage.documents/tree/primary%3A, modeFlags=3, persistedTime=1594551926876}

The question now becomes

How do I ensure saf permissions are recognised by the resolver.insert method when inserting/modify tracks into the Media database


问:
How do I call my Javascript inside my other PHP file class
i will try to create a language converter in using PHP but I don't understand how to I call my js code in PHP class !!!

```<code><?php
     require_once __DIR__.'/src/Unicode2Bijoy.php';
?>

<script>

function myfunction(){
    var uni1_val = document.getElementById('uni1_val').value;
    console.log(uni1_val);

   var bijoy_result = <?php echo mirazmac\Unicode2Bijoy::convert($str) ?>;
   console.log(bijoy_result);
}
</script>
</code>```

how can i call this class and result show in my console

Body:
i will try to create a language converter in using PHP but I don't understand how to I call my js code in PHP class !!!

<?php
     require_once __DIR__.'/src/Unicode2Bijoy.php';
?>

how can i call this class and result show in my console

Body: echo"<script>myfunction();</script>";


问:
Passing variable from type std::function fails although the caller expect the exact same type
for some reason I cannot pass value to method with the exact type.

But if I cast the variable I wish to pass using decltype of itself, it somehow works (?)
Perhaps anybody know what's the reason.

Also, When I pass the lambda block to std::function it doesn't require any casting, although they're not exactly the same.

the following example demonstrate my findings :

```<code>#include <functional>

class A {
public:
    A(std::function<void(std::string&, int)> &&f): _f(f) { }

    std::function<void(std::string&,int)> _f;
};

class B : public A {
public:
    //B(std::function<void(std::string&, int)> &&f) : A(f) { } --> fail on casting error, why ?
    B(std::function<void(std::string&, int)> &&f) : A((decltype(f)) f) { }
};

class C {
public:
    C(std::function<void(std::string&,int)> f) {
        //b = new B(f); --> this one trigger casting error, why ?
        b = new B((decltype(f)) f);
    }
    B *b;
};

int main(int argc, const char * argv[]) {
    // this works for some reason, even though C c'tor expect std::function ... why ?
    C c([=](std::string&a, int b) {
        printf("%s %d\n", a.c_str(), b);
    });
}

</code>```

答:
// this works for some reason, even though C c'tor expect std::function ... why ?

```<code>C c([=](std::string&a, int b) {
       printf("%s %d\n", a.c_str(), b);
    });
</code>```

Since the constructors are not explicit, the compiler looks for a constructor that the passed value can be implicitly converted to. So, the passed value, i.e. the lambda, can be converted to a std::function through one of std::function constructors.

```<code>//b = new B(f); --> this one trigger casting error, why ?
b = new B((decltype(f)) f);
</code>```

B's constructor expects a rvalue but f is a lvalue. That causes the error. However the cast creates a temporary, i.e. a copy, which is a rvalue.

```<code>//B(std::function<void(std::string&, int)> &&f) : A(f) { } --> fail on casting error, why ?
B(std::function<void(std::string&, int)> &&f) : A((decltype(f)) f) { }
</code>```

Although f is bound to a rvalue, the f itself since it has a name is a lvalue. Casting it to rvalue (decltype(f)) f)) will convert it back to a rvalue. This is the thing that std::move does.

Body:
for some reason I cannot pass value to method with the exact type.

But if I cast the variable I wish to pass using decltype of itself, it somehow works (?)
Perhaps anybody know what's the reason.

Also, When I pass the lambda block to std::function it doesn't require any casting, although they're not exactly the same.

the following example demonstrate my findings :

#include <functional>

class A {
public:
    A(std::function<void(std::string&, int)> &&f): _f(f) { }

    std::function<void(std::string&,int)> _f;
};

class B : public A {
public:
    //B(std::function<void(std::string&, int)> &&f) : A(f) { } --> fail on casting error, why ?
    B(std::function<void(std::string&, int)> &&f) : A((decltype(f)) f) { }
};

class C {
public:
    C(std::function<void(std::string&,int)> f) {
        //b = new B(f); --> this one trigger casting error, why ?
        b = new B((decltype(f)) f);
    }
    B *b;
};

int main(int argc, const char * argv[]) {
    // this works for some reason, even though C c'tor expect std::function ... why ?
    C c([=](std::string&a, int b) {
        printf("%s %d\n", a.c_str(), b);
    });
}

Body:
// this works for some reason, even though C c'tor expect std::function ... why ?

C c([=](std::string&a, int b) {
       printf("%s %d\n", a.c_str(), b);
    });

Since the constructors are not explicit, the compiler looks for a constructor that the passed value can be implicitly converted to. So, the passed value, i.e. the lambda, can be converted to a std::function through one of std::function constructors.

//b = new B(f); --> this one trigger casting error, why ?
b = new B((decltype(f)) f);

B's constructor expects a rvalue but f is a lvalue. That causes the error. However the cast creates a temporary, i.e. a copy, which is a rvalue.

//B(std::function<void(std::string&, int)> &&f) : A(f) { } --> fail on casting error, why ?
B(std::function<void(std::string&, int)> &&f) : A((decltype(f)) f) { }

Although f is bound to a rvalue, the f itself since it has a name is a lvalue. Casting it to rvalue (decltype(f)) f)) will convert it back to a rvalue. This is the thing that std::move does.


问:
setInterval on a for loop?
```<code>for (var i=list.length; i>=0; i--){
    //do something....
}
</code>```

I want to use a setInterval to make this process take 1 whole min no matter how many items are in the list. So if there are 10 items it would trigger every 6sec, 30items, every two seconds, etc.

Thanks for any help!

答:
Try something like the following:</p>

```<code>var interval = 2;
for (var i=list.length; i>=0; i--){
    setTimeout(your_code_here(), i*interval);
}
</code>```

Title: setInterval on a for loop?

Body:
for (var i=list.length; i>=0; i--){
    //do something....
}

I want to use a setInterval to make this process take 1 whole min no matter how many items are in the list. So if there are 10 items it would trigger every 6sec, 30items, every two seconds, etc.

Thanks for any help!

Body:
Try something like the following:

var interval = 2;
for (var i=list.length; i>=0; i--){
    setTimeout(your_code_here(), i*interval);
}


问:
Highcharts - Line chart mark selected Point
I have a line-chart on my angular app. What I need to do is when I click on any point of the chart to mark that point to distinguish it from the rest. Below is my chart configuration:

```<code>highcharts = Highcharts;
  chartOptions = {
    chart: {
       type: "line"
       },
    credits: {
      enabled: false
    },
    title: {
      enabled: true,
      text: "Reach +1/" + this.xAxis.name,
      verticalAlign: "top",
      align: "left"
    },
    tooltip: {
      formatter: function (data) {
          return data.chart.userOptions.xAxis.title.text + ": " + this.x.toFixed(4) + "<br/>" +
              "Reach: " + this.y.toFixed(4);
      }
  },
    xAxis: {
      title: {
        text: this.xAxis.name
      },
    },
    yAxis: {
       title: {
          text: "Reach"
       }
    },
    series: [
      {
        name: this.xAxis.name,
        data: null,
        allowPointSelect: true,
        point: {
          events: {
            click: function(event) {
              this.yPoint = event.point.y;
              this.xPoint = event.point.x;
              this.filterOptimizationResults(this.xPoint, this.yPoint);
              }.bind(this)
            },
          },
          state: {
            select: {
              enabled: true
            }
          }
        }
      ]
    };
</code>```

Below I'm sharing a screen of the chart for reference:

So for example if y select the point (25,75) I need that point to be circled.

答:
Here is a basic example of how to implement the point toggling by using the point.update and events.click features.

Demo: https://jsfiddle.net/BlackLabel/sh4o3enL/

```<code>point: {
  events: {
    click() {
      let point = this;

      if (point.marker && point.marker.enabled) {
        point.update({
          marker: {
            enabled: false
          }
        })
      } else {
        point.update({
          marker: {
            enabled: true
          }
        })
      }
    }
  }
}
</code>```

API: https://api.highcharts.com/class-reference/Highcharts.Point#update

API: https://api.highcharts.com/highcharts/series.line.point.events.click

Body:
I have a line-chart on my angular app. What I need to do is when I click on any point of the chart to mark that point to distinguish it from the rest. Below is my chart configuration:

highcharts = Highcharts;
  chartOptions = {
    chart: {
       type: "line"
       },
    credits: {
      enabled: false
    },
    title: {
      enabled: true,
      text: "Reach +1/" + this.xAxis.name,
      verticalAlign: "top",
      align: "left"
    },
    tooltip: {
      formatter: function (data) {
          return data.chart.userOptions.xAxis.title.text + ": " + this.x.toFixed(4) + "
" +
              "Reach: " + this.y.toFixed(4);
      }
  },
    xAxis: {
      title: {
        text: this.xAxis.name
      },
    },
    yAxis: {
       title: {
          text: "Reach"
       }
    },
    series: [
      {
        name: this.xAxis.name,
        data: null,
        allowPointSelect: true,
        point: {
          events: {
            click: function(event) {
              this.yPoint = event.point.y;
              this.xPoint = event.point.x;
              this.filterOptimizationResults(this.xPoint, this.yPoint);
              }.bind(this)
            },
          },
          state: {
            select: {
              enabled: true
            }
          }
        }
      ]
    };

Below I'm sharing a screen of the chart for reference:

So for example if y select the point (25,75) I need that point to be circled.

Body:
Here is a basic example of how to implement the point toggling by using the point.update and events.click features.

Demo: https://jsfiddle.net/BlackLabel/sh4o3enL/

point: {
  events: {
    click() {
      let point = this;

      if (point.marker && point.marker.enabled) {
        point.update({
          marker: {
            enabled: false
          }
        })
      } else {
        point.update({
          marker: {
            enabled: true
          }
        })
      }
    }
  }
}

API: https://api.highcharts.com/class-reference/Highcharts.Point#update

API: https://api.highcharts.com/highcharts/series.line.point.events.click


问:
constrOptim initial values
I'm attempting to use the constrOptim() function in R to optimise:

2x + 2y + 3z

subject to:

-2x + y + z <= 1

4x - y + 3z <= 3

x, y, z >= 0

What I have so far is this:

```<code>ui = matrix(c(2,-1,-1,-4, 1,-3, 1, 0, 0, 0, 1, 0, 0, 0, 1),
                     nrow = 5,
                     byrow = T)

ci = c(-1, -3, 0, 0, 0)
theta = c(0, 1, 0)

constrOptim(
  theta = theta,
  f = func,
  ui = ui,
  ci = ci)
</code>```

This gives me the error that "initial value is not in the interior of the feasible region". However, if I run the following as a test:

```<code>ui = matrix(c(2,-1,-1,-4, 1,-3, 1, 0, 0, 0, 1, 0, 0, 0, 1),
                     nrow = 5,
                     byrow = T)

ci = c(-1, -3, 0, 0, 0)
theta = c(0, 1, 0)

ui %*% theta - ci
</code>```

I get (0  4  0  1  0), which is definitely >=0.

My question is why do I get an error telling me that ui %*% theta - ci is not >= 0, when it clearly is? What am I missing?

Edit: managed to sort it out thanks to Stéphane Laurent.

Any ideas how best to plot the feasible region in R? Any useful packages?

答:
The starting value must be in the interior of the feasible region, so you need > 0 and not >= 0. You can use theta = c(0.1, 1, 0.1)

```<code>ui = matrix(c(2,-1,-1,-4, 1,-3, 1, 0, 0, 0, 1, 0, 0, 0, 1),
            nrow = 5,
            byrow = T)
ci = c(-1, -3, 0, 0, 0)
theta = c(0.1, 1, 0.1)

all(ui %*% theta - ci > 0) # TRUE

constrOptim(
  theta = theta,
  f = function(xyz) c(crossprod(c(2,2,3), xyz)),
  grad = NULL,
  ui = ui,
  ci = ci)
</code>```

BTW, it seems obvious to me that the solution is c(0,0,0).

Title: constrOptim initial values

Body:
I'm attempting to use the constrOptim() function in R to optimise:

2x + 2y + 3z

subject to:

-2x + y + z <= 1

4x - y + 3z <= 3

x, y, z >= 0

What I have so far is this:

ui = matrix(c(2,-1,-1,-4, 1,-3, 1, 0, 0, 0, 1, 0, 0, 0, 1),
                     nrow = 5,
                     byrow = T)

ci = c(-1, -3, 0, 0, 0)
theta = c(0, 1, 0)

constrOptim(
  theta = theta,
  f = func,
  ui = ui,
  ci = ci)

This gives me the error that "initial value is not in the interior of the feasible region". However, if I run the following as a test:

ui = matrix(c(2,-1,-1,-4, 1,-3, 1, 0, 0, 0, 1, 0, 0, 0, 1),
                     nrow = 5,
                     byrow = T)

ci = c(-1, -3, 0, 0, 0)
theta = c(0, 1, 0)

ui %*% theta - ci

I get (0  4  0  1  0), which is definitely >=0.

My question is why do I get an error telling me that ui %*% theta - ci is not >= 0, when it clearly is? What am I missing?

Edit: managed to sort it out thanks to Stéphane Laurent.

Any ideas how best to plot the feasible region in R? Any useful packages?

Body:
The starting value must be in the interior of the feasible region, so you need > 0 and not >= 0. You can use theta = c(0.1, 1, 0.1)

ui = matrix(c(2,-1,-1,-4, 1,-3, 1, 0, 0, 0, 1, 0, 0, 0, 1),
            nrow = 5,
            byrow = T)
ci = c(-1, -3, 0, 0, 0)
theta = c(0.1, 1, 0.1)

all(ui %*% theta - ci > 0) # TRUE

constrOptim(
  theta = theta,
  f = function(xyz) c(crossprod(c(2,2,3), xyz)),
  grad = NULL,
  ui = ui,
  ci = ci)

BTW, it seems obvious to me that the solution is c(0,0,0).


问:
remove border bottom in ion header
I have a problem trying to remove ion header border bottom in my ionic app

Here is the code of tab-home.html:

```<code>                <ion-view hide-nav-bar="true">
            <ion-header-bar align-title="left" class="bar-transparent" >
            <button menu-toggle="left" class="button button-icon ion-ios7-settings">
            </button>
            <div class="title"> </div>
            <h1 class="title">proximiti</h1>
            </ion-header-bar>
            <!--<ion-nav-bar class="bar-transparent">
            </ion-nav-bar>-->
            <ion-pane ng-controller="CardsCtrl">
            <!--<ion-nav-buttons side="left">
            <button menu-toggle="left" class="button button-icon ion-navicon"></button>
            </ion-nav-buttons>-->
            <td-cards>
            <td-card ng-repeat="card in cards" on-destroy="cardDestroyed($index)" on-swipe-left="cardSwipedLeft($index)" on-swipe-right="cardSwipedRight($index)" on-partial-swipe="cardPartialSwipe(amt)" class="card-{{card.index}}" ng-controller="CardCtrl">
            <div class="image">
            <!--<div class="yes-text" ng-style="leftTextOpacity">LIKE</div>-->
            <img ng-src="{{card.image}}">
            <!--<div class="no-text" ng-style="rightTextOpacity">NOPE</div>-->
            </div>
            </td-card>
            </td-cards>
            </ion-pane>
            </ion-view>
</code>```

As you can see here the part we're interested in:

```<code>                <ion-view hide-nav-bar="true">
            <ion-header-bar align-title="left" class="bar-transparent" >
            <button menu-toggle="left" class="button button-icon ion-ios7-settings">
            </button>
            <div class="title"> </div>
            <h1 class="title">proximiti</h1>
            </ion-header-bar>
</code>```

I tried everything (in the browser i don't see this border!), but nothing to change it!
Anyone could help me trying to find the way to delete that border?
N.B. : also tried to edit ionic.css and changed only in the browser.

EDIT: And it should be hidden only in this view, so where the class is bar-transparent

答:
For ionic 5, it should be</p>

```<code><ion-header class="ion-no-border"></ion-header>
</code>```

Title: remove border bottom in ion header

Body:
I have a problem trying to remove ion header border bottom in my ionic app

Here is the code of tab-home.html:

                <ion-view hide-nav-bar="true">
            <ion-header-bar align-title="left" class="bar-transparent" >
            <button menu-toggle="left" class="button button-icon ion-ios7-settings">
            </button>

proximiti

            </ion-header-bar>

            <ion-pane ng-controller="CardsCtrl">

            </ion-pane>
            </ion-view>

As you can see here the part we're interested in:

                <ion-view hide-nav-bar="true">
            <ion-header-bar align-title="left" class="bar-transparent" >
            <button menu-toggle="left" class="button button-icon ion-ios7-settings">
            </button>

proximiti

            </ion-header-bar>

I tried everything (in the browser i don't see this border!), but nothing to change it!
Anyone could help me trying to find the way to delete that border?
N.B. : also tried to edit ionic.css and changed only in the browser.

EDIT: And it should be hidden only in this view, so where the class is bar-transparent

Body:
For ionic 5, it should be

<ion-header class="ion-no-border"></ion-header>


问:
How to correctly use regexp match in to find the first 3 letter of relevance in the following strings
I have the following variants of strings.

i) ABC17/REV100/ABC17

ii) 17ABC/REV100/ABC17

iii) ABC17/REV100/17ABC

iv) 17ABC/REV100/17ABC

v) REV100/17ABC

vi) REV100/17

vii) 17ABC/REV100

viii) 17/REV100

ix) REV100

In all of these cases, the three letters REV are the ones I want to extract. How do I set up the correct pattern to match on the three letters in all of these strings?

EDIT:

It does not always have to be REV OR ABC17, it can be other letters. the rule is that its always at the location where REV is in the example strings.

My pattern is not able to match on all strings, example

```<code> '[0-9]?[A-Z]?.*?/?([A-Z]{3}.*?)','REV100/ABC17').group(1)
  prints ABC
</code>```

How do I correctly write the pattern?

答:
You could use an optional group matching 1 or more chars A-Z or digits 0-9 as they come in a different order and match the forward slash.

Then use a capturing group to capture the first 3 uppercase A-Z after the forward slash.

```<code>^(?:[A-Z0-9]+/)?([A-Z]{3})
</code>```

^ Start of string

(?: Non capture group

[A-Z0-9]+/ Match 1+ occurrences of any of the listed

)? Close group and make it optional

([A-Z]{3}) Capture group 1, match 3 uppercase chars

Regex demo | Python demo

If there should be 3 digits following:

```<code>^(?:[A-Z0-9]+/)?([A-Z]{3})\d{3}
</code>```

For example

```<code>import re

items = [
    "ABC17/REV100/ABC17",
    "17ABC/REV100/ABC17",
    "ABC17/REV100/17ABC",
    "17ABC/REV100/17ABC",
    "REV100/17ABC",
    "REV100/17",
    "17ABC/REV100",
    "17/REV100",
    "REV100"
    ]

for item in items:
    print(re.match('^(?:[A-Z0-9]+/)?([A-Z]{3})\d{3}',item).group(1))
</code>```

Output

```<code>REV
REV
REV
REV
REV
REV
REV
REV
REV
</code>```

Body:
I have the following variants of strings.

i) ABC17/REV100/ABC17

ii) 17ABC/REV100/ABC17

iii) ABC17/REV100/17ABC

iv) 17ABC/REV100/17ABC

v) REV100/17ABC

vi) REV100/17

vii) 17ABC/REV100

viii) 17/REV100

ix) REV100

In all of these cases, the three letters REV are the ones I want to extract. How do I set up the correct pattern to match on the three letters in all of these strings?

EDIT:

It does not always have to be REV OR ABC17, it can be other letters. the rule is that its always at the location where REV is in the example strings.

My pattern is not able to match on all strings, example

 '[0-9]?[A-Z]?.*?/?([A-Z]{3}.*?)','REV100/ABC17').group(1)
  prints ABC

How do I correctly write the pattern?

Body:
You could use an optional group matching 1 or more chars A-Z or digits 0-9 as they come in a different order and match the forward slash.

Then use a capturing group to capture the first 3 uppercase A-Z after the forward slash.

^(?:[A-Z0-9]+/)?([A-Z]{3})

^ Start of string

(?: Non capture group

[A-Z0-9]+/ Match 1+ occurrences of any of the listed

)? Close group and make it optional

([A-Z]{3}) Capture group 1, match 3 uppercase chars

Regex demo | Python demo

If there should be 3 digits following:

^(?:[A-Z0-9]+/)?([A-Z]{3})\d{3}

For example

import re

items = [
    "ABC17/REV100/ABC17",
    "17ABC/REV100/ABC17",
    "ABC17/REV100/17ABC",
    "17ABC/REV100/17ABC",
    "REV100/17ABC",
    "REV100/17",
    "17ABC/REV100",
    "17/REV100",
    "REV100"
    ]

for item in items:
    print(re.match('^(?:[A-Z0-9]+/)?([A-Z]{3})\d{3}',item).group(1))

Output

REV
REV
REV
REV
REV
REV
REV
REV
REV


问:
Tokenizing the stop words generated tokens ['ha', 'le', 'u', 'wa'] not in stop_words
I am making a chatbot using Python.
Code:

```<code>import nltk
import numpy as np
import random
import string
f=open('/home/hostbooks/ML/stewy/speech/chatbot.txt','r',errors = 'ignore')
raw=f.read()
raw=raw.lower()# converts to lowercase

sent_tokens = nltk.sent_tokenize(raw)# converts to list of sentences
word_tokens = nltk.word_tokenize(raw)# converts to list of words

lemmer = nltk.stem.WordNetLemmatizer()

def LemTokens(tokens):
    return [lemmer.lemmatize(token) for token in tokens]

remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)

def LemNormalize(text):
    return LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict)))

GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up","hey","hii")
GREETING_RESPONSES = ["hi", "hey", "*nods*", "hi there", "hello", "I am glad! You are talking to me"]

def greeting(sentence):
    for word in sentence.split():
        if word.lower() in GREETING_INPUTS:
            return random.choice(GREETING_RESPONSES)

from sklearn.feature_extraction.text import TfidfVectorizer

from sklearn.metrics.pairwise import cosine_similarity

def response(user_response):
    robo_response=''
    sent_tokens.append(user_response)

    TfidfVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english')
    tfidf = TfidfVec.fit_transform(sent_tokens)
    vals = cosine_similarity(tfidf[-1], tfidf)
    idx=vals.argsort()[0][-2]
    flat = vals.flatten()
    flat.sort()
    req_tfidf = flat[-2]

    if(req_tfidf==0):
        robo_response=robo_response+"I am sorry! I don't understand you"
        return robo_response
    else:
        robo_response = robo_response+sent_tokens[idx]
        return robo_response

flag=True
print("ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye!")

while(flag==True):
    user_response = input()
    user_response=user_response.lower()
    if(user_response!='bye'):
        if(user_response=='thanks' or user_response=='thank you' ):
            flag=False
            print("ROBO: You are welcome..")
        else:
            if(greeting(user_response)!=None):
                print("ROBO: "+greeting(user_response))
            else:
                print("ROBO: ",end="")
                print(response(user_response))
                sent_tokens.remove(user_response)
    else:
        flag=False
        print("ROBO: Bye! take care..")
</code>```

It is running well but with every conversation it's giving this error:

```<code>/home/hostbooks/django1/myproject/lib/python3.6/site-packages/sklearn/feature_extraction/text.py:300: UserWarning: Your stop_words may be inconsistent with your preprocessing.

Tokenizing the stop words generated tokens ['ha', 'le', 'u', 'wa'] not in stop_words.
</code>```

These are some conversations from CMD:

ROBO: a chatbot is a piece of software that conducts a conversation via auditory or textual methods.

what is india

```<code>    /home/hostbooks/django1/myproject/lib/python3.6/site-packages/sklearn/feature_extraction/text.py:300: UserWarning: Your stop_words may be inconsistent with your preprocessing. Tokenizing the stop words generated tokens ['ha', 'le', 'u', 'wa'] not in stop_words. 'stop_words.' % sorted(inconsistent))
</code>```

ROBO: india's wildlife, which has traditionally been viewed with tolerance in india's culture, is supported among these forests, and elsewhere, in protected habitats.

what is chatbot

```<code>    /home/hostbooks/django1/myproject/lib/python3.6/site-packages/sklearn/feature_extraction/text.py:300: UserWarning: Your stop_words may be inconsistent with your preprocessing. Tokenizing the stop words generated tokens ['ha', 'le', 'u', 'wa'] not in stop_words. 'stop_words.' % sorted(inconsistent))
</code>```

ROBO: a chatbot is a piece of software that conducts a conversation via auditory or textual methods.

答:
The reason is that you have used custom tokenizer and used default stop_words='english' so while extracting features a check is made to see if there is any inconsistency between stop_words and tokenizer

If you dig deeper into the code of sklearn/feature_extraction/text.py you will find this snippet performing the consistency check:

```<code>def _check_stop_words_consistency(self, stop_words, preprocess, tokenize):
    """Check if stop words are consistent

    Returns
    -------
    is_consistent : True if stop words are consistent with the preprocessor
                    and tokenizer, False if they are not, None if the check
                    was previously performed, "error" if it could not be
                    performed (e.g. because of the use of a custom
                    preprocessor / tokenizer)
    """
    if id(self.stop_words) == getattr(self, '_stop_words_id', None):
        # Stop words are were previously validated
        return None

    # NB: stop_words is validated, unlike self.stop_words
    try:
        inconsistent = set()
        for w in stop_words or ():
            tokens = list(tokenize(preprocess(w)))
            for token in tokens:
                if token not in stop_words:
                    inconsistent.add(token)
        self._stop_words_id = id(self.stop_words)

        if inconsistent:
            warnings.warn('Your stop_words may be inconsistent with '
                          'your preprocessing. Tokenizing the stop '
                          'words generated tokens %r not in '
                          'stop_words.' % sorted(inconsistent))
</code>```

As you can see it raises warning if an inconsistency is found.

Hope it helps.

Body:
I am making a chatbot using Python.
Code:

import nltk
import numpy as np
import random
import string
f=open('/home/hostbooks/ML/stewy/speech/chatbot.txt','r',errors = 'ignore')
raw=f.read()
raw=raw.lower()# converts to lowercase

sent_tokens = nltk.sent_tokenize(raw)# converts to list of sentences
word_tokens = nltk.word_tokenize(raw)# converts to list of words

lemmer = nltk.stem.WordNetLemmatizer()

def LemTokens(tokens):
    return [lemmer.lemmatize(token) for token in tokens]

remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)

def LemNormalize(text):
    return LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict)))

GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up","hey","hii")
GREETING_RESPONSES = ["hi", "hey", "*nods*", "hi there", "hello", "I am glad! You are talking to me"]

def greeting(sentence):
    for word in sentence.split():
        if word.lower() in GREETING_INPUTS:
            return random.choice(GREETING_RESPONSES)

from sklearn.feature_extraction.text import TfidfVectorizer

from sklearn.metrics.pairwise import cosine_similarity

def response(user_response):
    robo_response=''
    sent_tokens.append(user_response)

    TfidfVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english')
    tfidf = TfidfVec.fit_transform(sent_tokens)
    vals = cosine_similarity(tfidf[-1], tfidf)
    idx=vals.argsort()[0][-2]
    flat = vals.flatten()
    flat.sort()
    req_tfidf = flat[-2]

    if(req_tfidf==0):
        robo_response=robo_response+"I am sorry! I don't understand you"
        return robo_response
    else:
        robo_response = robo_response+sent_tokens[idx]
        return robo_response

flag=True
print("ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye!")

while(flag==True):
    user_response = input()
    user_response=user_response.lower()
    if(user_response!='bye'):
        if(user_response=='thanks' or user_response=='thank you' ):
            flag=False
            print("ROBO: You are welcome..")
        else:
            if(greeting(user_response)!=None):
                print("ROBO: "+greeting(user_response))
            else:
                print("ROBO: ",end="")
                print(response(user_response))
                sent_tokens.remove(user_response)
    else:
        flag=False
        print("ROBO: Bye! take care..")

It is running well but with every conversation it's giving this error:

/home/hostbooks/django1/myproject/lib/python3.6/site-packages/sklearn/feature_extraction/text.py:300: UserWarning: Your stop_words may be inconsistent with your preprocessing.

Tokenizing the stop words generated tokens ['ha', 'le', 'u', 'wa'] not in stop_words.

These are some conversations from CMD:

ROBO: a chatbot is a piece of software that conducts a conversation via auditory or textual methods.

what is india

    /home/hostbooks/django1/myproject/lib/python3.6/site-packages/sklearn/feature_extraction/text.py:300: UserWarning: Your stop_words may be inconsistent with your preprocessing. Tokenizing the stop words generated tokens ['ha', 'le', 'u', 'wa'] not in stop_words. 'stop_words.' % sorted(inconsistent))

ROBO: india's wildlife, which has traditionally been viewed with tolerance in india's culture, is supported among these forests, and elsewhere, in protected habitats.

what is chatbot

    /home/hostbooks/django1/myproject/lib/python3.6/site-packages/sklearn/feature_extraction/text.py:300: UserWarning: Your stop_words may be inconsistent with your preprocessing. Tokenizing the stop words generated tokens ['ha', 'le', 'u', 'wa'] not in stop_words. 'stop_words.' % sorted(inconsistent))

ROBO: a chatbot is a piece of software that conducts a conversation via auditory or textual methods.

Body:
The reason is that you have used custom tokenizer and used default stop_words='english' so while extracting features a check is made to see if there is any inconsistency between stop_words and tokenizer

If you dig deeper into the code of sklearn/feature_extraction/text.py you will find this snippet performing the consistency check:

def _check_stop_words_consistency(self, stop_words, preprocess, tokenize):
    """Check if stop words are consistent

    Returns
    -------
    is_consistent : True if stop words are consistent with the preprocessor
                    and tokenizer, False if they are not, None if the check
                    was previously performed, "error" if it could not be
                    performed (e.g. because of the use of a custom
                    preprocessor / tokenizer)
    """
    if id(self.stop_words) == getattr(self, '_stop_words_id', None):
        # Stop words are were previously validated
        return None

    # NB: stop_words is validated, unlike self.stop_words
    try:
        inconsistent = set()
        for w in stop_words or ():
            tokens = list(tokenize(preprocess(w)))
            for token in tokens:
                if token not in stop_words:
                    inconsistent.add(token)
        self._stop_words_id = id(self.stop_words)

        if inconsistent:
            warnings.warn('Your stop_words may be inconsistent with '
                          'your preprocessing. Tokenizing the stop '
                          'words generated tokens %r not in '
                          'stop_words.' % sorted(inconsistent))

As you can see it raises warning if an inconsistency is found.

Hope it helps.


答:
Something like this could be done:

```<code>var list = [1,2,3,4,5,6,7,8,9,10];
var timeFrame = 60000;
var interval = timeFrame / (list.length-1);
var i = 0;

(function iterate () {
    if (list.length > i) {
        console.log(list[i]);
        i++;
    }
    setTimeout(iterate, interval);
})();
</code>```

JsFiddle Demo

I am not sure if this is what you're looking for, but this will "iterate" through all items in the list, without using for loop, in the given timeframe. The function will always "call itself" using setTimeout. The timeout is calculated in the beginning based on the number of items.

This solution is much more "trustable" than setInterval. The next timeout will be set when the previous action is already done, so it won't stack up.

Title: setInterval on a for loop?

Body:
Something like this could be done:

var list = [1,2,3,4,5,6,7,8,9,10];
var timeFrame = 60000;
var interval = timeFrame / (list.length-1);
var i = 0;

(function iterate () {
    if (list.length > i) {
        console.log(list[i]);
        i++;
    }
    setTimeout(iterate, interval);
})();

JsFiddle Demo

I am not sure if this is what you're looking for, but this will "iterate" through all items in the list, without using for loop, in the given timeframe. The function will always "call itself" using setTimeout. The timeout is calculated in the beginning based on the number of items.

This solution is much more "trustable" than setInterval. The next timeout will be set when the previous action is already done, so it won't stack up.


问:
404 page in REACT
I created the component NotFound and it works fine when I go to a page that doesn't exist. But the same page it's appearing in all my pages, not only the one that doesn't exist. This is the component:

```<code>import React from 'react'

const NotFound = () =>
  <div>
    <h3>404 page not found</h3>
    <p>We are sorry but the page you are looking for does not exist.</p>
  </div>

export default NotFound
</code>```

And this is how I used it in the main page:

```<code>class MainSite extends Component {
  render () {
    return (
      <div>
        {/* Render nav */}
        <Route path='/dashboard' component={Nav} />
        <Route path='/retrospectives' component={Nav} />
        <Route path='/users' component={Nav} />
        <Route path='/projects' component={Nav} />

        {/* Dashboard page */}
        <ProtectedRoute exact path='/dashboard' component={DashboardPage} />

        {/* Retrospectives page */}
        <ProtectedRoute exact path='/retrospectives' component={RetrospectivesPage} />

        {/* Users page */}
        <ProtectedRoute exact path='/users' component={UsersPage} />

        {/* Projects page */}
        <ProtectedRoute exact path='/projects' component={ProjectsPage} />

        {/* Retrospective related pages */}
        <Route exact path='/retrospectives/:retrospectiveId' component={Retrospective} />
        <Route exact path='/join-retrospective' component={JoinRetrospective} />
        <ProtectedRoute exact path='/create-retrospective/:retrospectiveId' component={Retrospective} />

        {/* OnBoarding pages */}
        <ProtectedRoute exact path='/beta-code' component={BetaCodeAccess} />
        <Route exact path='/auth-handler' component={AuthHandler} />
        <Route exact path='/join-organization' component={JoinOrganization} />
      </div>
    )
  }
}

export default MainSite
</code>```

As you can see I use <Route path="*" component={NotFound} /> to create the 404 pages, but that component is appearing in every existing page as well. How can I fix this?

答:
All below example works fine:

```<code><Route path="" component={NotFound} /> // empty ""
<Route path="*" component={NotFound} /> // star *
<Route component={NotFound} /> // without path
</code>```

Or if you want to return a simple 404 message without any component:

```<code><Route component={() => (<div>404 Not found </div>)} />
</code>```

Title: 404 page in REACT

Body:
I created the component NotFound and it works fine when I go to a page that doesn't exist. But the same page it's appearing in all my pages, not only the one that doesn't exist. This is the component:

import React from 'react'

const NotFound = () =>

404 page not found

We are sorry but the page you are looking for does not exist.

export default NotFound

And this is how I used it in the main page:

class MainSite extends Component {
  render () {
    return (

        {/* Render nav */}
        <Route path='/dashboard' component={Nav} />
        <Route path='/retrospectives' component={Nav} />
        <Route path='/users' component={Nav} />
        <Route path='/projects' component={Nav} />

        {/* Dashboard page */}
        <ProtectedRoute exact path='/dashboard' component={DashboardPage} />

        {/* Retrospectives page */}
        <ProtectedRoute exact path='/retrospectives' component={RetrospectivesPage} />

        {/* Users page */}
        <ProtectedRoute exact path='/users' component={UsersPage} />

        {/* Projects page */}
        <ProtectedRoute exact path='/projects' component={ProjectsPage} />

        {/* Retrospective related pages */}
        <Route exact path='/retrospectives/:retrospectiveId' component={Retrospective} />
        <Route exact path='/join-retrospective' component={JoinRetrospective} />
        <ProtectedRoute exact path='/create-retrospective/:retrospectiveId' component={Retrospective} />

        {/* OnBoarding pages */}
        <ProtectedRoute exact path='/beta-code' component={BetaCodeAccess} />
        <Route exact path='/auth-handler' component={AuthHandler} />
        <Route exact path='/join-organization' component={JoinOrganization} />

    )
  }
}

export default MainSite

As you can see I use <Route path="*" component={NotFound} /> to create the 404 pages, but that component is appearing in every existing page as well. How can I fix this?

Body:
All below example works fine:

<Route path="" component={NotFound} /> // empty ""
<Route path="*" component={NotFound} /> // star *
<Route component={NotFound} /> // without path

Or if you want to return a simple 404 message without any component:

<Route component={() => (<div>404 Not found </div>)} />


问:
How to pick color from buttons
I have html tables,and I would like to change its colors by picking up from button and clicking cells.

First,I would like to select colors from buttons,

↓

Second,When I select colors from buttons,I would like to click cells to change color.

↓

Third,After selecting colors,Can I change cell's color by clicking on it?

```<code><tr>
<td>color</td>
</tr>

<button>yellow</button>
<button>aqua</button>
</code>```

At first I assume it will realize by changing td's class,but I couldn't find out the ways.

If someone has experienced such method,please let me know.

Thanks

```<code>td {
  background-color: yellow;
  }

td {
  background-color: aqua;
  }
</code>```

答:
Try this once. It's working

var color = 'black';

$('.click_btn').on('click', function(e) {
  e.preventDefault();
  color = $(this).css('color');
})

$('.click_td').on('click', function(e) {
  e.preventDefault();
  $(this).css('color', color);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="click_td">color</td>
    <td class="click_td">color II</td>
  </tr>
</table>
<button class="click_btn" style="color:yellow;">yellow</button>
<button class="click_btn" style="color:aqua;">aqua</button></code>```

Title: How to pick color from buttons

Body:
I have html tables,and I would like to change its colors by picking up from button and clicking cells.

First,I would like to select colors from buttons,

↓

Second,When I select colors from buttons,I would like to click cells to change color.

↓

Third,After selecting colors,Can I change cell's color by clicking on it?

color

<button>yellow</button>
<button>aqua</button>

At first I assume it will realize by changing td's class,but I couldn't find out the ways.

If someone has experienced such method,please let me know.

Thanks

td {
  background-color: yellow;
  }

td {
  background-color: aqua;
  }

Body:
Try this once. It's working

var color = 'black';

$('.click_btn').on('click', function(e) {
  e.preventDefault();
  color = $(this).css('color');
})

$('.click_td').on('click', function(e) {
  e.preventDefault();
  $(this).css('color', color);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="click_td">color</td>
    <td class="click_td">color II</td>
  </tr>
</table>
<button class="click_btn" style="color:yellow;">yellow</button>
<button class="click_btn" style="color:aqua;">aqua</button>


问:
Python join two frames with one common column
I have in python frame A

and frame B:

How can I Add new column 'name' in frame A in order to display the column z value from the frame b? The common columns between the two frames are A['b'] and B['v']

I'm trying with pandas concat or merge but i'm failing.

The expected result in frame A I would have is:

Thanks a lot.
Best Regards
Giancarlo

答:
How is your merge failing? It should work on a left join with A as left and specifying the left_on and right_on columns:

```<code>final_output = A.merge(B,how='left',left_on='b',right_on='v').rename(columns={'z':'name'}).drop(columns='v')
</code>```

Output:

```<code>     a  b    c     d   name
0  Yes  1  Yes   Buy  name1
1  Yes  2  Yes  Sell  name2
2  Yes  3  Yes   Buy  name3
3  Yes  4  Yes  Sell  name4
</code>```

Body:
How is your merge failing? It should work on a left join with A as left and specifying the left_on and right_on columns:

final_output = A.merge(B,how='left',left_on='b',right_on='v').rename(columns={'z':'name'}).drop(columns='v')

Output:

     a  b    c     d   name
0  Yes  1  Yes   Buy  name1
1  Yes  2  Yes  Sell  name2
2  Yes  3  Yes   Buy  name3
3  Yes  4  Yes  Sell  name4


问:
Is this a bad way to implement a graph?
When I look at a book, I only show examples of how to implement graphs in almost every book by adjacent matrix method and adjacent list method.

I'm trying to create a node-based editor, in which case the number of edges that stretch out on each node is small, but there's a lot of vertex.

So I'm trying to implement the adjacent list method rather than the adjacent matrix method.
However, adjacent lists store and use each edge as a connection list.

But, I would like to use the node in the form listed below.

```<code>class GraphNode
{
    int x, y;
    dataType data;
    vector<GraphNode*> in;
    vector<GraphNode*> out;
public:
    GraphNode(var...) = 0;
};
</code>```

So like this, I want to make the node act as a vertex and have access to other nodes that are connected.

Because when I create a node-based editor program, I have to access and process different nodes that are connected to each node.

I want to implement this without using a linked list.

And, I'm going to use graph algorithms in this state.

Is this a bad method?

Lastly, I apologize for my poor English.

Thank you for reading.

答:
You're just missing the point of the difference between adjacency list and adjacency matrix. The main point is the complexity of operations, like finding edges or iterating over them. If you compare a std::list and a std::vector as datatype implementing an adjacency list, both have a complexity of O(n) (n being the number of edges) for these operations, so they are equivalent.

Other considerations:

If you're modifying the graph, insertion and deletion may be relevant as well. In that case, you may prefer a linked list.

I said that the two are equivalent, but generally std::vector has a better locality of reference and less memory overhead, so it performs better. The general rule in C++ is to use std::vector for any sequential container, until profiling has shown that it is a bottleneck.

Title: Is this a bad way to implement a graph?

Body:
When I look at a book, I only show examples of how to implement graphs in almost every book by adjacent matrix method and adjacent list method.

I'm trying to create a node-based editor, in which case the number of edges that stretch out on each node is small, but there's a lot of vertex.

So I'm trying to implement the adjacent list method rather than the adjacent matrix method.
However, adjacent lists store and use each edge as a connection list.

But, I would like to use the node in the form listed below.

class GraphNode
{
    int x, y;
    dataType data;
    vector<GraphNode*> in;
    vector<GraphNode*> out;
public:
    GraphNode(var...) = 0;
};

So like this, I want to make the node act as a vertex and have access to other nodes that are connected.

Because when I create a node-based editor program, I have to access and process different nodes that are connected to each node.

I want to implement this without using a linked list.

And, I'm going to use graph algorithms in this state.

Is this a bad method?

Lastly, I apologize for my poor English.

Thank you for reading.


问:
How to Take Advantage of Scrapy's Concurrency With Non-Selenium Requests
I've got an interesting problem here.  I'm writing a Scrapy web scraper to obtain products off of a website.  The catalog pages use lazy-loading, which means I cannot obtain more than the first 12 items or use pagination using the default Scrapy.  I have started using Selenium with a headless chrome client in order to scroll the page manually to obtain the data.

I have read online that using Scrapy + Selenium means that I can't run Scrapy requests concurrently, which is unfortunate because the vast majority of my requests don't require Selenium.  My selenium middleware checks the request.meta property to see if it needs to do anything, otherwise it simply returns None.  However, all requests are filtered through the middleware.

My question is  this: Is there a way to allow those requests that DON'T require Selenium to be run concurrently?

My middleware:

```<code>def __init__(self):
    options = Options()
    options.add_argument("--headless")
    self.driver = webdriver.Chrome("path/to/driver", chrome_options=options)

def process_request(self, request, spider):
    if request.meta.get("selenium"):
        self.driver.get(request.url)
        ... # Perform selinium scroll logic and return body
    return None
</code>```

My spider parse function:

```<code>def parse(self, response):
    meta = {"otherMetaData": "data", "selenium": True}
    ... # Obtain link to catalog page
    yield response.follow(page_link, callback=self.parseProducts, meta=meta)

def parseProducts(self, response):
    ... # Obtain links to product pages
    response.meta.pop("selenium")
    yield response.follow(page_link, callback=self.parseProductPage, response.meta)
</code>```

EDIT: Formatting

答:
This was an Issue I faced recently, what you need to know is that Scrapy relies on the scheduler to issue the timing of the requests, The scheduler waits until the value of CONCURRENT_REQUESTS (this value will be skipped if there are less amount of requests to be made i.e when spider is finishing up final requests) is reached then it will make it's requests, the scheduler also depends on priority which you can modify to give certain links higher priority to make them launch earlier in the queue.

There is no direct way of doing what you are asking for,but a good way to do it would be to pass your "non-selenium" requests to a different spider with it's own custom_settings

Body:
I've got an interesting problem here.  I'm writing a Scrapy web scraper to obtain products off of a website.  The catalog pages use lazy-loading, which means I cannot obtain more than the first 12 items or use pagination using the default Scrapy.  I have started using Selenium with a headless chrome client in order to scroll the page manually to obtain the data.

I have read online that using Scrapy + Selenium means that I can't run Scrapy requests concurrently, which is unfortunate because the vast majority of my requests don't require Selenium.  My selenium middleware checks the request.meta property to see if it needs to do anything, otherwise it simply returns None.  However, all requests are filtered through the middleware.

My question is  this: Is there a way to allow those requests that DON'T require Selenium to be run concurrently?

My middleware:

def __init__(self):
    options = Options()
    options.add_argument("--headless")
    self.driver = webdriver.Chrome("path/to/driver", chrome_options=options)

def process_request(self, request, spider):
    if request.meta.get("selenium"):
        self.driver.get(request.url)
        ... # Perform selinium scroll logic and return body
    return None

My spider parse function:

def parse(self, response):
    meta = {"otherMetaData": "data", "selenium": True}
    ... # Obtain link to catalog page
    yield response.follow(page_link, callback=self.parseProducts, meta=meta)

def parseProducts(self, response):
    ... # Obtain links to product pages
    response.meta.pop("selenium")
    yield response.follow(page_link, callback=self.parseProductPage, response.meta)

EDIT: Formatting


问:
HTML table to proper excel table Python
I am pretty new at Python and struggling with printing the web scraping data to beautiful excel table.
Here is a table I am trying to scrape and replicate in Python:
HTML Table.

Here is how HTML page looks like:

```<code></div>
    <section id="first" style="display:none" aria-label="Power situation graph section">
        <div class="gridModule-2up">
            <div class="prognos_controls hidden" data-proggraph="1">
                Show data for:
                <button value="1" onclick="this.blur();" type="button" class="btn  btn--secondary prognosdaybutton"><span class="fa fa-clock-o" aria-hidden="true"></span> Yesterday</button>
                <button value="2" onclick="this.blur();" type="button" class="btn  btn--tertiary prognosdaybutton"><span class="fa fa-clock-o" aria-hidden="true"></span> Today</button>
                <button value="3" onclick="this.blur();" type="button" class="btn  btn--secondary prognosdaybutton"><span class="fa fa-clock-o" aria-hidden="true"></span> Tomorrow</button>
            </div>
            <table summary="Consumption" id="prognos_datatable_total" class="prognos_datatable scrollable">
                <thead>
                    <tr>
                                <th data-sheets-numberformat="[null,1]"></th>
                                <th data-sheets-value="[null,2,'17/02/2020']" data-sheets-numberformat="[null,1]" scope="col">2020-02-17</th>
                                <th data-sheets-numberformat="[null,1]"></th>
                                <th data-sheets-value="[null,2,'18/02/2020']" data-sheets-numberformat="[null,1]" scope="col">2020-02-18</th>
                                <th data-sheets-numberformat="[null,1]"></th>
                                <th data-sheets-value="[null,2,'19/02/2020']" data-sheets-numberformat="[null,1]" scope="col">2020-02-19</th>

                    </tr>
                    <tr>
                        <th caldata-sheets-value="[null,2,'Timme']" data-sheets-numberformat="[null,1]" scope="col">Hour</th>
                                <th data-sheets-value="[null,2,'F\u00f6rbrukning']" data-sheets-numberformat="[null,1]" scope="col">Consumption</th>
                                <th data-sheets-value="[null,2,'Prognos']" data-sheets-numberformat="[null,1]" scope="col">Forecast</th>
                                <th data-sheets-value="[null,2,'F\u00f6rbrukning']" data-sheets-numberformat="[null,1]" scope="col">Consumption</th>
                                <th data-sheets-value="[null,2,'Prognos']" data-sheets-numberformat="[null,1]" scope="col">Forecast</th>
                                <th data-sheets-value="[null,2,'F\u00f6rbrukning']" data-sheets-numberformat="[null,1]" scope="col">Consumption</th>
                                <th data-sheets-value="[null,2,'Prognos']" data-sheets-numberformat="[null,1]" scope="col">Forecast</th>

                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <th data-sheets-value="[null,2,'00-01']" data-sheets-numberformat="[null,1]" scope="col">
                            00-01
                        </th>

                            <td data-sheets-value="[null,2,'15544']" data-sheets-numberformat="[null,1]">15 544</td>
                            <td class="alert_1" data-sheets-value="[null,2,'15143']" data-sheets-numberformat="[null,1]">15 143</td>
                            <td data-sheets-value="[null,2,'15669']" data-sheets-numberformat="[null,1]">15 669</td>
                            <td class="alert_1" data-sheets-value="[null,2,'15869']" data-sheets-numberformat="[null,1]">15 869</td>
                            <td data-sheets-value="[null,2,'-']" data-sheets-numberformat="[null,1]">-</td>
                            <td class="alert_1" data-sheets-value="[null,2,'16422']" data-sheets-numberformat="[null,1]">16 422</td>
                    </tr>
                    <tr>
                        <th data-sheets-value="[null,2,'01-02']" data-sheets-numberformat="[null,1]" scope="col">
                            01-02
                        </th>

                            <td data-sheets-value="[null,2,'15238']" data-sheets-numberformat="[null,1]">15 238</td>
                            <td class="alert_1" data-sheets-value="[null,2,'15052']" data-sheets-numberformat="[null,1]">15 052</td>
                            <td data-sheets-value="[null,2,'15509']" data-sheets-numberformat="[null,1]">15 509</td>
                            <td class="alert_1" data-sheets-value="[null,2,'15366']" data-sheets-numberformat="[null,1]">15 366</td>
                            <td data-sheets-value="[null,2,'-']" data-sheets-numberformat="[null,1]">-</td>
                            <td class="alert_1" data-sheets-value="[null,2,'16176']" data-sheets-numberformat="[null,1]">16 176</td>
                    </tr>
                    <tr>
                        <th data-sheets-value="[null,2,'02-03']" data-sheets-numberformat="[null,1]" scope="col">
                            02-03
                        </th>

                            <td data-sheets-value="[null,2,'15250']" data-sheets-numberformat="[null,1]">15 250</td>
                            <td class="alert_1" data-sheets-value="[null,2,'15135']" data-sheets-numberformat="[null,1]">15 135</td>
                            <td data-sheets-value="[null,2,'15576']" data-sheets-numberformat="[null,1]">15 576</td>
                            <td class="alert_1" data-sheets-value="[null,2,'15501']" data-sheets-numberformat="[null,1]">15 501</td>
                            <td data-sheets-value="[null,2,'-']" data-sheets-numberformat="[null,1]">-</td>
                            <td class="alert_1" data-sheets-value="[null,2,'16124']" data-sheets-numberformat="[null,1]">16 124</td>
                    </tr>
                    <tr>
                        <th data-sheets-value="[null,2,'03-04']" data-sheets-numberformat="[null,1]" scope="col">
                            03-04
                        </th>.............
</code>```

Here is the code I used:

```<code>import requests
import lxml.html as lh
import pandas as pd
from bs4 import BeautifulSoup
import csv

url = 'myURLlink'

response = requests.get(url)

soup = BeautifulSoup(response.text, 'lxml')

extract = soup.select("table")[1]

table = [[item.text for item in row_data.select("th,td")]
                for row_data in extract.select("tr")]

for item in table:
    print(' '.join(item))
</code>```

This is how my output looks with this code: Output.

How can I create a normal data frame from this that I can then export to Excel?

I would appreciate any help.

答:
Try going with pandas here. It uses beautifulsoup under the hood. I can't test it on your URL since you havent provided one.</p>

```<code>import pandas as pd

url = 'myURLlink'
df = pd.read_html(url)[1]

df.to_csv('file.csv', index=False)
print (df.to_string())
</code>```

Title: HTML table to proper excel table Python

Body:
I am pretty new at Python and struggling with printing the web scraping data to beautiful excel table.
Here is a table I am trying to scrape and replicate in Python:
HTML Table.

Here is how HTML page looks like:

                Show data for:
                <button value="1" onclick="this.blur();" type="button" class="btn  btn--secondary prognosdaybutton"> Yesterday</button>
                <button value="2" onclick="this.blur();" type="button" class="btn  btn--tertiary prognosdaybutton"> Today</button>
                <button value="3" onclick="this.blur();" type="button" class="btn  btn--secondary prognosdaybutton"> Tomorrow</button>

                                2020-02-17

                                2020-02-18

                                2020-02-19

                        Hour
                                Consumption
                                Forecast
                                Consumption
                                Forecast
                                Consumption
                                Forecast

                            00-01

                            15 544
                            15 143
                            15 669
                            15 869
                            -
                            16 422

                            01-02

                            15 238
                            15 052
                            15 509
                            15 366
                            -
                            16 176

                            02-03

                            15 250
                            15 135
                            15 576
                            15 501
                            -
                            16 124

                            03-04
                        	.............

Here is the code I used:

import requests
import lxml.html as lh
import pandas as pd
from bs4 import BeautifulSoup
import csv

url = 'myURLlink'

response = requests.get(url)

soup = BeautifulSoup(response.text, 'lxml')

extract = soup.select("table")[1]

table = [[item.text for item in row_data.select("th,td")]
                for row_data in extract.select("tr")]

for item in table:
    print(' '.join(item))

This is how my output looks with this code: Output.

How can I create a normal data frame from this that I can then export to Excel?

I would appreciate any help.

Body:
Try going with pandas here. It uses beautifulsoup under the hood. I can't test it on your URL since you havent provided one.

import pandas as pd

url = 'myURLlink'
df = pd.read_html(url)[1]

df.to_csv('file.csv', index=False)
print (df.to_string())


问:
pd.read_csv is reading less rows than the expected
I'm using pandas to read a csv file, beforehand I already know the file has 13,000 rows, and pandas reads just 9,500 without raising any errors... but here is the thing, when I use 'to_csv()' method, and open the file with excel, it has 13,000 rows, so I don't understand what's happening here...</p>

```<code>raw_data = pd.read_csv(file
                   ,delimiter='|'
                   ,sep='|'
                   ,low_memory= False
                  )
</code>```

答: I had a similar problem once and never really looked into why it added extra rows although i found out that using to_xlsx() and then re-saving it to_csv() it didn't add the extra lines.

Body:
I'm using pandas to read a csv file, beforehand I already know the file has 13,000 rows, and pandas reads just 9,500 without raising any errors... but here is the thing, when I use 'to_csv()' method, and open the file with excel, it has 13,000 rows, so I don't understand what's happening here...

raw_data = pd.read_csv(file
                   ,delimiter='|'
                   ,sep='|'
                   ,low_memory= False
                  )


问:
Static type analysis with Python dicts
Can someone explain why this code, while valid, makes the mypy static analyser complain in multiple ways:

```<code>ranges = dict()
ranges['max'] = 0
ranges['services'] = []
ranges['services'].append('a')
</code>```

Namely:

error: Incompatible types in assignment (expression has type "List[<nothing>]", target has type "int")

error: "int" has no attribute "append"
```

If I simply add a type hint to the initial variable of ranges: dict = dict() it works fine.

I am confused about why the static analyser can't work this out by itself, especially as I am using the dict keyword to initialise the dict in the first instance.

答:
Dictionaries are usually used as keyed collections, the most important operation being to look up the value associated with an arbitrary key. Normally in a dictionary every key has the same type, and every value has the same type; if the values are heterogeneous then the expression ranges[key] wouldn't necessarily have a particular type (though you could represent it as a union).

In your code, the static analyser is trying to infer the type of your dictionary. The type it expects is of the form Dict[K, V] where K and V are yet to be determined. The first assignment ranges['max'] = 0 gives information about both unknowns: K seems to be str and V seems to be int. So at this point, ranges is inferred as type Dict[str, int].

The next two lines then give errors, because an empty list can't be used as a value in a Dict[str, int], and values from a Dict[str, int] don't have an append method.

The explicit type annotation ranges: dict = dict() overrules the default behaviour by specifying that this is a heterogeneous dictionary, so that the values don't all have to have the same type. Given that information, the static analyser doesn't assume that because one of the values is an int that they all have to be ints.

Title: Static type analysis with Python dicts

Body:
Can someone explain why this code, while valid, makes the mypy static analyser complain in multiple ways:

ranges = dict()
ranges['max'] = 0
ranges['services'] = []
ranges['services'].append('a')

Namely:

error: Incompatible types in assignment (expression has type "List[<nothing>]", target has type "int")

error: "int" has no attribute "append"

If I simply add a type hint to the initial variable of ranges: dict = dict() it works fine.

I am confused about why the static analyser can't work this out by itself, especially as I am using the dict keyword to initialise the dict in the first instance.


答:
You want a full join.  You can emulate this in MS Access using:

```<code>select t.CustID, t.DATE, t.Exp1, t.Exp2, s.tem1, s.tem2
from TableT as t left outer join
     tableS as s
     on t.CustId = s.CustId and t.date = s.date
union all
select s.CustID, s.DATE, null, null, s.tem1, s.tem2
from tableS as s left outer join
     tableT as t
     on t.CustId = s.CustId and t.date = s.date
where t.CustId is null;
</code>```

Title: MS Access merge two tables

Body:
I need to create a new table base on two tables. I have a database in ms access and need to migrate.

               tableT                                          tableS

  ID   CustID   DATE   Exp1   Exp2              ID   CustID   DATE   Tem1   Tem2
  --------------------------------              ---------------------------------
  1       1    1/1/00   5      5                1       1    1/1/00   3      4
  2       2    1/1/00   1      3                2       2    1/1/00   5      0
  3       1    3/1/00   3      2                3       1    5/1/00   0      3
  4       3    4/1/00   4      1                4       3    6/1/00   0      0

Desired output table tableNew:

  ID   CustID   DATE   Exp1   Exp2  Tem1   Tem2
  ---------------------------------------------
  1       1    1/1/00   5      5     3      4
  2       2    1/1/00   1      3     5      0
  3       1    3/1/00   3      2
  4       3    4/1/00   4      1
  5       1    5/1/00                0      3
  6       3    6/1/00                0      0

If I use outer join, I will not get the output I need.

Any idea or help.

Body:
You want a full join.  You can emulate this in MS Access using:

select t.CustID, t.DATE, t.Exp1, t.Exp2, s.tem1, s.tem2
from TableT as t left outer join
     tableS as s
     on t.CustId = s.CustId and t.date = s.date
union all
select s.CustID, s.DATE, null, null, s.tem1, s.tem2
from tableS as s left outer join
     tableT as t
     on t.CustId = s.CustId and t.date = s.date
where t.CustId is null;


问:
What is the difference between the PHP functions iconv_strlen, mb_strlen and strlen?
What is the difference between the iconv_strlen, mb_strlen and strlen functions?

And what is each used for in the real world?

答:
The difference of strlen() to mb_strlen() is, that the second respects multibyte characters. This means, that this is the real character count. The first one assumes, that the string is always in ascii, what also means, that it always returns the size in bytes (very useful when handling binary "strings").

As far as I can see iconv_strlen() is quite similar to mb_strlen(), but fails on bad character sequences, in contrast to mb_strlen(), that just ignores them. And it uses the iconv-library (obviously ;)).


问:
NgbDropdown doesn't stay open
I want to have a login dropdown in my navbar. However, as soon as something within the login form is clicked, the dropdown closes.

Another question: How can I make the dropdown appear aligned with the toggle on the right side? Right now it left-aligns with the toggle.

Here is my code:

```<code><nav class="navbar navbar-dark bg-inverse">
   <ul class="nav navbar-nav">
      <li *ngIf="!user" class="nav-item dropdown float-xs-right">
        <div ngbDropdown autoClose="false" class="d-inline-block pull-left">
            <a class="nav-link" id="loginDropdown" aria-haspopup="true" aria-expanded="false" ngbDropdownToggle>Login</a>
            <div class="dropdown-menu" aria-labelledby="loginDropdown">
                <login></login> <!--The login component, it's just a form-->
            </div>
        </div>
      </li>
   </ul>
</nav>
</code>```

答:
You're looking for autoClose with value "outside"

```<code><div ngbDropdown [autoClose]="'outside'" >
</code>```

The dropdown will close only on the outside clicks and not on menu clicks.

Title: NgbDropdown doesn't stay open

Body:
I want to have a login dropdown in my navbar. However, as soon as something within the login form is clicked, the dropdown closes.

Another question: How can I make the dropdown appear aligned with the toggle on the right side? Right now it left-aligns with the toggle.

Here is my code:

            Login

                <login></login>

Body:
You're looking for autoClose with value "outside"

<div ngbDropdown [autoClose]="'outside'" >

The dropdown will close only on the outside clicks and not on menu clicks.


问:
Using "Format as table" to filter rows is slow
I currently have a sheet that has 1381 rows and 128 columns (info type by rows, country by columns).
Above the data I have several buttons that keeps only specific rows hidden, that belong to a group or section.
I was asked to allow more than one section to remain visible, and what I did is inserted 1 column, filled it with the Section name, used "Format as table" only on that row, created a slicer from that table, and that allows me to use the Slicer to Hide/Unhide rows that have the same Section Name.
The problem is it is very slow if I use it this way, I select a section from the slicer, or filter, and it takes 2-3 minutes to process...
I converted the table to a normal range, generated the filter, and it's almost instant, but I lose slicer functionality if i do it this way.

The only formula I use on the only column converted to table is:

```<code>=CHOOSE(--SWITCH_REG+1,OffChar,OnChar) & " " & "Site contracting"
</code>```

The "SWITCH_" and the ending string change for each section, but they are manually generated, so I don't see why the table is so slow.

Am I doing something wrong that the table filter is so slow?

答:
I solved the issue by following these steps:

Converted table to range.

Created pivot table with 1 field from said
range.

Created Slicer from the pivot table.

Added macro trigger on pivot table change to get filter values from the Slicer and apply them as a filter to the initial range. Code below:

```<code>Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)

    Dim rngTableAll As Range, filterField, arrFilterValues
    Dim firstCol, lastCol, sectionI

    'UPDATE FILTER WHEN SLICER IS UPDATED
    If Target.NAME = "CatPiv" Then
        With Inputs_03
            Set rngTableAll = .Range("_FilterDatabase")
            filterField = 1
            arrFilterValues = GETSLICERITEMS_ARRAY("Slicer_SubCat")
            rngTableAll.AutoFilter Field:=filterField, Criteria1:=arrFilterValues, Operator:=xlFilterValues, VisibleDropDown:=False

            'HIDE ARROWS 'CAREFULL, IT'S SLOW
'            Application.Calculation = xlCalculationManual
'            For filterField = 2 To rngTableAll.Columns.Count - 2
'                rngTableAll.AutoFilter Field:=filterField, VisibleDropDown:=False
'            Next
'            Application.Calculation = xlCalculationAutomatic
        End With

    End If

End Sub
Public Function GETSLICERITEMS_ARRAY(SlicerName As String)
    'https://www.excelforum.com/excel-general/1178647-trigger-event-on-slicer-selection-update.html
    Dim arrItems, strItems

    strItems = GETSLICERITEMS(SlicerName)
    arrItems = Split(strItems, ", ")

    GETSLICERITEMS_ARRAY = arrItems
End Function
</code>```

How to get slicer items: 'https://www.excelforum.com/excel-general/1178647-trigger-event-on-slicer-selection-update.html

Body:
I currently have a sheet that has 1381 rows and 128 columns (info type by rows, country by columns).
Above the data I have several buttons that keeps only specific rows hidden, that belong to a group or section.
I was asked to allow more than one section to remain visible, and what I did is inserted 1 column, filled it with the Section name, used "Format as table" only on that row, created a slicer from that table, and that allows me to use the Slicer to Hide/Unhide rows that have the same Section Name.
The problem is it is very slow if I use it this way, I select a section from the slicer, or filter, and it takes 2-3 minutes to process...
I converted the table to a normal range, generated the filter, and it's almost instant, but I lose slicer functionality if i do it this way.

The only formula I use on the only column converted to table is:

=CHOOSE(--SWITCH_REG+1,OffChar,OnChar) & " " & "Site contracting"

The "SWITCH_" and the ending string change for each section, but they are manually generated, so I don't see why the table is so slow.

Am I doing something wrong that the table filter is so slow?

Body:
I solved the issue by following these steps:

Converted table to range.

Created pivot table with 1 field from said
range.

Created Slicer from the pivot table.

Added macro trigger on pivot table change to get filter values from the Slicer and apply them as a filter to the initial range. Code below:

Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)

    Dim rngTableAll As Range, filterField, arrFilterValues
    Dim firstCol, lastCol, sectionI

    'UPDATE FILTER WHEN SLICER IS UPDATED
    If Target.NAME = "CatPiv" Then
        With Inputs_03
            Set rngTableAll = .Range("_FilterDatabase")
            filterField = 1
            arrFilterValues = GETSLICERITEMS_ARRAY("Slicer_SubCat")
            rngTableAll.AutoFilter Field:=filterField, Criteria1:=arrFilterValues, Operator:=xlFilterValues, VisibleDropDown:=False

            'HIDE ARROWS 'CAREFULL, IT'S SLOW
'            Application.Calculation = xlCalculationManual
'            For filterField = 2 To rngTableAll.Columns.Count - 2
'                rngTableAll.AutoFilter Field:=filterField, VisibleDropDown:=False
'            Next
'            Application.Calculation = xlCalculationAutomatic
        End With

    End If

End Sub
Public Function GETSLICERITEMS_ARRAY(SlicerName As String)
    'https://www.excelforum.com/excel-general/1178647-trigger-event-on-slicer-selection-update.html
    Dim arrItems, strItems

    strItems = GETSLICERITEMS(SlicerName)
    arrItems = Split(strItems, ", ")

    GETSLICERITEMS_ARRAY = arrItems
End Function

How to get slicer items: 'https://www.excelforum.com/excel-general/1178647-trigger-event-on-slicer-selection-update.html