text:
Q: How to handle errors from third party libraries in PHP I've set up my own error handlers which in development stops the application and displays a custom error page with details regardless of the error type (fatal, warnings) etc and this is great because I'm finding all errors easily as they don't end up getting output with HTML.
The problem that I'm having is that sometimes third party libraries throw error warnings which aren't really an issue. This causes the script to stop and display an error which I don't want to see.
For example, I'm using a library that depends on Buzz and it's throwing this error
"file_get_contents(): Content-type not specified assuming application/x-www-form-urlencoded".

It still works regardless.
Now It's nothing to do with anything I've written I don't want to go in and fix this error myself.
Do you have any ideas as to how I go about handling these types of scenarios?


text:
Q: sshd_config GatewayPorts Is there any reason why I should not set GatewayPorts yes in my sshd_config file if the hosts are only going to be internal to the network?

A: Seems reasonably safe to do so; the only caveat is if there's any way for that machine to be compromised it's a bit less insecure than not.  If it's a purely internal machine with no external ports forwarded to it or anything, it should be just fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Broadcast receiver in activity Android Is it possible that If I place some part of the code from my Activity in Broadcast and then even if the activity is not running the broadcasted piece of code will continue to work?If yes any reference to it plz?
To b specific I've facebook activity that retrieves notifications on button click.I want that get notification method to b in a broadcast so that every time notification arrives it generates alert.Can provide the code aswel.. Kindly help

A:
Is it possible that If I place some part of the code from my Activity
  in Broadcast and then even if the activity is not running the
  broadcasted piece of code will continue to work?

No, it is not possible that your activity is not running and you defined your broadcast in the activity and you still want the broadcast to run that is within that activity.

A: Add the BroadCast Receiver in a Service class. register and unregister this broadcast receiver from onCreate() and onDestroy() methods respectively of Service class.


text:
Q: SQLite: ROWID not found I am getting an error whenever i query for data to insert into another activity.
The major problem is that i am not getting an output in my stack trace and being a new programer, i am unable to figure out what is happening.
I am new to SQLite and do not fully understand how the queries work, so any help would be appreciated.
The problem occurs when ever i want to click on an item in the Listview on the activity_main layout.
I have set the onItemClickListener to change the activity to the edit_data layout and to fill the EditText fields with the appropriate data from the SQLite database table whenever an item on the list is clicked.
But whenever i click on an item it makes a toast that says: "No ID associated with that name".
This toast message is built in to the app by myself, so i know what is toasting this message but i dont know why.
Here is my code:
MainActivity.java
package com.TheAbstractLightbulb.cohen.not_at_homes_app;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";
    DBHelper dbHelper;

    public MainActivity() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        setContentView(R.layout.activity_main);
        dbHelper = new DBHelper(this);

        populateListView();
    }

    public void toInputScreen(View view) {
        Button addButton = (Button) findViewById(R.id.addButton);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(MainActivity.this, InputPage.class);
                startActivity(intent1);
            }
        });
    }

    private void populateListView() {
        Log.d(TAG, "populateListView: Displaying data in list view.");
        final Cursor data = dbHelper.getData();
        ArrayList<String> listData = new ArrayList<>();
        while (data.moveToNext()) {
            listData.add(data.getString(2));
        }
        ListView listview = (ListView) findViewById(R.id.MainListView);
        final ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
        listview.setAdapter(adapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String map = adapterView.getItemAtPosition(i).toString();
                String name = adapterView.getItemAtPosition(i).toString();
                String date = adapterView.getItemAtPosition(i).toString();
                String notAtHomes = adapterView.getItemAtPosition(i).toString();
                Log.d(TAG, "onItemClick: You Clicked on " + notAtHomes);

                Cursor data = dbHelper.getItemID(map, name, date, notAtHomes);
                int itemID = -1;
                while (data.moveToNext()) {
                    itemID = data.getInt(0);
                }
                if (itemID > -1) {
                    Log.d(TAG, "onItemClick: The ID is: " + itemID);
                    Intent editDataIntent = new Intent(MainActivity.this, EditData.class);
                    editDataIntent.putExtra("id", itemID);
                    editDataIntent.putExtra("map", map);
                    editDataIntent.putExtra("name", name);
                    editDataIntent.putExtra("date", date);
                    editDataIntent.putExtra("notAtHomes", notAtHomes);
                    startActivity(editDataIntent);
                } else {
                    Toast.makeText(getBaseContext(), "No ID associated with that name", Toast.LENGTH_LONG).show();
                }

            }
        });
    }
}

EditData.java
package com.TheAbstractLightbulb.cohen.not_at_homes_app;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Created by cohen on 2/06/2017.
 */

public class EditData extends Activity {
    private static final String TAG = "EditData";

    DBHelper dbhelper;

    private int selectedID;
    private String selectedMap;
    private String selectedName;
    private String selectedDate;
    private String selectedNotAtHomes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_data);
        final Button saveButton2 = (Button)findViewById(R.id.saveButton2);
        Button deleteButton1 = (Button)findViewById(R.id.deleteButton1);
        final EditText textNotAtHomes2 = (EditText)findViewById(R.id.textNotAtHomes2);
        final EditText mapNoDisplay2 = (EditText)findViewById(R.id.mapNoDisplay2);
        final EditText dateDisplay2 = (EditText)findViewById(R.id.dateDisplay2);
        final EditText ListName2 = (EditText)findViewById(R.id.ListName2);
        DBHelper DB = new DBHelper(this);

        Intent receivedIntent = getIntent();
        // ID
        selectedID = receivedIntent.getIntExtra("id",-1);
        // Map no
        selectedMap = receivedIntent.getStringExtra("map");
        // Name
        selectedName = receivedIntent.getStringExtra("name");
        // Date
        selectedDate = receivedIntent.getStringExtra("date");
        // Not at homes note file
        selectedNotAtHomes = receivedIntent.getStringExtra("notAtHomes");

        ListName2.setText(selectedName);
        mapNoDisplay2.setText(selectedMap);
        dateDisplay2.setText(selectedDate);
        textNotAtHomes2.setText(selectedNotAtHomes);

        saveButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String item1 = ListName2.getText().toString();
                String item2 = mapNoDisplay2.getText().toString();
                String item3 = dateDisplay2.getText().toString();
                String item4 = textNotAtHomes2.getText().toString();
                if (!item1.equals("")){
                    if (!item2.equals("")){
                        if (!item3.equals("")) {
                            if (!item4.equals("")) {
                                dbhelper.updateData(selectedID, item2, selectedMap, item1, selectedName, item3, selectedDate, item4, selectedNotAtHomes);
                            } else {
                                new AlertDialog.Builder(getBaseContext())
                                        .setTitle("emptyBoxes")
                                        .setMessage("Some boxes have been left empty, /n" +
                                                "are you sure you are done?")
                                        .setNegativeButton("Cancel", null)
                                        .setPositiveButton("Save", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {

                                            }
                                        }).create().show();
                            }

                        }

                        }
                    }

                }
            });

        deleteButton1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dbhelper.deleteData(selectedID, selectedMap, selectedName, selectedDate, selectedNotAtHomes);
                Intent intent = new Intent(EditData.this, MainActivity.class);
                startActivity(intent);
                Toast.makeText(getBaseContext(), "Note Deleted successfully", Toast.LENGTH_LONG).show();
            }
        });
        }

        private void toSendNote(View view){
            Button sendButton = (Button)findViewById(R.id.sendButton);
            sendButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent1 = new Intent(EditData.this, SendRecord.class);
                    intent1.putExtra("Note", selectedNotAtHomes);
                    startActivity(intent1);
                }
            });
        }

    }

DBHelper.java
package com.TheAbstractLightbulb.cohen.not_at_homes_app;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Created by cohen on 31/05/2017.
 */

public class DBHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "App_database.db";
    public static final String TABLE_NAME = "App_date_table";
    public static final String MAP_NO = "Map_no";
    public static final String LOCATION = "Location";
    public static final String DATE = "Date";
    public static final String NOTATHOMES = "Not_at_homes";
    public static final String ID = "ID";
    public static final String TAG = "DBHelper";

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
       String createTable = "CREATE TABLE " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, " + MAP_NO + " INTEGER, " + LOCATION + " TEXT, " + DATE + " INTEGER, " + NOTATHOMES + " TEXT)";
        db.execSQL(createTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);

    }

    public boolean insertData(String Map_no, String Location, String Date, String Not_at_homes) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(MAP_NO, Map_no);
        contentValues.put(LOCATION, Location);
        contentValues.put(DATE, Date);
        contentValues.put(NOTATHOMES, Not_at_homes);

        Log.d(TAG, "addData: Adding " + Location + " to " + TABLE_NAME);

        long result = db.insert(TABLE_NAME, null, contentValues);
        if (result == -1) {
            return false;
        } else {
            return true;
        }

    }

    public Cursor getData() {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_NAME;
        Cursor data = db.rawQuery(query, null);
        return data;
    }

    public Cursor getItemID(String map, String location, String date, String notAtHomes) {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT " + ID + " FROM " + TABLE_NAME +
                " WHERE " + MAP_NO + " = '" + map + "' AND " + LOCATION + " = '" + location +
                "' AND " + DATE + " = '" + date + "' AND "
                + NOTATHOMES + " = '" + notAtHomes + "'";
        Cursor data = db.rawQuery(query, null);
        return data;
    }

    public void updateData(int id,String newMapNo, String oldMapNo, String newLocation, String oldLocation, String newDate, String oldDate, String newNotAtHomes, String oldNotAtHomes){
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "UPDATE " + TABLE_NAME + " SET " + MAP_NO +
                " = '" + newMapNo + " WHERE " + ID + " = '" + id + "'" +
                " AND " + MAP_NO + " = '" + oldMapNo + "'"+ LOCATION +
                " = '" + newLocation + " WHERE " + ID + " = '" + id + "'" +
                " AND " + LOCATION + " = '" + oldLocation + "'"+ DATE +
                " = '" + newDate + " WHERE " + ID + " = '" + id + "'" +
                " AND " + DATE + " = '" + oldDate + "'"+ NOTATHOMES +
                " = '" + newNotAtHomes + " WHERE " + ID + " = '" + id + "'" +
                " AND " + NOTATHOMES + " = '" + oldNotAtHomes + "'";
        Log.d(TAG, "updating: query: " + query);
        Log.d(TAG, "updating: Setting map number, Location, Date and Not at homes to new values: Map number: " +
                newMapNo + " Location: " + newLocation + " Date: " +
                newDate + " Not at homes: " + newNotAtHomes);
        db.execSQL(query);
    }

    public void deleteData(int id, String mapNo, String location, String date, String notAtHomes){
        SQLiteDatabase database = this.getWritableDatabase();
        String query = "DELETE FROM " + TABLE_NAME + " WHERE "
                + ID + " + '" + id + "'" + " AND " + MAP_NO + " = '" + mapNo + "'" +
                LOCATION + " = '" + location + "'" + DATE + " = '" + date + "'" + NOTATHOMES +
                " = '" + notAtHomes + "'";
        Log.d(TAG, "deleting: query: " + query);
        Log.d(TAG, "deleting: Deleting note with values: Map number: " + mapNo + " Location: " + location + " Created on: " + date + " With notes: " + notAtHomes + ".");
        database.execSQL(query);
    }
}

MainActivity XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.TheAbstractLightbulb.cohen.not_at_homes_app.MainActivity"
    android:background="@color/BackgroundGrey">

    <Button
        android:id="@+id/addButton"
        android:layout_width="351dp"
        android:layout_height="61dp"
        android:layout_marginBottom="16dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="449dp"
        android:onClick="toInputScreen"
        android:background="@drawable/buttons"
        android:text="@string/ButtonAddButton"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.733"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />

    <ListView
        android:id="@+id/MainListView"
        android:layout_width="336dp"
        android:layout_height="521dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:divider="@color/blackText"
        android:headerDividersEnabled="false"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.6"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

</android.support.constraint.ConstraintLayout>

EditData XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".EditData"
    android:background="@color/BackgroundGrey">

    <Button
        android:id="@+id/saveButton2"
        android:layout_width="110dp"
        android:layout_height="66dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@drawable/buttons"
        android:onClick="toSaveField"
        android:text="@string/saveButton"
        android:textSize="16sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.005"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />

    <Button
        android:id="@+id/deleteButton1"
        android:layout_width="110dp"
        android:layout_height="66dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@drawable/buttons"
        android:onClick="toDeleteNote"
        android:text="@string/ButtonDeleteButton"
        android:textSize="16sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />

    <Button
        android:id="@+id/sendButton"
        android:layout_width="110dp"
        android:layout_height="66dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@drawable/buttons"
        android:onClick="toSendNote"
        android:text="@string/sendButtonText"
        android:textSize="16sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />

    <EditText
        android:id="@+id/textNotAtHomes2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:ems="10"
        android:background="@color/hintTextColour"
        android:inputType="textMultiLine"
        android:hint="@string/hintText2"
        android:textColorHint="@color/hintTextColour2"
        android:layout_marginLeft="9dp"
        android:gravity="fill_horizontal"
        android:padding="6dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="9dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="89dp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="89dp"
        tools:layout_constraintTop_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintBottom_creator="1"
        android:layout_marginStart="9dp"
        android:layout_marginEnd="9dp"
        tools:layout_constraintLeft_creator="1"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintVertical_bias="1.0" />

    <EditText
        android:id="@+id/ListName2"
        android:layout_width="0dp"
        android:layout_height="37dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@color/BackgroundGrey2"
        android:inputType="text"
        android:textColor="@color/blackText"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1" />

    <EditText
        android:id="@+id/mapNoDisplay2"
        android:layout_width="172dp"
        android:layout_height="37dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@color/BackgroundGrey2"
        android:inputType="number"
        android:textColor="@color/blackText"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.065" />

    <EditText
        android:id="@+id/dateDisplay2"
        android:layout_width="172dp"
        android:layout_height="37dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@color/BackgroundGrey2"
        android:inputType="date"
        android:textColor="@color/blackText"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.065" />

</android.support.constraint.ConstraintLayout>

A: It's not clear what you are querying. These are all the exact same string
String map = adapterView.getItemAtPosition(i).toString();
String name = adapterView.getItemAtPosition(i).toString();
String date = adapterView.getItemAtPosition(i).toString();
String notAtHomes = adapterView.getItemAtPosition(i).toString();

So therefore, sqlite can't find what you passed into dbHelper.getItemID, returns an invalid ID value.
I think you're looking to get different data from the adapter, which isn't really possible because you only added the third  column of the cursor to the adapter.
    ArrayList<String> listData = new ArrayList<>();
    while (data.moveToNext()) {
        listData.add(data.getString(2));
    }

You should really consider using a CursorAdapter to correctly implement a ListView with a Database


text:
Q: How to pass multiple input format files to map-reduce job? I am writing map-reduce program to query cassandra column-family. I need to read only subset of rows(using row key) from only one column family. I have the set of row keys of rows what I have to read. How can I pass "row key set" to the map reduce job so that It can output only those subset of rows from cassandra columnfamily?
Abstract:
enter code here

  class GetRows()
  {
   public set<String> getRowKeys()
   {
     logic.....
     return set<string>;
   }
  }

  class MapReduceCassandra()
  {
    inputformat---columnFamilyInputFormat
     .
     ;
    also need input key-set .. How to get it?
  }

Can any one suggest the best method to call mapreduce from java application and how to pass set of keys to mapreduce?

A: Calling map reduce from Java
To do this, you can use classes from org.apache.hadoop.mapreduce namespace (you can use older mapred using a very similar approach, just check the API doc) from within your java application:
Job job = Job.getInstance(new Configuration());
// configure job: set input and output types and directories, etc.

job.setJarByClass(MapReduceCassandra.class);
job.submit();

Passing data to the mapreduce job
If your set of row keys is really small, you can serialize it to a string, and pass it as a configuration parameter:
job.getConfiguration().set("CassandraRows", getRowsKeysSerialized()); // TODO: implement serializer

//...

job.submit();

nside the job you'll be able to access the parameter through the context object:
public void map(
    IntWritable key,  // your key type
    Text value,       // your value type
    Context context
)
{
    // ...

    String rowsSerialized = context.getConfiguration().get("CassandraRows");
    String[] rows = deserializeRows(rowsSerialized);  // TODO: implement deserializer

    //...
}

However if your set is potentially unbounded, passing it as a parameter would be a bad idea.  Instead you should pass the keys in a file, and take advantage of the distributed cache.
Then you can just add this line to the portion above before you submit the job:
job.addCacheFile(new Path(pathToCassandraKeySetFile).toUri());

//...

job.submit();

Inside the job you'll be able to access this file through the context object:
public void map(
    IntWritable key,  // your key type
    Text value,       // your value type
    Context context
)
{
    // ...

    URI[] cacheFiles = context.getCacheFiles();

    // find, open and read your file here

    // ...
}

NOTE: All of this is for the New APIs (org.apache.hadoop.mapreduce).  If you're using org.apache.hadoop.mapred the approach is very similar, but some relevant methods are invoked on different objects.


text:
Q: Obtaining an average from if statement Python 3 Ok so I got everything figured out. But now I am trying to use an if statement to tell the loop to take the average mpg (from the .txt file) from vehicles that get less than 22 mpg and then just average that up and output it IDLE. I feel like I should run the if statement before the loop. I am just not sure what I really need to change. I figure I should be able to slice variable holding the text file data. anyways here is my code. Can someone help me understand what I am not doing right?
def cityGasGuzzler():
# Input:that assigns a text file to a value and provides other definition
 values
cityGuzz = open("carModelData_city.","r")
# Process: For loop to get average of gas guzzling city street driving
  vehicles
for line in cityGuzz:
# Process: Uses if statement to get the average of lower mpg or gas guzzlers
    if cityGuzz[0:-1] < 22:
        sum = sum + eval(line)
        count = count + 1
        avrg = sum / count
# Output: using the round function to get average to the 2nd decimal place
#         and prints string and rounded variable to IDLE.
print("The average city MPG is,", round(avrg, 2))

cityGasGuzzler()

Just to clarify, my main objective is as follows, take the numeric values from the text file that are less than 22, average those up and output the average to IDLE.

A: Your problem is that you are trying to divide to quantity in each iteration of loop. Also you have several mistakes in your code. Try this out.
sum = 0.0
quantity = 0
with open('file.txt', 'r') as f:
    for line in f.readline():
        if line.isdigit():
            sum += float(line)
            quantity += 1
average = sum/quantity
print average

A: If I understand the question correctly, your issue is with this line:
if cityGuzz[0:-1] < 22:

That's not working for several reasons, not least because cityGuzz is the file object, not the current line. You need to convert the current line into a number before comparing it with a number like 22.
Try something like this:
total = 0 # renamed to avoid masking the builtin sum function
count = 0

for line in cityGuzz:
    mpg = float(line)
    if mpg < 22:
        total += mpg
        count += 1

average = total / count

I renamed sum to total because sum is the name of a builtin function. In fact, it might be a useful one to replace the explicit loop to add up the values from the file. Here's an alternative implementation of the average calculation:
guzzlers = [mpg for mpg in map(float, cityGuzz) if mpg < 22]
average = sum(guzzlers) / len(guzzlers)


text:
Q: org.gradle.api.plugins.UnknownPluginException: Plugin [id: 'org.jetbrains.kotlin.android', version: '1.6.21', apply: false] Hey I just created a new project in android studio. I am getting this weird issue. Can anyone know why this is giving error.
Error
Build file '/Users/vmodi/AndroidStudioProjects/KtorApplication/build.gradle' line: 5

Plugin [id: 'org.jetbrains.kotlin.android', version: '1.6.21', apply: false] was not found in any of the following sources:

* Try:
Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Exception is:
org.gradle.api.plugins.UnknownPluginException: Plugin [id: 'org.jetbrains.kotlin.android', version: '1.6.21', apply: false] was not found in any of the following sources:

- Gradle Core Plugins (plugin is not in 'org.gradle' namespace)
- Plugin Repositories (could not resolve plugin artifact 'org.jetbrains.kotlin.android:org.jetbrains.kotlin.android.gradle.plugin:1.6.21')
  Searched in the following repositories:
    Gradle Central Plugin Repository
    Google
    MavenRepo
    at ...

build.gradle.kts
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.1.3' apply false
    id 'com.android.library' version '7.1.3' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.21' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

I am using latest bumblebee android studio. Thanks

A: Use id("kotlinx-serialization") in the build.gradle.kts(Module:app)

A: Be sure that the settings.gradle file contains all the plugin repositories that you should have:
pluginManagement {
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
    }
}
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
    }
}

Also you may need to downgrade the kotlin version or upgrade the gradle version, there's a compatibility matrix of versions compatible between them.
https://docs.gradle.org/current/userguide/compatibility.html


text:
Q: .NET - Exception when sending email I'm currently developing a website with a contact form.
When the contact form is filled, an email must be sent to the person who have inserted this.

*

*I'm using SMTP.

*I'm using a shared email server.
My code looks like:
Task.Factory.StartNew(() =>
        {
            try
            {

                var smtpClient = new SmtpClient(SmtpHost, Port)
                {
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new NetworkCredential(From, Password)
                };

                using (smtpClient)
                {
                    using (MailMessage mailMessage = new MailMessage(From, From, "test", "test"))
                    {
                        smtpClient.Send(mailMessage);
                    }
                }
            }
            catch (Exception e)
            {

            }
        });

Everytime, I receive the following exception:

[System.Net.Mail.SmtpException] = {"Transaction failed. The server response is: 5.7.1 Recipient address rejected: Authentication required"}
      bij System.Net.Mail.RecipientCommand.CheckResponse(SmtpStatusCode statusCode, String response)
     bij System.Net.Mail.RecipientCommand.Send(SmtpConnection conn, String to, String& response)
     bij System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)
     bij System.Net.Mail.SmtpClient.Send(MailMessage message)

In the code example I try to send an email to the same address as the sender. I already tried to send an email to my personal email accounts and this also fails.
Anyone knows what is going wrong here? I didn't found solutions on google/stackoverflow.
A few months ago, I developed a website with the same smtp host (but other domain) and this is still working fine..
Thank you.

A: The only thing I saw in the web is problem with firewall so try to turn it of and try again to execute the application.

A: Please check you mail configuration settings .Make sure your given port no is correct.


text:
Q: Cython vs. Pure Python with Memoryviews I'm just starting to learn Cython and I'm confused on an issue. If you look at the main tutorial they have examples that show a "Pure Python" mode vs. "Cython" mode. The pure python mode uses the PEP-484 type hints whereas the Cython mode introduces new keywords that aren't parsed by the python interpreter like cdef and you have to be sure to compile the .pyx file in one of the approved ways.
But I want to interact with NumPy arrays and algorithms. When I go to the most recent page on using  Cython for NumPy Users there seems to be no mention of pure python modes. I don't know if that's because it's impossible with the memoryview approach detailed there or if the documentation is out of date. If I want to use NumPy arrays should I just constrain myself to using the Cython-specific syntax or is there some way of using the pure python mode as well that I'm not seeing?


text:
Q: event using for autoupdate I have this small code on c# .NET which publish tweets and shows timeline of twitter using tweetinvi . And I'd like to autoupdate timeline whenever the tweet is sent. Can anyone advice how to do it with event? Thanks for answers.
private void button1click(object sender, EventArgs e)
    {
        if (richTextBox1.Text != "")
        {
            Tweet.PublishTweet(richTextBox1.Text);
            MessageBox.Show("Your tweet was sent!", "Important Message");

        }
        else
        {
            MessageBox.Show("You need to write something!", "Important Message");
        }
    }

    private void Timeline_GetHomeTimeline(object sender, EventArgs e)
    {

    var loggedUser = User.GetLoggedUser();
        string x = "";
        var homeTimelineTweets = loggedUser.GetHomeTimeline();
        foreach (var tweet in homeTimelineTweets)
        {
            x += tweet.Text + Environment.NewLine;
        }
        richTextBox2.Text = x;

    }

A: First of all please note that it is a very bad practice to make several calls User.GetLoggedUser();. The reason being that the endpoint is limited to 15 requests every 15 minutes (1 per minute).
If the user happens to publish more than 15 tweets in 15 minutes, your code will break.
Now you have multiple solutions to solve the problem, but the best one is the UserStream (solution 1).
Solution 1
I would suggest to add the following code in the Initialized event.
var us = Stream.CreateUserStream();
us.TweetCreatedByMe += (sender, args) =>
{
    // Update your rich textbox by adding the new tweet with tweet.Text
    var tweetPublishedByMe = args.Tweet;

    // OR Get your timeline and rewrite the text entirely in your textbox
    var userTimeline = Timeline.GetHomeTimeline();
    if (userTimeline != null)
    {
        // foreach ...
    }
};

us.StartStreamAsync();

Solution 2
If you do not need to reload your Timeline each time the user publishes a tweet but you do need the new tweet to be displayed use the following solution.
var tweet = Tweet.PublishTweet("hello");
if (tweet != null)
{
    // Update your rich textbox
}

Solution 3
Update your timeline if a tweet has been published successfully.
var tweet = Tweet.PublishTweet("hello");
if (tweet != null)
{
    var userTimeline = Timeline.GetHomeTimeline();
    if (userTimeline != null)
    {
        // foreach ...
    }
}

NOTE Please note that I have never had the need to retrieve the LoggedUser at any point. Most of the time a LoggedUser should be retrieved once and then used across your app.
Also please note that I am the main developer of Tweetinvi.


text:
Q: Joint significance testing w/ large samples long time listener, first time caller. Unfortunately I can't show code as the computer the analysis is done on has rather tight security.
I need to test for joint significance in a logit model that includes an interaction term. Normally I would use a likelihood ratio test, but every time I do it results in: Pr(>Chisq) < 2.2e-16. This is even if I try using random numbers as an IV. If I decrease the sample size, I can control the likelihood ratio. However, choosing a sample based on the test statistic seems like a faux-pas.
Can anybody give me some insight into what is going on / suggest a different way to test my model with a large sample (>700,000 obs)


text:
Q: how does oplog collection work in mongodb? in our application we use transaction. The primary and secondary node are on the same machine, there is no requirement for an high availability. Sometimes we have a transaction that runs over many mongodb update queries. The data that be updated can over 5 Gb and that leads to the problem that the oplog collection limit will reached. It ends with a Exception "MongoCommandException: Command update failed: Transaction has been aborted" Currently it is set to 10 Gb but i have to set it to over 100 Gb to make an successful transaction.
The application is used by one user at one time.
Can anybody explain me (or link to explaination :) ) why it is required to increase the limit so much? Or how can i avoid that the limit will reach? Why the collection cant grow dynamically for example?

A: Few points:

*

*Running a two node replica set is useless. You should remove the secondary so you end up with only a single node replica set

*OpLog is a capped collection (per node, stored in local database), so the size is changeable

*Running that big multi document transaction sounds fishy, you should really think about what exactly are you doing and do you really need a transaction? What kind of operations are you doing (inserts/updates/replace?)


text:
Q: Create a simple OpenCV pipeline with GStreamer I have a pipeline to stream images over UDP

fps = 20
width = 500
height = 500

out_send = cv2.VideoWriter(
        "appsrc ! videoconvert ! "
        "video/x-raw,format=I420 ! "
        "jpegenc ! rtpjpegpay !"
        "udpsink host=127.0.0.1 port=5000",
        cv2.CAP_GSTREAMER, 0, fps, (width, height), True
    )

while True:
    frame = np.random.randint(255, size=(height, width, 3), dtype=np.uint8)

    out_send.write(frame)

    time.sleep(0.05)

This starts the pipeline but I am unable to receive using the following pipeline. The streaming wont begin, just hangs.
gst-launch-1.0 udpsrc port=5000 ! application/x-rtp,media=video,payload=26,clock-rate=90000,encoding-name=JPEG ! rtpjpegdepay ! jpegdec ! videoconvert ! queue ! xvimagesink

However if the frame is captured from webcam as below
cap_send = cv2.VideoCapture(0)

fps = int(cap_send.get(cv2.CAP_PROP_FPS))
width = int(cap_send.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap_send.get(cv2.CAP_PROP_FRAME_HEIGHT))

while True:
    ret, frame = cap_send.read()

    if not ret:
        break

    out_send.write(frame)

Then the receiving pipeline starts and streams without any issues.
In both cases I see the following message on the receiving end
Setting pipeline to PAUSED ...
Pipeline is live and does not need PREROLL ...
Pipeline is PREROLLED ...
Setting pipeline to PLAYING ...
New clock: GstSystemClock

Edit:
I ran the receiving pipeline with GST_DEBUG=3 and see the following output
gst_rtp_jpeg_depay_process:<rtpjpegdepay0> discarding data packets received when we have no header

This only happens if the sending pipeline uses raw images / numpy arrays as above.
What am I doing incorrect here. Very new to gstreamer and need some help
Goal: To stream images generated in opencv, asynchronously.

A: @Micka pointed me in the right direction.
The issue was with frame sizes. I have tried MJPEG and H264 and both need frame sizes (width/height) that are multiples of 8. Gstreamer will round them up to the closest 8th multiple. If the height is rounded then there is jitter seen at the end of the frame. If the width is rounded then a green screen is seen at the receiver.


text:
Q: AxMsRdpClient9 Dismiss login dialog I am writing rdp client using c#. Simple example:
        AxMsRdpClient9NotSafeForScripting c = new AxMsRdpClient9NotSafeForScripting();
        Form1.Controls.Add(c);
        c.Server = s.ip;
        c.UserName = s.pass;
        c.AdvancedSettings9.ClearTextPassword = s.pass;
        c.Connect();

So, when I try to connect to Win7 or less it works perfect, but when I try to connect to Win Server 2012, rdpclient doesn't connect and doesn't return any errors. Connecting to win server works when I use this option:
c.AdvancedSettings9.EnableCredSspSupport = true;

but with this option, when I try to connect to win server with invalid credentials it shows dialog with login\pass fields, that I can't dissmiss programmatically, I have to do it "by hand".
So question is: how can I connect to win server without
c.AdvancedSettings9.EnableCredSspSupport = true;

or how can I dissmiss login\pass dialog in code?

A: The solution is to set AllowPromptingForCredentials to false.

A: Here are the additional details to finish @davyjohnes answer:
....
Form1.Controls.Add(c);
var ocx = c.GetOcx() as MSTSCLib.IMsRdpClientNonScriptable5;
ocx.AllowPromptingForCredentials = false;
c.Server = s.ip;
....


text:
Q: Why can't I see my jQuery UI animation? I have an element that's going into a slideshow, and when the slide comes in, this element uses the jQuery UI effect explode to appear.
$e.show('explode', {}, 1000);

When I first ran it, I didn't see the element appear at all. So I thought "Oh, it must be z-index" and set the element's z-index to 10 and made sure it had position defined. (The slide's z-index is 5)
This made the image show up after the effect is complete. I hid the slide to test, and sure enough, the animation was happening behind the slide, seemingly with a lower z-index.
Why can't I see the element until after the animation?

A: What's Happening
When certain elements are animating with jQuery UI, depending on the effect, the element itself may be cloned. The element that you are manipulating ($e) is actually hidden, and not part of the DOM at the time of animation, so your CSS rules are useless here. Some of the rules are applied to the cloned element with jQuery, however, z-index is not one of them.
Fix it With CSS Animations
I suggest using CSS Animations which directly manipulate your element, and have no need to clone the element. Though this makes effects like explode slightly more complex, not only are you maintaining your CSS rules, but CSS animations make for a huge performance gain over jQuery UI animations. (jQuery UI applies each 'step' of the animation individually, meaning many repaints). A limitation with this, however, is cross-browser compatibility, as it looks like IE is still not up to par with this.
Fix it With z-index
If you're hell-bent on using jQuery UI for your animations, or can't risk the lack of cross-browser compatibility, there is still hope. In my tests, the 'cloned' element gets a class added to it temporarily of ui-effects-explode. It seems that most jQuery UI animations that require cloning the original element apply a class with similar syntax (ui-effects-*).
Your catch-all to save yourself the frustration on individual effects is to make a CSS-rule like the following:
[class^=ui-effects] {
    z-index: 10;
}

Where ^= means 'begins with'. This will apply the z-index to any cloned elements within jQuery UI namespace, and should resolve your issue.


text:
Q: How to export data using reports from SFDC programmatically? We have an issue where we have to manually click Export Report on SFDC reports though the UI on many reports. These reports have several filters and filter logic such as "(1 or 2) AND (4 AND 1)" and other filters such as ("Status=Completed AND User="First_Last") OR (CloseDate>=TODAY), etc.
Ideally, we want to automate the process of running the report, exporting the data as a xls (excel) format, and saving to a particular location.
The idea was to create a java class that pulls a selective list of reports that we can export into an XML file. Then another java class can then use the XML file to find the filter criteria and logic that can be used to build a SOQL query dynamically so that if in Salesforce the report criteria or filters are updated, we can easily have the java class update without manually updating (basically trying to prevent the hardcoding of soql query).
I am needing assistance with trying to get the appropriate API to use so that when the selective list of reports are pulled, i can parse through the XML file and easy create an Excel file for each report that contains the filter logic and criteria. I imagine i can use the ANT migration tool to generate the xml files.
Any thoughts?

A: You can get the report filter details by passing the folder and report name from metadata api.
Here what I tried in my developer org:
1) Created a report All_Leads inside the folder Sample_Folder with filter condition as created date between 03-15-2015 and 03-31-2016.

Filter conditions that I gave for the report:

2) Created a class named Metadataservice in my developer org and copied the contents from here
3) Added the Remote site settings for my org instance and then executed the below code in anonymous window by passing the folder and report name:
MetadataService.MetadataPort service = new MetadataService.MetadataPort();
service.SessionHeader = new MetadataService.SessionHeader_element();
service.SessionHeader.sessionId = UserInfo.getSessionId();
MetadataService.Report report =
    (MetadataService.Report) service.readMetadata('Report',
                                                  new String[] {'Sample_Folder/All_Leads' }).getRecords()[0];
System.debug(report);

4) Below is the debug log of the response from the metadata call and we can see that Start date and End date from the log are matching with what I entered in the UI.
timeFrameFilter=ReportTimeFrameFilter:
        [apex_schema_type_info=(http://soap.sforce.com/2006/04/metadata, true, false),
        dateColumn=CREATED_DATE,
        dateColumn_type_info=(dateColumn, http://soap.sforce.com/2006/04/metadata, null, 1, 1, false),
        endDate=2016-03-31 00:00:00,
        endDate_type_info=(endDate, http://soap.sforce.com/2006/04/metadata, null, 0, 1, false),
        field_order_type_info=(dateColumn, endDate, interval, startDate), interval=INTERVAL_CUSTOM,
        interval_type_info=(interval, http://soap.sforce.com/2006/04/metadata, null, 1, 1, false),
        startDate=2015-03-01 00:00:00,
        startDate_type_info=(startDate, http://soap.sforce.com/2006/04/metadata, null, 0, 1, false)],
    timeFrameFilter_type_info=(timeFrameFilter, http://soap.sforce.com/2006/04/metadata, null, 0, 1, false),
    type=Report,
    type_att_info=(xsi:type),
    userFilter=null,
    userFilter_type_info=(userFilter, http://soap.sforce.com/2006/04/metadata, null, 0, 1, false)]

But If you follow this approach there is going to be lot of xml processing in your java application to parse the values.
I guess there might be other elegant solutions than this for what you are trying to do but I was intrigued by your question and wanted to see if that is possible by metadata api.


text:
Q: How to fix apache restart We've setup Uptime Robot and noticed that one of our server apache service has gone away and restarted, i've found error logs as shown below. any idea what should i do with server configuration i have fully access to server
Linux version : CentOS 7.1
[Sun Mar 18 03:38:57.748759 2018] [auth_digest:notice] [pid 8715] AH01757: generating secret for digest authentication ...
[Sun Mar 18 03:38:57.749478 2018] [lbmethod_heartbeat:notice] [pid 8715] AH02282: No slotmem from mod_heartmonitor
[Sun Mar 18 03:38:57.757017 2018] [ssl:warn] [pid 8715] AH02292: Init: Name-based SSL virtual hosts only work for clients with TLS server name indication support (RFC 4366)
[Sun Mar 18 03:38:57.796338 2018] [mpm_prefork:notice] [pid 8715] AH00163: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips mod_fcgid/2.3.9 PHP/5.4.16 SVN/1.7.14 configured -- resuming normal operations
[Sun Mar 18 03:38:57.796360 2018] [core:notice] [pid 8715] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND'
PHP Warning:  Module 'mcrypt' already loaded in Unknown on line 0
PHP Warning:  Module 'mongo' already loaded in Unknown on line 0
PHP Warning:  Module 'mcrypt' already loaded in Unknown on line 0
PHP Warning:  Module 'mongo' already loaded in Unknown on line 0
PHP Warning:  Module 'mcrypt' already loaded in Unknown on line 0
PHP Warning:  Module 'mcrypt' already loaded in Unknown on line 0
PHP Warning:  Module 'mongo' already loaded in Unknown on line 0
PHP Warning:  Module 'mongo' already loaded in Unknown on line 0
PHP Warning:  Module 'mcrypt' already loaded in Unknown on line 0
PHP Warning:  Module 'mongo' already loaded in Unknown on line 0
PHP Warning:  Module 'mcrypt' already loaded in Unknown on line 0
PHP Warning:  Module 'mongo' already loaded in Unknown on line 0
[Sun Mar 18 03:39:01.492462 2018] [mpm_prefork:notice] [pid 8715] AH00171: Graceful restart requested, doing restart
PHP Warning:  Module 'mcrypt' already loaded in Unknown on line 0
PHP Warning:  Module 'mongo' already loaded in Unknown on line 0
[Sun Mar 18 03:39:12.880639 2018] [fcgid:error] [pid 9246] FastCGI process 9250 still did not exit, terminating forcefully
[Sun Mar 18 03:39:12.880733 2018] [fcgid:error] [pid 9246] FastCGI process 9252 still did not exit, terminating forcefully
[Sun Mar 18 03:39:12.880750 2018] [fcgid:error] [pid 9246] FastCGI process 9254 still did not exit, terminating forcefully
[Sun Mar 18 03:39:12.880755 2018] [fcgid:error] [pid 9246] FastCGI process 9256 still did not exit, terminating forcefully
[Sun Mar 18 03:39:12.880760 2018] [fcgid:error] [pid 9246] FastCGI process 9257 still did not exit, terminating forcefully
[Sun Mar 18 03:39:12.880765 2018] [fcgid:error] [pid 9246] FastCGI process 9259 still did not exit, terminating forcefully
[Sun Mar 18 03:39:12.880771 2018] [fcgid:error] [pid 9246] FastCGI process 9297 still did not exit, terminating forcefully
AH00112: Warning: DocumentRoot [/home/multiwordpress/public_html/uae] does not exist
[Sun Mar 18 03:39:14.014337 2018] [auth_digest:notice] [pid 8715] AH01757: generating secret for digest authentication ...
[Sun Mar 18 03:39:14.015086 2018] [lbmethod_heartbeat:notice] [pid 8715] AH02282: No slotmem from mod_heartmonitor
[Sun Mar 18 03:39:14.022805 2018] [ssl:warn] [pid 8715] AH02292: Init: Name-based SSL virtual hosts only work for clients with TLS server name indication support (RFC 4366)
[Sun Mar 18 03:39:14.062739 2018] [mpm_prefork:notice] [pid 8715] AH00163: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips mod_fcgid/2.3.9 PHP/5.4.16 SVN/1.7.14 configured -- resuming normal operations
[Sun Mar 18 03:39:14.062761 2018] [core:notice] [pid 8715] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND'
PHP Warning:  Module 'mcrypt' already loaded in Unknown on line 0
PHP Warning:  Module 'mongo' already loaded in Unknown on line 0
PHP Warning:  Module 'mcrypt' already loaded in Unknown on line 0
PHP Warning:  Module 'mongo' already loaded in Unknown on line 0
[Sun Mar 18 03:39:17.317788 2018] [mpm_prefork:notice] [pid 8715] AH00171: Graceful restart requested, doing restart
[Sun Mar 18 03:39:28.702785 2018] [fcgid:error] [pid 9947] FastCGI process 9951 still did not exit, terminating forcefully
[Sun Mar 18 03:39:28.702961 2018] [fcgid:error] [pid 9947] FastCGI process 9957 still did not exit, terminating forcefully
AH00112: Warning: DocumentRoot [/home/multiwordpress/public_html/uae] does not exist
[Sun Mar 18 03:39:29.831593 2018] [auth_digest:notice] [pid 8715] AH01757: generating secret for digest authentication ...
[Sun Mar 18 03:39:29.832364 2018] [lbmethod_heartbeat:notice] [pid 8715] AH02282: No slotmem from mod_heartmonitor
[Sun Mar 18 03:39:29.839686 2018] [ssl:warn] [pid 8715] AH02292: Init: Name-based SSL virtual hosts only work for clients with TLS server name indication support (RFC 4366)
[Sun Mar 18 03:39:29.877180 2018] [mpm_prefork:notice] [pid 8715] AH00163: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips mod_fcgid/2.3.9 PHP/5.4.16 SVN/1.7.14 configured -- resuming normal operations
[Sun Mar 18 03:39:29.877201 2018] [core:notice] [pid 8715] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND'


text: Q: How to retrieve image from mongodb grid_fs using carrierwave In my rails application I am uploading image using carrierwave to mongoid grid_fs. I am using my remote system "192.xxx.xx.xx" as my mongodb server. While retrieving image is not displayed. If i use my local system as mongodb then its displaying fine.


text:
Q: Obtaining formula of $E[X^T A X B X^T CX]$ for Gaussian $X$ Suppose $X$ is an $m\times n$ random matrix where rows are I.I.D. samples $x$ of $n$-dimensional Gaussian. The code at the end of the post verifies a candidate (incorrect) formula for the following expression in terms of $H=E[xx']$ (this parameterization simplified related formula considerably compared to $\mu,\Sigma$ parameterization). What's the correct formula?
$$E[X^T A X B X^T CX]\approx m(m-1)HBH$$
There's this detailed answer on computing arbitrary moments of Gaussian distributions.
Alternatively there's this notebook which automatically derives non-central Wick's Theorem in summation form by doing the following:

*

*MomentConvert[Moment[{1, 1, 1, 1}], "Cumulant"]

*Set cumulants of order 3 and 4 to zero

*MomentConvert back

A similar approach may be feasible for the question at hand, but a bit of a programming challenge!
d = 3;
x1 = Array[xx1, d];
x2 = Array[xx2, d];
X = {x1, x2};

SeedRandom[1];
sigma = DiagonalMatrix[RandomInteger[{1, 10}, {d}]];
mu = RandomInteger[{1, 10}, {d}];
mu = ConstantArray[0, {d}];

H = sigma + Outer[Times, mu, mu];
dist = MultinormalDistribution[mu, sigma];
EX[expr_] :=
  Expectation[
   expr, {x1 \[Distributed] dist, x2 \[Distributed] dist}];
m = Length[X];
Unprotect[C];
{A, C} = RandomInteger[{-5, 5}, {2, m, m}];
B = RandomInteger[{-5, 5}, {d, d}];

Print["Check passed: ",
 EX[X\[Transpose] . A . X . B . X\[Transpose] . C . X] ==
  m (m - 1) H . B . H]

Related unanswered question on stats.SE

A: Note: Many thanks to @JimB for pointing out a mistake in an earlier version.
This question can be worked out by pencil and paper.
Special case. Let me first assume that $Y$ is a rectangular matrix whose entries are i.i.d. and standard normal, $N(0,1)$. Then:
$$
E[Y^TAYBY^TCY]
=
(\text{tr}  A)(\text{tr}  C) B + B^T \text{tr} (A^T C) + \text{tr} (B) \text{tr} (AC) \mathbb{1}
$$
The proof goes like this:
$$
E[Y^TAYBY^TCY]_{ij}
= \sum_{a,b,c,d,e,f} E[Y_{ai} A_{ab} Y_{bc} B_{cd} Y_{ed} C_{ef} Y_{fj}]
= \sum_{a,b,c,d,e,f} A_{ab} B_{cd} C_{ef} E[Y_{ai} Y_{bc} Y_{ed} Y_{fj}]
$$
Using Isserli's theorem this is equal to
$$
= \sum_{a,b,c,d,e,f} A_{ab} B_{cd} C_{ef}
(\delta_{ab} \delta_{ic} \delta_{ef} \delta_{dj} + \delta_{ae} \delta_{id} \delta_{bf} \delta_{cj}
+ \delta_{af} \delta_{ij} \delta_{be} \delta_{cd})
$$
where $\delta$ is the Kronecker symbol. It is now just a matter of checking what is contracted with what, for example in the first term we have $A_{ab} \delta_{ab}$ which gives $\text{tr}  A$, and so on. The result follows.
By a similar calculation:
$$
E[YAY] = E[Y^T A Y^T] = A^T
\qquad
E[YAY^T] = E[Y^T AY] = \text{tr}(A) \mathbb{1}
$$
General case (but still zero mean). Now assume that $Z = YK$ where $K$ is some constant matrix, and denote $H = K^T K$. Then
$$
E[Z^TAZBZ^TCZ]
=
(\text{tr}  A)(\text{tr}  C) HBH + HB^T H \text{tr} (A^T C) + \text{tr} (BH) \text{tr} (AC) H
$$
The proof is, using the special case above:
$$
E[Z^TAZBZ^TCZ]
=
E[K^TY^TAYKBK^T K^T Y^TCYK]
=
K^T E[Y^TAY(KBK^T) Y^TCY]K
=
(\text{tr}  A)(\text{tr}  C) K^TKBK^TK + K^T KB^T K^TK \text{tr} (A^T C) + \text{tr} (KBK^T) \text{tr} (AC) K^T K
$$
and then replacing $K^T K = H$.
By a similar calculation:
$$
E[ZAZ] = A^T H
\qquad
E[Z^T A Z^T] = H A^T$$
$$
E[ZAZ^T] = \text{tr}(AH) \mathbb{1}
\qquad
E[Z^T AZ] = \text{tr}(A) H
$$
General case (non-zero mean). Suppose $M$ is the mean, $E[X] = M$. This is equivalent to $X = Z + M$ where $Z$ is as before.
Then
$$
E[X^TAXBX^TCX]\\
=
(\text{tr}  A)(\text{tr}  C) HBH + HB^T H \text{tr} (A^T C) + \text{tr} (BH) \text{tr} (AC) H\\
+ \text{tr}(A) HBM^TCM\\
+ H (AMB)^T CM\\
+ \text{tr}(BH) M^TACM\\
+ \text{tr}(AMBM^TC) H \\
+ M^TA (BM^TC)^T H\\
+ \text{tr}(C) M^TAMB H \\
+ M^TAMBM^TCM
$$
The proof goes like this (expectation values of terms that are linear or cubic in $Z$ are  equal to zero):
$$
E[X^TAXBX^TCX]\\
=
E[Z^TAZBZ^TCZ]\\
+ E[Z^TAZBM^TCM]\\
+ E[Z^TAMBZ^TCM]\\
+ E[M^TAZBZ^TCM]\\
+ E[Z^TAMBM^TCZ]\\
+ E[M^TAZBM^TCZ]\\
+ E[M^TAMBZ^TCZ]\\
+ E[M^TAMBM^TCM]\\
=
E[Z^TAZBZ^TCZ]\\
+ E[Z^TAZ]BM^TCM\\
+ E[Z^T(AMB)Z^T]CM\\
+ M^TAE[ZBZ^T]CM\\
+ E[Z^T(AMBM^TC)Z]\\
+ M^TAE[Z(BM^TC)Z]\\
+ M^TAMBE[Z^TCZ]\\
+ M^TAMBM^TCM
$$
Now it is just a matter of plugging in the results given for $Z$.
Note. It would be easy to make a mistake in such a calculation, so use at your own risk :)

A: This is just an extended comment in that one can find the expectation much quicker by using replacement rules rather than using Expectation.  (I understand that the real answer must be in matrix terms.)
d = 3; (* Dimensions *)
m = 2; (* Number of independent samples *)
X = Table[x[i, j], {i, m}, {j, d}];

H = DiagonalMatrix[Range[d]];  (* Covariance matrix *)
dist = MultinormalDistribution[H];

A = Array[a, {d, d}];
W = X\[Transpose] . X . A . X\[Transpose] . X;
expectations = {x[i_, j_]^3 -> 0, x[i_, j_]^4 -> 3 j^2, x[i_, j_]^2 x[i_, k_]^2 -> j k,
  x[i_, j_]^2 -> j, x[i_, j_] -> 0};
AbsoluteTiming[(X\[Transpose] . X . A . X\[Transpose] . X // Expand) /. expectations;]
(* {0.0028874, Null} *)

It takes 1.4 seconds using Expectation with your code.
The expectations in the replacement list are found using Moments and recognizing that each random term (after Expand) is a product of powers of 1, 2, or 3 elements of the $X$ matrix such as $x_{1,1}^2 x_{1,3}^2 and $x_{2,1} x_{2,3}^3.  And the expectation of any of those products with any term with an odd power is zero.
So with $d=3$ we have the expectation of $x_{1,1}^2 x_{1,3}^2$ being
Moment[dist, {2, 0, 2}]
(* 3 *)

For $x_{2,2}^4$ the expectation is
Moment[dist, {0, 4, 0}]
(* 12 *)

And the replacement list was constructed by noticing patterns.  (Unfortunately the order of the replacements is important as I need to replace x[i, j]^2 before replacing x[i, j] with zero.)


text:
Q: What procedure was Alice going to take in Once Upon A Time In Wonderland? In Once Upon A Time in Wonderland, Alice wanted to forget about Cyrus by undergoing a special procedure. But what was it? Was it ever revealed?
Answers are appreciated.

A: I was under the impression that the procedure in question was a lobotomy, though perhaps that isn't clear if you aren't already familiar with it. Assuming she'd survived the procedure I'm not sure if it would have taken away her memories of Cyrus anyway, since they were real rather than - as everybody else believed - delusions.
From Wikipedia:

Lobotomy (Greek: λοβός – lobos: "lobe (of brain)"; τομή – tomē: "cut/slice") is a neurosurgical procedure, a form of psychosurgery, also known as a leukotomy or leucotomy (from the Greek λευκός – leukos: "clear/white" and tome). It consists of cutting or scraping away most of the connections to and from the prefrontal cortex, the anterior part of the frontal lobes of the brain.


text:
Q: Why is Light an EM wave? Well, the definition of electromagnetic waves in a couple of textbooks is stated to be, 'A wave produced or resulting from the accelerated motion of a charged particle'. My question is straightforward- If it is so, light should not be an EM wave, since photons are not charged. I know that light consists of oscillating electric and magnetic fields,but then there's either something wrong with the definition or my understanding (which is much more probable). Where am I going wrong, folks?

A: There are two main ways for photons to be emitted:

*

*Accelerating charges (as you have mentioned); and

*Spontaneous emission when an excited electron drops to a lower energy state.

Electromagnetic waves are defined as propagating waves consisting of orthogonal electric and magnetic fields satisfying Maxwells equations. By this definition, light IS an electromagnetic wave. As I mentioned above, acceleration of a charged particle is not the only way to produce such radiation.
Also just to be clear, photons have no rest mass and no charge. Their energy is purely kinetic. In terms of accelerating charges, the accelerating charge such as an electron or proton induces the EM wave. By your wording you are suggesting that the photon is oscillating and producing the EM wave which is incorrect. The photon can be thought of as discrete packets of energies which are a result of the accelerating electron/proton.


text:
Q: How Many Ways to Construct Trees With No More Than 4 Connections per Vertex. I am a high school student (so sorry if my thinking is way off) with a problem related to chemistry essentially dealing with the number of ways you can arrange carbon atoms in a alkane. I saw that this was related to mathematical trees and so I started working towards creating a function that will return the number of unique structures you can make given a certain number of carbon atoms. In math speak this translates to: Given $n$ vertices how many ways can you construct unique trees (no rotational, reflectional or translational symmetry) so that no vertex has more than four connections.
Note:

The first image is not a branch because in order to be a branch there must be at least three connections, so that there is more than one path to follow if you were travelling along the chain. My thinking was to start by defining a fixed length $c \leq n$ and determine how many ways I can branch off of $c$ so that in total there are $n$ vertices without creating a chain greater than $c$ by these branches.
Eg. if $c=n$ then there is only one way to construct a unique tree (obviously).
if $c=n-1$ then there is $\left\lceil\frac{n}{2}\right\rceil$ ways to construct a unique tree.
The idea I had was to continue this process until some limit where you cannot branch off of $c$ with $n-c$ vertices and maintain the maximum continuous chain length $c$.
The formula (which is still missing something) is:
$$z\left(n\right) = 1 + \sum_{k=1}^{a_n} \sum_{i=0}^{k-\left\lfloor\frac{k}{2}\right\rfloor} \left\lceil \frac{n-k}{2} \right\rceil - \left(k-i\right) + \left(k-1\right)\left[ {{n-(k+2)}\choose{k-i}} - {{\left\lceil \frac{n}{2} \right\rceil - (k+2)}\choose{k-i}}\right]$$.
Where $a_n$ is a sequence defined by the smallest chain $c$ that can exist while maintaining the maximum length of $c$, $k$ is the difference $n-c$ and $i$ represents the idea of moving a branch vertex onto the other connection on the main chain vertex in order to lower the length of the chain it forms. The function Should return $(1,1,1,2,3,5,9,18)$ for the first 8 inputs.
As I said before the formula is wrong, but I don't know how to include the information I am missing. Any input would be appreciated, thank you!


text:
Q: What type of click should I use in my web app? Background:
We are developing a web application that includes charts. Currently one can left-click on a chart point to zoom/drill-down into that section of the data. We are adding some other functionality that allows users to add meta data to data points. I know users will be exclusively using Mozilla, though I shy away from anything that limits to a single browser. No js libraries please.
Question:
What type of "click should I use for adding metadata to an element that already has a left-click (hyper-link)?
Some alternatives I've brainstormed:

*

*capture oncontext menu of right-click (this is abhorrent to me)

*double-click

*ctrl-click

*make left-click open a context-ish menu that has the existing left-click as well as new functionality

Are there any conventions for these? What would you find most intuitive?

A: Rather than having a single click zoom in, why not use a double click instead? Personally, I find that to be more intuitive when viewing something not to mention it being a fairly common standard.

A: Put some kind of affordance (maybe a small icon) next to the link that responds to a single click. Else, go with a right click.

A: Try to meet the users expectations.  What do they expect to happen when they single-click, double-click, etc...  i.e. How do other applications handle that action?

A: I would change your idea from a type of click to a specific mode in the chart.
The problem with a special type of click is that there is no affordance for the capability that you want to provide. There is no apparent thing in the user interface that says, "The user is able to add meta-data to data points." Users would only be able to learn about this through trial-and-error or training. Or, perhaps, a note on your app that says, "Ctrl-click to add meta-data." But that is not elegant.
A better approach might be to have a mode button. I'm picturing a toolbar. Think about Microsoft Word, where selecting the Highlight tool turns your pointer into a highlighter. In highlight mode, you can click and drag to highlight text. You can then switch to other modes, like the default text mode. Perhaps you should have an "Add Metadata" mode.
In general for UI design, if you're trying to do something that seems non-standard, think about how existing products have solved the problem. How does Microsoft Excel let you add information to a data point in a chart, for example? Maybe it doesn't. But are there other products that do?

A: My vote is the "make left-click open a context-ish menu that has the existing left-click as well as new functionality". That needs the least amount of documentation to explain to users how to use. And for a web app usually users expect and read zero documentation.


text:
Q: My dataset as "?" values. How can I find all the missing values with R? I'm new to R and I'm trying to find all the missing values in my data set. I'm using R and I tried the is.na function and it didn't work. Missing entries in my dataset have a "?"

A: df[df=="?"] <- NA


text:
Q: VBA - Excel Delay and Forcestop a macro at opening I got a file in task scheduler which has a macro that triggers opening like this:
Private Sub Workbook_Open()
Call OpenRunMacroandCopy
End Sub

A bit like a house alarm, I'd like to have this macro wait before executing the Call for a set duration so I could use ctrl+Break which i believe would interrupt execution and let me read the file and close it without OpenRunMacroandCopy running at all.
I know of Application.Wait and Sleep but they don't work here and i do not know why.
I also used Application.OnTime Now + 5 / 1440, "OpenRunMacroandCopy" which does seem to make it wait but ctrl+Break gives me no notification and i've had that macro run anyway so i'm not sure interruption is working? When I use ctrl+Break on an infinite loop macro i do get an error window which is quite nice so i definitely know i have it stopped.
Got an idea, or a more purposeful way to make that happen?


text:
Q: Can peripheral advertisement/broadcasting be reactivated in the background? From what I understand, once an app is terminated by iOS for memory use, my app will stop advertising as a peripheral (even if I've enabled the peripheral in the background).
Is it possible to reactivate the peripheral advertisement when my app is woken in the background for a periodic server update, or in the case of using Significant Location Changes where the app is woken in the background every time the phone moves to a new location?


text:
Q: Finding $\sum_{i=0}^{\log_2\log_2n} n^{\frac{2^{i+1}-1}{2^i}}$ I have a task on finding runtime complexity of an algorithm. I worked out the following summation expression, unsuccessfully tried to get a result from Wolfram Alpha, have no idea in what direction I should search.
$$\sum_{i=0}^{\log_2\log_2n} n^{\frac{2^{i+1}-1}{2^i}}$$

A: Rewriting as
$$n^2\sum_{i=0}^{\log_2 \log_2 n} n^{-2^{-i}}$$
we can find lower and upper bounds by recognizing that
$$n^{-1} < n^{-2^{-i}} < n^{\frac{-1}{\log_2 n}} = n^{-\log_n 2} = 2^{-1}$$
which implies
$$ n \log_2 \log_2 n < n^2\sum_{i=1}^{\log_2 \log_2 n} n^{-2^{-i}} < \frac{1}{2}n^2 \log_2 \log_2 n$$


text:
Q: Proving that $f(x)=c \cdot e^x$ is the only function such that $f'(x)=f(x)$
Possible Duplicate:
Proof that $\exp(x)$ is the only function for which $f(x) = f'(x)$

Here's a question I got for homework:

Let f a differentiable function such that $f(x)=f'(x)$ for all $x$.
  Prove that there exist a $c \in \mathbb{R}$ such that $f(x) = c \cdot
 e^x$
Hint: notice $\dfrac{f(x)}{e^x}$

So, as it turns out this hint was not enough.
Any more hints? Thanks!

A: HINT:
What's the derivative of $\dfrac{f(x)}{e^x}$ (With the quotient rule, perhaps it's easier to see). Then what does that mean?

A: It's a first-order linear ordinary differential equation.
To put it in a simple way, let $y=f(x)$.
Then
$$
         \frac{dy}{dx}=y.
$$
Hence,
$$
         \frac{dy}{y}=dx,
$$
(if $y$ doesn't equal $0$).
Integrating in both sides, we get
$$
         \ln|y|=x+c_1,
$$
where $c_1$ is a constant.
Therefore,
$$
         |y|=e^{x+c_1}=e^{c_1}*e^x.
$$
Let $|c|=e^{c_1}$, then we get
$$
         y=c*e^x.
$$
If $y=0$, then it of course satisfies the condition.


text:
Q: In a subset $Y=\{(x,y,z)\in\mathbb{R}^3: x^2+2y^2+3z^2=6\}$ of a metric space show that a Cauchy sequence converges Let $(\mathbb{R}^3 ,||)$ a metric space and $Y=\{(x,y,z)\in\mathbb{R}^3: x^2+2y^2+3z^2=6\}$
i) Show that each sequence Cauchy of elements of $Y$ converges to a point of $Y$.
ii) Show that each sequence of elements of $Y$ has a convergent sequence
I think for the first part Ii have to show that $Y$ is a closed set but I am not sure how to show it.
For the second par, if I show that the sequence is bounded, then I think that it has a convergent sequence.
I observe that $6-x^2\geq0 \Rightarrow x^2\leq6\Rightarrow |x| \leq\sqrt{6}$
Similarly $6-2y^2\geq 0 \Rightarrow y^2 \leq3 \Rightarrow |y| \leq\sqrt{3} $
and
$ 6-3z^2 \geq0 \Rightarrow z^2 \leq2 \Rightarrow|z] \leq\sqrt{2}$
I really need help.Thank you.

A: Hint:
$Y$ is the inverse image of the set $\{6\}\subset \mathbf R$ (closed in $\mathbf R$), by the continuous function
\begin{align}
\mathbf R^3&\longrightarrow\mathbf R, \\
(x,y,z)&\longmapsto x^2+2y^2+3z^2.
\end{align}
Toshow $Y$ is bounded, observe that $\;0\le x^2+y^2+z^2 \le x^2+2y^2+3z^2$.


text:
Q: Не видно кнопку button на iOS На этой странице в самой нижней форме есть кнопка отправки формы <button></button>. Почему-то кнопка не видна на телефоне и планшете (iOS). Видна только левая обводка. Из-за чего это может быть?

A: right 25px center - что Вы тут хотели задать?
Попробуйте:
background: url(../images/send_message_icon.png) right 25px no-repeat #76BEE3;

P.S: background-position имеет 2 значения, а не 3


text:
Q: Custom remote event handling in app from iOS lock screen How does spotify handle custom remote events? Currently on iPhone 6 running iOS 8.1.3 and spotify version 2.4.0.1822 I get the following controls on the lock screen when I turn on spotify radio. Ive tried reading all docs pertaining to remote events, and I'm unable to find any resources which allow custom remote events from the lock screen.

A: Maybe that is implemented with MPRemoteCommandCenter.
Here is example...
MPRemoteCommandCenter *remoteCommandCenter = [MPRemoteCommandCenter sharedCommandCenter];
[[remoteCommandCenter skipForwardCommand] addTarget:self action:@selector(skipForward)];
[[remoteCommandCenter togglePlayPauseCommand] addTarget:self action:@selector(togglePlayPause)];
[[remoteCommandCenter pauseCommand] addTarget:self action:@selector(pause)];
[[remoteCommandCenter likeCommand] addTarget:self action:@selector(like)];

Implement this code, play music on your app, and lock your iPhone. You will probably see a customized lock screen.
Note - Menu can be customized label, but it can not customize icon image and number of row.


text:
Q: my display() is not running or showing my println The program I am working on currently runs successfully but it doesn't execute part of my program and it shows no errors.
The prompt was:
"Create an application that declares a Purchase object and prompts the user for purchase details. When you prompt for an invoice number, do not let the user proceed until a number between 1000 and 8000 has been entered. When you prompt for a sale amount, do not proceed until the user has entered a non-negative number, sale amount, and sales tax. Save the file as CreatePurchase.java."
import java.util.Scanner;

public final class CreatePurchase {
    static int invoiceNum; // I made these variables static because
    static double amount; // it fixed an error I was having with using
                            // non-static variables in a static field?

    double tax = .05;
    double totalamount;

    public static void main(String[] args) {
        Purchase completedPurchase = new Purchase();
        Scanner input = new Scanner(System.in);
        System.out
                .println("Please enter the invoice number! (Must be between 1000 and 8000!)");
        invoiceNum = input.nextInt();
        System.out
                .println("Please enter the amount of the sale! (Must be greater than 0!)");
        amount = input.nextDouble();

        while (invoiceNum < 1000 || invoiceNum > 8000) {
            System.out
                    .println("The invoice number you entered is invalid, try again!");
        }
        while (amount < 0) {
            System.out.println("The sale amount is invalid, try again!");
        }
    }

    public int getInvoiceNum(int invoiceNum) {
        return invoiceNum;
    }

    public double getAmount(double amount) {
        return amount;
    }

    public double getTotalAmount(double totalAmount) {
        return totalAmount;
    }

    public void setTotalAmount(double tax, double amount) {
        double totalAmount = (amount * tax);
    }

    public void display(int invoiceNum, double amount, double totalAmount) {
        System.out.println("Your invoice number is:" + invoiceNum + ".");
        System.out.println("Your sale amount is: " + amount + ".");
        System.out.println("Your sale amount after tax is: " + totalAmount
                + ".");
    }
}

I have spent hours trying to figure out what I need to fix in order to get my display method to work. The program runs successfully, and there are no errors, so I am not sure what to even try to fix.
(Sorry if my code or question doesn't make sense.)

A: I would massively refactor your code if given the chance.  First, the CreatePurchase class should be a simply POJO (plain old Java object), containing state for the invoice number, purchase amount, and sales tax, along with getter and setter methods for accessing and changing that state.  Next, the main() method within this class will instantiate a CreatePurchase object for storing the user input.  A big change I made was in how the code handles user inputs.  My code below uses two while loops to poll the user for a correct invoice number (between 1000 and 8000) and amount (non negative), and only then proceeds with the remainder of the method.  Finally, the CreatePurchase object created is used to output the result to the console.
public final class CreatePurchase {
    private int invoiceNum;
    private double amount;
    private double totalamount;

    // I am hard-coding the sales tax as 5%, as you did in your question,
    // though this code can easily be modified if you also want to input the tax
    private final double tax = .05;

    public int getInvoiceNum() {
        return invoiceNum;
    }

    public void setInvoiceNum(int invoiceNum) {
        this.invoiceNum = invoiceNum;
    }

    public double getAmount() {
        return amount;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }

    public double getTotalAmount() {
        return totalAmount;
    }

    public void setTotalAmount(double totalAmount) {
        this.totalAmount = totalAmount;
    }

    public static void main(String[] args) {
        CreatePurchase cp = new CreatePurchase();
        Scanner input = new Scanner(System.in);

        // these next two do-while loops will continue polling the user
        // until he enters a valid input
        do {
            System.out.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
            invoiceNum = input.nextInt();
        } while (invoiceNum < 1000 || invoiceNum > 8000);

        cp.setInvoiceNum(invoiceNum);

        do {
            System.out.println("Please enter the amount of the sale! (Must be greater than 0!)");
            amount = input.nextDouble();
        } while (amount < 0);

        totalamount = amount*(1 + tax);
        cp.setAmount(amount);
        cp.setTotalAmount(totalAmount);

        // now use the CreatePurchase object to print out
        // details of the transaction
        System.out.println("Your invoice number is:" + cp.getInvoiceNum() + ".");
        System.out.println("Your sale amount is: " + cp.getAmount() + ".");
        System.out.println("Your sale amount after tax is: " + cp.getTotalAmount() + ".");
    }
}

A: You declared method public void display(int invoiceNum, double amount, double totalAmount) but you never actually used it.

A: try the below code, this should help!
import java.util.Scanner;

public final class CreatePurchase {
    static int invoiceNum; // I made these variables static because
    static double amount; // it fixed an error I was having with using
                            // non-static variables in a static field?

    static double tax = .05;
    static double totalAmount;

    public void updatePurchase(final Purchase purchase) {
        Scanner input = new Scanner(System.in);
        System.out
                .println("Please enter the invoice number! (Must be between 1000 and 8000!)");
        invoiceNum = input.nextInt();

        if (invoiceNum < 1000 || invoiceNum > 8000) {
            System.out
                    .println("The invoice number you entered is invalid, try again!");
            updatePurchase(purchase);

        }
        System.out
                .println("Please enter the amount of the sale! (Must be greater than 0!)");
        amount = input.nextDouble();

        if (amount < 0) {
            System.out.println("The sale amount is invalid, try again!");
            updatePurchase(purchase);
        }

        setTotalAmount(tax, amount);

        display(invoiceNum, amount, getTotalAmount());

    }

    public static void main(String[] args) {
        Purchase completedPurchase = new Purchase();
        new CreatePurchase().updatePurchase(completedPurchase);
    }

    public int getInvoiceNum(int invoiceNum) {
        return invoiceNum;
    }

    public double getAmount(double amount) {
        return amount;
    }

    public double getTotalAmount() {
        return totalAmount;
    }

    public void setTotalAmount(double tax, double amount) {
        totalAmount = (amount * tax);
    }

    public void display(int invoiceNum, double amount, double totalAmount) {
        System.out.println("Your invoice number is:" + invoiceNum + ".");
        System.out.println("Your sale amount is: " + amount + ".");
        System.out.println("Your sale amount after tax is: " + totalAmount
                + ".");
    }
}


text:
Q: Strange Allowed Apex Syntax Found some crazy apex syntax and I have no clue what it does.
public Account<List<String<Contact>>> whatIsWrongWithApex;

Is this a defect?  Should this do something?  Compiler not strict enough?
For the sake of the question, here is a simpler example:
public String<String> iThoughtThisShouldOnlyWorkForCollections;

Edit: Here is a full example where I instantiate an Account using this method and successfully insert it into the database:
public class ABug {
  public Account<List<String<Contact>>> whatIsWrongWithApex;

  public ABug() {
    whatIsWrongWithApex = new Account<List<String<Contact>>>();
    whatIsWrongWithApex.Name = 'Account Name';
    insert whatIsWrongWithApex;
  }
}

Anonymous Apex:
new ABug();

A: This 'strange' syntax is a result of native Java support for Generics.
We cannot leverage the power of generics in Apex just yet, but the platform itself most certainly does. This is likely being exposed here through the definition & inheritance of the sObject class.
Java Generic Types


text:
Q: Hypothesis Testing Coins t-test Hey all I'm trying to tackle the following problem:
Suppose we have the results of coin tosses of 3 people:

Person
Tosses
Heads

X
400
58

Y
100
20

Z
1000
120

a) Can we claim that the 3 people's tosses are statistically equal?
b) Compare person X and Y. Can we say that they are statistically equal?
c) What is the probability that the heads rate (no of heads/tosses) of person Z is greater than that of person Y?
For b) I thought of using two-sided proportions_ztest but how to compare all 3 samples for a) and what about the probability question? Does cumulative distribution function come to apply?
Thanks


text:
Q: WPF Application level ViewModel I'm new to WPF and MVVM, but I'm trying to create an application-level viewmodel for the multiple windows in my application.  Here's my code:
ApplicationViewModel.cs:
public class ApplicationViewModel : ViewModelBase
{
   // for MainWindow
   private MainWindowViewModel mainWindowViewModel;
   public MainWindowViewModel MainWindowViewModel
   {
      get { return this.mainWindowViewModel; }
      private set
      {
         this.mainWindowViewModel = value;
         OnPropertyChanged("MainWindowViewModel");
      }
   }

   // other window code...

   public ApplicationViewModel()
   {
      this.mainWindowViewModel = new MainWindowViewModel();

      // Now show the MainWindow
      MainWindow mainWindow = new MainWindow();
      mainWindow.Show();
   }
}

App.xaml:
<Application x:Class="SomeApp.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:viewModel="clr-namespace:SomeApp.viewModel">
   <Application.Resources>
      <viewModel:ApplicationViewModel x:Key="applicationViewModel" />
...

MainWindow.xaml:
<Window x:Class="SomeApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:viewModel="clr-namespace:SomeApp.viewModel">
<Grid DataContext="{StaticResource applicationViewModel}">
   <TextBox Name="courseNameTxtBox" Width="200" MaxLength="251"
            Text="{Binding Path=MainWindowViewModel.SomeMainWindowObject,ValidatesOnDataErrors=True,UpdateSourceTrigger=PropertyChanged}" />
...

For some reason, it seems that applicationViewModel is never instantiated as the MainWindow is never displayed.  What am I doing wrong?
I have also tried this:
App.xaml:
<Application x:Class="CourseAttendanceTracking.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Startup="Application_Startup">
...

App.xaml.cs:
public partial class App : Application
{
   private void Application_Startup(object sender, StartupEventArgs e)
   {
      this.Resources.Add("applicationViewModel", new ApplicationViewModel());
   }
}

And I get this error:

System.Windows.Markup.XamlParseException occurred   Message='Provide
  value on 'System.Windows.StaticResourceExtension' threw an exception.'
  Line number '15' and line position '19'.
  Source=PresentationFramework   LineNumber=15   LinePosition=19
  StackTrace:    at
  System.Windows.Markup.XamlReader.RewrapException(Exception e,
  IXamlLineInfo lineInfo, Uri baseUri)    at
  System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader,
  IXamlObjectWriterFactory writerFactory, Boolean
  skipJournaledProperties, Object rootObject, XamlObjectWriterSettings
  settings, Uri baseUri)    at
  System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader,
  Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel
  accessLevel, Uri baseUri)    at
  System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext
  parserContext, Object parent, Boolean closeStream)    at
  System.Windows.Application.LoadComponent(Object component, Uri
  resourceLocator)    at SomeApp.MainWindow.InitializeComponent() in
  \MainWindow.xaml:line 1    at SomeApp.MainWindow..ctor() in
  \MainWindow.xaml.cs:line 25    InnerException:     Message=Cannot find
  resource named 'applicationViewModel'. Resource names are case
  sensitive.    Source=PresentationFramework    StackTrace:
          at  System.Windows.StaticResourceExtension.ProvideValueInternal(IServiceProvider
  serviceProvider, Boolean allowDeferredReference)
          at System.Windows.StaticResourceExtension.ProvideValue(IServiceProvider
  serviceProvider)
          at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CallProvideValue(MarkupExtension
  me, IServiceProvider serviceProvider)    InnerException:

My XAML works fine if I do this though:
MainWindow.xaml
<Window.Resources>
   <viewModel:ApplicationViewModel x:Key="applicationViewModel" />

But I really don't want to instantiate the ApplicationViewModel in this Window as I won't be able to see it in another window.  Thanks in advance.

A: Try changing the {StaticResource XXX} for a {DynamicResource XXX}


text:
Q: Ok to not include some non-member functions in header? If you want some non-member functions to be possible to be called only by functions in the same translation unit, is ok to not define them in the header?

A: This is common.  Keeps clutter out of the header file.  Normally, you would put them in an anonymous namespace in the .cpp file.
You can accomplish this without an anonymous namespace by using the static keyword.

A: Yes, non-member functions can be placed inside the translation unit.
Declare and define them as static so they are private within the translation unit.

A: It's OK to declare them in header file. But if you define them in the header and the header was included by more than one compiling unit, it will cause a link error of confliction.
See this example:
header.h
class Foo
{
};

void f()
{
}

b.cpp
# include "header.h"

a.cpp
# include "header.h"

int main()
{
}

Compiling OK but link error:
[~]$ g++ -c a.cpp
[~]$ g++ -c b.cpp
[~]$ g++ -o run a.o b.o
b.o: In function `f()':
b.cpp:(.text+0x0): multiple definition of `f()'
a.o:a.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
[~]$

Alternately, if you separate the declaration and definition like this:
header.h
class Foo
{
};

void f();

b.cpp
#include "header.h"

void f()
{
}

a.cpp
#include "header.h"

int main()
{
}

Then it will be fine
[~]$ g++ -c a.cpp
[~]$ g++ -c b.cpp
[~]$ g++ -o run a.o b.o
[~]$

Also, the static works for that as the posts above said.

A: You can just put functions in their own namespace so that it doesn't interfere with rest code. A common practice is to make the namespace an inner namespace of your main library namespace and to call it details or something similar.
Of course, if you need to function to be available through ADL(argument dependent lookup) then it has to live in the namespace enclosing the classes for which the ADL is supposed to match. There's no way around this.


text:
Q: Link to a different page in asp.net I have the following code which should go to a particular company page from the request page. In the website folder Company page is under a folder called Companies and the request page is under Requests folder.
 Dim strUrl As String = "/Companies/Details.aspx?Company_ID=" & .Company_id
 litlCompany.Text = "" & .Company.Name & ""

The Url should be built as,
http://localhost/Companies/Details.aspx?Company_ID=222
But it comes as,
http://localhost/Requests/Companies/Details.aspx?Company_ID=222
Does anyone knows why?

A: I'm assuming you are currently on http://localhost/Requests/something.aspx? If so, that's because you forgot the tilde root specifier:
~/Companies/Details.aspx

Which should fix your problem.

A: You can also try
Page.ResolveClientUrl("~/Companies/Details.aspx?Company_ID=" + Company_id)

A: By the name of your control it appears that you are using a Literal.
Try changing this to a HyperLink, then you won't need to put the HTML (<a href=...) in the text property, you will be able to use hypCompany.NavigateUrl = strUrl and ASP.Net will generate it for you. This is the neatest way to do it anyhow.
Also add in the tilde to go to the root :-)
E.G.
Dim strUrl As String = "~/Companies/Details.aspx?Company_ID=" & .Company_id
hypCompany.NavigateUrl = strUrl

A: Am assuming that this link is built in the request.aspx page.
I think the a href is being rendered to the current httpcontext. Have you tried creating the string as :
Dim strUrl As String = "~/Companies/Details.aspx?Company_ID=" & .Company_id
I think this will work if the Companies folder is in the root. The tilda should ensure it looks from the root down.


text:
Q: Drop a row in pandas Dataframe base on integer index location I have time series data that has duplicate timestamp indexes but I would only like to drop a single row based on the integer location.  For example if I have the following :
import numpy as np
import pandas as pd

dates       = pd.to_datetime(["2015-10-22 09:40:00","2015-10-22 09:40:00","2015-10-22 09:40:00","2015-10-22 09:50:00","2015-10-22 10:00:00"])
data_rand   = np.random.rand(len(dates),3)
col_head    = ['A','B','C']

df          = pd.DataFrame(data=data_rand, index=dates, columns=col_head)

print(df)
rowindex    = 1

df.drop(df.index[rowindex], inplace=True)
#df.drop(df.index.iloc[[rowindex]], inplace=True)

print(df)

The data outputs a dataframe that looks like:
                            A         B         C
2015-10-22 09:40:00  0.755642  0.797471  0.366410
2015-10-22 09:40:00  0.475411  0.629229  0.733368
2015-10-22 09:40:00  0.003278  0.461901  0.184833
2015-10-22 09:50:00  0.803465  0.218510  0.864337
2015-10-22 10:00:00  0.153356  0.950724  0.249950

Now if I wanted to remove the second row I would use the drop function but because there are two other labels with the exact same index all three would be dropped. Is there a way to only drop the middle of the three duplicate time stamps? I would prefer to do this without resetting the index.
What I would want the data to look like is this:
                            A         B         C
2015-10-22 09:40:00  0.755642  0.797471  0.366410
2015-10-22 09:40:00  0.003278  0.461901  0.184833
2015-10-22 09:50:00  0.803465  0.218510  0.864337
2015-10-22 10:00:00  0.153356  0.950724  0.249950

A: You could use iloc or loc like
In [5055]: idx = np.ones(len(df.index), dtype=bool)

In [5057]: idx[rowindex] = False

In [5058]: df.iloc[idx]     # or df.loc[idx]
Out[5058]:
                            A         B         C
2015-10-22 09:40:00  0.704959  0.995358  0.355915
2015-10-22 09:40:00  0.151127  0.398876  0.240856
2015-10-22 09:50:00  0.343456  0.513128  0.666625
2015-10-22 10:00:00  0.105908  0.130895  0.321981

Details
In [5059]: df
Out[5059]:
                            A         B         C
2015-10-22 09:40:00  0.704959  0.995358  0.355915
2015-10-22 09:40:00  0.762548  0.593177  0.691702
2015-10-22 09:40:00  0.151127  0.398876  0.240856
2015-10-22 09:50:00  0.343456  0.513128  0.666625
2015-10-22 10:00:00  0.105908  0.130895  0.321981

A: You could use the integer location to find the name of the row (which is the index):
df = df.drop(df.iloc[i].name)

A: Using np.arange and iloc to select rows other than rowindex . Much similar to dropping rowindex i.e (I suggest @Zero's answer in case of thinking of dropping multiple row indices)
rowindex = 2
ndf = df.iloc[~(np.arange(df.shape[0]) == rowindex )]

Output:

                       A         B         C
2015-10-22 09:40:00  0.568431  0.302549  0.497309
2015-10-22 09:40:00  0.683263  0.916699  0.108929
2015-10-22 09:50:00  0.751543  0.480892  0.797728
2015-10-22 10:00:00  0.282703  0.433418  0.009757

df
                            A         B         C
2015-10-22 09:40:00  0.568431  0.302549  0.497309
2015-10-22 09:40:00  0.683263  0.916699  0.108929
2015-10-22 09:40:00  0.495492  0.232836  0.436861
2015-10-22 09:50:00  0.751543  0.480892  0.797728
2015-10-22 10:00:00  0.282703  0.433418  0.009757


text:
Q: How to use sub query in SQL? I have 4 tables :
Travelers (TravelerID,FirstName,LastName)
Guides(GuideID,FirstName,LastName)
Locations(LocationID,LocationName)
Trips(TravelerID,GuideID,LocationID,Stars,StartDate,ReturnDate)
I want to return per guide the name of location which he guided the maximum number of  travelers .
I have tried to use this sub query but it doesn't work :
SELECT G.FirstName,L.LocationName,count(distinct(TravelerID))as number_of_travelers_per_guide
FROM Guides AS G
LEFT JOIN Trips AS T USING (GuideID)
LEFT JOIN Locations AS L USING (LocationID)
GROUP BY G.FirstName,L.LocationName
HAVING max((SELECT T1.number_of_travelers_per_guide
            FROM Trips AS T1
            WHERE T.GuideID=T1.GuideID));

I will appreciate any help

A: try using the complete function and not the alis
SELECT G.FirstName,L.LocationName, count(distinct T.TravelerID ) as number_of_travelers_per_guide
FROM Guides AS G
LEFT JOIN Trips AS T USING (GuideID)
LEFT JOIN Locations AS L USING (LocationID)
GROUP BY G.FirstName,L.LocationName
HAVING count(distinct TravelerID ) = (
            select max(my_count) from (SELECT count(distinct T.TravelerID) my_count
            FROM Guides AS G
            LEFT JOIN Trips AS T USING (GuideID)
            LEFT JOIN Locations AS L USING (LocationID)
            GROUP BY G.FirstName, L.LocationName ) my_t );

A: This is a real pain in MySQL, because pre v 8 versions have neither CTEs nor window functions.  One method uses variables:
SELECT gl.*
FROM (SELECT gl.*,
             (@rn := if(@g = gl.FirstName, @rn + 1,
                        if(@g := gl.FirstName, 1, 1)
                       )
             ) as rn
      FROM (SELECT G.FirstName, L.LocationName, count(distinct TravelerID) as number_of_travelers_per_guide
            FROM Guides G LEFT JOIN
                 Trips T
                 USING (GuideID) LEFT JOIN
                 Locations L
                 USING (LocationID)
            GROUP BY G.FirstName, L.LocationName
            ORDER BY G.FirstName, number_of_travelers_per_guide DESC
           ) gl CROSS JOIN
           (SELECT @g := '', @rn := -1) params
      ) gl
WHERE rn = 1;

I wouldn't stress out on understanding variables in MySQL.  Instead, learn about row_number(), rank(), and dense_rank() -- those are the right way to solve the problem in almost all databases.

A: If CTEs and analytic functions cannot be used, I think you'd be looking at something like the following. There is a danger however that if a guide has two equal-ranking locations, two or more rows will be returned for that guide instead of just one.
SELECT
    G.FirstName
    ,L.LocationName
    ,guide_stats.traveler_count

FROM
    (
        SELECT
            GuideID
            ,LocationID
            ,COUNT(DISTINCT TravelerID) AS traveler_count

        FROM Trips
        GROUP BY GuideID, LocationID

    ) AS guide_stats

INNER JOIN
    (
        SELECT
            guide_stats_for_max.GuideID
            ,MAX(guide_stats_for_max.traveler_count) AS max_traveler_count

        FROM
        (
            SELECT
                GuideID
                ,LocationID
                ,COUNT(DISTINCT TravelerID) AS traveler_count

            FROM Trips
            GROUP BY GuideID, LocationID

        ) AS guide_stats_for_max

        GROUP BY GuideID

    ) AS guide_max
    ON (guide_stats.GuideID = guide_max.GuideID)
    AND (guide_stats.traveler_count = guide_max.max_traveler_count)

LEFT JOIN Guides    AS G USING (guide_stats.GuideID)
LEFT JOIN Locations AS L USING (guide_stats.LocationID)

Note I've written this code without testing - please excuse small errors.