问:
LaunchNavigator availableApps is returning empty even if google maps is installed
I have this code : </p>

```<code>constructor(
    private launchNavigator: LaunchNavigator
) {

}

getApps() {
   this.launchNavigator.availableApps().then((result: any) => {
       console.log(result);
   });
}
</code>```

<p>Available apps is empty when I try in ios. On Android is working fine. Can you help me please with some advices ? </p>

答: as an iPhone user, you can NOT make google maps your default navigator. Your only option is Apple Maps. so I think you deleted Apple Maps and the function availableApps() is not finding it. install it again and try again with Apple Maps instead.</p>

Body:
I have this code :

constructor(
    private launchNavigator: LaunchNavigator
) {

}

getApps() {
   this.launchNavigator.availableApps().then((result: any) => {
       console.log(result);
   });
}

Available apps is empty when I try in ios. On Android is working fine. Can you help me please with some advices ?


来源: stackexchange

问:
In VBA, how to extract the string before a number from the text
From ActiveWorkbook.name, I would like to extract the strings that are before (left side of ) the numbers. Since I want to use the same code in multiple workbooks, the file names would be variable, but every file name has date info in the middle  (yyyymmdd).

In case of excel file, I can use the below formula, but can I apply the same kind of method in VBA?

```<code>=LEFT(A1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},ASC(A1)&1234567890))-1)
</code>```

Example: MyExcelWorkbook_Management_20200602_MyName.xlsm

In above case, I want to extract "MyExcelWorkbook_Management_".

答:
The most basic thing you could do is to replicate something that worked for you in Excel through Evaluate:

```<code>Sub Test()
    Dim str As String: str = "MyExcelWorkbook_Management_20200602_MyName.xlsm"
    Debug.Print Evaluate(Replace("=LEFT(""X"",MIN(FIND({0,1,2,3,4,5,6,7,8,9},ASC(""X"")&1234567890))-1)", "X", str))
End Sub
</code>```

Pretty? Not really, but it does the job and got it's limitations.

ContentLicense: CC BY-SA 4.0

Body:
From ActiveWorkbook.name, I would like to extract the strings that are before (left side of ) the numbers. Since I want to use the same code in multiple workbooks, the file names would be variable, but every file name has date info in the middle  (yyyymmdd).

In case of excel file, I can use the below formula, but can I apply the same kind of method in VBA?

=LEFT(A1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},ASC(A1)&1234567890))-1)

Example: MyExcelWorkbook_Management_20200602_MyName.xlsm

In above case, I want to extract "MyExcelWorkbook_Management_".

Body:
The most basic thing you could do is to replicate something that worked for you in Excel through Evaluate:

Sub Test()
    Dim str As String: str = "MyExcelWorkbook_Management_20200602_MyName.xlsm"
    Debug.Print Evaluate(Replace("=LEFT(""X"",MIN(FIND({0,1,2,3,4,5,6,7,8,9},ASC(""X"")&1234567890))-1)", "X", str))
End Sub

Pretty? Not really, but it does the job and got it's limitations.


问:
Why the dataframe is altered when only df.to_numpy() is involved in the computation?
```<code>import pandas as pd
import numpy as np

url = "https://raw.githubusercontent.com/PawinData/UC/SFBA/DistanceMatrix_shortestnetworks.csv"
Distance_df = pd.read_csv(url, index_col=0)

D = Distance_df.to_numpy()
</code>```

I have a dataframe Distance_df and I convert it to a numpy array D for computation. What happens subsequently only concerns D and doesn't involve Distance_df at all. However, both D and Distance_df are altered (to the same thing) in the end.

Although I can't figure out why D would change either, it's the behavior of Distance_df, the dataframe, that puzzles me the most. How can it be altered when it doesn't even show up in the code? Somehow I sense that this is not about the code but how values and objects are handled behind the scene. Can anybody explain a little bit?

答:
You need to add copy=True as an argument to to_numpy().

According to DataFrame.to_numpy docs:

copy : bool, default False

Whether to ensure that the returned value is a not a view on another array. Note that copy=False does not ensure that to_numpy() is no-copy. Rather, copy=True ensure that a copy is made, even if not strictly necessary.

In other words, writing D = Distance_df.to_numpy() may result in D being a reference to the underlying numpy arrays of Distance_df, instead of copying them.

Write D = Distance_df.to_numpy(copy=True) to ensure that D and Distance_df are independent objects.

Body:
import pandas as pd
import numpy as np

url = "https://raw.githubusercontent.com/PawinData/UC/SFBA/DistanceMatrix_shortestnetworks.csv"
Distance_df = pd.read_csv(url, index_col=0)

D = Distance_df.to_numpy()

I have a dataframe Distance_df and I convert it to a numpy array D for computation. What happens subsequently only concerns D and doesn't involve Distance_df at all. However, both D and Distance_df are altered (to the same thing) in the end.

Although I can't figure out why D would change either, it's the behavior of Distance_df, the dataframe, that puzzles me the most. How can it be altered when it doesn't even show up in the code? Somehow I sense that this is not about the code but how values and objects are handled behind the scene. Can anybody explain a little bit?


问:
What are data breakpoints?
I just came to know that there are data breakpoints. I have worked for the last 5 years in C++ using Visual Studio, and I have never used data breakpoints.

Can someone throw some light on what data breakpoints are, when to use them and how to use them with VS?

As per my understanding we can set a data breakpoint when we want to check for changes to a variable's value. In this case, we can set a data breakpoint with a condition on the variable value.

Any other examples?

答: I believe data breakpoints are breakpoints which will occur when some memory is set to a certain value.  For example, you can set a breakpoint when i == 10 in a typical for loop to stop after the 10th iteration.  You can also watch for changes to variables on the heap, like wait for a member of a class to be modified.</p>

ContentLicense: CC BY-SA 2.5

Title: What are data breakpoints?

LastEditorDisplayName: MarkJ

OwnerDisplayName: strager


问:
checkboxes in php - problem with access
i need to reproduce with the code below something like:

```<code>myformdata[languages1]
myformdata[languages2]
myformdata[languages3]
</code>```

But with this code only reproduce myformdata[languages

```<code>    <?php
    $sql=mysql_query("select id_spoken_languages, language, path from spoken_languages");
    $i=0;
    while($row=mysql_fetch_array($sql)) {
    $id=$row['id_spoken_languages'];
    $data=$row['language'];
    $flag=$row['path'];
    echo nl2br ("<input type='checkbox' name='myformdata[languages'.$i++.']' value='$id' class='semLargura'>$data <img style='float:right; margin-top:5px; border:1px solid grey;' src='$flag'></img> \n");
    }
    ?>
</code>```

i already tried remove the increment and only access with $form_data_array["languages"][1] but in this case i get:

Notice:  Uninitialized string offset: 1 in C:\Users\fel\VertrigoServ\www\login\validation2.php on line 9

but if i use `$form_data_array["languages"][0], no error is showed, seems like all checkbox have the
index 0.

what is the best way to solve this problem?

答:
Looks like quotes are messed up:</p>

```<code>echo nl2br ("<input type='checkbox' name='myformdata[languages" . $i++ . "]' value='$id' class='semLargura'>$data <img style='float:right; margin-top:5px; border:1px solid grey;' src='$flag'></img> \n");
</code>```

ContentLicense: CC BY-SA 3.0

Title: checkboxes in php - problem with access

Body:
i need to reproduce with the code below something like:

myformdata[languages1]
myformdata[languages2]
myformdata[languages3]

But with this code only reproduce myformdata[languages

    <?php
    $sql=mysql_query("select id_spoken_languages, language, path from spoken_languages");
    $i=0;
    while($row=mysql_fetch_array($sql)) {
    $id=$row['id_spoken_languages'];
    $data=$row['language'];
    $flag=$row['path'];
    echo nl2br ("<input type='checkbox' name='myformdata[languages'.$i++.']' value='$id' class='semLargura'>$data  \n");
    }
    ?>

i already tried remove the increment and only access with $form_data_array["languages"][1] but in this case i get:

Notice:  Uninitialized string offset: 1 in C:\Users\fel\VertrigoServ\www\login\validation2.php on line 9

but if i use `$form_data_array["languages"][0], no error is showed, seems like all checkbox have the
index 0.

what is the best way to solve this problem?

Body:
Looks like quotes are messed up:

echo nl2br ("<input type='checkbox' name='myformdata[languages" . $i++ . "]' value='$id' class='semLargura'>$data <img style='float:right; margin-top:5px; border:1px solid grey;' src='$flag'></img> \n");


问:
Laravel Datatables getting net::ERR_EMPTY_RESPONSE error when adding extra column
I'm using DataTable 1.10.21 with Laravel 7. I'm trying to populate all of the users data, except my user table has an additional column named group_id, which define the user group (ie. admin, manager, user etc)

Right now my user model has this relationship:

```<code>public function group() {
        return $this->belongsTo(Group::class);
    }
</code>```

When I call

```<code>App\User::select(*)->with('group')->get();
</code>```

I'll get something like this which is good:

```<code>App\User {#105150
         id: 1,
         group_id: 1,
         name: "Admin",
         email: "admin@admin.com",
         email_verified_at: "2020-01-01 01:01:01",
         ...
         deleted_at: null,
         group: App\Group {#105096
           id: 1,
           name: "admin",
         },
       }
       ...
</code>```

In my UserController I have this function:

```<code>public function datatable() {
        $data = User::select("*")->with('group');
        $dt = Datatables::of($data)->make(true);
        \Log::debug($dt); //this works!!
        return $dt;
    }
</code>```

I can use tinker to get $data and $dt without any problem.

My view contains the following javascript:

```<code>$(function() {
               $('#table').DataTable({
               processing: true,
               serverSide: true,
               ajax: '{{ url('user/datatable') }}',
               columns: [
                        { data: 'id', name: 'id' },
                        { data: 'name', name: 'name' },
                        { data: 'group_id', name: 'group_id' }, /* this won't work */
                        { data: 'group.name', name: 'group.name' }, /* this won't work either */
                        { data: 'created_at', name: 'created_at' },
                        { data: 'email', name: 'email' }
                     ]
            });
         });
</code>```

```<code><table class="table table-bordered" id="table">
               <thead>
                  <tr>
                     <th>ID</th>
                     <th>Name</th>
                     <th>Group ID</th>
                     <th>Group Name</th>
                     <th>Creation Date</th>
                     <th>Email</th>
                  </tr>
               </thead>
            </table>
</code>```

Neither of the group_id or group.name col will work. (net::ERR_EMPTY_RESPONSE error even $dt has response) but if I remove both columns then it works fine.

Please advise.

Edit: May 29 2020

I digged a little deeper and here's what I have found:

If I use my local test domain (ie. myproject.test)

If I remove some other columns (ie. created at, email) it worked

If I include all columns (ie. id, name, group_id, group.name, created_at, email) I got the ERR_EMPTY_RESPONSE error

If I use 127.0.0.1:8000

it worked even if I include all columns!!!!

Can someone please explain to me why??

答:
Yajra\Datatables is one of those areas I personally prefer to use raw sql.

With your above requirements I'd see it like so

```<code>$data = DB::select("
Select
  a.id as 'users.id',
  a.name as 'users.name',
  b.id as 'group.id',
  b.name as 'group.name',
  a.created_at as 'users.created_at',
  a.email as 'users.email'
FROM
  users as a
LEFT JOIN
  groups as b
ON
  a.group_id = b.id");

$data = Datatables::of($data)->make(true);
return $data;
</code>```

Then in your columns section of your datatable initialization code just update the data with "users.id", "users.name", etc (same with the name fields).

Yajra is great, but I ran into issues with it and eloquent myself.  Hence why I just went back to raw sql, havent had a problem since.

Edit - with new data:
Then I'd suggest you post your .env file that has been loaded to the server in question. Are you doing all of this locally or do you have a seperate server you are having problems on?

Body:
I'm using DataTable 1.10.21 with Laravel 7. I'm trying to populate all of the users data, except my user table has an additional column named group_id, which define the user group (ie. admin, manager, user etc)

Right now my user model has this relationship:

public function group() {
        return $this->belongsTo(Group::class);
    }

When I call

App\User::select(*)->with('group')->get();

I'll get something like this which is good:

App\User {#105150
         id: 1,
         group_id: 1,
         name: "Admin",
         email: "admin@admin.com",
         email_verified_at: "2020-01-01 01:01:01",
         ...
         deleted_at: null,
         group: App\Group {#105096
           id: 1,
           name: "admin",
         },
       }
       ...

In my UserController I have this function:

public function datatable() {
        $data = User::select("*")->with('group');
        $dt = Datatables::of($data)->make(true);
        \Log::debug($dt); //this works!!
        return $dt;
    }

I can use tinker to get $data and $dt without any problem.

My view contains the following javascript:

$(function() {
               $('#table').DataTable({
               processing: true,
               serverSide: true,
               ajax: '{{ url('user/datatable') }}',
               columns: [
                        { data: 'id', name: 'id' },
                        { data: 'name', name: 'name' },
                        { data: 'group_id', name: 'group_id' }, /* this won't work */
                        { data: 'group.name', name: 'group.name' }, /* this won't work either */
                        { data: 'created_at', name: 'created_at' },
                        { data: 'email', name: 'email' }
                     ]
            });
         });

                     ID
                     Name
                     Group ID
                     Group Name
                     Creation Date
                     Email

Neither of the group_id or group.name col will work. (net::ERR_EMPTY_RESPONSE error even $dt has response) but if I remove both columns then it works fine.

Please advise.

Edit: May 29 2020

I digged a little deeper and here's what I have found:

If I use my local test domain (ie. myproject.test)

If I remove some other columns (ie. created at, email) it worked

If I include all columns (ie. id, name, group_id, group.name, created_at, email) I got the ERR_EMPTY_RESPONSE error

If I use 127.0.0.1:8000

it worked even if I include all columns!!!!

Can someone please explain to me why??

Body:
Yajra\Datatables is one of those areas I personally prefer to use raw sql.

With your above requirements I'd see it like so

$data = DB::select("
Select
  a.id as 'users.id',
  a.name as 'users.name',
  b.id as 'group.id',
  b.name as 'group.name',
  a.created_at as 'users.created_at',
  a.email as 'users.email'
FROM
  users as a
LEFT JOIN
  groups as b
ON
  a.group_id = b.id");

$data = Datatables::of($data)->make(true);
return $data;

Then in your columns section of your datatable initialization code just update the data with "users.id", "users.name", etc (same with the name fields).

Yajra is great, but I ran into issues with it and eloquent myself.  Hence why I just went back to raw sql, havent had a problem since.

Edit - with new data:
Then I'd suggest you post your .env file that has been loaded to the server in question. Are you doing all of this locally or do you have a seperate server you are having problems on?


问:
What is the best practice for looping through a dictionary of pandas dataframes and making modifications?
I have a dictionary of DataFrames with the key referring to the year of the data. I would like to iterate through the dict and make modifications to the DataFrames. I make modifications to both the column names and the contents of the dfs.

```<code>for year, df in df_data.items():
    cols = df .columns
    new_cols = [re.sub(r'\s\d{4}\-\d{2}', '', c) for c in cols]
    df.columns = new_cols

for year, df in df_data.items():
    df['Date'] = pd.to_datetime(df['Date'], infer_datetime_format=True)
    df = df.drop_duplicates(subset='Id', keep='first')
</code>```

Can someone explain to me the behavior of doing this? Particularly, how the dfs are stored in memory and why the rename of columns works but the modification to the contents do not.
Also, is there a best way to do this either by copying the df and then replacing it in the dict index or by constantly making the changes to the df_data[year] reference?

答:
As @juanpa.arrivillaga describes above, drop_duplicates returns a dataframe, which you're assigning to the local variable df. Consider the following example:

```<code>a = [0, 1]
for b in a:
    print(f'b: {b}')
    b = 2
    print(f'b: {b}')

print(f'a: {a}')
</code>```

This is the output:

```<code>b: 0
b: 2
b: 1
b: 2
a: [0, 1]
</code>```

You can see that the local var b is being assigned the value 2, but that the list a is unchanged after the loop completes. This is because b is a reference to the list, not the list itself. Assigning b = 2 causes b to change to a reference to the integer 2, but does not cause the list item that b refers to to change to a reference to the integer 2.
At the start of the first loop, the references look like this:

```<code>b -> a[0] -> the integer 0
</code>```

Assigning b = 2 results in this:

```<code>a[0] -> the integer 0
   b -> the integer 2
</code>```

Not this:

```<code>b -> a[0] -> the integer 2
</code>```

To mutate an object in loop, you must work only with methods which work in place, or you must work with a direct reference to the object:

```<code>for year in df_data.keys():
    cols = df[year].columns
    new_cols = [re.sub(r'\s\d{4}\-\d{2}', '', c) for c in cols]
    df[year].columns = new_cols

for year in df_data.keys():
    df[year]['Date'] = pd.to_datetime(df[year]['Date'], infer_datetime_format=True)
    df[year] = df[year].drop_duplicates(subset='Id', keep='first')
</code>```

Body:
I have a dictionary of DataFrames with the key referring to the year of the data. I would like to iterate through the dict and make modifications to the DataFrames. I make modifications to both the column names and the contents of the dfs.

for year, df in df_data.items():
    cols = df .columns
    new_cols = [re.sub(r'\s\d{4}\-\d{2}', '', c) for c in cols]
    df.columns = new_cols

for year, df in df_data.items():
    df['Date'] = pd.to_datetime(df['Date'], infer_datetime_format=True)
    df = df.drop_duplicates(subset='Id', keep='first')

Can someone explain to me the behavior of doing this? Particularly, how the dfs are stored in memory and why the rename of columns works but the modification to the contents do not.
Also, is there a best way to do this either by copying the df and then replacing it in the dict index or by constantly making the changes to the df_data[year] reference?

Body:
As @juanpa.arrivillaga describes above, drop_duplicates returns a dataframe, which you're assigning to the local variable df. Consider the following example:

a = [0, 1]
for b in a:
    print(f'b: {b}')
    b = 2
    print(f'b: {b}')

print(f'a: {a}')

This is the output:

b: 0
b: 2
b: 1
b: 2
a: [0, 1]

You can see that the local var b is being assigned the value 2, but that the list a is unchanged after the loop completes. This is because b is a reference to the list, not the list itself. Assigning b = 2 causes b to change to a reference to the integer 2, but does not cause the list item that b refers to to change to a reference to the integer 2.
At the start of the first loop, the references look like this:

b -> a[0] -> the integer 0

Assigning b = 2 results in this:

a[0] -> the integer 0
   b -> the integer 2

Not this:

b -> a[0] -> the integer 2

To mutate an object in loop, you must work only with methods which work in place, or you must work with a direct reference to the object:

for year in df_data.keys():
    cols = df[year].columns
    new_cols = [re.sub(r'\s\d{4}\-\d{2}', '', c) for c in cols]
    df[year].columns = new_cols

for year in df_data.keys():
    df[year]['Date'] = pd.to_datetime(df[year]['Date'], infer_datetime_format=True)
    df[year] = df[year].drop_duplicates(subset='Id', keep='first')


问:
Is there a standard way to document Svelte components?
I come from the world of JavaDocs and love the DX of working on a thoroughly-annotated application after a certain level of complexity.

Being able to hover over and peek all the props (and implied types) of a component with some brief documentation would save me so much time instead of having to open up and read through the whole component. Better yet, running a command to generate a documentation site just like you can with JavaDocs would be dope!

Are there any standards or tools built around creating SvelteDocs? I looked through the VS Code marketplace and didn't see any documentation tooling related to Svelte.

答:
After more digging, I found just a couple projects for documenting Svelte.

SvelteDoc Parser -- takes a VueDoc approach, based on JSDoc standards, generates JSON documentation for Svelte components

Svelte-Docs -- documentation in Markdown mixed with Svelte's features, can embed components in the generated doc pages

Both look interesting while taking completely separate approaches to solving the issue of application documentation. Perhaps there's still room to build a CLI-based site generator for the SvelteDoc Parser which could be turned into a VS Code plugin!


问:
Why does flatten on nested Iterator not compile and why do I need type ascription?
```<code>(new Iterator[List[Int]] {
  def hasNext: Boolean = ???
  def next(): List[Int] = ???
}).flatten
</code>```

gives error:

```<code>value flatten is not a member of Iterator[List[Int]]
[error] possible cause: maybe a semicolon is missing before `value flatten'?
[error]     }.flatten
[error]       ^
[error] one error found
</code>```

But

```<code>(new Iterator[List[Int]] {
  def hasNext: Boolean = ???
  def next(): List[Int] = ???
}: Iterator[List[Int]]).flatten
</code>```

works.  Also storing the iterator in a val works.

Scala version: 2.11.8

答:
I think it tries to parse this:

new Iterator[List[Int]] {
      def hasNext: Boolean = ???
      def next(): List[Int] = ???
    }.flatten
```

<p>as this</p>

<pre class="lang-scala prettyprint-override"><code>new Iterator[List[Int]] ( {
      def hasNext: Boolean = ???
      def next(): List[Int] = ???
    }.flatten )
</code>```

Notice where I added the parentheses ().

Body:
(new Iterator[List[Int]] {
  def hasNext: Boolean = ???
  def next(): List[Int] = ???
}).flatten

gives error:

value flatten is not a member of Iterator[List[Int]]
[error] possible cause: maybe a semicolon is missing before `value flatten'?
[error]     }.flatten
[error]       ^
[error] one error found

But

(new Iterator[List[Int]] {
  def hasNext: Boolean = ???
  def next(): List[Int] = ???
}: Iterator[List[Int]]).flatten

works.  Also storing the iterator in a val works.

Scala version: 2.11.8

Body:
I think it tries to parse this:

new Iterator[List[Int]] {
      def hasNext: Boolean = ???
      def next(): List[Int] = ???
    }.flatten

as this

new Iterator[List[Int]] ( {
      def hasNext: Boolean = ???
      def next(): List[Int] = ???
    }.flatten )

Notice where I added the parentheses ().


问:
"stderr;" as a statement throws no warning
Suppose I have a source code like this:

```<code>#include <stdio.h>

FILE *p;

int main(void) {
    p;
}
</code>```

... which will compile (using gcc) without any errors or warnings – unless I turn on -Wall, in which case a statement with no effect warning will be output.

However if the code went like this:

```<code>#include <stdio.h>

int main(void) {
    stderr;
}
</code>```

... no warnings would be shown regardless of -Wall.

Am I missing something here?

gcc version 9.3.0

答:
This program:

```<code>$ cat main.c
#include <stdio.h>

int main(void)
{
    FILE *p;
    42;         // statement with no effect
    p;          // statement with no effect
    stderr;     // statement with no effect
    return 0;
}
</code>```

might be expected to elicit 3 statement with no effect
diagnostics whenever it elicits any. But as you've discovered,
in the hands of gcc, that is not true.

```<code>$ gcc --version
gcc (Ubuntu 9.3.0-10ubuntu2) 9.3.0
...

$ gcc -Wall -c main.c
main.c: In function ‘main’:
main.c:6:5: warning: statement with no effect [-Wunused-value]
    6 |     42;
      |     ^~
main.c:7:5: warning: statement with no effect [-Wunused-value]
    7 |     p;
      |     ^
</code>```

stderr - which denotes a FILE *, like p - has a free pass for being implicitly
evaluated with no effect.

Notoriously, -Wall does not really enable all warnings. But this free
pass survives to the customary limit of diagnostic rigour:

```<code>$ gcc -Wall -Wextra -pedantic -c main.c
main.c: In function ‘main’:
main.c:6:5: warning: statement with no effect [-Wunused-value]
    6 |     42;
      |     ^~
main.c:7:5: warning: statement with no effect [-Wunused-value]
    7 |     p;
      |     ^
</code>```

We should be clear that this free pass is carried by the identfier
stderr, as distinct from the value it names:-

It is not transferable to another FILE * by making that other one equal to stderr:

```<code>$ cat main.c; gcc -Wall -c main.c
#include <stdio.h>

int main(void)
{
    FILE *p = stderr;
    42;
    p;
    return 0;
}

main.c: In function ‘main’:
main.c:6:5: warning: statement with no effect [-Wunused-value]
    6 |     42;
      |     ^~
main.c:7:5: warning: statement with no effect [-Wunused-value]
    7 |     p;
      |     ^
</code>```

It is not enjoyed by the FILE * that actually is stderr, if we do not refer to it as stderr.

```<code>$ cat main.c; gcc -Wall -c main.c
#include <stdio.h>

int main(void)
{
    FILE **p = &stderr;
    42;
    *p;     // a.k.a `stderr`
    return 0;
}

main.c: In function ‘main’:
main.c:6:5: warning: statement with no effect [-Wunused-value]
    6 |     42;
      |     ^~
main.c:7:5: warning: statement with no effect [-Wunused-value]
    7 |     *p;     // a.k.a `stderr`
      |     ^~
</code>```

But on the other hand, even when stderr is referred to as stderr,
the free pass is forfeit if that identifier is anything less than
the entire context that is evaluated with no effect:

```<code>$ cat main.c; gcc -Wall -c main.c
#include <stdio.h>

int main(void)
{
    stdout;             // Undiagnosed
    stderr;             // Undiagnosed
    stderr, stdout;     // Diagnosed once
    42, stderr;         // Diagnosed twice
    stderr - stdout;    // Diagnosed once
    (stderr);           // Diagnosed once
    return 0;
}

main.c: In function ‘main’:
main.c:7:11: warning: left-hand operand of comma expression has no effect [-Wunused-value]
    7 |     stderr, stdout;     // Diagnosed once
      |           ^
main.c:8:7: warning: left-hand operand of comma expression has no effect [-Wunused-value]
    8 |     42, stderr;         // Diagnosed twice
      |       ^
main.c:8:5: warning: statement with no effect [-Wunused-value]
    8 |     42, stderr;         // Diagnosed twice
      |     ^~
main.c:9:12: warning: statement with no effect [-Wunused-value]
    9 |     stderr - stdout;    // Diagnosed once
      |            ^
main.c:10:5: warning: statement with no effect [-Wunused-value]
   10 |     (stderr);           // Diagnosed once
      |     ^
</code>```

Here I've slipped in the assumption that what goes for stderr goes likewise
for stdout, which is vindicated. It's a notable detail that while 42, stderr;
is diagnosed as a statement with no effect, stderr, stdout; is not.

It seems fair to say that gcc does not come across as self-assured about the nature and
limits of the diagnostic immunity it wants to extend to stderr and similarly
qualifying identifiers. This is perhaps understandable, when we probe the
ramifications in the sort of code that nobody writes except to fence with the compiler.

Be that as it may, one would like to be clear about the motivation of this diagnostic
immunity and to know whether gcc can be told to revoke it, so that, e.g. all of
the ineffectual statements I write in a program will be diagnosed as such.

The answer on the second score is Yes:

```<code>$ cat main.c; gcc -Wall -Wsystem-headers -c main.c
#include <stdio.h>

int main(void)
{
    FILE *p;
    42;         // statement with no effect
    p;          // statement with no effect
    stderr;     // statement with no effect
    return 0;
}
main.c: In function ‘main’:
main.c:6:5: warning: statement with no effect [-Wunused-value]
    6 |     42;         // statement with no effect
      |     ^~
main.c:7:5: warning: statement with no effect [-Wunused-value]
    7 |     p;          // statement with no effect
      |     ^
In file included from main.c:1:
main.c:8:5: warning: statement with no effect [-Wunused-value]
    8 |     stderr;     // statement with no effect
      |     ^~~~~~
</code>```

and:

```<code>$ cat main.c; gcc -Wall -Wsystem-headers -c main.c
#include <stdio.h>

int main(void)
{
    stdout;
    stderr;
    stderr, stdout;
    42, stderr;
    stderr - stdout;
    (stderr);
    return 0;
}
In file included from main.c:1:
main.c: In function ‘main’:
main.c:5:5: warning: statement with no effect [-Wunused-value]
    5 |     stdout;
      |     ^~~~~~
main.c:6:5: warning: statement with no effect [-Wunused-value]
    6 |     stderr;
      |     ^~~~~~
main.c:7:11: warning: left-hand operand of comma expression has no effect [-Wunused-value]
    7 |     stderr, stdout;
      |           ^
In file included from main.c:1:
main.c:7:5: warning: statement with no effect [-Wunused-value]
    7 |     stderr, stdout;
      |     ^~~~~~
main.c:8:7: warning: left-hand operand of comma expression has no effect [-Wunused-value]
    8 |     42, stderr;
      |       ^
main.c:8:5: warning: statement with no effect [-Wunused-value]
    8 |     42, stderr;
      |     ^~
main.c:9:12: warning: statement with no effect [-Wunused-value]
    9 |     stderr - stdout;
      |            ^
main.c:10:5: warning: statement with no effect [-Wunused-value]
   10 |     (stderr);
      |     ^
</code>```

And the documentation of -Wsystem-headers
offers the motivating rationale:

-Wsystem-headers

Print warning messages for constructs found in system header files. Warnings from
  system headers are normally suppressed, on the assumption that they usually do not
  indicate real problems and would only make the compiler output harder to read.
  Using this command-line option tells GCC to emit warnings from system headers as
  if they occurred in user code.
  ...

So, stderr, stderr get their diagnostic immunity by virtue of being declared in a system
header, <stdio.h>1. Warnings from system headers are by default assumed to
be spurious.

Before we go about our business, however, its worth appreciating that the documented explanation of
the effect of -Wsystem-headers, and of its absence, does not actually explain
those effects as we observe them. The failure to diagnose

```<code>stderr;     // statement with no effect
</code>```

in our first program in the absence of -Wsystem-headers is not the suppression
of a warning from a system header. It is the suppression of a warning from main.c,
in which that statement is exactly as ineffectual as:

```<code>p;          // statement with no effect
</code>```

And the effect of -Wsystem-headers on the compilation of that program is not
that GCC starts to emit any previously suppressed warning from a system header
as if it occurred in user code. It causes GCC to emit a previously suppressed
warning that occurred in user code all along.

Evidently the real effect of the default -Wno-system-headers includes, at least,
the suppression of certain warnings, in user code or not, when the context

```<code>$ gcc --version
gcc (Ubuntu 9.3.0-10ubuntu2) 9.3.0
...

$ gcc -Wall -c main.c
main.c: In function ‘main’:
main.c:6:5: warning: statement with no effect [-Wunused-value]
    6 |     42;
      |     ^~
main.c:7:5: warning: statement with no effect [-Wunused-value]
    7 |     p;
      |     ^
</code>```0

that would otherwise provoke the warning contains an identifier that was declared
in a system header. The manual tells us how to stop this, but only gestures
at explaining it.

[1] It is not obvious what is meant by system header in the documentation,
but experimentation shows that a file is only a system header in the
appropriate sense if it is a header file installed by GCC.

Body:
Suppose I have a source code like this:

#include <stdio.h>

FILE *p;

int main(void) {
    p;
}

... which will compile (using gcc) without any errors or warnings – unless I turn on -Wall, in which case a statement with no effect warning will be output.

However if the code went like this:

#include <stdio.h>

int main(void) {
    stderr;
}

... no warnings would be shown regardless of -Wall.

Am I missing something here?

gcc version 9.3.0

Body:
This program:

$ cat main.c
#include <stdio.h>

int main(void)
{
    FILE *p;
    42;         // statement with no effect
    p;          // statement with no effect
    stderr;     // statement with no effect
    return 0;
}

might be expected to elicit 3 statement with no effect
diagnostics whenever it elicits any. But as you've discovered,
in the hands of gcc, that is not true.

$ gcc --version
gcc (Ubuntu 9.3.0-10ubuntu2) 9.3.0
...

$ gcc -Wall -c main.c
main.c: In function ‘main’:
main.c:6:5: warning: statement with no effect [-Wunused-value]
    6 |     42;
      |     ^~
main.c:7:5: warning: statement with no effect [-Wunused-value]
    7 |     p;
      |     ^

stderr - which denotes a FILE *, like p - has a free pass for being implicitly
evaluated with no effect.

Notoriously, -Wall does not really enable all warnings. But this free
pass survives to the customary limit of diagnostic rigour:

$ gcc -Wall -Wextra -pedantic -c main.c
main.c: In function ‘main’:
main.c:6:5: warning: statement with no effect [-Wunused-value]
    6 |     42;
      |     ^~
main.c:7:5: warning: statement with no effect [-Wunused-value]
    7 |     p;
      |     ^

We should be clear that this free pass is carried by the identfier
stderr, as distinct from the value it names:-

It is not transferable to another FILE * by making that other one equal to stderr:

$ cat main.c; gcc -Wall -c main.c
#include <stdio.h>

int main(void)
{
    FILE *p = stderr;
    42;
    p;
    return 0;
}

main.c: In function ‘main’:
main.c:6:5: warning: statement with no effect [-Wunused-value]
    6 |     42;
      |     ^~
main.c:7:5: warning: statement with no effect [-Wunused-value]
    7 |     p;
      |     ^

It is not enjoyed by the FILE * that actually is stderr, if we do not refer to it as stderr.

$ cat main.c; gcc -Wall -c main.c
#include <stdio.h>

int main(void)
{
    FILE **p = &stderr;
    42;
    *p;     // a.k.a `stderr`
    return 0;
}

main.c: In function ‘main’:
main.c:6:5: warning: statement with no effect [-Wunused-value]
    6 |     42;
      |     ^~
main.c:7:5: warning: statement with no effect [-Wunused-value]
    7 |     *p;     // a.k.a `stderr`
      |     ^~

But on the other hand, even when stderr is referred to as stderr,
the free pass is forfeit if that identifier is anything less than
the entire context that is evaluated with no effect:

$ cat main.c; gcc -Wall -c main.c
#include <stdio.h>

int main(void)
{
    stdout;             // Undiagnosed
    stderr;             // Undiagnosed
    stderr, stdout;     // Diagnosed once
    42, stderr;         // Diagnosed twice
    stderr - stdout;    // Diagnosed once
    (stderr);           // Diagnosed once
    return 0;
}

main.c: In function ‘main’:
main.c:7:11: warning: left-hand operand of comma expression has no effect [-Wunused-value]
    7 |     stderr, stdout;     // Diagnosed once
      |           ^
main.c:8:7: warning: left-hand operand of comma expression has no effect [-Wunused-value]
    8 |     42, stderr;         // Diagnosed twice
      |       ^
main.c:8:5: warning: statement with no effect [-Wunused-value]
    8 |     42, stderr;         // Diagnosed twice
      |     ^~
main.c:9:12: warning: statement with no effect [-Wunused-value]
    9 |     stderr - stdout;    // Diagnosed once
      |            ^
main.c:10:5: warning: statement with no effect [-Wunused-value]
   10 |     (stderr);           // Diagnosed once
      |     ^

Here I've slipped in the assumption that what goes for stderr goes likewise
for stdout, which is vindicated. It's a notable detail that while 42, stderr;
is diagnosed as a statement with no effect, stderr, stdout; is not.

It seems fair to say that gcc does not come across as self-assured about the nature and
limits of the diagnostic immunity it wants to extend to stderr and similarly
qualifying identifiers. This is perhaps understandable, when we probe the
ramifications in the sort of code that nobody writes except to fence with the compiler.

Be that as it may, one would like to be clear about the motivation of this diagnostic
immunity and to know whether gcc can be told to revoke it, so that, e.g. all of
the ineffectual statements I write in a program will be diagnosed as such.

The answer on the second score is Yes:

$ cat main.c; gcc -Wall -Wsystem-headers -c main.c
#include <stdio.h>

int main(void)
{
    FILE *p;
    42;         // statement with no effect
    p;          // statement with no effect
    stderr;     // statement with no effect
    return 0;
}
main.c: In function ‘main’:
main.c:6:5: warning: statement with no effect [-Wunused-value]
    6 |     42;         // statement with no effect
      |     ^~
main.c:7:5: warning: statement with no effect [-Wunused-value]
    7 |     p;          // statement with no effect
      |     ^
In file included from main.c:1:
main.c:8:5: warning: statement with no effect [-Wunused-value]
    8 |     stderr;     // statement with no effect
      |     ^~~~~~

and:

$ cat main.c; gcc -Wall -Wsystem-headers -c main.c
#include <stdio.h>

int main(void)
{
    stdout;
    stderr;
    stderr, stdout;
    42, stderr;
    stderr - stdout;
    (stderr);
    return 0;
}
In file included from main.c:1:
main.c: In function ‘main’:
main.c:5:5: warning: statement with no effect [-Wunused-value]
    5 |     stdout;
      |     ^~~~~~
main.c:6:5: warning: statement with no effect [-Wunused-value]
    6 |     stderr;
      |     ^~~~~~
main.c:7:11: warning: left-hand operand of comma expression has no effect [-Wunused-value]
    7 |     stderr, stdout;
      |           ^
In file included from main.c:1:
main.c:7:5: warning: statement with no effect [-Wunused-value]
    7 |     stderr, stdout;
      |     ^~~~~~
main.c:8:7: warning: left-hand operand of comma expression has no effect [-Wunused-value]
    8 |     42, stderr;
      |       ^
main.c:8:5: warning: statement with no effect [-Wunused-value]
    8 |     42, stderr;
      |     ^~
main.c:9:12: warning: statement with no effect [-Wunused-value]
    9 |     stderr - stdout;
      |            ^
main.c:10:5: warning: statement with no effect [-Wunused-value]
   10 |     (stderr);
      |     ^

And the documentation of -Wsystem-headers
offers the motivating rationale:

-Wsystem-headers

Print warning messages for constructs found in system header files. Warnings from
  system headers are normally suppressed, on the assumption that they usually do not
  indicate real problems and would only make the compiler output harder to read.
  Using this command-line option tells GCC to emit warnings from system headers as
  if they occurred in user code.
  ...

So, stderr, stderr get their diagnostic immunity by virtue of being declared in a system
header, <stdio.h>1. Warnings from system headers are by default assumed to
be spurious.

Before we go about our business, however, its worth appreciating that the documented explanation of
the effect of -Wsystem-headers, and of its absence, does not actually explain
those effects as we observe them. The failure to diagnose

stderr;     // statement with no effect

in our first program in the absence of -Wsystem-headers is not the suppression
of a warning from a system header. It is the suppression of a warning from main.c,
in which that statement is exactly as ineffectual as:

p;          // statement with no effect

And the effect of -Wsystem-headers on the compilation of that program is not
that GCC starts to emit any previously suppressed warning from a system header
as if it occurred in user code. It causes GCC to emit a previously suppressed
warning that occurred in user code all along.

Evidently the real effect of the default -Wno-system-headers includes, at least,
the suppression of certain warnings, in user code or not, when the context

... identifier ...

that would otherwise provoke the warning contains an identifier that was declared
in a system header. The manual tells us how to stop this, but only gestures
at explaining it.

[1] It is not obvious what is meant by system header in the documentation,
but experimentation shows that a file is only a system header in the
appropriate sense if it is a header file installed by GCC.


答:
```<code>D = Distance_df.to_numpy()
</code>```

Running now D is Distance_df returns True. Both variables refer to the same object.

However, if you do D = Distance_df.copy().to_numpy(), D is Distance_df will return False. They are now different objects.

It's just how Python handles variable references.

Title: Why the dataframe is altered when only df.to_numpy() is involved in the computation?

Body:
D = Distance_df.to_numpy()

Running now D is Distance_df returns True. Both variables refer to the same object.

However, if you do D = Distance_df.copy().to_numpy(), D is Distance_df will return False. They are now different objects.

It's just how Python handles variable references.


问:
geom_line with x-axis in order of appearance
this is the first question I post here, so please excuse if I don't provide all information right away.

I'm trying to build a line graph with two lines:

```<code>y1 <- c(1000,1500,1000,1500,2000,3000,4000)

y2 <- c(1100,1400,900,1500,2000,2500,3500)

x <- c(49,50,51,1,2,49,50)

df <- data.frame(y1,y2,x)
</code>```

Imagine x being calendar weeks, I skipped the weeks between 3 and 48 of the second year.
Now I want to build a line graph, which display the x-axis values (time series) in this order.

First I tried a really simple approach:

```<code>p <- ggplot()

p <- p + geom_line(data=df,aes(x=x,y=y1))

p <- p + geom_line(data=df,aes(x=x,y=y2), color = "red")

p
</code>```

Problem: R sorts the x values and also sums up same week numbers.

I then tried to change the x values to make them unique, e.g. 49/19,50/19, but R still changes the order. Same happens if I use geom_path instead of geom_line.

I then tried to change x to a factor and use x_scale_discrete, but I couldn't figure out, how to do it, either the lines or the x labels were always missing.

I hope you can give me some kind of advice.

Many thanks,

Andre

答:
You can add a prefix of the year to your x value, and we pad it using str_pad() from stringr with a zero, so that they will be sorted from 01 all the way to 52:

```<code>library(tidyr)
library(stringr)
library(ggplot2)

df$week = paste(rep(c("2019","2020"),c(3,4)),
str_pad(df$x,2,pad="0"),sep="_")
</code>```

pivot this long, so that we get a legend:

```<code>pivot_longer(df[,c("week","y1","y2")],-week)
    # A tibble: 14 x 3
   week    name  value
   <chr>   <chr> <dbl>
 1 2019_49 y1     1000
 2 2019_49 y2     1100
 3 2019_50 y1     1500
 4 2019_50 y2     1400
 5 2019_51 y1     1000
 6 2019_51 y2      900
 7 2020_01 y1     1500
 8 2020_01 y2     1500
 9 2020_02 y1     2000
</code>```

Then use this directly in ggplot

```<code>ggplot(pivot_longer(df[,c("week","y1","y2")],-week),
aes(x=week,y=value,group=name,col=name)) +
geom_line() + scale_color_manual(values=c("black","red"))
</code>```

Body:
this is the first question I post here, so please excuse if I don't provide all information right away.

I'm trying to build a line graph with two lines:

y1 <- c(1000,1500,1000,1500,2000,3000,4000)

y2 <- c(1100,1400,900,1500,2000,2500,3500)

x <- c(49,50,51,1,2,49,50)

df <- data.frame(y1,y2,x)

Imagine x being calendar weeks, I skipped the weeks between 3 and 48 of the second year.
Now I want to build a line graph, which display the x-axis values (time series) in this order.

First I tried a really simple approach:

p <- ggplot()

p <- p + geom_line(data=df,aes(x=x,y=y1))

p <- p + geom_line(data=df,aes(x=x,y=y2), color = "red")

p

Problem: R sorts the x values and also sums up same week numbers.

I then tried to change the x values to make them unique, e.g. 49/19,50/19, but R still changes the order. Same happens if I use geom_path instead of geom_line.

I then tried to change x to a factor and use x_scale_discrete, but I couldn't figure out, how to do it, either the lines or the x labels were always missing.

I hope you can give me some kind of advice.

Many thanks,

Andre

Body:
You can add a prefix of the year to your x value, and we pad it using str_pad() from stringr with a zero, so that they will be sorted from 01 all the way to 52:

library(tidyr)
library(stringr)
library(ggplot2)

df$week = paste(rep(c("2019","2020"),c(3,4)),
str_pad(df$x,2,pad="0"),sep="_")

pivot this long, so that we get a legend:

pivot_longer(df[,c("week","y1","y2")],-week)
    # A tibble: 14 x 3
   week    name  value
   <chr>   <chr> <dbl>
 1 2019_49 y1     1000
 2 2019_49 y2     1100
 3 2019_50 y1     1500
 4 2019_50 y2     1400
 5 2019_51 y1     1000
 6 2019_51 y2      900
 7 2020_01 y1     1500
 8 2020_01 y2     1500
 9 2020_02 y1     2000

Then use this directly in ggplot

ggplot(pivot_longer(df[,c("week","y1","y2")],-week),
aes(x=week,y=value,group=name,col=name)) +
geom_line() + scale_color_manual(values=c("black","red"))


问:
Download .xls file using Angular: Unexpected token P in JSON at position 0 at JSON.parse (<anonymous>)
I have the following server method for returning an byte[] for an xls document stored in Azure Blob Storage.

```<code>[FunctionName("ReadBatchFile")]
        public async static Task<HttpResponseMessage> ReadBatchFile([HttpTrigger(AuthorizationLevel.Function, WebRequestMethods.Http.Get, Route = "Agreements/ReadBatchFile")]HttpRequestMessage req, TraceWriter log)
        {
            try
            {
                var fileName = req.GetQueryNameValuePairs()
                   .FirstOrDefault(q => string.Compare(q.Key, "fileName", true) == 0)
                   .Value;
                var response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new ByteArrayContent(await AzureHelpers.ReadFromBlobStorage(fileName));  //returns byte[]
                response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = fileName };
                response.Content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");
                return response;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                req.CreateResponse(HttpStatusCode.InternalServerError);
            }
            return req.CreateResponse(HttpStatusCode.BadRequest);
        }
</code>```

As can be seen from the above, the response.Content is set an ByteArrayContent and my contentType is application/octet-stream.

In Angular, I have the following method in my service to call the above function.

```<code>readBatchFile(fileName: string): Observable<Blob> {
    let endpoint = environment.endpoints.agreement.baseUrl + environment.endpoints.agreement.readBatchFile + "&fileName=" + fileName;
    const httpOptions = {
      headers: new HttpHeaders({ contentType: 'application/octet-stream' })}; //application/vnd.ms-excel   application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    return this.http.get<Blob>(endpoint, httpOptions);
  }
</code>```

Although I am specifying that the contentType is application/octet-stream, and that my get method should return a Blob type, I still get the following error:

Unexpected token P in JSON at position 0↵    at JSON.parse
  ()

Why is Angular still seeing the response from the server as JSON?

Update

Here is my request headers:

```<code>Accept: application/json, text/plain, */*
Authorization: Bearer ...
Origin: http://localhost:4200
Referer: http://localhost:4200/batches
responseType: application/octet-stream
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
</code>```

Response Headers:

```<code>Access-Control-Allow-Origin: *
Cache-Control: no-cache
Content-Disposition: attachment; filename=B4debe034-efc6-416f-8082-422a4122a857_MTN_Upgrade_20181017_T065548.xls
Content-Length: 3011
Content-Type: application/octet-stream
Date: Wed, 17 Oct 2018 06:55:48 GMT
Expires: -1
Pragma: no-cache
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
</code>```

And the Response:

```<code>PKø6QMäH¯3[Content_Types].xmlµÏJ1Æ_eÉU´D¤ÛªU°>ÀÌvCóÌ´¶oo6+"¥z$ßÌ÷ý3_¼köÉÆÐÆM+ÞÖ[ÑC0àbÀVÄr1_RSfµ¢gNwJîÑÉ0¥ÙkÞ¨zT×ÓéÒ10ðà!ó{ì`ç¸Yïu+ %g5pÁRÅL4"Ã]ýanÌ    ÌäDftµzèê4 ¨4$<ÉÖà¿"b×Y&ê/#RF0Ô#²w²VéÁ1ô2?/®êàÔGÌÛ÷·²j"êù·ü*ªevAâ£C:G1*î!£yå\ü<ÁÏoU~ñ   PKäH¯3PKø6QMÚë®'_rels/.relsÏÁ0àWYzc1ájðæVÖe
oïb<xlú÷ûÓ²^æ=Ñ¬"Ë¡U¤kÜÚËî,DiµÈ¢ÔUyÅIÆtúÁô1ºçAõ8ËC6ùYÆ4zÃT£4È÷y~àþÓÉ-À7ºÖ®ÿ±©ëgRmüQñH²ô£eâ/òãhÌ
¼*ùæÁê
PKÚë®'PKø6QMæl($×Sxl/workbook.xmlO½NÄ0~È;ÂpBUÛ`9    é{Hkt]9)åÝx$^ôª
F&ö÷cûûó«9|Ä ÞQgjávWB²Ü{:·0ews®Y.oÌUÔjiaÈy¬µNvÀhÒG¤Â9hriå¬Ù9oñí²¾«ª½&Miðc5í?Yi4}skT4 k«^=Îé÷È¥UºkôîjÝª"±$Muûò>(©}rì^26£5Á>rSèÍêXTÛêîPKæl($×SPKø6QMb¢Ö4xl/_rels/workbook.xml.relsÏjÃ0_Åè¾8é`Q·1èµ@ØJØÆÒÚåík6VR(cdôý>¬åúkÔ2÷1hª]:ýÇÓ+(ÈÀDëÕrKJYaß'VØIoZ³õ4"W1Q(/mÌ#Jis§Ú#v¤uý¢ó·LµqòÆ5 öS¢ÿ°cÛöÞ£ý)È}ùÈH
sGbà:bý]ªPAßY<ReÊ_^M~ú¿âï1ÛI.[ÌÇ¿2úæÚ«PKb¢Ö4PKø6QMÄÎ«hïxl/worksheets/sheet1.xmlËr0F_a_Ðýâ±Iã:ñ®ÓE»¦¶äpwë¢ÔW¨ÀÄ7 Ðù~I
ðïÏßùÃG~Þ±.!@¨b«wYñºOåþó³6o6Uª^ØYiYgql·©Êé£*\ß^<)Ý¥yõ~mÕJoO¹*ÊÀb£Ié²iv´á¥Ú=µìÑ¨dWO!?\JåIVËù.sÕ«ÙFíá#mHÄËy
ÿÌÔÙÞ´j%¿µ~«.6»Ej6öàu=øwìÔ>9Êúü¢²×´thÙêAUêÂ O>êó9Û©k¡!Â\ÇödKÿjºÃø&8jã<J±LFã¸ãÛÑ!Å  $ÆI'·q! ¥
Î)<mâôÇe!8ÀÑÑ8kâìÀ
/³Ñ8oâüg#&¥ «M\\ã p½Clâò§nòHp¡tÒñeóÔ;mÉrnô90U¯+]5q[oO·ã¬»û¾óø½6ÄW]âÉ'PXùîß|tµOÐ.ñì¬K¼øï-;{BÔ*D^DöúìY~@zWH-c    "$§C"z6§«ÞS{@zíezeQ¤£·Jñ¤Rð }¥ø~¥ÓÕÖH_éÒW:½²Í(ÒQJZ¥dR©OxJ¾Rr¿Òéjë¤¯té+^Ùf¹(oÞ£©ûMPfu©Lýeo]ÿPKÄÎ«hïPKø6QM"tÛ4SÎ
xl/styles.xmlR½nÃ ~ÄÞGjUU¶3T²Ô%K:tÅ6ØHp ÀÝWëÐGê+°8Q¥Lw|þ~ð?_ßù~TuBC³Í#nt<xÆû2w~ìØ3æQà+pï½y!Ä5=SÔm´a¾pmõáh;âe´uQ¤$Ùm·ODQ¸ÌaPò5z_àIÊk¸@üNT$K, ÍÀ+¢¶"¡dæ¦âRHy¶Úá(sC½gªp@Kÿ>V`ÐÀD¼Cï,²ÝãZJH®µmÃ,×¿1Ce.÷QaE×§ÆkK½×*v *ïliwÃ¤<Æ=|ð«£y omeÂÒF£µl6¹£§ÆÈé0¨Ù*3ÒÖ®PéYF~vÎI©WQgÅ=øýåÊ£ôþ»~0mG~óhÈåa¿PK"tÛ4SÎPKø6QMPùûxl/sharedStrings.xmlm]k0ÿJÈ}h][Z2è2Ðþ ÇfsÛ¿_ÆØÖË<ÏÄ=±wp8Zð`/9ÓØv4}ÂoõóîÌ2¬rvIcDbþªÁDó£Ø îíÆÎ:È]/pv ZHO"ò(´
g]ù²gßÈþ/1¦1¥Euò2ÆâüÐêZ°Ò®ijÇ2ÛÂRtÇ^TóªzØÌÿºZ¹±ë6#O
ù¥1¾o$h×¾¨Kû¥mñÌj
píä)ÑÃñt^WdT6p åNkq{§þ!ü¦_PKPùûPK-ø6QMäH¯3[Content_Types].xmlPK-ø6QMÚë®'Y_rels/.relsPK-ø6QMæl($×S@xl/workbook.xmlPK-ø6QMb¢Ö4Txl/_rels/workbook.xml.relsPK-ø6QMÄÎ«hïrxl/worksheets/sheet1.xmlPK-ø6QM"tÛ4SÎ
 xl/styles.xmlPK-ø6QMPùû®xl/sharedStrings.xmlPKÂë
</code>```

答:
I resoloved the problem in Angular 9.1.4 by using responseType blob and setting type in BlobPropertyBag later, e.g. for Excel files:</p>

```<code> return this.httpClient.get(url, {
  responseType: 'blob',
  params: queryParams
})
  .pipe(
    map((res: any) => {
      const blob = new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
      return blob;
    })
  );
</code>```

Body:
I have the following server method for returning an byte[] for an xls document stored in Azure Blob Storage.

[FunctionName("ReadBatchFile")]
        public async static Task<HttpResponseMessage> ReadBatchFile([HttpTrigger(AuthorizationLevel.Function, WebRequestMethods.Http.Get, Route = "Agreements/ReadBatchFile")]HttpRequestMessage req, TraceWriter log)
        {
            try
            {
                var fileName = req.GetQueryNameValuePairs()
                   .FirstOrDefault(q => string.Compare(q.Key, "fileName", true) == 0)
                   .Value;
                var response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new ByteArrayContent(await AzureHelpers.ReadFromBlobStorage(fileName));  //returns byte[]
                response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = fileName };
                response.Content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");
                return response;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                req.CreateResponse(HttpStatusCode.InternalServerError);
            }
            return req.CreateResponse(HttpStatusCode.BadRequest);
        }

As can be seen from the above, the response.Content is set an ByteArrayContent and my contentType is application/octet-stream.

In Angular, I have the following method in my service to call the above function.

readBatchFile(fileName: string): Observable<Blob> {
    let endpoint = environment.endpoints.agreement.baseUrl + environment.endpoints.agreement.readBatchFile + "&fileName=" + fileName;
    const httpOptions = {
      headers: new HttpHeaders({ contentType: 'application/octet-stream' })}; //application/vnd.ms-excel   application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    return this.http.get<Blob>(endpoint, httpOptions);
  }

Although I am specifying that the contentType is application/octet-stream, and that my get method should return a Blob type, I still get the following error:

Unexpected token P in JSON at position 0↵    at JSON.parse
  ()

Why is Angular still seeing the response from the server as JSON?

Update

Here is my request headers:

Accept: application/json, text/plain, */*
Authorization: Bearer ...
Origin: http://localhost:4200
Referer: http://localhost:4200/batches
responseType: application/octet-stream
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36

Response Headers:

Access-Control-Allow-Origin: *
Cache-Control: no-cache
Content-Disposition: attachment; filename=B4debe034-efc6-416f-8082-422a4122a857_MTN_Upgrade_20181017_T065548.xls
Content-Length: 3011
Content-Type: application/octet-stream
Date: Wed, 17 Oct 2018 06:55:48 GMT
Expires: -1
Pragma: no-cache
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET

And the Response:

PKø6QMäH¯3[Content_Types].xmlµÏJ1Æ_eÉU´D¤ÛªU°>ÀÌvCóÌ´¶oo6+"¥z$ßÌ÷ý3_¼köÉÆÐÆM+ÞÖ[ÑC0àbÀVÄr1_RSfµ¢gNwJîÑÉ0¥ÙkÞ¨zT×ÓéÒ10ðà!ó{ì`ç¸Yïu+ %g5pÁRÅL4"Ã]ýanÌ    ÌäDftµzèê4 ¨4$<ÉÖà¿"b×Y&ê/#RF0Ô#²w²VéÁ1ô2?/®êàÔGÌÛ÷·²j"êù·ü*ªevAâ£C:G1*î!£yå\ü<ÁÏoU~ñ   PKäH¯3PKø6QMÚë®'_rels/.relsÏÁ0àWYzc1ájðæVÖe
oïb<xlú÷ûÓ²^æ=Ñ¬"Ë¡U¤kÜÚËî,DiµÈ¢ÔUyÅIÆtúÁô1ºçAõ8ËC6ùYÆ4zÃT£4È÷y~àþÓÉ-À7ºÖ®ÿ±©ëgRmüQñH²ô£eâ/òãhÌ
¼*ùæÁê
PKÚë®'PKø6QMæl($×Sxl/workbook.xmlO½NÄ0~È;ÂpBUÛ`9    é{Hkt]9)åÝx$^ôª
F&ö÷cûûó«9|Ä ÞQgjávWB²Ü{:·0ews®Y.oÌUÔjiaÈy¬µNvÀhÒG¤Â9hriå¬Ù9oñí²¾«ª½&Miðc5í?Yi4}skT4 k«^=Îé÷È¥UºkôîjÝª"±$Muûò>(©}rì^26£5Á>rSèÍêXTÛêîPKæl($×SPKø6QMb¢Ö4xl/_rels/workbook.xml.relsÏjÃ0_Åè¾8é`Q·1èµ@ØJØÆÒÚåík6VR(cdôý>¬åúkÔ2÷1hª]:ýÇÓ+(ÈÀDëÕrKJYaß'VØIoZ³õ4"W1Q(/mÌ#Jis§Ú#v¤uý¢ó·LµqòÆ5 öS¢ÿ°cÛöÞ£ý)È}ùÈH
sGbà:bý]ªPAßY<ReÊ_^M~ú¿âï1ÛI.[ÌÇ¿2úæÚ«PKb¢Ö4PKø6QMÄÎ«hïxl/worksheets/sheet1.xmlËr0F_a_Ðýâ±Iã:ñ®ÓE»¦¶äpwë¢ÔW¨ÀÄ7 Ðù~I
ðïÏßùÃG~Þ±.!@¨b«wYñºOåþó³6o6Uª^ØYiYgql·©Êé£*\ß^<)Ý¥yõ~mÕJoO¹*ÊÀb£Ié²iv´á¥Ú=µìÑ¨dWO!?\JåIVËù.sÕ«ÙFíá#mHÄËy
ÿÌÔÙÞ´j%¿µ~«.6»Ej6öàu=øwìÔ>9Êúü¢²×´thÙêAUêÂ O>êó9Û©k¡!Â\ÇödKÿjºÃø&8jã<J±LFã¸ãÛÑ!Å  $ÆI'·q! ¥
Î)<mâôÇe!8ÀÑÑ8kâìÀ
/³Ñ8oâüg#&¥ «M\\ã p½Clâò§nòHp¡tÒñeóÔ;mÉrnô90U¯+]5q[oO·ã¬»û¾óø½6ÄW]âÉ'PXùîß|tµOÐ.ñì¬K¼øï-;{BÔ*D^DöúìY~@zWH-c    "$§C"z6§«ÞS{@zíezeQ¤£·Jñ¤Rð }¥ø~¥ÓÕÖH_éÒW:½²Í(ÒQJZ¥dR©OxJ¾Rr¿Òéjë¤¯té+^Ùf¹(oÞ£©ûMPfu©Lýeo]ÿPKÄÎ«hïPKø6QM"tÛ4SÎ
xl/styles.xmlR½nÃ ~ÄÞGjUU¶3T²Ô%K:tÅ6ØHp ÀÝWëÐGê+°8Q¥Lw|þ~ð?_ßù~TuBC³Í#nt<xÆû2w~ìØ3æQà+pï½y!Ä5=SÔm´a¾pmõáh;âe´uQ¤$Ùm·ODQ¸ÌaPò5z_àIÊk¸@üNT$K, ÍÀ+¢¶"¡dæ¦âRHy¶Úá(sC½gªp@Kÿ>V`ÐÀD¼Cï,²ÝãZJH®µmÃ,×¿1Ce.÷QaE×§ÆkK½×*v *ïliwÃ¤<Æ=|ð«£y omeÂÒF£µl6¹£§ÆÈé0¨Ù*3ÒÖ®PéYF~vÎI©WQgÅ=øýåÊ£ôþ»~0mG~óhÈåa¿PK"tÛ4SÎPKø6QMPùûxl/sharedStrings.xmlm]k0ÿJÈ}h][Z2è2Ðþ ÇfsÛ¿_ÆØÖË<ÏÄ=±wp8Zð`/9ÓØv4}ÂoõóîÌ2¬rvIcDbþªÁDó£Ø îíÆÎ:È]/pv ZHO"ò(´
g]ù²gßÈþ/1¦1¥Euò2ÆâüÐêZ°Ò®ijÇ2ÛÂRtÇ^TóªzØÌÿºZ¹±ë6#O
ù¥1¾o$h×¾¨Kû¥mñÌj
píä)ÑÃñt^WdT6p åNkq{§þ!ü¦_PKPùûPK-ø6QMäH¯3[Content_Types].xmlPK-ø6QMÚë®'Y_rels/.relsPK-ø6QMæl($×S@xl/workbook.xmlPK-ø6QMb¢Ö4Txl/_rels/workbook.xml.relsPK-ø6QMÄÎ«hïrxl/worksheets/sheet1.xmlPK-ø6QM"tÛ4SÎ
 xl/styles.xmlPK-ø6QMPùû®xl/sharedStrings.xmlPKÂë

Body:
I resoloved the problem in Angular 9.1.4 by using responseType blob and setting type in BlobPropertyBag later, e.g. for Excel files:

 return this.httpClient.get(url, {
  responseType: 'blob',
  params: queryParams
})
  .pipe(
    map((res: any) => {
      const blob = new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
      return blob;
    })
  );


问:
How to take ID of a row in gridview when you press a button in a row
```<code><asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" DataKeyNames="IDProject" DataSourceID="SqlDataSource1" GridLines="Vertical" style="margin-top:2rem" Width="1056px">
    <AlternatingRowStyle BackColor="#DCDCDC" />
    <Columns>
        <asp:CommandField ShowEditButton="True" />
        <asp:TemplateField SortExpression="ProjectLeader" HeaderText="Project Leader">
            <ItemTemplate>
                <asp:Label Text='<%# Bind("ProjectLeader") %>' ID="lvProjectLeader"  runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="ProjectName" HeaderText="Project Name" SortExpression="ProjectName" />
        <asp:TemplateField HeaderText="Start date:" SortExpression="StartDate">
            <ItemTemplate>
                <asp:Label Text='<%# Bind("StartDate") %>' ID="lbStartDate" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Client Name" SortExpression="Client name">
            <ItemTemplate>
                <asp:Label Text='<%# Bind("Client name") %>' ID="lbClientName" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Employees">
            <ItemTemplate>
                <asp:Button Text="Open" ID="EmployeesOpen" OnClick="EmployeesOpen_Click" runat="server" CssClass="btn btn-outline-primary" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
    InsertCommand="Insert into Project values(@ProjectName, @ClientID,@ProjectLeader,@StartDate)"
    SelectCommand="select IDProject, ProjectLeader, ProjectName, StartDate, ClientID, Client.Name from Project inner join Client on IDClient = ClientID"
    UpdateCommand="Update Project set ProjectName = @ProjectName where IDProject = @IDProject">
    <InsertParameters>
        <asp:Parameter Name="ProjectName" />
        <asp:Parameter Name="ClientID" />
        <asp:Parameter Name="ProjectLeader" />
        <asp:Parameter Name="StartDate" />
    </InsertParameters>
    <UpdateParameters>
        <asp:Parameter Name="ProjectName" />
        <asp:Parameter Name="IDProject" />
    </UpdateParameters>
</asp:SqlDataSource>
</code>```

I made a gridview table for Projects which has values ProjectName, ClientID, ProjectLeader, StartDate and all the employees that work on that Project. Since i cant fit all the employees that work on a single project inside a small table i made a button inside that column that redirects you to another page where you can see table with all the employees. The employees are in another table in sql and i made third table which connects Projects and employees and it only contains ProjectID and EmployeeID. I have a button inside every row but i cant find a way how to make in code behind so that it takes the id of that project and prints on another page only employees that are working on that project.

```<code>public partial class Project : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void EmployeesOpen_Click(object sender, EventArgs e)
    {
        Response.Redirect("Employees_On_Project.aspx");
    }
}
</code>```

答: You will find what you are looking for here : https://forums.asp.net/t/1957409.aspx?Gridview+get+SelectedRow+in+button+click+event</p>

Body:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" DataKeyNames="IDProject" DataSourceID="SqlDataSource1" GridLines="Vertical" style="margin-top:2rem" Width="1056px">
    <AlternatingRowStyle BackColor="#DCDCDC" />
    <Columns>
        <asp:CommandField ShowEditButton="True" />
        <asp:TemplateField SortExpression="ProjectLeader" HeaderText="Project Leader">
            <ItemTemplate>
                <asp:Label Text='<%# Bind("ProjectLeader") %>' ID="lvProjectLeader"  runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="ProjectName" HeaderText="Project Name" SortExpression="ProjectName" />
        <asp:TemplateField HeaderText="Start date:" SortExpression="StartDate">
            <ItemTemplate>
                <asp:Label Text='<%# Bind("StartDate") %>' ID="lbStartDate" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Client Name" SortExpression="Client name">
            <ItemTemplate>
                <asp:Label Text='<%# Bind("Client name") %>' ID="lbClientName" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Employees">
            <ItemTemplate>
                <asp:Button Text="Open" ID="EmployeesOpen" OnClick="EmployeesOpen_Click" runat="server" CssClass="btn btn-outline-primary" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
    InsertCommand="Insert into Project values(@ProjectName, @ClientID,@ProjectLeader,@StartDate)"
    SelectCommand="select IDProject, ProjectLeader, ProjectName, StartDate, ClientID, Client.Name from Project inner join Client on IDClient = ClientID"
    UpdateCommand="Update Project set ProjectName = @ProjectName where IDProject = @IDProject">
    <InsertParameters>
        <asp:Parameter Name="ProjectName" />
        <asp:Parameter Name="ClientID" />
        <asp:Parameter Name="ProjectLeader" />
        <asp:Parameter Name="StartDate" />
    </InsertParameters>
    <UpdateParameters>
        <asp:Parameter Name="ProjectName" />
        <asp:Parameter Name="IDProject" />
    </UpdateParameters>
</asp:SqlDataSource>

I made a gridview table for Projects which has values ProjectName, ClientID, ProjectLeader, StartDate and all the employees that work on that Project. Since i cant fit all the employees that work on a single project inside a small table i made a button inside that column that redirects you to another page where you can see table with all the employees. The employees are in another table in sql and i made third table which connects Projects and employees and it only contains ProjectID and EmployeeID. I have a button inside every row but i cant find a way how to make in code behind so that it takes the id of that project and prints on another page only employees that are working on that project.

public partial class Project : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void EmployeesOpen_Click(object sender, EventArgs e)
    {
        Response.Redirect("Employees_On_Project.aspx");
    }
}


问:
How to setup Mock to already present object as defaul behavior?
I can do this:

```<code>var alreadyPresentMyClass = GetMyClass();//retrieving MyClass from somewhere

var mock = new Mock<IMyClass>();
mock.Setup(x=> x.Method1()).Callback(alreadyPresentMyClass.Method1);
mock.Setup(x=> x.Method2()).Callback(alreadyPresentMyClass.Method2);
....
mock.Setup(x=> x.Method666()).Throws(new Exception("BAD LUCK")); //this is only method which is throwing error in this test. So the only one I want to setup.
....
mock.Setup(x=> x.Method1000()).Callback(alreadyPresentMyClass.Method1000);
</code>```

How one can remove unnecessary garbage of setuping thousands of methods, and instead setup it based on another object as default, like this:

```<code>var mock = Mock.CreateByAlreadyPresent(GetMyClass());
mock.Setup(x=> x.Method666()).Throws(new Exception("BAD LUCK"));
</code>```

Any thoughts? I can write reflection method myself, but is there already such method?

答:
You would use the property CallBase for that:

```<code>var mock = new Mock<MyClass> { CallBase = true };
mock.Setup(x => x.Method666()).Throws(new Exception("BAD LUCK"));
</code>```

The other methods will have their default behaviour.

Body:
I can do this:

var alreadyPresentMyClass = GetMyClass();//retrieving MyClass from somewhere

var mock = new Mock<IMyClass>();
mock.Setup(x=> x.Method1()).Callback(alreadyPresentMyClass.Method1);
mock.Setup(x=> x.Method2()).Callback(alreadyPresentMyClass.Method2);
....
mock.Setup(x=> x.Method666()).Throws(new Exception("BAD LUCK")); //this is only method which is throwing error in this test. So the only one I want to setup.
....
mock.Setup(x=> x.Method1000()).Callback(alreadyPresentMyClass.Method1000);

How one can remove unnecessary garbage of setuping thousands of methods, and instead setup it based on another object as default, like this:

var mock = Mock.CreateByAlreadyPresent(GetMyClass());
mock.Setup(x=> x.Method666()).Throws(new Exception("BAD LUCK"));

Any thoughts? I can write reflection method myself, but is there already such method?

Body:
You would use the property CallBase for that:

var mock = new Mock<MyClass> { CallBase = true };
mock.Setup(x => x.Method666()).Throws(new Exception("BAD LUCK"));

The other methods will have their default behaviour.


问:
Haproxy TLS terminating and passthrough based on sni
I have similar path for the requests:

```<code>client mydomain.com -> nlb:443 -> haproxy -> cloudfront
client a.mydomain.com -> nlb:443 -> haproxy -> target_group_a
</code>```

Main idea is do tls passthrough for the main domain name and send it to cloudfront without TLS termination. Requests into a.mydomain.com should pass to target_group_a and it should terminate tls. So my config for this is:

```<code>frontend main
    bind *:443
    mode tcp
    option tcplog
    log global

    tcp-request inspect-delay 5s

    acl is_main req_ssl_sni -i "${pDomainName}"
    acl is_a req_ssl_sni -m beg "a"

    tcp-request content accept if { req_ssl_hello_type 1 }

    use_backend main if is_main
    use_backend a if is_a

backend main
    mode tcp
    option ssl-hello-chk
    server cloudfront "${pCloudFrontUrl}:443" check resolvers aws

backend a
    mode tcp
    server local 127.0.0.1:9666 send-proxy

frontend a
    bind *:9666 ssl crt server.pem ca-file ca.pem verify required accept-proxy
    mode http

    default_backend proxy_a

backend proxy_a
    mode http
    server elb "${pServer}:80" check resolvers aws
</code>```

Main record pass successfull and I get CloudFront SSL termination and everything is okay, but not for a.mydomain.com.

Also I tried to watch what SNI Haproxy is capture but I got only capture0: - in logs. I did like (right after tcp inspect line)

```<code>tcp-request content capture req_ssl_sni len 15
log-format "capture0: %[capture.req.hdr(0)]"
</code>```

and it's strange because routing works.

I've tried a lot of possibilities.. For now I get SSL peer handshake failed, the server most likely requires a client certificate to connect error, but if I do listen frontend a on another port and in http mode everyting works fine.

Maybe I miss something basic or not, but I'm stuck on it for ages and maybe someone could help me.

答:
For someone who is suffering or will suffer with that situation, just be sure that you are testing with gnu version of curl (or build it with properly libraries) because it doesn't work for me with BSD curl. My curl version and libs</p>

```<code>curl 7.66.0 (x86_64-apple-darwin17.7.0) libcurl/7.66.0 SecureTransport zlib/1.2.11
Release-Date: 2019-09-11
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: AsynchDNS IPv6 Largefile libz NTLM NTLM_WB SSL UnixSockets
</code>```

Body:
I have similar path for the requests:

client mydomain.com -> nlb:443 -> haproxy -> cloudfront
client a.mydomain.com -> nlb:443 -> haproxy -> target_group_a

Main idea is do tls passthrough for the main domain name and send it to cloudfront without TLS termination. Requests into a.mydomain.com should pass to target_group_a and it should terminate tls. So my config for this is:

frontend main
    bind *:443
    mode tcp
    option tcplog
    log global

    tcp-request inspect-delay 5s

    acl is_main req_ssl_sni -i "${pDomainName}"
    acl is_a req_ssl_sni -m beg "a"

    tcp-request content accept if { req_ssl_hello_type 1 }

    use_backend main if is_main
    use_backend a if is_a

backend main
    mode tcp
    option ssl-hello-chk
    server cloudfront "${pCloudFrontUrl}:443" check resolvers aws

backend a
    mode tcp
    server local 127.0.0.1:9666 send-proxy

frontend a
    bind *:9666 ssl crt server.pem ca-file ca.pem verify required accept-proxy
    mode http

    default_backend proxy_a

backend proxy_a
    mode http
    server elb "${pServer}:80" check resolvers aws

Main record pass successfull and I get CloudFront SSL termination and everything is okay, but not for a.mydomain.com.

Also I tried to watch what SNI Haproxy is capture but I got only capture0: - in logs. I did like (right after tcp inspect line)

tcp-request content capture req_ssl_sni len 15
log-format "capture0: %[capture.req.hdr(0)]"

and it's strange because routing works.

I've tried a lot of possibilities.. For now I get SSL peer handshake failed, the server most likely requires a client certificate to connect error, but if I do listen frontend a on another port and in http mode everyting works fine.

Maybe I miss something basic or not, but I'm stuck on it for ages and maybe someone could help me.

Body:
For someone who is suffering or will suffer with that situation, just be sure that you are testing with gnu version of curl (or build it with properly libraries) because it doesn't work for me with BSD curl. My curl version and libs

curl 7.66.0 (x86_64-apple-darwin17.7.0) libcurl/7.66.0 SecureTransport zlib/1.2.11
Release-Date: 2019-09-11
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: AsynchDNS IPv6 Largefile libz NTLM NTLM_WB SSL UnixSockets


问:
How to get associative array from url query string, javascript
I have url query string

```<code>?filter%5B%22customer_rating_heading%22%5D=customer_rating_6_up%2Ccustomer_rating_7_up%2Ccustomer_rating_9_up&map=1
</code>```

which is

```<code>?filter["customer_rating_heading"]=customer_rating_6_up,customer_rating_7_up,customer_rating_9_up&map=1
</code>```

I want to ask for filter like params.get('filter) and get

```<code>[customer_rating_heading => 'customer_rating_6_up,customer_rating_7_up,customer_rating_9_up' //(later I'll make array from this string)
</code>```

But I don't know how to do this, I tried let query = Object.fromEntries(new URLSearchParams(location.search) but it gives me:

```<code>{filter["customer_rating_heading"]: "customer_rating_6_up,customer_rating_7_up,customer_rating_9_up"
map: "1"}
</code>```

but I can't get filter like query.filter it's always undefined

does anyone know a solution for such problem?

答:
Solution with "match"

let query = Object.fromEntries(new URLSearchParams(location.search))

let firstKey = Object.keys(query)[0];
let found = firstKey.match(/\[(.*)\]/)[1]

let key = found.replace(/\"/g, '');
let value = query[firstKey];

console.log(`${key} => ${value}`)```

Body:
I have url query string

?filter%5B%22customer_rating_heading%22%5D=customer_rating_6_up%2Ccustomer_rating_7_up%2Ccustomer_rating_9_up&map=1

which is

?filter["customer_rating_heading"]=customer_rating_6_up,customer_rating_7_up,customer_rating_9_up&map=1

I want to ask for filter like params.get('filter) and get

[customer_rating_heading => 'customer_rating_6_up,customer_rating_7_up,customer_rating_9_up' //(later I'll make array from this string)

But I don't know how to do this, I tried let query = Object.fromEntries(new URLSearchParams(location.search) but it gives me:

{filter["customer_rating_heading"]: "customer_rating_6_up,customer_rating_7_up,customer_rating_9_up"
map: "1"}

but I can't get filter like query.filter it's always undefined

does anyone know a solution for such problem?


问:
How to prevent direct access to private members outside of getters/setters in the same class?

Challenge

Given a class with a non-trivial getter and some other internal method accessing the same private member field:

Valid Example

class TestType {
    private String value;

    public String getValue() {
        return this.value == null || this.value.isEmpty() ? "default" : this.value;
    }

    public void setValue(String newValue) {
        this.value = newValue;
    }

    public int getValueLength() {
        return this.getValue().length();
    }
}
```

<p>I want to forbid the by-passing of the getter in the <code>getValueLength()</code> method.
The following implementation of <code>getValueLength()</code> should produce some kind of error (unit test failure, checkstyle error, or whatever else can be automated in a generic way):</p>

<h3>Invalid Method</h3>

<pre class="lang-java prettyprint-override"><code>    public int getValueLength() {
        // ERROR: possible NullPointerException
        return this.value.length();
    }
</code>```

Background

In my real-life code there is some lazy-loading going on inside the getter that only loads the actual value when it is being accessed for the first time. Calling getValueLength() first may result in a NullPointerException directly or perform wrong actions based on the missing value.

The motivation is to ensure that future developers don't forget to only use the getter method and never access the member directly. Since this is an isolated issue (i.e. only where this kind of lazy-loaded is being specifically added) it is acceptable if some extra annotations are required, e.g. on the member itself that it should only be accessed in selected methods and those methods to be marked as well -- or specific checkstyle comments enabling/disabling specific rules.

答:
There is not a way to protect a member from its own class, however you can protect a member from its children/subclasses. For example:

class TestParent {
    private String value;

    public String getValue() {
        return this.value == null || this.value.isEmpty() ? "default" : this.value;
    }

    public void setValue(String newValue) {
        this.value = newValue;
    }

}

class TestType extends TestParent {
    public int getValueLength() {
        return this.getValue().length();
    }
}
```

This way TestType can still use setValue() and getValue(), but trying to directly access this.value will not work because value has private access in TestParent

Body:
Challenge

Given a class with a non-trivial getter and some other internal method accessing the same private member field:

Valid Example

class TestType {
    private String value;

    public String getValue() {
        return this.value == null || this.value.isEmpty() ? "default" : this.value;
    }

    public void setValue(String newValue) {
        this.value = newValue;
    }

    public int getValueLength() {
        return this.getValue().length();
    }
}

I want to forbid the by-passing of the getter in the getValueLength() method.
The following implementation of getValueLength() should produce some kind of error (unit test failure, checkstyle error, or whatever else can be automated in a generic way):

Invalid Method

    public int getValueLength() {
        // ERROR: possible NullPointerException
        return this.value.length();
    }

Background

In my real-life code there is some lazy-loading going on inside the getter that only loads the actual value when it is being accessed for the first time. Calling getValueLength() first may result in a NullPointerException directly or perform wrong actions based on the missing value.

The motivation is to ensure that future developers don't forget to only use the getter method and never access the member directly. Since this is an isolated issue (i.e. only where this kind of lazy-loaded is being specifically added) it is acceptable if some extra annotations are required, e.g. on the member itself that it should only be accessed in selected methods and those methods to be marked as well -- or specific checkstyle comments enabling/disabling specific rules.

Body:
There is not a way to protect a member from its own class, however you can protect a member from its children/subclasses. For example:

class TestParent {
    private String value;

    public String getValue() {
        return this.value == null || this.value.isEmpty() ? "default" : this.value;
    }

    public void setValue(String newValue) {
        this.value = newValue;
    }

}

class TestType extends TestParent {
    public int getValueLength() {
        return this.getValue().length();
    }
}

This way TestType can still use setValue() and getValue(), but trying to directly access this.value will not work because value has private access in TestParent


问:
iOS Missing or Invalid Signature: The bundle is not signed using an Apple Submission Certificate
I have been trying to sign my iOS app for about a week now and when I attempt to submit to the app store through Xcode and through Application Loader I keep running into this error:

Application Loader

Xcode:

I am building the app with the Apache Cordova tools for Visual Studio and i have tried both building the .ipa file through visual studio under the 'release' setting and also using on the project files built by the 'remotebuild' tool on a mac to create a new Xcode project and then trying to archive and submit it to the app store that way.

In the Xcode situation, i have tried the solutions given in this question Failed to submit app to iTunes Store and i have made sure that the bundle ID of the app matches the bundle ID of the provisioning profile.  When I run the validation and export tasks in the archive organizer they both work fine but i cannot get past this error despite that.

When i try to publish through visual studio, I am building the app with the 'release' setting so there is a .ipa file within the app's directories and then i'm transferring the files of my PC to my Mac with a flash drive, taking the newly created .ipa file, and submitting it through Application loader and it is giving me the same exact error.  Does anyone have any idea how to verify or manually sign an app with a provisioning profile or can they recommend a fix to this bug?

EDIT:
I believe I have the correct keys in my keychain

答: This can also happen if you are trying to upload and submit a build created with xcodebuild after an Xcode or OS X version update if you haven't installed the latest Xcode components on the your machine or build server (and didn't use the -runFirstLaunch parameter).


问:
How to dynamically generate mathematica code?
I want to make a mini programming language in mma. From a textfile to Module(s) in a Package. Ideally I should be able to generate the package and modules from within Mathematica by functions in another package.

Question:
Is this possible? I am looking for a reference or an example to get this started.

EDIT:
For example:

Imagine a memory bank with n integer typed registers.

The instructions are:

1   Z(n)

2   C(m,n)

3   J(m,n,q)

4   S(n)

Each line has an address. First line 1, second 2, etc.
Z(n) store 0 in register n.
C(m,n) store value of register m in register n.
J(m,n,q) if value register m equals value of register n then jump to line with address q.
S(n) add 1 to value in register n.

Then given two working programs P and Q I want to generate the concatenated program P+Q.

Then given two working programs P and Q I want to generate the substitution Q after P.

Finally I want to start experimenting with recursion... the purpose of this 'mini-project'.

答:
Your question has several parts. First, if you want to use some non-mma syntax for your language, you need to make a parser from your language to mma expression (AST of your code). I will leave this one out (since this is a separate topic) and assume that you are willing to use mma syntax or have means to transfer your program to some mma expression.

Regarding the mma code generation, Mathematica is very well suited for it since it embraces the code-is-data paradigm. The hardest part here is the evaluation control - we want to make sure that none of our generated code pieces evaluates during the code-generation process. The standard techniques of evaluation control can be successfully used for that, but this will generally make things rather complicated. I will illustrate one technique of mma code generation, which is not the best/most powerful  one, but the easiest.

Consider a toy language created by these definitions:

```<code>SetAttributes[testSet, HoldFirst];
SetAttributes[testIf, HoldRest];
SetAttributes[testVar, HoldAll];
SetAttributes[module, HoldAll];
SetAttributes[{package, inContext}, HoldRest];
testPlus[x_, y_] := Plus[x, y];
testTimes[x_, y_] := Times[x, y];
testDivide[x_, y_] := If[y == 0, Inf, Times[x, Power[y, -1]]];
testPower[x_, y_] := If[x == 0 && y < 0, Inf, Power[x, y]];
testSet[HoldPattern[testVar[x_]], expr_] := Set[x, expr];
testVar[x_] := If[ValueQ[x], x, Throw[$Failed, {"varundef", x}]];
testIf[cond_, expr_] := If[cond, expr];
testIf[cond_, expr_, else_] := If[cond, expr, else];
module[{vars__}, body_] := Module[{vars}, body];
package[name_, code_] := (BeginPackage[name]; code; EndPackage[]);
inContext[name_, code_] := (Begin[name]; code; End[]);
</code>```

Here is a small code snippet in this new language (wrapped in Hold):

```<code>cd =
Hold[module[{a}, testSet[testVar[a],
  testPlus[testTimes[testTimes[testPlus[1, 2],
    testPower[testPlus[3, 4], -1]], testPlus[5, 6]], -7]]; testVar[a]]]
</code>```

It corresponds to this mma code:

```<code>Module[{a},a = (1 + 2)/(3 + 4)*(5 + 6) - 7; a]
</code>```

Our code-generator is based on a very simple idea - we will repeatedly apply local rules to our held code. The local rules will be extracted from the definitions of our functions, like so:

```<code>ClearAll[expansionRules];
expansionRules[heads : {__Symbol}] := Flatten[DownValues /@ heads]
</code>```

We need to supply a list of heads for our language. I will do that manually, but it is easy to automate, by creating custom assignment operators.

```<code>allHeadsToExpand[] := {testIf, testVar, testPlus, testTimes, testDivide,
      testPower, testSet, testIf,module,package, inContext}
</code>```

Now, we generate our code:

```<code>In[195]:= expanded = cd//.expansionRules[allHeadsToExpand[]]

Out[195]=
 Hold[Module[{a},
    a = ((1 + 2) If[3 + 4 == 0 && -1 < 0, Inf, 1/(3 + 4)]) (5 + 6) - 7;
    If[ValueQ[a], a, Throw[$Failed, {"varundef", a}]]]]
</code>```

To execute it, you can simply use ReleaseHold:

```<code>In[197]:= ReleaseHold[expanded]

Out[197]= -(16/7)
</code>```

The advantage of our construction is that we can also execute our AST directly:

```<code>In[198]:= ReleaseHold[cd]

Out[198]= -(16/7)
</code>```

To save this to a package, you can simply use Put command. It is also easy to extend the language in any way you want. Of course, the way the code in this language looks is not pretty, since it is essentially the AST expressed as mma expression. To make it prettier, you'd need to introduce your own syntax and write a parser from it to mma AST, but that is another story.

EDIT

Regarding automating of code-generation and saving the generated code into a package: here are a couple of utilities to do that.

```<code>Clear[generateCode];
generateCode[code_Hold] :=
  code //. expansionRules[allHeadsToExpand[]] //.
   HoldPattern[
      CompoundExpression[left___, CompoundExpression[middle___], right___]] :>
       (left; middle; right);

Clear[formatCode];
formatCode[code_Hold] :=
  StringReplace[Function[Null, ToString[Unevaluated[#], InputForm], HoldAll] @@
     code, ";" :> ";\n"];

Clear[saveCode];
saveCode[file_, generatedCode_] :=
 With[{result = BinaryWrite[file, formatCode@generatedCode]},
   Close[file];
   result];
</code>```

Here is the same example but placed in a package:

```<code>cdp = Hold[
   package["myPackage`",
     inContext["`Private`",
       module[{a},
         testSet[testVar[a],
           testPlus[testTimes[testTimes[testPlus[1, 2],
            testPower[testPlus[3, 4], -1]], testPlus[5, 6]], -7]];
         testVar[a]]]]]
</code>```

We generate and save the code as follows:

```<code>In[101]:= file = FileNameJoin[{"C:","Temp","myPackage.m"}]
Out[101]= C:\Temp\myPackage.m

In[106]:= saved =saveCode[file,generateCode[cdp]]
Out[106]= C:\Temp\myPackage.m
</code>```

We can Import it to test:

```<code>In[107]:= Import[file,"Text"]

Out[107]=
BeginPackage["myPackage`"];
 Begin["`Private`"];
 Module[{a}, a = ((1 + 2)*If[3 + 4 == 0 && -1 < 0, Inf, (3 + 4)^(-1)])*(5 + 6) - 7;
  If[ValueQ[a], a, Throw[$Failed, {"varundef", a}]]];
 End[];
 EndPackage[]
</code>```

EDIT 2

Regarding the way the code in your language will look, you can make this prettier without going all the way to create your own parser, by using the Notation package to alter the way you can input code and Format/FormatValues to control how it is rendered by the FrontEnd.

Body:
Your question has several parts. First, if you want to use some non-mma syntax for your language, you need to make a parser from your language to mma expression (AST of your code). I will leave this one out (since this is a separate topic) and assume that you are willing to use mma syntax or have means to transfer your program to some mma expression.

Regarding the mma code generation, Mathematica is very well suited for it since it embraces the code-is-data paradigm. The hardest part here is the evaluation control - we want to make sure that none of our generated code pieces evaluates during the code-generation process. The standard techniques of evaluation control can be successfully used for that, but this will generally make things rather complicated. I will illustrate one technique of mma code generation, which is not the best/most powerful  one, but the easiest.

Consider a toy language created by these definitions:

SetAttributes[testSet, HoldFirst];
SetAttributes[testIf, HoldRest];
SetAttributes[testVar, HoldAll];
SetAttributes[module, HoldAll];
SetAttributes[{package, inContext}, HoldRest];
testPlus[x_, y_] := Plus[x, y];
testTimes[x_, y_] := Times[x, y];
testDivide[x_, y_] := If[y == 0, Inf, Times[x, Power[y, -1]]];
testPower[x_, y_] := If[x == 0 && y < 0, Inf, Power[x, y]];
testSet[HoldPattern[testVar[x_]], expr_] := Set[x, expr];
testVar[x_] := If[ValueQ[x], x, Throw[$Failed, {"varundef", x}]];
testIf[cond_, expr_] := If[cond, expr];
testIf[cond_, expr_, else_] := If[cond, expr, else];
module[{vars__}, body_] := Module[{vars}, body];
package[name_, code_] := (BeginPackage[name]; code; EndPackage[]);
inContext[name_, code_] := (Begin[name]; code; End[]);

Here is a small code snippet in this new language (wrapped in Hold):

cd =
Hold[module[{a}, testSet[testVar[a],
  testPlus[testTimes[testTimes[testPlus[1, 2],
    testPower[testPlus[3, 4], -1]], testPlus[5, 6]], -7]]; testVar[a]]]

It corresponds to this mma code:

Module[{a},a = (1 + 2)/(3 + 4)*(5 + 6) - 7; a]

Our code-generator is based on a very simple idea - we will repeatedly apply local rules to our held code. The local rules will be extracted from the definitions of our functions, like so:

ClearAll[expansionRules];
expansionRules[heads : {__Symbol}] := Flatten[DownValues /@ heads]

We need to supply a list of heads for our language. I will do that manually, but it is easy to automate, by creating custom assignment operators.

allHeadsToExpand[] := {testIf, testVar, testPlus, testTimes, testDivide,
      testPower, testSet, testIf,module,package, inContext}

Now, we generate our code:

In[195]:= expanded = cd//.expansionRules[allHeadsToExpand[]]

Out[195]=
 Hold[Module[{a},
    a = ((1 + 2) If[3 + 4 == 0 && -1 < 0, Inf, 1/(3 + 4)]) (5 + 6) - 7;
    If[ValueQ[a], a, Throw[$Failed, {"varundef", a}]]]]

To execute it, you can simply use ReleaseHold:

In[197]:= ReleaseHold[expanded]

Out[197]= -(16/7)

The advantage of our construction is that we can also execute our AST directly:

In[198]:= ReleaseHold[cd]

Out[198]= -(16/7)

To save this to a package, you can simply use Put command. It is also easy to extend the language in any way you want. Of course, the way the code in this language looks is not pretty, since it is essentially the AST expressed as mma expression. To make it prettier, you'd need to introduce your own syntax and write a parser from it to mma AST, but that is another story.

EDIT

Regarding automating of code-generation and saving the generated code into a package: here are a couple of utilities to do that.

Clear[generateCode];
generateCode[code_Hold] :=
  code //. expansionRules[allHeadsToExpand[]] //.
   HoldPattern[
      CompoundExpression[left___, CompoundExpression[middle___], right___]] :>
       (left; middle; right);

Clear[formatCode];
formatCode[code_Hold] :=
  StringReplace[Function[Null, ToString[Unevaluated[#], InputForm], HoldAll] @@
     code, ";" :> ";\n"];

Clear[saveCode];
saveCode[file_, generatedCode_] :=
 With[{result = BinaryWrite[file, formatCode@generatedCode]},
   Close[file];
   result];

Here is the same example but placed in a package:

cdp = Hold[
   package["myPackage`",
     inContext["`Private`",
       module[{a},
         testSet[testVar[a],
           testPlus[testTimes[testTimes[testPlus[1, 2],
            testPower[testPlus[3, 4], -1]], testPlus[5, 6]], -7]];
         testVar[a]]]]]

We generate and save the code as follows:

In[101]:= file = FileNameJoin[{"C:","Temp","myPackage.m"}]
Out[101]= C:\Temp\myPackage.m

In[106]:= saved =saveCode[file,generateCode[cdp]]
Out[106]= C:\Temp\myPackage.m

We can Import it to test:

In[107]:= Import[file,"Text"]

Out[107]=
BeginPackage["myPackage`"];
 Begin["`Private`"];
 Module[{a}, a = ((1 + 2)*If[3 + 4 == 0 && -1 < 0, Inf, (3 + 4)^(-1)])*(5 + 6) - 7;
  If[ValueQ[a], a, Throw[$Failed, {"varundef", a}]]];
 End[];
 EndPackage[]

EDIT 2

Regarding the way the code in your language will look, you can make this prettier without going all the way to create your own parser, by using the Notation package to alter the way you can input code and Format/FormatValues to control how it is rendered by the FrontEnd.


问:
Is there a way to update a Google AutoML Translation model without having to change the API call for translation?
I am pretty new to using Google AutoML and I was wondering what the best practice was in the following scenario.

My goal is to update a Google AutoML Translate model without having to change the API call to get translations, and I am not sure if this is possible.

Currently the only way to update a AutoML Translate model is to create a new model, base it on the old one, and train it on the new examples (This is at least what seems to be the case). And when you make an API request to get a translation, you must specify which model you want to use by giving the identifier of that model. Because the old version of the model and the new version have different identifiers does this mean that every API call must be changed so that it uses the new model? Is there any way around changing the API call?

答:
First of all, indeed the only way to update an AutoML Translate model is to create a new one, base it on the old one, and train it with the new examples. This is a clear security measure so you do not loose the old model in the process. Although on paper training with more sentences should help the model accuracy/performance, doing so might hinder the accuracy instead.

Second of all, the API call needs to be changed accordingly. You could code the API call in a way that uses the last model submitted so it does not need to be changed every time you update the model.

To do so, the first idea that comes to my mind is using a cloud function that gets triggered once a model is trained/created and stores the model-id in a bucket in GCS that the code performing the API calls recovers.

Nevertheless, the model performance should be assessed before assigning the translation calls from one model to the other, so I do not recommend simply changing it to the newest version without additional checks unless it is for testing purposes.


问:
Force VS Code to open new files as the same type as current file open
I could have sworn this was added as a feature a while back, but has now been removed with a recent update? Example, if I have my_file.ts open, and I go to new => file, I want it to create Untitled-1.ts as a TS file instead of plain text. I can't find it in the settings and I don't even know what to search for really. I'm sure it's in the settings somewhere.</p>

答:
Found it. It's files.defaultLanguage. If you set it as ${activeEditorLanguage} it will do what you've described. I wouldn't aware of this option before :)

Reference


问:
AttributeError: 'str' object has no attribute 'json'
I wrote little script on python 3.7 to receive actual browser version

Here is it:

```<code>import json

def json_open():
    file_json = open('/Users/user/PycharmProjects/Test/configuration.json')
    return json.load(file_json)

def get_last_version(browser_name):
    f = json_open()
    res = (f['global']['link_to_latest_browser_version'])
    last_version = repr(res.json()['latest']['client'][browser_name]['version'])
    #print(last_version[1:-1])
    return last_version[1:-1]
</code>```

Also, json file exists, but it does not matter now.

Received:

```<code>AttributeError: 'str' object has no attribute 'json'.
</code>```

In row

```<code>last_version = repr(res.json()['latest']['client'][browser_name]['version'])
</code>```

Please, tell me what is my mistake?

答:
Your "res" variable is of type string.
Strings do not have an attribute called json.
So res.json() is invalid.</p>

Body:
I wrote little script on python 3.7 to receive actual browser version

Here is it:

import json

def json_open():
    file_json = open('/Users/user/PycharmProjects/Test/configuration.json')
    return json.load(file_json)

def get_last_version(browser_name):
    f = json_open()
    res = (f['global']['link_to_latest_browser_version'])
    last_version = repr(res.json()['latest']['client'][browser_name]['version'])
    #print(last_version[1:-1])
    return last_version[1:-1]

Also, json file exists, but it does not matter now.

Received:

AttributeError: 'str' object has no attribute 'json'.

In row

last_version = repr(res.json()['latest']['client'][browser_name]['version'])

Please, tell me what is my mistake?


问:
How can I add pandas "match" based on column list values and value in additional column?
I have a dataframe that contains a column with a list of identifiers called Multiple_IDS and a column called ID. Now, I would like to create an additional column called "Match" that tells weather an ID was contained in the Multiple_IDs column or not. The ouput should be an additional column called Match that contains True or False values. Here some sample input data:

```<code>data = {'ID':[2128441, 2128447, 2128500], 'Multiple_IDs':["2128442, 2128443, 2128444, 2128441", "2128446, 2128447", "2128503, 2128508"]}
df = pd.DataFrame(data)
</code>```

The list has the datatype "object".

The desire output would then be this according to the input data provided above.

I know I can achieve this using explode and then comparing the values but I am wondering if there something more elegant ?

答:
What I will do </p>

```<code>s=pd.DataFrame(df.Multiple_IDs.str.split(', ').tolist(),index=df.index).eq(df.ID.astype(str),axis=0).any(1)
Out[10]:
0     True
1     True
2    False
dtype: bool
df['Match']=s
</code>```

Body:
I have a dataframe that contains a column with a list of identifiers called Multiple_IDS and a column called ID. Now, I would like to create an additional column called "Match" that tells weather an ID was contained in the Multiple_IDs column or not. The ouput should be an additional column called Match that contains True or False values. Here some sample input data:

data = {'ID':[2128441, 2128447, 2128500], 'Multiple_IDs':["2128442, 2128443, 2128444, 2128441", "2128446, 2128447", "2128503, 2128508"]}
df = pd.DataFrame(data)

The list has the datatype "object".

The desire output would then be this according to the input data provided above.

I know I can achieve this using explode and then comparing the values but I am wondering if there something more elegant ?

Body:
What I will do

s=pd.DataFrame(df.Multiple_IDs.str.split(', ').tolist(),index=df.index).eq(df.ID.astype(str),axis=0).any(1)
Out[10]:
0     True
1     True
2    False
dtype: bool
df['Match']=s


问:
Is it possible to install the latests Firebase Crashlytics iOS SDK manually?
I am trying to migrate Crashlytics from Fabric to Firebase and in the documentation Upgrade to the Firebase Crashlytics SDK there is only a description for Cocoapods. I am not using Cocoapods in my project and don't want to, but I haven't found any alternative for installing the Firebase Crashlytics SDK. Does anyone has the same issue and found already a solution?

I have found this post from Saravana How to add Firebase Crashlytics to iOS app, but it is over one year old, so the SDK offered there is probably not the latest one.

This is my first question, please be kind :) And thanks a lot in advance!

答: Firebase is also distributed as a downloadable zip and via an experimental Carthage distribution.</p>