text:
Q: Trying to add a new column guys, I'm trying to add a new column (KEY_EXAMPLE) in my "searchable dictionary" code example
The KEY_EXAMPLE should be the third column. But it doesn't work....
Here is my code:
DictionaryDatabase.Java
public class DictionaryDatabase {
private static final String TAG = "DictionaryDatabase";

//The columns we'll include in the dictionary table
public static final String KEY_WORD = SearchManager.SUGGEST_COLUMN_TEXT_1;
public static final String KEY_DEFINITION = SearchManager.SUGGEST_COLUMN_TEXT_2;
public static final String KEY_EXAMPLE = SearchManager.SUGGEST_COLUMN_TEXT_1;

private static final String DATABASE_NAME = "dictionary";
private static final String FTS_VIRTUAL_TABLE = "FTSdictionary";
private static final int DATABASE_VERSION = 2;

private final DictionaryOpenHelper mDatabaseOpenHelper;
private static final HashMap<String,String> mColumnMap = buildColumnMap();

/**
 * Constructor
 * @param context The Context within which to work, used to create the DB
 */
public DictionaryDatabase(Context context) {
    mDatabaseOpenHelper = new DictionaryOpenHelper(context);
}

/**
 * Builds a map for all columns that may be requested, which will be given to the
 * SQLiteQueryBuilder. This is a good way to define aliases for column names, but must include
 * all columns, even if the value is the key. This allows the ContentProvider to request
 * columns w/o the need to know real column names and create the alias itself.
 */
private static HashMap<String,String> buildColumnMap() {
    HashMap<String,String> map = new HashMap<String,String>();
    map.put(KEY_WORD, KEY_WORD);
    map.put(KEY_DEFINITION, KEY_DEFINITION);
    map.put(KEY_EXAMPLE, KEY_EXAMPLE);
    map.put(BaseColumns._ID, "rowid AS " +
            BaseColumns._ID);
    map.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID, "rowid AS " +
            SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
    map.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, "rowid AS " +
            SearchManager.SUGGEST_COLUMN_SHORTCUT_ID);
    return map;
}

/**
 * Returns a Cursor positioned at the word specified by rowId
 *
 * @param rowId id of word to retrieve
 * @param columns The columns to include, if null then all are included
 * @return Cursor positioned to matching word, or null if not found.
 */
public Cursor getWord(String rowId, String[] columns) {
    String selection = "rowid = ?";
    String[] selectionArgs = new String[] {rowId};

    return query(selection, selectionArgs, columns);

    /* This builds a query that looks like:
     *     SELECT <columns> FROM <table> WHERE rowid = <rowId>
     */
}

/**
 * Returns a Cursor over all words that match the given query
 *
 * @param query The string to search for
 * @param columns The columns to include, if null then all are included
 * @return Cursor over all words that match, or null if none found.
 */
public Cursor getWordMatches(String query, String[] columns) {
    String selection = KEY_WORD + " MATCH ?";
    String[] selectionArgs = new String[] {query+"*"};

    return query(selection, selectionArgs, columns);

    /* This builds a query that looks like:
     *     SELECT <columns> FROM <table> WHERE <KEY_WORD> MATCH 'query*'
     * which is an FTS3 search for the query text (plus a wildcard) inside the word column.
     *
     * - "rowid" is the unique id for all rows but we need this value for the "_id" column in
     *    order for the Adapters to work, so the columns need to make "_id" an alias for "rowid"
     * - "rowid" also needs to be used by the SUGGEST_COLUMN_INTENT_DATA alias in order
     *   for suggestions to carry the proper intent data.
     *   These aliases are defined in the DictionaryProvider when queries are made.
     * - This can be revised to also search the definition text with FTS3 by changing
     *   the selection clause to use FTS_VIRTUAL_TABLE instead of KEY_WORD (to search across
     *   the entire table, but sorting the relevance could be difficult.
     */
}

/**
 * Performs a database query.
 * @param selection The selection clause
 * @param selectionArgs Selection arguments for "?" components in the selection
 * @param columns The columns to return
 * @return A Cursor over all rows matching the query
 */
private Cursor query(String selection, String[] selectionArgs, String[] columns) {
    /* The SQLiteBuilder provides a map for all possible columns requested to
     * actual columns in the database, creating a simple column alias mechanism
     * by which the ContentProvider does not need to know the real column names
     */
    SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
    builder.setTables(FTS_VIRTUAL_TABLE);
    builder.setProjectionMap(mColumnMap);

    Cursor cursor = builder.query(mDatabaseOpenHelper.getReadableDatabase(),
            columns, selection, selectionArgs, null, null, null);

    if (cursor == null) {
        return null;
    } else if (!cursor.moveToFirst()) {
        cursor.close();
        return null;
    }
    return cursor;
}

/**
 * This creates/opens the database.
 */
private static class DictionaryOpenHelper extends SQLiteOpenHelper {

    private final Context mHelperContext;
    private SQLiteDatabase mDatabase;

    /* Note that FTS3 does not support column constraints and thus, you cannot
     * declare a primary key. However, "rowid" is automatically used as a unique
     * identifier, so when making requests, we will use "_id" as an alias for "rowid"
     */
    private static final String FTS_TABLE_CREATE =
                "CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE +
                " USING fts3 (" +
                KEY_WORD + ", " +
                KEY_DEFINITION + ", " +
                KEY_EXAMPLE + " );";

    DictionaryOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        mHelperContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        mDatabase = db;
        mDatabase.execSQL(FTS_TABLE_CREATE);
        loadDictionary();
    }

    /**
     * Starts a thread to load the database table with words
     */
    private void loadDictionary() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    loadWords();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    private void loadWords() throws IOException {
        Log.d(TAG, "Loading words...");
        final Resources resources = mHelperContext.getResources();
        InputStream inputStream = resources.openRawResource(R.raw.definitions);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        try {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] strings = TextUtils.split(line, "//");
                if (strings.length < 2) continue;
                long id = addWord(strings[0].trim(), strings[1].trim(), strings[2].trim());
                if (id < 0) {
                    Log.e(TAG, "unable to add word: " + strings[0].trim());
                }
            }
        } finally {
            reader.close();
        }
        Log.d(TAG, "DONE loading words.");
    }

    /**
     * Add a word to the dictionary.
     * @return rowId or -1 if failed
     */
    public long addWord(String word, String definition, String example) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_WORD, word);
        initialValues.put(KEY_DEFINITION, definition);
        initialValues.put(KEY_EXAMPLE, example);
        return mDatabase.insert(FTS_VIRTUAL_TABLE, null, initialValues);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
        onCreate(db);
    }
}

}

DictionaryProvider.java
public class DictionaryProvider extends ContentProvider {
String TAG = "DictionaryProvider";

public static String AUTHORITY = "com.example.android.searchabledict.DictionaryProvider";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/dictionary");

// MIME types used for searching words or looking up a single definition
public static final String WORDS_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE +
                                              "/vnd.example.android.searchabledict";
public static final String DEFINITION_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE +
                                                   "/vnd.example.android.searchabledict";

private DictionaryDatabase mDictionary;

// UriMatcher stuff
private static final int SEARCH_WORDS = 0;
private static final int GET_WORD = 1;
private static final int SEARCH_SUGGEST = 2;
private static final int REFRESH_SHORTCUT = 3;
private static final UriMatcher sURIMatcher = buildUriMatcher();

/**
 * Builds up a UriMatcher for search suggestion and shortcut refresh queries.
 */
private static UriMatcher buildUriMatcher() {
    UriMatcher matcher =  new UriMatcher(UriMatcher.NO_MATCH);
    // to get definitions...
    matcher.addURI(AUTHORITY, "dictionary", SEARCH_WORDS);
    matcher.addURI(AUTHORITY, "dictionary/#", GET_WORD);
    // to get suggestions...
    matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST);
    matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGEST);

    /* The following are unused in this implementation, but if we include
     * {@link SearchManager#SUGGEST_COLUMN_SHORTCUT_ID} as a column in our suggestions table, we
     * could expect to receive refresh queries when a shortcutted suggestion is displayed in
     * Quick Search Box, in which case, the following Uris would be provided and we
     * would return a cursor with a single item representing the refreshed suggestion data.
     */
    matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT, REFRESH_SHORTCUT);
    matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*", REFRESH_SHORTCUT);
    return matcher;
}

@Override
public boolean onCreate() {
    mDictionary = new DictionaryDatabase(getContext());
    return true;
}

/**
 * Handles all the dictionary searches and suggestion queries from the Search Manager.
 * When requesting a specific word, the uri alone is required.
 * When searching all of the dictionary for matches, the selectionArgs argument must carry
 * the search query as the first element.
 * All other arguments are ignored.
 */
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
                    String sortOrder) {

    // Use the UriMatcher to see what kind of query we have and format the db query accordingly
    switch (sURIMatcher.match(uri)) {
        case SEARCH_SUGGEST:
            if (selectionArgs == null) {
              throw new IllegalArgumentException(
                  "selectionArgs must be provided for the Uri: " + uri);
            }
            return getSuggestions(selectionArgs[0]);
        case SEARCH_WORDS:
            if (selectionArgs == null) {
              throw new IllegalArgumentException(
                  "selectionArgs must be provided for the Uri: " + uri);
            }
            return search(selectionArgs[0]);
        case GET_WORD:
            return getWord(uri);
        case REFRESH_SHORTCUT:
            return refreshShortcut(uri);
        default:
            throw new IllegalArgumentException("Unknown Uri: " + uri);
    }
}

private Cursor getSuggestions(String query) {
  query = query.toLowerCase();
  String[] columns = new String[] {
      BaseColumns._ID,
      DictionaryDatabase.KEY_WORD,

   /* SearchManager.SUGGEST_COLUMN_SHORTCUT_ID,
                    (only if you want to refresh shortcuts) */
      SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID};

  return mDictionary.getWordMatches(query, columns);
}

private Cursor search(String query) {
  query = query.toLowerCase();
  String[] columns = new String[] {
      BaseColumns._ID,
      DictionaryDatabase.KEY_WORD,
      DictionaryDatabase.KEY_DEFINITION,
      DictionaryDatabase.KEY_EXAMPLE};

  return mDictionary.getWordMatches(query, columns);
}

private Cursor getWord(Uri uri) {
  String rowId = uri.getLastPathSegment();
  String[] columns = new String[] {
      DictionaryDatabase.KEY_WORD,
      DictionaryDatabase.KEY_DEFINITION,
      DictionaryDatabase.KEY_EXAMPLE};

  return mDictionary.getWord(rowId, columns);
}

private Cursor refreshShortcut(Uri uri) {
  /* This won't be called with the current implementation, but if we include
   * {@link SearchManager#SUGGEST_COLUMN_SHORTCUT_ID} as a column in our suggestions table, we
   * could expect to receive refresh queries when a shortcutted suggestion is displayed in
   * Quick Search Box. In which case, this method will query the table for the specific
   * word, using the given item Uri and provide all the columns originally provided with the
   * suggestion query.
   */
  String rowId = uri.getLastPathSegment();
  String[] columns = new String[] {
      BaseColumns._ID,
      DictionaryDatabase.KEY_WORD,
      DictionaryDatabase.KEY_DEFINITION,
      DictionaryDatabase.KEY_EXAMPLE,
      SearchManager.SUGGEST_COLUMN_SHORTCUT_ID,
      SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID};

  return mDictionary.getWord(rowId, columns);
}

/**
 * This method is required in order to query the supported types.
 * It's also useful in our own query() method to determine the type of Uri received.
 */
@Override
public String getType(Uri uri) {
    switch (sURIMatcher.match(uri)) {
        case SEARCH_WORDS:
            return WORDS_MIME_TYPE;
        case GET_WORD:
            return DEFINITION_MIME_TYPE;
        case SEARCH_SUGGEST:
            return SearchManager.SUGGEST_MIME_TYPE;
        case REFRESH_SHORTCUT:
            return SearchManager.SHORTCUT_MIME_TYPE;
        default:
            throw new IllegalArgumentException("Unknown URL " + uri);
    }
}

// Other required implementations...

@Override
public Uri insert(Uri uri, ContentValues values) {
    throw new UnsupportedOperationException();
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
    throw new UnsupportedOperationException();
}

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    throw new UnsupportedOperationException();
}

}

SearchableDictionary.java
public class SearchableDictionary extends Activity {

private TextView mTextView;
private ListView mListView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mTextView = (TextView) findViewById(R.id.text);
    mListView = (ListView) findViewById(R.id.list);

    handleIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
    // Because this activity has set launchMode="singleTop", the system calls this method
    // to deliver the intent if this activity is currently the foreground activity when
    // invoked again (when the user executes a search from this activity, we don't create
    // a new instance of this activity, so the system delivers the search intent here)
    handleIntent(intent);
}

private void handleIntent(Intent intent) {
    if (Intent.ACTION_VIEW.equals(intent.getAction())) {
        // handles a click on a search suggestion; launches activity to show word
        Intent wordIntent = new Intent(this, WordActivity.class);
        wordIntent.setData(intent.getData());
        startActivity(wordIntent);
    } else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        // handles a search query
        String query = intent.getStringExtra(SearchManager.QUERY);
        showResults(query);
    }
}

/**
 * Searches the dictionary and displays results for the given query.
 * @param query The search query
 */
private void showResults(String query) {

    Cursor cursor = managedQuery(DictionaryProvider.CONTENT_URI, null, null,
                            new String[] {query}, null);

    if (cursor == null) {
        // There are no results
        mTextView.setText(getString(R.string.no_results, new Object[] {query}));
    } else {
        // Display the number of results
        int count = cursor.getCount();
        String countString = getResources().getQuantityString(R.plurals.search_results,
                                count, new Object[] {count, query});
        mTextView.setText(countString);

        // Specify the columns we want to display in the result
        String[] from = new String[] { DictionaryDatabase.KEY_WORD,
                                       DictionaryDatabase.KEY_DEFINITION,
                                       DictionaryDatabase.KEY_EXAMPLE};

        // Specify the corresponding layout elements where we want the columns to go
        int[] to = new int[] { R.id.word,
                               R.id.definition,
                               R.id.example};

        // Create a simple cursor adapter for the definitions and apply them to the ListView
        SimpleCursorAdapter words = new SimpleCursorAdapter(this,
                                      R.layout.result, cursor, from, to);
        mListView.setAdapter(words);

        // Define the on-click listener for the list items
        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // Build the Intent used to open WordActivity with a specific word Uri
                Intent wordIntent = new Intent(getApplicationContext(), WordActivity.class);
                Uri data = Uri.withAppendedPath(DictionaryProvider.CONTENT_URI,
                                                String.valueOf(id));
                wordIntent.setData(data);
                startActivity(wordIntent);
            }
        });
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.options_menu, menu);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setIconifiedByDefault(false);
    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.search:
            onSearchRequested();
            return true;
        default:
            return false;
    }
}
}

WordActivity.java
public class WordActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.word);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    Uri uri = getIntent().getData();
    Cursor cursor = managedQuery(uri, null, null, null, null);

    if (cursor == null) {
        finish();
    } else {
        cursor.moveToFirst();

        TextView word = (TextView) findViewById(R.id.word);
        TextView definition = (TextView) findViewById(R.id.definition);
        TextView example = (TextView) findViewById(R.id.example);

        int wIndex = cursor.getColumnIndexOrThrow(DictionaryDatabase.KEY_WORD);
        int dIndex = cursor.getColumnIndexOrThrow(DictionaryDatabase.KEY_DEFINITION);
        int eIndex = cursor.getColumnIndexOrThrow(DictionaryDatabase.KEY_EXAMPLE);

        word.setText(cursor.getString(wIndex));
        definition.setText(cursor.getString(dIndex));
        example.setText(cursor.getString(eIndex));
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.options_menu, menu);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setIconifiedByDefault(false);
    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.search:
            onSearchRequested();
            return true;
        case android.R.id.home:
            Intent intent = new Intent(this, SearchableDictionary.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            return true;
        default:
            return false;
    }
}
}

A: Close inspection reveals that you have the same string value assigned to 1 and 3
public static final String KEY_WORD = SearchManager.SUGGEST_COLUMN_TEXT_1;
public static final String KEY_DEFINITION = SearchManager.SUGGEST_COLUMN_TEXT_2;
public static final String KEY_EXAMPLE = SearchManager.SUGGEST_COLUMN_TEXT_1;

A: it is a limitation that you can have only two items in the search suggestion provided by android
refer section

The biggest problem with search suggestions

in http://www.grokkingandroid.com/android-tutorial-adding-suggestions-to-search/


text:
Q: Get parent values from multidimensional associative json file I have a multi- and variable-level json file that looks like the example at the bottom of this post. What I need to do is search for a particular value, let's say "Gap junction" and return the value for "name" for all of the higher level parents, in this example "Junction", "Plasma membrane" and "Cell". I need to do this using php and I think I need a recursive loop to traverse the array that will record the "name" value for each depth level into an array and then return this "name" array once the search term is found, but I'm struggling a bit at achieving this. Any help would be appreciated.
{
    "name": "Cell",
    "children": [
        {
            "name": "Plasma membrane",
            "children": [
                {
                    "name": "Junction",
                    "children": [
                        {"name": "Adherens junction"},
                        {"name": "Caveola"},
                        {"name": "Gap junction"},
                        {"name": "Lipid raft"},
                        {"name": "Tight junction"}
                    ]
                },
                {"name": "Focal adhesion"}
            ]
        },
        {
            "name": "Vesicle",
            "children": [
                {
                    "name": "Endosome",
                    "children": [
                        {"name": "Early Endosome"},
                        {"name": "Late Endosome"},
                        {"name": "Recyling Endosome"}
                    ]
                },
                { "name": "Microsome"}
            ]
        }
    ]
}

EDIT
Current code as requested. The $found variable is certainly not working how I intended it too. Code is based/modified on this answer: Get Parent and Child depth level from JSON using PHP?
$jsonString = file_get_contents("./information/localization.json");
$jsonArray = json_decode($jsonString);

$currOrganelle = "Gap junction";

$parents = read_tree_recursively($jsonArray, $currOrganelle);

function read_tree_recursively($items, $searchTerm, $result = array(), $level = 0, $found = false) {

    foreach($items as $child) {
        if(!$found) {
            $currName = $child->name;

            if($currName == $searchTerm) {
                $found = true;
                return $result;
            }
            elseif(!empty($child->children)) {
                $result[$level] = $currName;
                $result = read_tree_recursively($child->children, $searchTerm, $result, $level + 1, $found);
                if($found) return $result;
            }
            else {
            }
        }
        else {
            return $result;
        }
    }
}

A: Solution with RecursiveIteratorIterator and RecursiveArrayIterator classes:
// $str - is your initial json string
$decoded = json_decode($str, TRUE);

function getParentNameKeys($arr = [], $needle = "") {
    $iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arr));
    $nameKeys = [];
    foreach ($iterator as $key => $value) {
        if ($value === $needle) {
            $depth = $iterator->getDepth();
            while ($depth--){
                if ($iterator->getSubIterator($depth)->offsetExists('name')) {
                    $nameKeys[] = $iterator->getSubIterator($depth)->offsetGet('name');
                }
            }
        }
    }
    return $nameKeys;
}

$nameKeys = getParentNameKeys($decoded, "Gap junction");
var_dump($nameKeys);
// the output:
array (size=3)
  0 => string 'Junction' (length=8)
  1 => string 'Plasma membrane' (length=15)
  2 => string 'Cell' (length=4)

$nameKeys = getParentNameKeys($decoded, "Early Endosome");
var_dump($nameKeys);
// the output:
array (size=3)
  0 => string 'Endosome' (length=8)
  1 => string 'Vesicle' (length=7)
  2 => string 'Cell' (length=4)

http://php.net/manual/en/class.recursiveiteratoriterator.php

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scatter plot Text labels in R
Below is the code.
stripchart(Age~Smoke, data = survey_clean_data , pch=16 , col = "blue", method = "jitter" ,main = "AGE VS SMOKE",na.rm = T)

I want to add labels to it like below image,

I tried several options.. but it is getting written on top of of other.
means = c(paste("mean_Age =",roumean(survey_clean_data[Smoke == "Heavy","Age"],na.rm =T)),
          paste("mean_Age =",mean(survey_clean_data[Smoke == "Never","Age"],na.rm =T)),
          paste("mean_Age =",mean(survey_clean_data[Smoke == "Regul","Age"],na.rm =T)),
          paste("mean_Age =",mean(survey_clean_data[Smoke == "Occas","Age"],na.rm =T)))

text(50,survey_clean_data$Smoke,labels =  means)

DATA: library(MASS) attach(survey)

A: There are a few problems with your code. The main thing is that you are sending text() four labels (the contents of means), but a number of y-coordinates equal to the number of data points, since you are sending it survey_clean_data. R tries to equalize these uneven vectors, resulting in the over plotting.
Instead, you might do (data are artificial since you didn't provide any):
stripchart(Age~Smoke, data = survey_clean_data , pch=16 , col = "blue", method = "jitter" ,main = "AGE VS SMOKE",na.rm = T)

means <- aggregate(Age~Smoke, data = survey_clean_data, FUN = mean) # mean of each category
means$y <- 1:4 # add y-coordinates for each category

with(means, text(50, Smoke, labels = sprintf('Mean Age = %0.1f', Age))) # plot text labels on top of stripchart

Result:

A: answer give by jdobres worked fine. The below is one more solution.
add ylim=c(0.8,4.2) parameter to the scatterplot. You can adjust these ranges from c(1,4) to c(0.8,4.2). The later one worked for me.
stripchart(Age~Smoke, data = survey_clean_data , pch=16 , col = 634, method = "jitter" ,main = "AGE VS SMOKE",na.rm = T,ylim=c(0.8,4.2))

With the below line you can adjust the vertical height of the text.
eg: +0.1, -0.1 etc
text(50,c(1:4)+0.1,means)


text:
Q: Office 365 Email Stats I'm trying to count total emails sent and received from a specific email account per a period. The code is working but giving a bit of overstated result. Please, look at the code below if it could provide correct result.
I know that I could use the $Allmessages only once without filtering by SenderAddress and then by RecipientAddress but it's running forever without the filtering.
    $Allmessages_sent = @()
    $P = 1
    do
   {
    $pagedmessages_sent = Get-MessageTrace -SenderAddress $emailgroup -StartDate $StartDate -EndDate $EndDate -PageSize 1000 -Page $p `
            | Select Received,SenderAddress,RecipientAddress,Size
    $Allmessages_sent += $pagedmessages_sent
    $p = $p + 1
   }
    until ($pagedmessages_sent -eq $null)
    $senderssorted = 0;
    $senderssorted = $Allmessages_sent |group senderaddress | select @{n="SentCount";e={$_.Count}}
    $Allmessages_rcvd = @()
    $P_ = 1
   do
   {
    $pagedmessages_rcvd = Get-MessageTrace -RecipientAddress $emailgroup -StartDate $StartDate -EndDate $EndDate -PageSize 1000 -Page $p_ `
            | Select Received,SenderAddress,RecipientAddress,Size
    $Allmessages_rcvd += $pagedmessages_rcvd
    $p_ = $p_ + 1
    }
    until ($pagedmessages_rcvd -eq $null)
    $recipientsorted = 0;
    $recipientsorted = $Allmessages_rcvd |group recipientaddress | select @{n="ReceivedCount";e={$_.Count}};
    $totalSent = 0;
    $totalRsvd = 0;
    $totalSent = $senderssorted.Sentcount;
    $totalRsvd = $recipientsorted.ReceivedCount;
    $arrayResult = @();
    $arrayResult += $totalSent;
    $arrayResult += $totalRsvd
    Write-Host "Sent: " $arrayResult[0];
    Write-Host "Received: " $arrayResult[1];

Thanks

A: It's solved. The discrepancies explained:
-   The Total 'Received' discrepancies were due to the 'Failed' status emails were counted. So, I added -Status 'Delivered' for the both parts "Get-MessageTrace -SenderAddress …" and also "Get-MessageTrace -RecipientAddress".
-   The Total 'Sent' discrepancies were due to the forwarded emails via setup 'Rules' from my mail-box that I wasn't able to see in my Outlook 'Sent' folder.


text:
Q: Set private setter on property via reflection I know this has several canonical answers (that I've used successfully in the past!) See https://stackoverflow.com/a/1778410/1675729 and https://stackoverflow.com/a/1565766/1675729. For reference, these methods involve using the SetValue method on the PropertyInfo of the property, or otherwise invoking the setter method with reflection, or in extreme cases, setting the backing field directly. However, none of these methods seem to be working for me now, and I'm curious if something has changed that has broken this functionality.
Consider the following:
using System;
using System.Reflection;

public class Program
{
    public static void Main()
    {
        var exampleInstance = new Example();
        var exampleType = typeof(Example);
        var fooProperty = exampleType.GetProperty("Foo"); // this works fine - the "GetSetMethod" method returns null, however

        // fails with the following:
        // [System.MethodAccessException: Attempt by method 'Program.Main()' to access method 'Example.set_Foo(Int32)' failed.]
        //fooProperty.SetValue(exampleInstance, 24);

        // same error here:
        //Run-time exception (line 14): Attempt by method 'Program.Main()' to access method 'Example.set_Foo(Int32)' failed.
        //exampleType.InvokeMember(fooProperty.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty | BindingFlags.Instance, null, exampleInstance, new object[] { 24 });
    }
}

public class Example
{
    public int Foo { get; private set; }
}

The Foo property has a setter, it's just private. It also fails if I change the setter to protected, which seems even more bizarre, since it's no longer the C#6 initializer-only setter. This fails with both .NET 4.5 and .NET Core 2 as the runtime. What am I missing?

A: I was having a similar issue (with the exception that I'm using a static property) and I was able to invoke private setter like this:
public static class Example
{
    public static int Foo { get; private set; }
}

typeof(Example).GetProperty("Foo").SetMethod.Invoke(null, new object[] { 42});

Haven't tested with non-static though.

A: This behaviour is by design.
There are some strict rules that govern the ability to abuse reflection in this way.
Accessing Members That Are Normally Inaccessible
In fact if you plan on using reflection at all, in a real life secnario the entire article might be worth a read.
Security Considerations for Reflection


text:
Q: Yet another question related to sequence points Yes i read the article on sequence points. However i could not understand why ++i = 2 would invoke undefined behavior? The final value of i would be 2 regardless of anything, so how come the expression is ub?
code snippet
int main()
{
  int i =0;
  ++i=2;
  return 0;
}

Sorry my english is not very good.

A: You observe that value will be what you claim, that's how UB can manifest itself among other possible scenarios. The program might output what you expect, output some unrelated data, crash, corrupt data or spend all your money ordering pizza. Once C++ standard says that some construct is UB you should not expect any specific behavior. Observed results can vary from one program run to another.

A: The undefined behavior occurs because a compiler could implement the following code:
++i = 2;

as either:
i = 2;
++i;

or
++i;
i = 2;

It's unspecified in the language, a compiler could choose to implement either of the above. The first would produce 3 and the second 2. So it's undefined.

A: It looks obvious to you, because obviously i will first be assigned i+1, then second be assigned the value 2.
However, both of these assignments happen within the same sequence point, therefore it's up to the compiler to which happens frist and which happens second, therefore different compiler implementations can generate code that will give different results, therefore it's UB.

A: Calling ++i = 2; does not in and of itself invoke undefined behaviour; any compiler can, if it wants, do a very defined action upon reaching that code. However the c++ standard states that such an operation is undefined,therefore a compiler may do something unexpected (like delete all the files on the C drive or send a text message to the pope) and still be a compliant compiler. The only thing that makes this UB is that the standard says it is UB.
Perhaps the most important point is that one version of a compiler may do something different from the next version of the same compiler.

A: From the exact same link you are providing :

*

*Furthermore, the prior value shall be
  accessed only to determine the value
  to be stored.

  What does it mean? It means if an
  object is written to within a full
  expression, any and all accesses to it
  within the same expression must be
  directly involved in the computation
  of the value to be written.

Here on the left hand side of operator =, the access to i is not involved in the computation of the value written.

A: ++i (should be) an rvalue, and hence, can't be used as a lvalue, but (++i) = 2; should work fine.  I don't believe this is UB, but, as always, I might be wrong.


text:
Q: Sony WH-1000XM3 are connected only in hands-free mode WIN11 i got OS update to Win11 Pro. I'd like to connect my Sony WH-1000XM3 via bluetooth. I made standard connection process but my audio quality is bad. On win10 i could easiely switch between stereo/hands-free mode to solve this. I cant find any solution to this. In new bluetooth setting i can see my headphones connected with "Connected voice" message. I tried multiple solutions on web:
Drivers reinstall - no help.
Disable mic input device from headphones - no help
Advanced settings -> allow private acces from apps in unchecked - no help.
Devices and printers ->Sony WH-1000XM3 properties -> services -> unchecked Hands-Free or i tried uncheck everything except Audio Sink, Remote control - on this case i am not able to use my headphones at all, it is connected in bluetooth settings but there is no option to use them in new/old sound settings
Thanks for help


text:
Q: Not able to share image and text to facebook from android app I have made a demo android app,In that I want to share a text and an image from app to facebook,I have integrated the app with facebook,It gives me login tto,But gives an error that "06-03 18:14:27.221: D/Request(21053): Warning: Sessionless Request needs token but missing either application ID or client token.
So,Please help me and save me.My code is as below:
package com.epe.smaniquines.ui;

public class DetailsActivity extends Activity implements OnClickListener {
    ImageView proImage, ivSave, ivInfo, ivPlay, ivBak, iv_share;
    RelativeLayout rl_botm, rl_option;
    TextView tv_facebuk, tv_twiter, tv_nothanks, tv_email, tv_save;
    String big_img;
    ArrayList<String> resultArray;
    private DisplayImageOptions options;
    public static ImageLoader imageLoader;
    RelativeLayout rl_info;
    public boolean flag = false;
    int i = 0;
    private int PicPosition;
    private Handler handler = new Handler();
    int mFlipping = 0;
    ViewFlipper viewFlipper;
    Timer timer;
    int flagD = 0;
    String data;
    String shareType;
    File image;
    public static String PACKAGE_NAME;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_detail);
        PACKAGE_NAME = getApplicationContext().getPackageName();
        initialize();
        showHashKey(this);

        printKeyHashForThisDevice();
        /*
         * Intent i = getIntent(); data = i.getStringExtra("data"); shareType =
         * i.getStringExtra("type");
         */

        big_img = getIntent().getStringExtra(Const.TAG_BIG_IMG);
        resultArray = getIntent().getStringArrayListExtra("array");
        System.out.println("::::::::::::::ArraySize::::::::" + resultArray);
        imageLoader.displayImage(big_img, proImage, options);
        ivInfo.setOnClickListener(this);
        ivPlay.setOnClickListener(this);
        tv_email.setOnClickListener(this);
        tv_facebuk.setOnClickListener(this);
        tv_nothanks.setOnClickListener(this);
        tv_save.setOnClickListener(this);
        tv_twiter.setOnClickListener(this);
        iv_share.setOnClickListener(this);
        ivBak.setOnClickListener(this);
        // viewFlipper = (ViewFlipper) findViewById(R.id.flipper);
        imageLoader.displayImage(big_img, proImage, options);
        proImage.postDelayed(swapImage, 3000);

    }

    public void open(View view) {

        Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
        shareIntent.setType("*/*");
        shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello test"); // <- String
        Uri screenshotUri = Uri.parse(image.getPath());
        shareIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
        startActivity(Intent.createChooser(shareIntent, "Share image using"));
    }

    void initialize() {
        proImage = (ImageView) findViewById(R.id.iv_det);
        ivInfo = (ImageView) findViewById(R.id.iv_info);
        ivPlay = (ImageView) findViewById(R.id.iv_play);
        ivBak = (ImageView) findViewById(R.id.iv_back);
        rl_botm = (RelativeLayout) findViewById(R.id.rl_bottom);
        rl_option = (RelativeLayout) findViewById(R.id.rl_options);
        tv_save = (TextView) findViewById(R.id.tv_save);
        tv_email = (TextView) findViewById(R.id.tv_email);
        tv_facebuk = (TextView) findViewById(R.id.tv_facebook);
        tv_nothanks = (TextView) findViewById(R.id.tv_no_thanks);
        tv_twiter = (TextView) findViewById(R.id.tv_twiter);
        rl_option.setVisibility(View.GONE);

        iv_share = (ImageView) findViewById(R.id.iv_share);
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration
                .createDefault(DetailsActivity.this));
        rl_info = (RelativeLayout) findViewById(R.id.rl_info);
        rl_info.setVisibility(View.GONE);
        resultArray = new ArrayList<String>();
        ivPlay.setVisibility(View.VISIBLE);

    }

    @SuppressLint("NewApi")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.iv_share:
            rl_option.setVisibility(View.VISIBLE);

            break;

        case R.id.iv_play:
            proImage.setVisibility(View.GONE);
            AdapterViewFlipper flipper = (AdapterViewFlipper) findViewById(R.id.flipper);
            flipper.setAdapter(new FlipperAdapter(DetailsActivity.this,
                    resultArray));
            ivPlay.setVisibility(View.GONE);
            break;
        case R.id.iv_back:
            finish();
            break;
        case R.id.tv_email:
            rl_option.setVisibility(View.GONE);
            Intent email = new Intent(Intent.ACTION_SEND);
            email.putExtra(Intent.EXTRA_EMAIL,
                    new String[] { "youremail@yahoo.com" });
            email.putExtra(Intent.EXTRA_SUBJECT, "subject");
            email.putExtra(Intent.EXTRA_TEXT, "message");
            email.setType("message/rfc822");
            startActivity(Intent.createChooser(email,
                    "Choose an Email client :"));
            break;
        case R.id.tv_save:
            save();
            rl_option.setVisibility(View.GONE);
            break;
        case R.id.tv_facebook:

            facebookShare();
            /*
             * save(); open(v);
             */
            rl_option.setVisibility(View.GONE);
            break;
        case R.id.tv_no_thanks:
            rl_option.setVisibility(View.GONE);
            break;
        case R.id.tv_twiter:
            rl_option.setVisibility(View.GONE);
            break;
        case R.id.iv_info:
            rl_option.setVisibility(View.GONE);
            if (flag) {
                rl_info.setVisibility(View.VISIBLE);
                flag = false;
            } else {
                rl_info.setVisibility(View.GONE);
                flag = true;
            }

            break;

        }
    }

    public static void showHashKey(Context context) {
        try {

            PackageInfo info = context.getPackageManager().getPackageInfo(
                    "com.epe.3SManiquines", PackageManager.GET_SIGNATURES); // Your
                                                                            // package
                                                                            // name
                                                                            // here
            for (android.content.pm.Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.v("KeyHash:",
                        Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (NameNotFoundException e) {
        } catch (NoSuchAlgorithmException e) {
        }
    }

    // slide show..!!!

    MediaPlayer introSound, bellSound;
    Runnable swapImage = new Runnable() {
        @Override
        public void run() {
            myslideshow();
            handler.postDelayed(this, 1000);
        }
    };

    private void myslideshow() {
        PicPosition = resultArray.indexOf(big_img);
        if (PicPosition >= resultArray.size())
            PicPosition = resultArray.indexOf(big_img); // stop
        else
            resultArray.get(PicPosition);// move to the next gallery element.
    }

    //

    // SAVE TO SD CARD..!!
    void save() {
        BitmapDrawable drawable = (BitmapDrawable) proImage.getDrawable();
        Bitmap bitmap = drawable.getBitmap();
        File sdCardDirectory = Environment.getExternalStorageDirectory();

        File dir = new File(sdCardDirectory.getAbsolutePath()
                + "/3sManiquines/");
        image = new File(sdCardDirectory, "3s_" + System.currentTimeMillis()
                + ".png");
        dir.mkdirs();
        boolean success = false;

        // Encode the file as a PNG image.
        FileOutputStream outStream;
        try {

            outStream = new FileOutputStream(image);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            /* 100 to keep full quality of the image */

            outStream.flush();
            outStream.close();

            success = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (success) {
            addImageToGallery(dir + "", DetailsActivity.this);
            Toast.makeText(getApplicationContext(), "Image saved with success",
                    Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(),
                    "Error during image saving", Toast.LENGTH_LONG).show();
        }
    }//

    public static void addImageToGallery(final String filePath,
            final Context context) {

        ContentValues values = new ContentValues();

        values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
        values.put(Images.Media.MIME_TYPE, "image/png");
        values.put(MediaStore.MediaColumns.DATA, filePath);

        context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI,
                values);
    }

    // facebook...
    public void sharetext(String text) // Text to be shared
    {

        Intent share = new Intent(android.content.Intent.ACTION_SEND);

        share.setType("text/plain");
        share.putExtra(android.content.Intent.EXTRA_SUBJECT, "TITLE");
        share.putExtra(android.content.Intent.EXTRA_TEXT, text);
        startActivity(Intent.createChooser(share, "Share via"));
        finish();

    }

    public void shareimage(String text) // argument is image file name with
                                        // extention
    {

        Intent shareimage = new Intent(android.content.Intent.ACTION_SEND);

        shareimage.setType("*/*");// for all
        shareimage.setClassName("com.android.mms",
                "com.android.mms.ui.ComposeMessageActivity");

        shareimage.putExtra(Intent.EXTRA_STREAM, resultArray.indexOf(big_img));
        startActivity(Intent.createChooser(shareimage, "Share Image"));
        finish();
    }

    private void printKeyHashForThisDevice() {
        try {
            System.out
                    .println("::::::::::::::::::::HAsh key called:::::::::::::");
            PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME,
                    PackageManager.GET_SIGNATURES);
            for (android.content.pm.Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());

                String keyHash = Base64.encodeToString(md.digest(),
                        Base64.DEFAULT);
                System.out
                        .println(":::::::::::KEy hash:::::::::::::" + keyHash);

                System.out.println("================KeyHash================ "
                        + keyHash);

            }
        } catch (NameNotFoundException e) {
        } catch (NoSuchAlgorithmException e) {
        }
    }

    // facebook post image and text......!!
    private void facebookShare() {

        try {

            String aarti = "Hello friends this is demo for facebook.";

            FacebookShared fs = new FacebookShared(DetailsActivity.this, this);

            String vincentUrl = big_img;

            fs.setData(aarti, vincentUrl);

            fs.loginToFacebook(); // for logout dialog

        }

        catch (Exception e) {

            e.printStackTrace();

        }

    }
}

A: try this one:
public void share(String friendID, String name, String caption,
        String description, String link, String picture,
        OnCompleteListener listener) {
    if (Session.getActiveSession() == null) {
        getSession();
    }
    Bundle params = new Bundle();
    params.putString("name", name);
    params.putString("caption", caption);
    params.putString("description", description);
    params.putString("link", link);
    params.putString("picture", picture);
    if (friendID != null)
        params.putString("to", friendID);

    WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(activity,
            Session.getActiveSession(), params)).setOnCompleteListener(
            listener).build();
    feedDialog.show();
}

public void getFriends(GraphUserListCallback callback) throws Exception {
    if (Session.getActiveSession() == null) {
        getSession();
    }
    if (Session.getActiveSession() == null)
        throw new Exception();
    Request.newMyFriendsRequest(Session.getActiveSession(), callback)
            .executeAsync();
}


text:
Q: creating own application using ws4py I have created a web server socket using ws4py and which uses cherrypy.  When I connect to the server using ip:port it connects perfectly and am able to chat through multiple browsers. However when I try to connect ip:port/ws it also works.
However, after I connect without using the ws, I am unable to handshake.  I want to handle all request from client browser or it may another from different sources like using c# by this url ip:port/app and send payload from the client.
I have installed ws4py by this command sudo pip install ws4py and my server script is:
 # -*- coding: utf-8 -*-
import argparse
import random
import os

import cherrypy

from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool
from ws4py.websocket import WebSocket
from ws4py.messaging import TextMessage

class ChatWebSocketHandler(WebSocket):
    def received_message(self, m):
        print "Message Received---------------------1"
        print m
        cherrypy.engine.publish('websocket-broadcast', m)

    def closed(self, code, reason="A client left the room without a proper explanation."):
        print "Socket Closed---------------------2"
        cherrypy.engine.publish('websocket-broadcast', TextMessage(reason))

class Root(object):
    def __init__(self, host, port, ssl=False):
        print "Rooot host "+str(host)+ " Port "+str(port)+ " -----------3"
        self.host = host
        self.port = port
        self.scheme = 'wss' if ssl else 'ws'

    @cherrypy.expose
    def index(self):
        return """<html>
    <head>
      <script type='application/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js'></script>
      <script type='application/javascript'>
        $(document).ready(function() {

          websocket = '%(scheme)s://%(host)s:%(port)s/ws';
          if (window.WebSocket) {
            ws = new WebSocket(websocket);
          }
          else if (window.MozWebSocket) {
            ws = MozWebSocket(websocket);
          }
          else {
            console.log('WebSocket Not Supported');
            return;
          }

          window.onbeforeunload = function(e) {
            $('#chat').val($('#chat').val() + 'Bye bye...\\n');
            ws.close(1000, '%(username)s left the room');

            if(!e) e = window.event;
            e.stopPropagation();
            e.preventDefault();
          };
          ws.onmessage = function (evt) {
             $('#chat').val($('#chat').val() + evt.data + '\\n');
          };
          ws.onopen = function() {
             ws.send("%(username)s entered the room");
          };
          ws.onclose = function(evt) {
             $('#chat').val($('#chat').val() + 'Connection closed by server: ' + evt.code + ' \"' + evt.reason + '\"\\n');
          };

          $('#send').click(function() {
             console.log($('#message').val());
             ws.send('%(username)s: ' + $('#message').val());
             $('#message').val("");
             return false;
          });
        });
      </script>
    </head>
    <body>
    <form action='#' id='chatform' method='get'>
      <textarea id='chat' cols='35' rows='10'></textarea>
      <br />
      <label for='message'>%(username)s: </label><input type='text' id='message' />
      <input id='send' type='submit' value='Send' />
      </form>

      HI ****************************************************************************

    </body>
    </html>
    """ % {'username': "User%d" % random.randint(0, 100), 'host': self.host, 'port': self.port, 'scheme': self.scheme}

    @cherrypy.expose
    def ws(self):
        print ("request for ws------------------------------------------------------4")
        cherrypy.log("Handler created: %s" % repr(cherrypy.request.ws_handler))

    @cherrypy.expose
    def App(self):
        print ("request for App---------------------------------------------5")
        cherrypy.log("Handler created: %s" % repr(cherrypy.request.ws_handler))

if __name__ == '__main__':
    import logging
    from ws4py import configure_logger
    configure_logger(level=logging.DEBUG)

    print " Start Main ----------------------------------------------0"
    parser = argparse.ArgumentParser(description='Echo CherryPy Server')
    parser.add_argument('--host', default='192.x.x.x')
    parser.add_argument('-p', '--port', default=yyyy, type=int)
    parser.add_argument('--ssl', action='store_true')
    args = parser.parse_args()

    cherrypy.config.update({'server.socket_host': args.host,
                            'server.socket_port': args.port,
                            'tools.staticdir.root': os.path.abspath(os.path.join(os.path.dirname(__file__), 'static'))})

    if args.ssl:
        cherrypy.config.update({'server.ssl_certificate': './server.crt',
                                'server.ssl_private_key': './server.key'})

    WebSocketPlugin(cherrypy.engine).subscribe()
    cherrypy.tools.websocket = WebSocketTool()

    cherrypy.quickstart(Root(args.host, args.port, args.ssl), '', config={
        '/ws': {
            'tools.websocket.on': True,
            'tools.websocket.handler_cls': ChatWebSocketHandler
            },
        '/js': {
              'tools.staticdir.on': True,
              'tools.staticdir.dir': 'js'
            }
        }
    )

A: Could you precsie what you mean by:

However, after I connect whithot using the ws, I am unable to handshake.

Do you mean you can't use the server at all afterwards? As a remainder, you can only perform websocket upgrade on the /ws path here since that's how you configured it at the bottom of your snippet.


text:
Q: Groovy property iteration In the Groovy code below I replace the values of the feck, arse, drink properties of an instance of Foo with those of an instance of Foo2
class Foo {
    def feck = "fe"
    def arse = "ar"
    def drink = "dr"
}

class Foo2 {

    def feck = "fe2"
    def arse = "ar2"
    def drink = "dr2"
}

def f = new Foo()
def f2 = new Foo2()

["feck", "arse", "drink"].each {it ->
    f."$it" = f2."$it"
}

Is there a better way to do this? My specific concern with the code above is that the property names are stored as strings in a list, which would likely be missed when (for example) using a refactoring IDE to change one of these property names.

A: I haven't yet found a good approach for excluding the read-only properties (i.e., metaClass, class), but if you want to set the value of all properties in the Foo instance that are also in the Foo2 instance you could do the following.
class Foo {
    def feck = "fe"
    def arse = "ar"
    def drink = "dr"
}

class Foo2 {

    def feck = "fe2"
    def arse = "ar2"
    def drink = "dr2"
}

def f = new Foo()
def f2 = new Foo2()

f2.properties.each { prop, val ->
    if(prop in ["metaClass","class"]) return
    if(f.hasProperty(prop)) f[prop] = val
}

assert f.feck == "fe2"
assert f.arse == "ar2"
assert f.drink == "dr2"

A: Very late answer... however what about to take only the non synthetic declaredFields of Foo class. Using your approach:
class Foo {
    def feck = "fe"
    def arse = "ar"
    def drink = "dr"
}

class Foo2 {
    def feck = "fe2"
    def arse = "ar2"
    def drink = "dr2"
}

def f = new Foo()
def f2 = new Foo2()

Foo.declaredFields.findAll { !it.synthetic }*.name.each {it ->
    f[it] = f2[it]
}

assert f.feck == "fe2"
assert f.arse == "ar2"
assert f.drink == "dr2"

If in refactoring something change for example in Foo but not in Foo2  then an Exception will be thrown from this code advising that something is wrong.


text:
Q: Why does my while loop never end, if the boolean in my while loop updates properly? I am attempting to make a song play in the main menu of my game but when the user plays the game (gets out of the main menu) the music stops. So for this I attempted to use a while loop. I have a boolean labeled, 'startPressed' that is updated to true when the user exits the main menu. However when using this public static boolean in my while loop my while loop never ends. Here is my code:
In the beginning of the game:
try {
    Clip clip = AudioSystem.getClip();
    AudioInputStream inputStream = AudioSystem.getAudioInputStream(
            Game.class.getResourceAsStream("/mymusic.wav"));
    clip.open(inputStream); // gets the audio ready
    FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
    gainControl.setValue(-22.0f); // lowers the volume.
    clip.start(); // plays song (yes i know it only plays it once ill fix that later)
    while(!startPressed) {
    } // doesn't end
    clip.close();
    clip.stop();
} catch (Exception e) {
    System.err.println(e.getMessage());
}

The boolean I am referring to:
public static boolean startPressed = false;

What makes the variable update to true:
if (key == KeyEvent.VK_ENTER) {
    if (Game.startPressed == false) {
        Game.startPressed = true;
    }
}

Sorry for the long question I tried to put as little as possible.


text:
Q: Preloading images in Javascript I have created a simple photo gallery viewer, and I would like to preload the images in the background, and then run a function when they are done.
My question is, how do I do that?

A: var image = new Image();
image.src = "http://foo.com/myimage.jpg";

//if you have a div on the page that's waiting for this image...
var div = getElementById("imageWrapperDiv");

//you can set it on the image object as the item to draw into...
image.myDiv = div;

image.onload = function(){
  //do whatever you're going to do to display the image

  //so in this example, because I have set this objects myDiv property to a div on the page
 // I can then just populate that div with an img tag.
 //it's not the most elegant solution, but you get the idea and can improve upon it easily
  this.myDiv.innerHTML = "";
}

Once the image loads, it's in the browser's cache, so, if you use the src property you can draw it anywhere on the page and it will display instantly.

A: To preload an image use the <link> tag and add preload to the rel-attribute:
<link rel=preload href=path/to/the/image.jpg as=image>
Alternatively in Javascript:
var preImg = document.createElement('link')
preImg.href = 'path/to/image.jpg'
preImg.rel = 'preload'
preImg.as = 'image'
document.head.appendChild(preImg)

The preload value of the  element's rel attribute allows you to
  write declarative fetch requests in your HTML , specifying
  resources that your pages will need very soon after loading, which you
  therefore want to start preloading early in the lifecycle of a page
  load, before the browser's main rendering machinery kicks in. This
  ensures that they are made available earlier and are less likely to
  block the page's first render, leading to performance improvements.

Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content

A: I like this CSS method versus the typical Javascript function:
Place this in your CSS file:
div#preload { display: none; }

Place this at the bottom of your HTML document:

This method ensures that your images are preloaded and available for use elsewhere in the document. Just remember to use the same path as the the preloaded images.
http://perishablepress.com/pure-css-better-image-preloading-without-javascript/


text:
Q: What are the consequences of mutating state in a reducer? The redux guide states:

We don't mutate the state. We create a copy with Object.assign(). Object.assign(state, { visibilityFilter: action.filter }) is also wrong: it will mutate the first argument. You must supply an empty object as the first parameter. You can also enable the object spread operator proposal to write { ...state, ...newState } instead.

I happened to catch myself writing the following snippet of working code:
[actions.setSelection](state, {payload}) {
    state[payload.key] = payload.value;
    return state;
},

I had a bad vibe about it, and revisited the guide for wisdom. I have since rewritten it as this:
[actions.setSelection](state, {payload}) {
    const result = Object.assign({}, state);
    result[payload.key] = payload.value;
    return result;
},

I am fairly sure I have offended the commandment noted above elsewhere in my code.  What kind of consequence am I looking at for not tracking them down with diligence?
(Note: The reducer syntax above is via redux-actions. It would otherwise be the block of code in a reducer fn switch/case.)

A: Mutating state is an anti-pattern in React. React uses a rendering engine which depends on the fact that state changes are observable. This observation is made by comparing previous state with next state. It will alter a virtual dom with the differences and write changed elements back to the dom.
When you alter the internal state, React does not know what's changed, and even worse; it's notion of the current state is incorrect. So the dom and virtual dom will become out of sync.
Redux uses the same idea to update it's store; an action can be observed by reducers which calculate the next state of the store. Changes are emitted and for example consumed by react-redux connect.
So in short: never ever, mutate state. Instead of Object.assign you can use the stage-3 spread syntax:
{...previousState,...changes}

Also please note, this is true for arrays as well!


text:
Q: how fix props.match undefined this is my Editstudent.js
async componentDidMount() {
    const stud_id = this.props.match;
    console.log(stud_id);
}

this is my App.js
  <Routes>
    <Route exact path="/" element={<Student/>} />
    <Route path="/add-student" element={<Addstudent/>} />
    <Route path="/edit-student/:id" element={<Editstudent/>} />
  </Routes>

but i got error, it said undefined
what should I do?

A: In your case, you should wrap Editstudent.js in withRouter
import { withRouter } from "react-router";

class EditStudent extends React.Component {
   async componentDidMount() {
     const stud_id = this.props.match;
     console.log(stud_id);
   }
}

export default withRouter(EditStudent);

You can check this document for a better understanding

If you use react-router-dom v6 which does not support class-based components, you can have HOC (higher-order component) with react router hooks (useMatch, useParams, etc.) like below
import { useMatch } from "react-router-dom";

//HOC like this
function withMatch(Component) {
  return props => <Component {...props} match={useMatch()} />;
}

class EditStudent extends React.Component {
   async componentDidMount() {
     const stud_id = this.props.match;
     console.log(stud_id);
   }
}

//use `withMatch` as a wrapper
export default withMatch(EditStudent);

Or you can convert your component to function-based components and then use hooks directly
import { useMatch } from "react-router-dom";

const EditStudent = () =>  {
   const match = useMatch();
   useEffect(() => {
     const stud_id = match;
     console.log(stud_id);
   }, []) //similar to `componentDidMount`

   return

 //similar to `render()`
}

export default EditStudent;


text:
Q: Django and api widget I am relatively new in web development and I needed your help with the following.
I am creating a basic website using Django where a user can manage his portfolio.
Now I was using this widget from Tradingview.com in this manner.
Now what I wanted to know was if I could somehow store what the user was adding in the watchlist in the database itself and load it when the widget loads next time

A: Tradingview.com's widget is implemented using an iframe tag on your website, so you want to execute javascript inside the iframe so everytime a user adds to his wishlist you sent an ajax request to your django backend.
but thats not possibles if the widget is from another domain than tradingview.com

Calling a parent JS function from iframe is possible, but only when
  both the parent and the page loaded in the iframe are from same
  domain i.e. abc.com, and both are using same protocol i.e. both are
  either on http:// or https://.
The call will fail in below mentioned cases:

*

*Parent page and the iframe page are from different domain.

*They are using different protocols, one is on http:// and other is on https://.
Any workaround to this restriction would be extremely insecure.
For instance, imagine I registered the domain superwinningcontest.com
  and sent out links to people's emails. When they loaded up the main
  page, I could hide a few iframes in there and read their Facebook
  feed, check recent Amazon or PayPal transactions, or--if they used a
  service that did not implement sufficient security--transfer money out
  of their accounts. That's why JavaScript is limited to same-domain and
  same-protocol.

SOURCE: https://stackoverflow.com/a/2663118/4885802


text:
Q: Cross browser @font-face use I've been having a lot of difficulties with using custom fonts and @font-face. I'm trying to get a font consistent across the latest versions of Chrome, Safari & Firefox (shown in that order in the screenshot below:

I'm using the following to generate this:
@font-face {
    font-family: 'dineng';
    src: url('fonts/dineng.eot');
    src: url('fonts/dineng.eot?#iefix') format('embedded-opentype'),
         url('fonts/dineng.woff') format('woff'),
         url('fonts/dineng.ttf') format('truetype'),
         url('fonts/dineng.svg#dineng') format('svg');
    font-weight: normal;
    font-style: normal;
}

And:
.menu-button a {
    height:25px;
    float:left;
    border-bottom:2px solid white;
    color:#ccccff;
    text-decoration:none;
    padding:8px 21px 0px 20px;
    text-align:center!IMPORTANT;
    background-color:#00378f;
    font-size:18px;
    font-family:'dineng', Arial;
    text-shadow:0 0 1px rgba(0,0,0,0.3);
    }

I've tried all manor of font-weight's to decrease the weight but nothing effects them. I did use the CSS3 hack below on Chrome to get it to look like my PSD but that doesn't work across the other browsers:
text-shadow:0 0 1px rgba(0,0,0,0.3);

Does anyone have any suggestions before I jump out the window!!
PLEASE NOTE THAT I'M UNABLE TO USE FONT SQUIRREL!

A: Try it like this:
@font-face {
    font-family: 'dineng';
    font-style: normal;
    font-weight: normal;
    src: url('fonts/dineng.eot');
    src: url('fonts/dineng.eot?#iefix') format('embedded-opentype'),
        url('fonts/dineng.woff') format('woff'),
         url('fonts/dineng.ttf') format('truetype'),
         url('fonts/dineng.svg#dineng') format('svg');
}

Otherwise, open the .TTF file on your computer. If it already appears bold, the font WILL NOT be able to be decreased in size because that's the normal look for the font.


text:
Q: Why only some page numbers stored in XML of docx file? I have added some page number in footer. It is visible in document properly. But if i unzip docx and check the footer.xml only some random page numbers are there. so how MS-Word is able to display page numbers properly, And where it store all page numbers?

A: There's no logic as to which page numbers are stored in a Word Open XML document. Basically, the page numbers you see in the Word Open XML header/footer section are meaningless as they'll be regenerated automatically when the document is opened and may well not reflect the actual paging.
All dynamic content in Word, such as page numbering, is managed by fields. A field basically has two parts: the field code and the field result. You can see this structure in the Word Open XML.
Depending on the field type and its location, fields will be updated automatically OR will require explicit updating. PAGE fields in the header/footer area update automatically, pretty much during the entire editing experience in the Word UI.
For fields that need to be updated explicitly, Word will usually store the last result in the document. But fields that Word updates automatically may or may not store the last result. PLUS there's no guarantee that the stored result will be correct when the document is opened the next time, or if it's edited. Depending on the individual machine, page layout can change fluidly when a document is opened. So any page numbers you see in the Open XML are no guarantee to be in the same place when a document is opened.
The total number of pages, however, that's stored in the document properties could be correct - also depending on how the page layout is done when the document is next opened.
The following article contains some relevant information on field updating: https://support.microsoft.com/en-us/help/211629/which-fields-are-updated-when-you-open--repaginate--or-print-document


text:
Q: How to load a CSS dynamically in cordova I'm trying to load a CSS dynamically in cordova over a xhr request.
The loading of the CSS is not a Problem, I can load it over xhr and store it to the filesystem over the HTML5 File API. Then I can get a URL this works perfectly.
But if i create a new link element in the header by javascript, like this:
<link rel="stylesheet" type="text/css" id="skin" href="cdvfile://localhost/temporary/mydomin.tdl/skin.css">

Thy stylesheet don't have any effect, how can I force cordova to take the stylesheet in account?

A: * UPDATE:  I've got a working solution and I'll add it to my answer below *
I've found this problem and the suggested answers unfortunately haven't resolved it.
Loading the CSS data from an external PHP script via an XHR request (as my CSS data is dynamic to each page) I use:
var storeCSSURL = "https://www.example.com/dynamicCSS.php?storeID=x";
$('head').append('<link rel="stylesheet" href="' + storeCSSURL + '" type="text/css" />');

I'd also tried replacing the existing stylesheet link with the new URL; and added datetime stamp to it to prevent caching, which also didn't work.
Works great in the web browser and I know the data is loading through the XHR request and also being applied to the head CSS tag, although it doesn't work in Cordova / Phone Gap... the Apps just don't update with the CSS changes from the PHP script.
* NEW UPDATE *
I finally came up with a solution that works, it's a bit of a hack as it doesn't directly solve the problem; but works around it and is great for my needs.
In PhoneGap / Cordova, I use a pageInit.js  type scenario that loads the web page in dynamically from a PHP script, I imagine most people use it in a somewhat similar way.
After page load I added:
$("body").append('<style id="dynamicStyles"></style>');

Then simply did a $.POST request to the Dynamic CSS (PHP) file, which returned all the dynamic style data; which I then loaded into a style tag.
This looks something like this:
$.post("https://www.example.com/controller.php", { url: url }, function (data, status) {
    if (status == "success") {
        $("body").html(data);
        // Loads the main page content into the body tag
        $("body").append('<style id="dynamicStyles"></style>');
        // Appends the main page content with a style tag
        $.post("https://www.example.com/dynamicCSS.php", { storeID: storeID }, function (data, status) {
            if (status == "success") {
                $("#dynamicStyles").html(data);
                // Loads CSS data from external PHP script dynamically
                // then places it into the new style tag.
            }
        });
    }
});

The CSS updates from this line:
$("#dynamicStyles").html(data);

This loads all the new dynamic style data into the style tag; so the result is an on-page style definition, which you can replace the styles with using .html() at any stage from your external PHP with CSS data.
Phone Gap / Cordava recognises the style tag changes and updates visuals accordingly :-)
I'm sure you could set your project up to load all CSS data in this way instead of the normal head CSS link; and you'd never have that annoying CSS caching issue with Phone Gap / Cordova.
I hope this is useful to someone!

A: $('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');

A: $(document).ready(function () {

    $("a").click(function () {

        $('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');

    });

});


text:
Q: WP cron doesn't pass trough my arguments I've been trying to import some posts trough a cron action. The problem is my last step. Everything is going well, except for the execution of the cron. It is only passing trough the first argument.
Which would (clearly) point at the following code
add_action( 'import_videos_recurring', 'import_recurring', 10, 3 );

But if I execute the following code for testing purposes (simplified code). It will still pass me only one argument.
function import_recurring_3( $args ) {

    var_dump( $args );

}

function add_timething() {
    wp_schedule_event( time(), 'minutly', 'import_videos_recurring_3', array(
        'user' => 'testding',
        'value' =>'testwaarde',
        'break' => true
    ) );
}

add_action('init', 'add_timething');

add_action( 'import_videos_recurring_3', 'import_recurring_3', 10, 3 );

I've read a couple of questions & answers on the exchange here. But can't find why the following code is not working.

A: Try:
function import_recurring_3( $args, $args2, $args3 ) {
    var_dump( $args );
    var_dump( $args2 );
    var_dump( $args3 );
}


text:
Q: How to implement paginator in search results I am able to get all my items from all categories displayed on search results, now I have to add paginator on my search result for all items in categories that have been searched for. How can I implement paginator on search results to display all items in categories paginated? With my code below, the search results do not paginate all item categories properly. I do not know if itertool will be a better idea.
def search_result(request):
  query = request.GET.get('q')
  if query is None:
      return redirect("shop:homepage")
  else:
      item = Item.objects.all().order_by("timestamp")
      if item:
          item = item.filter(
                  Q(title__icontains=query)
              ).distinct()

  if item.count() == 0:
      messages.error(request, "No search results found")

  paginator = Paginator(item, 1)
  page = request.GET.get('page')
  try:
      queryset = paginator.get_page(page)
  except PageNotAnInteger:
      queryset = paginator.get_page(1)
  except EmptyPage:
      queryset = paginator.get_page(paginator.num_pages)

  context = {
      'search': item,
      'pagination': queryset,
      'query': query,
  }
  return render(request, 'search_result.html', context)

      {% if pagination.has_other_pages %}

      {% if pagination.has_previous %}

      Previous
      Previous

      {% endif %}

      {% for i in pagination.paginator.page_range %}
      {% if pagination.number == i %}

{{ i }} (current)

      {% else %}

{{ i }}

      {% endif %}
      {% endfor %}

      {% if pagination.has_next %}

        Next
        Next

      {% endif %}

      {% endif %}

A: There are two methods to access pages from Paginator object "Paginator.get_page" and "Paginator.page". Where get_page method doesn't raise any exception if given page isn't a number but Paginator.page does.  You are using using "get_page" method but catching PageNotAnInteger exception, where this exception is raised by only  Paginator.page method.
From Django documentation

Paginator.get_page(number) -> Returns a Page object with the
  given 1-based index, while also handling out of range and invalid page
  numbers.
If the page isn't a number, it returns the first page. If the page
  number is negative or greater than the number of pages, it returns the
  last page.
Raises an EmptyPage exception only if you specify Paginator(...,
  allow_empty_first_page=False) and the object_list is empty.
Paginator.page(number) Returns a Page object with the given
  1-based index. Raises InvalidPage if the given page number doesn't
  exist.

Possibility: Seems like page number you are getting via query string isn't a valid number

To make it explicit change get_page method with page method

   page = request.GET.get('page')
    try:
        pagination= paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        pagination = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        pagination = paginator.page(paginator.num_pages)

     context = {
      'search': item,
      'pagination': pagination,
      'query': query,
     }
  return render(request, 'search_result.html', context)

Use logging on server or dev tools in browser to check if page number is going well in query string


text:
Q: PHP - Choose 3 random items in array and replace 3 items with those 3 random items What's the best way to choose randomly choose 3 items out an array and
use those three items to replace another 3 items in another array. I though about using
array_slice()

But im not sure. Also my second array will be different each time. I've just include example below:
$array1 = array('A','A','A','A','A');
$array2 = array('C','A','A','E','D');
for($i = 0; $i < 3; $i++){

    $min = 0;
    $max = 4;
    $n = rand($min, $max);

    $array1[$n] = $array2[$n];
}

A: This code will take 3 random elements from the first array, and replace 3 random items in the second array
<?php

$array1 = array('A','A','A','A','A');
$array2 = array('C','A','A','E','D');

$max1 = count($array1);
$max2 = count($array2);

for($i=0;$i<3;$i++) {
    $n1 = rand(0, $max1);
    $n2 = rand(0, $max2);

    $array2[$n2] = $array1[$n1];
}


text:
Q: iOS UIDatepicker accessibility with overridden minute interval I am using a UIDatePicker with a "time" mode and setting minuteinterval property to 30. I do see the time picker displaying time options in increments of 30 so that part works. The issue is accessibility where when i focus on the minutes section it keeps saying (00 minutes, picker item, adjustable, 35 out of 60). My problem is with the 35 out of 60. Shouldn't it read 1 out of 2 Since there are only two options (0 and 30)?
Screenshot of voiceover focus
Here is the code I use to setup the datepicker
datePicker.datePickerMode = .time
datePicker.minuteInterval = 30
datePicker.frame = CGRect(x: 0, y: 0, width: frame.width, height: 200)

// Set some of UIDatePicker properties
datePicker.timeZone = NSTimeZone.local
datePicker.backgroundColor = UIColor.white


text:
Q: javascript confirm function return false I want to show a message which writing are you sure …
I can show the message but user click NO return false; did not work

I call function with onclick here
echo 'SilDüzenle	';

A: You need to use the return value:

Just having it inside the onclick will execute the function but to actually cancel the click, you need to use the return value.
Also, the code can be slightly optimized:
function askCar(){
    return confirm ("Are you sure for deleting car ?");
}

No need in if..else when you can directly return the dialog result. (unless of course you want to perform exra actions)

A: You need to add the return also:
echo '
    Sil
    Düzenle
    	';

A: Your onclick function needs to use the return value:
echo '

            Sil

             Düzenle

      	';

A: When you use return within your function definition, you must have to use return in the place where you are calling that. Otherwise, you will not get proper result. So, the best code would be below
echo 'SilDüzenle	';


text:
Q: Citation numbering figures and tables after main text I am preparing a manuscript for submission to nature communications. Their formatting instructions are found here:
https://www.nature.com/ncomms/submit/how-to-submit
In particular, in the sections references they ask:
"References should be numbered sequentially first throughout the text, then in tables, followed by figures and, finally, boxes; that is, references that only appear in tables, figures or boxes should be last in the reference list."
I have a very large number of citations in the captions for my figures (it's a review plot). I was wondering if there was an easy way to specify this citation behavior or a way of doing it manually. I am not using bibtex, just the built in \cite{}.

A: All relevant instructions for you to heed are actually furnished in the link you provide. However, these instructions may not be easy to grasp if one is not at least somewhat familiar with basic publishing work flow.
Here are the most pertinent instructions:

All textual content should be provided in a single file.
To submit a TeX/LaTeX file, please use any of the standard class files such as article.cls, revtex.cls or amsart.cls. All textual material should be provided as a single file in default Computer Modern fonts. Please avoid non-standard fonts and packages and remove all personal macros before submitting. For graphics, we recommend graphicx.sty [and that package's \includegraphics macro].
The manuscript text file should include the following parts, in order: a title page with author affiliations and contact information (the corresponding author should be identified with an asterisk); the sections ... then References, Acknowledgements (optional), Author Contributions (Articles only), Competing Interests statement, [and figure and table environments].
Please use numerical references only for citations, and include the references within the manuscript file itself.  If you wish to use BibTeX, please copy the reference list from the .bbl file, paste it into the main manuscript .tex file, and delete the associated \bibliography and \bibliographystyle commands. [emphasis added. See also below]
Before submission, please ensure that the complete .tex file compiles successfully on your own system with no errors or warnings.
There is no need to spend time visually formatting the manuscript: our style will be imposed automatically when the paper is prepared for publication.

So what does all this mean for you?

*

*Make sure you've finished writing your paper. In particular, have you \cited all pieces you wish to cite? Perform a full recompile cycle: LaTeX, BibTeX, and LaTeX twice more. Mare sure that there are no unresolved syntax errors, unresolved cross-references, or citation call-outs. Eliminate all typos and other mistakes of content.

*Move all figure environments to the very end of the main tex file.

*Move all table environments (if any) to after the figure environments, i.e., to the very end of the main tex file.

*Perform a full recompile cycle: LateX, BibTeX, and LaTeX twice more. Be sure to check that there are no unresolved references or citation call-outs. And, crucially, do verify that the numeric-style citation call-outs that pertain to \cite instructions that occur in the figure environments occur after all others, numerically speaking. If the ordering isn't right, you probably didn't run BibTeX properly. Make sure you BibTeX do run it properly.

*Delete (or comment out) the \bibliography and \bibliographystyle instructions in the main tex file, as per the instructions reproduced above. Do not delete the instruction that loads the cite package (likely: \usepackage{cite}).

*Find the file \jobname.bbl, where \jobname is the name of your main tex file. Open this file and copy and paste the entire contents of this file into the main tex file, right where the \bibliography statement used to be. (The contents of the bbl file will likely start with \begin{thebibliography} and end with \end{thebibliography}.)

*Save the main tex file and perform two more LaTeX runs (no BibTeX runs, though, as there should be no more \bibliography or \bibliographystyle instructions). Look closely at the pdf file to make sure that all citation call-outs continue to be correct and that they occur in the required order.

*Finally, assuming you have 5 external graphics files, you should be uploading (a) the main tex file and (b) the 5 external graphics files, using the publisher's software.


text:
Q: How regenerate lexers and parsers in python with ATN? How regenerate lexers and parsers in python. I am new to this and I don't know what to do. The error I got is as follows:
In 'pddlLexer.py':
class pddlLexer(Lexer):
In 'pddlLexer.py':
atn = ATNDeserializer().deserialize(serializedATN())
In ATNDeserializer.py:
self.checkVersion()
In ATNDeserializer.py:
raise Exception("Could not deserialize ATN with version " + str(version) + " (expected " + str(SERIALIZED_VERSION) + ").")
Exception: Could not deserialize ATN with version  (expected 4).
The last error is the one I am  trying to resolve.
I was trying to parse a PDDL problem to visualize a plan using the 'planning_graph' package from this link:
https://github.com/debbynirwan/planning_graph


text:
Q: Установить ограничения в storyboard для картинки Доброй ночи, возник один вопрос, никогда не любил подгонять картинки дизайнеров под разные разрешения экрана. У меня есть изображение в png (@1x, @2x, @3x), я добавляю его на экран (подгоняю под iphone 5s). Выставляю ограничения по краям и по ширине с высотой. Когда тестирую на 5s, то все отлично, а когда на 6 или 6 plus, то оно значительно уменьшается. Подскажите как установить ограничения или может быть что-то другое нужно сделать?

p.s. Не обращайте внимание на стрелку спидометра, еще не дошли руки для ее установки)

A: Попробуйте:
Фиксированное расстояние до лево-право-верх и фиксированный aspect ratio если constraints;

или если autoresizing mask то флексибл все, кроме bottom:
view.autoresizingMask = UIViewAutoresizingFlexibleTopMargin |
                        UIViewAutoresizingFlexibleLeftMargin |
                        UIViewAutoresizingFlexibleRightMargin |
                        UIViewAutoresizingFlexibleWidth |
                        UIViewAutoresizingFlexibleHeight;


text:
Q: Laravel model where function I try to retrive data from database in laravel model, but my sql is wrong. I dont know why where dont work, set only keys without values.
        $passwordReset = PasswordReset::where([
            ['email', $request->get('email')],
            ['token', $request->get('token')]
            ])->toSql();

Array
(
    [token] => TCjM8BZXjLV1YfikyFDjeUwZMUmS5w5r88rEYOMC8XmkET779kjCQEkM9w1u
    [email] => mail@example.com
)

select * from password_resets where (email = ? and token = ?)
    print_r($request->json()->all());

A: use ->get()->toArray();
instead of toSql()
The first one will output your data in array format the second one will output the mysql query.


text:
Q: Computing cyclic decomposition of $\mathbb{R}^3$ w.r.t. a matrix I am trying to compute the cyclic decomposition of a $3\times 3$ nontriangular matrix $A$, whose minimal polynomial is not equal to the characteristic polynomial, which guarantees that the space $\mathbb{R}^3$ is not $A$-cyclic. I computed it by some method, but I want to know whether my method is ad-hoc or is there any systematic way?
$$A=
\begin{bmatrix}-1 & 2 & 2\\2 & -1 & 2\\2 & 2 & -1\end{bmatrix} \hskip5mm \mbox{(operating from left on column space $\mathbb{R}^3$)}$$
Step 1. Compute characteristic polynomial of $A$ (it is $(x+3)^2(x-3)$).
Step 2. Compute minimal polynomial of $A$ (it is $(x+3)(x-3)$).
Step 3. Invariant factors for $A$ are $(x+3)$ and $(x+3)(x-3)$
(means, $\mathbb{R}^3$ has decomposition into subspaces $W_1\oplus W_2$ where $W_1,W_2$ are $A$-cyclic subspaces, with minimal polynomials $(x+3)$ and $(x+3)(x-3)$ respectively.)
Step 4. To get $A$-cyclic space for $x+3$, take any eigenvector for eigenvalue $-3$:
$$
(A+3I)\begin{bmatrix}a_1 \\ a_2\\a_3\end{bmatrix}=0 \hskip5mm \Leftrightarrow \hskip5mm
\begin{bmatrix} 2 & 2 & 2\\2 & 2 & 2\\2 & 2 & 2\end{bmatrix}\begin{bmatrix}a_1 \\ a_2\\a_3\end{bmatrix}=0  \hskip5mm \Rightarrow \mbox{ we can take } \begin{bmatrix}a_1 \\ a_2\\a_3\end{bmatrix}=
\begin{bmatrix} 0 \\ 1 \\ -1\end{bmatrix}
$$
Put
$$
W_1=
\left\langle \begin{bmatrix} 0 \\ 1 \\ -1\end{bmatrix}\right\rangle
$$
Step 5. To get $A$-cyclic space for $(x+3)(x-3)$, take a vector $v$ not in $W_1$; for example, we can take $v=\begin{bmatrix} 1 \\ 0 \\ 0\end{bmatrix}$. Then,
$$
W_2=
\left\langle
v, Av
\right\rangle =
\left\langle
\begin{bmatrix} 1 \\ 0 \\ 0\end{bmatrix}, \hskip5mm
\begin{bmatrix} -1 \\ 2 \\ 2\end{bmatrix}
\right\rangle.
$$
Step 6. Final decomposition:
$$
\mathbb{R}^3=
\left\langle \begin{bmatrix} 0 \\ 1 \\ -1\end{bmatrix}\right\rangle
\oplus
\left\langle
\begin{bmatrix} 1 \\ 0 \\ 0\end{bmatrix}, \hskip5mm
\begin{bmatrix} -1 \\ 2 \\ 2\end{bmatrix}
\right\rangle
= \,\,\,\,\,
\begin{Bmatrix}
\begin{bmatrix}
0 \\ c\\ -c
\end{bmatrix}
\end{Bmatrix}
\,\,\,\,
\oplus \,\,\,\,
\begin{Bmatrix}
\begin{bmatrix}
a \\ b \\ b
\end{bmatrix}
\end{Bmatrix}.
$$
Question: Is this way of obtaining decomposition systematic, or one can suggest other more systematic approach? (for shortning arguments, we can use symbols $e_1,e_2,e_3$ for standard vectors etc; but I am worrying about method.)

A: There is an algorithm to find a cyclic decomposition of a matrix systematically. However, the justification of the algorithm is quite involved, so allow me to present you the algorithm, without justifying it first (i'll try to give you the ideas though).
This will work over arbitrary fields, so let $K$ be a field, and let $M\in M_n(K)$.
Part I. Preliminaries on matrices with coefficients in $K[X]$.
Let $S\in M_n(K[X])$. Let $L_1,\ldots,L_n$ its rows, and $C_1,\ldots,C_n$ its columns.
By elementary operations on rows, we will mean operations of the form $L_i\leftarrow L_i+Q L_j, Q\in K[X],i\neq j$, exchanging $L_i$ and $L_j$, or $L_i\leftarrow \lambda L_i, \lambda\in K^\times$ (and NOT $\lambda\in K[X]\setminus\{0\})$.
By elementary operations on columns, we will mean operations of the form $C_j\leftarrow C_j+Q C_i, Q\in K[X],i\neq j$, exchanging $C_i$ and $C_j$, or $C_i\leftarrow \lambda C_i, \lambda\in K^\times$ (and NOT $\lambda\in K[X]\setminus\{0\})$.
For $i\neq j$, we will denote by $T_{ij}(Q)$ the triangular matrix with $1$'s on the diagonale, $Q$ in position $(i,j)$ and $0$ elsewhere. We will denote by $S_{ij}$ the matrix with $1's$ in position $(i,j)$ and $(j,i)$ and $0$ elsewhere. If $\lambda\in K^\times$, we will denote by $D_i(\lambda)$ the diagonal matrix with $1's$ in position $(j,j),j\neq i$ and $\lambda$ in position $(i,i)$.
Matrices $T_{ij}(Q)$ will be called transvection matrices, matrices $S_{ij}$ will be called transposition matrices, matrices $D_i(\lambda)$ will be called dilatation matrices.
Note that these matrices are all invertible, viewed as matrices with coefficients in $K(X)$, and their inverses are matrices of $M_n(K[X])$. More precisely $T_{ij}(Q)^{-1}=T_{ij}(-Q),S_{ij}^{-1}=S_{ij},D_i(\lambda)^{-1}=D_i(\lambda^{-1})$.
The three row operations (resp. column operations) on $S$ described above correspond to left multiplication (resp. right multiplication) by $T_{ij}(\lambda),S_{ij},D_i(\lambda)$.
Theorem. There exist two matrices $U,V\in M_n(K[X])$ which are products of transvection, transposition and dilation matrices such that $USV=\begin{pmatrix}I_{n-r} &  & &\cr  & P_1  & & \cr & & \ddots & \cr & & & P_r\end{pmatrix}$, where $P_1,\ldots,P_r$ are monic non constant polynomials such that $P_1\mid P_2\cdots\mid P_r$.
Proof. This is equivalent to say that we may perform rows ad columns operations to transform $S$ into a diagonal matrix satisfying the conditions of the theorem.
The idea is to pick two non zero elements on the first row (say) of $S$ , and to perform Euclid algorithm to replace one of the elements by their gcd using the appropriate column operations. Doing that a certain number of times, we will get to the point where all the elements of the first row are multiple of the same element. We use again column operations to put this element in position $(1,1)$ and  make zeroes appear. Then do the same on column 1. We will get a matrix of the form $\begin{pmatrix}\Delta & 0\cr & S'\end{pmatrix}$. If the coefficients of $S'$ are all multiple of $\Delta$ do the same on $S'$ and continue. Otherwise, choose a row  on which there is a coefficient which is not a multiple of $\Delta$, add it to row $1$, and start over again. The process will end at some point to lead to a diagonal matrix. Now rearrange columns to get the right order of the diagonal coefficients.
Part II. Description of the algorithm.

*

*Step 1. Compute two matrices $U,V\in M_n(K[X])$ which are products of transvection, transposition and dilation matrices such that $U(XI_n-M)V=\begin{pmatrix}I_{n-r} &  & &\cr  & P_1  & & \cr & & \ddots & \cr & & & P_r\end{pmatrix}$, where $P_1,\ldots,P_r$ are monic non constant polynomials such that $P_1\mid P_2\cdots\mid P_r$.

*Step 2.  Compute $U^{-1}$.

*Step 3. Let $X_1,\ldots, X_r$ the last $r$ columns of $U^{-1}$.
Write $X_j=\begin{pmatrix}R_{1j}\cr\vdots\cr R_{nj}\end{pmatrix}$.
Compute $v_j=\displaystyle\sum_{i=1}^n R_{ij}(M)e_i$.
Thm. If $d_j=\deg(P_j)$,  set $V_j=Span(v_j,Mv_j,\ldots,M^{d_1-1}v_j)$. Then $K^n=V_1\oplus\cdots\oplus V_r$ will be a cyclic decomposition, and the matrix $P$ of the family $(v_1,\ldots,M^{d_1-1}, \ldots,v_r,Mv_r,\ldots,M^{d_r-1}v_r)$ into the canonical basis  will satisfy $P^{-1}MP=\begin{pmatrix}C_{P_1} & & \cr & \ddots & \cr & & C_{P_r}\end{pmatrix}$.
Computational remarks. We only need to keep track of row operations, so it's a good idea to perform as much as column operations as possible. Moreover, you can compute $U^{-1}$ step by step, and then perform steps 1) and 2) together.
Indeed , you have $U=U_mU_{m-1}\cdots U_1$, where $U_k$ is the matrix you used corresponding to the $k$-th row operation you did. Note that each $U_k$ is a transvection/transposition/dilatation matrix, so its inverse is known by the formulas above.
Then $U^{-1}=U_1^{-1}\cdots U_m^{-1}$. Thus, initializing $U^{-1}=I_n$ at the beginning of the algorithm, you can perform the computation step by step.
Worked example. Let $M=\begin{pmatrix}\phantom{-}1&\phantom{-}0&\phantom{-}0 \cr \phantom{-}0&\phantom{-}1&\phantom{-}0\cr -4&-1&-1\end{pmatrix}.$
We have
$XI_3-M=\left(\begin{array}{ccc}X-1&0&0\cr 0&X-1&0\cr 4&1&X+1\end{array}\right).$
We will compute $U^{-1}$ step by step, and we initialize by  $U^{-1}=I_3$.
Abusing notation, we will still denote by $U^{-1}$ the matrix found at each step. If $S_1,S_2\in M_n(K[X])$, we will denote by $S_1\sim S_2$
when $S_2$ is obtained from $S_1$ by elementary operations.
We have
$$XI_3-M\sim \left(\begin{array}{ccc}0&X-1&0\cr X-1&0&0\cr 1&4&X+1\end{array}\right)\sim \left(\begin{array}{ccc}1&4&X+1\cr X-1&0&0\cr 0&X-1&0\end{array}\right)$$
so
$$U^{-1}=\left(\begin{array}{ccc}0&0&1\cr 0&1&0\cr 1&0&0\end{array}\right).$$
Then, we get
$$XI_3-M\sim \left(\begin{array}{ccc}1&0&0\cr X-1&4-4X&1-X^2\cr 0&X-1&0\end{array}\right)\sim \left(\begin{array}{ccc}1&0&0\cr 0&4-4X&1-X^2\cr 0&X-1&0\end{array}\right)$$
and thus
$$U^{-1}=\left(\begin{array}{ccc}0&0&1\cr 0&1&0\cr 1&0&0\end{array}\right)\left(\begin{array}{ccc}1&0&0\cr X-1&1&0\cr 0&0&1\end{array}\right)=\left(\begin{array}{ccc}0&0&1\cr X-1&1&0\cr 1&0&0\end{array}\right).$$
Next, we have
$$ XI_3-M\sim \left(\begin{array}{ccc}1&0&0\cr 0&X-1&0\cr 0&4-4X&1-X^2\end{array}\right). $$
We then have
$$U^{-1}=\left(\begin{array}{ccc}0&0&1\cr X-1&1&0\cr 1&0&0\end{array}\right)\left(\begin{array}{ccc}1&0&0\cr 0&0&1\cr 0&1&0\end{array}\right)=\left(\begin{array}{ccc}0&1&0\cr X-1&0&1\cr 1&0&0\end{array}\right).$$
Therefore
$$ XI_3-M\sim \left(\begin{array}{ccc}1&0&0\cr 0&X-1&0\cr 0&0&1-X^2\end{array}\right). $$
We then have
$$U^{-1}=\left(\begin{array}{ccc}0&1&0\cr X-1&0&1\cr 1&0&0\end{array}\right)\left(\begin{array}{ccc}1&\phantom{-}0&0\cr 0&\phantom{-}1&0\cr 0&-4&1\end{array}\right)=\left(\begin{array}{ccc}0&\phantom{-}1&0\cr X-1&-4&1\cr 1&\phantom{-}0&0\end{array}\right).$$
Finally
$$XI_3-M\sim \left(\begin{array}{ccc}1&0&0\cr 0&X-1&0\cr 0&0&X^2-1\end{array}\right),$$
mutiplying the last column by $-1$, which does not change $U$.
All in all,
$$ U^{-1}=\left(\begin{array}{ccc}0&\phantom{-}1&0\cr X-1&-4&1\cr 1&\phantom{-}0&0\end{array}\right). $$
Set
$$v_1=\left(\begin{array}{r}1\cr -4\cr 0\end{array}\right) \quad \mbox{ and  } \quad v_2=\left(\begin{array}{c}0\cr 1\cr 0\end{array}\right).$$ (the fact that there are no $X$ in $v_1,v_2$ is a pure coincidence. Normally, there are some $X's$ and you need to perform step 3) )
Let
$$v_3=f(v_2)=\left(\begin{array}{r}0\cr 1\cr -1\end{array}\right). $$
The theorem above shows that
$$f(v_1)=v_1,\quad f(v_2)=v_3 \quad \mbox{ and } \ \, f(v_3)=v_2,$$
a fact that you can check by hand
If $P$ is the base change matrix, we then get  $$P^{-1}MP=\left(\begin{array}{ccc}1&0&0\cr 0&0&1\cr 0&1&0\end{array}\right).$$
Part III. Proof the algorithm.
Later in the weekend.


text:
Q: Google Maps setIcon to update path (not URL) I can't seem to find any documentation about updating the path of an icon (marker) in the Google Maps API. In this particular example I'm trying to change the fillOpacity of the icon from 0 to 1.
var myIcon = {
  path: google.maps.SymbolPath.CIRCLE,
  scale: 5,
  fillColor: "#ff00ff",
  fillOpacity: 0,
  strokeColor: "#ff00ff",
  strokeWeight: 2
};

var marker = new google.maps.Marker({
  position: position,
  icon: myIcon,
  map: map,
  title: 'My Marker>'
});

marker.addListener('click', function() {
  this.setOptions({icon:{fillOpacity: 0.5}}); // Not working
  this.setIcon({fillOpacity: 0.2}); // Not working either
});

A: The "icon" is an anonymous object.  You need to set the whole object again:
marker.addListener('click', function() {
  myIcon.fillOpacity = 0.5;
  this.setIcon(myIcon);
});

or:
marker.addListener('click', function() {
  myIcon.fillOpacity = 0.5;
  this.setOptions({
    icon: myIcon
  });
});

proof of concept fiddle

code snippet:

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {
      lat: -25.363882,
      lng: 131.044922
    }
  });
  var myIcon = {
    path: google.maps.SymbolPath.CIRCLE,
    scale: 5,
    fillColor: "#ff00ff",
    fillOpacity: 0,
    strokeColor: "#ff00ff",
    strokeWeight: 2
  };

  var marker = new google.maps.Marker({
    position: map.getCenter(),
    icon: myIcon,
    map: map,
    title: 'My Marker>'
  });

  marker.addListener('click', function() {
    myIcon.fillOpacity = 0.5;
    this.setIcon(myIcon);
  });
}
html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}