问:
MPAndroidChart not showing MarkerView
I have the following MarkerView:

```<code>public class DiagramLineMarker extends MarkerView {
    private TextView textViewValue = null;

    public DiagramLineMarker(Context context, int layoutResource) {
        super(context, layoutResource);

        this.textViewValue = (TextView) this.findViewById(R.id.line_fragment_marker_textview_value);
    }

    @Override
    public void refreshContent(Entry entry, int dataSetIndex) {
        this.textViewValue.setText("" + entry.getVal());
    }

    @Override
    public float getXOffset() {
        return - (getWidth() / 2);
    }

    @Override
    public float getYOffset() {
        return - getHeight();
    }
}
</code>```

And i set it like it is shown in the LineChartActivity1 example from MPAndroidChart:

```<code>this.lineChart.setMarkerView(new DiagramLineMarker(this.getActivity(), R.layout.activity_diagrams_line_fragment_marker));
</code>```

Unfortunately nothing happens when i select a value.

Complete implemenation:

```<code>public class DiagramLineFragment extends DiagramBaseFragment {
    private LineChart lineChart = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.setRetainInstance(true);
        this.setHasOptionsMenu(true);

        this.sessionLoginPreferences = new SessionLoginPreferences(this.getActivity());
        this.sessionLoginSingleton = SessionLoginSingleton.getInstance(this.getActivity());
        this.sessionProfilePreferences = new SessionProfilePreferences(this.getActivity());
        this.sessionMeasureDataPreferences = new SessionMeasureDataPreferences(this.getActivity());
        this.sessionMeasureDataList = SessionMeasureDataList.getInstance();
        this.sessionMeasureDataListFavourite = SessionMeasureDataListFavourite.getInstance();

        if(this.sessionMeasureDataList.getMeasureDataList() == null) {
            this.sessionMeasureDataList.setMeasureDataList(new MeasureDataList());
        }

        if(this.sessionMeasureDataListFavourite.getMeasureDataList() == null) {
            this.sessionMeasureDataListFavourite.setMeasureDataList(new MeasureDataList());
        }

        Bundle extras = this.getActivity().getIntent().getExtras();

        if(extras != null) {
            if(extras.getString(Globals.KEY_EMAIL_FAVOURITE) != null) {
                this.favourite = true;
            }
        }
    }

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

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        this.lineChart = (LineChart) view.findViewById(R.id.line_fragment_line_chart);
        this.lineChart.setDrawUnitsInChart(false);
        this.lineChart.setStartAtZero(false);
        this.lineChart.setDrawYValues(false);
        this.lineChart.setDrawXLabels(false);
        this.lineChart.setDrawBorder(false);
        this.lineChart.setDrawLegend(true);
        this.lineChart.setDescription("");
        this.lineChart.setNoDataTextDescription("");
        this.lineChart.setHighlightEnabled(true);
        this.lineChart.setTouchEnabled(true);
        this.lineChart.setDragEnabled(true);
        this.lineChart.setScaleEnabled(true);
        this.lineChart.setPinchZoom(true);
        this.lineChart.setMarkerView(new DiagramLineMarker(this.getActivity(), R.layout.activity_diagrams_line_fragment_marker));
        this.lineChart.setHighlightIndicatorEnabled(true);
        this.lineChart.setDrawGridBackground(false);
    }

    @Override
    public void onResume() {
        super.onResume();

        this.fragmentBecameVisible();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.diagram_activity_actions, menu);

        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if((this.sessionMeasureDataListFavourite != null || this.sessionMeasureDataList != null) && this.lineChart != null) {
            this.fragmentBecameVisible();
        }
    }

    public void fragmentBecameVisible() {
        this.initData();
    }

    private void initData() {
        List<MeasureDataListEntry> measureDataListEntry = null;

        if(this.favourite) {
            measureDataListEntry = this.sessionMeasureDataListFavourite.getMeasureDataList().getMeasureDataListEntries();
        } else {
            measureDataListEntry = this.sessionMeasureDataList.getMeasureDataList().getMeasureDataListEntries();
        }

        ArrayList<String> xValues = new ArrayList<String>();
        ArrayList<Entry> yValuesMonday = new ArrayList<Entry>();
        ArrayList<Entry> yValuesTuesday = new ArrayList<Entry>();
        ArrayList<Entry> yValuesWednesday = new ArrayList<Entry>();
        ArrayList<Entry> yValuesThursday = new ArrayList<Entry>();
        ArrayList<Entry> yValuesFriday = new ArrayList<Entry>();
        ArrayList<Entry> yValuesSaturday = new ArrayList<Entry>();
        ArrayList<Entry> yValuesSunday = new ArrayList<Entry>();

        for(int i = 0; i < measureDataListEntry.size(); i++) {
            String StringValue = measureDataListEntry.get(i).getTime();
            Long value = Long.parseLong(StringValue) * 1000;
            DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN);
            String date = dateFormat.format(new Date(value));

            xValues.add(date);
        }

        for(int i = 0; i < measureDataListEntry.size(); i++) {
            String stringValue = measureDataListEntry.get(i).getValue();
            int dayOfWeek = Helper.getDayOfWeek(measureDataListEntry.get(i).getTime());
            float value = Float.parseFloat(stringValue);

            switch(dayOfWeek) {
            case Calendar.MONDAY:
                yValuesMonday.add(new Entry(value, i));
                break;
            case Calendar.TUESDAY:
                yValuesTuesday.add(new Entry(value, i));
                break;
            case Calendar.WEDNESDAY:
                yValuesWednesday.add(new Entry(value, i));
                break;
            case Calendar.THURSDAY:
                yValuesThursday.add(new Entry(value, i));
                break;
            case Calendar.FRIDAY:
                yValuesFriday.add(new Entry(value, i));
                break;
            case Calendar.SATURDAY:
                yValuesSaturday.add(new Entry(value, i));
                break;
            case Calendar.SUNDAY:
                yValuesSunday.add(new Entry(value, i));
                break;
            }
        }

        LineDataSet lineDataSetMonday = new LineDataSet(yValuesMonday, this.getResources().getString(R.string.text_monday));

        lineDataSetMonday.enableDashedLine(10f, 5f, 0f);
        lineDataSetMonday.setColor(this.getResources().getColor(R.color.diagramGreenColor));
        lineDataSetMonday.setCircleColor(this.getResources().getColor(R.color.diagramGreenColor));
        lineDataSetMonday.setLineWidth(1f);
        lineDataSetMonday.setCircleSize(4f);
        lineDataSetMonday.setFillAlpha(65);
        lineDataSetMonday.setFillColor(this.getResources().getColor(R.color.diagramGreenColor));

        LineDataSet lineDataSetTuesday = new LineDataSet(yValuesTuesday, this.getResources().getString(R.string.text_tuesday));

        lineDataSetTuesday.enableDashedLine(10f, 5f, 0f);
        lineDataSetTuesday.setColor(this.getResources().getColor(R.color.diagramOrangeColor));
        lineDataSetTuesday.setCircleColor(this.getResources().getColor(R.color.diagramOrangeColor));
        lineDataSetTuesday.setLineWidth(1f);
        lineDataSetTuesday.setCircleSize(4f);
        lineDataSetTuesday.setFillAlpha(65);
        lineDataSetTuesday.setFillColor(this.getResources().getColor(R.color.diagramOrangeColor));

        LineDataSet lineDataSetWednesday = new LineDataSet(yValuesWednesday, this.getResources().getString(R.string.text_wednesday));

        lineDataSetWednesday.enableDashedLine(10f, 5f, 0f);
        lineDataSetWednesday.setColor(this.getResources().getColor(R.color.diagramPinkColor));
        lineDataSetWednesday.setCircleColor(this.getResources().getColor(R.color.diagramPinkColor));
        lineDataSetWednesday.setLineWidth(1f);
        lineDataSetWednesday.setCircleSize(4f);
        lineDataSetWednesday.setFillAlpha(65);
        lineDataSetWednesday.setFillColor(this.getResources().getColor(R.color.diagramPinkColor));

        LineDataSet lineDataSetThursday = new LineDataSet(yValuesThursday, this.getResources().getString(R.string.text_thursday));

        lineDataSetThursday.enableDashedLine(10f, 5f, 0f);
        lineDataSetThursday.setColor(this.getResources().getColor(R.color.diagramBlackColor));
        lineDataSetThursday.setCircleColor(this.getResources().getColor(R.color.diagramBlackColor));
        lineDataSetThursday.setLineWidth(1f);
        lineDataSetThursday.setCircleSize(4f);
        lineDataSetThursday.setFillAlpha(65);
        lineDataSetThursday.setFillColor(this.getResources().getColor(R.color.diagramBlackColor));

        LineDataSet lineDataSetFriday = new LineDataSet(yValuesFriday, this.getResources().getString(R.string.text_friday));

        lineDataSetFriday.enableDashedLine(10f, 5f, 0f);
        lineDataSetFriday.setColor(this.getResources().getColor(R.color.diagramBlueColor));
        lineDataSetFriday.setCircleColor(this.getResources().getColor(R.color.diagramBlueColor));
        lineDataSetFriday.setLineWidth(1f);
        lineDataSetFriday.setCircleSize(4f);
        lineDataSetFriday.setFillAlpha(65);
        lineDataSetFriday.setFillColor(this.getResources().getColor(R.color.diagramBlueColor));

        LineDataSet lineDataSetSaturday = new LineDataSet(yValuesSaturday, this.getResources().getString(R.string.text_saturday));

        lineDataSetSaturday.enableDashedLine(10f, 5f, 0f);
        lineDataSetSaturday.setColor(this.getResources().getColor(R.color.diagramRedColor));
        lineDataSetSaturday.setCircleColor(this.getResources().getColor(R.color.diagramRedColor));
        lineDataSetSaturday.setLineWidth(1f);
        lineDataSetSaturday.setCircleSize(4f);
        lineDataSetSaturday.setFillAlpha(65);
        lineDataSetSaturday.setFillColor(this.getResources().getColor(R.color.diagramRedColor));

        LineDataSet lineDataSetSunday = new LineDataSet(yValuesSunday, this.getResources().getString(R.string.text_sunday));

        lineDataSetSunday.enableDashedLine(10f, 5f, 0f);
        lineDataSetSunday.setColor(this.getResources().getColor(R.color.diagramYellowColor));
        lineDataSetSunday.setCircleColor(this.getResources().getColor(R.color.diagramYellowColor));
        lineDataSetSunday.setLineWidth(1f);
        lineDataSetSunday.setCircleSize(4f);
        lineDataSetSunday.setFillAlpha(65);
        lineDataSetSunday.setFillColor(this.getResources().getColor(R.color.diagramYellowColor));

        ArrayList<LineDataSet> dataSets = new ArrayList<LineDataSet>();

        dataSets.add(lineDataSetMonday);
        dataSets.add(lineDataSetTuesday);
        dataSets.add(lineDataSetWednesday);
        dataSets.add(lineDataSetThursday);
        dataSets.add(lineDataSetFriday);
        dataSets.add(lineDataSetSaturday);
        dataSets.add(lineDataSetSunday);

        LineData data = new LineData(xValues, dataSets);

        if(!this.favourite) {
            float hyper = (float)this.sessionProfilePreferences.getProfile(this.getEmail()).getHyperGlycemia();
            float hypo = (float)this.sessionProfilePreferences.getProfile(this.getEmail()).getHypoGlycemia();

            if(hyper > 0.0) {
                LimitLine limitLineHyper = new LimitLine(hyper);
                limitLineHyper.setLineWidth(4f);
                limitLineHyper.enableDashedLine(10f, 10f, 0f);
                limitLineHyper.setDrawValue(true);
                limitLineHyper.setLabelPosition(LimitLabelPosition.RIGHT);

                data.addLimitLine(limitLineHyper);
            }

            if(hypo > 0.0) {
                LimitLine limitLineHypo = new LimitLine(hypo);
                limitLineHypo.setLineWidth(4f);
                limitLineHypo.enableDashedLine(10f, 10f, 0f);
                limitLineHypo.setDrawValue(true);
                limitLineHypo.setLabelPosition(LimitLabelPosition.RIGHT);

                data.addLimitLine(limitLineHypo);
            }
        }

        this.lineChart.setData(data);
        this.lineChart.animateXY(1000, 1000);
    }
}
</code>```

Layout for the Marker:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/line_fragment_marker_textview_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginEnd="5dp"
        android:layout_marginStart="5dp"
        android:layout_marginTop="7dp"
        android:gravity="center"
        android:singleLine="true"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="@color/textcolorprimary"
        android:textSize="12sp" />

</LinearLayout>
</code>```

答: In the layout of your marker try setting layout_width="50dp". Give it a particular width same goes for the textview layout_width. I was also having a problem in displaying first then by setting the layout_width property, it got resolved.

Title: MPAndroidChart not showing MarkerView

Body:
I have the following MarkerView:

public class DiagramLineMarker extends MarkerView {
    private TextView textViewValue = null;

    public DiagramLineMarker(Context context, int layoutResource) {
        super(context, layoutResource);

        this.textViewValue = (TextView) this.findViewById(R.id.line_fragment_marker_textview_value);
    }

    @Override
    public void refreshContent(Entry entry, int dataSetIndex) {
        this.textViewValue.setText("" + entry.getVal());
    }

    @Override
    public float getXOffset() {
        return - (getWidth() / 2);
    }

    @Override
    public float getYOffset() {
        return - getHeight();
    }
}

And i set it like it is shown in the LineChartActivity1 example from MPAndroidChart:

this.lineChart.setMarkerView(new DiagramLineMarker(this.getActivity(), R.layout.activity_diagrams_line_fragment_marker));

Unfortunately nothing happens when i select a value.

Complete implemenation:

public class DiagramLineFragment extends DiagramBaseFragment {
    private LineChart lineChart = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.setRetainInstance(true);
        this.setHasOptionsMenu(true);

        this.sessionLoginPreferences = new SessionLoginPreferences(this.getActivity());
        this.sessionLoginSingleton = SessionLoginSingleton.getInstance(this.getActivity());
        this.sessionProfilePreferences = new SessionProfilePreferences(this.getActivity());
        this.sessionMeasureDataPreferences = new SessionMeasureDataPreferences(this.getActivity());
        this.sessionMeasureDataList = SessionMeasureDataList.getInstance();
        this.sessionMeasureDataListFavourite = SessionMeasureDataListFavourite.getInstance();

        if(this.sessionMeasureDataList.getMeasureDataList() == null) {
            this.sessionMeasureDataList.setMeasureDataList(new MeasureDataList());
        }

        if(this.sessionMeasureDataListFavourite.getMeasureDataList() == null) {
            this.sessionMeasureDataListFavourite.setMeasureDataList(new MeasureDataList());
        }

        Bundle extras = this.getActivity().getIntent().getExtras();

        if(extras != null) {
            if(extras.getString(Globals.KEY_EMAIL_FAVOURITE) != null) {
                this.favourite = true;
            }
        }
    }

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

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        this.lineChart = (LineChart) view.findViewById(R.id.line_fragment_line_chart);
        this.lineChart.setDrawUnitsInChart(false);
        this.lineChart.setStartAtZero(false);
        this.lineChart.setDrawYValues(false);
        this.lineChart.setDrawXLabels(false);
        this.lineChart.setDrawBorder(false);
        this.lineChart.setDrawLegend(true);
        this.lineChart.setDescription("");
        this.lineChart.setNoDataTextDescription("");
        this.lineChart.setHighlightEnabled(true);
        this.lineChart.setTouchEnabled(true);
        this.lineChart.setDragEnabled(true);
        this.lineChart.setScaleEnabled(true);
        this.lineChart.setPinchZoom(true);
        this.lineChart.setMarkerView(new DiagramLineMarker(this.getActivity(), R.layout.activity_diagrams_line_fragment_marker));
        this.lineChart.setHighlightIndicatorEnabled(true);
        this.lineChart.setDrawGridBackground(false);
    }

    @Override
    public void onResume() {
        super.onResume();

        this.fragmentBecameVisible();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.diagram_activity_actions, menu);

        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if((this.sessionMeasureDataListFavourite != null || this.sessionMeasureDataList != null) && this.lineChart != null) {
            this.fragmentBecameVisible();
        }
    }

    public void fragmentBecameVisible() {
        this.initData();
    }

    private void initData() {
        List<MeasureDataListEntry> measureDataListEntry = null;

        if(this.favourite) {
            measureDataListEntry = this.sessionMeasureDataListFavourite.getMeasureDataList().getMeasureDataListEntries();
        } else {
            measureDataListEntry = this.sessionMeasureDataList.getMeasureDataList().getMeasureDataListEntries();
        }

        ArrayList<String> xValues = new ArrayList<String>();
        ArrayList<Entry> yValuesMonday = new ArrayList<Entry>();
        ArrayList<Entry> yValuesTuesday = new ArrayList<Entry>();
        ArrayList<Entry> yValuesWednesday = new ArrayList<Entry>();
        ArrayList<Entry> yValuesThursday = new ArrayList<Entry>();
        ArrayList<Entry> yValuesFriday = new ArrayList<Entry>();
        ArrayList<Entry> yValuesSaturday = new ArrayList<Entry>();
        ArrayList<Entry> yValuesSunday = new ArrayList<Entry>();

        for(int i = 0; i < measureDataListEntry.size(); i++) {
            String StringValue = measureDataListEntry.get(i).getTime();
            Long value = Long.parseLong(StringValue) * 1000;
            DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN);
            String date = dateFormat.format(new Date(value));

            xValues.add(date);
        }

        for(int i = 0; i < measureDataListEntry.size(); i++) {
            String stringValue = measureDataListEntry.get(i).getValue();
            int dayOfWeek = Helper.getDayOfWeek(measureDataListEntry.get(i).getTime());
            float value = Float.parseFloat(stringValue);

            switch(dayOfWeek) {
            case Calendar.MONDAY:
                yValuesMonday.add(new Entry(value, i));
                break;
            case Calendar.TUESDAY:
                yValuesTuesday.add(new Entry(value, i));
                break;
            case Calendar.WEDNESDAY:
                yValuesWednesday.add(new Entry(value, i));
                break;
            case Calendar.THURSDAY:
                yValuesThursday.add(new Entry(value, i));
                break;
            case Calendar.FRIDAY:
                yValuesFriday.add(new Entry(value, i));
                break;
            case Calendar.SATURDAY:
                yValuesSaturday.add(new Entry(value, i));
                break;
            case Calendar.SUNDAY:
                yValuesSunday.add(new Entry(value, i));
                break;
            }
        }

        LineDataSet lineDataSetMonday = new LineDataSet(yValuesMonday, this.getResources().getString(R.string.text_monday));

        lineDataSetMonday.enableDashedLine(10f, 5f, 0f);
        lineDataSetMonday.setColor(this.getResources().getColor(R.color.diagramGreenColor));
        lineDataSetMonday.setCircleColor(this.getResources().getColor(R.color.diagramGreenColor));
        lineDataSetMonday.setLineWidth(1f);
        lineDataSetMonday.setCircleSize(4f);
        lineDataSetMonday.setFillAlpha(65);
        lineDataSetMonday.setFillColor(this.getResources().getColor(R.color.diagramGreenColor));

        LineDataSet lineDataSetTuesday = new LineDataSet(yValuesTuesday, this.getResources().getString(R.string.text_tuesday));

        lineDataSetTuesday.enableDashedLine(10f, 5f, 0f);
        lineDataSetTuesday.setColor(this.getResources().getColor(R.color.diagramOrangeColor));
        lineDataSetTuesday.setCircleColor(this.getResources().getColor(R.color.diagramOrangeColor));
        lineDataSetTuesday.setLineWidth(1f);
        lineDataSetTuesday.setCircleSize(4f);
        lineDataSetTuesday.setFillAlpha(65);
        lineDataSetTuesday.setFillColor(this.getResources().getColor(R.color.diagramOrangeColor));

        LineDataSet lineDataSetWednesday = new LineDataSet(yValuesWednesday, this.getResources().getString(R.string.text_wednesday));

        lineDataSetWednesday.enableDashedLine(10f, 5f, 0f);
        lineDataSetWednesday.setColor(this.getResources().getColor(R.color.diagramPinkColor));
        lineDataSetWednesday.setCircleColor(this.getResources().getColor(R.color.diagramPinkColor));
        lineDataSetWednesday.setLineWidth(1f);
        lineDataSetWednesday.setCircleSize(4f);
        lineDataSetWednesday.setFillAlpha(65);
        lineDataSetWednesday.setFillColor(this.getResources().getColor(R.color.diagramPinkColor));

        LineDataSet lineDataSetThursday = new LineDataSet(yValuesThursday, this.getResources().getString(R.string.text_thursday));

        lineDataSetThursday.enableDashedLine(10f, 5f, 0f);
        lineDataSetThursday.setColor(this.getResources().getColor(R.color.diagramBlackColor));
        lineDataSetThursday.setCircleColor(this.getResources().getColor(R.color.diagramBlackColor));
        lineDataSetThursday.setLineWidth(1f);
        lineDataSetThursday.setCircleSize(4f);
        lineDataSetThursday.setFillAlpha(65);
        lineDataSetThursday.setFillColor(this.getResources().getColor(R.color.diagramBlackColor));

        LineDataSet lineDataSetFriday = new LineDataSet(yValuesFriday, this.getResources().getString(R.string.text_friday));

        lineDataSetFriday.enableDashedLine(10f, 5f, 0f);
        lineDataSetFriday.setColor(this.getResources().getColor(R.color.diagramBlueColor));
        lineDataSetFriday.setCircleColor(this.getResources().getColor(R.color.diagramBlueColor));
        lineDataSetFriday.setLineWidth(1f);
        lineDataSetFriday.setCircleSize(4f);
        lineDataSetFriday.setFillAlpha(65);
        lineDataSetFriday.setFillColor(this.getResources().getColor(R.color.diagramBlueColor));

        LineDataSet lineDataSetSaturday = new LineDataSet(yValuesSaturday, this.getResources().getString(R.string.text_saturday));

        lineDataSetSaturday.enableDashedLine(10f, 5f, 0f);
        lineDataSetSaturday.setColor(this.getResources().getColor(R.color.diagramRedColor));
        lineDataSetSaturday.setCircleColor(this.getResources().getColor(R.color.diagramRedColor));
        lineDataSetSaturday.setLineWidth(1f);
        lineDataSetSaturday.setCircleSize(4f);
        lineDataSetSaturday.setFillAlpha(65);
        lineDataSetSaturday.setFillColor(this.getResources().getColor(R.color.diagramRedColor));

        LineDataSet lineDataSetSunday = new LineDataSet(yValuesSunday, this.getResources().getString(R.string.text_sunday));

        lineDataSetSunday.enableDashedLine(10f, 5f, 0f);
        lineDataSetSunday.setColor(this.getResources().getColor(R.color.diagramYellowColor));
        lineDataSetSunday.setCircleColor(this.getResources().getColor(R.color.diagramYellowColor));
        lineDataSetSunday.setLineWidth(1f);
        lineDataSetSunday.setCircleSize(4f);
        lineDataSetSunday.setFillAlpha(65);
        lineDataSetSunday.setFillColor(this.getResources().getColor(R.color.diagramYellowColor));

        ArrayList<LineDataSet> dataSets = new ArrayList<LineDataSet>();

        dataSets.add(lineDataSetMonday);
        dataSets.add(lineDataSetTuesday);
        dataSets.add(lineDataSetWednesday);
        dataSets.add(lineDataSetThursday);
        dataSets.add(lineDataSetFriday);
        dataSets.add(lineDataSetSaturday);
        dataSets.add(lineDataSetSunday);

        LineData data = new LineData(xValues, dataSets);

        if(!this.favourite) {
            float hyper = (float)this.sessionProfilePreferences.getProfile(this.getEmail()).getHyperGlycemia();
            float hypo = (float)this.sessionProfilePreferences.getProfile(this.getEmail()).getHypoGlycemia();

            if(hyper > 0.0) {
                LimitLine limitLineHyper = new LimitLine(hyper);
                limitLineHyper.setLineWidth(4f);
                limitLineHyper.enableDashedLine(10f, 10f, 0f);
                limitLineHyper.setDrawValue(true);
                limitLineHyper.setLabelPosition(LimitLabelPosition.RIGHT);

                data.addLimitLine(limitLineHyper);
            }

            if(hypo > 0.0) {
                LimitLine limitLineHypo = new LimitLine(hypo);
                limitLineHypo.setLineWidth(4f);
                limitLineHypo.enableDashedLine(10f, 10f, 0f);
                limitLineHypo.setDrawValue(true);
                limitLineHypo.setLabelPosition(LimitLabelPosition.RIGHT);

                data.addLimitLine(limitLineHypo);
            }
        }

        this.lineChart.setData(data);
        this.lineChart.animateXY(1000, 1000);
    }
}

Layout for the Marker:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/line_fragment_marker_textview_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginEnd="5dp"
        android:layout_marginStart="5dp"
        android:layout_marginTop="7dp"
        android:gravity="center"
        android:singleLine="true"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="@color/textcolorprimary"
        android:textSize="12sp" />

</LinearLayout>


来源: stackexchange

问:
How to see console.log statements in deployed Lambda function

I'm getting started trying to write a lambda function with node and puppeteer. I'm using the serverless framework

I've been trying to follow https://codissimo.sinumo.tech/2019/12/27/serverless-puppeteer-with-aws-lambda-layers-and-node-js/ to utilize the provisioned chrome at https://github.com/shelfio/chrome-aws-lambda-layer . My function is working as expected locally.

my handler.js contains:

```<code>module.exports.main = async event => {
    console.log('IN HANDLER');

  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: 'main function executed!',
        input: event,
      },
      null,
      2
    ),
  };
</code>```

my index.js contains a longrunning (45- 60 seconds) puppeteer function (main ) which returns an array of objects:

```<code>async function main(event, context, callback) {
  const chromium = require('chrome-aws-lambda');

 ...................................

 var obj_arr = [];
  var keys = head[0];
  for (let index = 0; index < body.length; index++) {
    var row = body[index];
    var obj = {};
    for (let i = 0; i < keys.length; i++) {
      var k = keys[i];
      obj[k] = row[i];
      console.log(obj);

    }
    obj_arr.push(obj);

  };

  console.log(obj_arr);
  return obj_arr;
</code>```

After uploading my function to lambda using  serverless framework without error. I followed the directions at the bottom of the article about testing the pre provisioned chrome in my layers dashboard. As you can see in the screenshot it appears to be working correctly.

being brand new to this I don't understand the log output:

```<code>START RequestId: f62dcf47-e2ff-4a96-9807-b34c39f218e3 Version: $LATEST
2020-05-31T19:10:21.280Z    f62dcf47-e2ff-4a96-9807-b34c39f218e3    INFO    SERVERLESS_ENTERPRISE {"c":true,"b":"H4sIAAAAAAAAA7VWbU/cOBD+Kyi6D3fSJms7ifNSIR1aoK1UKsouVe+ADyZxdlMSO9gJL0X732+cZF9ZEJzUL7CZeTyemWf82E+WVPk0F1Zs6ULbbMpFbQ0sncx4yb5zpXNpfMhBYK3zkuualRVYCCLIRr7t4gmOYoxigh0ShP8CTPHbBnCfU4BllKRJ5gU2J1lmeyyidhSiwL52vcSNMoJD7prIjxUHdK2Y0CypzaYDq2KPhWQQ5anPZ9KhtK0rJl7MUlZcMRPiKys7+FpYO2vEIj6UoupJ3oJ2l+OZcrhIXwW1NadNt6cVuw5ClAQuxIcsR1LU/KE2NUAWCX9PU8z6Fo+J5+IsRLYbUNf2QopsljFkezhKSYhpwMNrwD9MljucSVnvY9vnqYcwTgDpRiRKeeZSlvihl0VeSpIo+XDKFDC+j9yMJggSSVOCvYR/GAPLBU/3kTUHdthU72Dhpbb+z9lpmy3V1BQgmqIYWKyqijzZ4JIXBVdmE67u8oSvmesZL5hIhbzvqJ0unCm/A8siwZ0rbMDYJctFn6hsgDE6sBJZVk3N+4rZvXYKVl6nzFq6zhpRd8Ox8jpCpvyndjBxMHXcNTCfdi1ptM2Zrm288p3wUqrHcf7LxMKIeNuuc80Ns0+XltL6EuYsotSn1BtcWjPOqomsWQFmjJChmvZmswqslLoB8kIwwjByJToojjANw/n2TqdcJTAU0MFuT+T4oR+5gb/EmamGbnF1XnXVI6iUBL7nmrnvQZ/1SBbp2BwyK65Vw1ceAfwIGFVxJzt6RxL6CBmtdmh0Lcvx5sD1PhtabW8Tsb5ge/Y2IMdvHYSdq1ah//hyMDkaT7aBB8o4mRIxZBl3WcZLvmPs+6ZN1EUejRczGb8xidfmp0O8MkUdwLT8hq+O2Gbu9/rs/dq9EeLHb9GgrU2+yOlHJZuqp3AInR52nR6+sZMQYVwrzso+hFGkIfKHLh5e9MReURJGDLtpkEQIimchYYTD34S51zjJyHbMI3F3WrA6k6qEiEUumocdkAOVzMD9QJ9RA86OvvYow2EgOIJJ8T3vJeCx4tyc+MAPgBhMn+NGVQPKbV2AapQgSubUX1qf4Uoq/jz7a+8Hl8L8P1Uy4VpLtff3HnF89PHTr0sLtEJXvFUP4iMEn62EwycEa0B/WwVpHQKUGL7MT/1oEL7b2vO0MHYSwqh0IXJ1a4Dz+eA3ZdQ7nmVEvK2MCA42M7oyV/0dDGIvN424gQkSS+vb7q8WO5YNKOjiiLWmXp6MqC6vJK6UVKuj2H4es5b7NcuoKSqV1xu2o4eEV0Y5ulx3eU6gfe1mu5yQR3LTvkcW/rW7/D1PjpoLJjq1kG3kmYQ2YaNLcHmf58ZRfvqZfvNn3yYn9+NDF539g5cLO8D3sNCH09vR4bFOk1l0gkzkqmjgWbqSW9ehThu3NqdjDE8jbfh976sKXjOFbF8z8+6BBT8vrhYct++ci6v5/D/G0CmZFwsAAA==","origin":"sls-agent"}
END RequestId: f62dcf47-e2ff-4a96-9807-b34c39f218e3
REPORT RequestId: f62dcf47-e2ff-4a96-9807-b34c39f218e3  Duration: 14.09 ms  Billed Duration: 100 ms Memory Size: 1024 MB    Max Memory Used: 71 MB  Init Duration: 190.72 ms
</code>```

I get a similar log output when I run my deployed function through the api gatewaybut I don't see either the console.log In my function locally I am able to see console.log statements or the returned array of objects which I see when I run locally. How to I see those in my deployed lambda function when I run it?

EDIT:

I've added a screenshot of what I think you are referring to.  I don't see the console logged output I see locally. Can you explain further or am I looking in the wrong place?

EDIT1:

```<code>{ origin: 'sls-agent',
  schemaVersion: '0.0',
  timestamp: '2020-06-03T13:13:52.763Z',
  requestId: 'f4a4cb9b-3e09-46d3-adba-6f14753cdce3',
  type: 'transaction',
  payload:
   { schemaType: 's-span',
     .....
     tags:
      { schemaType: 's-transaction-function',
        schemaVersion: '0.0',
        timestamp: '2020-06-03T13:13:52.758Z',
        orgId: null,
        applicationName: 'xxxx',
        serviceName: 'xxxxxx',
        stageName: 'dev',
        functionName: 'xxxxx-dev-main',
        timeout: 6,
        computeType: 'aws.lambda',
        computeRuntime: 'aws.lambda.nodejs.12.16.3',
        computeRegion: 'us-east-1',
        computeMemorySize: '1024',
        computeMemoryUsed:
         '{"rss":39337984,"heapTotal":10039296,"heapUsed":6716000,"external":1191688}',
         ......
        eventCustomRequestTime: '03/Jun/2020:13:13:51 +0000',
        eventCustomRequestTimeEpoch: 1591190031809,
        eventCustomHttpPath: '/main/get',
        eventCustomHttpMethod: 'GET',
        eventCustomXTraceId: 'Root=1-5ed7a20f-9a64d880002f1600092ec680',
        eventCustomXForwardedFor: null,
        eventCustomUserAgent:
         'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0',
        errorId: null,
        errorFatal: null,
        errorCulprit: null,
        errorExceptionType: null,
        errorExceptionMessage: null,
        errorExceptionStacktrace: null,
        transactionId: '77fef8cb-3f2c-4f5a-be2c-7fcd51e9ed92',
        tenantId: 'option88',
        appUid: 'mHjdQ5hQ0RY1',
        tenantUid: 'V8lsDgch9M0b',
        pluginVersion: '3.6.11',
        totalSpans: 0,
        traceId: 'f4a4cb9b-3e09-46d3-adba-6f14753cdce3' },
     logs: {},
     spans: [],
     eventTags: [] } }
</code>```

Edit2:

Edit3:

I changed the handler to :

```<code>'use strict';
var index = require('./index.js');

module.exports.main = async event => {
  var res = await index.main();

  console.log('hello');
  console.log(res);

  console.log('IN HANDLER');
  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: 'main function executed!',
        input: event,
      },
      null,
      2
    ),
  };

};
</code>```

Now seeing error messages.

答:
The logs written to CloudWatch by your Lambda function seem to be Base64 encoded and compressed with the gzip format. This looks like the behavior of the serverless enterprise plugin after issues regarding high costs for CloudWatch were opened.

To retrieve the original logs, you can try running the following Node.js code and pass in the encoded log string.

```<code>function getReadableLogs(encodedLogs) {
    const decodedLog = Buffer.from(encodedLogs, 'base64'); // Decode log data
    const parsed = JSON.parse(zlib.gunzipSync(decodedLog).toString('utf8')); // Decompress log data
    return parsed;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm getting started trying to write a lambda function with node and puppeteer. I'm using the serverless framework

I've been trying to follow https://codissimo.sinumo.tech/2019/12/27/serverless-puppeteer-with-aws-lambda-layers-and-node-js/ to utilize the provisioned chrome at https://github.com/shelfio/chrome-aws-lambda-layer . My function is working as expected locally.

my handler.js contains:

module.exports.main = async event => {
    console.log('IN HANDLER');

  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: 'main function executed!',
        input: event,
      },
      null,
      2
    ),
  };

my index.js contains a longrunning (45- 60 seconds) puppeteer function (main ) which returns an array of objects:

async function main(event, context, callback) {
  const chromium = require('chrome-aws-lambda');

 ...................................

 var obj_arr = [];
  var keys = head[0];
  for (let index = 0; index < body.length; index++) {
    var row = body[index];
    var obj = {};
    for (let i = 0; i < keys.length; i++) {
      var k = keys[i];
      obj[k] = row[i];
      console.log(obj);

    }
    obj_arr.push(obj);

  };

  console.log(obj_arr);
  return obj_arr;

After uploading my function to lambda using  serverless framework without error. I followed the directions at the bottom of the article about testing the pre provisioned chrome in my layers dashboard. As you can see in the screenshot it appears to be working correctly.

being brand new to this I don't understand the log output:

START RequestId: f62dcf47-e2ff-4a96-9807-b34c39f218e3 Version: $LATEST
2020-05-31T19:10:21.280Z    f62dcf47-e2ff-4a96-9807-b34c39f218e3    INFO    SERVERLESS_ENTERPRISE {"c":true,"b":"H4sIAAAAAAAAA7VWbU/cOBD+Kyi6D3fSJms7ifNSIR1aoK1UKsouVe+ADyZxdlMSO9gJL0X732+cZF9ZEJzUL7CZeTyemWf82E+WVPk0F1Zs6ULbbMpFbQ0sncx4yb5zpXNpfMhBYK3zkuualRVYCCLIRr7t4gmOYoxigh0ShP8CTPHbBnCfU4BllKRJ5gU2J1lmeyyidhSiwL52vcSNMoJD7prIjxUHdK2Y0CypzaYDq2KPhWQQ5anPZ9KhtK0rJl7MUlZcMRPiKys7+FpYO2vEIj6UoupJ3oJ2l+OZcrhIXwW1NadNt6cVuw5ClAQuxIcsR1LU/KE2NUAWCX9PU8z6Fo+J5+IsRLYbUNf2QopsljFkezhKSYhpwMNrwD9MljucSVnvY9vnqYcwTgDpRiRKeeZSlvihl0VeSpIo+XDKFDC+j9yMJggSSVOCvYR/GAPLBU/3kTUHdthU72Dhpbb+z9lpmy3V1BQgmqIYWKyqijzZ4JIXBVdmE67u8oSvmesZL5hIhbzvqJ0unCm/A8siwZ0rbMDYJctFn6hsgDE6sBJZVk3N+4rZvXYKVl6nzFq6zhpRd8Ox8jpCpvyndjBxMHXcNTCfdi1ptM2Zrm288p3wUqrHcf7LxMKIeNuuc80Ns0+XltL6EuYsotSn1BtcWjPOqomsWQFmjJChmvZmswqslLoB8kIwwjByJToojjANw/n2TqdcJTAU0MFuT+T4oR+5gb/EmamGbnF1XnXVI6iUBL7nmrnvQZ/1SBbp2BwyK65Vw1ceAfwIGFVxJzt6RxL6CBmtdmh0Lcvx5sD1PhtabW8Tsb5ge/Y2IMdvHYSdq1ah//hyMDkaT7aBB8o4mRIxZBl3WcZLvmPs+6ZN1EUejRczGb8xidfmp0O8MkUdwLT8hq+O2Gbu9/rs/dq9EeLHb9GgrU2+yOlHJZuqp3AInR52nR6+sZMQYVwrzso+hFGkIfKHLh5e9MReURJGDLtpkEQIimchYYTD34S51zjJyHbMI3F3WrA6k6qEiEUumocdkAOVzMD9QJ9RA86OvvYow2EgOIJJ8T3vJeCx4tyc+MAPgBhMn+NGVQPKbV2AapQgSubUX1qf4Uoq/jz7a+8Hl8L8P1Uy4VpLtff3HnF89PHTr0sLtEJXvFUP4iMEn62EwycEa0B/WwVpHQKUGL7MT/1oEL7b2vO0MHYSwqh0IXJ1a4Dz+eA3ZdQ7nmVEvK2MCA42M7oyV/0dDGIvN424gQkSS+vb7q8WO5YNKOjiiLWmXp6MqC6vJK6UVKuj2H4es5b7NcuoKSqV1xu2o4eEV0Y5ulx3eU6gfe1mu5yQR3LTvkcW/rW7/D1PjpoLJjq1kG3kmYQ2YaNLcHmf58ZRfvqZfvNn3yYn9+NDF539g5cLO8D3sNCH09vR4bFOk1l0gkzkqmjgWbqSW9ehThu3NqdjDE8jbfh976sKXjOFbF8z8+6BBT8vrhYct++ci6v5/D/G0CmZFwsAAA==","origin":"sls-agent"}
END RequestId: f62dcf47-e2ff-4a96-9807-b34c39f218e3
REPORT RequestId: f62dcf47-e2ff-4a96-9807-b34c39f218e3  Duration: 14.09 ms  Billed Duration: 100 ms Memory Size: 1024 MB    Max Memory Used: 71 MB  Init Duration: 190.72 ms

I get a similar log output when I run my deployed function through the api gatewaybut I don't see either the console.log In my function locally I am able to see console.log statements or the returned array of objects which I see when I run locally. How to I see those in my deployed lambda function when I run it?

EDIT:

I've added a screenshot of what I think you are referring to.  I don't see the console logged output I see locally. Can you explain further or am I looking in the wrong place?

EDIT1:

{ origin: 'sls-agent',
  schemaVersion: '0.0',
  timestamp: '2020-06-03T13:13:52.763Z',
  requestId: 'f4a4cb9b-3e09-46d3-adba-6f14753cdce3',
  type: 'transaction',
  payload:
   { schemaType: 's-span',
     .....
     tags:
      { schemaType: 's-transaction-function',
        schemaVersion: '0.0',
        timestamp: '2020-06-03T13:13:52.758Z',
        orgId: null,
        applicationName: 'xxxx',
        serviceName: 'xxxxxx',
        stageName: 'dev',
        functionName: 'xxxxx-dev-main',
        timeout: 6,
        computeType: 'aws.lambda',
        computeRuntime: 'aws.lambda.nodejs.12.16.3',
        computeRegion: 'us-east-1',
        computeMemorySize: '1024',
        computeMemoryUsed:
         '{"rss":39337984,"heapTotal":10039296,"heapUsed":6716000,"external":1191688}',
         ......
        eventCustomRequestTime: '03/Jun/2020:13:13:51 +0000',
        eventCustomRequestTimeEpoch: 1591190031809,
        eventCustomHttpPath: '/main/get',
        eventCustomHttpMethod: 'GET',
        eventCustomXTraceId: 'Root=1-5ed7a20f-9a64d880002f1600092ec680',
        eventCustomXForwardedFor: null,
        eventCustomUserAgent:
         'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0',
        errorId: null,
        errorFatal: null,
        errorCulprit: null,
        errorExceptionType: null,
        errorExceptionMessage: null,
        errorExceptionStacktrace: null,
        transactionId: '77fef8cb-3f2c-4f5a-be2c-7fcd51e9ed92',
        tenantId: 'option88',
        appUid: 'mHjdQ5hQ0RY1',
        tenantUid: 'V8lsDgch9M0b',
        pluginVersion: '3.6.11',
        totalSpans: 0,
        traceId: 'f4a4cb9b-3e09-46d3-adba-6f14753cdce3' },
     logs: {},
     spans: [],
     eventTags: [] } }

Edit2:

Edit3:

I changed the handler to :

'use strict';
var index = require('./index.js');

module.exports.main = async event => {
  var res = await index.main();

  console.log('hello');
  console.log(res);

  console.log('IN HANDLER');
  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: 'main function executed!',
        input: event,
      },
      null,
      2
    ),
  };

};

Now seeing error messages.

Body:
The logs written to CloudWatch by your Lambda function seem to be Base64 encoded and compressed with the gzip format. This looks like the behavior of the serverless enterprise plugin after issues regarding high costs for CloudWatch were opened.

To retrieve the original logs, you can try running the following Node.js code and pass in the encoded log string.

function getReadableLogs(encodedLogs) {
    const decodedLog = Buffer.from(encodedLogs, 'base64'); // Decode log data
    const parsed = JSON.parse(zlib.gunzipSync(decodedLog).toString('utf8')); // Decompress log data
    return parsed;
}


问:
Left Join to the latest row using django
I have two tables.
Products [id, name, category]
Sales [product, date, price]

I want to get every Product with the latest row from Sales. If there is no row in sales, I still want to get that product row. The rows are foreign key related.

What is the Django way of doing such a left join?

答:
Probably you can use Subquery:

```<code>from django.db.models import Subquery, OuterRef

sales = Sales.objects.filter(product=OuterRef('pk')).order_by('-date')
products = Product.objects.annotate(latest_sale = Subquery(sales.values('price')[:1]))
</code>```

Body:
Probably you can use Subquery:

from django.db.models import Subquery, OuterRef

sales = Sales.objects.filter(product=OuterRef('pk')).order_by('-date')
products = Product.objects.annotate(latest_sale = Subquery(sales.values('price')[:1]))


问:
How to skip query in column where statement when value is null
I've got simple table

```<code>const Sequelize = require('sequelize');
const sequelize = require('../../util/database');
const Speed = sequelize.define('speed', {
   id: {type: Sequelize.INTEGER, autoIncrement: true, allowNull: false, primaryKey: true},
   level: Sequelize.INTEGER,
   ...
})
module.exports = Speed;
</code>```

and query

```<code>exports.getSpeed = async (req, res, next) => {
   const level = req.body.level
   try {
      const speed = await Speed.findAll({
         where: {level: level, ...}
      });
      res.status(200)
         .json({result: speed})
   }
   catch (err) {
      console.log(err)
   }
}
</code>```

How can I get all results from speed table when level from request body is null?

答:
You can do this: </p>

```<code>exports.getSpeed = async (req, res, next) => {
   const level = req.body.level
   let where = {};

   if(level)
      where = { level: level}

   try {
      const speed = await Speed.findAll({
         where
      });
      res.status(200)
         .json({result: speed})
   }
   catch (err) {
      console.log(err)
   }
}
</code>```

Body:
I've got simple table

const Sequelize = require('sequelize');
const sequelize = require('../../util/database');
const Speed = sequelize.define('speed', {
   id: {type: Sequelize.INTEGER, autoIncrement: true, allowNull: false, primaryKey: true},
   level: Sequelize.INTEGER,
   ...
})
module.exports = Speed;

and query

exports.getSpeed = async (req, res, next) => {
   const level = req.body.level
   try {
      const speed = await Speed.findAll({
         where: {level: level, ...}
      });
      res.status(200)
         .json({result: speed})
   }
   catch (err) {
      console.log(err)
   }
}

How can I get all results from speed table when level from request body is null?

Body:
You can do this:

exports.getSpeed = async (req, res, next) => {
   const level = req.body.level
   let where = {};

   if(level)
      where = { level: level}

   try {
      const speed = await Speed.findAll({
         where
      });
      res.status(200)
         .json({result: speed})
   }
   catch (err) {
      console.log(err)
   }
}


问:
Invoke-Sqlcmd with account that uses MFA in Azure
Anyone of you knows an option to execute a SQL command using PowerShell with Azure AD account that has MFA enabled? What is an alternative? Do I need to create a service principal for that?

I had no luck but only found this cmdlet,
Add-SqlAzureAuthenticationContext
but when I try to run Invoke-Sqlcmd I am getting the following error:

Invoke-Sqlcmd : The target principal name is incorrect.  Cannot
  generate SSPI context.

答:
Not really an answer.

Tried the following

    Add-SqlAzureAuthenticationContext -Interactive
    $sql = 'SELECT @@SERVERNAME AS ServerName';
    $ConnectionString = 'Data Source=tcp:azSERVER.database.windows.net,1433;Initial Catalog=DBNAME;Authentication="Active Directory Interactive";User ID=USERXX@DOMAINYY.COM'
    Invoke-Sqlcmd -ConnectionString $ConnectionString -Query $sql -Verbose
```

and got

Invoke-Sqlcmd : One or more errors occurred.
At line:4 char:5

Please notice that I want to use the interactive flag,

Body:
Not really an answer.

Tried the following

    Add-SqlAzureAuthenticationContext -Interactive
    $sql = 'SELECT @@SERVERNAME AS ServerName';
    $ConnectionString = 'Data Source=tcp:azSERVER.database.windows.net,1433;Initial Catalog=DBNAME;Authentication="Active Directory Interactive";User ID=USERXX@DOMAINYY.COM'
    Invoke-Sqlcmd -ConnectionString $ConnectionString -Query $sql -Verbose

and got

Invoke-Sqlcmd : One or more errors occurred.
At line:4 char:5

Please notice that I want to use the interactive flag,


问:
mongoose different ways to reference subdocuments?
This syntax is straight from the mongoose documentation on subtypes. However, I've also seen this alternate reference to subdocs. What is the difference?

https://mongoosejs.com/docs/subdocs.html

```<code>var childSchema = new Schema({ name: 'string' });

var parentSchema = new Schema({
  // Array of subdocuments
  children: [childSchema],
  // Single nested subdocuments. Caveat: single nested subdocs only work
  // in mongoose >= 4.2.0
  child: childSchema
});
</code>```

An alternate type of reference to subdocs

```<code>var childSchema = new Schema({ name: 'string' });

mongoose.model('children', childSchema);

var parentSchema = new Schema({
  children: {
    type: Schema.Types.ObjectId,
    ref: 'children'
  },
});
</code>```

答:
I have completed
Ravi Shankar Bharti Case 2 with some data writing example. Let's use a book-author scenario:

const authorSchema = new Schema({ name: 'string' });
const authorModel = mongoose.model('authors', authorSchema);

const bookSchema = new Schema({
  title: String,
  author: {
    type: Schema.Types.ObjectId,
    ref: 'author'
  },
});

const bookModel = mongoose.model('books', bookSchema)

const authorData = { name: "John Doe" }

// Check if author does exists. Insert if not or find if yes
const options = {
  upsert: true,
  new: true,
  setDefaultsOnInsert: true
};
const anAuthor = await authorModel.findOneAndUpdate(authorData, authorData, options)

// Insert a new book with reference to `anAuthor`
const aBook = new bookModel({ title: "MyBook" })
aBook.set({ author: anAuthor })
await aBook.save()

```
<p>In this syntax, child documents will be stored separately, and they reference id (_id) will be stored in the parent document.</p>
<p>Sample documents in this case will look something like this:</p>
```// authors documents
{ _id : "authorId1" , name : "John Doe"}
{ _id : "authorId2" , name : "Iron Man"}
{ _id : "authorId3" , name : "Thor Odinson"}

//books document
{
  _id : "parent_random_generated_id"
  title: "MyBook",
  author : "authorId1",
  ...
}
```
<p>And for reading, you can use <code>populate</code>:</p>
```let result = await bookModel.find()
result = await authorModel.populate(result, { path: 'author' })

```

Body:
This syntax is straight from the mongoose documentation on subtypes. However, I've also seen this alternate reference to subdocs. What is the difference?

https://mongoosejs.com/docs/subdocs.html

var childSchema = new Schema({ name: 'string' });

var parentSchema = new Schema({
  // Array of subdocuments
  children: [childSchema],
  // Single nested subdocuments. Caveat: single nested subdocs only work
  // in mongoose >= 4.2.0
  child: childSchema
});

An alternate type of reference to subdocs

var childSchema = new Schema({ name: 'string' });

mongoose.model('children', childSchema);

var parentSchema = new Schema({
  children: {
    type: Schema.Types.ObjectId,
    ref: 'children'
  },
});

Body:
I have completed
Ravi Shankar Bharti Case 2 with some data writing example. Let's use a book-author scenario:

const authorSchema = new Schema({ name: 'string' });
const authorModel = mongoose.model('authors', authorSchema);

const bookSchema = new Schema({
  title: String,
  author: {
    type: Schema.Types.ObjectId,
    ref: 'author'
  },
});

const bookModel = mongoose.model('books', bookSchema)

const authorData = { name: "John Doe" }

// Check if author does exists. Insert if not or find if yes
const options = {
  upsert: true,
  new: true,
  setDefaultsOnInsert: true
};
const anAuthor = await authorModel.findOneAndUpdate(authorData, authorData, options)

// Insert a new book with reference to `anAuthor`
const aBook = new bookModel({ title: "MyBook" })
aBook.set({ author: anAuthor })
await aBook.save()

In this syntax, child documents will be stored separately, and they reference id (_id) will be stored in the parent document.

Sample documents in this case will look something like this:

// authors documents
{ _id : "authorId1" , name : "John Doe"}
{ _id : "authorId2" , name : "Iron Man"}
{ _id : "authorId3" , name : "Thor Odinson"}

//books document
{
  _id : "parent_random_generated_id"
  title: "MyBook",
  author : "authorId1",
  ...
}

And for reading, you can use populate:

let result = await bookModel.find()
result = await authorModel.populate(result, { path: 'author' })


问:
How to search string under cursor in Eclipse
In vim, pressing * in command mode performs an automatic search of the word under the cursor. How can I obtain the same in Eclipse?

答:
Windows 10, tested on Eclipse 2020-03:

Two Steps:

1. Alt + Shift + Up Arrow, to select the word under the cursor

2. Ctrl + K to find the selected word forward

(Ctrl + Shift + K to find the selected word backward)

NOTE:

If you are inside an XML tag, Alt + Shift + Up Arrow will select from the beginning of the tag to the end tag, including all enclosing elements. Try it!

BONUS:

Ctrl + Shift + Down/Up arrows to navigate methods, as sometimes the selected word is a method you want to go to.

Better still,
Ctrl + O - Go to a specific method, by searching (Just enter the first few letters of the method, and Enter)

Cheers

ContentLicense: CC BY-SA 3.0


问:
How to generate load on IIS?
I want to start using load balancers, database replication and sharding, cloud computing. I know I can follow many tutorials, that's no problem, but I don't know how to generate sufficient traffic to load the web server. I want to see my test application working really slow and then apply some scaling techniques.

Q How can I generate huge load on my local IIS server? What tools can I use?

P.S. if it will help I want to use RESTful WCF service and No SQL DB/Cloud storage for a test app

答: I haven't used it extensively, but SoapUI and LoadUI work well together to do this.</p>

Title: How to generate load on IIS?


问:
Why StringCopyFromLiteral is faster than StringCopyFromString?
The Quick C++ Benchmarks example:

```<code>static void StringCopyFromLiteral(benchmark::State& state) {
  // Code inside this loop is measured repeatedly
  for (auto _ : state) {
    std::string from_literal("hello");
    // Make sure the variable is not optimized away by compiler
    benchmark::DoNotOptimize(from_literal);
  }
}
// Register the function as a benchmark
BENCHMARK(StringCopyFromLiteral);

static void StringCopyFromString(benchmark::State& state) {
  // Code before the loop is not measured
  std::string x = "hello";
  for (auto _ : state) {
    std::string from_string(x);
  }
}
// Register the function as a benchmark
BENCHMARK(StringCopyFromString);
</code>```

http://quick-bench.com/IcZllt_14hTeMaB_sBZ0CQ8x2Ro

What if I understand assembly...

More results:

http://quick-bench.com/39fLTvRdpR5zdapKSj2ZzE3asCI

答:
The answer is simple. In the case where you construct an std::string from a small string literal, the compiler optimizes this case by directly populating the contents of the string object using constants in assembly.  This avoids expensive looping as well as tests to see whether small string optimization (SSO) can be applied.  In this case it knows SSO can be applied so the code the compiler generates simply involves writing the string directly into the SSO buffer.

Note this assembly code in the StringCreation case:

```<code>// Populate SSO buffer (each set of 4 characters is backwards since
// x86 is little-endian)
19.63% movb   $0x6f,0x4(%r15)    // "o"
19.35% movl   $0x6c6c6568,(%r15) // "lleh"
// Set size
20.26% movq   $0x5,0x10(%rsp)    // size = 5
// Probably set heap pointer. 0 (nullptr) = use SSO buffer
20.07% movb   $0x0,0x1d(%rsp)
</code>```

You're looking at the constant values right there. That's not very much code, and no loop is required.  In fact, the std::string constructor doesn't even have to be invoked!  The compiler is just putting stuff in memory in the same places where the std::string constructor would.

If the compiler cannot apply this optimization, the results are quite different -- in particular, if we "hide" the fact that the source is a string literal by first copying the literal into a char array, the results flip:

```<code>char x[] = "hello";
for (auto _ : state) {
  std::string created_string(x);
  benchmark::DoNotOptimize(created_string);
}
</code>```

Now the "from-char-pointer" case takes twice as long!  Why?

I suspect that this is because the "copy from char pointer" case cannot simply check to see how long the string is by looking at a value.  It needs to know whether small string optimization can be performed.  There's a few ways it could go about this:

Measure the length of the string first, make an allocation (if needed), then copy the source to the destination.  In the case where SSO does apply (it almost certainly does here) I'd expect this to take twice as long since it has to walk the source twice -- once to measure, once to copy.

Copy from the source character-by-character, appending to the new string.  This requires testing on each append operation whether the string is now too long for SSO and needs to be copied into a heap-allocated char array.  If the string is currently in a heap-allocated array, it needs to instead test if the allocation needs to be resized.  This would also take quite a bit longer since there is at least one test for each character in the source string.

Copy from the source in chunks to lower the number of tests that need to be performed and to avoid walking the source twice.  This would be faster than the character-by-character approach both because the number of tests would be lower and, because the source is not being walked twice, the CPU memory cache is going to be more effective.  This would only show significant speed improvements for long strings, which we don't have here.  For short strings it would work about the same as the first approach (measure, then copy).

Contrast this to the case when it's copying from another string object: it can simply look at the size() of the other string and immediately know whether it can perform SSO, and if it can't perform SSO then it also knows exactly how much memory to allocate for the new string.

Body:
The Quick C++ Benchmarks example:

static void StringCopyFromLiteral(benchmark::State& state) {
  // Code inside this loop is measured repeatedly
  for (auto _ : state) {
    std::string from_literal("hello");
    // Make sure the variable is not optimized away by compiler
    benchmark::DoNotOptimize(from_literal);
  }
}
// Register the function as a benchmark
BENCHMARK(StringCopyFromLiteral);

static void StringCopyFromString(benchmark::State& state) {
  // Code before the loop is not measured
  std::string x = "hello";
  for (auto _ : state) {
    std::string from_string(x);
  }
}
// Register the function as a benchmark
BENCHMARK(StringCopyFromString);

http://quick-bench.com/IcZllt_14hTeMaB_sBZ0CQ8x2Ro

What if I understand assembly...

More results:

http://quick-bench.com/39fLTvRdpR5zdapKSj2ZzE3asCI

Body:
The answer is simple. In the case where you construct an std::string from a small string literal, the compiler optimizes this case by directly populating the contents of the string object using constants in assembly.  This avoids expensive looping as well as tests to see whether small string optimization (SSO) can be applied.  In this case it knows SSO can be applied so the code the compiler generates simply involves writing the string directly into the SSO buffer.

Note this assembly code in the StringCreation case:

// Populate SSO buffer (each set of 4 characters is backwards since
// x86 is little-endian)
19.63% movb   $0x6f,0x4(%r15)    // "o"
19.35% movl   $0x6c6c6568,(%r15) // "lleh"
// Set size
20.26% movq   $0x5,0x10(%rsp)    // size = 5
// Probably set heap pointer. 0 (nullptr) = use SSO buffer
20.07% movb   $0x0,0x1d(%rsp)

You're looking at the constant values right there. That's not very much code, and no loop is required.  In fact, the std::string constructor doesn't even have to be invoked!  The compiler is just putting stuff in memory in the same places where the std::string constructor would.

If the compiler cannot apply this optimization, the results are quite different -- in particular, if we "hide" the fact that the source is a string literal by first copying the literal into a char array, the results flip:

char x[] = "hello";
for (auto _ : state) {
  std::string created_string(x);
  benchmark::DoNotOptimize(created_string);
}

Now the "from-char-pointer" case takes twice as long!  Why?

I suspect that this is because the "copy from char pointer" case cannot simply check to see how long the string is by looking at a value.  It needs to know whether small string optimization can be performed.  There's a few ways it could go about this:

Measure the length of the string first, make an allocation (if needed), then copy the source to the destination.  In the case where SSO does apply (it almost certainly does here) I'd expect this to take twice as long since it has to walk the source twice -- once to measure, once to copy.

Copy from the source character-by-character, appending to the new string.  This requires testing on each append operation whether the string is now too long for SSO and needs to be copied into a heap-allocated char array.  If the string is currently in a heap-allocated array, it needs to instead test if the allocation needs to be resized.  This would also take quite a bit longer since there is at least one test for each character in the source string.

Copy from the source in chunks to lower the number of tests that need to be performed and to avoid walking the source twice.  This would be faster than the character-by-character approach both because the number of tests would be lower and, because the source is not being walked twice, the CPU memory cache is going to be more effective.  This would only show significant speed improvements for long strings, which we don't have here.  For short strings it would work about the same as the first approach (measure, then copy).

Contrast this to the case when it's copying from another string object: it can simply look at the size() of the other string and immediately know whether it can perform SSO, and if it can't perform SSO then it also knows exactly how much memory to allocate for the new string.


问:
Class Not Found in PHP Laravel 6.x when another class extends
I always get the class not found exception in php laravel 6 when i create a class and extend a parent class named A which is located in the same directory.

However, another child class that is located in same directory could extend class A successfully.

In addition, i couldn't also instantiate the class A due to class not found exception in another .php file.

Please help me on this.
Thanks in an advance.

Parent class: myContext

```<code><?php
namespace config\models;

class myContext {
    public static $conn;
    ...
}
</code>```

Class myUser: extension is fine.

```<code><?php
namespace config\models;

class myUser extends myContext {
   private $name;
   ...
}
</code>```

Class oauth: extension returns myContext class not found.

```<code><?php
namespace config\models;

class oauth extends myContext {
    private $user;
}
</code>```

Instantiate the class - returns class not found.

```<code><?php

use config\models\myContext as context;

$cont = new context();
</code>```

答:
Check whether the namespace is added correctly when the parent class is imported.

Refer

https://www.quora.com/What-is-namespaces-and-use-in-Laravel

external classes and PHP files in Laravel - Class not found

Laravel - Model Class not found

Laravel 6: Class 'Form' not found

Body:
I always get the class not found exception in php laravel 6 when i create a class and extend a parent class named A which is located in the same directory.

However, another child class that is located in same directory could extend class A successfully.

In addition, i couldn't also instantiate the class A due to class not found exception in another .php file.

Please help me on this.
Thanks in an advance.

Parent class: myContext

<?php
namespace config\models;

class myContext {
    public static $conn;
    ...
}

Class myUser: extension is fine.

<?php
namespace config\models;

class myUser extends myContext {
   private $name;
   ...
}

Class oauth: extension returns myContext class not found.

<?php
namespace config\models;

class oauth extends myContext {
    private $user;
}

Instantiate the class - returns class not found.

<?php

use config\models\myContext as context;

$cont = new context();


问:
So sockets generated by socketpair() are availble across different processes?
As we know fd(file descriptor,an int to be exact) is per process,that is,the same file opened in different processes may have different fd.

And I thought so should be for sockets.

But when reading nginx source code I found it's using sockets to communicate between processes:

```<code>    if (socketpair(AF_UNIX, SOCK_STREAM, 0, ngx_processes[s].channel) == -1)
    {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                      "socketpair() failed while spawning \"%s\"", name);
        return NGX_INVALID_PID;
    }
</code>```

Here ngx_processes[s].channel[0] is sent to other process.

But as I said fd is per process,how can it ensure that the same int will point to the same socket?

UPDATE

Why question is now how this works(it's the same way that nginx uses)?

http://swtch.com/usr/local/plan9/src/lib9/sendfd.c

答:
nginx uses unix domain sockets ancillary messages (specifically, the SCM_RIGHTS message, see  the man page for the unix protocol for more information on this) to pass file descriptors around.

When you receive an SCM_RIGHTS message, the kernel basically gives you a duplicate (as in dup) file descriptor, valid in the receiving process. This fd may or may not have the same number, which matters very little as the receiving side should use the contents of the message  and not some prior knowledge.

Body:
As we know fd(file descriptor,an int to be exact) is per process,that is,the same file opened in different processes may have different fd.

And I thought so should be for sockets.

But when reading nginx source code I found it's using sockets to communicate between processes:

    if (socketpair(AF_UNIX, SOCK_STREAM, 0, ngx_processes[s].channel) == -1)
    {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                      "socketpair() failed while spawning \"%s\"", name);
        return NGX_INVALID_PID;
    }

Here ngx_processes[s].channel[0] is sent to other process.

But as I said fd is per process,how can it ensure that the same int will point to the same socket?

UPDATE

Why question is now how this works(it's the same way that nginx uses)?

http://swtch.com/usr/local/plan9/src/lib9/sendfd.c


问:
Difference between SonarQube and Fortify?
Can someone tell me what is the difference between SonarQube and Fortify? Both are static code analysis tool. I found out Fortify is more inclined towards security as it gives information about vulnerabilities included in OWASP, SANS etc. SonarQube also shows this information.</p>

答:
When comparing product its good to have a list of things, here is my list let me know what you think.

Fortify

static analysis

can't add rules, using configuration as code

proprietary rules

manual file upload use case, no easy way of pipeline integration

does not provide git branch perspectives, improvements over other branches

provide only security code metrics

not opensource

has only paid support model

SonarQube

static analysis

can add rules, using configuration as code

has standard rules based on language being used

automated code upload use case, has tooling for major frameworks

provide git branch perspectives, improvements over other branches

provide all code quality metrics, including security

opensource

has paid support model

free cloud host sonarcloud.io


问:
Codeigniter's Model with QueryBuilder JOIN query
Really new to working with CI4's Model and struggling to adapt my existing MySQL JOIN queries to work with the examples in its User Guide.

I have adapted part of my code like so:

```<code>    public function brand_name($brand_name_slug)
    {
        return $this->asArray()
                    ->where('availability', 'in stock')
                    ->where('sku !=', '')
                    ->where('brand_name_slug', $brand_name_slug)
                    ->groupBy('gtin')
                    ->orderBy('brand_name, subbrand_name, product, size, unit')
                    ->findAll();
    }
</code>```

It works fine. I have looked at examples, and figured out I can add the code ->table('shop a') and it still works, but I also need to to add the following JOIN statement:

```<code>JOIN (SELECT gtin, MIN(sale_price) AS sale_price FROM shop GROUP BY gtin) AS b ON a.gtin = b.gtin AND a.sale_price = b.sale_price
</code>```

As soon as I add ->join('shop b', 'a.gtin = b.gtin and a.sale_price = b.sale_price') I get a '404 - File Not Found' error.

When I look at all examples of CI4 joins and adapt my code to fit, my foreach($shop as $row) loop generates a 'Whoops...' error because they end with a getResult() or getResultArray - instead of findAll().

Which is the way forward, and do I need to change my foreach loop.

Full MySQL statement:

```<code>SELECT * FROM shop a JOIN (SELECT gtin, MIN(sale_price) AS sale_price FROM shop GROUP BY gtin) AS b ON a.gtin = b.gtin AND a.sale_price = b.sale_price WHERE availability = 'in stock' AND sku != '' AND brand_name_slug = $brand_name_slug GROUP BY gtin ORDER BY brand_name, subbrand_name, product, size
</code>```

答:
BaseBuilder Class in Codeigniter expects the first join parameter to be the table name. So try passing the table name and join it on the table name itself. I haven't personally used the table aliases so I might also be wrong.

Following are the parameter that the JOIN query expects :

```<code>    public function join(string $table, string $cond, string $type = '', bool $escape = null)
</code>```

Here, it expects the first name be a table, so try out by switching aliases for the table's name directly.

For your second part of query, It would be better if you could show the whole error rather than just posting the first of the error.

Body:
Really new to working with CI4's Model and struggling to adapt my existing MySQL JOIN queries to work with the examples in its User Guide.

I have adapted part of my code like so:

    public function brand_name($brand_name_slug)
    {
        return $this->asArray()
                    ->where('availability', 'in stock')
                    ->where('sku !=', '')
                    ->where('brand_name_slug', $brand_name_slug)
                    ->groupBy('gtin')
                    ->orderBy('brand_name, subbrand_name, product, size, unit')
                    ->findAll();
    }

It works fine. I have looked at examples, and figured out I can add the code ->table('shop a') and it still works, but I also need to to add the following JOIN statement:

JOIN (SELECT gtin, MIN(sale_price) AS sale_price FROM shop GROUP BY gtin) AS b ON a.gtin = b.gtin AND a.sale_price = b.sale_price

As soon as I add ->join('shop b', 'a.gtin = b.gtin and a.sale_price = b.sale_price') I get a '404 - File Not Found' error.

When I look at all examples of CI4 joins and adapt my code to fit, my foreach($shop as $row) loop generates a 'Whoops...' error because they end with a getResult() or getResultArray - instead of findAll().

Which is the way forward, and do I need to change my foreach loop.

Full MySQL statement:

SELECT * FROM shop a JOIN (SELECT gtin, MIN(sale_price) AS sale_price FROM shop GROUP BY gtin) AS b ON a.gtin = b.gtin AND a.sale_price = b.sale_price WHERE availability = 'in stock' AND sku != '' AND brand_name_slug = $brand_name_slug GROUP BY gtin ORDER BY brand_name, subbrand_name, product, size

Body:
BaseBuilder Class in Codeigniter expects the first join parameter to be the table name. So try passing the table name and join it on the table name itself. I haven't personally used the table aliases so I might also be wrong.

Following are the parameter that the JOIN query expects :

    public function join(string $table, string $cond, string $type = '', bool $escape = null)

Here, it expects the first name be a table, so try out by switching aliases for the table's name directly.

For your second part of query, It would be better if you could show the whole error rather than just posting the first of the error.


问:
Is there a nuget package that contains Dapper.Net SqlBuilder?
I can't find a nuget package that contains Dapper.Net SqlBuilder.

It's not in Dapper dot net.
It's not in DapperExtensions.
Its' not in Dapper.Contrib.

Is there a nuget package available for Dapper.Net SqlBuilder?

答: The question was asked in 2014, and since 2015, the Nuget package is here: https://www.nuget.org/packages/Dapper.SqlBuilder/</p>


问:
ISSUE: Mysql converting Enum to Int
I have a very simple rating system in my database where each rating is stored as an enum('1','-1').  To calculate the total I tried using this statement:

```<code>SELECT SUM(CONVERT(rating, SIGNED)) as value from table WHERE _id = 1
</code>```

This works fine for the positive 1 but for some reason the -1 are parsed out to 2's.

Can anyone help or offer incite?

Or should I give up and just change the column to a SIGNED INT(1)?

答:
I wouldn't use enum here too, but it is still possible in this case to get what is needed

Creating table:

```<code>CREATE TABLE test (
    _id INT PRIMARY KEY,
    rating ENUM('1', '-1')
);
</code>```

Filling table:

```<code>INSERT INTO test VALUES(1, "1"), (2, "1"), (3, "-1"), (4, "-1"), (5, "-1");
</code>```

Performing math operations on enums converts them to indexes, so it is possible just to scale the result value:

```<code>SELECT
    SUM(3 - rating * 2)
FROM
    test;
</code>```

Result: -1 which is true for the test case.

Title: ISSUE: Mysql converting Enum to Int

Body:
I have a very simple rating system in my database where each rating is stored as an enum('1','-1').  To calculate the total I tried using this statement:

SELECT SUM(CONVERT(rating, SIGNED)) as value from table WHERE _id = 1

This works fine for the positive 1 but for some reason the -1 are parsed out to 2's.

Can anyone help or offer incite?

Or should I give up and just change the column to a SIGNED INT(1)?

Body:
I wouldn't use enum here too, but it is still possible in this case to get what is needed

Creating table:

CREATE TABLE test (
    _id INT PRIMARY KEY,
    rating ENUM('1', '-1')
);

Filling table:

INSERT INTO test VALUES(1, "1"), (2, "1"), (3, "-1"), (4, "-1"), (5, "-1");

Performing math operations on enums converts them to indexes, so it is possible just to scale the result value:

SELECT
    SUM(3 - rating * 2)
FROM
    test;

Result: -1 which is true for the test case.


问:
pd.Series.explode and ValueError: cannot reindex from a duplicate axis
I consulted a lot of the posts on ValueError: cannot reindex from a duplicate axis ([What does `ValueError: cannot reindex from a duplicate axis` mean? and other related posts. I understand that the error can arise with duplicate row indices or column names, but I still can't quite figure out what exactly is throwing me the error.

Below is my best at reproducing the spirit of the dataframe, which does throw the error.

```<code>d = {"id" : [1,2,3,4,5],
"cata" : [['aaa1','bbb2','ccc3'],['aaa4','bbb5','ccc6'],['aaa7','bbb8','ccc9'],['aaa10','bbb11','ccc12'],['aaa13','bbb14','ccc15']],
 "catb" : [['ddd1','eee2','fff3','ggg4'],['ddd5','eee6','fff7','ggg8'],['ddd9','eee10','fff11','ggg12'],['ddd13','eee14','fff15','ggg16'],['ddd17','eee18','fff19','ggg20']],
 "catc" : [['hhh1','iii2','jjj3', 'kkk4', 'lll5'],['hhh6','iii7','jjj8', 'kkk9', 'lll10'],['hhh11','iii12','jjj13', 'kkk14', 'lll15'],['hhh16','iii17','jjj18', 'kkk18', 'lll19'],['hhh20','iii21','jjj22', 'kkk23', 'lll24']]}

df = pd.DataFrame(d)

df.head()

    id  cata    catb    catc
0   1   [aaa1, bbb2, ccc3]  [ddd1, eee2, fff3, ggg4]    [hhh1, iii2, jjj3, kkk4, lll5]
1   2   [aaa4, bbb5, ccc6]  [ddd5, eee6, fff7, ggg8]    [hhh6, iii7, jjj8, kkk9, lll10]
2   3   [aaa7, bbb8, ccc9]  [ddd9, eee10, fff11, ggg12]     [hhh11, iii12, jjj13, kkk14, lll15]
3   4   [aaa10, bbb11, ccc12]   [ddd13, eee14, fff15, ggg16]    [hhh16, iii17, jjj18, kkk18, lll19]
4   5   [aaa13, bbb14, ccc15]   [ddd17, eee18, fff19, ggg20]    [hhh20, iii21, jjj22, kkk23, lll24]

df.set_index(['id']).apply(pd.Series.explode).reset_index()
</code>```

Here is the error:

```<code>---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-63-17e7c29b180c> in <module>()
----> 1 df.set_index(['id']).apply(pd.Series.explode).reset_index()

14 frames

/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in _can_reindex(self, indexer)
   3097         # trying to reindex on an axis with duplicates
   3098         if not self.is_unique and len(indexer):
-> 3099             raise ValueError("cannot reindex from a duplicate axis")
   3100
   3101     def reindex(self, target, method=None, level=None, limit=None, tolerance=None):

ValueError: cannot reindex from a duplicate axis
</code>```

The dataset I'm using is a few hundred MBs and it's a pain - lots of lists inside lists, but the example of above is a fair representation of where I'm stuck. Even when I try to generate a fake dataframe with unique values, I still don't understand why I'm getting the ValueError.

I have explored other ways to explode the lists like using df.apply(lambda x: x.apply(pd.Series).stack()).reset_index().drop('level_1', 1), which doesn't throw a value error, however, it's definitely not as fast and I'd probably would reconsider how I'm processing the df. Still, I want to understand why I'm getting the ValueError I'm getting when I don't have any obvious duplicate values.

Thanks!!!!

Adding desired output here, below, which i generated by chaining apply/stack/dropping levels.

```<code>    id  cata    catb    catc
0   1   aaa1    ddd1    hhh1
1   1   bbb2    eee2    iii2
2   1   ccc3    fff3    jjj3
3   1   NaN     ggg4    kkk4
4   1   NaN     NaN     lll5
5   2   aaa4    ddd5    hhh6
6   2   bbb5    eee6    iii7
7   2   ccc6    fff7    jjj8
8   2   NaN     ggg8    kkk9
9   2   NaN     NaN     lll10
10  3   aaa7    ddd9    hhh11
11  3   bbb8    eee10   iii12
12  3   ccc9    fff11   jjj13
13  3   NaN     ggg12   kkk14
14  3   NaN     NaN     lll15
15  4   aaa10   ddd13   hhh16
16  4   bbb11   eee14   iii17
17  4   ccc12   fff15   jjj18
18  4   NaN     ggg16   kkk18
19  4   NaN     NaN     lll19
20  5   aaa13   ddd17   hhh20
21  5   bbb14   eee18   iii21
22  5   ccc15   fff19   jjj22
23  5   NaN     ggg20   kkk23
24  5   NaN     NaN     lll24
</code>```

答:
The error of pd.Series.explode() cannot be solved, but a long form with an 'id' column is created.

```<code>tmp = pd.concat([df['id'],df['cata'].apply(pd.Series),df['catb'].apply(pd.Series),df['catc'].apply(pd.Series)],axis=1)
tmp2 = tmp.unstack().to_frame().reset_index()
tmp2 = tmp2[tmp2['level_0'] != 'id']
tmp2.drop('level_1', axis=1, inplace=True)
tmp2.rename(columns={'level_0':'id', 0:'value'}).set_index()
tmp2.reset_index(drop=True, inplace=True)

    id  value
0   0   aaa1
1   0   aaa4
2   0   aaa7
3   0   aaa10
4   0   aaa13
5   1   bbb2
6   1   bbb5
7   1   bbb8
8   1   bbb11
9   1   bbb14
10  2   ccc3
11  2   ccc6
12  2   ccc9
...
</code>```

Body:
I consulted a lot of the posts on ValueError: cannot reindex from a duplicate axis ([What does `ValueError: cannot reindex from a duplicate axis` mean? and other related posts. I understand that the error can arise with duplicate row indices or column names, but I still can't quite figure out what exactly is throwing me the error.

Below is my best at reproducing the spirit of the dataframe, which does throw the error.

d = {"id" : [1,2,3,4,5],
"cata" : [['aaa1','bbb2','ccc3'],['aaa4','bbb5','ccc6'],['aaa7','bbb8','ccc9'],['aaa10','bbb11','ccc12'],['aaa13','bbb14','ccc15']],
 "catb" : [['ddd1','eee2','fff3','ggg4'],['ddd5','eee6','fff7','ggg8'],['ddd9','eee10','fff11','ggg12'],['ddd13','eee14','fff15','ggg16'],['ddd17','eee18','fff19','ggg20']],
 "catc" : [['hhh1','iii2','jjj3', 'kkk4', 'lll5'],['hhh6','iii7','jjj8', 'kkk9', 'lll10'],['hhh11','iii12','jjj13', 'kkk14', 'lll15'],['hhh16','iii17','jjj18', 'kkk18', 'lll19'],['hhh20','iii21','jjj22', 'kkk23', 'lll24']]}

df = pd.DataFrame(d)

df.head()

    id  cata    catb    catc
0   1   [aaa1, bbb2, ccc3]  [ddd1, eee2, fff3, ggg4]    [hhh1, iii2, jjj3, kkk4, lll5]
1   2   [aaa4, bbb5, ccc6]  [ddd5, eee6, fff7, ggg8]    [hhh6, iii7, jjj8, kkk9, lll10]
2   3   [aaa7, bbb8, ccc9]  [ddd9, eee10, fff11, ggg12]     [hhh11, iii12, jjj13, kkk14, lll15]
3   4   [aaa10, bbb11, ccc12]   [ddd13, eee14, fff15, ggg16]    [hhh16, iii17, jjj18, kkk18, lll19]
4   5   [aaa13, bbb14, ccc15]   [ddd17, eee18, fff19, ggg20]    [hhh20, iii21, jjj22, kkk23, lll24]

df.set_index(['id']).apply(pd.Series.explode).reset_index()

Here is the error:

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-63-17e7c29b180c> in <module>()
----> 1 df.set_index(['id']).apply(pd.Series.explode).reset_index()

14 frames

/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in _can_reindex(self, indexer)
   3097         # trying to reindex on an axis with duplicates
   3098         if not self.is_unique and len(indexer):
-> 3099             raise ValueError("cannot reindex from a duplicate axis")
   3100
   3101     def reindex(self, target, method=None, level=None, limit=None, tolerance=None):

ValueError: cannot reindex from a duplicate axis

The dataset I'm using is a few hundred MBs and it's a pain - lots of lists inside lists, but the example of above is a fair representation of where I'm stuck. Even when I try to generate a fake dataframe with unique values, I still don't understand why I'm getting the ValueError.

I have explored other ways to explode the lists like using df.apply(lambda x: x.apply(pd.Series).stack()).reset_index().drop('level_1', 1), which doesn't throw a value error, however, it's definitely not as fast and I'd probably would reconsider how I'm processing the df. Still, I want to understand why I'm getting the ValueError I'm getting when I don't have any obvious duplicate values.

Thanks!!!!

Adding desired output here, below, which i generated by chaining apply/stack/dropping levels.

    id  cata    catb    catc
0   1   aaa1    ddd1    hhh1
1   1   bbb2    eee2    iii2
2   1   ccc3    fff3    jjj3
3   1   NaN     ggg4    kkk4
4   1   NaN     NaN     lll5
5   2   aaa4    ddd5    hhh6
6   2   bbb5    eee6    iii7
7   2   ccc6    fff7    jjj8
8   2   NaN     ggg8    kkk9
9   2   NaN     NaN     lll10
10  3   aaa7    ddd9    hhh11
11  3   bbb8    eee10   iii12
12  3   ccc9    fff11   jjj13
13  3   NaN     ggg12   kkk14
14  3   NaN     NaN     lll15
15  4   aaa10   ddd13   hhh16
16  4   bbb11   eee14   iii17
17  4   ccc12   fff15   jjj18
18  4   NaN     ggg16   kkk18
19  4   NaN     NaN     lll19
20  5   aaa13   ddd17   hhh20
21  5   bbb14   eee18   iii21
22  5   ccc15   fff19   jjj22
23  5   NaN     ggg20   kkk23
24  5   NaN     NaN     lll24

Body:
The error of pd.Series.explode() cannot be solved, but a long form with an 'id' column is created.

tmp = pd.concat([df['id'],df['cata'].apply(pd.Series),df['catb'].apply(pd.Series),df['catc'].apply(pd.Series)],axis=1)
tmp2 = tmp.unstack().to_frame().reset_index()
tmp2 = tmp2[tmp2['level_0'] != 'id']
tmp2.drop('level_1', axis=1, inplace=True)
tmp2.rename(columns={'level_0':'id', 0:'value'}).set_index()
tmp2.reset_index(drop=True, inplace=True)

    id  value
0   0   aaa1
1   0   aaa4
2   0   aaa7
3   0   aaa10
4   0   aaa13
5   1   bbb2
6   1   bbb5
7   1   bbb8
8   1   bbb11
9   1   bbb14
10  2   ccc3
11  2   ccc6
12  2   ccc9
...


问:
How to trim video with start and end pos of seekbar using FFmpeg android?
String[] cmd = new String[]{"-ss", startTrim + ".00", "-t", endTrim + ".00", "-noaccurate_seek", "-i", videoPath, "-codec", "copy", "-avoid_negative_ts", "1", outputAudioMux};</p>

答:
```<code> private void trimVideo(ProgressDialog progressDialog) {

    outputAudioMux = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath()
            + "/VidEffectsFilter" + "/" + new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date())
            + "filter_apply.mp4";

    if (startTrim.equals("")) {
        startTrim = "00:00:00";
    }

    if (endTrim.equals("")) {
        endTrim = timeTrim(player.getDuration());
    }

    String[] cmd = new String[]{"-ss", startTrim + ".00", "-t", endTrim + ".00", "-noaccurate_seek", "-i", videoPath, "-codec", "copy", "-avoid_negative_ts", "1", outputAudioMux};

    execFFmpegBinary1(cmd, progressDialog);
}

    private void execFFmpegBinary1(final String[] command, ProgressDialog prpg) {

    ProgressDialog progressDialog = prpg;

    try {
        ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
            @Override
            public void onFailure(String s) {
                progressDialog.dismiss();
                Toast.makeText(PlayerActivity.this, "Fail to generate video", Toast.LENGTH_SHORT).show();
                Log.d(TAG, "FAILED with output : " + s);
            }

            @Override
            public void onSuccess(String s) {
                Log.d(TAG, "SUCCESS wgith output : " + s);

                String finalPath = outputAudioMux;
                videoPath = outputAudioMux;
                Toast.makeText(PlayerActivity.this, "Storage Path =" + finalPath, Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(PlayerActivity.this, ShareVideoActivity.class);
                intent.putExtra("pathGPU", finalPath);
                startActivity(intent);
                finish();
                MediaScannerConnection.scanFile(PlayerActivity.this, new String[]{finalPath}, new String[]{"mp4"}, null);

            }

            @Override
            public void onProgress(String s) {
                Log.d(TAG, "Started gcommand : ffmpeg " + command);
                progressDialog.setMessage("Please Wait video triming...");
            }

            @Override
            public void onStart() {
                Log.d(TAG, "Startedf command : ffmpeg " + command);

            }

            @Override
            public void onFinish() {
                Log.d(TAG, "Finished f command : ffmpeg " + command);
                progressDialog.dismiss();
            }
        });
    } catch (FFmpegCommandAlreadyRunningException e) {
        // do nothing for now
    }
}
</code>```


问:
Error in sending data (post) from AJAX to NODEJS app
I need to get data sent from ajax to nodejs.
Here is AJAX side:

```<code> $.ajax({
  type:"POST",
  url: "http://127.0.0.1:3000/a",
  data: { id: "2" },
  dataType: 'jsonp',
  contentType: "application/json",
  success: function fun(json) {
    console.log(JSON.stringify(json));
  }
})
</code>```

And In Node:

```<code>var express = require('express')
var bodyParser = require('body-parser')
var app = express()
app.use(bodyParser.json())
var quizzController = require('./quizzController')

app.post('/a', function (req,rep) {
  rep.send('ok')
  console.log(req.body.id)
})
app.listen(3000)
</code>```

When I send, I get this error in AJAX side:

```<code>GET http://127.0.0.1:3000/a?                              callback=jQuery111105826120341114538_1490969686792&id=2&_=1490969686793
</code>```

答:
Give a try with following code:</p>

```<code>$.ajax({
  url: "/a",
  type:"POST",
  data: { id: "2" },
  dataType: 'json',
  contentType: "application/json",
  success: function fun(json) {
    console.log(JSON.stringify(json));
  }
})
</code>```

Body:
I need to get data sent from ajax to nodejs.
Here is AJAX side:

 $.ajax({
  type:"POST",
  url: "http://127.0.0.1:3000/a",
  data: { id: "2" },
  dataType: 'jsonp',
  contentType: "application/json",
  success: function fun(json) {
    console.log(JSON.stringify(json));
  }
})

And In Node:

var express = require('express')
var bodyParser = require('body-parser')
var app = express()
app.use(bodyParser.json())
var quizzController = require('./quizzController')

app.post('/a', function (req,rep) {
  rep.send('ok')
  console.log(req.body.id)
})
app.listen(3000)

When I send, I get this error in AJAX side:

GET http://127.0.0.1:3000/a?                              callback=jQuery111105826120341114538_1490969686792&id=2&_=1490969686793

Body:
Give a try with following code:

$.ajax({
  url: "/a",
  type:"POST",
  data: { id: "2" },
  dataType: 'json',
  contentType: "application/json",
  success: function fun(json) {
    console.log(JSON.stringify(json));
  }
})


问:
Java Recursion - Capture Parent Category based on Child Property
```<code>Class Category
{
  private String id;
  List<Category> subCategory;
  List<Products> products
}
</code>```

Is there a way to get all the categories which has products or any of its subcategories has products.

```<code>package algorithms;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Sample {

// The below recursion is capturing only last child nodes not the parent.

private static boolean recursion(Catalog currentCatList, List<Catalog> extractedCatsList) {
    if(currentCatList.getSubCat() == null) {
        return currentCatList.getProducts() != null;
    }
    Iterator<Catalog> subCatItr = currentCatList.getSubCat().iterator();
    while(subCatItr.hasNext()) {
        Catalog cat = subCatItr.next();
        boolean hasProducts = recursion(cat, extractedCatsList);
        if(hasProducts){
            extractedCatsList.add(cat);
        }
    }
    return currentCatList.getProducts() != null;
}

public static void main(String[] args) {
    Catalog cat = new Catalog();
    cat.setId("catId_1");
    createSubCategories(cat,1);
    List<Catalog> extractedCatsList = new ArrayList<Catalog>();
    recursion(cat,extractedCatsList);
    System.out.println("extractedCatsList >>>>> "+extractedCatsList);
}

// Below 2 only to create sample request -

public static void createSubCategories(Catalog cat,int SubCategoriesNeeded){
    List<Catalog> subCat = new ArrayList<Catalog>(2);
    for(int i = 0 ; i <= SubCategoriesNeeded; i ++){
        Catalog subCat1 = new Catalog();
        subCat1.setId("subCat_"+i);
        createSubSubCategories(subCat1,2,i);
        subCat.add(subCat1);
    }
    cat.setSubCat(subCat);
}

public static void createSubSubCategories(Catalog cat,int SubCategoriesNeeded,int subCatIndex){
    List<Catalog> subCat = new ArrayList<Catalog>(2);
    for(int i = 0 ; i < SubCategoriesNeeded; i ++){
        Catalog subCat1 = new Catalog();
        subCat1.setId("subCat_"+subCatIndex+"_"+i);
        if(subCatIndex != 1 && i%2 == 0){
            List<String> products = new ArrayList<String>();
            products.add("prodSubSub"+i);
            subCat1.setProducts(products);
        }
        subCat.add(subCat1);
    }
    cat.setSubCat(subCat);
}

}
</code>```

I tried the above with recursion method and got all the last Subcategories but not sure how to identify the parent categories whose subcategories has products.

Expected Output -
catId_1, SubCat_0, SubCat_0_0.

But the above is giving only SubCat_0_0. It should give the expected as above.

Any help is appreciated

答:
You can try this:</p>

```<code>private ArrayList<Category> found = new ArrayList<>();

private boolean searchInside(Category category) {
  boolean hasProduct = false;
  boolean subCategoryhasProduct = false;
  if ((category.products != null) && (category.products.size() > 0)) {
    found.add(category);
    hasProduct = true;
  }

  if (category.subCategory != null) {
    Iterator<Category> subCategoryIterator = category.subCategory.iterator();
    while(subCategoryIterator.hasNext()) {
        Category subCategory = subCategoryIterator.next();
        if (searchInside(subCategory)) {
            subCategoryhasProduct = true;
        }

        if (!hasProduct && subCategoryhasProduct) {
          found.add(category);
        }
    }
  }

  return hasProduct || subCategoryhasProduct;
}
</code>```

Body:
Class Category
{
  private String id;
  List<Category> subCategory;
  List<Products> products
}

Is there a way to get all the categories which has products or any of its subcategories has products.

package algorithms;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Sample {

// The below recursion is capturing only last child nodes not the parent.

private static boolean recursion(Catalog currentCatList, List<Catalog> extractedCatsList) {
    if(currentCatList.getSubCat() == null) {
        return currentCatList.getProducts() != null;
    }
    Iterator<Catalog> subCatItr = currentCatList.getSubCat().iterator();
    while(subCatItr.hasNext()) {
        Catalog cat = subCatItr.next();
        boolean hasProducts = recursion(cat, extractedCatsList);
        if(hasProducts){
            extractedCatsList.add(cat);
        }
    }
    return currentCatList.getProducts() != null;
}

public static void main(String[] args) {
    Catalog cat = new Catalog();
    cat.setId("catId_1");
    createSubCategories(cat,1);
    List<Catalog> extractedCatsList = new ArrayList<Catalog>();
    recursion(cat,extractedCatsList);
    System.out.println("extractedCatsList >>>>> "+extractedCatsList);
}

// Below 2 only to create sample request -

public static void createSubCategories(Catalog cat,int SubCategoriesNeeded){
    List<Catalog> subCat = new ArrayList<Catalog>(2);
    for(int i = 0 ; i <= SubCategoriesNeeded; i ++){
        Catalog subCat1 = new Catalog();
        subCat1.setId("subCat_"+i);
        createSubSubCategories(subCat1,2,i);
        subCat.add(subCat1);
    }
    cat.setSubCat(subCat);
}

public static void createSubSubCategories(Catalog cat,int SubCategoriesNeeded,int subCatIndex){
    List<Catalog> subCat = new ArrayList<Catalog>(2);
    for(int i = 0 ; i < SubCategoriesNeeded; i ++){
        Catalog subCat1 = new Catalog();
        subCat1.setId("subCat_"+subCatIndex+"_"+i);
        if(subCatIndex != 1 && i%2 == 0){
            List<String> products = new ArrayList<String>();
            products.add("prodSubSub"+i);
            subCat1.setProducts(products);
        }
        subCat.add(subCat1);
    }
    cat.setSubCat(subCat);
}

}

I tried the above with recursion method and got all the last Subcategories but not sure how to identify the parent categories whose subcategories has products.

Expected Output -
catId_1, SubCat_0, SubCat_0_0.

But the above is giving only SubCat_0_0. It should give the expected as above.

Any help is appreciated

Body:
You can try this:

private ArrayList<Category> found = new ArrayList<>();

private boolean searchInside(Category category) {
  boolean hasProduct = false;
  boolean subCategoryhasProduct = false;
  if ((category.products != null) && (category.products.size() > 0)) {
    found.add(category);
    hasProduct = true;
  }

  if (category.subCategory != null) {
    Iterator<Category> subCategoryIterator = category.subCategory.iterator();
    while(subCategoryIterator.hasNext()) {
        Category subCategory = subCategoryIterator.next();
        if (searchInside(subCategory)) {
            subCategoryhasProduct = true;
        }

        if (!hasProduct && subCategoryhasProduct) {
          found.add(category);
        }
    }
  }

  return hasProduct || subCategoryhasProduct;
}


问:
R - Repetitions of an array in other array
From a dataframe I get a new array, sliced from a dataframe.
I want to get the amount of times a certain repetition appears on it.

For example

```<code>main <- c(A,B,C,A,B,V,A,B,C,D,E)
p <- c(A,B,C)
q <- c(A,B)

someFunction(main,p)
2

someFunction(main,q)
3
</code>```

I've been messing around with rle but it counts every subrepetion also, undersirable.

Is there a quick solution I'm missing?

答:
Here's a way to do it using embed(v,n), which returns a matrix of all n-length sub-sequences of vector v:

```<code>find_x_in_y <- function(x, y)
                   sum( apply( embed( y, length(x)), 1,
                                  identical, rev(x)))

> find_x_in_y(p, main)
[1] 2
> find_x_in_y(q, main)
[1] 3
</code>```

Body:
From a dataframe I get a new array, sliced from a dataframe.
I want to get the amount of times a certain repetition appears on it.

For example

main <- c(A,B,C,A,B,V,A,B,C,D,E)
p <- c(A,B,C)
q <- c(A,B)

someFunction(main,p)
2

someFunction(main,q)
3

I've been messing around with rle but it counts every subrepetion also, undersirable.

Is there a quick solution I'm missing?

Body:
Here's a way to do it using embed(v,n), which returns a matrix of all n-length sub-sequences of vector v:

find_x_in_y <- function(x, y)
                   sum( apply( embed( y, length(x)), 1,
                                  identical, rev(x)))

> find_x_in_y(p, main)
[1] 2
> find_x_in_y(q, main)
[1] 3


问:
I am new to python with no previous coding experience. My program is supposed to display the price of a ticket depending on age. Why does it not work?
My code will display ticket price dependent on age. Why is it not working? This is exercise 7-5 from the Python Crash Course book.</p>

```<code>
prompt = "\nEnter Age: "
prompt += "\nEnter 'quit' when done."
age = ''

while age != 'quit':

    age = input(prompt)
    print(age)
    if age != 'quit':
        if age > '13':
            print(f'You ticket price is $15.00.')
            print(f'Retrieve your ticket(s) below')

        if age <= '13' and age > '2':
            print(f'Your ticket price is $10.00.')
            print(f'Retrieve your ticket(s) below')

        if age < '3':
            print(f'Your ticket price is free')
            print(f'Retrieve your ticket below')

print(f'Thank You Enjoy the show')
</code>```

答:
I hope this simplification of your code helps:</p>

```<code>age = int(input("Enter Age: "))
if age > 13:
    print('You ticket price is $15.00.')
    print('Retrieve your ticket(s) below')
if age <= 13 and age > 2:
    print(f'Your ticket price is $10.00.')
    print(f'Retrieve your ticket(s) below')
if age < 3:
    print('Your ticket price is free')
    print('Retrieve your ticket below')
</code>```

Body:
My code will display ticket price dependent on age. Why is it not working? This is exercise 7-5 from the Python Crash Course book.

prompt = "\nEnter Age: "
prompt += "\nEnter 'quit' when done."
age = ''

while age != 'quit':

    age = input(prompt)
    print(age)
    if age != 'quit':
        if age > '13':
            print(f'You ticket price is $15.00.')
            print(f'Retrieve your ticket(s) below')

        if age <= '13' and age > '2':
            print(f'Your ticket price is $10.00.')
            print(f'Retrieve your ticket(s) below')

        if age < '3':
            print(f'Your ticket price is free')
            print(f'Retrieve your ticket below')

print(f'Thank You Enjoy the show')

Body:
I hope this simplification of your code helps:

age = int(input("Enter Age: "))
if age > 13:
    print('You ticket price is $15.00.')
    print('Retrieve your ticket(s) below')
if age <= 13 and age > 2:
    print(f'Your ticket price is $10.00.')
    print(f'Retrieve your ticket(s) below')
if age < 3:
    print('Your ticket price is free')
    print('Retrieve your ticket below')


问:
WinSCP using PowerShell is adding a directory to the SFTP site I'm uploading to
I'm using a PowerShell script and WinSCP to upload a file onto an SFTP site, Root\Users\SFTPSite and it's placing the directory onto the SFTP site that I'm uploading from. So instead of putting it on Root\Users\SFTPSite it's putting it into Root\Users\SFTPSite\Outbound.  Not sure if it's a permissions issue that's preventing me from placing it in the SFTPSite directory or something to do with how the SFTP site was setup or something else because I'm using the same script for other sites without a problem. Here are the parameters I'm using

param (
    $localPath = "\\fileshare\ftp\ThirdParty\Outbound\",
    $remotePath = "/users/SFTPSite/"
)
```

<p>And here is how I'm transferring,</p>

```$transferResult = $session.PutFiles($localPath, $remotePath, $False, $transferOptions)
```

Any help would be greatly appreciated. - Thanks.

答:
Isn't it because you are copying the directory ?

Do you try to copy the content adding a * ?

```<code> param (
     $localPath = "\\fileshare\ftp\ThirdParty\Outbound\*",
     $remotePath = "/users/SFTPSite/"
      )
</code>```

Body:
I'm using a PowerShell script and WinSCP to upload a file onto an SFTP site, Root\Users\SFTPSite and it's placing the directory onto the SFTP site that I'm uploading from. So instead of putting it on Root\Users\SFTPSite it's putting it into Root\Users\SFTPSite\Outbound.  Not sure if it's a permissions issue that's preventing me from placing it in the SFTPSite directory or something to do with how the SFTP site was setup or something else because I'm using the same script for other sites without a problem. Here are the parameters I'm using

param (
    $localPath = "\\fileshare\ftp\ThirdParty\Outbound\",
    $remotePath = "/users/SFTPSite/"
)

And here is how I'm transferring,

$transferResult = $session.PutFiles($localPath, $remotePath, $False, $transferOptions)

Any help would be greatly appreciated. - Thanks.

Body:
Isn't it because you are copying the directory ?

Do you try to copy the content adding a * ?

 param (
     $localPath = "\\fileshare\ftp\ThirdParty\Outbound\*",
     $remotePath = "/users/SFTPSite/"
      )