text:
Q: Android: How should I pass a ListView between activities, when the Context object disallows Parcelable? I'm creating an alarm clock application, and I'd like the homepage to have multiple  Alarm objects shown, like the default Android clock application. To do this, I've been trying a ListView to create a button for each Alarm in an ArrayList of Alarms.
Debugging the crashes this caused, I've found that it can't implement Serializable or Parcelable due to the Context object within it, and thus I have no way to pass it from one activity to another. The ListView works fine when I create the alarms from the MainActivity itself, but when I use the CreateAlarmActivity that takes input from the user, the ListView won't pass through and it crashes.
I haven't found this precise problem on StackOverflow. This problem is close (Implementing Parcelable Class That Requires Context) but involves a database, which seems overkill for my needs.
If a ListView is even the best way to go about this, how should I pass the ListView between activities? If there's a better way, what would be a better implementation?
I apologise for the large amount of code. I'm not sure exactly what may prove relevant, so I've erred on the side of too much information rather than too little.
Code:
MainActivity.java:
public class MainActivity extends AppCompatActivity {

    ListView alarmListView;
    ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
    int[] testArray = {0, 0, 0, 0, 0, 0, 0};
    Alarm testAlarm = new Alarm("testAlarm", 6, 1, true, testArray, 10);
    Alarm testAlarm2 = new Alarm("testAlarm2", 6, 1, true, testArray, 10);
    AlarmAdapter alarmAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        alarmListView = (ListView) findViewById(R.id.alarmListView);
        alarmList.add(testAlarm);
        alarmList.add(testAlarm2);

        alarmAdapter = new AlarmAdapter(MainActivity.this, alarmList);
        alarmListView.setAdapter(alarmAdapter);
        alarmAdapter.notifyDataSetChanged();
    }

    // Create alarm when user presses FAB on activity_main.xml.
    public void createNewAlarm(View view) {
        Intent createAlarmIntent = new Intent(this, CreateAlarmActivity.class);
        createAlarmIntent.putExtra("alarmList", alarmList);
        createAlarmIntent.putExtra("alarmAdapter", alarmAdapter);
        startActivity(createAlarmIntent);
    }

    public void testAlarmActivated(View view){
        Intent activateAlarmIntent = new Intent(this, AlarmActivatedActivity.class);
        startActivity(activateAlarmIntent);
    }

}
AlarmAdapter.java:
public class AlarmAdapter extends BaseAdapter implements Parcelable {

    private Context alarmContext;
    private ArrayList<Alarm> alarmList;

    public AlarmAdapter(Context context, ArrayList arrayList) {
        super();
        alarmContext = context;
        alarmList = arrayList;
    }

    public int getCount() {
        return alarmList.size();
    }

    // getView method is called for each item of ListView
    public View getView(int position, View view, ViewGroup parent) {
        // inflate the layout for each item of listView
        LayoutInflater inflater = (LayoutInflater) alarmContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.alarm_row, parent, false);

        // get the reference of textView and button
        TextView alarmName = (TextView) view.findViewById(R.id.title);
        // Button alarmButton = (Button) view.findViewById(R.id.alarmButton);

        // Set the title and button name
        Alarm tempAlarm = alarmList.get(position);
        alarmName.setText(tempAlarm.name);
        // btnAction.setText("Action " + position);

        // Click listener of button
        /*btnAction.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Logic goes here
            }
        });*/

        return view;
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    protected AlarmAdapter(Parcel in) {
        alarmContext = (Context) in.readValue(Context.class.getClassLoader());
        if (in.readByte() == 0x01) {
            alarmList = new ArrayList<Alarm>();
            in.readList(alarmList, Alarm.class.getClassLoader());
        } else {
            alarmList = null;
        }
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeValue(alarmContext);
        if (alarmList == null) {
            dest.writeByte((byte) (0x00));
        } else {
            dest.writeByte((byte) (0x01));
            dest.writeList(alarmList);
        }
    }

    @SuppressWarnings("unused")
    public static final Parcelable.Creator<AlarmAdapter> CREATOR = new Parcelable.Creator<AlarmAdapter>() {
        @Override
        public AlarmAdapter createFromParcel(Parcel in) {
            return new AlarmAdapter(in);
        }

        @Override
        public AlarmAdapter[] newArray(int size) {
            return new AlarmAdapter[size];
        }
    };
}

Alarm.java:
public class Alarm implements Serializable {

    String name;
    int hour;
    int minute;
    boolean isPm;
    int[] daysActive;
    int snoozeTimer;

    public Alarm(String startName, int startHour, int startMinute,
                 Boolean startIsPm, int[] startDaysActive, int startSnoozeTimer){

        name = startName;
        hour = startHour;
        minute = startMinute;
        isPm = startIsPm;
        daysActive = startDaysActive;
        snoozeTimer = startSnoozeTimer;

    }
}

CreateAlarmActivity.java:
public class CreateAlarmActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_alarm);
        alarmList = (ArrayList<Alarm>)getIntent().getSerializableExtra("alarmList");
        alarmAdapter = (AlarmAdapter)getIntent().getParcelableExtra("alarmAdapter)");
    }

    int alarmHour = 6;
    int alarmMinute = 0;
    boolean isPm = false;
    int snoozeTimer = 10;
    int [] daysActive = new int[] {0, 0, 0, 0, 0, 0, 0};

    ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
    AlarmAdapter alarmAdapter;

    // Add one to the hour of the alarm.
    public void changeHour(View view) {
        Button btn = findViewById(R.id.buttonHours);

        if (alarmHour == 12){
            alarmHour = 0;
        }
        else {
            alarmHour++;
        }

        btn.setText(Integer.toString(alarmHour));

    }

    // Add one to the minute of the alarm.
    public void changeMinute(View view) {
        Button btn = findViewById(R.id.buttonMinutes);

        if (alarmMinute == 59) {
            alarmMinute = 0;
        }
        else {
            alarmMinute++;
        }

        if (alarmMinute < 10) {
            // Ensure minute 1 becomes 01, e.g, 6:01 am.
            btn.setText("0" + Integer.toString(alarmMinute));
        }
        else {
            btn.setText(Integer.toString(alarmMinute));
        }
    }

    public void changeAmPm(View view) {
        Button btn = findViewById(R.id.buttonAmPm);
        if (isPm == true) {
            isPm = false;
            btn.setText("am");
        }
        else {
            isPm = true;
            btn.setText("pm");
        }
    }

    public void changeSnoozeTimer(View view) {
        Button btn = findViewById(R.id.buttonSnoozeTimer);
        if (snoozeTimer == 15){
            snoozeTimer = 1;
        }
        else {
            snoozeTimer++;
        }
        btn.setText(Integer.toString(snoozeTimer));
    }

    public void finishAlarm(View view){
        EditText alarmName = findViewById(R.id.alarmName);
        String name = alarmName.getText().toString();
        Alarm alarm = new Alarm(name, alarmHour, alarmMinute, isPm, daysActive, snoozeTimer);
        alarmList.add(alarm);
        alarmAdapter.notifyDataSetChanged();
        Intent finishAlarmIntent = new Intent(this, MainActivity.class);
        finishAlarmIntent.putExtra("alarmList", alarmList);
        startActivity(finishAlarmIntent);
    }

    public void cancelAlarm(View view){
        Intent cancelAlarmIntent = new Intent(this, MainActivity.class);
        startActivity(cancelAlarmIntent);
    }

    public void changeSunday(View view) {
        Button btn = findViewById(R.id.buttonSunday);
        if (daysActive[0] == 0){
            daysActive[0] = 1;
            // Source: https://stackoverflow.com/questions/2173936/how-to-set-background-color-of-a-view
            // Credit goes to EddieB for the below line.
            btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
        }
        else {
            daysActive[1] = 0;
            // Source: https://stackoverflow.com/questions/14802354/how-to-reset-a-buttons-background-color-to-default
            // Credit goes to Ivo for the below line.
            btn.getBackground().clearColorFilter();
        }
    }

    public void changeMonday(View view) {
        Button btn = findViewById(R.id.buttonMonday);
        if (daysActive[1] == 0){
            daysActive[1] = 1;
            btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
        }
        else {
            daysActive[1] = 0;
            btn.getBackground().clearColorFilter();
        }
    }

    public void changeTuesday(View view) {
        Button btn = findViewById(R.id.buttonTuesday);
        if (daysActive[2] == 0){
            daysActive[2] = 1;
            btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
        }
        else {
            daysActive[2] = 0;
            btn.getBackground().clearColorFilter();
        }
    }

    public void changeWednesday(View view) {
        Button btn = findViewById(R.id.buttonWednesday);
        if (daysActive[3] == 0){
            daysActive[3] = 1;
            btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
        }
        else {
            daysActive[3] = 0;
            btn.getBackground().clearColorFilter();
        }
    }

    public void changeThursday(View view) {
        Button btn = findViewById(R.id.buttonThursday);
        if (daysActive[4] == 0){
            daysActive[4] = 1;
            btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
        }
        else {
            daysActive[4] = 0;
            btn.getBackground().clearColorFilter();
        }
    }

    public void changeFriday(View view) {
        Button btn = findViewById(R.id.buttonFriday);
        if (daysActive[5] == 0){
            daysActive[5] = 1;
            btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
        }
        else {
            daysActive[5] = 0;
            btn.getBackground().clearColorFilter();
        }
    }

    public void changeSaturday(View view) {
        Button btn = findViewById(R.id.buttonSaturday);
        if (daysActive[6] == 0){
            daysActive[6] = 1;
            btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
        }
        else {
            daysActive[6] = 0;
            btn.getBackground().clearColorFilter();
        }
    }

}


text:
Q: How to use ellipsis in responsive CSS table cell? I want to create something like this screenshot:

I tried using table display when the numbers and text are table-cell and the circle is absolute position, but it seems like I can't use ellipsis on table-cell.
My design is responsive so I can't use fixed width.
jsfiddle

        1

        very very long text that will need to be nowrap and with ellipsis very very long text that will need to be nowrap and with ellipsis
        very very long text that will need to be nowrap and with ellipsis
        very very long text that will need to be nowrap and with ellipsis

        absolute

.wrapper{
    display: table;
    width: 100%;
}
.cell{
    display: table-cell;
}
.cell1{
    background: yellow;
}
.cell2{
    background: lightblue;
}

A: Because CSS ellipsis normally only works with known width container, or in a fixed table layout, I wrapped the middle cell into some divs to create another inner table for it, so it's all responsive.
For creating multiple rows, you'll need another div container and set to display: table-row;
jsfiddle

.wrapper {
    display: table;
    border-collapse: collapse;
}
.row {
    display: table-row;
}
.cell {
    display: table-cell;
    border: 1px solid red;
}
.cell2 .content {
    display: table;
    table-layout: fixed;
    width: 100%;
}
.cell2 .content .ellipsis {
    display: table-cell;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

1

very very long text that will need to be nowrap and with ellipsis very very long text that will need to be nowrap and with ellipsis very very long text that will need to be nowrap and with ellipsis very very long text that will need to be nowrap and with ellipsis

circle

2

very very long text that will need to be nowrap and with ellipsis very very long text that will need to be nowrap and with ellipsis very very long text that will need to be nowrap and with ellipsis very very long text that will need to be nowrap and with ellipsis

circle

A: I hope this is what you wanted
I've added this CSS -
.cell3 {
    height: 0;
    padding-bottom: 100%;
    background-color: red;
    border-radius: 50%;
}

And this is the link to the fiddle
Tip: There are better way to achieve what you're trying to achieve

redpajama_set_name: RedPajamaStackExchange


text:
Q: IntelliJ IDEA Ultimate - Opening Error Mac: java.lang.IllegalArgumentException Installed the IntelliJ IDEA Ultimate and tried to open it but receive the error below (see code section). I am using macOS Sierra (Version 10.12.6) and installed IntelliJ IDEA Version 2017.3.3.
Can someone tell me how to solve this issue?
Many thanks.
Internal error. Please report to http://jb.gg/ide/critical-startup-errors java.lang.IllegalArgumentException: Width (0.0) or height (0.0) cannot be <= 0
at sun.awt.image.MultiResolutionCachedImage.checkSize(MultiResolutionCachedImage.java:79)
at sun.awt.image.MultiResolutionCachedImage.getResolutionVariant(MultiResolutionCachedImage.java:63)
at sun.awt.image.MultiResolutionCachedImage.getBaseImage(MultiResolutionCachedImage.java:122)
at java.awt.image.AbstractMultiResolutionImage.getWidth(AbstractMultiResolutionImage.java:69)

[[[... error continues ...]]]

A: I just restrated the system and - all of a sudden - it worked. (Please make also sure that you have the newest Java installed).


text:
Q: How to use xslt 1.0 translate() to replace multiple characters when one of the desired characters would be blank I am wondering the most efficient way to perform the following xslt variable selection:
<xsl:value-of select="translate(translate('1aaa1a1paa6a5p5aa4paaa52', 'a', ''), 'p' , '.')" />

The output should end up being 111.65.54.52
With this code it is correct, I am just wondering if there is a way to combine the two translate functions!
Thanks


text:
Q: Envio una solicitud ajax con un array de objetos, los cuales con tienen una llave de string con espacio y mi backend lo recibe sin espacios A mi backend envio un json como este:
[
  {
    "br": 2,
    "selectPrintMode": 0,
    "setColor": 0,
    "setDoubleStrike": false,
    "setEmphasis": true,
    "setFont": 0,
    "setJustification": 1,
    "setLineSpacing": 1,
    "setPrintLeftMargin": 0,
    "setPrintWidth": 576,
    "setReverseColors": false,
    "setTextSize": [
      1,
      1
    ],
    "setUnderline": 0,
    "text": "*** Vales ***"
  },
  {
    "br": 1,
    "selectPrintMode": 0,
    "setColor": 0,
    "setDoubleStrike": false,
    "setEmphasis": true,
    "setFont": 0,
    "setJustification": 1,
    "setLineSpacing": 1,
    "setPrintLeftMargin": 0,
    "setPrintWidth": 576,
    "setReverseColors": false,
    "setTextSize": [
      1,
      1
    ],
    "setUnderline": 0,
    "text": "Concepto       Observacion                 Monto"
  },
  {
    "br": 1,
    "selectPrintMode": 0,
    "setColor": 0,
    "setDoubleStrike": false,
    "setEmphasis": false,
    "setFont": 0,
    "setJustification": 0,
    "setLineSpacing": 1,
    "setPrintLeftMargin": 0,
    "setPrintWidth": 576,
    "setReverseColors": false,
    "setTextSize": [
      1,
      1
    ],
    "setUnderline": 0,
    "text": "restrooms    Esto tan solo es una               "
  },
  {
    "br": 1,
    "selectPrintMode": 0,
    "setColor": 0,
    "setDoubleStrike": false,
    "setEmphasis": false,
    "setFont": 0,
    "setJustification": 0,
    "setLineSpacing": 1,
    "setPrintLeftMargin": 0,
    "setPrintWidth": 576,
    "setReverseColors": false,
    "setTextSize": [
      1,
      1
    ],
    "setUnderline": 0,
    "text": "             prueba                             "
  },
  {
    "br": 1,
    "selectPrintMode": 0,
    "setColor": 0,
    "setDoubleStrike": false,
    "setEmphasis": false,
    "setFont": 0,
    "setJustification": 0,
    "setLineSpacing": 1,
    "setPrintLeftMargin": 0,
    "setPrintWidth": 576,
    "setReverseColors": false,
    "setTextSize": [
      1,
      1
    ],
    "setUnderline": 0,
    "text": "                                                "
  },
  {
    "br": 1,
    "selectPrintMode": 0,
    "setColor": 0,
    "setDoubleStrike": false,
    "setEmphasis": false,
    "setFont": 0,
    "setJustification": 0,
    "setLineSpacing": 1,
    "setPrintLeftMargin": 0,
    "setPrintWidth": 576,
    "setReverseColors": false,
    "setTextSize": [
      1,
      1
    ],
    "setUnderline": 0,
    "text": "                                                "
  },
  {
    "br": 1,
    "selectPrintMode": 0,
    "setColor": 0,
    "setDoubleStrike": false,
    "setEmphasis": false,
    "setFont": 0,
    "setJustification": 0,
    "setLineSpacing": 1,
    "setPrintLeftMargin": 0,
    "setPrintWidth": 576,
    "setReverseColors": false,
    "setTextSize": [
      1,
      1
    ],
    "setUnderline": 0,
    "text": "                                         9999.00"
  }
]
El problema es que cuando lo recibo en el backend obtengo las llaves text sin los espacios antes y despues del texto (como si estuviese haciendo un trim). ¿Alguien sabe como puedo evitar eso?
[
  {
    "br": "2",
    "selectPrintMode": "0",
    "setColor": "0",
    "setDoubleStrike": "false",
    "setEmphasis": "true",
    "setFont": "0",
    "setJustification": "1",
    "setLineSpacing": "1",
    "setPrintLeftMargin": "0",
    "setPrintWidth": "576",
    "setReverseColors": "false",
    "setTextSize": [
      "1",
      "1"
    ],
    "setUnderline": "0",
    "text": "*** Vales ***"
  },
  {
    "br": "1",
    "selectPrintMode": "0",
    "setColor": "0",
    "setDoubleStrike": "false",
    "setEmphasis": "true",
    "setFont": "0",
    "setJustification": "1",
    "setLineSpacing": "1",
    "setPrintLeftMargin": "0",
    "setPrintWidth": "576",
    "setReverseColors": "false",
    "setTextSize": [
      "1",
      "1"
    ],
    "setUnderline": "0",
    "text": "Concepto       Observacion                 Monto"
  },
  {
    "br": "1",
    "selectPrintMode": "0",
    "setColor": "0",
    "setDoubleStrike": "false",
    "setEmphasis": "false",
    "setFont": "0",
    "setJustification": "0",
    "setLineSpacing": "1",
    "setPrintLeftMargin": "0",
    "setPrintWidth": "576",
    "setReverseColors": "false",
    "setTextSize": [
      "1",
      "1"
    ],
    "setUnderline": "0",
    "text": "restrooms    Esto tan solo es una"
  },
  {
    "br": "1",
    "selectPrintMode": "0",
    "setColor": "0",
    "setDoubleStrike": "false",
    "setEmphasis": "false",
    "setFont": "0",
    "setJustification": "0",
    "setLineSpacing": "1",
    "setPrintLeftMargin": "0",
    "setPrintWidth": "576",
    "setReverseColors": "false",
    "setTextSize": [
      "1",
      "1"
    ],
    "setUnderline": "0",
    "text": "prueba"
  },
  {
    "br": "1",
    "selectPrintMode": "0",
    "setColor": "0",
    "setDoubleStrike": "false",
    "setEmphasis": "false",
    "setFont": "0",
    "setJustification": "0",
    "setLineSpacing": "1",
    "setPrintLeftMargin": "0",
    "setPrintWidth": "576",
    "setReverseColors": "false",
    "setTextSize": [
      "1",
      "1"
    ],
    "setUnderline": "0",
    "text": null
  },
  {
    "br": "1",
    "selectPrintMode": "0",
    "setColor": "0",
    "setDoubleStrike": "false",
    "setEmphasis": "false",
    "setFont": "0",
    "setJustification": "0",
    "setLineSpacing": "1",
    "setPrintLeftMargin": "0",
    "setPrintWidth": "576",
    "setReverseColors": "false",
    "setTextSize": [
      "1",
      "1"
    ],
    "setUnderline": "0",
    "text": null
  },
  {
    "br": "1",
    "selectPrintMode": "0",
    "setColor": "0",
    "setDoubleStrike": "false",
    "setEmphasis": "false",
    "setFont": "0",
    "setJustification": "0",
    "setLineSpacing": "1",
    "setPrintLeftMargin": "0",
    "setPrintWidth": "576",
    "setReverseColors": "false",
    "setTextSize": [
      "1",
      "1"
    ],
    "setUnderline": "0",
    "text": "9999.00"
  }
]
Actualización 1:
El backend lo manejo de esta manera. ¿Por que necesito los espacios? Es porque necesito imprimir en una impresora térmica la cual estoy ordenando los datos como si fuesen una tabla.
public function imprimir(Request $req) {
    try{
        $profile = CapabilityProfile::load("TM-T88IV");
        $connector = new NetworkPrintConnector($req['ip']);
        $printer = new Printer($connector, $profile);

        $lista = $req['lineas'];
        foreach ($lista as $key => $value) {
            $printer->selectPrintMode(intval($value['selectPrintMode']));
            $printer->setColor(intval($value['setColor']));
            $printer->setDoubleStrike(($value['setDoubleStrike']==='true')?true:false);
            $printer->setEmphasis(($value['setEmphasis']==='true')?true:false);
            $printer->setFont(intval($value['setFont']));
            $printer->setJustification(intval($value['setJustification']));
            $printer->setLineSpacing(intval($value['setLineSpacing']));
            $printer->setPrintLeftMargin(intval($value['setPrintLeftMargin']));
            $printer->setReverseColors(($value['setReverseColors']==='true')?true:false);
            $printer->setTextSize(intval($value['setTextSize'][0]),intval($value['setTextSize'][1]));
            $printer->setUnderline(intval($value['setUnderline']));
            $printer->text($value['text']);
        }

        $printer->feed();
        $printer->cut();
        $printer->close();
        return Response::json($req);
    }catch(Exception $e){
        return Response::json($e);
    }
}
Actualizacion 2:
Los envío en una petición ajax de la siguiente manera:
$.ajax({
    type: 'post',
    global: true,
    url: 'imprimir',
    data: datos, //acá va el json que envío.
}).then(
    function(data) {
        alertify.notify('Impreso correctamente','success');
    }, function(data) {
        console.log('this will run if the $.ajax fails');
        console.log('Error');
        console.log(data);
    }, function() {
        console.log('this will run if the deferred generates a progress update');
    }
);

A: El texto con los espacios en blanco pasalos por encodeURIComponent("   texto")
encodeURIComponent("Concepto       Observacion                 Monto")


text:
Q: How to return two values from a function in C? Need your help please.
I want the function "double racine" to return two values at the same time.
`
double racine(int a, int b, int c){

    int delta = (b*b) - 4*(a*c);
    return(((-b + sqrt(delta))/ 2*a) &&((-b - sqrt(delta))/ 2*a));

    }

`
double racine(int a, int b, int c){

    int delta = (b*b) - 4*(a*c);
    return(((-b + sqrt(delta))/ 2*a) &&((-b - sqrt(delta))/ 2*a));

    }


text:
Q: read file to bytearray adobe extendscript Is there a way to read a file in adobe extendscript to bytearray? I will upload
the bytes to a rest server.
Currently, i'm using below and it is giving me binary string.
var s = file.read();

A: Not really.  The JavaScript interpreter ExtendScript is based on pre-dates the typed array datatypes.  You'll have to work with the binary string.


text:
Q: localStorage and Javascript Object with arrays, save Issue I have the follwoing Components:
patientDiseasesStorage = new Object()
patientDiseasesStorage['p158246547'] = [1, 3, 8, 2, 5] //and many more of this with different p-number

I try now to save this Object/Array Combination
localStorage.setItem('patientDiseasesStorage', JSON.stringify(patientDiseasesStorage));

But when i try to read this back from localStorage it does not have the correct values:
patientDiseasesStorage = JSON.parse(localStorage.getItem('patientDiseasesStorage'));
patientDiseasesStorage['p158246547'] is now undefined and not the array.

What am I doing wrong?

A: If p158246547 is a string and not a variable name, it should have quotes around it:
patientDiseasesStorage['p158246547'] = [1, 3, 8, 2, 5] //and many more of this with different p-number

Use the quotes when you pull it back out of the localStorage as well.

A: What browser are you using? Latest Chrome works for me.
var a = [1, 2,3]
var obj = {'a': a}
obj.a
> [1, 2, 3]
localStorage.setItem('obj', JSON.stringify(obj))
var obj2 = JSON.parse(localStorage.getItem('obj'))
obj2.a
> [1, 2, 3]


text:
Q: Alamofire download progress totalBytesExpectedToRead always -1 I'm using Alamofire and found that with the download task and progress I get the correct bytes that it read and the total bytes currently read, but the totalBytesExpectedToRead always -1. Even in the test files the assertion says that this value should be always -1, why?
The download completes with no problem, but I want to show a progress bar while downloading PDF's.
Is it possible that this part of the library is not done yet?
Thank you in advance!

A: totalBytesExpectedToRead provides you the Content-Length that is received from server side.
When server does not providing "Content-Length" value in response header then it would be -1 always.
First confirm to webservices and from Web Developers team that they should provide you "Content-Length".
Actually, totalBytesExpectedToRead is give you the value from property of NSURLResponse  of "expectedContentLength"


text:
Q: Why the shape of box-shadow become a round rectangle Recently, probably because of the chrome browser update, the previous normal ripple animation effect has become abnormal, when the box-shadow spread is greater than 1em, it is no longer round, and I do not see where there is relevant documentation.
Request for some instructions or patch.
Html Code:

CSS Code:
.screen {
  width: 320px;
  height: 550px;
  position: relative;
  background-color: #242739;
  margin: 0px auto;
  box-shadow: 0px 4px 24px rgba(0, 0, 0, 0.4);
}

.sense-aroma {
  background-color: rgba(228, 36, 195, 0.6);
  box-shadow: 0px 0px 21px 0px #E424C3;
  width: 1em;
  height: 1em;
  border-radius: 50%;
  animation: ripple 1s linear infinite;
  position: absolute;
  top: 50%;
  margin: 0px auto;
  left: 0;
  right: 0;
}

@keyframes ripple {
  0% {
    box-shadow: 0 0 0 0 rgba(228, 36, 195, 0.2), 0 0 0 1em rgba(228, 36, 195, 0.2), 0 0 0 4em rgba(228, 36, 195, 0.2), 0 0 0 6em rgba(228, 36, 195, 0.2);
  }
  100% {
    box-shadow: 0 0 0 1em rgba(228, 36, 195, 0.2), 0 0 0 4em rgba(228, 36, 195, 0.2), 0 0 0 6em rgba(228, 36, 195, 0.2), 0 0 0 9em rgba(228, 36, 195, 0);
  }
}

https://codepen.io/srikantshetty/pen/bpWVYV


text:
Q: properly evaluating `rlang` expression inside list column This is a follow-up question to (using `rlang` for conditional labelling in `ggplot` using `ggrepel`), which solved the problem I was facing in a custom function using an expression to filter out data while labeling data points. But the answer raised another issue that I don't know how to solve.
Here is the custom function that uses rlang to evaluate the user-entered expression to filter out data while attaching labels to data points. And this function works fine when not used inside list columns. For example-
# loading needed libraries
library(tidyverse)
library(ggplot2)
library(ggrepel)

# custom function
label_adder <- function(data, x, y, label.var, exp = NULL) {
  param_list <- as.list(match.call())

  if ("exp" %in% names(param_list)) {
    my_exp <- rlang::enquo(exp)
  }
  else {
    a <- "dplyr::row_number(x = .) > 0"
    my_exp <- rlang::quo(!!rlang::sym(a))
  }

  plot <-
    ggplot(mapping = aes(
      x = !!rlang::enquo(x),
      y = !!rlang::enquo(y)
    )) +
    geom_point(data = data) +
    geom_smooth(data = data, method = "lm") +
    geom_label_repel(
      data = data %>% filter(!!my_exp),
      mapping = aes(label = !!rlang::enquo(label.var))
    )
  return(plot)
}

# using the function
label_adder(
  data = datasets::iris,
  x = Sepal.Length,
  y = Sepal.Width,
  label.var = Species,
  exp = Sepal.Length > 7
)

But when I use the same function with purrr::map, it fails.
# creating a list column
df.listcol <- datasets::iris %>%
  dplyr::mutate(.data = ., Species2 = Species) %>% # just creates a copy of this variable
  dplyr::group_by(.data = ., Species) %>%
  tidyr::nest(data = .)

# running function on dataframe with list columns
df.listcol %>% # creates a nested dataframe with list column called `data`
  dplyr::mutate( # creating a new list column of ggstatsplot outputs
    .data = .,
    plot = data %>%
      purrr::map(
        .x = .,
        .f = ~label_adder(
          data = .,
          x = Sepal.Length,
          y = Sepal.Width
        )
      )
  )
#> Error in mutate_impl(.data, dots): Evaluation error: Evaluation error: object 'dplyr::row_number(x = .) > 0' not found..

But if I use the function by specifying label.var and exp, it works just fine.
# running function on dataframe with list columns
df.listcol %>% # creates a nested dataframe with list column called `data`
  dplyr::mutate( # creating a new list column of ggstatsplot outputs
    .data = .,
    plot = data %>%
      purrr::map(
        .x = .,
        .f = ~label_adder(
          data = .,
          x = Sepal.Length,
          y = Sepal.Width,
          label.var = Species,
          exp = Sepal.Length > 7
        )
      )
  )
#> # A tibble: 3 x 3
#>   Species    data              plot
#>   <fct>      <list>            <list>
#> 1 setosa     <tibble [50 x 5]> <S3: gg>
#> 2 versicolor <tibble [50 x 5]> <S3: gg>
#> 3 virginica  <tibble [50 x 5]> <S3: gg>

So my question is why the function fails when label.var and exp are not specified and how to resolve this issue?
Created on 2018-08-31 by the reprex package (v0.2.0.9000).

A: So here we edit the function to make the filtering more flexible.
# loading needed libraries
library(tidyverse)
library(ggplot2)
library(ggrepel)

# custom function
label_adder <- function(data, x, y, label.var, exp = NULL) {
  param_list <- as.list(match.call())
  label_data <- data %>% {if ("exp" %in% names(param_list)) filter(., !!enquo(exp)) else .}

  plot <-
    ggplot(mapping = aes(
      x = !!rlang::enquo(x),
      y = !!rlang::enquo(y)
    )) +
    geom_point(data = data) +
    geom_smooth(data = data, method = "lm") +
    geom_label_repel(
      data = label_data,
      mapping = aes(label = !!rlang::enquo(label.var))
    )
  return(plot)
}

df.listcol <- datasets::iris %>%
  dplyr::mutate(.data = ., Species2 = Species) %>% # just creates a copy of this variable
  dplyr::group_by(.data = ., Species) %>%
  tidyr::nest(data = .)

test <- df.listcol %>% mutate(plot = map(data, ~label_adder(., x = Sepal.Length, label.var = Species2, y = Sepal.Width)))
test
#> # A tibble: 3 x 3
#>   Species    data              plot
#>   <fct>      <list>            <list>
#> 1 setosa     <tibble [50 × 5]> <S3: gg>
#> 2 versicolor <tibble [50 × 5]> <S3: gg>
#> 3 virginica  <tibble [50 × 5]> <S3: gg>
test$plot[[2]]

test2 <- df.listcol %>% mutate(plot = map(data, ~label_adder(., x = Sepal.Length, label.var = Species2, y = Sepal.Width, exp = Sepal.Length > 6.5)))
test2
#> # A tibble: 3 x 3
#>   Species    data              plot
#>   <fct>      <list>            <list>
#> 1 setosa     <tibble [50 × 5]> <S3: gg>
#> 2 versicolor <tibble [50 × 5]> <S3: gg>
#> 3 virginica  <tibble [50 × 5]> <S3: gg>
test2$plot[[2]]

Created on 2018-08-31 by the reprex
package (v0.2.0).


text:
Q: Understanding an exception message I have a dataframe All_companies and I am comparing the COMPANY_NUMBER in column 1 with the next element in the same column
COMPANY_NUMBER      COMPANY_NAME
444444               ABC
444444               ABC
555555               XYZ
555555               XYZ

The code
for (i in 1:(nrow(All_companies)-1)) {
  if(All_companies[i, 1] == All_companies[i + 1, 1])
  {
    print("Match")
  }
  else if (All_companies[i, 1] != All_companies[i + 1, 1])
  {
    print("No Match")
  }
}

The code runs fine but I get an error after the code finishes running-

Error in if (All_companies[i, 1] == All_companies[i + 1, 1]) { :
missing value where TRUE/FALSE needed

Any thoughts on how I can deal with this?
Many thanks in advance.

A: Sorry, I don't understand this syntax but shouldn't the main loop be for (i in 1:(nrow(All_companies)-2)) {?

A: If the comparison inside if statement is NA, then it exits with error:
if (NA) {
    print("Match")
}
#> Error in if (NA) print("Match") : missing value where TRUE/FALSE needed

So, you probably have some NA's in your All_companies dataset, because comparison of anything with NA is NA.
With NA it throws an error:
All_companies <- read.table(header = T, text = "
COMPANY_NUMBER      COMPANY_NAME
444444               ABC
444444               ABC
555555               XYZ
555555               XYZ
NA                   ABC
")

for (i in 1:(nrow(All_companies)-1)) {
  if (All_companies[i, 1] == All_companies[i + 1, 1])
  {
    print("Match")
  }
  else if (All_companies[i, 1] != All_companies[i + 1, 1])
  {
    print("No Match")
  }
}
#> [1] "Match"
#> [1] "No Match"
#> [1] "Match"
#> Error in if (All_companies[i, 1] == All_companies[i + 1, 1]) {: missing value where TRUE/FALSE needed

Without NA it runs:
All_companies <- read.table(header = T, text = "
COMPANY_NUMBER      COMPANY_NAME
444444               ABC
444444               ABC
555555               XYZ
555555               XYZ
")

for (i in 1:(nrow(All_companies)-1)) {
  if (All_companies[i, 1] == All_companies[i + 1, 1])
  {
    print("Match")
  }
  else if (All_companies[i, 1] != All_companies[i + 1, 1])
  {
    print("No Match")
  }
}
#> [1] "Match"
#> [1] "No Match"
#> [1] "Match"

Created on 2020-08-13 by the reprex package (v0.3.0)

A: Yes there were missing values indeed. However, even with the missing value when I added isTRUE to the code it ran without error message.
if(isTRUE(All_companies[i, 1] == All_companies[i + 1, 1]))


text:
Q: How to check the opcode of an instruction? In fact I have found two solutions, and I want to know if there is any difference:

*

*using isa, like isa<LoadInst>(i)

*using getopcode (i.getopcode() method and comparing to Load)

Which one should I use to check the opcode of an instruction?

A: isa is used to check for an existing derived instruction class.  class i.getopcode() could help you to get all of the operations' information.
According to the Inheritance diagram for llvm::Instruction,LLVM internally will divide all instructions into several different classes like llvm::BinaryOperator, llvm::CallInst, llvm::CmpInst, etc. But there is no exact operation information for these classes.
However, for Instruction::getOpcode(), it will directly get the operation from the llvm::Instruction object. You could refer to Instruction.def  for an idea about definition of each instruction. Basically, the opcode will be the exact operations the instruction intends to do.
Say, for an LLVM IR add, you can use isa<llvm::BinaryOperator> to know that this is a BinaryOperator. But this is only for what the instruction class it is. If you want to know whether it is an ADD or a SUB. i.getopcode() should be used here.


text:
Q: xampp's apache is not starting I have installed xampp in windows 8.1 . But while i start its control pannel it says,"api-ms-win-crt-runtime-l1-1-0.dll missing" . I tried installing
    vc_redist.x64.exe

but its not installing properly.
It display follwing log file:
            [0C14:06D4][2017-07-15T18:06:17]i001: Burn v3.7.3813.0, Windows v6.3 (Build 9600: Service Pack 0), path: C:\Users\Suzan\Downloads\Programs\vc_redist.x64.exe, cmdline: ''
            [0C14:06D4][2017-07-15T18:06:18]i000: Setting string variable 'WixBundleLog' to value 'C:\Users\Suzan\AppData\Local\Temp\dd_vcredist_amd64_20170715180618.log'
            [0C14:06D4][2017-07-15T18:06:18]i000: Setting string variable 'WixBundleOriginalSource' to value 'C:\Users\Suzan\Downloads\Programs\vc_redist.x64.exe'
            [0C14:06D4][2017-07-15T18:06:18]i000: Setting string variable 'WixBundleOriginalSourceFolder' to value 'C:\Users\Suzan\Downloads\Programs\'
            [0C14:06D4][2017-07-15T18:06:18]i100: Detect begin, 10 packages
            [0C14:06D4][2017-07-15T18:06:18]i000: File search: windows_uCRT_DetectKey, did not find path: C:\Windows\system32\ucrtbase.dll
            [0C14:06D4][2017-07-15T18:06:18]i000: File search: windows_uCRT_DetectKeyExists, did not find path: C:\Windows\system32\ucrtbase.dll
            [0C14:06D4][2017-07-15T18:06:18]i000: Setting numeric variable 'windows_uCRT_DetectKeyExists' to value 0
            [0C14:06D4][2017-07-15T18:06:18]i052: Condition '(VersionNT = v6.3 AND NOT VersionNT64) AND (windows_uCRT_DetectKeyExists AND windows_uCRT_DetectKey >= v10.0.10240.0)' evaluates to false.
            [0C14:06D4][2017-07-15T18:06:18]i052: Condition '(VersionNT = v6.3 AND VersionNT64) AND (windows_uCRT_DetectKeyExists AND windows_uCRT_DetectKey >= v10.0.10240.0)' evaluates to false.
            [0C14:06D4][2017-07-15T18:06:18]i052: Condition '(VersionNT = v6.2 AND NOT VersionNT64) AND (windows_uCRT_DetectKeyExists AND windows_uCRT_DetectKey >= v10.0.10240.0)' evaluates to false.
            [0C14:06D4][2017-07-15T18:06:18]i052: Condition '(VersionNT = v6.2 AND VersionNT64) AND (windows_uCRT_DetectKeyExists AND windows_uCRT_DetectKey >= v10.0.10240.0)' evaluates to false.
            [0C14:06D4][2017-07-15T18:06:18]i052: Condition '(VersionNT = v6.1 AND NOT VersionNT64) AND (windows_uCRT_DetectKeyExists AND windows_uCRT_DetectKey >= v10.0.10240.0)' evaluates to false.
            [0C14:06D4][2017-07-15T18:06:18]i052: Condition '(VersionNT = v6.1 AND VersionNT64) AND (windows_uCRT_DetectKeyExists AND windows_uCRT_DetectKey >= v10.0.10240.0)' evaluates to false.
            [0C14:06D4][2017-07-15T18:06:18]i052: Condition '(VersionNT = v6.0 AND NOT VersionNT64) AND (windows_uCRT_DetectKeyExists AND windows_uCRT_DetectKey >= v10.0.10240.0)' evaluates to false.
            [0C14:06D4][2017-07-15T18:06:18]i052: Condition '(VersionNT = v6.0 AND VersionNT64) AND (windows_uCRT_DetectKeyExists AND windows_uCRT_DetectKey >= v10.0.10240.0)' evaluates to false.
            [0C14:06D4][2017-07-15T18:06:18]i101: Detected package: vcRuntimeMinimum_x64, state: Present, cached: Complete
            [0C14:06D4][2017-07-15T18:06:18]i101: Detected package: vcRuntimeAdditional_x64, state: Present, cached: Complete
            [0C14:06D4][2017-07-15T18:06:18]i101: Detected package: Windows81_x86, state: Absent, cached: None
            [0C14:06D4][2017-07-15T18:06:18]i101: Detected package: Windows81_x64, state: Absent, cached: Complete
            [0C14:06D4][2017-07-15T18:06:18]i101: Detected package: Windows8_x86, state: Absent, cached: None
            [0C14:06D4][2017-07-15T18:06:18]i101: Detected package: Windows8_x64, state: Absent, cached: None
            [0C14:06D4][2017-07-15T18:06:18]i101: Detected package: Windows7_MSU_x86, state: Absent, cached: None
            [0C14:06D4][2017-07-15T18:06:18]i101: Detected package: Windows7_MSU_x64, state: Absent, cached: None
            [0C14:06D4][2017-07-15T18:06:18]i101: Detected package: WindowsVista_MSU_x86, state: Absent, cached: None
            [0C14:06D4][2017-07-15T18:06:18]i101: Detected package: WindowsVista_MSU_x64, state: Absent, cached: None
            [0C14:06D4][2017-07-15T18:06:18]i052: Condition 'VersionNT64 >= v6.0 OR (VersionNT64 = v5.2 AND ServicePackLevel >= 1)' evaluates to true.
            [0C14:06D4][2017-07-15T18:06:18]i199: Detect complete, result: 0x0
            [0C14:06D4][2017-07-15T18:06:20]i200: Plan begin, 10 packages, action: Repair
            [0C14:06D4][2017-07-15T18:06:20]i052: Condition '(VersionNT64)' evaluates to true.
            [0C14:06D4][2017-07-15T18:06:20]i000: Setting string variable 'WixBundleLog_vcRuntimeMinimum_x64' to value 'C:\Users\Suzan\AppData\Local\Temp\dd_vcredist_amd64_20170715180618_000_vcRuntimeMinimum_x64.log'
            [0C14:06D4][2017-07-15T18:06:20]i052: Condition '(VersionNT64)' evaluates to true.
            [0C14:06D4][2017-07-15T18:06:20]i000: Setting string variable 'WixBundleLog_vcRuntimeAdditional_x64' to value 'C:\Users\Suzan\AppData\Local\Temp\dd_vcredist_amd64_20170715180618_001_vcRuntimeAdditional_x64.log'
            [0C14:06D4][2017-07-15T18:06:20]i052: Condition 'VersionNT = v6.3 AND NOT VersionNT64' evaluates to false.
            [0C14:06D4][2017-07-15T18:06:20]w321: Skipping dependency registration on package with no dependency providers: Windows81_x86
            [0C14:06D4][2017-07-15T18:06:20]i052: Condition 'VersionNT = v6.3 AND VersionNT64' evaluates to true.
            [0C14:06D4][2017-07-15T18:06:20]w321: Skipping dependency registration on package with no dependency providers: Windows81_x64
            [0C14:06D4][2017-07-15T18:06:20]i052: Condition 'VersionNT = v6.2 AND NOT VersionNT64' evaluates to false.
            [0C14:06D4][2017-07-15T18:06:20]w321: Skipping dependency registration on package with no dependency providers: Windows8_x86
            [0C14:06D4][2017-07-15T18:06:20]i052: Condition 'VersionNT = v6.2 AND VersionNT64' evaluates to false.
            [0C14:06D4][2017-07-15T18:06:20]w321: Skipping dependency registration on package with no dependency providers: Windows8_x64
            [0C14:06D4][2017-07-15T18:06:20]i052: Condition 'VersionNT = v6.1 AND NOT VersionNT64' evaluates to false.
            [0C14:06D4][2017-07-15T18:06:20]w321: Skipping dependency registration on package with no dependency providers: Windows7_MSU_x86
            [0C14:06D4][2017-07-15T18:06:20]i052: Condition 'VersionNT = v6.1 AND VersionNT64' evaluates to false.
            [0C14:06D4][2017-07-15T18:06:20]w321: Skipping dependency registration on package with no dependency providers: Windows7_MSU_x64
            [0C14:06D4][2017-07-15T18:06:20]i052: Condition 'VersionNT = v6.0 AND NOT VersionNT64' evaluates to false.
            [0C14:06D4][2017-07-15T18:06:20]w321: Skipping dependency registration on package with no dependency providers: WindowsVista_MSU_x86
            [0C14:06D4][2017-07-15T18:06:20]i052: Condition 'VersionNT = v6.0 AND VersionNT64' evaluates to false.
            [0C14:06D4][2017-07-15T18:06:20]w321: Skipping dependency registration on package with no dependency providers: WindowsVista_MSU_x64
            [0C14:06D4][2017-07-15T18:06:20]i201: Planned package: vcRuntimeMinimum_x64, state: Present, default requested: Repair, ba requested: Repair, execute: Repair, rollback: None, cache: No, uncache: No, dependency: Register
            [0C14:06D4][2017-07-15T18:06:20]i201: Planned package: vcRuntimeAdditional_x64, state: Present, default requested: Repair, ba requested: Repair, execute: Repair, rollback: None, cache: No, uncache: No, dependency: Register
            [0C14:06D4][2017-07-15T18:06:20]i201: Planned package: Windows81_x86, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None
            [0C14:06D4][2017-07-15T18:06:20]i201: Planned package: Windows81_x64, state: Absent, default requested: Repair, ba requested: Repair, execute: Install, rollback: Uninstall, cache: No, uncache: No, dependency: None
            [0C14:06D4][2017-07-15T18:06:20]i201: Planned package: Windows8_x86, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None
            [0C14:06D4][2017-07-15T18:06:20]i201: Planned package: Windows8_x64, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None
            [0C14:06D4][2017-07-15T18:06:20]i201: Planned package: Windows7_MSU_x86, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None
            [0C14:06D4][2017-07-15T18:06:20]i201: Planned package: Windows7_MSU_x64, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None
            [0C14:06D4][2017-07-15T18:06:20]i201: Planned package: WindowsVista_MSU_x86, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None
            [0C14:06D4][2017-07-15T18:06:20]i201: Planned package: WindowsVista_MSU_x64, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None
            [0C14:06D4][2017-07-15T18:06:20]i299: Plan complete, result: 0x0
            [0C14:06D4][2017-07-15T18:06:20]i300: Apply begin
            [0964:0C48][2017-07-15T18:06:22]i360: Creating a system restore point.
            [0964:0C48][2017-07-15T18:06:22]i361: Created a system restore point.
            [0964:0C48][2017-07-15T18:06:22]i371: Updating session, registration key: SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{e9d78d68-c26c-4da7-9158-99355d8ef3ad}, resume: Active, restart initiated: No, disable resume: No
            [0964:0C7C][2017-07-15T18:06:22]i304: Verified existing payload: vcRuntimeMinimum_x64 at path: C:\ProgramData\Package Cache\{8D4F7A6D-6B81-3DC8-9C21-6008E4866727}v14.10.25017\packages\vcRuntimeMinimum_amd64\vc_runtimeMinimum_x64.msi.
            [0964:0C7C][2017-07-15T18:06:22]i304: Verified existing payload: cab5046A8AB272BF37297BB7928664C9503 at path: C:\ProgramData\Package Cache\{8D4F7A6D-6B81-3DC8-9C21-6008E4866727}v14.10.25017\packages\vcRuntimeMinimum_amd64\cab1.cab.
            [0964:0C7C][2017-07-15T18:06:22]i304: Verified existing payload: vcRuntimeAdditional_x64 at path: C:\ProgramData\Package Cache\{E512788E-C50B-3858-A4B9-73AD5F3F9E93}v14.10.25017\packages\vcRuntimeAdditional_amd64\vc_runtimeAdditional_x64.msi.
            [0964:0C7C][2017-07-15T18:06:22]i304: Verified existing payload: cab2C04DDC374BD96EB5C8EB8208F2C7C92 at path: C:\ProgramData\Package Cache\{E512788E-C50B-3858-A4B9-73AD5F3F9E93}v14.10.25017\packages\vcRuntimeAdditional_amd64\cab1.cab.
            [0964:0C7C][2017-07-15T18:06:23]i304: Verified existing payload: Windows81_x64 at path: C:\ProgramData\Package Cache\3ACBF3890FC9C8A6F3D2155ECF106028E5F55164\packages\Patch\x64\Windows8.1-KB2999226-x64.msu.
            [0964:0C48][2017-07-15T18:06:23]i301: Applying execute package: vcRuntimeMinimum_x64, action: Repair, path: C:\ProgramData\Package Cache\{8D4F7A6D-6B81-3DC8-9C21-6008E4866727}v14.10.25017\packages\vcRuntimeMinimum_amd64\vc_runtimeMinimum_x64.msi, arguments: ' MSIFASTINSTALL="7" NOVSUI="1"'
            [0C14:06D4][2017-07-15T18:06:23]i319: Applied execute package: vcRuntimeMinimum_x64, result: 0x0, restart: None
            [0964:0C48][2017-07-15T18:06:23]i325: Registering dependency: {e9d78d68-c26c-4da7-9158-99355d8ef3ad} on package provider: Microsoft.VS.VC_RuntimeMinimumVSU_amd64,v14, package: vcRuntimeMinimum_x64
            [0964:0C48][2017-07-15T18:06:23]i301: Applying execute package: vcRuntimeAdditional_x64, action: Repair, path: C:\ProgramData\Package Cache\{E512788E-C50B-3858-A4B9-73AD5F3F9E93}v14.10.25017\packages\vcRuntimeAdditional_amd64\vc_runtimeAdditional_x64.msi, arguments: ' MSIFASTINSTALL="7" NOVSUI="1"'
            [0C14:06D4][2017-07-15T18:06:24]i319: Applied execute package: vcRuntimeAdditional_x64, result: 0x0, restart: None
            [0964:0C48][2017-07-15T18:06:24]i325: Registering dependency: {e9d78d68-c26c-4da7-9158-99355d8ef3ad} on package provider: Microsoft.VS.VC_RuntimeAdditionalVSU_amd64,v14, package: vcRuntimeAdditional_x64
            [0964:0C48][2017-07-15T18:06:24]i301: Applying execute package: Windows81_x64, action: Install, path: C:\ProgramData\Package Cache\3ACBF3890FC9C8A6F3D2155ECF106028E5F55164\packages\Patch\x64\Windows8.1-KB2999226-x64.msu, arguments: '"C:\Windows\SysNative\wusa.exe" "C:\ProgramData\Package Cache\3ACBF3890FC9C8A6F3D2155ECF106028E5F55164\packages\Patch\x64\Windows8.1-KB2999226-x64.msu" /quiet /norestart'
            [0964:0C48][2017-07-15T18:06:26]e000: Error 0x80240017: Failed to execute MSU package.
            [0C14:06D4][2017-07-15T18:06:26]e000: Error 0x80240017: Failed to configure per-machine MSU package.
            [0C14:06D4][2017-07-15T18:06:26]i319: Applied execute package: Windows81_x64, result: 0x80240017, restart: None
            [0C14:06D4][2017-07-15T18:06:26]e000: Error 0x80240017: Failed to execute MSU package.
            [0964:0C48][2017-07-15T18:06:26]i372: Session end, registration key: SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{e9d78d68-c26c-4da7-9158-99355d8ef3ad}, resume: ARP, restart: None, disable resume: No
            [0964:0C48][2017-07-15T18:06:26]i371: Updating session, registration key: SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{e9d78d68-c26c-4da7-9158-99355d8ef3ad}, resume: ARP, restart initiated: No, disable resume: No
            [0C14:06D4][2017-07-15T18:06:26]i399: Apply complete, result: 0x80240017, restart: None, ba requested restart:  No

I also tried installing all the updates in windows. How can i solve this issue? Thanks :)

A: There seems to be two strategies for solving this problem:

*

*Apparently, the missing "api-ms-win-crt-runtime-l1-1-0.dll"  is generally installed with a Windows update, especially for pre-Windows 10 machines. According to the internet, to resolve this issue, you may wish to download and install the Update for Universal C Runtime in Windows from Microsoft (assuming Windows isn't doing what it needs to).

*If you are relatively sure you have this update, are hesitant to do this or are still having issues, you may need to pick up the latest Visual C++ redistributables and manually update them yourself. This may particularly apply in your case since the process your attempting seems to be uncooperative.
Here are the direct links for VS 2017 64 bit and 32 bit versions.
Here is a direct link for the latest VS 2015 Update 3 redistributables including 64-bit and 32-bit versions.
Regarding the redistributables, the error your receiving can be caused by both VS 2015 and VS 2017, so you may want to install the redistributables for both.
Also, though I would be a bit careful with this, if you are given the option to uninstall the redistributables when running the installer (so you can reinstall them afterwards), this is typically better than "Repairing" them.


text:
Q: Is MASE / Mean Absolute Scaled Error and the usually described denominator appropriate in this case? I have read through:
http://robjhyndman.com/hyndsight/smape/ and https://www.otexts.org/fpp/2/5
and a lot of
Hyndman, R. J. and Koehler, A. B. (2006) 'Another look at measures of forecast accuracy', International journal of forecasting, 22(4), pp. 679–688.
Having read  those, I understand the reasons MASE exists. I also believe I understand how it works in the examples given, but the examples tend to be for similar problems in which the training data and test data are consecutive. In my case I have a year of training data, and I want to test a model based on the data using a different year which does not directly follow.
As I am not attempting to forecast one step ahead, it does not seem appropriate to me to use $Y_t = Y_{t-1}$ as the naive method.

*

*Am I correct in thinking it is inappropriate?

*If so, what would be appropriate?

*One thought was that the denominator be the value recorded at that point in the training year: would that be more appropriate, or appropriate at all?


text:
Q: Query nested objects from MongoDB I created a script in SSIS to retrieve data from MongoDB.  While I don't have any issues querying regular documents, I am not sure how to retrieve values from nested documents.  For example, "Address" expanded contains "Country", "State", "City", "Street", and "Zip".  I am interested in retrieving the "Country" (field) values only.  In theory, I understand that it should be something like "Address.Country", but I do not know how to implement it in my code.  What is the best way to achieve that?
This is the code that retrieves all the other documents:
    public override void CreateNewOutputRows()
    {
        string connectionString = "mongodb://localhost";
        MongoServer myMongo = MongoServer.Create(connectionString);
        myMongo.Connect();
        var db = myMongo.GetDatabase("UserDB");
        /*ICursor<BsonDocument> cursor = db.GetCollection<BsonDocument>("UserDB").FindAll();*/
        foreach (BsonDocument document in db.GetCollection<BsonDocument>("UserDB").FindAll())
        {
            this.UserDBBuffer.AddRow();
            this.UserDBBuffer.ID = document["_id"] == null ? "" : document["_id"].ToString();

            this.UserDBBuffer.PrimaryEmail = document["primary_email"] == null ? "" : document["primary_email"].ToString();
            this.UserDBBuffer.Gender = document["gender"] == null ? "" : document["gender"].ToString();

        }
}

A: You can do that in C# using SetFields on the cursor returned by FindAll:
var fields = Fields.Include("Address.Country");
foreach (var document in collection.FindAll().SetFields(fields))
{
    Console.WriteLine(document.ToJson());
}

You can extract the Country value from the returned document using:
var country = document["Address"].AsBsonDocument["Country"].AsString;

A: db.users.find({_id: user_id},
              {'address.country': 1});

This will get you a document like
{"_id": ObjectId('4efb78234ee9184d8b5a4e92'),
 "address": {"country": "Russia"}}


text:
Q: UnicodeDecodeError: 'ascii' codec can't decode byte 0xb9 in position 23: ordinal not in range(128) I used Prepare Network but failed. The system is Windows 11, x64. I use ArcGIS 10.6, sDNA 4.0.3.
The error is:

Executing: sDNAPrepare D:\personal\aaa.mdb\roadroad
C:\Users\69580\Documents\ArcGIS\Default.gdb\roadroad_sDNAPrepare # #
REPAIR true false true true false # # # # # # Start Time: Fri Jan 27
17:27:53 2023 Running script sDNAPrepare...
Traceback (most recent call last):   File "", line 128, in
execute UnicodeDecodeError: 'ascii' codec can't decode byte 0xb9 in
position 23: ordinal not in range(128)
Failed to execute (sDNAPrepare). Failed at Fri Jan 27 17:27:55 2023
(Elapsed Time: 1.48 seconds)

A: Sorry, this is a bug in sDNA: we don't support non-ascii characters in the input data yet. Or in filenames. It's on the todo list.


text:
Q: Unexpected end of query at HTML start? I am performing a query that works without HTML, but when I add HTML, to better organize the results.  When I add in <div> and </div> tags, I get an error (see below).  Here's the query:
let $doc := doc('test')
for $v in $doc//item
where $v/product_info/unit[.='9291']
return
  <div>{ $v/seller_info/seller_company_id[position() lt 2]/text() }
  </div>
  <div>{ $v/seller_info/seller_rating[position() lt 3]/text()
  </div>

On this document:
<item>
<item_number>1171270</item_number>
<seller_info>
<seller_company_id>6356</seller_company_id>
<seller_rating>C31</seller_rating>
<seller_rating>T150 hr.</seller_rating>
</seller_info>
<product_info>
<unit>2022</unit>
<sinfo>55 cases</sinfo>
<sinfo>Yu-gi-oh trading card pack</sinfo>
<sinfo>.45kg per unit</sinfo>
<sinfo>24.7500kg shipment</sinfo>
</product_info>
<product_info>
<unit>9291</unit>
<sinfo>7 units</sinfo>
<sinfo>Naruto, Classic, action figure</sinfo>
<sinfo>1.8kg per unit</sinfo>
<sinfo>12.6kg shipment</sinfo>
</product_info>
</item>

And the error I'm getting:

Stopped at line 4, column 85: [XPST0003] Unexpected end of query: '>{ $v/seller_in...'

A: When you want to return multiple elements, you will have to wrap them in a sequence. Additionally, you forgot the closing } in the second <div/>.
let $doc := doc('test')
for $v in $doc//item
where $v/product_info/unit[.='9291']
return
(
  <div>{ $v/seller_info/seller_company_id[position() lt 2]/text() }
  </div>,
  <div>{ $v/seller_info/seller_rating[position() lt 3]/text() }
  </div>
)


text:
Q: Troca de linha na matriz Olá.
Estava programando em python e queria fazer a troca de linha(entre a segunda e terceira linha) de uma matriz utilizando o seguinte código. Porém eu queria saber porquer a variável auxLinha muda de valor quando modifico b[inicio]
def trocaLinhaB(b,inicio,final):
    listaAux = b[inicio]
    b[inicio] = b[final]
    b[final] = listaAux

A matriz original
0 2 3
0 -3 1
2 1 5

Porém o resultado foi
[[ 0.  2.  3.]
 [ 0. -3.  1.]
 [ 0. -3.  1.]]

e eu esperava o
[[ 0.  2.  3.]
 [ 2.  1.  5.]
 [ 0. -3.  1.]]

A: Acredito que você esteja utilizando a biblioteca numpy, portanto, a variável listaAux armazena apenas uma visualização da matriz e não os dados (e por isso, ela "muda" de valor).
Quando você altera a matriz, altera também a visualização.
Uma solução possível para este problema é armazenar uma cópia dos dados na variável listaAux antes de fazer a substituição.
O código da função fica da seguinte forma:
def trocaLinhaB(b,inicio,final):
    listaAux = b[inicio].copy()  # <= aqui: cria uma cópia
    b[inicio] = b[final]
    b[final] = listaAux


text:
Q: PHP Arrays with Datatables I have been playing around with datatables and now have a requirement to filter a table via select/dropdown which should filter one of my columns. My code is:
<?php
$urlPriority = $_GET['priority'];
if (empty($urlPriority)) {
  $urlPriority = 'High';
}
$priorityStatus = array('Low'=>'Low Priority', 'Medium'=>'Medium Priority', 'High'=>'High Priority');

echo createSelectControl('Priority', $priorityStatus, $urlPriority, -1, false, 'reload();')
?>

<script type="text/javascript">
function reload() {
  var priority = $("#Priority").val();
  location.search = '?priority=' + priority;

}
</script>

I added the line of code to my sql query:
$sql = "SELECT * from [table_name]
WHERE ... AND
Priority = '" . mssql_escape($urlPriority) . "' AND
etc AND
etc ";

This works great when selecting one of the options.
All I need now is for the user to be able to select all options, including Low, Medium and High, I have tried all methods i can think of but it just returns an empty table?
Thanks for any suggestions.

A: Use this,
if($urlPriority!="")
{
    //query with priority filter
}
else
{
    //query without priority filter
}

if user select priority value assign it to $urlPriority, else make it empty. then it will retrieve every result

A: Found a solution which does exactly what i needed, thought i'd share the JSFiddle
   initComplete: function() {
  var column = this.api().column(2);

  var select = $('<select class="filter"><option value=""></option></select>')
    .appendTo('#selectTriggerFilter')
    .on('change', function() {
      var val = $(this).val();
      //column.search(val ? '^' + $(this).val() + '$' : val, true, false).draw();
      column.search(val).draw()
    });

   var offices = [];
   column.data().toArray().forEach(function(s) {
        s = s.split(',');
      s.forEach(function(d) {
        if (!~offices.indexOf(d)) {
            offices.push(d)
          select.append('<option value="' + d + '">' + d + '</option>');                         }
      })
   })
}

http://jsfiddle.net/m1Ly9uxf/15/


text:
Q: Given number of array "distribute/scale" to specific value I am working on a project in which I need to distribute the values of an array and the sum of these values must be 100.
Examples:

*

*[70, 34, 92] and the total value 100. The output is [35.71, 17.35, 46.94] because 35.71 + 17.35 + 46.94 = 100.

*[86, 99.5, 100] and the total value 100. The output is [30.12, 34.85, 35.03].

*[96, 37] and the total value 100. The output is [72.18, 27.82].

*[98, 76.5, 68.5, 63.5, 38.5] and the total value 100. The output is [28.41, 22.17, 19.86, 18.41, 11.15] = 100(sum).

My solution so far:

*

*Sum all the values in the given array

*Multiply each value by 100

*Divide each value by the total sum

*use .toFixed(2).

The "formula/calculation": +(((valueOfArray * 100) / totalSumOfGivenArray).toFixed(2))
My first solution(problems with decimals so not acceptable):
prioritySum  = 0;
controlsKey.forEach((value) => {
      priorityVal = this.getDistributedValue(+form.controls[formId].value, totalCatSum); // return +(((valueOfArray * 100) / totalSumOfGivenArray).toFixed(2))
      prioritySum = prioritySum + priorityVal;
});

This solution sometimes doesn't return exactly the 100 value. Output various such as 99.99, 99.999999, 100(mostly), 100.0000000001, 99.999978, 100.09999999, 99.000009. There are some issues with decimal numbers here.
The other approach I used is this:
let i = 0;
for(i = 0;  i < controlsKey.length-1; i++){
  let formId = controlsKey[i];
  relValue = this.getDistributedValue(+form.controls[formId].value, totalActualSum); // returns formula result
  form.controls[formId].setValue(relValue))
  relativeSum = relativeSum + relValue;
}
relValue = 100 - relativeSum;
form.controls[controlsKey[i]].setValue(relValue)

This works fine but this solution hmmm...
So my question is there any elegant solution to this problem?
The first solution is ok for me but there are some issues with decimals even I used .toFixed(2)

A: So the big issue is that there is an inherent inaccuracy with floating point numbers.  If you don't use toFixed the issue impossible to resolve - even if you determine the error, and pick an element and increase/decrease it by the amount of the error, you'll simply be off by that amount in the other direction, since a floating point number is not capable of holding the necessary amount of precision across all of the operations:

function getDistribution(values) {
    var sum =  values.reduce((carry, current) => carry + current, 0)
    var distribution = values.map(v => 100 * v / sum)
    var err = distribution.reduce((carry, current) => carry+current, 0) - 100;
    console.log({distribution, err});
    distribution[0] -= err;
    err = distribution.reduce((carry, current) => carry+current, 0) - 100;
    console.log({distribution, err});
}

getDistribution([98, 76.5, 68.5, 63.5, 38.5]);

A: To prevent unwanted floating point values, you could use integer values and subtract the value from a base value of 10000 (100 and two places) and create an array of strings where the dot is inserted into the value for getting formatted string.

const nice = s => s.toString().replace(/\d\d$/, '.$&');

function get100(array) {
    var sum = array.reduce((a, b) => a + b),
        offset = 1e4;
    return array.map((v, j, { length }) => {
        if (j + 1 === length) return nice(offset);
        var i = Math.round(v * 1e4 / sum);
        offset -= i;
        return nice(i);
    });
}

console.log(...get100([70, 34, 92])); // [35.71, 17.35, 46.94]
console.log(...get100([86, 99.5, 100])); // [30.12, 34.85, 35.03].
console.log(...get100([96, 37])); // [72.18, 27.82].
console.log(...get100([98, 76.5, 68.5, 63.5, 38.5])); // [28.41, 22.17, 19.86, 18.41, 11.15]


text:
Q: FeynArts package fails to load This is definitely a duplicate of FeynArts not working properly. However, that post dates back 5 years. I am currently on Mathematica 11.0.1.0 with Windows 10 as my OS. I have been trying to load the FeynArts package but to no avail.
I have followed the route of automatic installation prescribed in the FeynCalc wiki(includes an option to install patched version of FeynArts 3.9):
1. Import["https://raw.githubusercontent.com/FeynCalc/feyncalc/master/install.m"]
2. InstallFeynCalc[]

Despite an apparent clean installation, FeynArts doesn't seem to be loaded.
Loading code:
$LoadFeynArts = True;
<<FeynCalc`;

which returned the output:

FeynCalc is already loaded! To reload it, please restart the kernel.

Now, when I tried the simplest piece of code one can have via this package:
CreateTopologies[1,1->1]
Paint[%]

it just returns the input back!
How to get this package(FeynArts) working side by side with FeynCalc?

A: The problem is actually a very simple one: once FeynCalc has been loaded, you cannot reload it or load FeynArts, TARCER, PHI, FeynHelpers or any other add-on without restarting the kernel. So doing something like
<<FeynCalc`

...

$LoadFeynArts=True;
<<FeynCalc`

will not work. You need to either issue Quit[] or go to Evaluation -> Quit Kernel -> Local.
I thought that the error message ending with To reload it, please restart the kernel. seems to be pretty clear on on what one should do, but somehow there is still some confusion.

A: It worked after implementing a forced patch as mentioned in the wiki https://github.com/FeynCalc/feyncalc/wiki/FeynArts under Patching FeynArts for FeynCalc 9.x and above.


text:
Q: How to build tesseract4.0 from source code in windows using cmake? I already tried the pre-compiled Leptonica binary link but I read here that I have to build this from source only. So I tried building Leptonica from source.
I downloaded the source code of Leptonica from this [link].(https://github.com/tesseract-ocr/tesseract) Then I tried to build this code using CMake. To build I used CMake GUI. In source-code path I gave where CMakeLists.txt is located and in cross compiling option I gave this scripts\buildsystems\vcpkg.cmake from this link.
But I am getting this error
CMake Error at C:/vcpkg/scripts/buildsystems/vcpkg.cmake:247 (_find_package):
Could not find a package configuration file provided by "Leptonica" (requested version 1.74) with any of the following names:

    LeptonicaConfig.cmake
    leptonica-config.cmake

Add the installation prefix of "Leptonica" to CMAKE_PREFIX_PATH or set
"Leptonica_DIR" to a directory containing one of the above files.
If "Leptonica" provides a separate development package or SDK,
be sure it has been installed.

For this I build leptonica separately and generated this LeptonicaConfig.cmake file as asked in this error. But now I have to change the CMakeLists.txt and set Leptonica_DIR to the directory where my this LeptonicaConfig.cmake located. I don't know how to do this I tried adding  this line in cmakelists file set(Leptonica_DIR="C:\Leptonica"). But this doesn't work, may be this is wrong.
I am really stuck, I am using tesseract4.0 and Leptonica 17.6 and really new to this building process.


text:
Q: Beg to differ - Why is there a need to beg for differ Wouldn't 'Wish to differ' be better than 'Beg to differ'? A friend of mine asked me why I like to 'beg to differ', instead of 'wish to differ' or 'want to differ'.
Any insight on the history of 'Beg to differ'? I know that 'Beg to differ' looks more polite but another friend told me that it is over-polite, so would 'Wish to differ' be a better choice?

A: I agree with Barrie's response. I'd just add that it's my observation that this phrase is becoming archaic. I am nearly 50, and find that the 30 and under co-workers of mine never use such a phrase. Just as my teen brings home new idioms I never heard as a child, others that I considered common are falling into disuse.

A: One of the uses of beg is to provide 'a courteous or apologetic mode of asking what is expected, or even of taking as a matter of course'(OED). It is found in beg leave (seek permission) and beg pardon (ask for forgiveness). Beg to differ is frequently heard in discussions in which the parties hold opposing views. Whether you choose to use it or not depends on circumstances. I personally don't like it. It sounds stilted to my ears. One alternative is I'm afraid I don't agree with that (where I'm afraid, is, like beg, used to limit the potential for confrontation).

A: As a Brit I can see the confusion. A lot depends on intonation when uttering the sentence.  It is partly archaic and you would not use the expression often in colloquial circumstances - but it is a polite form, if you intonate correctly.
If you were to "announce" using the phrase, offering the air of being emphatic you could well sound pompous as if you were saying "I, sir, beg to differ" in 1805 while carrying a cane and wearing a top hat.  But if you say it quizzically, thoughtfully and rather quietly as in "well, you know, I beg to differ" the deferential tone would sound quite normal, even in contemporary Britain.
Britons are highly tolerant of quiet argument and disagreement, it is built into our liberality of thought and expression across a highly complex set of language forms.
Much more difficult for non-Brits is the "joshing" we do with each other when we differ, a form of verbal sparring with often undisguised insults, swear words and attribution of personal inadequacies that might sound like the beginnings of a fight to outsiders. We'd respond; "Nah, mate, just a bit of fun, innit?"
I would give examples, but you might have a filter to bin rude words and insults.

A: I agree with Barrie's too. To non-anglophones, the word of beg sounds very stilted. However, I doubt it does not to anglophones. The real issue is that, it sounds too formal or archaic. There certainly are many other ways to express disagreement politely and formally. Being a non-anglophones, I would like to say "I beg to differ" someday, when communicate with English-speaking persons. Living in China, I know the chance is fat, though.


text:
Q: Whenever I want to start my Apache, below message is apperaring: Attempting to start Apache app...
    Status change detected: running
    Status change detected: stopped
    Error: Apache shutdown unexpectedly.
This may be due to a blocked port, missing dependencies,
improper privileges, a crash, or a shutdown by another method.
    Press the Logs button to view error logs and check
    the Windows Event Viewer for more clues
    If you need more help, copy and post this
    entire log window on the forums

A: Your log will tell you exactly what you need to know. Proceed to:
cd /var/log/apache2


text:
Q: PHP- Zend Framework- Call action from another action's view on CentOS Server I deploying my PHP project on CentOS and i using Zend Framework.
I have problem:
When i call an action from another action's view and it displayed is good on Windows Server but not good on CentOS Server. It's not load info in head tag when view source html.
Example:
In file: index.phtml (for index action in Product controller)

     <?php echo $this->action('left', $this->controller,'product',array('currentModule'=>$this->module)); ?>

    <?php echo $this->action('list', $this->controller, 'product',array('currentModule'=>$this->module,'back'=> $this->back,'page'=> $this->page)); ?>

So, we can see. In index.phtml, i called 2 another action (left action and list action in Product controller). Windows is OK but on CentOS, this code is not work.
Please help me for it run on CentOS.
When i was try remove 2 this action:

     //code

       //code

So, it's woking on CentOS :)
Thanks!

A: Windows migrations to unix based systems usually run into problems like this when you have case sensitivity issues - windows doesn't require case to be correct but unix does. Make sure your folders and php file names have the correct case and try it again - if not give us some of the errors your encountering and we could help more!
By the way, a little off topic here but the action view helper is not efficient, I would suggest looking into custom view helpers and the render view helper instead.


text:
Q: Copy entire php page to another _blank php page I'm trying to copy the content of a preview php page with a bunch of variables to a new blank php page to print, but all I get in the blank is the code I wrote in the preview page.
I'm storing the content of preview.php into a variable to retrieve it in blank_print.php
I tried POST, COOKIE, GET, SESSION but I got nothing. I don't know if I used them correctly though.
In preview.php I get all input fields from page1.php, I set them into a table for preview (perfect so far) and, if correct, press a print button to open a new window (fails to load previous data), print it, and finish the job.
preview.php:
  $content= 'page1, content with $variables';

    echo $content;

blank_print.php:
file_get_contents($content,'preview.php');

    echo $content;

    //also tried echo $_POST[$content];
Looked in the site and found this
You can set the php.ini value allow_url_fopen to true, then you can do this in a single line using file_get_contents() and file_put_contents():
 file_put_contents($file, file_get_contents($url));

But I don't realy know how to use it nor if it the solution to my problem.
Thanks a lot for any help!!

A: Sounds like you want to use session variables.
To start a session you have to call session_start(); at the top of every page who will use sessions. For example:
<?php
session_start();
...

Then you can use session variables to "transfer" variables and information between pages. For example:
page1.php
<?php
session_start();
$_SESSION['test'] = "Value";
?>

page2.php
<?php
session_start();
echo $_SESSION['test']; // Will output "Value"
?>

Here you can read more about sessions.

A: If I understood what you mean.
The best way is using $_SESSION
Store your variables in a Session before you Save or submit your form.
Toturial:
http://www.w3schools.com/php/php_sessions.asp


text:
Q: Combining lines in character vector in R I have a character vector (content) of about 50,000 lines in R. However, some of the lines when read in from a text file are on separate lines and should not be. Specifically, the lines look something like this:
[1] hello,
[2] world
[3] ""
[4] how
[5] are
[6] you
[7] ""

I would like to combine the lines so that I have something that looks like this:
[1] hello, world
[2] how are you

I have tried to write a for loop:
for(i in 1:length(content)){
    if(content[i+1] != ""){
        content[i+1] <- c(content[i], content[i+1])
    }
}

But when I run the loop, I get an error: missing value where TRUE/FALSE needed.
Can anyone suggest a better way to do this, maybe not even using a loop?
Thanks!
EDIT:
I am actually trying to apply this to a Corpus of documents that are all many thousands lines each. Any ideas on how to translate these solutions into a function that can be applied to the content of each of the documents?

A: you don't need a loop to do that
x <- c("hello,", "world", "", "how", "\nare", "you", "")

dummy <- paste(
  c("\n", sample(letters, 20, replace = TRUE), "\n"),
  collapse = ""
) # complex random string as a split marker
x[x == ""] <- dummy #replace empty string by split marker
y <- paste(x, collapse = " ") #make one long string
z <- unlist(strsplit(y, dummy)) #cut the string at the split marker
gsub(" $", "", gsub("^ ", "", z)) # remove space at start and end

A: I think there are more elegant solutions, but this might be usable for you:
chars <- c("hello,","world","","how","are","you","")
###identify groups that belong together (id increases each time a "" is found)
ids <- cumsum(chars=="")

#split vector (an filter out "" by using the select vector)
select <- chars!=""
splitted <- split(chars[select], ids[select])

#paste the groups together
res <- sapply(splitted,paste, collapse=" ")

#remove names(if necessary, probably not)
res <- unname(res) #thanks @Roland

> res
[1] "hello, world" "how are you"

A: Here's a different approach using data.table which is likely to be faster than for or *apply loops:
library(data.table)
dt <- data.table(x)
dt[, .(paste(x, collapse = " ")), rleid(x == "")][V1 != ""]$V1
#[1] "hello, world" "how are you"

Sample data:
x <- c("hello,", "world", "", "how", "are", "you", "")

A: Replace the "" with something you can later split on, and then collapse the characters together, and then use strsplit().  Here I have used the newline character since if you were to just paste it you could get the different lines on the output, e.g. cat(txt3) will output each phrase on a separate line.
txt <-  c("hello", "world", "", "how", "are", "you", "", "more", "text", "")
txt2 <- gsub("^$", "\n", txt)
txt3 <- paste(txt2, collapse = " ")
unlist(strsplit(txt3, "\\s\n\\s*"))
## [1] "hello world" "how are you" "more text"

A: Another way to add to the mix:
tapply(x[x != ''], cumsum(x == '')[x != '']+1, paste, collapse=' ')
#             1              2              3
#"hello, world"  "how are you"    "more text"

Group by non-empty strings. And paste the elements together by group.


text:
Q: Reactivity in props in Vue3 Composition API? I'm watching a couple of props on a child component (basicSalaryMin and basicSalaryMax). When the value changes I'm then trying to update a reactive the value on the parent component (data.companyModels which is also passed to the child component as a prop inside allReactiveData).
Child component:
<template>

  {{allReactiveData.companyModels}} // all data is rendered!

</template>

import { toRefs, watch, ref, reactive } from "vue";
import SimPrivate from '../views/SimPrivate.vue'

export default {
  name: "Simulator",
  components: {
      Slider,
      SimPrivate
    },
  props: {},
  setup( props, {emit}) {
    let data = reactive({
      avrgProfit: 0,
      basicsalaryMin: 3000,
      basicsalaryMax: 5000,
      TotalUBICreatedPerMonth: 0,
      companyModels: [
            { id: 'Big', workers: 250, ranks: 5, companyAvrgProfit: 0, totalWages: Number, wages: {1: '3000', 2: '3500', 3:'4000', 4: '4500', 5: '5000'  }},
            { id: 'Medium', workers: 75, ranks: 3, companyAvrgProfit: 0, totalWages: Number, wages: {1: '3000', 2: '4000', 3:'5000' }},
            { id: 'Small', workers: 10, ranks: 2, companyAvrgProfit: 0, totalWages: Number,  wages: {1: '3000', 2: '5000' }},
            { id: 'Individual', workers: 1, ranks: 1, companyAvrgProfit: 0, totalWages: Number, wages: {1: '3000'}}}
          ],
    )}
    let reactiveData = toRefs(data)
    return {
            allReactiveData,
            basicsalaryMin,
            basicsalaryMax,
    }
  )}

The goal is to then check the value of ranks (which will vary between 1 and 100) and create as many equidistant wage values as needed to match the rank number.
Any thoughts?

A: If you want to access or modify a ref from your script you need to do
yourref.value.
e.g.
yourref.value = 'Hello'
console.log(yourref.value)
// outputs : 'Hello'

So in your case allReactiveData.value
See docs


text:
Q: hdfs test result only displayed after typing $? How come when I run the command:
hdfs dfs -test -d /user/me/dirs
I have to type in $? to get the result:
sh: 0: command not found
Is there a way I could just get the result (0 or 1)itself and none of the other text?
Pretty terrible at bash so I might be missing something

A: In bash, $? gives you the exit code of the previous command. Simply typing $? will cause your shell to attempt to execute that return code as a command (which is not usually what you want). You could instead print the value using echo $?, or save it in a variable using retcode=$?.
Exit codes are not normally printed to your shell. The reason you may not be seeing any other output is because the hdfs command is likely not printing any text to your screen (either through stdout or stderr).
I suspect your best option might be hdfs dfs -test -d /user/me/dirs; echo $?, or some variant using a variable.

*

*Exit codes

*Understanding exit codes and how to use them in bash scripts


text:
Q: Inserindo dados usando array PHP Tenho uma tabela e preciso inserir dados desta tabela através de um array. Porém
dá este erro:
Notice: Array to string conversion in C:\xampp\htdocs\PhpProject1\salvar.php on line 17
Meu insert onde preenchi os valores: CHA, KG, KG foram inseridos desta forma no banco
INSERT INTO tipoprod (codigo_produto, codigo_tipo, descricao) VALUES ('CHA', 'Array', 'Array')

meu index.php
<form action='salvar.php' method='POST'>
    <?php
        $sql = "SELECT * FROM tipoprod";
        $resulta = $conn->query($sql);
        $row = $resulta->fetch_assoc();
    ?>

          Código do Produto:
        <input type="text" maxlength="6"  name="codigo_produto" value="<?php $row['codigo_produto'] ?>">

                Código
                Descrição

        <?php
            include("conn.php");

            $codigo_tipo = array();
            $descricao = array();
            for($i =0; $i <= 5; $i++){

                echo "
";
                echo "<input type='text' name='codigo_tipo[]' style='border:none; width:100%; background-color: transparent;'	";
                echo "<input type='text' name='descricao[]' value='' style='border:none; width:100%; background-color: transparent;'	";
                echo "
";
            }
        ?>

        <input type="submit" class="btn btn-success btn-lg btn-block" name="enviar_tipo" value="Salvar Informações">

</form>

meu salvar.php
if(isset($_POST['enviar_tipo'])){

    $codigo_produto = $_POST['codigo_produto'];
    $codigo_tipo = $_POST['codigo_tipo'];
    $descricao = $_POST['descricao'];

    $sql_tipo = "SELECT * FROM tipoprod WHERE codigo_produto = '$codigo_produto' ";
    $resulta = $conn->query($sql_tipo);
    $row = $resulta->fetch_assoc();

foreach($codigo_tipo as $k=>$v) {
$codigo_tipo = $v;
$desc = $descricao[$k];

if ($resulta->num_rows > 0) {
    $result_produto = "UPDATE tipoprod SET codigo_tipo = '$codigo_tipo', descricao = '$descricao' WHERE codigo_produto = '$codigo_produto' ";
} else {
    $result_produto = "INSERT INTO tipoprod (codigo_produto, codigo_tipo, descricao) VALUES ('$codigo_produto', '$codigo_tipo', '$descricao')";
}

    $resultado_produto = mysqli_query($conn, $result_produto);
    var_dump ($result_produto);
}
}

A: O fato é que vc adicionou o input com name pra virar um array (name='codigo_tipo[]').. com isso, no $_POST, ele vai te dar uma variavel array.. e por isso q no seu insert/update vc vai ter um Array e nao um valor especifico...
se vc quer fazer insert do resultado do $_POST faça algo do tipo:
if(isset($_POST['enviar_tipo'])){
$codigo_produto = $_POST['codigo_produto'];
$codigo_tipo = $_POST['codigo_tipo'];
$descricao = $_POST['descricao'];

$sql_tipo = "SELECT * FROM tipoprod WHERE codigo_produto = '$codigo_produto' ";
$resulta = $conn->query($sql_tipo);
$row = $resulta->fetch_assoc();

foreach($codigo_tipo as $k=>$v) {
    $codTipo = $v;
    $desc = $descricao[$k];

    if ($resulta->num_rows > 0) {
        $result_produto = "UPDATE tipoprod SET codigo_tipo = '$codTipo', descricao = '$desc' WHERE codigo_produto = '$codigo_produto' ";
    } else {
        $result_produto = "INSERT INTO tipoprod (codigo_produto, codigo_tipo, descricao) VALUES ('$codigo_produto', '$codTipo', '$desc')";
    }

    $resultado_produto = mysqli_query($conn, $result_produto);
}

A: Coloque isso no seu método post e irá funcionar o insert e o update, pelo menos aqui no meu código funcionou.
salvar.php
<?php
include("conn.php");

if(isset($_POST['enviar_tipo'])){

    $codigo_produto = $_POST['codigo_produto'];
    $codigo_tipo = $_REQUEST['codigo_tipo'];
    $descricao = $_REQUEST['descricao'];

    $sql_tipo = "SELECT * FROM tipoprod WHERE codigo_produto = '$codigo_produto' ";
    $resulta = $conn->query($sql_tipo);
    $row = $resulta->fetch_assoc();

for($i = 0; $i<count($_POST['codigo_tipo'])AND($_POST['descricao']); $i++) {

if ($resulta->num_rows > 0) {
    $result_produto = "UPDATE tipoprod SET codigo_tipo = '$codigo_tipo[$i]', descricao = '$descricao[$i]' WHERE codigo_produto = '$codigo_produto' ";
} else {
    $result_produto = "INSERT INTO tipoprod (codigo_produto, codigo_tipo, descricao) VALUES ('$codigo_produto', '$codigo_tipo[$i]', '$descricao[$i]')";
}

    $resultado_produto = mysqli_query($conn, $result_produto);
    echo "$result_produto
";
}
}
?>


text:
Q: How to dynamically add a new subscriber with a new topic at runtime in ROS What I expect:
A ros node is run, it has a publisher and a subscriber coded into it, and another dynamic subscriber
The publisher publishes data about the node to another master node, which then publishes to the subscriber in the node
a) a topic
b) type of message from that topic
Taking this information, the node must assign the topic and message type to the dynamic subscriber
The node, same code, will be run multiple times, but with different data that is being published to the master node so they all get their topics from the master node individually which might or might not be same
To be honest, I am pretty new to ros and I havent tried much, and I am unsure where to start too

A: I think It's not good practice and I would recommend not doing i,  but here's how you can:
Let's take the " slave " node

*

*you need to publish info about this node, let's assume we will publish the node name node1. So you will create a publisher that publishes message type String.

*creat a subscriber that receives a message type String your node needs to wait for this subscriber to receive a message with the name of the the new topic and it's message type (seperated by a comma). you can seperate them into "topic and type

*you will run into the problem that you need to import this " new message type" that changes from node to node which is actually doable for example see this answer
now your code should be something like this (not a running version):

#!/usr/bin/env python
import rospy
from std_msgs.msg import String

class Nodes(object):
    def __init__(self, name):
        rospy.init_node('node_name', anonymous=True)
        self.Name = name
        self.pub = rospy.Publisher('nodes_info', String, queue_size=10)
        self.pub.publish(self.Name)
        self.sub_once = rospy.Subscriber('master_topic', String, self.sub_callback, queue_size=10)
        self.rate = 10
        self.sub_msg = None
        self.topic = None
        self.type = None

    def sub_callback(self, msg):
        self.sub_msg = msg.data
        chunks = self.sub_msg.split(',')
        self.topic = chunks[0]
        self.type = chunks[1]
        ##
        # DO dynamic import here
        ##
        self.sub_once.unregister()

    def callback(self,data)
        # DO SOMETHING ( you main callback)
        d = data

    def spin(self):
        r = rospy.Rate(self.rate)
        while self.sub_msg == None:
            r.sleep()
        while not rospy.is_shutdown():
            rospy.Subscriber(topic, type, self.callback)
            print(self.sub_msg)
            r.sleep()

if __name__ == "__main__":
    SC = Nodes("node1")
    SC.spin()


text:
Q: Objective-C / Cocoa equivalent of C# ManualResetEvent Is there an equivalent of the .NET ManualResetEvent class available for use in Objective-C / Cocoa?

A: I'm not very familiar with ManualResetEvent, but based on the documentation, it looks like the NSCondition class might be what you are looking for.
NSCondition is by no means an exact equivalent, but it does provide similar signaling functionality. You might also want to read up on NSLock.

A: Here is a wrapper class I created which emulates ManualResetEvent using NSCondition.
@interface WaitEvent : NSObject {
    NSCondition *_condition;
    bool _signaled;
}

- (id)initSignaled:(BOOL)signaled;
- (void)waitForSignal;
- (void)signal;

@end

@implementation WaitEvent

- (id)initSignaled:(BOOL)signaled
{
    if (self = ([super init])) {
        _condition = [[NSCondition alloc] init];
        _signaled = signaled;
    }

    return self;
}

- (void)waitForSignal
{
    [_condition lock];
    while (!_signaled) {
        [_condition wait];
    }

    [_condition unlock];
}

- (void)signal
{
    [_condition lock];
    _signaled = YES;
    [_condition signal];
    [_condition unlock];
}

@end

I've done just some basic testing but I think it should get the job done with much less ceremony.

A: I'll give you the sample code I would have liked to find yesterday (but couldn't find anywhere). If you want to create a producer/consumer class where the consumer is asynchronous, this is what you need to do :
You need to declare and allocate the NSConditionLock.
NSArray * data = [self getSomeData];

if ( [data count] == 0 ) {
  NSLog(@"sendThread: Waiting...");
  [_conditionLock lockWhenCondition:1];
  [_conditionLock unlockWithCondition:0];
  NSLog(@"sendThread: Back to life...");
}
else {
  // Processing
}

And in the main code, when you add data and you want to unlock the other thread, you just have to add :
[_conditionLock lock];
[_conditionLock unlockWithCondition:1];

Note: I don't describe here how data are exchanged between the producer and the consumer. In my program it was going through an SQLite/CoreData database, so thread sync is done at a higher level. But if you use a NSMutableDictionary, you need to add some NSLock.

A: Ah, those are poor man's condition variables.
You could use the NSCondition class, but I think it's better
to go straight to the source. Start with pthread_cond_init.
You gonna love it.


text:
Q: Angular: Cannot find namespace "Spotify" when using @types/spotify-web-playback-sdk I'm trying to use https://www.npmjs.com/package/@types/spotify-web-playback-sdk in my angular project to type out the spotify player in one of my components. I Installed the types, as instructed...
npm install --save @types/spotify-web-playback-sdk

The Visual Studio code linter doesn't complain when I define this class variable and type it to a SpotifyPlayer ...
// class variable
spotifyPlayer: Spotify.SpotifyPlayer;

But, when I go to build my code, I get this error...
ERROR in src/app/components/header/header.component.ts:32:18 - error TS2503: Cannot find namespace 'Spotify'.

32   spotifyPlayer: Spotify.SpotifyPlayer;

I'm using ...
Angular CLI: 9.1.0
Node: 10.15.1
OS: win32 x64

Angular: 9.1.0
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router
Ivy Workspace: Yes

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.901.0
@angular-devkit/build-angular     0.901.0
@angular-devkit/build-optimizer   0.901.0
@angular-devkit/build-webpack     0.901.0
@angular-devkit/core              9.1.0
@angular-devkit/schematics        9.1.0
@ngtools/webpack                  9.1.0
@schematics/angular               9.1.0
@schematics/update                0.901.0
rxjs                              6.5.4
typescript                        3.8.3
webpack                           4.42.0

Appreciate the help!

A: As per the type definition here spotify-web-playback-sdk is non-npm package.
As per the Spotify documentation here, you would be adding the JS bundle in your html directly, which means this Script is not loaded as a module.
From DefinitelyTyped

You may need to add a types reference if you're not using modules

You can add the below line to top of the file where you are using Spotify namespace and the error should disappear.
///  <reference types="@types/spotify-web-playback-sdk"/>

More information is here and here. Whenever Spotify publishes a npm library prefer using that instead.

A: You'll have to import the namespace in every class
e.g. import * as Spotify from 'Spotify'


text:
Q: VSCode SyntaxError: Unexpected identifier on es6 imports I am getting this error when running a javascript file from inside using code runner.
(function (exports, require, module, __filename, __dirname) { import Vue from 'vue'
                                                                 ^^^

SyntaxError: Unexpected identifier

I do have a jsconfig.json file in the root of my project directory which includes
{
"compilerOptions": {
    "target": "es6"
}

}
and my code runner configuration is simply
"code-runner.executorMap": {
    "javascript": "node --no-warnings"
}

The only line of code in the test script is import Vue from 'vue'
How can i use es6 imports in vscode?

A: Take a look at this issue on GitHub. That  issue references the solution to your problem. You probably have to use babel-register:
1:
$ npm i -D babel-register

2:
$ npm i -D babel-preset-es2015

3:
config babel in package.json
{
  // ...
  // something else
  // ...
  "devDependencies": {
    "babel-preset-es2015": "^6.18.0",
    "babel-register": "^6.18.0"
  },
  "babel": {
    "presets": [
      "es2015"
    ],
    "sourceMaps": true,
    "retainLines": true
  }
}


text:
Q: Detect if line segment intersects square Anyone have a simple algorithm for this? No need for rotation or anything. Just finding if a line segment made from two points intersects a square

A: This code should do the trick. It checks where the line intersects the sides, then checks if that is within the width of the square. The number of intesections is returned.
float CalcY(float xval, float x0, float y0, float x1, float y1)
{
    if(x1 == x0) return NaN;
    return y0 + (xval - x0)*(y1 - y0)/(x1 - x0);
}

float CalcX(float yval, float x0, float y0, float x1, float y1)
{
    if(x1 == x0) return NaN;
    return x0 + (yval - y0)*(y1 - y0)/(x1 - x0);
}

int LineIntersectsSquare(int x0, int y0, int x1, int y1, int left, int top, int right, int bottom)
{
    int intersections = 0;
    if(CalcX(bottom, x0, y0, x1, y1) < right && CalcX(bottom, x0, y0, x1, y1) > left  ) intersections++;
    if(CalcX(top   , x0, y0, x1, y1) < right && CalcX(top   , x0, y0, x1, y1) > left  ) intersections++;
    if(CalcY(left  , x0, y0, x1, y1) < top   && CalcY(left  , x0, y0, x1, y1) > bottom) intersections++;
    if(CalcY(right , x0, y0, x1, y1) < top   && CalcY(right , x0, y0, x1, y1) > bottom) intersections++;
    return intersections;
}

NB: this code is theoretical and may not be correct, as it has not been tested

A: You can do this by casting a vector and counting the number of edges it crosses.
If the edges it crosses are even, it is outside the object, if the edges it crosses are odd, it is inside.
This works for all closed polygons.

A: Here's a way:
 - sort the vertex points of the square by x-coord
 - sort the endpoint of the line by x-coord
 - calculate angle from the minX end of the line to each of the middle two (by x-coord) square vertices
 - calculate angle of the line
 - if the line's angle is within the possible angles, all you have to do is a length check, is maxX end of the line > minX vertex of the square

This will probably break if the square is directly facing the line, in that case I'd just special-case it by checking the first edge of the square.


text:
Q: Proof of B1by OLS in a multiple regression model with dummies Given the model Y=B0 + B1C + B2A + e, where C=(0,1) and A=(0,1), how can I derive the formula for the estimator of B1 by OLS? I already know the formula for the general case in which A and C are not dummies and starting from that I don't know how to solve the problem.

A: There isn't much to it actually.
You have
$$Y=\beta X+\epsilon$$
Where the columns of $X$ are given by:
$$X_i=\left[\begin{matrix}1 \\ A_i \\ B_i\end{matrix}\right], A_i \in \{0,1\},B_i \in \{0,1\}$$
$\beta$ can be obtained just like in OLS:
$$\beta = YX^T(XX^T)^{-1}$$
We have that:
$$XX^T=
\left[\begin{matrix}
\mathbf 1\\A\\B\end{matrix}\right]
\left[\begin{matrix}
\mathbf 1^T&A^T&B^T\end{matrix}\right]=
\left[\begin{matrix}
\mathbf {11}^T & \mathbf {1}A^T & \mathbf {1}B^T\\
A\mathbf {1}^T & AA^T & AB^T\\
B\mathbf {1}^T & BA^T & BB^T
\end{matrix}\right]=
n \left[\begin{matrix}
1 & \mu_A & \mu_B\\
\mu_A & \mu_A & \mu_{A\cap B}\\
\mu_B & \mu_{A\cap B} & \mu_B
\end{matrix}\right]
$$
This matrix is invertible if $\mu_A \neq 0, \mu_B \neq 0$ and $\mu_{A \cap B}$ cannot be equal to $\mu_A, \mu_B$ at the same time (that would mean $A$ and $B$ are the same).
$$\begin{cases}
\mu_A = (1/n)\sum_i^n A_i\\
\mu_B = (1/n)\sum_i^n B_i\\
\mu_{A\cap B} = (1/n)\sum_i^n A_iB_i
\end{cases}$$
Assuming you calculated the solution for $\beta$, then you are left with a model:
$$\hat Y_i = \beta_0 + \beta_A A_i + \beta_B B_i$$
We are left with four possible combinations of $A_i, B_i$
$$\hat Y_i = \begin{cases}
\beta_0 & \{A_i := 0, B_i := 0\}  \\
\beta_0+\beta_A & \{A_i := 1, B_i := 0\}  \\
\beta_0+\beta_B & \{A_i := 0, B_i := 1\}\\
\beta_0+\beta_A+\beta_B & \{A_i := 1, B_i := 1\}\\
\end{cases}$$
So, interpretation is straightforward: each entry here represents conditional expected values.
$\beta_A$ therefore represents an increase (even if negative) of the expected value if $A_i = 1$ compared with the samples where both $A_i = B_i = 0$.
Similarly for $\beta_B$.


text:
Q: TYPO3: Is there any way to use javascript inside Alt-Doc form? I want to know that is there any way to add own javascript code which will be execute in the form processing of Alt-Doc.php.
I need to change a selectbox value depend on other selectbox(select event).
Is it possible ??

A: You can use the $TCA['tt_content']['ctrl']['requestUpdate'] = "yourfieldname" to let TYPO3 add the js code (onchange event) to the given field. You can then write different palettes to yout TCA with different values. It's done this bay by tt_content (field CType) and also in the pages table (type sysfolder vs. "normal page").
The other form elements completely change in those two cases. Of course, this will cause a reload of the whole form, so you should place a field with this behavior at the top of the form.