问:
RecyclerView onClick for multiple buttons and handling from Activity
I'm using RecyclerView with CardView and inside the CardView have 2 buttons. Now, have implemented the onClick events by implementing View.OnClickListener by the ViewHolder static class and overriding the event (its working )like

```<code>    @Override
    public void onClick(View v) {

        if (v.getId() == mClassBtn.getId()){

        }
        else if (v.getId() == mDaysBtn.getId()){

        }
     }
</code>```

Looking for a solution/pattern to handle the Click in the Activity class like

```<code>adapter = new ItemsListAdapter(getActivity(), data, new CustomItemClickListener() {

    @override
    public void onItemClick(View v, int position) {

       Log.d(TAG, "clicked position:" + position);
       // which button clicked and separate action for each button
    }
});
// CustomItemClickListener -- interface in the adapter class which holds the click event .
</code>```

The above code working fine and able to log the Clicks but not able to differentiate which button has clicked.

Appreciate any help

答:
Here my solution if it could help someone.

You could click in one item of the recyclerview or one of the two buttons.

The interface implements:

onStudentItemClick, for click in the recyclerview item

onChatItemClick and onAbsenceItemClick for click the buttons

With

```<code> holder.imgChat.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOnClickListener.onChatItemClick(mStudents.get(index));

                }
            });
</code>```

I set the click listener for one button

And in the class StudentViewHolder I implement OnClickListener and override onClik

```<code>@Override
        public void onClick(View v) {

            if (mOnClickListener != null){
                int clickedPosition = getAdapterPosition();
                mOnClickListener.onStudentItemClick(mStudents.get(clickedPosition));
            }
        }
</code>```

Here the Adapter:

```<code>public class StudentsAdapter extends RecyclerView.Adapter<StudentsAdapter.StudentsViewHolder> {

    private ListItemClickListener mOnClickListener;
    private ArrayList<Student> mStudents;

    public interface ListItemClickListener {
        void onStudentItemClick(Student student);
        void onChatItemClick(Student student);
        void onAbsenceItemClick(Student student);
    }

    public StudentsAdapter(ArrayList<Student> students, ListItemClickListener listener) {
        mStudents = students;
        mOnClickListener = listener;
    }

    @Override
    public StudentsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        Context context = viewGroup.getContext();
        int layoutIdForListItem = R.layout.student_list_item;
        LayoutInflater inflater = LayoutInflater.from(context);
        boolean shouldAttachToParentImmediately = false;

        View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
        StudentsViewHolder viewHolder = new StudentsViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(StudentsViewHolder holder, int position) {
        final Integer index = position;
        holder.tvStudent.setText(mStudents.get(position).nameForList());
        holder.imgChat.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mOnClickListener.onChatItemClick(mStudents.get(index));

            }
        });
        holder.imgAbsence.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mOnClickListener.onAbsenceItemClick(mStudents.get(index));

            }
        });

    }

    public Student getItem(Integer position){
        return mStudents.get(position);
    }

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

    class StudentsViewHolder extends RecyclerView.ViewHolder
            implements OnClickListener {

        ImageView imgStudent;
        TextView tvStudent;
        ImageButton imgChat, imgAbsence;

        public StudentsViewHolder(View itemView) {
            super(itemView);

            imgStudent = (ImageView) itemView.findViewById(R.id.img_student);
            tvStudent = (TextView) itemView.findViewById(R.id.tv_student);
            imgChat = (ImageButton) itemView.findViewById(R.id.btn_chat_student);
            imgAbsence = (ImageButton) itemView.findViewById(R.id.btn_absence);

            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {

            if (mOnClickListener != null){
                int clickedPosition = getAdapterPosition();
                mOnClickListener.onStudentItemClick(mStudents.get(clickedPosition));
            }
        }
    }
}
</code>```

Fragment the implement the interface:

```<code>public class SubjectDetailFragment extends Fragment implements  StudentsAdapter.ListItemClickListener {
...
@Override
public void onStudentItemClick(Student student) {
    StudentDetailFragment detailFragment = StudentDetailFragment.newInstance();
    Bundle bundle = new Bundle();
    bundle.putParcelable("student", student);
    detailFragment.setArguments(bundle);

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.frame_layout, detailFragment);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();

}

@Override
public void onChatItemClick(Student student) {
    ...
}

@Override
public void onAbsenceItemClick(Student student) {
    ...

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using RecyclerView with CardView and inside the CardView have 2 buttons. Now, have implemented the onClick events by implementing View.OnClickListener by the ViewHolder static class and overriding the event (its working )like

    @Override
    public void onClick(View v) {

        if (v.getId() == mClassBtn.getId()){

        }
        else if (v.getId() == mDaysBtn.getId()){

        }
     }

Looking for a solution/pattern to handle the Click in the Activity class like

adapter = new ItemsListAdapter(getActivity(), data, new CustomItemClickListener() {

    @override
    public void onItemClick(View v, int position) {

       Log.d(TAG, "clicked position:" + position);
       // which button clicked and separate action for each button
    }
});
// CustomItemClickListener -- interface in the adapter class which holds the click event .

The above code working fine and able to log the Clicks but not able to differentiate which button has clicked.

Appreciate any help

Body:
Here my solution if it could help someone.

You could click in one item of the recyclerview or one of the two buttons.

The interface implements:

onStudentItemClick, for click in the recyclerview item

onChatItemClick and onAbsenceItemClick for click the buttons

With

 holder.imgChat.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOnClickListener.onChatItemClick(mStudents.get(index));

                }
            });

I set the click listener for one button

And in the class StudentViewHolder I implement OnClickListener and override onClik

@Override
        public void onClick(View v) {

            if (mOnClickListener != null){
                int clickedPosition = getAdapterPosition();
                mOnClickListener.onStudentItemClick(mStudents.get(clickedPosition));
            }
        }

Here the Adapter:

public class StudentsAdapter extends RecyclerView.Adapter<StudentsAdapter.StudentsViewHolder> {

    private ListItemClickListener mOnClickListener;
    private ArrayList<Student> mStudents;

    public interface ListItemClickListener {
        void onStudentItemClick(Student student);
        void onChatItemClick(Student student);
        void onAbsenceItemClick(Student student);
    }

    public StudentsAdapter(ArrayList<Student> students, ListItemClickListener listener) {
        mStudents = students;
        mOnClickListener = listener;
    }

    @Override
    public StudentsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        Context context = viewGroup.getContext();
        int layoutIdForListItem = R.layout.student_list_item;
        LayoutInflater inflater = LayoutInflater.from(context);
        boolean shouldAttachToParentImmediately = false;

        View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
        StudentsViewHolder viewHolder = new StudentsViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(StudentsViewHolder holder, int position) {
        final Integer index = position;
        holder.tvStudent.setText(mStudents.get(position).nameForList());
        holder.imgChat.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mOnClickListener.onChatItemClick(mStudents.get(index));

            }
        });
        holder.imgAbsence.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mOnClickListener.onAbsenceItemClick(mStudents.get(index));

            }
        });

    }

    public Student getItem(Integer position){
        return mStudents.get(position);
    }

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

    class StudentsViewHolder extends RecyclerView.ViewHolder
            implements OnClickListener {

        ImageView imgStudent;
        TextView tvStudent;
        ImageButton imgChat, imgAbsence;

        public StudentsViewHolder(View itemView) {
            super(itemView);

            imgStudent = (ImageView) itemView.findViewById(R.id.img_student);
            tvStudent = (TextView) itemView.findViewById(R.id.tv_student);
            imgChat = (ImageButton) itemView.findViewById(R.id.btn_chat_student);
            imgAbsence = (ImageButton) itemView.findViewById(R.id.btn_absence);

            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {

            if (mOnClickListener != null){
                int clickedPosition = getAdapterPosition();
                mOnClickListener.onStudentItemClick(mStudents.get(clickedPosition));
            }
        }
    }
}

Fragment the implement the interface:

public class SubjectDetailFragment extends Fragment implements  StudentsAdapter.ListItemClickListener {
...
@Override
public void onStudentItemClick(Student student) {
    StudentDetailFragment detailFragment = StudentDetailFragment.newInstance();
    Bundle bundle = new Bundle();
    bundle.putParcelable("student", student);
    detailFragment.setArguments(bundle);

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.frame_layout, detailFragment);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();

}

@Override
public void onChatItemClick(Student student) {
    ...
}

@Override
public void onAbsenceItemClick(Student student) {
    ...

}


来源: stackexchange

问:
Show loading Screen while Image is loading in wicket
I'am populating a ListView with images.

In pseudocode:

```<code>populateItem(model){
    load base64 from database
    image.setDefaultModel(base64)
</code>```

The image is just a webcomponent and in html it is just
How can i show a indicator while the image is loaded?.
I first thought of adding IAjaxIndicatorAware but this triggers the indicator when the image is doing an AjaxRequest.

答:
Since you seem to load and display the image as a Base64 src it will directly get send in the html response and not loaded later (in contrast to images with a src that links to another URI).

You could wrap the image in an AjaxLazyLoadPanel.
This will first display an AjaxIndicator while the content is generated and get later replaced by the actual loaded content once it is done loading/generating:

edit

I got an Exception : Component must be applied to a tag of type [img].

i didn't consider that problem. AjaxLazyLoadPanel allways uses a
 as a html tag to display the component it loads. To display a base 64 image you would need to wrap it in another Panel:

```<code>public class Base64ImagePanel extends Panel {
     public Base64ImagePanel(String wicketId, String base64Data, String contentType) {
          super(wicketId);
          WebMarkupContainer image = new WebMarkupContainer("image") {
                protected void onComponentTag(ComponentTag tag) {
                      super.onComponentTag(tag);
                      checkComponentTag(tag, "img");
                      tag.put("src", "data:" + contentType + ";base64," + base64Data);
                }
          }
          add(image);
     }
}
</code>```

Base64ImagePanel.html:

```<code><wicket:panel>
    <img wicket:id="image"></img>
</wicket:panel>
</code>```

And then  use that wrapper Panel in the AjaxLazyLoadPanel:

```<code>add(new AjaxLazyLoadPanel("imageLazyLoad") {
    @Override
    public Component getLazyLoadComponent(String id) {
         //load your actual base64 from database, i use some example Strings for demonstration in the following line
         Base64ImagePanel imagePanel = new Base64ImagePanel(id, "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==", "image/png");
         return imagePanel;
    }
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'am populating a ListView with images.

In pseudocode:

populateItem(model){
    load base64 from database
    image.setDefaultModel(base64)

The image is just a webcomponent and in html it is just
How can i show a indicator while the image is loaded?.
I first thought of adding IAjaxIndicatorAware but this triggers the indicator when the image is doing an AjaxRequest.

Body:
Since you seem to load and display the image as a Base64 src it will directly get send in the html response and not loaded later (in contrast to images with a src that links to another URI).

You could wrap the image in an AjaxLazyLoadPanel.
This will first display an AjaxIndicator while the content is generated and get later replaced by the actual loaded content once it is done loading/generating:

edit

I got an Exception : Component must be applied to a tag of type [img].

i didn't consider that problem. AjaxLazyLoadPanel allways uses a <div> as a html tag to display the component it loads. To display a base 64 image you would need to wrap it in another Panel:

public class Base64ImagePanel extends Panel {
     public Base64ImagePanel(String wicketId, String base64Data, String contentType) {
          super(wicketId);
          WebMarkupContainer image = new WebMarkupContainer("image") {
                protected void onComponentTag(ComponentTag tag) {
                      super.onComponentTag(tag);
                      checkComponentTag(tag, "img");
                      tag.put("src", "data:" + contentType + ";base64," + base64Data);
                }
          }
          add(image);
     }
}

Base64ImagePanel.html:

<wicket:panel>
    <img wicket:id="image"></img>
</wicket:panel>

And then  use that wrapper Panel in the AjaxLazyLoadPanel:

add(new AjaxLazyLoadPanel("imageLazyLoad") {
    @Override
    public Component getLazyLoadComponent(String id) {
         //load your actual base64 from database, i use some example Strings for demonstration in the following line
         Base64ImagePanel imagePanel = new Base64ImagePanel(id, "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==", "image/png");
         return imagePanel;
    }
});


问:
How to move struct array value to another array value on one struct
I want to record my some student information on struct with realloc(memory allocator).When I try to solve this problem ; I will sort the data by given id's but each id has some additional information about whoose id's student. I sort the struct by id but when ı move the each data to another data compiler dont do this. Please could you help me ? Note: I don't mean to move struct to another struct.I just want to move strcut array one element values to another array element value or change theese data position for sorted data</p>

```<code>#include <string.h>
#include <stdlib.h>

typedef struct {
    int id;
    char name[10];
    char surname[10];
    double quiz1;
    double quiz2;
    double quiz3;
    double midterm;
    double finall;
}STUDENT;

int indis = 0;
void swapInt(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

void swapDouble(double *a, double *b)
{
    double temp = *a;
    *a = *b;
    *b = temp;
}

void str_swap(char const ** str1, char const ** str2)
{
    char const *temp = *str1;
    *str1 = *str2;
    *str2 = temp;
}

void sortSt(STUDENT *st) {
    int i, j, min;
    for (i = 0; i < indis - 1; i++) {
        min = i;
        for (j = i + 1; j < indis; j++)
            if (st[j].id < st[min].id) {
                min = j;
                // Swap the found minimum element with the first element
                memcpy()
                swapInt(&st[min].id, &st[i].id);
                str_swap(&st[min].name, &st[i].name);
                swapChar(st[min].surname, st[i].surname);
                swapDouble(&st[min].quiz1, &st[i].quiz1);
                swapDouble(&st[min].quiz2, &st[i].quiz2);
                swapDouble(&st[min].quiz3, &st[i].quiz3);
                swapDouble(&st[min].midterm, &st[i].midterm);
                swapDouble(&st[min].finall, &st[i].finall);
            }

    }
}
</code>```

答:
I asked this question to my T.A. He answered but the solution is very simple :)
Like this;

```<code>void removeStudent(STUDENT *st , int numberOfStudent) {
    int id;
    printf("Please enter id for remove student \n");
    scanf("%d", &id);
    for (int i = 0; i < indis; i++)
    {
        if (st[i].id == id) {
            st[i] = st[numberOfStudent];  // this is exactly answer
            printf("%d id's student removed \n", id);
            break;

}
    else if(i==indis) {
        printf("%d id's student not found \n ",id);
    }
}
</code>```

}

Body:
I want to record my some student information on struct with realloc(memory allocator).When I try to solve this problem ; I will sort the data by given id's but each id has some additional information about whoose id's student. I sort the struct by id but when ı move the each data to another data compiler dont do this. Please could you help me ? Note: I don't mean to move struct to another struct.I just want to move strcut array one element values to another array element value or change theese data position for sorted data

#include <string.h>
#include <stdlib.h>

typedef struct {
    int id;
    char name[10];
    char surname[10];
    double quiz1;
    double quiz2;
    double quiz3;
    double midterm;
    double finall;
}STUDENT;

int indis = 0;
void swapInt(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

void swapDouble(double *a, double *b)
{
    double temp = *a;
    *a = *b;
    *b = temp;
}

void str_swap(char const ** str1, char const ** str2)
{
    char const *temp = *str1;
    *str1 = *str2;
    *str2 = temp;
}

void sortSt(STUDENT *st) {
    int i, j, min;
    for (i = 0; i < indis - 1; i++) {
        min = i;
        for (j = i + 1; j < indis; j++)
            if (st[j].id < st[min].id) {
                min = j;
                // Swap the found minimum element with the first element
                memcpy()
                swapInt(&st[min].id, &st[i].id);
                str_swap(&st[min].name, &st[i].name);
                swapChar(st[min].surname, st[i].surname);
                swapDouble(&st[min].quiz1, &st[i].quiz1);
                swapDouble(&st[min].quiz2, &st[i].quiz2);
                swapDouble(&st[min].quiz3, &st[i].quiz3);
                swapDouble(&st[min].midterm, &st[i].midterm);
                swapDouble(&st[min].finall, &st[i].finall);
            }

    }
}

Body:
I asked this question to my T.A. He answered but the solution is very simple :)
Like this;

void removeStudent(STUDENT *st , int numberOfStudent) {
    int id;
    printf("Please enter id for remove student \n");
    scanf("%d", &id);
    for (int i = 0; i < indis; i++)
    {
        if (st[i].id == id) {
            st[i] = st[numberOfStudent];  // this is exactly answer
            printf("%d id's student removed \n", id);
            break;

}
    else if(i==indis) {
        printf("%d id's student not found \n ",id);
    }
}

}


问:
How to know the entire text of HTMLTableDataCellElement is selected
I have a table which have editable columns and when the text in the editable column is selected, how can we check using java-script whether the entire text of the HTMLTableDataCellElement is selected or not?

Like for input field there is a way

input.selectionStart == 0 && input.selectionEnd == input.value.length.

Thanks.

答:
I gave it a try.

document.onmouseup = (e) => {
  e = e || window.event;
  const target = e.target || e.srcElement;
  const selection = window.getSelection().toString();
  if (target.innerHTML === selection) {
    alert('Cell fully selected!');
  }
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  border-collapse: collapse;
}

td {
  padding: 4px 8px;
}</code>```

    Lorem ipsum
    Dolor sit

    Lorem ipsum
    Dolor sit amet dolor sit amet

    Lorem
    Ipsum dolor

```

Body:
I gave it a try.

document.onmouseup = (e) => {
  e = e || window.event;
  const target = e.target || e.srcElement;
  const selection = window.getSelection().toString();
  if (target.innerHTML === selection) {
    alert('Cell fully selected!');
  }
};

table {
  border-collapse: collapse;
}

td {
  padding: 4px 8px;
}

<table id="myTable" border="1">
  <tr>
    <td>Lorem ipsum</td>
    <td>Dolor sit</td>
  </tr>
  <tr>
    <td>Lorem ipsum</td>
    <td>Dolor sit amet dolor sit amet</td>
  </tr>
  <tr>
    <td>Lorem</td>
    <td>Ipsum dolor</td>
  </tr>
</table>


问:
How to change InnoDB AUTO_INCREMENT Lock Modes on Debian?
I create a table with auto_increment, and insert into it a lot of data.

My database skip number while I am using auto-increment, i found that i have to change the auto_incremet_lock_mode = 0, but i didn't find, where i have to do this change on Debian system?

I tried to find the my.cnf file in /etc/mysql/ but it contains only 2 rows, so i don't know how i can change it. I read the mysql site too but there isn't any information about it.

答:
It was hard, but i found the answer!

edit the /etc/my.cnf file with
[mysqld]
innodb_autoinc_lock_mode=0
//You have to use autoinc_lock_mode inside this [mysqld] part!

restart/reload configs with sudo /etc/init.d/mysql restart


问:
How to move Zoom buttons on MapView to different place?
I need to move zoom buttons from bottom center to bottom right position on MapView? Is that possible? Thanks.</p>

答: You could turn off the built in zoom controls via setBuiltInZoomControls and replace them with your own version that develop.</p>

ContentLicense: CC BY-SA 2.5


问:
Problems with mysql create procedure from doctrine raw sql
I am working with an application project in Symfony2.
By registration, per client, a database is created.
Schemas are created by a validation service when the client logs on.
The application needs some data to work, and so far, I used ORM fixtures.
For a number of reasons, I now need to move from fixtures load to get more close to the database.
I have created a stored procedure (mysql) which will replace all data loading. The procedure works, but I need to create this procedure in each database together with the schema.
I use doctrine raw sql for this purpose but I cannot get pass a problem with the first lines of the create procedure statement. It seems it's got to do with the 'delimiter $$'.

While executing the service with the sql statement i get:
"message":"An exception occurred while executing 'delimiter $$\r\n\r\nCREATE DEFINER=root@`localhost"

It seems to be because of line-breaks but I am not sure. Anyone knows of some way around this?

答:
I know this is a late answer however this post is high in Google's results and I found no other answer elsewhere so I would like to post a solution how to overcome the issue.

Long story short, one has to break the lines with the \n character inside the query, for instance:

```<code>$this->addSql(
    "CREATE EVENT event_example ON SCHEDULE EVERY 15 MINUTE ".
    "ON COMPLETION NOT PRESERVE ENABLE DO BEGIN\n".
    "INSERT INTO archives SELECT * FROM records;\n".
    "DELETE FROM records;\n".
    "END"
);
</code>```

Body:
I know this is a late answer however this post is high in Google's results and I found no other answer elsewhere so I would like to post a solution how to overcome the issue.

Long story short, one has to break the lines with the \n character inside the query, for instance:

$this->addSql(
    "CREATE EVENT event_example ON SCHEDULE EVERY 15 MINUTE ".
    "ON COMPLETION NOT PRESERVE ENABLE DO BEGIN\n".
    "INSERT INTO archives SELECT * FROM records;\n".
    "DELETE FROM records;\n".
    "END"
);


问:
Swift 4 migration getting error Cannot convert value of type '[String : AnyObject]?' to expected argument type '[NSAttributedStringKey : Any]?'
```<code>let linkTextAttributes = [
        NSAttributedStringKey.underlineStyle: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue as Int),
        NSAttributedStringKey.foregroundColor: FAColor.blackColor()
      ]

self.lblPinDidNotMatchDescription.linkTextAttributes = linkTextAttributes
</code>```

Getting error on Swift 4 migration

"Cannot convert value of type '[String : AnyObject]?' to expected argument type '[NSAttributedStringKey : Any]?'".

Any help?

答:
Change to NSUnderlineStyle.styleSingle.rawValue

Example

```<code>let linkTextAttributes: [NSAttributedStringKey: Any]  = [
                    NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue,
                    NSAttributedStringKey.foregroundColor: UIColor.black
                ]
</code>```

Body:
let linkTextAttributes = [
        NSAttributedStringKey.underlineStyle: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue as Int),
        NSAttributedStringKey.foregroundColor: FAColor.blackColor()
      ]

self.lblPinDidNotMatchDescription.linkTextAttributes = linkTextAttributes

Getting error on Swift 4 migration

"Cannot convert value of type '[String : AnyObject]?' to expected argument type '[NSAttributedStringKey : Any]?'".

Any help?

Body:
Change to NSUnderlineStyle.styleSingle.rawValue

Example

let linkTextAttributes: [NSAttributedStringKey: Any]  = [
                    NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue,
                    NSAttributedStringKey.foregroundColor: UIColor.black
                ]


问:
How to remove "Never ask again" text in this popup?
How can I request the permission popup without “Never ask again” text?

Here java Code ,

```<code>    if
 (intent.getAction().equals("com.finish.canceltrip.DriverMapActivity")) {
                if (!checkAccessFineLocationPermission() || !checkAccessCoarseLocationPermission() || !checkWriteExternalStoragePermission()) {
                    requestPermission();
                } else {
                    Intent i = new Intent(DriverMapActivity.this, DriverMapActivity.class);
                    i.putExtra("availability", "Yes");
                    finish();
                    startActivity(i);

                }
</code>```

答:
How can I request the permission popup without “Never ask again” text?

NO you can not remove “Never ask again”  from Permission Dialog

try this this hack if user selects Never ask again

ask for permission like this

```<code> btnCurrentLocationSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String permission = android.Manifest.permission.ACCESS_FINE_LOCATION;

                if (ActivityCompat.checkSelfPermission(SearchCityClass.this, permission)
                        != PackageManager.PERMISSION_GRANTED && ActivityCompat.
                        checkSelfPermission(SearchCityClass.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {

                    Toast.makeText(SearchCityClass.this, "Permission not granted", Toast.LENGTH_SHORT).show();

                    ActivityCompat.requestPermissions(SearchCityClass.this, new String[]
                            {permission}, requestCode);

                } else {
                    isPermissionGranted(true);
                }
            }

        });
</code>```

than handle permission result in onRequestPermissionsResult

```<code>    @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if (requestCode == requestCode) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    isPermissionGranted(true);
                } else {

                    isPermissionGranted(false);
                }
            }
        }
</code>```

than create a method like this

```<code>public void isPermissionGranted(boolean permission) {
        if (!permission) {
            Toast.makeText(this, "Permission not Granted", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                    Uri.fromParts("package", getPackageName(), null)));
        } else {
            Toast.makeText(SearchCityClass.this, "true", Toast.LENGTH_SHORT).show();
            Toast.makeText(SearchCityClass.this, "Permission granted", Toast.LENGTH_SHORT).show();
            // you need to perform all action here if user grants the permission
        }
    }
</code>```

Body:
How can I request the permission popup without “Never ask again” text?

Here java Code ,

    if
 (intent.getAction().equals("com.finish.canceltrip.DriverMapActivity")) {
                if (!checkAccessFineLocationPermission() || !checkAccessCoarseLocationPermission() || !checkWriteExternalStoragePermission()) {
                    requestPermission();
                } else {
                    Intent i = new Intent(DriverMapActivity.this, DriverMapActivity.class);
                    i.putExtra("availability", "Yes");
                    finish();
                    startActivity(i);

                }

Body:
How can I request the permission popup without “Never ask again” text?

NO you can not remove “Never ask again”  from Permission Dialog

try this this hack if user selects Never ask again

ask for permission like this

 btnCurrentLocationSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String permission = android.Manifest.permission.ACCESS_FINE_LOCATION;

                if (ActivityCompat.checkSelfPermission(SearchCityClass.this, permission)
                        != PackageManager.PERMISSION_GRANTED && ActivityCompat.
                        checkSelfPermission(SearchCityClass.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {

                    Toast.makeText(SearchCityClass.this, "Permission not granted", Toast.LENGTH_SHORT).show();

                    ActivityCompat.requestPermissions(SearchCityClass.this, new String[]
                            {permission}, requestCode);

                } else {
                    isPermissionGranted(true);
                }
            }

        });

than handle permission result in onRequestPermissionsResult

    @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if (requestCode == requestCode) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    isPermissionGranted(true);
                } else {

                    isPermissionGranted(false);
                }
            }
        }

than create a method like this

public void isPermissionGranted(boolean permission) {
        if (!permission) {
            Toast.makeText(this, "Permission not Granted", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                    Uri.fromParts("package", getPackageName(), null)));
        } else {
            Toast.makeText(SearchCityClass.this, "true", Toast.LENGTH_SHORT).show();
            Toast.makeText(SearchCityClass.this, "Permission granted", Toast.LENGTH_SHORT).show();
            // you need to perform all action here if user grants the permission
        }
    }


问:
How to allow download local file from controller in CakePHP 3
I'm using CakePHP 3.4+ for my application.

There is an XML file in local path and needs to be downloaded when on clicking the link. I want to return download from controller's action after checking few requirements as per my application

```<code>public function downloadXml()
{
    if ($this->_checkMembership()) {
        try {
            // file path /webroot/agency/data.xml
            $xmlLink = WWW_ROOT . 'agency/data.xml';

            $this->response->withFile($xmlLink, [
                'download' => true,
                'name' => 'data.xml',
            ]);
            return $this->response;
        } catch (NotFoundException $e) {
            $this->Flash->error('Requested file not found. Try again');
            return $this->redirect(['action' => 'index']);
        }
    }
}
</code>```

And in template

```<code><?= $this->Html->link(
      __('Download the site'),
      [
          'action' => 'downloadXml'
      ],
) ?>
</code>```

But this only shows a blank page on clicking the link

答:
The with* reponse methods are implemented using the PSR-7 immutability pattern, ie they return a new object instead of modifying the current one. You must return the newly created object:

```<code>return $this->response->withFile($xmlLink, [
    'download' => true,
    'name' => 'data.xml',
]);
</code>```

If you weren't to return a custom response, ie if you'd wanted to render a view instead of returning a response object, then you'd have to reassign the new object to $this->response in order to apply modifications.

Cookbook > 3.x Migration Guide > 3.4 Migration Guide > Adopting Immutable Responses

Cookbook > 3.x Migration Guide > 3.4 Migration Guide > Request & Response Deprecations

Cookbook > Request & Response Objects > Response > Sending Files

Body:
I'm using CakePHP 3.4+ for my application.

There is an XML file in local path and needs to be downloaded when on clicking the link. I want to return download from controller's action after checking few requirements as per my application

public function downloadXml()
{
    if ($this->_checkMembership()) {
        try {
            // file path /webroot/agency/data.xml
            $xmlLink = WWW_ROOT . 'agency/data.xml';

            $this->response->withFile($xmlLink, [
                'download' => true,
                'name' => 'data.xml',
            ]);
            return $this->response;
        } catch (NotFoundException $e) {
            $this->Flash->error('Requested file not found. Try again');
            return $this->redirect(['action' => 'index']);
        }
    }
}

And in template

<?= $this->Html->link(
      __('Download the site'),
      [
          'action' => 'downloadXml'
      ],
) ?>

But this only shows a blank page on clicking the link

Body:
The with* reponse methods are implemented using the PSR-7 immutability pattern, ie they return a new object instead of modifying the current one. You must return the newly created object:

return $this->response->withFile($xmlLink, [
    'download' => true,
    'name' => 'data.xml',
]);

If you weren't to return a custom response, ie if you'd wanted to render a view instead of returning a response object, then you'd have to reassign the new object to $this->response in order to apply modifications.

Cookbook > 3.x Migration Guide > 3.4 Migration Guide > Adopting Immutable Responses

Cookbook > 3.x Migration Guide > 3.4 Migration Guide > Request & Response Deprecations

Cookbook > Request & Response Objects > Response > Sending Files


问:
Can I Redirect from Child Action Method to the New Action Method and return their view instead of returning to the parent of that child?
For Suppose I have an action method e.g Pseudocode

Pseudo Code is here
Is this possible to redirect from child to another parent action mehtod and return their view instead of returning view to the parent of that child ?

答:
You can return any response you like from any action.  Using your example:

```<code>public ActionResult Method()
{
    return ChildActionMethod();
}

public ActionResult ChildActionMethod()
{
    return RedirectToAction("SomeAction");
}
</code>```

This would return the redirect result from Method, since it's returning whatever ChildActionMethod returns.

It's worth noting that if you do return View(); within ChildActionMethod and don't specify the view, the framework will use the current request to determine which view to use.  That is, it will use the view for Method instead of ChildActionMethod by default.  You'd need to specify the view in this case.

In fact, ChildActionMethod doesn't even need to be a public "action method".  It can be any method which returns an ActionResult.  At this point you're dealing with just the basics of the C# language (methods, types, etc.), not so much the ASP.NET MVC Framework.

Body:
You can return any response you like from any action.  Using your example:

public ActionResult Method()
{
    return ChildActionMethod();
}

public ActionResult ChildActionMethod()
{
    return RedirectToAction("SomeAction");
}

This would return the redirect result from Method, since it's returning whatever ChildActionMethod returns.

It's worth noting that if you do return View(); within ChildActionMethod and don't specify the view, the framework will use the current request to determine which view to use.  That is, it will use the view for Method instead of ChildActionMethod by default.  You'd need to specify the view in this case.

In fact, ChildActionMethod doesn't even need to be a public "action method".  It can be any method which returns an ActionResult.  At this point you're dealing with just the basics of the C# language (methods, types, etc.), not so much the ASP.NET MVC Framework.


问:
VBA join array elements to then pass as multiple parameters to function
[Update: The question has been formed so that the functions can be copied directly into a VBA module and tested by running the test_callback_loop_function_works_with_multiple_parameters method]

I am using the Application.Run function to dynamically call methods within my VBA. The idea is that this helper will save me looping through dictionaries throughout various functions/subs within my VBA. Instead I can just call the following helper which will do the looping for me:

```<code>Public Function user_func_dictionary_loop(Dictionary As Dictionary, _
                 MethodCallback As String, _
                 Optional Params As Variant) As Boolean

    Dim Key As Variant

    For Each Key In Dictionary

        If IsMissing(Params) Then
            Application.Run MethodCallback, Dictionary(Key)
        Else
            Application.Run MethodCallback, user_param_replace(Dictionary(Key), Params)
        End If

    Next Key

End Function
</code>```

If no Parameters are supplied to the function then it simply runs the MethodCallback with the Dictionary's key value. If there are parameters then an additional step is triggered below:

```<code>Private Function user_param_replace(Item As Variant, Optional Params As Variant) As Variant

    Dim i As Long
    Dim strTest As String
    Dim Output As Variant

    Output = replace_dictionary_values(Item, Params)

    If IsArray(Output) Then
        ReDim Preserve Output(0 To UBound(Output))

        user_param_replace = Join(Output, ",")
        Exit Function

    End If

    user_param_replace = Output

End Function

Private Function replace_dictionary_values(Item As Variant, Optional Params As Variant) As Variant

    Dim l As Long
    Dim varTemp() As Variant
    Dim Param_Item As Variant

    l = 0
    If IsMissing(Params) Or Not IsArray(Params) Then
        replace_dictionary_values = Replace$(Params, "{D:Value}", Item)
        Exit Function
    Else

        ReDim varTemp(0 To UBound(Params))

        For Each Param_Item In Params
            varTemp(l) = Replace$(Param_Item, "{D:Value}", Item)
            l = l + 1
        Next Param_Item

    End If

    replace_dictionary_values = varTemp

End Function
</code>```

The steps above allow a user to pass in parameters which contain {D:Value} which will then be replaced with the Dictionary's key value.

I've made a small unit test below with the idea that it should test the functionality of my method. At present I'm getting an "Argument not optional" error:

```<code>Function test_callback_loop_function_works_with_multiple_parameters() As Boolean

    Dim dictTest As New Dictionary

    dictTest.Add 1, "1 - Foo"
    dictTest.Add 2, "2 - Foo"
    dictTest.Add 3, "3 - Foo"

    Dim MyArray(0 To 1) As Variant

    MyArray(0) = "{D:Value}"
    MyArray(1) = "Bar"

    user_func_dictionary_loop dictTest, "custom_debug_print_multiple_params", MyArray

    test_callback_loop_function_works_with_multiple_parameters = True

End Function

Function custom_debug_print_multiple_params(strPrint As String, strPrint2 As String) As String

    Debug.Print strPrint & strPrint2

End Function
</code>```

The output should be:

```<code>1 - FooBar
2 - FooBar
3 - FooBar
</code>```

But I'm getting an

Run-time error '449' - Argument not optional

error on the Application.Run MethodCallback, user_param_replace(Dictionary(Key), Params) line.

My hunch is that because I'm trying to join array elements together with a "," to then pass through as parameters (in the Join(Output, ",") line) to the method, it's causing the test to fail.

So my question is, within VBA, is it possible to join the elements of an array together so they can then be passed, dynamically, to another method/function?

答:
There is a problem with this line of code.

```<code>replace_dictionary_values = Replace$(Params, "{D:Value}", Item)
</code>```

This line is called when IsMissing(Params) = True and, predictably, returns an error.

I also found that your test procedure can't work.

```<code>Function custom_debug_print_multiple_params(strPrint As String, strPrint2 As String) As String

    Debug.Print strPrint & strPrint2

End Function
</code>```

All your variables are variants but the two parameters of the above function are of string type. The arguments should be declared ByVal if variants of string type are to be passed. I recommend to test each function individually and make sure that it works before using its return value as parameters for other functions.

I suspect that part of your problem may be caused by your rather indiscriminate use of variants. For example, the Replace function you invoke in the faulty line quoted above requires 3 strings as arguments. In your code, both Item and Params (if it would exist) are variants. There is a good chance that your plan could actually work, but when something doesn't quite work, as is the case here, all those corners that were cut will have to be checked, adding more time to the debugging effort than could be saved during coding.

In the first example below the calling procedure supplies the two strings required by the called procedure. Variants of string type are passed which are converted to strings by the ByVal argument.

```<code>Function Test_TestPrint() As Boolean

    Dim dictTest As New Scripting.Dictionary
    Dim MyArray(0 To 1) As Variant

    dictTest.Add 1, "1 - Foo"
    dictTest.Add 2, "2 - Foo"
    dictTest.Add 3, "3 - Foo"
    MyArray(0) = "{D:Value}"
    MyArray(1) = "Bar"

    TestPrint MyArray(0), MyArray(1)
'    user_func_dictionary_loop dictTest, "TestPrint", MyArray
    Test_TestPrint = True
End Function

Sub TestPrint(ByVal strPrint As String, ByVal strPrint2 As String)
    Debug.Print strPrint & strPrint2
End Sub
</code>```

In the code below the array is passed to the executing procedure which expects such an array and prints out its elements.

```<code>Function Test_TestPrint2() As Boolean

    Dim dictTest As New Scripting.Dictionary
    Dim MyArray(0 To 1) As Variant

    dictTest.Add 1, "1 - Foo"
    dictTest.Add 2, "2 - Foo"
    dictTest.Add 3, "3 - Foo"
    MyArray(0) = "{D:Value}"
    MyArray(1) = "Bar"

Sub TestPrint2 MyArray
'    user_func_dictionary_loop dictTest, "TestPrint", MyArray
    Test_TestPrint2 = True
End Function
</code>```

Body:
[Update: The question has been formed so that the functions can be copied directly into a VBA module and tested by running the test_callback_loop_function_works_with_multiple_parameters method]

I am using the Application.Run function to dynamically call methods within my VBA. The idea is that this helper will save me looping through dictionaries throughout various functions/subs within my VBA. Instead I can just call the following helper which will do the looping for me:

Public Function user_func_dictionary_loop(Dictionary As Dictionary, _
                 MethodCallback As String, _
                 Optional Params As Variant) As Boolean

    Dim Key As Variant

    For Each Key In Dictionary

        If IsMissing(Params) Then
            Application.Run MethodCallback, Dictionary(Key)
        Else
            Application.Run MethodCallback, user_param_replace(Dictionary(Key), Params)
        End If

    Next Key

End Function

If no Parameters are supplied to the function then it simply runs the MethodCallback with the Dictionary's key value. If there are parameters then an additional step is triggered below:

Private Function user_param_replace(Item As Variant, Optional Params As Variant) As Variant

    Dim i As Long
    Dim strTest As String
    Dim Output As Variant

    Output = replace_dictionary_values(Item, Params)

    If IsArray(Output) Then
        ReDim Preserve Output(0 To UBound(Output))

        user_param_replace = Join(Output, ",")
        Exit Function

    End If

    user_param_replace = Output

End Function

Private Function replace_dictionary_values(Item As Variant, Optional Params As Variant) As Variant

    Dim l As Long
    Dim varTemp() As Variant
    Dim Param_Item As Variant

    l = 0
    If IsMissing(Params) Or Not IsArray(Params) Then
        replace_dictionary_values = Replace$(Params, "{D:Value}", Item)
        Exit Function
    Else

        ReDim varTemp(0 To UBound(Params))

        For Each Param_Item In Params
            varTemp(l) = Replace$(Param_Item, "{D:Value}", Item)
            l = l + 1
        Next Param_Item

    End If

    replace_dictionary_values = varTemp

End Function

The steps above allow a user to pass in parameters which contain {D:Value} which will then be replaced with the Dictionary's key value.

I've made a small unit test below with the idea that it should test the functionality of my method. At present I'm getting an "Argument not optional" error:

Function test_callback_loop_function_works_with_multiple_parameters() As Boolean

    Dim dictTest As New Dictionary

    dictTest.Add 1, "1 - Foo"
    dictTest.Add 2, "2 - Foo"
    dictTest.Add 3, "3 - Foo"

    Dim MyArray(0 To 1) As Variant

    MyArray(0) = "{D:Value}"
    MyArray(1) = "Bar"

    user_func_dictionary_loop dictTest, "custom_debug_print_multiple_params", MyArray

    test_callback_loop_function_works_with_multiple_parameters = True

End Function

Function custom_debug_print_multiple_params(strPrint As String, strPrint2 As String) As String

    Debug.Print strPrint & strPrint2

End Function

The output should be:

1 - FooBar
2 - FooBar
3 - FooBar

But I'm getting an

Run-time error '449' - Argument not optional

error on the Application.Run MethodCallback, user_param_replace(Dictionary(Key), Params) line.

My hunch is that because I'm trying to join array elements together with a "," to then pass through as parameters (in the Join(Output, ",") line) to the method, it's causing the test to fail.

So my question is, within VBA, is it possible to join the elements of an array together so they can then be passed, dynamically, to another method/function?

Body:
There is a problem with this line of code.

replace_dictionary_values = Replace$(Params, "{D:Value}", Item)

This line is called when IsMissing(Params) = True and, predictably, returns an error.

I also found that your test procedure can't work.

Function custom_debug_print_multiple_params(strPrint As String, strPrint2 As String) As String

    Debug.Print strPrint & strPrint2

End Function

All your variables are variants but the two parameters of the above function are of string type. The arguments should be declared ByVal if variants of string type are to be passed. I recommend to test each function individually and make sure that it works before using its return value as parameters for other functions.

I suspect that part of your problem may be caused by your rather indiscriminate use of variants. For example, the Replace function you invoke in the faulty line quoted above requires 3 strings as arguments. In your code, both Item and Params (if it would exist) are variants. There is a good chance that your plan could actually work, but when something doesn't quite work, as is the case here, all those corners that were cut will have to be checked, adding more time to the debugging effort than could be saved during coding.

In the first example below the calling procedure supplies the two strings required by the called procedure. Variants of string type are passed which are converted to strings by the ByVal argument.

Function Test_TestPrint() As Boolean

    Dim dictTest As New Scripting.Dictionary
    Dim MyArray(0 To 1) As Variant

    dictTest.Add 1, "1 - Foo"
    dictTest.Add 2, "2 - Foo"
    dictTest.Add 3, "3 - Foo"
    MyArray(0) = "{D:Value}"
    MyArray(1) = "Bar"

    TestPrint MyArray(0), MyArray(1)
'    user_func_dictionary_loop dictTest, "TestPrint", MyArray
    Test_TestPrint = True
End Function

Sub TestPrint(ByVal strPrint As String, ByVal strPrint2 As String)
    Debug.Print strPrint & strPrint2
End Sub

In the code below the array is passed to the executing procedure which expects such an array and prints out its elements.

Function Test_TestPrint2() As Boolean

    Dim dictTest As New Scripting.Dictionary
    Dim MyArray(0 To 1) As Variant

    dictTest.Add 1, "1 - Foo"
    dictTest.Add 2, "2 - Foo"
    dictTest.Add 3, "3 - Foo"
    MyArray(0) = "{D:Value}"
    MyArray(1) = "Bar"

Sub TestPrint2 MyArray
'    user_func_dictionary_loop dictTest, "TestPrint", MyArray
    Test_TestPrint2 = True
End Function


问:
Vue.js / Mixins - Is there a way to get the global mixin-object outside of the vue component?
I am new with Vue.js

I am using Vue.js 2.4.4.
I have created the global mixin in my app.js file:

```<code>...
import router from './router'
...(some imports and plugins definitions)

Vue.use(VeeValidate);
Vue.component(VuePassword);
...

Vue.mixin({
    data: function(){
        return {
            get auth(){
                return Auth;
            }
        }
    }
    });

const app = new Vue({
    el: '#root',
    template: `<app></app>`,
    components: { App },
    router
});
</code>```

This mixin imports some Auth object with validation methods e.t.c which needed to be in every component.
All of my components can check this mixin and it's working fine.

But I need to check the auth state after every route request, and I want to use my currently existing mixin, so I am trying to make something like this in my router.js file:

```<code>import Vue from 'vue'
import VueRouter from 'vue-router'
...

Vue.use(VueRouter);

const router = new VueRouter({
    routes:[
      ...
    ]
});
router.beforeEach((to, from, next) => {
    if(to.meta.requiresAuth) {
        if(...call to mixin method) {
            next();
        } else {
            next('/');
        }
    } else {
        next();
    }
});

export default router
</code>```

Question:
Is there a way to get the global mixin object and change it's inner values or can you please give some small advise or example what is the right solution to this kind of tasks?
Or should I use the plugins instead of mixins?

答:
I would rather create a seperate file for auth and not make it a mixin. Then using Vue.use() which will set auth on the vue object.
A sample of what the files might look like:

auth.js

```<code>export default function(Vue) {
    Vue.auth = {
        // do your auth logic
    }
}
</code>```

Then in your main js file
main.js

```<code>import Auth from './auth.js'
Vue.use(Auth);
</code>```

Then you should be able to use Vue.auth
Another option would be keep using the mixin and pass the value to a store (like vuex) or create your own if your project is small...

Body:
I am new with Vue.js

I am using Vue.js 2.4.4.
I have created the global mixin in my app.js file:

...
import router from './router'
...(some imports and plugins definitions)

Vue.use(VeeValidate);
Vue.component(VuePassword);
...

Vue.mixin({
    data: function(){
        return {
            get auth(){
                return Auth;
            }
        }
    }
    });

const app = new Vue({
    el: '#root',
    template: `<app></app>`,
    components: { App },
    router
});

This mixin imports some Auth object with validation methods e.t.c which needed to be in every component.
All of my components can check this mixin and it's working fine.

But I need to check the auth state after every route request, and I want to use my currently existing mixin, so I am trying to make something like this in my router.js file:

import Vue from 'vue'
import VueRouter from 'vue-router'
...

Vue.use(VueRouter);

const router = new VueRouter({
    routes:[
      ...
    ]
});
router.beforeEach((to, from, next) => {
    if(to.meta.requiresAuth) {
        if(...call to mixin method) {
            next();
        } else {
            next('/');
        }
    } else {
        next();
    }
});

export default router

Question:
Is there a way to get the global mixin object and change it's inner values or can you please give some small advise or example what is the right solution to this kind of tasks?
Or should I use the plugins instead of mixins?

Body:
I would rather create a seperate file for auth and not make it a mixin. Then using Vue.use() which will set auth on the vue object.
A sample of what the files might look like:

auth.js

export default function(Vue) {
    Vue.auth = {
        // do your auth logic
    }
}

Then in your main js file
main.js

import Auth from './auth.js'
Vue.use(Auth);

Then you should be able to use Vue.auth
Another option would be keep using the mixin and pass the value to a store (like vuex) or create your own if your project is small...


问:
PHP Image Uploaded Name won't change
I have PHP function to upload file (image).

```<code>foreach($_FILES['wallpaperFile']['tmp_name'] as $key => $tmpName)
{
    $file_name = $_FILES['wallpaperFile']['name'][$key];
    $file_type = $_FILES['wallpaperFile']['type'][$key];
    $file_size = $_FILES['wallpaperFile']['size'][$key];
    $file_tmp  = $_FILES['wallpaperFile']['tmp_name'][$key];

    move_uploaded_file($file_tmp,"assets/img/wallpapers/".time().$file_name);
}
</code>```

It's working and I can see the data image uploaded on my folder.

But now how can I set the image file name only time() without .$file_name

If I remove .$file_name, file uploaded is not correct without extension and only 1 file, even though I uploaded 3 files.

Example:

Image file name: 1510750186shubuh.jpg

What I want only

1510750186.jpg

答:
I don't think that the extension of the file is your problem here. It's that time() only has a one-second resolution. It's highly improbable that time() will have a different value in any iteration of that loop. As such all your files have the same name with just time().

It's probably better to use something like microtime(true), which has microsecond fidelity or uniqid() to get a higher resolution in the same request.

```<code>foreach($_FILES['wallpaperFile']['tmp_name'] as $key => $tmpName)
{
    $file_name = $_FILES['wallpaperFile']['name'][$key];
    $file_type = $_FILES['wallpaperFile']['type'][$key];
    $file_size = $_FILES['wallpaperFile']['size'][$key];
    $file_tmp  = $_FILES['wallpaperFile']['tmp_name'][$key];

    /* user either this */
    move_uploaded_file($file_tmp,"assets/img/wallpapers/" . microtime(true));

    /* or this */
    move_uploaded_file($file_tmp,"assets/img/wallpapers/" . uniqid());
}
</code>```

You can see the difference by simply printing the value of both time() and microtime(true) inside that loop to realize the problem that time() would pose on your requirements here.

```<code>foreach($_FILES['wallpaperFile']['tmp_name'] as $key => $tmpName)
{
    echo "time(): ", time(), "<br>\n";
    echo "microtime(true): ", microtime(true), "<br>\n";
    echo "uniqid(): ", uniqid(), "<br>\n";
}
</code>```

Warning

You should never rely on $_FILES['wallpaperFile']['name'] here, because it is user-supplied input, and as such it is vulnerable to manipulation. Avoid allowing the client to possibly exploit/manipulate your filesystem by handing them direct-access to it via this vector. Having a completely random filename on your filesystem, instead, and storing that random name in your database to associate it with some arbitrary user-supplied-input is preferrable, because it allows you to retain full-control over your server's file system while still allowing the user to retain control over their own data.

Title: PHP Image Uploaded Name won't change

Body:
I have PHP function to upload file (image).

foreach($_FILES['wallpaperFile']['tmp_name'] as $key => $tmpName)
{
    $file_name = $_FILES['wallpaperFile']['name'][$key];
    $file_type = $_FILES['wallpaperFile']['type'][$key];
    $file_size = $_FILES['wallpaperFile']['size'][$key];
    $file_tmp  = $_FILES['wallpaperFile']['tmp_name'][$key];

    move_uploaded_file($file_tmp,"assets/img/wallpapers/".time().$file_name);
}

It's working and I can see the data image uploaded on my folder.

But now how can I set the image file name only time() without .$file_name

If I remove .$file_name, file uploaded is not correct without extension and only 1 file, even though I uploaded 3 files.

Example:

Image file name: 1510750186shubuh.jpg

What I want only

1510750186.jpg

Body:
I don't think that the extension of the file is your problem here. It's that time() only has a one-second resolution. It's highly improbable that time() will have a different value in any iteration of that loop. As such all your files have the same name with just time().

It's probably better to use something like microtime(true), which has microsecond fidelity or uniqid() to get a higher resolution in the same request.

foreach($_FILES['wallpaperFile']['tmp_name'] as $key => $tmpName)
{
    $file_name = $_FILES['wallpaperFile']['name'][$key];
    $file_type = $_FILES['wallpaperFile']['type'][$key];
    $file_size = $_FILES['wallpaperFile']['size'][$key];
    $file_tmp  = $_FILES['wallpaperFile']['tmp_name'][$key];

    /* user either this */
    move_uploaded_file($file_tmp,"assets/img/wallpapers/" . microtime(true));

    /* or this */
    move_uploaded_file($file_tmp,"assets/img/wallpapers/" . uniqid());
}

You can see the difference by simply printing the value of both time() and microtime(true) inside that loop to realize the problem that time() would pose on your requirements here.

foreach($_FILES['wallpaperFile']['tmp_name'] as $key => $tmpName)
{
    echo "time(): ", time(), "<br>\n";
    echo "microtime(true): ", microtime(true), "<br>\n";
    echo "uniqid(): ", uniqid(), "<br>\n";
}

Warning

You should never rely on $_FILES['wallpaperFile']['name'] here, because it is user-supplied input, and as such it is vulnerable to manipulation. Avoid allowing the client to possibly exploit/manipulate your filesystem by handing them direct-access to it via this vector. Having a completely random filename on your filesystem, instead, and storing that random name in your database to associate it with some arbitrary user-supplied-input is preferrable, because it allows you to retain full-control over your server's file system while still allowing the user to retain control over their own data.


问:
Popping up a bootstrap model in a Knockout Foreach
I'm attempting to show the user a modal while using Knockout, it seems like whenever it is called from within the foreach, the modal does not work or in the case of a hardcoded link, the contents open in a new page instead of popping out a modal.

Have a look at the fiddle below, the button on line 32 looks like it ignores the click whereas the button on line 37 works as it should

```<code><div class="modal fade" tabindex="-1" role="dialog" data-bind="modal:showDialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h4 class="modal-title">title</h4>

      </div>
      <div class="modal-body">
        body
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary btn-xs" data-bind="click : submit">Close</button>
      </div>
    </div>
  </div>
</div>
<table>

  <thead>
  </thead>
  <tbody data-bind="foreach: SearchOptions" class="table">
    <tr class="gridRowSelect">

      <td>
        <span data-bind="text: id"></span>
      </td>
      <td>
        <span data-bind="text: text"></span>
      </td>
      <td>
        <button data-bind="click: function(){showDialog(true)}">Show</button>
      </td>
    </tr>
  </tbody>
</table>
<button data-bind="click: function(){showDialog(true)}">Show</button>
</code>```

https://jsfiddle.net/slipmatt/ckuqrrnn/2/

答:
You need to prefix the showDialog with the $parent keyword to provide proper binding context

```<code><button data-bind="click: function(){$parent.showDialog(true)}">Show</button>
</code>```

Inside the foreach binding, knockout looks for showDialog inside each AttributeKey object rather than the AttributeViewModel instance. You can prefix it with $root as well, since in this case $parent and $root refer to the AttributeViewModel instance.

Updated fiddle

Body:
I'm attempting to show the user a modal while using Knockout, it seems like whenever it is called from within the foreach, the modal does not work or in the case of a hardcoded link, the contents open in a new page instead of popping out a modal.

Have a look at the fiddle below, the button on line 32 looks like it ignores the click whereas the button on line 37 works as it should

        <button type="button" class="close" data-dismiss="modal">×</button>

title

        body

        <button type="button" class="btn btn-primary btn-xs" data-bind="click : submit">Close</button>

        <button data-bind="click: function(){showDialog(true)}">Show</button>

<button data-bind="click: function(){showDialog(true)}">Show</button>

https://jsfiddle.net/slipmatt/ckuqrrnn/2/

Body:
You need to prefix the showDialog with the $parent keyword to provide proper binding context

<button data-bind="click: function(){$parent.showDialog(true)}">Show</button>

Inside the foreach binding, knockout looks for showDialog inside each AttributeKey object rather than the AttributeViewModel instance. You can prefix it with $root as well, since in this case $parent and $root refer to the AttributeViewModel instance.

Updated fiddle


问:
Sort columns automatically
I have a database-table with some football-matches, 3 per week, and I wrote them in a table like this example:

```<code>week  |team1   |team2   |date1   |time1   |team3  |team4  |date2  |time2  |
46    |Chelsea |Man Utd |18/11   |13:30   |Arsenal|Stoke  |19/11  |18:00  |
</code>```

Then I have this code to call them:

```<code>"SELECT * FROM table_name WHERE week = '$week'";
</code>```

...where $week = Date('W');

```<code>echo $row['team1'].' - '.$row['team2'].'<br />
'.$row['team3'].' - '.$row['team4'].';
</code>```

and so on. But sometimes the date or time changes, so I have to make the whole row again, because else it will still show the first match first, even though the other match will be played first. Let say Chelea - Man Utd is moved to the 20/11 at 18:00. Can I somehow just change the date and time in the row and make the matches rearrange on the front-end?

Sorry if it's a bit difficult to understand what I'm talking about :)

答:
When you are asking about how to redesign or query an existing data structure, please include the definition of the data structure (in your case, the CREATE TABLE statement) as well as examples of the data it contains.

The title of your question talks about sorting - but the body of your question is about how the date/time of a match changes. If you want to control the order in which rows are retrieved from an SQL DBMS, then SQL has a solution for that - specify a ORDER BY clause in your SELECT statement.

But I suspect that your problem is the fact that you are putting details of multiple matches into a single row in your table. This is very wrong.

A table describing matches should only contain one match per row. Arguably, it shouldn't contain teams either (since both teams have the same physical relationship to a match, using different columns to hold them creates an artificial difference) but this is probably overkill for most purposes.

I would implement this as:

```<code>  CREATE TABLE match (
    ondate DATETIME,
    home_team VARCHAR(20),
    away_team VARCHAR(20)
    PRIMARY KEY (ondate, home_team)
  );
</code>```

(it may require other indices depending on usage).

I am assuming that the week can be derived from the datetime (e.g.if a match scheduled for week 40 is postponed by 7 days, it is then considered to be in week 41).

If you want to display all the matches occurring in one week as a row at the front end then, although its possible to format the data this way in the output of a SELECT statement, you should handle this in your PHP code.

Title: Sort columns automatically

Body:
I have a database-table with some football-matches, 3 per week, and I wrote them in a table like this example:

week  |team1   |team2   |date1   |time1   |team3  |team4  |date2  |time2  |
46    |Chelsea |Man Utd |18/11   |13:30   |Arsenal|Stoke  |19/11  |18:00  |

Then I have this code to call them:

"SELECT * FROM table_name WHERE week = '$week'";

...where $week = Date('W');

echo $row['team1'].' - '.$row['team2'].'

'.$row['team3'].' - '.$row['team4'].';

and so on. But sometimes the date or time changes, so I have to make the whole row again, because else it will still show the first match first, even though the other match will be played first. Let say Chelea - Man Utd is moved to the 20/11 at 18:00. Can I somehow just change the date and time in the row and make the matches rearrange on the front-end?

Sorry if it's a bit difficult to understand what I'm talking about :)

Body:
When you are asking about how to redesign or query an existing data structure, please include the definition of the data structure (in your case, the CREATE TABLE statement) as well as examples of the data it contains.

The title of your question talks about sorting - but the body of your question is about how the date/time of a match changes. If you want to control the order in which rows are retrieved from an SQL DBMS, then SQL has a solution for that - specify a ORDER BY clause in your SELECT statement.

But I suspect that your problem is the fact that you are putting details of multiple matches into a single row in your table. This is very wrong.

A table describing matches should only contain one match per row. Arguably, it shouldn't contain teams either (since both teams have the same physical relationship to a match, using different columns to hold them creates an artificial difference) but this is probably overkill for most purposes.

I would implement this as:

  CREATE TABLE match (
    ondate DATETIME,
    home_team VARCHAR(20),
    away_team VARCHAR(20)
    PRIMARY KEY (ondate, home_team)
  );

(it may require other indices depending on usage).

I am assuming that the week can be derived from the datetime (e.g.if a match scheduled for week 40 is postponed by 7 days, it is then considered to be in week 41).

If you want to display all the matches occurring in one week as a row at the front end then, although its possible to format the data this way in the output of a SELECT statement, you should handle this in your PHP code.


问:
How to return multiple values from a function in Kotlin like we do in Swift?
How to return 3 separate data values of the same type (Int) from a function in Kotlin?

I'm attempting to return the time of day, I need to return the Hour, Minute and Second as separate integers, but all in one go from the same function, is this possible?

In swift we do it like following,

```<code>func getTime() -> (Int, Int, Int) {
    ...
    return ( hour, minute, second)
}
</code>```

can we achieve this in Kotlin?

P.S: I know I can use Array or Hashmap for this but I want to know if there exists something in Kotlin like it is in Swift.

答:
You can't create arbitrary tuples in Kotlin, instead, you can use data classes. One option is using the built in Pair and Triple classes that are generic and can hold two or three values, respectively. You can use these combined with destructuring declarations like this:

```<code>fun getPair() = Pair(1, "foo")

val (num, str) = getPair()
</code>```

You can also destructure a List or Array, for up to the first 5 elements:

```<code>fun getList() = listOf(1, 2, 3, 4, 5)

val (a, b, c, d, e) = getList()
</code>```

The most idiomatic way however would be to define your own data class, which allows you to return a meaningful type from your function:

```<code>data class Time(val hour: Int, val minute: Int, val second: Int)

fun getTime(): Time {
    ...
    return Time(hour, minute, second)
}

val (hour, minute, second) = getTime()
</code>```

Body:
How to return 3 separate data values of the same type (Int) from a function in Kotlin?

I'm attempting to return the time of day, I need to return the Hour, Minute and Second as separate integers, but all in one go from the same function, is this possible?

In swift we do it like following,

func getTime() -> (Int, Int, Int) {
    ...
    return ( hour, minute, second)
}

can we achieve this in Kotlin?

P.S: I know I can use Array or Hashmap for this but I want to know if there exists something in Kotlin like it is in Swift.

Body:
You can't create arbitrary tuples in Kotlin, instead, you can use data classes. One option is using the built in Pair and Triple classes that are generic and can hold two or three values, respectively. You can use these combined with destructuring declarations like this:

fun getPair() = Pair(1, "foo")

val (num, str) = getPair()

You can also destructure a List or Array, for up to the first 5 elements:

fun getList() = listOf(1, 2, 3, 4, 5)

val (a, b, c, d, e) = getList()

The most idiomatic way however would be to define your own data class, which allows you to return a meaningful type from your function:

data class Time(val hour: Int, val minute: Int, val second: Int)

fun getTime(): Time {
    ...
    return Time(hour, minute, second)
}

val (hour, minute, second) = getTime()


答:
If you open your browser console, you'll see an error:

Uncaught ReferenceError: showDialog is not defined

This is because the first button is within a foreach binding, and so is looking for the showDialog function to exist on the AttributeKey item itself.  You instead need to point it to the parent context:

```<code><button data-bind="click: function(){$parent.showDialog(true)}">Show</button>
</code>```

Since the parent is also the root model, you can use that too:

```<code><button data-bind="click: function(){$root.showDialog(true)}">Show</button>
</code>```

This is useful in cases where you have multiple nested bindings and need to go directly back to your root model.

Title: Popping up a bootstrap model in a Knockout Foreach

Body:
If you open your browser console, you'll see an error:

Uncaught ReferenceError: showDialog is not defined

This is because the first button is within a foreach binding, and so is looking for the showDialog function to exist on the AttributeKey item itself.  You instead need to point it to the parent context:

<button data-bind="click: function(){$parent.showDialog(true)}">Show</button>

Since the parent is also the root model, you can use that too:

<button data-bind="click: function(){$root.showDialog(true)}">Show</button>

This is useful in cases where you have multiple nested bindings and need to go directly back to your root model.


问:
Data item current values not updated: internal-work queues get next item: blueprism
I am following a tutorial for blueprism (beginner). In the tutorial, I am asked to create a process, add an action stage and use the internal business object called work queues, with the action get next item. In the outputs tab of this get next item action, I used the auto-generate buttons in the Store In column to create the output data items.
After saving and running the process, these data items are supposed to be populated and have current values. However, my data items don't hold any current values. Can someone explain why?
Also, after publishing the process and refreshing the control room, I am not able to see the queue items in my queue management tab. I have attached here the pictures of the following:
Process-Page | Get Item Action properties | Queue Management</p>

答:
Could you please check if there are any pending items in queue?

If there are no pending items, then using action "Get next item" returns blank values.


问:
Best .NET Solution for Frequently Changed Database
I am currently architecting a small CRUD applicaton. Their database is a huge mess and will be changing frequently over the course of the next 6 months to a year. What would you recommend for my data layer:

1) ORM (if so, which one?)

2) Linq2Sql

3) Stored Procedures

4) Parametrized Queries

I really need a solution that will be dynamic enough (both fast and easy) where I can replace tables and add/delete columns frequently.

Note: I do not have much experience with ORM (only a little SubSonic) and generally tend to use stored procedures so maybe that would be the way to go. I would love to learn Ling2Sql or NHibernate if either would allow for the situation I've described above.

答:
EntitySpaces can regenerate your DAL/Business Layer in one minute, and no code loss, see the trial version ==> HERE

No Registration Necessary, runs under Visual Studio as well.

OwnerDisplayName: sestocker

LastEditorDisplayName: sestocker

OwnerDisplayName: Mike Griffin


问:
how to create LWUIT res file?
```<code>Resources res = Resources.open("/myTheme.res");
UIManager.getInstance().setThemeProps(res.getTheme("myTheme"));
</code>```

hi I need to open my resource file in LWUIT but how to create a resource file in the first place?

答:
There is also some excellent tutorials on how to create a LWUIT resource file on the Shais LWUIT blog

http://lwuit.blogspot.com/search/label/LWUIT%20GUIBuilder%20ResourceEditor%20tutorial

Title: how to create LWUIT res file?

Body:
Resources res = Resources.open("/myTheme.res");
UIManager.getInstance().setThemeProps(res.getTheme("myTheme"));

hi I need to open my resource file in LWUIT but how to create a resource file in the first place?


问:
Django image attribute has no file associated with it REST API
I have a model Employee with an ImageField, and I return REST API response of the model but it shows this error

```<code>The 'face_image' attribute has no file associated with it.
</code>```

My API generates a response this way:
https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py

```<code>@api_view(['GET'])
def get_employee(request):
    data = [emp.as_dict() for emp in Employee.objects.all()]
    return Response(data, status=status.HTTP_200_OK)
</code>```

The following is the model:

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py

```<code>class Employee(models.Model):
    ...
    face_image = models.ImageField(upload_to='face_image/', blank=True)

    def face_image_url(self):
        if self.face_image and hasattr(self.face_image, 'url'):
            return self.face_image.url

    def as_dict(self):
        return {"id":self.id,
                ...
                "face_image":self.face_image.url, <-- causes no file associated
                ...}
</code>```

How do I solve this REST response handling imagefield without file ? I tried to follow some ways in here Django The 'image' attribute has no file associated with it but I cant accomplish with the helper function.

If I remove the imagefield, it will generate a response this way https://imgur.com/a/JzQrD. But I want the imagefield to be in the structure, how to handle in this does not exist file situation

答:
You need to explicitly handle this case. In this case, your as_dict method should look like:

```<code>def as_dict(self):
    return {"id":self.id,
            ...
            "face_image": self.face_image.url if self.face_image else None
            ...}
</code>```

Body:
I have a model Employee with an ImageField, and I return REST API response of the model but it shows this error

The 'face_image' attribute has no file associated with it.

My API generates a response this way:
https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py

@api_view(['GET'])
def get_employee(request):
    data = [emp.as_dict() for emp in Employee.objects.all()]
    return Response(data, status=status.HTTP_200_OK)

The following is the model:

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py

class Employee(models.Model):
    ...
    face_image = models.ImageField(upload_to='face_image/', blank=True)

    def face_image_url(self):
        if self.face_image and hasattr(self.face_image, 'url'):
            return self.face_image.url

    def as_dict(self):
        return {"id":self.id,
                ...
                "face_image":self.face_image.url, <-- causes no file associated
                ...}

How do I solve this REST response handling imagefield without file ? I tried to follow some ways in here Django The 'image' attribute has no file associated with it but I cant accomplish with the helper function.

If I remove the imagefield, it will generate a response this way https://imgur.com/a/JzQrD. But I want the imagefield to be in the structure, how to handle in this does not exist file situation

Body:
You need to explicitly handle this case. In this case, your as_dict method should look like:

def as_dict(self):
    return {"id":self.id,
            ...
            "face_image": self.face_image.url if self.face_image else None
            ...}


问:
i want to display two popups, one for error message and other for success message
I'm new to modals, i want to submit a form and then show success popup if user form is validated else want to show error popup. Also my it should execute php file for sending the email to user in background.
So, far i'm successful in executing the php file in background and show the model when user clicks on submit button.
But i want the popup to show when the form is validated. Also i want to use type="submit" instead of type="button" for form submit.

Here's my code :

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <form class="well" action="" method="">
  <div class="form-group col-md-6">
        <label for="inputPassword4">Full Name</label>
        <input type="text" name="name" class="form-control" id="inputPassword4" placeholder="Enter Full Name">
      </div>
    </div>
    <div class="form-row">
      <div class="form-group col-md-6">
        <label for="inputEmail4">Phone Number</label>
        <input type="number" name="mobile" class="form-control" id="inputEmail4" placeholder="Enter Mobile Number">
      </div>
      <div class="form-group col-md-6">
        <label for="inputPassword4">Email</label>
        <input type="email" name="email" class="form-control" id="inputPassword4" placeholder="Enter Your Email">
      </div>
    </div>
    <button type="button" class="btn btn-primary" onclick="executePhp()" style="margin-left: 3%;"
    data-toggle="modal" data-target="#myModal">Check</button>
  </form>

    <!--  Code for popup -->

        <!-- Modal -->
        <div class="modal fade mymodal" id="myModal" role="dialog">
          <div class="modal-dialog mydialog">

            <!-- Modal content-->
            <div class="modal-content mycontent">
              <div class="modal-header myheader">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h3 class="modal-title">Message</h3>
              </div>
              <div class="modal-body mybody">
                <br>
                <br>
                <h3>Thanks for choosing</h3>
                <h4>
                  Your details will arive by email.
                  Sit back, we'll get back to you soon.
                </h4>
                <br>
                <br>
              </div>
              <div class="modal-footer myfooter">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
              </div>
            </div>

          </div>
         </div>

    <!--  Code for popup end--></code>```

Thank you.

答:
You can use Jquery to achieve this.
In you php you can have two variables before the validation like:

```<code>$popup_message = "";
$popup_message_color = "";
</code>```

Now if the form is validated you can display the modal like this:

```<code>  $popup_message = "login successfully.";
  $popup_message_color = "success";
    //Open Modal
    echo "<script type='text/javascript'>
    $(document).ready(function(){
    $('#myModal').modal('show');
    });
    </script>";
</code>```

In the modal body you can display the message and color.

```<code><div class="modal-body">
    <p class="text-<?php echo $popup_message_color; ?>"><?php echo $popup_message; ?></p>
</div>
</code>```

The same would be done for if validation fails, just change your message and color to $popup_message_color = "danger";

Note If you are validation to another page then the modal should be in that page and you change the close buttons to a link to go back.
Also php script should come after you loaded the jquery.

Body:
I'm new to modals, i want to submit a form and then show success popup if user form is validated else want to show error popup. Also my it should execute php file for sending the email to user in background.
So, far i'm successful in executing the php file in background and show the model when user clicks on submit button.
But i want the popup to show when the form is validated. Also i want to use type="submit" instead of type="button" for form submit.

Here's my code :

  <form class="well" action="" method="">

        Full Name
        <input type="text" name="name" class="form-control" id="inputPassword4" placeholder="Enter Full Name">

        Phone Number
        <input type="number" name="mobile" class="form-control" id="inputEmail4" placeholder="Enter Mobile Number">

        Email
        <input type="email" name="email" class="form-control" id="inputPassword4" placeholder="Enter Your Email">

    <button type="button" class="btn btn-primary" onclick="executePhp()" style="margin-left: 3%;"
    data-toggle="modal" data-target="#myModal">Check</button>
  </form>

                <button type="button" class="close" data-dismiss="modal">×</button>

Message

Thanks for choosing

                  Your details will arive by email.
                  Sit back, we'll get back to you soon.

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Thank you.

Body:
You can use Jquery to achieve this.
In you php you can have two variables before the validation like:

$popup_message = "";
$popup_message_color = "";

Now if the form is validated you can display the modal like this:

  $popup_message = "login successfully.";
  $popup_message_color = "success";
    //Open Modal
    echo "<script type='text/javascript'>
    $(document).ready(function(){
    $('#myModal').modal('show');
    });
    </script>";

In the modal body you can display the message and color.

<div class="modal-body">
    <p class="text-<?php echo $popup_message_color; ?>"><?php echo $popup_message; ?></p>
</div>

The same would be done for if validation fails, just change your message and color to $popup_message_color = "danger";

Note If you are validation to another page then the modal should be in that page and you change the close buttons to a link to go back.
Also php script should come after you loaded the jquery.


问:
mysql - woocomerce how to fetch products in a category
I'm writing a web service , I need to fetch all products in a category , I've written this so far :

```<code>   SELECT *,ID, `post_date` ,  `post_title` ,  `post_content` ,  `guid` FROM  `wp_posts` as post

INNER JOIN wp_term_relationships rs ON rs.object_id = post.ID
INNER JOIN wp_terms t ON t.term_id = rs.term_taxonomy_id

WHERE  `post_type` =  'product'
AND  `post_status` =  'publish'
AND rs.term_taxonomy_id =909
</code>```

the code return 3 items but the problem is , i've about 20 products in this category in my website and in the website it shows all these 20 products .

what is wrong with this code? how can I get all products in a category ?
by the way , I'm using woocomrce api either , if I can use it .

答:
You can get all product related to specific category by using below custom query

```<code> //your custom category id
 $cat_ids          =   123;
 $conn          =   new mysqli($servername, $username, $password,$database);

 $get_pro_by_cat   =   'SELECT ID, `post_title` FROM  `wp_posts` as post
                       INNER JOIN wp_term_relationships rs ON rs.object_id =
                       post.ID WHERE  `post_type` =  "product" AND `post_status`
                       =  "publish" AND rs.term_taxonomy_id  =' .$cat_ids.'
                       ORDER BY post_title';

$avail_products = $conn->query($get_pro_by_cat);
</code>```

NOTE: Replace your table prefix with wp_ table prefix in above query
wp_posts.

You can see the demo at this url : http://cadjewelrygallery.com/ .
I hope it will help you.

Body:
I'm writing a web service , I need to fetch all products in a category , I've written this so far :

   SELECT *,ID, `post_date` ,  `post_title` ,  `post_content` ,  `guid` FROM  `wp_posts` as post

INNER JOIN wp_term_relationships rs ON rs.object_id = post.ID
INNER JOIN wp_terms t ON t.term_id = rs.term_taxonomy_id

WHERE  `post_type` =  'product'
AND  `post_status` =  'publish'
AND rs.term_taxonomy_id =909

the code return 3 items but the problem is , i've about 20 products in this category in my website and in the website it shows all these 20 products .

what is wrong with this code? how can I get all products in a category ?
by the way , I'm using woocomrce api either , if I can use it .

Body:
You can get all product related to specific category by using below custom query

 //your custom category id
 $cat_ids          =   123;
 $conn          =   new mysqli($servername, $username, $password,$database);

 $get_pro_by_cat   =   'SELECT ID, `post_title` FROM  `wp_posts` as post
                       INNER JOIN wp_term_relationships rs ON rs.object_id =
                       post.ID WHERE  `post_type` =  "product" AND `post_status`
                       =  "publish" AND rs.term_taxonomy_id  =' .$cat_ids.'
                       ORDER BY post_title';

$avail_products = $conn->query($get_pro_by_cat);

NOTE: Replace your table prefix with wp_ table prefix in above query
wp_posts.

You can see the demo at this url : http://cadjewelrygallery.com/ .
I hope it will help you.


问:
Same font except its weight seems different on different browsers
The text is correctly displayed in Chrome. I want it to display this way in all browsers. How can I do this?

I was able to fix this in Safari with -webkit-font-smoothing: antialiased;

Chrome:

Firefox:

h1 {
    font-family: Georgia;
    font-weight: normal;
    font-size: 16pt;
    color: #444444;
    -webkit-font-smoothing: antialiased;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Hi, my name</h1></code>```

And a JSFiddle: http://jsfiddle.net/jnxQ8/1/

答:
I collected and tested discussed solutions:

Windows10 Prof x64:

```<code>* FireFox v.56.0 x32
* Opera v.49.0
* Google Chrome v.61.0.3163.100 x64-bit
</code>```

macOs X Serra v.10.12.6 Mac mini (Mid 2010):

```<code>* Safari v.10.1.2(12603.3.8)
* FireFox v.57.0 Quantum
* Opera v49.0
</code>```

Semi (still micro fat in Safari) solved fatty fonts:

```<code>text-transform: none; // mac ff fix
-webkit-font-smoothing: antialiased; // safari mac nicer
-moz-osx-font-smoothing: grayscale; // fix fatty ff on mac
</code>```

Have no visual effect

```<code>line-height: 1;
text-rendering: optimizeLegibility;
speak: none;
font-style: normal;
font-variant: normal;
</code>```

Wrong visual effect:

```<code>-webkit-font-smoothing: subpixel-antialiased !important; //more fatty in safari
text-rendering: geometricPrecision !important; //more fatty in safari
</code>```

do not forget to set !important when testing or be sure that your style is not overridden

Body:
The text is correctly displayed in Chrome. I want it to display this way in all browsers. How can I do this?

I was able to fix this in Safari with -webkit-font-smoothing: antialiased;

Chrome:

Firefox:

h1 {
    font-family: Georgia;
    font-weight: normal;
    font-size: 16pt;
    color: #444444;
    -webkit-font-smoothing: antialiased;
}

Hi, my name

And a JSFiddle: http://jsfiddle.net/jnxQ8/1/

Body:
I collected and tested discussed solutions:

Windows10 Prof x64:

* FireFox v.56.0 x32
* Opera v.49.0
* Google Chrome v.61.0.3163.100 x64-bit

macOs X Serra v.10.12.6 Mac mini (Mid 2010):

* Safari v.10.1.2(12603.3.8)
* FireFox v.57.0 Quantum
* Opera v49.0

Semi (still micro fat in Safari) solved fatty fonts:

text-transform: none; // mac ff fix
-webkit-font-smoothing: antialiased; // safari mac nicer
-moz-osx-font-smoothing: grayscale; // fix fatty ff on mac

Have no visual effect

line-height: 1;
text-rendering: optimizeLegibility;
speak: none;
font-style: normal;
font-variant: normal;

Wrong visual effect:

-webkit-font-smoothing: subpixel-antialiased !important; //more fatty in safari
text-rendering: geometricPrecision !important; //more fatty in safari

do not forget to set !important when testing or be sure that your style is not overridden


问:
jquery radio button change event not working
I want to display some form when the specific radio button is checked and to hide it when user selects other radio button

```<code><div class="col-sm-6" id="addresses">
  <input type="radio" name="deco_request[address]" value="value["id"]"> Some address<br>
  <input type="radio" name="deco_request[address]" value="other" id="other-address"> Other Address<br>
</div>
</code>```

js code:

```<code>$("#other-address").on("change", function() {
  if ($("#other-address").is(':checked')) {
    return $("#new-address").show();
  } else {
    return $("#new-address").hide();
  }
});
</code>```

from what I see the change event is not firing up, I also tried click event but didn't have any success with it too, also I noticed when I check the radio button no checked attributes is added but .is(':checked') returns true

答:
Using this you can do your issue solved

```<code>$('.radio').change(function(){
        if ($("#other-address").is(':checked')) {
          $("#new-address").show();
        } else {
          $("#new-address").hide();
          }
    });
</code>```

$('.radio').change(function(){
        if ($("#other-address").is(':checked')) {
          $("#new-address").show();
        } else {
          $("#new-address").hide();
          }
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#new-address{
display:none;}</code>```

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <input type="radio" class="radio" name="deco_request[address]" value="value["id"]"> Some address

  <input type="radio" class="radio" name="deco_request[address]" value="other" id="other-address"> Other Address

Hi

```

Body:
I want to display some form when the specific radio button is checked and to hide it when user selects other radio button

  <input type="radio" name="deco_request[address]" value="value["id"]"> Some address

  <input type="radio" name="deco_request[address]" value="other" id="other-address"> Other Address

js code:

$("#other-address").on("change", function() {
  if ($("#other-address").is(':checked')) {
    return $("#new-address").show();
  } else {
    return $("#new-address").hide();
  }
});

from what I see the change event is not firing up, I also tried click event but didn't have any success with it too, also I noticed when I check the radio button no checked attributes is added but .is(':checked') returns true

Body:
Using this you can do your issue solved

$('.radio').change(function(){
        if ($("#other-address").is(':checked')) {
          $("#new-address").show();
        } else {
          $("#new-address").hide();
          }
    });

$('.radio').change(function(){
        if ($("#other-address").is(':checked')) {
          $("#new-address").show();
        } else {
          $("#new-address").hide();
          }
    });

#new-address{
display:none;}

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="col-sm-6" id="addresses">
  <input type="radio" class="radio" name="deco_request[address]" value="value[&quot;id&quot;]"> Some address<br>
  <input type="radio" class="radio" name="deco_request[address]" value="other" id="other-address"> Other Address<br>
</div>

<div id="new-address">
Hi
</div>


问:
Responsive Design using md-grid-list in angular 2
I am looking at basic example of md-grid-list in Angular 2.

HTML Code :

```<code><md-grid-list cols="4" rowHeight="100px">
   <md-grid-tile *ngFor="let tile of tiles"
         [colspan]="tile.cols"
         [rowspan]="tile.rows"
         [style.background]="tile.color">
         {{tile.text}}
    </md-grid-tile>
</md-grid-list>
</code>```

TS Code :

```<code>export class GridListDynamicExample {
  tiles = [
    {text: 'One', cols: 3, rows: 1, color: 'lightblue'},
    {text: 'Two', cols: 1, rows: 2, color: 'lightgreen'},
    {text: 'Three', cols: 1, rows: 1, color: 'lightpink'},
    {text: 'Four', cols: 2, rows: 1, color: '#DDBDF1'},
  ];
}
</code>```

The above code results in this :

How can I make the layout as "column" that is column "Two" to go below the rows(One and Four) on smaller screen size using some HTML directive or CSS?

Angular Material in Angular 1 had option to achieve by specifying "md-cols-xs="1" md-cols-sm="2" md-cols-md="4" md-cols-gt-md="6" ".

答:
Making responsive design in angular 4 is not as simple as it is in bootstrape. To make md-grid-list responsive or should change view according to device width then we need to use flex layout library

To have clearity about how reponsive things work in angular visit below links

visit http://brianflove.com/2017/05/03/responsive-angular/

demo http://run.plnkr.co/preview/cja10xr7900083b5wx6srd0r6/

Body:
I am looking at basic example of md-grid-list in Angular 2.

HTML Code :

<md-grid-list cols="4" rowHeight="100px">
   <md-grid-tile *ngFor="let tile of tiles"
         [colspan]="tile.cols"
         [rowspan]="tile.rows"
         [style.background]="tile.color">
         {{tile.text}}
    </md-grid-tile>
</md-grid-list>

TS Code :

export class GridListDynamicExample {
  tiles = [
    {text: 'One', cols: 3, rows: 1, color: 'lightblue'},
    {text: 'Two', cols: 1, rows: 2, color: 'lightgreen'},
    {text: 'Three', cols: 1, rows: 1, color: 'lightpink'},
    {text: 'Four', cols: 2, rows: 1, color: '#DDBDF1'},
  ];
}

The above code results in this :

How can I make the layout as "column" that is column "Two" to go below the rows(One and Four) on smaller screen size using some HTML directive or CSS?

Angular Material in Angular 1 had option to achieve by specifying "md-cols-xs="1" md-cols-sm="2" md-cols-md="4" md-cols-gt-md="6" ".


问:
Best web-programming language for math-problems generator
Firstly I am new in web programming but have knowledge in Java,C++, and HTML
I have a project for my college, in which I'll be making some sort of math-problems generator using web-programming language. It is something like www.wamap.org or basically it generates math problems based on the data stored in the database, generates the solutions, and compare them with students' solution.
What would be the best language to use? I mean the one that is more convenient if I have experience in desktop programming. I am thinking of PHP right now, but a friend said Ruby on Rails would also make a great choice. I read a little bit about rails and I think it is more suitable for view-oriented web application which in this case is not my project. Any suggestions are really appreciated.

Regards,

Denny Harijanto

答:
Ruby is a powerful language and could certainly be used to solve your problem. While I'm a fan of it that doesn't necessarily make it a great fit

The Rails framework is an excellent guide to writing well structured web apps based around a REST model, typically backed by some form of SQL database. To my uninformed understanding of your problem this sounds like a good match for what you want to do. There's nothing I consider particularly "view oriented" about a Rails app compared to any other web application. For example I would still suggest Rails for a project which only intends to expose a RESTfull API and does not serve any html pages.