问:
Want to create a new group in contacts programmatically
I want to create a new contact group. I can query the group and display all the group names but I can't  create a group in android I tried as creating contacts method but not created... </p>

```<code>ContentResolver cr = this.getContentResolver();
    groupValues = new ContentValues();
    Log.e("Group","start");
    groupValues.put(android.provider.Contacts.GroupMembership.GROUP_ID, 4);
    groupValues.put(android.provider.Contacts.GroupMembership.NAME, "Sriseshaa");
    groupValues.put(android.provider.Contacts.GroupMembership.PERSON_ID, 1);

    cr.insert(android.provider.Contacts.GroupMembership.CONTENT_URI, groupValues);
</code>```

答:
i found the answer.i found in two ways but i dont know which is correct or best way to use.i am sharing those here..

its simple way like adding contact,

```<code>ContentValues groupValues;
create group()
{
 ContentResolver cr = this.getContentResolver();
 groupValues = new ContentValues();
 groupValues.put(ContactsContract.Groups.TITLE, "MyContactGroup");
 cr.insert(ContactsContract.Groups.CONTENT_URI, groupValues);
}
</code>```

Another method using ContentProviderOperation

```<code> private void createGroup() {
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    ops.add(ContentProviderOperation
            .newInsert(ContactsContract.Groups.CONTENT_URI)
            .withValue(ContactsContract.Groups.TITLE, "SRI").build());
    try {

        getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

    } catch (Exception e) {
        Log.e("Error", e.toString());
    }

}
</code>```

Thanks

Body:
I want to create a new contact group. I can query the group and display all the group names but I can't  create a group in android I tried as creating contacts method but not created...

ContentResolver cr = this.getContentResolver();
    groupValues = new ContentValues();
    Log.e("Group","start");
    groupValues.put(android.provider.Contacts.GroupMembership.GROUP_ID, 4);
    groupValues.put(android.provider.Contacts.GroupMembership.NAME, "Sriseshaa");
    groupValues.put(android.provider.Contacts.GroupMembership.PERSON_ID, 1);

    cr.insert(android.provider.Contacts.GroupMembership.CONTENT_URI, groupValues);

Body:
i found the answer.i found in two ways but i dont know which is correct or best way to use.i am sharing those here..

its simple way like adding contact,

ContentValues groupValues;
create group()
{
 ContentResolver cr = this.getContentResolver();
 groupValues = new ContentValues();
 groupValues.put(ContactsContract.Groups.TITLE, "MyContactGroup");
 cr.insert(ContactsContract.Groups.CONTENT_URI, groupValues);
}

Another method using ContentProviderOperation

 private void createGroup() {
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    ops.add(ContentProviderOperation
            .newInsert(ContactsContract.Groups.CONTENT_URI)
            .withValue(ContactsContract.Groups.TITLE, "SRI").build());
    try {

        getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

    } catch (Exception e) {
        Log.e("Error", e.toString());
    }

}

Thanks


来源: stackexchange

问:
How to copy from one folder all content (include subdirs) to distination?
I am new in c++, but I thought it should be pretty simple actually it doesn't.

What I need to do is copy all content of one dir to another destination, but not just copy I need to make implementation of progress for this I need to know entire amount of files that going to be copied and progress of coping.

For example I have such structure

```<code>1) myfolder -> foo.txt
2) myfolder -> a -> foo1.txt
3) myfolder -> a -> b -> foo2.txt
</code>```

I wrote such copy implementation for this

```<code>    /*static*/ void Utils::copy_files(std::string const & path_from,
        std::string const & path_to,
        TCallback progress_callback)
    {
        std::vector<std::string> paths_copy_from;
        std::vector<std::string> paths_copy_to;
        std::vector<std::string> tmp_final_dist;
        std::vector<std::string> path_to_inner_dirs;
        std::vector<std::string> paths = get_file_names_by_ext(path_from, "");

        if (progress_callback != nullptr)
        {
            progress_callback(0, 0);
        }

        separate_path_to_files_paht_to_folders(paths, tmp_final_dist, path_to_inner_dirs);

        for each(std::string tmp_dest in tmp_final_dist)
        {
            std::string file_name = base_name<std::string>(tmp_dest);
            std::string full_file_name = path_to + "\\" + file_name;
            paths_copy_to.push_back(full_file_name);
            paths_copy_from.push_back(tmp_dest);
        }

        tmp_final_dist.clear();

        for each(std::string tmp_dir in path_to_inner_dirs)
        {
            std::string dir_name = base_name<std::string>(tmp_dir);
            fs::create_directories(path_to + "\\" + dir_name);
            tmp_final_dist = get_file_names_by_ext(tmp_dir, "");

            for each(std::string tmp_files in tmp_final_dist)
            {
                std::string file_name = base_name<std::string>(tmp_files);
                std::string full_path_dest = path_to + "\\" + dir_name + "\\" + file_name;
                paths_copy_to.push_back(full_path_dest);
                paths_copy_from.push_back(tmp_files);
            }

            tmp_final_dist.clear();
        }

        tmp_final_dist.clear();

        //Actually these sizes always should be equal
        int length = min(static_cast<int>(paths_copy_from.size()), static_cast<int>(paths_copy_to.size()));

        for (int i = 0; i < length; i++)
        {
            std::ifstream  src(paths_copy_from[i], std::ios::binary);
            std::ofstream  dst(paths_copy_to[i], std::ios::binary);

            dst << src.rdbuf();

            src.close();
            dst.close();

            if (progress_callback != nullptr)
            {
                progress_callback(length, i + 1);
            }
        }
    }
</code>```

But because it is not a recursive I can copy just first to cases (mentioned above), what I can't copy is such structure myfolder -> a -> b -> foo2.txt, because here I have 2 inner layers.

About the solution I understand that I can add in my code one more for loop in order to iterate one more layer, but it is not what I am looking for, because tomorrow it could be +3 more layers and I will be need to add a lot of for loop interactions.

I need to find some kind of recursive solution where it does not matter how many layer I need to copy and also I need to know entire amount of file to be copied and copy progress.

答:
C++17 helps a lot. The below code (which I've written in 4.5 minutes and it's not tested) should give an idea of one possible solution:

```<code>#include <filesystem>
#include <algorithm>
#include <string>

void copy (const std::string& from, const std::string& to, long actualCopy);

int main()
{
    auto iterator = std::filesystem::directory_iterator("/tmp/source");
    int count = std::count_if (begin(iterator), end(iterator), [](auto& entry) {
        return (entry.is_regular_file() || entry.is_directory());
    });
    long actualCopy = 0;
    copy ("/tmp/source", "/tmp/dest", actualCopy);
    return 0;
}

void copy (const std::string& from, const std::string& to, long actualCopy)
{
    for(auto& p: std::filesystem::directory_iterator(from))
    {
        std::filesystem::copy(p, to);
        ++actualCopy;
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new in c++, but I thought it should be pretty simple actually it doesn't.

What I need to do is copy all content of one dir to another destination, but not just copy I need to make implementation of progress for this I need to know entire amount of files that going to be copied and progress of coping.

For example I have such structure

1) myfolder -> foo.txt
2) myfolder -> a -> foo1.txt
3) myfolder -> a -> b -> foo2.txt

I wrote such copy implementation for this

    /*static*/ void Utils::copy_files(std::string const & path_from,
        std::string const & path_to,
        TCallback progress_callback)
    {
        std::vector<std::string> paths_copy_from;
        std::vector<std::string> paths_copy_to;
        std::vector<std::string> tmp_final_dist;
        std::vector<std::string> path_to_inner_dirs;
        std::vector<std::string> paths = get_file_names_by_ext(path_from, "");

        if (progress_callback != nullptr)
        {
            progress_callback(0, 0);
        }

        separate_path_to_files_paht_to_folders(paths, tmp_final_dist, path_to_inner_dirs);

        for each(std::string tmp_dest in tmp_final_dist)
        {
            std::string file_name = base_name<std::string>(tmp_dest);
            std::string full_file_name = path_to + "\\" + file_name;
            paths_copy_to.push_back(full_file_name);
            paths_copy_from.push_back(tmp_dest);
        }

        tmp_final_dist.clear();

        for each(std::string tmp_dir in path_to_inner_dirs)
        {
            std::string dir_name = base_name<std::string>(tmp_dir);
            fs::create_directories(path_to + "\\" + dir_name);
            tmp_final_dist = get_file_names_by_ext(tmp_dir, "");

            for each(std::string tmp_files in tmp_final_dist)
            {
                std::string file_name = base_name<std::string>(tmp_files);
                std::string full_path_dest = path_to + "\\" + dir_name + "\\" + file_name;
                paths_copy_to.push_back(full_path_dest);
                paths_copy_from.push_back(tmp_files);
            }

            tmp_final_dist.clear();
        }

        tmp_final_dist.clear();

        //Actually these sizes always should be equal
        int length = min(static_cast<int>(paths_copy_from.size()), static_cast<int>(paths_copy_to.size()));

        for (int i = 0; i < length; i++)
        {
            std::ifstream  src(paths_copy_from[i], std::ios::binary);
            std::ofstream  dst(paths_copy_to[i], std::ios::binary);

            dst << src.rdbuf();

            src.close();
            dst.close();

            if (progress_callback != nullptr)
            {
                progress_callback(length, i + 1);
            }
        }
    }

But because it is not a recursive I can copy just first to cases (mentioned above), what I can't copy is such structure myfolder -> a -> b -> foo2.txt, because here I have 2 inner layers.

About the solution I understand that I can add in my code one more for loop in order to iterate one more layer, but it is not what I am looking for, because tomorrow it could be +3 more layers and I will be need to add a lot of for loop interactions.

I need to find some kind of recursive solution where it does not matter how many layer I need to copy and also I need to know entire amount of file to be copied and copy progress.

Body:
C++17 helps a lot. The below code (which I've written in 4.5 minutes and it's not tested) should give an idea of one possible solution:

#include <filesystem>
#include <algorithm>
#include <string>

void copy (const std::string& from, const std::string& to, long actualCopy);

int main()
{
    auto iterator = std::filesystem::directory_iterator("/tmp/source");
    int count = std::count_if (begin(iterator), end(iterator), [](auto& entry) {
        return (entry.is_regular_file() || entry.is_directory());
    });
    long actualCopy = 0;
    copy ("/tmp/source", "/tmp/dest", actualCopy);
    return 0;
}

void copy (const std::string& from, const std::string& to, long actualCopy)
{
    for(auto& p: std::filesystem::directory_iterator(from))
    {
        std::filesystem::copy(p, to);
        ++actualCopy;
    }
}


问:
Extracting year from datetime datatypes is giving output as float
I'm a newbee in Pandas. I need your support in a problem i'm facing
I have a datatime column in a dataframe and I'm trying to extract the year from it but the output it is giving is in float?

```<code>fifa['Joined_date'].head()
0   1970-01-01
1   1970-01-01
2   1970-01-01
3   1970-01-01
4   1970-01-01
Name: Joined_date, dtype: datetime64[ns]

fifa['Joined_date'].dt.year
0        1970.0
1        1970.0
2        1970.0
3        1970.0
4        1970.0
Name: Joined, Length: 18207, dtype: float64

Output Expected is --> 1970
</code>```

Can you please help?

答:
There are different ways but below are 2 may help you

this will apply on entire frame

```<code>pd.options.display.float_format = '{:,.0f}'.format
</code>```

this is for the column

```<code>df['your column'] = df['your column'].astype(int)
</code>```

if your column has mixed type of data

```<code> df['your column'] = df['your column'].astype(int, errors='ignore')
</code>```

Some cases you may have to convert the columns first to str and then again to int

Body:
I'm a newbee in Pandas. I need your support in a problem i'm facing
I have a datatime column in a dataframe and I'm trying to extract the year from it but the output it is giving is in float?

fifa['Joined_date'].head()
0   1970-01-01
1   1970-01-01
2   1970-01-01
3   1970-01-01
4   1970-01-01
Name: Joined_date, dtype: datetime64[ns]

fifa['Joined_date'].dt.year
0        1970.0
1        1970.0
2        1970.0
3        1970.0
4        1970.0
Name: Joined, Length: 18207, dtype: float64

Output Expected is --> 1970

Can you please help?

Body:
There are different ways but below are 2 may help you

this will apply on entire frame

pd.options.display.float_format = '{:,.0f}'.format

this is for the column

df['your column'] = df['your column'].astype(int)

if your column has mixed type of data

 df['your column'] = df['your column'].astype(int, errors='ignore')

Some cases you may have to convert the columns first to str and then again to int


答: You don't have to use header = 1 because you only have 1 row of header, remove header parameter, or use header = 0 or header = [0]

Title: Python KeyError column name not in index

Body:
another newbie question from me. Have following dataframe from Excel and I get the error, can someone let me know what I'm doing wrong, thank you:

EDIT:
here are the columns from the Excel

+----+--------+------+----+----+---+----+-----+----+-----+----+-------+-------+----------+--------+-----------+--------+-----+--------+------------+------+----------+-------+------------+-------+---------+-----+-----+-----+-----+------+----+-----+------+-----------+----------+----------+---------+
| Rk | Player | From | To | Tm | G | GS | Yrs | PB | AP1 | AV | GS/Yr | AV/Yr | QB_score | Height | Height-in | Weight | BMI | School | BCS School | 40YD | Vertical | Bench | Broad Jump | 3cone | Shuttle | Cmp | Att | Pct | Yds | AY/A | TD | Int | Rate | Rush_Att  | Rush_Yds | Rush_Avg | Rush_TD |
+----+--------+------+----+----+---+----+-----+----+-----+----+-------+-------+----------+--------+-----------+--------+-----+--------+------------+------+----------+-------+------------+-------+---------+-----+-----+-----+-----+------+----+-----+------+-----------+----------+----------+---------+

KeyError: "['Rush_Att'] not in index"

df = pd.read_excel('sportsref-qbdata-raw-v2.xlsx', header=1)

cols_to_keep = ['Player', 'QB_score', 'Height-in', 'Weight', 'BMI', 'BCS School', 'Cmp', 'Att', 'Pct', 'Yds', 'AY/A', 'TD', 'Int', 'Rate', 'Rush_Att', 'Rush_Yds', 'Rush_Avg', 'Rush_TD']

df = df[cols_to_keep]


问:
8 Columns in Twitter Bootstrap
How can I set up 8 equal columns in the latest version of Twitter bootstrap.

I can create 4 equal columns by doing the following but don't get how I can get 8:

```<code>    <div class="col-sm-12">
        <div class="row">
            <div class="col-sm-3">
                <div class="col-sm-12 col-xs-6">
                    <a href="#"><img src="/image.png" class="img-responsive" alt="..."></a>
                </div>
            </div>
            <div class="col-sm-3">
                <div class="col-sm-12 col-xs-6">
                    <a href="#"><img src="/image.png" class="img-responsive" alt="..."></a>
                </div>
            </div>
            <div class="col-sm-3">
                <div class="col-sm-12 col-xs-6">
                    <a href="#"><img src="/image.png" class="img-responsive" alt="..."></a>
                </div>
            </div>
            <div class="col-sm-3">
                <div class="col-sm-12 col-xs-6">
                    <a href="#"><img src="/image.png" class="img-responsive" alt="..."></a>
                </div>
            </div>
        </div>
    </div>
</code>```

答:
Best way to deal with this is to create table and divide the section with vw and then use bootstrap grid inside it.

My example is I wanted to divide layout into 63:37 ratio and again divide first part into 3 parts and second into two parts.

So I created table with two columns with width 63vw and 37vw then use bootstrap grid inside it respectively.

```<code><div class="row">
<table id="main_table" style="width: 100%;height: 100%" cellspacing="0">
    <tr style="width: 100%; position: relative">
        <td id="donut1" style="width: 63vw;">
            <div class="row">
                <div class="col-sm-4">
                    Loading
                </div>
                <div class="col-sm-4">
                    Loading
                </div>
                <div class="col-sm-4">
                    Loading
                </div>
            </div>
        </td>
        <td id="donut1" style="width: 37vw;">
            <div class="row">
                <div class="col-sm-6">
                    Loading
                </div>
                <div class="col-sm-6">
                    Loading
                </div>
            </div>
        </td>
    </tr>
</table>
</code>```

ContentLicense: CC BY-SA 3.0

Title: 8 Columns in Twitter Bootstrap

Body:
Best way to deal with this is to create table and divide the section with vw and then use bootstrap grid inside it.

My example is I wanted to divide layout into 63:37 ratio and again divide first part into 3 parts and second into two parts.

So I created table with two columns with width 63vw and 37vw then use bootstrap grid inside it respectively.

<div class="row">
<table id="main_table" style="width: 100%;height: 100%" cellspacing="0">
    <tr style="width: 100%; position: relative">
        <td id="donut1" style="width: 63vw;">
            <div class="row">
                <div class="col-sm-4">
                    Loading
                </div>
                <div class="col-sm-4">
                    Loading
                </div>
                <div class="col-sm-4">
                    Loading
                </div>
            </div>
        </td>
        <td id="donut1" style="width: 37vw;">
            <div class="row">
                <div class="col-sm-6">
                    Loading
                </div>
                <div class="col-sm-6">
                    Loading
                </div>
            </div>
        </td>
    </tr>
</table>


问:
jqGrid does not selects cell value as a selected dorp down value In edit mode
I am using jqGrid v 4.0 in my application to display tabuler data with Inline edit feature. One of the column in the Grid is a type of "Select". I have populated this select with following server side code:

```<code>    //get all Departments
    HRDept = $.ajax({
                        url: '../../PerformanceReview/GetHRDepartments/',
                        async: false,
                        success: function(data, result) {
                                    if (!result)
                                        alert('Failure to retrieve the HR Departments.');
                                 }
                         }).responseText;
</code>```

I have populated the Grid column with following sysntax:

```<code>    name: 'HRDepartment', index: 'Department', align: 'left', editable: true, edittype: 'select', editoptions: {value: HRDept}
</code>```

But on click of edit button (inline), it shows dropdown on on top of cell but the value is not equal to current cell value. it is always first value of drop down. I had compared the text which i am populating while loading Grid with the text of Dropdown and they are matching.

Could some one help me to set dropdown value similar as cell value.

答:
Your edit options look wrong, it should be "value:text;" and the value should match your data results.

```<code>    { ... editoptions: {value: "HRDept:HR Department;" }}
</code>```

You can checkout the demo of Row Edition -> Input Types at the jqGrid Demo site., which includes a dropdown list edit cell.

Body:
I am using jqGrid v 4.0 in my application to display tabuler data with Inline edit feature. One of the column in the Grid is a type of "Select". I have populated this select with following server side code:

    //get all Departments
    HRDept = $.ajax({
                        url: '../../PerformanceReview/GetHRDepartments/',
                        async: false,
                        success: function(data, result) {
                                    if (!result)
                                        alert('Failure to retrieve the HR Departments.');
                                 }
                         }).responseText;

I have populated the Grid column with following sysntax:

    name: 'HRDepartment', index: 'Department', align: 'left', editable: true, edittype: 'select', editoptions: {value: HRDept}

But on click of edit button (inline), it shows dropdown on on top of cell but the value is not equal to current cell value. it is always first value of drop down. I had compared the text which i am populating while loading Grid with the text of Dropdown and they are matching.

Could some one help me to set dropdown value similar as cell value.

Body:
Your edit options look wrong, it should be "value:text;" and the value should match your data results.

    { ... editoptions: {value: "HRDept:HR Department;" }}

You can checkout the demo of Row Edition -> Input Types at the jqGrid Demo site., which includes a dropdown list edit cell.


问:
How to incorporate a variable into a URI?
Basically I'm trying to put a result of a query into a file path, into the image source.

Updated code. Now I actually get the string I want but I still have trouble with interpolating it into the Uri constructor.

```<code> Random rand = new Random();
            var nrand = rand.Next(1, 4);

            using (var db = new DungeonContext())
            {
                var query = db.Rooms.Where(b => b.RoomId == nrand).Select(b => b.RoomName);
                foreach(string name in query)
                {
                    nameOfRoom = name;
                }
            }
</code>```

Somehow I have trouble setting images dir as Resources since I'm missing advancent properties for this folder.

```<code>roomScreen.Source = new BitmapImage(new Uri($"/images/{nameOfRoom}.png", UriKind.Relative));
</code>```

Making Uri relative seemed to stop throwing exceptions, but the intended effect does not happen.

答:
If it's in the project directory, utilizing the System.IO.Path namespace comes to mind - something like

```<code>Path.Combine(Environment.CurrentDirectory, $"/images/{nameOfRoom}.png")
</code>```

Body:
Basically I'm trying to put a result of a query into a file path, into the image source.

Updated code. Now I actually get the string I want but I still have trouble with interpolating it into the Uri constructor.

 Random rand = new Random();
            var nrand = rand.Next(1, 4);

            using (var db = new DungeonContext())
            {
                var query = db.Rooms.Where(b => b.RoomId == nrand).Select(b => b.RoomName);
                foreach(string name in query)
                {
                    nameOfRoom = name;
                }
            }

Somehow I have trouble setting images dir as Resources since I'm missing advancent properties for this folder.

roomScreen.Source = new BitmapImage(new Uri($"/images/{nameOfRoom}.png", UriKind.Relative));

Making Uri relative seemed to stop throwing exceptions, but the intended effect does not happen.

Body:
If it's in the project directory, utilizing the System.IO.Path namespace comes to mind - something like

Path.Combine(Environment.CurrentDirectory, $"/images/{nameOfRoom}.png")


问:
How can I generate a tsconfig.json file?
How can I generate a tsconfig.json via the command line?
I tried command tsc init, but this doesn't work.

答:
I recommend to uninstall typescript first with the command:

```<code>npm uninstall -g typescript
</code>```

then use the chocolatey package in order to run:

```<code>choco install typescript
</code>```

in PowerShell.

Body:
I recommend to uninstall typescript first with the command:

npm uninstall -g typescript

then use the chocolatey package in order to run:

choco install typescript

in PowerShell.


问:
Angular5 httpClient get:Cannot read property 'toLowerCase' of undefined
I am trying to get a list of Users from an API but I get the following error:

```<code>TypeError: Cannot read property 'toLowerCase' of undefined
at HttpXsrfInterceptor.intercept (http.js:2482)
at HttpInterceptorHandler.handle (http.js:1796)
at HttpInterceptingHandler.handle (http.js:2547)
at MergeMapSubscriber.eval [as project] (http.js:1466)
at MergeMapSubscriber._tryNext (mergeMap.js:128)
at MergeMapSubscriber._next (mergeMap.js:118)
at MergeMapSubscriber.Subscriber.next (Subscriber.js:92)
at ScalarObservable._subscribe (ScalarObservable.js:51)
at ScalarObservable.Observable._trySubscribe (Observable.js:172)
at ScalarObservable.Observable.subscribe (Observable.js:160)
</code>```

I have a login component that calls the homeService.getUsers() which uses HttpClient to retrieve the users but the http request never reaches the server.

login.component.ts:

```<code>import { Component, OnInit } from '@angular/core';

import { HomeService } from '../service/home.service';
import { User } from '../domain/user';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  user: User = {
      id: undefined,
      userName: undefined,
      password: undefined
  };
  users: User[];

  constructor(
    private homeService: HomeService
  ) { }

  ngOnInit() {
    this.getUsers();
  }

  getUsers(): void {
    this.homeService.getUsers()
    .subscribe(users => this.users = users);
  }
}
</code>```

Home.service:

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';

import { User } from '../domain/user';
import { MessageService } from '../service/message.service';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable()
export class HomeService {

  private usersUrl: 'http://localhost:8080/users';

  constructor(
    private http: HttpClient,
    private messageService: MessageService
  ) { }

  getUsers (): Observable<User[]> {
    return this.http.get<User[]>(this.usersUrl)
      .pipe(
        tap(users => this.log(`fetched users`)),
        catchError(this.handleError('getUsers', []))
      );
  }

  /**
  * Handle Http operation that failed.
  * Let the app continue.
  * @param operation - name of the operation that failed
  * @param result - optional value to return as the observable result
  */
  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // TODO: better job of transforming error for user consumption
      this.log(`${operation} failed: ${error.message}`);

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }

  private log(message: string) {
    this.messageService.add(message);
  }

}
</code>```

and the app.module:

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterModule, Routes } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { HttpClientXsrfModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { HomeService } from './service/home.service';
import { MessagesComponent } from './messages/messages.component';
import { MessageService } from './service/message.service';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    LoginComponent,
    RegisterComponent,
    MessagesComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    HttpClientXsrfModule.withOptions({
      cookieName: 'My-Xsrf-Cookie',
      headerName: 'My-Xsrf-Header',
    })
  ],
  providers: [HomeService, MessageService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

I can see the error message displayed in the logging, so it seems like an error from the HttpClient. But I can't figure out why it is failing before sending the Http request to the server.

答:
I also faced a similar kind of error, and, in order to solve it, I looked  up a bit and realised I declared the URL in wrongly.

The declaration should be something like this

```<code>private urlVariable = 'http://sampleurl.com';
</code>```

Body:
I am trying to get a list of Users from an API but I get the following error:

TypeError: Cannot read property 'toLowerCase' of undefined
at HttpXsrfInterceptor.intercept (http.js:2482)
at HttpInterceptorHandler.handle (http.js:1796)
at HttpInterceptingHandler.handle (http.js:2547)
at MergeMapSubscriber.eval [as project] (http.js:1466)
at MergeMapSubscriber._tryNext (mergeMap.js:128)
at MergeMapSubscriber._next (mergeMap.js:118)
at MergeMapSubscriber.Subscriber.next (Subscriber.js:92)
at ScalarObservable._subscribe (ScalarObservable.js:51)
at ScalarObservable.Observable._trySubscribe (Observable.js:172)
at ScalarObservable.Observable.subscribe (Observable.js:160)

I have a login component that calls the homeService.getUsers() which uses HttpClient to retrieve the users but the http request never reaches the server.

login.component.ts:

import { Component, OnInit } from '@angular/core';

import { HomeService } from '../service/home.service';
import { User } from '../domain/user';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  user: User = {
      id: undefined,
      userName: undefined,
      password: undefined
  };
  users: User[];

  constructor(
    private homeService: HomeService
  ) { }

  ngOnInit() {
    this.getUsers();
  }

  getUsers(): void {
    this.homeService.getUsers()
    .subscribe(users => this.users = users);
  }
}

Home.service:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';

import { User } from '../domain/user';
import { MessageService } from '../service/message.service';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable()
export class HomeService {

  private usersUrl: 'http://localhost:8080/users';

  constructor(
    private http: HttpClient,
    private messageService: MessageService
  ) { }

  getUsers (): Observable<User[]> {
    return this.http.get<User[]>(this.usersUrl)
      .pipe(
        tap(users => this.log(`fetched users`)),
        catchError(this.handleError('getUsers', []))
      );
  }

  /**
  * Handle Http operation that failed.
  * Let the app continue.
  * @param operation - name of the operation that failed
  * @param result - optional value to return as the observable result
  */
  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // TODO: better job of transforming error for user consumption
      this.log(`${operation} failed: ${error.message}`);

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }

  private log(message: string) {
    this.messageService.add(message);
  }

}

and the app.module:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterModule, Routes } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { HttpClientXsrfModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { HomeService } from './service/home.service';
import { MessagesComponent } from './messages/messages.component';
import { MessageService } from './service/message.service';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    LoginComponent,
    RegisterComponent,
    MessagesComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    HttpClientXsrfModule.withOptions({
      cookieName: 'My-Xsrf-Cookie',
      headerName: 'My-Xsrf-Header',
    })
  ],
  providers: [HomeService, MessageService],
  bootstrap: [AppComponent]
})
export class AppModule { }

I can see the error message displayed in the logging, so it seems like an error from the HttpClient. But I can't figure out why it is failing before sending the Http request to the server.

Body:
I also faced a similar kind of error, and, in order to solve it, I looked  up a bit and realised I declared the URL in wrongly.

The declaration should be something like this

private urlVariable = 'http://sampleurl.com';


Title: Pyspark - calculate average velocity in group based on time and location

Body:
I have the following PYSPARK dataframe:

+-------------------+----+---------+------+
|      timestamplast|ship|  X_pos  |time_d|
+-------------------+----+---------+------+
|2019-08-01 00:00:00|   1|     3   |   0  |
|2019-08-01 00:00:09|   1|     4   |   9  |
|2019-08-01 00:00:20|   1|     5   |  11  |
|2019-08-01 00:00:27|   1|     9   |   7  |
|2019-08-01 00:00:38|   2|     3   |   0  |
|2019-08-01 00:00:39|   2|     8   |   1  |
|2019-08-01 00:00:57|   2|     20  |  18  |
+-------------------+----+---------+------+

Where timestamplast is the datetime, time_d is the time difference within group "ship" (time_d is zero when a new "ship" starts. I want to calculate the average velocity within group "ship" and append the result to the dataframe based on the time difference and the position X_pos

The average velocity for ship==1 would be :(1/9 + 1/11 + 4/7)/3 = 0.26 m/s.
The average velocity for ship==2 would be :(5/1 + 12/18 /2 = 2.83 m/s.

EDIT:
The average velocity for ship==1 would be :((4-3)/(9) + (5-4)/(11) + (9-5)/(7))/3 = 0.26 m/s.
The average velocity for ship==2 would be :((8-3)/1 + ((20-8)/18)) /2 = 2.83 m/s.

Results should look like:

+-------------------+----+---------+------+-----------+
|      timestamplast|name|     X   |time_d| avg_vel_x |
+-------------------+----+---------+------+-----------|
|2019-08-01 00:00:00|   1|     3   |   0  |     0.26  |
|2019-08-01 00:00:09|   1|     4   |   9  |     0.26  |
|2019-08-01 00:00:20|   1|     5   |  11  |     0.26  |
|2019-08-01 00:00:27|   1|     9   |   7  |     0.26  |
|2019-08-01 00:00:38|   2|     3   |   0  |     2.83  |
|2019-08-01 00:00:39|   2|     8   |   1  |     2.83  |
|2019-08-01 00:00:57|   2|     20  |  18  |     2.83  |
+-------------------+----+---------+------+-----------|

Body:
transform in pandas can be replicated by windows function in pyspark similar to sql , your expected output for ship == 1 should be 0.26 instead. You can try:

import pyspark.sql.functions as F

w = Window.partitionBy('ship')
pct_change=((F.col("X_pos")-F.lag("X_pos").over(w.orderBy("timestamplast")))
                                                /F.col("time_d"))
df.withColumn("avg_vel_x",F.round(F.sum(pct_change).over(w)
                                 /(F.count("ship").over(w)-1),2)).show()

+-------------------+----+-----+------+---------+
|      timestamplast|ship|X_pos|time_d|avg_vel_x|
+-------------------+----+-----+------+---------+
|2019-08-01 00:00:00|   1|    3|     0|     0.26|
|2019-08-01 00:00:09|   1|    4|     9|     0.26|
|2019-08-01 00:00:20|   1|    5|    11|     0.26|
|2019-08-01 00:00:27|   1|    9|     7|     0.26|
|2019-08-01 00:00:38|   2|    3|     0|     2.83|
|2019-08-01 00:00:39|   2|    8|     1|     2.83|
|2019-08-01 00:00:57|   2|   20|    18|     2.83|
+-------------------+----+-----+------+---------+


问:
Simulating finally block in C++0x
Inspired from the other topic, I wrote this code which simulates a finally block:

```<code>#include <cassert>
#include <iostream>

struct base { virtual ~base(){} };

template<typename TLambda>
struct exec : base
{
   TLambda lambda;
   exec(TLambda l) : lambda(l){}
   ~exec() { lambda(); }
};

class lambda{
    base *pbase;
public:
    template<typename TLambda>
    lambda(TLambda l): pbase(new exec<TLambda>(l)){}
    ~lambda() { delete pbase; }
};

class A{
    int a;
public:
    void start(){
        int a=1;
        lambda finally = [&]{a=2; std::cout<<"finally executed";};
        try{
            assert(a==1);
            //do stuff
        }
        catch(int){
            //do stuff
        }
    }
};
int main() {
    A a;
    a.start();
}
</code>```

Output (ideone):

```<code>finally executed
</code>```

@Johannes seems to think that its not entirely correct, and commented that:

It can crash if the compiler doesn't
  elide the temporary in the copy
  initialization, because then it
  deletes twice with the same pointer
  value

I would like to know how exactly. Help me understanding the problem :-)

EDIT:

Problem fixed as:

```<code>class lambda{
    base *pbase;
public:
    template<typename TLambda>
    lambda(TLambda l): pbase(new exec<TLambda>(l)){}
    ~lambda() { delete pbase; }

    lambda(const lambda&)= delete;            //disable copy ctor
    lambda& operator=(const lambda&)= delete; //disable copy assignment
};
</code>```

And then use it as:

```<code>//direct initialization, no copy-initialization
lambda finally([&]{a=2;  std::cout << "finally executed" << std::endl; });
</code>```

Complete code : http://www.ideone.com/hsX0X

答:
Seems way more complicated than necessary.  Why not just:

```<code>class finally
{
    std::function<void (void)> const action;
    finally(const finally&) = delete;

public:
    finally(std::function<void (void)> a)
        : action(a)
    {}

    ~finally() { action(); }
};
</code>```

But in general, one should try not to carry bad Java habits over into C++.

Title: Simulating finally block in C++0x

Body:
Inspired from the other topic, I wrote this code which simulates a finally block:

#include <cassert>
#include <iostream>

struct base { virtual ~base(){} };

template<typename TLambda>
struct exec : base
{
   TLambda lambda;
   exec(TLambda l) : lambda(l){}
   ~exec() { lambda(); }
};

class lambda{
    base *pbase;
public:
    template<typename TLambda>
    lambda(TLambda l): pbase(new exec<TLambda>(l)){}
    ~lambda() { delete pbase; }
};

class A{
    int a;
public:
    void start(){
        int a=1;
        lambda finally = [&]{a=2; std::cout<<"finally executed";};
        try{
            assert(a==1);
            //do stuff
        }
        catch(int){
            //do stuff
        }
    }
};
int main() {
    A a;
    a.start();
}

Output (ideone):

finally executed

@Johannes seems to think that its not entirely correct, and commented that:

It can crash if the compiler doesn't
  elide the temporary in the copy
  initialization, because then it
  deletes twice with the same pointer
  value

I would like to know how exactly. Help me understanding the problem :-)

EDIT:

Problem fixed as:

class lambda{
    base *pbase;
public:
    template<typename TLambda>
    lambda(TLambda l): pbase(new exec<TLambda>(l)){}
    ~lambda() { delete pbase; }

    lambda(const lambda&)= delete;            //disable copy ctor
    lambda& operator=(const lambda&)= delete; //disable copy assignment
};

And then use it as:

//direct initialization, no copy-initialization
lambda finally([&]{a=2;  std::cout << "finally executed" << std::endl; });

Complete code : http://www.ideone.com/hsX0X

Body:
Seems way more complicated than necessary.  Why not just:

class finally
{
    std::function<void (void)> const action;
    finally(const finally&) = delete;

public:
    finally(std::function<void (void)> a)
        : action(a)
    {}

    ~finally() { action(); }
};

But in general, one should try not to carry bad Java habits over into C++.


问:
Multiline macro in c (#if-#endif)
my code:

```<code>#define DEBUG 3
#define TEST(...)
    #if (DEBUG == 3) \
        printf("%s: %s\n", __FILE__, __VA_ARGS__);
    #endif

int main(void) {

    TEST("TEST")

    return 0;
}
</code>```

Error: missing the binary operator before token 'printf'.

I don't understand what's the problem

答:
You're trying to put the #if inside the macro, but C doesn't permit that kind of thing.  The reason it's failing is the printf inside the #if is unexpected.  This is a common request, but it's just not allowed.

However, you can accomplish the same thing by changing the way you do the test:

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

#define DEBUG 3

#if (DEBUG == 3)
# define TEST(...) printf("%s: %s\n", __FILE__, __VA_ARGS__);
#else
# define TEST(...)
#endif

int main(void) {

   TEST("TEST")

   return 0;
}
</code>```

EDIT: Though test-type macros like this are common, this is not a great way to do it because it can lead to unhappy surprises in debug/nondebug situations.

What happens in this case?

```<code>   if (something)
       TEST("blah")
   else
       TEST("no")
</code>```

This works as you expect in debug mode, but won't even compile in production because it devolves to if (something) else - it doesn't even have a closing semicolon. It's easy to find other examples that are much more devious.

Hiding a semicolon inside a macro like this is usually asking for trouble, so the better approach is to make them function-like where you have to provide the semicolon yourself, and the most obvious way to do it is:

```<code>#  #define TEST(...) printf("%s: %s\n", __FILE__, __VA_ARGS__) // no semicolon

...
    if (something)
        TEST("blah");
    else
        TEST("no");
</code>```

This is better and leads to less surprises, but it's still a little troublesome in that it can leave a dangling semicolon lying around, which some compilers object to.

A fix for this can be:

```<code>#if (DEBUG == 3)
# define TEST(...) printf("%s: %s\n", __FILE__, __VA_ARGS__)
#else
# define TEST(...) ((void)0)  // dummy statement
#endif
</code>```

which at least quiets the compiler.  There are other approaches here too.

Title: Multiline macro in c (#if-#endif)

Body:
my code:

#define DEBUG 3
#define TEST(...)
    #if (DEBUG == 3) \
        printf("%s: %s\n", __FILE__, __VA_ARGS__);
    #endif

int main(void) {

    TEST("TEST")

    return 0;
}

Error: missing the binary operator before token 'printf'.

I don't understand what's the problem

Body:
You're trying to put the #if inside the macro, but C doesn't permit that kind of thing.  The reason it's failing is the printf inside the #if is unexpected.  This is a common request, but it's just not allowed.

However, you can accomplish the same thing by changing the way you do the test:

#include <stdio.h>

#define DEBUG 3

#if (DEBUG == 3)
# define TEST(...) printf("%s: %s\n", __FILE__, __VA_ARGS__);
#else
# define TEST(...)
#endif

int main(void) {

   TEST("TEST")

   return 0;
}

EDIT: Though test-type macros like this are common, this is not a great way to do it because it can lead to unhappy surprises in debug/nondebug situations.

What happens in this case?

   if (something)
       TEST("blah")
   else
       TEST("no")

This works as you expect in debug mode, but won't even compile in production because it devolves to if (something) else - it doesn't even have a closing semicolon. It's easy to find other examples that are much more devious.

Hiding a semicolon inside a macro like this is usually asking for trouble, so the better approach is to make them function-like where you have to provide the semicolon yourself, and the most obvious way to do it is:

#  #define TEST(...) printf("%s: %s\n", __FILE__, __VA_ARGS__) // no semicolon

...
    if (something)
        TEST("blah");
    else
        TEST("no");

This is better and leads to less surprises, but it's still a little troublesome in that it can leave a dangling semicolon lying around, which some compilers object to.

A fix for this can be:

#if (DEBUG == 3)
# define TEST(...) printf("%s: %s\n", __FILE__, __VA_ARGS__)
#else
# define TEST(...) ((void)0)  // dummy statement
#endif

which at least quiets the compiler.  There are other approaches here too.


问:
Flash Builder 4.5 - orange question mark circle, how to get rid of it?
I noticed a new addition in the FB 4.5, a question mark in orange circle appears on the left border of text editor. I don't know what it should indicate but for my 4.1 project it appears on every single line of code with messages like this:

Type was not found or was not a compile-time constant: String

Whaaa??

I have no errors in the code and project compiles normally. Any idea how to get rid of them?

答: This may b due to imported classes are not registered properly, just import the classes/components again and clean your project by click on project menu and select clean. compile it and then see, if the same situation then reply here.</p>


问:
understanding tensorflow binary image classification results
For one of my first attempts at using Tensor flow I've followed the Binary Image Classification tutorial https://www.tensorflow.org/tutorials/keras/text_classification_with_hub#evaluate_the_model.

I was able to follow the tutorial fine, but then I wanted to try to inspect the results more closely, namely I wanted to see what predictions the model made for each item in the test data set.

In short, I wanted to see what "label" (1 or 0) it would predict applies to a given movie review.

So I tried:

results = model.predict(test_data.batch(512))

and then

for i in results:
    print(i)

This gives me close to what I would expect. A list of 25,000 entries (one for each movie review).

But the value of each item in the array is not what I would expect. I was expecting to see a predicted label, so either a 0 (for negative) or 1 (for positive).

But instead I get this:

```<code>[0.22731477]
[2.1199656]
[-2.2581818]
[-2.7382329]
[3.8788114]
[4.6112833]
[6.125982]
[5.100685]
[1.1270659]
[1.3210837]
[-5.2568426]
[-2.9904163]
[0.17620209]
[-1.1293088]
[2.8757455]
...and so on for 25,000 entries.
</code>```

Can someone help me understand what these numbers mean.

Am I misunderstanding what the "predict" method does, or (since these number look similar to the word embedding vectors introduced in the first layer of the model) perhaps I am misunderstanding how the prediction relates to the word embedding layer and the ultimate classification label.

I know this a major newbie question. But appreciate your help and patience :)

答:
According to the link that you provided, the problem come from your output activation function. That code use dense vector with 1 neuron without activation function. So it just multiplying output from previous layer with weight and bias and sum them together. The output that you get will have a range between -infinity(negative class) and +infinity(positive class), Therefore if you really want your output between zero and one you need an activation function such as sigmoid model.add(tf.keras.layers.Dense(1), activation='sigmoid'). Now we just map every thing to range 0 to 1, so we can classify as negative class if output is less than 0.5(mid point) and vice versa.

Actually your understanding of prediction function is correct. You simply did not add an activation to fit with your assumption, that's why you gat that output instead of value between 0 and 1.

Body:
For one of my first attempts at using Tensor flow I've followed the Binary Image Classification tutorial https://www.tensorflow.org/tutorials/keras/text_classification_with_hub#evaluate_the_model.

I was able to follow the tutorial fine, but then I wanted to try to inspect the results more closely, namely I wanted to see what predictions the model made for each item in the test data set.

In short, I wanted to see what "label" (1 or 0) it would predict applies to a given movie review.

So I tried:

results = model.predict(test_data.batch(512))

and then

for i in results:
    print(i)

This gives me close to what I would expect. A list of 25,000 entries (one for each movie review).

But the value of each item in the array is not what I would expect. I was expecting to see a predicted label, so either a 0 (for negative) or 1 (for positive).

But instead I get this:

[0.22731477]
[2.1199656]
[-2.2581818]
[-2.7382329]
[3.8788114]
[4.6112833]
[6.125982]
[5.100685]
[1.1270659]
[1.3210837]
[-5.2568426]
[-2.9904163]
[0.17620209]
[-1.1293088]
[2.8757455]
...and so on for 25,000 entries.

Can someone help me understand what these numbers mean.

Am I misunderstanding what the "predict" method does, or (since these number look similar to the word embedding vectors introduced in the first layer of the model) perhaps I am misunderstanding how the prediction relates to the word embedding layer and the ultimate classification label.

I know this a major newbie question. But appreciate your help and patience :)


问:
Append to URL and refresh page
I am looking to write a piece of javascript that will append a parameter to the current URL and then refresh the page - how can I do this?</p>

答:
Also:

```<code>window.location.href += (window.location.href.indexOf('?') > -1 ? '&' : '?') + 'param=1'
</code>```

Just one liner of Shlomi answer usable in bookmarklets

Title: Append to URL and refresh page

Body:
Also:

window.location.href += (window.location.href.indexOf('?') > -1 ? '&' : '?') + 'param=1'

Just one liner of Shlomi answer usable in bookmarklets


问:
AddThis. LinkedIn sharing is not working on iPhone
When I try to share my page with AddThis to Linkedin it is working fine from desktop, but even the same URL is not working when I do just the same from iPhone.

To test it:

Open AddThis home page and click share to LinkedIn button. As a result I have http://www.linkedin.com/shareArticle?mini=true&url=http%3A%2F%2Fwww.addthis.com%2F%23.Tt3z80Hs1Wo.linkedin&title=AddThis+-+Share+Button%2C+Social+Bookmark%2C+Sharing+Plugins+and+Module&ro=false&summary=&source= opened in my browser, which is working fine.

Try to open just the same URL from an iPhone. I have the following error in this case: "We’re sorry. Something unexpected happened and your request could not be completed. Please close this window and try again."

Sounds like LinkedIn API issue. Any ideas how can I fix it?

Thank you.

答:
You're going to want to update your URL format to conform to the Official Microsoft "Share on LinkedIn" Documentation.  The format of your URL should be...

```<code>https://www.linkedin.com/sharing/share-offsite/?url={url}
</code>```

Furthermore, parameters like source, title, and summary have all been deprecated, but you can replicate their behavior again by setting the appropriate og: tags in the HTML of your web page, which is good standard anyway.  Quoting from Official LinkedIn "Making Your Website Shareable on LinkedIn" Documentation, just put these into your page's HTML:

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

If you make these adjustments, sharing on your page should behave just like it once did!

Body:
You're going to want to update your URL format to conform to the Official Microsoft "Share on LinkedIn" Documentation.  The format of your URL should be...

https://www.linkedin.com/sharing/share-offsite/?url={url}

Furthermore, parameters like source, title, and summary have all been deprecated, but you can replicate their behavior again by setting the appropriate og: tags in the HTML of your web page, which is good standard anyway.  Quoting from Official LinkedIn "Making Your Website Shareable on LinkedIn" Documentation, just put these into your page's HTML:

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

If you make these adjustments, sharing on your page should behave just like it once did!


问:
How to debug kubernetes deployed service using Eclipse
I have a micro service written using Java EE + Openliberty. I have deployed this into kubernetes in my Docker-Desktop. I want to know, is there any way to debug this deployed service? I am using Eclipse. Please let me know how can I debug deployed service. Thank you!

答:
I heartily endorse looking at telepresence.  I don't use it for real yet, but I've verified it will be very useful in our enterprise once we get some pieces in place.

However, I don't believe you need that complication for your simpler situation.  Telepresence will be very nice for injecting NEW code into a cluster without actually deploying it.  In your case, you just want to debug the existing code.  This allows for a simpler mechanism.

To remotely debug in Eclipse, you need to connect to a debugger port.  To do this with code running in a k8s cluster, you have to expose the port to connect to, and make it available on your desktop.

In your image, you have to ensure that your Java command line has the "-Xdebug" parameters, which specifies the debugger port (5005 by convention).  You also have to ensure that your Dockerfile specifies that port to be exposed.  When that is running in your cluster, you have to use "kubectl port-forward" on your desktop (with appropriate parameters). This will proxy the debugger port in the cluster to a corresponding port on your desktop.  You then connect to that port from Eclipse.


问:
Can't replace string content in pandas DataFrame
I have values from submission that I appended into a data frame that look like the following:

```<code>df['SalePrice'] = submission

0       [381659.34]
1       [639894.75]
2       [189159.39]
3       [203588.45]
4       [609621.25]
</code>```

I tried to remove the brackets from each side of the float with this code:

```<code>df['SalePrice'] = df.SalePrice.replace("[","").replace("]","")
print(df['SalePrice'])
</code>```

I am not able to remove the brackets.  Is there any way to clean-up this float in Python?

答:
Try flattening the list before you put it into the dataframe:</p>

```<code>submission_flat = [item for sublist in submission for item in sublist]
df['SalePrice'] = submission_flat
</code>```

Body:
I have values from submission that I appended into a data frame that look like the following:

df['SalePrice'] = submission

0       [381659.34]
1       [639894.75]
2       [189159.39]
3       [203588.45]
4       [609621.25]

I tried to remove the brackets from each side of the float with this code:

df['SalePrice'] = df.SalePrice.replace("[","").replace("]","")
print(df['SalePrice'])

I am not able to remove the brackets.  Is there any way to clean-up this float in Python?

Body:
Try flattening the list before you put it into the dataframe:

submission_flat = [item for sublist in submission for item in sublist]
df['SalePrice'] = submission_flat


答: In C #define cannot "contain" #ifs

Title: Multiline macro in c (#if-#endif)

Body: In C #define cannot "contain" #ifs


问:
Problem submitting form not working for me
i need help, am trying to submit a form using jquery but its not working for me    </p>

```<code><form id="form" method="post" value="" action="https://google.com">
    <input type="text" id="input">
    <input type="button" id="button" value="Submit">
</form>

<script type="text/javascript">
$(document).ready(function () {
    $( "#button" ).click(function() {
        $( "#form" ).submit();
    });
});
</script>
</code>```

答:
```<code><form id="form" class="anyname" method="post" value="" action="https://google.com">
    <input type="text" id="input">
    <input type="button" id="button" value="Submit">
</form>
</code>```

after giving a class to the form you can run the following jquery

```<code>$('.anyname')[0].submit();
</code>```

Body:
i need help, am trying to submit a form using jquery but its not working for me

<form id="form" method="post" value="" action="https://google.com">
    <input type="text" id="input">
    <input type="button" id="button" value="Submit">
</form>

Body:
<form id="form" class="anyname" method="post" value="" action="https://google.com">
    <input type="text" id="input">
    <input type="button" id="button" value="Submit">
</form>

after giving a class to the form you can run the following jquery

$('.anyname')[0].submit();


问:
Scroll bar Style change in all browser?
Is there any strong CSS or jQuery in web technology which can change style of scroll-bar in all browsers .I want to change default full width window screen scroll bar style. </p>

答:
The following CSS won't work in Internet Explorer, Microsoft Edge, or Firefox:</p>

```<code>/*used to determine the width of scroll bar*/
::-webkit-scrollbar
{width:5px;}

/*where the draggable handle moves*/
::-webkit-scrollbar-track
{background:#212121;}

/*defining the draggable handle*/
::-webkit-scrollable-thumb
{background:#f1f1f1; border-radius:2.5px}

/*hovering over draggable handle*/
::-webkit-scrollbar-thumb:hover
{background:#555;}
</code>```

Title: Scroll bar Style change in all browser?

Body:
The following CSS won't work in Internet Explorer, Microsoft Edge, or Firefox:

/*used to determine the width of scroll bar*/
::-webkit-scrollbar
{width:5px;}

/*where the draggable handle moves*/
::-webkit-scrollbar-track
{background:#212121;}

/*defining the draggable handle*/
::-webkit-scrollable-thumb
{background:#f1f1f1; border-radius:2.5px}

/*hovering over draggable handle*/
::-webkit-scrollbar-thumb:hover
{background:#555;}


答:
Try using onclick event.

function ClickMethod() {
  document.getElementById("form").submit();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form" method="post" value="" action="https://google.com">
  <input type="text" id="input">
  <input type="button" id="btnSubmit" onclick="ClickMethod()" value="Submit">
</form></code>```

Title: Problem submitting form not working for me

Body:
Try using onclick event.

function ClickMethod() {
  document.getElementById("form").submit();
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form" method="post" value="" action="https://google.com">
  <input type="text" id="input">
  <input type="button" id="btnSubmit" onclick="ClickMethod()" value="Submit">
</form>


问:
Show Bootstrap Alert on Button Click via Javascript / jQuery
I've referenced some other questions on here about showing and hiding a Bootstrap Alert on button click, but for some reason my implementation is not working. I am using Bootstrap 4, however, although from my beginner knowledge things should still work correctly.

I've referenced Bootstrap's documentation on dismissing alerts, and I have modified their sample to remove the show class from the alert as I simply want to show the alert upon a button click. The dismissal should work fine as the close button on the alert will be implemented from the HTML.

HTML

```<code><!-- Alert -->
<div class="alert alert-success alert-dismissible fade" role="alert" id="buttonAlert">
    <strong>Success!</strong> You just showed an alert.
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">×</span>
    </button>
</div>

<!-- Submit Button -->
<div class="form-group">
    <a href="#" class="btn btn-primary" data-toggle="modal" data-target="#ModalCenter" id="modalButton">Click me</a>
    </div>
</div>
</code>```

JavaScript

```<code>  $(document).ready(function() {
      $("#modalButton").click(function(){
          // alert("Success!") //Test to see if the function worked, it did
      $("#buttonAlert").show() //Shows Bootstrap alert
      })
  })
</code>```

So the JavaScript function works as I've tested it with alert("Success!"), but the Bootstrap alert line $("#buttonAlert").show() does not show anything?

Note I am brand new to Bootstrap and Javascript/Jquery, I'm just trying to put some sample code together to learn so please bear with me.

答:
If you want it fully dynamic and can use the new templating in JS, you could do something like this if you had a div with id of "notification". I just pass in message hard-code "Success" for the title, but you could change that if you'd like.

The css for it is like this:

```<code>#notification {
    position: fixed;
    right: 20px;
    top: 50px;
    width: 400px;
    z-index: 999999;
}
</code>```

JS Code:

```<code>const handleToastOpenAndClose = ($alert, autoCloseDelay) => {
    $alert.fadeIn();

    const fadeCall = fadingEvent => fadingEvent.slideUp(500, () => $alert.slideUp(500, () => $alert.alert('close')));
    if (autoCloseDelay) {
        var fadingEvent = $alert.fadeTo(autoCloseDelay, 500, () => fadeCall(fadingEvent));
        $alert.hover(
            () => fadingEvent.stop(),
            () => fadingEvent = $alert.fadeTo(autoCloseDelay, 500, () => fadeCall(fadingEvent))
        );
    }
};

window.toastSuccess = (message, autoCloseDelay) => {
    var html = `<div class="alert alert-success alert-dismissible hidden" role="alert">
            <div><strong>Success</strong></div>
            ${message}
            <button class="close" type="button" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">x</span>
            </button>
       </div>`;

    $('#notification').append(html);
    var $alert = $("#notification .alert:last");
    handleToastOpenAndClose($alert, autoCloseDelay);
};
</code>```

Body:
I've referenced some other questions on here about showing and hiding a Bootstrap Alert on button click, but for some reason my implementation is not working. I am using Bootstrap 4, however, although from my beginner knowledge things should still work correctly.

I've referenced Bootstrap's documentation on dismissing alerts, and I have modified their sample to remove the show class from the alert as I simply want to show the alert upon a button click. The dismissal should work fine as the close button on the alert will be implemented from the HTML.

HTML

    Success! You just showed an alert.
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        ×
    </button>

    Click me

JavaScript

  $(document).ready(function() {
      $("#modalButton").click(function(){
          // alert("Success!") //Test to see if the function worked, it did
      $("#buttonAlert").show() //Shows Bootstrap alert
      })
  })

So the JavaScript function works as I've tested it with alert("Success!"), but the Bootstrap alert line $("#buttonAlert").show() does not show anything?

Note I am brand new to Bootstrap and Javascript/Jquery, I'm just trying to put some sample code together to learn so please bear with me.

Body:
If you want it fully dynamic and can use the new templating in JS, you could do something like this if you had a div with id of "notification". I just pass in message hard-code "Success" for the title, but you could change that if you'd like.

The css for it is like this:

#notification {
    position: fixed;
    right: 20px;
    top: 50px;
    width: 400px;
    z-index: 999999;
}

JS Code:

const handleToastOpenAndClose = ($alert, autoCloseDelay) => {
    $alert.fadeIn();

    const fadeCall = fadingEvent => fadingEvent.slideUp(500, () => $alert.slideUp(500, () => $alert.alert('close')));
    if (autoCloseDelay) {
        var fadingEvent = $alert.fadeTo(autoCloseDelay, 500, () => fadeCall(fadingEvent));
        $alert.hover(
            () => fadingEvent.stop(),
            () => fadingEvent = $alert.fadeTo(autoCloseDelay, 500, () => fadeCall(fadingEvent))
        );
    }
};

window.toastSuccess = (message, autoCloseDelay) => {
    var html = `<div class="alert alert-success alert-dismissible hidden" role="alert">
            <div><strong>Success</strong></div>
            ${message}
            <button class="close" type="button" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">x</span>
            </button>
       </div>`;

    $('#notification').append(html);
    var $alert = $("#notification .alert:last");
    handleToastOpenAndClose($alert, autoCloseDelay);
};


问:
jQuery preventDefault onclick function
I have this simple jQuery script that asks to confirm action when you click on a link. And it works great when it's a normal a href link, but I have onclick script assigned to the button and it does not prevent it from firing. I need it to prevent it only once. How can I achieve that?

$(".mybutton").one('click', function() {
    event.preventDefault();
    $(this).html("Are you sure?");
});

function test() {
  $(".forthebutton").html("button click function worked");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="mybutton" onclick="test();">Button</button>

<br /><br /><br />

<span class="forthebutton">button click should change this text</span></code>```

答:
You need to remove original onclick and give it back in this case because you can't influent on onclick handler.

const btn = $(".mybutton");
const onclick = btn.prop('onclick'); // save onclick fn

btn.prop('onclick', null); // remove onclick from button
btn.one('click', function() {
    $(this).html("Are you sure?");
    btn.on('click', onclick); // add onclick back to button
});

function test() {
  $(".forthebutton").html("button click function worked");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="mybutton" onclick="test();">Button</button>

<br /><br /><br />

<span class="forthebutton">button click should change this text</span></code>```

Title: jQuery preventDefault onclick function

Body:
I have this simple jQuery script that asks to confirm action when you click on a link. And it works great when it's a normal a href link, but I have onclick script assigned to the button and it does not prevent it from firing. I need it to prevent it only once. How can I achieve that?

$(".mybutton").one('click', function() {
    event.preventDefault();
    $(this).html("Are you sure?");
});

function test() {
  $(".forthebutton").html("button click function worked");
}

<button class="mybutton" onclick="test();">Button</button>

button click should change this text

Body:
You need to remove original onclick and give it back in this case because you can't influent on onclick handler.

const btn = $(".mybutton");
const onclick = btn.prop('onclick'); // save onclick fn

btn.prop('onclick', null); // remove onclick from button
btn.one('click', function() {
    $(this).html("Are you sure?");
    btn.on('click', onclick); // add onclick back to button
});

function test() {
  $(".forthebutton").html("button click function worked");
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="mybutton" onclick="test();">Button</button>

<br /><br /><br />

<span class="forthebutton">button click should change this text</span>


问:
Distributing subtraction over bigop
What is the best way to rewrite \sum_(i...) (F i - G i) as (\sum_(i...) F i - \sum_(i...) G i) on ordinals with bigop, assuming that underflows are properly managed?

More precisely, regarding these underflows, I'm interested in the following lemma:

Lemma big_split_subn (n : nat) (P : 'I_n -> bool) (F G : 'I_n -> nat) :
  (forall i : 'I_n, P i -> G i <= F i) ->
    \sum_(i < n | P i) (F i - G i) = \sum_(i < n | P i) F i - \sum_(i < n | P i) G i.

It seems that big_split should work for an addition (or subtraction in Z, using big_distrl with -1), but I need to use it for a subtraction on (bounded) naturals.

Thanks in advance for any suggestion.

Bye,

Pierre

答:
Here is a nice answer written by Emilio Gallego Arias (user:1955696) (thanks, Emilio).</p>

```<code>Lemma big_split_subn (P : 'I_k -> bool) F1 F2
      (H : forall s : 'I_k, P s -> F2 s <= F1 s) :
  \sum_(s < k | P s) (F1 s - F2 s) =
  \sum_(s < k | P s) F1 s - \sum_(s < k | P s) F2 s.
Proof.
suff:
  \sum_(s < k | P s) (F1 s - F2 s) =
    \sum_(s < k | P s) F1 s - \sum_(s < k | P s) F2 s /\
    \sum_(s < k | P s) F2 s <= \sum_(s < k | P s) F1 s by case.
pose K x y z := x = y - z /\ z <= y.
apply: (big_rec3 K); first by []; rewrite {}/K.
move=> i b_x b_y b_z /H Pi [] -> Hz; split; last exact: leq_add.
by rewrite addnBA ?addnBAC ?subnDA.
Qed.
</code>```

Title: Distributing subtraction over bigop

Body:
Here is a nice answer written by Emilio Gallego Arias (user:1955696) (thanks, Emilio).

Lemma big_split_subn (P : 'I_k -> bool) F1 F2
      (H : forall s : 'I_k, P s -> F2 s <= F1 s) :
  \sum_(s < k | P s) (F1 s - F2 s) =
  \sum_(s < k | P s) F1 s - \sum_(s < k | P s) F2 s.
Proof.
suff:
  \sum_(s < k | P s) (F1 s - F2 s) =
    \sum_(s < k | P s) F1 s - \sum_(s < k | P s) F2 s /\
    \sum_(s < k | P s) F2 s <= \sum_(s < k | P s) F1 s by case.
pose K x y z := x = y - z /\ z <= y.
apply: (big_rec3 K); first by []; rewrite {}/K.
move=> i b_x b_y b_z /H Pi [] -> Hz; split; last exact: leq_add.
by rewrite addnBA ?addnBAC ?subnDA.
Qed.


问:
Protecting Java data (saving items to a secure file)?
I am making a simple text game in Java and I wanted a safe way to save statistics (money, etc).

I could do a text file but then it could just be modified. I was wondering if there was a simple way to make it a little more difficult for someone to mess around with the saved statistics.

答:
Serializing might be a simple solution. Store the data that needs to be saved into a Serializable class (Look up the java Serializable interface) and write it to a file. It won't be uber-encrypted, but it'll stop people from just opening it up in notepad and changing it.

Here's a simple example of how to serialize an object to a file; googling around should produce more if needed.
http://www.rgagnon.com/javadetails/java-0075.html


问:
Back navigation after deeplink by navigation architecture component
When I open the app from a deeplink (user clicks on URL) and press back button I expect user to navigate to a previous fragment in my navigation graph but it just exits the app.

The documentation says that back navigation should work the same way as if it the user got to that screen naturally.

Can I somehow specify the desired backstack in my navigation graph? Or can be backstack formed automatically after a deeplink? For older version of the library I found out that after back press it should navigate to the root of my navigation graph but that does not happen.

I’m using the navigation library from Android architecture components (version 1.0.0-beta01).

答:
I found out what's going on here, for explicit deep links its supposed to go to a new back stack which is what you app would have if a user had naturally navigated to the view not the existing back stack (existing stack is cleared.

When a user opens your app via an explicit deep link, the task back stack is cleared and replaced with the deep link destination. When nesting graphs, the start destination from each level of nesting—that is, the start destination from each  element in the hierarchy—is also added to the stack. This means that when a user presses the Back button from a deep link destination, they navigate back up the navigation stack just as though they entered your app from its entry point.

For implicit its a bit strange. You can make it do what explicit does but setting Intent.FLAG_ACTIVITY_NEW_TASK otherwise the back button and the navigation up button do two separate things:

The back button will do as you might expect, it will go back in your apps existing back stack and load that fragment.

The up button however will clear the a back stack and make a new one as if it was an explicit link.

If the flag is not set, you remain on the task stack of the previous app where the implicit deep link was triggered. In this case, the Back button takes you back to the previous app, while the Up button starts your app's task on the hierarchical parent destination within your navigation graph.kquote

Source: Android Documentation


问:
Python3 - List comprehension: Not in nested lists
I have some simple code:

```<code>list1 = [['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
list2 = ['one', 'three', 'four', 'five', 'six']

for l in list2:

    new_list = [x for x in list1 if x[0] != l]
    print(new_list)
</code>```

I want my output to be:

```<code>'four'
'five'
'six'
</code>```

...instead however I am getting:

```<code>[['two', 'green', 'dog'], ['three', 'red', 'horse']]
[['one', 'blue', 'cat'], ['two', 'green', 'dog']]
[['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
[['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
[['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
</code>```

...what am I doing wrong?

Thanks

答:
You are printing a new list in every iteration. I believe this is what you meant to do?

```<code>list1 = [['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
list2 = ['one', 'three', 'four', 'five', 'six']

list3 = []
for l in list1:
    list3 += l

new_list = [w for w in list2 if w not in list3]
print('\n'.join(new_list))
</code>```

Output:

```<code>four
five
six
</code>```

Body:
I have some simple code:

list1 = [['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
list2 = ['one', 'three', 'four', 'five', 'six']

for l in list2:

    new_list = [x for x in list1 if x[0] != l]
    print(new_list)

I want my output to be:

'four'
'five'
'six'

...instead however I am getting:

[['two', 'green', 'dog'], ['three', 'red', 'horse']]
[['one', 'blue', 'cat'], ['two', 'green', 'dog']]
[['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
[['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
[['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]

...what am I doing wrong?

Thanks

Body:
You are printing a new list in every iteration. I believe this is what you meant to do?

list1 = [['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
list2 = ['one', 'three', 'four', 'five', 'six']

list3 = []
for l in list1:
    list3 += l

new_list = [w for w in list2 if w not in list3]
print('\n'.join(new_list))

Output:

four
five
six


问:
Activity to fragment Communication in Android
I am using fragment for the first time. I am trying to get List of videos from youtube present in my fragment. I am retrieving a youtube url from firebase and extract playlist id from it. This playlist id is passed as a parameter to fragment which would then list out all the videos present in the playist. i am successfully able to retrieve the playlist id in the fragment, but it changes to null in the url. Any help is appreciable.thanks in advance.
CollegeGallery.java

```<code>    public CollegeImageGrid imagegrid;
    private static final String TAG = "CollegeGallery";
    public GridView grid_image, grid_video;
    public DatabaseReference ref;
    private String collegeid;
    private TextView moreimages, morevideos;
    private String playlistid;

    public void setPlayid(String playlistid) {
        this.playlistid = playlistid;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_college_gallery);

        ref = FirebaseDatabase.getInstance().getReference("collegedata");
        //this will get the data from previous intent
        collegeid = getIntent().getStringExtra("gallery");
        grid_image = findViewById(R.id.grid_image);
//        grid_video = findViewById(R.id.grid_video); //for grid view of videos

        moreimages = findViewById(R.id.more_images);
        morevideos = findViewById(R.id.more_videos);

        //a list of string will  be passed to  imagegrid object
        ref.child(String.valueOf(collegeid)).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
               //object of College class to get getImageurls() which has the list of urls
                College clg = dataSnapshot.getValue(College.class);
                //setting the list to imagegrid, passing url from this activity to imageview.
                imagegrid = new CollegeImageGrid(CollegeGallery.this,clg.getImageurls());
                //setting adapter to grid with the list of urls
                grid_image.setAdapter(imagegrid); //check error, getCount is null, crashes application.
                //extracting playlist id
                String playid = getYoutubeVideoId(clg.getVideourls());
                //fragment code
                YoutubeVideoList yt = new YoutubeVideoList();
                FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
                tr.replace(R.id.youtube_frag, YoutubeVideoList.newInstance(playid)).commit();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(CollegeGallery.this, "No images", Toast.LENGTH_SHORT).show();
            }
        });

        moreimages.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent image_in = new Intent(CollegeGallery.this,AllCollegeImages.class);
                image_in.putExtra("image",collegeid);
                startActivity(image_in);
            }
        });

        //will take to activity with only playlist video list fragment
        morevideos.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(CollegeGallery.this, CompleteVideoList.class));
            }
        });

    }

    //function to extract playlist id
    public static String getYoutubeVideoId(String youtubeUrl) {
        String video_id = "";
        if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http")) {

            String expression = "^.*?(?:list)=(.*?)(?:&|$)";

            CharSequence input = youtubeUrl;
            Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(input);
            if (matcher.matches()) {
                String groupIndex1 = matcher.group(1);
                video_id = groupIndex1;
            }
        }
        return video_id;
    }

}
</code>```

YoutubeVideoList.java(Fragment)

```<code>
    private static String ARG_Param1;
    private static String id;
    List<YoutubeVideoModel> vids;
    Button btn;
    YoutubeAdapter adapter;
    RecyclerView recyclerView;
    RecyclerView.LayoutManager manager;
    String mparam1;

    public YoutubeVideoList() {
    }

    //retrieving playlist id from the previous activity
    public static YoutubeVideoList newInstance(String id) {
        YoutubeVideoList yt = new YoutubeVideoList();
        Bundle args = new Bundle();
        args.putString(ARG_Param1, id);
        yt.setArguments(args);
        return yt;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mparam1 = getArguments().getString(ARG_Param1);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_youtube_video_list, container, false);
    }

    @Override
    public  void onViewCreated(View container, Bundle savedInstanceState) {
        super.onViewCreated(container, savedInstanceState);
        recyclerView = container.findViewById(R.id.vidReclycer);
        manager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(manager);
        recyclerView.setHasFixedSize(false);

         id = mparam1;
        //right here, id has the playlist id
        System.out.println("this is the playlist id------------------->"+id);
        String url = "https://www.googleapis.com/youtube/v3/playlistItems?key=AIzaSyBmISPZAjsrku2_yKLcTW4Y6qq6aqlht-0&playlistId="+id+"&part=snippet&maxResults=36";
        //even url has the value but the list is not shown and id changes to null
        System.out.println(url);
        RequestQueue queue = Volley.newRequestQueue(getContext());

        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        vids = new ArrayList<>();
                        try {
                            JSONObject mainObject = new JSONObject(response);
                            JSONArray itemArray = (JSONArray) mainObject.get("items");
                            for (int i = 0; i < itemArray.length(); i++) {
                                String title = itemArray.getJSONObject(i).getJSONObject("snippet").getString("title");
                                String url = itemArray.getJSONObject(i).getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("maxres").getString("url");
                                String vidid = itemArray.getJSONObject(i).getJSONObject("snippet").getJSONObject("resourceId").getString("videoId");
                                YoutubeVideoModel vid = new YoutubeVideoModel(title, url, vidid);
                                vids.add(vid);
                            }
                            adapter = new YoutubeAdapter(getContext(), vids);
                            recyclerView.setAdapter(adapter);
                            recyclerView.getAdapter().notifyDataSetChanged();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
//                Log.e("Error in request", error.getMessage());
            }
        });
        queue.add(request);
        }
    }
```this is the image of my logcat. It prints id and url as required, but then it changes to null

```

答:
Got the answer. there was a problem in sharing data between activity and fragment. the value was being set null twice, one before and one after the function call(i dont know why but). then instead of calling newInstance() i used bundle, checked if it is null or not in fragment class and then set the value of id.
CollgeGallery.java

```<code>            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
               //object of College class to get getImageurls() which has the list of urls
                College clg = dataSnapshot.getValue(College.class);
                String playid = getYoutubeVideoId(clg.getVideourls());
                //setting the list to imagegrid, passing url from this activity to imageview.
                imagegrid = new CollegeImageGrid(CollegeGallery.this,clg.getImageurls());
                //setting adapter to grid with the list of urls
                grid_image.setAdapter(imagegrid); //check error, getCount is null, crashes application.
                //extracting playlist id
//                String playid = getYoutubeVideoId(clg.getVideourls());
                //fragment code
                setPlayid(playid);
                Bundle bun = new Bundle();
                YoutubeVideoList firstfrag = new YoutubeVideoList();
                bun.putString("test", playid);
                firstfrag.setArguments(bun);
                getSupportFragmentManager().beginTransaction().add(R.id.youtube_frag, firstfrag).commit();
//                FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
//                tr.add(R.id.youtube_frag, YoutubeVideoList.newInstance(playid)).commit();
            }```
**YoutubeVideoList.java**

    ```@Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Bundle args = this.getArguments();
            if(args != null){
                id = args.getString("test");
            }
        }```

Thanks everyone for your help. :)

```

Body:
I am using fragment for the first time. I am trying to get List of videos from youtube present in my fragment. I am retrieving a youtube url from firebase and extract playlist id from it. This playlist id is passed as a parameter to fragment which would then list out all the videos present in the playist. i am successfully able to retrieve the playlist id in the fragment, but it changes to null in the url. Any help is appreciable.thanks in advance.
CollegeGallery.java

    public CollegeImageGrid imagegrid;
    private static final String TAG = "CollegeGallery";
    public GridView grid_image, grid_video;
    public DatabaseReference ref;
    private String collegeid;
    private TextView moreimages, morevideos;
    private String playlistid;

    public void setPlayid(String playlistid) {
        this.playlistid = playlistid;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_college_gallery);

        ref = FirebaseDatabase.getInstance().getReference("collegedata");
        //this will get the data from previous intent
        collegeid = getIntent().getStringExtra("gallery");
        grid_image = findViewById(R.id.grid_image);
//        grid_video = findViewById(R.id.grid_video); //for grid view of videos

        moreimages = findViewById(R.id.more_images);
        morevideos = findViewById(R.id.more_videos);

        //a list of string will  be passed to  imagegrid object
        ref.child(String.valueOf(collegeid)).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
               //object of College class to get getImageurls() which has the list of urls
                College clg = dataSnapshot.getValue(College.class);
                //setting the list to imagegrid, passing url from this activity to imageview.
                imagegrid = new CollegeImageGrid(CollegeGallery.this,clg.getImageurls());
                //setting adapter to grid with the list of urls
                grid_image.setAdapter(imagegrid); //check error, getCount is null, crashes application.
                //extracting playlist id
                String playid = getYoutubeVideoId(clg.getVideourls());
                //fragment code
                YoutubeVideoList yt = new YoutubeVideoList();
                FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
                tr.replace(R.id.youtube_frag, YoutubeVideoList.newInstance(playid)).commit();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(CollegeGallery.this, "No images", Toast.LENGTH_SHORT).show();
            }
        });

        moreimages.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent image_in = new Intent(CollegeGallery.this,AllCollegeImages.class);
                image_in.putExtra("image",collegeid);
                startActivity(image_in);
            }
        });

        //will take to activity with only playlist video list fragment
        morevideos.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(CollegeGallery.this, CompleteVideoList.class));
            }
        });

    }

    //function to extract playlist id
    public static String getYoutubeVideoId(String youtubeUrl) {
        String video_id = "";
        if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http")) {

            String expression = "^.*?(?:list)=(.*?)(?:&|$)";

            CharSequence input = youtubeUrl;
            Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(input);
            if (matcher.matches()) {
                String groupIndex1 = matcher.group(1);
                video_id = groupIndex1;
            }
        }
        return video_id;
    }

}

YoutubeVideoList.java(Fragment)

    private static String ARG_Param1;
    private static String id;
    List<YoutubeVideoModel> vids;
    Button btn;
    YoutubeAdapter adapter;
    RecyclerView recyclerView;
    RecyclerView.LayoutManager manager;
    String mparam1;

    public YoutubeVideoList() {
    }

    //retrieving playlist id from the previous activity
    public static YoutubeVideoList newInstance(String id) {
        YoutubeVideoList yt = new YoutubeVideoList();
        Bundle args = new Bundle();
        args.putString(ARG_Param1, id);
        yt.setArguments(args);
        return yt;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mparam1 = getArguments().getString(ARG_Param1);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_youtube_video_list, container, false);
    }

    @Override
    public  void onViewCreated(View container, Bundle savedInstanceState) {
        super.onViewCreated(container, savedInstanceState);
        recyclerView = container.findViewById(R.id.vidReclycer);
        manager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(manager);
        recyclerView.setHasFixedSize(false);

         id = mparam1;
        //right here, id has the playlist id
        System.out.println("this is the playlist id------------------->"+id);
        String url = "https://www.googleapis.com/youtube/v3/playlistItems?key=AIzaSyBmISPZAjsrku2_yKLcTW4Y6qq6aqlht-0&playlistId="+id+"&part=snippet&maxResults=36";
        //even url has the value but the list is not shown and id changes to null
        System.out.println(url);
        RequestQueue queue = Volley.newRequestQueue(getContext());

        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        vids = new ArrayList<>();
                        try {
                            JSONObject mainObject = new JSONObject(response);
                            JSONArray itemArray = (JSONArray) mainObject.get("items");
                            for (int i = 0; i < itemArray.length(); i++) {
                                String title = itemArray.getJSONObject(i).getJSONObject("snippet").getString("title");
                                String url = itemArray.getJSONObject(i).getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("maxres").getString("url");
                                String vidid = itemArray.getJSONObject(i).getJSONObject("snippet").getJSONObject("resourceId").getString("videoId");
                                YoutubeVideoModel vid = new YoutubeVideoModel(title, url, vidid);
                                vids.add(vid);
                            }
                            adapter = new YoutubeAdapter(getContext(), vids);
                            recyclerView.setAdapter(adapter);
                            recyclerView.getAdapter().notifyDataSetChanged();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
//                Log.e("Error in request", error.getMessage());
            }
        });
        queue.add(request);
        }
    }
```this is the image of my logcat. It prints id and url as required, but then it changes to null

Body:
Got the answer. there was a problem in sharing data between activity and fragment. the value was being set null twice, one before and one after the function call(i dont know why but). then instead of calling newInstance() i used bundle, checked if it is null or not in fragment class and then set the value of id.
CollgeGallery.java

            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
               //object of College class to get getImageurls() which has the list of urls
                College clg = dataSnapshot.getValue(College.class);
                String playid = getYoutubeVideoId(clg.getVideourls());
                //setting the list to imagegrid, passing url from this activity to imageview.
                imagegrid = new CollegeImageGrid(CollegeGallery.this,clg.getImageurls());
                //setting adapter to grid with the list of urls
                grid_image.setAdapter(imagegrid); //check error, getCount is null, crashes application.
                //extracting playlist id
//                String playid = getYoutubeVideoId(clg.getVideourls());
                //fragment code
                setPlayid(playid);
                Bundle bun = new Bundle();
                YoutubeVideoList firstfrag = new YoutubeVideoList();
                bun.putString("test", playid);
                firstfrag.setArguments(bun);
                getSupportFragmentManager().beginTransaction().add(R.id.youtube_frag, firstfrag).commit();
//                FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
//                tr.add(R.id.youtube_frag, YoutubeVideoList.newInstance(playid)).commit();
            }```
**YoutubeVideoList.java**

    ```@Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Bundle args = this.getArguments();
            if(args != null){
                id = args.getString("test");
            }
        }```

Thanks everyone for your help. :)