问:
Angular HTTP ProgressEvent only tracked in HTTPInterceptor and not in actual API call
I have tried tips from several posts. But there is no success. I am trying to trace the progress of file upload but unable to track the progress in actual API call, though I can trace the same in two interceptors that I have added. Strangely if I remove the interceptors still progress events are not reported. Below the code snippet for my API call. We are using Angular 9 and trying to upload file to google bucket via a signed URL.
I tried a JS XHRRequest to trace the progress events and it works here as well.

```<code>public upload(file: File, url: string): Observable<any> {
  const formData: FormData = new FormData();
  formData.append('file', file, file.name);

  const req = new HttpRequest('PUT', url, formData, {
    reportProgress: true,
    headers: new HttpHeaders().set('Content-Type', file.type)
  });
  //return this.httpClient.request(req) // <-- I have tried this as well as per documentation
  return this.httpClient
    .put(url, formData, {
       reportProgress: true,
       observe: 'events'
    })
    .pipe(
      tap((event) => {
        console.log(event); //<-- Progress Not reported here.
        return event;
      })
      // catchError(this.handleError(file))
    );
}
</code>```

Progress events are however reported in interceptor. I have two such interceptors to work with both handle Errors. One is HTTPErrorInterceptor and other is AuthErrorInterceptor.
Originally interceptors looks like this:

```<code>intercept(
    request: HttpRequest<Record<string, string> | null>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        if (this.authService.isAuthTokenExpired() && error.status === 401) {
          this.authService.loginRedirect();
        }
        return throwError(error);
      })
    );
</code>```

But if add tap operator in pipe I can see the progress reported inside same in interceptors only.

```<code> tap((ev: HttpEvent<any>) => {
   if (ev.type === HttpEventType.UploadProgress) {
    const percentDone = Math.round((100 * ev.loaded) / ev.total);
    console.log(`File is ${percentDone}% uploaded.`);
   }
   return of(ev);
}),
</code>```

Honestly I am unable to understand where is the miss and how to propagate this progress events to actual API call. If anyone can point out the mistake from above code that will be of great help.

答:
You will need a low-level HttpRequest for this as put method only listens to Response event:
https://angular.io/guide/http#tracking-and-showing-request-progress

const req = new HttpRequest('POST', '/upload/file', file, {
  reportProgress: true
});
// The `HttpClient.request` API produces a raw event stream
// which includes start (sent), progress, and response events.
return this.http.request(req).pipe(
  map(event => this.getEventMessage(event, file)),
  tap(message => this.showProgress(message)),
  last(), // return last (completed) message to caller
  catchError(this.handleError(file))
);
```

Body:
I have tried tips from several posts. But there is no success. I am trying to trace the progress of file upload but unable to track the progress in actual API call, though I can trace the same in two interceptors that I have added. Strangely if I remove the interceptors still progress events are not reported. Below the code snippet for my API call. We are using Angular 9 and trying to upload file to google bucket via a signed URL.
I tried a JS XHRRequest to trace the progress events and it works here as well.

public upload(file: File, url: string): Observable<any> {
  const formData: FormData = new FormData();
  formData.append('file', file, file.name);

  const req = new HttpRequest('PUT', url, formData, {
    reportProgress: true,
    headers: new HttpHeaders().set('Content-Type', file.type)
  });
  //return this.httpClient.request(req) // <-- I have tried this as well as per documentation
  return this.httpClient
    .put(url, formData, {
       reportProgress: true,
       observe: 'events'
    })
    .pipe(
      tap((event) => {
        console.log(event); //<-- Progress Not reported here.
        return event;
      })
      // catchError(this.handleError(file))
    );
}

Progress events are however reported in interceptor. I have two such interceptors to work with both handle Errors. One is HTTPErrorInterceptor and other is AuthErrorInterceptor.
Originally interceptors looks like this:

intercept(
    request: HttpRequest<Record<string, string> | null>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        if (this.authService.isAuthTokenExpired() && error.status === 401) {
          this.authService.loginRedirect();
        }
        return throwError(error);
      })
    );

But if add tap operator in pipe I can see the progress reported inside same in interceptors only.

 tap((ev: HttpEvent<any>) => {
   if (ev.type === HttpEventType.UploadProgress) {
    const percentDone = Math.round((100 * ev.loaded) / ev.total);
    console.log(`File is ${percentDone}% uploaded.`);
   }
   return of(ev);
}),

Honestly I am unable to understand where is the miss and how to propagate this progress events to actual API call. If anyone can point out the mistake from above code that will be of great help.


来源: stackexchange

问:
How to use REF datatype in PL/SQL code or in SQL statements?
In my understanding REF is an datatype which can store reference to an Object.

I have created a type person.

```<code>CREATE TYPE person AS OBJECT(
    names   VARCHAR2(20),
    age     NUMBER(4, 2)
);
</code>```

I created a table of it and inserted a row.

```<code>create table person_table of person;
</code>```
```<code>insert into person_table values ('Sam', 24);
</code>```

Can anyone please tell how I can use REF to store the reference of the inserted object in some other table or PL/SQL block or use REF in any SQL statement?

答:
You need to simply use REF in table creation which will store reference of the PERSON type as follows:

```<code>CREATE TABLE EMPLOYEE
(PERSON_DETAILS REF PERSON);
</code>```

and you can insert data into this table using REF keyword by pointing to the PERSON_TABLE which is itself table of PERSON type as follows:

```<code>INSERT INTO EMPLOYEE
SELECT REF(P) FROM PERSON_TABLE P WHERE NAMES = 'Sam';
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In my understanding REF is an datatype which can store reference to an Object.

I have created a type person.

CREATE TYPE person AS OBJECT(
    names   VARCHAR2(20),
    age     NUMBER(4, 2)
);

I created a table of it and inserted a row.

create table person_table of person;

insert into person_table values ('Sam', 24);

Can anyone please tell how I can use REF to store the reference of the inserted object in some other table or PL/SQL block or use REF in any SQL statement?

Body:
You need to simply use REF in table creation which will store reference of the PERSON type as follows:

CREATE TABLE EMPLOYEE
(PERSON_DETAILS REF PERSON);

and you can insert data into this table using REF keyword by pointing to the PERSON_TABLE which is itself table of PERSON type as follows:

INSERT INTO EMPLOYEE
SELECT REF(P) FROM PERSON_TABLE P WHERE NAMES = 'Sam';


Title: How to for loop on pandas dataframe by grouping the values by dates then extracting the filtered group to be saved as a new dataframe

Body:
I've been trying to find out how I can efficiently group the rows in my dataframe using a for loop based on the column ' Date (UTC)'. For every similar date, I need to extract all the rows with that date and save it to a new dataframe. Below is the sample of my data.

data = pd.read_csv('MasterData.csv')
print(data)

    Date (UTC)    Magnitude    Vector Station
0   2020-01-05    26.474679 -0.730455   A
1   2020-01-05    30.746291  0.020503   B
2   2020-01-05    37.829401  0.252316   C
3   2020-01-05  1904.611372  0.977388   D
4   2020-01-19    38.441813 -0.044736   B
5   2020-01-19    31.067455  0.419826   C
6   2020-01-19    15.972198 -0.592661   A
7   2020-01-19  1261.038155  0.977394   D
8   2020-02-02    36.628855  0.518991   B
9   2020-02-02    29.724500 -0.818267   A
10  2020-02-02   673.138440  0.977481   D
11  2020-02-02    13.119385  0.327124   C
12  2020-02-16     7.864772  0.311480   C
13  2020-02-16   312.438088  0.977436   D
14  2020-02-16     7.422883 -0.735439   A
15  2020-02-16    30.693853  0.079296   B
16  2020-02-16     4.722992 -0.434787   E
17  2020-03-01    27.501789  0.393106   C
18  2020-03-01   479.118903  0.977505   D
19  2020-03-01    10.022614 -0.887412   A
20  2020-03-01     4.171703 -0.338138   E
21  2020-03-01    26.057769  0.307710   B
22  2020-03-15   580.257861  0.977406   D
23  2020-03-15    17.528845 -0.927358   A
24  2020-03-15     2.963810  0.222188   E
25  2020-03-15    17.535629 -0.052694   B
26  2020-03-15    38.560337  0.283103   C
27  2020-03-29   943.100243  0.977399   D
28  2020-03-29    36.560799 -0.105109   B
29  2020-03-29    17.055374 -0.677127   A
30  2020-03-29     4.614302 -0.315060   E
31  2020-04-12  1095.538437  0.977369   D
32  2020-04-12     6.650060  0.660921   E
33  2020-04-12    55.495947 -0.316548   B
34  2020-04-12    16.269334 -0.614226   A

print(data.dtypes)

 Date (UTC)     object
Magnitude      float64
Vector         float64
Station         object
dtype: object

The expected output is that for every new dataframe saved from the filtered data, I need to plot the magnitude and vector of all the stations in a given date using matplotlib quiver.

Body:
It's possible to create an empty dictionary and then group the dates into groups and do a loop process.

df_dict = {}
for name, group in df.groupby('Date_UTC'):
    df_dict[name] = group

df_dict.values()
    dict_values([    Date_UTC    Magnitude Vector Station
0 2020-01-05    26.474679     -0.730455A
1 2020-01-05    30.746291      0.020503B
2 2020-01-05    37.829401      0.252316C
3 2020-01-05  1904.611372      0.977388D,     Date_UTC    Magnitude Vector Station
4 2020-01-19    38.441813     -0.044736B
5 2020-01-19    31.067455      0.419826C
6 2020-01-19    15.972198     -0.592661A
7 2020-01-19  1261.038155      0.977394D,      Date_UTC   Magnitude Vector Station
 ...])

You can also get simply grouping

for name, group in df.groupby('Date_UTC'):
    print('split_date:', name)
    print(group)

    split_date: 2020-01-05 00:00:00
    Date_UTC    Magnitude Vector Station
0 2020-01-05    26.474679     -0.730455A
1 2020-01-05    30.746291      0.020503B
2 2020-01-05    37.829401      0.252316C
3 2020-01-05  1904.611372      0.977388D
split_date: 2020-01-19 00:00:00
    Date_UTC    Magnitude Vector Station
4 2020-01-19    38.441813     -0.044736B
5 2020-01-19    31.067455      0.419826C
6 2020-01-19    15.972198     -0.592661A
7 2020-01-19  1261.038155      0.977394D
....

Create dataframe

df_list = ['df_0','df_1','df_2','df_3','df_4','df_5','df_6','df_7']
i = 0
for name, group in df.groupby('Date_UTC'):
    df_list[i] = group
    i += 1

df_0
    Date_UTC    Magnitude   Vector Station
0   2020-01-05  26.474679   -0.730455A
1   2020-01-05  30.746291   0.020503B
2   2020-01-05  37.829401   0.252316C
3   2020-01-05  1904.611372 0.977388D


问:
How to convert type 3 fonts to type 1 fonts in eps file?
I created an image in Microsoft PowerPoint. Then i used file -> Save as -> svg option. Later I imported this svg image in Inkscape and saved as an eps image.

However, it seems like my eps image has type 3 fonts. I want my eps image to have type 1 fonts. Is there a way to prevent inclusion of type 3 fonts in inkscape or powerpoint?

I am happy to provide more details if needed.

答:
You can't guarantee to be able to convert a type 3 font to a type 1 font. That's because type 3 fonts can contain anything.

To be more specific; type 3 fonts can contain colour operators, and images, neither of which is possible in a type 1 font. Type 1 fonts may only contain vector descriptions of the glyph outline.

Without seeing any of the files, it's difficult to be certain, but it's possible that the original .ppt file used pattern fills, Microsoft applications (and, to be fair, other tools) have something of a habit of turning patterns into type 3 fonts. My guess would be that's what is going on. If that's the case then you can't turn the type 3 fonts into type 1.

I'm not an expert on SVG, but I understand that its font support is somewhat limited, and not well supported by SVG consumers. I also don't think it supports type 1 fonts at all.


问:
How to design the icon of a Modelica component?
Is there any software that allows designing the icon of a Modelica component, and then copy into Dymola?
It is hard to draw the picture in Dymola.

A short summary of the answers, there is 4 software support this task:

OMEdit;

MoVE;

InkSpace;

PowerPoint;

答:
For some tasks OMEdit is better.  Properties of graphical elements are nicely presented in a single dialog and you can easily edit the points of lines and polygons.

As an alternative you can use svg and png files, which can be nicely drawn with Inkscape.


问:
Compilers and argument order of evaluation in C++
Okay, I'm aware that the standard dictates that a C++ implementation may choose in which order arguments of a function are evaluated, but are there any implementations that actually 'take advantage' of this in a scenario where it would actually affect the program?

Classic Example:

```<code>int i = 0;
foo(i++, i++);
</code>```

Note: I'm not looking for someone to tell me that the order of evaluation can't be relied on, I'm well aware of that. I'm only interested in whether any compilers actually do evaluate out of a left-to-right order because my guess would be that if they did lots of poorly written code would break (rightly so, but they would still probably complain).

答:
Read this

It's not an exact copy of your question, but my answer (and a few others) cover your question as well.

There are very good optimization reasons why the compiler might not just choose right-to-left but also interleave them.

The standard doesn't even guarantee a sequential ordering. It only guarantees that when the function gets called, all arguments have been fully evaluated.

And yes, I have seen a few versions of GCC do exactly this. For your example, foo(0,0) would be called, and i would be 2 afterwards. (I can't give you the exact version number of the compiler. It was a while ago - but I wouldn't be surprised to see this behavior pop up again. It's an efficient way to schedule instructions)

OwnerDisplayName: Cypherjb

ContentLicense: CC BY-SA 3.0

Body:
Okay, I'm aware that the standard dictates that a C++ implementation may choose in which order arguments of a function are evaluated, but are there any implementations that actually 'take advantage' of this in a scenario where it would actually affect the program?

Classic Example:

int i = 0;
foo(i++, i++);

Note: I'm not looking for someone to tell me that the order of evaluation can't be relied on, I'm well aware of that. I'm only interested in whether any compilers actually do evaluate out of a left-to-right order because my guess would be that if they did lots of poorly written code would break (rightly so, but they would still probably complain).

OwnerDisplayName: jalf

ContentLicense: CC BY-SA 2.5


答:
W:input volume size

F:kernel size

S:stride

P:amount of padding

size of output volume = (W-F+2P)/S+1

e.g.

input:7x7, kernel:3x3, stride:1, pad:0

output size = (7-3+2*0)/1+1 = 5 =>5x5

Title: padding='same' conversion to PyTorch padding=#

Body:
I'm trying to convert the following Keras model code to pytorch, but am having problems dealing with padding='same'.

    model = Sequential()
    model.add(Conv2D(64, (3, 3), input_shape=img_size))
    model.add(BatchNormalization(axis=1))
    model.add(Activation('relu'))
    model.add(Dropout(0.3))
    model.add(Conv2D(64, (3, 3), padding='same'))
    model.add(BatchNormalization(axis=1))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))

Which produces the following summary:

Layer (type)                 Output Shape              Param #
=================================================================
conv2d_1 (Conv2D)            (None, 30, 30, 64)        1792
_________________________________________________________________
batch_normalization_1 (Batch (None, 30, 30, 64)        120
_________________________________________________________________
activation_1 (Activation)    (None, 30, 30, 64)        0
_________________________________________________________________
dropout_1 (Dropout)          (None, 30, 30, 64)        0
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 30, 30, 64)        36928
_________________________________________________________________
batch_normalization_2 (Batch (None, 30, 30, 64)        120
_________________________________________________________________
activation_2 (Activation)    (None, 30, 30, 64)        0
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 15, 15, 64)        0
=================================================================
Total params: 38,960
Trainable params: 38,840
Non-trainable params: 120

Right now, I would write:

self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3,
                      bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.Dropout(0.3),
            nn.Conv2d(64, 64, kernel_size=3, padding = ?
                      bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2, padding = ?),
        )

Where padding should have numerical value. I was wondering if there is an easier way to calculate this since we're using padding='same'.

Also, the next line of the Keras model looks like:

model.add(Conv2D(128, (3, 3), padding='same'))

So I really need to brush up on how to calculate padding, especially after stride too. From a rough eye only, is the padding 2?


问:
Can't read data using read_csv due to encoding errors
So, I am facing a huge issue. I am trying to read a csv file which has '|' as delimiters. If I use utf-8 or utf-sig-8 as encoders then I get the following error:

```<code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc0 in position 0: invalid start byte
</code>```

but I use the unicode_escape encoding then I get this error:

```<code>UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 13: \ at end of string
</code>```

Is it an issue with the dataset?

答: it worked after I 'Saved with Encoding - utf-8' in Sublime Text Editor. I think the data had some issues. </p>

Body:
So, I am facing a huge issue. I am trying to read a csv file which has '|' as delimiters. If I use utf-8 or utf-sig-8 as encoders then I get the following error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc0 in position 0: invalid start byte

but I use the unicode_escape encoding then I get this error:

UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 13: \ at end of string

Is it an issue with the dataset?


问:
Problem changing icon in Delphi 2007
I've been working with a program someone else has made and I wanted to change the icon.

The icon I have is 256x256. I used http://converticon.com/ to create the icon (from a bmp I think). I used the icon in Inno Setup to create an installer and it worked fine

So I go to Options -> Application and attempt to load it. However, Delphi 2007 gives me an error 'The parameter is incorrect.' with this info: http://i.stack.imgur.com/vRCgs.png

When I do the same thing in Delphi XE, it works and loads the icon and changes it on compile. I can't use XE right now because the program uses a math parser that has a problem with unicode (thats something to fix for later haha)

So, what I did was open the project in XE, change the icon, save it, delete the dproj and open it in 2007. This works, compiles and displays the correct icon, but when I go to the project options, it gives me the same 'The parameter is incorrect' error.

The workaround isn't a big deal, but I shouldn't need to do it. Does anyone know why I can't change the icon in Delphi 2007?

Edit: I just used that same converticon site to convert the 256x256 icon to 192x192 and smaller and now it works perfectly. Thanks for the answers

答:
2007 will let you select icons with a 256 pixel image.  Here is what I tried:

The default icon for Delphi XE contains several image sizes, including a 256 pixel image.

If I extract the icon from a Delphi XE application using a resource editor, I can add that icon to a Delphi 2007 application using the IDE's project options.  I don't get an error, and the icon images show as expected in Windows Vista/7 using Explorer at different sizes.

If I take the same icon that worked in Delphi 2007 and remove all of the image sizes other than the 256 pixel image using IcoFX, and try to select it again, then I get an error.

Try creating a .ico that includes other image sizes and see if that works for you.

Title: Problem changing icon in Delphi 2007


问:
How to tokenize python code using the Tokenize module?
Consider that I have a string that contains the python code.

```<code>input = "import nltk
 from nltk.stem import PorterStemmer
 porter_stemmer=PorterStemmer()
 words=["connect","connected","connection","connections","connects"]
 stemmed_words=[porter_stemmer.stem(word) for word in words]
 stemmed_words"
</code>```

How can I tokenize the code? I found the tokenize module (https://docs.python.org/3/library/tokenize.html). However, it is not clear to me how to use the module. It has tokenize.tokenize(readline) but the parameter takes a generator, not a string.

答:
If you want to stick with tokenize.tokenize(), then this is what you can do:

from tokenize import tokenize
from io import BytesIO

code = """import nltk
 from nltk.stem import PorterStemmer
 porter_stemmer=PorterStemmer()
 words=["connect","connected","connection","connections","connects"]
 stemmed_words=[porter_stemmer.stem(word) for word in words]
 stemmed_words"""

for tok in tokenize(BytesIO(code.encode('utf-8')).readline):
    print(f"Type: {tok.type}\nString: {tok.string}\nStart: {tok.start}\nEnd: {tok.end}\nLine: {tok.line.strip()}\n======\n")
```

From the documentation you can see:

The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and column where the token begins in the source; a 2-tuple (erow, ecol) of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed (the last tuple item) is the physical line. The 5 tuple is returned as a named tuple with the field names: type string start end line.

The returned named tuple has an additional property named exact_type that contains the exact operator type for OP tokens. For all other token types exact_type equals the named tuple type field.

Body:
Consider that I have a string that contains the python code.

input = "import nltk
 from nltk.stem import PorterStemmer
 porter_stemmer=PorterStemmer()
 words=["connect","connected","connection","connections","connects"]
 stemmed_words=[porter_stemmer.stem(word) for word in words]
 stemmed_words"

How can I tokenize the code? I found the tokenize module (https://docs.python.org/3/library/tokenize.html). However, it is not clear to me how to use the module. It has tokenize.tokenize(readline) but the parameter takes a generator, not a string.

Body:
If you want to stick with tokenize.tokenize(), then this is what you can do:

from tokenize import tokenize
from io import BytesIO

code = """import nltk
 from nltk.stem import PorterStemmer
 porter_stemmer=PorterStemmer()
 words=["connect","connected","connection","connections","connects"]
 stemmed_words=[porter_stemmer.stem(word) for word in words]
 stemmed_words"""

for tok in tokenize(BytesIO(code.encode('utf-8')).readline):
    print(f"Type: {tok.type}\nString: {tok.string}\nStart: {tok.start}\nEnd: {tok.end}\nLine: {tok.line.strip()}\n======\n")

From the documentation you can see:

The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and column where the token begins in the source; a 2-tuple (erow, ecol) of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed (the last tuple item) is the physical line. The 5 tuple is returned as a named tuple with the field names: type string start end line.

The returned named tuple has an additional property named exact_type that contains the exact operator type for OP tokens. For all other token types exact_type equals the named tuple type field.


问:
get dotnet to output using ansi escape sequences
so - I'm running a "dotnet test" build on a build server.

The build server understands ansi escape sequences, but doesn't seem to understand whatever dotnet uses, so I don't get coloured output, even though the batch file around it has colours from ansi.

Does dotnet have any weird configuration properties or is there some way of inserting a different console, or any other way of getting ansi colour sequences out of it?

答:
.NET uses UNICODE (16 bit characters) for almost everything. I believe the Windows console is using UTF-8 encoding.

Here's an article someone wrote about what you're trying to do:

https://www.jerriepelser.com/blog/using-ansi-color-codes-in-net-console-apps/


问:
UTF-8 SELECT IBM i DB2 throught unixODBC php PDO Debian 9 in CLI php
I have a problem, very very picky.

I have a LAMP server which is connected to an IBM i (AS400) throught unixODBC. PHP execute sql on IBM i throught ODBC connection on IBM i.

I want to do a simple SELECT in my databse.
It's work very well when the script is executed by a navigator (apache), but when the script is executed by CLI (php example.php) and when i have special characters like : Ô ô é à @ etc in my record PDO return NULL. And when i execute the script in my Web browser all the special characters are okay.

I don't understand why. I put 'CHARSET=UTF-8' in my DSN PDO connection.

I think this bug is related to : iSeries Access ODBC Driver with unixodbc on Debian - Invalid UTF-8 characters being returned from iSeries because when I SELECT with HEX(field) i have the hexa from browser and CLI.

PHP latest version (7.4.6), Debian 9.

答: As per comment thread, the cause of the issue was that when running from the command-line shell and php CLI, the shell was not correctly configured for UTF-8 for the correct locale (country etc).</p>


问:
Unable to get user's email ID in user_friends API of Facebook
I'm fetching the list of user's friends who all are using the application with Login with Facebook feature. In GraphAPI for "user_freinds" request, I'm requesting for id, email & name of the users. However the API is not returning the email of users. Only name and ID of users are being returned. Please check the code below.

```<code>func getFacebookFriends() {
    if AccessToken.current != nil {
        let fbUserID = AccessToken.current?.userId ?? ""
        let friendsPath = "/\(fbUserID)/friends"
        let params = ["fields": "id, name, email"]
        let fbFriendsRequest = GraphRequest(graphPath: friendsPath, parameters: params, httpMethod: .GET)
        fbFriendsRequest.start { (_, result) in
            switch result {
            case .success(let response):
                print(response.dictionaryValue as Any)
                let responseDict = response.dictionaryValue!
                let data = responseDict["data"] as! [[String:Any]]
                if data.count != 0 {
                    // Sync the list with API
                } else {
                    // Show error
                }
            case .failed(let error):
                // Show error
            }
        }
    }
}
</code>```

Is there anything I'm missing here?

Also note that I'm using test users of Facebook, created by Developer portal of Facebook. Friends are added and authorised via Developer portal only.

答: Looking on the docs you are missing user_friends permission which needs to be added.

Body:
I'm fetching the list of user's friends who all are using the application with Login with Facebook feature. In GraphAPI for "user_freinds" request, I'm requesting for id, email & name of the users. However the API is not returning the email of users. Only name and ID of users are being returned. Please check the code below.

func getFacebookFriends() {
    if AccessToken.current != nil {
        let fbUserID = AccessToken.current?.userId ?? ""
        let friendsPath = "/\(fbUserID)/friends"
        let params = ["fields": "id, name, email"]
        let fbFriendsRequest = GraphRequest(graphPath: friendsPath, parameters: params, httpMethod: .GET)
        fbFriendsRequest.start { (_, result) in
            switch result {
            case .success(let response):
                print(response.dictionaryValue as Any)
                let responseDict = response.dictionaryValue!
                let data = responseDict["data"] as! [[String:Any]]
                if data.count != 0 {
                    // Sync the list with API
                } else {
                    // Show error
                }
            case .failed(let error):
                // Show error
            }
        }
    }
}

Is there anything I'm missing here?

Also note that I'm using test users of Facebook, created by Developer portal of Facebook. Friends are added and authorised via Developer portal only.


问:
Android Studio: The application installed from Run 'app' and application installed from build/outputs/apk/debug/app-debug.apk are different
I am still new to android studio application and here is the problem I have faced:

When I'm running the application from Run 'app' in the android studio, all of the application functions work and I am able to run the rating bar and location map in my application.

However, when trying to install it via the app/build/outputs/apk/debug/app-debug.apk, all of the application functions work except the rating bar and location map in my application. The app crashes after I click on the button that intent these functions. Why does it not working?

[Working] Running from Run 'app' in android studio:

The screenshot of rating and locate button:

The screenshot of working rating function:

The screenshot of working locate function:

[Not Working] Running from app/build/outputs/apk/debug/app-debug.apk:

The screenshot of rating and locate button:

The screenshot of app crashes after a click on either the rating or locate button:

What I have tried:

I have already clean the project/rebuild the project/or even manually delete the build folder to rebuild the project to generate new APK.

I have also updated the dependencies to the newest version.

Yet, not working.

I expect all the functions in the application will run smoothly when trying to install the application from app/build/outputs/apk/debug/app-debug.apk, but it crashes.

Here is the debug logcat when I clicked on the rate button:

```<code>2019-08-13 18:32:17.760 13713-13713/? I/e.nad.whattoea: Late-enabling -Xcheck:jni
2019-08-13 18:32:17.823 13713-13713/? E/libc: Access denied finding property "persist.vendor.sys.activitylog"
2019-08-13 18:32:17.822 13713-13713/? W/re-initialized>: type=1400 audit(0.0:1239971): avc: denied { read } for name="u:object_r:mtk_amslog_prop:s0" dev="tmpfs" ino=7827 scontext=u:r:untrusted_app:s0:c80,c257,c512,c768 tcontext=u:object_r:mtk_amslog_prop:s0 tclass=file permissive=0
2019-08-13 18:32:17.855 13713-13713/learncode.nad.whattoeat D/VivoTheme: load old package name start
2019-08-13 18:32:17.865 13713-13713/learncode.nad.whattoeat I/e.nad.whattoea: The ClassLoaderContext is a special shared library.
2019-08-13 18:32:18.278 13713-13748/learncode.nad.whattoeat W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
2019-08-13 18:32:18.301 13713-13713/learncode.nad.whattoeat D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
2019-08-13 18:32:18.302 13713-13713/learncode.nad.whattoeat I/FirebaseInitProvider: FirebaseApp initialization successful
2019-08-13 18:32:18.302 13713-13750/learncode.nad.whattoeat W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
2019-08-13 18:32:18.309 13713-13750/learncode.nad.whattoeat I/FirebaseAuth: [FirebaseAuth:] Loading module via FirebaseOptions.
2019-08-13 18:32:18.309 13713-13750/learncode.nad.whattoeat I/FirebaseAuth: [FirebaseAuth:] Preparing to create service connection to gms implementation
2019-08-13 18:32:18.314 13713-13713/learncode.nad.whattoeat D/NightModeController: learncode.nad.whattoeat = true
2019-08-13 18:32:18.314 13713-13713/learncode.nad.whattoeat D/NightModeController: disable nightmode package:learncode.nad.whattoeat
2019-08-13 18:32:18.353 13713-13747/learncode.nad.whattoeat I/FA: App measurement is starting up, version: 16250
2019-08-13 18:32:18.353 13713-13747/learncode.nad.whattoeat I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
2019-08-13 18:32:18.353 13713-13747/learncode.nad.whattoeat I/FA: To enable faster debug mode event logging run:
      adb shell setprop debug.firebase.analytics.app learncode.nad.whattoeat
2019-08-13 18:32:18.353 13713-13747/learncode.nad.whattoeat D/FA: Debug-level message logging enabled
2019-08-13 18:32:18.366 13713-13747/learncode.nad.whattoeat D/OpenSSLLib: OpensslErr:Module:12(177:); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:168;Function:ASN1_get_object
2019-08-13 18:32:18.374 13713-13713/learncode.nad.whattoeat I/FtBuild: getRomVersion mRomVer=9.0
2019-08-13 18:32:18.384 13713-13713/learncode.nad.whattoeat W/e.nad.whattoea: Accessing hidden method Landroid/graphics/drawable/Drawable;->getOpticalInsets()Landroid/graphics/Insets; (light greylist, linking)
2019-08-13 18:32:18.385 13713-13713/learncode.nad.whattoeat W/e.nad.whattoea: Accessing hidden field Landroid/graphics/Insets;->left:I (light greylist, linking)
2019-08-13 18:32:18.385 13713-13713/learncode.nad.whattoeat W/e.nad.whattoea: Accessing hidden field Landroid/graphics/Insets;->right:I (light greylist, linking)
2019-08-13 18:32:18.385 13713-13713/learncode.nad.whattoeat W/e.nad.whattoea: Accessing hidden field Landroid/graphics/Insets;->top:I (light greylist, linking)
2019-08-13 18:32:18.385 13713-13713/learncode.nad.whattoeat W/e.nad.whattoea: Accessing hidden field Landroid/graphics/Insets;->bottom:I (light greylist, linking)
2019-08-13 18:32:18.411 13713-13713/learncode.nad.whattoeat W/Glide: Failed to find GeneratedAppGlideModule. You should include an annotationProcessor compile dependency on com.github.bumptech.glide:compiler in your application and a @GlideModule annotated AppGlideModule implementation or LibraryGlideModules will be silently ignored
2019-08-13 18:32:18.462 13713-13713/learncode.nad.whattoeat D/VivoPhoneWindow: DEBUG_ALIENSCREEN:getRotation mRotation=0
2019-08-13 18:32:18.463 13713-13713/learncode.nad.whattoeat I/PhoneWindow: initSystemUIColor
2019-08-13 18:32:18.492 13713-13713/learncode.nad.whattoeat W/e.nad.whattoea: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
2019-08-13 18:32:18.494 13713-13713/learncode.nad.whattoeat W/e.nad.whattoea: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
2019-08-13 18:32:18.634 13713-13713/learncode.nad.whattoeat W/e.nad.whattoea: Accessing hidden method Landroid/widget/TextView;->getTextDirectionHeuristic()Landroid/text/TextDirectionHeuristic; (light greylist, linking)
2019-08-13 18:32:18.709 13713-13713/learncode.nad.whattoeat D/OpenGLRenderer: Skia GL Pipeline
2019-08-13 18:32:18.709 13713-13713/learncode.nad.whattoeat I/SurfaceFactory: [static] sSurfaceFactory = com.mediatek.view.impl.SurfaceFactoryImpl@2e418c9
2019-08-13 18:32:18.716 13713-13747/learncode.nad.whattoeat I/FA: Tag Manager is not found and thus will not be used
2019-08-13 18:32:18.723 13713-13713/learncode.nad.whattoeat D/ViewRootImpl[MainActivity]: hardware acceleration = true , fakeHwAccelerated = false, sRendererDisabled = false, forceHwAccelerated = false, sSystemRendererDisabled = false
2019-08-13 18:32:18.729 13713-13747/learncode.nad.whattoeat D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=-2282275983064218132}]
2019-08-13 18:32:18.750 13713-13713/learncode.nad.whattoeat I/CatcherGestureDetector: DecorView onAttached
2019-08-13 18:32:18.751 13713-13758/learncode.nad.whattoeat D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2019-08-13 18:32:18.756 13713-13758/learncode.nad.whattoeat W/System: ClassLoader referenced unknown path: system/framework/mediatek-cta.jar
2019-08-13 18:32:18.758 13713-13758/learncode.nad.whattoeat I/System.out: e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaHttp
2019-08-13 18:32:18.758 13713-13758/learncode.nad.whattoeat D/Linux: [Posix_connect Debug]Process learncode.nad.whattoeat :443
2019-08-13 18:32:18.802 13713-13713/learncode.nad.whattoeat D/Surface: Surface::allocateBuffers(this=0x7dfb784000)
2019-08-13 18:32:18.811 13713-13757/learncode.nad.whattoeat I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
2019-08-13 18:32:18.811 13713-13757/learncode.nad.whattoeat I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
2019-08-13 18:32:18.811 13713-13757/learncode.nad.whattoeat I/OpenGLRenderer: Initialized EGL, version 1.4
2019-08-13 18:32:18.811 13713-13757/learncode.nad.whattoeat D/OpenGLRenderer: Swap behavior 2
2019-08-13 18:32:18.811 13713-13757/learncode.nad.whattoeat E/OpenGLRenderer: Device claims wide gamut support, cannot find matching config, error = EGL_SUCCESS
2019-08-13 18:32:18.817 13713-13713/learncode.nad.whattoeat E/RecyclerView: No adapter attached; skipping layout
2019-08-13 18:32:18.820 13713-13757/learncode.nad.whattoeat D/Surface: Surface::connect(this=0x7dfb784000,api=1)
2019-08-13 18:32:18.821 13713-13757/learncode.nad.whattoeat D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
2019-08-13 18:32:18.848 13713-13750/learncode.nad.whattoeat D/OpenSSLLib: OpensslErr:Module:12(177:); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:168;Function:ASN1_get_object
2019-08-13 18:32:18.969 13713-13757/learncode.nad.whattoeat E/ion: ioctl c0044901 failed with code -1: Invalid argument
2019-08-13 18:32:19.011 13713-13747/learncode.nad.whattoeat D/FA: Connected to remote service
2019-08-13 18:32:19.267 13713-13758/learncode.nad.whattoeat D/OpenSSLLib: OpensslErr:Module:12(177:); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:168;Function:ASN1_get_object
2019-08-13 18:32:19.268 13713-13758/learncode.nad.whattoeat D/OpenSSLLib: OpensslErr:Module:12(177:); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:168;Function:ASN1_get_object
2019-08-13 18:32:20.817 13713-13784/learncode.nad.whattoeat D/skia: SkJpegCodec::onGetPixels fEnTdshp 0 fISOSpeedRatings -1!
2019-08-13 18:32:20.834 13713-13784/learncode.nad.whattoeat D/skia: SkJpegCodec::onGetPixels fEnTdshp 0 fISOSpeedRatings -1!
2019-08-13 18:32:20.848 13713-13784/learncode.nad.whattoeat I/chatty: uid=10336(learncode.nad.whattoeat) glide-disk-cach identical 1 line
2019-08-13 18:32:20.863 13713-13784/learncode.nad.whattoeat D/skia: SkJpegCodec::onGetPixels fEnTdshp 0 fISOSpeedRatings -1!
2019-08-13 18:32:20.871 13713-13713/learncode.nad.whattoeat W/Glide: Load failed for  with size [453x390]
    class com.bumptech.glide.load.engine.GlideException: Failed to load resource
2019-08-13 18:32:20.871 13713-13713/learncode.nad.whattoeat W/Glide: Load failed for  with size [453x390]
    class com.bumptech.glide.load.engine.GlideException: Failed to load resource
2019-08-13 18:32:20.876 13713-13784/learncode.nad.whattoeat D/skia: SkJpegCodec::onGetPixels fEnTdshp 0 fISOSpeedRatings -1
</code>```

The logcat after filter to error:

```<code>2019-08-13 18:36:18.694 13899-13899/? E/libc: Access denied finding property "persist.vendor.sys.activitylog"
2019-08-13 18:36:18.708 13899-13914/? E/e.nad.whattoea: Unable to peek into adb socket due to error. Closing socket.: Connection reset by peer
2019-08-13 18:36:19.731 13899-13950/learncode.nad.whattoeat E/OpenGLRenderer: Device claims wide gamut support, cannot find matching config, error = EGL_SUCCESS
2019-08-13 18:36:19.744 13899-13899/learncode.nad.whattoeat E/RecyclerView: No adapter attached; skipping layout
2019-08-13 18:36:19.889 13899-13950/learncode.nad.whattoeat E/ion: ioctl c0044901 failed with code -1: Invalid argument
</code>```

答:
I got this error about 'persist.vendor.sys.activitylog', and wasted the better part of an hour on it.

I can confirm that it is phone-dependent.

The error appears to be coming from the initial launching of the app. before anything happens in my (very simple) code.  Something like this from a Nokia 1 running Android 9:

```<code>I/ActivityManager: Start proc <proc-id>:org.goldang.appdope.dbg/u0a472 for activity org.mydom.myapp.dbg/org.mydom.myapp.MainActivity
I/ang.myapp.db: Late-enabling -Xcheck:jni
I/ADB_SERVICES: service_to_fd shell:stat -c %u /proc/20716 | xargs -n 1 pm list packages --uid
W/re-initialized>: type=1400 audit(0.0:23144): avc: denied { read } for name="u:object_r:mtk_amslog_prop:s0" dev="tmpfs" ino=7302 scontext=u:r:untrusted_app:s0:c216,c257,c512,c768 tcontext=u:object_r:mtk_amslog_prop:s0 tclass=file permissive=0
I/ang.myapp.db: Late-enabling -Xcheck:jni
E/libc: Access denied finding property "persist.vendor.sys.activitylog"
</code>```

Body:
I am still new to android studio application and here is the problem I have faced:

When I'm running the application from Run 'app' in the android studio, all of the application functions work and I am able to run the rating bar and location map in my application.

However, when trying to install it via the app/build/outputs/apk/debug/app-debug.apk, all of the application functions work except the rating bar and location map in my application. The app crashes after I click on the button that intent these functions. Why does it not working?

[Working] Running from Run 'app' in android studio:

The screenshot of rating and locate button:

The screenshot of working rating function:

The screenshot of working locate function:

[Not Working] Running from app/build/outputs/apk/debug/app-debug.apk:

The screenshot of rating and locate button:

The screenshot of app crashes after a click on either the rating or locate button:

What I have tried:

I have already clean the project/rebuild the project/or even manually delete the build folder to rebuild the project to generate new APK.

I have also updated the dependencies to the newest version.

Yet, not working.

I expect all the functions in the application will run smoothly when trying to install the application from app/build/outputs/apk/debug/app-debug.apk, but it crashes.

Here is the debug logcat when I clicked on the rate button:

2019-08-13 18:32:17.760 13713-13713/? I/e.nad.whattoea: Late-enabling -Xcheck:jni
2019-08-13 18:32:17.823 13713-13713/? E/libc: Access denied finding property "persist.vendor.sys.activitylog"
2019-08-13 18:32:17.822 13713-13713/? W/re-initialized>: type=1400 audit(0.0:1239971): avc: denied { read } for name="u:object_r:mtk_amslog_prop:s0" dev="tmpfs" ino=7827 scontext=u:r:untrusted_app:s0:c80,c257,c512,c768 tcontext=u:object_r:mtk_amslog_prop:s0 tclass=file permissive=0
2019-08-13 18:32:17.855 13713-13713/learncode.nad.whattoeat D/VivoTheme: load old package name start
2019-08-13 18:32:17.865 13713-13713/learncode.nad.whattoeat I/e.nad.whattoea: The ClassLoaderContext is a special shared library.
2019-08-13 18:32:18.278 13713-13748/learncode.nad.whattoeat W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
2019-08-13 18:32:18.301 13713-13713/learncode.nad.whattoeat D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
2019-08-13 18:32:18.302 13713-13713/learncode.nad.whattoeat I/FirebaseInitProvider: FirebaseApp initialization successful
2019-08-13 18:32:18.302 13713-13750/learncode.nad.whattoeat W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
2019-08-13 18:32:18.309 13713-13750/learncode.nad.whattoeat I/FirebaseAuth: [FirebaseAuth:] Loading module via FirebaseOptions.
2019-08-13 18:32:18.309 13713-13750/learncode.nad.whattoeat I/FirebaseAuth: [FirebaseAuth:] Preparing to create service connection to gms implementation
2019-08-13 18:32:18.314 13713-13713/learncode.nad.whattoeat D/NightModeController: learncode.nad.whattoeat = true
2019-08-13 18:32:18.314 13713-13713/learncode.nad.whattoeat D/NightModeController: disable nightmode package:learncode.nad.whattoeat
2019-08-13 18:32:18.353 13713-13747/learncode.nad.whattoeat I/FA: App measurement is starting up, version: 16250
2019-08-13 18:32:18.353 13713-13747/learncode.nad.whattoeat I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
2019-08-13 18:32:18.353 13713-13747/learncode.nad.whattoeat I/FA: To enable faster debug mode event logging run:
      adb shell setprop debug.firebase.analytics.app learncode.nad.whattoeat
2019-08-13 18:32:18.353 13713-13747/learncode.nad.whattoeat D/FA: Debug-level message logging enabled
2019-08-13 18:32:18.366 13713-13747/learncode.nad.whattoeat D/OpenSSLLib: OpensslErr:Module:12(177:); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:168;Function:ASN1_get_object
2019-08-13 18:32:18.374 13713-13713/learncode.nad.whattoeat I/FtBuild: getRomVersion mRomVer=9.0
2019-08-13 18:32:18.384 13713-13713/learncode.nad.whattoeat W/e.nad.whattoea: Accessing hidden method Landroid/graphics/drawable/Drawable;->getOpticalInsets()Landroid/graphics/Insets; (light greylist, linking)
2019-08-13 18:32:18.385 13713-13713/learncode.nad.whattoeat W/e.nad.whattoea: Accessing hidden field Landroid/graphics/Insets;->left:I (light greylist, linking)
2019-08-13 18:32:18.385 13713-13713/learncode.nad.whattoeat W/e.nad.whattoea: Accessing hidden field Landroid/graphics/Insets;->right:I (light greylist, linking)
2019-08-13 18:32:18.385 13713-13713/learncode.nad.whattoeat W/e.nad.whattoea: Accessing hidden field Landroid/graphics/Insets;->top:I (light greylist, linking)
2019-08-13 18:32:18.385 13713-13713/learncode.nad.whattoeat W/e.nad.whattoea: Accessing hidden field Landroid/graphics/Insets;->bottom:I (light greylist, linking)
2019-08-13 18:32:18.411 13713-13713/learncode.nad.whattoeat W/Glide: Failed to find GeneratedAppGlideModule. You should include an annotationProcessor compile dependency on com.github.bumptech.glide:compiler in your application and a @GlideModule annotated AppGlideModule implementation or LibraryGlideModules will be silently ignored
2019-08-13 18:32:18.462 13713-13713/learncode.nad.whattoeat D/VivoPhoneWindow: DEBUG_ALIENSCREEN:getRotation mRotation=0
2019-08-13 18:32:18.463 13713-13713/learncode.nad.whattoeat I/PhoneWindow: initSystemUIColor
2019-08-13 18:32:18.492 13713-13713/learncode.nad.whattoeat W/e.nad.whattoea: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
2019-08-13 18:32:18.494 13713-13713/learncode.nad.whattoeat W/e.nad.whattoea: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
2019-08-13 18:32:18.634 13713-13713/learncode.nad.whattoeat W/e.nad.whattoea: Accessing hidden method Landroid/widget/TextView;->getTextDirectionHeuristic()Landroid/text/TextDirectionHeuristic; (light greylist, linking)
2019-08-13 18:32:18.709 13713-13713/learncode.nad.whattoeat D/OpenGLRenderer: Skia GL Pipeline
2019-08-13 18:32:18.709 13713-13713/learncode.nad.whattoeat I/SurfaceFactory: [static] sSurfaceFactory = com.mediatek.view.impl.SurfaceFactoryImpl@2e418c9
2019-08-13 18:32:18.716 13713-13747/learncode.nad.whattoeat I/FA: Tag Manager is not found and thus will not be used
2019-08-13 18:32:18.723 13713-13713/learncode.nad.whattoeat D/ViewRootImpl[MainActivity]: hardware acceleration = true , fakeHwAccelerated = false, sRendererDisabled = false, forceHwAccelerated = false, sSystemRendererDisabled = false
2019-08-13 18:32:18.729 13713-13747/learncode.nad.whattoeat D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=-2282275983064218132}]
2019-08-13 18:32:18.750 13713-13713/learncode.nad.whattoeat I/CatcherGestureDetector: DecorView onAttached
2019-08-13 18:32:18.751 13713-13758/learncode.nad.whattoeat D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2019-08-13 18:32:18.756 13713-13758/learncode.nad.whattoeat W/System: ClassLoader referenced unknown path: system/framework/mediatek-cta.jar
2019-08-13 18:32:18.758 13713-13758/learncode.nad.whattoeat I/System.out: e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaHttp
2019-08-13 18:32:18.758 13713-13758/learncode.nad.whattoeat D/Linux: [Posix_connect Debug]Process learncode.nad.whattoeat :443
2019-08-13 18:32:18.802 13713-13713/learncode.nad.whattoeat D/Surface: Surface::allocateBuffers(this=0x7dfb784000)
2019-08-13 18:32:18.811 13713-13757/learncode.nad.whattoeat I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
2019-08-13 18:32:18.811 13713-13757/learncode.nad.whattoeat I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
2019-08-13 18:32:18.811 13713-13757/learncode.nad.whattoeat I/OpenGLRenderer: Initialized EGL, version 1.4
2019-08-13 18:32:18.811 13713-13757/learncode.nad.whattoeat D/OpenGLRenderer: Swap behavior 2
2019-08-13 18:32:18.811 13713-13757/learncode.nad.whattoeat E/OpenGLRenderer: Device claims wide gamut support, cannot find matching config, error = EGL_SUCCESS
2019-08-13 18:32:18.817 13713-13713/learncode.nad.whattoeat E/RecyclerView: No adapter attached; skipping layout
2019-08-13 18:32:18.820 13713-13757/learncode.nad.whattoeat D/Surface: Surface::connect(this=0x7dfb784000,api=1)
2019-08-13 18:32:18.821 13713-13757/learncode.nad.whattoeat D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
2019-08-13 18:32:18.848 13713-13750/learncode.nad.whattoeat D/OpenSSLLib: OpensslErr:Module:12(177:); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:168;Function:ASN1_get_object
2019-08-13 18:32:18.969 13713-13757/learncode.nad.whattoeat E/ion: ioctl c0044901 failed with code -1: Invalid argument
2019-08-13 18:32:19.011 13713-13747/learncode.nad.whattoeat D/FA: Connected to remote service
2019-08-13 18:32:19.267 13713-13758/learncode.nad.whattoeat D/OpenSSLLib: OpensslErr:Module:12(177:); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:168;Function:ASN1_get_object
2019-08-13 18:32:19.268 13713-13758/learncode.nad.whattoeat D/OpenSSLLib: OpensslErr:Module:12(177:); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:168;Function:ASN1_get_object
2019-08-13 18:32:20.817 13713-13784/learncode.nad.whattoeat D/skia: SkJpegCodec::onGetPixels fEnTdshp 0 fISOSpeedRatings -1!
2019-08-13 18:32:20.834 13713-13784/learncode.nad.whattoeat D/skia: SkJpegCodec::onGetPixels fEnTdshp 0 fISOSpeedRatings -1!
2019-08-13 18:32:20.848 13713-13784/learncode.nad.whattoeat I/chatty: uid=10336(learncode.nad.whattoeat) glide-disk-cach identical 1 line
2019-08-13 18:32:20.863 13713-13784/learncode.nad.whattoeat D/skia: SkJpegCodec::onGetPixels fEnTdshp 0 fISOSpeedRatings -1!
2019-08-13 18:32:20.871 13713-13713/learncode.nad.whattoeat W/Glide: Load failed for  with size [453x390]
    class com.bumptech.glide.load.engine.GlideException: Failed to load resource
2019-08-13 18:32:20.871 13713-13713/learncode.nad.whattoeat W/Glide: Load failed for  with size [453x390]
    class com.bumptech.glide.load.engine.GlideException: Failed to load resource
2019-08-13 18:32:20.876 13713-13784/learncode.nad.whattoeat D/skia: SkJpegCodec::onGetPixels fEnTdshp 0 fISOSpeedRatings -1

The logcat after filter to error:

2019-08-13 18:36:18.694 13899-13899/? E/libc: Access denied finding property "persist.vendor.sys.activitylog"
2019-08-13 18:36:18.708 13899-13914/? E/e.nad.whattoea: Unable to peek into adb socket due to error. Closing socket.: Connection reset by peer
2019-08-13 18:36:19.731 13899-13950/learncode.nad.whattoeat E/OpenGLRenderer: Device claims wide gamut support, cannot find matching config, error = EGL_SUCCESS
2019-08-13 18:36:19.744 13899-13899/learncode.nad.whattoeat E/RecyclerView: No adapter attached; skipping layout
2019-08-13 18:36:19.889 13899-13950/learncode.nad.whattoeat E/ion: ioctl c0044901 failed with code -1: Invalid argument

Body:
I got this error about 'persist.vendor.sys.activitylog', and wasted the better part of an hour on it.

I can confirm that it is phone-dependent.

The error appears to be coming from the initial launching of the app. before anything happens in my (very simple) code.  Something like this from a Nokia 1 running Android 9:

I/ActivityManager: Start proc <proc-id>:org.goldang.appdope.dbg/u0a472 for activity org.mydom.myapp.dbg/org.mydom.myapp.MainActivity
I/ang.myapp.db: Late-enabling -Xcheck:jni
I/ADB_SERVICES: service_to_fd shell:stat -c %u /proc/20716 | xargs -n 1 pm list packages --uid
W/re-initialized>: type=1400 audit(0.0:23144): avc: denied { read } for name="u:object_r:mtk_amslog_prop:s0" dev="tmpfs" ino=7302 scontext=u:r:untrusted_app:s0:c216,c257,c512,c768 tcontext=u:object_r:mtk_amslog_prop:s0 tclass=file permissive=0
I/ang.myapp.db: Late-enabling -Xcheck:jni
E/libc: Access denied finding property "persist.vendor.sys.activitylog"


问:
Is it possible to store the alembic connect string outside of alembic.ini?
I'm using Alembic with SQLAlchemy. With SQLAlchemy, I tend to follow a pattern where I don't store the connect string with the versioned code. Instead I have file secret.py that contains any confidential information. I throw this filename in my .gitignore so it doesn't end up on GitHub.

This pattern works fine, but now I'm getting into using Alembic for migrations. It appears that I cannot hide the connect string. Instead in alembic.ini, you place the connect string as a configuration parameter:

```<code># the 'revision' command, regardless of autogenerate
# revision_environment = false

sqlalchemy.url = driver://user:pass@localhost/dbname

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembi
</code>```

I fear I'm going to accidentally commit a file with username/password information for my database. I'd rather store this connect string in a single place and avoid the risk of accidentally committing it to version control.

What options do I have?

答:
I was bumping into this problem as well since we're running our migrations from our local machines. My solution is to put environment sections in the alembic.ini which stores the database config (minus the credentials):

```<code>[local]
host = localhost
db = dbname

[test]
host = x.x.x.x
db = dbname

[prod]
host = x.x.x.x
db = dbname
</code>```

Then I put the following in the env.py so the user can pick their environment and be prompted for the credentials:

```<code>from alembic import context
from getpass import getpass

...

envs = ['local', 'test', 'prod']

print('Warning: Do not commit your database credentials to source control!')
print(f'Available migration environments: {", ".join(envs)}')

env = input('Environment: ')

if env not in envs:
    print(f'{env} is not a valid environment')
    exit(0)

env_config = context.config.get_section(env)
host = env_config['host']
db = env_config['db']

username = input('Username: ')
password = getpass()
connection_string = f'postgresql://{username}:{password}@{host}/{db}'

context.config.set_main_option('sqlalchemy.url', connection_string)
</code>```

You should store your credentials in a password manager that the whole team has access to, or whatever config/secret store you have available. Though, with this approach the password is exposed to your local clip board - an even better approach would be to have env.py directly connect to your config/secret store API and pull out the username/password directly but this adds a third party dependency.

Body:
I'm using Alembic with SQLAlchemy. With SQLAlchemy, I tend to follow a pattern where I don't store the connect string with the versioned code. Instead I have file secret.py that contains any confidential information. I throw this filename in my .gitignore so it doesn't end up on GitHub.

This pattern works fine, but now I'm getting into using Alembic for migrations. It appears that I cannot hide the connect string. Instead in alembic.ini, you place the connect string as a configuration parameter:

# the 'revision' command, regardless of autogenerate
# revision_environment = false

sqlalchemy.url = driver://user:pass@localhost/dbname

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembi

I fear I'm going to accidentally commit a file with username/password information for my database. I'd rather store this connect string in a single place and avoid the risk of accidentally committing it to version control.

What options do I have?

Body:
I was bumping into this problem as well since we're running our migrations from our local machines. My solution is to put environment sections in the alembic.ini which stores the database config (minus the credentials):

[local]
host = localhost
db = dbname

[test]
host = x.x.x.x
db = dbname

[prod]
host = x.x.x.x
db = dbname

Then I put the following in the env.py so the user can pick their environment and be prompted for the credentials:

from alembic import context
from getpass import getpass

...

envs = ['local', 'test', 'prod']

print('Warning: Do not commit your database credentials to source control!')
print(f'Available migration environments: {", ".join(envs)}')

env = input('Environment: ')

if env not in envs:
    print(f'{env} is not a valid environment')
    exit(0)

env_config = context.config.get_section(env)
host = env_config['host']
db = env_config['db']

username = input('Username: ')
password = getpass()
connection_string = f'postgresql://{username}:{password}@{host}/{db}'

context.config.set_main_option('sqlalchemy.url', connection_string)

You should store your credentials in a password manager that the whole team has access to, or whatever config/secret store you have available. Though, with this approach the password is exposed to your local clip board - an even better approach would be to have env.py directly connect to your config/secret store API and pull out the username/password directly but this adds a third party dependency.


问:
JS Regex returning -1 & 0
I was tasked with the following:

take a string

print each of the vowels on a new line (in order) then...

print each of the consonants on a new line (in order)

The problem I found was with the regex. I originally used...

/[aeiouAEIOU\s]/g```
</div>
</div>
</p>

<p>But this would return 0 with a vowel and -1 with a consonant (so everything happened in reverse).
I really struggled to understand why and couldn't for the life of me find the answer. In the end it was simple enough to just invert the string but I want to know why this is happening the way it is. Can anyone help?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let i;
let vowels = /[^aeiouAEIOU\s]/g;
let array = [];
function vowelsAndConsonants(s) {
    for(i=0;i<s.length;i++){
        //if char is vowel then push to array
        if(s[i].search(vowels)){
           array.push(s[i]);
        }

    }
    for(i=0;i<s.length;i++){
        //if char is cons then push to array
        if(!s[i].search(vowels)){
           array.push(s[i]);
        }
    }
    for(i=0;i<s.length;i++){
        console.log(array[i]);
    }
}

vowelsAndConsonants("javascript");</code>```

答:
You used:

```<code>/[^aeiouAEIOU\s]/g
</code>```

Instead of:

```<code>/[aeiouAEIOU\s]/g
</code>```

^ means "not", so your REGEX /[^aeiouAEIOU\s]/g counts all the consonants.

Title: JS Regex returning -1 & 0

Body:
I was tasked with the following:

take a string

print each of the vowels on a new line (in order) then...

print each of the consonants on a new line (in order)

The problem I found was with the regex. I originally used...

/[aeiouAEIOU\s]/g

But this would return 0 with a vowel and -1 with a consonant (so everything happened in reverse).
I really struggled to understand why and couldn't for the life of me find the answer. In the end it was simple enough to just invert the string but I want to know why this is happening the way it is. Can anyone help?

let i;
let vowels = /[^aeiouAEIOU\s]/g;
let array = [];
function vowelsAndConsonants(s) {
    for(i=0;i<s.length;i++){
        //if char is vowel then push to array
        if(s[i].search(vowels)){
           array.push(s[i]);
        }

    }
    for(i=0;i<s.length;i++){
        //if char is cons then push to array
        if(!s[i].search(vowels)){
           array.push(s[i]);
        }
    }
    for(i=0;i<s.length;i++){
        console.log(array[i]);
    }
}

vowelsAndConsonants("javascript");

Body:
You used:

/[^aeiouAEIOU\s]/g

Instead of:

/[aeiouAEIOU\s]/g

^ means "not", so your REGEX /[^aeiouAEIOU\s]/g counts all the consonants.


问:
two std::cout, only one outputting
I have a program which accepts input for 10 people, and is then supposed to cout the person who consumed the highest number of pancakes and the person who ate the fewest. I've tried:

std::endl; at the end of every cout.

std::flush; at the end.

after this didn't work on my machine, I put the code into repl.it, and it still didn't work. This (from my understanding of how repl.it works) rules out an issue with compiler/ide (which is g++ and visual studio 2019).

My code:

main.cpp:

```<code>    #include <iostream>
    #include <string>
    #include <vector>
    #include "header.h"

    std::vector<int> person = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    std::vector<int> num_eaten_pancakes(10);

    int most_pancakes = 0;
    int least_pancakes = 0;
    int person_who_ate_most = 0;
    int person_who_ate_least = 0;

     int main() {
       get_nums_of_pancakes();
       person_who_ate_most = who_ate_most();
       std::cout << "Person " << who_ate_most() << " ate the most pancakes with " << num_eaten_pancakes[person_who_ate_most - 1] << " eaten." << std::flush;

       person_who_ate_least = who_ate_least();
       std::cout << "Person " << who_ate_least() << " ate the least pancakes with " << num_eaten_pancakes[person_who_ate_least - 1] << " eaten." << std::flush;
       return 0;
    }
</code>```

funcs.cpp

```<code>#include <iostream>
#include <string>
#include <vector>
#include "header.h"

void get_nums_of_pancakes() {
//Get the no. of pancakes eaten by person 1, 2, etc. up to person 10.
for (int i = 0; i < 10; i++) {
    person[i] = i + 1;
    std::cout << "Input the number of pancakes entered by person " << person[i] << ": ";
    std::cin >> num_eaten_pancakes[i];
  }
}

//Who ate the most pancakes
int who_ate_most() {
for (int i = 0; i < 10; i++) {
    if (num_eaten_pancakes[i] > most_pancakes) {
        most_pancakes = num_eaten_pancakes[i];
        person_who_ate_most = person[i];
    }
  }
  return person_who_ate_most;
}

//Who ate the least pancakes
int who_ate_least() {
  for (int i = 0; i < 10; i++) {
     do
        least_pancakes = num_eaten_pancakes[i];
     while (i == 0);

     if (num_eaten_pancakes[i] < least_pancakes) {
         least_pancakes = num_eaten_pancakes[i];
         person_who_ate_least = person[i];
     }
   }
   return person_who_ate_least;
 }
</code>```

header.h

```<code>#include <vector>
#include <string>

//VARIABLES
//Vectors for 10 people, pancakes
extern std::vector<int> person;
extern std::vector<int> num_eaten_pancakes;

extern int most_pancakes;
extern int least_pancakes;
extern int person_who_ate_most;
extern int person_who_ate_least;

//FUNCTIONS
void get_nums_of_pancakes();
int who_ate_most();
int who_ate_least();
</code>```

The output, when I enter the number of pancakes consumed, is correct for the person who ate the most, but when it comes to the person who consumed the fewest, there's nothing.

答: You have an infinite do-while-loop in who_ate_least(): If i == 0 you never change i and never make the condition become false.

Title: two std::cout, only one outputting

Body:
I have a program which accepts input for 10 people, and is then supposed to cout the person who consumed the highest number of pancakes and the person who ate the fewest. I've tried:

std::endl; at the end of every cout.

std::flush; at the end.

after this didn't work on my machine, I put the code into repl.it, and it still didn't work. This (from my understanding of how repl.it works) rules out an issue with compiler/ide (which is g++ and visual studio 2019).

My code:

main.cpp:

    #include <iostream>
    #include <string>
    #include <vector>
    #include "header.h"

    std::vector<int> person = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    std::vector<int> num_eaten_pancakes(10);

    int most_pancakes = 0;
    int least_pancakes = 0;
    int person_who_ate_most = 0;
    int person_who_ate_least = 0;

     int main() {
       get_nums_of_pancakes();
       person_who_ate_most = who_ate_most();
       std::cout << "Person " << who_ate_most() << " ate the most pancakes with " << num_eaten_pancakes[person_who_ate_most - 1] << " eaten." << std::flush;

       person_who_ate_least = who_ate_least();
       std::cout << "Person " << who_ate_least() << " ate the least pancakes with " << num_eaten_pancakes[person_who_ate_least - 1] << " eaten." << std::flush;
       return 0;
    }

funcs.cpp

#include <iostream>
#include <string>
#include <vector>
#include "header.h"

void get_nums_of_pancakes() {
//Get the no. of pancakes eaten by person 1, 2, etc. up to person 10.
for (int i = 0; i < 10; i++) {
    person[i] = i + 1;
    std::cout << "Input the number of pancakes entered by person " << person[i] << ": ";
    std::cin >> num_eaten_pancakes[i];
  }
}

//Who ate the most pancakes
int who_ate_most() {
for (int i = 0; i < 10; i++) {
    if (num_eaten_pancakes[i] > most_pancakes) {
        most_pancakes = num_eaten_pancakes[i];
        person_who_ate_most = person[i];
    }
  }
  return person_who_ate_most;
}

//Who ate the least pancakes
int who_ate_least() {
  for (int i = 0; i < 10; i++) {
     do
        least_pancakes = num_eaten_pancakes[i];
     while (i == 0);

     if (num_eaten_pancakes[i] < least_pancakes) {
         least_pancakes = num_eaten_pancakes[i];
         person_who_ate_least = person[i];
     }
   }
   return person_who_ate_least;
 }

header.h

#include <vector>
#include <string>

//VARIABLES
//Vectors for 10 people, pancakes
extern std::vector<int> person;
extern std::vector<int> num_eaten_pancakes;

extern int most_pancakes;
extern int least_pancakes;
extern int person_who_ate_most;
extern int person_who_ate_least;

//FUNCTIONS
void get_nums_of_pancakes();
int who_ate_most();
int who_ate_least();

The output, when I enter the number of pancakes consumed, is correct for the person who ate the most, but when it comes to the person who consumed the fewest, there's nothing.


问:
How to monitor a folder for new files in swift?
How would I monitor a folder for new files in swift, without polling (which is very inefficient)? I've heard of APIs such as kqueue and FSEvents - but I'm not sure it's possible to implement them in swift?</p>

答:
I faced a problem that is not mentioned in any of the answers. As my app is using a UIDocumentBrowserViewController (i.e. Apple's own Files app) to manage its documents, I have no control over my users' habits. I was using SKQueue to monitor all files in order to keep metadata in sync, and at a certain point the app started crashing.

As it turns out, there is an upper limit of 256 file descriptors that can be open by an app simultaneously, even just for monitoring. I ended up combining SKQueue and Apple's Directory Monitor (reference to which you can find in this answer of the current thread) to create a class I named SFSMonitor, which monitors a whole queue of files or directories by using Dispatch Sources.

I detailed my findings and the practices I now use in this SO thread.


问:
python search the user name
```<code>Mon Apr 27 18:12:54 '<rdpDirect> ITC\109975@win_itsskdcbkp2_10.18.2.104
Mon Apr 27 18:14:31 '<rdpDirect> JDAWMSAPPDEV\VINOTHKUMAR@win_jdawmsappdev_10.10.45.172
Mon Apr 27 18:14:32 '<rdpDirect> JDAWMSAPPDEV\VINOTHKUMAR@win_jdawmsappdev_10.10.45.172
Mon Apr 27 18:24:21 '<rdpDirect> SAAMARTHA\UITSMUSR@win_saamarthaad_10.10.45.147
Mon Apr 27 18:24:21 '<rdpDirect> SAAMARTHA\UITSMUSR@win_saamarthaad_10.10.45.147
</code>```

From the above text, need to search user name which is mentioned between the "\" and "@" sign. This can be numeric, characters, or alphanumeric.

eg: in the above example, 109975, VINOTHKUMAR, UITSMUSR etc.

答:
Search for the group with zero or more characters within \ and @ character.

```<code>import re

data = "Mon Apr 27 18:12:54 ' ITC\\109975@win_itsskdcbkp2_10.18.2.104 Mon Apr 27 18:14:31 ' JDAWMSAPPDEV\\VINOTHKUMAR@win_jdawmsappdev_10.10.45.172 Mon Apr 27 18:14:32 ' JDAWMSAPPDEV\\VINOTHKUMAR@win_jdawmsappdev_10.10.45.172 Mon Apr 27 18:24:21 ' SAAMARTHA\\UITSMUSR@win_saamarthaad_10.10.45.147 Mon Apr 27 18:24:21 ' SAAMARTHA\\UITSMUSR@win_saamarthaad_10.10.45.147"
usernames = re.findall(r"\\(.*?)@", data)
print(usernames)
</code>```

Output:

```<code>['109975', 'VINOTHKUMAR', 'VINOTHKUMAR', 'UITSMUSR', 'UITSMUSR']
</code>```

re.findall() method returns list of non overlapping occurrences of the searched string. More can be read in the official documentation of findall method.

Title: python search the user name

Body:
Mon Apr 27 18:12:54 '<rdpDirect> ITC\109975@win_itsskdcbkp2_10.18.2.104
Mon Apr 27 18:14:31 '<rdpDirect> JDAWMSAPPDEV\VINOTHKUMAR@win_jdawmsappdev_10.10.45.172
Mon Apr 27 18:14:32 '<rdpDirect> JDAWMSAPPDEV\VINOTHKUMAR@win_jdawmsappdev_10.10.45.172
Mon Apr 27 18:24:21 '<rdpDirect> SAAMARTHA\UITSMUSR@win_saamarthaad_10.10.45.147
Mon Apr 27 18:24:21 '<rdpDirect> SAAMARTHA\UITSMUSR@win_saamarthaad_10.10.45.147

From the above text, need to search user name which is mentioned between the "\" and "@" sign. This can be numeric, characters, or alphanumeric.

eg: in the above example, 109975, VINOTHKUMAR, UITSMUSR etc.

Body:
Search for the group with zero or more characters within \ and @ character.

import re

data = "Mon Apr 27 18:12:54 ' ITC\\109975@win_itsskdcbkp2_10.18.2.104 Mon Apr 27 18:14:31 ' JDAWMSAPPDEV\\VINOTHKUMAR@win_jdawmsappdev_10.10.45.172 Mon Apr 27 18:14:32 ' JDAWMSAPPDEV\\VINOTHKUMAR@win_jdawmsappdev_10.10.45.172 Mon Apr 27 18:24:21 ' SAAMARTHA\\UITSMUSR@win_saamarthaad_10.10.45.147 Mon Apr 27 18:24:21 ' SAAMARTHA\\UITSMUSR@win_saamarthaad_10.10.45.147"
usernames = re.findall(r"\\(.*?)@", data)
print(usernames)

Output:

['109975', 'VINOTHKUMAR', 'VINOTHKUMAR', 'UITSMUSR', 'UITSMUSR']

re.findall() method returns list of non overlapping occurrences of the searched string. More can be read in the official documentation of findall method.


答:
You got infinite-loop at this part, so the function who_ate_least stucked.

```<code>     do
        least_pancakes = num_eaten_pancakes[i];
     while (i == 0);
</code>```

Title: two std::cout, only one outputting

Body:
You got infinite-loop at this part, so the function who_ate_least stucked.

     do
        least_pancakes = num_eaten_pancakes[i];
     while (i == 0);


问:
pam_cracklib.so is not added to my Rocko build when I add PAM support
I am trying to add PAM support to my embedded Linux build.   I am using a the Rocko version of the Yocto project.  I added DISTRO_FEATURES_append += " pam" to my build. In my build I see the pam.d folder as expected.  In my /lib/security folder I see many of the expected modules like pam_unix.so and pam_group.so.  What I do NOT see is the pam_cracklib.so module.  I looked at the BB recipe for pam given by the Rocko release and I see that it depends on cracklib and the supplied cracklib recipe is run.

I must be missing something basic.  Why do I not see the pam_cracklib.so module available?  I also verified it is not in some other folder.

答: libpam recipe uses dynamic packaging to put each plugin into its own package. You need to add the correct package into your image: it should be pam-plugin-cracklib-<baselib> -- check e.g. the $WORKDIR/packages-split/ directory to see what packages were built.


问:
Set row number for batch of N rows per category
I have table

```<code>+-----+----------+---------+
| id  | name     | phase   |
+-----+----------+---------+
| 101 | Bolt     | PHASE 1 |
| 102 | Nut      | PHASE 1 |
| 103 | Screw    | PHASE 1 |
| 104 | Hex BOLT | PHASE 1 |
| 105 | Rubber   | PHASE 1 |
| 106 | Aluminum | PHASE 2 |
| 107 | Slate    | PHASE 2 |
| 108 | Pen      | PHASE 3 |
| 109 | Pencil   | PHASE 3 |
| 110 | Mouse    | PHASE 3 |
| 111 | Keyboard | PHASE 3 |
+-----+----------+---------+
</code>```

I want to create a another column in which i have to put row number.

Logic :
For 3 rows, it should be same and change to next value for 4th row. And Whenever the PHASE is changing, it should go to next number even if the set of 3 is not complete for the previous number.

Expected Output

```<code>+-----+----------+---------+-----+
| id  | name     | phase   | SET |
+-----+----------+---------+-----+
| 101 | Bolt     | PHASE 1 | 1   |
| 102 | Nut      | PHASE 1 | 1   |
| 103 | Screw    | PHASE 1 | 1   |
| 104 | Hex BOLT | PHASE 1 | 2   |
| 105 | Rubber   | PHASE 1 | 2   |
| 106 | Aluminum | PHASE 2 | 3   |
| 107 | Slate    | PHASE 2 | 3   |
| 108 | Pen      | PHASE 3 | 4   |
| 109 | Pencil   | PHASE 3 | 4   |
| 110 | Mouse    | PHASE 3 | 4   |
| 111 | Keyboard | PHASE 3 | 5   |
+-----+----------+---------+-----+
</code>```

I have tried the below query, but it is not giving me the required output.

```<code>select *, (row_number() over (order by phase)-1) / 3 as sets
from table_main
</code>```

Actual Output:

```<code>+-----+----------+---------+------+
| id  | name     | phase   | sets |
+-----+----------+---------+------+
| 101 | Bolt     | PHASE 1 | 0    |
| 102 | Nut      | PHASE 1 | 0    |
| 103 | Screw    | PHASE 1 | 0    |
| 104 | Hex BOLT | PHASE 1 | 1    |
| 105 | Rubber   | PHASE 1 | 1    |
| 106 | Aluminum | PHASE 2 | 1    |
| 107 | Slate    | PHASE 2 | 2    |
| 108 | Pen      | PHASE 3 | 2    |
| 109 | Pencil   | PHASE 3 | 2    |
| 110 | Mouse    | PHASE 3 | 3    |
| 111 | Keyboard | PHASE 3 | 3    |
+-----+----------+---------+------+
</code>```

I have tried with DENSE_RANK() as well but not getting the expected output.

FIDDLE HERE

答:
Give it a try:</p>

```<code>WITH CTE
as
(
select *, ROW_NUMBER () OVER (PARTITION BY phase ORDER BY id) as rn
from table_main
)
SELECT *,DENSE_RANK() over (ORDER BY phase ,CEILING(rn/3.0)) as set
FROM CTE
</code>```

Body:
I have table

+-----+----------+---------+
| id  | name     | phase   |
+-----+----------+---------+
| 101 | Bolt     | PHASE 1 |
| 102 | Nut      | PHASE 1 |
| 103 | Screw    | PHASE 1 |
| 104 | Hex BOLT | PHASE 1 |
| 105 | Rubber   | PHASE 1 |
| 106 | Aluminum | PHASE 2 |
| 107 | Slate    | PHASE 2 |
| 108 | Pen      | PHASE 3 |
| 109 | Pencil   | PHASE 3 |
| 110 | Mouse    | PHASE 3 |
| 111 | Keyboard | PHASE 3 |
+-----+----------+---------+

I want to create a another column in which i have to put row number.

Logic :
For 3 rows, it should be same and change to next value for 4th row. And Whenever the PHASE is changing, it should go to next number even if the set of 3 is not complete for the previous number.

Expected Output

+-----+----------+---------+-----+
| id  | name     | phase   | SET |
+-----+----------+---------+-----+
| 101 | Bolt     | PHASE 1 | 1   |
| 102 | Nut      | PHASE 1 | 1   |
| 103 | Screw    | PHASE 1 | 1   |
| 104 | Hex BOLT | PHASE 1 | 2   |
| 105 | Rubber   | PHASE 1 | 2   |
| 106 | Aluminum | PHASE 2 | 3   |
| 107 | Slate    | PHASE 2 | 3   |
| 108 | Pen      | PHASE 3 | 4   |
| 109 | Pencil   | PHASE 3 | 4   |
| 110 | Mouse    | PHASE 3 | 4   |
| 111 | Keyboard | PHASE 3 | 5   |
+-----+----------+---------+-----+

I have tried the below query, but it is not giving me the required output.

select *, (row_number() over (order by phase)-1) / 3 as sets
from table_main

Actual Output:

+-----+----------+---------+------+
| id  | name     | phase   | sets |
+-----+----------+---------+------+
| 101 | Bolt     | PHASE 1 | 0    |
| 102 | Nut      | PHASE 1 | 0    |
| 103 | Screw    | PHASE 1 | 0    |
| 104 | Hex BOLT | PHASE 1 | 1    |
| 105 | Rubber   | PHASE 1 | 1    |
| 106 | Aluminum | PHASE 2 | 1    |
| 107 | Slate    | PHASE 2 | 2    |
| 108 | Pen      | PHASE 3 | 2    |
| 109 | Pencil   | PHASE 3 | 2    |
| 110 | Mouse    | PHASE 3 | 3    |
| 111 | Keyboard | PHASE 3 | 3    |
+-----+----------+---------+------+

I have tried with DENSE_RANK() as well but not getting the expected output.

FIDDLE HERE

Body:
Give it a try:

WITH CTE
as
(
select *, ROW_NUMBER () OVER (PARTITION BY phase ORDER BY id) as rn
from table_main
)
SELECT *,DENSE_RANK() over (ORDER BY phase ,CEILING(rn/3.0)) as set
FROM CTE


问:
strtod accepts "e" but also "d" -- why?
I find this strange.

While it makes sense that strtod accepts 'e' as one of the characters (exactly one to be precise) in the input string I find that it also accepts 'd'.

Can someone please explain?

```<code>#include < stdio.h >
#include < stdlib.h >
int main ()
{
char *s[] = {"1a1", "1e1", "1d1", "1f1"};
char * pEnd;
double d0, d1, d2, d3;
d0 = strtod (s[0],&pEnd);
d1 = strtod (s[1],NULL);
d2 = strtod (s[2],NULL);
d3 = strtod (s[3],NULL);
printf ("::: [%f] [%f] [%f] [%f] \n", d0, d1, d2, d3);
return 0;
}
</code>```

答: Use of D instead of E is the Fortran way to mark out double data (instead of float).  You probably are using a standard library which accept it as an extension.

Title: strtod accepts "e" but also "d" -- why?

Body:
I find this strange.

While it makes sense that strtod accepts 'e' as one of the characters (exactly one to be precise) in the input string I find that it also accepts 'd'.

Can someone please explain?

#include < stdio.h >
#include < stdlib.h >
int main ()
{
char *s[] = {"1a1", "1e1", "1d1", "1f1"};
char * pEnd;
double d0, d1, d2, d3;
d0 = strtod (s[0],&pEnd);
d1 = strtod (s[1],NULL);
d2 = strtod (s[2],NULL);
d3 = strtod (s[3],NULL);
printf ("::: [%f] [%f] [%f] [%f] \n", d0, d1, d2, d3);
return 0;
}


问:
Passing params from a Google Cloud Function GET Request to BigQuery
I have successfully deployed a google cloud function that takes in parameters from a POST request.  I am now trying to change it to take in parameters from a GET request since the parameters don't contain any private data.

It seems I am correctly getting the passed in parameters, but when I then try to pass them to bigQuery it tells me I have missing parameters for my query.  I know my code is correct because if I hard code the values of the parameters it works correctly e.g.:

```<code>bigQuery.createQueryJob({
    query,
    params: {
    "make": "acura",
    "model": "mdx",
    "modelYear": 2005
}
}).then...
</code>```

I also know I am getting the parameters correctly because if I change my cloud function to just return the passed in query string params, it correctly returns them (commented out lines below).  If I change the cloud function to use req.body instead of req.query and make it a POST request, it also works fine.

I'm at a loss as to why "params" is not being passed to createQueryJob correctly.  Any help would be much appreciated.  Here is the code (I had to remove the actual query for privacy reasons):

package.json:

```<code>{
    "name": "sample-http",
    "version": "0.0.1",
    "dependencies": {
        "@google-cloud/bigquery": "^2.0.6"
    }
}
</code>```

index.js:

```<code>const { BigQuery } = require("@google-cloud/bigquery");

/**
 * Responds to any HTTP request.
 *
 * @param {!express:Request} req HTTP request context.
 * @param {!express:Response} res HTTP response context.
 */
exports.getRecallDataByVehicleInfo = (req, res) => {
    res.set('Access-Control-Allow-Origin', "*");
    res.set('Access-Control-Allow-Methods', 'GET, POST');
    res.setHeader(
        "Access-Control-Allow-Headers",
        "X-Requested-With,content-type"
    );

    const params = req.query;
   // res.status(200).send("make is - " + params.make + ", model is - " + params.model + ", model year is -" + params.modelYear);
   // return;

    const bigQuery = new BigQuery();

    const query = `myQuery
        where Make = @make
        and Model = @model
        and ModelYear = @modelYear`

    bigQuery.createQueryJob({
        query,
        params
    }).then(results => {
        const job = results[0];
        return job.getQueryResults({
            autoPaginate: false,
            timeoutMs: 1000000
        },
        callback());
    });

    const callback = () => (err, rows) => {
        if (err) {
            res.status(401).send(JSON.stringify(err));
        }
        else {
            res.status(200).send(rows);
        }
    };
}
</code>```

答:
You don't use the right method. Have a look to the createQueryJob definition

There is no param, it's for creating a query as job. If you have a look to the official (bad) example, you have to use query method. Here its definition

Note: Why the example is bad?

In the official example, the param provided to the query method is named option. In the documentation of the query method, the first (and mandatory) param is named query, and you can optionally add an option param. So, the naming is confusing.

Body:
I have successfully deployed a google cloud function that takes in parameters from a POST request.  I am now trying to change it to take in parameters from a GET request since the parameters don't contain any private data.

It seems I am correctly getting the passed in parameters, but when I then try to pass them to bigQuery it tells me I have missing parameters for my query.  I know my code is correct because if I hard code the values of the parameters it works correctly e.g.:

bigQuery.createQueryJob({
    query,
    params: {
    "make": "acura",
    "model": "mdx",
    "modelYear": 2005
}
}).then...

I also know I am getting the parameters correctly because if I change my cloud function to just return the passed in query string params, it correctly returns them (commented out lines below).  If I change the cloud function to use req.body instead of req.query and make it a POST request, it also works fine.

I'm at a loss as to why "params" is not being passed to createQueryJob correctly.  Any help would be much appreciated.  Here is the code (I had to remove the actual query for privacy reasons):

package.json:

{
    "name": "sample-http",
    "version": "0.0.1",
    "dependencies": {
        "@google-cloud/bigquery": "^2.0.6"
    }
}

index.js:

const { BigQuery } = require("@google-cloud/bigquery");

/**
 * Responds to any HTTP request.
 *
 * @param {!express:Request} req HTTP request context.
 * @param {!express:Response} res HTTP response context.
 */
exports.getRecallDataByVehicleInfo = (req, res) => {
    res.set('Access-Control-Allow-Origin', "*");
    res.set('Access-Control-Allow-Methods', 'GET, POST');
    res.setHeader(
        "Access-Control-Allow-Headers",
        "X-Requested-With,content-type"
    );

    const params = req.query;
   // res.status(200).send("make is - " + params.make + ", model is - " + params.model + ", model year is -" + params.modelYear);
   // return;

    const bigQuery = new BigQuery();

    const query = `myQuery
        where Make = @make
        and Model = @model
        and ModelYear = @modelYear`

    bigQuery.createQueryJob({
        query,
        params
    }).then(results => {
        const job = results[0];
        return job.getQueryResults({
            autoPaginate: false,
            timeoutMs: 1000000
        },
        callback());
    });

    const callback = () => (err, rows) => {
        if (err) {
            res.status(401).send(JSON.stringify(err));
        }
        else {
            res.status(200).send(rows);
        }
    };
}


答:
These are two different types of vector representation called dense and sparse. For example, a dense vector [21.0,5.0,0.0,0.0] is same as sparse vector (4, [0,1], [21.0, 5.0]) where 4 represents size of the vector, [0,1] represents indices having non-zero elements and [21.0, 5.0] represents corresponding values. All other values are assumed to be zero.

The representation of the vector depends on the number of zeros in the vector. If a vector has more zeros it will be represented by a sparse vector whereas if a vector has more non-zero elements it will be represented by a dense vector.

There is no need to fix anything in this.

Check out this spark document for more clarification

Title: Why results structure change when I change column name in Python spark?

Body:
My dataframe dff is this

       10311  105903003  373873005  385055001  392521001  ...  26  27  28  29  30
0       21.0        5.0        5.0       21.0        8.0  ...   0   0   0   0   1
1        0.0        3.0        3.0        0.0        6.0  ...   0   0   0   0   1
2       32.0        8.0        8.0       32.0        4.0  ...   0   0   0   0   1
3       15.0        7.0        7.0       15.0        5.0  ...   0   0   0   0   1
4        0.0        4.0        4.0        0.0        4.0  ...   0   0   0   0   1
     ...        ...        ...        ...        ...  ...  ..  ..  ..  ..  ..
52699    0.0        2.0        2.0        0.0        6.0  ...   0   0   0   0   1
52700    0.0        2.0        2.0        0.0        6.0  ...   0   0   0   0   1
52701   22.0        4.0        4.0       22.0        9.0  ...   0   0   0   0   1
52702    0.0        4.0        4.0        0.0        8.0  ...   0   0   0   0   1
52703    0.0        2.0        2.0        0.0        2.0  ...   0   0   0   0   1
[52704 rows x 43 columns]

and this is my code

from pyspark.sql import SQLContext
sc = SparkContext.getOrCreate()
sqlContext = SQLContext(sc)

spark_dff = sqlContext.createDataFrame(dff.astype(float))
spark_dff.head(4)

Returns this

Out[99]:
[Row(10311=21.0, 105903003=5.0, 373873005=5.0, 385055001=21.0, 392521001=8.0, 410942007=5.0, 423367003=12.0, 46992007=21.0, 4850=27.0, 87612001=43.0, filename=1.0, filename_int=1.0, 0=0.0, 1=0.0, 2=0.0, 3=0.0, 4=0.0, 5=0.0, 6=0.0, 7=0.0, 8=0.0, 9=0.0, 10=0.0, 11=0.0, 12=0.0, 13=0.0, 14=0.0, 15=0.0, 16=0.0, 17=0.0, 18=0.0, 19=0.0, 20=0.0, 21=0.0, 22=0.0, 23=0.0, 24=0.0, 25=0.0, 26=0.0, 27=0.0, 28=0.0, 29=0.0, 30=1.0),
 Row(10311=0.0, 105903003=3.0, 373873005=3.0, 385055001=0.0, 392521001=6.0, 410942007=3.0, 423367003=0.0, 46992007=0.0, 4850=6.0, 87612001=3.0, filename=10.0, filename_int=10.0, 0=0.0, 1=0.0, 2=0.0, 3=0.0, 4=0.0, 5=0.0, 6=0.0, 7=0.0, 8=0.0, 9=0.0, 10=0.0, 11=0.0, 12=0.0, 13=0.0, 14=0.0, 15=0.0, 16=0.0, 17=0.0, 18=0.0, 19=0.0, 20=0.0, 21=0.0, 22=0.0, 23=0.0, 24=0.0, 25=0.0, 26=0.0, 27=0.0, 28=0.0, 29=0.0, 30=1.0),
 Row(10311=32.0, 105903003=8.0, 373873005=8.0, 385055001=32.0, 392521001=4.0, 410942007=8.0, 423367003=15.0, 46992007=32.0, 4850=9.0, 87612001=9.0, filename=100.0, filename_int=100.0, 0=0.0, 1=0.0, 2=0.0, 3=0.0, 4=0.0, 5=0.0, 6=0.0, 7=0.0, 8=0.0, 9=0.0, 10=0.0, 11=0.0, 12=0.0, 13=0.0, 14=0.0, 15=0.0, 16=0.0, 17=0.0, 18=0.0, 19=0.0, 20=0.0, 21=0.0, 22=0.0, 23=0.0, 24=0.0, 25=0.0, 26=0.0, 27=0.0, 28=0.0, 29=0.0, 30=1.0),
 Row(10311=15.0, 105903003=7.0, 373873005=7.0, 385055001=15.0, 392521001=5.0, 410942007=7.0, 423367003=7.0, 46992007=15.0, 4850=12.0, 87612001=21.0, filename=10000.0, filename_int=10000.0, 0=0.0, 1=0.0, 2=0.0, 3=0.0, 4=0.0, 5=0.0, 6=0.0, 7=0.0, 8=0.0, 9=0.0, 10=0.0, 11=0.0, 12=0.0, 13=0.0, 14=0.0, 15=0.0, 16=0.0, 17=0.0, 18=0.0, 19=0.0, 20=0.0, 21=0.0, 22=0.0, 23=0.0, 24=0.0, 25=0.0, 26=0.0, 27=0.0, 28=0.0, 29=0.0, 30=1.0)]

spark_dff

returns this

spark_dff
Out[100]: DataFrame[10311: double, 105903003: double, 373873005: double, 385055001: double, 392521001: double, 410942007: double, 423367003: double, 46992007: double, 4850: double, 87612001: double, filename: double, filename_int: double, 0: double, 1: double, 2: double, 3: double, 4: double, 5: double, 6: double, 7: double, 8: double, 9: double, 10: double, 11: double, 12: double, 13: double, 14: double, 15: double, 16: double, 17: double, 18: double, 19: double, 20: double, 21: double, 22: double, 23: double, 24: double, 25: double, 26: double, 27: double, 28: double, 29: double, 30: double]

Now here is my problem

lz = ['10311','105903003','373873005','385055001']      #<------ (1)

from pyspark.ml.feature import VectorAssembler
vectorAssemblerZ = VectorAssembler(inputCols = lz , outputCol = 'zz')
vhouse_df = vectorAssemblerZ.transform(spark_dff)
vhouse_df = vhouse_df.select(['zz'])
vhouse_df.show(3)

this will return

+-------------------+
|                 zz|
+-------------------+
|[21.0,5.0,5.0,21.0]|
|  [0.0,3.0,3.0,0.0]|
|[32.0,8.0,8.0,32.0]|
+-------------------+

This looks good
an array with 4 values in it.

but when I change the line (1)

lz = ['1','2','3','4']

The result becomes different structure  !!!!

+-----------------+
|               zz|
+-----------------+
|        (4,[],[])|
|    (4,[2],[1.0])|
|    (4,[3],[1.0])|
+-----------------+

Its a number then array, then another array !!!

I dont know why it is this structure

I made another change

lz = ['10311','105903003','3','4']

The result is even weirder!!

+------------------+
|                zz|
+------------------+
|[21.0,5.0,0.0,0.0]|
|     (4,[1],[3.0])|
|[32.0,8.0,0.0,0.0]|
+------------------+

Why when I change the column the structure change and how I can I get this fixed?!


问:
How to scale histogram y-axis in million in matplotlib
I am plotting a histogram using matplotlib but my y-axis range is in the millions. How can I scale the y-axis so that instead of printing 5000000 it will print 5

Here is my code

```<code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

filename = './norstar10readlength.csv'
df=pd.read_csv(filename, sep=',',header=None)

n, bins, patches = plt.hist(x=df.values, bins=10, color='#0504aa',
                            alpha=0.7, rwidth=0.85)
plt.grid(axis='y', alpha=0.75)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('My Very Own Histogram')
maxfreq = n.max()
# Set a clean upper y-axis limit.
plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)
plt.show()
</code>```

And here is the plot I am generating now

答:
An elegant solution is to apply a FuncFormatter to format y labels.

Instead of your source data, I used the following DataFrame:

```<code>       Val
0   800000
1  2600000
2  6700000
3  1400000
4  1700000
5  1600000
</code>```

and made a bar plot. "Ordinary" bar plot:

```<code>df.Val.plot.bar(rot=0, width=0.75);
</code>```

yields a picture with original values on the y axis (1000000 to
7000000).

But if you run:

```<code>from matplotlib.ticker import FuncFormatter

def lblFormat(n, pos):
    return str(int(n / 1e6))

lblFormatter = FuncFormatter(lblFormat)
ax = df.Val.plot.bar(rot=0, width=0.75)
ax.yaxis.set_major_formatter(lblFormatter)
</code>```

then y axis labels are integers (the number of millions):

So you can arrange your code something like this:

```<code>n, bins, patches = plt.hist(x=df.values, ...)
#
# Other drawing actions, up to "plt.ylim" (including)
#
ax = plt.gca()
ax.yaxis.set_major_formatter(lblFormatter)
plt.show()
</code>```

Body:
I am plotting a histogram using matplotlib but my y-axis range is in the millions. How can I scale the y-axis so that instead of printing 5000000 it will print 5

Here is my code

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

filename = './norstar10readlength.csv'
df=pd.read_csv(filename, sep=',',header=None)

n, bins, patches = plt.hist(x=df.values, bins=10, color='#0504aa',
                            alpha=0.7, rwidth=0.85)
plt.grid(axis='y', alpha=0.75)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('My Very Own Histogram')
maxfreq = n.max()
# Set a clean upper y-axis limit.
plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)
plt.show()

And here is the plot I am generating now

Body:
An elegant solution is to apply a FuncFormatter to format y labels.

Instead of your source data, I used the following DataFrame:

       Val
0   800000
1  2600000
2  6700000
3  1400000
4  1700000
5  1600000

and made a bar plot. "Ordinary" bar plot:

df.Val.plot.bar(rot=0, width=0.75);

yields a picture with original values on the y axis (1000000 to
7000000).

But if you run:

from matplotlib.ticker import FuncFormatter

def lblFormat(n, pos):
    return str(int(n / 1e6))

lblFormatter = FuncFormatter(lblFormat)
ax = df.Val.plot.bar(rot=0, width=0.75)
ax.yaxis.set_major_formatter(lblFormatter)

then y axis labels are integers (the number of millions):

So you can arrange your code something like this:

n, bins, patches = plt.hist(x=df.values, ...)
#
# Other drawing actions, up to "plt.ylim" (including)
#
ax = plt.gca()
ax.yaxis.set_major_formatter(lblFormatter)
plt.show()


问:
Unable to get IAM security credentials for AWS S3
This error is driving me crazy, had the same issue with a lambda web api, but that worked when uploaded, so that will do for now

This project however will be a NuGet package, and i need to be able to simply upload a file to S3

I have the code in place using the following : "https://docs.aws.amazon.com/AmazonS3/latest/dev/HLuploadFileDotNet.html"

im trying to run this local, but getting the Unable to get IAM security credentials from EC2 Instance Metadata Service." error

within visual studio, i can see the AWS Explorer, and i can create a bucket from here... so i have my user setup... but when i run local... there is no user???

i know its going to be a one line missing value somewhere :(

答:
Thank you @Geeshan for your answer, it gave me some direction on where to look

However, I had my credentials file setup, but the answer to my question was you also need to have a profile setup with the name "default"

Also, now know that you dont need a matching "default" IAM user.

On the AWS IAM User page, you create your users as normal, no need to create a default user.  In Visual studio, when you create a new profile, if your profile is named "default", and you enter they key and secret key for one of your IAM user, running your application will use that user (I miss understood this profile name, and was assuming it needs to match your IAM user, so initially i create a "Default" IAM user. which i now know, is not needed)

If you dont want to use the default then, you can choose a user by using "TryGetProfile and TryGetAWSCredentials in your application code (see below)