text:
Q: Cleaner way to do pytest fixture parameterization based on command-line switch? I've technically already solved the problem I was working on, but I can't help but feel like my solution is ugly:
I've got a pytest suite that I can run in two modes: Local Mode (for developing tests; everything just runs on my dev box through Chrome), and Seriousface Regression Testing Mode (for CI; the suite gets run on a zillion browsers and OSes). I've got a command-line flag to toggle between the two modes, --test-local. If it's there, I run in local mode. If it's not there, I run in seriousface mode. Here's how I do it:
# contents of conftest.py
import pytest

def pytest_addoption(parser):
    parser.addoption("--test-local", action="store_true", default=False, help="run locally instead of in seriousface mode")

def pytest_generate_tests(metafunc):
    if "dummy" in metafunc.fixturenames:
        if metafunc.config.getoption("--test-local"):
            driverParams = [(True, None)]
        else:
            driverParams = [(False, "seriousface setting 1"), (False, "seriousface setting 2")]
        metafunc.parameterize("dummy", driverParams)

@pytest.fixture(scope="function")
def driver(dummy):
    _driver = makeDriverStuff(dummy[0], dummy[1])
    yield _driver
    _driver.cleanup()

@pytest.fixture
def dummy():
    pass

The problem is, that dummy fixture is hideous. I've tried having pytest_generate_tests parameterize the driver fixture directly, but it ends up replacing the fixture rather than just feeding stuff into it, so cleanup() never gets called when the test finishes. Using the dummy lets me replace the dummy with my parameter tuple, so that that gets passed into driver().
But, to reiterate, what I have does work, it just feels like a janky hack.

A: You can try a different approach: instead of dynamically selecting the parameter set for the test, declare ALL parameter sets on it, but deselect the irrelevant ones at launch time.
# r.py
import pytest

real = pytest.mark.real
mock = pytest.mark.mock

@pytest.mark.parametrize('a, b', [
    real((True, 'serious 1')),
    real((True, 'serious 2')),
    mock((False, 'fancy mock')),
    (None, 'always unmarked!'),
])
def test_me(a, b):
    print([a, b])

Then run it as follows:
pytest -ra -v -s   r.py -m real        # strictly marked sets
pytest -ra -v -s   r.py -m mock        # strictly marked sets
pytest -ra -v -s   r.py -m 'not real'  # incl. non-marked sets
pytest -ra -v -s   r.py -m 'not mock'  # incl. non-marked sets

Also, skipif marks can be used for the selected parameter set (different from deselecting). They are natively supported by pytest. But the syntax is quite ugly. See more in the pytest's Skip/xfail with parametrize section.
The official manual also contains exactly the same case as in your question in Custom marker and command line option to control test runs. However, it is also not as elegant as -m test deselection, and is more suitable for complex run-time conditions, not on the apriori known structure of the tests.


text:
Q: Can't check if document exists in cloud firestore database and with reactjs I was doing a simple project when I encountered a problem in the firestore database code, When I check if a document exists it only returns true but never false event when it should do
My Code:
    db.collection("Users")
            .where("email", "==", state.email_value).get()
            .then(function(querySnapshot) {
                querySnapshot.forEach(function(doc) {
                    if(doc.exists) {
                        console.log("Document Exist");
                    } else {
                        console.log("Document Doesn't Exist);
                    }
                });
            });

The Code only executes when the condition is true but not false. I even tried outputing the doc.exists value but it only outputs when its true

A: If there are no documents, the querySnapshot.forEach(function(doc) ... will never be entered.
You'll want to instead check if the query itself has results:
db.collection("Users")
        .where("email", "==", state.email_value).get()
        .then(function(querySnapshot) {
            if (!querySnapshot.empty) {
                console.log("Document Exist");
            }
            else {
                console.log("Document Doesn't Exist");
            }
        });

For situations like this, I highly recommend keeping the reference documentation of Firebase handy: https://firebase.google.com/docs/reference/js/firebase.firestore.QuerySnapshot

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to send only Xamarin.iOS executable to friend in development team I have a Xamarin.iOS Console Application and an Xcode ObjC app that opens (ie. runs) the Xam console app.
I want to send to a friend the ObjC project and only the Xamarin.iOS executable because friend doesn't know Visual Studio.
Where is the Xamarin console app executable (ie. path and which files) and how does friend install it?
Here is how ObjC app runs the Xam app executable:
[[UIApplication sharedApplication] openURL: [NSURL URLWithString:@"XamariniOS://"]];
In the Xam project, I set:
Info.plist > Advanced > URL Types > URL Schemes = scheme name = "XamariniOS"

A:
Where is the Xamarin console app executable (ie. path and which files) and how does friend install it?

As SushiHangover's said, you could distribute the Xamarin.iOS Application as Ad-Hoc mode. Then you will get an .ipa file. You could send it to your friend, then he can open and install the Xamarin.iOS application in your friend's iPhone.
The detailed steps to distriute a Ad-Hoc ios app, you could refer to shared official document to know.

Ad hoc distribution has the advantage of not requiring App Store approval, and it can be installed over-the-air from a web server, or via iTunes. It is, however, limited to 100 devices per membership year, for both development and distribution, and these must be manually added in the Member Center by their UDID.

In addition, if you are a member of the Apple Enterprise Developer Program, you also
also could distribute it as In-House mode to send it to your friend.


text:
Q: renaming two different file extensions in one batch file I have this code segment:
SET PREFIX=pic
FOR /f "tokens=*" %%G IN ('dir /b *.jpg') DO (call :renum "%%G")
GOTO :eof

:renum
 ren %1 %PREFIX%%count%.jpg
 set /a count+=1
 GOTO :eof

For renaming all the jpg files. I'd like to add the same thing for mp4, but editing the jpg to mp4 doesn't work.
How can I rename them both? (I think it's related to the oef label.)

A: This is untested:
@echo off
set count=0
FOR /f "delims=" %%G IN ('dir /b /a-d *.jpg') DO call :renum "%%G" "pic"
set count=0
FOR /f "delims=" %%G IN ('dir /b /a-d *.mp4') DO call :renum "%%G" "video"
echo done
pause
GOTO :eof

:renum
 set /a count+=1
 echo renaming "%~1" to "%~2%count%%~x1"
 ren "%~1" "%~2%count%%~x1"
 GOTO :eof


text:
Q: Unable to change desktop image because url is not file url I am trying to change desktop image using below code:
NSError *anError = nil;
NSString *imageURLString = [[NSBundle mainBundle] pathForResource:@"wallpaper" ofType:@"jpg"];
NSURL *imageURL = [NSURL URLWithString:imageURLString];

[[NSWorkspace sharedWorkspace] setDesktopImageURL:imageURL forScreen:[NSScreen mainScreen] options:nil error:&anError];

but it is always throwing this exception message in console:
Invalid parameter not satisfying: url != nil && [url isFileURL]

When I tried to log - [url isFileURL] it is returning NO, which I am unable to figure out.
When I tried to print description of imageURL, it printed following message:
<CFURL 0x100165c50 [0x7fff7f508ea0]>{type = 15, string = /Users/miraaj/Library/Developer/Xcode/DerivedData/DesktopFun-cevkcaebvcfnstgqbulqyibcfvru/Build/Products/Debug/DesktopFun.app/Contents/Resources/wallpaper.jpg, encoding = 134217984, base = (null)}

Can anyone suggest me the reason for this problem?

A: You're using the wrong method to create an NSURL.  You want
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"wallpaper" ofType:@"jpg"];
NSURL* imageURL = [NSURL fileURLWithPath:imagePath isDirectory:NO];

Or, you could save a step and get an NSURL directly from NSBundle (on 10.6 and later):
NSURL* imageURL = [[NSBundle mainBundle] URLForResource:@"wallpaper" withExtension:@"jpg"];


text:
Q: Archive page for custom taxonomy grouped by month I am working on archive page of custom taxonomy of custom post types. I need to show archives by month of particular taxonomy.
For retrieving post in particular taxonomy by month. However, I have used following code.
function my_custom_post_archive_where($where,$args){
    $post_type  = isset($args['post_type'])  ? $args['post_type']  : 'post';
    $where = "WHERE post_type = '$post_type' AND post_status = 'publish'";
    return $where;
}

add_filter( 'getarchives_where','my_custom_post_archive_where',10,2);

But above filter gives all post in certain post type. I only need posts in particular taxonomy and also its respective pages.
For example:
Archives:
July 2015
June 2015
How can I do it? Please anyone suggests me, as I am really trapped here.
Thanks in advance :).

A: Hey anyways I found with an exact answer which works as a charm. I hope it would be helpful to someone so I am posting it over here.
First you need to add the following code in function.php
/**
 * Custom post type date archives
 */

/**
 * Custom post type specific rewrite rules
 * @return wp_rewrite             Rewrite rules handled by Wordpress
 */
function cpt_rewrite_rules($wp_rewrite) {
    $rules = cpt_generate_date_archives('your-post-type', $wp_rewrite);
    $wp_rewrite->rules = $rules + $wp_rewrite->rules;
    return $wp_rewrite;
}
add_action('generate_rewrite_rules', 'cpt_rewrite_rules');

/**
 * Generate date archive rewrite rules for a given custom post type
 * @param  string $cpt        slug of the custom post type
 * @return rules              returns a set of rewrite rules for Wordpress to handle
 */
function cpt_generate_date_archives($cpt, $wp_rewrite) {
    $rules = array();

    $post_type = get_post_type_object($cpt);
    $slug_archive = $post_type->has_archive;
    if ($slug_archive === false) return $rules;
    if ($slug_archive === true) {
        $slug_archive = $post_type->name;
    }

    $dates = array(
        array(
            'rule' => "([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})",
            'vars' => array('year', 'monthnum', 'day')),
        array(
            'rule' => "([0-9]{4})/([0-9]{1,2})",
            'vars' => array('year', 'monthnum')),
        array(
            'rule' => "([0-9]{4})",
            'vars' => array('year'))
        );

    foreach ($dates as $data) {
        $query = 'index.php?post_type='.$cpt;
        $rule = $slug_archive.'/'.$data['rule'];

        $i = 1;
        foreach ($data['vars'] as $var) {
            $query.= '&'.$var.'='.$wp_rewrite->preg_index($i);
            $i++;
        }

        $rules[$rule."/?$"] = $query;
        $rules[$rule."/feed/(feed|rdf|rss|rss2|atom)/?$"] = $query."&feed=".$wp_rewrite->preg_index($i);
        $rules[$rule."/(feed|rdf|rss|rss2|atom)/?$"] = $query."&feed=".$wp_rewrite->preg_index($i);
        $rules[$rule."/page/([0-9]{1,})/?$"] = $query."&paged=".$wp_rewrite->preg_index($i);
    }
    return $rules;
}

/**
 * Get a montlhy archive list for a custom post type
 * @param  string  $cpt  Slug of the custom post type
 * @param  boolean $echo Whether to echo the output
 * @return array         Return the output as an array to be parsed on the template level
 */
function get_cpt_archives( $cpt, $echo = false )
{
    global $wpdb;
    $sql = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_type = %s AND post_status = 'publish' GROUP BY YEAR($wpdb->posts.post_date), MONTH($wpdb->posts.post_date) ORDER BY $wpdb->posts.post_date DESC", $cpt);
    $results = $wpdb->get_results($sql);

    if ( $results )
    {
        $archive = array();
        foreach ($results as $r)
        {
            $year = date('Y', strtotime( $r->post_date ) );
            $month = date('F', strtotime( $r->post_date ) );
            $month_num = date('m', strtotime( $r->post_date ) );
            $link = get_bloginfo('siteurl') . '/' . $cpt . '/' . $year . '/' . $month_num;
            $this_archive = array( 'month' => $month, 'year' => $year, 'link' => $link );
            array_push( $archive, $this_archive );
        }

        if( !$echo )
            return $archive;
        foreach( $archive as $a )
        {
            echo '
' . $a['month'] . ' ' . $a['year'] . '
';
        }
    }
    return false;
}

Edit this line
 $rules = cpt_generate_date_archives('your-post-type', $wp_rewrite);
change with your post type then on the page where you want to show archives for post type call it like this
<?php get_cpt_archives( 'your-post-type', true ); ?>

If you want to remove formatting such as li then simply use as below:
<?php get_cpt_archives( 'your-post-type' ); ?>

And don't forget you have to create an archive page like this
archive-{your-post-type}.php

That's it. Happy coding :)


text:
Q: Haskell Filter list by custom tuple I am trying to write a function to filter my list of custom tuples in the form ((d1,d2),d3) by the a parameter value larger than d3.
filterTuple 1.5 [((1.0,2.0),1.0),((3.0,5.0),2.0),((4.0,5.0),2.0)] should return [((3.0,5.0),2.0),((4.0,5.0),2.0)]
filterTuples :: Double ->[((Double, Double), Double)] -> [((Double, Double), Double)]
filterTuples val [((d1,d2),d3)] = filter (d3 < val) [((d1,d2),d3)]

This throws the error below with the expression in d3 < val, what is correct to write in there instead?
x8.hs:54:47: error:
• Couldn't match expected type '((Double, Double), Double) -> Bool'
              with actual type 'Bool'
• Possible cause: '(<)' is applied to too many arguments
  In the first argument of 'filter', namely '(d3 < value)'
  In the expression: filter (d3 < value) [((d1, d2), d3)]
  In an equation for 'filterTuples':
      filterTuples value [((d1, d2), d3)]
        = filter (d3 < value) [((d1, d2), d3)]    |

A: What you here have written is pattern matching that only matches a list with one element. You write:
filterTuples val [((d1,d2),d3)] = ...
So this means a list with one element: a tuple ((d1,d2),d3). This is not how you should filter lists an arbitrary number of elements.
We can write it as l:
filterTuples val l = ...
but now we of course still have to write a filter. The filter :: (a -> Bool) -> [a] -> [a] function expects a function a -> Bool as parameter that is a predicate that should decide what elements to keep.
We thus have to design such function. We can write this as a lambda expression:
\((d1,d2),d3) -> d3 < val

So now we can write it as:
filterTuples :: Ord a => a -> [((b,c),a)] -> [((b,c),a)]
filterTuples val l = filter (\((d1,d2),d3) -> d3 < val) l
Now we can still improve it. For instance we can perform an eta reduction: eliminate the variable both in the head and body of the clause:
filterTuples :: Ord a => a -> [((b,c),a)] -> [((b,c),a)]
filterTuples val = filter (\((d1,d2),d3) -> d3 < val)
Still we can improve it. For instance it is not clear why you want to filter only tuples with a tuple as first element. Why not generalize it to all possible 2-tuples?
filterTuples :: Ord a => a -> [(d,a)] -> [(d,a)]
filterTuples val = filter (\(dx,d3) -> d3 < val)
We also usually write variables we do not care about with an underscore (_):
filterTuples :: Ord a => a -> [(d,a)] -> [(d,a)]
filterTuples val = filter (\(_,d3) -> d3 < val)


text:
Q: How to display favorite list on RecyclerView in another Fragment I already made a RecyclerView list of recipes which contains the image, title, and some description inside a fragment. I also add a star button in a row that if it clicked,it changes the color and change the favorite status of the recipe from 0 to 1.
My question is, how do I display all the recipes whose favorite status equals to 1, on a RecyclerView on another fragment.
DatabaseHandler.java
public class DatabaseHandler {
    public DatabaseHandler(Context context) {
        super(context, Util.DATABASE_NAME, null, Util.DATABASE_VERSION);
    }

    //We create our table..
    @Override
    public void onCreate(SQLiteDatabase db) {
        //SQL- Structured Query Language
       /*
        create table _name(id, name, desc, ingredient, image);
        */
        String CREATE_CONTACT_TABLE = "CREATE TABLE " + Util.TABLE_NAME + "("
                + Util.KEY_ID + " INTEGER PRIMARY KEY," + Util.KEY_NAME + " TEXT,"
                + Util.KEY_DESCRIPTION + " TEXT," + Util.KEY_INGREDIENT + " TEXT,"
                + Util.KEY_IMAGE + " BLOB," + Util.KEY_FAV_STATUS + " TEXT" + ")";
        db.execSQL(CREATE_CONTACT_TABLE); //Creating our table..
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String DROP_TABLE = String.valueOf(R.string.db_drop);
        db.execSQL(DROP_TABLE, new String[]{Util.DATABASE_NAME});

        //Create table again
        onCreate(db);
    }

    //Add Recipe
    public void addRecipe(Recipe recipe) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(Util.KEY_NAME, recipe.getName());
        values.put(Util.KEY_DESCRIPTION, recipe.getDescription());
        values.put(Util.KEY_INGREDIENT, recipe.getIngredient());
        values.put(Util.KEY_IMAGE, recipe.getImage());
        values.put(Util.KEY_FAV_STATUS, recipe.getFavStatus());

        //Insert into row..
        db.insert(Util.TABLE_NAME, null, values);
        Log.d("DBHandler", "addRecipe: " + "item added");
        db.close();
    }

    //Get a recipe
    public Recipe getRecipe(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(Util.TABLE_NAME,
                new String[] { Util.KEY_ID, Util.KEY_NAME, Util.KEY_DESCRIPTION, Util.KEY_FAV_STATUS,
                        Util.KEY_INGREDIENT, Util.KEY_IMAGE}, Util.KEY_ID +"=?",
                new String[]{String.valueOf(id)},
                null, null, null);

        if (cursor != null)
            cursor.moveToFirst();

        Recipe recipe = new Recipe();
        recipe.setId(Integer.parseInt(cursor.getString(0)));
        recipe.setName(cursor.getString(1));
        recipe.setDescription(cursor.getString(2));
        recipe.setIngredient(cursor.getString(3));
        recipe.setImage(Integer.parseInt(cursor.getString(4)));
        recipe.setFavStatus(cursor.getString(5));

        return recipe;
    }

    //Get all Recipes
    public List<Recipe> getAllRecipes() {
        List<Recipe> recipeList = new ArrayList<>();

        SQLiteDatabase db = this.getReadableDatabase();

        //Select all recipes
        String selectAll = "SELECT * FROM " + Util.TABLE_NAME;
        Cursor cursor = db.rawQuery(selectAll, null);

        //Loop through our data
        if (cursor.moveToFirst()) {
            do {
                Recipe recipe = new Recipe();
                recipe.setId(Integer.parseInt(cursor.getString(0)));
                recipe.setName(cursor.getString(1));
                recipe.setDescription(cursor.getString(2));
                recipe.setIngredient(cursor.getString(3));
                recipe.setImage(Integer.parseInt(cursor.getString(4)));
                recipe.setFavStatus((cursor.getString(5)));

                //add recipe objects to our list
                recipeList.add(recipe);
            }while (cursor.moveToNext());
        }

        return recipeList;
    }

    public Cursor read_all_data(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        String sql = "SELECT * FROM " + Util.TABLE_NAME + " WHERE " + Util.KEY_ID + "=" + id + "";
        return db.rawQuery(sql, null, null);
    }

    //Update recipe
    public int updateRecipe (Recipe recipe) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(Util.KEY_NAME, recipe.getName());
        values.put(Util.KEY_DESCRIPTION, recipe.getDescription());
        values.put(Util.KEY_INGREDIENT, recipe.getIngredient());
        values.put(Util.KEY_IMAGE, recipe.getImage());
        values.put(Util.KEY_FAV_STATUS, recipe.getFavStatus());

        //Update the row
        return db.update(Util.TABLE_NAME, values, Util.KEY_ID + "=?",
                new String[]{String.valueOf(recipe.getId())});
    }

    //Delete single recipe
    public void deleteRecipe(Recipe recipe) {
        SQLiteDatabase db = this.getWritableDatabase();

        db.delete(Util.TABLE_NAME, Util.KEY_ID + "=?",
                new String[]{String.valueOf(recipe.getId())});
        db.close();
    }

    //Select all favorite list method.
    public Cursor getAllFavRecipes() {

        SQLiteDatabase db = this.getReadableDatabase();
        String sql = "SELECT * FROM " + Util.TABLE_NAME + " WHERE " + Util.KEY_FAV_STATUS + " ='1'";
        return db.rawQuery(sql, null, null);
    }
}

Recipe Model class
public class Recipe {
    private int id;
    private String name;
    private String description;
    private String ingredient;
    private int image;
    private String favStatus;

    public Recipe() {
    }

    public Recipe(int id, String name, String description, String ingredient, int image, String favStatus) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.ingredient = ingredient;
        this.image = image;
        this.favStatus = favStatus;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getIngredient() {
        return ingredient;
    }

    public void setIngredient(String ingredient) {
        this.ingredient = ingredient;
    }

    public int getImage() {
        return image;
    }

    public void setImage(int image) {
        this.image = image;
    }

    public String getFavStatus() {
        return favStatus;
    }

    public void setFavStatus(String favStatus) {
        this.favStatus = favStatus;
    }
}

RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements Filterable{

    private Context context;
    private List<Recipe> recipeList;
    private List<Recipe> recipeListFull;
    private DatabaseHandler db;
    private Recipe recipe;

    public RecyclerViewAdapter(Context context, List<Recipe> recipeList) {
        this.context = context;
        this.recipeList = recipeList;
        recipeListFull = new ArrayList<>(recipeList);
        db = new DatabaseHandler(context);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.recipe_row, viewGroup, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
        Recipe recipe = recipeList.get(position); //each recipe object inside of our list

        readCursorData(recipe, viewHolder);
        viewHolder.recipeName.setText(recipe.getName());
        viewHolder.description.setText(recipe.getDescription());
        viewHolder.image.setImageResource(recipe.getImage());
    }

    @Override
    public int getItemCount() {
        return recipeList.size();
    }

    @Override
    public Filter getFilter() {
        return filterRecipe;
    }

    private Filter filterRecipe = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            String searchText = charSequence.toString().toLowerCase();
            List<Recipe> tempList = new ArrayList<>();
            if(searchText.length()==0 | searchText.isEmpty()) {
                tempList.addAll(recipeListFull);
            }else {
                for (Recipe item:recipeListFull) {
                    if (item.getName().toLowerCase().contains(searchText)) {
                        tempList.add(item);
                    }
                }
            }
            FilterResults filterResults = new FilterResults();
            filterResults.values = tempList;

            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults filterResults) {
            recipeList.clear();
            recipeList.addAll((Collection<? extends Recipe>) filterResults.values);
            notifyDataSetChanged();

        }
    };

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public TextView recipeName;
        public TextView description;
        public ImageView image;
        public ImageView favBtn;

        public ViewHolder(@NonNull  View itemView) {
            super(itemView);

            itemView.setOnClickListener(this);
            recipeName = itemView.findViewById(R.id.name);
            description = itemView.findViewById(R.id.description);
            image = itemView.findViewById(R.id.recipe_imageView);
            favBtn = itemView.findViewById(R.id.fav_image_btn);

            favBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int position = getAdapterPosition();
                    Recipe recipe = recipeList.get(position);

                    if (recipe.getFavStatus().equals("0")) {
                        recipe.setFavStatus("1");
                        db.updateRecipe(recipe);
                        favBtn.setImageResource(R.drawable.favourite_star);
                    } else {
                        recipe.setFavStatus("0");
                        db.updateRecipe(recipe);
                        favBtn.setImageResource(R.drawable.shadow_fav_star);
                    }
                }
            });

        }

        @Override
        public void onClick(View v) {

            int position = getAdapterPosition();
            Recipe recipe = recipeList.get(position);

            Intent intent = new Intent(context, DetailsActivity.class);
            intent.putExtra("name", recipe.getName());
            intent.putExtra("description", recipe.getDescription());
            intent.putExtra("ingredient", recipe.getIngredient());
            intent.putExtra("image", recipe.getImage());

            context.startActivity(intent);

            //Log.d("Clicked", "onClick: " + recipe.getName());

        }
    }

    //Create method to read and check for fav status for every row..
    private void readCursorData (Recipe recipe, ViewHolder viewHolder) {
        Cursor cursor = db.read_all_data(recipe.getId());
        SQLiteDatabase sqLiteDatabase = db.getReadableDatabase();
        try {
            while (cursor.moveToNext()) {
                String item_fav_status = cursor.getString(cursor.getColumnIndex(Util.KEY_FAV_STATUS));
                recipe.setFavStatus(item_fav_status);

                //check fav status
                if (item_fav_status != null && item_fav_status.equals("1")) {
                    viewHolder.favBtn.setImageResource(R.drawable.favourite_star);
                } else if (item_fav_status != null && item_fav_status.equals("0")) {
                    viewHolder.favBtn.setImageResource(R.drawable.shadow_fav_star);
                }
            }
        } finally {
            if (cursor != null && cursor.isClosed())
                cursor.close();
            db.close();
        }
    }
}

A: There can be multiple ways to do achieve this.

*

*ViewModel

*EventBus

*Interface

ViewModel

ViewModel is a class that is responsible for preparing and managing the data for an Activity or a Fragment. It also handles the communication of the Activity / Fragment with the rest of the application (e.g. calling the business logic classes).

Using ViewModel with LiveData we can communicate between multiple fragment by observing LiveData object. for example when user click on favorite button you will post the Recipe id by using method postValue(). so all observer will receive the id that has been posted and using this you can fetch new data and display into Adapter.
EventBus
EventBus is library and it's use publisher/subscriber pattern for loose coupling and it can be used for communicating between multiple component.
you can read more about it here
Interface
Using this way you will create a Listener and implement in activity, so in this scenario Activity will be used to communicate between multiple fragments.
I will suggest you to use ViewModel cause they are Life-Cycle aware component. and it's easy to implement and use. in following link Communicating with fragments you can read about it.


text:
Q: how to perform merging of keys for common values in hash of hash in perl I am working on a below hash of hashes in perl, wherein i have some values in
inner hash that are same for different key timestamps. Is there any way to merge the timestamp keys for similar values?
'Test Responder Data String' => {
                        '2018-01-26' => 'zzz00175002802;newData1',
                        '2018-01-20' => 'xxy00171329968;data1',
                        '2018-01-27' => 'xxy00171329968;data1',
                        '2018-01-28' => 'xxy00171329968;data1'
                        '2018-01-04' => 'www00171510082;ResponderData',
                        '2018-01-17' => 'rrr00175002256;try data',
                        '2018-01-05' => 'aaa00175033226;response try',
                        '2018-01-08' => 'aaa00175033226;response try'
                       }

Expected Result:
'Test Responder Data String' => {
                        '2018-01-26'                       => 'zzz00175002802;newData1',
                        '2018-01-20,2018-01-27,2018-01-28' => 'xxy00171329968;data1',
                        '2018-01-04'                       => 'www00171510082;ResponderData',
                        '2018-01-17'                       => 'rrr00175002256;try data',
                        '2018-01-05,2018-01-08'            => 'aaa00175033226;response try'
                       }

A: my %h=(
    '2018-01-26' => 'zzz00175002802;newData1',
    '2018-01-20' => 'xxy00171329968;data1',
    '2018-01-27' => 'xxy00171329968;data1',
    '2018-01-28' => 'xxy00171329968;data1',
    '2018-01-04' => 'www00171510082;ResponderData',
    '2018-01-17' => 'rrr00175002256;try data',
    '2018-01-05' => 'aaa00175033226;response try',
    '2018-01-08' => 'aaa00175033226;response try'
);
my %t;
push @{ $t{ $h{$_} } }, $_ for keys %h;

my %result = map { join(",", @{$t{$_}}) => $_ } keys %t;

use Data::Dumper; print Dumper \%result;

output
$VAR1 = {
      '2018-01-17' => 'rrr00175002256;try data',
      '2018-01-05,2018-01-08' => 'aaa00175033226;response try',
      '2018-01-26' => 'zzz00175002802;newData1',
      '2018-01-04' => 'www00171510082;ResponderData',
      '2018-01-27,2018-01-20,2018-01-28' => 'xxy00171329968;data1'
    };


text:
Q: How to find the exact position of the mouse on the webpage I have been trying to develop a drawing application. When I try to plot a point for freehand drawing, the point appears a good 100 or so pixels away from the actual position of the mouse pointer. Is there any way I can get the exact position of the mouse? You can see and run the code below.

const canvasEle = document.getElementById('drawContainer');
const context = canvasEle.getContext('2d');

function setMousePosition (e) {
    var x = e.clientX;
    var y = e.clientY;
    console.log("x coord " + x + " y coord " + y);

    changePixelColor(x, y)
}

function changePixelColor (x, y) {
    context.fillRect(x,y,1,1);
}

canvasEle.addEventListener("mousemove", setMousePosition)
canvas {
    border: 1px solid black;
    width: 500px;
    height: 500px;
    position: absolute;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Draw</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <canvas id="drawContainer"></canvas>
</body>
<script src="app.js"></script>
</html>

A: Try removing height and width from CSS and use the canvas' width and height attributes instead. Another tip to center the mouse on the painted rectangle is to subtract half the size of the rectangle, e.g. context.fillRect(x-0.5,y-0.5,1,1). In your case it's hard to actually see that the dot isn't centered so try with context.fillRect(x-25,y-25,50,50) and you will see a difference compared to context.fillRect(x-25,y,50,50)

const canvasEle = document.getElementById('drawContainer');
const context = canvasEle.getContext('2d');

function setMousePosition (e) {
    var x = e.clientX;
    var y = e.clientY;
    //console.log("x coord " + x + " y coord " + y);

    changePixelColor(x, y)
}

function changePixelColor (x, y) {
 context.fillRect(x-0.5,y-0.5,1,1);
 //context.fillRect(x,y,50,50); compare these to see the difference
 //context.fillRect(x-25,y-25,50,50);
}

canvasEle.addEventListener("mousemove", setMousePosition)
canvas {
    border: 1px solid black;
    position: absolute;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Draw</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
     <canvas width="500" height="500" id="drawContainer"></canvas>
</body>
<script src="app.js"></script>
</html>

A: Try like this:

const canvasEle = document.getElementById('drawContainer');
const context = canvasEle.getContext('2d');
const cr = canvasEle.getBoundingClientRect();

function setMousePosition (e) {
    var x = e.clientX - cr.x;
    var y = e.clientY - cr.y;
    console.log("x coord " + x + " y coord " + y);

    changePixelColor(x, y)
}

function changePixelColor (x, y) {
    context.fillRect(x,y,1,1);
}

canvasEle.width  = 500;
canvasEle.height = 500;
canvasEle.addEventListener("mousemove", setMousePosition)
canvas {
    border: 1px solid black;
    width: 500px;
    height: 500px;
    position: absolute;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Draw</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <canvas id="drawContainer"></canvas>
</body>
<script src="app.js"></script>
</html>

Two additions to resolve this:

*

*offsetting the x and y values in setMousePosition, so that they become relative to the canvas position, rather than to the page.

*setting the width and height of the canvas element in either JavaScript or the HTML attributes.


text:
Q: Count of Daily Users in PostgreSQL I have a database that looks like this
users
phone        created
8001234578   1540231160
9001234578   1540220360
1001234578   1540144760
2001234578   1540058360

Note that the created column is a unix timestamp.
I want to group them by users created on the same day with a count of users, so the above example database should return something like this.
[
  {day: '10/22/2018', count: 2},
  {day: '10/21/2018', count: 1},
  {day: '10/20/2018', count: 1},
]

I tried learning about the to_char command but I couldn't figure it out, this is what I tried:
SELECT
  to_char(created, 'Day') as day,
COUNT(*) as count
FROM users
WHERE created >= ${startDate} AND created <= ${endDate}
GROUP BY to_char(created, 'Day')

It returned this:
[{day: ' .ay', count: '4'}]

A: First, if it's within your control, you should consider using Postgres's built in TIMESTAMP data type, instead of storing your dates as UNIX timestamps. This will make your queries much easier.
That being said, if you're stuck with using UNIX timestamps (presumably stored as integers), you'll have to convert them to a TIMESTAMP anyways to get what you want. You can use the TO_TIMESTAMP to convert from the UNIX timestamp, and use the DATE_TRUNC function to just get the date portion:
SELECT
    DATE_TRUNC('day', TO_TIMESTAMP(created)),
    COUNT(*)
FROM users
GROUP BY DATE_TRUNC('day', TO_TIMESTAMP(created))

Of course, if you're storing the dates as a Postgres TIMESTAMP, it's the same query, but simpler:
SELECT
    DATE_TRUNC('day', created),
    COUNT(*)
FROM users
GROUP BY DATE_TRUNC('day', created)

A: SELECT date_trunc('day', users.created) "day", count(*) as count
FROM users
WHERE created >= ${startDate} AND created <= ${endDate}
GROUP BY 1

A: You can set datetime format, so you got result like this
postgres# select to_char(now(), 'DD Mon YYYY');
   to_char
-------------
 22 Oct 2018
(1 row)

In your case query will be like this
SELECT
  to_char(created, 'DD Mon YYYY') as day,
COUNT(*) as count
FROM users
WHERE created >= ${startDate} AND created <= ${endDate}
GROUP BY to_char(created, 'DD Mon YYYY')

Here you can find datetime format specification https://www.postgresql.org/docs/9.6/static/functions-formatting.html#FUNCTIONS-FORMATTING-DATETIME-TABLE


text:
Q: List> cannot be assigned to List> when type parameter is involved In the following code, get() is called and it's result assigned to a variable whose type is List<List<?>>. get() returns a List<List<T>> and is called on an instance whose type parameter T is set to ?, so it should fit.
import java.util.List;

class Test {
    void foo(NestedListProducer<?> test) {
        List<List<?>> a = test.get();
    }

    interface NestedListProducer<T> {
        List<List<T>> get();
    }
}

But both IntelliJ IDEA and Oracle's javac version 1.7.0_45 reject my code as invalid. This is the error message of 'javac':
java: incompatible types
  required: java.util.List<java.util.List<?>>
  found:    java.util.List<java.util.List<capture#1 of ?>>

Why is this code invalid, i.e. what could go wrong if it was allowed?

A: The ? is a wildcard meaning any type.  One ? cannot be the same as another ?, because another ? could be any other type, and they don't match.  You must use generics to say that the types are the same:
// Make this generic
<A> void foo(NestedListProducer<A> test) {
    List<List<A>> a = test.get();
}

A: List<List<T>> means a list that you can read List<T>'s from or write new List<T>s to, and similarly List<List<?>> means a list that you can read List<?>'s from or write new List<T>s to. The thing that's weird about ? is that you can convert a list of any type S to a List<?>. For instance you can write:
void foo(List<String> a, List<Integer> b, List<List<?>> out) {
  List<?> unknownA = a;
  List<?> unknownB = b;
  out.add(a);
  out.add(b);
}

If you could convert a List<List<T>> into a List<List<?>>, you could call foo with a List<List<PeanutButter>>, and then add lists of strings and integers to it.
Generally people run into this because they're trying to express the notion that they want a collection of subcollections whose types don't matter. If that's what you want, you can change the type from List<List<?>> to List<? extends List<?>>, which expresses the notion of a list of sublists that I can read from but not write to. It is legal to convert a List<List<T>> to a List<? extends List<?>>.

A: You seem to be confused with how compiler treats a List<?> and a List<List<?>>. A List<?> is a List of some type that is unknown, whereas, List<List<?>> is a List of List(of different types that are unknown).
So for List<?>, the wildcard ? represent a single unknown type, so it would be captured by the compiler to a place-holder for that single unknown type. While in List<List<?>>, the wildcard ? represents different unknown types. Compiler wouldn't capture such types, as there can't be a single place-holder for different unknown types.
Now considering your original example:
void foo(NestedListProducer<?> test) {
    List<List<?>> a = test.get();
}

In this case, the compiler would capture the ? of NestedListProducer to create an anonymous type parameter at compile time, and will create a helper method somewhat like:
<CAP#1 of ?> void foo_2(NestedListProducer<CAP#1 of ?> test) {
    List<List<?>> a = test.get();
}

(Note: It would not capture the ? in List<List<?>>, so it will remain as it is).
Now the return type of test.get() in this case would be List<List<CAP#1 of ?>>. Which is not assignment capture convertible from List<List<?>>, and hence it can't be assigned to it. Thus it fails to compile.
So the workaround is to add the type parameters yourself, as already suggested:
<T> void foo(NestedListProducer<T> test) {
    List<List<T>> a = test.get();
}

Query from the comments:
Now as you asked in comments, why the following code works?
void foo(List<List<?>> arg) {
    List<List<?>> a = arg;
}

From above explanation, you can guess that the wildcard ? in the List<List<?>> in formal parameter wouldn't be captured. Hence the assignment is really from a List<List<?>> to List<List<?>>, which is valid. There is no CAP#1 of ? here.

A: You can use this trick (wildcard capture)
void foo(NestedListProducer<?> test) {
    foo2(test);
}

<T> void foo2(NestedListProducer<T> test) {
    List<List<T>> a = test.get();
}


text:
Q: Scroll bars not working correctly with canvas The scroll bars move the canvas but they always snap back to the  top or the left.  What am I doing wrong?
import tkinter as Tk
root = Tk.Tk()
root.rowconfigure(0,weight=1)
root.columnconfigure(0,weight=1)
frame = Tk.Frame(root)
frame.grid(row=0, column=0, sticky='NSEW')
frame.rowconfigure(0,weight=1)
frame.columnconfigure(0,weight=1)
canvas = Tk.Canvas(frame)
canvas.grid(row=0, column=0, sticky='NSEW')
scroll_x = Tk.Scrollbar(frame, orient="horizontal", command=canvas.xview)
scroll_x.grid(row=1, column=0, sticky="ew")
scroll_y = Tk.Scrollbar(frame, orient="vertical", command=canvas.yview)
scroll_y.grid(row=0, column=1, sticky="ns")
canvas.create_oval(0,0,1333,1000)
canvas.configure(scrollregion=canvas.bbox("all"))
root.mainloop()

A: Scrollbars require two-way communication with the widgets they are controlling. You've properly configured the scrollbars but haven't configured the canvas to update the scrollbars.
To do that, add the following code after you've defined the canvas and scrollbars:
canvas.configure(yscrollcommand=scroll_y.set, xscrollcommand=scroll_x.set)


text:
Q: How to perform a Mongoose validate function only for create user page and not edit user page? Background
I am currently building a website with Node.js, Express, and MongoDB. I am using mongoose to work with my MongoDB server.
Right now I have a function in my Mongoose schema that checks to see if a user's inputed email address already exists in the DB. I want this function to only get called on the create account page. Any help would be greatly appreciated! Thanks!
The Problem
The function works great but it is getting called on the edit user profile page as well as the create user page. This means that if a user doesn't change their email on the edit profile page, they can't update their profile. I only want this validate unique email function to be called for the create user page so I can avoid this problem. How do I run a function depending on the page the user is on?
The Code

Function in my User Schema to check if email already exists
UserSchema.path('email').validate(function(value, done) {
    this.model('User').count({ email: value }, function(err, count) {
        if (err) {
            return done(err);
        }
        // If `count` is greater than zero, "invalidate"
        done(!count);
    });
}, 'Email already exists');

Entire User Schema (filename is user.server.model.js)
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    crypto = require('crypto');

/**
 * A Validation function for local strategy properties
 */
var validateLocalStrategyProperty = function(property) {
    return ((this.provider !== 'local' && !this.updated) || property.length);
};

/**
 * A Validation function for local strategy password
 */
var validateLocalStrategyPassword = function(password) {
    return (this.provider !== 'local' || (password && password.length > 6));
};

/**
 * User Schema
 */
var UserSchema = new Schema({
    firstName: {
        type: String,
        trim: true,
        default: '',
        validate: [validateLocalStrategyProperty, 'Please fill in your first name']
    },
    lastName: {
        type: String,
        trim: true,
        default: '',
        validate: [validateLocalStrategyProperty, 'Please fill in your last name']
    },
    displayName: {
        type: String,
        trim: true
    },
    companyName: {
        type: String,
        trim: true,
        default: ''
    },
    companyWebsite: {
        type: String,
        trim: true,
        default: ''
    },
    companyAddress1: {
        type: String,
        trim: true,
        default: ''
    },
    companyAddress2: {
        type: String,
        trim: true,
        default: ''
    },
    companyCity: {
        type: String,
        trim: true,
        default: ''
    },
    companyState: {
        type: String,
        trim: true,
        default: ''
    },
    companyZip: {
        type: String,
        trim: true,
        default: ''
    },
    phone: {
        type: String,
        trim: true,
        default: ''
    },
    email: {
        type: String,
        trim: true,
        default: '',
        unique: true,
        validate: [validateLocalStrategyProperty, 'Please fill in your email'],
        match: [/.+\@.+\..+/, 'Please fill a valid email address']
    },
    username: {
        type: String,
        unique: 'testing error message',
        required: 'Please fill in a username',
        trim: true
    },
    password: {
        type: String,
        default: '',
        validate: [validateLocalStrategyPassword, 'Password should be longer']
    },
    salt: {
        type: String
    },
    provider: {
        type: String,
        required: 'Provider is required'
    },
    providerData: {},
    additionalProvidersData: {},
    roles: {
        type: [{
            type: String,
            enum: ['user', 'admin']
        }],
        default: ['user']
    },
    updated: {
        type: Date
    },
    created: {
        type: Date,
        default: Date.now
    },
    /* For reset password */
    resetPasswordToken: {
        type: String
    },
    resetPasswordExpires: {
        type: Date
    }
});

/**
 * Hook a pre save method to hash the password
 */
UserSchema.pre('save', function(next) {
    if (this.password && this.password.length > 6) {
        this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
        this.password = this.hashPassword(this.password);
    }

    next();
});

/**
 * Check if email already exists in database
 */
UserSchema.path('email').validate(function(value, done) {
    this.model('User').count({ email: value }, function(err, count) {
        if (err) {
            return done(err);
        }
        // If `count` is greater than zero, "invalidate"
        done(!count);
    });
}, 'Email already exists');

/**
 * Create instance method for hashing a password
 */
UserSchema.methods.hashPassword = function(password) {
    if (this.salt && password) {
        return crypto.pbkdf2Sync(password, this.salt, 10000, 64).toString('base64');
    } else {
        return password;
    }
};

/**
 * Create instance method for authenticating user
 */
UserSchema.methods.authenticate = function(password) {
    return this.password === this.hashPassword(password);
};

/**
 * Find possible not used username
 */
UserSchema.statics.findUniqueUsername = function(username, suffix, callback) {
    var _this = this;
    var possibleUsername = username + (suffix || '');

    _this.findOne({
        username: possibleUsername
    }, function(err, user) {
        if (!err) {
            if (!user) {
                callback(possibleUsername);
            } else {
                return _this.findUniqueUsername(username, (suffix || 0) + 1, callback);
            }
        } else {
            callback(null);
        }
    });
};

mongoose.model('User', UserSchema);

users.server.routes.js file
'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport');

module.exports = function(app) {
    // User Routes
    var users = require('../../app/controllers/users.server.controller');

    // Setting up the users profile api
    app.route('/users/me').get(users.me);
    app.route('/users').put(users.update);
    app.route('/users/accounts').delete(users.removeOAuthProvider);

    // Setting up the users password api
    app.route('/users/password').post(users.changePassword);
    app.route('/auth/forgot').post(users.forgot);
    app.route('/auth/reset/:token').get(users.validateResetToken);
    app.route('/auth/reset/:token').post(users.reset);

    // Setting up the users authentication api
    app.route('/auth/signup').post(users.signup);
    app.route('/auth/signin').post(users.signin);
    app.route('/auth/signout').get(users.signout);

    // Finish by binding the user middleware
    app.param('userId', users.userByID);
};

A: You can use the Document.isNew flag to only run your check on creation. Like this:
UserSchema.pre('save', function(next) {
    if (this.isNew) {
        // Enforce constraints here
    }

    if (this.password && this.password.length > 6) {
        this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
        this.password = this.hashPassword(this.password);
    }

    next();
});

You also have Document.isModified at your disposal, so in your save hook you could check this.isModified('email') as well.

A: Than you to Andrew Lavers. I think his answer would have worked fine but what I ended up doing was simply using the unique index validation on my email in the schema.
email: {
    type: String,
    trim: true,
    validate: [validateLocalStrategyProperty, 'Please fill in your email'],
    match: [/.+\@.+\..+/, 'Please fill a valid email address'],
    unique: 'testing error message'
},

The mean.js boiler plate code has a controller in the server called errors.server.controller.js which handles errors that appear when unique index validation fails (they give error codes 11000 and 11001).
exports.getErrorMessage = function(err) {
    var message = '';

    if (err.code) {
        switch (err.code) {
            case 11000:
            case 11001:
                message = getUniqueErrorMessage(err);
                break;
            default:
                message = 'Something went wrong';
        }
    } else {
        for (var errName in err.errors) {
            if (err.errors[errName].message) message = err.errors[errName].message;
        }
    }

    return message;
};

When I used the unique index validation instead I did not have any problems on the edit profile page.
I tried the unique property before and it didn't work, I found out this is because if there are already duplicate values in your database you have to delete all the information in your database. I heard there are other ways of solving this problem but for me it was easiest to delete the database.
The unique validation index approach is the recommended approach by Mongoose creator Aaron Heckmann to avoid un-expected race condition related errors faced when using other approaches.
See http://nraj.tumblr.com/post/38706353543/handling-uniqueness-validation-in-mongo-mongoose


text:
Q: Subversion: How do I commit a Update To Revision? I have a situation where:

*

*Developer is working on SVN project.

*Person checks out SVN project, walks away, kid/cat/wife sits/dools/sleepwalks/whatever at computer and inserts gobbledygook asdfg-code. Person commits project.

*Developer sees bad files and Update To Revision back to the last working version

All is well untill the developer wants to commit the project. If the developer has made changes to the file in question, it will be committed just fine. BUT if not - the dev only Update To Revision and made no further changes - that file will not be commited, and any updates to the project will render the  gobbledygook asdfg-code file to you.
Question : If I only 'Update To Revision' a file, how do I commit it again without manually editing the file?

A: I think you have chosen the wrong route around the problem.
Rather than changing what revision you are looking at, you should have:

*

*Updated to latest revision including the rubbish

*found the rubbish commit on the revision log and chosen revert this change

*committed the cleanup with or without any other changes you had to your working copy

So what you would do now is to update to the latest version (applying the rubbish change) and revert their change which brings you back in line.  Pretty much as if they made the change while you where working and didn't have the change in the first place.
You can only commit when your code is up to date with the head of the working branch/trunk.
SVN won't make a branch for you dynamically at this point of earlier revision, you have to choose to make a branch, or to update to the head.

A: If you are on windows, and are using TortoiseSVN:

*

*Right click on the dir, select "TortoiseSVN > Merge..."

*Select "Merge a range of revisions"

*In "Url to merge from" select the current branch (the one which is checked out in the current dir)

*In "Revision range to merge" type or select ("Show log") the latest wrong revision

*Mark "Reverse merge" checkbox

Then after the merge, just commit! :)

A: You can simply undo changes by using the following
svn merge -c -RevisionWhichWasWrong ^/trunk

The RevisionWhichWasWrong is the latest which you've checked in. After that simply do
svn commit

and that's it.
BTW: It's not posssible to checkin if you have never made changes to the contents of files.

A: Good question! As far as i know it's only possible by manually adding a white space or something to the file so subversion sees the file as changed. After that it creates a new revision.

A: 1- Update to special version that you want to be the last version.
2- Export this version to a folder.
3- Update working copy to last version.
4- Overwrite exported files and folders into working copy folder.
5- Commit!


text:
Q: Get the data from a array and arrange it to different structure of JS array I have a array and I need to get the data from that array and arrange a new array with different structure.
Array what I have
[[21,1],[22,2],[32,4],[35,6],[45,1],[82,1]]

Array what I need
[[0-10,0],[10-20,0],[20-30,3],[30-40,10],[40-50,1],[80-90,1] ]

can we do it using JavaScript?

A: You could divide the range value by ten and add the count value

const
    data = [[21, 1], [22, 2], [32, 4], [35, 6], [45, 1], [82, 1]],
    result = data.reduce((r, [v, c]) => {
        const i = Math.floor(v / 10);
        while (r.length <= i) r.push([`${r.length * 10}-${(r.length + 1) * 10 - 1}`, 0]);
        r[i][1] += c;
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: Convert a rows list to pyspark dataframe I have a pyspark dataframe (df) with very many rows and two columns (col1, col2), though I want to get a dataframe with only the top 30 rows. I've seen that I can display them with:
df.show(30)
But this isn't what I want to do, I need an actual dataframe with only these 30 rows. I've also seen that I can run:
df.head(30) or df.take(30)
But these don't output a dataframe but rather a list of the form [Row(col1=100, col2=200), Row(col1=300, col2=500), ...]
What I am wanting to know is how I can convert this list [Row(col1=100, col2=200), Row(col1=300, col2=500), ...] back into a dataframe. I have tried DataFrame and createDataFrame, but these are throwing up errors. Specifically, I have tried:
df_list=df.head(30)
df_Columns = ["col1","col2"]
new_df=DataFrame(df_list, df_Columns)

But this is throwing up errors. I am at a loss as to how to do this seemingly simple task, so I am looking for a straightforward method to do so (convert the df.head(30) list back to a pyspark dataframe). Any guidance or insights are greatly appreciated.


text:
Q: Safari v6.0.5 (8536.30.1) behaves different when download same file but different server Recently I switch from one hosting (A Hosting) to another hosting server (B Hosting). Previously my Mac's Safari using able to download the MP3 by, right click "Download Linked File As.." to save the MP3 to local machine.
However, once I switch to another hosting, with the same PHP code, same MP3. B Hosting webserver, cannot save the MP3, but only allow streaming from the website (Full Screen Audio Player).
On the Safari Downloads Windows, it shows "Zero KB of ? - The requested URL was not found on this server." This is impossible. I believe it is same kind of setting in the server make this option not available.
After I did some research, some Mac User said that we can use "Option"+"Click" to download the MP3. This method works for A Hosting and B Hosting. I just want to know how to fix "Download Linked File As..." to make in work in B Hosting.
Thanks!
Update:-
A Hosting:

B Hosting:

As you can see A Hosting didn't have Content-Disposition, but Safari don't have any issue to download the file. Is it really Content-Disposition matter?

A: It's about content-disposition header (http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html) and/or default or strict MIME type configured on web server, by default webservers like apache use text/plain, switching to application/octet-stream solves the problem.


text:
Q: How to handle spelling mistakes in UnigramTagger in nltk python? I am doing Named Entity Recognition using python nltk library.I am using UnigramTagger to custom tag tokens.And its happening perfectly fine.
The problem is the tagger exactly tags to words that I mention in my model.With any spelling mistake,it fails to find the word.
How do I solve this problem?
I liked how fuzzywuzzy allows ratio search but don't know if the same functionality is provided by any nltk tagger .Need some help here.Thanks.

A: You need to correct spellings before Named Entity Recognition. You can do this from following url..
spell checker


text:
Q: How to move axes to center of chart in Maxima draw The draw (2d) function in Maxima has several settings to control the axis, but as far as I can tell, none that sets the xy-axis to the center of the chart.
I did find the equivalent in the plot2d function, where I can just set [box, false].
I found this related question, that does it in gnuplot. Maybe that's possible to use with the option user_preamble?

A: Right. You'll use something like the following, with symmetric ranges for x and y.
load(draw)$
draw2d( user_preamble="set zeroaxis linetype 5; set xtics axis;
       set ytics axis; set border 0;", explicit(sin(x),x,-%pi, %pi))$


text:
Q: Meaning of "at least initially" What does "at least initially" mean? I've heard this but don't understand this phrase.

A: "At least initially" expresses the idea that your statement about something is, or was, only true in the beginning. It is similar to the phrase, "At first".
"Most diets work, at least initially." This means that when you start a diet, you will probably lose some weight. However, over time, you may be less successful.
"At least initially, he was nice to me." This suggests that the person was nice at the beginning of your relationship, but eventually turned into a jerk.


text:
Q: How can I resize an overlay image with ffmpeg? I am trying to add an overlay to a video using the following command
ffmpeg -y -i "$videoPath" -i "$overlayPath" -filter_complex "[0:v] [1:v] overlay=$overlayPosition" -pix_fmt yuv420p -c:a copy "$outputPath"

However, I would like to be able to resize the overlay I am about to apply to some arbitrary resolution (no care for keeping proportions). However, although I followed a couple of similar solutions from SO (like FFMPEG - How to resize an image overlay?), I am not quite sute about the meaning of the parameters or what I need to add it in my case.
I would need to add something like (?)
[1:v]scale=360:360[z] [1:v]overlay=$overlayPosition[z]

This doesn't seem to work so I'm not sure what I should be aiming for.
I would appreciate any assistance, perhaps with some explanation.
Thanks!

A: You have found all parts. Let's bring them together:
ffmpeg -i "$videoPath" -i "$overlayPath" -filter_complex "[1:v]scale=360:360[z];[0:v][z]overlay[out]" -map "[out]" -map "0:a" "$outputPath"

For explanation:
We're executing here two filter within the "filter_complex" parameter separated by a semicolon ";".
First we scale the second video input ([1:v]) to a new resolution and store the output in variable "z" (you can put here any name).
Second we bring the first input video ([0:v]) and the overlay ([z]) together and store the output in variable "out".
Now it's time to tell ffmpeg what he should pack into our output file:
-map "[out]" (for the video)
-map "0:a" (for the audio of the first input file)


text:
Q: Fix $u,x\in V$. Define $T\in \mathcal{L}(V)$ By $Tv=\langle v,u\rangle x$ for every $v\in V$ Please someone help me with following question.
Fix $u,x\in V$. Define $T\in \mathcal{L}(V)$ By
$$Tv=\langle v,u\rangle x$$ for every $v\in V$
(a)  Suppose $F=R$. Prove that $T$ is self-adjoint if and only if $u, x$ is linearly dependent.
(b)  Prove that $T$ is normal if and only if $u, x$ is linearly dependent

A: *

*If $u,x$ are linearly dependent, write $u=\lambda x$. We want to prove $<Tv,y> = <v,Ty>$ for any $v,y\in V$, and for fixed $u,x \in V$. Notice that $<Tv,y>=<v,u><x,y>$ and $<v,Ty>=<y,u><v,x>$. By substituting $u=\lambda x$, $<Tv,y>=<v,u><x,y>=\lambda<v,x><x,y>$ and $<v,Ty>=<y,u><v,x>=\lambda<y,x><v,x>=\lambda<x,y><v,x>$. Thus we conclude $T$ is self-adjoint. Rewrite this step from bottom to top, we can see the converse of the proposition. Note that it is only happen because $F=\mathbb{R}$ as $<x,y>=<y,x>$ in the field of real number.

A: Observe that if u or x are zero we have nothig to show. So suppose that x and u are nonzero vectors. Use the orthogonal descomposition of u as a multiple of x and some w orthogonal to x. That is to said u iquals c times x plus w with x and w orthogonal vectors. Use the Pitagoryan theorem to stablish that the square of the norm of u equals the square of the norm of c times x plus the square of the norm of w. Use the adjoind or normal condition to show that w is zero.


text:
Q: Asteroids Game - Buggy Collision Detection I am making an asteroid game using Processing 3.5.3. As you will see the collision detection is very buggy. When it detects collision between ship/asteroid sometimes it is greater than the asteroid size, sometimes it is smaller. Also, when the asteroids get smaller, the collision detect still seems to be calling the larger size asteroid. The collision between bullet and asteroid seems to only be a hit when the bullet is in the center of the asteroid.
Apologies for all the comments - they are required for my internal documentation.
Here is my code, it is broken up into classes.
Ship
class Ship {

  PVector shipAcceleration;
  PVector shipVelocity;
  PVector shipPosition;
  PShape shipShape;
  float shipDirection;
  int shipLastFire;  //holds the time in millis that the last bullet was fired
  int shipDelayTime;

  Ship() {
    shipAcceleration = new PVector();
    shipVelocity = new PVector();
    shipPosition = new PVector(width/2, height/2); // player starts in middle of screen
    shipDirection = 0;  // set to 0 to so "up" is a sense of direction
    shipLastFire = 0;
    shipDelayTime = 300;
    keys = new boolean[5];
    shipShape = createShape();
    shipShape.beginShape();
    shipShape.fill(255, 0, 0);
    shipShape.vertex(0, -4);
    shipShape.vertex(2, 0);
    shipShape.vertex(2, 2);
    shipShape.vertex(0, 1);
    shipShape.vertex(-2, 2);
    shipShape.vertex(-2, 0);
    shipShape.vertex(0, -4);
    shipShape.endShape();
  }

  void moveShip() {
    shipShape.resetMatrix();
    // reset.Matrix sourced from https://processing.org/reference/resetMatrix_.html
    shipShape.rotate(radians(shipDirection));  // rotates ship
    shape(shipShape, shipPosition.x, shipPosition.y, 10, 10);
  }

  void updateShip() {
    // motion sourced from Chapter 22 of 'Processing: A programming handbook
    // for visual designers and asrtists' by Casey Reas and Ben Fry
    shipAcceleration.x = 0;
    shipAcceleration.y = 0;
    if (keys[0]) {
      shipAcceleration.x = 0.5 * cos(radians(shipDirection)  - PI/2);
      shipAcceleration.y = 0.5 * sin(radians(shipDirection) - PI/2);
    }
    if (keys[1] && !keys[2])
    {
      shipDirection -= 5;
    }
    if (keys[2] && !keys[1])
    {
      shipDirection += 5;
    }
    shipVelocity.add(shipAcceleration);
    // add sourced from https://processing.org/reference/PVector_add_.html
    shipPosition.add(shipVelocity);
    shipVelocity.mult(.95);
    // mult sourced from https://processing.org/reference/PVector_mult_.html
    shipPosition.x %= width;
    if (shipPosition.x < -10)
    {
      shipPosition.x = width;
    }
    shipPosition.y %= height;
    if (shipPosition.y < -10)
    {
      shipPosition.y = height;
    }
    if (keys[4]) {
      if (millis() - shipLastFire > shipDelayTime) {
        shipLastFire = millis();
        fireBullet(shipPosition, shipVelocity, shipDirection);
      }
    }
  }
}

Bullet
class Bullet {

  PVector bulletPosition;
  PVector bulletVelocity;
  boolean bulletHidden;  // used if lifespan is max and to help recycle
  int bulletSize;
  int bulletCreationTime;
  int bulletLifespan; //the time in milli seconds that bullets last
  int bulletSpeed;

  Bullet() {
    bulletHidden = true;
    bulletSize = 5;
    bulletPosition = new PVector();
    bulletVelocity = new PVector();
    bulletCreationTime = 0;
    bulletLifespan = 3000;
    bulletSpeed = 5;
  }
  void updateBullet() {
    if (!bulletHidden) {
      bulletPosition.add(bulletVelocity);
      if (millis() - bulletCreationTime > bulletLifespan)
      // millis sourced from https://processing.org/reference/millis_.html
      {
        bulletHidden = true;
      }
      bulletPosition.x %= width;
      if (bulletPosition.x < -1)
      {
        bulletPosition.x = width;
      }
      bulletPosition.y %= height;
      if (bulletPosition.y < -1)
      {
        bulletPosition.y = height;
      }
    }
  }
  void drawBullet() {
    if (!bulletHidden) {
      updateBullet();
      ellipse(bulletPosition.x, bulletPosition.y, bulletSize, bulletSize);
    }
  }

  void reset(PVector pos, PVector spe, float direct) {
    bulletPosition = new PVector(pos.x + (20 * cos(radians(direct) - PI/2)), pos.y + (20 * sin(radians(direct) - PI/2)));
    bulletVelocity.x = bulletSpeed * cos(radians(direct) - PI/2) + spe.x;
    bulletVelocity.y = bulletSpeed * sin(radians(direct) - PI/2) + spe.y;
    bulletCreationTime =  millis();
    bulletHidden = false;
  }
}

Asteroid
class Asteroid {
  float asteroidSize = (width/80*12);
  float x;
  float y;
  float velocityX;
  float velocityY;
  PVector[] vertices = new PVector[8];
  boolean active = true;  //false after collision
  int level = 1;  // how many times has it been shot.  Level 1 is not yet shot

  Asteroid(float xPos, float yPos, int aLevel) {
    if (xPos == 0 && yPos == 0) {   //if begin level asteroids
      x = random(width) ;            // set random start positions
      y = random (height);
    } else {                           // if collision generating 2 smaller asteroids
      x = xPos;                      // set from asteroid x, y
      y = yPos;
    }
    velocityX = random(-2, 2);
    velocityY = random(-2, 2);

    level = aLevel; //sets asteroid level (how many times shot)

    //create polygon.  /aLevel generates smaller polygons with each collision.
    vertices[0] = new PVector(random (width/80*3/aLevel), random(height/80*3/aLevel) );
    vertices[1] = new PVector(random((width/80*4/aLevel), (width/80*8/aLevel)), random(height/80*3/aLevel) );
    vertices[2] = new PVector(random((width/80*9/aLevel), (width/80*12/aLevel)), random(height/80*3/aLevel) );
    vertices[3] = new PVector(random((width/80*9/aLevel), (width/80*12/aLevel)), random((height/80*4/aLevel), (height/80*8/aLevel)) );
    vertices[4] = new PVector(random((width/80*9/aLevel), (width/80*12/aLevel)), random((height/80*9/aLevel), (height/80*12/aLevel)) );
    vertices[5] = new PVector(random((width/80*4/aLevel), (width/80*8/aLevel)), random((height/80*9/aLevel), (height/80*12/aLevel)) );
    vertices[6] = new PVector(random(width/80*3/aLevel), random((height/80*9/aLevel), (height/80*12/aLevel)) );
    vertices[7] = new PVector(random(width/80*3/aLevel), random((height/80*4/aLevel), (height/80*8/aLevel)) );
  }

  void moveAsteroid() {
    x = x + velocityX;  //asteroids to move with a random velocity
    y = y + velocityY;

    if ( x < -1 * asteroidSize ) {
      x = width + asteroidSize;
    }  //if off screen left, come back in right
    if ( x > width + asteroidSize ) {
      x = -1 * asteroidSize;
    }  // if off screen right, come back in left
    if ( y < -1 * asteroidSize ) {
      y = height + asteroidSize;
    }  //if off top of screen, come back in bottom
    if ( y > height + asteroidSize ) {
      y = -1 * asteroidSize ;
    }  //if off bottom of screen, come back in top
  }

  void asteroidDraw() {
    if (active == false) {  // If not active don't draw
      return;
    }
    stroke(150);
    fill(255);

    // this was how I orginally coded.  Have kept commented out for now, so I can see what I did, but will delete before submission.
    /*beginShape();
     vertex(vertices[0].x, vertices[0].y );
     vertex(vertices[1].x, vertices[1].y );
     vertex(vertices[2].x, vertices[2].y );
     vertex(vertices[3].x, vertices[3].y );
     vertex(vertices[4].x, vertices[4].y );
     vertex(vertices[5].x, vertices[5].y );
     vertex(vertices[6].x, vertices[6].y );
     vertex(vertices[7].x, vertices[7].y );
     endShape(CLOSE);  */

    beginShape();
    for (PVector v : vertices) {
      vertex(x+v.x, y+v.y);
    }
    endShape(CLOSE);
  }

  void manDown() {
    active = false;   //sets to in active so will stop drawing

    // add 2 new asteroids to array
    asteroids = (Asteroid[]) append( asteroids, new Asteroid( x+20, y+20, level + 1 ) ); // Appends asteroid to array.  Changing level makes the asteroid smaller.
    asteroids = (Asteroid[]) append( asteroids, new Asteroid( x-20, y-20, level + 1 ) ); // Appends two smaller asteroids to array.
  }
}

Game Manager
class GameManager {

  int scoreCount;
  boolean gameState = true;
  int lifeCount;

  void newGame()
  {
    gameState = true;  //sets game state to in play
    scoreCount = 0;  //set counter of flies killed to 0
    lifeCount = 3;
  }

  void scoreUpdate()
  {
    textSize(width*3/100);
    textAlign(LEFT);
    fill(255);
    text("Score " + scoreCount, (width*2/100), (height*4/100));
  }

  void lifeLost()
  {
    lifeCount = lifeCount - 1;
    if (lifeCount <= 0) {
      gameState = false;
      gameOver();
    }
  }

  void lifeUpdate()
  {
    textSize(height*3/100);
    textAlign(LEFT);
    fill(255);
    text("Lives " + lifeCount, (width*2/100), ((height*4/100) + (height*3/100)) );
  }

  void gameOver()
  {

    background(0);
    textSize(height*5/100);
    textAlign(CENTER);
    fill(255);
    text("Game over", width/2, height/2.6);

    //play again button
    fill(255);
    rect(((width/2)-(width/4)), (((height/2)- (height/12))), width/2, height/8);
    fill(0);
    text("Play Again", width/2, height/2);

    //define area for play again button collision
    if (mousePressed)
    {
      if (
        (mouseX > width/4) &&
        (mouseX < width/4  +width/2) &&
        (mouseY > (height/2-height/10.5)) &&
        (mouseY < ((height/2-height/10.5) + height/8))
        )
      {
        setup();  //reset game
      }
    }
  }
}

Main
Asteroid[] asteroids;  //K  Level 1 starts with 6, add 2 each level, 10 levels
Ship myShip;
GameManager gameManager;
ArrayList<Bullet> bullets;
// Array help sourced from chapter 28 of 'Processing: A programming handbook
// for visual designers and asrtists' by Casey Reas and Ben Fry
int bulletIndex;  // used to recycle bullets
// index sourced from https://py.processing.org/reference/list_index.html
int startNum = 6;  //K begin game with 6 asteroids in the level
boolean[] keys;  // boolean for storing keypressed/released

void setup() {
  size(800, 800);
  gameManager = new GameManager();
  gameManager.newGame();
  bulletIndex = 0;
  bullets = new ArrayList<Bullet>();
  keys = new boolean[5];
  myShip = new Ship();
  asteroids = new Asteroid [startNum];  //K
  for (int a = 0; a < startNum; a++) { //K create asteroids in array
    asteroids[a] = new Asteroid(0, 0, 1);  //K
  }
  for (int i = 0; i < 20; i++)
  {
    bullets.add(new Bullet());  // create bullets
  }
}

void draw() {
  background(0);
  collisionDetect();
  gameManager.gameState = true;
  myShip.updateShip(); // E
  myShip.moveShip();  // E
  for (int a = 0; a < asteroids.length; a++) {  //K  for asteroids in array
    asteroids[a].moveAsteroid();   //K
    asteroids[a].asteroidDraw();   //K
  }
  gameManager.scoreUpdate();
  gameManager.lifeUpdate();
  for (int i = 0; i < bullets.size(); i++)
  {
    bullets.get(i).drawBullet();  // drawing bullets
  }
}

void keyPressed() {
  if (key == CODED) {
    if (keyCode == UP)
      keys[0] = true;
    if (keyCode == LEFT)
      keys[1] = true;
    if (keyCode == RIGHT)
      keys[2] = true;
    if (keyCode == DOWN)
      keys[3] = true;
  } else {
    if (key == 'w')
      keys[0] = true;
    if (key == 'a')
      keys[1] = true;
    if (key == 'd')
      keys[2] = true;
    if (key == 's')
      keys[3] = true;
    if (key == ' ')
      keys[4] = true;
  }
}

void keyReleased() {
  if (key == CODED) {
    if (keyCode == UP)
      keys[0] = false;
    if (keyCode == LEFT)
      keys[1] = false;
    if (keyCode == RIGHT)
      keys[2] = false;
    if (keyCode == DOWN)
      keys[3] = false;
  } else {
    if (key == 'w')
      keys[0] = false;
    if (key == 'a')
      keys[1] = false;
    if (key == 'd')
      keys[2] = false;
    if (key == 's')
      keys[3] = false;
    if (key == ' ')
      keys[4] = false;
  }
}

void fireBullet(PVector pos, PVector spe, float dir) {
  bullets.get(bulletIndex).reset(pos, spe, dir);
  // set attributes of last used bullet
  // get sourced from https://processing.org/reference/get_.html
  bulletIndex++;  //update index
  bulletIndex %= bullets.size();  //keep index in range
}

void collisionDetect(){
    Asteroid testHolder;
    Bullet bulletHolder;
    //  asteroid and bullet objects to minimize creating new objects
    for(int i = 0; i < asteroids.length; i++){
      testHolder = asteroids[i];
     if(dist(testHolder.x, testHolder.y, myShip.shipPosition.x,
     myShip.shipPosition.y) < testHolder.asteroidSize)
     //  collision of player and the asteroid
        {gameManager.gameOver();}

      for(int j = 0; j < bullets.size(); j++){
        bulletHolder = bullets.get(j);
        //  pull and store each bullet from the list
        if(bulletHolder.bulletHidden){continue;}
        //  don't calculate anything if it is hidden
        if(dist(testHolder.x, testHolder.y, bulletHolder.bulletPosition.x,
          bulletHolder.bulletPosition.y) < testHolder.asteroidSize){
          testHolder.manDown();
          //  used to detect collision and split if collided
          bulletHolder.bulletHidden = true;
          //  hide the bullet so it won't go 'through' the asteroids
          j++;
        }
      }
    }
}

A: For the problem with the smaller asteroids, you need to make the asteroidSize dependent on the level. Currently they are all the same: float asteroidSize = (width/80*12);
As the to collision issue, the first thing is that you also have to take the size to the ship/bullet hitting the asteroid into account:
if(dist(testHolder.x, testHolder.y, myShip.shipPosition.x, myShip.shipPosition.y) < (testHolder.asteroidSize + myShip.size))
For clarity: size is in both cases the radius.
Second, there will always be some area's where this basic type of collision detection does not follow the visual, because your shapes are not circles. The randomness that you use for the asteroids does not help in that respect. A way to get more control over this is to define a couple of shapes per level, and pick one of those at random when creating an asteroid. This way you can tweak the shape/radius to make a good trade off between looks and function so it looks 'believable enough'.


text:
Q: Heroku 503 server error when using GoogleMaps Marker's OnClickListener I have an android activity that displays a map with markers. I set on marker click functionality in the onMapReady() method. There is one server request made to my Heroku server from this on click listener:
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                MapStyleOptions options = new MapStyleOptions("[]");
                mMap.setMapStyle(options);
                mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                    @Override
                    public boolean onMarkerClick(Marker marker) {
                        LatLng loc = marker.getPosition();
                        String userId = listingPointers.get(loc);
                        if (userId != null) {
                            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                            String token = preferences.getString("token", "");
                            Response.Listener<JSONObject> responseListener = new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    try {
                                        String firstName = response.getString("firstName");
                                        String lastName = response.getString("lastName");
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            };
                            JSONObject request = new JSONObject();
                            Response.ErrorListener errorListener = new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    test = false;
                                }
                            };
                            String address = "https://abcd.herokuapp.com/users/" + userId;
                            GetSingleRequest infoRequest = new GetSingleRequest(address, token, responseListener, request, errorListener);
                            RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
                            queue.add(infoRequest);
                        }
                        return false;
                    }
                });
            }
        });

I get a 503 status code from the Heroku Server, with an error code H10. I have no idea what causes this problem, and it causes the whole server to become unresponsive until I reset it.


text:
Q: UITableView loses selection after swipe I have a problem with the UITableView selection. If I swipe to show the Delete button, and then I tap somewhere else to cancel it, I loses the current selection.
How can I retain my selection by the Table even having done that, or at least know if the Delete button is being dismissed (so that I can manually re-select it)?

A: That is the default swipe to delete behaviour. There isn't any clean ways to retain the selection after you scroll.
It sounds like what you're trying to do is just to remember a cell selection? In that case, you will need to override the swipe gesture and add your own method. You can store this information any way you like.
As an example, you can check out this project that shows how to handle selections.


text:
Q: How to solve "Unable to create an object of type 'ApplicationDbContext'."? I am trying to creating new column in "Setting" table name "Description". But I am getting error like,

Error Number:207,State:1,Class:16
  An error occurred while accessing the IWebHost on class 'Program'. Continuing without the application service provider. Error: Invalid column name 'Description'.
  Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

I had tried to add column in another table, it's working fine. What was the cause behind this specific table. Any idea?
Thanks in advance.

A: Thank you everyone for your response. I had solved issue by just move the sequence of Dependency Injection in startup file.
Also,I was trying to migrate data base in Program.cs which cause issue. So moved that code in Startup.cs file.
            #region Migration

        context.Database.Migrate();

        HttpContextExtension.HttpContextAccessor = serviceProvider.GetService<IHttpContextAccessor>();
        var settingService = serviceProvider.GetService<ISettingService>();
        WebHelper.ContentRootPath = settingService.GetSettingByKey(Services.Constants.ConstantValues.SettingContentBasePath);

        #endregion


text:
Q: Como fazer UPDATE de imagem mysql php Galera tenho esse codigo e preciso fazer update da imagem que ja esta salva no banco, mas ele da erro, Undefined index: foto e file_get_contents(): Filename cannot be empty
Codigos
    <?php

require 'conexao.php';

//Pega o id da url
if ( isset( $_GET['id'] ) && ! empty( $_GET['id'] ) ) {
    //Prepra ligacao php mysql
    $stm = $pdo->prepare( 'SELECT id, nome, conteudo, tipo, tamanho FROM ifsp WHERE id = :id LIMIT 1' );
    //Atribui o paramentro ao $_GET['id'] que é o id que esta na url e coloca ele no prepare acima
    $stm->bindValue( ':id', $_GET['id'] );
    //Executa o pdo
    $stm->execute();

    //Tranforma o consulta em matriz
    $consulta = $stm->fetch( PDO::FETCH_ASSOC );

// Se executado
if ($stm->execute())
{
    // Alocando foto
    $foto = $stm->fetchObject();

    // Se existir
    if ($foto != null)
    {

    }
}

// Verificando se selecionou alguma imagem
if (!isset($foto->conteudo))
{
    exit;
} else {

    // Recupera os dados dos campos
    $foto = $_FILES['foto'];
    $nome = $foto['name'];
    $tipo = $foto['type'];
    $tamanho = $foto['size'];

     // Transformando foto em dados (binário)
    $conteudo = file_get_contents($foto['tmp_name']);

    if ( $_POST ) {

        //Ligação php mysql
            $stm = $pdo->prepare( 'UPDATE ifsp SET nome = :nome,
                                                   conteudo = :conteudo,
                                                   tipo = :tipo,
                                                   tamanho = :tamanho WHERE id = :id' );

        //Atribui o paramentro ao $_POST['e a referecia onde ele esta'] e coloca ele no prepare acima
        $stm->bindParam(':nome', $nome, PDO::PARAM_STR);
        $stm->bindParam(':conteudo', $conteudo, PDO::PARAM_LOB);
        $stm->bindParam(':tipo', $tipo, PDO::PARAM_STR);
        $stm->bindParam(':tamanho', $tamanho, PDO::PARAM_INT);
            //Atribui o paramentro ao $_GET['id'] que é o id que esta na url e coloca ele no prepare acima
        $stm->bindValue( ':id', $_GET['id'] );

            //Executa o pdo
            $stm->execute();

            //depois de executar o header o rediciona para outro local
            header( 'Location: index.php' );
        }
    }
}
    require 'views/editarfoto.php';

html

<?php include 'header.php'; ?>

Editar Contato

    <form enctype="multipart/form-data" action='editarfoto.php?id=<?php echo $consulta['id']; ?>'  method='post'>
        Foto
        <input type="file" name="foto" />

        <input type="submit" value="Salvar" />
        Cancelar
    </form>

<?php include 'footer.php'; ?>

banco
CREATE TABLE `ifsp` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `nome` varchar(60) NOT NULL,
 `conteudo` mediumblob NOT NULL,
 `tipo` varchar(20) NOT NULL,
 `tamanho` int(10) unsigned NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB;


text:
Q: I was advised not to use reflection here... Why not? This code is used to sort a List.  The list could contain in the thousands of elements but less than 10k.
protected <E> int compareFields(E o1, E o2, String fieldName){
    try {
        Comparable o1Data = (Comparable) o1.getClass().getMethod(fieldName).invoke(o1);
        Comparable o2Data = (Comparable) o2.getClass().getMethod(fieldName).invoke(o2);
        return o1Data == null ? o2Data == null ? 0 : 1 :
               o2Data == null ? -1 : o1Data.compareTo(o2Data);
    } catch(Exception e) {
        throw new RuntimeException(e);
    }
}

I was advised to

"Please don't use reflection for things like this!!
  Either supply the method with a suitable Comparator, or a method to extract the relevant property (may be computed in a way not supported by the original type), or both."

An example of a better way to do this would be nice.
Context:
I've got many screens with data tables.  Each one is build from a List.  Each data table needs to be sortable by each of its 6 columns.  The columns are either Date or String.

A: Using reflection here will potentially be much slower, as you are adding number of stack frames to each comparison by using getClass, getMethod and invoke rather than using the objects' native compare method.
Ideally, you would write the method to avoid the use of object in the signature.  A "suitable Comparator" would at least be strongly bound to the objects' type (which you assume are the same).  If you must have dynamic field comparison (as it appears), then at least the reflection could be encapsulated in that comparator.
If you are going to call this thousands of times, though, it would be best to pre-bind a Comparator to the field you are sorting by.  This way, you only call getMethod once up front, rather than once for each individual comparison.

A: It's hard to give a good example without context, so for now here's a small list of why it's not the best idea:

*

*The field provided has no guarantee of being Comparable (not sure why the code here needs to catch that exception and rebrand it).

*What if the type of objects provided are not meant to be compared in this way? (It's an overly generic method name to know how it's supposed to be used).

*It's not strongly typed. Providing the field name as a string means you'll have to change your code everywhere whenever the property name changes, and it'll be hard to track down where you need to make those changes.

*Reflection is potentially slower than if implemented in a strongly typed manner.

A: The other answers described well why it is not advised to use reflection. I want to add an example using a more conventional solution.
Instead of specifying the field that is used to compare the two objects, you should take a Comparator instance as an argument. This way the client who uses this method can specify how to compare the two objects.
protected <E> int compareFields(E o1, E o2, Comparator<E> comparator) {
    return comparator.compare(o1, o2);
}

And an example call to this function would look like this:
MyClass a = ...;
MyClass b = ...;
Comparator<MyClass> intFieldComparator = new Comparator<MyClass> {
    public int compare(MyClass o1, MyClass o2) {
        int field1 = o1.getIntField();
        int field2 = o2.getIntField();

        return field2 - field1;
    }
};

compareFields(a, b, intFieldComparator);

You can define different comparators if you want to compare the objects using several fields.


text:
Q: What exactly are the css boundaries in web components?

Styles!

somebody made a very broad selector

    <isolated-stuff></isolated-stuff>

I am struggling to understand the style scoping for web modules.
This css-tricks page says

Note that the functionality still works (although we had to querySelector through the shadowRoot), but we've totally lost the global styling. The Shadow DOM boundary (shadow root) prevents styling coming in or going out (sorta like an iframe).

I realize that the document I'm working with probably shouldn't have used such a broad body style. Can I find some documentation on why the text in my div is blue?

A: The short answer is that inheritance crosses the Shadow DOM boundary.
See 3.1. Informative Explanation of Shadow DOM. In particular it says:

... the shadow tree, when it exists, is used in the construction of the flattened element tree, which CSS uses for all purposes after Selectors (including inheritance and box construction).

This is why custom properties (CSS variables) can cross the Shadow DOM boundary, as described in the CSS-Tricks article.
Since color is an inherited property, and in your example is not reassigned inside the shadow tree, the text inside inherits the blue color.


text:
Q: Webkit/Blink: child padding set in %, when the parent has padding as well I am seing a strange behavior in all Webkit|Blink-based browsers I can reach (Opera 16+, Chrome 12, 29, Safari 5.1 Windows).
Assume we have a parent div, and a child block element inside it. If we set the child's width:xx% and some padding:xx%, the properties are calculated to the required values.
But if the parent has padding itself, the child's padding (which is in percents) does not respect the parent's paddings. I see this only in Webkit|Blink. The child's width does respect the parent's padding in all browsers. box-sizing seems not to influence this behavior.
For the example please see the fiddle. The bottom's child is square, as it should be. And the top's child is not: its padding-bottom:50% and width:50% are calculated to different values. Again, in FF, IE (9 at least), pre-Blink Opera both dash-bordered blocks are square. And below are the code exerpts.
HTML:

CSS:
.parent{
    position:relative;
    width:200px;
    height:100px;
}
.parent.padded{
    padding:20px 30px;
}
.parent:after{
    position:absolute;
    bottom:0;
    left:0;
    box-sizing:border-box;
    width:50%;
    padding-bottom:50%;

    content:"";
}

Could anyone please help me make it clear: is it the engine's bug? Or maybe there is some explaination to this anywhere in the Spec?
Thanks!


text:
Q: Why is 4.096V so often used as a voltage reference? I get that each mV is equivalent to a bit in a 12-bit ADC, but why is 4.096V used so often? I've heard of this being from a "bridge". What does this mean and what is the historical significance?

A: It may or may not have historical significance, but if you have a perfect 12 bit DAC/ADC, each A/D count (or LSBit) corresponds to 1 mV, making some math easier.
FWIW, I personally see 2.5v being more common and I use internal bandgap references for non-critical measurements.

A: 4.096 volts appears to have nothing in common with various Standard Cells, such as they Weston Cell. Even using Li, you'll not get much more than 3 volts from a standardizable chemical reaction.
NIST Standard cell calibrations (pdf):

The US. Legal (or NBS) Volt is presently defined in terms of the atomic constants h (the Planck constant) and e (the elementary charge) via the ac Josepson effect[26]. Critical to this is definition is the role of the Josephson junction which may be regarded as a frequency to voltage converter, where the frequency-to-voltage ratio is precisely equal to to the combination of physical constants 2e/h.... The U.S. legal definition of voltage is known to be smaller than the SI unit by about (9+-1) ppm...

There's no obvious conection to 4.096 volts there either, so I strongly suspect the value 4.096 is chosen for its convenience when using 12 bit ADC, rather than any underlying fundamental physical principle.

A: You run that 4.096 as the reference to your ADC, and as the power to your bridge. Then, if it varies with time or temp, the reading into  your ADC stays the same. I've heard it called a radiometric measurement. The 4.096 gives you plenty of range on your 5V ADC, some headroom for your esd diodes and is commonly available.


text:
Q: initialise jquery-isotope with angular2 i need some help for angular2 issue. Currently i use jquery-isotope in my angular2 component. But i have problem to initialise jquery-isotope.
Could you help me please ?
This is my code:
Querygrid;
ngOnInit():
any {
 /* initiate isotope */
   this.jQuerygrid = jQuery('.draggable_media_list').isotope({
   itemSelector: 'div.dd',
   layoutMode: 'fitRows'
    });
 }


text:
Q: UIActivityIndicatorView not centering on screen, specifically when UITableView is root view I have a weird issue where my UIActivityIndicator isnt centering in a NIB that has a root view of a UITableView.  My other views have a root view of UIView with a UITableView inside it and works fine.  The screenshot below shows the indicator isnt in the middle but a little further down.
UIActivityIndicatorView  *activity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];

    CGRect frame = activity.frame;
    frame.origin.x = self.view.frame.size.width / 2 - frame.size.width / 2;
    frame.origin.y = self.view.frame.size.height / 2 - frame.size.height / 2;
    activity.frame = frame;
    [self.view addSubview:activity];
    activity.tag = 1;
    [activity startAnimating];

A: It works fine for me sure this will help you
UIActivityIndicatorView *activity=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activity.center=CGPointMake(self.tableView.center.x, self.YourtableView.center.y-64);
  [self.YourtableView addSubview:activity ];
[activity startAnimating];


text:
Q: Orthogonal projection to the unit line (1,1,1,1) 4d I have data that shows the strength of an effect for 4 conditions over multiple features. (For each Features the Effect are always the same sign)
I want to find a way to order the features by the strength of the effect with a metric. In 2D I would make an orthogonal projection to the (1,1) line and use the distance of the projected point to the origin as a metric.
Is it possible to do the same thing in 4D?
I am not a very good mathematician, and I am really unsure about what I have done.
I was hoping to use the Pythagoras theorem and the dot product but I am not sure if what I done is correct. So could you tell me if my solution is correct? and if it is not correct how to achieve my goal?
Here the 3 dimension representation of the problem

We have a 4 D space with axes orthogonal and origins O as (0,0,0,0)
We have a point $P(P_x, P_y, P_z, P_w)$ that represents a feature. I want to make an orthogonal projection over the line w(1x,1y,1z,1w). $R$ the point of the orthogonal projection of P over w.
The distance $\lVert \vec{OR} \rVert$ is the score I look for.
If Pythagoras is applicable then:
$ \lVert \vec{OR} \rVert = \sqrt[2]{\lVert \vec{OP} \rVert^{2} - \lVert \vec{RP} \rVert^{2} }$
with $ \lVert \vec{RP} \rVert  = \sin{\theta} * \lVert \vec{OP} \rVert $
and to get theta we use the dot product between $\vec{OP}$ and any point of w. let pick w1 the point (1,1,1,1).
$$ \theta = \arccos{ \frac{ \vec{Ow1} . \vec{OP}} {\lVert \vec{Ow1} \rVert  * \lVert \vec{OP} \rVert }}$$
So in the end we obtain
$$  \lVert \vec{OR} \rVert = \sqrt[2]{\lVert \vec{OP} \rVert^{2} -  (\sin{\arccos{ \frac{ \vec{Ow1} . \vec{OP}} {\lVert \vec{Ow1} \rVert  * \lVert \vec{OP} \rVert }}} * \lVert \vec{OP} \rVert) ^{2}} $$
I don't know if it matter but I plan to use euclidean distance.


text:
Q: cakephp: displaying error message in controller when beforeSave method of model returns false? I have this beforeSave method in my Student model which returns true or false.
Instead of displaying a standard msg for all save errors in StudentsController(Your admission could not be saved. Please try again.), I want to display a different error message when beforeSave mtd of Student model returns false. How can I do that?
StudentsController
function add(){
if ($this->Student->saveAll($this->data)){
$this->Session->setFlash('Your child\'s admission has been received. We will send you an email shortly.');
 }else{
$this->Session->setFlash(__('Your admission could not be saved. Please, try again.', true));
   }
}

A: I suggest implementing validation rules and then calling:
if ($this->Model->validates() ) {
  save
} else {
  error message / redirect
}

Read up on data validation within CakePHP

A: Deceze and Chapman were right. I found the solution from the DAta validation chapter of cakephp cookbook. Thanks a lot guys.
The following is the validation rule i've added:
for Student's name in Student Model:
var $validate=array(
        'name'=>array(
                'nameRule1'=>array(
                    'rule'=>array('minLength',3),
                    'required'=>true,
                    'allowEmpty'=>false,
                    'message'=>'Name is required!'
                    ),
                'nameRule2'=>array(
                       'rule'=>'isUnique',
                       'message'=>'Student name with the same parent name already exist!'
                     )
                ),

Then in StudentsController's add function:
//checking to see if parent already exist in merry_parents table when siblings or twin are admitted.
            $merry_parent_id=$this->Student->MerryParent->getMerryParentId($this->data['MerryParent']['email']);
            if (isset($merry_parent_id)){
                $this->data['Student']['merry_parent_id']=intval($merry_parent_id);
                var_dump($this->data['Student']['merry_parent_id']);
                if ($this->Student->save($this->data)){
                //data is saved only to Students table and not merry_parents table.
                    $this->Session->setFlash(__('Your child\'s admission has been received.
                                        We will send you an email shortly.',true));
                }else
                        $this->Session->setFlash(__('Your admission could not be saved. Please, try again.',true));
            }else{//New record. So, data is saved to Students table and merry_parents table.
                      if ($this->Student->saveAll($this->data)){ //save to students table and merry_parents table
                         $this->Session->setFlash(__('Your child\'s admission has been received.
                                                          We will send you an email shortly.',true));
                      }else
                          $this->Session->setFlash(__('Your admission could not be saved. Please, try again.', true));
                 }//new record end if

There was no need for me to validate the data without saving as mentioned by Chapman. So, I didn't use:
if ($this->Model->validates() ) {
  save
} else {
  error message / redirect
}