Q: Sqlite wont save data added I'm making an app, which needs a sqlite database. I can add data and view it, but on each restart of the app, closing, reopening the data get deleted. Why is that?
DB Handler:
package com.spxc.wakeuptext.sql;

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

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

public class DatabaseHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "contactsManager";

    // Contacts table name
    public static final String TABLE_CONTACTS = "contacts";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NO = "phone_number";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                + KEY_PH_NO + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

        // Create tables again
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    public // Adding new contact
    void addContact(WhiteList contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName()); // Contact Name
        values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone

        // Inserting Row
        db.insert(TABLE_CONTACTS, null, values);
        db.close(); // Closing database connection
    }

    // Getting single contact
    WhiteList getContact(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        WhiteList contact = new WhiteList(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2));
        // return contact
        return contact;
    }

    // Getting All Contacts
    public List<WhiteList> getAllContacts() {
        List<WhiteList> contactList = new ArrayList<WhiteList>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                WhiteList contact = new WhiteList();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setName(cursor.getString(1));
                contact.setPhoneNumber(cursor.getString(2));
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }

        // return contact list
        return contactList;
    }

    // Updating single contact
    public int updateContact(WhiteList contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName());
        values.put(KEY_PH_NO, contact.getPhoneNumber());

        // updating row
        return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
    }

    // Deleting single contact
    public void deleteContact(WhiteList contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
        db.close();
    }

    // Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }

}

And I have my activity which is adding 1 record on startup just to have something there. My activity / fragment:
package com.spxc.wakeuptext.frag;

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

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.spxc.wakeuptext.R;
import com.spxc.wakeuptext.sql.DatabaseHandler;
import com.spxc.wakeuptext.sql.WhiteList;

public class Fragment_2 extends SherlockListFragment{

    private ArrayList<String> results = new ArrayList<String>();
    private String tableName = DatabaseHandler.TABLE_CONTACTS;
    private SQLiteDatabase newDB;
    private static final int ADD = 1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        View v = inflater.inflate(R.layout.fragment_2, null);
        return v;
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        DatabaseHandler db = new DatabaseHandler(getActivity());
        db.addContact(new WhiteList("Ravi", "9100000000"));

        openAndQueryDatabase();
        displayResultList();
    }

    private void openAndQueryDatabase() {
        try {
            DatabaseHandler dbHelper = new DatabaseHandler(getActivity().getApplicationContext());
            newDB = dbHelper.getWritableDatabase();
            Cursor c = newDB.rawQuery("SELECT name, phone_number FROM " +
                    tableName, null);

            if (c != null ) {
                if  (c.moveToFirst()) {
                    do {
                        String firstName = c.getString(c.getColumnIndex("name"));
                        int age = c.getInt(c.getColumnIndex("phone_number"));
                        results.add("Name: " + firstName + ",Pne: " + age);
                    }while (c.moveToNext());
                }
            }
        } catch (SQLiteException se ) {
            Log.e(getClass().getSimpleName(), "Could not create or Open the database");
        } finally {
            if (newDB != null)
                newDB.execSQL("DELETE FROM " + tableName);
                newDB.close();
        }

    }

    private void displayResultList() {
        TextView tView = new TextView(getActivity());
        tView.setText("This data is retrieved from the database and only 4 " +
                "of the results are displayed");
        getListView().addHeaderView(tView);

        setListAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, results));

        getListView().setTextFilterEnabled(true);

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        MenuItem search = menu.add(0, ADD, 0, "Refresh");
        search.setIcon(android.R.drawable.ic_menu_add);
        search.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case ADD:
                addNumber();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void addNumber(){
        LayoutInflater factory = LayoutInflater.from(getActivity());

        final View textEntryView = factory.inflate(R.layout.text_entry, null);

        final EditText name = (EditText) textEntryView.findViewById(R.id.editText1);
        final EditText phone = (EditText) textEntryView.findViewById(R.id.editText2);

        name.setHint("Name");
        phone.setHint("Phone Number");

        final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
        alert.setTitle(
          "Contact information").setView(
          textEntryView).setPositiveButton("Save",
          new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog,
             int whichButton) {
               DatabaseHandler db = new DatabaseHandler(getActivity());
               db.addContact(new WhiteList(name.getText().toString(), phone.getText().toString()));
               openAndQueryDatabase();
               displayResultList();
           }
          }).setNegativeButton("Cancel",
          new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog,
             int whichButton) {
             /*
             * User clicked cancel so do some stuff
             */
           }
          });
        alert.show();
    }
}

Why isn't my database data getting saved? I'm running the app on a real device. All the data get deleted on reopening the app. Any help is much appreciated!

A: This is because you are deleting all records from the table in every openAndQueryDatabase()
finally {
        if (newDB != null)
            newDB.execSQL("DELETE FROM " + tableName);
            newDB.close();
    }

A:
I guess your are again recreating the database again ..every time application
  starts

A: Yes, because creating your db code is in onCreate method.
    public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_PH_NO + " TEXT" + ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}


Q: How to remove products from a JSON-formatted list? (using an ID) here is an example of the JSON generated from values retrieved from my database:
    {
    "product": [
        {
            "id": "1",
            "title": "producta",
            "size": "50",
            "weight": "1000",
            "quantity": "100",
            "cartID": "1"
        },
        {
            "id": "2",
            "title": "productb",
            "size": "50",
            "weight": "1000",
            "quantity": "100",
            "cartID": "2"
        },
        {
            "id": "3",
            "title": "productb",
            "size": "10",
            "weight": "9000",
            "quantity": "100",
            "cartID": "3"
        },
        {
            "id": "4",
            "title": "productd",
            "size": "100",
            "weight": "500",
            "quantity": "100",
            "cartID": "4"
        },
        {
            "id": "5",
            "title": "producta",
            "size": "45",
            "weight": "880",
            "quantity": "120",
            "cartID": "5"
        }
    ]
}

When the user selects to remove an item from the shopping cart, the variable $remove_cartid is passed to  my PHP page. If  $remove_cartid = 4, then the product with "cartID": "4" must be removed:
    {
    "product": [
        {
            "id": "1",
            "title": "producta",
            "size": "50",
            "weight": "1000",
            "quantity": "100",
            "cartID": "1"
        },
        {
            "id": "2",
            "title": "productb",
            "size": "50",
            "weight": "1000",
            "quantity": "100",
            "cartID": "2"
        },
        {
            "id": "3",
            "title": "productb",
            "size": "10",
            "weight": "9000",
            "quantity": "100",
            "cartID": "3"
        },
        {
            "id": "5",
            "title": "producta",
            "size": "45",
            "weight": "880",
            "quantity": "120",
            "cartID": "5"
        }
    ]
}

I have made several attempts using the PHP explode function to try and remove the product from the JSON list, but I feel that there is a better way (one that will actually work)
Any advice or help is greatly appreciated

A: $list = json_decode($jsonList, true);

foreach ($list['product'] as $key => $product) {
    if ($product['cartID'] == $remove_cartid) {
        unset($list['product'][$key]);
    }
}

$jsonList = json_encode($list);


Q: Pandas Similar Function to COUNTIFS Sample Data
Please see Sample Data image.  I'm trying to replicate the COUNTIFS functionality within Python / Pandas but I'm having troubles finding the correct solution.
=COUNTIFS(B:B,"BD*",A:A,A2,C:C,">"&C2)
B is the Type column, A is the Reference column, and C is the Doc Condition column.  So the count is only greater than zero if the Type is 'BD', the Reference Matches the current row's Reference, and the Doc Condition is greater than the current row's Doc Condition.  I hope that makes sense?
I've tried coming to a solution using GroupBy but I'm not getting any closer to my desired solution and I think I'm overcomplicating this.

A: You should include your input data as text. Screenshots are really hard to work with.
You can use numpy broadcasting. However, this will have an n^2 computational complexity since you are comparing every row against every other row:
reference, type_, doc_condition = df.to_numpy().T
match = (
    (type_[:, None] == "BD")
    & (reference[:, None] == reference)
    & (doc_condition[:, None] < doc_condition)
)
df["COUNTIFS"] = match.sum(axis=1)

Within the snippet above, you can read reference[:, None] as "the Reference value of the current row; reference as "the Reference values of all rows". This is what enables the comparison between the current row and all other rows (including itself) by numpy.


Q: Is Colorama required for Flask or Click? I'm trying to do the Flask "Hello World" tutorial and when I do the 'flask run' command on terminal I get the following traceback:
PS C:\Users\boymeetscode\PycharmProjects\beerRPG> flask run
Traceback (most recent call last):
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\Scripts\flask-script.py", line 9, in <module>
    sys.exit(main())
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\flask\cli.py", line 990, in main
    cli.main(args=sys.argv[1:])
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\flask\cli.py", line 596, in main
    return super().main(*args, **kwargs)
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\core.py", line 1062, in main
    rv = self.invoke(ctx)
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\core.py", line 1668, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\core.py", line 1404, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\core.py", line 763, in invoke
    return __callback(*args, **kwargs)
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\decorators.py", line 84, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\core.py", line 763, in invoke
    return __callback(*args, **kwargs)
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\flask\cli.py", line 844, in run_command
    show_server_banner(get_env(), debug, info.app_import_path, eager_loading)
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\flask\cli.py", line 678, in show_server_banner
    click.echo(f" * Environment: {env}")
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\utils.py", line 294, in echo
    file = auto_wrap_for_ansi(file)  # type: ignore
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\_compat.py", line 541, in auto_wrap_for_ansi
    import colorama
ModuleNotFoundError: No module named 'colorama'

I am on Windows, Python 3.9.7 and did the pip install flask in my venv so if colorama is a dependency I would expect that it would have been installed automatically. Why isn't it?
Update: I manually installed colorama and now Flask works. I'm just still confused why if this is a dependency it wasn't installed automatically. My pip install didn't appear to return any errors.

A: Can confirm something in conda or click broke recently: colorama is missing after installing click (which was installed for black in my case). I use conda environment files so instead of manually installing I added a more recent version with
  - conda-forge::click

in the .yml file.
Then conda update installed click 8.03 and colorama, over click 8.0.1 which I had. Without an env file conda install -c conda-forge click should do the trick.
I do not know what exactly fixed it though, it is not in click's release notes: though there was arecent change to always install colorama, that was in version 8.0.0.


Q: Calling type-bound procedure for an array of derrived types in Fortran Let's assume that I have a derived type Coordinates with its type-bound procedure swap:
module myTypes
    implicit none
    public :: Coordinates

    type Coordinates
        real :: x,y
    contains
        procedure :: swap  ! Error here
    end type
contains
    subroutine swap(this)
        class (Coordinates) :: this
        this%x = this%x + this%y
        this%y = -(this%y - this%x)
        this%x = this%x - this%y
    end subroutine
end module

Now, if I have an instance of Coordinates called point_A, and if I want to call the type-bound procedure swap for it, I would just write: call point_A%swap. But if I have an array of instances of Coordinates, like:
type(Coordinates), dimension(:), allocatable :: setOfPoints

then to call the swap for all the elements of setOfPoints, I would like to write:
call setOfPoints(:)%swap

In order to achieve that, I change the code of swap procedure to:
subroutine swap(these)
        class (Coordinates), dimension(:)  :: these
        integer :: i
        do i = 1, size(this)
            this(i)%x = this(i)%x + this(i)%y
            this(i)%y = -(this(i)%y - this(i)%x)
            this(i)%x = this(i)%x - this(i)%y
        end do
end subroutine

Unfortunately, gfortran doesn't like my idea. On the line that I marked in the first piece of code it says:
Error: Passed-object dummy argument of 'swap' must be scalar.

Question: how can I call the type-bound procedure for all the instances of the derived type at once? I don't want to put the call in the loop, but I want to do this as I wrote it before, like what we always do with arrays in Fortran.
I read about the ELEMENTAL keyword, but if I want to use it, I need the type-bound procedure to be 'pure', which is not my case.
I tried to place a DEFERRED keyword after the word procedure, but then compiler says:
Error: Interface must be specified for DEFERRED binding

I created an interface for swap, but I couldn't figure out where to place it. I tried many positions and compiler said that 'interface was unexpected there'.
Also, I read about SELECT TYPE, but I think it won't help in my case.

A: Your specific example is perfectly fine with ELEMENTAL
module myTypes
    implicit none
    public :: Coordinates

    type Coordinates
        real :: x,y
    contains
        procedure :: swap  ! Error here
    end type
contains
    elemental subroutine swap(this)
        class (Coordinates), intent(inout) :: this
        this%x = this%x + this%y
        this%y = -(this%y - this%x)
        this%x = this%x - this%y
    end subroutine

end module

 use myTypes

 type(Coordinates) :: arr(10)

 arr = Coordinates(1.,2.)

 call arr%swap

 end

Your subroutine is pure. If it cannot be, consider using impure elemental.


Q: In Python, how to format string while saving in a file Is it possible to format strings while saving in a file, similar when printing to a console?
f = open('test.txt', 'w')
f.write('{0:10} {1:10}').format('one', 'two')
f.close()

A: Yes it is. I think that one of your closing parenthesis was not where you meant it to be:
with open('test.txt', 'w') as f:
    f.write('{0:10} {1:10}'.format('one', 'two'))


Q: Google Cloud Platform, ML Engine, "No module named absl" I am trying to train an object detector using TensorFlow following the following tutorial: https://cloud.google.com/blog/products/gcp/training-an-object-detector-using-cloud-machine-learning-engine
The tutorial asks to use object_detection.train, however this has been moved to legacy so I've used object_detection.model_main instead. Line 21 of this python file calls the module absl, however this causes the following error (from the GCP Logs Viewer).

Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py",
  line 162, in _run_module_as_main "main", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in
  run_globals File
  "/root/.local/lib/python2.7/site-packages/object_detection/model_main.py",
  line 21, in  from absl import flags ImportError: No module
  named absl

I tried to include absl>=0.1 in the required packages section of the setup.py file for the object_detection package but that didn't work. Next I tried to move my absl folder into the models/research/object_detection directory before packaging and starting the job, but that didn't work either. How do I fix this? I'm very new to Tensorflow and the GCP platform so your help will be appreciated. Thanks.

A: The package that you should be adding to REQUIRED_PACKAGES list in setup.py is 'absl-py>=0.1.0'. Apart from that, download this package tar.gz file to models/research/dist . Install by running pip install absl-py . Then, when starting the job add dist/avsl-0.4.0.tar.gz to the variables passed to the --packages flag.


Q: create J2me launcher Hi I have to create J2me launcher in which when I run the emulator then icon is displayed when I click on it, then it will redirect me to the website which I have given. I have researched it on internet but I cannot find any solution Please if anyone can help me please help me and it there are any suggestions then give me.

A: Why don't you use something like this:
platformRequest("http://ololo.com");

It will call a default browser to open the link.

A:  public void openBrowser(String URL) {
        try {
            mainMIDlet.platformRequest(URL);
        } catch (ConnectionNotFoundException e) {
            // error
        }
    }


Q: counting the vowels, without using raw input and the string 's' is defined.My result a infinite loop, whats wrong in it k=0
if (s[-1] == "a" or s[-1] == "e" or s[-1] == "i" or s[-1] == "o" or s[-1] == "u"):
    k=1
else:
    K=0
t=len(s)-1
while t>=0:
if (s[t-1:t] == "a"  or  s[t-1:t] == "e"  or s[t-1:t] == "i" or s[t-1:t] == "o" or s[t-1:t] == "u"):

    t=t-1

    k=k+1

else:

    t=t-1
print "Number of vowels:", k

A: simply use for loop to iterate every character from the string.
Demo:
In [28]: s = "qazxswedcvfrgbnhyujmkiopl"

In [29]: count = 0

In [30]: for i in s:
   ....:     if i.lower() in ["a", "i", "o", "u", "e"]:
   ....:         count += 1
   ....:

In [31]: print count
5


Q: how to synchronize between cuda kernel function? I have two cuda kernel functions like this
a<<<BLK_SIZE,THR_SIZE>>>(params,...);
b<<<BLK_SIZE,THR_SIZE>>>(params,...);

After function a started, I want to wait until a finishes and then start function b.
so I inserted cudaThreadSynchronize() between a and b like this,
a<<<BLK_SIZE,THR_SIZE>>>(params,...);
err=cudaThreadSynchronize();
if( err != cudaSuccess)
    printf("cudaThreadSynchronize error: %s\n", cudaGetErrorString(err));
b<<<BLK_SIZE,THR_SIZE>>>(params,...);

but cudaThreadSynchronize() returns error code: the launch timed out and was terminated cuda error
how can I fix it?

A simple code explanation:
mmap(sequence file);
mmap(reference file);

cudaMemcpy(seq_cuda, sequence);
cudaMemcpy(ref_cuda,reference);

kernel<<<>>>(params); //find short sequence in reference
cudaThreadSynchronize();
kernel<<<>>>(params);

cudaMemcpy(result, result_cuda);
report result

and in kernel function, there is a big for loop which contains some if-else for the pattern matching algorithm to reduce number of comparisons.

A: This launch error means that something went wrong when your first kernel was launched or maybe even something before that. To work your way out of this, try checking the output of all CUDA runtime calls for errors. Also, do a cudaThreadSync followed by error check after all kernel calls. This should help you find the first place where the error occurs.
If it is indeed a launch failure, you will need to investigate the execution configuration and the code of the kernel to find the cause of your error.
Finally, note that it is highly unlikely that your action of adding in a cudaThreadSynchronize caused this error. I say this because the way you have worded the query points to the cudaThreadSynchronize as the culprit. All this call did was to catch your existing error earlier.


Q: How to get the image from a facebook photo comment? Either API or FQL, I am trying to get the photo submitted as comment in a photo post.
To make clearer here is what I am saying

*

*I post a photo on my page timeline.

*people now post comments on the said photo

*either text comment or attaching photo in each comment.

Now, what I am getting is the comment information only.
I want to get the information about the photo used in comment also.
Thanks.

A: The picture (in the comment) could be fetched with the attachment parameter.
By default, you did not get the attachment field in the result, so you have to write this field explicitly. just like this -
me/posts?fields=comments.message,comments.id,comments.attachment

Demo
Ref: Comments

A: This is the same for page comments as I just discovered:
/{page-post-id}/comments?fields=from,message,id,attachment,created_time,comments.fields(from,message,id,attachment,created_time)
this will return all replies (and replies to those replies) for a particular page post. if there is an image on a reply it will be under 'attachment'
result is a bit like this:

Array
(
    [data] => Array
        (
            [0] => Array
                (
                    [from] => Array
                        (
                            [name] => ***********
                            [id] => ***********
                        )

                    [message] => test reply with a picture
                    [id] => ***********
                    [attachment] => Array
                        (
                            [type] => photo
                            [target] => Array
                                (
                                    [id] => ***********
                                    [url] => ***********
                                )

                            [url] => ***********
                            [media] => Array
                                (
                                    [image] => Array
                                        (
                                            [height] => 540
                                            [src] => ***********
                                            [width] => 720
                                        )

                                )

                        )

                    [created_time] => 2014-03-29T11:59:53+0000
                )

            [1] => Array
                (
                    [from] => Array
                        (
                            [name] => ***********
                            [id] => ***********
                        )

                    [message] => ***********
                    [id] => ***********
                    [created_time] => 2014-03-29T11:55:09+0000
                )

            [2] => Array
                (
                    [from] => Array
                        (
                            [name] => ***********
                            [id] => ***********
                        )

                    [message] => ***********
                    [id] => ***********
                    [created_time] => 2014-03-29T11:16:45+0000
                    [comments] => Array
                        (
                            [data] => Array
                                (
                                    [0] => Array
                                        (
                                            [from] => Array
                                                (
                                                    [name] => ***********
                                                    [id] => ***********
                                                )

                                            [message] => ***********
                                            [id] => ***********
                                            [created_time] => 2014-03-29T11:18:07+0000
                                        )

                                    [1] => Array
                                        (
                                            [from] => Array
                                                (
                                                    [name] => ***********
                                                    [id] => ***********
                                                )

                                            [message] => ************
                                            [id] => ***********
                                            [created_time] => 2014-03-29T11:18:48+0000
                                        )


Q: How to access a dynamically created control's value in a gridview in ASP.NET I can't figure out how to access the value of a control in a dynamically-created gridview. Thhe problem is that I don't know the name of the control. If I knew the name of the control I could do just do this :
string dropDownListText =((DropDownList).row.FindControl("DropDownList1")).SelectedItem.Value;`

I know the type of control and I know the cell it is in. Is there any way using the information about the control I have to be able to access the control's value?

A: If you know what cell it is, then you could do something like this;
TableCell tc = GridView1.Cells[indexOfCell];
// where GridView1 is the id of your GridView and indexOfCell is your index
foreach ( Control c in tc.Controls ){
    if ( c is YourControlTypeThatYouKnow ){
        YourControlTypeThatYouKnow myControl = (YourControlTypeThatYouKnow)c;
    }
}

If you don't know what cell it is exactly, then you can always loop through each cell. I am sure there is a better way in Linq.
With Linq (I think this should work)
var controls = GridView1.Cells[indexOfCell].Cast<Control>();
YourControlTypeThatYouKnow myControl = (YourControlTypeThatYouKnow) controls.Where( x => x is YourControlTypeThatYouKnow).FirstOrDefault();

A: On ItemDataBound event handler of GridView, access the table-cell as follows. Within the cell, Controls collection provides you access to ASP control embedded in the cell
TableCell cell = e.Item.Cells[0];
if (cell.Controls.Count > 0)
{
   cell.Controls[0].Visible = false;
}

A: I have had the same problem. Add a command name to your field like CommandName="ProjectClick". Then add a rowcommand and in the row command do this:
if (e.CommandName.Equals("ProjectClick")) {
}

or you can use the text:
if (e.CommandName.Equals("")) {
    if (((System.Web.UI.WebControls.LinkButton)(e.CommandSource)).Text.Equals("Projects")) {
    }
}


Q: ServiceStack Clients and Ambiguous Routes I have a service stack service we'll call Orders that has the standard GET routes

*

*/orders - Gets All Customers

*/orders/{Ids} - Gets Specific customers

This works all fine and dandy, but I thought I'd add another route

*

*/orders/customers/{CustomerId} -Gets orders with a specific customer id

This works find when hitting the routes in the browser, but when I use the ServiceStack Client I get ambiguous routes exception, and it lists the three routes.
I'm not quite sure what the best way around this is..is what I'm doing not the correct RESTish way to it?
I know I can simply manual enter the routes into the JsonServiceClient like
client.Get<List<Orders>>("/orders/customers/7")
and that will work, but I would prefer to do it the typed way...i.e
client.Get(new OrdersRequest { CustomerId = 7 });
Here's an example RequestDTO i'm using
public class OrdersRequest : IReturn<List<Orders>>
{
   public int[] Ids {get; set;}
   public CustomerId {get; set;}

   public OrdersRequest(params int[] ids)
   {
        this.Ids = ids;
   }
}

Do I have to use different Dtos for this or...?
any help or pointers to any of the samples that have a way around this, or a better way to create the services would be appreciated.
Thanks

A: My advise is you're not using REST properly. There is a good answer about how to best structure a ServiceStack REST service. It's a common issue when starting out, I had issues like this too.
Understanding your use case:
In your specific case if we look at /orders/customers/7 this would work better is you think of it this way:

/customers/7/orders

The reason you do it this way:

*

*It resolves your route ambiguity problems

*The context is clear. We can see we are working with Customer 7 without navigating a long url

*We can see 'with customer 7' we want their orders

Think of routing like this:
/orders                   Everybody's Orders
/orders/1                 Order 1 (without being aware of the customer it belongs to)
/customers                All Customers
/customers/7              Customer 7's details
/customers/7/orders       All Customer 7's orders
/customers/7/orders/3     Customer 7's order number 3

The beauty of doing things like this is operations on data are done consistently. So you want to find all cancelled orders:
/orders/cancelled

You want to cancel a specific order by it's orderId
/orders/4/cancel

You want to list a specific customer's open orders
/customers/6/orders/open

You want to list customer 6's cancelled orders
/customers/6/orders/cancelled

You want to cancel an order for customer 6 that you are viewing
/customers/6/orders/2/cancel

Obviously these are just scenarios, your routes will differ.
Simplifying action handlers:
You will probably want to define your action handlers so they can cope with coming from multiple routes. What I mean is, one action handler would be responsible for Listing Orders
/orders
/customers/6/orders

What I do is this:
[Route("/orders","GET")]
[Route("/customers/{CustomerId}/orders","GET")]
public class ListOrdersRequest : IReturn<List<Order>>
{
    public int? CustomerId { get; set; }
}

So you can see the two order listing routes come in. If they use /orders then our customerId won't have a value but the other route will. So in our action handler we can simply test for this:
public List<Order> Get(ListOrdersRequest request)
{
    // Use `CustomerId` to narrow down your search scope

    if(request.CustomerId.HasValue){
        // Find customer specific orders
    } else {
        // Find all orders
    }

    return orders;
}

Client-side concerns:
So to address your using 'typed' client concerns. Creating the routes and action handlers using the above method will allow you to do:
client.Get(new ListOrdersRequest { CustomerId = 7 }); // To get customer 7's orders
client.Get(new ListOrdersRequest()); // All orders

Thus giving you 1 clear method for Listing Orders.
Final thoughts:
Obviously it means you will have to rework what you have which will probably be a pain, but it's the best approach, well worth the effort.
I hope this helps you understand the best structure.

Update:
@stefan2410 requested that I address the issue of Kyle's use of an int[] in a route for a GET request:
If you want to use an int[] in a GET request you have to consider changing it during transport in the URL so it can be used RESTfully.
So you could do this:
class OrdersRequest
{
    public string Ids { get; set; }

    public OrdersRequest(int[] ids)
    {
        Ids = string.Join(",", Array.ConvertAll(ints, item => item.ToString()));
    }
}

client.Get(new OrdersRequest(new [] {1,2,3}));

Creates the route /orders/1,2,3 and matches /orders/{Ids}. The problem with doing this is in order to use the Ids at the server side you have to convert the string "1,2,3" back to an int[].
The better way to deal with an int[] in a request is to use POST. So you can do:
class OrdersRequest
{
    public int[] Ids { get; set; }

    public OrdersRequest(int[] ids)
    {
        Ids = ids;
    }
}

client.Post(new OrdersRequest(new[] {1,2,3}));

Creates the route /orders and matches the route /orders.


Q: Exception safety in the composite pattern I used the composite pattern to represent devices, which I would like to shut down before killing their power (calling their dtor).
I ran into a problem trying to group the devices, especially regarding their state.
How would I proceed in the following scenario:
class IDevice
{
public:
    virtual void shutdown() = 0;
    virtual void turn_on() = 0;
    virtual bool is_on() const = 0;
}

class Router: public IDevice {...};
class Computer: public IDevice {...};
class Monitor: public IDevice {...};
// etc...

class WorkStation: public IDevice {...};

The work station might contain several devices, and you'd want to shut all of them down safely before killing the station electricity. (In this metaphor, I'm very cheap).
It is also worth noting that I would never want any one of the devices turned on on its own - Everything will always act as one unit.
The problem comes when one of the inner devices doesn't want to shut down safely - It will throw an exception (e.g. A computer's program prevents it from shutting down).
What should is_on() return in that state? what should consecutive method calls do?
Alternatively, what is another design pattern can I use to represent my problem better?

A: The main big problem is that you want to throw from the dtor.
https://www.kolpackov.net/projects/c++/eh/dtor-1.xhtml has a nice explanation of why this does not play nicely with the language and its idioms.
In general, if you expect that a device can fail at shutting down, then you should probably handle this part explicity, because it not something that happens "exceptionally".
For example, you could have the destructor try to gracefully shut off the device, and in case of errors (or exceptions), apply a force shut off. then, if the user of your system wants to handle the case of a device that can't shut off, he can still call shutoff directly.
Finally, modeling from real world objects is just a first draft of your class design. don't worry to notstick to what the real world object do, if it helps to get a more practical design and a better UX.


Q: How to print value after enabledelayedexpansion Setting a variable in a "setlocal enabledelayedexpansion" works with
set HASGCC=0
for /f "delims=" %%i in (...) do (
        setlocal enabledelayedexpansion
            set HASGCC=1
        endlocal
    )

but sadly a echo after doesn't result in the correct value (always 0).
   echo Finished %HASGCC%

Afterwards
if !HASGCC! == 0  >>"%PREFS_F...

is evaluated correct.
How to print correct value.
echo Finished !HASGCC!

results in

Finished !HASGCC!

A: Solved it by removing
setlocal enabledelayedexpansion

but don't know why.

A: setlocal with or without EnableDelayedExpansion creates a new scope for variables.
It makes a copy of all variables and then all changes are made to these copies.
An endlocal leaves this scope and discard the copy and all changes are dsicarded.
For some variable manipulations you have to enable delayed expansion for some it's better to use disabled delayed expansion, but the only way to switch between them is to use setlocal.
But in your case it seems, that you don't need it at all.


Q: Redirect to another controller/action in anther application I have to build an ASP.NET MVC 3 application that can redirect to other ASP.NET MVC 3 applications by calling their controller/action. I was thinking of just building the URL. I would have to know the controller/action names and the host. I was thinking of storing the Host strings in a database so if the app is moved I would be able to update the database with this information without making changes to code and recompiling. I'm just not sure if this is the best approach. Any help would really be appreciated.

A: In general, 3rd party integration is always easier and more maintainable when it's done in a black box manner. Rather than integrate based on how a 3rd party implements their solutions, you integrate based on their black box facade, so that you don't have to deal with knowing their implementation details.
Comparing it to a SQL query - a SQL query typically describes just what you want, rather than how you want the database server to retrieve what you want.

A: Yes - you absolutely have to know the controllers and action names unless you share a common routing table. However if you think if the destination application as a service, then this is fine as you have restful urls to the service endpoints, as would be typical in any app that calls a service. I would however store these in a single location - as you mentioned table, config file, etc.


Q: ModuleNotFoundError: No module named 'win32crypt' I'm trying to run a Python module for a school project and I am getting this error ModuleNotFoundError: No module named 'win32crypt' at line import win32crypt.
I've search the website for solution and encountered a post that states pywin32 is required. So I installed it with pip. I also tried installing pypiwin32. None of these installs worked. Now I've tried Dependency Walker to see if there are any dependencies missing and I see at least 100 DLLs that are. How can I fix the issue?

A: win32cryrpt is a part of the Windows Extensions for Python or pywin32. It is a wrapper around the Windows crypto API. It doesn't make sense to try and install it without pywin32 and if your install of that has failed then that is the problem you have to solve.
Please try pip install pypiwin32 again, being sure to execute it in the correct folder, which is the Scripts subfolder of the Python environment you want to install it in. You may have more than one Python installation without realizing it, and if you run pip from outside that folder, you may get a different instance of pip. The standard location for Python installations is C:\Program Files\Python3x. If the pip install doesn't complete as expected then edit your question to include the messages from the failed install. Did not work isn't enough to go on.


Q: CSS code for pinterest layout style My challenge is trying to make the listing grid view looking like pinterest similar layout.
I've already made a little code with it... but it's not enough.
the rows below don't fit each other.
#content .category_grid_view li.featured {  position:relative; -moz-border-radius:3px;  -webkit-border-radius:3px; }
#content .category_grid_view li .featured_img { width:69px; height:72px;     position:absolute; left:15px; top:0px; text-indent:-9009px; }
#content .category_grid_view li p.timing { margin:0; padding:0; }
#content .category_grid_view li p.timing span { color:#000; }
#content .category_grid_view li .widget_main_title { height:25px;overflow:hidden; clear:left;}
#content .category_grid_view li a.post_img {height:auto;width:100%;padding:1%;}
#content .category_grid_view li a.post_img img{height:100%;max-height:100%;width:auto;}
#page .category_grid_view {
width: auto;
padding-left:0px;
}
#content .category_grid_view li a.post_img {
height:auto;
max-width:100%;
overflow:hidden;
}
#content .category_grid_view li a.post_img img {
margin:0 auto;
display:block;
height:auto;
}
#content .category_grid_view {
margin:-10 0 20px -15px;
padding:0;
width:650px;
clear:both;
}
#content .category_grid_view li {
background: none repeat scroll 0 0 transparent;
float: left;
list-style: none outside none;
margin: -10 0 20px;
padding: 0 0 0 15px;
position: relative;
width: 200px;
}
#content .category_grid_view li.hr {
display: none;
}
#content {
float: left;
overflow: hidden;
padding-left: 5px;
width: 640px;
}
#content .category_grid_view li a.post_img {
display: block;
margin-bottom: 0;
padding: 0;
background: none repeat scroll 0 0 #FFFFFF;
border: 0 solid #E2DFDF;
box-shadow: 0 0 0 #DDDDDD;
height: auto;
width: 100%;
overflow: hidden;
}
#content .category_grid_view li a.post_img img {
height: auto;
overflow: hidden;
width: 100%;
}
#content .category_grid_view li.featured a.post_img {
border: 0 solid #B1D7E0;
}
#content .category_grid_view li .widget_main_title {
padding-top: 7px;
clear: left;
height: 25px;
overflow: hidden;
background: none repeat scroll 0 0 #EBEBEB;
}
#content .category_grid_view li .rating {
background: none repeat scroll 0 0 #EBEBEB;
display: block;
margin: 0px 0;
padding-bottom: 7px;
padding-top: 7px;
}
#content .category_grid_view li p.review {
background: none repeat scroll 0 0 #EBEBEB;
border-bottom: 10px solid #EBEBEB;
border-top: 1px solid #EBEBEB;
color: #EBEBEB;
margin-bottom: 20px;
padding: 5px 0;
}

This is how it looks like:
http://images.findout-macau.com/2013/09/grid-view-rows.png
Meanwhile, i've made search through the web and only found out the following code... yet i don't know how to implement it. Can  someone tip me here? Like where tu insert what?!
html, body{
margin:auto;
width:100%;
background-color:#e6e6e6;
}
#wrapper {
width: 100%;
margin: 10px auto;
}
#columns {
-webkit-column-count: 4;
-webkit-column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-count: 4;
-moz-column-gap: 10px;
-moz-column-fill: auto;
column-count: 4;
column-gap: 10px;
column-fill: auto;
}
.pin {
display: inline-block;
background: #FEFEFE;
border: 2px solid #FAFAFA;
box-shadow: 0 1px 2px rgba(34, 25, 25, 0.4);
margin: 0 2px 15px;
-webkit-column-break-inside: avoid;
-moz-column-break-inside: avoid;
column-break-inside: avoid;
padding: 15px;
padding-bottom: 5px;
background: -webkit-linear-gradient(45deg, #FFF, #F9F9F9);
opacity: 0.85;
-webkit-transition: all .3s ease;
-moz-transition: all .3s ease;
-o-transition: all .3s ease;
transition: all .3s ease;
}

A: You'll need to use a jQuery plugin of some kind to help close all those gaps you're seeing. As James mentioned, masonry is a very popular option. Another plugin (without as many options/features) is jQuery Waterfall. Both have lots of examples to help get you up and running.

A: You should insert the code that you have found in to an .css file, then link to it from your html file and use the classes/id's provided (eg. ".pin" "#columns") on the elemts you want to stylize with the code you found

A: This is small library which implements Pinterest layout. Filling the grid goes from left to right. Count of columns can be customized in config for each resolution. Columns adaptive changes on resize. Image can be at up or down of pin.
https://github.com/yury-egorenkov/pins-grid


Q: SSIS :: How to implement SCD type 2 in SSIS without using SCD Wizard. When incoming dataset has multiple records for the same Business Key In SSIS, if an incoming dataset has multiple records for the same Business Key, how do I load it to the dimensions table with SCD type 2 without using the SCD Wizard.
Sample dataset
Customer ID   Name      Segment     Postal Code
1             James     Corporate   50026
2             Andrew    Consumer    33311
3             Steven    Consumer    90025
2             Andrew    Consumer    33306
3             Steven    Consumer    90032
1             James     Corporate   50087
3             Steven    Consumer    90000

In my case, if I try Loading the dimension table with other SSIS components (Lookup/Conditional Split) all the record show up a new row in the table because they are all coming in all at the same time.
I have ‘CurrentFlag’ as the indicator of the current record.
In SSIS, if I have an incoming dataset that has multiple records for the same Business Key, How do I get to recognize these, and set the CurrentFlag as necessary, whether or not a record in the target table has that Business Key already?
Thanks.

A: OK, this is a massive simplification because SCD's are very challenging to correctly implement. You will need to sit down and think critically about this. My answer below only handles ongoing daily processing - it does not explain how to handle historical files being re-processed, which could potentially result in duplicate records with different EffectiveStart and End Dates.
By definition, you will have an existing record source component (i.e., query from the database table) and an incoming data source component (i.e., a *.csv flatfile). You will need to perform a merge join to identify new records versus existing records. For existing records, you will need to determine if any of the columns have changed (do this in a Derived Column transformation).
You will need to also include two columns for EffectiveStartDate and EffectiveEndDate.
IncomingEffectiveStartDate = FileDate
IncomingEffectiveEndDate = 12-31-9999
ExistingEffectiveEndDate = FileDate - 1

Note on 12-31-9999: This is effectively the Y10K bug. But, it allows users to query the database between date ranges without having to consciously add ISNULL(GETDATE()) in the WHERE clause of a query in the event that they are querying between date ranges.
This will prevent the dates on the columns from overlapping, which could potentially result in multiple records being returned for a given date.
To determine if a record has changed, create a new column called RecordChangedInd of type Bit.
(ISNULL(ExistingColumn1, 0) != ISNULL(IncomingColumn1, 0) ||
 ISNULL(ExistingColumn2, 0) != ISNULL(IncomingColumn2, 0) ||

....

ISNULL(ExistingColumn_N, 0) != ISNULL(IncomingColumn_N, 0) ? 1 : 0)

Then, in your split condition you can create two outputs: RecordHasChanged (this will be an INSERT) and RecordHasNotChanged (this will be an UPDATE to deactivate the exiting record and an INSERT).
You can conceivably route both inputs to the same INSERT destination. But, you will need to be careful suppress the update record's ExistingEffectiveEndDate value that deactivates the date.


Q: Reindex a dataframe using tickers from another dataframe I read csv files into dataframe using
from glob import glob
import pandas as pd

def read_file(f):
    df = pd.read_csv(f)
    df['ticker'] = f.split('.')[0]
    return df

df = pd.concat([read_file(f) for f in glob('*.csv')])
df = df.set_index(['Date','ticker'])[['Close']].unstack()

And got the following dataframe:
                 Close
ticker            AAPL        AMD        BIDU        GOOGL          IXIC
Date
2011-06-01   12.339643   8.370000  132.470001   263.063049   2769.189941
.
.
.

now I would like to use the 'ticker' to reindex another random dataframe created by
data = np.random.random((df.shape[1], 100))
df1 = pd.DataFrame(data)

which looks like:
          0         1         2         3         4         5         6   \...
0   0.493036  0.114539  0.862388  0.156381  0.030477  0.094902  0.132268
1   0.486184  0.483585  0.090874  0.751288  0.042761  0.150361  0.781567
2   0.318586  0.078662  0.238091  0.963334  0.815566  0.274273  0.320380
3   0.708489  0.354177  0.285239  0.565553  0.212956  0.275228  0.597578
4   0.150210  0.423037  0.785664  0.956781  0.894701  0.707344  0.883821
5   0.005920  0.115123  0.334728  0.874415  0.537229  0.557406  0.338663
6   0.066458  0.189493  0.887536  0.915425  0.513706  0.628737  0.132074
7   0.729326  0.241142  0.574517  0.784602  0.287874  0.402234  0.926567
8   0.284867  0.996575  0.002095  0.325658  0.525330  0.493434  0.701801
9   0.355176  0.365045  0.270155  0.681947  0.153718  0.644909  0.952764
10  0.352828  0.557434  0.919820  0.952302  0.941161  0.246068  0.538714
11  0.465394  0.101752  0.746205  0.897994  0.528437  0.001023  0.979411

I tried
df1 = df1.set_index(df.columns.values)

but it seems my df only has one level of index since the error says
IndexError: Too many levels: Index has only 1 level, not 2

But if I check the index by df.index it gives me the Date, can someone help me solve this problem?

A: You can get the column labels of a particular level of the MultiIndex in df by MultiIndex.get_level_values, as follows:
df_ticker = df.columns.get_level_values('ticker')

Then, if df1 has the same number of columns, you can copy the labels extracted to df1 by:
df1.columns = df_ticker


Q: IDEA+Gradle: exclude sources from tree and compilation? In IDEA 2019 I have created a Gradle project and added the following lines to the build.gradle file:
plugins {
    id 'java'
}
sourceSets {
    main {
        java {
            srcDir "../src"
            include "com/example/abc/**"
            exclude "com/example/abc/tst/**"
        }
    }
}

When compiling the project, the compiler apparently does what I expect: starting from the ../src folder, it compiles only the abc package and subpackages except the tst subpackage.
However, in the IDEA sources tree on the left-hand side, the whole content of src is displayed. It makes it harder to navigate in the project and to understand what is compiled and what is not.
Obviously, IDEA is parsing the .gradle file because it correctly understands the ..\src location of my sources. But for some reason it doesn't respect the include and exclude statements. What should I do to make IDEA display exactly the same content which is being compiled?
I know I can hide a folder using the "Mark directory as excluded" context menu. But this is a bad solution because it forces me to make the same thing twice in different places and discredits the concept of having everything in the .gradle file.


Q: how to add custom scroll bar for textbox and listbox in c# winforms Can some explain thoroughly or share your source code on how to change textbox / listbox scroll bar to custom scroll bar on c# winforms.
Cause textbox and listbox doesnt have a scroll attribute like on panel. Thanks! Cant find a source code here to study, all i get is locating the scroll position using the GetScrollInfo API. I want to learn how set values or adapt my scroll bar to the default listbox and textbox. Thanks!


Q: R on MacOS Error: vector memory exhausted (limit reached?) I'm trying to run an R script (in particular, I am using the "getLineages" function from the Bioconductor package, Slingshot.
I'm wondering why the error "vector memory exhausted (limit reached?)" is showing up when I use this function, as it doesn't seem to be the most memory-intensive function compared to the other functions in this package (with the data I am analyzing).
I do understand that there are other questions like this on Stackoverflow, but they all suggest to switch over to the 64-bit version of R. However, I am already using this version. There seem to be no other answers to this issue so far, I was wondering if anyone might know?
The data is only ~120mb in size, which is far less than my computer's 8GB of RAM.

A: This can be done through R studio as well.
library(usethis)
usethis::edit_r_environ()

when the tab opens up in R studio, add this to the 1st line: R_MAX_VSIZE=100Gb (or whatever memory you wish to allocate).
Re-start R and/or restart computer and run the R command again that gave you the memory error.

A: I had the same problem, increasing the "R_MAX_VSIZE" did not help in my case, instead cleaning the variables no longer needed solved the problem. Hope this helps those who are struggling here.
rm(large_df, large_list, large_vector, temp_variables)

A: For those using Rstudio, I've found that setting Sys.setenv('R_MAX_VSIZE'=32000000000), as has been suggested on multiple StackOverflow posts, only works on the command line, and that setting that parameter while using Rstudio does not prevent this error:
Error: vector memory exhausted (limit reached?)
After doing some more reading, I found this thread, which clarifies the problem with Rstudio, and identifies a solution, shown below:
Step 1: Open terminal,
Step 2:
cd ~
touch .Renviron
open .Renviron

Step 3: Save the following as the first line of .Renviron:
R_MAX_VSIZE=100Gb

Step 4: Close RStudio and reopen
Note: This limit includes both physical and virtual memory; so setting _MAX_VSIZE=16Gb on a machine with 16Gb of physical memory may not prevent this error. You may have to play with this parameter, depending on the specs of your machine

A: I had this problem when running Rcpp::sourceCpp("my_cpp_file.cpp"), resulting in
Error: vector memory exhausted (limit reached?)

changing the Makevars file solved it for me. Currently it looks like
CC=gcc
CXX=g++
CXX11=g++
CXX14=g++
cxx18=g++
cxx1X=g++
LDFLAGS=-L/usr/lib


Q: How can I get the path of a file from an OpenFileDialog and pass it to a PDFReader? (C#) OpenFileDialog ofd = new OpenFileDialog();
private void button1_Click(object sender, EventArgs e)
{
    ofd.Filter = "PDF|*.pdf";
    if (ofd.ShowDialog() == DialogResult.OK)
    {
           richTextBox1.Text = ofd.SafeFileName;
    }

}
public static string pdfText(string path)
{
     //this is the error, I cannot get the path of the File I chose from the OpenFileDialog
    PdfReader reader = new PdfReader(ofd.FileName);
    string text = string.Empty;

    for (int page = 1; page <= reader.NumberOfPages; page++)
    {
        text = text += PdfTextExtractor.GetTextFromPage(reader, page);

    }
    reader.Close();
    return text;
}

I need to get the path of the file chosen by the user from the OpenFileDialog but I cant pass it to the PDFReader

A: 1) you cannot use a class variable in a static method so accessing ofd in this line:
PdfReader reader = new PdfReader(ofd.FileName);

should result in an compiler error message that

for the non-static field 'ofd' an object instance is required.

2) It seems that you are not calling your method. You need to call it and pass the filename as parameter into it
private void button1_Click(object sender, EventArgs e)
{
    ofd.Filter = "PDF|*.pdf";
    if (ofd.ShowDialog() == DialogResult.OK)
    {
           richTextBox1..Text = pdfText(ofd.SafeFileName);
    }
}

Then you need to use the method parameter inside the method:
public static string pdfText(string path)
{
     //this is the error, I cannot get the path of the File I chose from the OpenFileDialog
    PdfReader reader = new PdfReader(path); // Here use path

Now the returned string should appear in your richTextBox1


Q: Match string begins and ends with consonant In order to matches any string that begins and ends with a consonant, while no consonants in between, I know that r'^[b-df-hj-np-tv-z][^b-df-hj-np-tv-z]*[b-df-hj-np-tv-z]$' works. But I would like to know, what is the problem with r'^[^aeiou\s][aeiou]*[^aeiou\s]$'? It seems that it doesn't work. And by the way, what are the difference between '^ string $' and '\b string \b' Thank you!


Q: Which of the different type of mobile apps has the worst access to native APIs ? and WHY? my question is which of the different type of mobile apps has the worst access to native APIs ? and WHY?, the option is:Native Apps\Mobile Web Apps\Hybrid Apps.
And please give me a reason, thanks !!!

A: Mobile Web Apps. U are relying on plugins to access native API's. Native Apps has the access to the API integrated in the native Language (java for android, objective c for iOS). Hybrid Apps: u can program the device dependant code in native. Mobile WEb, u need a plugin.


Q: is it possible to convert uploadcollection's object into a xstring? Using the sapui5 uploadcollection to upload files in the frontend and then sending them through ajax with a post request...
I need to know how to convert te returned object from the uploadcollection control into a xstring, so then I can send that xstring (that contains the file content) To a sap gateway by using ajax post method.
Any idea how could I do this?
Right now I'm sending files by using the uploadcollection, once I upload an attachment, the control returns an object that represents the file content.
I'm trying to make this object a xstring by using filereader:
                                                        //obtiene archivo
                                                        var file = files[i];

                                                        //Convierte archivo en binario
                                                        var reader = new FileReader();
                                                        reader.onload = function(readerEvt) {

                                                            var binaryString = readerEvt.target.result;
                                                            var base64 = btoa(binaryString);
                                                            var base64file;

                                                            if(typeof base64file == "undefined" || typeof base64file == null){
                                                                base64file = base64;
                                                            }else{
                                                              base64file = base64file +'new'+base64;
                                                            }
                                                        };
                                                        reader.readAsBinaryString(file);

                                                        console.log(file)

But this work only with files of type image, the others like pdf, .doc etc etc give the following error when I try to send them with ajax.
"The Data Services Request could not be understood due to malformed syntax".
Any idea how can I send convert these files into a xstring data?

A: Take a look at this example. Hope this helps.
View
<u:FileUploader change="onChange" fileType="pdf" mimeType="pdf" buttonText="Upload" />

Controller
convertBinaryToHex: function(buffer) {
        return Array.prototype.map.call(new Uint8Array(buffer), function(x) {
            return ("00" + x.toString(16)).slice(-2);
        }).join("");
    },

onChange: function(oEvent){
    var that = this;
    var reader = new FileReader();
    var file = oEvent.getParameter("files")[0];

    reader.onload = function(e) {
        var raw = e.target.result;
        var hexString = that.convertBinaryToHex(raw).toUpperCase();
        // DO YOUR THING HERE
    };

    reader.onerror = function() {
        sap.m.MessageToast.show("Error occured when uploading file");
    };

    reader.readAsArrayBuffer(file);
},

A: I figured it out by filling an array everytime that a file was uploaded through the control,
                    change: function(oEvent) {

                        //Get file content
                        file = oEvent.getParameter("files")[0];

                        //Prepare data for slug
                        fixname = file.name;
                        filename = fixname.substring(0, fixname.indexOf("."));
                        extension = fixname.substring(fixname.indexOf(".") + 1);

                        //fill array with uploaded file
                        var fileData = {
                            file: file,
                            filename: filename,
                            extension: extension
                        }
                        fileArray.push(fileData);

                    },

and then I did a loop over that array to post every single file I keept there by using ajax method post.
                                                $.each(fileArray, function(j, valor) {

                                                    //get file
                                                    file = fileArray[j].file;

                                                    //get file lenght
                                                    var numfiles = fileArray.length;

                                                    //Convert file to binary
                                                    var reader = new FileReader();
                                                    reader.readAsArrayBuffer(file);
                                                    reader.onload = function(evt) {
                                                        fileString = evt.target.result;

                                                        //get and make slug
                                                        filename = fileArray[j].filename;
                                                        extension = fileArray[j].extension;
                                                        slug = documento + '/' + filename + '/' + extension;

                                                        //User url service
                                                        var sUrlUpload = "sap url";
                                                        runs++;

                                                        //Post files
                                                        jQuery.ajax({});
                                                    }
                                                });


Q: How do we know we reached the last message in the kafka topic using KafkaMessageListenerContainer I am running consumer using KafkaMessageListenerContainer.I need to stop the consumer on the topic's last message.How can i identify particular message is the last message in the topic.

A: You can get it with the following shell command (remove --partition parameter to get offsets for all topic's partitions):
./bin/kafka-run-class kafka.tools.GetOffsetShell --broker-list <host>:<port> --topic <topic-name> --partition <partition-number> --time -1

As you can see, this is using the GetOffsetShell [0] object that you may use to get the last message offset and compare it with record's offset.
[0] https://github.com/apache/kafka/blob/trunk/core/src/main/scala/kafka/tools/GetOffsetShell.scala


Q: Passing multiple line value from JCL instream to Cobol variable 88 Example:
01  VAR1             PIC 9(05).
    88 WS-VAR1  VALUE 1000 1001 1002 1003
       1004 1009 2000 2002 3000 4000 4009
       5000 5001 6000 7000 8000 2332 8484.

How can we pass value from JCL as instream to a Cobol program variable 88.
So, that it will be easier to modify the value without changing the program.
Two solutions which I found:
1. Using internal indexed table. So that Binary search will do the task fast.
2. Using VSAM file instead of passing data instream. (Less likely)
I think Binary search definitely be slower than 88 condition check.
I am trying to find something of equivalent efficiency as of 88 condition check.

A: It sounds like you want to pass a value from JCL PARM= or from SYSIN to make the COBOL program independent of a hard coded value.
This web article has a good explanation of how you can accomplish this.
JCL looks like this:
//* *******************************************************************
//* Step 2 of 4, Execute the COBOL program with a parameter. //*
//PARJ1S02 EXEC PGM=CBLPARC1,
//             PARM='This is a Parameter from the EXEC and PARM= ...'

and in the COBOL program linkage section:
  *****************************************************************
   LINKAGE SECTION.
   01  PARM-BUFFER.
       05  PARM-LENGTH         pic S9(4)   comp.
       05  PARM-DATA           pic X(256).

In your case you can validate the data passed in the linkage section based on your criteria.  So, once validated, you could move the value from the linkage section after converting it to a numeric value for the test.


Q: how to solve NoClassDefFoundError in cucumber test i am using eclipse as a IDE and Selenium web driver. i am trying to run test in cucumber-JVM.
when i am run test it show me "NoClassDefFoundError ". can anyone help me to solve my problem. all relevant jar files are build in to project file.

A: Add cucumber-jvm-deps-1.0.3.jar file into your build path. You can download cucumber-jvm-deps-1.0.3.jar file from cucumber-jvm-deps-1.0.3

A: If the NoClassDefFoundError is coming from either XmlPullParser or dom4j/element
u need to install this Eclipse Plugin/Update:
Eclipse -> Help -> Install New Software…
http://cucumber.github.com/cucumber-eclipse/update-site


Q: iOS: Building a slideshow with fullscreen images I want to build a slideshow in which you slide images (displayed in fullscreen modality). I was planning to use UIViews and add gesture recognizers.. but I was wondering if there is something already done I can reuse, or any tip.
I would like to have the same effect you have when you slide through open apps on the iPad (you can slide them, and you can slide and you still see part of the first view when the second view comes in. (and in case you are moving back your finger, the first view comes back.
thanks

A: You can use the Three20 photo viewer. You can look at this tutorial for help on using it.
There is also a WWDC video from last year which gives you an idea on how this can be implemented.
There are other tools that you can look into. Cocoa Controls has a fairly exhaustive list of tools that you can use for your projects.

A: At the most basic level, a UIScrollView with paging enabled will work fine for swiping to get to the next image. You'll probably need to be more specific than that.


Q: iOS: Adding Qt to an existing Xcode project I want to use some Qt core functionality in an existing iOS 7 Xcode project (similar to this). I do not need Slots or Signals.
Is there a way to import the Qt libraries, and use them in the existing Xcode project?
Regards.

A: Hi have you tried QT for iOS?
QT for iOS


Q: Show selected options as the bootstrap dropdown menu in Html & JavaScript Is it possible to  create a multi-select checkbox dropdown like this in Bootstrap, HTML and JavaScript.
I have tried I couldn't able to achieve it. I'm new to JavaScript as well However I'm just exploring the JS and make it to work but this seems really challenging for me. I don't know how to implement JS script for this.
For instance: If the user selects the countries in the multiselect checkbox I want it to show it  all countries name instead of Choose option.
code:

Country

              Choose option

<input type="checkbox" name="country" value="US"
                  placeholder="Select Country" id="id_country_0" onclick="filter_type();">
                US

<input type="checkbox" name="country" value="India"
                  placeholder="Select Country" id="id_country_1" onclick="filter_type();">
                India

<input type="checkbox" name="country" value="Japan"
                  placeholder="Select Country" id="id_country_2" onclick="filter_type();">
                Japan

<input type="checkbox" name="country" value="UK"
                  placeholder="Select Country" id="id_country_3" onclick="filter_type();">
                UK

js fiddle here: http://jsfiddle.net/shalman44/92drs7ax/3/

A: Since you are already using bootstrap, you might aswell want to use jQuery.
There is a plugin called bootstrap-select for achieving a multi select like in your example, where the syntax is as follows:
<select class="selectpicker" multiple>
  <option>Mustard</option>
  <option>Ketchup</option>
  <option>Relish</option>
</select>

$(function () {
    $('select').selectpicker();
});

You might also want to have a look at this question.

A: I just searched google with "bootstrap multiselect" and i found this codepen

    $(document).ready(function() {
        $('#multiple-checkboxes').multiselect({
          includeSelectAllOption: true,
        });
    });

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css">

    Select Language:
    <select id="multiple-checkboxes" multiple="multiple">
        <option value="php">PHP</option>
        <option value="javascript">JavaScript</option>
        <option value="java">Java</option>
        <option value="sql">SQL</option>
        <option value="jquery">Jquery</option>
        <option value=".net">.Net</option>
    </select>


Q: Procedure to perform a web search (Bing) in Office 2013 task pane app I am trying to make an office 2013 task pane app where it is required to make a web search and display the result in the task pane.
Please explain the processes involved.
There is not much given in MSDN.
Thank You!

A: http://technet.microsoft.com/en-us/library/jj219429.aspx  This explains the process in detail.  The process is slightly different depending on which office app you're building for.  You can do task panes in... Excel, Word, Project and PowerPoint.
Here is a link to tutorials and samples... http://msdn.microsoft.com/en-us/library/office/fp142152.


Q: If Route doesn't exist -> go to other route using its default action? So I'm having a little problem here with routing.
There are two parts to this web application:
  1. Brochure / Display Website
  2. Internal Site / Client Application
We wanted a way to release changes for the brochure without having to do a whole release of said Web application.
Visiting existing named views will take the user to a brochure page, however if it doesn't exist, it will act like they are a client and will redirect them to their company's login screen.
Global.asax:
//if view doesnt exist then url is a client and should be redirected
routes.MapRoute(
    name: "Brochure",
    url: "{id}",
    defaults: new { controller = "brochure", action = "Brochure", id = "Index" },
    namespaces: new[] { "Web.Areas.Brochure.Controllers" }
);

//This is home page
routes.MapRoute(
    name: "HomeDefault",
    url: "{client}/{action}",
    defaults: new { controller = "home", action = "index" },
    namespaces: new string[] { "Web.Controllers" }
);

Controller:
/// <summary> Check if the view exists in our brochure list </summary>
private bool ViewExists(string name) {
    ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, name, null);
    return (result.View != null);
}

/// <summary> Generic action result routing for all pages.
/// If the view doesn't exist in the brochure area, then redirect to interal web
/// This way, even when we add new pages to the brochure, there is no need to re-compile & release the whole Web project. </summary>
public ActionResult Brochure(string id) {
    if (ViewExists(id)) {
        return View(id);
    }

    return RedirectToRoute("HomeDefault", new { client = id });
}

This code works fine up until we log in and go to the landing page. It seems to keep the Brochure action in the route and doesn't want to go to the subsequent controller which results in a 500 error.
e.g. 'domain/client/Brochure' when it needs to be: 'domain/client/Index'
Things tried but not worked:

*

*Changing RedirectToRoute() to a RedirectToAction() - this results in a
finite loop of going back to the ActionResult Brochure(). So
changing controllers through that didn't work.

*Create an ActionResult called Brochure() inside the 'HomeController'. It
doesn't even get hit.

*Passed in namespaces for RedirectToRoute() as an attribute. I knew this would probably not work, but it was worth a try.

So the question is:
How can I get the route to act properly?

A: If you can restrict id to some subset of all values you can add that constraints to route (i.e. numbers only) to let default handle the rest.
routes.MapRoute(
    name: "Brochure",
    url: "{id}",
    defaults: new { controller = "brochure", action = "Brochure", id = "Index" },
    namespaces: new[] { "Web.Areas.Brochure.Controllers" }
    constraints : new { category = @"\d+"}
);

If you can't statically determine restrictions - automatically redirecting in your BrochureController similar to your current code would work. The only problem with sample in the question is it hits the same route again and goes into infinite redirect loop - redirect to Url that does not match first rule:
// may need to remove defaults from second route
return RedirectToRoute("HomeDefault", new { client = id, action = "index" });

If standard constraints do not work and you must keep single segment in url - use custom constraints - implement IRouteConstraint and use it in first route. See Creating custom constraints.

A: Two ways I could have solved this issue:
Way 1
I reviewed the redirect and just passed in an action in order to get a route that has 2 segments in the url. i.e. client/Index. The Index action now handles logins - going past a custom controller.
public class HomeController : CustomController
public ActionResult Brochure(string id, string action) {
    if (ViewExists(id)) {
        return View(id);
    }

    return RedirectToAction("Index", "Home", new { client = id, action = "Index" });
}

Way 2
(from @Alexei_Levenkov)
Create a custom Route constraint so the route will be ignored if the view cannot be found.
namespace Web.Contraints {
    public class BrochureConstraint : IRouteConstraint {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) {
            //Create our 'fake' controllerContext as we cannot access ControllerContext here
            HttpContextWrapper context = new HttpContextWrapper(HttpContext.Current);
            RouteData routeData = new RouteData();
            routeData.Values.Add("controller", "brochure");
            ControllerContext controllerContext = new ControllerContext(new RequestContext(context, routeData), new BrochureController());

            //Check if our view exists in the folder -> if so the route is valid - return true
            ViewEngineResult result = ViewEngines.Engines.FindView(controllerContext, "~/Areas/Brochure/Views/Brochure/" + values["id"] + ".cshtml", null);
            return result.View != null;
        }
    }
}

namespace Web {
    public class MvcApplication : System.Web.HttpApplication {
        //If view doesnt exist then url is a client so use the 'HomeDefault' route below
        routes.MapRoute(
            name: "Brochure",
            url: "{id}",
            defaults: new { controller = "brochure", action = "Brochure", id = "Index" },
            namespaces: new[] { "Web.Areas.Brochure.Controllers" },
            constraints: new { isBrochure = new BrochureConstraint() }
        );

        //This is home page for client
        routes.MapRoute(
            name: "HomeDefault",
            url: "{client}/{action}",
            defaults: new { controller = "home", action = "index" },
            namespaces: new string[] { "Web.Controllers" }
        );
    }
}

I hope this helps someone else out there.

A: There are several issues with your configuration. I can explain what is wrong with it, but I am not sure I can set you on the right track because you didn't provide the all of the URLs (at least not all of them from what I can tell).
Issues

*

*Your Brouchure route, which has 1 optional URL segment named {id}, will match any URL that is 0 or 1 segments (such as / and /client). The fact that it matches your home page (and you have another route that is named HomeDefault that will never be given the chance to match the home page) leads me to believe this wasn't intended. You can make the {id} value required by removing the default value id = "Index".

*The Brouchure route has a namespace that indicates it is probably in an Area. To properly register the area, you have to make the last line of that route ).DataTokens["area"] = "Brochure"; or alternatively put it into the /Areas/Brouchure/AreaRegistration.cs file, which will do that for you.

*The only way to get to the HomeDefault route is to supply a 2 segment URL (such as /client/Index, which will take you to the Index method on the HomeController). The example URLs you have provided have 3 segments. Neither of the routes you have provided will match a URL with 3 segments, so if these URLs are not getting 404 errors they are obviously matching a route that you haven't provided in your question. In other words, you are looking for the problem in the wrong place.

If you provide your entire route configuration including all Area routes and AttributeRouting routes (including the line that registers them), as well as a complete description of what URL should go to what action method, I am sure you will get more helpful answers.

So the question is:
  How can I get the route to act properly?

Unknown. Until you describe what properly is.
Related: Why map special routes first before common routes in asp.net mvc?


Q: What is the correct way to prevent reentrancy and ensure a lock is acquired for certain operations? I'm designing a base class that, when inherited, will provide business functionality against a context in a multithreaded environment. Each instance may have long-running initialization operations, so I want to make the objects reusable. In order to do so, I need to be able to:

*

*Assign a context to one of these objects to allow it to do its work

*Prevent an object from being assigned a new context while it already has one

*Prevent certain members from being accessed while the object doesn't have a context

Also, each context object can be shared by many worker objects.
Is there a correct synchronization primitive that fits what I'm trying to do? This is the pattern I've come up with that best fits what I need:
private Context currentContext;

internal void BeginProcess(Context currentContext)
{
    // attempt to acquire a lock; throw if the lock is already acquired,
    // otherwise store the current context in the instance field
}

internal void EndProcess()
{
    // release the lock and set the instance field to null
}

private void ThrowIfNotProcessing()
{
    // throw if this method is called while there is no lock acquired
}

Using the above, I can protect base class properties and methods that shouldn't be accessed unless the object is currently in the processing state.
protected Context CurrentContext
{
    get
    {
        this.ThrowIfNotProcessing();
        return this.context;
    }
}

protected void SomeAction()
{
    this.ThrowIfNotProcessing();

    // do something important
}

My initial though was to use Monitor.Enter and related functions, but that doesn't prevent same-thread reentrancy (multiple calls to BeginProcess on the original thread).

A: There is one synchronization object in .NET that isn't re-entrant, you are looking for a Semaphore.
Before you commit to this, do get your ducks in a row and ask yourself how it can be possible that BeginProcess() can be called again on the same thread.  That is very, very unusual, your code has to be re-entrant for that to happen.  This can normally only happen on a thread that has a dispatcher loop, the UI thread of a GUI app is a common example.  If this is truly possible and you actually use a Semaphore then you'll get to deal with the consequence as well, your code will deadlock.  Since it recursed into BeginProcess and stalls on the semaphore.  Thus never completing and never able to call EndProcess().  There's a good reason why Monitor and Mutex are re-entrant :)

A: You can use Semaphore class which came with .NET Framework 2.0.
A good usage of Semaphores is to synchronize limited amount of resources. In your case it seems you have resources like Context which you want to share between consumers.
You can create a semaphore to manage the resources like:
var resourceManager = new Semaphore(0, 10);

And then wait for a resource to be available in the BeginProcess method using:
resourceManager.WaitOne();

And finally free the resource in the EndProcess method using:
resourceManager.Release();

Here's a good blog about using Semaphores in a situation like yours:
https://web.archive.org/web/20121207180440/http://www.dijksterhuis.org/using-semaphores-in-c/

A: There is very simple way to prevent re-entrancy (on one thread):
private bool bRefresh = false;
private void Refresh()
{
  if (bRefresh) return;
  bRefresh = true;
  try
  {
    // do something here
  }
  finally
  {
    bRefresh = false;
  }
}

A: The Interlocked class can be used for a thread-safe solution that exits the method, instead of blocking when a re-entrant call is made. Like Vlad Gonchar solution, but thread-safe.

    private int refreshCount = 0;
    private void Refresh()
    {
      if (Interlocked.Increment(ref refreshCount) != 1) return;

      try
      {
        // do something here
      }
      finally
      {
        Interlocked.Decrement(ref refreshCount);
      }
    }


Q: laravel image validation image intervention I have a file upload in my vue js component which sends base64 in server
methods: {
    onFileChange(e) {
        console.log(e.target.files[0]);
        let fileReader = new FileReader();
        fileReader.readAsDataURL(e.target.files[0]);
        fileReader.onload = (e) => {
        this.product.cover_image = e.target.result
       };
   },

    Upload Image of Product
    <input type="file" ref="fileupload" v-on:change="onFileChange" id="exampleInputFile">

and in my controller in laravel im using image intervention to save the image via Image::make
public function store(Request $request){
   $this->validate($request, [
       'name' => 'required|max:255',
       'price' => 'required|numeric',
       ]);
   $image = $request->get('cover_image');
   $name = time().'.' . explode('/', explode(':', substr($image, 0, strpos($image, ';')))[1])[1];
   Image::make($request->get('cover_image'))->save(public_path('cover_images/').$name);
   $product = new Product;
   $product->name = $request->input('name');
   $product->description = $request->input('description');
   $product->price = $request->input('price');
   $product->cover_image = $name;
   if($product->save()) {
          return new ProductsResource($product);
     }
  }

how can i validate the image before saving? it is in base64 i dont know how to validate it on laravel.

A: Inside the AppServiceProvider i put the custom validation
public function boot()
{
    Validator::extend('image64', function ($attribute, $value, $parameters, $validator) {
        $type = explode('/', explode(':', substr($value, 0, strpos($value, ';')))[1])[1];
        if (in_array($type, $parameters)) {
            return true;
        }
        return false;
    });

    Validator::replacer('image64', function($message, $attribute, $rule, $parameters) {
        return str_replace(':values',join(",",$parameters),$message);
    });
}

and on the validation.php i put the
'image64' => 'The :attribute must be a file of type: :values.',

now i can use this in validating the request
'image' => 'required|image64:jpeg,jpg,png'

credits to https://medium.com/@jagadeshanh/image-upload-and-validation-using-laravel-and-vuejs-e71e0f094fbb

A: If you only want to validate uploaded file to be an image type:
$this->validate($request, [
   'name' => 'required|max:255',
   'price' => 'required|numeric',
   'cover_image' => 'required|image'
]);

The file under validation must be an image (jpeg, png, bmp, gif, or
  svg)

Laravel 5.6 image validation rule


Q: Generating a unique random non-key value in Entity Framework/SQL I have a booking application where a customer will create a reservation. I do not want them to have to create an account and log in, so they will modify/view their reservation using a Confirmation code (like the airlines use) and the last 4 of their credit card (again, like airlines).  My reservation class already has a primary key, a GUID, however, I do not want to give that to the customer, I want something nicer to look at like a 6-8 digit alpha code.
I am using Entity Framework and C#/ASP.NET Core, and while I COULD generate the value in my code, check with the DB (MSSQL) that the value has not been used, and then persist if it is unique, I would rather have a single operation if I could.  Is the accepted way of doing something like this to have the database generate the value or is there a more EF way of doing it?

A: Like a two-factor (TOTP) code, but based on your GUID instead of a timestamp?
// userData should be populated with whatever immutable user data you want
// applicationSecret should be a constant
public string ComputeCode(byte[] userData, byte[] applicationSecret, int length)
{
    using var hashAlgorithm = new HMACSHA256(applicationSecret);
    var hash = hashAlgorithm.ComputeHash(userData);
    return BitConverter.ToString(hash).Replace("-", "").Substring(0, length);
}

A: I can't speak to the EF-related aspects of your question, but I recently had to figure out a way to generate unique, user-friendly IDs for a personal project.
What I eventually settled on was the following:

*

*Start with a 32-bit integer. (In my case it was an incrementing database ID.)

*"Encrypt" the integer using RC5 with a block size of 32 bits. This scrambles the key space. You'll probably have to write your own RC5 implementation, but it's a simple algorithm. (Mine was <100 lines of python.)

*Encode the resulting 4 bytes in Base32. I recommend z-base-32 for the most user-friendly alphabet. You might have to write your own Base32 implementation, but again, it's quite simple.

This algorithm produces a reversible mapping similar to the following:
1 <-> "4zm5cna"
2 <-> "5ytgepe"
3 <-> "e94rs4e"
etc.


Q: Opening PDF on React Native I tried to open a pdf file using react-native-pdf-view
my code is :
export default class PDFExample extends Component {
constructor(props) {
    super(props);
}

render(){
    return(
        <PDFView ref={(pdf)=>{this.pdfView = pdf;}}
            src={"./Tizi.pdf"}
            onLoadComplete = {(pageCount)=>{
            this.pdfView.setNativeProps({
            zoom: 1.5
                });
            }}
    style={styles.pdf}/>
            )
    }
}

and i got this error :
Invariant Violation: Native component for "RNPDFView" does not exist

A: The issue is that you did not link the library. The steps are usually the following:
1) npm install THE_PACKAGE --save
2) react-native THE_PACKAGE
If the package does not contain any issues it will be linked, otherwise you need to link it manually, or switch to another solution, for example, https://www.npmjs.com/package/react-native-view-pdf. There you can also find a readme which describes the steps need to be done. It's generic, so you can apply for any package.


Q: Google LineChart  Html tag with html tooltip I'm using google line charts in my project and I've got a bit of a problem with customizing tooltips.
Fiddle with this problem : http://jsfiddle.net/nq7sk6mq/7/
I want to use HTML tooltips and my chart settings are:
if google
  google.load "visualization", "1.0",
    packages: ["corechart"]
    callback: ->
      data = new google.visualization.DataTable()
      data.addColumn('number', ' v1')
      data.addColumn('number', 'v2')
      data.addColumn({type:'boolean',role:'certainty'})
      data.addColumn('number', 'v3')
      data.addColumn({type:'boolean',role:'certainty'})
      data.addColumn('number', 'v4')
      data.addColumn({type:'boolean',role:'certainty'})
      data.addColumn({type: 'string', role: 'tooltip','p':{'html': 'true'}})

My data for it:
values.push [
          iterator,
          values2[iterator],
          true,
          values3[iterator],
          true,
          values4[iterator],
          false,
          customTooltip()]

Options:
options = {
        legend:{position:"top"},
        vAxes: {
          0: {},
        },
        hAxis: {
          ticks: data.getDistinctValues(0)
        },
        series:{
          0: {pointSize: 5, color: "#0f8d4c"},
          1: {pointSize: 5, color: "#b74848"},
          2: {color: "#00a259", pointSize: 4}
        },

        width : width,
        tooltip: {isHtml: true}
      }

call the draw:
google.setOnLoadCallback(drawChart(values,chartid,options))
drawChart: (data, chartid,options) ->
  chart = new google.visualization.LineChart(document.getElementById(chartid));
  chart.draw(data,options)

customTooltip:
customTooltip: () ->
return '
' +
  "
Teeest
"+
'
'

And I get in Chrome:

  <undefined class="google-visualization-tooltip" style="width: 66px; height: 20px; left: 181.5px; top: 133.5px;">

Teeest

  </undefined>

Charts are displayed correctly and, if using normal tooltips, they also works correctly. So my question is why do I get this undefined tag which is destroying the tooltip layout?
I found that not only I am the person who encountered this problem.http://code.google.com/p/google-visualization-api-issues/issues/detail?id=1290

A: According to @juvian help The problem was that styling was set inline on div cointainer and it seems that tooltips inherited it from div. So the answer is to remove the styling from div container and apply it to the desired element.


Q: Mocking AOP method implementation for unit tests I've a java application which has multiple modules - (GWT-)RPC services, perf-library, remote-client (All java code written/owned by my team). The perf-library contains Spring AOP aspects related code and it's primarily used to push intercepted method logs to a data store. Now, perf-library is dependent on another remote-client which actually maintains a queue and handles the job of pushing logs to the data store. So, in a way, perf-library just delegates the task to remote-client.
The business logic code calls intercepted methods which have AOP logic and hence there is a dependency on remote-client. Obviously, I don't want to connect to the remote-client from within unit tests. I think I need to mock the implementation of method push() which connects to remote-client. What I'm unable to figure out is how to use the mock implementation for the business logic code package unit tests.
To clarify things, I've modules like this -

*

*RPC service module - e.g. method login() is intercepted.

*perf-library - Has aspects (to intercept methods like login()) and implementation to call remote-client

*remote-client - Push data to some data-store

Now, for writing the unit tests for RPC service methods, how do I get the mock implementation of push() as it is internal to perf-library. Let's say, I've an interface LogClient (having method push()) which is implemented by two classes (one for production and another for test). I can use this Test implementation for unit tests of perf-library itself, but how do I make the RPC unit tests use it. I'm new to Spring, so not sure if this can be done easily with Spring or anything else. Any help will be nice.
Note: We're using Spring for maintaining beans and DI.

A: Not sure exactly how but Mockito can be a good choice.
Check this link for details.


Q: Angular Nested mat-menu expansion mat-menu gracefully handles expansion when opening near the bottom of a page (if too close to bottom of page, it will open up) but what if there is an expandable button within the mat-menu. Expansion will always open downwards and off the screen.
A workaround seems to be to programmatically scroll screen by 1 pixel. This allows the mat-menu to recalculate its position and pop up to a viewable area, but it is quite a hack and not performant on IE browser. Is there a more elegant solution?
Sample:
<mat-menu #menu="matMenu" xPosition="before"(closed)="onMenuClosed()">
  <ng-template matMenuContent>
    <div #popoverMenu>
      <button mat-menu-item class="primary-action"
          [ngClass]="{'expanded-section': isPanelExpanded }"
          (click)="expandMenuOptions($event)">
 .
 .
 .


Q: Java delete single file from GridFS Is there a way to delete a single file without the objedId in GridFS?
I just found this on MongoDB:
objectId fileId; //ObjectId of a file uploaded to GridFS
gridFSBucket.delete(fileId);

But I don't know how to query all the objectId's to do this.
Thanks in advance for your help.

A: I got the solution:
GridFSFindIterable gridFSFile = gridFSBucket.find(eq("filename",listOfFiles.get(i).getName()));
// listOfFiles are a list which contains the names
gridFSBucket.delete(gridFSFile.cursor().next().getId());

I hope it is helpful.


Q: Combine two different device capture frame into one frame and write a video I'm beginner in opencv but well versed in C#/C++.
I have created a openCV console app to capture and write frames data to videos from multiple devices or RTSP streams which is working fine.
I require to merge the output of two separate devices frames into one frame and write to video have done this in the snippet below but the video file generated is corrupted.
The video capture and video writer are set to grab at 1920 x 1080 resolution.
  for (int i = 0; i < devices; i++) {
  Mat frame;
  Mat f1, f2;
  //Grab frame from camera capture
  if (videoCapturePool[i].grab()) {
    videoCapturePool[i].retrieve(f1);
    f2 = f1.clone();
    if (isPause) {
      circle(f1, Point(f1.size().width / 2, f1.size().height / 2), 10, (255, 255, 10), -1);
      circle(f2, Point(f2.size().width / 2, f2.size().height / 2), 10, (255, 255, 10), -1);
    }
    hconcat(f1, f2, frame);

    imshow("Output", frame);

    waitKey(10);

    frameData[i].camerFrames.push_back(frame);
  }
  f1.release();
  f2.release();

}

for (int i = 0; i < devices; i++) {
  int32_t frame_width(static_cast < int32_t > (videoCapturePool[i].get(CV_CAP_PROP_FRAME_WIDTH)));
  int32_t frame_height(static_cast < int32_t > (videoCapturePool[i].get(CV_CAP_PROP_FRAME_HEIGHT)));

  VideoWriter vidwriter = VideoWriter(videoFilePaths[i], CV_FOURCC('M', 'J', 'P', 'G'), 30, Size(frame_width, frame_height), true);

  videoWriterPool.push_back(vidwriter);
  writer << frameData[i].camerFrames.size() << endl;
  for (size_t j = 0; j < frameData[i].camerFrames.size(); j++) {
    //write the frame
    videoWriterPool[i].write(frameData[i].camerFrames[j]);
  }
  frameData[i].camerFrames.clear();
}

A: Your approach must be generally refactored. I don't say about code - just about architecture. It has a big problem with memory - let's calculate!

*

*The size of the one RGB frame 1920x1080: frame_size = 1920 * 1080 * 3 = 6 Mb

*How many frames do you want capture from 2 cameras? For example 1 minute of video with 30 fps: video_size = 2 camera * 6 Mb/frame * 60 seconds = 21 Gb! Do you have so memory per process?
I advice to make queues in different threads for capture frames and 2 threads for pick up frames from capture queues and write it to files.