问:
Listen for Google Cast Session Events on iOS
I'm using the Google Cast SDK from iOS. I'm able to cast my application correctly, but I'm not able to get the <GCKSessionManagerListener> Protocol to work correctly. According to the GCKSessionManager documenation, I should just be able to bind the listener and define the callbacks I care about, but they don't seem to be called:

I initialize and bind the listener (on the main application thread):

```<code>GCKCastOptions *options =
    [[GCKCastOptions alloc] initWithReceiverApplicationID:@"ABCDEFGH"];
[GCKCastContext setSharedInstanceWithOptions:options];

GCKSessionManager *sessionManager =
    [GCKCastContext sharedInstance].sessionManager;
[sessionManager addListener:self];
</code>```

Then I've defined (in the same file):

```<code>#pragma mark - GCKSessionManagerListener

- (void)sessionManager:(GCKSessionManager *)sessionManager
    didStartSession:(GCKSession *)session {
  RCTLogInfo(@"EVENT didStartSession");
}
</code>```

I've also tried the didStartCastSession variant without any luck either.

In my header file, I include the interface too:

```<code>@interface MyGoogleCast : NSObject <RCTBridgeModule, GCKSessionManagerListener>
</code>```

What am I missing?

答: I was able to resolve a similar problem by postponing the addListener call until later in the app lifecycle.

Body:
I'm using the Google Cast SDK from iOS. I'm able to cast my application correctly, but I'm not able to get the <GCKSessionManagerListener> Protocol to work correctly. According to the GCKSessionManager documenation, I should just be able to bind the listener and define the callbacks I care about, but they don't seem to be called:

I initialize and bind the listener (on the main application thread):

GCKCastOptions *options =
    [[GCKCastOptions alloc] initWithReceiverApplicationID:@"ABCDEFGH"];
[GCKCastContext setSharedInstanceWithOptions:options];

GCKSessionManager *sessionManager =
    [GCKCastContext sharedInstance].sessionManager;
[sessionManager addListener:self];

Then I've defined (in the same file):

#pragma mark - GCKSessionManagerListener

- (void)sessionManager:(GCKSessionManager *)sessionManager
    didStartSession:(GCKSession *)session {
  RCTLogInfo(@"EVENT didStartSession");
}

I've also tried the didStartCastSession variant without any luck either.

In my header file, I include the interface too:

@interface MyGoogleCast : NSObject <RCTBridgeModule, GCKSessionManagerListener>

What am I missing?


来源: stackexchange

问:
Read in scientific notation with numpy loadtxt
I have a datafile containing 3 columns with floats in scientific notation,

```<code>20346.7353    0.139945D+04    0.922215D+03
20347.0689    0.139958D+04    0.922340D+03
20347.4024    0.139970D+04    0.922464D+03
20347.7360    0.139983D+04    0.922589D+03
...           ...             ...
</code>```

, which I want to read using a python script in order to plot the data with pyplot. However the numpy loadtxt command

x, y1, y2 = np.loadtxt(sys.argv[1], unpack=True, dtype=float, usecols=(0, 1, 2))

does not recognise the floats due to the scientific notation. How could I read in this file (with approximately 30000 lines)?
Thank you

ContentLicense: CC BY-SA 4.0

Body:
I have a datafile containing 3 columns with floats in scientific notation,

20346.7353    0.139945D+04    0.922215D+03
20347.0689    0.139958D+04    0.922340D+03
20347.4024    0.139970D+04    0.922464D+03
20347.7360    0.139983D+04    0.922589D+03
...           ...             ...

, which I want to read using a python script in order to plot the data with pyplot. However the numpy loadtxt command

x, y1, y2 = np.loadtxt(sys.argv[1], unpack=True, dtype=float, usecols=(0, 1, 2))

does not recognise the floats due to the scientific notation. How could I read in this file (with approximately 30000 lines)?
Thank you

Body:
The python scientific notation uses E, not D. So you can replace them before reading the data:

# reading from string here, read from file in your case
data = '''20346.7353    0.139945D+04    0.922215D+03
20347.0689    0.139958D+04    0.922340D+03
20347.4024    0.139970D+04    0.922464D+03
20347.7360    0.139983D+04    0.922589D+03'''

import io

np.loadtxt(io.StringIO(data.replace('D', 'E')))

output:

array([[20346.7353,  1399.45  ,   922.215 ],
       [20347.0689,  1399.58  ,   922.34  ],
       [20347.4024,  1399.7   ,   922.464 ],
       [20347.736 ,  1399.83  ,   922.589 ]])


问:
DataContext. Is there a single method where I can add an extra WHERE?
So basically I have an application that works with just one user, but I'd like to make it multi-user. This would involve me logging a user in, and keeping the user ID in session, plus adding a user id column to my database tables. no biggy.

I'd like to change my dbml, or use it's partial, so that any query I throw through it also gets

```<code>.WHERE(user=>user.id=MYPARAM)
</code>```

added to it, to return just records for the logged in user.

Is there a quick win to be had? A single place where I can specify this in the .dbml?

答:
I would perhaps create a lambda expression dynamically.

The Where clause takes an object of type Expression>

You can then create an expression using the following.

```<code>Expression<Func<User,bool>> func = null;
</code>```

Then

```<code>ParameterExpression xParam = Expression.Parameter(typeof(User), "u");
</code>```

You would then create an expression for u.id = "test" by using a binary expression.

```<code>BinaryExpression uidTest = Expression.Equal(Expression.Property(xParam, "id"),
                                                               Expression.Constant("test");
</code>```

and then attaching it to the Expression as follows:

```<code>func = Expression.Lambda<Func<User, bool>>(uidTest, xParam)
</code>```

In effect this is building a lambda expression u=> u.id = "test"

The func object can then be used in the .Where as follows:
.Where(func)

Obviously, you can dynamically build this to any criteria you need at any time in your application.

OwnerDisplayName: jdee

ContentLicense: CC BY-SA 2.5

Body:
So basically I have an application that works with just one user, but I'd like to make it multi-user. This would involve me logging a user in, and keeping the user ID in session, plus adding a user id column to my database tables. no biggy.

I'd like to change my dbml, or use it's partial, so that any query I throw through it also gets

.WHERE(user=>user.id=MYPARAM)

added to it, to return just records for the logged in user.

Is there a quick win to be had? A single place where I can specify this in the .dbml?

LastEditorDisplayName: jdee

Body:
I would perhaps create a lambda expression dynamically.

The Where clause takes an object of type Expression>

You can then create an expression using the following.

Expression<Func<User,bool>> func = null;

Then

ParameterExpression xParam = Expression.Parameter(typeof(User), "u");

You would then create an expression for u.id = "test" by using a binary expression.

BinaryExpression uidTest = Expression.Equal(Expression.Property(xParam, "id"),
                                                               Expression.Constant("test");

and then attaching it to the Expression as follows:

func = Expression.Lambda<Func<User, bool>>(uidTest, xParam)

In effect this is building a lambda expression u=> u.id = "test"

The func object can then be used in the .Where as follows:
.Where(func)

Obviously, you can dynamically build this to any criteria you need at any time in your application.

OwnerDisplayName: Kinlan


问:
PUT command Snowflake on VSCode
I use the snowflake driver for SQLTools on vscode and i'm connect to my snowflake account but i'm some issues when i want to put some files with extensions .csv from my local machine to my stage in snowflake. Indeed, when i use the command put file:///mypath/file.csv @nameofmystage; it works on terminal but not in the window vscode with extension Snowflake driver. However, others commands like copy into works on the driver vscode ...

The error's message is Unsupported feature 'unsupported_requested_format:snowflake'

thanks in advance for your help

答:
Not a solution or final answer, but a hint - here someone is having the same error, but with the Go-Driver: https://github.com/snowflakedb/gosnowflake/issues/227

Go didn't support PUT in this case.

Title: PUT command Snowflake on VSCode


问:
How to "describe" a column in pandas for python
I'm using pandas in python and I have a dataframe where one column is a timestamp and others contain data.

The blue line stays constant for a while, then suddenly increases to zero, then at some point descends again to about -98 and stays there until it suddenly goes up to zero. What I need is a new column with the status of the blue color: constant,sudden increase, constant, decrease, constant, sudden increase, constant or somehow an object that describes the data:

```<code>blue line{
'08.02.2022 08:30:00.000' : 'sudden increase',
'08.02.2022 10:39:30.000' : 'start decrease',
'08.02.2022 10:59:40.000' : 'end decrease',
'08.02.2022 13:50:30.000' : 'sudden increase'
}
</code>```

Is there a package for something like this? I hope it isn't too far feched

Kind Regards, Alexander

答:
constant,sudden increase, constant, decrease, constant, sudden
increase, constant

Then I suggest taking looking at numpy.gradient, consider following simple example

```<code>import numpy as np
arr = np.array([0,0,0,1,2,3,4,5,6,7,7,7,7,7,5,3,1])
arrg = np.gradient(arr)
for a,g in zip(arr,arrg):
    print(a,g,sep=",")
</code>```

output

```<code>0,0.0
0,0.0
0,0.5
1,1.0
2,1.0
3,1.0
4,1.0
5,1.0
6,1.0
7,0.5
7,0.0
7,0.0
7,0.0
7,-1.0
5,-2.0
3,-2.0
1,-2.0
</code>```

Observe that constant parts result in zeros (potentially excluding these point adjacent to increase/decrease), increase result in positive values, decrease result in negative values, more increase/decrease the more value is far from zero.

You might need to convert pandas.Series (column of pandas.DataFrame) into numpy.array - for which pandas.Series sports method .to_numpy.

Disclaimer: this solution assumes that your data are evenly spaced, e.g. from sensor providing value each second.

Edit in order to detect borders of increase/decrease you might leverage numpy.diff following way, using arr and arrg from example above

```<code>arrb = abs(np.diff(arrg)) > 0.01
for a,b in zip(arr,arrb):
    print(a,b,sep=",")
</code>```

output

```<code>0,False
0,True
0,True
1,False
2,False
3,False
4,False
5,False
6,True
7,True
7,False
7,False
7,True
7,True
5,False
3,False
</code>```

Beware that due to how numpy.diff work you will get result shorter by 1 observation.

This does compute difference between adjacent elements then checks if it is absolute value is greater than 0.01 (you might need to adjust value depending on your data), when there is True (possibly few adjacent Trues) there is kink.

Body:
I'm using pandas in python and I have a dataframe where one column is a timestamp and others contain data.

The blue line stays constant for a while, then suddenly increases to zero, then at some point descends again to about -98 and stays there until it suddenly goes up to zero. What I need is a new column with the status of the blue color: constant,sudden increase, constant, decrease, constant, sudden increase, constant or somehow an object that describes the data:

blue line{
'08.02.2022 08:30:00.000' : 'sudden increase',
'08.02.2022 10:39:30.000' : 'start decrease',
'08.02.2022 10:59:40.000' : 'end decrease',
'08.02.2022 13:50:30.000' : 'sudden increase'
}

Is there a package for something like this? I hope it isn't too far feched

Kind Regards, Alexander

Body:
constant,sudden increase, constant, decrease, constant, sudden
increase, constant

Then I suggest taking looking at numpy.gradient, consider following simple example

import numpy as np
arr = np.array([0,0,0,1,2,3,4,5,6,7,7,7,7,7,5,3,1])
arrg = np.gradient(arr)
for a,g in zip(arr,arrg):
    print(a,g,sep=",")

output

0,0.0
0,0.0
0,0.5
1,1.0
2,1.0
3,1.0
4,1.0
5,1.0
6,1.0
7,0.5
7,0.0
7,0.0
7,0.0
7,-1.0
5,-2.0
3,-2.0
1,-2.0

Observe that constant parts result in zeros (potentially excluding these point adjacent to increase/decrease), increase result in positive values, decrease result in negative values, more increase/decrease the more value is far from zero.

You might need to convert pandas.Series (column of pandas.DataFrame) into numpy.array - for which pandas.Series sports method .to_numpy.

Disclaimer: this solution assumes that your data are evenly spaced, e.g. from sensor providing value each second.

Edit in order to detect borders of increase/decrease you might leverage numpy.diff following way, using arr and arrg from example above

arrb = abs(np.diff(arrg)) > 0.01
for a,b in zip(arr,arrb):
    print(a,b,sep=",")

output

0,False
0,True
0,True
1,False
2,False
3,False
4,False
5,False
6,True
7,True
7,False
7,False
7,True
7,True
5,False
3,False

Beware that due to how numpy.diff work you will get result shorter by 1 observation.

This does compute difference between adjacent elements then checks if it is absolute value is greater than 0.01 (you might need to adjust value depending on your data), when there is True (possibly few adjacent Trues) there is kink.


问:
How can I sort a JPA query result where the parameter is a String and the result is a List of Objects?
I'm writing a Spring Boot API endpoint and I need to return a list of Airlines ordered by a String (description) of 3 or more chars, the List must be sorted with the results that match the String at the beginning of the word at the top and the rest by alphabetical order

Airline class:

```<code>@Getter
@Setter
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "airline")
public class Airline implements Serializable {
    private static final long serialVersionUID = -5962418077659300886L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;

    @Column
    private String code;

    @Column
    private String description;
}
</code>```

I get the list that matches the String but I cannot get the order right

AirlineRepository

```<code>public interface AirlineRepository extends JpaRepository<Airline, Integer> {
    Airline getById(Integer id);

    List<Airline> findByDescriptionContainingIgnoreCase(String description, Pageable pageable);
    List<Airline> findByDescriptionStartsWithIgnoreCase(String description, Pageable pageable);
}
</code>```

If I search the keyword 'ala' all airlines whose name starts with 'ala' should come first.

This is what I get

```<code>{
  "status": "SUCCESS",
  "message": "Execution Successful",
  "totalCount": 10,
  "content": [
    {
      "id": 962,
      "code": "6T",
      "description": "Air Mandalay"
    },
    {
      "id": 46,
      "code": "NZ",
      "description": "Air New Zealand"
    },
    {
      "id": 18,
      "code": "AS",
      "description": "Alaska Airlines"
    },
    {
      "id": 519,
      "code": "KO",
      "description": "Alaska Central Express"
    },
    {
      "id": 477,
      "code": "J5",
      "description": "Alaska Seaplane"
    },
    {
      "id": 30,
      "code": "YZ",
      "description": "ALAS URUGUAY"
    },
    {
      "id": 324,
      "code": "C9",
      "description": "Alphaland Aviation"
    },
    {
      "id": 286,
      "code": "A7",
      "description": "Calafia Airlines"
    },
    {
      "id": 330,
      "code": "CE",
      "description": "Chalair"
    },
    {
      "id": 521,
      "code": "L3",
      "description": "DHL de Guatemala"
    }
  ],
  "timestamp": null
}````
```

答:
you can use something like :

```<code>@Query("select * from Airline a order by substring(a.description, 0,search_text_length)")
List<Airline> findAirline();
</code>```

You can get an idea here

Body:
I'm writing a Spring Boot API endpoint and I need to return a list of Airlines ordered by a String (description) of 3 or more chars, the List must be sorted with the results that match the String at the beginning of the word at the top and the rest by alphabetical order

Airline class:

@Getter
@Setter
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "airline")
public class Airline implements Serializable {
    private static final long serialVersionUID = -5962418077659300886L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;

    @Column
    private String code;

    @Column
    private String description;
}

I get the list that matches the String but I cannot get the order right

AirlineRepository

public interface AirlineRepository extends JpaRepository<Airline, Integer> {
    Airline getById(Integer id);

    List<Airline> findByDescriptionContainingIgnoreCase(String description, Pageable pageable);
    List<Airline> findByDescriptionStartsWithIgnoreCase(String description, Pageable pageable);
}

If I search the keyword 'ala' all airlines whose name starts with 'ala' should come first.

This is what I get

{
  "status": "SUCCESS",
  "message": "Execution Successful",
  "totalCount": 10,
  "content": [
    {
      "id": 962,
      "code": "6T",
      "description": "Air Mandalay"
    },
    {
      "id": 46,
      "code": "NZ",
      "description": "Air New Zealand"
    },
    {
      "id": 18,
      "code": "AS",
      "description": "Alaska Airlines"
    },
    {
      "id": 519,
      "code": "KO",
      "description": "Alaska Central Express"
    },
    {
      "id": 477,
      "code": "J5",
      "description": "Alaska Seaplane"
    },
    {
      "id": 30,
      "code": "YZ",
      "description": "ALAS URUGUAY"
    },
    {
      "id": 324,
      "code": "C9",
      "description": "Alphaland Aviation"
    },
    {
      "id": 286,
      "code": "A7",
      "description": "Calafia Airlines"
    },
    {
      "id": 330,
      "code": "CE",
      "description": "Chalair"
    },
    {
      "id": 521,
      "code": "L3",
      "description": "DHL de Guatemala"
    }
  ],
  "timestamp": null
}````

Body:
you can use something like :

@Query("select * from Airline a order by substring(a.description, 0,search_text_length)")
List<Airline> findAirline();

You can get an idea here


问:
Save Pandas DataFrames with formulas to xlsx files
In a Pandas DataFrame i have some "cells" with values and some that need to contain excel formulas. I have read that i can get formulas with

```<code>link = 'HYPERLINK("#Groups!A' + str(someInt) + '"; "LINKTEXT")'
xlwt.Formula(link)
</code>```

and store them in the dataframe.

When i try to save my dataframe as an xlsx file with

```<code>writer = pd.ExcelWriter("pandas" + str(fileCounter) + ".xlsx", engine = "xlsxwriter")
df.to_excel(writer, sheet_name = "Paths", index = False)
# insert more sheets here
writer.save()
</code>```

i get the error:

```<code>TypeError: Unsupported type <class 'xlwt.ExcelFormula.Formula'> in write()
</code>```

So i tried to write my formula as a string to my dataframe but Excel wants to restore the file content and then fills all formula cells with 0's.

Edit: I managed to get it work with regular strings but nevertheless would be interested in a solution for xlwt formulas.

So my question is: How do i save dataframes with formulas to xlsx files?

答:
you need to save in as usual just keep in mind to write the formula as string.

you can use also f strings with vars.

```<code>    writer = pd.ExcelWriter(FILE_PATH ,mode='a', if_sheet_exists='overlay')

    col_Q_index = 3
    best_formula = f'=max(L1,N98,Q{col_Q_index})'
    formula_df = pd.DataFrame([[best_formula]])
    formula_df.to_excel(writer, sheet_name=SHEET_NAME, startrow=i, startcol=17, index=False, header=False)

    writer.save()
</code>```

Body:
In a Pandas DataFrame i have some "cells" with values and some that need to contain excel formulas. I have read that i can get formulas with

link = 'HYPERLINK("#Groups!A' + str(someInt) + '"; "LINKTEXT")'
xlwt.Formula(link)

and store them in the dataframe.

When i try to save my dataframe as an xlsx file with

writer = pd.ExcelWriter("pandas" + str(fileCounter) + ".xlsx", engine = "xlsxwriter")
df.to_excel(writer, sheet_name = "Paths", index = False)
# insert more sheets here
writer.save()

i get the error:

TypeError: Unsupported type <class 'xlwt.ExcelFormula.Formula'> in write()

So i tried to write my formula as a string to my dataframe but Excel wants to restore the file content and then fills all formula cells with 0's.

Edit: I managed to get it work with regular strings but nevertheless would be interested in a solution for xlwt formulas.

So my question is: How do i save dataframes with formulas to xlsx files?

Body:
you need to save in as usual just keep in mind to write the formula as string.

you can use also f strings with vars.

    writer = pd.ExcelWriter(FILE_PATH ,mode='a', if_sheet_exists='overlay')

    col_Q_index = 3
    best_formula = f'=max(L1,N98,Q{col_Q_index})'
    formula_df = pd.DataFrame([[best_formula]])
    formula_df.to_excel(writer, sheet_name=SHEET_NAME, startrow=i, startcol=17, index=False, header=False)

    writer.save()


问:
How do I get Magento 2 data to use in the template?
I am starting in the Magento development world, and I'm creating a new theme.

On my theme, I have a block which displays business contact info, but I don't know how to get the data from the store.
I have to make a custom menu as well, but stop in the same problem: getting category data from the store.

I also wanted to know if there is any place where you can find more references on this data return issue, such as what available methods and classes are available, for example.

答:
Where do you want to display the custom data ? In a product page or your custom module's separate page ?

If you want to use custom block in sidebar you can follow steps given here
https://aureatelabs.com/magento-2/how-to-add-a-static-block-in-a-sidebar-column-magento-2/.

Here are some ref you can use:

https://itectec.com/magento/magento-magento-2-get-custom-module-data-in-theme-phtml/

https://code.vky.co.in/display-custom-module-collection-data-frontend-magento-2/


问:
Get file from GCS and load to bigquery based on file name pattern
We have requirement of loading file from gcs bucket to different bigquery table based on file name pattern.
eg

```<code>bucket/folder/test_a_20221023.csv  -> should go to table a
bucket/folder/file_a_20221023_2.csv  -> should go to table a
bucket/folder/control_b_20221023.csv  -> should go to table b
bucket/folder/test_b_20221023_2.csv  -> should go to table b
</code>```

So prefix can be anything before a or b pattern in the filename and based on a or b we have to load to specific table in bigquery. Is there any way to get the file in gcs based on some pattern other than gsutil command

```<code>gsutil ls gs://[BUCKET_NAME]/** | grep string
</code>```

答: I strongly recommend to you use a BATCH DataFlow to make this, maybe it's gonna be necessary learn how to use a Apache-beam[GCP] or you can try use a DEFAULT Dataflow that make this, but I don't think he gonna respect the name files</p>

Body:
We have requirement of loading file from gcs bucket to different bigquery table based on file name pattern.
eg

bucket/folder/test_a_20221023.csv  -> should go to table a
bucket/folder/file_a_20221023_2.csv  -> should go to table a
bucket/folder/control_b_20221023.csv  -> should go to table b
bucket/folder/test_b_20221023_2.csv  -> should go to table b

So prefix can be anything before a or b pattern in the filename and based on a or b we have to load to specific table in bigquery. Is there any way to get the file in gcs based on some pattern other than gsutil command

gsutil ls gs://[BUCKET_NAME]/** | grep string


问:
Clicking content below image with higher z-index
I have created a slider using jquery and the slides plugin. I wanted to create an effect where it looks like the slider is circular shaped, so I positioned an image with a transparent circular center absolutely above the slider, with a higher z-index. You can see a working example here:  http://vitaminjdesign.com/example/examples/Standard/index.html

The problem I have having is that you cannot click on anything within the slider, because of the "mask image" which has a higher z-index than the rest of the content. I want to be able to click on the links within the caption area, as well as the entire slide. Does anybody have any good ideas on how to solve this issue?

I cannot give .caption a higher z-index than the mask because then you would see the background pass above the circular mask. BUT I need to be able to click within the transparent area of the image mask. Any ideas?

答:
Instead of using one div for the masked image, I split it up into 6 Divs each having their own background position.
 (see image)

Please see http://vitaminjdesign.com/example/examples/Standard/index.html for updated example.

ContentLicense: CC BY-SA 3.0


问:
Computing All Valid IP Addresses From Raw IP String
I'm now solving leetcode problem 93. Restore IP Addresses.

Here's the url link: https://leetcode.com/problems/restore-ip-addresses/

The description looks like this:
Given a string s containing only digits. Return all possible valid IP addresses that can be obtained from s. You can return them in any order.

A valid IP address consists of exactly four integers, each integer is between 0 and 255, separated by single points and cannot have leading zeros. For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses and "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses.

However, as I was trying to solve my problem via backtracking, I couldn't figure out the reason that I'm always returning an empty ArrayList. I double checked my base case and my recursion and still couldn't find the bug. Any help would be greatly appreciated, thank you!

```<code>public List<String> restoreIpAddresses(String s) {
        List<String> res = new ArrayList<>();
        if(s.length() == 0){
            return res;
        }
        int[] path = new int[4];
        snapshotIP(res,s,0,path,0);
        return res;
    }

    public void snapshotIP(List<String> res, String s, int index, int[] path, int segment){
        if(segment == 4 && index == s.length()){
            res.add(path[0]+"."+path[1]+"."+path[2]+"."+path[3]);
            return;
        }
        else if(segment == 4 || index == s.length()){
            return;
        }
        for(int len = 1; len <= 3 && index + len <= s.length(); len++){
            String snap = s.substring(index,index+len);
            int val = Integer.parseInt(snap);
            if(val > 225 || len >= 2 && s.charAt(index) == '0'){
                break;
            }
            path[segment] = val;
            snapshotIP(res,s,index+len,path,segment+1);
            path[segment] = -1; //undo the choice

        }
    }
</code>```

答:
```<code>internal static IEnumerable<string> FetchPossibleIPs(string input, int currentSection = 1)
            {
                List<string> possibleIPs = new List<string>();
                if (input.Length > 0)
                {
                    // If section is 4 then no need
                    // to break further and simply verify.
                    if (currentSection == 4)
                    {
                        if (int.Parse(input) <= 255 && input[0].ToString() != "0")
                        {
                            possibleIPs.Add(input);
                        }
                    }
                    // Else if section is < 4 then break the string
                    // with substring of length of 1,2 or 3 to
                    // figure out possible combinations.
                    else
                    {
                        for (int i = 1; i <= 3; ++i)
                        {
                            var section = input.Substring(0, i);
                            if (int.Parse(section) <= 255 && section[0].ToString() != "0")
                            {
                                var otherSections = FetchPossibleIPs(input.Substring(i), currentSection + 1);
                                foreach (var item in otherSections)
                                {
                                    possibleIPs.Add($"{section}.{item}");
                                }
                            }
                        }
                    }
                }
                return possibleIPs;
            }
</code>```

A sample solution in C# using recursion to solve it.
It uses recursion and backtracking to solve the problem.

Body:
I'm now solving leetcode problem 93. Restore IP Addresses.

Here's the url link: https://leetcode.com/problems/restore-ip-addresses/

The description looks like this:
Given a string s containing only digits. Return all possible valid IP addresses that can be obtained from s. You can return them in any order.

A valid IP address consists of exactly four integers, each integer is between 0 and 255, separated by single points and cannot have leading zeros. For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses and "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses.

However, as I was trying to solve my problem via backtracking, I couldn't figure out the reason that I'm always returning an empty ArrayList. I double checked my base case and my recursion and still couldn't find the bug. Any help would be greatly appreciated, thank you!

public List<String> restoreIpAddresses(String s) {
        List<String> res = new ArrayList<>();
        if(s.length() == 0){
            return res;
        }
        int[] path = new int[4];
        snapshotIP(res,s,0,path,0);
        return res;
    }

    public void snapshotIP(List<String> res, String s, int index, int[] path, int segment){
        if(segment == 4 && index == s.length()){
            res.add(path[0]+"."+path[1]+"."+path[2]+"."+path[3]);
            return;
        }
        else if(segment == 4 || index == s.length()){
            return;
        }
        for(int len = 1; len <= 3 && index + len <= s.length(); len++){
            String snap = s.substring(index,index+len);
            int val = Integer.parseInt(snap);
            if(val > 225 || len >= 2 && s.charAt(index) == '0'){
                break;
            }
            path[segment] = val;
            snapshotIP(res,s,index+len,path,segment+1);
            path[segment] = -1; //undo the choice

        }
    }

Body:
internal static IEnumerable<string> FetchPossibleIPs(string input, int currentSection = 1)
            {
                List<string> possibleIPs = new List<string>();
                if (input.Length > 0)
                {
                    // If section is 4 then no need
                    // to break further and simply verify.
                    if (currentSection == 4)
                    {
                        if (int.Parse(input) <= 255 && input[0].ToString() != "0")
                        {
                            possibleIPs.Add(input);
                        }
                    }
                    // Else if section is < 4 then break the string
                    // with substring of length of 1,2 or 3 to
                    // figure out possible combinations.
                    else
                    {
                        for (int i = 1; i <= 3; ++i)
                        {
                            var section = input.Substring(0, i);
                            if (int.Parse(section) <= 255 && section[0].ToString() != "0")
                            {
                                var otherSections = FetchPossibleIPs(input.Substring(i), currentSection + 1);
                                foreach (var item in otherSections)
                                {
                                    possibleIPs.Add($"{section}.{item}");
                                }
                            }
                        }
                    }
                }
                return possibleIPs;
            }

A sample solution in C# using recursion to solve it.
It uses recursion and backtracking to solve the problem.


问:
Angular Rxjs. don't close the subscription after reaching the error, but log the error in Angular's error handler
community.
I have one problem. I need to log an error in Angular's error handler without closing the stream subscription when an error occurs.

I have the following data stream:

```<code>/**DATA Provider Service*/
 getData(settings): Observable<any> {
  return HttpClientGET$(settings).pipe(
/***/
   map(response => transformMethod(response)),
/***/
   tap(convertedData => sendData(convertedData))
 );
}

sendData(data: any): void {
  this.replaySubject.next(data);
}

getConvertedData(): Observable<any> {
  this.replaySubject.asObservable();
}
</code>```
```<code> /**Parent Component*/

ngOnInit(): void {
 this.changePositionStream$.pipe(
  switchMap((settings) => this.dataService.getData(settings))
).subscribe();
}
</code>```
```<code>/**Child - Data Component*/

ngONInit(): void {
  this.service.getConvertedData().subscribe();
}
</code>```

Issue - an error can be caught in the Angular error handler when the error stream doesn't interrupt or use the throwError(). But when an error is thrown the subscription is closing.

How do I log an error without closing the data subscription?

答:
In the general case what you're asking isn't possible.

As per the Observable contract, once an observable has emitted an error or complete, then that observable is done and may never emit anything else (it's free to release any resources, etc). An observable will never error twice, complete twice, or both error and complete. Once is all it gets.

RxJS does come with a set of tools to manage errors and re-try/re-subscribe to source observables etc. We can't know from what you've written here, what would work for you, but there are many questions/answers already about how to do manage RxJS errors.

Body:
community.
I have one problem. I need to log an error in Angular's error handler without closing the stream subscription when an error occurs.

I have the following data stream:

/**DATA Provider Service*/
 getData(settings): Observable<any> {
  return HttpClientGET$(settings).pipe(
/***/
   map(response => transformMethod(response)),
/***/
   tap(convertedData => sendData(convertedData))
 );
}

sendData(data: any): void {
  this.replaySubject.next(data);
}

getConvertedData(): Observable<any> {
  this.replaySubject.asObservable();
}

 /**Parent Component*/

ngOnInit(): void {
 this.changePositionStream$.pipe(
  switchMap((settings) => this.dataService.getData(settings))
).subscribe();
}

/**Child - Data Component*/

ngONInit(): void {
  this.service.getConvertedData().subscribe();
}

Issue - an error can be caught in the Angular error handler when the error stream doesn't interrupt or use the throwError(). But when an error is thrown the subscription is closing.

How do I log an error without closing the data subscription?


问:
sending the value from jsp to java or javascript to java
I have a list of names in a table. When I click the name, it displays people under that particular name.
Ex:

```<code>aaa       bbb
          ccc
</code>```

Now I want to do moveover on aaa which l show 2 (number of ppl under aaa) in a tooltip.

```<code><a id="tool" title="toolTip" onmouseover="toolTip(localArrGroupNames[<%=in.intValue() %>])">

function toolTip(name){
  alert(name);
  //can I send this name to a java class ???

}
</code>```

I get the name aaa in the localArrGroupNames[0].But I am unable to get the name in a java class where i count the number of people below the aaa. How to send this value to java class? Please help me.

答:
A jsp is server side, the rendered HTML is client side so the javascript is running in a webbrowser on the client.

To send any data from that client to your java class that is on the server you need to put in some form of request.

This can be simple by using a submit on your html form

So you could have your tooltip javascript method store the chosen name in a hidden input field and then via submit pass it to the java class( usuually a servlet or some jsp )

Or more complex with the AJAX ( or similar ) frameworks that allow your javascript to pass the name to your server without having the entire page to be submitted

Body:
I have a list of names in a table. When I click the name, it displays people under that particular name.
Ex:

aaa       bbb
          ccc

Now I want to do moveover on aaa which l show 2 (number of ppl under aaa) in a tooltip.

<a id="tool" title="toolTip" onmouseover="toolTip(localArrGroupNames[<%=in.intValue() %>])">

function toolTip(name){
  alert(name);
  //can I send this name to a java class ???

}

I get the name aaa in the localArrGroupNames[0].But I am unable to get the name in a java class where i count the number of people below the aaa. How to send this value to java class? Please help me.


问:
opencl - using image multiple times
So I want to make a app that shows some images and when the window resizes, it scales also all images to fit on the screen.
My strategy is this:

call clCreateImage for every original image and store the cl_mem pointers in a global map (something like: filename -> cl_mem)

call scale(cl_mem img, int width, int height), that calls a kernel and reads the output image data. Then show the scaled images.

when the a window resize event occures: drop all scaled images and call scale(...) another time, with the cl_mem pointers stored in the map

I tried it on a small scale where I just create one image, and call scale two times. The first is OK and scaled, but the second is corrupted. I don't know why, the src image is CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, the out image is created in scale function.

original: https://ibb.co/pQDwScW

first time scaled (to fit in 300x300): https://ibb.co/nnN9kTY

second try (to fit in 500x500): https://ibb.co/561SkSn

But also when I try just 300x300 and then also 300x300 it is corrupted.
Is there a rule, that images can't be used in a kernel multiple times? Or im just missing something?

EDIT:

C code is here: https://pastebin.com/NpSaxRyT

It is used from golang with cgo, so the createImage returns the cl_mem as void*, so that the Go part doesn't need to include cl.h.

init() function is called on startup of the Go program. createImage function is called from Go with pixel data.

So the image pointers (cl_mem pointers) are in Go and then the resize (scale) function is called. It takes the void* pointer and buffer pointer where the pixel data will be transfered.
Also the buffer is allocated by Go, but with the first image it is OK and I think that the GC doesn't kick in (also tried to disable GC entirely).

like so:

    outData := make([]byte, outWidth*outHeight*ir.pixelSize)
    ret := C.resize(
        cl_mem_img_pointer, //unsafe.Pointer (void*)
        C.int(origWidth),
        C.int(origHeight),
        C.int(outWidth),
        C.int(outHeight),
        C.int(rowPitch),
        C.uint(image_channel_order),
        C.uint(image_channel_data_type),
        unsafe.Pointer(&outData[0]),
    )
```

答:
You are releasing right after the first resize operation

```<code>if err := ir.Release(); err != nil {
    t.Fatal(err)
}

img2, err := ir.Resize(200, 200)
if err != nil {
    t.Fatal(err)
}
</code>```

and the 200x200 resize failes as it can not find the img component that was released.

All of OpenCL objects are re-usable until you exit the program. Before exiting, just don't forget to release the resources in the reverse-order they were allocated.

If you are using only same kernel for all tasks, you can use just one global kernel object to be used for all resize calls. It only needs re-setting kernel arguments which are changed between calls. For example, changing sizes of output image, image buffer itself, etc.

Title: opencl - using image multiple times

Body:
You are releasing right after the first resize operation

if err := ir.Release(); err != nil {
    t.Fatal(err)
}

img2, err := ir.Resize(200, 200)
if err != nil {
    t.Fatal(err)
}

and the 200x200 resize failes as it can not find the img component that was released.

All of OpenCL objects are re-usable until you exit the program. Before exiting, just don't forget to release the resources in the reverse-order they were allocated.

If you are using only same kernel for all tasks, you can use just one global kernel object to be used for all resize calls. It only needs re-setting kernel arguments which are changed between calls. For example, changing sizes of output image, image buffer itself, etc.


问:
Why do the col divs stack instead of aligning aside?
I'm new to Vue.JS and new to front-end programming more in general.
I was trying to set a page with a fixed sidebar and a content page, which is  to rendered below a navbar.
I tried using this configuration:

```<code><template>
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-6">.col-md-6</div>
      <div class="col-md-12">.col-md-12</div>
    </div>
  </div>
</template>
</code>```

To place my sidebar content in the .col-md-6 div, but they're being rendered stacked instead of being aside.

Screenshot of app

答: They will not show up side by side unless you make the second div of class col-md-6. If there are more than 12 columns, they will not appear in one row.</p>

Body:
I'm new to Vue.JS and new to front-end programming more in general.
I was trying to set a page with a fixed sidebar and a content page, which is  to rendered below a navbar.
I tried using this configuration:

<template>

.col-md-6

.col-md-12

</template>

To place my sidebar content in the .col-md-6 div, but they're being rendered stacked instead of being aside.

Screenshot of app


问:
Selenium Automation - How to click on particular button periodically until getting another element's updated text value?
In my webpage, I have a refresh button and one Text Field,
when i landed to that page, Initially that Text Field value would be processing (In backend there is a functionality which is processing, Inorder to inform the user, textfield value is processing in UI), and after functionality is done, that Text Field would be completed

Now coming to the question,
We will get to know the updated value of Text Field only when we click on the refresh button,

Is there a way to make a WebElement to be waited until that Text field has value as completed? We also need to click on that particular refresh button periodically to check that text field value became completed or not

I've found a method called textToBePresentInElement in ExpectedConditions, But using this, we cannot refresh button periodically,
Any other solution selenium webdriver is providing?

答:
You need to write a custom method to wait for sometime then to perform click operation. You can see below sample code,

Code:

Create a re-usable method and write down the logic inside the method for click operation and element value check on given explicit interval times.

```<code>public static void clickUntilStatusIsChanged(By element1, By element2, String expectedStatus, int timeOutSeconds) {
    WebDriverWait wait = new WebDriverWait(driver, 5);

    /* The purpose of this loop is to wait for maximum of 50 seconds */
    for (int i = 0; i < timeOutSeconds / 10; i++) {
        if (wait.until(ExpectedConditions.textToBePresentInElementLocated(element2, expectedStatus))) {
            break;
        } else {
            /* Waits for 10 seconds and performs click operation */
            waitForTime(timeOutSeconds / 5);
            driver.findElement(element1).click();
        }
    }
}

public static void waitForTime(int interval) {
    int waitTillSeconds = interval;
    long waitTillTime = Instant.now().getEpochSecond() + waitTillSeconds;
    while (Instant.now().getEpochSecond() < waitTillTime) {
        // Do nothing...
    }
}
</code>```

Pass the parameters to the re-usable method:

```<code>clickUntilStatusIsChanged(By.xpath("Element#1"), By.xpath("Element#2"), "completed", 50);
</code>```

Body:
You need to write a custom method to wait for sometime then to perform click operation. You can see below sample code,

Code:

Create a re-usable method and write down the logic inside the method for click operation and element value check on given explicit interval times.

public static void clickUntilStatusIsChanged(By element1, By element2, String expectedStatus, int timeOutSeconds) {
    WebDriverWait wait = new WebDriverWait(driver, 5);

    /* The purpose of this loop is to wait for maximum of 50 seconds */
    for (int i = 0; i < timeOutSeconds / 10; i++) {
        if (wait.until(ExpectedConditions.textToBePresentInElementLocated(element2, expectedStatus))) {
            break;
        } else {
            /* Waits for 10 seconds and performs click operation */
            waitForTime(timeOutSeconds / 5);
            driver.findElement(element1).click();
        }
    }
}

public static void waitForTime(int interval) {
    int waitTillSeconds = interval;
    long waitTillTime = Instant.now().getEpochSecond() + waitTillSeconds;
    while (Instant.now().getEpochSecond() < waitTillTime) {
        // Do nothing...
    }
}

Pass the parameters to the re-usable method:

clickUntilStatusIsChanged(By.xpath("Element#1"), By.xpath("Element#2"), "completed", 50);


问:
Certificate error during Jenkins plugin update
Since a few months I have problems updating Jenkins plugins.

As soon as I want to update more than one or two plugins at a time I get the following message for all other plugins:

sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

However, if I then update each of these plugins individually and restart the Jenkins server in between, it works.

About my System:

Jenkins 2.321

OpenJDK 11

答:
Solution is to update the JRE:
https://issues.jenkins.io/browse/JENKINS-67756</p>


问:
How can we get the same output in c++?
I'm new to c++ and recently shifted from python. Can anyone explain me what should be the actual code in c++, if we want to print items of a list in for loop.
For example: in python. We do something like.

sample_list = ['you', 'are','awesome']
for i in sample_list:
    print(i)
```
<p>In C++ its something like.</p>
```for(initialisation, condition, updation )
{
Your code
}
```

But there is no update We just want to get items from a list.

How can I do same in C++?

答:
```<code>for(int i = 0; i < sample_list.size(); i++){
    cout << sample_list[i] << "\n";
}
</code>```

or

```<code>for(auto i : sample_list) {
    cout << i << "\n";
}
</code>```

Title: How can we get the same output in c++?

Body:
I'm new to c++ and recently shifted from python. Can anyone explain me what should be the actual code in c++, if we want to print items of a list in for loop.
For example: in python. We do something like.

sample_list = ['you', 'are','awesome']
for i in sample_list:
    print(i)

In C++ its something like.

for(initialisation, condition, updation )
{
Your code
}

But there is no update We just want to get items from a list.

How can I do same in C++?

Body:
for(int i = 0; i < sample_list.size(); i++){
    cout << sample_list[i] << "\n";
}

or

for(auto i : sample_list) {
    cout << i << "\n";
}


问:
How to group columns and sum them, in a large CSV?
I have a large CSV (hundreds of millions of rows) and I need to sum the Value column based on the grouping of the ID, Location, and Date columns.

My CSV is similar to:

    ID Location        Date  Value
 1   1     Loc1  2022-01-27      5
 2   1     Loc1  2022-01-27      4
 3   1     Loc1  2022-01-28      7
 4   1     Loc2  2022-01-29      8
 5   2     Loc1  2022-01-27     11
 6   2     Loc2  2022-01-28      4
 7   2     Loc2  2022-01-29      6
 8   3     Loc1  2022-01-28      9
 9   3     Loc1  2022-01-28      9
10   3     Loc2  2022-01-29      1
```
<ul>
<li><code>{ID: 1, Location: Loc1, Date: 2022-01-27}</code> is one such group, and its sub values <code>5</code> and <code>4</code> should be summed to <code>9</code></li>
<li><code>{ID: 3, Location: Loc1, Date: 2022-01-28}</code> is another group and its sum should be <code>18</code></li>
</ul>
<p>Here's what that sample input should look like, processed/summed, and written to a new CSV:</p>
<pre class="lang-none prettyprint-override"><code>ID Location        Date  Value
1     Loc1  2022-01-27      9
1     Loc1  2022-01-28      7
1     Loc2  2022-01-29      8
2     Loc1  2022-01-27     11
2     Loc2  2022-01-28      4
2     Loc2  2022-01-29      6
3     Loc1  2022-01-28     18
3     Loc2  2022-01-29      1
</code>```

I know using df.groupby([columns]).sum() would give the desired result, but the CSV is so big I keep getting memory errors. I've tried looking at other ways to read/manipulate CSV data but have still not been successful, so if anyone knows a way I can do this in python without maxing out my memory that would be great!

NB: I know there is a unnamed first column in my initial csv, this is irrelevant and doesn't need to be in the outputted, but doesn't matter if it is :)

答:
If the lines to be concatenated are consecutive, the good old csv module allows to process huge files one line at a time, hence with a minimal memory footprint.

Here you could use:

```<code>with open('input.csv') as fd, open('output.csv', 'w', newline='') as fdout:
    rd, wr = csv.reader(fd), csv.writer(fdout)
    _ = wr.writerow(next(rd))      # header line
    old = [None]*4
    for row in rd:
        row[3] = int(row[3])       # convert value field to integer
        if row[:3] == old[:3]:
            old[3] += row[3]       # concatenate values of similar rows
        else:
            if old[0]:             # and write the concatenated row
                _ = wr.writerow(old)
            old = row
    if old[0]:                     # do not forget the last row...
        _ = wr.writerow(old)
</code>```

With the shown input data, it gives as expected:

```<code>ID,Location,Date,Value
1,Loc1,2022-01-27,9
1,Loc1,2022-01-28,7
1,Loc2,2022-01-29,8
2,Loc1,2022-01-27,11
2,Loc2,2022-01-28,4
2,Loc2,2022-01-29,6
3,Loc1,2022-01-28,18
3,Loc2,2022-01-29,1
</code>```

Not as clean and neat than Pandas code but it should process files greater than the available memory without any problem.

Body:
I have a large CSV (hundreds of millions of rows) and I need to sum the Value column based on the grouping of the ID, Location, and Date columns.

My CSV is similar to:

    ID Location        Date  Value
 1   1     Loc1  2022-01-27      5
 2   1     Loc1  2022-01-27      4
 3   1     Loc1  2022-01-28      7
 4   1     Loc2  2022-01-29      8
 5   2     Loc1  2022-01-27     11
 6   2     Loc2  2022-01-28      4
 7   2     Loc2  2022-01-29      6
 8   3     Loc1  2022-01-28      9
 9   3     Loc1  2022-01-28      9
10   3     Loc2  2022-01-29      1

{ID: 1, Location: Loc1, Date: 2022-01-27} is one such group, and its sub values 5 and 4 should be summed to 9

{ID: 3, Location: Loc1, Date: 2022-01-28} is another group and its sum should be 18

Here's what that sample input should look like, processed/summed, and written to a new CSV:

ID Location        Date  Value
1     Loc1  2022-01-27      9
1     Loc1  2022-01-28      7
1     Loc2  2022-01-29      8
2     Loc1  2022-01-27     11
2     Loc2  2022-01-28      4
2     Loc2  2022-01-29      6
3     Loc1  2022-01-28     18
3     Loc2  2022-01-29      1

I know using df.groupby([columns]).sum() would give the desired result, but the CSV is so big I keep getting memory errors. I've tried looking at other ways to read/manipulate CSV data but have still not been successful, so if anyone knows a way I can do this in python without maxing out my memory that would be great!

NB: I know there is a unnamed first column in my initial csv, this is irrelevant and doesn't need to be in the outputted, but doesn't matter if it is :)

Body:
If the lines to be concatenated are consecutive, the good old csv module allows to process huge files one line at a time, hence with a minimal memory footprint.

Here you could use:

with open('input.csv') as fd, open('output.csv', 'w', newline='') as fdout:
    rd, wr = csv.reader(fd), csv.writer(fdout)
    _ = wr.writerow(next(rd))      # header line
    old = [None]*4
    for row in rd:
        row[3] = int(row[3])       # convert value field to integer
        if row[:3] == old[:3]:
            old[3] += row[3]       # concatenate values of similar rows
        else:
            if old[0]:             # and write the concatenated row
                _ = wr.writerow(old)
            old = row
    if old[0]:                     # do not forget the last row...
        _ = wr.writerow(old)

With the shown input data, it gives as expected:

ID,Location,Date,Value
1,Loc1,2022-01-27,9
1,Loc1,2022-01-28,7
1,Loc2,2022-01-29,8
2,Loc1,2022-01-27,11
2,Loc2,2022-01-28,4
2,Loc2,2022-01-29,6
3,Loc1,2022-01-28,18
3,Loc2,2022-01-29,1

Not as clean and neat than Pandas code but it should process files greater than the available memory without any problem.


答:
You can use the form for(:) to iterate over every list element.

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

int main()
{
    std::vector<std::string> sample_list{"you", "are", "awesome"};

    for (auto item : sample_list)
        std::cout << item << std::endl;

    return 0;
}
</code>```

Title: How can we get the same output in c++?

Body:
You can use the form for(:) to iterate over every list element.

#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::vector<std::string> sample_list{"you", "are", "awesome"};

    for (auto item : sample_list)
        std::cout << item << std::endl;

    return 0;
}


问:
Flutter how to iterate through map
hey can u help iterate through map and build Text widget every time ?
this is the code i used for filling Map</p>
```<code>  Map<sectorItems, bool> sectors = {};
  @override
  void initState() {
    for (int i = 0; i < sectors.length; i++) {
      sectors = {sectorItems.values[i]: false};
    }
    super.initState();
  }
</code>```

答:
Assuming your sectors is a Map, you can use this code.

```<code>    List<Widget> widgets = [];

    for(var key in sectors.values){
      //get string for text widget
      widgets.add(Text(string));
    }
</code>```

This cycles through the keys in your map

```<code>    for(var key in sectors.values){
       ...
    }
</code>```

Title: Flutter how to iterate through map

Body:
hey can u help iterate through map and build Text widget every time ?
this is the code i used for filling Map

  Map<sectorItems, bool> sectors = {};
  @override
  void initState() {
    for (int i = 0; i < sectors.length; i++) {
      sectors = {sectorItems.values[i]: false};
    }
    super.initState();
  }

Body:
Assuming your sectors is a Map, you can use this code.

    List<Widget> widgets = [];

    for(var key in sectors.values){
      //get string for text widget
      widgets.add(Text(string));
    }

This cycles through the keys in your map

    for(var key in sectors.values){
       ...
    }


问:
Linked List insertion isn't working in for/while loop
I am learning DSA, and was trying to implement linked list but the insertion function that i wrote is not
working in a for or while loop, its not the same when i call that function outside the loop, it works that way. I am not able to figure it out, please someone help me.

```<code>#include <iostream>

class Node {

public:
  int data;
  Node *next;

  Node(int &num) {
    this->data = num;
    next = NULL;
  }
};

class LinkedList {

  Node *head = NULL;

public:
  void insert(int num) {
    Node *tmp;
    if (head == NULL) {
      head = new Node(num);
      tmp = head;
    } else {
      tmp->next = new Node(num);
      tmp = tmp->next;
    }
  }

  void printList() {
    Node *tmp = head;
    while (tmp) {
      std::cout << tmp->data << "  ";
      tmp = tmp->next;
    }
    std::cout << std::endl;
  }

  void reverseList() {
    Node *curr = head, *prev = NULL, *nextNode;
    while (curr) {
      nextNode = curr->next;
      curr->next = prev;
      prev = curr;
      curr = nextNode;
    }
    head = prev;
  }
};

int main() {
  LinkedList list1;
  // This is not working
  int num;
  while (num != -1) {
    std::cin >> num;
    list1.insert(num);
  }

  // This is working
  // list1.insert(1);
  // list1.insert(2);
  // list1.insert(3);
  // list1.insert(4);
  // list1.insert(5);

  list1.printList();
  list1.reverseList();
  list1.printList();

  return 0;
}
</code>```

I expect this after insertion

Edit:
although @Roberto Montalti solved this for me, but before that I tried passing incrementing value using a for loop which worked but as soon as I pull that cin out it crashes. can someone tell me what's happening under the hood?

```<code>for (int i = 1; i <= 10; i++)
{
    list1.insert(i);
}
</code>```

答:
When inserting the nth item (1st excluded) tmp is a null pointer, i don't understand what you are doing there, you are assigning to next of some memory then you make that pointer point to another location, losing the pointer next you assigned before, you must keep track of the last item if you want optimal insertion. This way you are only assigning to some *tmp then going out of scope loses all your data... The best way is to just keep a pointer to the last inserted item, no need to use *tmp.

class LinkedList
{
   Node *head = NULL;
   Node *tail = NULL;

public:
    void insert(int num)
    {
        if (head == NULL)
        {
            head = new Node(num);
            tail = head;
        }
        else
        {
            tail->next = new Node(num);
            tail = tail->next;
        }
    }
...
}
```

Body:
I am learning DSA, and was trying to implement linked list but the insertion function that i wrote is not
working in a for or while loop, its not the same when i call that function outside the loop, it works that way. I am not able to figure it out, please someone help me.

#include <iostream>

class Node {

public:
  int data;
  Node *next;

  Node(int &num) {
    this->data = num;
    next = NULL;
  }
};

class LinkedList {

  Node *head = NULL;

public:
  void insert(int num) {
    Node *tmp;
    if (head == NULL) {
      head = new Node(num);
      tmp = head;
    } else {
      tmp->next = new Node(num);
      tmp = tmp->next;
    }
  }

  void printList() {
    Node *tmp = head;
    while (tmp) {
      std::cout << tmp->data << "  ";
      tmp = tmp->next;
    }
    std::cout << std::endl;
  }

  void reverseList() {
    Node *curr = head, *prev = NULL, *nextNode;
    while (curr) {
      nextNode = curr->next;
      curr->next = prev;
      prev = curr;
      curr = nextNode;
    }
    head = prev;
  }
};

int main() {
  LinkedList list1;
  // This is not working
  int num;
  while (num != -1) {
    std::cin >> num;
    list1.insert(num);
  }

  // This is working
  // list1.insert(1);
  // list1.insert(2);
  // list1.insert(3);
  // list1.insert(4);
  // list1.insert(5);

  list1.printList();
  list1.reverseList();
  list1.printList();

  return 0;
}

I expect this after insertion

Edit:
although @Roberto Montalti solved this for me, but before that I tried passing incrementing value using a for loop which worked but as soon as I pull that cin out it crashes. can someone tell me what's happening under the hood?

for (int i = 1; i <= 10; i++)
{
    list1.insert(i);
}


问:
How to send a csv from my local machine HBASE using nifi?
I am very new to DBMS and nifi platforms.

I am learning it and now I want to send a .csv file with some data from my local machine to HBASE using nifi.

It would be good to know the steps to be followed.

Also, to run hbase do I also need to install HDFS ?

答:
No, you don't require HDFS to install HBASE. HBASE can be installed using your local file system also. It can be installed in different different modes. Find the link below on the same, by this you will get an idea of different installation modes.

Install HBASE in different modes

Also, you want to ingest data from CSV file to some HBASE table. You can use a couple of processors to do so. Please find the steps below :

Read file : Get File Processor Details

Parse CSV file : CSVReader Processor Details

Put data into HBASE : PutHBaseCell OR PutHbasejSON OR PutHbaseRecord (Use appropriate processor as per your scenario)


问:
Fetch API giving Network request failed Expo App Nodejs
I have written an API in Nodejs which helps in reset password using Mysql database.It is working fine in Postman.I have called this API in Expo IOS App.But I am getting Network request failed error. Below is the Node js program:

app.js:

```<code>var express = require('express');
var path = require('path');
var connection = require('./database.js');
var nodemailer = require('nodemailer');
const bcrypt = require("bcryptjs")

var randtoken = require('rand-token');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var flash = require('express-flash');
var session = require('express-session');
var bodyParser = require('body-parser');

const createError = require('http-errors');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();
var connection = require('./database.js');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))

//send email
function sendEmail(email, token) {
var email = email;
var token = token;
var mail = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'c***********@gmail.com', // Your email id
pass: '**********' // Your password
}
});
var mailOptions = {
from: 'poornima@abccompany.com',
to: email,
subject: 'Reset Password Link - ABCCompany.com',
html: '<p>You requested for reset password, kindly use this <a
href="http://localhost:4000/reset-password?token=' + token + '">link</a> to reset
your password</p>'
};
mail.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(1)
} else {
console.log(0)
}
});
}

app.post('/reset-password-email', function(req, res, next) {
var email = req.body.email;
console.log('email from api '+email);
connection.query('SELECT * FROM JTGDB.UserInfo WHERE email ="' + email + '"',
function(err, result) {
 if (err) throw err;
 var type = ''
 var msg = ''
 console.log(result[0]);
 if (result[0].Email.length > 0) {
 var token = randtoken.generate(20);
 var sent = sendEmail(email, token);
 if (sent != '0') {
 var data = {
  token: token
 }
 connection.query('UPDATE JTGDB.UserInfo SET ? WHERE email ="' + email + '"', data,
 function(err, result) {
 if(err) throw err
 })
 type = 'success';
 msg = 'The reset password link has been sent to your email address';
 } else {
 type = 'error';
 msg = 'Something goes to wrong. Please try again';
 }
 } else {
  console.log('2');
 type = 'error';
 msg = 'The Email is not registered with us';
 }
 res.redirect('/');
 });
 })

 // view engine setup
 app.set('views', path.join(__dirname, 'views'));
 app.set('view engine', 'ejs');

 app.use(logger('dev'));
 app.use(express.json());
 app.use(express.urlencoded({ extended: false }));
 app.use(cookieParser());
 app.use(express.static(path.join(__dirname, 'public')));

 app.use(session({
secret: '123458cat',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 }
 }))

 app.use(flash());
 app.use('/', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

app.listen(4000, function () {
console.log('Node app is running on port 4000');
});

module.exports = app;
</code>```

Below is the IOS App ForgetPassword Screen page:

ForgetPasswordScreen.js:

```<code>import React, { Component, Fragment, useState } from "react";
import { View, Text,SafeAreaView, Image, StyleSheet } from "react-native";
import { Formik } from "formik";
import * as Yup from "yup";
import FormInput from "../../components/UI/FormInput";
import FormButton from "../../components/UI/FormButton";
import ErrorMessage from "../../components/UI/ErrorMessage";
import * as authActions from '../../store/actions/auth';
import {useDispatch} from "react-redux";
import Toast from 'react-native-root-toast';

const validationSchema = Yup.object().shape({
email: Yup.string()
.label("Email")
.email("Enter a valid email")
.required("Please enter a registered email"),
});

const ForgotPasswordScreen = props => {
const [isLoading,setIsLoading] = React.useState(false);
const [error, setError] = React.useState('');
const dispatch = useDispatch();
const handlePasswordReset = async (values, actions) => {
const { email } = values;
console.log('email is '+email);
let action
action =  authActions.resetpassword(
         email
         );
setError(null);
setIsLoading(true);
     try{
      await dispatch(action);
  props.navigation.navigate("Login");
} catch (error) {
  actions.setFieldError("general", error.message);
}
};
return (
  <SafeAreaView>
    <View style={styles.emailiconview}>
    <Image source={require('../../assets/reset_email.png')} />
    </View>
     <View style ={styles.instrview1}>
       <Text>
         Please enter your registered email address below to
       </Text>
       </View>
     <View style={styles.instrview2}>
       <Text>receive password reset instruction</Text>
     </View>
     <View style={styles.emailinputview}>
     <Formik
      initialValues={{ email: "" }}
      onSubmit={(values, actions) => {
      handlePasswordReset(values, actions);
      }}
      validationSchema={validationSchema}
    >
      {({
        handleChange,
        values,
        handleSubmit,
        errors,
        isValid,
        touched,
        handleBlur,
        isSubmitting,
      }) => (
        <Fragment>
          <FormInput
            name="email"
            value={values.email}
            onChangeText={handleChange("email")}
            placeholder="Enter email"
            autoCapitalize="none"
            iconName="ios-mail"
            iconColor="blue"
            onBlur={handleBlur("email")}
          />
          <ErrorMessage errorValue={touched.email && errors.email} />
          <View style={styles.buttonContainer}>
            <FormButton
              buttonType="outline"
              onPress={handleSubmit}
              title="Send Email"
              buttonColor="blue"
              disabled={!isValid || isSubmitting}
            />
          </View>
          <ErrorMessage errorValue={errors.general} />
        </Fragment>
      )}
    </Formik>
    </View>
  </SafeAreaView>
  )
  }

  const styles = StyleSheet.create({
  container: {
  flex: 1,
  backgroundColor: "#fff",
  marginTop: 150,
  },
  text: {
  color: "#333",
  fontSize: 24,
  marginLeft: 25,
  },
buttonContainer: {
margin: 25,
},
emailiconview:{
justifyContent:'center',
alignItems:'center',
top:"30%"
},
instrview1:{
top:'40%',
justifyContent:'center',
alignSelf:'center'
},  instrview2:{
top:'45%',
justifyContent:'center',
alignSelf:'center'
},
 emailinputview:{
top:'50%'
}
});
export default ForgotPasswordScreen;
</code>```

Below is the store auth where I fetch API:

auth.js:

```<code>import Device from '../../model/Device';
import AsyncStorage from '@react-native-async-storage/async-storage'

export const FORGOTPASSWORD = 'FORGOTPASSWORD';

export const resetpassword=(email) =>{
console.log(email);
return async dispatch =>{
  const response = await fetch(
    'http://my_IPV4_Address:4000/reset-password-email',
    {
     method: 'POST',
     header: {
       'Content-Type': 'application/json',
     },
     body: JSON.stringify({
      email: email
     })
    }
  );
  const resData = await response.text();
   console.log(resData);
  dispatch({type:FORGOTPASSWORD});
};
}
</code>```

After running this I am getting the below error in Expo:

Network request failed

It is taking email, but not hitting the api.

```<code>email is cpoornima.1987@gmail.com
Email id to API cpoornima.1987@gmail.com
</code>```

I am getting below error in NodeJs:

```<code>email from api undefined
undefined
</code>```

I have added

```<code>     <key>NSAppTransportSecurity</key>
     <dict>
     <key>NSAllowsArbitraryLoads</key>
     <true/>
     </dict>
</code>```

to the Info.plist. I am just checking in IOS Simulator attached to Expo App. How to get through this?

答:
Below is the auth.js fetch API which is working good.As soon as I press Send Email button, an email is going to provided email id for reset password using real Iphone device.

auth.js:

```<code>import Device from '../../model/Device';
import AsyncStorage from '@react-native-async-storage/async-storage'

export const FORGOTPASSWORD = 'FORGOTPASSWORD';

export const resetpassword=(email) =>{
const formData = new FormData();
formData.append('email',email);
console.log('Email id to API '+email);
return async dispatch =>{
  fetch('http://My_IPV4_Address:4000/reset-password-email',
    {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body:JSON.stringify({
        email: email,
      }),
    })
    .then(res => res.text())
    .then(
      (signupresult) =>{

      }).catch(err =>{
        console.log(err);
      })
      dispatch({type:FORGOTPASSWORD});
      };
      }
</code>```

Body:
I have written an API in Nodejs which helps in reset password using Mysql database.It is working fine in Postman.I have called this API in Expo IOS App.But I am getting Network request failed error. Below is the Node js program:

app.js:

var express = require('express');
var path = require('path');
var connection = require('./database.js');
var nodemailer = require('nodemailer');
const bcrypt = require("bcryptjs")

var randtoken = require('rand-token');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var flash = require('express-flash');
var session = require('express-session');
var bodyParser = require('body-parser');

const createError = require('http-errors');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();
var connection = require('./database.js');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))

//send email
function sendEmail(email, token) {
var email = email;
var token = token;
var mail = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'c***********@gmail.com', // Your email id
pass: '**********' // Your password
}
});
var mailOptions = {
from: 'poornima@abccompany.com',
to: email,
subject: 'Reset Password Link - ABCCompany.com',
html: '
You requested for reset password, kindly use this link to reset
your password
'
};
mail.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(1)
} else {
console.log(0)
}
});
}

app.post('/reset-password-email', function(req, res, next) {
var email = req.body.email;
console.log('email from api '+email);
connection.query('SELECT * FROM JTGDB.UserInfo WHERE email ="' + email + '"',
function(err, result) {
 if (err) throw err;
 var type = ''
 var msg = ''
 console.log(result[0]);
 if (result[0].Email.length > 0) {
 var token = randtoken.generate(20);
 var sent = sendEmail(email, token);
 if (sent != '0') {
 var data = {
  token: token
 }
 connection.query('UPDATE JTGDB.UserInfo SET ? WHERE email ="' + email + '"', data,
 function(err, result) {
 if(err) throw err
 })
 type = 'success';
 msg = 'The reset password link has been sent to your email address';
 } else {
 type = 'error';
 msg = 'Something goes to wrong. Please try again';
 }
 } else {
  console.log('2');
 type = 'error';
 msg = 'The Email is not registered with us';
 }
 res.redirect('/');
 });
 })

 // view engine setup
 app.set('views', path.join(__dirname, 'views'));
 app.set('view engine', 'ejs');

 app.use(logger('dev'));
 app.use(express.json());
 app.use(express.urlencoded({ extended: false }));
 app.use(cookieParser());
 app.use(express.static(path.join(__dirname, 'public')));

 app.use(session({
secret: '123458cat',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 }
 }))

 app.use(flash());
 app.use('/', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

app.listen(4000, function () {
console.log('Node app is running on port 4000');
});

module.exports = app;

Below is the IOS App ForgetPassword Screen page:

ForgetPasswordScreen.js:

import React, { Component, Fragment, useState } from "react";
import { View, Text,SafeAreaView, Image, StyleSheet } from "react-native";
import { Formik } from "formik";
import * as Yup from "yup";
import FormInput from "../../components/UI/FormInput";
import FormButton from "../../components/UI/FormButton";
import ErrorMessage from "../../components/UI/ErrorMessage";
import * as authActions from '../../store/actions/auth';
import {useDispatch} from "react-redux";
import Toast from 'react-native-root-toast';

const validationSchema = Yup.object().shape({
email: Yup.string()
.label("Email")
.email("Enter a valid email")
.required("Please enter a registered email"),
});

const ForgotPasswordScreen = props => {
const [isLoading,setIsLoading] = React.useState(false);
const [error, setError] = React.useState('');
const dispatch = useDispatch();
const handlePasswordReset = async (values, actions) => {
const { email } = values;
console.log('email is '+email);
let action
action =  authActions.resetpassword(
         email
         );
setError(null);
setIsLoading(true);
     try{
      await dispatch(action);
  props.navigation.navigate("Login");
} catch (error) {
  actions.setFieldError("general", error.message);
}
};
return (
  <SafeAreaView>
    <View style={styles.emailiconview}>
    <Image source={require('../../assets/reset_email.png')} />
    </View>
     <View style ={styles.instrview1}>
       <Text>
         Please enter your registered email address below to
       </Text>
       </View>
     <View style={styles.instrview2}>
       <Text>receive password reset instruction</Text>
     </View>
     <View style={styles.emailinputview}>
     <Formik
      initialValues={{ email: "" }}
      onSubmit={(values, actions) => {
      handlePasswordReset(values, actions);
      }}
      validationSchema={validationSchema}
    >
      {({
        handleChange,
        values,
        handleSubmit,
        errors,
        isValid,
        touched,
        handleBlur,
        isSubmitting,
      }) => (
        <Fragment>
          <FormInput
            name="email"
            value={values.email}
            onChangeText={handleChange("email")}
            placeholder="Enter email"
            autoCapitalize="none"
            iconName="ios-mail"
            iconColor="blue"
            onBlur={handleBlur("email")}
          />
          <ErrorMessage errorValue={touched.email && errors.email} />
          <View style={styles.buttonContainer}>
            <FormButton
              buttonType="outline"
              onPress={handleSubmit}
              title="Send Email"
              buttonColor="blue"
              disabled={!isValid || isSubmitting}
            />
          </View>
          <ErrorMessage errorValue={errors.general} />
        </Fragment>
      )}
    </Formik>
    </View>
  </SafeAreaView>
  )
  }

  const styles = StyleSheet.create({
  container: {
  flex: 1,
  backgroundColor: "#fff",
  marginTop: 150,
  },
  text: {
  color: "#333",
  fontSize: 24,
  marginLeft: 25,
  },
buttonContainer: {
margin: 25,
},
emailiconview:{
justifyContent:'center',
alignItems:'center',
top:"30%"
},
instrview1:{
top:'40%',
justifyContent:'center',
alignSelf:'center'
},  instrview2:{
top:'45%',
justifyContent:'center',
alignSelf:'center'
},
 emailinputview:{
top:'50%'
}
});
export default ForgotPasswordScreen;

Below is the store auth where I fetch API:

auth.js:

import Device from '../../model/Device';
import AsyncStorage from '@react-native-async-storage/async-storage'

export const FORGOTPASSWORD = 'FORGOTPASSWORD';

export const resetpassword=(email) =>{
console.log(email);
return async dispatch =>{
  const response = await fetch(
    'http://my_IPV4_Address:4000/reset-password-email',
    {
     method: 'POST',
     header: {
       'Content-Type': 'application/json',
     },
     body: JSON.stringify({
      email: email
     })
    }
  );
  const resData = await response.text();
   console.log(resData);
  dispatch({type:FORGOTPASSWORD});
};
}

After running this I am getting the below error in Expo:

Network request failed

It is taking email, but not hitting the api.

email is cpoornima.1987@gmail.com
Email id to API cpoornima.1987@gmail.com

I am getting below error in NodeJs:

email from api undefined
undefined

I have added

     <key>NSAppTransportSecurity</key>
     <dict>
     <key>NSAllowsArbitraryLoads</key>
     <true/>
     </dict>

to the Info.plist. I am just checking in IOS Simulator attached to Expo App. How to get through this?

Body:
Below is the auth.js fetch API which is working good.As soon as I press Send Email button, an email is going to provided email id for reset password using real Iphone device.

auth.js:

import Device from '../../model/Device';
import AsyncStorage from '@react-native-async-storage/async-storage'

export const FORGOTPASSWORD = 'FORGOTPASSWORD';

export const resetpassword=(email) =>{
const formData = new FormData();
formData.append('email',email);
console.log('Email id to API '+email);
return async dispatch =>{
  fetch('http://My_IPV4_Address:4000/reset-password-email',
    {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body:JSON.stringify({
        email: email,
      }),
    })
    .then(res => res.text())
    .then(
      (signupresult) =>{

      }).catch(err =>{
        console.log(err);
      })
      dispatch({type:FORGOTPASSWORD});
      };
      }


问:
Redirect to old page at logout in PHP
I am developing a CMS. I have three scripts, and 2 session variables

```<code> $_SESSION['logged']
 $_SESSION['redirect']
</code>```

"auth.inc.php" - Run every time a user requests a page. It checks if $_SESSION['logged'] is set and equal to 1. If it isn't redirects ti main page using

```<code>header(location:index.php)
</code>```

and the page referrer link is saved in $_SESSION['redirect']. If $_SESSION['logged'] is set  inactivity time is less than a required value it redirects to the requested page other wise it redirects to logout.php

"index.php" - checks for user name and password. I successful sets

```<code>$_SESSION['logged']=1
</code>```

If  $_SESSION['redirect'] is set it redirects to that page otherwise to deafult page

"logout.php" - Its unsets and destroys the session using

```<code>session_unset();
session_destroy();
</code>```

But I want if user is logged out due to session timeout then after login it should be redirected to old page. Since I was unsetting the session  $_SESSION['redirect'] was lost. So instead of using  session_unset() I only unset $_SESSION['logged']

```<code>unset($_SESSION['logged']);
session_destroy();
</code>```

but still I am not able to retrieve $_SESSION['redirect'] after session_destroy(). The variable is still not set. How should I redirect to old page after logout due to session expire

答:
@Marc Towler:
Sorry, I can't post comment now.
What I want to say is that not all the Browser support referer page, like IE.</p>

Title: Redirect to old page at logout in PHP

Body:
I am developing a CMS. I have three scripts, and 2 session variables

 $_SESSION['logged']
 $_SESSION['redirect']

"auth.inc.php" - Run every time a user requests a page. It checks if $_SESSION['logged'] is set and equal to 1. If it isn't redirects ti main page using

header(location:index.php)

and the page referrer link is saved in $_SESSION['redirect']. If $_SESSION['logged'] is set  inactivity time is less than a required value it redirects to the requested page other wise it redirects to logout.php

"index.php" - checks for user name and password. I successful sets

$_SESSION['logged']=1

If  $_SESSION['redirect'] is set it redirects to that page otherwise to deafult page

"logout.php" - Its unsets and destroys the session using

session_unset();
session_destroy();

But I want if user is logged out due to session timeout then after login it should be redirected to old page. Since I was unsetting the session  $_SESSION['redirect'] was lost. So instead of using  session_unset() I only unset $_SESSION['logged']

unset($_SESSION['logged']);
session_destroy();

but still I am not able to retrieve $_SESSION['redirect'] after session_destroy(). The variable is still not set. How should I redirect to old page after logout due to session expire


问:
Is there a way to declare a parameter at class level with testng
I am struggling with declaring a parameter at class level with testNG. I have a browser parameter that works fine when declared at the method level.

Because I am mapping the test to a cucumber step definition and will be declaring a url parameter at the method level, I want to take the browser parameter away from the method to the class (global) level. So, in the xml file, I moved the browser parameter from test level to the suite level like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="Suite" parallel="tests" thread-count="5">

    <!-- Parametter moved to suite level -->
    <parameter name="Browser" value="CHROME"/>
    <parameter name="Browser" value="FF"/>

    <test name="Chrome Test">
        <classes>
            <class name="tests.web.WebTest"/>
        </classes>
    </test>

    <test name="Firefox Test">
        <classes>
            <class name="tests.web.WebTest"/>
        </classes>
    </test>
</suite>
</code>```

Then in the test class, I removed the browser parameter from the method and to the class
and declared browser as public static. Sadly, the browser could not be found at runtime, resulting in a NullPointerException:

```<code>@Parameters("Browser") //parameter declared at class level
public class WebTest {

  WebDriver driver = null;
  BasePageWeb basePage;
  public static String browser; //class variable

  @BeforeClass
  public void navigateToUrl() {
    switch (browser) { //NullpointerException thrown here

      case "CHROME":
        WebDriverManager.chromedriver().setup();
        driver = new ChromeDriver();
        break;

      case "FF":
        WebDriverManager.firefoxdriver().setup();
        driver = new FirefoxDriver();
        break;

      default:
        driver = null;
        break;
    }
    driver.get("www.google.com");

  }
</code>```

How do I declare the browser parameter successfully at class level?

答:
For Parameters annotation METHOD, CONSTRUCTOR, TYPE target ElementTypes defined.

```<code>@Retention(RUNTIME)
@Target({METHOD, CONSTRUCTOR, TYPE})
public @interface Parameters {|
...
</code>```

TYPE means it might be defined on class level.

And I've tried to find any example with such usage and also tried to make it work myself (also trying to assign to a static variable).

But no luck..

So I can suggest just this alternative (define @Parameter for CONSTRUCTOR):

```<code>public class WebTest {

   public String browser;

   @Parameters({ "Browser" })
   public WebTest(String browser) {
       this.browser = browser;
   }

...
}
</code>```

and xml seems to be:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="Suite" parallel="tests" thread-count="5">

    <test name="Chrome Test">
        <parameter name="Browser" value="CHROME"/>
        <classes>
            <class name="tests.web.WebTest"/>
        </classes>
    </test>

    <test name="Firefox Test">
        <parameter name="Browser" value="FF"/>
        <classes>
            <class name="tests.web.WebTest"/>
        </classes>
    </test>
</suite>
</code>```

Body:
I am struggling with declaring a parameter at class level with testNG. I have a browser parameter that works fine when declared at the method level.

Because I am mapping the test to a cucumber step definition and will be declaring a url parameter at the method level, I want to take the browser parameter away from the method to the class (global) level. So, in the xml file, I moved the browser parameter from test level to the suite level like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="Suite" parallel="tests" thread-count="5">

    <parameter name="Browser" value="CHROME"/>
    <parameter name="Browser" value="FF"/>

    <test name="Chrome Test">
        <classes>
            <class name="tests.web.WebTest"/>
        </classes>
    </test>

    <test name="Firefox Test">
        <classes>
            <class name="tests.web.WebTest"/>
        </classes>
    </test>
</suite>

Then in the test class, I removed the browser parameter from the method and to the class
and declared browser as public static. Sadly, the browser could not be found at runtime, resulting in a NullPointerException:

@Parameters("Browser") //parameter declared at class level
public class WebTest {

  WebDriver driver = null;
  BasePageWeb basePage;
  public static String browser; //class variable

  @BeforeClass
  public void navigateToUrl() {
    switch (browser) { //NullpointerException thrown here

      case "CHROME":
        WebDriverManager.chromedriver().setup();
        driver = new ChromeDriver();
        break;

      case "FF":
        WebDriverManager.firefoxdriver().setup();
        driver = new FirefoxDriver();
        break;

      default:
        driver = null;
        break;
    }
    driver.get("www.google.com");

  }

How do I declare the browser parameter successfully at class level?

Body:
For Parameters annotation METHOD, CONSTRUCTOR, TYPE target ElementTypes defined.

@Retention(RUNTIME)
@Target({METHOD, CONSTRUCTOR, TYPE})
public @interface Parameters {|
...

TYPE means it might be defined on class level.

And I've tried to find any example with such usage and also tried to make it work myself (also trying to assign to a static variable).

But no luck..

So I can suggest just this alternative (define @Parameter for CONSTRUCTOR):

public class WebTest {

   public String browser;

   @Parameters({ "Browser" })
   public WebTest(String browser) {
       this.browser = browser;
   }

...
}

and xml seems to be:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="Suite" parallel="tests" thread-count="5">

    <test name="Chrome Test">
        <parameter name="Browser" value="CHROME"/>
        <classes>
            <class name="tests.web.WebTest"/>
        </classes>
    </test>

    <test name="Firefox Test">
        <parameter name="Browser" value="FF"/>
        <classes>
            <class name="tests.web.WebTest"/>
        </classes>
    </test>
</suite>


问:
get current users data from firestore on reactjs using uid as a link between the user auth and firestore. get this Error: Too many re-renders
i am trying to get user data from firestore using uid to link the firestore data and the user auth. i have tried this but keep getting a blank screen with too many re-renders errors. would anyone be able to help?
my firestore collection is named values and it stores Fname,Lname, bio, username and uid

```<code>import {
 StyleSheet,
 Text,
 View,
 Image,
} from 'react-native';
import { auth, db } from '../Firebase'

const  UserProfileView = () => {

   const [user, setUser] = useState();
   const {uid} = auth.currentUser.uid;

     const userRef = db.collection('values').doc(uid);
     const doc =  userRef.get();
     doc.data;

   const userData = doc.data;
   setUser(userData);

// Get user on mount
useEffect(() => {
   UserProfileView();
}, []);

//adapted from https://www.bootdey.com/react-native-snippet/12/User-profile-with-options

</code>```

My return the only code that relates to the above is the text tag with user && user?.Fname

```<code>    return (
      <View style={styles.container}>
          <View style={styles.header}>
            <View style={styles.headerContent}>
                <Image style={styles.avatar}
                  source={{uri: 'https://bootdey.com/img/Content/avatar/avatar6.png'}}/>

                <Text style={styles.name}>{auth.currentUser?.uid} </Text>
                <Text style={styles.name}>{user && user?.Fname}</Text>
                <Text style={styles.userInfo}>{auth.currentUser?.email}</Text>
                <Text style={styles.userInfo}>Florida </Text>
            </View>
          </View>

          <View style={styles.body}>
            <View style={styles.item}>
              <View style={styles.iconContent}>
                <Image style={styles.icon} source={{uri: 'https://img.icons8.com/color/70/000000/cottage.png'}}/>
              </View>
              <View style={styles.infoContent}>
                <Text style={styles.info}>Home</Text>
              </View>
            </View>

            <View style={styles.item}>
              <View style={styles.iconContent}>
                <Image style={styles.icon} source={{uri: 'https://img.icons8.com/color/70/000000/administrator-male.png'}}/>
              </View>
              <View style={styles.infoContent}>
                <Text style={styles.info}>Settings</Text>
              </View>
            </View>

            <View style={styles.item}>
              <View style={styles.iconContent}>
                <Image style={styles.icon} source={{uri: 'https://img.icons8.com/color/70/000000/filled-like.png'}}/>
              </View>
              <View style={styles.infoContent}>
                <Text style={styles.info}>News</Text>
              </View>
            </View>

            <View style={styles.item}>
              <View style={styles.iconContent}>
                <Image style={styles.icon} source={{uri: 'https://img.icons8.com/color/70/000000/facebook-like.png'}}/>
              </View>
              <View style={styles.infoContent}>
                <Text style={styles.info}>Shop</Text>
              </View>
            </View>

          </View>
      </View>
    );
  }
export default UserProfileView;```
```

答:
DocumentSnapshot.data() is a method, not a property, so:

```<code>const userData = doc.data;
</code>```

Should actually be:

```<code>const userData = doc.data();
</code>```

Body:
i am trying to get user data from firestore using uid to link the firestore data and the user auth. i have tried this but keep getting a blank screen with too many re-renders errors. would anyone be able to help?
my firestore collection is named values and it stores Fname,Lname, bio, username and uid

import {
 StyleSheet,
 Text,
 View,
 Image,
} from 'react-native';
import { auth, db } from '../Firebase'

const  UserProfileView = () => {

   const [user, setUser] = useState();
   const {uid} = auth.currentUser.uid;

     const userRef = db.collection('values').doc(uid);
     const doc =  userRef.get();
     doc.data;

   const userData = doc.data;
   setUser(userData);

// Get user on mount
useEffect(() => {
   UserProfileView();
}, []);

//adapted from https://www.bootdey.com/react-native-snippet/12/User-profile-with-options

My return the only code that relates to the above is the text tag with user && user?.Fname

    return (
      <View style={styles.container}>
          <View style={styles.header}>
            <View style={styles.headerContent}>
                <Image style={styles.avatar}
                  source={{uri: 'https://bootdey.com/img/Content/avatar/avatar6.png'}}/>

                <Text style={styles.name}>{auth.currentUser?.uid} </Text>
                <Text style={styles.name}>{user && user?.Fname}</Text>
                <Text style={styles.userInfo}>{auth.currentUser?.email}</Text>
                <Text style={styles.userInfo}>Florida </Text>
            </View>
          </View>

          <View style={styles.body}>
            <View style={styles.item}>
              <View style={styles.iconContent}>
                <Image style={styles.icon} source={{uri: 'https://img.icons8.com/color/70/000000/cottage.png'}}/>
              </View>
              <View style={styles.infoContent}>
                <Text style={styles.info}>Home</Text>
              </View>
            </View>

            <View style={styles.item}>
              <View style={styles.iconContent}>
                <Image style={styles.icon} source={{uri: 'https://img.icons8.com/color/70/000000/administrator-male.png'}}/>
              </View>
              <View style={styles.infoContent}>
                <Text style={styles.info}>Settings</Text>
              </View>
            </View>

            <View style={styles.item}>
              <View style={styles.iconContent}>
                <Image style={styles.icon} source={{uri: 'https://img.icons8.com/color/70/000000/filled-like.png'}}/>
              </View>
              <View style={styles.infoContent}>
                <Text style={styles.info}>News</Text>
              </View>
            </View>

            <View style={styles.item}>
              <View style={styles.iconContent}>
                <Image style={styles.icon} source={{uri: 'https://img.icons8.com/color/70/000000/facebook-like.png'}}/>
              </View>
              <View style={styles.infoContent}>
                <Text style={styles.info}>Shop</Text>
              </View>
            </View>

          </View>
      </View>
    );
  }
export default UserProfileView;```

Body:
DocumentSnapshot.data() is a method, not a property, so:

const userData = doc.data;

Should actually be:

const userData = doc.data();