答:
Here more visual solution with numpy. Filter by boolean array:</p>

```<code>import numpy as np
x = np.array(range(0,500))
b = np.array(([True] * 50 + [False] * 50) * 5)
x[b]
</code>```

Title: Python slicing - Skips certain number of rows

Body: I currently have 500 rows of data. I want to use the first fifty rows, then skip 50 rows and so on. How do I go on about doing this?

Body:
Here more visual solution with numpy. Filter by boolean array:

import numpy as np
x = np.array(range(0,500))
b = np.array(([True] * 50 + [False] * 50) * 5)
x[b]


来源: stackexchange

问:
Python: TypeError __init__() takes exactly 5 arguments (4 given)
I just started to work with Python and came across a problem I have no explanation for. Hope you can help out.

```<code>def createGrid(x,y,N):
    nDictionary={}
    for i in range(N+1):
        node=Node(i,x/N*i,y/N*i)
        nDictionary[node.nlabel] = node

    return nDictionary

class Node(object):
    def __init__(self,nlabel,x,y,z):
        self.nlabel = nlabel
        self.coordinates = x,y,z
</code>```

Now

```<code>nDictionary={}
node=Node(0,0,0,0)
nDictionary[node.nlabel]=node
</code>```

works but calling the method

```<code>createGrid(10,10,10)
</code>```

leads to the following error

```<code>TypeError: __init__() takes exactly 5 arguments (4 given)
</code>```

I really don't know why.

答:
I guess the problem is with this line:

```<code>node=Node(i,x/N*i,y/N*i)
</code>```

I'd guess you would like to have 4 arguments here, not 3.

(The reason the error message is slightly confusing (saying you should have 5, 4 given) is because of special handling of the self parameter - see an external explanation)

ContentLicense: CC BY-SA 3.0

Body:
I just started to work with Python and came across a problem I have no explanation for. Hope you can help out.

def createGrid(x,y,N):
    nDictionary={}
    for i in range(N+1):
        node=Node(i,x/N*i,y/N*i)
        nDictionary[node.nlabel] = node

    return nDictionary

class Node(object):
    def __init__(self,nlabel,x,y,z):
        self.nlabel = nlabel
        self.coordinates = x,y,z

Now

nDictionary={}
node=Node(0,0,0,0)
nDictionary[node.nlabel]=node

works but calling the method

createGrid(10,10,10)

leads to the following error

TypeError: __init__() takes exactly 5 arguments (4 given)

I really don't know why.

Body:
I guess the problem is with this line:

node=Node(i,x/N*i,y/N*i)

I'd guess you would like to have 4 arguments here, not 3.

(The reason the error message is slightly confusing (saying you should have 5, 4 given) is because of special handling of the self parameter - see an external explanation)


问:
How to change border width of custom UIButton
So, I'm working on simple form for my app. I have two button that allow user to choose wether they want to input email or phone number. I make 2 button that looks like android style tab button. Like Below:

So I made custom class for my button. Here is the code:

```<code>@IBDesignable
class HC24Button: UIButton {

    @IBInspectable var tabButtonBorderWidth: CGFloat = 1.0

    @IBInspectable var borderWidth: CGFloat = 0{
        didSet{
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var borderColor: UIColor? {
        didSet{
            updateView()
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 0{
        didSet{
            layer.cornerRadius = cornerRadius
        }
    }

    @IBInspectable var tabsButton : Bool = false{
        didSet{
            updateView()
        }
    }

    func updateView(){
        let border = CALayer()
        let width = tabButtonBorderWidth
        border.borderColor = borderColor?.cgColor
        border.frame = CGRect(x: 0, y: frame.size.height - width, width:  frame.size.width + 20, height: frame.size.height)

        border.borderWidth = width

        layer.addSublayer(border)
        layer.masksToBounds = true
    }

}
</code>```

And here is the code on my view controller:

```<code>   @IBAction func PhoneTapped(_ sender: HC24Button) {
        sender.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        sender.tabButtonBorderWidth = 4.0
        sender.borderColor = HC24AppColors.Main
        EmailButton.tabButtonBorderWidth = 1.0
        EmailButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        EmailButton.borderColor = .lightGray
        UserPhoneEmailTextField.text = "62"
        UserPhoneEmailTextField.keyboardType = .numberPad
    }

    @IBAction func EmailTapped(_ sender: HC24Button) {
        sender.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        sender.tabButtonBorderWidth = 4.0
        sender.borderColor = HC24AppColors.Main
        PhoneButton.tabButtonBorderWidth = 1.0
        PhoneButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        PhoneButton.borderColor = .lightGray
        UserPhoneEmailTextField.text = ""
        UserPhoneEmailTextField.placeholder = "Alamat Email"
    }
</code>```

But this is the result I got:

I want only one button that have colored border, like a switch. How can I fix this issue?

答:
In updateView() you are adding a new border but never really removing the border for the deselected tab. Instead of creating the border every time, just create it once and then simply change its color to hide it.

Modified version would be:

@IBDesignable
class HC24Button: UIButton {

```<code>@IBInspectable var tabButtonBorderWidth: CGFloat = 1.0

@IBInspectable var borderWidth: CGFloat = 0{
    didSet{
        layer.borderWidth = borderWidth
    }
}

@IBInspectable var borderColor: UIColor? {
    didSet{
        updateView()
    }
}

@IBInspectable var cornerRadius: CGFloat = 0{
    didSet{
        layer.cornerRadius = cornerRadius
    }
}

@IBInspectable var tabsButton : Bool = false{
    didSet{
        updateView()
    }
}

var border: CALayer?

func updateView(){
    if let border = border {
        border.borderColor = borderColor?.cgColor
        border.borderWidth = tabButtonBorderWidth
        return
    }
    border = CALayer()
    border.borderColor = borderColor?.cgColor
    let width = tabButtonBorderWidth
    border.borderWidth = width
    border.frame = CGRect(x: 0, y: frame.size.height - width, width:  frame.size.width + 20, height: frame.size.height)
    layer.addSublayer(border)
    layer.masksToBounds = true
}
</code>```

}

Body:
So, I'm working on simple form for my app. I have two button that allow user to choose wether they want to input email or phone number. I make 2 button that looks like android style tab button. Like Below:

So I made custom class for my button. Here is the code:

@IBDesignable
class HC24Button: UIButton {

    @IBInspectable var tabButtonBorderWidth: CGFloat = 1.0

    @IBInspectable var borderWidth: CGFloat = 0{
        didSet{
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var borderColor: UIColor? {
        didSet{
            updateView()
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 0{
        didSet{
            layer.cornerRadius = cornerRadius
        }
    }

    @IBInspectable var tabsButton : Bool = false{
        didSet{
            updateView()
        }
    }

    func updateView(){
        let border = CALayer()
        let width = tabButtonBorderWidth
        border.borderColor = borderColor?.cgColor
        border.frame = CGRect(x: 0, y: frame.size.height - width, width:  frame.size.width + 20, height: frame.size.height)

        border.borderWidth = width

        layer.addSublayer(border)
        layer.masksToBounds = true
    }

}

And here is the code on my view controller:

   @IBAction func PhoneTapped(_ sender: HC24Button) {
        sender.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        sender.tabButtonBorderWidth = 4.0
        sender.borderColor = HC24AppColors.Main
        EmailButton.tabButtonBorderWidth = 1.0
        EmailButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        EmailButton.borderColor = .lightGray
        UserPhoneEmailTextField.text = "62"
        UserPhoneEmailTextField.keyboardType = .numberPad
    }

    @IBAction func EmailTapped(_ sender: HC24Button) {
        sender.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        sender.tabButtonBorderWidth = 4.0
        sender.borderColor = HC24AppColors.Main
        PhoneButton.tabButtonBorderWidth = 1.0
        PhoneButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        PhoneButton.borderColor = .lightGray
        UserPhoneEmailTextField.text = ""
        UserPhoneEmailTextField.placeholder = "Alamat Email"
    }

But this is the result I got:

I want only one button that have colored border, like a switch. How can I fix this issue?

Body:
In updateView() you are adding a new border but never really removing the border for the deselected tab. Instead of creating the border every time, just create it once and then simply change its color to hide it.

Modified version would be:

@IBDesignable
class HC24Button: UIButton {

@IBInspectable var tabButtonBorderWidth: CGFloat = 1.0

@IBInspectable var borderWidth: CGFloat = 0{
    didSet{
        layer.borderWidth = borderWidth
    }
}

@IBInspectable var borderColor: UIColor? {
    didSet{
        updateView()
    }
}

@IBInspectable var cornerRadius: CGFloat = 0{
    didSet{
        layer.cornerRadius = cornerRadius
    }
}

@IBInspectable var tabsButton : Bool = false{
    didSet{
        updateView()
    }
}

var border: CALayer?

func updateView(){
    if let border = border {
        border.borderColor = borderColor?.cgColor
        border.borderWidth = tabButtonBorderWidth
        return
    }
    border = CALayer()
    border.borderColor = borderColor?.cgColor
    let width = tabButtonBorderWidth
    border.borderWidth = width
    border.frame = CGRect(x: 0, y: frame.size.height - width, width:  frame.size.width + 20, height: frame.size.height)
    layer.addSublayer(border)
    layer.masksToBounds = true
}

}


问:
How to fetch JSON file in Angular 2
as I am new to the Angular, can anyone please give a simple solution on loading the JSON file data using angular 2.

My code is like below

Index.html

    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="css/styles.css">

    <my-app>Loading...</my-app>

```
</div>
</div>
</p>

<p>app.component.ts</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {Component} from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
          <div id="main">
            Main Div
               <div id = "header"></div>
               <div id = "content">
                  <ul class="games">
                      <li>

                      </li>
                  </ul>
               </div>
          </div>
     `
})
export class AppComponent {
 }</code>```

games.json

{
 "games":[
  {
   "title":"Primary Operations",
   "enabled":true
  },
  {
   "title":"Curated Games",
   "enabled":false
  }
 ]
}```

I want to fetch all games from games.json into li at app.component.ts
Please advise in detail.

答:
In Angular 5

you can just say

```<code>this.http.get<Example>('assets/example.json')
</code>```

This will give you Observable<Example>

ContentLicense: CC BY-SA 4.0

Title: How to fetch JSON file in Angular 2

Body:
as I am new to the Angular, can anyone please give a simple solution on loading the JSON file data using angular 2.

My code is like below

Index.html

    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="css/styles.css">

    <my-app>Loading...</my-app>

app.component.ts

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

@Component({
  selector: 'my-app',
  template: `

            Main Div

     `
})
export class AppComponent {
 }

games.json

{
 "games":[
  {
   "title":"Primary Operations",
   "enabled":true
  },
  {
   "title":"Curated Games",
   "enabled":false
  }
 ]
}

I want to fetch all games from games.json into li at app.component.ts
Please advise in detail.

Body:
In Angular 5

you can just say

this.http.get<Example>('assets/example.json')

This will give you Observable<Example>


问:
Deserialize JSON array in VB.NET / C#
I have a web service that gives me a json with this format:

In case of positive login: ["67", 1];

In the negative: ["fail", "Data entered for the user is incorrect."]

How to properly deserialize?

I have tried :

```<code>Dim ser As New JavaScriptSerializer()
Dim result = ser.Deserialize(Of LoginResult)(wsResult.ToString())

Public Class LoginResult
   Public Property idcliente As String
   Public Property idutente As String
End Class
</code>```

答:
You can use newtonsoft.JObject </p>

```<code>   Dim json as jObject = JObject.Parse(yourJson)
    If (json.SelectToken("fail") = null)
      \\do somting
    If (json.SelectToken("67") = null)
      \\do somting
</code>```

Title: Deserialize JSON array in VB.NET / C#

Body:
I have a web service that gives me a json with this format:

In case of positive login: ["67", 1];

In the negative: ["fail", "Data entered for the user is incorrect."]

How to properly deserialize?

I have tried :

Dim ser As New JavaScriptSerializer()
Dim result = ser.Deserialize(Of LoginResult)(wsResult.ToString())

Public Class LoginResult
   Public Property idcliente As String
   Public Property idutente As String
End Class

Body:
You can use newtonsoft.JObject

   Dim json as jObject = JObject.Parse(yourJson)
    If (json.SelectToken("fail") = null)
      \\do somting
    If (json.SelectToken("67") = null)
      \\do somting


问:
callback in recyclerview affect all cells
I have a button in every cell of a RecyclerView that launches a download network call. The cell displays differently according to whether it's downloading, downloaded or finished.

my simplified code :

```<code>@Override public void onBindViewHolder(final CatalogViewHolder holder, int position) {

    final DownloadStatusCallback statusCallback = new DownloadStatusCallback() {
        @Override public void started() {

            mainThreadHandler.post(new Runnable() {
                @Override public void run() {
                    holder.itemView.setBackground(//color1
                }
            });
        }

        @Override public void finished() {
            mainThreadHandler.post(new Runnable() {
                @Override public void run() {
                    holder.itemView.setBackground(//color 2
                }
            });
        }

        @Override public void error(Exception e) {
            mainThreadHandler.post(new Runnable() {
                @Override public void run() {
                    holder.itemView.setBackground(//color 3
                }
            });
        }
    };

    holder.button1.setOnClickListener(new View.OnClickListener() {
        @Override public void onClick(View view) {
            assyncCall(statusCallback);
        }
    });

}
</code>```

The first time i clic on a cell, everything works fine. If I clic on the download button of another cell, both of them will update.

I understand that's due to recyclerview recycling cells, but I can't figure out how to do better.

Thanks !

my full adapter :

```<code>public class CatalogRecyclerAdapter extends RecyclerView.Adapter<CatalogViewHolder> {

    public static final String TAG = "CatalogRecyclerAdapter";

    private final LayoutInflater inflater;
    private final DownloadCenter downloadCenter;
    private final ListInterface.FlowController flowController;
    private final ResourcesStringRepository resourcesStringRepository;
    private final ImageManagerFactory imageManagerFactory;
    private final Handler mainThreadHandler;

    public CatalogRecyclerAdapter(LayoutInflater inflater, ListInterface.FlowController flowController,
            DownloadCenter downloadCenter, ResourcesStringRepository resourcesStringRepository,
            ImageManagerFactory imageManagerFactory, Handler mainThreadHandler) {
        this.inflater = inflater;
        this.flowController = flowController;
        this.downloadCenter = downloadCenter;
        this.resourcesStringRepository = resourcesStringRepository;
        this.imageManagerFactory = imageManagerFactory;
        this.mainThreadHandler = mainThreadHandler;
    }

    private static final int TITLE = 0;
    private static final int USER = 2;
    private static final int PROGRAM = 3;
    private static final int COURSE = 4;
    private static final int GROUP = 5;
    private static final int MEDIA = 6;
    private static final int ERROR = 7;
    private static final int DEMO = 8;

    //The list of all elements
    private List<FilterableUser> users = new ArrayList<>();
    private List<CatalogProgram> programs = new ArrayList<>();
    private List<CatalogProgram> demos = new ArrayList<>();
    private List<CatalogCourse> courses = new ArrayList<>();
    private List<FilterableGroup> groups = new ArrayList<>();
    private List<CatalogMedia> medias = new ArrayList<>();

    //The list that will be displayed after filtering and research.
    List<Object> displayedList = new ArrayList<>();

    static final String TITLES[] = new String[10];

    static {
        Context ctx = M360Application.getContext();
        TITLES[USER] = ctx.getString(R.string.users);
        TITLES[PROGRAM] = ctx.getString(R.string.programs);
        TITLES[COURSE] = ctx.getString(R.string.courses);
        TITLES[GROUP] = ctx.getString(R.string.groups);
        TITLES[MEDIA] = ctx.getString(R.string.documents);
        TITLES[DEMO] = ctx.getString(R.string.programs_demo);
    }

    private String searchString;

    @Override public int getItemViewType(int position) {
        if (displayedList.get(position) instanceof String) {
            return TITLE;
        } else if (displayedList.get(position) instanceof FilterableUser) {
            return USER;
        } else if (displayedList.get(position) instanceof CatalogProgramDemo) {
            return DEMO;
        } else if (displayedList.get(position) instanceof CatalogProgram) {
            return PROGRAM;
        } else if (displayedList.get(position) instanceof CatalogCourse) {
            return COURSE;
        } else if (displayedList.get(position) instanceof FilterableGroup) {
            return GROUP;
        } else if (displayedList.get(position) instanceof CatalogMedia) {
            return MEDIA;
        } else if (displayedList.get(position) instanceof CatalogError) {
            return ERROR;
        } else {
            throw new ClassCastException(
                    "this adapter's displayedList is corrupted" + displayedList.get(position).toString());
        }
    }

    public void setData(List<Filterable> data, String searchedString) {
        searchString = searchedString;
        setData(data);
    }

    private void setData(List<Filterable> data) {

        LogDev.i(TAG, "setting data size: " + data.size());

        groups.clear();
        users.clear();
        programs.clear();
        demos.clear();
        courses.clear();
        medias.clear();

        for (Filterable element : data) {
            if (element instanceof CatalogCourse) {
                courses.add((CatalogCourse) element);
            } else if (element instanceof FilterableUser) {
                users.add((FilterableUser) element);
            } else if (element instanceof CatalogProgramDemo) {
                demos.add((CatalogProgramDemo) element);
            } else if (element instanceof CatalogProgram) {
                programs.add((CatalogProgram) element);
            } else if (element instanceof FilterableGroup) {
                groups.add((FilterableGroup) element);
            } else if (element instanceof CatalogMedia) {
                medias.add((CatalogMedia) element);
            }
        }

        constructDataSet();
    }

    private void constructDataSet() {
        displayedList.clear();

        if (!demos.isEmpty()) {
            displayedList.add(TITLES[DEMO]);
            displayedList.addAll(demos);
        }

        if (!programs.isEmpty()) {
            displayedList.add(TITLES[PROGRAM]);
            displayedList.addAll(programs);
        }

        if (!courses.isEmpty()) {
            displayedList.add(TITLES[COURSE]);
            displayedList.addAll(courses);
        }

        if (!users.isEmpty()) {
            displayedList.add(TITLES[USER]);
            displayedList.addAll(users);
        }

        if (!groups.isEmpty()) {
            displayedList.add(TITLES[GROUP]);
            displayedList.addAll(groups);
        }

        if (!medias.isEmpty()) {
            displayedList.add(TITLES[MEDIA]);
            displayedList.addAll(medias);
        }

        if (displayedList.isEmpty()) {
            displayedList.add(new CatalogError());
        }

        LogDev.w(TAG, "displayedList.size() : " + displayedList.size());

        notifyDataSetChanged();
    }

    @Override public CatalogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        switch (viewType) {
            case TITLE:
                return new TitleViewHolder(inflater.inflate(R.layout.item_list_title_catalog, parent, false));
            case USER:
                return new UserViewHolder(inflater.inflate(R.layout.widget_user_small, parent, false));
            case PROGRAM:
            case DEMO:
                return new ProgramViewHolder(inflater.inflate(R.layout.widget_program_small, parent, false));
            case COURSE:
                return new CourseViewHolder(inflater.inflate(R.layout.widget_course_small, parent, false));
            case GROUP:
                return new GroupViewHolder(inflater.inflate(R.layout.widget_group_small, parent, false));
            case MEDIA:
                return new MediaViewHolder(inflater.inflate(R.layout.widget_media_small, parent, false));
            case ERROR:
                return new CatalogErrorViewHolder(inflater.inflate(R.layout.widget_noresult_small, parent, false));
            default:
                LogDev.e(TAG, "view type not supported");
                return null;
        }
    }

    @Override public void onBindViewHolder(CatalogViewHolder holder, int position) {

        Object displayedObject = displayedList.get(position);
        //holder.bind(displayedObject, errorDisplayInterface);

        if (holder instanceof TitleViewHolder && displayedObject instanceof String) {

            ((TitleViewHolder) holder).tv.setText((String) displayedObject);
        } else if (holder instanceof ProgramViewHolder && displayedObject instanceof CatalogProgram) {

            bindProgramViewHolder((ProgramViewHolder) holder, (CatalogProgram) displayedObject);
        } else if (holder instanceof CourseViewHolder && displayedObject instanceof CatalogCourse) {

            bindCourseViewHolder((CourseViewHolder) holder, (CatalogCourse) displayedObject);
        } else if (holder instanceof GroupViewHolder && displayedObject instanceof FilterableGroup) {

            bindGroupViewHolder((GroupViewHolder) holder, (FilterableGroup) displayedObject);
        } else if (holder instanceof UserViewHolder && displayedObject instanceof FilterableUser) {

            bindUserViewHolder((UserViewHolder) holder, (FilterableUser) displayedObject);
        } else if (holder instanceof MediaViewHolder && displayedObject instanceof CatalogMedia) {

            bindMediaViewHolder((MediaViewHolder) holder, (CatalogMedia) displayedObject);
        } else if (holder instanceof CatalogErrorViewHolder) {
            //No binding with any data
        } else {
            throw new ClassCastException(displayedObject.toString());
        }

        //Highlight
        if (searchString != null && !searchString.isEmpty())

        {
            TextViewHighlighter.highlight(holder, searchString);
        }
    }

    private void bindCourseViewHolder(final CourseViewHolder courseViewHolder, final CatalogCourse course) {
        courseViewHolder.name_textView.setText(course.name);
        courseViewHolder.viewNb_textView.setText(course.views != null ? course.views.toString() : "0");

        if (course.elementCount == null) {
            courseViewHolder.counterLinear.setVisibility(View.GONE);
        } else {
            courseViewHolder.counterLinear.setVisibility(View.VISIBLE);
            courseViewHolder.questionNb_textView.setText(
                    course.elementCount.questions != null ? course.elementCount.questions.toString() : "0");
            courseViewHolder.mediaNb_textView.setText(
                    course.elementCount.medias != null ? course.elementCount.medias.toString() : "0");
            courseViewHolder.sheetNb_textView.setText(
                    course.elementCount.sheets != null ? course.elementCount.sheets.toString() : "0");
        }

        imageManagerFactory.course(course.id).thumbnail(courseViewHolder.pic_imageView);
        //new CourseImageManager(course.id).load(courseViewHolder.pic_imageView);

        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override public void onClick(View view) {
                flowController.routeToCourse(course.id);
            }
        };

        courseViewHolder.container.setOnClickListener(clickListener);

        if (course.canBeOffline) {

            courseViewHolder.downloadBlock.setVisibility(View.VISIBLE);

            DownloadState state = downloadCenter.getCourseStatus(course.id);

            LogDev.i(TAG, "can be offline " + state.name());

            if (state == DownloadState.DOWNLOADING) {
                updateDownloadBlock(courseViewHolder, DownloadableStatus.DOWNLOADING);
            }

            if (state == DownloadState.TO_DOWNLOAD) {
                updateDownloadBlock(courseViewHolder, DownloadableStatus.DOWNLOADABLE);
            }

            if (state == DownloadState.DOWNLOADED || state == DownloadState.DOWNLOADED_WITH_SHARED_MODE) {
                updateDownloadBlock(courseViewHolder, DownloadableStatus.DOWNLOADED);
            } else {

                DownloadStatusCallback statusCallback = new DownloadStatusCallback() {
                    @Override public void started() {

                        LogDev.i(TAG, "started");

                        mainThreadHandler.post(new Runnable() {
                            @Override public void run() {
                                updateDownloadBlock(courseViewHolder, DownloadableStatus.DOWNLOADING);
                            }
                        });
                    }

                    @Override public void finished() {
                        mainThreadHandler.post(new Runnable() {
                            @Override public void run() {
                                updateDownloadBlock(courseViewHolder, DownloadableStatus.DOWNLOADED);
                            }
                        });
                    }

                    @Override public void error(Exception e) {
                        mainThreadHandler.post(new Runnable() {
                            @Override public void run() {
                                updateDownloadBlock(courseViewHolder, DownloadableStatus.ERROR);
                            }
                        });
                    }
                };

                downloadCenter.subscribe(course.id, statusCallback);
                courseViewHolder.downloadBlock.setOnClickListener(new View.OnClickListener()

                {
                    @Override public void onClick(View v) {
                        new Thread() {
                            @Override public void run() {
                                super.run();
                                try {
                                    downloadCenter.downloadCourse(course.id, null);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }.start();
                    }
                });
            }
        } else {
            LogDev.i(TAG, "can't be offline");
            courseViewHolder.downloadBlock.setVisibility(View.INVISIBLE);
        }
    }

    private void updateDownloadBlock(CourseViewHolder courseViewHolder, DownloadableStatus status) {

        if (status == null) return;

        courseViewHolder.downloadBlock.setVisibility(
                status.equals(DownloadableStatus.NOT_DOWNLOADABLE) ? View.GONE : View.VISIBLE);
        courseViewHolder.downloadImage.setVisibility(
                status.equals(DownloadableStatus.DOWNLOADABLE) ? View.VISIBLE : View.GONE);
        courseViewHolder.downloadProgress.setVisibility(
                status.equals(DownloadableStatus.DOWNLOADING) ? View.VISIBLE : View.GONE);
        courseViewHolder.downloadedImage.setVisibility(
                status.equals(DownloadableStatus.DOWNLOADED) ? View.VISIBLE : View.GONE);
        courseViewHolder.downloadErrImage.setVisibility(
                status.equals(DownloadableStatus.ERROR) ? View.VISIBLE : View.GONE);
    }

    private enum DownloadableStatus {
        NOT_DOWNLOADABLE, DOWNLOADABLE, DOWNLOADING, DOWNLOADED, ERROR
    }

    private void bindProgramViewHolder(ProgramViewHolder programViewHolder, final CatalogProgram program) {

        imageManagerFactory.program(program.id).thumbnail(programViewHolder.pic_imageView);
        //new ProgramImageManager(program.id).load(programViewHolder.pic_imageView);
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override public void onClick(View view) {
                flowController.routeToProgram(program.id);
            }
        };

        programViewHolder.container.setOnClickListener(onClickListener);
        programViewHolder.pic_imageView.setOnClickListener(onClickListener);
        programViewHolder.title_textView.setText(program.name);
        programViewHolder.viewCount_textView.setText(program.views != null ? program.views.toString() : "0");
    }

    private void bindUserViewHolder(UserViewHolder userViewHolder, final FilterableUser user) {

        userViewHolder.name_textView.setText(user.name);
        userViewHolder.job_textView.setText(user.description);

        imageManagerFactory.user(user.id).thumbnail(userViewHolder.pic_imageView);
        //new UserImageManager(user.id).loadProfilePic(userViewHolder.pic_imageView, NetworkUtils.isNetworkAvailable(),
        //        true);

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override public void onClick(View view) {
                flowController.routeToUser(user.id);
            }
        };

        userViewHolder.pic_imageView.setOnClickListener(onClickListener);
        userViewHolder.container.setOnClickListener(onClickListener);
    }

    private void bindMediaViewHolder(MediaViewHolder mediaViewHolder, final CatalogMedia media) {

        imageManagerFactory.media(media.id, media.type, media.extention).symbolOnThumbnail(mediaViewHolder.complex);
        //new MediaImageManager(media).load(mediaViewHolder.pic_imageView, NetworkUtils.isNetworkAvailable(), false);
        mediaViewHolder.title_textView.setText(media.title);
        mediaViewHolder.authorName_textView.setText(media.authorName);

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override public void onClick(final View view) {
                flowController.routeToDocument(media.id);
            }
        };

        mediaViewHolder.complex.setOnClickListener(onClickListener);
        mediaViewHolder.container.setOnClickListener(onClickListener);
    }

    private void bindGroupViewHolder(GroupViewHolder groupViewHolder, final FilterableGroup group) {

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override public void onClick(View view) {
                flowController.routeToGrouop(group.id);
            }
        };

        groupViewHolder.pic_imageView.setOnClickListener(onClickListener);
        groupViewHolder.container.setOnClickListener(onClickListener);

        groupViewHolder.name_textView.setText(group.name);
        String str = resourcesStringRepository.getQuantityString(R.plurals.catalog_group_stat_program,
                group.nbProgramsRunning, group.nbProgramsRunning);
        str += " - " + resourcesStringRepository.getQuantityString(R.plurals.catalog_group_stat_user, group.nbUser,
                group.nbUser);
        groupViewHolder.stats_textView.setText(str);

        imageManagerFactory.group(group.id).thumbnail(groupViewHolder.pic_imageView);
        //new GroupImageManager(group.id).load(groupViewHolder.pic_imageView, NetworkUtils.isNetworkAvailable(), true);
    }

    @Override public int getItemCount() {
        return displayedList.size();
    }
}
</code>```

答:
Solution

As Surender and Trickcy Solution suggested, I updated the presented data and then tell the adapter to update the cell accordingly :

```<code>DownloadStatusCallback statusCallback = new DownloadStatusCallback() {
                    @Override public void started() {

                        LogDev.i(TAG, "started");

                        course.downloadState = DownloadState.DOWNLOADING;

                        final int position = courseViewHolder.getAdapterPosition();
                        mainThreadHandler.post(new Runnable() {
                            @Override public void run() {
                                notifyItemChanged(position);
                            }
                        });
                    }

                    @Override public void finished() {
                        course.downloadState = DownloadState.DOWNLOADED;

                        final int position = courseViewHolder.getAdapterPosition();
                        mainThreadHandler.post(new Runnable() {
                            @Override public void run() {
                                notifyItemChanged(position);
                            }
                        });
                    }

                    @Override public void error(Exception e) {
                        course.downloadState = DownloadState.ERROR_WHILE_DOWNLOADING;

                        final int position = courseViewHolder.getAdapterPosition();
                        mainThreadHandler.post(new Runnable() {
                            @Override public void run() {
                                notifyItemChanged(position);
                            }
                        });
                    }
                };
</code>```

Body:
I have a button in every cell of a RecyclerView that launches a download network call. The cell displays differently according to whether it's downloading, downloaded or finished.

my simplified code :

@Override public void onBindViewHolder(final CatalogViewHolder holder, int position) {

    final DownloadStatusCallback statusCallback = new DownloadStatusCallback() {
        @Override public void started() {

            mainThreadHandler.post(new Runnable() {
                @Override public void run() {
                    holder.itemView.setBackground(//color1
                }
            });
        }

        @Override public void finished() {
            mainThreadHandler.post(new Runnable() {
                @Override public void run() {
                    holder.itemView.setBackground(//color 2
                }
            });
        }

        @Override public void error(Exception e) {
            mainThreadHandler.post(new Runnable() {
                @Override public void run() {
                    holder.itemView.setBackground(//color 3
                }
            });
        }
    };

    holder.button1.setOnClickListener(new View.OnClickListener() {
        @Override public void onClick(View view) {
            assyncCall(statusCallback);
        }
    });

}

The first time i clic on a cell, everything works fine. If I clic on the download button of another cell, both of them will update.

I understand that's due to recyclerview recycling cells, but I can't figure out how to do better.

Thanks !

my full adapter :

public class CatalogRecyclerAdapter extends RecyclerView.Adapter<CatalogViewHolder> {

    public static final String TAG = "CatalogRecyclerAdapter";

    private final LayoutInflater inflater;
    private final DownloadCenter downloadCenter;
    private final ListInterface.FlowController flowController;
    private final ResourcesStringRepository resourcesStringRepository;
    private final ImageManagerFactory imageManagerFactory;
    private final Handler mainThreadHandler;

    public CatalogRecyclerAdapter(LayoutInflater inflater, ListInterface.FlowController flowController,
            DownloadCenter downloadCenter, ResourcesStringRepository resourcesStringRepository,
            ImageManagerFactory imageManagerFactory, Handler mainThreadHandler) {
        this.inflater = inflater;
        this.flowController = flowController;
        this.downloadCenter = downloadCenter;
        this.resourcesStringRepository = resourcesStringRepository;
        this.imageManagerFactory = imageManagerFactory;
        this.mainThreadHandler = mainThreadHandler;
    }

    private static final int TITLE = 0;
    private static final int USER = 2;
    private static final int PROGRAM = 3;
    private static final int COURSE = 4;
    private static final int GROUP = 5;
    private static final int MEDIA = 6;
    private static final int ERROR = 7;
    private static final int DEMO = 8;

    //The list of all elements
    private List<FilterableUser> users = new ArrayList<>();
    private List<CatalogProgram> programs = new ArrayList<>();
    private List<CatalogProgram> demos = new ArrayList<>();
    private List<CatalogCourse> courses = new ArrayList<>();
    private List<FilterableGroup> groups = new ArrayList<>();
    private List<CatalogMedia> medias = new ArrayList<>();

    //The list that will be displayed after filtering and research.
    List<Object> displayedList = new ArrayList<>();

    static final String TITLES[] = new String[10];

    static {
        Context ctx = M360Application.getContext();
        TITLES[USER] = ctx.getString(R.string.users);
        TITLES[PROGRAM] = ctx.getString(R.string.programs);
        TITLES[COURSE] = ctx.getString(R.string.courses);
        TITLES[GROUP] = ctx.getString(R.string.groups);
        TITLES[MEDIA] = ctx.getString(R.string.documents);
        TITLES[DEMO] = ctx.getString(R.string.programs_demo);
    }

    private String searchString;

    @Override public int getItemViewType(int position) {
        if (displayedList.get(position) instanceof String) {
            return TITLE;
        } else if (displayedList.get(position) instanceof FilterableUser) {
            return USER;
        } else if (displayedList.get(position) instanceof CatalogProgramDemo) {
            return DEMO;
        } else if (displayedList.get(position) instanceof CatalogProgram) {
            return PROGRAM;
        } else if (displayedList.get(position) instanceof CatalogCourse) {
            return COURSE;
        } else if (displayedList.get(position) instanceof FilterableGroup) {
            return GROUP;
        } else if (displayedList.get(position) instanceof CatalogMedia) {
            return MEDIA;
        } else if (displayedList.get(position) instanceof CatalogError) {
            return ERROR;
        } else {
            throw new ClassCastException(
                    "this adapter's displayedList is corrupted" + displayedList.get(position).toString());
        }
    }

    public void setData(List<Filterable> data, String searchedString) {
        searchString = searchedString;
        setData(data);
    }

    private void setData(List<Filterable> data) {

        LogDev.i(TAG, "setting data size: " + data.size());

        groups.clear();
        users.clear();
        programs.clear();
        demos.clear();
        courses.clear();
        medias.clear();

        for (Filterable element : data) {
            if (element instanceof CatalogCourse) {
                courses.add((CatalogCourse) element);
            } else if (element instanceof FilterableUser) {
                users.add((FilterableUser) element);
            } else if (element instanceof CatalogProgramDemo) {
                demos.add((CatalogProgramDemo) element);
            } else if (element instanceof CatalogProgram) {
                programs.add((CatalogProgram) element);
            } else if (element instanceof FilterableGroup) {
                groups.add((FilterableGroup) element);
            } else if (element instanceof CatalogMedia) {
                medias.add((CatalogMedia) element);
            }
        }

        constructDataSet();
    }

    private void constructDataSet() {
        displayedList.clear();

        if (!demos.isEmpty()) {
            displayedList.add(TITLES[DEMO]);
            displayedList.addAll(demos);
        }

        if (!programs.isEmpty()) {
            displayedList.add(TITLES[PROGRAM]);
            displayedList.addAll(programs);
        }

        if (!courses.isEmpty()) {
            displayedList.add(TITLES[COURSE]);
            displayedList.addAll(courses);
        }

        if (!users.isEmpty()) {
            displayedList.add(TITLES[USER]);
            displayedList.addAll(users);
        }

        if (!groups.isEmpty()) {
            displayedList.add(TITLES[GROUP]);
            displayedList.addAll(groups);
        }

        if (!medias.isEmpty()) {
            displayedList.add(TITLES[MEDIA]);
            displayedList.addAll(medias);
        }

        if (displayedList.isEmpty()) {
            displayedList.add(new CatalogError());
        }

        LogDev.w(TAG, "displayedList.size() : " + displayedList.size());

        notifyDataSetChanged();
    }

    @Override public CatalogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        switch (viewType) {
            case TITLE:
                return new TitleViewHolder(inflater.inflate(R.layout.item_list_title_catalog, parent, false));
            case USER:
                return new UserViewHolder(inflater.inflate(R.layout.widget_user_small, parent, false));
            case PROGRAM:
            case DEMO:
                return new ProgramViewHolder(inflater.inflate(R.layout.widget_program_small, parent, false));
            case COURSE:
                return new CourseViewHolder(inflater.inflate(R.layout.widget_course_small, parent, false));
            case GROUP:
                return new GroupViewHolder(inflater.inflate(R.layout.widget_group_small, parent, false));
            case MEDIA:
                return new MediaViewHolder(inflater.inflate(R.layout.widget_media_small, parent, false));
            case ERROR:
                return new CatalogErrorViewHolder(inflater.inflate(R.layout.widget_noresult_small, parent, false));
            default:
                LogDev.e(TAG, "view type not supported");
                return null;
        }
    }

    @Override public void onBindViewHolder(CatalogViewHolder holder, int position) {

        Object displayedObject = displayedList.get(position);
        //holder.bind(displayedObject, errorDisplayInterface);

        if (holder instanceof TitleViewHolder && displayedObject instanceof String) {

            ((TitleViewHolder) holder).tv.setText((String) displayedObject);
        } else if (holder instanceof ProgramViewHolder && displayedObject instanceof CatalogProgram) {

            bindProgramViewHolder((ProgramViewHolder) holder, (CatalogProgram) displayedObject);
        } else if (holder instanceof CourseViewHolder && displayedObject instanceof CatalogCourse) {

            bindCourseViewHolder((CourseViewHolder) holder, (CatalogCourse) displayedObject);
        } else if (holder instanceof GroupViewHolder && displayedObject instanceof FilterableGroup) {

            bindGroupViewHolder((GroupViewHolder) holder, (FilterableGroup) displayedObject);
        } else if (holder instanceof UserViewHolder && displayedObject instanceof FilterableUser) {

            bindUserViewHolder((UserViewHolder) holder, (FilterableUser) displayedObject);
        } else if (holder instanceof MediaViewHolder && displayedObject instanceof CatalogMedia) {

            bindMediaViewHolder((MediaViewHolder) holder, (CatalogMedia) displayedObject);
        } else if (holder instanceof CatalogErrorViewHolder) {
            //No binding with any data
        } else {
            throw new ClassCastException(displayedObject.toString());
        }

        //Highlight
        if (searchString != null && !searchString.isEmpty())

        {
            TextViewHighlighter.highlight(holder, searchString);
        }
    }

    private void bindCourseViewHolder(final CourseViewHolder courseViewHolder, final CatalogCourse course) {
        courseViewHolder.name_textView.setText(course.name);
        courseViewHolder.viewNb_textView.setText(course.views != null ? course.views.toString() : "0");

        if (course.elementCount == null) {
            courseViewHolder.counterLinear.setVisibility(View.GONE);
        } else {
            courseViewHolder.counterLinear.setVisibility(View.VISIBLE);
            courseViewHolder.questionNb_textView.setText(
                    course.elementCount.questions != null ? course.elementCount.questions.toString() : "0");
            courseViewHolder.mediaNb_textView.setText(
                    course.elementCount.medias != null ? course.elementCount.medias.toString() : "0");
            courseViewHolder.sheetNb_textView.setText(
                    course.elementCount.sheets != null ? course.elementCount.sheets.toString() : "0");
        }

        imageManagerFactory.course(course.id).thumbnail(courseViewHolder.pic_imageView);
        //new CourseImageManager(course.id).load(courseViewHolder.pic_imageView);

        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override public void onClick(View view) {
                flowController.routeToCourse(course.id);
            }
        };

        courseViewHolder.container.setOnClickListener(clickListener);

        if (course.canBeOffline) {

            courseViewHolder.downloadBlock.setVisibility(View.VISIBLE);

            DownloadState state = downloadCenter.getCourseStatus(course.id);

            LogDev.i(TAG, "can be offline " + state.name());

            if (state == DownloadState.DOWNLOADING) {
                updateDownloadBlock(courseViewHolder, DownloadableStatus.DOWNLOADING);
            }

            if (state == DownloadState.TO_DOWNLOAD) {
                updateDownloadBlock(courseViewHolder, DownloadableStatus.DOWNLOADABLE);
            }

            if (state == DownloadState.DOWNLOADED || state == DownloadState.DOWNLOADED_WITH_SHARED_MODE) {
                updateDownloadBlock(courseViewHolder, DownloadableStatus.DOWNLOADED);
            } else {

                DownloadStatusCallback statusCallback = new DownloadStatusCallback() {
                    @Override public void started() {

                        LogDev.i(TAG, "started");

                        mainThreadHandler.post(new Runnable() {
                            @Override public void run() {
                                updateDownloadBlock(courseViewHolder, DownloadableStatus.DOWNLOADING);
                            }
                        });
                    }

                    @Override public void finished() {
                        mainThreadHandler.post(new Runnable() {
                            @Override public void run() {
                                updateDownloadBlock(courseViewHolder, DownloadableStatus.DOWNLOADED);
                            }
                        });
                    }

                    @Override public void error(Exception e) {
                        mainThreadHandler.post(new Runnable() {
                            @Override public void run() {
                                updateDownloadBlock(courseViewHolder, DownloadableStatus.ERROR);
                            }
                        });
                    }
                };

                downloadCenter.subscribe(course.id, statusCallback);
                courseViewHolder.downloadBlock.setOnClickListener(new View.OnClickListener()

                {
                    @Override public void onClick(View v) {
                        new Thread() {
                            @Override public void run() {
                                super.run();
                                try {
                                    downloadCenter.downloadCourse(course.id, null);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }.start();
                    }
                });
            }
        } else {
            LogDev.i(TAG, "can't be offline");
            courseViewHolder.downloadBlock.setVisibility(View.INVISIBLE);
        }
    }

    private void updateDownloadBlock(CourseViewHolder courseViewHolder, DownloadableStatus status) {

        if (status == null) return;

        courseViewHolder.downloadBlock.setVisibility(
                status.equals(DownloadableStatus.NOT_DOWNLOADABLE) ? View.GONE : View.VISIBLE);
        courseViewHolder.downloadImage.setVisibility(
                status.equals(DownloadableStatus.DOWNLOADABLE) ? View.VISIBLE : View.GONE);
        courseViewHolder.downloadProgress.setVisibility(
                status.equals(DownloadableStatus.DOWNLOADING) ? View.VISIBLE : View.GONE);
        courseViewHolder.downloadedImage.setVisibility(
                status.equals(DownloadableStatus.DOWNLOADED) ? View.VISIBLE : View.GONE);
        courseViewHolder.downloadErrImage.setVisibility(
                status.equals(DownloadableStatus.ERROR) ? View.VISIBLE : View.GONE);
    }

    private enum DownloadableStatus {
        NOT_DOWNLOADABLE, DOWNLOADABLE, DOWNLOADING, DOWNLOADED, ERROR
    }

    private void bindProgramViewHolder(ProgramViewHolder programViewHolder, final CatalogProgram program) {

        imageManagerFactory.program(program.id).thumbnail(programViewHolder.pic_imageView);
        //new ProgramImageManager(program.id).load(programViewHolder.pic_imageView);
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override public void onClick(View view) {
                flowController.routeToProgram(program.id);
            }
        };

        programViewHolder.container.setOnClickListener(onClickListener);
        programViewHolder.pic_imageView.setOnClickListener(onClickListener);
        programViewHolder.title_textView.setText(program.name);
        programViewHolder.viewCount_textView.setText(program.views != null ? program.views.toString() : "0");
    }

    private void bindUserViewHolder(UserViewHolder userViewHolder, final FilterableUser user) {

        userViewHolder.name_textView.setText(user.name);
        userViewHolder.job_textView.setText(user.description);

        imageManagerFactory.user(user.id).thumbnail(userViewHolder.pic_imageView);
        //new UserImageManager(user.id).loadProfilePic(userViewHolder.pic_imageView, NetworkUtils.isNetworkAvailable(),
        //        true);

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override public void onClick(View view) {
                flowController.routeToUser(user.id);
            }
        };

        userViewHolder.pic_imageView.setOnClickListener(onClickListener);
        userViewHolder.container.setOnClickListener(onClickListener);
    }

    private void bindMediaViewHolder(MediaViewHolder mediaViewHolder, final CatalogMedia media) {

        imageManagerFactory.media(media.id, media.type, media.extention).symbolOnThumbnail(mediaViewHolder.complex);
        //new MediaImageManager(media).load(mediaViewHolder.pic_imageView, NetworkUtils.isNetworkAvailable(), false);
        mediaViewHolder.title_textView.setText(media.title);
        mediaViewHolder.authorName_textView.setText(media.authorName);

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override public void onClick(final View view) {
                flowController.routeToDocument(media.id);
            }
        };

        mediaViewHolder.complex.setOnClickListener(onClickListener);
        mediaViewHolder.container.setOnClickListener(onClickListener);
    }

    private void bindGroupViewHolder(GroupViewHolder groupViewHolder, final FilterableGroup group) {

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override public void onClick(View view) {
                flowController.routeToGrouop(group.id);
            }
        };

        groupViewHolder.pic_imageView.setOnClickListener(onClickListener);
        groupViewHolder.container.setOnClickListener(onClickListener);

        groupViewHolder.name_textView.setText(group.name);
        String str = resourcesStringRepository.getQuantityString(R.plurals.catalog_group_stat_program,
                group.nbProgramsRunning, group.nbProgramsRunning);
        str += " - " + resourcesStringRepository.getQuantityString(R.plurals.catalog_group_stat_user, group.nbUser,
                group.nbUser);
        groupViewHolder.stats_textView.setText(str);

        imageManagerFactory.group(group.id).thumbnail(groupViewHolder.pic_imageView);
        //new GroupImageManager(group.id).load(groupViewHolder.pic_imageView, NetworkUtils.isNetworkAvailable(), true);
    }

    @Override public int getItemCount() {
        return displayedList.size();
    }
}

Body:
Solution

As Surender and Trickcy Solution suggested, I updated the presented data and then tell the adapter to update the cell accordingly :

DownloadStatusCallback statusCallback = new DownloadStatusCallback() {
                    @Override public void started() {

                        LogDev.i(TAG, "started");

                        course.downloadState = DownloadState.DOWNLOADING;

                        final int position = courseViewHolder.getAdapterPosition();
                        mainThreadHandler.post(new Runnable() {
                            @Override public void run() {
                                notifyItemChanged(position);
                            }
                        });
                    }

                    @Override public void finished() {
                        course.downloadState = DownloadState.DOWNLOADED;

                        final int position = courseViewHolder.getAdapterPosition();
                        mainThreadHandler.post(new Runnable() {
                            @Override public void run() {
                                notifyItemChanged(position);
                            }
                        });
                    }

                    @Override public void error(Exception e) {
                        course.downloadState = DownloadState.ERROR_WHILE_DOWNLOADING;

                        final int position = courseViewHolder.getAdapterPosition();
                        mainThreadHandler.post(new Runnable() {
                            @Override public void run() {
                                notifyItemChanged(position);
                            }
                        });
                    }
                };


问:
PHP undefined index database issues
I am having issues with displaying the database table. My database table (activities) have the following value, ID (Primary Key), type, title, description and picture. I am trying to retrieve and display title,description and picture in a table format but is facing an  error

"Notice: Undefined index: title, Notice: Undefined index: description
  and Notice: Undefined index: picture"

which I am unable to solve it.
Below are my php code:

```<code>      <div class="col-md-4 col-md-offset-1">
           <div id="content">
               <table><?php
                $servername = "localhost";
                $username = "root";
                $password = "";
                $dbname = "sentosa_resort";

                $conn = new mysqli($servername, $username, $password,
               $dbname);
               // Check connection
               if ($conn->connect_error) {
                   die("Connection failed: " . $conn->connect_error);
               }

                $query = "SELECT title,description,picture FROM activites";
                $result = $conn->query($sql);;

                 // start a table tag in the HTML

                while($row=mysqli_fetch_array($result)){
                    $title = $row['title'];
                    $description = $row['description'];
                   $picture = $row['picture'];
                    echo "<tr>";
                    echo "<td>" . $title . "</td>";
                    echo "<td>" . $description . "</td>";
                     echo "<td>" . $picture . "</td>";
                    echo "</tr>";
                }
                ?></table>
                </div>
          </div>
</code>```

答:
You are getting those Notices because you are using mysqli_fetch_array(), instead you need to use mysqli_fetch_assoc().

If you want to continue using mysqli_fetch_array() then change the code to:

```<code>$title = $row[0];
$description = $row[1];
$picture = $row[2];
</code>```

Title: PHP undefined index database issues

Body:
I am having issues with displaying the database table. My database table (activities) have the following value, ID (Primary Key), type, title, description and picture. I am trying to retrieve and display title,description and picture in a table format but is facing an  error

"Notice: Undefined index: title, Notice: Undefined index: description
  and Notice: Undefined index: picture"

which I am unable to solve it.
Below are my php code:

<?php
                $servername = "localhost";
                $username = "root";
                $password = "";
                $dbname = "sentosa_resort";

                $conn = new mysqli($servername, $username, $password,
               $dbname);
               // Check connection
               if ($conn->connect_error) {
                   die("Connection failed: " . $conn->connect_error);
               }

                $query = "SELECT title,description,picture FROM activites";
                $result = $conn->query($sql);;

                 // start a table tag in the HTML

                while($row=mysqli_fetch_array($result)){
                    $title = $row['title'];
                    $description = $row['description'];
                   $picture = $row['picture'];
                    echo "
";
                    echo "" . $title . "	";
                    echo "" . $description . "	";
                     echo "" . $picture . "	";
                    echo "
";
                }
                ?>

Body:
You are getting those Notices because you are using mysqli_fetch_array(), instead you need to use mysqli_fetch_assoc().

If you want to continue using mysqli_fetch_array() then change the code to:

$title = $row[0];
$description = $row[1];
$picture = $row[2];


问:
How to create this entity named query
I have a notification service.Notification show to users depends on their permission.Notification is implemeted by the help of three tables they are Notification,Notification type(its Define notification type and its belogs to which permission users is defined), and permission table(id,and permission name)
Notification and notification type tables are added below.

notification

```<code>public class Notifications  {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String title;
private String deatils;
private String link;
@OneToOne(fetch=FetchType.EAGER)
@PrimaryKeyJoinColumn(name="NotificationTypeId",referencedColumnName="Id")
private NotificationTypes notificationTypes;
private Boolean tenantSpecific;
private Boolean userSpecific;
private Long recieverUserId;
private Boolean activeFlag;
private Long tenantId;
@Temporal(TemporalType.TIMESTAMP)
private Date insertedDttm;
private Long insertedBy;
@Temporal(TemporalType.TIMESTAMP)
private Date updatedDttm;
private Long updatedBy;
}
</code>```

NotifiactionType Entity

```<code>public class NotificationTypes implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

private String typeName;
@Temporal(TemporalType.TIMESTAMP)
private Date insertedDttm;
private Long insertedBy;
@Temporal(TemporalType.TIMESTAMP)
private Date updatedDttm;
private Long updatedBy;

@OneToMany(fetch = FetchType.EAGER)
private List<RLPermissions> permissions;

}
</code>```

in above two enties i want find list of notification by specific permissions
such that
Select nt from notification nt where nt.notificationType.permission in(permissionList)
How can i solve this in named queries.

答:
Try to get to the id of Permission using joins and then pass in the list of ids:

```<code>Select nt
from notification n
   inner join n.notificationType nt
   inner join nt.permissions p
where p.id in :permissionIds
</code>```

in the transactional method:

```<code>session.createNamedQuery("query", Notifications.class)
            .setParameterList("permissionIds", permissionIds)
            .list();
</code>```

Title: How to create this entity named query

Body:
I have a notification service.Notification show to users depends on their permission.Notification is implemeted by the help of three tables they are Notification,Notification type(its Define notification type and its belogs to which permission users is defined), and permission table(id,and permission name)
Notification and notification type tables are added below.

notification

public class Notifications  {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String title;
private String deatils;
private String link;
@OneToOne(fetch=FetchType.EAGER)
@PrimaryKeyJoinColumn(name="NotificationTypeId",referencedColumnName="Id")
private NotificationTypes notificationTypes;
private Boolean tenantSpecific;
private Boolean userSpecific;
private Long recieverUserId;
private Boolean activeFlag;
private Long tenantId;
@Temporal(TemporalType.TIMESTAMP)
private Date insertedDttm;
private Long insertedBy;
@Temporal(TemporalType.TIMESTAMP)
private Date updatedDttm;
private Long updatedBy;
}

NotifiactionType Entity

public class NotificationTypes implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

private String typeName;
@Temporal(TemporalType.TIMESTAMP)
private Date insertedDttm;
private Long insertedBy;
@Temporal(TemporalType.TIMESTAMP)
private Date updatedDttm;
private Long updatedBy;

@OneToMany(fetch = FetchType.EAGER)
private List<RLPermissions> permissions;

}

in above two enties i want find list of notification by specific permissions
such that
Select nt from notification nt where nt.notificationType.permission in(permissionList)
How can i solve this in named queries.

Body:
Try to get to the id of Permission using joins and then pass in the list of ids:

Select nt
from notification n
   inner join n.notificationType nt
   inner join nt.permissions p
where p.id in :permissionIds

in the transactional method:

session.createNamedQuery("query", Notifications.class)
            .setParameterList("permissionIds", permissionIds)
            .list();


问:
What is the typecast of an element created with componentsSeparatedByString?
I need to extract some info from a number of strings in infoArray. The layout for each element in infoArray looks like @"NO,YES,YES,YES,YES,NO,NO,YES", etc.

When I use the following:

```<code>[splitArray setArray:[[infoArray objectAtIndex: i] componentsSeparatedByString:@","]];
</code>```

I can access whatever I need in the new splitArray with something like:

```<code>NSLog(@"Result = %@", [infoArray objectAtIndex: 0]);
</code>```

and in this case it will print out correctly. The problem is when I need to use it next for conditions:

```<code>if([infoArray objectAtIndex: 0] == @"YES"){
    //do something
}
</code>```

The above code obviously doesn't work even if the value was "YES".  I believe the typecast is wrong.  I'm a bit of a newbie.  Any suggestions?

答:
Sorry about that I made an error in my notes:

```<code>NSLog(@"Result = %@", [infoArray objectAtIndex: 0]);
</code>```

should be

```<code>NSLog(@"Result = %@", [splitArray objectAtIndex: 0]);
</code>```

and

```<code>if([infoArray objectAtIndex: 0] == @"YES"){
</code>```

should be

```<code>if([splitArray objectAtIndex: 0] == @"YES"){
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I need to extract some info from a number of strings in infoArray. The layout for each element in infoArray looks like @"NO,YES,YES,YES,YES,NO,NO,YES", etc.

When I use the following:

[splitArray setArray:[[infoArray objectAtIndex: i] componentsSeparatedByString:@","]];

I can access whatever I need in the new splitArray with something like:

NSLog(@"Result = %@", [infoArray objectAtIndex: 0]);

and in this case it will print out correctly. The problem is when I need to use it next for conditions:

if([infoArray objectAtIndex: 0] == @"YES"){
    //do something
}

The above code obviously doesn't work even if the value was "YES".  I believe the typecast is wrong.  I'm a bit of a newbie.  Any suggestions?

Body:
Sorry about that I made an error in my notes:

NSLog(@"Result = %@", [infoArray objectAtIndex: 0]);

should be

NSLog(@"Result = %@", [splitArray objectAtIndex: 0]);

and

if([infoArray objectAtIndex: 0] == @"YES"){

should be

if([splitArray objectAtIndex: 0] == @"YES"){


问:
Error while trying to bind Azure Function to CosmosDB
I want to connect my Azure Function with my CosmosDB collection using DocumentDB output binding.

My Function:

public static class HttpTriggerSave
{
    [FunctionName("HttpTriggerSave")]
    public static void Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, [DocumentDB("dbName", "collectionName", Id = "id")] dynamic outputDoc, TraceWriter log)
    {
        outputDoc = new
        {
            Text = "text",
            id = Guid.NewGuid()
        };
    }
}
```

<p>My local.settings.json</p>

```{
"IsEncrypted": false,
"Values": {
    "AzureWebJobsStorage": "",
    "AzureWebJobsDashboard": "",
    "AzureWebJobsServiceBus": "Endpoint=sb://<namespace>/;SharedAccessKeyName=<keyname>;SharedAccessKey=<key>",
    "AzureWebJobsDocumentDBConnectionString": "mongodb://..."
  }
}
```

<p>However I get every time the same error:</p>

```mscorlib: Exception while executing function: HttpTriggerSave. Microsoft.Azure.WebJobs.Host: Exception binding parameter 'outputDoc'. Microsoft.Azure.Documents.Client: Value cannot be null.
Parameter name: authKeyOrResourceToken.
```

How can I fix that?

答:
mscorlib: Exception while executing function: HttpTriggerSave. Microsoft.Azure.WebJobs.Host: Exception binding parameter 'outputDoc'. Microsoft.Azure.Documents.Client: Value cannot be null.
  Parameter name: authKeyOrResourceToken.

According to the exception, it indicates that it has no access to Documentdb. According to your local.settings.json that you use the MongoDb connection string.

So please use the documentdb connection string.

```<code>AccountEndpoint=https://{documentDbName}.documents.azure.com:443/;AccountKey=xxxxx;
</code>```

And I also do a demo on my side, it works correctly.

```<code> [FunctionName("HttpTriggerSave")]
 public static void Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req,[DocumentDB("tomdb", "collectionId")] out dynamic outputDoc, TraceWriter log)
 {
    outputDoc = new
    {
          Text = "text",
          Id= Guid.NewGuid()
    };
  }
</code>```

Body:
I want to connect my Azure Function with my CosmosDB collection using DocumentDB output binding.

My Function:

public static class HttpTriggerSave
{
    [FunctionName("HttpTriggerSave")]
    public static void Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, [DocumentDB("dbName", "collectionName", Id = "id")] dynamic outputDoc, TraceWriter log)
    {
        outputDoc = new
        {
            Text = "text",
            id = Guid.NewGuid()
        };
    }
}

My local.settings.json

{
"IsEncrypted": false,
"Values": {
    "AzureWebJobsStorage": "",
    "AzureWebJobsDashboard": "",
    "AzureWebJobsServiceBus": "Endpoint=sb://<namespace>/;SharedAccessKeyName=<keyname>;SharedAccessKey=<key>",
    "AzureWebJobsDocumentDBConnectionString": "mongodb://..."
  }
}

However I get every time the same error:

mscorlib: Exception while executing function: HttpTriggerSave. Microsoft.Azure.WebJobs.Host: Exception binding parameter 'outputDoc'. Microsoft.Azure.Documents.Client: Value cannot be null.
Parameter name: authKeyOrResourceToken.

How can I fix that?

Body:
mscorlib: Exception while executing function: HttpTriggerSave. Microsoft.Azure.WebJobs.Host: Exception binding parameter 'outputDoc'. Microsoft.Azure.Documents.Client: Value cannot be null.
  Parameter name: authKeyOrResourceToken.

According to the exception, it indicates that it has no access to Documentdb. According to your local.settings.json that you use the MongoDb connection string.

So please use the documentdb connection string.

AccountEndpoint=https://{documentDbName}.documents.azure.com:443/;AccountKey=xxxxx;

And I also do a demo on my side, it works correctly.

 [FunctionName("HttpTriggerSave")]
 public static void Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req,[DocumentDB("tomdb", "collectionId")] out dynamic outputDoc, TraceWriter log)
 {
    outputDoc = new
    {
          Text = "text",
          Id= Guid.NewGuid()
    };
  }


问:
How to sort a list of objects by date when date is String?
I have the following Java POJO, Start date is a string:

POJO Object:

```<code>public class Schedule {

    private String id;

    private String startDate = "";

    //const and getters and setters
}
</code>```

I want to sort a list of these objects by the start date field:

Adding POJOS to list:

```<code>List<Schedule> schedules = new ArrayList<Schedule>();

Schedule s1 = new Schedule();
s1.setStartDate("2018-09-01T15:00:00+0000");

Schedule s2 = new Schedule();
s2.setStartDate("2018-09-15T15:00:00+0000");

schedules.add(s1);
schedules.add(s2);
</code>```

I have tried writing a comparator but it does not seem to work, is there a way of sorting strings by date (earliest first)?

Edit: I am currently using Java 7

答:
Try java 8 Comparator maybe ?

```<code>DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
schedules.sort(Comparator.comparing(s -> dateTimeFormatter.parse(s.getStartDate(), ZonedDateTime::from)));
</code>```

Java 8 ZonedDateTime requires a colon in the offset, +00:00. Code should work in Java 9!

Java 8 workaround, either use an explicit formatter or insert the colon yourself. – Ole V.V.

```<code>List<Schedule> schedules = new ArrayList<>();

Schedule s1 = new Schedule();
s1.setStartDate("2018-09-01T15:00:00+00:00"); //add a colon in the offset

Schedule s2 = new Schedule();
s2.setStartDate("2018-09-15T15:00:00+00:00"); //add a colon in the offset

schedules.add(s1);
schedules.add(s2);

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
schedules.sort(Comparator.comparing(s -> dateTimeFormatter.parse(s.getStartDate(), ZonedDateTime::from)));
</code>```

Or you would need to create a formatter on your own and use it in the lambda above.

```<code>//final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("your format");
</code>```

Body:
I have the following Java POJO, Start date is a string:

POJO Object:

public class Schedule {

    private String id;

    private String startDate = "";

    //const and getters and setters
}

I want to sort a list of these objects by the start date field:

Adding POJOS to list:

List<Schedule> schedules = new ArrayList<Schedule>();

Schedule s1 = new Schedule();
s1.setStartDate("2018-09-01T15:00:00+0000");

Schedule s2 = new Schedule();
s2.setStartDate("2018-09-15T15:00:00+0000");

schedules.add(s1);
schedules.add(s2);

I have tried writing a comparator but it does not seem to work, is there a way of sorting strings by date (earliest first)?

Edit: I am currently using Java 7

Body:
Try java 8 Comparator maybe ?

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
schedules.sort(Comparator.comparing(s -> dateTimeFormatter.parse(s.getStartDate(), ZonedDateTime::from)));

Java 8 ZonedDateTime requires a colon in the offset, +00:00. Code should work in Java 9!

Java 8 workaround, either use an explicit formatter or insert the colon yourself. – Ole V.V.

List<Schedule> schedules = new ArrayList<>();

Schedule s1 = new Schedule();
s1.setStartDate("2018-09-01T15:00:00+00:00"); //add a colon in the offset

Schedule s2 = new Schedule();
s2.setStartDate("2018-09-15T15:00:00+00:00"); //add a colon in the offset

schedules.add(s1);
schedules.add(s2);

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
schedules.sort(Comparator.comparing(s -> dateTimeFormatter.parse(s.getStartDate(), ZonedDateTime::from)));

Or you would need to create a formatter on your own and use it in the lambda above.

//final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("your format");


问:
Iterate array and make service call and store the response in array
WordId is an array. I want to iterate an array and make service call and store the response in responses array.

```<code>var wordId = [];
var responses = [];

for (var i = 0; i < result.words.length; i++) {
if (result.words[i].exampleSentences == undefined) {
wordId.push(result.words[i].identifier);
}
}

self.getWordExample(0, wordId, responses, function(responses) {
                console.log(responses);
            });
            console.log("outside",responses);
</code>```

My service file

```<code>getWordExample: function(i, wordId, responses,callback) {
    var self = this;
    services.WordExampleService.getWordExamples(wordId[i], function(err, response) {
        responses.push(response);
        i++;
        if (wordId[i]) {
            console.log("wordid",wordId[i]);
            self.getWordExample(i, wordId, responses);
        }
        else if(callback){
            console.log(responses);
            callback(responses);
        }
    });
}
</code>```

This is the console.Why the service is executing first and wordid is executing next
Is there any way to execute the function first and then return the responses

答:
Call it in a recursive async way:

```<code>function callService(wordIdIndex, callback) {
    services.WordExampleService.getWordExamples(wordId[wordIdIndex], function(err, response) {
        responses.push(response);

        wordIdIndex++;
        if (wordId[wordIdIndex]) {
            callService(wordIdIndex);
        }
        else if (callback) {
            callback(responses);
        }
    });
}

 callService(0, function(responses) {
     console.log(responses);
 });
</code>```

Use this code instead of the second for statement.

Remember, as your requests are async, everything which relies on responses should be executed inside that callback for now on.

Body:
WordId is an array. I want to iterate an array and make service call and store the response in responses array.

var wordId = [];
var responses = [];

for (var i = 0; i < result.words.length; i++) {
if (result.words[i].exampleSentences == undefined) {
wordId.push(result.words[i].identifier);
}
}

self.getWordExample(0, wordId, responses, function(responses) {
                console.log(responses);
            });
            console.log("outside",responses);

My service file

getWordExample: function(i, wordId, responses,callback) {
    var self = this;
    services.WordExampleService.getWordExamples(wordId[i], function(err, response) {
        responses.push(response);
        i++;
        if (wordId[i]) {
            console.log("wordid",wordId[i]);
            self.getWordExample(i, wordId, responses);
        }
        else if(callback){
            console.log(responses);
            callback(responses);
        }
    });
}

This is the console.Why the service is executing first and wordid is executing next
Is there any way to execute the function first and then return the responses

Body:
Call it in a recursive async way:

function callService(wordIdIndex, callback) {
    services.WordExampleService.getWordExamples(wordId[wordIdIndex], function(err, response) {
        responses.push(response);

        wordIdIndex++;
        if (wordId[wordIdIndex]) {
            callService(wordIdIndex);
        }
        else if (callback) {
            callback(responses);
        }
    });
}

 callService(0, function(responses) {
     console.log(responses);
 });

Use this code instead of the second for statement.

Remember, as your requests are async, everything which relies on responses should be executed inside that callback for now on.


问:
How to create a single color image using ImageView in android programmatically?
Is there any way to create an image using ImageView containing a solid single color programmatically?</p>

答:
Try this...

Initialize a new Bitmap object

```<code>Bitmap bitmap = Bitmap.createBitmap(
                        500, // Width
                        300, // Height
                        Bitmap.Config.ARGB_8888 // Config
                );
</code>```

Initialize a new Canvas instance

```<code>Canvas canvas = new Canvas(bitmap);
</code>```

Draw a solid color to the canvas background

```<code>canvas.drawColor(Color.LTGRAY);
</code>```

Initialize a new Paint instance to draw the Circle

```<code>Paint paint = new Paint();
                paint.setStyle(Paint.Style.FILL);
                paint.setColor(Color.RED);
                paint.setAntiAlias(true);
</code>```

Calculate the available radius of canvas

```<code>int radius = Math.min(canvas.getWidth(),canvas.getHeight()/2);
</code>```

Set a pixels value to padding around the circle

```<code>int padding = 5;
</code>```

Finally, draw the circle on the canvas

```<code>canvas.drawCircle(
                        canvas.getWidth() / 2, // cx
                        canvas.getHeight() / 2, // cy
                        radius - padding, // Radius
                        paint // Paint
                );
</code>```

Display the newly created bitmap on app interface

```<code>mImageView.setImageBitmap(bitmap);
</code>```

Body:
Try this...

Initialize a new Bitmap object

Bitmap bitmap = Bitmap.createBitmap(
                        500, // Width
                        300, // Height
                        Bitmap.Config.ARGB_8888 // Config
                );

Initialize a new Canvas instance

Canvas canvas = new Canvas(bitmap);

Draw a solid color to the canvas background

canvas.drawColor(Color.LTGRAY);

Initialize a new Paint instance to draw the Circle

Paint paint = new Paint();
                paint.setStyle(Paint.Style.FILL);
                paint.setColor(Color.RED);
                paint.setAntiAlias(true);

Calculate the available radius of canvas

int radius = Math.min(canvas.getWidth(),canvas.getHeight()/2);

Set a pixels value to padding around the circle

int padding = 5;

Finally, draw the circle on the canvas

canvas.drawCircle(
                        canvas.getWidth() / 2, // cx
                        canvas.getHeight() / 2, // cy
                        radius - padding, // Radius
                        paint // Paint
                );

Display the newly created bitmap on app interface

mImageView.setImageBitmap(bitmap);


问:
array_merge in php on a single mutlidimensional array
I got an array here which differs in just one field[4].

Somehow my brains says use 'array_merge' but there is no usable result for me.

Can you please have a look?

```<code>Array
(
    [0] => Array
        (
            [0] => 12
            [1] => someCssClass
            [2] => AnyText
            [3] => 1,2,3,4,5,6,7
            [4] => 4,5
        )

    [1] => Array
        (
            [0] => 12
            [1] => someCssClass
            [2] => AnyText
            [3] => 1,2,3,4,5,6,7
            [4] => 6,7
        )
)
</code>```

Below is what I think should be the output.

```<code>Array
(
    [0] => Array
        (
            [0] => 12
            [1] => someCssClass
            [2] => AnyText
            [3] => 1,2,3,4,5,6,7
            [4] => 4,5,6,7
           )

)
</code>```

答:
If you know only 4 th index is changed you can simply concatenate them

```<code>$arr = Array
(
    0 => Array
        (
            0 => 12,
            1 => "someCssClass",
            2 => "AnyText",
            3 => "1,2,3,4,5,6,7",
            4 => "4,5"
        ),

    1 => Array
        (
            0=> 12,
            1 => "someCssClass",
            2 => "AnyText",
            3 => "1,2,3,4,5,6,7",
            4 => "6,7"
        )
);
$new_array[] = $arr[0];
$new_array[0][4]=$arr[0][4].",".$arr[1][4];
print_r($new_array);
</code>```

DEMO

Body:
I got an array here which differs in just one field[4].

Somehow my brains says use 'array_merge' but there is no usable result for me.

Can you please have a look?

Array
(
    [0] => Array
        (
            [0] => 12
            [1] => someCssClass
            [2] => AnyText
            [3] => 1,2,3,4,5,6,7
            [4] => 4,5
        )

    [1] => Array
        (
            [0] => 12
            [1] => someCssClass
            [2] => AnyText
            [3] => 1,2,3,4,5,6,7
            [4] => 6,7
        )
)

Below is what I think should be the output.

Array
(
    [0] => Array
        (
            [0] => 12
            [1] => someCssClass
            [2] => AnyText
            [3] => 1,2,3,4,5,6,7
            [4] => 4,5,6,7
           )

)

Body:
If you know only 4 th index is changed you can simply concatenate them

$arr = Array
(
    0 => Array
        (
            0 => 12,
            1 => "someCssClass",
            2 => "AnyText",
            3 => "1,2,3,4,5,6,7",
            4 => "4,5"
        ),

    1 => Array
        (
            0=> 12,
            1 => "someCssClass",
            2 => "AnyText",
            3 => "1,2,3,4,5,6,7",
            4 => "6,7"
        )
);
$new_array[] = $arr[0];
$new_array[0][4]=$arr[0][4].",".$arr[1][4];
print_r($new_array);

DEMO


问:
How to hide Login fields from the logged user
I am developping an ASP MVC using ADO.net. I am trying to hide the login fields after the user login on.

Indeed, after authentication from the home page, the user is redirected to his profil page. The problem is that when the user go back to the home page, he find always the Login Fields.

According to the Debugger, Session["currentUser"] stay always null and then the script is rendered.

I didn't find also an error in dev tools.

This is what I've tried :

```<code> @if (Session["currentUser"] != null)
 {
    <script type='text/javascript'>
$(document).ready(function(){
    $("#login").hide();
});
    </script>
 }
        <div class="login" id="login">
            @*@RenderPage("~/Views/Home/Login.cshtml")*@
            <link href="~/Content/toastr.css" rel="stylesheet" />
            <div class="main-w3l">
                <div class="w3layouts-main" style="background-image:url('/template/web/images/bg3.jpg'); margin-top:50px;">
                    <h2>Login Now</h2>

                    @using (Html.BeginForm("Login", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
                    {

                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                        <input value="E-MAIL" name="Email" type="email" required="" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'E-Mail';}" />
                        <input value="PASSWORD" name="Password" type="password" required="" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'password';}" />
                        <span><input type="checkbox" />Remember Me</span>
                        <h6><a href="#">Forgot Password?</a></h6>
                        <div class="clear"></div>
                        <input type="submit" value="login" name="login">

                    }

                    <p>Don't Have an Account ?<a href="#" onclick="@("window.location.href='" + @Url.Action("Create", "Client") + "'") ;">Register Now</a></p>
                </div>
            </div>
</code>```

UPDATE :
Controller :

```<code>  public ActionResult Login()
        {
            return View();
        }

    database_Access_layer.db dblayer = new database_Access_layer.db();

    [HttpPost]
    public ActionResult Login(FormCollection fc, string LastName, string Email)
    {

        int res = dblayer.Admin_Login(fc["Email"], fc["Password"]);
        if (res == 1)
        {
            Session["currentUser"] = Email;
            string z = Email;
            connection();
            con.Open();
            SqlCommand command = new SqlCommand("select Email from Client", con);

            List<string> result = new List<string>();
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                    result.Add(reader.GetString(0));
                con.Close();
            }
            foreach (string x in result)
            {
                if (x == z)
                {

                    SqlCommand command2 = new SqlCommand($"select LastName from Client WHERE Email= '{x}' ", con);
                    con.Open();
                    string y = command2.ExecuteScalar().ToString();
                    con.Close();
                    Session["currentUser"] = y;

                }
            }

            return RedirectToAction("Profil", "Client");
            Session.RemoveAll();

        }
        else {

            TempData["msg"] = " Email or Password is wrong !";
            return RedirectToAction("Index", "Home");

        }

    }
</code>```

答:
There are built in systems to help you with the login. Session variables shouldn't be used for several reasons.

To set the login, you can use the following function inside your controller:

```<code>FormsAuthentication.SetAuthCookie(UserName, remember);
</code>```

Similarly you can use FormsAuthentication.SignOut() for logging out.

Now within your razor or in any controller you can check for User.Identity.IsAuthenticated to verify if the user is logged in.

For this functionality to work, you also need to make sure you have the following under your web.config, under your <system.web>:

```<code><authentication mode="Forms">

</authentication>
</code>```

Further more if you would like to take advantage of this login feature, you can add your login form into a separate cshtml page different from your home page. Lets say this page is in the location Home/Login. Now you can modify the above code within web.config as follows

```<code><authentication mode="Forms">
    <forms loginUrl="~/Home/Login" timeout="2880" />
</authentication>
</code>```

This assigns your default login page. Now if any URL needs to only be accessed on login, it would automatically redirect to this location if the user is not logged in. To specify that an action needs authentication, use [Authorize] before the action or the entire controller if you need the whole controller authorized. Your action will look something like this:

```<code>[Authorize]
public ActionResult Index(){
    return View()
}
</code>```

Finally your sample HomeController can look something like this:

```<code>public class HomeController : Controller
{

    public ActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public ActionResult Login()
    {
        return View();  // for the login form
    }

    [HttpPost]
    public void Login(string UserName, .... <other fields>)
    {
        // validate your login first here
        FormsAuthentication.SetAuthCookie(UserName, true);
    }

}
</code>```

Body:
I am developping an ASP MVC using ADO.net. I am trying to hide the login fields after the user login on.

Indeed, after authentication from the home page, the user is redirected to his profil page. The problem is that when the user go back to the home page, he find always the Login Fields.

According to the Debugger, Session["currentUser"] stay always null and then the script is rendered.

I didn't find also an error in dev tools.

This is what I've tried :

 @if (Session["currentUser"] != null)
 {

 }

            @*@RenderPage("~/Views/Home/Login.cshtml")*@
            <link href="~/Content/toastr.css" rel="stylesheet" />

Login Now

                    @using (Html.BeginForm("Login", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
                    {

                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                        <input value="E-MAIL" name="Email" type="email" required="" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'E-Mail';}" />
                        <input value="PASSWORD" name="Password" type="password" required="" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'password';}" />
                        <input type="checkbox" />Remember Me

Forgot Password?

                        <input type="submit" value="login" name="login">

                    }

Don't Have an Account ?Register Now

UPDATE :
Controller :

  public ActionResult Login()
        {
            return View();
        }

    database_Access_layer.db dblayer = new database_Access_layer.db();

    [HttpPost]
    public ActionResult Login(FormCollection fc, string LastName, string Email)
    {

        int res = dblayer.Admin_Login(fc["Email"], fc["Password"]);
        if (res == 1)
        {
            Session["currentUser"] = Email;
            string z = Email;
            connection();
            con.Open();
            SqlCommand command = new SqlCommand("select Email from Client", con);

            List<string> result = new List<string>();
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                    result.Add(reader.GetString(0));
                con.Close();
            }
            foreach (string x in result)
            {
                if (x == z)
                {

                    SqlCommand command2 = new SqlCommand($"select LastName from Client WHERE Email= '{x}' ", con);
                    con.Open();
                    string y = command2.ExecuteScalar().ToString();
                    con.Close();
                    Session["currentUser"] = y;

                }
            }

            return RedirectToAction("Profil", "Client");
            Session.RemoveAll();

        }
        else {

            TempData["msg"] = " Email or Password is wrong !";
            return RedirectToAction("Index", "Home");

        }

    }

Body:
There are built in systems to help you with the login. Session variables shouldn't be used for several reasons.

To set the login, you can use the following function inside your controller:

FormsAuthentication.SetAuthCookie(UserName, remember);

Similarly you can use FormsAuthentication.SignOut() for logging out.

Now within your razor or in any controller you can check for User.Identity.IsAuthenticated to verify if the user is logged in.

For this functionality to work, you also need to make sure you have the following under your web.config, under your <system.web>:

<authentication mode="Forms">

</authentication>

Further more if you would like to take advantage of this login feature, you can add your login form into a separate cshtml page different from your home page. Lets say this page is in the location Home/Login. Now you can modify the above code within web.config as follows

<authentication mode="Forms">
    <forms loginUrl="~/Home/Login" timeout="2880" />
</authentication>

This assigns your default login page. Now if any URL needs to only be accessed on login, it would automatically redirect to this location if the user is not logged in. To specify that an action needs authentication, use [Authorize] before the action or the entire controller if you need the whole controller authorized. Your action will look something like this:

[Authorize]
public ActionResult Index(){
    return View()
}

Finally your sample HomeController can look something like this:

public class HomeController : Controller
{

    public ActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public ActionResult Login()
    {
        return View();  // for the login form
    }

    [HttpPost]
    public void Login(string UserName, .... <other fields>)
    {
        // validate your login first here
        FormsAuthentication.SetAuthCookie(UserName, true);
    }

}


问:
How to save logs to file from "Debug" in my project
I use in my project Debug package https://www.npmjs.com/package/debug.
I set environment variable (variablename: DEBUG & value:*). After this i see in my console output logs from my app. I would like save all this logs to file. How i can make this?</p>

答:
There are many npm packages that can log into files, see for example Winston.

Or you can create your own function that handles where to write the log line - see the Debug documentation here


问:
YouTube IFrame Player API getVideoData is removed: how to get title?
On November 13th, I got a call from a customer reporting that the YouTube player didn't work anymore. After a quick look in the dev tool, I found that there was an error:

```<code>Uncaught TypeError: a.getVideoData is not a function
</code>```

Looking into what the player object was containing, I learned that there's no function getVideoData anymore.

The function getVideoData provided a way to get the video title. Now, how can I get the title?

Is there any article from Google about this change?

答:
To get a video's title, you can query the YouTube Data API v3:

```<code>GET https://www.googleapis.com/youtube/v3/videos
    ?part=snippet
    &id=VIDEO_ID
    &key=YOUR_API_KEY
</code>```

For that you need to sign up on the Google Cloud Console and create an API key (it's free). You can restrict the API key to only be used from your website, that way you can safely make it public in your JS source code/html code without others being able to make queries on your behalf. Make sure to enable the YouTube Data API v3 in the console as well, otherwise your queries will return errors.

The above query will return a JSON representation of the information on the video that you are interested in (the snippet part). Say you parse the JSON into an object called result. Then you can get the video title via

```<code>result.items[0].snippet.title
</code>```

Body:
On November 13th, I got a call from a customer reporting that the YouTube player didn't work anymore. After a quick look in the dev tool, I found that there was an error:

Uncaught TypeError: a.getVideoData is not a function

Looking into what the player object was containing, I learned that there's no function getVideoData anymore.

The function getVideoData provided a way to get the video title. Now, how can I get the title?

Is there any article from Google about this change?

Body:
To get a video's title, you can query the YouTube Data API v3:

GET https://www.googleapis.com/youtube/v3/videos
    ?part=snippet
    &id=VIDEO_ID
    &key=YOUR_API_KEY

For that you need to sign up on the Google Cloud Console and create an API key (it's free). You can restrict the API key to only be used from your website, that way you can safely make it public in your JS source code/html code without others being able to make queries on your behalf. Make sure to enable the YouTube Data API v3 in the console as well, otherwise your queries will return errors.

The above query will return a JSON representation of the information on the video that you are interested in (the snippet part). Say you parse the JSON into an object called result. Then you can get the video title via

result.items[0].snippet.title


问:
std::string part into integer
I have a std::string: 01001, I want to get each number:

```<code>std::string foo = "01001";
for (int i=0; i < foo.size(); ++i)
{
   int res = atoi( foo[i] );  // fail
   int res = atoi( &foo[i] ); // ok, but res = 0 in any case
}
</code>```

How to do that?

答:
If you know all characters of foo are digits, you can use (int) (foo[i] - '0') which subtracts the ascii value of '0' from the character. This works for all digits because their ascii values are consecutive.

Your first attempt fails because foo[i] is a single char, while atoi() takes a cstring. Your second attempt fails because &foo[i] is a reference to that character.

Title: std::string part into integer

Body:
I have a std::string: 01001, I want to get each number:

std::string foo = "01001";
for (int i=0; i < foo.size(); ++i)
{
   int res = atoi( foo[i] );  // fail
   int res = atoi( &foo[i] ); // ok, but res = 0 in any case
}

How to do that?


问:
XPath to get all child elements except one with specific name?
How do I target all elements in a document except a particular element name?

For example I want to exclude the terminate elements. They can occur throughout the document.

```<code> <root>
     <terminate attr="1" />
     <other>
         The brown fox jumps over the fence.
         <terminate>
            <b>stuff</b>
         </terminate>
     </other>
 </root>
</code>```

I've tried using the not(..) operator without success likely because I'm using it wrong.

And frankly trying to Google 'not' is tough!

答:
If you are using XPath 2.0 you can use

```<code>/root/* except /root/terminate
</code>```

Which does what you would expect. It matches for nodes that exist in the first sequence but not the second.

XPath 2.0 Specification - except operator

Body:
How do I target all elements in a document except a particular element name?

For example I want to exclude the terminate elements. They can occur throughout the document.

 <root>
     <terminate attr="1" />
     <other>
         The brown fox jumps over the fence.
         <terminate>
            stuff
         </terminate>
     </other>
 </root>

I've tried using the not(..) operator without success likely because I'm using it wrong.

And frankly trying to Google 'not' is tough!

Body:
If you are using XPath 2.0 you can use

/root/* except /root/terminate

Which does what you would expect. It matches for nodes that exist in the first sequence but not the second.

XPath 2.0 Specification - except operator