问:
Not in table between dates
I have 2 tables :

terminal

```<code>id   text
1    abc
2    def
3    dfg
</code>```

termusage

```<code>id  termid   date
1   1        2010-11-01
2   1        2010-10-13
3   2        2010-11-10
4   3        2010-11-13
</code>```

+ many more records (10 million) approv half are within the date (2010-11-01 and 2010-12-01)

What i want to do is find the terminal.id of the records that do not exist in the termusage table between 2010-11-01 and 2010-12-01

I have looked at select where not exists but nothing is being returned - example

```<code>select * from terminal
where not exists (
select * from termusage where date between '2010-11-01' and '2010-12-01' group by termid)
</code>```

Can anyone please explain how i need to use the where not exists clause or another method !! Cheers

答:
```<code>SELECT DISTINCT `terminal`.`id`
  FROM `terminal`
  LEFT JOIN
      (
       SELECT `termid`
         FROM `termusage`
        WHERE `date` BETWEEN "2010-11-01" AND "2010-12-01"
      )
    AS `_` ON (`terminal`.`id` = `_`.`termid`)
 WHERE ISNULL(`_`.`termid`)
</code>```

The ON clause indicates how the LEFT JOIN will be performed, and the _ is a table alias. A table alias is required here.

BTW, what's termusage.id for? Do you really need that column?

Title: Not in table between dates

Body:
I have 2 tables :

terminal

id   text
1    abc
2    def
3    dfg

termusage

id  termid   date
1   1        2010-11-01
2   1        2010-10-13
3   2        2010-11-10
4   3        2010-11-13

+ many more records (10 million) approv half are within the date (2010-11-01 and 2010-12-01)

What i want to do is find the terminal.id of the records that do not exist in the termusage table between 2010-11-01 and 2010-12-01

I have looked at select where not exists but nothing is being returned - example

select * from terminal
where not exists (
select * from termusage where date between '2010-11-01' and '2010-12-01' group by termid)

Can anyone please explain how i need to use the where not exists clause or another method !! Cheers

Body:
SELECT DISTINCT `terminal`.`id`
  FROM `terminal`
  LEFT JOIN
      (
       SELECT `termid`
         FROM `termusage`
        WHERE `date` BETWEEN "2010-11-01" AND "2010-12-01"
      )
    AS `_` ON (`terminal`.`id` = `_`.`termid`)
 WHERE ISNULL(`_`.`termid`)

The ON clause indicates how the LEFT JOIN will be performed, and the _ is a table alias. A table alias is required here.

BTW, what's termusage.id for? Do you really need that column?


来源: stackexchange

问:
Expo with Android Studio Emulator error: "Error running adb: This computer is not authorized to debug the device"
I am trying to connect an Android Studio Emulator to my expo application, but I get this error message:

Couldn't start project on Android: Error running adb: This computer is
  not authorized to debug the device. Please follow the instructions
  here to enable USB debugging:
  https://developer.android.com/studio/run/device.html#developer-device-options.
  If you are using Genymotion go to Settings -> ADB, select "Use custom
  Android SDK tools", and point it at your Android SDK directory.

Does anyone know what to do with this?

Thanks!

答:
I know the exact answer of this question
The Problem is your AVD manager is not set to the path
Than you have add to path first is ANDROID_SDK_ROOT and PLATFORM-TOOLS
HERE I GIVE ALL THE LOCATION PLATFORM TOOLS - C:\Users\YOUR_USERNAME\AppData\Local\Android\Sdk\platform-tools
ANDROID_DK_ROOT - C:\Users\YOUR_USERNAME\AppData\Local\Android\Sdk
ADD in path (SEARCH ON START EVIRONMENT VARIABLES) and than restart your pc</p>

ContentLicense: CC BY-SA 4.0


问:
How can I clean html code data in a DataFrame?

I called an api, and put it in a DataFrame.

 There is a column with a lot of rows and the values are HTML code. I would like to clean the HTML code, only the wording itself. How can I do that?

Example:

```<code><p><span style="color: red;">家庭旅遊保險計劃</span><span style="font-size: 11.5pt;color: red;">包</span><span style="font-size: 11.5pt;color: red;">括</span><span style="color: red;">申請人及配偶，及<b>免費</b>最多其四名</span><span style="color: red;">18</span><span style="color: red;">歲以下之同行子女</span><span style="color: red;"></span></p><p>每人每次最高賠償額* (港元)</p><p><b>金計劃</b><span style="font-size: 11.5pt;color: black;"><br/> </span>醫療費用 $1,000,000<span style="font-size: 11.5pt;color: black;"><br/> </span>個人意外 $1,000,000<span style="font-size: 11.5pt;color: black;"><br/> </span>手機意外損毀或遺失 $3,000</p><p><b>銅計劃</b><span style="font-size: 11.5pt;color: black;"><br/> </span>醫療費用 $250,000<span style="font-size: 11.5pt;color: black;"><br/> </span>個人意外 $250,000</p><p>*18歲以下及75歲以上之受保人於計劃內的保障額將會減少<br/></p>
</code>```

答:
You can use beautiful soup to find the HTML class and then use .text to store it in a list.

```<code>
title = new_soup.find("HTML tag", class_="add class name of HTML tag")
name.append(title.text)

</code>```

It will filter out everything except text.

Body:
I called an api, and put it in a DataFrame.

 There is a column with a lot of rows and the values are HTML code. I would like to clean the HTML code, only the wording itself. How can I do that?

Example:

家庭旅遊保險計劃包括申請人及配偶，及免費最多其四名18歲以下之同行子女

每人每次最高賠償額* (港元)

金計劃
 醫療費用 $1,000,000
 個人意外 $1,000,000
 手機意外損毀或遺失 $3,000

銅計劃
 醫療費用 $250,000
 個人意外 $250,000

*18歲以下及75歲以上之受保人於計劃內的保障額將會減少

Body:
You can use beautiful soup to find the HTML class and then use .text to store it in a list.

title = new_soup.find("HTML tag", class_="add class name of HTML tag")
name.append(title.text)

It will filter out everything except text.


问:
C++ Can Inherited Methods Use Child Class Members
As the title states, in C++ can inherited methods use child class members?

For example suppose we define a solid to have a property (a volume) and a method that returns the property. Then in the child class, say a box, we have the same property. Will the inherited method return the parent class's property or the child class's property?

And as an extension to that, can inherited methods use child class specific (overridden) implementations of methods also defined in the parent class? Or would the best solution be to pass in function pointers?

EDIT:

For the extension part of the question consider this example:

class A{
   public:
        void foo(){
           foo2();
        }
        void foo2(){
           // implementation here
        }
}

class B:A{
   public:
        void foo2(){
           // child implementation here
        }
}

int main(){
  B b;
  A a;
  b.foo(); // I want foo to use b's implementation of foo2
}
```

答:
It is able to be realized using CRTP pattern, which utilize template.</p>
```<code>template<class Derived>
class A {
public:
    void foo() {
        static_cast<Derived*>(this)->foo2();
    }
};

class B :public A<B> {
public:
    void foo2() {
        // child implementation here
    }
};

int main() {
    B b;
    b.foo(); // Uses foo to use b's implementation of foo2
}
</code>```

Body:
It is able to be realized using CRTP pattern, which utilize template.

template<class Derived>
class A {
public:
    void foo() {
        static_cast<Derived*>(this)->foo2();
    }
};

class B :public A<B> {
public:
    void foo2() {
        // child implementation here
    }
};

int main() {
    B b;
    b.foo(); // Uses foo to use b's implementation of foo2
}


问:
Is there a risk in using self signed public key for issuing JWT token?
I have a service that issues tokens to registered clients.
Service generates a public key and private key. Stores the private key securely.
When a client requests for a token, my service authenticates the client and issues a JWT token which is signed using the private key. My service also publishes the JWKS URI,which has public key info and a public certificate.

Question:

My service is exposing the token and JWKS URI to the internet (https) . What is the risk of exposing the public key and certificate which is self-signed?

答:
Compromised self-signed certificates can pose many security challenges, since attackers can spoof the identity of the victim. Unlike CA-issued certificates, self-signed certificates cannot be revoked. The inability to quickly find and revoke private key associated with a self-signed certificate creates serious risk.

more details here on this link


问:
What does the keyword ref mean in C#?
Below is my code please explain what is ref cboListType.</p>

```<code>Lists.LoadListTypes(ref cboListType);

public static void LoadListTypes(ref DropDownList dropDown)
{
    if (!Util.IsCached(LIST_TYPES))
    {
        Util.InsertIntoCache(LIST_TYPES, DataAccess.ListListTypes());
    }

    dropDown.DataSource = (DataTable)Util.GetFromCache(LIST_TYPES);
    dropDown.DataBind();
    dropDown.Items.Insert(0, new ListItem("", ""));
}
</code>```

答: ref means parameter is passed by reference, not by value. More detailed info

ContentLicense: CC BY-SA 3.0

Title: What does the keyword ref mean in C#?

Body:
Below is my code please explain what is ref cboListType.

Lists.LoadListTypes(ref cboListType);

public static void LoadListTypes(ref DropDownList dropDown)
{
    if (!Util.IsCached(LIST_TYPES))
    {
        Util.InsertIntoCache(LIST_TYPES, DataAccess.ListListTypes());
    }

    dropDown.DataSource = (DataTable)Util.GetFromCache(LIST_TYPES);
    dropDown.DataBind();
    dropDown.Items.Insert(0, new ListItem("", ""));
}


问:
I keep getting "ERROR: AddressSanitizer: heap-buffer-overflow on address"
I can't figure out this error.

Problem > Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".

```<code>char * longestCommonPrefix(char ** strs, int strsSize){
    int i = 1;
    int j = 0;
    int k = 1;
    int n = 0;

    if (strsSize == 0) return ("");
    if (strsSize == 1) return (strs[0]);
    if (strsSize > 1 && strcmp(strs[0],"") == 0) return ("");

    char *s = calloc(strlen(strs[0]), sizeof(char));
    char *temp = calloc(strlen(strs[0]), sizeof(char));
    if (!s || !temp) return (0);

    // while (strs[0][j] != '\0') {
    //     temp[j] = strs[0][j];
    //     j++;
    // }
    strcpy(temp, strs[0]);

    while (k < strsSize) {
        j = 0;
        n = 0;
        memset(s, 0, strlen(s));
        while (strs[i][j]){
            if (temp[j] == strs[i][j]) {
                s[n] = strs[i][j];
                n++;
            }
            else if (temp[j] != strs[i][j]){
                break;
            }
            j++;
        }
        strcpy(temp, s);
        k++;
        i++;
    }
    return (s);
}
</code>```

It works without any problem on my visual studio but when I submit this code to Leetcode, it always has that error message. I assume error occurs on either line 7 or 8 because it dose not show same error when I hide those two line of codes. Also, when I copy strs[0] string to temp using while loop, it works fine on both Leetcode and visual studio but it does not work when I use "scrcpy" function on Leetcode but again, it works on my visual studio.

Another minor problem. The reason that I use calloc to allocate the memory is because It shows same error message "Address sani~" when using malloc. It does not matter on visual studio. Both calloc and malloc work ok.

I've added an extra memory for NULL terminator.

```<code>char *s = malloc((strlen(strs[0]) + 1) * sizeof(char));
</code>```

It seems alright in my head but It has same memory issue.

I've tried many different ways but I still have issue with the way I use malloc and clear a string.

```<code>int len = strlen(strs[0]);
char *temp = malloc((len+1) * sizeof(char))
//it still gives me a memory error.
</code>```

When I clear my string with memset, it returns a correct output but it does not return the right answer when I clear the string simply using NULL terminator. Is there a difference?

```<code>s[j] = '\0';
memset(s, 0, strlen(s));
</code>```

答:
The main difference between malloc and calloc is that malloc only reserves memory but doesn't modify its contents, whereas calloc reserves memory and zero-initializes every byte.

So, what's happening inside your loop where you begin copying string prefixes into s is you did this:

```<code>memset(s, 0, strlen(s));
</code>```

Now, you thought that you just cleared the string, but at this point it's the first time you've done anything with s at all.  So if s was allocated with malloc then calling strlen(s) could do anything.  Very likely the uninitialized memory contents will not be a NUL-terminated string, and strlen will happily search past the end of that block of memory and into other parts of memory that your program did not request.

This is known as Undefined Behavior.

So, what can you do about it?  Well, in the comments you tried this:

```<code>s[0] = '\0';
</code>```

Great!  But now every other byte of the string is not initialized.  You're about to loop over strs[i] and copy stuff into s.  The problem is that afterwards you never copied in a NUL-terminator, so once again you have an un-terminated string.  And, to be specific, the place where that terminator would have gone is still uninitialized.

As I already said very early on in comments, all you need to do is write that terminator after copying.  You don't really need two variables j and n because they're going to be the same value anyway.  Let's just use j.  It makes the code simpler.

```<code>j = 0;
while (strs[i][j] && temp[j] == strs[i][j])
{
    s[j] = strs[i][j];
    j++;
}
s[j] = '\0';
</code>```

That's all.  You have a terminated string.  You didn't need to pre-initialize it, because you were about to overwrite that memory anyway.  The important part is the line after the loop.

Now, let's think a bit about what you're really trying to achieve here.

The task is to search all strings in the array and find the longest common prefix.  And looking at your code, not only is it doing too much work, it's actually not even achieving the required task.  Hint: you never used the variable k.

So why not take a step back and think about it differently?  Do you actually need to copy prefixes over and over?  No, you don't.  All you need to do is see how many characters they have in common.  And, you don't even need to check all the characters -- you only need to check up to whatever maximum count you've already found.

```<code>// Find longest common prefix
int commonPrefixLength = strlen(strs[0]);
for (int i = 1; i < strsSize; i++)
{
    int p = 0;
    while (p < commonPrefixLength && strs[i][p] == strs[0][p]) ++p;
    commonPrefixLength = p;
}

// Copy prefix to a new string
char *commonPrefix = malloc(commonPrefixLength + 1);
memcpy(commonPrefix, strs[0], commonPrefixLength);
commonPrefix[commonPrefixLength] = 0;
</code>```

That's all you need to do.  You don't even need to check for the NUL terminator when searching the strings because you've already bounded the search by the longest prefix and it's guaranteed that if you encounter a NUL-terminator then it won't be equal to the character you're testing in strs[0].  Nice.

However we have another issue, and that is your function is not consistent about what it returns.  You wrote some special cases that might return strs[0] or a string literal "".  Otherwise it allocates new memory and returns that.  This is a problem, because the caller does not know whether it is supposed to free this memory or not.

So you should decide.  The options are:

Function either allocates or returns NULL -- caller always responsible for freeing memory.

Function never allocates -- returns NULL or modifies str[0] and returns that

If you choose 2, then instead of allocating and copying stuff after the loop, you'd just terminate the string.  However, you can only do this if input array was not string literals:

```<code>strs[0][commonPrefixLength] = '\0';
</code>```

So the safest choice is probably option 1.  But here are both...

Option 1:

```<code>char * longestCommonPrefix(char ** strs, int strsSize)
{
    if (strsSize == 0)
        return NULL;

    int commonPrefixLength = strlen(strs[0]);
    for (int i = 1; i < strsSize; i++)
    {
        int p = 0;
        while (p < commonPrefixLength && strs[i][p] == strs[0][p]) ++p;
        commonPrefixLength = p;
    }

    char *commonPrefix = malloc(commonPrefixLength + 1);
    if (commonPrefix != NULL)
    {
        memcpy(commonPrefix, strs[0], commonPrefixLength);
        commonPrefix[commonPrefixLength] = 0;
    }
    return commonPrefix;
}
</code>```

Option 2:

```<code>char * longestCommonPrefix(char ** strs, int strsSize)
{
    if (strsSize == 0)
        return NULL;

    int commonPrefixLength = strlen(strs[0]);
    for (int i = 1; i < strsSize; i++)
    {
        int p = 0;
        while (p < commonPrefixLength && strs[i][p] == strs[0][p]) ++p;
        commonPrefixLength = p;
    }

    strs[0][commonPrefixLength] = '\0';
    return strs[0];
}
</code>```

Live demo: https://godbolt.org/z/bebs7zz6j

Body:
I can't figure out this error.

Problem > Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".

char * longestCommonPrefix(char ** strs, int strsSize){
    int i = 1;
    int j = 0;
    int k = 1;
    int n = 0;

    if (strsSize == 0) return ("");
    if (strsSize == 1) return (strs[0]);
    if (strsSize > 1 && strcmp(strs[0],"") == 0) return ("");

    char *s = calloc(strlen(strs[0]), sizeof(char));
    char *temp = calloc(strlen(strs[0]), sizeof(char));
    if (!s || !temp) return (0);

    // while (strs[0][j] != '\0') {
    //     temp[j] = strs[0][j];
    //     j++;
    // }
    strcpy(temp, strs[0]);

    while (k < strsSize) {
        j = 0;
        n = 0;
        memset(s, 0, strlen(s));
        while (strs[i][j]){
            if (temp[j] == strs[i][j]) {
                s[n] = strs[i][j];
                n++;
            }
            else if (temp[j] != strs[i][j]){
                break;
            }
            j++;
        }
        strcpy(temp, s);
        k++;
        i++;
    }
    return (s);
}

It works without any problem on my visual studio but when I submit this code to Leetcode, it always has that error message. I assume error occurs on either line 7 or 8 because it dose not show same error when I hide those two line of codes. Also, when I copy strs[0] string to temp using while loop, it works fine on both Leetcode and visual studio but it does not work when I use "scrcpy" function on Leetcode but again, it works on my visual studio.

Another minor problem. The reason that I use calloc to allocate the memory is because It shows same error message "Address sani~" when using malloc. It does not matter on visual studio. Both calloc and malloc work ok.

I've added an extra memory for NULL terminator.

char *s = malloc((strlen(strs[0]) + 1) * sizeof(char));

It seems alright in my head but It has same memory issue.

I've tried many different ways but I still have issue with the way I use malloc and clear a string.

int len = strlen(strs[0]);
char *temp = malloc((len+1) * sizeof(char))
//it still gives me a memory error.

When I clear my string with memset, it returns a correct output but it does not return the right answer when I clear the string simply using NULL terminator. Is there a difference?

s[j] = '\0';
memset(s, 0, strlen(s));

Body:
The main difference between malloc and calloc is that malloc only reserves memory but doesn't modify its contents, whereas calloc reserves memory and zero-initializes every byte.

So, what's happening inside your loop where you begin copying string prefixes into s is you did this:

memset(s, 0, strlen(s));

Now, you thought that you just cleared the string, but at this point it's the first time you've done anything with s at all.  So if s was allocated with malloc then calling strlen(s) could do anything.  Very likely the uninitialized memory contents will not be a NUL-terminated string, and strlen will happily search past the end of that block of memory and into other parts of memory that your program did not request.

This is known as Undefined Behavior.

So, what can you do about it?  Well, in the comments you tried this:

s[0] = '\0';

Great!  But now every other byte of the string is not initialized.  You're about to loop over strs[i] and copy stuff into s.  The problem is that afterwards you never copied in a NUL-terminator, so once again you have an un-terminated string.  And, to be specific, the place where that terminator would have gone is still uninitialized.

As I already said very early on in comments, all you need to do is write that terminator after copying.  You don't really need two variables j and n because they're going to be the same value anyway.  Let's just use j.  It makes the code simpler.

j = 0;
while (strs[i][j] && temp[j] == strs[i][j])
{
    s[j] = strs[i][j];
    j++;
}
s[j] = '\0';

That's all.  You have a terminated string.  You didn't need to pre-initialize it, because you were about to overwrite that memory anyway.  The important part is the line after the loop.

Now, let's think a bit about what you're really trying to achieve here.

The task is to search all strings in the array and find the longest common prefix.  And looking at your code, not only is it doing too much work, it's actually not even achieving the required task.  Hint: you never used the variable k.

So why not take a step back and think about it differently?  Do you actually need to copy prefixes over and over?  No, you don't.  All you need to do is see how many characters they have in common.  And, you don't even need to check all the characters -- you only need to check up to whatever maximum count you've already found.

// Find longest common prefix
int commonPrefixLength = strlen(strs[0]);
for (int i = 1; i < strsSize; i++)
{
    int p = 0;
    while (p < commonPrefixLength && strs[i][p] == strs[0][p]) ++p;
    commonPrefixLength = p;
}

// Copy prefix to a new string
char *commonPrefix = malloc(commonPrefixLength + 1);
memcpy(commonPrefix, strs[0], commonPrefixLength);
commonPrefix[commonPrefixLength] = 0;

That's all you need to do.  You don't even need to check for the NUL terminator when searching the strings because you've already bounded the search by the longest prefix and it's guaranteed that if you encounter a NUL-terminator then it won't be equal to the character you're testing in strs[0].  Nice.

However we have another issue, and that is your function is not consistent about what it returns.  You wrote some special cases that might return strs[0] or a string literal "".  Otherwise it allocates new memory and returns that.  This is a problem, because the caller does not know whether it is supposed to free this memory or not.

So you should decide.  The options are:

Function either allocates or returns NULL -- caller always responsible for freeing memory.

Function never allocates -- returns NULL or modifies str[0] and returns that

If you choose 2, then instead of allocating and copying stuff after the loop, you'd just terminate the string.  However, you can only do this if input array was not string literals:

strs[0][commonPrefixLength] = '\0';

So the safest choice is probably option 1.  But here are both...

Option 1:

char * longestCommonPrefix(char ** strs, int strsSize)
{
    if (strsSize == 0)
        return NULL;

    int commonPrefixLength = strlen(strs[0]);
    for (int i = 1; i < strsSize; i++)
    {
        int p = 0;
        while (p < commonPrefixLength && strs[i][p] == strs[0][p]) ++p;
        commonPrefixLength = p;
    }

    char *commonPrefix = malloc(commonPrefixLength + 1);
    if (commonPrefix != NULL)
    {
        memcpy(commonPrefix, strs[0], commonPrefixLength);
        commonPrefix[commonPrefixLength] = 0;
    }
    return commonPrefix;
}

Option 2:

char * longestCommonPrefix(char ** strs, int strsSize)
{
    if (strsSize == 0)
        return NULL;

    int commonPrefixLength = strlen(strs[0]);
    for (int i = 1; i < strsSize; i++)
    {
        int p = 0;
        while (p < commonPrefixLength && strs[i][p] == strs[0][p]) ++p;
        commonPrefixLength = p;
    }

    strs[0][commonPrefixLength] = '\0';
    return strs[0];
}

Live demo: https://godbolt.org/z/bebs7zz6j


问:
Razor Page Trouble calling Post Method
I have a .cshtml file and it's .cs file. I am using Razor pages. I am using Dropzone for uploading a file.  The action in the form doesn't hit the method in the .cs page.  I cannot figure out why the code in the .cs file is not hit.  I used break points and it never appears to ever get to c# code.
Can anyone see what I am doing wrong?</p>
```<code>-----------
@page
@model SipiARPortal.Pages.SystemAdmin.AdminUsersModel
@inject IVendor _vendor
@{
ViewData["Title"] = "Admin File Upload";
ViewData["Header"] = new PageHeader()
{
    Title = "ADMIN FILE UPLOAD",
    SubTitle = "Upload Files here",
    Breadcrumbs = new List<Breadcrumb>() {
        new Breadcrumb() { Name = "Admin File Uplaod", URL = "/systemadmin/adminfileupload" }
    }
  };
 }
<link href="~/css/dropzone.css" rel="stylesheet" />
<div class="card shadow-sm mb-5">
<div class="card-body">
    <div class="row">
        <form action="/systemadmin/adminfileupload" method="post"
             class="dropzone" enctype="multipart/form-data"
              id="my-dropzone">
        </form>
    </div>
    <div class="row mg-t-5">
        <div id="verification" class="col-12"></div>
    </div>
    </div>
    </div>
   @section Scripts {
   <script src="~/lib/dropzone/dropzone.js"></script>
<script type="text/javascript">
    var gridObj = null;
    Dropzone.options.myDropzone = {
        createImageThumbnails: false,
        acceptedFiles:'',
        allowedExtensions: '.pdf,.zip',
        dictDefaultMessage: 'Drop results file here for verification',
        init: function () {
            this.on("success", function (file, data) {
                magalert.ajaxMessage(data);
                if (data.success) {
                    if (gridObj !== null) {
                        $("#Grid").ejGrid("destroy");
                    }
                    gridObj = $("#verification").ejGrid({
                        dataSource: data.data,
                        allowPaging: true,
                        allowSorting: true,
                        isResponsive: true,
                        allowFiltering: true,
                        enableHeaderHover: true,
                        filterSettings: { filterType: "excel" },
                        columns: [
                            { field: "filename", headerText: "FileName", width: 275 },

                        ]
                    });
                    var target = $('#verification');
                    if (target.length) {
                        $('html,body').animate({
                            scrollTop: target.offset().top
                        }, 1000);
                    }
                }
                e
            });
        }
    };

</script>
}

---------
namespace SipiARPortal.Pages.SystemAdmin
{
[Authorize(Roles = "SystemAdmin,SipiAdmin")]
public class AdminFileUploadsModel : PageModel
{
    private readonly ILogger<AdminUsersModel> _logger;
    private readonly UserManager<ApplicationUser> _userManager;
    public readonly IAzureBlob _blob;
    private readonly ApplicationDbContext _db;
    private readonly ConfigurationDbContext _cdb;

    public async Task OnPostAsync(IFormFile UploadFiles)
    {
        await _blob.SaveFileStream(UploadFiles.OpenReadStream(), "pending", UploadFiles.FileName);

    }
    [HttpPost]
    public async Task<IActionResult> ResultsUpload(IFormFile UploadFiles)
    {

        ServiceResult<List<ResultIssue>> retVal = new ServiceResult<List<ResultIssue>>() { Data = new List<ResultIssue>(), Success = true };
        try
        {
            await _blob.SaveFileStream(UploadFiles.OpenReadStream(), "pending", UploadFiles.FileName);
            //var blobStream = await _blob.GetFileStream(blob, sigFileName);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Results Upload");
            retVal.Message = "Error parsing results file - did you select the correct format?";
            retVal.Success = false;
        }
        return new JsonResult(retVal);
    }

}

}
</code>```

答:
The request url should be /systemadmin/adminfileuploads, you miss an s.

Anti-forgery token validation is enabled by default in Razor Pages. You need manually add it by using @Html.AntiForgeryToken() in the form.

```<code><form action="/systemadmin/adminfileuploads" method="post"
     class="dropzone" enctype="multipart/form-data"
     id="my-dropzone">
     @Html.AntiForgeryToken()
</form>
</code>```

Title: Razor Page Trouble calling Post Method

Body:
I have a .cshtml file and it's .cs file. I am using Razor pages. I am using Dropzone for uploading a file.  The action in the form doesn't hit the method in the .cs page.  I cannot figure out why the code in the .cs file is not hit.  I used break points and it never appears to ever get to c# code.
Can anyone see what I am doing wrong?

-----------
@page
@model SipiARPortal.Pages.SystemAdmin.AdminUsersModel
@inject IVendor _vendor
@{
ViewData["Title"] = "Admin File Upload";
ViewData["Header"] = new PageHeader()
{
    Title = "ADMIN FILE UPLOAD",
    SubTitle = "Upload Files here",
    Breadcrumbs = new List<Breadcrumb>() {
        new Breadcrumb() { Name = "Admin File Uplaod", URL = "/systemadmin/adminfileupload" }
    }
  };
 }
<link href="~/css/dropzone.css" rel="stylesheet" />

        <form action="/systemadmin/adminfileupload" method="post"
             class="dropzone" enctype="multipart/form-data"
              id="my-dropzone">
        </form>

   @section Scripts {

}

---------
namespace SipiARPortal.Pages.SystemAdmin
{
[Authorize(Roles = "SystemAdmin,SipiAdmin")]
public class AdminFileUploadsModel : PageModel
{
    private readonly ILogger<AdminUsersModel> _logger;
    private readonly UserManager<ApplicationUser> _userManager;
    public readonly IAzureBlob _blob;
    private readonly ApplicationDbContext _db;
    private readonly ConfigurationDbContext _cdb;

    public async Task OnPostAsync(IFormFile UploadFiles)
    {
        await _blob.SaveFileStream(UploadFiles.OpenReadStream(), "pending", UploadFiles.FileName);

    }
    [HttpPost]
    public async Task<IActionResult> ResultsUpload(IFormFile UploadFiles)
    {

        ServiceResult<List<ResultIssue>> retVal = new ServiceResult<List<ResultIssue>>() { Data = new List<ResultIssue>(), Success = true };
        try
        {
            await _blob.SaveFileStream(UploadFiles.OpenReadStream(), "pending", UploadFiles.FileName);
            //var blobStream = await _blob.GetFileStream(blob, sigFileName);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Results Upload");
            retVal.Message = "Error parsing results file - did you select the correct format?";
            retVal.Success = false;
        }
        return new JsonResult(retVal);
    }

}

}

Body:
The request url should be /systemadmin/adminfileuploads, you miss an s.

Anti-forgery token validation is enabled by default in Razor Pages. You need manually add it by using @Html.AntiForgeryToken() in the form.

<form action="/systemadmin/adminfileuploads" method="post"
     class="dropzone" enctype="multipart/form-data"
     id="my-dropzone">
     @Html.AntiForgeryToken()
</form>


问:
Does a contract instance created via interfaces have the same address as the original deployed contract?
I have been following Solidity, Blockchain, and Smart Contract Course – Beginner to Expert Python Tutorial (https://www.youtube.com/watch?v=M576WGiDBdQ&t=28658s). instead of copying a ton of code, I'm trying to generalize my question as follows:

consider the following code snippet:

```<code>weth=interface.IWeth(SomeAddress)
tx=weth.deposit({"from":account, "value": 0.01*10**18})
</code>```

I understand that interface.IWeth(SomeAddress) tells Ethereum virtual machine to create an instance of the contract at SomeAddress ( which I will call SomeContract) with the functionalities of the interface.

I would like to confirm the following:

Does weth and SomeContract share the same address?

will the following state changes have the same outcome?

```<code>weth.deposit({"from":account, "value": 0.01*10**18})
</code>```

and

```<code>SomeContract.deposit({"from":account, "value": 0.01*10**18})
</code>```

答:
Let's say you have contractB and contractA. Inside contractB you want to interact with contractA but you do not know the code of contractA. All you know is interface and address of the contractA. In this case, you interact with contractA inside contractB via the interface, and any change you make to contractA will be reflected inside contractA in blockchain.

In your question when you call weth.deposit you are actually modifying the state of contract at given address.

You could test this easily on Remix.

Let's say you have contractA and interface of it:

    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;

    interface InterfaceA {
        function count() external view returns (uint256);
        function increment() external;
    }

    contract contractA {
        uint256 number = 0;

       function count() external view returns (uint256) {
          return number;
       }

       function increment() external {
          number++ ;
       }
    }
```
<p>You compile it and then deploy it. (Make sure when you deploy it, select the contractA not interfaceA). Get the address of deployment. Then create contractB:</p>
<pre class="lang-js prettyprint-override"><code>    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;

    import './contractA.sol' ;

    contract contractB {
        address addressA;
        constructor (address _addressA) {
              addressA = _addressA;
        }

        function getCount() external view returns (uint256) {
             InterfaceA b = InterfaceA(addressA);
             return b.count();
        }

        function addToIncrement() external {
             InterfaceA b = InterfaceA(addressA);
             b.increment();
        }
    }
</code>```

Now when you deploy this, since I wrote a constructor with an argument, you need to pass the address of cotractA. Then call addToIncrement() of contractB. This will call the increment function of contractA. Now go to contractA and call count and you will get updated value.

Body:
I have been following Solidity, Blockchain, and Smart Contract Course – Beginner to Expert Python Tutorial (https://www.youtube.com/watch?v=M576WGiDBdQ&t=28658s). instead of copying a ton of code, I'm trying to generalize my question as follows:

consider the following code snippet:

weth=interface.IWeth(SomeAddress)
tx=weth.deposit({"from":account, "value": 0.01*10**18})

I understand that interface.IWeth(SomeAddress) tells Ethereum virtual machine to create an instance of the contract at SomeAddress ( which I will call SomeContract) with the functionalities of the interface.

I would like to confirm the following:

Does weth and SomeContract share the same address?

will the following state changes have the same outcome?

weth.deposit({"from":account, "value": 0.01*10**18})

and

SomeContract.deposit({"from":account, "value": 0.01*10**18})

Body:
Let's say you have contractB and contractA. Inside contractB you want to interact with contractA but you do not know the code of contractA. All you know is interface and address of the contractA. In this case, you interact with contractA inside contractB via the interface, and any change you make to contractA will be reflected inside contractA in blockchain.

In your question when you call weth.deposit you are actually modifying the state of contract at given address.

You could test this easily on Remix.

Let's say you have contractA and interface of it:

    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;

    interface InterfaceA {
        function count() external view returns (uint256);
        function increment() external;
    }

    contract contractA {
        uint256 number = 0;

       function count() external view returns (uint256) {
          return number;
       }

       function increment() external {
          number++ ;
       }
    }

You compile it and then deploy it. (Make sure when you deploy it, select the contractA not interfaceA). Get the address of deployment. Then create contractB:

    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;

    import './contractA.sol' ;

    contract contractB {
        address addressA;
        constructor (address _addressA) {
              addressA = _addressA;
        }

        function getCount() external view returns (uint256) {
             InterfaceA b = InterfaceA(addressA);
             return b.count();
        }

        function addToIncrement() external {
             InterfaceA b = InterfaceA(addressA);
             b.increment();
        }
    }

Now when you deploy this, since I wrote a constructor with an argument, you need to pass the address of cotractA. Then call addToIncrement() of contractB. This will call the increment function of contractA. Now go to contractA and call count and you will get updated value.


问:
Extract row corresponding to minimum value of a variable by group
I wish to (1) group data by one variable (State), (2) within each group find the row of minimum value of another variable (Employees), and (3) extract the entire row.

(1) and (2) are easy one-liners, and I feel like (3) should be too, but I can't get it.

Here is a sample data set:

```<code>> data
  State Company Employees
1    AK       A        82
2    AK       B       104
3    AK       C        37
4    AK       D        24
5    RI       E        19
6    RI       F       118
7    RI       G        88
8    RI       H        42

data <- structure(list(State = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
        2L), .Label = c("AK", "RI"), class = "factor"), Company = structure(1:8, .Label = c("A",
        "B", "C", "D", "E", "F", "G", "H"), class = "factor"), Employees = c(82L,
        104L, 37L, 24L, 19L, 118L, 88L, 42L)), .Names = c("State", "Company",
        "Employees"), class = "data.frame", row.names = c(NA, -8L))
</code>```

Calculate min by group is easy, using aggregate:

```<code>> aggregate(Employees ~ State, data, function(x) min(x))
  State Employees
1    AK        24
2    RI        19
</code>```

...or data.table:

```<code>> library(data.table)
> DT <- data.table(data)
> DT[ , list(Employees = min(Employees)), by = State]
   State Employees
1:    AK        24
2:    RI        19
</code>```

But how do I extract the entire row corresponding to these min values, i.e. also including Company in the result?

答:
Another data.table solution:

```<code>DT[, E_min := min(Employees), by = State][Employees == E_min]
</code>```

Pretty straightforward and among the fastest. Below I rerun David Arenburg's benchmarking with this and the other fastest data.table solutions.

```<code>library(data.table)
library(microbenchmark)

set.seed(123)
N <- 1e6
data <- data.frame(State = stri_rand_strings(N, 2, '[A-Z]'),
                   Employees = sample(N * 10, N, replace = TRUE))
DT <- copy(data)
setDT(DT)
DT2 <- copy(DT)
DT3 <- copy(DT)

microbenchmark(
    "(data.table) min column: " = DT3[, E_min := min(Employees), by = State][Employees == E_min],
    "(data.table) .I[which.min]: " = DT[DT[, .I[which.min(Employees)], by = State]$V1],
    "(data.table) order/unique: " = unique(DT[order(Employees)], by = "State"),
    "(data.table) self join (setkey):" = {
        tmp <- DT2[, .(Employees = min(Employees)), by = State]
        setkey(tmp, State, Employees)
        setkey(DT2, State, Employees)
        DT2[tmp, mult = "first"]
    }
)

                             expr      min       lq      mean   median        uq      max neval
        (data.table) min column:  44.30078 52.17932  68.31826 58.65887  76.89786 184.0207   100
     (data.table) .I[which.min]:  20.34116 26.31244  39.36874 34.01958  42.65439 124.9204   100
      (data.table) order/unique:  70.07820 80.20577 109.71235 95.25586 114.87695 514.4456   100
 (data.table) self join (setkey): 13.48105 16.06614  22.58310 17.35083  22.31206 161.9103   100
</code>```

This solution is most useful if you want just a few columns returned among many, e.g. [Employees == E_min, ..columns_to_keep], in which case it can be even faster.

Body:
I wish to (1) group data by one variable (State), (2) within each group find the row of minimum value of another variable (Employees), and (3) extract the entire row.

(1) and (2) are easy one-liners, and I feel like (3) should be too, but I can't get it.

Here is a sample data set:

> data
  State Company Employees
1    AK       A        82
2    AK       B       104
3    AK       C        37
4    AK       D        24
5    RI       E        19
6    RI       F       118
7    RI       G        88
8    RI       H        42

data <- structure(list(State = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
        2L), .Label = c("AK", "RI"), class = "factor"), Company = structure(1:8, .Label = c("A",
        "B", "C", "D", "E", "F", "G", "H"), class = "factor"), Employees = c(82L,
        104L, 37L, 24L, 19L, 118L, 88L, 42L)), .Names = c("State", "Company",
        "Employees"), class = "data.frame", row.names = c(NA, -8L))

Calculate min by group is easy, using aggregate:

> aggregate(Employees ~ State, data, function(x) min(x))
  State Employees
1    AK        24
2    RI        19

...or data.table:

> library(data.table)
> DT <- data.table(data)
> DT[ , list(Employees = min(Employees)), by = State]
   State Employees
1:    AK        24
2:    RI        19

But how do I extract the entire row corresponding to these min values, i.e. also including Company in the result?

Body:
Another data.table solution:

DT[, E_min := min(Employees), by = State][Employees == E_min]

Pretty straightforward and among the fastest. Below I rerun David Arenburg's benchmarking with this and the other fastest data.table solutions.

library(data.table)
library(microbenchmark)

set.seed(123)
N <- 1e6
data <- data.frame(State = stri_rand_strings(N, 2, '[A-Z]'),
                   Employees = sample(N * 10, N, replace = TRUE))
DT <- copy(data)
setDT(DT)
DT2 <- copy(DT)
DT3 <- copy(DT)

microbenchmark(
    "(data.table) min column: " = DT3[, E_min := min(Employees), by = State][Employees == E_min],
    "(data.table) .I[which.min]: " = DT[DT[, .I[which.min(Employees)], by = State]$V1],
    "(data.table) order/unique: " = unique(DT[order(Employees)], by = "State"),
    "(data.table) self join (setkey):" = {
        tmp <- DT2[, .(Employees = min(Employees)), by = State]
        setkey(tmp, State, Employees)
        setkey(DT2, State, Employees)
        DT2[tmp, mult = "first"]
    }
)

                             expr      min       lq      mean   median        uq      max neval
        (data.table) min column:  44.30078 52.17932  68.31826 58.65887  76.89786 184.0207   100
     (data.table) .I[which.min]:  20.34116 26.31244  39.36874 34.01958  42.65439 124.9204   100
      (data.table) order/unique:  70.07820 80.20577 109.71235 95.25586 114.87695 514.4456   100
 (data.table) self join (setkey): 13.48105 16.06614  22.58310 17.35083  22.31206 161.9103   100

This solution is most useful if you want just a few columns returned among many, e.g. [Employees == E_min, ..columns_to_keep], in which case it can be even faster.


问:
Blazemeter Taurus Increment variable
I would like to perform a PUT test with BZT, but its not clear how to use a dynamic variable, for example a count function where I am using the execution number as the variable when making a put to a database.</p>

答:
Taurus is only a wrapper performing configuration, launching and results processing of the underlying Executor.

So you need to refer to the particular Executor documentation to learn how to implement the "counter" there.

Taurus default executor is JMeter which means that the "requests" you specify declaratively in YAML are translated into JMeter .jmx test plan

So the most straightforward solution would be using JMeter's __counter() function where required so if you put the function call like ${__counter(,)} into your script - it will generate an incremented number each time it will be called.

More information: How to Use a Counter in a JMeter Test

Title: Blazemeter Taurus Increment variable


问:
.NET MVC Shopping Cart
What .NET MVC3 (or MVC) shopping cart software is available (open source or commercial)? Preferably with existing payment gateways. I'm only aware of MvcMusicStore. Are there any others?</p>

答: Nopcommerce has been upgraded to ASP .NET MVC3 and is very feature rich.</p>

Title: .NET MVC Shopping Cart


问:
Read spark csv dataframe as pandas
After processing a big data on pyspark, I saved it on csv using the following command:

```<code>df.repartition(1).write.option("header", "true").option("delimeter", "\t").csv("csv_data", mode="overwrite")
</code>```

Now, I want use pd.read_csv() to load it again.

```<code>info = pd.read_csv('part0000.csv', sep='\t', header='infer')
</code>```

info is returned as 1 column where the data is separated by comma not '\t'.

```<code>col1name,col2name,col3name
val1,val2,val3
</code>```

I tried to specify the sep=',' but I got an parsing error where some rows have more than 3 cols.

How to fix that without skipping any rows ? Is there anything to do with spark to resolve it such as specify a '|' as delimiter

答:
The csv format writer method DOESN'T have the delimeter option, guess what you need is the sep option.

Please refer to here

Title: Read spark csv dataframe as pandas

Body:
After processing a big data on pyspark, I saved it on csv using the following command:

df.repartition(1).write.option("header", "true").option("delimeter", "\t").csv("csv_data", mode="overwrite")

Now, I want use pd.read_csv() to load it again.

info = pd.read_csv('part0000.csv', sep='\t', header='infer')

info is returned as 1 column where the data is separated by comma not '\t'.

col1name,col2name,col3name
val1,val2,val3

I tried to specify the sep=',' but I got an parsing error where some rows have more than 3 cols.

How to fix that without skipping any rows ? Is there anything to do with spark to resolve it such as specify a '|' as delimiter


问:
Evaluate an expression stored in variable in jmeter using beanshell
I've pulled an expression from SQL db and that expression is stored as String in jmeter beanshell assertion.
Now I would like to use that expression to evaluate different values

String LeftTank_conv = vars.get("Conv_formula_5") + ""; LeftTank_conv = "{x*100*245/345;}"(something like this)
how can I use this string as an expression to evaluate for different x values

TIA

答:
If you really need the possibility to evaluate arbitrary arithmetic formulae you could use JEXL engine which is being used in JMeter's __jexl3() function

Since JMeter 3.1 it's recommended to use Groovy for scripting so I'll provide the example solution using Groovy syntax:

```<code>def context = new org.apache.commons.jexl3.MapContext()
context.set('x', 1)

def engine = new org.apache.commons.jexl3.JexlBuilder().create()
def e = engine.createExpression(vars.get('Conv_formula_5'))

def result = e.evaluate(context)

log.info('Execution result: ' + result as String)
</code>```

Demo:

Body:
If you really need the possibility to evaluate arbitrary arithmetic formulae you could use JEXL engine which is being used in JMeter's __jexl3() function

Since JMeter 3.1 it's recommended to use Groovy for scripting so I'll provide the example solution using Groovy syntax:

def context = new org.apache.commons.jexl3.MapContext()
context.set('x', 1)

def engine = new org.apache.commons.jexl3.JexlBuilder().create()
def e = engine.createExpression(vars.get('Conv_formula_5'))

def result = e.evaluate(context)

log.info('Execution result: ' + result as String)

Demo:


问:
Laravel homestead 502 bad gateway
Everytime i go to my project I get a 502 bad gateway. When I refresh, the page works.. If I click a link to another page I get 502 bad gateway again. After the refresh the page loads. What could be the problem here.

Homestead.yaml

```<code>---
ip: "192.168.10.10"
memory: 2048
cpus: 1
provider: virtualbox

authorize: c:/Users/MyNameHere/.ssh/id_rsa.pub

keys:
    - c:/Users/MyNameHere/.ssh/id_rsa

folders:
    - map: c:/Users/MyNameHere/Desktop/sites
      to: /home/vagrant/code

sites:
    - map: spa.test
      to: /home/vagrant/code/spa/public

databases:
    - homestead
</code>```

Got the latest version for virtualbox and vagrant.

My spa folder contains the newest version laravel.

答:
For Chinese,
if you are using Clash for Windows,
then edit "Bypass Domain".

It's not relevant to this question,
but Google lead me here,

Title: Laravel homestead 502 bad gateway

Body:
Everytime i go to my project I get a 502 bad gateway. When I refresh, the page works.. If I click a link to another page I get 502 bad gateway again. After the refresh the page loads. What could be the problem here.

Homestead.yaml

---
ip: "192.168.10.10"
memory: 2048
cpus: 1
provider: virtualbox

authorize: c:/Users/MyNameHere/.ssh/id_rsa.pub

keys:
    - c:/Users/MyNameHere/.ssh/id_rsa

folders:
    - map: c:/Users/MyNameHere/Desktop/sites
      to: /home/vagrant/code

sites:
    - map: spa.test
      to: /home/vagrant/code/spa/public

databases:
    - homestead

Got the latest version for virtualbox and vagrant.

My spa folder contains the newest version laravel.


问:
How to open a file of any type of extension with Android's "open with" option?
I have been stuck on a problem for almost 1 week, so I allow myself to call on you.

I would like from an application that I am currently developing, to be able to open a file of any type of extension from the internal storage of the phone.

Example in picture:

If I click on an .mp3 file from my application that I am developing, Android would have to recognize the type and automatically suggest applications on my phone that can play the file:

"Ouvrir avec" means Open With

The same goes for the other types.

PDF:

JPG:

Do you have a solution to answer my problem?

I tried many attempts, my last was this:

```<code>    String path = "/storage/emulated/0/Download/Cours1.pdf";

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.parse("content://" + path), "application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    getApplicationContext().startActivity(intent);
</code>```

But my file does not open:

答:
You can do something like this:

First go to manifest file and write the following tag under the <application> tag

```<code><provider
  android:name="androidx.core.content.FileProvider"
  android:authorities="${applicationId}.provider"
  android:exported="false"
  android:grantUriPermissions="true">
  <meta-data
    android:name="android.support.FILE_PROVIDER_PATHS"
    android:resource="@xml/providerpaths" />
</provider>
</code>```

Then create a xml folder in res and create a file named: providerpaths.xml and then copy paste the code:

```<code><?xml version="1.0" encoding="utf-8"?>
  <paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
  name="external_files"
  path="." />
</paths>
</code>```

In java

```<code>private void openFile(Context context ,String filePath) {
  File file = new File(filePath);
  Uri uri =  FileProvider.getUriForFile(Objects.requireNonNull(context.getApplicationContext()),BuildConfig.APPLICATION_ID + ".provider",file);
   String mime = context.getContentResolver().getType(uri);
   Intent intent = new Intent();
   intent.setAction(Intent.ACTION_VIEW);
   intent.setDataAndType(uri, mime);
   intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
   intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   context.startActivity(intent);
}
</code>```

How to use

```<code>String path = "/storage/emulated/0/Download/Cours1.pdf";
  try {
    openFile(MainActivity.this ,path) ;
  }catch (Exception e){
    Toast.makeText(this, "Cannot open the file", Toast.LENGTH_SHORT).show();
}
</code>```

Body:
I have been stuck on a problem for almost 1 week, so I allow myself to call on you.

I would like from an application that I am currently developing, to be able to open a file of any type of extension from the internal storage of the phone.

Example in picture:

If I click on an .mp3 file from my application that I am developing, Android would have to recognize the type and automatically suggest applications on my phone that can play the file:

"Ouvrir avec" means Open With

The same goes for the other types.

PDF:

JPG:

Do you have a solution to answer my problem?

I tried many attempts, my last was this:

    String path = "/storage/emulated/0/Download/Cours1.pdf";

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.parse("content://" + path), "application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    getApplicationContext().startActivity(intent);

But my file does not open:

Body:
You can do something like this:

First go to manifest file and write the following tag under the <application> tag

<provider
  android:name="androidx.core.content.FileProvider"
  android:authorities="${applicationId}.provider"
  android:exported="false"
  android:grantUriPermissions="true">
  <meta-data
    android:name="android.support.FILE_PROVIDER_PATHS"
    android:resource="@xml/providerpaths" />
</provider>

Then create a xml folder in res and create a file named: providerpaths.xml and then copy paste the code:

<?xml version="1.0" encoding="utf-8"?>
  <paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
  name="external_files"
  path="." />
</paths>

In java

private void openFile(Context context ,String filePath) {
  File file = new File(filePath);
  Uri uri =  FileProvider.getUriForFile(Objects.requireNonNull(context.getApplicationContext()),BuildConfig.APPLICATION_ID + ".provider",file);
   String mime = context.getContentResolver().getType(uri);
   Intent intent = new Intent();
   intent.setAction(Intent.ACTION_VIEW);
   intent.setDataAndType(uri, mime);
   intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
   intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   context.startActivity(intent);
}

How to use

String path = "/storage/emulated/0/Download/Cours1.pdf";
  try {
    openFile(MainActivity.this ,path) ;
  }catch (Exception e){
    Toast.makeText(this, "Cannot open the file", Toast.LENGTH_SHORT).show();
}


问:
Convert large csv Blob to Pandas dataframe in App service
I work for a retail organization. We are developing a control tool which will retrieve transactional data and displays 3 sites which are performing closely similar to a test site which we have chosen based on a chosen parameter(example :sales). This is currently working fine when the code is developed in R Shiny, connected to the On Prem database and executed from personal laptops. The requirement is to host this tool on Azure so others can access it easily.

We will be rewriting this tool using python and are planning to retrieve the csv data (which we have already ingested) from a datalake gen1.

Panda dataframe can only be created from local files and not directly from storage. This means we have to download the csv from the datalake, convert it to a pandas dataframe and then execute our python algorithms. When the files are downloaded to local storage, this would occupy disk storage on the app service which is limited to 250GB. The files can be are fairly large (>5GB) and there can be multiple of them. We will also have multiple users accessing this tool. I would think that the disk storage will get filled up fairly quickly.

Is there any way to automatically clear of the temp storage at regular intervals automatically? Should this be managed in the code itself after each execution.

答:
First of all there is no such thing "Convert large csv Blob to Pandas dataframe".

Python Pandas module allows us to read any CSV file, transform the data and save it at any desired location.

What you are asking can be achieved using Azure Function.

Refer this SO thread to create a Azure function and read a blob file using it.

Use the below code to read that file using Pandas:

```<code># Import pandas
import pandas as pd

# reading csv file
dataframe = pd.read_csv(<variable_in_which_you_read_the_CSV_file>)
</code>```

Do the required transformation on this dataframe and upload the file to Azure Storage.

Refer Upload blobs to a container given code sample for uploading part.

Body:
First of all there is no such thing "Convert large csv Blob to Pandas dataframe".

Python Pandas module allows us to read any CSV file, transform the data and save it at any desired location.

What you are asking can be achieved using Azure Function.

Refer this SO thread to create a Azure function and read a blob file using it.

Use the below code to read that file using Pandas:

# Import pandas
import pandas as pd

# reading csv file
dataframe = pd.read_csv(<variable_in_which_you_read_the_CSV_file>)

Do the required transformation on this dataframe and upload the file to Azure Storage.

Refer Upload blobs to a container given code sample for uploading part.


答:
The ref keyword indicates that a parameter is passed by reference.

In the code you posted, it's perfectly useless, because the method doesn't change the value of the parameter (changing properties of the parameter doesn't require passing it by reference, at least not if it is a reference type)

Title: What does the keyword ref mean in C#?


问:
Regex Extraction - Match before a space, or NOT before a space
Here are my potential inputs:

brian@muck.co, brian@gmail.com

brian@gmail.com, brian@muck.co

What I want to do is extract the @muck.co email address.

What I have tried is:
\s.*@muck.co

The problem is that this only grabs an email address if it is preceded by a space (so it would only match the second example input above). . . How would I write a Regex expression to match either inputs?

答:
\s matches for a space, so you should wanted to use something like [^\s]*@muck.co - this means any number of not space caracters. [] - for a set of symbols, ^ - for negate effect.

It does not work for me, because \s in my regex flavour seems to not contain regular space, but this works [^[:space:]]\+@muck\.co. Also \+ instead of * for one or more non-space characters instead of any number and escape dot \. which unescaped stands for any single character.


问:
hide labels and 0 values in chart.js?
I am beginner on this Chart.js and wanna ask,  How can I hide the labels and 0 values in the bar Chart. I cannot just hide the whole Dataset since I am using a SQL Table to get the Values "into" Chart.Js. I just want the bar chart show only if the labels have the value. Need your help

sample chart

```<code>{
    {
        $.post("datachartasr.php",
        function (data)
        {
            console.log(data);
            var intake = [];
            var active = [];
            var inactive = [];
            var deffered = [];
            var widthdrawn = [];
            var dis_ter_dereg = [];
            var missing = [];
            for (var i in data) {
                intake.push(data[i].intake);
                active.push(data[i].active);
                inactive.push(data[i].inactive);
                deffered.push(data[i].deffered);
                widthdrawn.push(data[i].widthdrawn);
                dis_ter_dereg.push(data[i].dis_ter_dereg);
                missing.push(data[i].missing);
            }
            var chartdata = {
                labels: intake,
                datasets: [
                    {
                        label: 'Active Status',
                        backgroundColor: '#1E90FF',
                        borderColor: '#1E90FF',
                        hoverBackgroundColor: '#1E90FF',
                        hoverBorderColor: '#666666',
                        data: active
                    },
                    {
                        label: 'Deferred Status',
                        backgroundColor: '#708090',
                        borderColor: '#708090',
                        hoverBackgroundColor: '#708090',
                        hoverBorderColor: '#666666',
                        data: deffered
                    },

.....
.....
.....

                ]
            };
            var graphTarget = $("#graphCanvas");
            var barGraph = new Chart(graphTarget, {
                type: 'bar',
                data: chartdata,
            });
        });
    }
}
</code>```

答:
You can have the below function inside data labels to hide the Zero value:

```<code>options: {
  plugins: {
    datalabels: {
       display: function(context) {
          return context.dataset.data[context.dataIndex] !== 0; // or >= 1 or ...
       }
    }
  }
}
</code>```

See more on this issue here https://github.com/chartjs/chartjs-plugin-datalabels/issues/6

Title: hide labels and 0 values in chart.js?

Body:
I am beginner on this Chart.js and wanna ask,  How can I hide the labels and 0 values in the bar Chart. I cannot just hide the whole Dataset since I am using a SQL Table to get the Values "into" Chart.Js. I just want the bar chart show only if the labels have the value. Need your help

sample chart

{
    {
        $.post("datachartasr.php",
        function (data)
        {
            console.log(data);
            var intake = [];
            var active = [];
            var inactive = [];
            var deffered = [];
            var widthdrawn = [];
            var dis_ter_dereg = [];
            var missing = [];
            for (var i in data) {
                intake.push(data[i].intake);
                active.push(data[i].active);
                inactive.push(data[i].inactive);
                deffered.push(data[i].deffered);
                widthdrawn.push(data[i].widthdrawn);
                dis_ter_dereg.push(data[i].dis_ter_dereg);
                missing.push(data[i].missing);
            }
            var chartdata = {
                labels: intake,
                datasets: [
                    {
                        label: 'Active Status',
                        backgroundColor: '#1E90FF',
                        borderColor: '#1E90FF',
                        hoverBackgroundColor: '#1E90FF',
                        hoverBorderColor: '#666666',
                        data: active
                    },
                    {
                        label: 'Deferred Status',
                        backgroundColor: '#708090',
                        borderColor: '#708090',
                        hoverBackgroundColor: '#708090',
                        hoverBorderColor: '#666666',
                        data: deffered
                    },

.....
.....
.....

                ]
            };
            var graphTarget = $("#graphCanvas");
            var barGraph = new Chart(graphTarget, {
                type: 'bar',
                data: chartdata,
            });
        });
    }
}

Body:
You can have the below function inside data labels to hide the Zero value:

options: {
  plugins: {
    datalabels: {
       display: function(context) {
          return context.dataset.data[context.dataIndex] !== 0; // or >= 1 or ...
       }
    }
  }
}

See more on this issue here https://github.com/chartjs/chartjs-plugin-datalabels/issues/6


问:
Material-UI's Tabs integration with react router 4?
The new react-router syntax uses the Link component to move around the routes. But how could this be integrated with material-ui?

In my case, I'm using tabs as the main navigation system, So in theory I should have something like this:

const TabLink = ({ onClick, href, isActive, label }) =>
  <Tab
    label={label}
    onActive={onClick}
  />

export default class NavBar extends React.Component {
  render () {
    return (
      <Tabs>
        <Link to="/">{params => <TabLink label="Home" {...params}/>}</Link>
        <Link to="/shop">{params => <TabLink label="shop" {...params}/>}</Link>
        <Link to="/gallery">{params => <TabLink label="gallery" {...params}/>}</Link>
      </Tabs>
    )
  }
}
```

But when it renders, material-ui throws an error that the child of Tabs must be a Tab component. What could be the way to proceed? How do I manage the isActive prop for the tab?

Thanks in advance

答:
I solved this in a much easier fashion (I was surprised this worked so well - maybe there's a problem I haven't found out). I'm using Router 6 and React 17 (I know these packages are newer).
In any case, I just used the useNavigate hook in the handleChange function. Thus, now there is NO need for Switch and the code becomes much simpler. See below:

```<code>let navigate = useNavigate();
const [selection, setSelection] = useState();

const handleChange = (event, newValue) => {
    setSelection(newValue);
    navigate(`${newValue}`);
}

return (
    <Tabs value={selection} onChange={handleChange}>
         <Tab label="Products" value="products"  />
         <Tab label="Customers" value="customers" />
         <Tab label="Invoices" value="invoices" />
    </Tabs>
  );
}
</code>```

The handleChange function updates 'selection' which controls the display of the tabs, and also navigates to the right path.
if you set the  component somewhere in your React space, and set correctly a :style route (as explained by React Router: https://reactrouter.com/docs/en/v6/getting-started/overview), you can also control in which area of the page will the content be rendered. Hope it helps somebody!

Body:
The new react-router syntax uses the Link component to move around the routes. But how could this be integrated with material-ui?

In my case, I'm using tabs as the main navigation system, So in theory I should have something like this:

const TabLink = ({ onClick, href, isActive, label }) =>
  <Tab
    label={label}
    onActive={onClick}
  />

export default class NavBar extends React.Component {
  render () {
    return (
      <Tabs>
        <Link to="/">{params => <TabLink label="Home" {...params}/>}</Link>
        <Link to="/shop">{params => <TabLink label="shop" {...params}/>}</Link>
        <Link to="/gallery">{params => <TabLink label="gallery" {...params}/>}</Link>
      </Tabs>
    )
  }
}

But when it renders, material-ui throws an error that the child of Tabs must be a Tab component. What could be the way to proceed? How do I manage the isActive prop for the tab?

Thanks in advance

Body:
I solved this in a much easier fashion (I was surprised this worked so well - maybe there's a problem I haven't found out). I'm using Router 6 and React 17 (I know these packages are newer).
In any case, I just used the useNavigate hook in the handleChange function. Thus, now there is NO need for Switch and the code becomes much simpler. See below:

let navigate = useNavigate();
const [selection, setSelection] = useState();

const handleChange = (event, newValue) => {
    setSelection(newValue);
    navigate(`${newValue}`);
}

return (
    <Tabs value={selection} onChange={handleChange}>
         <Tab label="Products" value="products"  />
         <Tab label="Customers" value="customers" />
         <Tab label="Invoices" value="invoices" />
    </Tabs>
  );
}

The handleChange function updates 'selection' which controls the display of the tabs, and also navigates to the right path.
if you set the  component somewhere in your React space, and set correctly a :style route (as explained by React Router: https://reactrouter.com/docs/en/v6/getting-started/overview), you can also control in which area of the page will the content be rendered. Hope it helps somebody!


问:
How can use elements "getElementById("site") and getElementById("button")" more than one for lists?
I tried to use more than one "List" with changing names of getElementById("site") and getElementById("button") but it dosent work well.

The "submit" button dosnt work correctly
I want each button do separately and open link from own list.

This example for 3 list, but I have more than 10 lists with same name but different addresses.

HTML code:

```<code><html>

<body>
    <form method="get">
        <label for="Links">Choose a Site:</label>
        <select id="site01" name="site">
            <option value="Google">Google</option>
            <option value="Yahoo">Yahoo</option>
            <option value="MSN">MSN</option>
        </select>
    </form>
    <button type="button" id="button01">Submit</button>
    <script src="script1.js"></script>
    <form method="get">
        <label for="Links">Choose a Site:</label>
        <select id="site02" name="site">
            <option value="Google">Google</option>
            <option value="Yahoo">Yahoo</option>
            <option value="MSN">MSN</option>
        </select>
    </form>
    <button type="button" id="button02">Submit</button>
    <script src="script1.js"></script>
    <form method="get">
        <label for="Links">Choose a Site:</label>
        <select id="site03" name="site">
            <option value="Google">Google</option>
            <option value="Yahoo">Yahoo</option>
            <option value="MSN">MSN</option>
        </select>
    </form>
    <button type="button" id="button03">Submit</button>
    <script src="script1.js"></script>
</body>

</html>
</code>```

script1.js code

```<code>var select = document.getElementById('site01');

document.getElementById("button01").onclick = function(){
    var value = select.value
    if (value == "Google")
    {
        window.open('https://www.google01.com', '_blank');
    }
    else if (value == "Yahoo")
    {
        window.open('https://www.yahoo01.com', '_blank');
    }
    else if (value == "MSN")
    {
        window.open('https://www.msn01.com', '_blank');
    }
};

var select = document.getElementById('site02');

document.getElementById("button02").onclick = function(){
    var value = select.value
    if (value == "Google")
    {
        window.open('https://www.google02.com', '_blank');
    }
    else if (value == "Yahoo")
    {
        window.open('https://www.yahoo02.com', '_blank');
    }
    else if (value == "MSN")
    {
        window.open('https://www.msn02.com', '_blank');
    }
};

var select = document.getElementById('site03');

document.getElementById("button03").onclick = function(){
    var value = select.value
    if (value == "Google")
    {
        window.open('https://www.google03.com', '_blank');
    }
    else if (value == "Yahoo")
    {
        window.open('https://www.yahoo03.com', '_blank');
    }
    else if (value == "MSN")
    {
        window.open('https://www.msn03.com', '_blank');
    }
};
</code>```

whats wrong ?

答:
When change select option, you didn't store changed value that's why always you show first loaded data that's why its not working exactly.

Please check following codes and run it in your environmnet.

```<code>var selectValue = document.getElementById('site01').value;

document.getElementById('site01').addEventListener('change', function() {
  selectValue = this.value;
});

document.getElementById("button01").onclick = function(){
    if (selectValue == "Google")
    {
        window.open('https://www.google01.com', '_blank');
    }
    else if (selectValue == "Yahoo")
    {
        window.open('https://www.yahoo01.com', '_blank');
    }
    else if (selectValue == "MSN")
    {
        window.open('https://www.msn01.com', '_blank');
    }
};

</code>```

Hopefully, now it'll be worked, thank you.

Body:
I tried to use more than one "List" with changing names of getElementById("site") and getElementById("button") but it dosent work well.

The "submit" button dosnt work correctly
I want each button do separately and open link from own list.

This example for 3 list, but I have more than 10 lists with same name but different addresses.

HTML code:

    <form method="get">
        Choose a Site:
        <select id="site01" name="site">
            <option value="Google">Google</option>
            <option value="Yahoo">Yahoo</option>
            <option value="MSN">MSN</option>
        </select>
    </form>
    <button type="button" id="button01">Submit</button>

    <form method="get">
        Choose a Site:
        <select id="site02" name="site">
            <option value="Google">Google</option>
            <option value="Yahoo">Yahoo</option>
            <option value="MSN">MSN</option>
        </select>
    </form>
    <button type="button" id="button02">Submit</button>

    <form method="get">
        Choose a Site:
        <select id="site03" name="site">
            <option value="Google">Google</option>
            <option value="Yahoo">Yahoo</option>
            <option value="MSN">MSN</option>
        </select>
    </form>
    <button type="button" id="button03">Submit</button>

script1.js code

var select = document.getElementById('site01');

document.getElementById("button01").onclick = function(){
    var value = select.value
    if (value == "Google")
    {
        window.open('https://www.google01.com', '_blank');
    }
    else if (value == "Yahoo")
    {
        window.open('https://www.yahoo01.com', '_blank');
    }
    else if (value == "MSN")
    {
        window.open('https://www.msn01.com', '_blank');
    }
};

var select = document.getElementById('site02');

document.getElementById("button02").onclick = function(){
    var value = select.value
    if (value == "Google")
    {
        window.open('https://www.google02.com', '_blank');
    }
    else if (value == "Yahoo")
    {
        window.open('https://www.yahoo02.com', '_blank');
    }
    else if (value == "MSN")
    {
        window.open('https://www.msn02.com', '_blank');
    }
};

var select = document.getElementById('site03');

document.getElementById("button03").onclick = function(){
    var value = select.value
    if (value == "Google")
    {
        window.open('https://www.google03.com', '_blank');
    }
    else if (value == "Yahoo")
    {
        window.open('https://www.yahoo03.com', '_blank');
    }
    else if (value == "MSN")
    {
        window.open('https://www.msn03.com', '_blank');
    }
};

whats wrong ?

Body:
When change select option, you didn't store changed value that's why always you show first loaded data that's why its not working exactly.

Please check following codes and run it in your environmnet.

var selectValue = document.getElementById('site01').value;

document.getElementById('site01').addEventListener('change', function() {
  selectValue = this.value;
});

document.getElementById("button01").onclick = function(){
    if (selectValue == "Google")
    {
        window.open('https://www.google01.com', '_blank');
    }
    else if (selectValue == "Yahoo")
    {
        window.open('https://www.yahoo01.com', '_blank');
    }
    else if (selectValue == "MSN")
    {
        window.open('https://www.msn01.com', '_blank');
    }
};

Hopefully, now it'll be worked, thank you.


问:
Sklearn PCA explained variance and explained variance ratio difference
I'm trying to get the variances from the eigen vectors.

What is the difference between explained_variance_ratio_ and explained_variance_ in PCA?

答:
The example used by @seralouk unfortunately already has only 2 components. So, the explanation for pca.explained_variance_ratio_ is incomplete.

The denominator should be the sum of pca.explained_variance_ratio_ for the original set of features before PCA was applied, where the number of components can be greater than the number of components used in PCA.

Here is an explanation of this quantity using the iris dataset.

```<code>import numpy as np
from sklearn import datasets
from sklearn.decomposition import PCA

iris=datasets.load_iris()

X = iris.data
#y = iris.target

pca_2c_model=PCA(n_components=2)
x_pca_2c=pca_2c_model.fit_transform(X)

print('Explained variance:\n', pca_2c_model.explained_variance_)

print('Explained variance ratio:\n', pca_2c_model.explained_variance_ratio_)
</code>```

returns

```<code>Explained variance:
 [4.22824171 0.24267075]
Explained variance ratio:
 [0.92461872 0.05306648]
</code>```

The quantity pca_2c_model.explained_variance_ contains the diagonal elements of the covariance of the two principal components. For principal components, by very definition the covariance matrix should be diagonal.

```<code>var=np.cov(x_pca_2c.T)
explained_var=var.diagonal()
print('Explained variance calculated manually is\n',explained_var)
</code>```

returns

```<code>Explained variance calculated manually is
 [4.22824171 0.24267075]
</code>```

To calculate the ratio, the denominator has to be calculated for the original set of features before PCA (i.e. on all components). So, we can just use the trace of the covariance of the full set of features to find the ratio. Here, we are using the idea of trace invariance of a matrix.

```<code>all_var=np.cov(X.T)
sum_all_var=np.sum(all_var.diagonal()) # same as np.trace(all_var)
explained_var_ratio=explained_var/sum_all_var
print('Explained variance ratio calculated manually is\n',explained_var_ratio)
</code>```

returns

```<code>Explained variance ratio calculated manually is
 [0.92461872 0.05306648]
</code>```

Further,

```<code>print(sum(explained_var_ratio))
</code>```

returns

```<code>0.9776852063187955
</code>```

So, the sum of explained_variance_ratio_ does not add to 1.0 implying that the small deviation from 1.0 is contained in the other components of the original feature space.

Body:
The example used by @seralouk unfortunately already has only 2 components. So, the explanation for pca.explained_variance_ratio_ is incomplete.

The denominator should be the sum of pca.explained_variance_ratio_ for the original set of features before PCA was applied, where the number of components can be greater than the number of components used in PCA.

Here is an explanation of this quantity using the iris dataset.

import numpy as np
from sklearn import datasets
from sklearn.decomposition import PCA

iris=datasets.load_iris()

X = iris.data
#y = iris.target

pca_2c_model=PCA(n_components=2)
x_pca_2c=pca_2c_model.fit_transform(X)

print('Explained variance:\n', pca_2c_model.explained_variance_)

print('Explained variance ratio:\n', pca_2c_model.explained_variance_ratio_)

returns

Explained variance:
 [4.22824171 0.24267075]
Explained variance ratio:
 [0.92461872 0.05306648]

The quantity pca_2c_model.explained_variance_ contains the diagonal elements of the covariance of the two principal components. For principal components, by very definition the covariance matrix should be diagonal.

var=np.cov(x_pca_2c.T)
explained_var=var.diagonal()
print('Explained variance calculated manually is\n',explained_var)

returns

Explained variance calculated manually is
 [4.22824171 0.24267075]

To calculate the ratio, the denominator has to be calculated for the original set of features before PCA (i.e. on all components). So, we can just use the trace of the covariance of the full set of features to find the ratio. Here, we are using the idea of trace invariance of a matrix.

all_var=np.cov(X.T)
sum_all_var=np.sum(all_var.diagonal()) # same as np.trace(all_var)
explained_var_ratio=explained_var/sum_all_var
print('Explained variance ratio calculated manually is\n',explained_var_ratio)

returns

Explained variance ratio calculated manually is
 [0.92461872 0.05306648]

Further,

print(sum(explained_var_ratio))

returns

0.9776852063187955

So, the sum of explained_variance_ratio_ does not add to 1.0 implying that the small deviation from 1.0 is contained in the other components of the original feature space.


问:
Layout align checkbox and date textview right in table layout?
```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:paddingTop="4dip" android:paddingBottom="6dip"
    android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:orientation="horizontal">
    <TableLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TableRow android:layout_width="fill_parent"
            android:layout_height="20dp" >
            <TextView android:id="@+id/text_sender" android:textStyle="bold" android:textColor="#ffffff" android:focusable="false"
                android:layout_width="0dp" android:layout_height="20dp" android:layout_weight=".75" />
            <TextView android:id="@+id/text_date" android:text="date"
                android:layout_width="0dp" android:layout_gravity="right"  android:layout_weight=".25" android:focusable="false"
                android:layout_height="20dp" />
        </TableRow>
        <TableRow android:layout_width="fill_parent"
            android:layout_height="35dp" android:gravity="top">
            <TextView android:id="@+id/text_msg" android:layout_width="0dp" android:layout_weight=".75"
                android:layout_height="35dp" android:focusable="false" />

            <CheckBox android:layout_width="0dp" android:id="@+id/ck_msg" android:layout_weight=".25"
                android:checked="false" android:layout_height="35dp" android:focusable="false"
                android:layout_gravity="right"  />
        </TableRow>
    </TableLayout>
</LinearLayout>
</code>```

i want to aligh both of them to extream right

答:
this should work..</p>

```<code>          <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:paddingTop="4dip" android:paddingBottom="6dip"
    android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:orientation="vertical">
         <TableLayout android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
            android:layout_gravity = "right">
                    <TableRow android:layout_width="fill_parent"
                        android:layout_height="20dp"
    android:layout_gravity = "right">
                        <TextView android:id="@+id/text_sender" android:textStyle="bold" android:textColor="#ffffff" android:focusable="false"
                            android:layout_width="0dp" android:layout_height="20dp" android:layout_weight=".75" />
                        <TextView android:id="@+id/text_date" android:text="date"
                            android:layout_width="0dp" android:layout_gravity="right"  android:layout_weight=".25" android:focusable="false"
                            android:layout_height="20dp" />
                    </TableRow>
                    <TableRow android:layout_width="fill_parent"
                        android:layout_height="35dp" android:layout_gravity = "right">
                        <TextView android:id="@+id/text_msg" android:layout_width="0dp" android:layout_weight=".75"
                            android:layout_height="35dp" android:focusable="false" />

                        <CheckBox android:layout_width="0dp" android:id="@+id/ck_msg" android:layout_weight=".25"
                            android:checked="false" android:layout_height="35dp" android:focusable="false"
                            android:layout_gravity="right"  />
                    </TableRow>
                </TableLayout>
</LinearLayout>
</code>```

Body:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:paddingTop="4dip" android:paddingBottom="6dip"
    android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:orientation="horizontal">
    <TableLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TableRow android:layout_width="fill_parent"
            android:layout_height="20dp" >
            <TextView android:id="@+id/text_sender" android:textStyle="bold" android:textColor="#ffffff" android:focusable="false"
                android:layout_width="0dp" android:layout_height="20dp" android:layout_weight=".75" />
            <TextView android:id="@+id/text_date" android:text="date"
                android:layout_width="0dp" android:layout_gravity="right"  android:layout_weight=".25" android:focusable="false"
                android:layout_height="20dp" />
        </TableRow>
        <TableRow android:layout_width="fill_parent"
            android:layout_height="35dp" android:gravity="top">
            <TextView android:id="@+id/text_msg" android:layout_width="0dp" android:layout_weight=".75"
                android:layout_height="35dp" android:focusable="false" />

            <CheckBox android:layout_width="0dp" android:id="@+id/ck_msg" android:layout_weight=".25"
                android:checked="false" android:layout_height="35dp" android:focusable="false"
                android:layout_gravity="right"  />
        </TableRow>
    </TableLayout>
</LinearLayout>

i want to aligh both of them to extream right

Body:
this should work..

          <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:paddingTop="4dip" android:paddingBottom="6dip"
    android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:orientation="vertical">
         <TableLayout android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
            android:layout_gravity = "right">
                    <TableRow android:layout_width="fill_parent"
                        android:layout_height="20dp"
    android:layout_gravity = "right">
                        <TextView android:id="@+id/text_sender" android:textStyle="bold" android:textColor="#ffffff" android:focusable="false"
                            android:layout_width="0dp" android:layout_height="20dp" android:layout_weight=".75" />
                        <TextView android:id="@+id/text_date" android:text="date"
                            android:layout_width="0dp" android:layout_gravity="right"  android:layout_weight=".25" android:focusable="false"
                            android:layout_height="20dp" />
                    </TableRow>
                    <TableRow android:layout_width="fill_parent"
                        android:layout_height="35dp" android:layout_gravity = "right">
                        <TextView android:id="@+id/text_msg" android:layout_width="0dp" android:layout_weight=".75"
                            android:layout_height="35dp" android:focusable="false" />

                        <CheckBox android:layout_width="0dp" android:id="@+id/ck_msg" android:layout_weight=".25"
                            android:checked="false" android:layout_height="35dp" android:focusable="false"
                            android:layout_gravity="right"  />
                    </TableRow>
                </TableLayout>
</LinearLayout>


问:
Powershell - capture all non-blank lines between key words
I have a script that was put together with the community help and it works great.  I'm trying to alter it to work for my new requirements.
I have data (See below) that needs to be captured from 10K+ files.
Inside each file could be multiple iterations of the data I need to capture.  The script I'm using captured only the file name and not the data I need.  Can someone see where I'm off (Code wise) and offer another option.

Here is my Raw Data.  There could be four or five places in a text member with this data and I need to capture it all.
The words in Bold (Select and From) are the words I'm keying on.  I need to capture those lines as well as all the lines between them.

```<code>    SELECT   FIL_ID_NUM,                                             00481002
             LAU_CRE_DTS,                                            00482002
             LAU_CD,                                                 00483002
             LAU_EFF_DT,                                             00484002
             LAU_EFF_TIM,                                            00485002
             LAU_EXP_DT,                                             00486002
             LAU_EXP_TIM,                                            00487002
             LAU_SERV_REAS1_CD,                                      00488002
             LAU_SERV_REAS2_CD,                                      00489002
             LAU_SERV_REAS3_CD,                                      00489102
             LAU_CARE_IND,                                           00489202
             SEG_UPDT_LOCK_NUM,                                      00489302
             LAU_AGRMT_PER_NAM,                                      00489402
             LAU_AGRMT_DSGT_NAM,                                     00489502
             LAU_AGRMT_DIR_TXT,                                      00489602
             LAU_TERMS_TXT                                           00489702
                                                                     00520002
        FROM TLEGAL
</code>```

Here is my script....

```<code># create a List object to collect the 'flowerbox' strings in
$Flowerbox = [System.Collections.Generic.List[string]]::new()
$treat = $false

# get a list of the .pl1m files and loop through. Collect all output in variable $result
$CBLFileList = Get-ChildItem -Path 'C:\src' -Filter '*.pl1m' -File -Recurse
$result = foreach ($CBLFile in $CBLFileList) {
    Write-Host "Processing ... $($CBLFile.Name)" -ForegroundColor Green

    $Flowerbox.Clear()  # empty the list for the next run
    $treat = $false
    switch -Regex -File $CBLFile.FullName {
        'SELECT' {
        Write-Host "Found Select" -ForegroundColor DarkYellow
            # start collecting lines from here
            $treat = $true
        }
        'FROM ' {
        Write-Host "Found From" -ForegroundColor DarkRed
           if ($treat) {

            # stop colecting Flowerbox lines and output what we already have
            # output an object with the two properties you need
            [PsCustomObject]@{
                Program     = $CBLFile.Name  # or $CBLFile.FullName
                Description = $Flowerbox -join [environment]::NewLine
            }
            }
            $Flowerbox.Clear()  # empty the list for the next run
            $treat = $false
        }
        default {
                # Add captures data here
                if ($treat -and ($_ -match '/[^\s\\]/')) {
                $Flowerbox.Add($Matches[1])
            }
        }
    }
}

# now you have everything in an array of PSObjects so you can save that as Csv
$result | Export-Csv -Path 'C:\src\SQL_Desc.csv' -UseCulture -NoTypeInformation
</code>```

答:
I love Santiago Squarzon's approach, but his code doesn't seem to remove blank lines.  This code is a little bit of a hybrid of everyone else's code.  I learned a lot about switch by doing this, amazing what you can get switch to do once you get your head wrapped around what it is doing.

```<code>function Process-Line {
    Process {
        ($Input -Split ',' | ForEach-Object { $_.Trim() } ) -join ', '
    }
}
function Process-File {
    Process {
        $Inside = $false;
        switch -Regex -File $Input.FullName {
            '^\s*$' { continue }
            '(?i)^\s*SELECT\s.*$' { $Inside = $true }
            '^.+$'                { if($Inside) { $Matches[0] | Process-Line } }
            '(?i)^\s*from\s.*$'   { $Inside = $false }
            default { continue }
        }
    }
}
$Result = Get-ChildItem -Path 'D:\Sync\Projects\ps1\Crypto' -Filter '*.pl1m' -Recurse | Process-File
$Result | Out-File -FilePath 'D:\Sync\Projects\ps1\Crypto\SQL_Desc.csv'
</code>```

Taking your data exactly as is, it produced this, which I'm nearly 100% sure isn't exactly what you want.  If you give some more details on the exact layout of the CSV, and if you are sure the source data is missing commas, I think we can figure a way to beat it into shape.  But we need to get it into a uniform pattern before packaging it in a PSCustomObject and piping it to Export-CSV.

```<code>SELECT   FIL_ID_NUM, 00481002
LAU_CRE_DTS, 00482002
LAU_CD, 00483002
LAU_EFF_DT, 00484002
LAU_EFF_TIM, 00485002
LAU_EXP_DT, 00486002
LAU_EXP_TIM, 00487002
LAU_SERV_REAS1_CD, 00488002
LAU_SERV_REAS2_CD, 00489002
LAU_SERV_REAS3_CD, 00489102
LAU_CARE_IND, 00489202
SEG_UPDT_LOCK_NUM, 00489302
LAU_AGRMT_PER_NAM, 00489402
LAU_AGRMT_DSGT_NAM, 00489502
LAU_AGRMT_DIR_TXT, 00489602
LAU_TERMS_TXT                                           00489702
00520002
FROM TLEGAL
</code>```

Also, do you want:

A header line in the csv file? And if so, what column headers do you want?

Are there really numbers, such as the last number (00520002), on a line by themselves?

Do you want the "SELECT" and "FROM TLEGAL" to appear?  They don't fit well in the CSV format.

Body:
I have a script that was put together with the community help and it works great.  I'm trying to alter it to work for my new requirements.
I have data (See below) that needs to be captured from 10K+ files.
Inside each file could be multiple iterations of the data I need to capture.  The script I'm using captured only the file name and not the data I need.  Can someone see where I'm off (Code wise) and offer another option.

Here is my Raw Data.  There could be four or five places in a text member with this data and I need to capture it all.
The words in Bold (Select and From) are the words I'm keying on.  I need to capture those lines as well as all the lines between them.

    SELECT   FIL_ID_NUM,                                             00481002
             LAU_CRE_DTS,                                            00482002
             LAU_CD,                                                 00483002
             LAU_EFF_DT,                                             00484002
             LAU_EFF_TIM,                                            00485002
             LAU_EXP_DT,                                             00486002
             LAU_EXP_TIM,                                            00487002
             LAU_SERV_REAS1_CD,                                      00488002
             LAU_SERV_REAS2_CD,                                      00489002
             LAU_SERV_REAS3_CD,                                      00489102
             LAU_CARE_IND,                                           00489202
             SEG_UPDT_LOCK_NUM,                                      00489302
             LAU_AGRMT_PER_NAM,                                      00489402
             LAU_AGRMT_DSGT_NAM,                                     00489502
             LAU_AGRMT_DIR_TXT,                                      00489602
             LAU_TERMS_TXT                                           00489702
                                                                     00520002
        FROM TLEGAL

Here is my script....

# create a List object to collect the 'flowerbox' strings in
$Flowerbox = [System.Collections.Generic.List[string]]::new()
$treat = $false

# get a list of the .pl1m files and loop through. Collect all output in variable $result
$CBLFileList = Get-ChildItem -Path 'C:\src' -Filter '*.pl1m' -File -Recurse
$result = foreach ($CBLFile in $CBLFileList) {
    Write-Host "Processing ... $($CBLFile.Name)" -ForegroundColor Green

    $Flowerbox.Clear()  # empty the list for the next run
    $treat = $false
    switch -Regex -File $CBLFile.FullName {
        'SELECT' {
        Write-Host "Found Select" -ForegroundColor DarkYellow
            # start collecting lines from here
            $treat = $true
        }
        'FROM ' {
        Write-Host "Found From" -ForegroundColor DarkRed
           if ($treat) {

            # stop colecting Flowerbox lines and output what we already have
            # output an object with the two properties you need
            [PsCustomObject]@{
                Program     = $CBLFile.Name  # or $CBLFile.FullName
                Description = $Flowerbox -join [environment]::NewLine
            }
            }
            $Flowerbox.Clear()  # empty the list for the next run
            $treat = $false
        }
        default {
                # Add captures data here
                if ($treat -and ($_ -match '/[^\s\\]/')) {
                $Flowerbox.Add($Matches[1])
            }
        }
    }
}

# now you have everything in an array of PSObjects so you can save that as Csv
$result | Export-Csv -Path 'C:\src\SQL_Desc.csv' -UseCulture -NoTypeInformation

Body:
I love Santiago Squarzon's approach, but his code doesn't seem to remove blank lines.  This code is a little bit of a hybrid of everyone else's code.  I learned a lot about switch by doing this, amazing what you can get switch to do once you get your head wrapped around what it is doing.

function Process-Line {
    Process {
        ($Input -Split ',' | ForEach-Object { $_.Trim() } ) -join ', '
    }
}
function Process-File {
    Process {
        $Inside = $false;
        switch -Regex -File $Input.FullName {
            '^\s*$' { continue }
            '(?i)^\s*SELECT\s.*$' { $Inside = $true }
            '^.+$'                { if($Inside) { $Matches[0] | Process-Line } }
            '(?i)^\s*from\s.*$'   { $Inside = $false }
            default { continue }
        }
    }
}
$Result = Get-ChildItem -Path 'D:\Sync\Projects\ps1\Crypto' -Filter '*.pl1m' -Recurse | Process-File
$Result | Out-File -FilePath 'D:\Sync\Projects\ps1\Crypto\SQL_Desc.csv'

Taking your data exactly as is, it produced this, which I'm nearly 100% sure isn't exactly what you want.  If you give some more details on the exact layout of the CSV, and if you are sure the source data is missing commas, I think we can figure a way to beat it into shape.  But we need to get it into a uniform pattern before packaging it in a PSCustomObject and piping it to Export-CSV.

SELECT   FIL_ID_NUM, 00481002
LAU_CRE_DTS, 00482002
LAU_CD, 00483002
LAU_EFF_DT, 00484002
LAU_EFF_TIM, 00485002
LAU_EXP_DT, 00486002
LAU_EXP_TIM, 00487002
LAU_SERV_REAS1_CD, 00488002
LAU_SERV_REAS2_CD, 00489002
LAU_SERV_REAS3_CD, 00489102
LAU_CARE_IND, 00489202
SEG_UPDT_LOCK_NUM, 00489302
LAU_AGRMT_PER_NAM, 00489402
LAU_AGRMT_DSGT_NAM, 00489502
LAU_AGRMT_DIR_TXT, 00489602
LAU_TERMS_TXT                                           00489702
00520002
FROM TLEGAL

Also, do you want:

A header line in the csv file? And if so, what column headers do you want?

Are there really numbers, such as the last number (00520002), on a line by themselves?

Do you want the "SELECT" and "FROM TLEGAL" to appear?  They don't fit well in the CSV format.