问:
Faster way to calculate driving distance to many points
I am trying to calculate the driving distance from one origin point and then to many different destinations points (I need to find the closest driver).
I use PHP and I basically run this function many times:

```<code>file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/json?origins=' . $latitude . ',' . $longitude . '&destinations=' . $latitude1 . ',' . $longitude1 . '&mode=car&language=da-DK&key=My_API&alternatives=false&sensor=false');
</code>```

I need the distance from latitude, longitude and in some cases 40+ different potential destinations.
My problem is, that it takes forever to calculate the many points one call at the time. It takes 51-56 sec to find the distance from the one origin point to 37 different potential destination points.

Is there a faster way? or service ?

I wish you all a great day.

best regards

答:
I did start out with the nodejs, and that did also do it. However I managed to find an even smarter way.
Efter more intense reading, google can actually you do it for you.

It is posible to enter one origin and multiple destinations.
origins=lat,lng&destinations=lat1,lng1|lat2,lng2|...latn,lngn&

simply use |  to divide destinations.

I went from 51 seconds to 2 seconds.

Body:
I am trying to calculate the driving distance from one origin point and then to many different destinations points (I need to find the closest driver).
I use PHP and I basically run this function many times:

file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/json?origins=' . $latitude . ',' . $longitude . '&destinations=' . $latitude1 . ',' . $longitude1 . '&mode=car&language=da-DK&key=My_API&alternatives=false&sensor=false');

I need the distance from latitude, longitude and in some cases 40+ different potential destinations.
My problem is, that it takes forever to calculate the many points one call at the time. It takes 51-56 sec to find the distance from the one origin point to 37 different potential destination points.

Is there a faster way? or service ?

I wish you all a great day.

best regards


来源: stackexchange

问:
Added new entity to model - although it doesnt show up in generated code
I have added a new entity to our edmx. We have the ..dataaccess.g.cs file that is generated. This generated file does not seem to show the new entity I created, even when I delete it and rebuild our Entity project. I need this because it is a navigation property that we need to be able to access. any thoughts would be appreciated.</p>

答: I was missing some needed namespaces in a partial classes that we created off this domain service</p>

ContentLicense: CC BY-SA 2.5


问:
How to configure spring boot resttemplate proxy for client and server
I have an architecture where my server component will be deployed on separate host and client component (UI) will be deployed on separate.

I am stuck with RestTemplate Proxy, can someone please help me how can I achieve it.

Below is the example, I am trying to follow, but not sure if its the right approach.

```<code>@Value("${generic.proxyHost}")
private String proxyHost;

@Value("${generic.proxyPort}")
private Integer proxyPort;

@Bean
public RestTemplate restTemplate() {

    LOGGER.info("Setting up proxy with HOSTNAME => " + proxyHost + " and PORT => " + proxyPort);

    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();

    Proxy proxy= new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
    requestFactory.setProxy(proxy);

    return new RestTemplate(requestFactory);
}
</code>```

Also it would be help if I can know how to handle multipart file request.

Any help will be greatly appericiated.

答:
I need to consume REST API on separate host and I am just looking for an example. I just googled around the stuff but no luck

There's a nice tutorial about Rest Template at Baeldung's blog.

You could use this simple example to understand how to use it:

```<code>RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl = "http://localhost:8080/spring-rest/foos";
ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
</code>```

There's a plenty of examples in the article I linked above that will help you during your learn path.

Also it would be help if I can know how to handle multipart file request.

I believe that this other question has the information you need to start implementing this use case.

Cheers!

ContentLicense: CC BY-SA 3.0

Body:
I have an architecture where my server component will be deployed on separate host and client component (UI) will be deployed on separate.

I am stuck with RestTemplate Proxy, can someone please help me how can I achieve it.

Below is the example, I am trying to follow, but not sure if its the right approach.

@Value("${generic.proxyHost}")
private String proxyHost;

@Value("${generic.proxyPort}")
private Integer proxyPort;

@Bean
public RestTemplate restTemplate() {

    LOGGER.info("Setting up proxy with HOSTNAME => " + proxyHost + " and PORT => " + proxyPort);

    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();

    Proxy proxy= new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
    requestFactory.setProxy(proxy);

    return new RestTemplate(requestFactory);
}

Also it would be help if I can know how to handle multipart file request.

Any help will be greatly appericiated.

Body:
I need to consume REST API on separate host and I am just looking for an example. I just googled around the stuff but no luck

There's a nice tutorial about Rest Template at Baeldung's blog.

You could use this simple example to understand how to use it:

RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl = "http://localhost:8080/spring-rest/foos";
ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));

There's a plenty of examples in the article I linked above that will help you during your learn path.

Also it would be help if I can know how to handle multipart file request.

I believe that this other question has the information you need to start implementing this use case.

Cheers!


问:
How to put cardviews textview values in edittext in a fragment?
I try to describe actually what i want to do using below image

According to my image 2nd request details is a number of cardviews which is added onclick of Add button and when i click on editImageButton then all textview values will again put on edittext of first request details. And there are two fragments 1.NewRequest 2.ModifyRequest and when i open 1 fragment editImageButton will be invisible and in 2 fragment it will be visible. But i cant understand how to to this.Please suggest me.

Adapter Class

```<code>public class TravelRequestDetailAdapter extends BaseAdapter {

private final LayoutInflater layoutInflater;
private List<TravelRequestAddDetails> mDataset;
private RequestDetailsFragment mContext;
private RequestDetailModification modification;

static class ViewHolder {
    TextView TrDate, TrFrom, TrTo, TrAmount, TrDesc;
    ImageButton RemoveItem, editItem;
}

@Override
public int getCount() {
    return mDataset.size();
}

@Override
public TravelRequestAddDetails getItem(int position) {
    return mDataset.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

public void removeItem(int position) {
    try {
        mDataset.remove(position);
        notifyDataSetChanged();
        mContext.updateTotalAmount();
        modification.updateTotalAmount();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView == null) {
        convertView = layoutInflater.inflate(R.layout.travel_request_adddetails, parent, false);
        viewHolder = new ViewHolder();
        viewHolder.TrDate = (TextView) convertView.findViewById(R.id.TDate);
        viewHolder.TrFrom = (TextView) convertView.findViewById(R.id.TFrom);
        viewHolder.TrTo = (TextView) convertView.findViewById(R.id.TTo);
        viewHolder.TrAmount = (TextView) convertView.findViewById(R.id.TAmount);
        viewHolder.TrDesc = (TextView) convertView.findViewById(R.id.TDesc);
        viewHolder.RemoveItem = (ImageButton) convertView.findViewById(R.id.btn_delete);
        viewHolder.editItem = (ImageButton) convertView.findViewById(R.id.btn_edit);
        convertView.setTag(viewHolder);
    }

    viewHolder = (ViewHolder) convertView.getTag();

    viewHolder.TrDate.setText(getItem(position).getTRAVELDATE());
    viewHolder.TrFrom.setText(getItem(position).getTRAVELFROM());
    viewHolder.TrTo.setText(getItem(position).getTRAVELTO());
    viewHolder.TrAmount.setText(getItem(position).getAMOUNT());
    viewHolder.TrDesc.setText(getItem(position).getDESCRIPTION());

    viewHolder.RemoveItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            removeItem(position);
        }
    });

  //  viewHolder.editItem.setVisibility(View.GONE);
    viewHolder.editItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            modification.editRequest();
        }
    });
    return convertView;
}

public TravelRequestAddDetails getIteam(int position) {
    return mDataset.get(position);
}

public TravelRequestDetailAdapter(List<TravelRequestAddDetails> myDataset, RequestDetailsFragment mContext) {
    mDataset = myDataset;
    this.mContext = mContext;
    layoutInflater = (LayoutInflater) mContext.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public TravelRequestDetailAdapter(List<TravelRequestAddDetails> myDataset, RequestDetailModification mContext) {
    mDataset = myDataset;
    this.modification = mContext;
    layoutInflater = (LayoutInflater) mContext.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}}
</code>```

Pojo class

```<code>public class TravelRequestAddDetails {

@SerializedName("REIMBURSEMENT_DTL_ID")
@Expose
private Integer rEIMBURSEMENTDTLID;
@SerializedName("REIMBURSEMENT_HDR_ID")
@Expose
private Integer rEIMBURSEMENTHDRID;
@SerializedName("TRAVEL_DATE")
@Expose
private String tRAVELDATE;
@SerializedName("TRAVEL_FROM")
@Expose
private String tRAVELFROM;

@SerializedName("TRAVEL_TO")
@Expose
private String tRAVELTO;
@SerializedName("AMOUNT")
@Expose
private String aMOUNT;
@SerializedName("DESCRIPTION")
@Expose
private String dESCRIPTION;

public TravelRequestAddDetails() {
}

public TravelRequestAddDetails(String tRAVELDATE, String tRAVELFROM, String tRAVELTO, String aMOUNT, String dESCRIPTION) {
    this.tRAVELDATE = tRAVELDATE;
    this.tRAVELFROM = tRAVELFROM;
    this.tRAVELTO = tRAVELTO;
    this.aMOUNT = aMOUNT;
    this.dESCRIPTION = dESCRIPTION;
}
public Integer getREIMBURSEMENTDTLID() {
    return rEIMBURSEMENTDTLID;
}

public void setREIMBURSEMENTDTLID(Integer rEIMBURSEMENTDTLID) {
    this.rEIMBURSEMENTDTLID = rEIMBURSEMENTDTLID;
}

public Integer getREIMBURSEMENTHDRID() {
    return rEIMBURSEMENTHDRID;
}

public void setREIMBURSEMENTHDRID(Integer rEIMBURSEMENTHDRID) {
    this.rEIMBURSEMENTHDRID = rEIMBURSEMENTHDRID;
}

public String getTRAVELDATE() {
    return tRAVELDATE;
}

public String setTRAVELDATE(String tRAVELDATE) {
    this.tRAVELDATE = tRAVELDATE;
    return tRAVELDATE;
}

public String getTRAVELFROM() {
    return tRAVELFROM;
}

public String setTRAVELFROM(String tRAVELFROM) {
    this.tRAVELFROM = tRAVELFROM;
    return tRAVELFROM;
}

public String getTRAVELTO() {
    return tRAVELTO;
}

public String setTRAVELTO(String tRAVELTO) {
    this.tRAVELTO = tRAVELTO;
    return tRAVELTO;
}

public String getAMOUNT() {
    return aMOUNT;
}

public String setAMOUNT(String aMOUNT) {
    this.aMOUNT = aMOUNT;
    return aMOUNT;
}

public String getDESCRIPTION() {
    return dESCRIPTION;
}

public String setDESCRIPTION(String dESCRIPTION) {
    this.dESCRIPTION = dESCRIPTION;
    return dESCRIPTION;
}
</code>```

ModificationFragment Class

```<code>   public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.travel_request, container, false);
    approverList=new ArrayList<>();
    travelRequestAddDetailses = new ArrayList<>();
    mAdapter = new TravelRequestDetailAdapter(travelRequestAddDetailses, this);
    requestDetailsList = (ListView) rootView.findViewById(R.id.TravelRequestAdd);
    requestDetailsList.setAdapter(mAdapter);

    LayoutInflater inflaterHeader = getActivity().getLayoutInflater();
    ViewGroup header = (ViewGroup) inflaterHeader.inflate(
            R.layout.lc_modification, requestDetailsList, false);
    requestDetailsList.addHeaderView(header);

    LayoutInflater inflaterFooter = getActivity().getLayoutInflater();
    ViewGroup footer = (ViewGroup) inflaterFooter.inflate(
            R.layout.travel_details_footer, requestDetailsList, false);
    requestDetailsList.addFooterView(footer);
    raisedBy = (TextView) rootView.findViewById(R.id.text_raised);

    approver = (TextView) rootView.findViewById(R.id.text_approver);
    recyclerView = (RecyclerView) rootView.findViewById(R.id.wq_approver_recycler_view);
    recyclerView.setHasFixedSize(true);
    list = new ArrayList<>();
    circleProgressBar = (CircleProgressBar) rootView.findViewById(R.id.progressBar);
    travelFrom = (EditText) rootView.findViewById(R.id.txt_travel_from);
    travelTo = (EditText) rootView.findViewById(R.id.txt_travel_to);
    travelAmount = (EditText) rootView.findViewById(R.id.txt_amount);
    travelDesc = (EditText) rootView.findViewById(R.id.txt_desc);
    remark = (EditText) rootView.findViewById(R.id.remark);
    documentList = (ListView) rootView.findViewById(R.id.documentList);
    textViewTotal = (TextView) rootView.findViewById(R.id.txt_totalAmount);

    selectDate = (TextView) rootView.findViewById(R.id.raiseddate);
    dateFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
    selectTravelDate = (EditText) rootView.findViewById(R.id.texttravelDate);
    selectTravelDate.setInputType(InputType.TYPE_NULL);

    selectTravelDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectTravellingDate();
        }
    });
    imgSelectedfile = (ImageView) rootView.findViewById(R.id.IVPCUploadDoc);
    imgSelectedfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openFileChooser();
        }
    });

    btn_add = (Button) rootView.findViewById(R.id.addButton);
    btn_add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (validateData(v)) {
                addRequestDetails();
                updateTotalAmount();
            }

        }
    });
    setRequestDetails();
    return rootView;
}

 public void addRequestDetails() {
    TravelRequestAddDetails obj = new TravelRequestAddDetails(selectTravelDate.getText().toString(),
            travelFrom.getText().toString(),
            travelTo.getText().toString(),
            travelAmount.getText().toString(),
            travelDesc.getText().toString());

    travelRequestAddDetailses.add(obj);
    mAdapter.notifyDataSetChanged();

    selectTravelDate.setText("");
    travelFrom.setText("");
    travelTo.setText("");
    travelAmount.setText("");
    travelDesc.setText("");

}

public void updateTotalAmount() {
    int total = 0;
    if (travelRequestAddDetailses != null && !travelRequestAddDetailses.isEmpty()) {
        for (TravelRequestAddDetails travelRequestAddDetails : travelRequestAddDetailses) {
            total = Integer.parseInt(travelRequestAddDetails.getAMOUNT()) + total;
        }
    }
    textViewTotal.setText(total + "");
}
public void editRequest(){

    for(int i=0;i<travelRequestAddDetailses.size();i++) {
      //  selectTravelDate.setText();

    }
}}
</code>```

答: Better to store your savings in some local databaase or in Shared Preferences. And then access them whenever you want them. </p>

Body:
I try to describe actually what i want to do using below image

According to my image 2nd request details is a number of cardviews which is added onclick of Add button and when i click on editImageButton then all textview values will again put on edittext of first request details. And there are two fragments 1.NewRequest 2.ModifyRequest and when i open 1 fragment editImageButton will be invisible and in 2 fragment it will be visible. But i cant understand how to to this.Please suggest me.

Adapter Class

public class TravelRequestDetailAdapter extends BaseAdapter {

private final LayoutInflater layoutInflater;
private List<TravelRequestAddDetails> mDataset;
private RequestDetailsFragment mContext;
private RequestDetailModification modification;

static class ViewHolder {
    TextView TrDate, TrFrom, TrTo, TrAmount, TrDesc;
    ImageButton RemoveItem, editItem;
}

@Override
public int getCount() {
    return mDataset.size();
}

@Override
public TravelRequestAddDetails getItem(int position) {
    return mDataset.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

public void removeItem(int position) {
    try {
        mDataset.remove(position);
        notifyDataSetChanged();
        mContext.updateTotalAmount();
        modification.updateTotalAmount();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView == null) {
        convertView = layoutInflater.inflate(R.layout.travel_request_adddetails, parent, false);
        viewHolder = new ViewHolder();
        viewHolder.TrDate = (TextView) convertView.findViewById(R.id.TDate);
        viewHolder.TrFrom = (TextView) convertView.findViewById(R.id.TFrom);
        viewHolder.TrTo = (TextView) convertView.findViewById(R.id.TTo);
        viewHolder.TrAmount = (TextView) convertView.findViewById(R.id.TAmount);
        viewHolder.TrDesc = (TextView) convertView.findViewById(R.id.TDesc);
        viewHolder.RemoveItem = (ImageButton) convertView.findViewById(R.id.btn_delete);
        viewHolder.editItem = (ImageButton) convertView.findViewById(R.id.btn_edit);
        convertView.setTag(viewHolder);
    }

    viewHolder = (ViewHolder) convertView.getTag();

    viewHolder.TrDate.setText(getItem(position).getTRAVELDATE());
    viewHolder.TrFrom.setText(getItem(position).getTRAVELFROM());
    viewHolder.TrTo.setText(getItem(position).getTRAVELTO());
    viewHolder.TrAmount.setText(getItem(position).getAMOUNT());
    viewHolder.TrDesc.setText(getItem(position).getDESCRIPTION());

    viewHolder.RemoveItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            removeItem(position);
        }
    });

  //  viewHolder.editItem.setVisibility(View.GONE);
    viewHolder.editItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            modification.editRequest();
        }
    });
    return convertView;
}

public TravelRequestAddDetails getIteam(int position) {
    return mDataset.get(position);
}

public TravelRequestDetailAdapter(List<TravelRequestAddDetails> myDataset, RequestDetailsFragment mContext) {
    mDataset = myDataset;
    this.mContext = mContext;
    layoutInflater = (LayoutInflater) mContext.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public TravelRequestDetailAdapter(List<TravelRequestAddDetails> myDataset, RequestDetailModification mContext) {
    mDataset = myDataset;
    this.modification = mContext;
    layoutInflater = (LayoutInflater) mContext.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}}

Pojo class

public class TravelRequestAddDetails {

@SerializedName("REIMBURSEMENT_DTL_ID")
@Expose
private Integer rEIMBURSEMENTDTLID;
@SerializedName("REIMBURSEMENT_HDR_ID")
@Expose
private Integer rEIMBURSEMENTHDRID;
@SerializedName("TRAVEL_DATE")
@Expose
private String tRAVELDATE;
@SerializedName("TRAVEL_FROM")
@Expose
private String tRAVELFROM;

@SerializedName("TRAVEL_TO")
@Expose
private String tRAVELTO;
@SerializedName("AMOUNT")
@Expose
private String aMOUNT;
@SerializedName("DESCRIPTION")
@Expose
private String dESCRIPTION;

public TravelRequestAddDetails() {
}

public TravelRequestAddDetails(String tRAVELDATE, String tRAVELFROM, String tRAVELTO, String aMOUNT, String dESCRIPTION) {
    this.tRAVELDATE = tRAVELDATE;
    this.tRAVELFROM = tRAVELFROM;
    this.tRAVELTO = tRAVELTO;
    this.aMOUNT = aMOUNT;
    this.dESCRIPTION = dESCRIPTION;
}
public Integer getREIMBURSEMENTDTLID() {
    return rEIMBURSEMENTDTLID;
}

public void setREIMBURSEMENTDTLID(Integer rEIMBURSEMENTDTLID) {
    this.rEIMBURSEMENTDTLID = rEIMBURSEMENTDTLID;
}

public Integer getREIMBURSEMENTHDRID() {
    return rEIMBURSEMENTHDRID;
}

public void setREIMBURSEMENTHDRID(Integer rEIMBURSEMENTHDRID) {
    this.rEIMBURSEMENTHDRID = rEIMBURSEMENTHDRID;
}

public String getTRAVELDATE() {
    return tRAVELDATE;
}

public String setTRAVELDATE(String tRAVELDATE) {
    this.tRAVELDATE = tRAVELDATE;
    return tRAVELDATE;
}

public String getTRAVELFROM() {
    return tRAVELFROM;
}

public String setTRAVELFROM(String tRAVELFROM) {
    this.tRAVELFROM = tRAVELFROM;
    return tRAVELFROM;
}

public String getTRAVELTO() {
    return tRAVELTO;
}

public String setTRAVELTO(String tRAVELTO) {
    this.tRAVELTO = tRAVELTO;
    return tRAVELTO;
}

public String getAMOUNT() {
    return aMOUNT;
}

public String setAMOUNT(String aMOUNT) {
    this.aMOUNT = aMOUNT;
    return aMOUNT;
}

public String getDESCRIPTION() {
    return dESCRIPTION;
}

public String setDESCRIPTION(String dESCRIPTION) {
    this.dESCRIPTION = dESCRIPTION;
    return dESCRIPTION;
}

ModificationFragment Class

   public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.travel_request, container, false);
    approverList=new ArrayList<>();
    travelRequestAddDetailses = new ArrayList<>();
    mAdapter = new TravelRequestDetailAdapter(travelRequestAddDetailses, this);
    requestDetailsList = (ListView) rootView.findViewById(R.id.TravelRequestAdd);
    requestDetailsList.setAdapter(mAdapter);

    LayoutInflater inflaterHeader = getActivity().getLayoutInflater();
    ViewGroup header = (ViewGroup) inflaterHeader.inflate(
            R.layout.lc_modification, requestDetailsList, false);
    requestDetailsList.addHeaderView(header);

    LayoutInflater inflaterFooter = getActivity().getLayoutInflater();
    ViewGroup footer = (ViewGroup) inflaterFooter.inflate(
            R.layout.travel_details_footer, requestDetailsList, false);
    requestDetailsList.addFooterView(footer);
    raisedBy = (TextView) rootView.findViewById(R.id.text_raised);

    approver = (TextView) rootView.findViewById(R.id.text_approver);
    recyclerView = (RecyclerView) rootView.findViewById(R.id.wq_approver_recycler_view);
    recyclerView.setHasFixedSize(true);
    list = new ArrayList<>();
    circleProgressBar = (CircleProgressBar) rootView.findViewById(R.id.progressBar);
    travelFrom = (EditText) rootView.findViewById(R.id.txt_travel_from);
    travelTo = (EditText) rootView.findViewById(R.id.txt_travel_to);
    travelAmount = (EditText) rootView.findViewById(R.id.txt_amount);
    travelDesc = (EditText) rootView.findViewById(R.id.txt_desc);
    remark = (EditText) rootView.findViewById(R.id.remark);
    documentList = (ListView) rootView.findViewById(R.id.documentList);
    textViewTotal = (TextView) rootView.findViewById(R.id.txt_totalAmount);

    selectDate = (TextView) rootView.findViewById(R.id.raiseddate);
    dateFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
    selectTravelDate = (EditText) rootView.findViewById(R.id.texttravelDate);
    selectTravelDate.setInputType(InputType.TYPE_NULL);

    selectTravelDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectTravellingDate();
        }
    });
    imgSelectedfile = (ImageView) rootView.findViewById(R.id.IVPCUploadDoc);
    imgSelectedfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openFileChooser();
        }
    });

    btn_add = (Button) rootView.findViewById(R.id.addButton);
    btn_add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (validateData(v)) {
                addRequestDetails();
                updateTotalAmount();
            }

        }
    });
    setRequestDetails();
    return rootView;
}

 public void addRequestDetails() {
    TravelRequestAddDetails obj = new TravelRequestAddDetails(selectTravelDate.getText().toString(),
            travelFrom.getText().toString(),
            travelTo.getText().toString(),
            travelAmount.getText().toString(),
            travelDesc.getText().toString());

    travelRequestAddDetailses.add(obj);
    mAdapter.notifyDataSetChanged();

    selectTravelDate.setText("");
    travelFrom.setText("");
    travelTo.setText("");
    travelAmount.setText("");
    travelDesc.setText("");

}

public void updateTotalAmount() {
    int total = 0;
    if (travelRequestAddDetailses != null && !travelRequestAddDetailses.isEmpty()) {
        for (TravelRequestAddDetails travelRequestAddDetails : travelRequestAddDetailses) {
            total = Integer.parseInt(travelRequestAddDetails.getAMOUNT()) + total;
        }
    }
    textViewTotal.setText(total + "");
}
public void editRequest(){

    for(int i=0;i<travelRequestAddDetailses.size();i++) {
      //  selectTravelDate.setText();

    }
}}


问:
How do I retrieve the username that a Windows service is running under?
Given a service name, I would like to retrieve the username that it runs under (i.e. the username shown in the 'Log On' tab of a service's properties window).

There doesn't appear to be anything in the ServiceController class to retrieve this basic information. Nothing else in System.ServiceProcess looks like it exposes this information either.

Is there a managed solution to this, or am I going to have to drop down into something lower-level?

答:
```<code>    public String getUsername() {
    string username = null;
    try {
      ManagementScope ms = new ManagementScope("\\\\.\\root\\cimv2");
      ms.Connect();
      ObjectQuery query = new ObjectQuery
              ("SELECT * FROM Win32_ComputerSystem");
      ManagementObjectSearcher searcher =
              new ManagementObjectSearcher(ms, query);
      foreach (ManagementObject mo in searcher.Get()) {
        username = mo["UserName"].ToString();
      }
      string[] usernameParts = username.Split('\\');
      username = usernameParts[usernameParts.Length - 1];
    } catch (Exception) {
      username = "SYSTEM";
    }
    return username;
  }
</code>```

ContentLicense: CC BY-SA 4.0


问:
Outlook Interop Delete Appointments Matching Patern
So, essentially, what I'm trying to do is delete all appointments in Outlook that match a certain pattern (it's a simple one so there's no need for a Regex).

So, I use the following code to retrieve every item in the calendar using interop.

```<code>Outlook.Application outlook = new Outlook.Application();
Outlook.NameSpace mapiNameSpace = outlook.GetNamespace("MAPI");
Outlook.MAPIFolder calendarFolder = mapiNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);
Outlook.Items outlookCalendarItems = calendarFolder.Items;
</code>```

And then the following code to iterate over and delete them:

```<code>foreach (Outlook.AppointmentItem appointment in outlookCalendarItems)
{
     if (appointment.Subject.Contains("On Call: Regions:"))
     {
          appointment.Delete();
     }
}
</code>```

However, for some reason some of the items seem to get deleted and some of them get missed with no obvious pattern to why. The Subject of each appointment is generated in the same way for each appointment (in a different part of the application):

```<code>appt.Subject = $"On Call: {appointment.Region}";
</code>```

Where appointment.Region is generated using:

```<code>Region = $"Regions: {regions.Aggregate((x, y) => x + " & " + y)}"
</code>```

Which results in:

On Call: Regions: 6 & 7

On Call: Regions: NS

etc...

So if it's working for some, it should be working for all.

Any ideas?

答:
If deleting from the items collection you have to delete from the end to the beginning best using indexer. That means if you delete an item it is removed from the items collection and sent to the deleted folder.

This is documented for example in the MSDN

If you don't do it this way but iterate from the beginning the item is removed and the one after this replaces it. So most likely you are skipping an entry. If the following item would also comply to your filter you would not delete it. That explains why you find it on the second run.

This is not a .net collection. You are using an interop wrapper. It can behave differently from what you expect in c#.

For example try this. According to documentation the index is 1-based. Not 0-based - but better double check yourself as I can not currently test this myself:

```<code>for (int i = outlookCalenderItems.Count; i > 0; i--)
{
     if (outlookCalenderItems[i].Subject.Contains("On Call: Regions:"))
     {
          outlookCalenderItems[i].Delete();
     }
}
</code>```

Body:
So, essentially, what I'm trying to do is delete all appointments in Outlook that match a certain pattern (it's a simple one so there's no need for a Regex).

So, I use the following code to retrieve every item in the calendar using interop.

Outlook.Application outlook = new Outlook.Application();
Outlook.NameSpace mapiNameSpace = outlook.GetNamespace("MAPI");
Outlook.MAPIFolder calendarFolder = mapiNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);
Outlook.Items outlookCalendarItems = calendarFolder.Items;

And then the following code to iterate over and delete them:

foreach (Outlook.AppointmentItem appointment in outlookCalendarItems)
{
     if (appointment.Subject.Contains("On Call: Regions:"))
     {
          appointment.Delete();
     }
}

However, for some reason some of the items seem to get deleted and some of them get missed with no obvious pattern to why. The Subject of each appointment is generated in the same way for each appointment (in a different part of the application):

appt.Subject = $"On Call: {appointment.Region}";

Where appointment.Region is generated using:

Region = $"Regions: {regions.Aggregate((x, y) => x + " & " + y)}"

Which results in:

On Call: Regions: 6 & 7

On Call: Regions: NS

etc...

So if it's working for some, it should be working for all.

Any ideas?

Body:
If deleting from the items collection you have to delete from the end to the beginning best using indexer. That means if you delete an item it is removed from the items collection and sent to the deleted folder.

This is documented for example in the MSDN

If you don't do it this way but iterate from the beginning the item is removed and the one after this replaces it. So most likely you are skipping an entry. If the following item would also comply to your filter you would not delete it. That explains why you find it on the second run.

This is not a .net collection. You are using an interop wrapper. It can behave differently from what you expect in c#.

For example try this. According to documentation the index is 1-based. Not 0-based - but better double check yourself as I can not currently test this myself:

for (int i = outlookCalenderItems.Count; i > 0; i--)
{
     if (outlookCalenderItems[i].Subject.Contains("On Call: Regions:"))
     {
          outlookCalenderItems[i].Delete();
     }
}


问:
What is the simplest way to print a counter after a loop has finished?
If I run the following code it will output 0.

var total = 0;
for(var i = i; i <= 100; i++) {
    total = total + i;
}
console.log(total); ```

This is because the line console.log(total) doesn't wait for the loop to finish; it just immediately executes.

How can I print the final value of total?

答:
There is a mistake in your code:

change:

```<code>for(var i = i; i <= 100; i++)
</code>```

To:

```<code>for(var i = 0; i <= 100; i++)
</code>```

And it works:

var total = 0;
for(var i = 0; i <= 100; i++) {
    total = total + i;
}
console.log(total); ```

Body:
If I run the following code it will output 0.

var total = 0;
for(var i = i; i <= 100; i++) {
    total = total + i;
}
console.log(total);

This is because the line console.log(total) doesn't wait for the loop to finish; it just immediately executes.

How can I print the final value of total?

Body:
There is a mistake in your code:

change:

for(var i = i; i <= 100; i++)

To:

for(var i = 0; i <= 100; i++)

And it works:

var total = 0;
for(var i = 0; i <= 100; i++) {
    total = total + i;
}
console.log(total);


问:
IF statement, number less than X but greater than Y
Within my program I have a column(H) specifying hours:

```<code>(24.2, 23.5, 21.5, 25.0, 28.3, 23.1, 22.5, 17.9, 22.1, 16.2, 24.3, 23.8)
</code>```

this continues for 600 or so more rows.

```<code>Max hours = 36.88348
Min hours = 16.15569
</code>```

I'm trying to categorise the hours into four different numbers to later use for more accurate data than averages:

```<code>0 = 16-20,
1 = 21-25,
2 = 26-30,
3 = 31>.
</code>```

So far I have came to this solution:

```<code>=IF($H4>=31,3,IF($H4<=20,0,IF($H4>=21<=25,1,IF($H4>=26,2))))
</code>```

This works apart from the 21-25($H4>=21<=25,1).

If anybody could assist me, I believe it's something basic as my syntax.

Body:
Within my program I have a column(H) specifying hours:

(24.2, 23.5, 21.5, 25.0, 28.3, 23.1, 22.5, 17.9, 22.1, 16.2, 24.3, 23.8)

this continues for 600 or so more rows.

Max hours = 36.88348
Min hours = 16.15569

I'm trying to categorise the hours into four different numbers to later use for more accurate data than averages:

0 = 16-20,
1 = 21-25,
2 = 26-30,
3 = 31>.

So far I have came to this solution:

=IF($H4>=31,3,IF($H4<=20,0,IF($H4>=21<=25,1,IF($H4>=26,2))))

This works apart from the 21-25($H4>=21<=25,1).

If anybody could assist me, I believe it's something basic as my syntax.

Body:
The following should work:

=IF($H4>=31,3,IF($H4>=26,2,IF($H4>=21,1,IF($H4<21,0))))


问:
WCF slow ServiceHost.Open() call
This is a similar question as this one:
 Win32Exception @ ServiceHost.Open() for WCF service.

I have a machine that is very slow on the ServiceHost.Open call below. It consistently takes 7 seconds or so to open the service, every time. This machine is my home box, and it is not part of a domain.

I can run the same code on another box (my work box) which is part of a domain and the service host opens in about 3-4 seconds on the first call, but if I run the program again the service host opens in about 1 second or less.

I have worked with MS support on this, and we generated trace logs and the part it's hanging in is where is goes out and tries to connect to a domain, even on the machine that isn't part of a domain. And it gets the "The specified domain either does not exist or could not be contacted." exception in the trace log, and that's where all the time is getting eaten up.

But what's really weird is that even on my work machine, if I'm not connected to a domain (like if I'm not on my work network and just running from home) I still don't get the delay.

I rebuilt my machine using Windows 7 64-bit, and the same behavior occurs (was running XP SP3, which I restored when Windows 7 didn't seem to fix the problem).

I just wondered if anyone had any ideas of what could cause this. By the way, if I disable "Client for microsoft networks", the time is like 4 seconds to open the ServiceHost, but that's still not as fast as this machine used to be able to open the service. Somehow, it thinks it's supposed to be part of a domain or something.

```<code>    static void RunServiceWithinEXE()
    {
        Uri baseAddress = new Uri("http://localhost:11111/Demo");
        ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress);

        try
        {
            // Add a service endpoint
            serviceHost.AddServiceEndpoint(
                typeof(ICalculator),
                new WSHttpBinding(),
                "CalculatorService");

            // Enable metadata exchange
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            serviceHost.Description.Behaviors.Add(smb);
            serviceHost.Opening += new EventHandler(serviceHost_Opening);
            serviceHost.Opened += new EventHandler(serviceHost_Opened);
            serviceHost.Open();
            Console.WriteLine("The service is ready.");

            // Close the ServiceHostBase to shutdown the service.
            serviceHost.Close();
        }
        catch (CommunicationException ce)
        {
            Console.WriteLine("An exception occured: {0}", ce.Message);
            serviceHost.Abort();
        }
    }

    static void serviceHost_Opened(object sender, EventArgs e)
    {
        TimeSpan timeToOpen = DateTime.Now - shOpening;
        Console.WriteLine("Time To Open: :" + timeToOpen.Seconds);
    }

    static void serviceHost_Opening(object sender, EventArgs e)
    {
        shOpening = DateTime.Now;
    }
</code>```

Here is my app.config, but I don't have any special security configuration settings for the service in there, only some diagnostic settings to enable the WCF trace.

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <diagnostics>
            <messageLogging maxMessagesToLog="30000"
                    logEntireMessage="true"
                    logMessagesAtServiceLevel="false"
                    logMalformedMessages="true"
                    logMessagesAtTransportLevel="true">
                <filters>
                    <clear/>
                </filters>
            </messageLogging>
        </diagnostics>
    </system.serviceModel>

    <system.diagnostics>
        <sources>
            <source name="System.ServiceModel" switchValue="Warning, ActivityTracing" propagateActivity="true" >
                <listeners>
                    <add name="xml" />
                </listeners>
            </source>
            <source name="System.ServiceModel.MessageLogging" switchValue="Warning">
                <listeners>
                    <add name="xml" />
                </listeners>
            </source>
        </sources>
        <sharedListeners>
            <add name="xml" type="System.Diagnostics.XmlWriterTraceListener" initializeData="C:\Temp\Server.svclog" />
        </sharedListeners>
        <trace autoflush="true" indentsize="4">
            <listeners>
                <remove name="Default" />
                <add name="ScottsConsoleListener" type="System.Diagnostics.ConsoleTraceListener" />
                <add name="ScottsTextListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="C:\Temp\DebugLog.txt" />
            </listeners>
        </trace>
    </system.diagnostics>
</configuration>
</code>```

Note also that my service definition has SessionMode required (see below). If I take the SessionMode requirement out, I don't get the delays.

```<code>using System;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace Microsoft.ServiceModel.Samples
{
    // Define a service contract.
    [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples", SessionMode = SessionMode.Required)]
    public interface ICalculator
    {
        [OperationContract]
        double Add(double n1, double n2);

        [OperationContract]
        double Subtract(double n1, double n2);

        [OperationContract]
        double Multiply(double n1, double n2);

        [OperationContract]
        double Divide(double n1, double n2);

        [OperationContract]
        string PrintName(string firstName, string lastName);

        [OperationContract]
        Point MakePoint(double x, double y);

    }
}
</code>```

答:
It turns out that if I disable netbios on my network connections, I don't get the delays on the ServiceHost.Open calls. I am not sure why, but this seemed to fix the problem.

What's weird is that when I did a clean install of XP, I didn't have the delays even with the Netbios enabled, so I have no idea why it happens with my existing installation (I did the clean install on this same machine, and then restored my backup from an image to run these tests).

Title: WCF slow ServiceHost.Open() call

Body:
This is a similar question as this one:
 Win32Exception @ ServiceHost.Open() for WCF service.

I have a machine that is very slow on the ServiceHost.Open call below. It consistently takes 7 seconds or so to open the service, every time. This machine is my home box, and it is not part of a domain.

I can run the same code on another box (my work box) which is part of a domain and the service host opens in about 3-4 seconds on the first call, but if I run the program again the service host opens in about 1 second or less.

I have worked with MS support on this, and we generated trace logs and the part it's hanging in is where is goes out and tries to connect to a domain, even on the machine that isn't part of a domain. And it gets the "The specified domain either does not exist or could not be contacted." exception in the trace log, and that's where all the time is getting eaten up.

But what's really weird is that even on my work machine, if I'm not connected to a domain (like if I'm not on my work network and just running from home) I still don't get the delay.

I rebuilt my machine using Windows 7 64-bit, and the same behavior occurs (was running XP SP3, which I restored when Windows 7 didn't seem to fix the problem).

I just wondered if anyone had any ideas of what could cause this. By the way, if I disable "Client for microsoft networks", the time is like 4 seconds to open the ServiceHost, but that's still not as fast as this machine used to be able to open the service. Somehow, it thinks it's supposed to be part of a domain or something.

    static void RunServiceWithinEXE()
    {
        Uri baseAddress = new Uri("http://localhost:11111/Demo");
        ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress);

        try
        {
            // Add a service endpoint
            serviceHost.AddServiceEndpoint(
                typeof(ICalculator),
                new WSHttpBinding(),
                "CalculatorService");

            // Enable metadata exchange
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            serviceHost.Description.Behaviors.Add(smb);
            serviceHost.Opening += new EventHandler(serviceHost_Opening);
            serviceHost.Opened += new EventHandler(serviceHost_Opened);
            serviceHost.Open();
            Console.WriteLine("The service is ready.");

            // Close the ServiceHostBase to shutdown the service.
            serviceHost.Close();
        }
        catch (CommunicationException ce)
        {
            Console.WriteLine("An exception occured: {0}", ce.Message);
            serviceHost.Abort();
        }
    }

    static void serviceHost_Opened(object sender, EventArgs e)
    {
        TimeSpan timeToOpen = DateTime.Now - shOpening;
        Console.WriteLine("Time To Open: :" + timeToOpen.Seconds);
    }

    static void serviceHost_Opening(object sender, EventArgs e)
    {
        shOpening = DateTime.Now;
    }

Here is my app.config, but I don't have any special security configuration settings for the service in there, only some diagnostic settings to enable the WCF trace.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <diagnostics>
            <messageLogging maxMessagesToLog="30000"
                    logEntireMessage="true"
                    logMessagesAtServiceLevel="false"
                    logMalformedMessages="true"
                    logMessagesAtTransportLevel="true">
                <filters>
                    <clear/>
                </filters>
            </messageLogging>
        </diagnostics>
    </system.serviceModel>

    <system.diagnostics>
        <sources>
            <source name="System.ServiceModel" switchValue="Warning, ActivityTracing" propagateActivity="true" >
                <listeners>
                    <add name="xml" />
                </listeners>
            </source>
            <source name="System.ServiceModel.MessageLogging" switchValue="Warning">
                <listeners>
                    <add name="xml" />
                </listeners>
            </source>
        </sources>
        <sharedListeners>
            <add name="xml" type="System.Diagnostics.XmlWriterTraceListener" initializeData="C:\Temp\Server.svclog" />
        </sharedListeners>
        <trace autoflush="true" indentsize="4">
            <listeners>
                <remove name="Default" />
                <add name="ScottsConsoleListener" type="System.Diagnostics.ConsoleTraceListener" />
                <add name="ScottsTextListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="C:\Temp\DebugLog.txt" />
            </listeners>
        </trace>
    </system.diagnostics>
</configuration>

Note also that my service definition has SessionMode required (see below). If I take the SessionMode requirement out, I don't get the delays.

using System;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace Microsoft.ServiceModel.Samples
{
    // Define a service contract.
    [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples", SessionMode = SessionMode.Required)]
    public interface ICalculator
    {
        [OperationContract]
        double Add(double n1, double n2);

        [OperationContract]
        double Subtract(double n1, double n2);

        [OperationContract]
        double Multiply(double n1, double n2);

        [OperationContract]
        double Divide(double n1, double n2);

        [OperationContract]
        string PrintName(string firstName, string lastName);

        [OperationContract]
        Point MakePoint(double x, double y);

    }
}


问:
Matching multiple BEM modifiers in Sass
I am using BEM, and have an element with multiple modifiers:

```

<p>I'm using SCSS and taking advantage of it to write nested rules compatible with BEM. If I want to write a rule where an element (like the above) has <em>both</em> the m1 and m2 modifier, is there a way to write that compatible with the way I'm currently writing them? This is the kind of syntax I'm after, but results in a syntax error:</p>

<pre class="lang-css prettyprint-override"><code>.block {
    display: block;

    &__element {
        display: inline;

        &--m1 {
            background-color: red;
        }

        &--m2 {
            background-color: green;
        }

        // Syntax error
        &--m1&--m2 {
            background-color: yellow;
        }
    }
}
</code>```

I can think of ways around this by using attribute selectors, but is there a neater way?

For the record, the compiled attribute selector should be:

.block__element--m1.block__element--m2
```

答:
@3rdthemagical's answer did give me some inspiration for a better solution. Sass simply doesn't like & appearing after the beginning of the selector, but it doesn't mind it wrapped in #{}:

.block {
    display: block;

    &__element {
        display: inline;

        &--m1 {
            background-color: red;
        }

        &--m2 {
            background-color: green;
        }

        // Correct!
        &--m1#{&}--m2 {
            background-color: yellow;
        }
    }
}
```

Title: Matching multiple BEM modifiers in Sass

Body:
I am using BEM, and have an element with multiple modifiers:

I'm using SCSS and taking advantage of it to write nested rules compatible with BEM. If I want to write a rule where an element (like the above) has both the m1 and m2 modifier, is there a way to write that compatible with the way I'm currently writing them? This is the kind of syntax I'm after, but results in a syntax error:

.block {
    display: block;

    &__element {
        display: inline;

        &--m1 {
            background-color: red;
        }

        &--m2 {
            background-color: green;
        }

        // Syntax error
        &--m1&--m2 {
            background-color: yellow;
        }
    }
}

I can think of ways around this by using attribute selectors, but is there a neater way?

For the record, the compiled attribute selector should be:

.block__element--m1.block__element--m2


问:
Python Crawler - html.fromstring
I am trying to parse web page with this code.

```<code>ac = requests.get('link....')
html_text = ac.text
lx = html.fromstring(html_text)
</code>```

When I run this code I am getting this error

```<code>Traceback (most recent call last):
File "Crawler.py", line 197, in <module>
cnx.close()
File "Crawler.py", line 46, in RequestPage
lx = html.fromstring(html_text)
File "C:\Python27\lib\site-packages\lxml\html\__init__.py", line 867, in fromstring
doc = document_fromstring(html, parser=parser, base_url=base_url, **kw)
File "C:\Python27\lib\site-packages\lxml\html\__init__.py", line 752, in document_fromstring
value = etree.fromstring(html, parser, **kw)
File "src\lxml\lxml.etree.pyx", line 3213, in lxml.etree.fromstring (src\lxml\lxml.etree.c:76696)
File "src\lxml\parser.pxi", line 1830, in lxml.etree._parseMemoryDocument (src\lxml\lxml.etree.c:115101)
File "src\lxml\parser.pxi", line 1711, in lxml.etree._parseDoc (src\lxml\lxml.etree.c:113677)
File "src\lxml\parser.pxi", line 1051, in lxml.etree._BaseParser._parseUnicodeDoc (src\lxml\lxml.etree.c:107847)
File "src\lxml\parser.pxi", line 584, in lxml.etree._ParserContext._handleParseResultDoc (src\lxml\lxml.etree.c:102150)
File "src\lxml\parser.pxi", line 694, in lxml.etree._handleParseResult (src\lxml\lxml.etree.c:103800)
File "src\lxml\parser.pxi", line 633, in lxml.etree._raiseParseError (src\lxml\lxml.etree.c:102888)
lxml.etree.XMLSyntaxError: line 1843: Tag ie:menuitem invalid
</code>```

I found the html tag which cause to the error:

```<code><ie:menuitem id="MSOMenu_Help" iconsrc="/_layouts/images/HelpIcon.gif" onmenuclick="MSOWebPartPage_SetNewWindowLocation(MenuWebPart.getAttribute('helpLink'), MenuWebPart.getAttribute('helpMode'))" text="Help" type="option" style="display:none">

</ie:menuitem>
</code>```

答:
You found the HTML tag that case the error but did you fix it? If not try this:

ac = requests.get('link....')
lx = html.fromstring(ac.content)
valueOfHTMLTag = lx.xpath('//TAG[@class/id="Name"]/text()')

where you change:

TAG in the tag that you want to get the value of.

choose class or id of the tag

the id/class name of the tag

This will return an array with the values of that tag with the correct class/id.

Hope this helps!

Title: Python Crawler - html.fromstring

Body:
I am trying to parse web page with this code.

ac = requests.get('link....')
html_text = ac.text
lx = html.fromstring(html_text)

When I run this code I am getting this error

Traceback (most recent call last):
File "Crawler.py", line 197, in <module>
cnx.close()
File "Crawler.py", line 46, in RequestPage
lx = html.fromstring(html_text)
File "C:\Python27\lib\site-packages\lxml\html\__init__.py", line 867, in fromstring
doc = document_fromstring(html, parser=parser, base_url=base_url, **kw)
File "C:\Python27\lib\site-packages\lxml\html\__init__.py", line 752, in document_fromstring
value = etree.fromstring(html, parser, **kw)
File "src\lxml\lxml.etree.pyx", line 3213, in lxml.etree.fromstring (src\lxml\lxml.etree.c:76696)
File "src\lxml\parser.pxi", line 1830, in lxml.etree._parseMemoryDocument (src\lxml\lxml.etree.c:115101)
File "src\lxml\parser.pxi", line 1711, in lxml.etree._parseDoc (src\lxml\lxml.etree.c:113677)
File "src\lxml\parser.pxi", line 1051, in lxml.etree._BaseParser._parseUnicodeDoc (src\lxml\lxml.etree.c:107847)
File "src\lxml\parser.pxi", line 584, in lxml.etree._ParserContext._handleParseResultDoc (src\lxml\lxml.etree.c:102150)
File "src\lxml\parser.pxi", line 694, in lxml.etree._handleParseResult (src\lxml\lxml.etree.c:103800)
File "src\lxml\parser.pxi", line 633, in lxml.etree._raiseParseError (src\lxml\lxml.etree.c:102888)
lxml.etree.XMLSyntaxError: line 1843: Tag ie:menuitem invalid

I found the html tag which cause to the error:

<ie:menuitem id="MSOMenu_Help" iconsrc="/_layouts/images/HelpIcon.gif" onmenuclick="MSOWebPartPage_SetNewWindowLocation(MenuWebPart.getAttribute('helpLink'), MenuWebPart.getAttribute('helpMode'))" text="Help" type="option" style="display:none">

</ie:menuitem>


问:
How to register an implicit system broadcast like "android.provider.Telephony.SMS_RECEIVED" which is not supported in the Android Oreo
How to register an implicit system broadcast like android.provider.Telephony.SMS_RECEIVED  which is not supported in the Android Oreo

答: You register it the same way as you always have, as it is documented as being on the implicit Intent broadcast whitelist.


问:
The type or namespace name could not be found
I have a C# solution with several projects in Visual Studio 2010.
One is a test project (I'll call it "PrjTest"), the other is a Windows Forms Application project (I'll call it "PrjForm").  There is also a third project referenced by PrjForm, which it is able to reference and use successfully.

PrjForm references PrjTest, and PrjForm has a class with a using statement:

```<code>using PrjTest;
</code>```

Reference has been correctly added

using statement is correctly in place

Spelling is correct

PrjTest builds successfully

PrjForm almost builds, but breaks on the using PrjTest; line with the error:

The type or namespace name 'PrjTest' could not be found (are you missing a using directive or an assembly reference?)

I've tried the following to resolve this:

Removed Resharper (since Resharper had no trouble recognizing the referenced project, I thought it might be worth a shot)

Removed and re-added the reference and using statement

Recreated PrjForm from scratch

PrjForm currently resides inside the PrjTest folder, I tried moving it to an outside folder

Loaded the solution on a different computer with a fresh copy of VS 2010

I have done my homework and spent far too long looking for an answer online, none of the solutions has helped yet.

What else could I try?

答:
If your project (PrjTest) does not expose any public types within the PrjTest namespace, it will cause that error.

Does the project (PrjTest) include any classes or types in the "PrjTest" namespace which are public?

Body:
I have a C# solution with several projects in Visual Studio 2010.
One is a test project (I'll call it "PrjTest"), the other is a Windows Forms Application project (I'll call it "PrjForm").  There is also a third project referenced by PrjForm, which it is able to reference and use successfully.

PrjForm references PrjTest, and PrjForm has a class with a using statement:

using PrjTest;

Reference has been correctly added

using statement is correctly in place

Spelling is correct

PrjTest builds successfully

PrjForm almost builds, but breaks on the using PrjTest; line with the error:

The type or namespace name 'PrjTest' could not be found (are you missing a using directive or an assembly reference?)

I've tried the following to resolve this:

Removed Resharper (since Resharper had no trouble recognizing the referenced project, I thought it might be worth a shot)

Removed and re-added the reference and using statement

Recreated PrjForm from scratch

PrjForm currently resides inside the PrjTest folder, I tried moving it to an outside folder

Loaded the solution on a different computer with a fresh copy of VS 2010

I have done my homework and spent far too long looking for an answer online, none of the solutions has helped yet.

What else could I try?


问:
Bit Coin API for bit coin rate
I am using following code to get bitcoin price it is working off line but not working on server. </p>

```<code>$api = "http://blockchain.info/ticker";
$json = file_get_contents($api);
$data = json_decode($json, TRUE);
$rate = $data["USD"]["15m"];
$symbol = $data["USD"]["symbol"];

echo $rate.$symbol;
?>
</code>```

答: This method is not secure to perform a request to other server. You should use curl instead of file_get_contents. Btw, if still you want to keep this approach you can enable it in php.ini setting allow_url_fopen to 1

Title: Bit Coin API for bit coin rate

Body:
I am using following code to get bitcoin price it is working off line but not working on server.

$api = "http://blockchain.info/ticker";
$json = file_get_contents($api);
$data = json_decode($json, TRUE);
$rate = $data["USD"]["15m"];
$symbol = $data["USD"]["symbol"];

echo $rate.$symbol;
?>


答:
Change for loop to

```<code>for(var i = 0; i <= 100; i++) { //i=0 instead of i = i
</code>```

i = i will cause i = undefined and that will cause i < 100 to fail

Title: What is the simplest way to print a counter after a loop has finished?

Body:
Change for loop to

for(var i = 0; i <= 100; i++) { //i=0 instead of i = i

i = i will cause i = undefined and that will cause i < 100 to fail


问:
Loading a CSV in Neo4j with a field separated by comma
I have a CSV file that looks like this

```<code>id;title;startdate;enddate;budget;description;department;supervisor;supervisor_email;member;member_email;tags
49206;Some title;29.09.2015;27.04.2016;4 billion;Something about the title;ABC;Person1;person1@aol.com;Person2, Person3;person2@aol.com, person3@aol.com;Some tags
8501;Some Title2;13.07.2015;15.02.2016;14 billion;Something about Title2;DEF;Person4;person4@aol.com;Person5, Person6;person5@aol.com, person6@aol.com;Title2
</code>```

I wrote the following Cypher

```<code>LOAD CSV WITH HEADERS FROM 'file:///..../Project.csv' AS row FIELDTERMINATOR ';'
MERGE (pr:Project {projectID: row.id, title: row.title, startdate: row.startdate, enddate: row.enddate, budget: row.budget})
FOREACH (n IN row.member_email |
    WITH SPLIT(row.member_email, ", ") AS memberEmails
    MERGE (p:Person {email: memberEmails})
    MERGE (p)-[:IS_MEMBER]->(pr)
)
</code>```

As we can see that the member email address is separated by a comma, I want to split the email address and use the email address to match the person to create a new relationship that project has members.

SPLIT and FOREACH are creating a conflict and I can't figure why. Really appreciate if someone could help me.

答:
Solution

```<code>LOAD CSV WITH HEADERS FROM 'file:///..../Project.csv' AS row FIELDTERMINATOR ';'
MERGE (pr:Project {projectID: row.id, title: row.title, startdate: row.startdate, enddate: row.enddate, budget: row.budget})
WITH pr, SPLIT(row.member_email, ", ") AS memberEmails
UNWIND memberEmails as email
FOREACH (n IN memberEmails | MERGE (p:Person {email: email}) MERGE (p)-[:IS_MEMBER]->(pr) )
</code>```

Body:
I have a CSV file that looks like this

id;title;startdate;enddate;budget;description;department;supervisor;supervisor_email;member;member_email;tags
49206;Some title;29.09.2015;27.04.2016;4 billion;Something about the title;ABC;Person1;person1@aol.com;Person2, Person3;person2@aol.com, person3@aol.com;Some tags
8501;Some Title2;13.07.2015;15.02.2016;14 billion;Something about Title2;DEF;Person4;person4@aol.com;Person5, Person6;person5@aol.com, person6@aol.com;Title2

I wrote the following Cypher

LOAD CSV WITH HEADERS FROM 'file:///..../Project.csv' AS row FIELDTERMINATOR ';'
MERGE (pr:Project {projectID: row.id, title: row.title, startdate: row.startdate, enddate: row.enddate, budget: row.budget})
FOREACH (n IN row.member_email |
    WITH SPLIT(row.member_email, ", ") AS memberEmails
    MERGE (p:Person {email: memberEmails})
    MERGE (p)-[:IS_MEMBER]->(pr)
)

As we can see that the member email address is separated by a comma, I want to split the email address and use the email address to match the person to create a new relationship that project has members.

SPLIT and FOREACH are creating a conflict and I can't figure why. Really appreciate if someone could help me.

Body:
Solution

LOAD CSV WITH HEADERS FROM 'file:///..../Project.csv' AS row FIELDTERMINATOR ';'
MERGE (pr:Project {projectID: row.id, title: row.title, startdate: row.startdate, enddate: row.enddate, budget: row.budget})
WITH pr, SPLIT(row.member_email, ", ") AS memberEmails
UNWIND memberEmails as email
FOREACH (n IN memberEmails | MERGE (p:Person {email: email}) MERGE (p)-[:IS_MEMBER]->(pr) )


问:
Zookeeper and headless service in kubernetes
In kubernetes I have deployed a statefulset called zookeeper:

```<code>apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
  name: zookeeper
spec:
  serviceName: zookeeper-svc
  replicas: 1
  template:
    metadata:
      labels:
        app: zookeeper
</code>```

and a headless service:

```<code>apiVersion: v1
kind: Service
metadata:
  name: zookeeper-svc
  labels:
    app: zookeeper
spec:
  clusterIP: None
  ports:
  - port: 2888
    name: server
  - port: 3888
    name: leader-election
</code>```

Entering inside my zookeeper-0 pod I can see its IP:

```<code>zookeeper@zookeeper-0:/usr/bin$ cat /etc/hosts
# Kubernetes-managed hosts file.
127.0.0.1       localhost
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
fe00::0 ip6-mcastprefix
fe00::1 ip6-allnodes
fe00::2 ip6-allrouters
10.32.0.11      zookeeper-0.zookeeper-svc.default.svc.cluster.local     zookeeper-0
</code>```

But looking for the IP

kb exec dnsutils nslookup zookeeper-0

Server:         10.96.0.10
Address:        10.96.0.10#53

** server can't find zookeeper-0: NXDOMAIN

I cannot see it.

Where am I wrong?
Any suggestion is appreciated.

答: have you tried accessing zookeeper-0.zookeeper-svc service names are not added to search domain list in /etc/resolv.conf so you need to add everything that preceeds the namespace name in the name.

Body:
In kubernetes I have deployed a statefulset called zookeeper:

apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
  name: zookeeper
spec:
  serviceName: zookeeper-svc
  replicas: 1
  template:
    metadata:
      labels:
        app: zookeeper

and a headless service:

apiVersion: v1
kind: Service
metadata:
  name: zookeeper-svc
  labels:
    app: zookeeper
spec:
  clusterIP: None
  ports:
  - port: 2888
    name: server
  - port: 3888
    name: leader-election

Entering inside my zookeeper-0 pod I can see its IP:

zookeeper@zookeeper-0:/usr/bin$ cat /etc/hosts
# Kubernetes-managed hosts file.
127.0.0.1       localhost
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
fe00::0 ip6-mcastprefix
fe00::1 ip6-allnodes
fe00::2 ip6-allrouters
10.32.0.11      zookeeper-0.zookeeper-svc.default.svc.cluster.local     zookeeper-0

But looking for the IP

kb exec dnsutils nslookup zookeeper-0

Server:         10.96.0.10
Address:        10.96.0.10#53

** server can't find zookeeper-0: NXDOMAIN

I cannot see it.

Where am I wrong?
Any suggestion is appreciated.


问:
Selenium - WebElement object has no attribute 'sendKeys'
I'm trying to enter text into an input field using selenium but it's giving an error. The code is:

```<code>input1 = browser.find_element_by_xpath('//*[@id="login-dialog dialog"]/div[2]/div[2]/div[2]/form/div[1]/input')
input1.sendKeys("myusername")
</code>```

However it gives this error

```<code>Traceback (most recent call last):
File "C:\Users\Bradley Jo\Desktop\Project\app.py", line 14, in
<module>
input1.sendKeys("hello")
AttributeError: 'WebElement' object has no attribute 'sendKeys'
</code>```

答:
the method is not sendKeys. It is send_keys.</p>

```<code>input1 = browser.find_element_by_xpath('//*[@id="login-dialog dialog"]/div[2]/div[2]/div[2]/form/div[1]/input')
input1.send_keys("myusername")
</code>```

Body:
I'm trying to enter text into an input field using selenium but it's giving an error. The code is:

input1 = browser.find_element_by_xpath('//*[@id="login-dialog dialog"]/div[2]/div[2]/div[2]/form/div[1]/input')
input1.sendKeys("myusername")

However it gives this error

Traceback (most recent call last):
File "C:\Users\Bradley Jo\Desktop\Project\app.py", line 14, in
<module>
input1.sendKeys("hello")
AttributeError: 'WebElement' object has no attribute 'sendKeys'

Body:
the method is not sendKeys. It is send_keys.

input1 = browser.find_element_by_xpath('//*[@id="login-dialog dialog"]/div[2]/div[2]/div[2]/form/div[1]/input')
input1.send_keys("myusername")


问:
How to convert "2012-03-04 00:00:00.0" to Date with Format "dd-mm-yyyy HH:mm:ss" Using Java
I have a date format that I am getting from the database and is a String type. It has a value stored that is like "2012-03-04 00:00:00.0" but I have declared a SimpleDateFormat as "dd-MMM-yyyy HH:mm:ss" which is needed in my project. Now whenever I am retrieving some data alsong with date from database I get a parse Exception with the log as below.

java.text.ParseException: Unparseable date: "2012-03-04 00:00:00.0"
          at java.text.DateFormat.parse(Unknown Source)
          at com.tcs.tool.iris.aep.selfProfile.dao.AepSelfProfileDaoImpl$1.setValues(AepSelfProfileDaoImpl.java:1188)
          at org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:892)
          at org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:1)
          at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:586)
          at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:614)
          at org.springframework.jdbc.core.JdbcTemplate.batchUpdate(JdbcTemplate.java:883)
          at com.tcs.tool.iris.aep.selfProfile.dao.AepSelfProfileDaoImpl.insertDataIntoActionItems(AepSelfProfileDaoImpl.java:1174)
          at com.tcs.tool.iris.aep.selfProfile.service.AepSelfProfileServiceImpl.insertDataIntoActionItems(AepSelfProfileServiceImpl.java:214)
          at com.tcs.tool.iris.aep.selfProfile.controller.UpdateProgressController.onSubmit(UpdateProgressController.java:48)
          at org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:272)
          at org.springframework.web.servlet.mvc.AbstractFormController.handleInvalidSubmit(AbstractFormController.java:675)
          at org.springframework.web.servlet.mvc.AbstractFormController.handleRequestInternal(AbstractFormController.java:275)
          at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
          at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
          at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
          at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
          at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
          at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
          at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
          at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
          at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
          at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
          at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
          at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
          at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
          at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
          at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
          at java.lang.Thread.run(Unknown Source)

Please help me to figure out whats wrong with this. And how to convert it into the correct format.

The code snippet where I get the exception is as follows:-

```<code>SimpleDateFormat sdf = new SimpleDateFormat(
                                "dd-MMM-yyyy HH:mm:ss");
                        Calendar currenttime = Calendar.getInstance();
                        java.util.Date currentdate = currenttime.getTime();
                        String currentDateInsert = sdf.format(currentdate);
                        CommentNActionItem commentAndAction = commentActionItem
                                .get(i);
                        java.util.Date datefromDb = null;
                        try {
                            @SuppressWarnings("unused")
                            Date dateF=sdf.parse(commentAndAction.getCreatedDate());
                            datefromDb = (java.sql.Date)sdf.parseObject(commentAndAction.getCreatedDate());
                        } catch (Exception e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
</code>```

}

答:
Date format with week day name in Java Android</p>

```<code>Input: 2017-08-02T12:54:54+04:00
you are required to show results like:
Output:    Wednesday
           August 2, 2017 12:54 pm

 public static String getDateFormat(String date){
      String input_date= date;
     //incase you are getting format 2017-08-02T12:54:54+04:00 you need to
    // replace T with " " doing so String input_date = date.replace("T","");
      SimpleDateFormat format1=new SimpleDateFormat("yyyy-MM-dd HH:mm");
      Date dt1= null;
      try {
        dt1 = format1.parse(input_date);
      } catch (ParseException e) {
        e.printStackTrace();
      }

      DateFormat format2=new SimpleDateFormat("EEEE");
      String finalDay=format2.format(dt1);
      String stringDate = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.SHORT).format(dt1); // for seconds removal use DateFormat.SHORT in second parameter
      return finalDay+"\n"+stringDate;
      }
</code>```

Body:
I have a date format that I am getting from the database and is a String type. It has a value stored that is like "2012-03-04 00:00:00.0" but I have declared a SimpleDateFormat as "dd-MMM-yyyy HH:mm:ss" which is needed in my project. Now whenever I am retrieving some data alsong with date from database I get a parse Exception with the log as below.

java.text.ParseException: Unparseable date: "2012-03-04 00:00:00.0"
          at java.text.DateFormat.parse(Unknown Source)
          at com.tcs.tool.iris.aep.selfProfile.dao.AepSelfProfileDaoImpl$1.setValues(AepSelfProfileDaoImpl.java:1188)
          at org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:892)
          at org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:1)
          at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:586)
          at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:614)
          at org.springframework.jdbc.core.JdbcTemplate.batchUpdate(JdbcTemplate.java:883)
          at com.tcs.tool.iris.aep.selfProfile.dao.AepSelfProfileDaoImpl.insertDataIntoActionItems(AepSelfProfileDaoImpl.java:1174)
          at com.tcs.tool.iris.aep.selfProfile.service.AepSelfProfileServiceImpl.insertDataIntoActionItems(AepSelfProfileServiceImpl.java:214)
          at com.tcs.tool.iris.aep.selfProfile.controller.UpdateProgressController.onSubmit(UpdateProgressController.java:48)
          at org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:272)
          at org.springframework.web.servlet.mvc.AbstractFormController.handleInvalidSubmit(AbstractFormController.java:675)
          at org.springframework.web.servlet.mvc.AbstractFormController.handleRequestInternal(AbstractFormController.java:275)
          at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
          at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
          at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
          at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
          at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
          at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
          at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
          at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
          at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
          at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
          at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
          at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
          at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
          at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
          at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
          at java.lang.Thread.run(Unknown Source)

Please help me to figure out whats wrong with this. And how to convert it into the correct format.

The code snippet where I get the exception is as follows:-

SimpleDateFormat sdf = new SimpleDateFormat(
                                "dd-MMM-yyyy HH:mm:ss");
                        Calendar currenttime = Calendar.getInstance();
                        java.util.Date currentdate = currenttime.getTime();
                        String currentDateInsert = sdf.format(currentdate);
                        CommentNActionItem commentAndAction = commentActionItem
                                .get(i);
                        java.util.Date datefromDb = null;
                        try {
                            @SuppressWarnings("unused")
                            Date dateF=sdf.parse(commentAndAction.getCreatedDate());
                            datefromDb = (java.sql.Date)sdf.parseObject(commentAndAction.getCreatedDate());
                        } catch (Exception e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();

}

Body:
Date format with week day name in Java Android

Input: 2017-08-02T12:54:54+04:00
you are required to show results like:
Output:    Wednesday
           August 2, 2017 12:54 pm

 public static String getDateFormat(String date){
      String input_date= date;
     //incase you are getting format 2017-08-02T12:54:54+04:00 you need to
    // replace T with " " doing so String input_date = date.replace("T","");
      SimpleDateFormat format1=new SimpleDateFormat("yyyy-MM-dd HH:mm");
      Date dt1= null;
      try {
        dt1 = format1.parse(input_date);
      } catch (ParseException e) {
        e.printStackTrace();
      }

      DateFormat format2=new SimpleDateFormat("EEEE");
      String finalDay=format2.format(dt1);
      String stringDate = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.SHORT).format(dt1); // for seconds removal use DateFormat.SHORT in second parameter
      return finalDay+"\n"+stringDate;
      }


问:
Advanced custom fields + repeater + slider
I combined a slider with the repeater fields.
under the repeater I have 2 subfields. one called “image” and the other “title”

this slider has a class called “selected-item” that dynamically appear when an image is selected. (when this class is on an image the image change it’s size).

How can I define that when the class “selected-item” is on some image also the “title” form the same row of the image will appear?

this is the code the displays the images:

```<code>    <?php

    // check if the repeater field has rows of data
    $i = 1;
  if( have_rows('carousel_images') ):
// loop through the rows use_cases_fields data
while ( have_rows('carousel_images') ) : the_row();
    $title=get_sub_field('image_carousel_discription');
    $image = get_sub_field('image_carousel1');

    if( !empty($image) ):
        // thumbnail
        $thumb = $image;
    ?>

            <li id="image11" data-row="<?php echo $i; ?>" > <a
  href="#home"><img  src="<?php echo $thumb ?>"/></a> </li>

      <h3 id="h3-data" data-row="<?php echo $i; ?>"><?php echo $title ?>
     </h3>

         <?php $i++; ?>

    <?php endif; ?>

    <?php
endwhile;
endif;
  ?>
</code>```

JS- the "carousel on" adding the class "selected-item" to image.

```<code> carousel.on('itemSelected.sc', function (evt) {
           var image1=
  document.getElementById("image11").getAttribute("data-row");
             var hdata =       document.getElementById("h3-
     data").getAttribute("data-row");
   var hdata2=    document.getElementById("h3-data").innerText;
    if(image1==hdata){
      document.getElementById("change_h2").innerHTML =hdata2;
  }
</code>```

答:
You can add data atribute to image and title (f.e. data-row="< echo $i; >").
Define variable $i = 1; before repeater and at the end of each itereation increment $i value by one. Then, when selected image has "selected-item" class check which title has the same data-row atributte. </p>

```<code><?php

// check if the repeater field has rows of data
$i = 1;
if( have_rows('carousel_images') ):
    // loop through the rows use_cases_fields data
    while ( have_rows('carousel_images') ) : the_row();
        $title=get_sub_field('image_carousel_discription');
        $image = get_sub_field('image_carousel1');

        if( !empty($image) ):
            // thumbnail
            $thumb = $image;
        ?>

             <h1 data-row="<?php echo $i; ?>"><?php echo $title ?></h1>
             <li> <a href="#home"><img  data-row="<?php echo $i; ?>" src="<?php echo $thumb ?>"/></a> </li>

             <?php $i++; ?>
        <?php endif; ?>

        <?php
    endwhile;
endif;
?>
</code>```

Body:
I combined a slider with the repeater fields.
under the repeater I have 2 subfields. one called “image” and the other “title”

this slider has a class called “selected-item” that dynamically appear when an image is selected. (when this class is on an image the image change it’s size).

How can I define that when the class “selected-item” is on some image also the “title” form the same row of the image will appear?

this is the code the displays the images:

    <?php

    // check if the repeater field has rows of data
    $i = 1;
  if( have_rows('carousel_images') ):
// loop through the rows use_cases_fields data
while ( have_rows('carousel_images') ) : the_row();
    $title=get_sub_field('image_carousel_discription');
    $image = get_sub_field('image_carousel1');

    if( !empty($image) ):
        // thumbnail
        $thumb = $image;
    ?>

            <li id="image11" data-row="<?php echo $i; ?>" > <img  src="<?php echo $thumb ?>"/>

      <h3 id="h3-data" data-row="<?php echo $i; ?>"><?php echo $title ?>

         <?php $i++; ?>

    <?php endif; ?>

    <?php
endwhile;
endif;
  ?>

JS- the "carousel on" adding the class "selected-item" to image.

 carousel.on('itemSelected.sc', function (evt) {
           var image1=
  document.getElementById("image11").getAttribute("data-row");
             var hdata =       document.getElementById("h3-
     data").getAttribute("data-row");
   var hdata2=    document.getElementById("h3-data").innerText;
    if(image1==hdata){
      document.getElementById("change_h2").innerHTML =hdata2;
  }

Body:
You can add data atribute to image and title (f.e. data-row="< echo $i; >").
Define variable $i = 1; before repeater and at the end of each itereation increment $i value by one. Then, when selected image has "selected-item" class check which title has the same data-row atributte.

<?php

// check if the repeater field has rows of data
$i = 1;
if( have_rows('carousel_images') ):
    // loop through the rows use_cases_fields data
    while ( have_rows('carousel_images') ) : the_row();
        $title=get_sub_field('image_carousel_discription');
        $image = get_sub_field('image_carousel1');

        if( !empty($image) ):
            // thumbnail
            $thumb = $image;
        ?>

             <h1 data-row="<?php echo $i; ?>"><?php echo $title ?></h1>
             <li> <a href="#home"><img  data-row="<?php echo $i; ?>" src="<?php echo $thumb ?>"/></a> </li>

             <?php $i++; ?>
        <?php endif; ?>

        <?php
    endwhile;
endif;
?>


问:
Convert column into object in R
I wanna convert first column into object in R so if the input looks like:

```<code>#name of df - KPIF
    namePill KPIPill
1: pill_tech     0.3
2:  pill_EUX     0.2
3:  pill_Bus     0.3
</code>```

the output should looks like:

```<code>#name of df - KPIF
           KPIPill
pill_tech    0.3
pill_EUX     0.2
pill_Bus     0.3
</code>```

Anyone could help ?
Regards,
Aleksandra

答:
You can just save the vector you want (the KPIPill column) in a new object and assign the other vector (namePill) as names() for the new object:

```<code>KPIF <- read.table(text = "    namePill KPIPill
1: pill_tech     0.3
                   2:  pill_EUX     0.2
                   3:  pill_Bus     0.3", header = TRUE)

KPIF_named <- KPIF$KPIPill
names(KPIF_named) <- KPIF$namePill

> KPIF_named
pill_tech  pill_EUX  pill_Bus
      0.3       0.2       0.3
</code>```

Title: Convert column into object in R

Body:
I wanna convert first column into object in R so if the input looks like:

#name of df - KPIF
    namePill KPIPill
1: pill_tech     0.3
2:  pill_EUX     0.2
3:  pill_Bus     0.3

the output should looks like:

#name of df - KPIF
           KPIPill
pill_tech    0.3
pill_EUX     0.2
pill_Bus     0.3

Anyone could help ?
Regards,
Aleksandra

Body:
You can just save the vector you want (the KPIPill column) in a new object and assign the other vector (namePill) as names() for the new object:

KPIF <- read.table(text = "    namePill KPIPill
1: pill_tech     0.3
                   2:  pill_EUX     0.2
                   3:  pill_Bus     0.3", header = TRUE)

KPIF_named <- KPIF$KPIPill
names(KPIF_named) <- KPIF$namePill

> KPIF_named
pill_tech  pill_EUX  pill_Bus
      0.3       0.2       0.3


问:
Access Jira from eclipse java for ETL process
We have a Project tracking tool  named Jira . I want to use Core java skills to extract number of  defects from JIRA and transform into excel. Let me now how to do the handshaking between JIRA and eclipse.  </p>

答:
For getting the dependency, its called jira rest java client (JRJC)

```<code><dependency>
  <groupId>com.atlassian.jira</groupId>
  <artifactId>jira-rest-java-client-core</artifactId>
  <version>2.0.0-m15</version>
</dependency>
</code>```

and then authenticate (eg. basic authentication),

```<code>final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
final JiraRestClient restClient = factory.createWithBasicHttpAuthentication(jiraServerUri, "admin", "admin");
try {
    final Issue issue = restClient.getIssueClient().getIssue("TST-7").claim();
    println(issue);
}
finally {
    // cleanup the restClient
    restClient.close();
}
</code>```

or use OAuth.

Once authenticated, use the list of apis provided - Jira Cloud REST API Reference.

Body:
For getting the dependency, its called jira rest java client (JRJC)

<dependency>
  <groupId>com.atlassian.jira</groupId>
  <artifactId>jira-rest-java-client-core</artifactId>
  <version>2.0.0-m15</version>
</dependency>

and then authenticate (eg. basic authentication),

final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
final JiraRestClient restClient = factory.createWithBasicHttpAuthentication(jiraServerUri, "admin", "admin");
try {
    final Issue issue = restClient.getIssueClient().getIssue("TST-7").claim();
    println(issue);
}
finally {
    // cleanup the restClient
    restClient.close();
}

or use OAuth.

Once authenticated, use the list of apis provided - Jira Cloud REST API Reference.


问:
input tab key does not work in Bootstrap Modal
I am trying to use angularjs to improve myself. So in my form page I have an a href element to open my bootstrap modal which is in the same page.

```<code><a class="btn btn-danger btn-condensed myPlusButton" data-toggle="modal" data-target="#myModal"><i class="fa fa-plus"></i></a>
</code>```

and my modal codes are;

```<code><div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">×</button>
      <h4 class="modal-title">
        <i class="fa fa-user-plus" aria-hidden="true"></i> modal title</h4>
    </div>
    <div class="modal-body">
      <form class="form-horizontal">
        <div class="panel panel-default">
          <div class="panel-body">
            <div class="form-group">
              <label class="col-md-4 col-xs-12 control-label">input 1 (only digits):</label>
              <div class="col-md-8 col-xs-12">
                <div class="input-group">
                  <span class="input-group-addon">
                    <span class="fa fa-check"></span>
                  </span>
                  <input name="firstinput" autocomplete="off" ng-model="myData.first" maxlength="11" type="text" class="form-control" onkeypress="return isNumber(event)">
                </div>
              </div>
            </div>
            <div class="form-group">
              <label class="col-md-4 col-xs-12 control-label">input 2:</label>
              <div class="col-md-8 col-xs-12">
                <div class="input-group">
                  <span class="input-group-addon">
                    <span class="fa fa-font"></span>
                  </span>
                  <input name="secondinput" autocomplete="off" ng-disabled="isDisable" ng-model="myData.second" type="text" class="form-control">
                </div>
              </div>
            </div>
            <div class="form-group">
              <label class="col-md-4 col-xs-12 control-label">input 3:</label>
              <div class="col-md-8 col-xs-12">
                <div class="input-group">
                  <span class="input-group-addon">
                    <span class="fa fa-id-card-o"></span>
                  </span>
                  <input name="thirdinput" ng-disabled="isDisable" ng-model="myData.third" maxlength="10" type="text" class="form-control">
                </div>
              </div>
            </div>
          </div>
        </div>
      </form>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
      <button type="button" ng-click="submitMyValues(myData)" ng-disabled="isDisable" class="btn btn-success">Save</button>
    </div>
  </div>
</div>
</code>```

Also isNumber function codes are;

```<code>function isNumber(evt) {
evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
  return true;
}
</code>```

isDisabled change either true or false according to the some data on page load.

When my modal open I try to use tab key to go down for other inputs but it does not work correctly. It's just stack on first input element.

Also I have tried to use html "tabIndex" attribute for input but it does not work too.

Where am I doing wrong?

答:
When the tab key is pressed false is returned by the isNumber function (onkeypress="return isNumber(event)"). The return value of an event handler determines whether or not the default browser behaviour should take place as well. Since false is returned, the default tab behavior is not executed.

To fix this you could change isNumber to the following:

```<code>function isNumber(evt) {
evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;

  // Added this line. 9 is the code for the tab key.
  if(charCode === 9) return true;

  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
  return true;
}
</code>```

Body:
I am trying to use angularjs to improve myself. So in my form page I have an a href element to open my bootstrap modal which is in the same page.

and my modal codes are;

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

         modal title

      <form class="form-horizontal">

              input 1 (only digits):

                  <input name="firstinput" autocomplete="off" ng-model="myData.first" maxlength="11" type="text" class="form-control" onkeypress="return isNumber(event)">

              input 2:

                  <input name="secondinput" autocomplete="off" ng-disabled="isDisable" ng-model="myData.second" type="text" class="form-control">

              input 3:

                  <input name="thirdinput" ng-disabled="isDisable" ng-model="myData.third" maxlength="10" type="text" class="form-control">

      </form>

      <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
      <button type="button" ng-click="submitMyValues(myData)" ng-disabled="isDisable" class="btn btn-success">Save</button>

Also isNumber function codes are;

function isNumber(evt) {
evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
  return true;
}

isDisabled change either true or false according to the some data on page load.

When my modal open I try to use tab key to go down for other inputs but it does not work correctly. It's just stack on first input element.

Also I have tried to use html "tabIndex" attribute for input but it does not work too.

Where am I doing wrong?

Body:
When the tab key is pressed false is returned by the isNumber function (onkeypress="return isNumber(event)"). The return value of an event handler determines whether or not the default browser behaviour should take place as well. Since false is returned, the default tab behavior is not executed.

To fix this you could change isNumber to the following:

function isNumber(evt) {
evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;

  // Added this line. 9 is the code for the tab key.
  if(charCode === 9) return true;

  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
  return true;
}


问:
Index a foreign key label with FosElasticaBundle

When I index my relationnal database (Postgresql), I want to get the string value intead of the foreign key id (recreate the relation between the two tables personn and country..)
I wish to do that in the fos_elastica.yml mapping file

Example:

```<code>fos_elastica:
    clients:
        default: { host: %elastic_host%, port: %elastic_port% }
    indexes:
        ex_app:
            client: default
            types:
                personn:
                    mappings:
                        id:
                            type: integer
                        name:
                            type: text
                            boost: 5
                        firstname:
                            type: text
                            boost: 3
                        dateofbirth:
                            type: date
                        country:
                            type: integer
                    persistence:
                        driver: orm
                        model: AppBundle\Entity\Personn
                        finder: ~
                        provider: ~
                        listener: ~
</code>```

I want to find the person by typing the name of the country and not the country id.

答:
I'm pretty sure that you should use "nested" : </p>

```<code>fos_elastica:
        clients:
            default: { host: %elastic_host%, port: %elastic_port% }
        indexes:
            ex_app:
                client: default
                types:
                    personn:
                        mappings:
                            id:
                                type: integer
                            name:
                                type: text
                                boost: 5
                            firstname:
                                type: text
                                boost: 3
                            dateofbirth:
                                type: date
                            country:
                                type: "nested"
                                 properties:
                                 id:
                                    type : integer
                                 label:
                                    type: text
                        persistence:
                            driver: orm
                            model: AppBundle\Entity\Personn
                            finder: ~
                            provider: ~
                            listener: ~
</code>```

Body:
When I index my relationnal database (Postgresql), I want to get the string value intead of the foreign key id (recreate the relation between the two tables personn and country..)
I wish to do that in the fos_elastica.yml mapping file

Example:

fos_elastica:
    clients:
        default: { host: %elastic_host%, port: %elastic_port% }
    indexes:
        ex_app:
            client: default
            types:
                personn:
                    mappings:
                        id:
                            type: integer
                        name:
                            type: text
                            boost: 5
                        firstname:
                            type: text
                            boost: 3
                        dateofbirth:
                            type: date
                        country:
                            type: integer
                    persistence:
                        driver: orm
                        model: AppBundle\Entity\Personn
                        finder: ~
                        provider: ~
                        listener: ~

I want to find the person by typing the name of the country and not the country id.

Body:
I'm pretty sure that you should use "nested" :

fos_elastica:
        clients:
            default: { host: %elastic_host%, port: %elastic_port% }
        indexes:
            ex_app:
                client: default
                types:
                    personn:
                        mappings:
                            id:
                                type: integer
                            name:
                                type: text
                                boost: 5
                            firstname:
                                type: text
                                boost: 3
                            dateofbirth:
                                type: date
                            country:
                                type: "nested"
                                 properties:
                                 id:
                                    type : integer
                                 label:
                                    type: text
                        persistence:
                            driver: orm
                            model: AppBundle\Entity\Personn
                            finder: ~
                            provider: ~
                            listener: ~