问:
Combine rows on case when with non numeric
HI all i'm trying to get all rows rolled up to one. I have tried MAX Case when but there is a non numeric string in the case when and it isn't working to roll up the data. I have tried to find other examples but can't so i'm asking for your help. Thanks in advance

I have two fields that have different data but all have the same control number and i need to get all data for the control number rolled into one row.

```<code>SELECT CNTL_NUM
  ,TRANS_TYP
  ,CASE WHEN SEQ_NUM = '02' THEN SUBSTRING(TRANS_INFO,28,9) END AS 'SSN'
  ,CASE WHEN SEQ_NUM = '11' THEN SUBSTRING(TRANS_INFO,46,2) END AS 'IPS_STATE'
  FROM LVJPROD.IPS_LNA
  WHERE TRANS_TYP = 'TA'
  GROUP BY CNTL_NUM, TRANS_TYP,SEQ_NUM,TRANS_INFO
  order by CNTL_NUM
</code>```

I am hoping to get all 6 lines rolled up to one from the screen shot below

答:
You can group them again. The problem is with the case statement where it manipulates data. So you need to treat these as a subquery and have a grouping in the outer query and the MAX should work

```<code>WITH yourtable
 AS (SELECT cntl_num,
            trans_typ,
            CASE
              WHEN seq_num = '02' THEN Substring(trans_info, 28, 9)
            END AS ssn,
            CASE
              WHEN seq_num = '11' THEN Substring(trans_info, 46, 2)
            END AS ips_state
     FROM   lvjprod.ips_lna
     WHERE  trans_typ = 'TA'
     GROUP  BY cntl_num,
               trans_typ,
               seq_num,
               trans_info)
SELECT cntl_num,
       trans_typ,
       Max(ssn),
       Max(ips_state)
FROM   yourtable
GROUP  BY cntl_num,
          trans_typ
ORDER  BY cntl_num;
</code>```

OR

```<code>SELECT cntl_num,
       trans_typ,
       Max(ssn),
       Max(ips_state)
FROM   (SELECT cntl_num,
               trans_typ,
               CASE
                 WHEN seq_num = '02' THEN Substring(trans_info, 28, 9)
               END AS ssn,
               CASE
                 WHEN seq_num = '11' THEN Substring(trans_info, 46, 2)
               END AS ips_state
        FROM   lvjprod.ips_lna
        WHERE  trans_typ = 'TA'
        GROUP  BY cntl_num,
                  trans_typ,
                  seq_num,
                  trans_info) a
GROUP  BY cntl_num,
          trans_typ
ORDER  BY cntl_num;
</code>```

Body:
HI all i'm trying to get all rows rolled up to one. I have tried MAX Case when but there is a non numeric string in the case when and it isn't working to roll up the data. I have tried to find other examples but can't so i'm asking for your help. Thanks in advance

I have two fields that have different data but all have the same control number and i need to get all data for the control number rolled into one row.

SELECT CNTL_NUM
  ,TRANS_TYP
  ,CASE WHEN SEQ_NUM = '02' THEN SUBSTRING(TRANS_INFO,28,9) END AS 'SSN'
  ,CASE WHEN SEQ_NUM = '11' THEN SUBSTRING(TRANS_INFO,46,2) END AS 'IPS_STATE'
  FROM LVJPROD.IPS_LNA
  WHERE TRANS_TYP = 'TA'
  GROUP BY CNTL_NUM, TRANS_TYP,SEQ_NUM,TRANS_INFO
  order by CNTL_NUM

I am hoping to get all 6 lines rolled up to one from the screen shot below

Body:
You can group them again. The problem is with the case statement where it manipulates data. So you need to treat these as a subquery and have a grouping in the outer query and the MAX should work

WITH yourtable
 AS (SELECT cntl_num,
            trans_typ,
            CASE
              WHEN seq_num = '02' THEN Substring(trans_info, 28, 9)
            END AS ssn,
            CASE
              WHEN seq_num = '11' THEN Substring(trans_info, 46, 2)
            END AS ips_state
     FROM   lvjprod.ips_lna
     WHERE  trans_typ = 'TA'
     GROUP  BY cntl_num,
               trans_typ,
               seq_num,
               trans_info)
SELECT cntl_num,
       trans_typ,
       Max(ssn),
       Max(ips_state)
FROM   yourtable
GROUP  BY cntl_num,
          trans_typ
ORDER  BY cntl_num;

OR

SELECT cntl_num,
       trans_typ,
       Max(ssn),
       Max(ips_state)
FROM   (SELECT cntl_num,
               trans_typ,
               CASE
                 WHEN seq_num = '02' THEN Substring(trans_info, 28, 9)
               END AS ssn,
               CASE
                 WHEN seq_num = '11' THEN Substring(trans_info, 46, 2)
               END AS ips_state
        FROM   lvjprod.ips_lna
        WHERE  trans_typ = 'TA'
        GROUP  BY cntl_num,
                  trans_typ,
                  seq_num,
                  trans_info) a
GROUP  BY cntl_num,
          trans_typ
ORDER  BY cntl_num;


来源: stackexchange

问:
CSS Semicircle with segments
I am trying to create a semicircle with 5 segments, as shown in the image below, where I can easily adjust the spacing between various segments and the size of the segments themselves.

CSS Semicircle Example

I'm very much a novice at frontend development, but I have tried several resources, so as to figure this out on my own before coming here:

Building a Circular Navigation with CSS Transforms

Segments in a circle using CSS3

A ton of codepen pens.

I need help with a simple and pure CSS solution that doesn't involve working with a crazy ton of math by way of mixins or rolling a SVG solution.

Any help would be appreciated... I've been at this for 3 days and this is pretty much a last resort.

答:
So, I've taken this from a previous answer and modified it a bit to get it into the right sort of shape.

The spacing between each segment will be difficult without using something like SVG because of the limitations that CSS has.

It's not perfect and it will be difficult to make it perfect with just pure CSS.

.wheel,
.umbrella,
.color {
  content: "";
  position: absolute;
  border-radius: 50%;
  width: 15em;
  height: 15em;
  margin: 0;
  padding: 0;
}
.wheel {
  overflow: hidden;
  width: 15em;
  height: 15em;
  position: relative;
  border: 1px solid black;
  transform: rotate(270deg);
  padding: 3px;
}
.umbrella {
  position: relative;
  -webkit-transform: scale(1.35);
  margin: 3px;
  padding: 5px;
}
.color,
.color:nth-child(n+7):after {
  clip: rect(0, 15em, 15em, 7.5em);
}
.color:after,
.color:nth-child(n+7) {
  content: "";
  position: absolute;
  border-radius: 50%;
  left: calc(50% - 7.5em);
  top: calc(50% - 7.5em);
  width: 15em;
  height: 15em;
  clip: rect(0, 7.5em, 15em, 0);
}
.color:nth-child(1):after {
  background-color: #9ED110;
  transform: rotate(30deg);
  z-index: 12;
}
.color:nth-child(2):after {
  background-color: #50B517;
  transform: rotate(60deg);
  z-index: 11;
}
.color:nth-child(3):after {
  background-color: #179067;
  transform: rotate(90deg);
  z-index: 10;
}
.color:nth-child(4):after {
  background-color: #476EAF;
  transform: rotate(120deg);
  z-index: 9;
}
.color:nth-child(5):after {
  background-color: #9f49ac;
  transform: rotate(150deg);
  z-index: 8;
}
.color:nth-child(6):after {
  background-color: #CC42A2;
  transform: rotate(180deg);
  z-index: 7;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wheel">
  <ul class="umbrella">
    <li class="color"></li>
    <li class="color"></li>
    <li class="color"></li>
    <li class="color"></li>
    <li class="color"></li>
    <li class="color"></li>
  </ul>
</div></code>```

An alternative would be to make a single SVG shape which is then referenced as a clip-path in CSS. The above code would stay pretty much the exact same, it would just be the change of how the shape is generated.

ContentLicense: CC BY-SA 3.0

Title: CSS Semicircle with segments

Body:
So, I've taken this from a previous answer and modified it a bit to get it into the right sort of shape.

The spacing between each segment will be difficult without using something like SVG because of the limitations that CSS has.

It's not perfect and it will be difficult to make it perfect with just pure CSS.

.wheel,
.umbrella,
.color {
  content: "";
  position: absolute;
  border-radius: 50%;
  width: 15em;
  height: 15em;
  margin: 0;
  padding: 0;
}
.wheel {
  overflow: hidden;
  width: 15em;
  height: 15em;
  position: relative;
  border: 1px solid black;
  transform: rotate(270deg);
  padding: 3px;
}
.umbrella {
  position: relative;
  -webkit-transform: scale(1.35);
  margin: 3px;
  padding: 5px;
}
.color,
.color:nth-child(n+7):after {
  clip: rect(0, 15em, 15em, 7.5em);
}
.color:after,
.color:nth-child(n+7) {
  content: "";
  position: absolute;
  border-radius: 50%;
  left: calc(50% - 7.5em);
  top: calc(50% - 7.5em);
  width: 15em;
  height: 15em;
  clip: rect(0, 7.5em, 15em, 0);
}
.color:nth-child(1):after {
  background-color: #9ED110;
  transform: rotate(30deg);
  z-index: 12;
}
.color:nth-child(2):after {
  background-color: #50B517;
  transform: rotate(60deg);
  z-index: 11;
}
.color:nth-child(3):after {
  background-color: #179067;
  transform: rotate(90deg);
  z-index: 10;
}
.color:nth-child(4):after {
  background-color: #476EAF;
  transform: rotate(120deg);
  z-index: 9;
}
.color:nth-child(5):after {
  background-color: #9f49ac;
  transform: rotate(150deg);
  z-index: 8;
}
.color:nth-child(6):after {
  background-color: #CC42A2;
  transform: rotate(180deg);
  z-index: 7;
}

<div class="wheel">
  <ul class="umbrella">
    <li class="color"></li>
    <li class="color"></li>
    <li class="color"></li>
    <li class="color"></li>
    <li class="color"></li>
    <li class="color"></li>
  </ul>
</div>

An alternative would be to make a single SVG shape which is then referenced as a clip-path in CSS. The above code would stay pretty much the exact same, it would just be the change of how the shape is generated.


问:
differentiating inputs by user in JOptionPane
I want to write a program in which a box is shown to user and asks to enter a name.

If the name is typed correctly (real name), final message comes up but if for instance the user types an integer, the program asks the user to type a real name in String again.

Code :

```<code>import javax.swing.*;

public class Project018 {
    public static void main(String[] args) {

    String name = JOptionPane.showInputDialog("What is your name?");

    try {

    int number = Integer.parseInt(name);

        } catch (NumberFormatException n){

             JOptionPane.showMessageDialog(null, "Dear " + name + "\nwelcome to java programming course");
        }

    String message = String.format("your name must not contain any number");

        JOptionPane.showMessageDialog(null, message);
    }

}
</code>```

I want to know how I can loop back the program to the top when the user types an integer and how I can skip the second message when a real name is entered

答:
I want to know how I can loop back the program to the top when the user types an integer

Well, for this I would use a do-while loop.

For checking if the input is / has numbers, you shouldn't do it trying to parse the numbers to integer. Instead I would use a Pattern with a Matcher and regex. Otherwise you're not considering this case: Foo123

In this case something like: [0-9]+ for the regex, and if the Matcher matches with it, then it has a number.

how I can skip the second message when a real name is entered

Based on if the Matcher matches something you show one dialog or the other

For example:

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class LoopingJOptionPane {
    private static final String REGEX = "[0-9]+";

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new LoopingJOptionPane()::createAndShowGui);
    }

    private void createAndShowGui() {
        boolean found = true;
        do { //This repeats this code if input is incorrect
            Pattern pattern = Pattern.compile(REGEX);

            String name = JOptionPane.showInputDialog("Enter your name");
            Matcher matcher = pattern.matcher(name); //We try to find if there's a number in our string

            found = matcher.find();

            if (found) { //If there's a number, show this message
                JOptionPane.showMessageDialog(null, "Please write only letters");
            } else { //Otherwise show this one
                JOptionPane.showMessageDialog(null, "Welcome " + name);
            }
        } while (found); //If it has no numbers, don't repeat
    }
}
</code>```

Body:
I want to write a program in which a box is shown to user and asks to enter a name.

If the name is typed correctly (real name), final message comes up but if for instance the user types an integer, the program asks the user to type a real name in String again.

Code :

import javax.swing.*;

public class Project018 {
    public static void main(String[] args) {

    String name = JOptionPane.showInputDialog("What is your name?");

    try {

    int number = Integer.parseInt(name);

        } catch (NumberFormatException n){

             JOptionPane.showMessageDialog(null, "Dear " + name + "\nwelcome to java programming course");
        }

    String message = String.format("your name must not contain any number");

        JOptionPane.showMessageDialog(null, message);
    }

}

I want to know how I can loop back the program to the top when the user types an integer and how I can skip the second message when a real name is entered

Body:
I want to know how I can loop back the program to the top when the user types an integer

Well, for this I would use a do-while loop.

For checking if the input is / has numbers, you shouldn't do it trying to parse the numbers to integer. Instead I would use a Pattern with a Matcher and regex. Otherwise you're not considering this case: Foo123

In this case something like: [0-9]+ for the regex, and if the Matcher matches with it, then it has a number.

how I can skip the second message when a real name is entered

Based on if the Matcher matches something you show one dialog or the other

For example:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class LoopingJOptionPane {
    private static final String REGEX = "[0-9]+";

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new LoopingJOptionPane()::createAndShowGui);
    }

    private void createAndShowGui() {
        boolean found = true;
        do { //This repeats this code if input is incorrect
            Pattern pattern = Pattern.compile(REGEX);

            String name = JOptionPane.showInputDialog("Enter your name");
            Matcher matcher = pattern.matcher(name); //We try to find if there's a number in our string

            found = matcher.find();

            if (found) { //If there's a number, show this message
                JOptionPane.showMessageDialog(null, "Please write only letters");
            } else { //Otherwise show this one
                JOptionPane.showMessageDialog(null, "Welcome " + name);
            }
        } while (found); //If it has no numbers, don't repeat
    }
}


问:
How to update an item on a recyclerview after excuting AsyncTask doInBackground?
I'm creating a chat feature for an application and it works super fine. But I would like to show the user that message has been sent or it still wating for the server's response.

Fields:

```<code>List<ChatMessage> chatMessages;
ChatAdapter chatAdapter;
RecyclerView chatRecyclerView;
ImageButton submitMessageBtn;
</code>```

this how I send a message on my ChatActivity class:

```<code>    public void submitMessage(final String messageType, final byte[] message){
    final ChatMessageResponse messageObject = new ChatMessageResponse();
    new AsyncTask<Void, Void, Void>() {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            messageObject.setMessage( message);
            messageObject.setYours(true);
            messageObject.setUserNickname(getNickname());
            messageObject.setCreationDate(DateTime.now().withZone(DateTimeZone.UTC));
            messageObject.setType(messageType);

            AddMessage(messageObject);
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {

                chatClient.chat().sendMessage(eventId,  messageType, message);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // Update message on the list after has been sent to server
                    }
                });

            } catch (IOException e) {
                e.printStackTrace();
            }
         return null;
        }
    }.execute();

}
</code>```

```<code>  public void AddMessage(ChatMessage message)
    {
        chatMessages.add(message);
        chatAdapter.notifyDataSetChanged();
        chatRecyclerView.scrollToPosition(chatMessages.size() -1);
    }
</code>```

When message is immediatly added to the adapter it should look like this:
  my ChatAdapter class is setup like this:

```<code>          public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ChatViewHolder> {

            private static final int VIEW_TYPE_MESSAGE_THIS_USER = 0;
            private static final int VIEW_TYPE_MESSAGE_OTHER_USER = 1;
            private final Activity activity;
            public List<ChatMessage> chats=new ArrayList<>();
            ArrayList<String> usercolor=new ArrayList<>();
            Context mContext;
            View view;

    public ChatAdapter(List<ChatMessage> chats, Context mContext, Activity activity) {
                this.chats = chats;
                this.mContext = mContext;
                this.activity = activity;
            }

            @Override
            public ChatViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
                mContext = parent.getContext();

                if (viewType == VIEW_TYPE_MESSAGE_OTHER_USER) {
                    view = View.inflate(mContext, R.layout.message_item_left, null);
                } else if (viewType == VIEW_TYPE_MESSAGE_THIS_USER){
                    view = View.inflate(mContext, R.layout.message_item, null);
                }

                return new ChatViewHolder(view,(View.OnLongClickListener)activity);
            }

        @Override
        public void onBindViewHolder(final ChatViewHolder holder, int position){
            final ChatMessageResponse m = (ChatMessageResponse) chats.get(position);
            if (getItemViewType(position) == VIEW_TYPE_MESSAGE_OTHER_USER){
                holder.bindToView1(m);
            } else if (getItemViewType(position) == VIEW_TYPE_MESSAGE_THIS_USER)
            {
                holder.bindToView(m);
            }
        }

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

        @Override
        public int getItemViewType(int position) {
            return chats.get(position).isYours() ? VIEW_TYPE_MESSAGE_THIS_USER : VIEW_TYPE_MESSAGE_OTHER_USER;
            }

  }
</code>```

When the server's response is positive the views in the ChatViewHolder (that I don't show the code because is too long) should change visibility state
Someone told me to get a referece for the view and change it on the activity's asynctask or create a Callback listener for my adapter.

But I have no Idea how to do either one of then any help is appreciated.

答:
Are you familiar with the use of "Callbacks" or "Interfaces"? You can create an interface and implement it in your activity. Pass the callback by parameters in the "AsyncTask" and use it there.

```<code>//Interface class
/**
 * Created by gmora
 */
public interface IProcess {

    void updateAdapter(String result);
}
</code>```

On Activity:

```<code>public class YourActivity extends AppCompatActivity {

    private IProcess mProcess;
    private Adapter mRecyclerAdapter;
    private RecyclerView mRecyclerView;
    private List<ChatMessage> chats; //update chats on activity and refresh your adapter

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_layout);
         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
         setSupportActionBar(toolbar);

         mProcess = new IProceso() {
                @Override
                public void updateAdapter(String pException) {
                  //update chats ... and update mAdater.notifyDataChange()...
                  // or mRecyclerView.setAdapter(new Adpater.... with new list chats)..
                }
            };

        mRecyclerView = find....
        // etc....
        mRecyclerAdapter = new RecyclerAdapter( chats, ...);
        mRecyclerView.setAdapter(mRecyclerAdapter);
    }
}
</code>```

Finally on AsyncTask... create a external class from AsyncTask please!

```<code>/**
 * Created by gmora.
 */

public class YourAsyncTaskClass extends AsyncTask<String, Void, String > {

    private IProcess iProcess;

    public StarSearchPrinterTask(IProcess pIProcess) {
        this.iProcess= pIProcess;
    }

    @Override
    protected void onPreExecute() {
        //loading... its optional
    }

    @Override
    protected String doInBackground(String... interfaceType) {
        // execute webservice or api and get results..

        return results;
    }

    @Override
    protected void onPostExecute(String results) {
        mIProceso.updateAdapter(results);
    }
}
</code>```

Body:
I'm creating a chat feature for an application and it works super fine. But I would like to show the user that message has been sent or it still wating for the server's response.

Fields:

List<ChatMessage> chatMessages;
ChatAdapter chatAdapter;
RecyclerView chatRecyclerView;
ImageButton submitMessageBtn;

this how I send a message on my ChatActivity class:

    public void submitMessage(final String messageType, final byte[] message){
    final ChatMessageResponse messageObject = new ChatMessageResponse();
    new AsyncTask<Void, Void, Void>() {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            messageObject.setMessage( message);
            messageObject.setYours(true);
            messageObject.setUserNickname(getNickname());
            messageObject.setCreationDate(DateTime.now().withZone(DateTimeZone.UTC));
            messageObject.setType(messageType);

            AddMessage(messageObject);
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {

                chatClient.chat().sendMessage(eventId,  messageType, message);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // Update message on the list after has been sent to server
                    }
                });

            } catch (IOException e) {
                e.printStackTrace();
            }
         return null;
        }
    }.execute();

}

  public void AddMessage(ChatMessage message)
    {
        chatMessages.add(message);
        chatAdapter.notifyDataSetChanged();
        chatRecyclerView.scrollToPosition(chatMessages.size() -1);
    }

When message is immediatly added to the adapter it should look like this:
  my ChatAdapter class is setup like this:

          public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ChatViewHolder> {

            private static final int VIEW_TYPE_MESSAGE_THIS_USER = 0;
            private static final int VIEW_TYPE_MESSAGE_OTHER_USER = 1;
            private final Activity activity;
            public List<ChatMessage> chats=new ArrayList<>();
            ArrayList<String> usercolor=new ArrayList<>();
            Context mContext;
            View view;

    public ChatAdapter(List<ChatMessage> chats, Context mContext, Activity activity) {
                this.chats = chats;
                this.mContext = mContext;
                this.activity = activity;
            }

            @Override
            public ChatViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
                mContext = parent.getContext();

                if (viewType == VIEW_TYPE_MESSAGE_OTHER_USER) {
                    view = View.inflate(mContext, R.layout.message_item_left, null);
                } else if (viewType == VIEW_TYPE_MESSAGE_THIS_USER){
                    view = View.inflate(mContext, R.layout.message_item, null);
                }

                return new ChatViewHolder(view,(View.OnLongClickListener)activity);
            }

        @Override
        public void onBindViewHolder(final ChatViewHolder holder, int position){
            final ChatMessageResponse m = (ChatMessageResponse) chats.get(position);
            if (getItemViewType(position) == VIEW_TYPE_MESSAGE_OTHER_USER){
                holder.bindToView1(m);
            } else if (getItemViewType(position) == VIEW_TYPE_MESSAGE_THIS_USER)
            {
                holder.bindToView(m);
            }
        }

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

        @Override
        public int getItemViewType(int position) {
            return chats.get(position).isYours() ? VIEW_TYPE_MESSAGE_THIS_USER : VIEW_TYPE_MESSAGE_OTHER_USER;
            }

  }

When the server's response is positive the views in the ChatViewHolder (that I don't show the code because is too long) should change visibility state
Someone told me to get a referece for the view and change it on the activity's asynctask or create a Callback listener for my adapter.

But I have no Idea how to do either one of then any help is appreciated.

Body:
Are you familiar with the use of "Callbacks" or "Interfaces"? You can create an interface and implement it in your activity. Pass the callback by parameters in the "AsyncTask" and use it there.

//Interface class
/**
 * Created by gmora
 */
public interface IProcess {

    void updateAdapter(String result);
}

On Activity:

public class YourActivity extends AppCompatActivity {

    private IProcess mProcess;
    private Adapter mRecyclerAdapter;
    private RecyclerView mRecyclerView;
    private List<ChatMessage> chats; //update chats on activity and refresh your adapter

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_layout);
         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
         setSupportActionBar(toolbar);

         mProcess = new IProceso() {
                @Override
                public void updateAdapter(String pException) {
                  //update chats ... and update mAdater.notifyDataChange()...
                  // or mRecyclerView.setAdapter(new Adpater.... with new list chats)..
                }
            };

        mRecyclerView = find....
        // etc....
        mRecyclerAdapter = new RecyclerAdapter( chats, ...);
        mRecyclerView.setAdapter(mRecyclerAdapter);
    }
}

Finally on AsyncTask... create a external class from AsyncTask please!

/**
 * Created by gmora.
 */

public class YourAsyncTaskClass extends AsyncTask<String, Void, String > {

    private IProcess iProcess;

    public StarSearchPrinterTask(IProcess pIProcess) {
        this.iProcess= pIProcess;
    }

    @Override
    protected void onPreExecute() {
        //loading... its optional
    }

    @Override
    protected String doInBackground(String... interfaceType) {
        // execute webservice or api and get results..

        return results;
    }

    @Override
    protected void onPostExecute(String results) {
        mIProceso.updateAdapter(results);
    }
}


问:
Unable to locate element with in selenium using xpath written in python
I am trying to automate an iCal download from this website: webuntis.dk using python and selenium. So far I have managed to get get python to enter the credentials of au_health on the login site. Next I need it to press the small calendar icon in the top right corner. It keeps returning:

```<code>NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/a[@id="Timetable_toolbar_icalButton"]"}
</code>```

My code is as follow:

```<code>from selenium import webdriver

browser = webdriver.Chrome('/Users/juliushvidt/Desktop/chromedriver')

browser.get('https://webuntis.dk/WebUntis/login.do')

username = browser.find_element_by_id("school")

username.send_keys("au_health")

NEXT_BUTTON_XPATH = '//input[@type="submit"]'
button = browser.find_element_by_xpath(NEXT_BUTTON_XPATH)
button.click()

browser.get('https://webuntis.dk/WebUntis/index.do#Timetable?type=3&id=1140')

driver = browser

time.sleep(5.5) #this did the trick

NEXT_BUTTON_XPATH = '//button[@id="Timetable_toolbar_icalButton"]' #using the current button notation was definitely also contributing :)
button = browser.find_element_by_xpath(NEXT_BUTTON_XPATH)
button.click()
</code>```

The inspecting the element im trying to reach on the website I get the following source code:

Hope you can point me in the right direction as I'm at a loss.

Code exert from the source of the website:

```<code><div data-dojo-type="dijit/layout/ContentPane" data-dojo-attach-point="_toolbarContainer" class="dijitContentPane toolbarContainer dijitBorderContainerNoGutter-child dijitBorderContainerNoGutter-dijitContentPane dijitBorderContainerNoGutterPane dijitAlignTop" data-dojo-props="region: 'top'" id="dijit_layout_ContentPane_0" widgetid="dijit_layout_ContentPane_0" style="left: 0px; top: 0px; position: absolute; width: 31px;"><div class="grupetWidgetToolbar" id="Timetable_toolbar" widgetid="Timetable_toolbar"><div class="grupetWidgetLabelPanel" id="grupet_widget_LabelPanel_0" widgetid="grupet_widget_LabelPanel_0" style="display: inline-block; vertical-align: middle;">
    <div class="grupetWidgetLabelPanelText_ABOVE" data-dojo-attach-point="textNode">Fag</div>
    <div class="grupetWidgetLabelPanelContainer_ABOVE" data-dojo-attach-point="containerNode"><div class="dijit dijitReset dijitInline dijitLeft dijitTextBox dijitComboBox dijitValidationTextBox" id="widget_Timetable_toolbar_elementSelect" role="combobox" aria-haspopup="true" data-dojo-attach-point="_popupStateNode" widgetid="Timetable_toolbar_elementSelect"><div class="dijitReset dijitRight dijitButtonNode dijitArrowButton dijitDownArrowButton dijitArrowButtonContainer" data-dojo-attach-point="_buttonNode" role="presentation"><input class="dijitReset dijitInputField dijitArrowButtonInner" value="▼ " type="text" tabindex="-1" readonly="readonly" role="button presentation" aria-hidden="true"></div><div class="dijitReset dijitValidationContainer"><input class="dijitReset dijitInputField dijitValidationIcon dijitValidationInner" value="Χ " type="text" tabindex="-1" readonly="readonly" role="presentation"></div><div class="dijitReset dijitInputField dijitInputContainer"><input class="dijitReset dijitInputInner" type="text" autocomplete="off" data-dojo-attach-point="textbox,focusNode" role="textbox" aria-autocomplete="list" tabindex="0" id="Timetable_toolbar_elementSelect" aria-required="false" value="1. sem. Medicinsk filosofi forelæsning" aria-invalid="false"><span class="dijitPlaceHolder dijitInputField" style="display: none;">Vælg her</span><input type="hidden" value="1140"></div></div></div>
</div><div class="grupetWidgetLabelPanel" id="grupet_widget_LabelPanel_1" widgetid="grupet_widget_LabelPanel_1" style="display: inline-block; vertical-align: middle;">
    <div class="grupetWidgetLabelPanelText_ABOVE" data-dojo-attach-point="textNode">Afdeling</div>
    <div class="grupetWidgetLabelPanelContainer_ABOVE" data-dojo-attach-point="containerNode"><div class="dijit dijitReset dijitInline dijitLeft grupetWidgetHasResetButton dijitTextBox dijitComboBox dijitValidationTextBox" id="widget_Timetable_toolbar_elementFilter_IDC_ABTEILUNG" role="combobox" aria-haspopup="true" data-dojo-attach-point="_popupStateNode" widgetid="Timetable_toolbar_elementFilter_IDC_ABTEILUNG"><div class="dijitReset dijitRight dijitButtonNode dijitArrowButton dijitDownArrowButton dijitArrowButtonContainer" data-dojo-attach-point="_buttonNode" role="presentation"><input class="dijitReset dijitInputField dijitArrowButtonInner" value="▼ " type="text" tabindex="-1" readonly="readonly" role="button presentation" aria-hidden="true"></div><div class="dijitReset dijitValidationContainer"><input class="dijitReset dijitInputField dijitValidationIcon dijitValidationInner" value="Χ " type="text" tabindex="-1" readonly="readonly" role="presentation"></div><div class="dijitReset dijitRight dijitButtonNode grupetWidgetResetButton grupetWidgetResetButtonContainer grupetDisplayNone">
    <input type="text" role="presentation" readonly="readonly" tabindex="-1" value=" " title="Nulstil" class="dijitReset dijitInputField grupetWidgetResetButtonInner">
</div><div class="dijitReset dijitInputField dijitInputContainer"><input class="dijitReset dijitInputInner" type="text" autocomplete="off" data-dojo-attach-point="textbox,focusNode" role="textbox" aria-autocomplete="list" tabindex="0" id="Timetable_toolbar_elementFilter_IDC_ABTEILUNG" aria-required="false" value="" aria-invalid="false"><span class="dijitPlaceHolder dijitInputField">Vælg her</span><input type="hidden" value=""></div></div></div>
</div><div class="grupetWidgetLabelPanel" id="grupet_widget_LabelPanel_2" widgetid="grupet_widget_LabelPanel_2" style="display: inline-block; vertical-align: middle;">
    <div class="grupetWidgetLabelPanelText_ABOVE" data-dojo-attach-point="textNode">Aktuel uge</div>
    <div class="grupetWidgetLabelPanelContainer_ABOVE" data-dojo-attach-point="containerNode"><div class="dijit dijitReset dijitInline dijitLeft date-week-select dijitTextBox dijitComboBox dijitDateTextBox dijitValidationTextBox" id="widget_timetablePageToolbar_dateWeekSelect" role="combobox" aria-haspopup="true" data-dojo-attach-point="_popupStateNode" widgetid="timetablePageToolbar_dateWeekSelect"><div class="dijitReset dijitRight dijitButtonNode dijitArrowButton dijitDownArrowButton dijitArrowButtonContainer" data-dojo-attach-point="_buttonNode" role="presentation"><input class="dijitReset dijitInputField dijitArrowButtonInner" value="▼ " type="text" tabindex="-1" readonly="readonly" role="button presentation" aria-hidden="true"></div><div class="dijitReset dijitValidationContainer"><input class="dijitReset dijitInputField dijitValidationIcon dijitValidationInner" value="Χ " type="text" tabindex="-1" readonly="readonly" role="presentation"></div><span role="button" class="fa fa-caret-right"></span><span role="button" class="fa fa-caret-left"></span><div class="dijitReset dijitInputField dijitInputContainer"><input class="dijitReset dijitInputInner" type="text" autocomplete="off" data-dojo-attach-point="textbox,focusNode" role="textbox" tabindex="0" id="timetablePageToolbar_dateWeekSelect" value="04/12/2017" aria-invalid="false"><input type="hidden" value="2017-12-04"></div></div></div>
</div><span class="dijit dijitReset dijitInline gp-iconfont-button dijitDropDownButton" widgetid="Timetable_toolbar_settingsButton" style="display: inline-block; vertical-align: middle; float: right;"><span class="dijitReset dijitInline dijitButtonNode" data-dojo-attach-event="ondijitclick:__onClick" data-dojo-attach-point="_buttonNode"><span class="dijitReset dijitStretch dijitButtonContents dijitDownArrowButton" data-dojo-attach-point="focusNode,titleNode,_arrowWrapperNode,_popupStateNode" role="button" aria-haspopup="true" aria-labelledby="Timetable_toolbar_settingsButton_label" tabindex="0" id="Timetable_toolbar_settingsButton" aria-disabled="false" style="user-select: none;"><span class="dijitReset dijitInline dijitIcon fa fa-2x fa-cog" data-dojo-attach-point="iconNode"></span><span class="dijitReset dijitInline dijitButtonText" data-dojo-attach-point="containerNode" id="Timetable_toolbar_settingsButton_label"></span><span class="dijitReset dijitInline dijitArrowButtonInner"></span><span class="dijitReset dijitInline dijitArrowButtonChar">▼</span></span></span><input type="button" value="" class="dijitOffScreen" tabindex="-1" data-dojo-attach-event="onclick:_onClick" data-dojo-attach-point="valueNode" role="presentation" aria-hidden="true"></span><button type="button" class="gp-iconfont-button fa fa-2x fa-print" id="Timetable_toolbar_printButton" title="Udskriftsversion" aria-label="Udskriftsversion" widgetid="Timetable_toolbar_printButton" style="display: inline-block; vertical-align: middle; float: right;"></button><button type="button" class="icon-ical-24 imageButton imageButtonFocused dijitFocused" title="ICS kalender" aria-label="ICS kalender" id="Timetable_toolbar_icalButton" widgetid="Timetable_toolbar_icalButton" style="display: inline-block; vertical-align: middle; float: right;"><div class="icon icon-ical-24"></div></button></div></div>
</code>```

答:
With only a single slash, XPATH doesn't look down the tree. To do that you need to use two slashes. Also, the source in your image shows that you are trying to reach a <button> element. Try this instead.

```<code>NEXT_BUTTON_XPATH = '//button[@id="Timetable_toolbar_icalButton"]'
</code>```

EDIT:
I see that parts of the page is dynamically loaded, so you explicitly need to wait for the button to be added to the page. The following should do the trick:

```<code>from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait

...

NEXT_BUTTON_XPATH = '//button[@id="Timetable_toolbar_icalButton"]'
wait = WebDriverWait(driver, 10)
condition = expected_conditions.presence_of_element_located(
    (By.XPATH, NEXT_BUTTON_XPATH))
button = wait.until(condition)
button.click()
</code>```

NOTE: Using time.sleep(5.5) will probably work in some circumstances, but not always as it is dependent on the time used to render the page. Using WebDriverWait will ensure that:

You are not dependent on timing.

The code returns as soon as the element is available.

Some tips: In the Chrome developer console you can test your xpath expresssions. To do this first go to the Elements tab. Then press Ctrl+F. Then you can enter your xpath expression to test it.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to automate an iCal download from this website: webuntis.dk using python and selenium. So far I have managed to get get python to enter the credentials of au_health on the login site. Next I need it to press the small calendar icon in the top right corner. It keeps returning:

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/a[@id="Timetable_toolbar_icalButton"]"}

My code is as follow:

from selenium import webdriver

browser = webdriver.Chrome('/Users/juliushvidt/Desktop/chromedriver')

browser.get('https://webuntis.dk/WebUntis/login.do')

username = browser.find_element_by_id("school")

username.send_keys("au_health")

NEXT_BUTTON_XPATH = '//input[@type="submit"]'
button = browser.find_element_by_xpath(NEXT_BUTTON_XPATH)
button.click()

browser.get('https://webuntis.dk/WebUntis/index.do#Timetable?type=3&id=1140')

driver = browser

time.sleep(5.5) #this did the trick

NEXT_BUTTON_XPATH = '//button[@id="Timetable_toolbar_icalButton"]' #using the current button notation was definitely also contributing :)
button = browser.find_element_by_xpath(NEXT_BUTTON_XPATH)
button.click()

The inspecting the element im trying to reach on the website I get the following source code:

Hope you can point me in the right direction as I'm at a loss.

Code exert from the source of the website:

Fag

<input class="dijitReset dijitInputField dijitArrowButtonInner" value="▼ " type="text" tabindex="-1" readonly="readonly" role="button presentation" aria-hidden="true">

<input class="dijitReset dijitInputField dijitValidationIcon dijitValidationInner" value="Χ " type="text" tabindex="-1" readonly="readonly" role="presentation">

<input class="dijitReset dijitInputInner" type="text" autocomplete="off" data-dojo-attach-point="textbox,focusNode" role="textbox" aria-autocomplete="list" tabindex="0" id="Timetable_toolbar_elementSelect" aria-required="false" value="1. sem. Medicinsk filosofi forelæsning" aria-invalid="false">Vælg her<input type="hidden" value="1140">

Afdeling

<input class="dijitReset dijitInputField dijitArrowButtonInner" value="▼ " type="text" tabindex="-1" readonly="readonly" role="button presentation" aria-hidden="true">

<input class="dijitReset dijitInputField dijitValidationIcon dijitValidationInner" value="Χ " type="text" tabindex="-1" readonly="readonly" role="presentation">

    <input type="text" role="presentation" readonly="readonly" tabindex="-1" value=" " title="Nulstil" class="dijitReset dijitInputField grupetWidgetResetButtonInner">

<input class="dijitReset dijitInputInner" type="text" autocomplete="off" data-dojo-attach-point="textbox,focusNode" role="textbox" aria-autocomplete="list" tabindex="0" id="Timetable_toolbar_elementFilter_IDC_ABTEILUNG" aria-required="false" value="" aria-invalid="false">Vælg her<input type="hidden" value="">

Aktuel uge

<input class="dijitReset dijitInputField dijitArrowButtonInner" value="▼ " type="text" tabindex="-1" readonly="readonly" role="button presentation" aria-hidden="true">

<input class="dijitReset dijitInputField dijitValidationIcon dijitValidationInner" value="Χ " type="text" tabindex="-1" readonly="readonly" role="presentation">

<input class="dijitReset dijitInputInner" type="text" autocomplete="off" data-dojo-attach-point="textbox,focusNode" role="textbox" tabindex="0" id="timetablePageToolbar_dateWeekSelect" value="04/12/2017" aria-invalid="false"><input type="hidden" value="2017-12-04">

▼<input type="button" value="" class="dijitOffScreen" tabindex="-1" data-dojo-attach-event="onclick:_onClick" data-dojo-attach-point="valueNode" role="presentation" aria-hidden="true"><button type="button" class="gp-iconfont-button fa fa-2x fa-print" id="Timetable_toolbar_printButton" title="Udskriftsversion" aria-label="Udskriftsversion" widgetid="Timetable_toolbar_printButton" style="display: inline-block; vertical-align: middle; float: right;"></button><button type="button" class="icon-ical-24 imageButton imageButtonFocused dijitFocused" title="ICS kalender" aria-label="ICS kalender" id="Timetable_toolbar_icalButton" widgetid="Timetable_toolbar_icalButton" style="display: inline-block; vertical-align: middle; float: right;">

</button>

Body:
With only a single slash, XPATH doesn't look down the tree. To do that you need to use two slashes. Also, the source in your image shows that you are trying to reach a <button> element. Try this instead.

NEXT_BUTTON_XPATH = '//button[@id="Timetable_toolbar_icalButton"]'

EDIT:
I see that parts of the page is dynamically loaded, so you explicitly need to wait for the button to be added to the page. The following should do the trick:

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait

...

NEXT_BUTTON_XPATH = '//button[@id="Timetable_toolbar_icalButton"]'
wait = WebDriverWait(driver, 10)
condition = expected_conditions.presence_of_element_located(
    (By.XPATH, NEXT_BUTTON_XPATH))
button = wait.until(condition)
button.click()

NOTE: Using time.sleep(5.5) will probably work in some circumstances, but not always as it is dependent on the time used to render the page. Using WebDriverWait will ensure that:

You are not dependent on timing.

The code returns as soon as the element is available.

Some tips: In the Chrome developer console you can test your xpath expresssions. To do this first go to the Elements tab. Then press Ctrl+F. Then you can enter your xpath expression to test it.


问:
Using Java, take in a Json message, find a subset of fields, check said fields, then map to new Code values and export as Json
Okay, I'm new to using Json in Java and heres what I'm looking to do.

Using Java I'm taking in a Json message, something like:

```<code>{
    "toy": [
        {
             "color":"red",
             "age":"2-4",
             "type": {
                 "format":"electronic",
                 "batteries":"Y"
             },
             "price":"$50"
        }
     ]
}
</code>```

Now, say I have several of these coming through with different values for the fields above. I want to take the message and extract fields based on some requirements which will require certain fields to map to new fields. For example:

Requirement1

Field: color

Maps to: Colour

Field: batteries

Maps to: Batteries Required?

So the output would be:

```<code>{
    "Toy": [
        {
            "Colour":"red",
            "Batteries Required?":"Y"
        }
    ]
}
</code>```

Then assume there may be other requirements requiring different fields or a combination of fields, or transformation of fields (like currency conversion).

I want to know what the cleanest and most efficient way would be. Does this kind of thing already exist in Json within Java?

答:
You may use Jolt to transform Json objects like XSLT does for XMLs: https://github.com/bazaarvoice/jolt. Using this lib you can define a "transformation rule" that reads your input and produces a json based on the rules.

An alternative is Json Path, that allows you to find elements in a json object like in xpath: https://github.com/json-path/JsonPath

Body:
Okay, I'm new to using Json in Java and heres what I'm looking to do.

Using Java I'm taking in a Json message, something like:

{
    "toy": [
        {
             "color":"red",
             "age":"2-4",
             "type": {
                 "format":"electronic",
                 "batteries":"Y"
             },
             "price":"$50"
        }
     ]
}

Now, say I have several of these coming through with different values for the fields above. I want to take the message and extract fields based on some requirements which will require certain fields to map to new fields. For example:

Requirement1

Field: color

Maps to: Colour

Field: batteries

Maps to: Batteries Required?

So the output would be:

{
    "Toy": [
        {
            "Colour":"red",
            "Batteries Required?":"Y"
        }
    ]
}

Then assume there may be other requirements requiring different fields or a combination of fields, or transformation of fields (like currency conversion).

I want to know what the cleanest and most efficient way would be. Does this kind of thing already exist in Json within Java?


问:
iPhone GPS Coordinate uploading
I am looking for a way for the iPhone to push out GPS coordinates every hour and display them on a public website.

I have a friend biking across the country for charity and he wants everyone to be able to view his progress.  Any creative ideas besides the iPhone?  Any ideas with minimal programming would be appreciated.

Thanks for the help!
Dylan

答: If I were doing this, I'd probably just use Runkeeper Live</p>

ContentLicense: CC BY-SA 2.5

Title: iPhone GPS Coordinate uploading


问:
UnderscoreJS : Find difference between two array having different type of elements
In UnderscoreJS there is a method called _.difference which can give difference between two arrays.

But In my case I have two different arrays as shown below:

Array 1:

```<code>var obj1 = [
{
    id: 1,
    name: 'abc-1',
    lname: 'xyz-1',
    phone: 'xxxxxx1',
    company: 'Comp-1',
    address: 'Address-1',
    country: 'C-1',
    securityNo: 'xxxx-1'
},
{
    id: 2,
    name: 'abc-2',
    lname: 'xyz-2',
    phone: 'xxxxxx2',
    company: 'Comp-2',
    address: 'Address-2',
    country: 'C-2',
    securityNo: 'xxxx-2'
},
{
    id: 3,
    name: 'abc-3',
    lname: 'xyz-3',
    phone: 'xxxxxx3',
    company: 'Comp-3',
    address: 'Address-3',
    country: 'C-3',
    securityNo: 'xxxx-3'
}]
</code>```

And another array contains only limited properties:

Array 2:

```<code>var obj2 = [
{
    id: 1,
    name: 'abc-1',
    lname: 'xyz-1'
},
{
    id: 2,
    name: 'abc-2',
    lname: 'xyz-2'
}]
</code>```

Now I would like to apply difference between these two arrays like:

```<code>_.difference(obj1, obj2);
</code>```

And it should give me 3rd element as a result.

But I could not find any way to achieve this.

答: See answer using underscore's “difference” method on arrays of objects. This is due to Object comparison.</p>

Body:
In UnderscoreJS there is a method called _.difference which can give difference between two arrays.

But In my case I have two different arrays as shown below:

Array 1:

var obj1 = [
{
    id: 1,
    name: 'abc-1',
    lname: 'xyz-1',
    phone: 'xxxxxx1',
    company: 'Comp-1',
    address: 'Address-1',
    country: 'C-1',
    securityNo: 'xxxx-1'
},
{
    id: 2,
    name: 'abc-2',
    lname: 'xyz-2',
    phone: 'xxxxxx2',
    company: 'Comp-2',
    address: 'Address-2',
    country: 'C-2',
    securityNo: 'xxxx-2'
},
{
    id: 3,
    name: 'abc-3',
    lname: 'xyz-3',
    phone: 'xxxxxx3',
    company: 'Comp-3',
    address: 'Address-3',
    country: 'C-3',
    securityNo: 'xxxx-3'
}]

And another array contains only limited properties:

Array 2:

var obj2 = [
{
    id: 1,
    name: 'abc-1',
    lname: 'xyz-1'
},
{
    id: 2,
    name: 'abc-2',
    lname: 'xyz-2'
}]

Now I would like to apply difference between these two arrays like:

_.difference(obj1, obj2);

And it should give me 3rd element as a result.

But I could not find any way to achieve this.


问:
this.setState making infinite loop outside of array.map function
I have this array map function for rendering some stuff...
I have 5 variables that start from 0 and depending on a switch statement each variable value is increased by 1.

```<code>renderUser = (index)=>{
    let C1Count = 0, C2Count = 0, C3Count = 0, C4Count = 0, C5Count = 0;
    let users = this.state.users.map((user,index)=>{

   // swiching some value , that is from 0 to 4

   switch(this.state.users[index].result){
      case 0: { C1Count += 1;   break; }
      case 1: { C2Count += 1;  break; }
      case 2: { C3Count += 1;  break; }
      case 3: { C4Count += 1;   break; }
      case 4: { C5Count += 1;   break; }
      default: { console.log("non");  break; };
    }
    return(
      ....stuff to render
                   )

   }).reverse();

  return users;
</code>```

}

I want to update 5 states

```<code>this.setState({
C1Count:C1Count, // state : variable value
C2Count:C2Count, // state : variable value
C3Count:C3Count, // state : variable value
C4Count:C4Count, // state : variable value
C5Count:C5Count  // state : variable value
});
</code>```

If i place the setState code after ...}).reverse(); and before  ..return users;

I get a

Maximum update depth exceeded. This can happen when a component
  repeatedly calls setState inside componentWillUpdate or
  componentDidUpdate. React limits the number of nested updates to
  prevent infinite loops.

error .... so my question is ... how to update the state AFTER all the loops are finished and the C1Count, C2Count, C3Count, C4Count, C5Count variables are updated.

答:
By default, a React Component will re-render when its state is changed through setState(), which is why render() should be a pure function (i.e., do not modify state).

For your case, Count variables are derived state, so you wouldn't need to actually keep the value. Instead, you could create a function that calculated its value:

```<code>getCounts() {
  return this.state.users.reduce((counts, user) => {
    switch (user.result) {
      case 0:
        counts.C1Count++; break;
      case 1:
        counts.C2Count++; break;
      case 2:
        counts.C3Count++; break;
      case 3:
        counts.C4Count++; break;
      case 4:
        counts.C5Count++; break;
      default:
        console.log("non");
    }

    return counts;
  }, { C1Count: 0, C2Count: 0, C3Count: 0, C4Count: 0, C5Count: 0 });
}
</code>```

Body:
I have this array map function for rendering some stuff...
I have 5 variables that start from 0 and depending on a switch statement each variable value is increased by 1.

renderUser = (index)=>{
    let C1Count = 0, C2Count = 0, C3Count = 0, C4Count = 0, C5Count = 0;
    let users = this.state.users.map((user,index)=>{

   // swiching some value , that is from 0 to 4

   switch(this.state.users[index].result){
      case 0: { C1Count += 1;   break; }
      case 1: { C2Count += 1;  break; }
      case 2: { C3Count += 1;  break; }
      case 3: { C4Count += 1;   break; }
      case 4: { C5Count += 1;   break; }
      default: { console.log("non");  break; };
    }
    return(
      ....stuff to render
                   )

   }).reverse();

  return users;

}

I want to update 5 states

this.setState({
C1Count:C1Count, // state : variable value
C2Count:C2Count, // state : variable value
C3Count:C3Count, // state : variable value
C4Count:C4Count, // state : variable value
C5Count:C5Count  // state : variable value
});

If i place the setState code after ...}).reverse(); and before  ..return users;

I get a

Maximum update depth exceeded. This can happen when a component
  repeatedly calls setState inside componentWillUpdate or
  componentDidUpdate. React limits the number of nested updates to
  prevent infinite loops.

error .... so my question is ... how to update the state AFTER all the loops are finished and the C1Count, C2Count, C3Count, C4Count, C5Count variables are updated.

Body:
By default, a React Component will re-render when its state is changed through setState(), which is why render() should be a pure function (i.e., do not modify state).

For your case, Count variables are derived state, so you wouldn't need to actually keep the value. Instead, you could create a function that calculated its value:

getCounts() {
  return this.state.users.reduce((counts, user) => {
    switch (user.result) {
      case 0:
        counts.C1Count++; break;
      case 1:
        counts.C2Count++; break;
      case 2:
        counts.C3Count++; break;
      case 3:
        counts.C4Count++; break;
      case 4:
        counts.C5Count++; break;
      default:
        console.log("non");
    }

    return counts;
  }, { C1Count: 0, C2Count: 0, C3Count: 0, C4Count: 0, C5Count: 0 });
}


问:
Debugging SSIS Script task - Breakpoint is enabled but it does not hit
I am working on an SSIS package. The package has a script (C# language) task. I need to debug the script task. I set the break point. The script in script editor (Visual Studio) and the task in SSIS package editor, both, show break point in red color - means the break point is enabled. However, when I debug the package the break point does not hit.

The break point has no conditions on it, so I expect it to hit every time the package runs.

I am using Visual Studio 2008 on Windows 2003 R2 64-bit SP2.

答:
Update: Guys, I againg lost any ability to set breakpoints (a request to MS)

My previous fixes are below.

Now I'm using logging and tracing instead of debugging.

C# new features (after C# 4.0) are blamed for killing debugging of the SSIS Script Task.

To return the breakpoint capability I do the following.

Remove C# new features

Run my Script Task once, successfully. I.e. without a crash.

Reopen the Vsta Project from my Script Task and put breakpoints there.

At the end, you have to see a red circle on your Script Task.

(Tested in VS 2017.)

Note. I have to mention that debugging works even if your use "Execute Task" only, not "Execute Package"!

Remove C# new features

To remove the C# new features, I can advise you two ways.

First, restrict Vsta Project properties to C# 4.0 (migrated packages may not support this).

Dobule click your "Script Task" to open "Script Task Editor".

Click "Edit Script..." button to open Visual Studio.

In "Solution Explorer" select the project and click the F4 key on your keyboard.

In opened "Properties" window in "C# Language Level" choise "C# 4.0"

Build your project and fix compilation errors.

Secondly, Vsta Projects in old/migrated packages may not show the above "C# Language Level" property.

So you can put your code in a fake project in Visual Studio 2010 and compile it there.

Run it once successfully

After you fix your C#, you have to run your Script Task once successfully.

You may want to put the return statement at the beginning of the Main() method to prevent any real execution.

Sorry, this doesn't always work and I don't realise why but you definitely need to fix your C# in the first place.

At least you will get a working Script Task and can debug it in an old fashioned way (logs by Dts.Events..., exceptions, etc.)

TL;DR

It looks like I even got severe cases when C# new features forced Script Tasks to fail silently with a success completion status.

As an example, add the following to your Script task.

```<code>string Bug { get; } // Only getter properties.
//...
var str = $"Now is {DateTime.Now}"; // String Interpolation in C#
//...
var dummy = val?.ToUpper(); // ?. and ?[] null-conditional Operators
</code>```

And workarounds for this non-complete list:

```<code>string Bug { get; set; }
//...
var str = string.Format("Now is {0}", DateTime.Now);
// etc.
</code>```

What I also do, I build my C# code in Visual Studio 2010. It simply doesn't compile the new .NET features and do not allows .NET Framework versions above 4.0. So far, so good.

Of course, other answers from this SO-question didn't help me.

Body:
Update: Guys, I againg lost any ability to set breakpoints (a request to MS)

My previous fixes are below.

Now I'm using logging and tracing instead of debugging.

C# new features (after C# 4.0) are blamed for killing debugging of the SSIS Script Task.

To return the breakpoint capability I do the following.

Remove C# new features

Run my Script Task once, successfully. I.e. without a crash.

Reopen the Vsta Project from my Script Task and put breakpoints there.

At the end, you have to see a red circle on your Script Task.

(Tested in VS 2017.)

Note. I have to mention that debugging works even if your use "Execute Task" only, not "Execute Package"!

Remove C# new features

To remove the C# new features, I can advise you two ways.

First, restrict Vsta Project properties to C# 4.0 (migrated packages may not support this).

Dobule click your "Script Task" to open "Script Task Editor".

Click "Edit Script..." button to open Visual Studio.

In "Solution Explorer" select the project and click the F4 key on your keyboard.

In opened "Properties" window in "C# Language Level" choise "C# 4.0"

Build your project and fix compilation errors.

Secondly, Vsta Projects in old/migrated packages may not show the above "C# Language Level" property.

So you can put your code in a fake project in Visual Studio 2010 and compile it there.

Run it once successfully

After you fix your C#, you have to run your Script Task once successfully.

You may want to put the return statement at the beginning of the Main() method to prevent any real execution.

Sorry, this doesn't always work and I don't realise why but you definitely need to fix your C# in the first place.

At least you will get a working Script Task and can debug it in an old fashioned way (logs by Dts.Events..., exceptions, etc.)

TL;DR

It looks like I even got severe cases when C# new features forced Script Tasks to fail silently with a success completion status.

As an example, add the following to your Script task.

string Bug { get; } // Only getter properties.
//...
var str = $"Now is {DateTime.Now}"; // String Interpolation in C#
//...
var dummy = val?.ToUpper(); // ?. and ?[] null-conditional Operators

And workarounds for this non-complete list:

string Bug { get; set; }
//...
var str = string.Format("Now is {0}", DateTime.Now);
// etc.

What I also do, I build my C# code in Visual Studio 2010. It simply doesn't compile the new .NET features and do not allows .NET Framework versions above 4.0. So far, so good.

Of course, other answers from this SO-question didn't help me.


问:
Different behaviors on success/fail on PHPMailer
I have a PHPMailer form and I am using .ajax using this SO answer jquery-ajax-post-example-with-php

It is successfully sending or not sending, so I know the Mailer and captcha are working. Now, if I could get different behaviors for success and fail, that would be great, but I am not getting this right somehow.

PREFERRED BEHAVIORS

SUCCESS --> reload screen and show bootstrap modal with success msg

FAIL --> reload screen and show bootstrap modal with fail msg

I have a lot of code so, Think of the modals as vanilla as possible, and the PHPMailer is, in fact, sending as well. The problem I am having should be in the code below, but if you have to have something else, just ask. Trying to keep the question as decluttered as possible

```<code>  <script type="text/javascript">
        $(document).ready(function() {
            var request;

            $("#contactForm").submit(function(event){
                event.preventDefault();

                // Abort any pending request
                if (request) {
                    request.abort();
                }

                // setup some local variables
                var $form = $(this);

                // Let's select and cache all the fields
                var $inputs = $form.find("input, select, button, textarea");

                // Serialize the data in the form
                var serializedData = $form.serialize();

                // Let's disable the inputs for the duration of the Ajax request.
                // Note: we disable elements AFTER the form data has been serialized.
                // Disabled form elements will not be serialized.
                $inputs.prop("disabled", true);

                request = $.ajax({
                    url: "processLogin.php",
                    type: "post",
                    data: serializedData
                });

                // Callback handler that will be called on success
                request.done(function (response, textStatus, jqXHR){
                    if (response == true ) {
                        top.location.reload();
                        // top.location.href="/";
                        // $('#successEmail').modal('show');
                    } else {
                        // top.location.reload();
                        $('#failEmail').modal('show');
                    }
                });

                // Callback handler that will be called on failure
                request.fail(function (jqXHR, textStatus, errorThrown){
                    // Log the error to the console
                    // console.error(
                    //     "The following error occurred: "+
                    //     textStatus, errorThrown
                    // );
                    // top.location.reload();
                });

                // Callback handler that will be called regardless
                // if the request failed or succeeded
                request.always(function () {
                    // Reenable the inputs
                    $inputs.prop("disabled", false);
                });

            });
        });
    </script>
</code>```

PHPMailer Form

```<code><?php
    session_start();
?>
<?php
    /**
    * This example shows how to handle a simple contact form.
    */
    $msg = '';

    use PHPMailer\PHPMailer\PHPMailer;

    require './mail/PHPMailer.php';
    require './mail/Exception.php';
    require './mail/SMTP.php';
    require './mail/PHPMailerAutoload.php';

    include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';

    $securimage = new Securimage();

    //Don't run this unless we're handling a form submission
    if (array_key_exists('email', $_POST)) {
        date_default_timezone_set('Etc/UTC');

        //Create a new PHPMailer instance
        $mail = new PHPMailer;

        $mail->SMTPDebug = 0;
        $mail->isSMTP();
        $mail->Host = 'smtp.live.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'email@outlook.com';
        $mail->Password = 'password';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;

        $mail->setFrom('email@outlook.com', 'Mailer');
        $mail->addAddress('email@outlook.com', 'First Last');

        $email = isset($_POST['email']) ? $_POST['email'] : null;
        $name = isset($_POST['name']) ? $_POST['name'] : null;
        $phone = isset($_POST['phone']) ? $_POST['phone'] : null;
        $message = isset($_POST['message']) ? $_POST['message'] : null;

        if ($mail->addReplyTo($_POST['email'], $_POST['name'])) {
            $mail->Subject = 'Contact request';
            $mail->isHTML(true);
            $mail->Body = <<<EOT
    <div style="width:100%">
    <div><label style="color: #044F69; font-weight:bold">Email:</label> <span>{$_POST['email']}</span></div>
    <div><label style="color: #044F69; font-weight:bold">Name:</label> <span>{$_POST['name']}</span></div>
    <div><label style="color: #044F69; font-weight:bold">Phone:</label> <span>{$_POST['phone']}</span></div>
    <div><label style="color: #044F69; font-weight:bold">Message:</label> <span>{$_POST['message']}</span></div>
    </div>
    EOT;

            if ($securimage->check($_POST['captcha_code']) == false) {
                // echo "<meta http-equiv='refresh' content='0'>";
                exit;
            }

            //Send the message, check for errors
            if (!$mail->send()) {
                $msg = 'Sorry, something went wrong. Please try again later.';
            } else {
                header("Location: /");
                exit;
            }
        } else {
            $msg = 'Invalid email address, message ignored.';
        }
    }
    ?>
</code>```

P.S. The code as I have it (See above), shows the fail modal and no reload regardless of whether it passes or fail.

Thanks in advance!

答:
Your callback function for done should only reflect the success condition, while the fail should reflect the alternative.

```<code>// Callback handler that will be called on success
request.done(function(response, textStatus, jqXHR) {
  $('#successEmail').modal('show');
});

// Callback handler that will be called on failure
request.fail(function(jqXHR, textStatus, errorThrown) {
  // Log the error to the console
  // console.error(
  //     "The following error occurred: "+
  //     textStatus, errorThrown
  // );
  $("#failEmail").modal("show");
});
</code>```

As provided/described in your question, reloading the page would prevent the script from getting to show either modal- if you need to reload, you should store a localStorage variable or cookie and test its value on page load to show modal as necessary.

Body:
I have a PHPMailer form and I am using .ajax using this SO answer jquery-ajax-post-example-with-php

It is successfully sending or not sending, so I know the Mailer and captcha are working. Now, if I could get different behaviors for success and fail, that would be great, but I am not getting this right somehow.

PREFERRED BEHAVIORS

SUCCESS --> reload screen and show bootstrap modal with success msg

FAIL --> reload screen and show bootstrap modal with fail msg

I have a lot of code so, Think of the modals as vanilla as possible, and the PHPMailer is, in fact, sending as well. The problem I am having should be in the code below, but if you have to have something else, just ask. Trying to keep the question as decluttered as possible

PHPMailer Form

<?php
    session_start();
?>
<?php
    /**
    * This example shows how to handle a simple contact form.
    */
    $msg = '';

    use PHPMailer\PHPMailer\PHPMailer;

    require './mail/PHPMailer.php';
    require './mail/Exception.php';
    require './mail/SMTP.php';
    require './mail/PHPMailerAutoload.php';

    include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';

    $securimage = new Securimage();

    //Don't run this unless we're handling a form submission
    if (array_key_exists('email', $_POST)) {
        date_default_timezone_set('Etc/UTC');

        //Create a new PHPMailer instance
        $mail = new PHPMailer;

        $mail->SMTPDebug = 0;
        $mail->isSMTP();
        $mail->Host = 'smtp.live.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'email@outlook.com';
        $mail->Password = 'password';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;

        $mail->setFrom('email@outlook.com', 'Mailer');
        $mail->addAddress('email@outlook.com', 'First Last');

        $email = isset($_POST['email']) ? $_POST['email'] : null;
        $name = isset($_POST['name']) ? $_POST['name'] : null;
        $phone = isset($_POST['phone']) ? $_POST['phone'] : null;
        $message = isset($_POST['message']) ? $_POST['message'] : null;

        if ($mail->addReplyTo($_POST['email'], $_POST['name'])) {
            $mail->Subject = 'Contact request';
            $mail->isHTML(true);
            $mail->Body = <<<EOT

Email: {$_POST['email']}

Name: {$_POST['name']}

Phone: {$_POST['phone']}

Message: {$_POST['message']}

    EOT;

            if ($securimage->check($_POST['captcha_code']) == false) {
                // echo "<meta http-equiv='refresh' content='0'>";
                exit;
            }

            //Send the message, check for errors
            if (!$mail->send()) {
                $msg = 'Sorry, something went wrong. Please try again later.';
            } else {
                header("Location: /");
                exit;
            }
        } else {
            $msg = 'Invalid email address, message ignored.';
        }
    }
    ?>

P.S. The code as I have it (See above), shows the fail modal and no reload regardless of whether it passes or fail.

Thanks in advance!

Body:
Your callback function for done should only reflect the success condition, while the fail should reflect the alternative.

// Callback handler that will be called on success
request.done(function(response, textStatus, jqXHR) {
  $('#successEmail').modal('show');
});

// Callback handler that will be called on failure
request.fail(function(jqXHR, textStatus, errorThrown) {
  // Log the error to the console
  // console.error(
  //     "The following error occurred: "+
  //     textStatus, errorThrown
  // );
  $("#failEmail").modal("show");
});

As provided/described in your question, reloading the page would prevent the script from getting to show either modal- if you need to reload, you should store a localStorage variable or cookie and test its value on page load to show modal as necessary.


问:
Can I get Jetty to rewrite Cookie paths?
We've got a lot of applications based on Jetty. For historical reasons; these have been sitting behind Apache servers. One of the duties of Apache has been rewrites, and we want to move to using just Jetty. But we are hitting some snags when it comes to porting it. Specifically Cookie path rewrites. Is it even possible in Jetty?

The original config for Apache looks like this:

```<code>ProxyPassMatch          ^/${basePattern}/${market}/(${appContextName}/.*)                http://127.0.0.1:8080/app/${symbol_dollar}1 retry=0
ProxyPassReverse        /                                                             http://127.0.0.1:8080/

ProxyPassInterpolateEnv on
ProxyPassReverseCookiePath /appCookiePath /${basePattern}/${market}/${appContextName} interpolate
</code>```

I've looked at the code for both Rule (from the rewrite API) as well as Jetty Handlers. I can't really find anything in those APIs that would let me rewrite the Cookies... Any pointers?

答:
There is no built in feature of Jetty for rewriting Set-Cookie headers or Cookie headers.

If you are not afraid of Java code, you could create a CookiePathHandler that is placed at the start of the Server handler list to perform this logic for you in java code.

Pop into jetty-users mailing list or #jetty on chat.freenode.net for help (if you've never written a Jetty handler before)

Body:
We've got a lot of applications based on Jetty. For historical reasons; these have been sitting behind Apache servers. One of the duties of Apache has been rewrites, and we want to move to using just Jetty. But we are hitting some snags when it comes to porting it. Specifically Cookie path rewrites. Is it even possible in Jetty?

The original config for Apache looks like this:

ProxyPassMatch          ^/${basePattern}/${market}/(${appContextName}/.*)                http://127.0.0.1:8080/app/${symbol_dollar}1 retry=0
ProxyPassReverse        /                                                             http://127.0.0.1:8080/

ProxyPassInterpolateEnv on
ProxyPassReverseCookiePath /appCookiePath /${basePattern}/${market}/${appContextName} interpolate

I've looked at the code for both Rule (from the rewrite API) as well as Jetty Handlers. I can't really find anything in those APIs that would let me rewrite the Cookies... Any pointers?


问:
Categorizing data based on the data's signature
Let us say I have some large collection of rows of data, where each element in the row is a (key, value) pair:

```<code>1)    [(bird, "eagle"), (fish, "cod"),      ... , (soda, "coke")]
2)    [(bird, "lark"),  (fish, "bass"),     ...,  (soda, "pepsi")]
n)    ....
n+1)  [(bird, "robin"), (fish, "flounder"), ...,  (soda, "fanta")]
</code>```

I would like the ability to run some computation that would allow me to determine for a new row, what is the row that is "most similar" to this row?

The most direct way I could think of finding the "most similar" row for any particular row is to directly compare said row against all other rows. This is obviously computationally very expensive.

I am looking for a solution of the following form.

A function that can take a row, and generate some derivative integer for that row. This returned integer would be a sort of "signature" of the row. The important property of this signature is that if two rows are very "similar" they would generate very close integers, if rows are very "different", they would generate distant integers. Obviously, if they are identical rows they would generate the same signature.

I could then takes these generated signatures, with the index of the row they point to, and sort them all by their signatures. This data structure I would keep so that I can do fast lookups. Call it database B.

When I have a new row, I wish to know which existent row in database B is most similar, I would:

Generate a signature for the new row

Binary search through the sorted list of (signature,index) in database B for the closet match

Return the closest matching (could be a perfect match) row in database B.

I know their is a lot of hand waving in this question. My problem is that I do not actually know what the function would be that would generate this signature. I see Levenshtein distances, but those represent the transformation cost, not so much the signature. I see that I could try lossy compressions, two things might be "bucketable" as they compress to the same thing. I am looking for other ideas on how to do this.

Thank you.

答:
If you had a lot of data, and wanted to do this hardcore, I would suggest a statistical method like PLSA or PSVM, which can extract identifying topics from text and identify documents with similar topic probabilities.

A simpler, but less accurate way of doing it is using Soundex, which is available for many languages.  You can store the soundex (which will be a short string, not an integer I'm afraid), and look for exact matches to the soundex, which should point to similar rows.

I think it's unrealistic to expect a function to turn a series of strings into an integer such that integers near each other map to similar strings.  The closest you might come is doing a checksum on each individual tuple, and comparing the checksums for the new row to the checksums of existing rows, but I'm guessing you're trying to come up with a single number you can index on.

Body:
Let us say I have some large collection of rows of data, where each element in the row is a (key, value) pair:

1)    [(bird, "eagle"), (fish, "cod"),      ... , (soda, "coke")]
2)    [(bird, "lark"),  (fish, "bass"),     ...,  (soda, "pepsi")]
n)    ....
n+1)  [(bird, "robin"), (fish, "flounder"), ...,  (soda, "fanta")]

I would like the ability to run some computation that would allow me to determine for a new row, what is the row that is "most similar" to this row?

The most direct way I could think of finding the "most similar" row for any particular row is to directly compare said row against all other rows. This is obviously computationally very expensive.

I am looking for a solution of the following form.

A function that can take a row, and generate some derivative integer for that row. This returned integer would be a sort of "signature" of the row. The important property of this signature is that if two rows are very "similar" they would generate very close integers, if rows are very "different", they would generate distant integers. Obviously, if they are identical rows they would generate the same signature.

I could then takes these generated signatures, with the index of the row they point to, and sort them all by their signatures. This data structure I would keep so that I can do fast lookups. Call it database B.

When I have a new row, I wish to know which existent row in database B is most similar, I would:

Generate a signature for the new row

Binary search through the sorted list of (signature,index) in database B for the closet match

Return the closest matching (could be a perfect match) row in database B.

I know their is a lot of hand waving in this question. My problem is that I do not actually know what the function would be that would generate this signature. I see Levenshtein distances, but those represent the transformation cost, not so much the signature. I see that I could try lossy compressions, two things might be "bucketable" as they compress to the same thing. I am looking for other ideas on how to do this.

Thank you.


问:
How to specify a multi-column UNIQUE constraint in code-first Entity Framework fluent API
Suppose I have the following entities:

```<code>public class Calendar{
    public int ID{get;set;}
    public ICollection<Day> Days { get; set; }
}
public class Day{
    public int ID{get;set;}
    public DateTime Date{get;set;}
    public int CalendarID{get;set;}
}
</code>```

This is a one-to-many relationship with CalendarID as a foreign key. The issue is I also want to make sure that each date exists only once in each calendar. That is, no two days have both the same Date and same CalendarID. In raw SQL I can do this by:

```<code>ALTER TABLE Days
ADD CONSTRAINT UN_Day UNIQUE ([Date],CalendarID);
</code>```

However, Entity Framework won't know I want this when it creates the table automatically. How can I specify this in the fluent API?

答:
See Configuring an Index on one or more properties.

In your mapping class, assuming it extends from EntityTypeConfiguration<Day> then you will need to add using System.Data.Entity.Infrastructure.Annotations; and do the following:

```<code>this.Property(x => x.Date)
    .HasColumnAnnotation(IndexAnnotation.AnnotationName,
                 new IndexAnnotation(new IndexAttribute("UN_Day", 0) { IsUnique = true }));

this.Property(x => x.CalendarID)
    .HasColumnAnnotation(IndexAnnotation.AnnotationName,
                 new IndexAnnotation(new IndexAttribute("UN_Day", 1) { IsUnique = true }));
</code>```

Body:
Suppose I have the following entities:

public class Calendar{
    public int ID{get;set;}
    public ICollection<Day> Days { get; set; }
}
public class Day{
    public int ID{get;set;}
    public DateTime Date{get;set;}
    public int CalendarID{get;set;}
}

This is a one-to-many relationship with CalendarID as a foreign key. The issue is I also want to make sure that each date exists only once in each calendar. That is, no two days have both the same Date and same CalendarID. In raw SQL I can do this by:

ALTER TABLE Days
ADD CONSTRAINT UN_Day UNIQUE ([Date],CalendarID);

However, Entity Framework won't know I want this when it creates the table automatically. How can I specify this in the fluent API?

Body:
See Configuring an Index on one or more properties.

In your mapping class, assuming it extends from EntityTypeConfiguration<Day> then you will need to add using System.Data.Entity.Infrastructure.Annotations; and do the following:

this.Property(x => x.Date)
    .HasColumnAnnotation(IndexAnnotation.AnnotationName,
                 new IndexAnnotation(new IndexAttribute("UN_Day", 0) { IsUnique = true }));

this.Property(x => x.CalendarID)
    .HasColumnAnnotation(IndexAnnotation.AnnotationName,
                 new IndexAnnotation(new IndexAttribute("UN_Day", 1) { IsUnique = true }));


问:
How to sort a multidimensional array on PHP where keys are not string labels
I have this multidimensional array:

```<code>$serviceTimes = Array (
  [0] => Array ( [0] => PM1900 [1] => 7:00pm )
  [1] => Array ( [0] => PM1900 [1] => 7:00pm )
  [2] => Array ( [0] => PM1415 [1] => 2:15pm )
  [3] => Array ( [0] => PM1919 [1] => 7:19pm )
  [6] => Array ( [0] => PM2020 [1] => 8:20pm )
)
</code>```

But I am unable to sort the array on the [0] element. This does not work:

array_multisort( $serviceTimes[0], SORT_ASC, $serviceTimes );

nor does this work

array_multisort( $serviceTimes[][0], SORT_ASC, $serviceTimes );

Any thoughts?

Ideally and ultimately, this is what I am looking to produce:

```<code>Array (
  [0] => 2:15pm )
  [1] => 7:00pm )
  [2] => 7:00pm )
  [3] => 7:19pm )
  [4] => 8:20pm )
)
</code>```

答:
Generally, you may also use usort() with you own compoare function for this kind of custom sort (all functions prefixed with "u" : usort, uasort, uksort...)</p>

```<code><?php
function mysort ($a, $b){
    return strcmp($a[0], $b[0]);
}

$serviceTimes = array ( 0 => array ( 0 => 'PM1900', 1 => '7:00pm', ), 1 => array ( 0 => 'PM1900', 1 => '7:00pm', ), 2 => array ( 0 => 'PM1415', 1 => '2:15pm', ), 3 => array ( 0 => 'PM1919', 1 => '7:19pm', ), 4 => array ( 0 => 'PM2020', 1 => '8:20pm', ), );

usort($serviceTimes, 'mysort');

var_dump(serviceTimes);
</code>```

Body:
I have this multidimensional array:

$serviceTimes = Array (
  [0] => Array ( [0] => PM1900 [1] => 7:00pm )
  [1] => Array ( [0] => PM1900 [1] => 7:00pm )
  [2] => Array ( [0] => PM1415 [1] => 2:15pm )
  [3] => Array ( [0] => PM1919 [1] => 7:19pm )
  [6] => Array ( [0] => PM2020 [1] => 8:20pm )
)

But I am unable to sort the array on the [0] element. This does not work:

array_multisort( $serviceTimes[0], SORT_ASC, $serviceTimes );

nor does this work

array_multisort( $serviceTimes[][0], SORT_ASC, $serviceTimes );

Any thoughts?

Ideally and ultimately, this is what I am looking to produce:

Array (
  [0] => 2:15pm )
  [1] => 7:00pm )
  [2] => 7:00pm )
  [3] => 7:19pm )
  [4] => 8:20pm )
)

Body:
Generally, you may also use usort() with you own compoare function for this kind of custom sort (all functions prefixed with "u" : usort, uasort, uksort...)

<?php
function mysort ($a, $b){
    return strcmp($a[0], $b[0]);
}

$serviceTimes = array ( 0 => array ( 0 => 'PM1900', 1 => '7:00pm', ), 1 => array ( 0 => 'PM1900', 1 => '7:00pm', ), 2 => array ( 0 => 'PM1415', 1 => '2:15pm', ), 3 => array ( 0 => 'PM1919', 1 => '7:19pm', ), 4 => array ( 0 => 'PM2020', 1 => '8:20pm', ), );

usort($serviceTimes, 'mysort');

var_dump(serviceTimes);


问:
Best practice Joomla multilingual country list database tables?
What is the best practice to design multilingual database tables which contains translated country specific data depending on the users language in Joomla?

I can not add a language key row like used in other Joomla database tables like for com_content because some rows are and must be unique.

This is the current database table

Image 1: Current database table content

Image 2: Current database table structure

Image 3: Current database table Indexes

This is the result I need.

Data for language A

```<code>ID| Name     | Code3 | Code2 | TaxRateID | EU
- - - - - - - - - - - - - - - - - - - - - -
12  Aruba       ABW     AW         1       0
13  Australia   AUS     AU         1       0
14  Austria     AUT     AT         2       1
</code>```

Data for language B

```<code>ID | Name     | Code3 | Code2 | TaxRateID | EU
- - - - - - - - - - - - - - - - - - - - - - -
12  Aruba        ABW     AW         1       0
13  Australien   AUS     AU         1       0
14  Österreich   AUT     AT         2       1
</code>```

Should I add extra tables with an language suffix for each language?

```<code>prefix_table_LANGUAGE
</code>```

Or is there an other and better way?
Thanks in advance!

答:
Since you're creating your own component, you don't need to use Joomla's native multilingual feature.

I'd keep your table as is, using the name as fallback for missing translations. Add another table, country_names, with language and code3 as primary key, to keep the translated country names.

So you'll end up with (simplified)

```<code>#__countries {
    id,
    name,
    code3,
    code2,
    tax_rate_id,
    eu
}
</code>```

and

```<code>#__country_names {
    code3,
    language,
    name
}
</code>```

Your query would look like this:

```<code>   SELECT a.id, COALESCE(b.name, a.name) AS name, a.code3, a.code2, a.tax_rate_id, a.eu
     FROM #__countries AS a
LEFT JOIN #__country_names AS b ON (a.code3=b.code3 AND b.language=$lang)
</code>```

(not tested - take it as a sketch).

Body:
What is the best practice to design multilingual database tables which contains translated country specific data depending on the users language in Joomla?

I can not add a language key row like used in other Joomla database tables like for com_content because some rows are and must be unique.

This is the current database table

Image 1: Current database table content

Image 2: Current database table structure

Image 3: Current database table Indexes

This is the result I need.

Data for language A

ID| Name     | Code3 | Code2 | TaxRateID | EU
- - - - - - - - - - - - - - - - - - - - - -
12  Aruba       ABW     AW         1       0
13  Australia   AUS     AU         1       0
14  Austria     AUT     AT         2       1

Data for language B

ID | Name     | Code3 | Code2 | TaxRateID | EU
- - - - - - - - - - - - - - - - - - - - - - -
12  Aruba        ABW     AW         1       0
13  Australien   AUS     AU         1       0
14  Österreich   AUT     AT         2       1

Should I add extra tables with an language suffix for each language?

prefix_table_LANGUAGE

Or is there an other and better way?
Thanks in advance!

Body:
Since you're creating your own component, you don't need to use Joomla's native multilingual feature.

I'd keep your table as is, using the name as fallback for missing translations. Add another table, country_names, with language and code3 as primary key, to keep the translated country names.

So you'll end up with (simplified)

#__countries {
    id,
    name,
    code3,
    code2,
    tax_rate_id,
    eu
}

and

#__country_names {
    code3,
    language,
    name
}

Your query would look like this:

   SELECT a.id, COALESCE(b.name, a.name) AS name, a.code3, a.code2, a.tax_rate_id, a.eu
     FROM #__countries AS a
LEFT JOIN #__country_names AS b ON (a.code3=b.code3 AND b.language=$lang)

(not tested - take it as a sketch).


问:
How can I convert an HTML element to a canvas element?
It would be incredibly useful to be able to temporarily convert a regular element into a canvas. For example, say I have a styled div that I want to flip. I want to dynamically create a canvas, "render" the HTMLElement into the canvas, hide the original element and animate the canvas.

Can it be done?

答:
the next code can be used in 2 modes, mode 1 save the html code to a image, mode 2 save the html code to a canvas.

this code work with the library: https://github.com/tsayen/dom-to-image

*the "id_div" is the id of the element html that you want to transform.

**the "canvas_out" is the id of the div that will contain the canvas
 so try this code.
:

```<code>   function Guardardiv(id_div){

      var mode = 2 // default 1 (save to image), mode 2 = save to canvas
      console.log("Process start");
      var node = document.getElementById(id_div);
      // get the div that will contain the canvas
      var canvas_out = document.getElementById('canvas_out');
      var canvas = document.createElement('canvas');
      canvas.width = node.scrollWidth;
      canvas.height = node.scrollHeight;

      domtoimage.toPng(node).then(function (pngDataUrl) {
          var img = new Image();
          img.onload = function () {
          var context = canvas.getContext('2d');
          context.drawImage(img, 0, 0);
        };

        if (mode == 1){ // save to image
             downloadURI(pngDataUrl, "salida.png");
        }else if (mode == 2){ // save to canvas
          img.src = pngDataUrl;
          canvas_out.appendChild(img);

        }
      console.log("Process finish");
    });

    }
</code>```

so, if you want to save to image just add this function:

```<code>    function downloadURI(uri, name) {
        var link = document.createElement("a");

        link.download = name;
        link.href = uri;
        document.body.appendChild(link);
        link.click();
    }
</code>```

Example of use:

```<code> <html>
 <head>
 </script src="/dom-to-image.js"></script>
 </head>
 <body>
 <div id="container">
   All content that want to transform
  </div>
  <button onclick="Guardardiv('container');">Convert<button>

 <!-- if use mode 2 -->
 <div id="canvas_out"></div>
 </html>
</code>```

Comment if that work.
Comenten si les sirvio :)

Body:
the next code can be used in 2 modes, mode 1 save the html code to a image, mode 2 save the html code to a canvas.

this code work with the library: https://github.com/tsayen/dom-to-image

*the "id_div" is the id of the element html that you want to transform.

**the "canvas_out" is the id of the div that will contain the canvas
 so try this code.
:

   function Guardardiv(id_div){

      var mode = 2 // default 1 (save to image), mode 2 = save to canvas
      console.log("Process start");
      var node = document.getElementById(id_div);
      // get the div that will contain the canvas
      var canvas_out = document.getElementById('canvas_out');
      var canvas = document.createElement('canvas');
      canvas.width = node.scrollWidth;
      canvas.height = node.scrollHeight;

      domtoimage.toPng(node).then(function (pngDataUrl) {
          var img = new Image();
          img.onload = function () {
          var context = canvas.getContext('2d');
          context.drawImage(img, 0, 0);
        };

        if (mode == 1){ // save to image
             downloadURI(pngDataUrl, "salida.png");
        }else if (mode == 2){ // save to canvas
          img.src = pngDataUrl;
          canvas_out.appendChild(img);

        }
      console.log("Process finish");
    });

    }

so, if you want to save to image just add this function:

    function downloadURI(uri, name) {
        var link = document.createElement("a");

        link.download = name;
        link.href = uri;
        document.body.appendChild(link);
        link.click();
    }

Example of use:

 <html>
 <head>
 </script src="/dom-to-image.js"></script>
 </head>
 <body>
 <div id="container">
   All content that want to transform
  </div>
  <button onclick="Guardardiv('container');">Convert<button>

 <!-- if use mode 2 -->
 <div id="canvas_out"></div>
 </html>

Comment if that work.
Comenten si les sirvio :)


问:
Where is my mistake - Date calculator for selectbox in Javascript/jQuery?
```<code>$(.dateselboxes) .change( function(){

var y; y=$("#year").val();
var m; m=$("#month").val();
var d;
</code>```

// check leap year

```<code>var leapYear;
if(y%4==0)
{
    if(y%100==0)
    {
        if(y%400==0) {leapYear=true;}
        else {leapYear=false;}
    }
    else {leapYear=true;}
}
else {leapYear=false;}
</code>```

// calculate the number of days

```<code>var dz;
if(m==1 || m=3 || m=5 || m=7 || m=8 || m=10 || m=12) {dz=31;}
else if(m==2)
    {
        if(leapYear==true) {dz=29;}
        else {dz=28;}
    }
else {dz=30;}
</code>```

// remove last option a couple of times

```<code>switch(dz)
    {
        case 28:
            for(i=0;i<3;i++)
            {$("#day option:last").remove();}
            break;
        case 29:
            for(i=0;i<2;i++)
            {$("#day option:last").remove();}
            break;
        case 30:
            $("#day option:last").remove();
            break;
        default:
            var axaxax=0;
            break;
    }
</code>```

});

答:
The problem is with assigning (=) to variable m instead of comparing (==)

```<code>if(m==1 || m==3 || m==5 || m==7 || m==8 || m==10 || m==12) {dz=31;}
</code>```

As a side note, you could rewrite some parts of your script.

leapYear var - this uses 2 statements to reduce it yet still keep it readable.

```<code>leapYear = (y%4==0);
if (leapYear && (y%100==0) && !(y%400==0))
    leapYear=false;
</code>```

to remove the last options (0-indexed)

```<code>{$("#day option:gt(" + dz + ")").remove();}
</code>```

Body:
$(.dateselboxes) .change( function(){

var y; y=$("#year").val();
var m; m=$("#month").val();
var d;

// check leap year

var leapYear;
if(y%4==0)
{
    if(y%100==0)
    {
        if(y%400==0) {leapYear=true;}
        else {leapYear=false;}
    }
    else {leapYear=true;}
}
else {leapYear=false;}

// calculate the number of days

var dz;
if(m==1 || m=3 || m=5 || m=7 || m=8 || m=10 || m=12) {dz=31;}
else if(m==2)
    {
        if(leapYear==true) {dz=29;}
        else {dz=28;}
    }
else {dz=30;}

// remove last option a couple of times

switch(dz)
    {
        case 28:
            for(i=0;i<3;i++)
            {$("#day option:last").remove();}
            break;
        case 29:
            for(i=0;i<2;i++)
            {$("#day option:last").remove();}
            break;
        case 30:
            $("#day option:last").remove();
            break;
        default:
            var axaxax=0;
            break;
    }

});

Body:
The problem is with assigning (=) to variable m instead of comparing (==)

if(m==1 || m==3 || m==5 || m==7 || m==8 || m==10 || m==12) {dz=31;}

As a side note, you could rewrite some parts of your script.

leapYear var - this uses 2 statements to reduce it yet still keep it readable.

leapYear = (y%4==0);
if (leapYear && (y%100==0) && !(y%400==0))
    leapYear=false;

to remove the last options (0-indexed)

{$("#day option:gt(" + dz + ")").remove();}


问:
Can I pass additional parameters into an inline usort function?
Consider the following code:

```<code>$external_variable = TRUE;
usort($array, function($a, $b) {
    // do sorting stuff based on $external_variable
});
</code>```

How can I access and use $external_variable within the usort function?

答:
Using the use keyword:

```<code>$external_variable = TRUE;

usort($array, function($a, $b) use($external_variable) {
    // do sorting stuff based on $external_variable
});
</code>```

http://php.net/manual/en/functions.anonymous.php

Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct. From PHP 7.1, these variables must not include superglobals, $this, or variables with the same name as a parameter.

Body:
Consider the following code:

$external_variable = TRUE;
usort($array, function($a, $b) {
    // do sorting stuff based on $external_variable
});

How can I access and use $external_variable within the usort function?

Body:
Using the use keyword:

$external_variable = TRUE;

usort($array, function($a, $b) use($external_variable) {
    // do sorting stuff based on $external_variable
});

http://php.net/manual/en/functions.anonymous.php

Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct. From PHP 7.1, these variables must not include superglobals, $this, or variables with the same name as a parameter.


问:
How can I exclude the past (past days) using moment js?
I simply need to disable all past days from this date picker:

```<code><DatePicker
   todayButton={"Today"}
   selected={this.state.day}
   onChange={this.onDateChange}
   excludeDates={[moment(), moment().subtract(1, 'days') ]}
   isClearable={true}
   placeholderText="Choose date"
/>
</code>```

Dynamically subtract all past days.

答:
Alright there is minDate prop.</p>

```<code><DatePicker
  todayButton={"Today"}
  selected={this.state.day}
  onChange={this.onDateChange}
  minDate={moment()}
  isClearable={true}
  placeholderText="Choose date"
/>
</code>```

Body:
I simply need to disable all past days from this date picker:

<DatePicker
   todayButton={"Today"}
   selected={this.state.day}
   onChange={this.onDateChange}
   excludeDates={[moment(), moment().subtract(1, 'days') ]}
   isClearable={true}
   placeholderText="Choose date"
/>

Dynamically subtract all past days.

Body:
Alright there is minDate prop.

<DatePicker
  todayButton={"Today"}
  selected={this.state.day}
  onChange={this.onDateChange}
  minDate={moment()}
  isClearable={true}
  placeholderText="Choose date"
/>