Code for writing and reading from the database

Question: I created code for inserting and retrieving data from a specific table. I tried to optimize it and make it as beautiful and easy to read as I can, but maybe (almost certainly) I'm missing something.
It works well, but I wonder if I did all right?  Have I forgotten about something?
public class EpgManager {

private DatabaseHandler db;
private List<JSONEpgManagerModel> jsonEpgManagerModel;
private EPGManagerEvent epgManagerEvent;
private SQLiteDatabase sqlDB;
private List<EPGModel> singleEpgChannel;
private List<EPGFullRowModel> fullRowModelList = new ArrayList<>();

public EpgManager(Context context, EPGManagerEvent epgManagerEvent) {
    db = new DatabaseHandler(context);
    sqlDB = db.getWritableDatabase();
    this.epgManagerEvent = epgManagerEvent;
}

/**
 * Method: Serializes Json String into Object of type JsonEpgManagementModel
 *

 *
Creates a sql insert query

 *
Cleans epg_table

 *
Loads data from JSON

 *
Calls the {@link #epgManagerEvent onEpgUpdated} to show completion

 *

 *
 * @param JSON epg json array
 */
public void updateEpgTable(final String JSON, final HashMap<String, Integer> channelNumberMap,
    final HashMap<String, String> channelImageMap) {

    new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... params) {
            sqlDB.delete(db.EPG_TABLE, null, null);

            try {
                jsonEpgManagerModel = Arrays
                    .asList(new Gson().fromJson(JSON, JSONEpgManagerModel[].class));
            } catch (Exception e) {
                e.printStackTrace();
            }

            writeEPGTable(jsonEpgManagerModel, channelNumberMap, channelImageMap);

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            epgManagerEvent.onEpgUpdated();

        }
    }.execute();
}

/**
 * Method: Inserts rows into epg_table
 *
 * @param jsonEpgManagerModel Serialized EPG Model
 * @param channelNumberMap Channel ID and Channel Number HashMap
 * @param channelImageMap Channel ID and Channel Image HashMap
 */
private void writeEPGTable(List<JSONEpgManagerModel> jsonEpgManagerModel,
    HashMap<String, Integer> channelNumberMap, HashMap<String, String> channelImageMap) {
    String epgSqlInsertStatement = "INSERT INTO "
        + db.EPG_TABLE
        + "("
        + db.KEY_EPG_ID + "," + db.KEY_EPG_DATE + ","
        + db.KEY_EPG_DATE_MILLISECONDS + "," + db.KEY_EPG_DISPLAY_TIME + ","
        + db.KEY_EPG_TITLE + "," + db.KEY_EPG_DESCRIPTION + "," + db.KEY_EPG_IMAGE_URL + ","
        + db.KEY_EPG_DURATION + "," + db.KEY_EPG_CHANNEL_ID + ","
        + db.KEY_EPG_CHANNEL_NUMBER + "," + db.KEY_EPG_CHANNEL_IMAGE_LINK
        + ")"
        + " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";

    sqlDB.beginTransaction();
    SQLiteStatement sqLiteStatement = sqlDB.compileStatement(epgSqlInsertStatement);

    for (int i = 0; i < jsonEpgManagerModel.size(); i++) {
        for (int k = 0; k < jsonEpgManagerModel.get(i).getEPGList().size(); k++) {

            ChannelPrograms epgProgram = jsonEpgManagerModel.get(i).getEPGList().get(k);

            sqLiteStatement.bindString(1, epgProgram.getEpgId());
            sqLiteStatement.bindString(2, epgProgram.getEpgDate());
            sqLiteStatement.bindLong(3, getDateInMilliseconds(epgProgram.getEpgDate()));
            sqLiteStatement.bindString(4, epgProgram.getEpgDisplayTime());
            sqLiteStatement.bindString(5, epgProgram.getEpgTitle());
            sqLiteStatement.bindString(6, epgProgram.getEpgDescription());
            sqLiteStatement.bindString(7, epgProgram.getEpgImageUrl());
            sqLiteStatement.bindString(8, epgProgram.getEpgDuration());
            sqLiteStatement.bindString(9, jsonEpgManagerModel.get(i).getEpgChannelId());
            sqLiteStatement.bindString(10, "" + channelNumberMap.get(jsonEpgManagerModel.get(i).getEpgChannelId()));
            sqLiteStatement.bindString(11, "" + channelImageMap.get(jsonEpgManagerModel.get(i).getEpgChannelId()));

            sqLiteStatement.executeInsert();
            sqLiteStatement.clearBindings();
        }
    }

    sqlDB.setTransactionSuccessful();
    sqlDB.endTransaction();
}

/**
 * Method returns list of epg channels and programs in order to build the epg
 *

 *
Gets rows from channel_table

 *
Gets rows from epg_table by channel_table channel_id

 *
Populates list of EPGFullRowModel class

 *

 *
 * @return EPG Screen data list of type EPGFullRowModel
 */
public List<EPGFullRowModel> getAllChannelPrograms() {
    List<EPGModel> epgProgramList = new ArrayList<>();

    Cursor channelCursor = sqlDB.query(db.CHANNEL_TABLE,
        new String[] {db.KEY_CHANNEL_ID, db.KEY_CHANNEL_IMG_LINK, db.KEY_CHANNEL_NUMBER}, null,
        null, null, null, null);
    Cursor epgCursor;

    while (channelCursor.moveToNext()) {

        epgCursor = sqlDB.query(db.EPG_TABLE, null, db.KEY_EPG_CHANNEL_ID + "=?",
            new String[] {channelCursor.getString(0)}, null, null,
            db.KEY_EPG_DATE_MILLISECONDS + " ASC");
        while (epgCursor.moveToNext()) {
            epgProgramList.add(
                new EPGModel(
                    epgCursor.getString(1),epgCursor.getString(2),
                    epgCursor.getString(3),epgCursor.getString(4),
                    epgCursor.getString(5),epgCursor.getString(6),
                    epgCursor.getString(7),epgCursor.getString(8),
                    epgCursor.getString(9),channelCursor.getString(2),
                    epgCursor.getString(1)
                )
            );

        }
        fullRowModelList.add(new EPGFullRowModel(
            new ChannelModel(channelCursor.getString(0), channelCursor.getString(1),
                Integer.valueOf(channelCursor.getString(2))), epgProgramList));

        epgCursor.close();
        epgProgramList = new ArrayList<>();
    }

    channelCursor.close();
    return fullRowModelList;
}

/**
 * Method returns list of epg programs in order to build the single channel epg
 *
 * @param channelId Channel unique id
 * @return Single epg row list of type EPGModel
 */
public List<EPGModel> getSingleChannelPrograms(String channelId) {

    Cursor cursor = sqlDB
        .query(db.EPG_TABLE, null, db.KEY_EPG_CHANNEL_ID + "=?", new String[] {channelId}, null,
            null,  db.KEY_EPG_DATE_MILLISECONDS + " ASC", null);

    singleEpgChannel = new ArrayList<>();
    Log.e("CURSOR ", String.valueOf(cursor.getCount()));
    if (cursor.moveToFirst()) {
        do {
            singleEpgChannel.add(
                new EPGModel(cursor.getString(1), cursor.getString(2), cursor.getString(3),
                    cursor.getString(4), cursor.getString(5), cursor.getString(6),
                    cursor.getString(7), cursor.getString(8), cursor.getString(9),
                    cursor.getString(10), cursor.getString(11)));
        } while (cursor.moveToNext());
    }
    cursor.close();
    return singleEpgChannel;
}

/**
 * Method transforms the date of string into long of milliseconds
 *
 * @param date Epg program date
 * @return Milliseconds
 */
private long getDateInMilliseconds(String date) {

    date = date.replaceAll("T", " ");
    date = date.replaceAll("Z", "");
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar calendar = Calendar.getInstance();
    try {
        calendar.setTime(simpleDateFormat.parse(date));
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return calendar.getTimeInMillis();
}
}

Comment: Good on you for using a compiled statement to run the insert! They are so much faster than using the SQLiteDatabase#insert helper method
Answer: As RobAu said, there's a lot going on. A priori, I am developing enterprise applications, so there's usually a lot of stupid logic involved, way too much data and thousands of concurrent acccesses to databases - and maybe I sound like a bit like I'm ranting and nitpicking and maybe some suggestions are a bit overkill. But since we're here...
Transactions / unit of works
You are working with transactions within the writeEGPTable method. But this method is called in updateEpgTable which actually does whipe the table. Just keep in mind, that if you have a unit of work, where you do more than an insert, you can get inconsistent data in a concurrent environment (not only concurrent within your app, but others accessing and manipulating the database). The transaction management is usually decoupled from the database access object, since, like in your example, the writeEPGTable method does not know about what is happening around it. I highly recommend to read about those topics (transaction management, unit of work, isolation levels). Speaking from experience: It's surprisingly easy to mess everything up, if you do not know exactly what you are doing. So easy ...
delete and insert all
Usually, deleting and inserting is way more expensive than to update existing, insert new ones, and deleting non existing ones. If you delete everything, and insert everything, you mess up indexes and statistics.
column index access
During reading, you read the values using the column indexes. It's almost always better to use the column names. If you declare the columns' order within select statement (which I do not recommend), you always have to change both, the statement and the retrieving of the column values. If you select * and the columns get reordered, your application will break.
JSON / Model
You actually provide an EPGFullRowModel, but you pass json to updateEpgTable, which then is de-jsonified to the an List<EpgManagerModel>, which then will be passed to writeEPGTable, within that, you get the ChannelPrograms and create the insert statement. The json has no business in the data layer, the mapping from json to the actual type to write should be performed in its separate type. I recommend to write a type which holds the data it needs and pass this one, instead of JSON, a map of channelNumbers and a map of channelImages.
tidy up
Your methods are way too long. For instance, the writeEPGTable, consider the following points: Declare the insert statement as constant in the class and move the binding of the values to a separate static helper method. That should look much better.
SQLite
I never worked with SQLite, to be honest. But: Keep in mind, you cannot exchange your database without a huge amount of work - at least that's how it looks. I would have implemented it using standard jdbc, assuming sqllite provides a jdbc driver.
other

I think there's code duplication for the instantiation of ChannelModel in getAllChannelPrograms and getSingleChannelPrograms
You declare singleEpgChannel as member variable, but it's only instantiated and accessed in getSingleChannelPrograms, which does return the actual member singleEpgChannel. The member variable can be removed.

further readings
I made this section, because you want to write your own database access, and to not use ORM's like hibernate or eclipse's link. So this should interest you
Maybe you'd like to check Fowler's list of eea patterns: https://martinfowler.com/eaaCatalog/ - especially the Data Source Architectural Patterns. And also the "dao" j2ee pattern from core j2ee patterns: http://www.corej2eepatterns.com/DataAccessObject.htm, that's a very common one (which only decouples backend implementation, there's still a lot of other problems).
Also, "Tom" from oracle has a lot of very, like very good blog posts about databases, not only oracle specific. Just google "ask tom " + whatever you want to know (about databases, of course). For transaction management and isolation levels, read this one: http://www.oracle.com/technetwork/testcontent/o65asktom-082389.html.
(Keep in mind, design patterns can't usually work on their own and will not per se solve your problems. But it should give you an idea, how problems have been solved and you can apply that to your own design).
Hops this helps.
Answer: There is a lot going on in your code, but this struck me first:
If / do / while
if (cursor.moveToFirst()) {
    do {
     .....
    } while (cursor.moveToNext());
}

This can be written as:
while (cursor.moveToFirst()) {
     .....
}

Static / Casing?
This is something you should never see:
db.EPG_TABLE

Either EPG_TABLE is static on DatabaseHandler, in which case you should access it using DatabaseHandler.EPG_TABLE. Or it is a field, and then it should be camelCase.


Can I bring protein powder and health bars into the UK from the US?

Question: Will be travelling to the U.K. from the U.S. and would like to take my protein powder and some health bars to snack on during my visit.  Is this allowed to bring into the country?
Comment: Just curious - you can buy those fairly easily in the UK - any reason you particularly want to bring your own?
Comment: http://www.defra.gov.uk/food-farm/food/personal-imports/rules/
Answer: This is an old thread, but just to close the loop, it is my understanding that dairy (even if powder) products are not allowed unless you carry a health certificate with them.
Thus any milk-based protein powder will face an issue.
Comment: This is exactly correct. The [UK government website](http://www.defra.gov.uk/food-farm/food/personal-imports/rules/) cited in Brian Nixon's comment below the question continues to state that one may not bring "milk or milk-based products, except powdered infant milk, infant food or special food (including pet food) needed for medical reasons" from the US.
Answer: I don't see any reason why not, unless your planning to import enough to pass from personal to commercial use. In my experience, custom agents are mostly interested in  animal or plant products and not packaged foods.
Comment: This is not correct. See the answer above from John Connor and comment below.


What type of microphone is best for a medium space room mix?

Question: I'm looking for a way to record a live dance class in a 25' x 20' space. I want the classroom ambience but also want the teacher's voice to be clear. I'll be using a PA system either in the back or front of the class. I'll be routing the output of the PA system directly into a computer and likely mixing that with a room mic to add the classroom ambience. Is there a suitable microphone that, if placed properly, will pickup a teacher at the front of the class as well as a robust room ambience? The teacher will be located between 3 and 10 feet from the microphone. The teacher will also face the microphone as I intend to mount this microphone on the wall towards the ceiling. I know I could mix a room mic with a fitness mic (something the teacher wears), but I'm wondering if there is a suitable mic that would remove the need for two mics.
In addition, this recording takes place in a dance studio in which almost all wall surface area is covered in mirrors. What considerations should I have regarding this environment when choosing a microphone?
Thanks for reading
Answer: I've been avoiding answering this for the whole day, because my overwhelming thought is "you don't want to do it like that".
Ambience is going to be the enemy of clarity in that type of environment.
You're feeding a 'fitness mic' - which I assume is some kind of cheap headset mic near the mouth - into a PA in a very live room.
Any other mic you put in that room is going to be ambient - whether it's 3ft or 10ft from your instructor. You do not want to be feeding this mic to your PA at all.
The only solution I can see does involve both mics.
Your 'fitness mic' feeds to the PA & to your recording. Get the PA at the opposite end of the room from the instructor.
Your ambient mic feeds only to your recording. The further away from your instructor & the PA, the better. This is [attempting to be] purely for room sound, so you want to avoid the main voice as much as possible.
You judiciously balance one against the other using headphones before feeding it to your recorder, unless you are recording multi-track so you can mix later.
This will all need to be mono, else you will need two ambient mics.
As for mic choice; you may as well just go for a dynamic cardioid on a wall, pointing at the room centre.
Answer:
I know I could mix a room mic with a fitness mic (something the teacher wears), but I'm wondering if there is a suitable mic that would remove the need for two mics.

You want to capture the ambience.  The class is the ambience and wants to hear the teacher.  Case closed.
Since you say you are going to pick up the teacher via the PA, all you need to worry about is the ambience.  You'd use a cardioid or hypercardioid condensor for that and put the teacher's PA as well as possible into its dead zone while pointing at a representative part of the group.  Prioritising that group over the PA may require moving up a bit: try not to be creepy.  If the distance is a bit more, a reasonably quiet large diaphragm condenser would help you avoid hiss (hiss sounds like electronics, not like ambience).  You'll want a good microphone suspension (spider) and possibly a lowcut on the microphone to avoid stomping noises dominating the recording levels.
Whether you do some lo-fi and reverb treatment of the PA part of your recording to make it blend in better is up to your choice: a clean take from the instructor mic leaves open your options.


How to change a css class style through Javascript?

Question: According to the book I am reading it is better to change CSS by class when you are using Javascript. But how? Can someone give a sample snippet for this?
Answer: Suppose you have:

text

and the following styles:
.oldclass { color: blue }
.newclass { background-color: yellow }

You can change the class on mydiv in javascript like this:
document.getElementById('mydiv').className = 'newclass';

After the DOM manipulation you will be left with:

text

If you want to add a new css class without removing the old one, you can append to it:
document.getElementById('mydiv').className += ' newClass';

This will result in:

text

Comment: Instead of `document.getElementById('mydiv').className += ' newClass';`, use `classList` to add and remove classes: `document.getElementById('mydiv').classList.add('newclass');`.  By doing it this way, you won't need to test if the class already exists before adding it, the add method will do that for you.  Likewise with remove, you won't have to test if a class exists before manipulating the `className` property.  You also don't have to remember to prefix the class you're adding with a space.
Comment: @Asaph: Actually it's supported in Chrome >= 8.0, Firefox >= 3.6, Safari >=5.1, Opera >= 11.5, and IE >= 10.0. [Source](http://caniuse.com/#feat=classlist)(click on Show all versions). The only older browser you should worry about support for is IE <= 9.0 which a polyfill like [classList.js](https://github.com/eligrey/classList.js) should work fine for.
Comment: @nwayve: `classList` is only supported on IE >= 10, Chrome >= 34, Firfox >= 29 and Safari >= 7. Source: http://caniuse.com/#search=classList . If you need support for older browsers, use `className`.
Comment: @nwayve: The source you linked is the same one I did. But I wasn't aware that I need to click on "Show all versions" to see the minimum supported version (not the most intuitive ui if you ask me). Thanks for the clarification. In any case, the point still stands, `className` is more backwards compatible than `classList`.
Comment: Bas answer but prolly the only one.
Answer: Since classList is supported in all major browsers and jQuery drops support for IE<9 (in 2.x branch as Stormblack points in the comment), considering this HTML

text

you can comfortably use this syntax:
document.getElementById('mydiv').classList.add("newClass");

This will also result in:

text

plus you can also use remove, toggle, contains methods.
Comment: to clarify - jQuery hasn't dropped support for IE<9. They still update the 1.x branch, which is designed to have IE browser support. 2.x has no such support, but is somewhat faster because of this.
Comment: I think this is the best pure JS solution, using `add` and `remove`. Much better than the accepted answer.
Answer: If you want to manipulate the actual CSS class instead of modifying the DOM elements or using modifier CSS classes, see
https://stackoverflow.com/a/50036923/482916.
Answer: I'd highly recommend jQuery.  It then becomes as simple as:
$('#mydiv').addClass('newclass');

You don't have to worry about removing the old class then as addClass() will only append to it.  You also have removeClass();
The other advantage over the getElementById() method is you can apply it to multiple elements at the same time with a single line of code.
$('div').addClass('newclass');
$('.oldclass').addClass('newclass');

The first example will add the class to all DIV elements on the page.  The second example will add the new class to all elements that currently have the old class.
Comment: It's good to know how to do things without a framework, for understanding and when you want to make something truly lightweight, but there's no reason to not use a library like jQuery for most development.
Comment: Totally agree, Mark. I now think of it like being a manager - never delegate work to a sub-ordinate that you wouldn't be able to do yourself. I.e. never use a framework to do something you wouldn't know how to do yourself.
Comment: thanks for the tips sir. I'll get into that soon. I am just starting to read about javascript ;)
Comment: Another benefit in using a framework is that you can more easily add or remove class names rather than simply replace the entire class attribute's value (e.g. to remove "myclass" from an element with a class attribute of "myclass myotherclass" you'd otherwise have to replace the attribute value with "myotherclass" or do something funky like split the string into an array and remove the entry "myclass" from it before joining it back together, etc. Go Frameworks!
Comment: I never entertained the idea of using a Javascript library as I thought it'd just be yet another framework to use, another JS file to download, another place to debug to find problems... yada yada yada.

One day I was bored, bit the bullet and tried jQuery.  Within an hour I'd vowed never to create a website or webapp without it - it's so easy!

You could probably even learn jQuery and never touch any other Javascript.
Answer: There are two ways in which this can be accomplished using vanilla javascript.  The first is className and the second is classList.  className works in all browsers but can be unwieldy to work with when modifying an element's class attribute.  classList is an easier way to modify an element's class(es).
To outright set an element's class attribute, className is the way to go, otherwise to modify an element's class(es), it's easier to use classList.
Initial Html

Setting the class attribute
var div = document.getElementById('ID');
div.className = "foo bar car";

Result:

Adding a class
div.classList.add("car");// Class already exists, nothing happens
div.classList.add("tar");

Note: There's no need to test if a class exists before adding it. If a class needs to be added, just add it. If it already exists, a duplicate won't be added.
Result:

Removing a class
div.classList.remove("car");
div.classList.remove("tar");
div.classList.remove("car");// No class of this name exists, nothing happens

Note: Just like add, if a class needs to be removed, remove it. If it's there, it'll be removed, otherwise nothing will happen.
Result:

Checking if a class attribute contains a specific class
if (div.classList.contains("foo")) {
  // Do stuff
}

Toggling a class
var classWasAdded = div.classList.toggle("bar"); // "bar" gets removed
// classWasAdded is false since "bar" was removed

classWasAdded = div.classList.toggle("bar"); // "bar" gets added
// classWasAdded is true since "bar" was added

.toggle has a second boolean parameter that, in my opinion, is redundant and isn't worth going over.
For more information on classList, check out MDN. It also covers browser compatibility if that's a concern, which can be addressed by using Modernizr for detection and a polyfill if needed.
Answer: use the className property:
document.getElementById('your_element_s_id').className = 'cssClass';

Comment: Be carefull, if you just want to add a new class, this way will replace all the class="" attributes, not just append the new one.
Answer: document.getElementById("my").className = 'myclass';
Answer: You may also be interested in modifying it using jQuery:
http://api.jquery.com/category/css/
Answer: <!DOCTYPE html>

This is a paragraph.


Force WordPress live preview to reload

Question: I have some elements that are loaded into my home page if the option to do so is set in the theme customizer. When adding the control to the theme customizer to display the element I have set transport to postMessage so the preview does not reload when the option is changed. In the javascript file I am using to update the preview in real time, when the option to display the extra elements is changed I am checking weather or not the elements have been loaded and if they have I use fadeIn and fadeOut to remove or add the elements, however if they have not been loaded I will need to force the preview to reload using jquery as the elements will not yet exist to fadeIn or fadeOut. Below is my jquery so far...
wp.customize( 'element_show', function( value ) {
  value.bind( function( newval ) {
    if($(".element").length == 0){
      //elements are not loaded so need to reload the live preview on change to load the elements, this is where I am stuck
    }
    else{
      //elements are loaded so it is just a case of using fadeIn and fadeOut
      if(newval == 'yes'){
        $(".element").fadeIn();
      }
      else{
        $(".element").fadeOut();
      }
    }
  } );
} );

I hope that makes sense, thank you in advance :)
Answer: Use this to force refresh the preview pane in customizer :
wp.customize.previewer.refresh();

Final code
wp.customize( 'element_show', function( value ) {
value.bind( function( newval ) {
if($(".element").length == 0){
  wp.customize.previewer.refresh();
}
else{
  if(newval == 'yes'){
    $(".element").fadeIn();
  }
  else{
    $(".element").fadeOut();
  }
}
} );
} );

Force WordPress live preview to reload


How can I avoid the prompts when installing a FreeBSD port?

Question: When I install a port, I am often presented with a menu screen to select configuration options. If I'm going to install a really big package with lots of dependencies, that will be extremely inconvenient. Is there a make flag for accepting the default answers for all such prompts?
Answer: Probably BATCH, described in ports(7), is what you're looking for:
# cd /usr/ports/sysutils/screen
# export BATCH=yes
# make rmconfig
# make install clean
(no configuration menu is displayed)

make rmconfig removes OPTIONS config for this port, and you can use it to remove OPTIONS which were previously saved when you configured and installed screen(1) the first time. OPTIONS are stored to directory which is specifed via PORT_DB_DIR (defaults to /var/db/ports).
If you use bash, BATCH can be set automatically every time you log in:
# echo 'export BATCH=yes' >> ~/.bash_profile

Comment: I prefer `make config-recursive && make install clean`, as it gives you all config-dialogs upfront while the actual installation will likely work unattended.
Comment: Also please run `make config-recursive` multiple times until you stop getting new options (i.e. at least twice). Any time you change an option, it may bring in another dependency that has yet more options.
Comment: Also, to shorten your workload required for configuration, it's often a reasonable idea to exclusively look at the options that are *active by default* and just consider deactivating any of those.
Comment: `export` will only work on `sh` which is not the FreeBSD default shell
Answer: I think it's worth mentioning that you might not always want to do this.  I seem to remember, for instance, needing to config emacs to add xft support.  If you want to bypass the prompts for a single build,
make install clean BATCH=yes

will work as well.
Comment: somehow works better than putting "BATCH=yes" in the front of make. Thanks.
Comment: Worth noting that `make install clean BATCH=` has the same effect, as according to the manual for `ports(7)`, it must only be defined. It can be set to anything or nothing at all
Answer: This doesn't automatically accept defaults like you're asking, but I like the "make config-recursive" method which runs you through any options for the port you want as well as options for all dependencies.  You don't have to change anything if you don't want to, but you go through all selection screens at once rather than whenever the building process arrives at them.
Once that's done, your "make install clean" should go pretty much unattended.
Comment: As I said on @Yasir's post--make sure to run this multiple times. If you change an option which brings in another dependency, if that dependency has options to configure you won't touch it until the next run of `make config-recursive`.
Comment: Personally think this should be the accepted answer.


Moderated Mediation Insignificant C'

Question: I am conducting a moderated mediation analysis using Hayes' Process Macro Model 7. I am having a significant index of moderated mediation, significant a path and b path and significant moderator X Predictor(X) interaction.  Simple slopes show moderation and I also was able interpret mediation b/c a and b path are significant at all levels of moderator. the only thing that isn't significant is the c' path (Direct path).How do I interpret that? the pearson's correlation (r) between IV (x) and DV(Y) is significant and all the studies say that X is significant predictor of Y. what does not having a c' prime mean?
Answer: Since the goal of mediation analyses is to test the mechanism through which X affects Y, a non significant direct effect (c') can be interpreted to mean that the total effect between X and Y runs primarily through the indirect effect (i.e., via your hypothesized mediator M).
Some people may call this scenario "full mediation", but I strongly recommend that you avoid using this term because of the reasons given in Zhao, Lynch, & Chen (2010). Namely, (1) you could simply fail to observe a significant c' because of low statistical power. (2) Claiming full mediations may lead to the (often incorrect) conclusion that no alternative mechanisms for the X-Y effect exists. After all, if M fully explains the effect of X on Y, then why do any more study on this effect?
So what should you do instead? I'd reckon that the top psych journals would require that you report the conditional indirect effects. That is, what are your 'ab' coefficients at various levels of the moderator? Also do report the c' coefficient since it is a useful information. Just note that the direct effect is not statistically significant and move on to interpret your main results.

Moderated Mediation Insignificant C'


How do i install an previous of flask?

Question: I want to install an older version of flask and can't figure out how to do that and I am using an Linux machine. I checked other questions about how to determine the version of flask but they only return the version of flask and even after trying different methods I cannot figure out how to do it.
Comment: https://stackoverflow.com/search?q=%5Bpip%5D+install+old+version+package
Answer: pip install flask==<VERSION>

Comment: While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation.
Answer: Looking at the pip documentation it looks like you can do that by typing:
pip install packagename == 1.4

in this case you would type pip install flask==(the version you want)

How do i install an previous of flask?


What is this old dark grey LEGO wedge piece with a grooved handle?

Question: Here is an odd piece that I have found - any idea what it is? 2x2 plate is shown for scale.
Answer: It's a LEGO brick Separator tool. Mostly used to preserve the structural integrity of the human nail, teeth, gum line etc...
Watch the classical use of it here.

Here's a recent post of some unorthodox uses of the Separator tool.
Answer: To expand on a previous answer, it is the original brick separator that was produced between 1996 and 2011 in two colors. It was replaced in 2012 by a different part with the same name and purpose but slightly different features.
Comment: It is always orange, but one of the only sets which have the part in a different color is 80013. I just noticed right now.
Comment: @mindstormsboi You might want to clarify your comment. First of all, my answer is to the question about what the part in the question's image is, which is the original brick separator which does NOT come in orange.Second, your comment both says that the new separator is always in orange and also that it comes in a second color. Both statements can not be true. :-)
Comment: Yeah, you're right, and besides that I've already found some other sets that have this piece in a different color. But it doesn't matter.


How are the meanings of words determined?

Question: I know that the meaning of words is determined by those who use them, but is there a specific number of people who have to agree on the definition of a word in order for it to appear in the dictionary?  I ask because I'm having an online debate about the difference between atheism and agnosticism with several other people and I'm trying to explain to some of them that it's important that people have the same understanding of what those terms mean before engaging in a debate.  When I pointed out to one guy that he didn't get to decide what all the words in the English language mean, I was accused of an ad hominem.
Comment: To a large extent it is set by the meaning of constituent words, including prefixes and suffixes. But that is simply moving the question, and makes you ask who affixed the meaning to those constituent words! I don't know, and am watching this question to know. One field of knowledge where this question is pertinent is Mathematics. Terminology used in Mathematics is quite interesting. Meanings of words like algorithm, arithmetic etc have changed dramatically over time and I have always wondered about this.
Answer: Usually, the meanings of the words are determined (by a lexicographer) by examining a corpus of text (usually some mixture of news, novels, and non-fictional texts).
However, in humanities and some fields of science things are different: There is often a specific meaning of a certain word assigned to it by a single author (and other others assign a different meaning to the same word), and one has to cross-check that one uses the word in the same meaning as the author one refers to uses it.
Answer: The primary source of dictionary definitions is authoritative dictionary definitions. The first cut would be between (online) lexical-redistribution systems which just take definitions from dictionaries and put them online, leaving information content unchanged. I ignore those. There are dictionaries that do some work on definitions; of these, the Oxford English Dictionary and the Merriam-Webster dictionary have a substantial research underpinning.
The general strategy is to not reinvent the wheel unnecessarily, so that definitions tend to be very similar across editions. There does not appear to be any automatic rule regarding what kind of attestation is sufficient vs. insufficient to warrant a change – furthermore, the driving goals of dictionaries are not constant (OED and Webster's both aspire to being descriptive rather than prescriptive, which leads to a volley of denunciations when an evil new word is added, such as "ain't"). The tendency is to base modifications in meaning to those motivated by "upper-echelon" sources. There is no attempt to sample usage by the masses.
Reading definitions in the OED (full version) is particularly informative, since they are quite happy to list all of the senses of a word and gives ample historical attestations, for which reason OED is my go-to authoritative dictionary. Almost no dictionary, though, gives really current definitions. The exception is Urbandictionary, but the problem there is that you get whatever (mis)understanding of a word a user feels like submitting, and I think there is a certain amount of vandalism (esp. lexicalized phrases that refer to shocking or repulsive situations).
You will not find any source that gives an exhaustive listing of all of the definitions of a word "out there", because there are too many hundreds of millions of people to survey. The approach that good dictionaries take is to focus on respectable sources, and in that sense they do not reflect contemporary usage.


Why use protocol, not call the method directly?

Question: I was asked this question in an interview. For eg: UITableviewDelegate protocol has CellForRowAtIndexpath. Why make it a delegate method in a protocol not a method in the UITableView class and call it directly?
Answer: Protocols are used to define a set of methods to interact with regardless of the type of the object implementing them. It allows you to easily interchange external resources that the view interacts with and reduces the overall coupling of your code. This is in contrast to directly calling the resource with knowledge of its type.
Answer: By not putting the -[tableView:cellForRowAtIndexPath:] in the UITableViewController class, one can write another class to use as datasource (cellForRow is in the datasource). This can be useful for code organization or code-reuse.
By putting it in a protocol, the class can have any superclass: useful when subclassing your own datasources or delegates. It also gives to ability to add in the datasource anywhere you want, even in the app delegate or a view subclass (don't do this).
Answer: Here's what Apple have to say about it:

Delegation
Delegation is a mechanism by which a host object embeds a weak reference (weak in the sense that it's a simple pointer reference, unretained) to another object—its delegate—and periodically sends messages to the delegate when it requires its input for a task. The host object is generally an "off-the-shelf" framework object (such as an NSWindow or NSXMLParser object) that is seeking to accomplish something, but can only do so in a generic fashion. The delegate, which is almost always an instance of a custom class, acts in coordination with the host object, supplying program-specific behavior at certain points in the task. Thus delegation makes it possible to modify or extend the behavior of another object without the need for subclassing.

So, in this case, you want to supply a custom-built cell, but you don't want to subclass the UITableView to do so.  Any class that conforms to the protocol can supply the custom cell.


Is Quarry Mining As Effective As Staircase Mining?

Question: I just started a survival world to test out a type of mining called quarry mining.  For those of you that don't know what quarry mining is it is when you dig a big hole straight down and use lots of vines and ladders.  My hole is in a snow biome, is 19 blocks deep, 8 blocks wide, and 8 blocks deep.  Unfortunately I have only found 18 coal, 10 iron, and I haven't found a single cave.  When I normally mine I use staircase mining which seems to help bring in much more resources and entrances to many more caves than quarry mining.  So what I want to know is if I just got really unlucky and quarry mining is better or if staircase mining is better.  Thanks for the help!
Comment: Your "quarry mining" sounds like [open-pit mining](http://en.wikipedia.org/wiki/Open-pit_mining) (as opposed to [shaft mining](http://en.wikipedia.org/wiki/Shaft_mining) where you would dig a narrow shaft or some sort of staircase downward) or am I misunderstanding?
Answer: No, it is not as efficient as you are mining much more blocks than you need to. The most effective way to mine for ores is branch mining. You dig a tunnel on levels 12 to 6 and every 2 blocks you branch off with another tunnel for about 20 to 30 blocks.
Comment: To see what level you are on hit F3 and check your y axis
Answer: Staircase mining is more effective than quarry mining. Since mining a 2 wide staircase shaft, each block you mine reveals 3 new blocks, and on discovering a mineral you branch out to clear the vein. With quarry mining in most cases you just reveal 1 unseen block, the one below you, which makes it very inefficient.
More effective even than a staircase shaft would be branch mining: you mine long tunnels of 1x2 next to each other with 2 solid blocks in between them. You can stack them on top of each other too, again with 2 solid blocks in between. This reveals the most blocks in a solid mass (all of them) with the least of digging, so the chance of finding something is greater.
There are even more effective ways of mining if you use mods. I am currently playing FTB Unleashed, a mod pack. It includes some completely automated options that require a little or more work to set up first, but which save time in the end. Some of these options are:

Automated quarry
Mining turtle
Arcane Bore
Answer: Quarry mining is only efficient in a multi-player server, when it overrules strip mining, due to everyone being able to do something at the same time, while strip mining is more effective for the single person. If you are working on an SP world, I would say go for strip mining, as it is faster. As an elaboration on my first point, when many people are working on a single strip mine, it is harder to organize, and the amount of people in one space is limited, since overlap causes unproductive. When in a large quarry, everyone can be mining at one time, and less organisation is needed, therefore giving it a higher productivity. Strip mining will always be the "faster" choice, though.
Comment: You mean branch mining when you say strip mining, right? Because a quarry and a strip mine are the same thing.
Comment: I do not agree, it is very easy to organize. Make teams of 4 and 5 floors to work on. Each player of a team gets his own direction, now you have 20 players mining perfectly organized and 20 times as effective as branch mining solo.
Comment: @MennoGouw Branch mining is most often done on level 12 to get diamonds as well as iron/coal/redstone while avoiding lava lakes, so 5 floors may be optimistic... but otherwise yeah, you're right.


Best way to travel from Bangalore to Chennai by road

Question: I am planning to drive down from Bangalore to Chennai? Which is the best route to take? How much toll do I need to pay?
Answer: There are two options for you -

Via Kolar & Chittor which is shorter by 30KMs but slower due to two lane roads and no toll.
Via Krishnagiri & Vellore, quicker but one need to pay toll.

There are 5 toll booths between Bangalore and Chennai via Krishnagiri. Toll keeps varying as the toll operators keep changing the toll every 4-6 months.
Comment: "Toll keeps varying as the toll operators keep changing the toll every 4-6 months."... What does that mean??
Comment: @Fiksdal: Hope he is about the amount to pay the toll gates, the fare may revised on every 6 months. So he doesn't know the exact amount to pay for the tolls.It is his answer for the _How much toll do I need to pay?_


How to find an inflection point (maximum slope) of a log-log plot?

Question: I have a function $f(x)$ and I have plotted it on a log-log plot. I would like to find the location of the inflection point of the function. (note: that means the inflection point in "log-log space" which is not the same as the inflection point of $f(x)$ itself.) I know the following is true: $\frac {d \log y}{d \log x} = \frac{x}{y} \frac{dy}{dx}$. What is the correct formula to find the local maximum of $\frac {d \log y}{d \log x}$?
Comment: I believe I got the correct answer by taking the derivative of $\frac{x}{y} \frac{dy}{dx}$, and finding the local maximum by setting the result equal to zero and solving for $x$. Is that the correct approach?
Answer: Suppose $y=f(x)$ for some function $f$.  When you make a log-log plot you are essentially introducing two new variables
$$u = \log x,  v = \log y$$
and plotting the function
$$v=g(u)$$
You can express $g$ in terms of $f$ as follows:
$$v = \log y = \log f(x) = \log f(e^u) $$
and therefore the function you are interested in is $g(u) = \log f(e^u)$.
Now, you are looking for the inflection point(s) of $g$.  That means you need to study the second derivative of $g$, i.e. $g''(u) = \frac{d^2v}{du^2}$.  By the chain rule
$$g'(u) = \frac{f'(e^u)e^u}{f(e^u)}$$
and then using the quotient rule and chain rule
$$g''(u) =\frac{f(e^u)\left(f''(e^u)e^{2u}+f'(e^u)e^u\right)-\left(f'(e^u)\right)^2e^{2u}}{(f(e^u)^2}$$
In terms of the original variables $x$ and $y$, this is
$$\frac{y\left(f''(x)x^{2}+f'(x)x\right)-\left(f'(x)\right)^2x^{2}}{y^2}$$
At an inflection point, the second derivative changes sign, which means that either the quantity above is zero (i.e. its numerator is zero), or the quantity is undefined (i.e. its denominator is zero).
The denominator will be zero if $y=0$, but since you are doing a log-log plot presumably you know that $y>0$ so we can discard this case.  The numerator will be zero if
$$ y\left(f''(x)x^{2}+f'(x)x\right)=\left(f'(x)\right)^2x^{2}$$
Once again since we are doing a log-log plot I assume you already know that $x>0$, so we can divide through by $x^2$ to get
$$ y\left(f''(x)+\frac{f'(x)}{x}\right)=\left(f'(x)\right)^2$$
The criterion $g''(u)=0$ is equivalent to this equation relating $f(x)$ and its derivatives $f'(x)$ and $f(x)$.  I don't see any simpler way to write this but perhaps if you know something about $f(x)$ you might be able to simplify it still further.


SQL SERVER EXPRESS 2008

Question: i my developer pc with the 2008 express on 1 site and the server somewhere else
is it possible to connect and view the server's DB?
Answer: Yes, all you need to do is install and launch the SQL Server Management Studio and use it to connect to the remote database.
Comment: can i do it with windows authentication or only with SQL?
Comment: what if i install that managment but sent my server with windows authentication - how can i change it?
Comment: If your computer and the server are on the same Windows domain then your domain account just needs to be given access to the server.  If they aren't on the same domain then you can create an account on the server with the same username and password as the account which you use on your computer.  This will allow you to use Windows Authentication.  You can change the server to use SQL Authentication by logging into the server as an admin and right clicking on the instance and selecting properties then select the security tab.

SQL SERVER EXPRESS 2008


perl sort function efficiency

Question: I'm importing roughly 40,000 strings each roughly 50 characters into an array which I then need to sort. Initially I was going to make a merge sort, but then I realized there is a built in sort function into perl. How is the efficiency on the built in sort function and what runtime might I expect from it? If you think it'd likely be more than a few minutes I'll go the merge sort way, and would appreciate any good examples you could provide.
Comment: Coincidentally, Perl's `sort` is a merge sort :)
Comment: You know, you could just try it and see. :)
Answer: It is unlikely that you're going to be able to write a sort that's faster than Perl's built-in sort that has been optimized for the past few decades.
It's impossible to say what kind of runtime you might expect, since we don't know anything about your machine, but try the built-in sort yourself and see how it runs before you worry about doing it faster.  Premature optimization is the root of all evil.
Here's a test program I put together.  It takes 0.47 seconds on my Macbook to sort 500,000 strings (10x what you're sorting).
<code>$ cat foo.pl
#!/usr/bin/perl

use warnings;
use strict;
use 5.010;

use Time::HiRes qw( gettimeofday tv_interval );

my $nrecs = 500_000;

my @strings = map { random_string() } 1 .. $nrecs;

my $t0 = [gettimeofday];
my @sorted = sort @strings;

my $elapsed = tv_interval( $t0 );

say "Took $elapsed to sort $nrecs strings";

sub random_string {
    my @chars = ( 'a'..'z', 'A'..'Z' );
    return join( '', map { $chars[rand @chars] } 1..10 );
}

$ perl foo.pl
Took 0.474914 to sort 500000 strings
</code>
Answer: The following takes less than half a second on my laptop, even with generating and printing all the strings.
<code>#! /usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

my @array = map {
    join "", map chr(32 + rand 95), 1 .. 50
} 1 .. 40_000;

my @sorted = sort @array;
say for @sorted;
</code>
So, don't worry about the performance and don't bother implementing the sort yourself.

perl sort function efficiency


Weather proofing a Pi

Question: I'm looking to deploy several copies of the Enviro hat around my garden to monitor temperature and light levels to study the optimal spots to plant new plants. How might I weatherproof the Pis without obscuring the sensors?
Comment: @Dave, the post you've linked has been closed without an answer (and specifically to allow for a repost of separate and detailed question). It is therefore not a dupe. Please mind the hint on the close reason "duplicate" -> *This question has been asked before and already has an answer.*
Comment: Possible duplicate of [All weather deployment of several Pi and sensor pairs](https://raspberrypi.stackexchange.com/questions/85484/all-weather-deployment-of-several-pi-and-sensor-pairs)
Answer: You've probably searched for a cover (as I just did), and didn't find anything that you could buy. That being the case, you must shift into "DIY Mode", and come up with your own solution. Before going any further, I should say that as you've not identified the "Enviro hat" hardware specifically, I will assume it's this device.
You might start by asking yourself this question: Does the RPi and the "Enviro hat" need protection from the weather? Based on limited anecdotal evidence: 1., and 2. I would venture a guess that exposure to rain is to be avoided! But, if you live in an arid climate, no chance of rain on days you wish to deploy, then maybe no protection is needed. This is something you'll have to decide for yourself.
Given that you will need rain protection, the Enviro pHat sensory functions will guide your design of the rain protector. The Enviro pHat provides the following sensory functions:

temperature,
pressure,
light level,
colour,
3-axis motion,
compass heading

Since you didn't specify, I will guess that temperature and light level are the only relevant functions for a garden application. If that's the case, then your rain protector must minimize its influence on those readings; i.e. it must pass light (be transparent), and it should not "trap" heat and humidity. A glass bowl might do the job (like this one from Ikea). You will place this bowl on the ground, and then drive 3 or 4 small wooden stakes in the ground such that when the glass bowl is turned upside down, it is held off the ground by the wooden stakes.
Now you have a ventilated, translucent shelter for your RPi and Enviro pHat. If you don't wish for them to lie on the ground, you could fashion a mesh sling to the bowl, and let the hardware rest in that lovely hammock.
Comment: If the bowl isn't closed, it magically turns into a slug meeting point in the great outdoors. You have to make it slug-safe first.
Comment: I guess one would still encounter significant issues with moisture (such as dew) if the bowl is not closed.
Comment: That could well be... feel free to embellish  :)  But yeah, this is going to be a trial-and-error approach to the requirement.
Answer: I make enclosures mostly using snap-tight tupperware (the kind with snaps and a rubber seal) and epoxy.  Although only one of them has been used in a permanent spot outdoors, it's a very adaptable approach and requires fairly minimal effort and expense,1 meaning it is easy to experiment -- if you aren't certain about your design, put some cardboard inside and leave it deployed for a while until you are satisfied it is going to keep what's inside dry.  I do have a few I've left outside e.g., mostly buried in snow, for a few hours or days, and I'm pretty confident I could leave them indefinitely.
The tupperware needs some modification, of course, mostly to allow for power input.  I used to use a drill, hacksaw blade, and metal files for this, until Steve Robillard (thanks Steve!) introduced me to the Dremel, aka. rotary tool.  You can buy a small handheld generic (Dremel is a brand name) rotary tool online for < $50 that may or may not be great for working some material, but it handles plastic just fine.  This increased my enclosure making productivity probably a 1000%.
Also potentially handy in this is duct tape.  A few further thoughts:

As Ghanima hints, you probably don't want the unit completely sealed. My approach here would be to use a small tub inside a larger one with the small one secured under the top of the outer one and some ventilation holes in the bottom and then in the sides of the outer enclosure.
Measuring temperature is usually done in the shade as an enclosure exposed to direct sunlight will not provide accurate readings. This does not mean total darkness, of course, and I think no matter where you put it (including in direct sunlight), you are going to have to gauge through observation what a unit's light level readings imply about actual conditions.

"Dollar stores" that sell both cheap epoxy and an extensive array of cheap tupperware are common where I live. I doubt any of the things I've made cost more than $5.
Answer: A rather simple approach is to use a clear zip-lock sandwich bag.

The zip-lock is good at sealing around any cables that may need to hang out - although its not completely watertight, but it should do the job.
Answer: The Zip bag made think, so many thanks @sa_leinad. I need the Pi to be exposed to the environment and not sealed so its sensors for temperature and light and not interfered with. I then recalled you can get spray for waterproofing walking gear etc, and surprise surprise similar is available for electronics as a conformal coating which can brushed on or sprayed on. It leaves a very thin layer 25-250 μm (micrometers) thick, and together with being transparent it should not interfere with the sensors.

Weather proofing a Pi


Where do gravitational waves draw the energy from?

Question: Imagine binary neutron stars inspiral, they generate gravitational wave which carries energy away and causing the pair to become ever closer. Since all wave must carry energy I wonder where do gravitational wave draws their energy from? I know mass is not a conserved quantity so i think it should be the gravitational potential energy converted into kinetic energy but how can vacuum spacetime gains this kinetic energy? Is this perhaps due to moving observer seeing different result compared to nearby observer?
Comment: Their momentum is carried away, that's it. Spacetime is as real thing as anything else.
Answer: In simple terms, if you think of the geometry as a field on a given spacetime, it does not simply consist of a pair of lumps at the position of each neutron star as one would intuitively expect in newtonian dynamics.
Instead, it is a smooth configuration extended to the whole spacetime. Using the ADM formalism, we can actually define a unique energy (ADM energy) corresponding to this geometry configuration.
When the two Neutron Stars get closer, although their "mass" remain constant, the ADM energy of the field is radiated away in the form of GWs. We can say that before the neutron stars collide, Gravitational waves feed directly from the "energy" of the "geometry field" itself.
Comment: I mostly like this answer, except that the first sentence of the final paragraph seems to suggest that the ADM energy changes.  This is not the case; ADM energy is a property of the entire spacetime — past, present, and future.  It is conserved.  After the GWs have been emitted, their energy is still included in the ADM energy, because they will always be present on any spacelike slice in the future.
Comment: Yes, you are right, I guess I meant some localized version of it is traveling with the waves away from the source
Answer: Another way to approach the concept is as follows:

The "missing" mass/energy was indeed radiated away as gravitational waves. But that isn't due to mass escaping from a black hole – it comes from the potential energy in the positions and spins of the two black holes.

[New Scientist, 25 Oct, 2017]


Simple (Dumb) LINQ Provider

Question: How easy would it be to write a dumb LINQ provider that can just use my class definitions (which don't have any object references as properties) and give me the translated SQL. It can assume the name of the properties and the columns to be same as well as the names of the classes and the underlying tables. Can you please give me some pointers.?
Answer: It took me about 4 months of fulltime work (8 hours a day) to build a stable, working provider that implements the entire spec of linq. I would say I had a very simple, buggy and unstable version after about three weeks, so if you're just looking for something rough I would say you're probably looking at anything from a week up to two months depending on how good you are and what types of requiements you have.
I must point you to the Wayward blog for this, Matt has written a really good walkthrough on how to implement a linq provider, and even if you're probably not going to be able to copy and paste, it will help you to get to grips with how to think when working. You can find Matt´s walkthrough here: http://blogs.msdn.com/mattwar/archive/2007/07/30/linq-building-an-iqueryable-provider-part-i.aspx . I recommend you go about it the same way Matt does, and extend the expression tree visitor Matt includes in the second part of his tutorial.
Also, when I began working with this, I had so much help from the expression tree visualizer, it really made parsing a whole lot easier once you could see how linq parsed to queries.
Building a provider is really a lot of fun, even if a bit frustrating at times. I wish you all the best of luck!
Answer: Give a look to the LINQExtender project, is a toolkit for creating custom LINQ providers.
Answer: Another option for giving you a leg up seems to be re-linq which is a framework for creating custom LINQ providers.
Here's the Source code and a nice overview (pdf) of what's involved in writing one.
Answer: I've written a tutorial series on my blog base on my experience developing a LINQ-to-SQL provider from scratch, starting with the expression tree composition stage (calling the LINQ methods), continuing with the expression visitor, breaking down of the query into components, parsing the where clause, generating the text and parameter and, eventually, compiling the whole thing into IL using the .NET expression namespace.
I've seen many incomplete posts that promised to explain how to write a provider, falling very short of the mark, barely scratching the surface and not actually delivering anything remotely executable.
The blog series I've written based on my experience has a sample project available for download with the simple provider that covers only the functionality required by the tutorial example. However, it also includes the production version supporting a number of operations (where, join, first, count, top, etc.), subqueries, nested statements, and etc. Additionally, it produces a cleaner SQL than a lot of what I've seen from Entities and LINQ-to-SQL. There's no unnecessary/redundant nesting, wrapping everything in brackets and etc.
For anyone with a good level of abstract thinking, developing such a provider isn't such a difficult task many set it out to be. I've developed one that's used in production environment in about 3 months of part time work (meaning some evenings and weekends). From the get go it was aimed with performance and tidy SQL in mind – a goal it achieved.
It was a little hard to find the time to publish this material, but I thought – if it may help someone out there, there's no reason for this experience to go to waste:

How to write a LINQ to SQL provider in C# Part 1 - Introduction
How to write a LINQ to SQL provider in C# Part 2 - Expression Visitor
How to write a LINQ to SQL provider in C# Part 3 - Where Clause Visitor
How to write a LINQ to SQL provider in C# Part 4 - Compiling Expression Trees
Answer: I have created a project 'LinqToAnything' which is designed to make it very very easy to implement a (simple) Linq provider.

Simple (Dumb) LINQ Provider


Lenovo A2010-a keyboard

Question: I updated my lenovo A2010-a system and I can't unlock it cause my password is a pass code type, and the keyboard isn't working.
I already tried restarting my phone many times.
What should i do?
Answer: Have you tried the following fixes:

Fix 1: Restart the keyboard

Restarting the keyboard can be very effective in solving the problem. Many have found this to be helpful.

Go to the Settings menu of the device
Scroll down to the Apps section and Tap on Application Manager
Swipe to go to the "All" tab
Now look for the app Android Keyboard and tap on it
Now tap on Force Stop to stop the keyboard

Exit out of the Settings menu and go back to using the keyboard and check if it works. If you happen to use a third party keyboard or if the device manufacturer has installed its own keyboard then you should look for the keyboard that is in use.

Fix 2: Clear Cache and Data for Keyboard

Clearing the cache and data of an application allows you to clear files that can be possibly corrupted or which may be creating problems because of bugs.
While deleting the cache files does not delete any important information, you will lose your personal settings when you delete the data files from any app.
If you had made specific changes to the keyboard, you will lose those settings. You will have to go back into the keyboard settings and make the changes once again.

Go to the Settings menu of your device
Tap on Application Manager which is under the apps section
Swipe to the tab which includes "All" apps
Now look for the keyboard app. It can be Android Keyboard or the keyboard that you are using if you have installed a third-party      keyboard or if you have the manufacturer skin on top of the stock       Android.
Tap on the keyboard app
Tap on Clear Cache
Now tap on Clear Data
Tap on OK to confirm.

Fix 3:  Clear Cache and Data Files for Dictionary App

The dictionary app is closely linked with the keyboard app.
If for any reason you get the "unfortunately keyboard has stopped" error, there is a chance that it may be because of corrupt files in the dictionary app.
Deleting these files can be helpful in solving the problem.

Go to the Settings menu of your device
Tap on Applications Manager
Swipe to go to the "All" tab
Scroll and look for Dictionary app and tap on it
Tap on Clear Cache
Tap on Clear Data
Tap on OK to confirm

Once the cache and data files have been deleted, check if the problem has been fixed.

Fix 4: Install Updates for Google Keyboard
You can try fixing this issue by installing updates for Google keyboard. For that, navigate to play store on your android phone and look for the updates. Alternatively download the updated Google keyboard from google play store via your PC (Apk leecher website - can directly download the apk from Google play servers)

Acknowledgements:
Fix Android keyboard stopped working
Comment: Hello sir, thank you for your suggestion. But, i cant unlock my phone cause i need the keyboard to enter my password.

What if i use trusted devices? how do i do that?
Comment: Absolutely, you can use "trusted devices" , do you have any devices (e.g smartwatch or smartphone) you had allowed to use that feature?
Comment: Yup! I added my friends phone as a trusted device.
Comment: Great! Now you need his device to be in close range.  The lock screen security on your  device gets disabled when you are connected to a trusted via Bluetooth (your friend's device).
Comment: Lemmie know if this works, if you didn't have Bluetooth enabled, if you didn't have it active and cant access it from lockscreen, I guess you could try a workaround by installing Bluetooth toggle app, via PC using a simpler tool (android app installer or adb)

Lenovo A2010-a keyboard


Does VI v4.0 on Solaris 2.5.0 have a command history

Question: I normally use VIM but have to fiddle with files in VI. Does the vi on Solaris 2.5 have history I can recall to re-use commands? It's a pain to retype complete lines sometimes. In VIM I can go ESC, ESC, Up-Arrow.
Answer: No, there is unfortunately no history support in the SVR4 release of vi.
Note it is not vi version 4 but "Version SVR4.0, Solaris 2.5.0". This version string is hardcoded and reported even in recent releases (Solaris 2.5 is something like 18 years old).
Starting from Solaris 11, vim is bundled with the OS.
Answer: It's possible to replay keystrokes in vi as a macro, if this is sufficient for your needs. This can be done in two ways.
In both cases, I'll lead with similar content for vim and then differentiate for vi.
1. Register Macros
These are captured and replayed interactively.
1.1 vim
Recall that in vim, a macro is created by recording a series of keystrokes to a register in recording mode (reached from command mode). Then the macro is executed by executing the contents of the register.
qa                # 1. Enter recording mode, will save to register "a.
  ihello<esc>     #    Type key strokes to insert string "hello".
             q    #    Return to command mode.

@a                # 2. Execute contents of register "a (insert "hello").

@@                # 3. Repeat last macro execution (insert "hello").

As the question is asked, these steps wouldn't be utilised in vim, rather you'd use the application's command histories.
1.2 vi
In vi, step 1. above is performed in a different way: the macro contents must be typed in a buffer in insert mode and then yanked/copied/etc into a register.
i                            # 1a. Enter insert mode.
 ihello<ctrl-v><esc>         #     Type key strokes to insert string "hello", escaping necessary keys.
                    <esc>    #     Return to command mode.

"aY                          # 1b. Yank entire line to register "a (macro text should appear on a line by itself).

@a                           # 2. Execute contents of register "a (insert "hello").

@@                           # 3. Repeat last macro execution (insert "hello").

2. Key Mappings
These can be captured interactively or in the appropriate *rc file.
When executing a mapping, both vim and vi wait 1 sec (default) to accept all keystrokes that constitute the mapped word.
2.1 vim
:cmap lhs rhs<enter>    # Map rhs-words to lhs-word for command-mode mappings.
:imap lhs rhs<enter>    #                           for insert-mode mappings.
:map! lhs rhs<enter>    #                           for command- and insert-mode mappings.
:map  lhs rhs<enter>    #                           for normal-mode mappings.
:nmap lhs rhs<enter>    #                           for strict normal-mode mappings.
                        # Escape necessary keys in lhs and rhs.
                        # lhs "#n" means function key "n"
                        # Use vim's extensive symbolic key names.

:vmap                   # Other variants
:xmap
:smap
:omap
:lmap

:unmap lhs              # Remove map
:nunmap                 # Other variants
:vunmap
:xunmap
:sunmap
:ounmap
:unmap!
:iunmap
:lunmap
:cunmap

2.1.1 Example
Make the q key write and exit the editor, exploiting vim's symbolic key names.
:nmap q :wq<CR><enter>     # <CR> is typed as 4 chars, <enter> as 1.

2.2 vi
:map  lhs rhs<enter>    # Map rhs-words to lhs-word for command-mode mappings.
:map! lhs rhs<enter>    #                           for insert-mode mappings.
                        # Escape necessary keys in lhs and rhs.
                        # lhs "#n" means function key "n"

:unmap lhs              # Remove map

2.2.1 Example
Make the q key write and exit the editor.
:map q :wq<ctrl-v><enter><enter>

References

The vim documentation, eg: here.
An Introduction to Display Editing with Vi, by the authors of vi, eg: this PDF.


set background image for entire iPhone / iPad app

Question: I have a single image I want as the background for my app no matter what viewcontroller they are on - how do you accomplish this?
Answer: Here's how you set a background to an image:
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Background.png"]];

Edit: To write up what Felixyz said (and thanks to Manni), do this in your delegate:
window.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Background.png"]];

And in each view you want to have the image, do this:
self.view.backgroundColor = [UIColor clearColor];

Comment: I ended up using an UIImageView on the main window nib and UIColor clearColor on my views.  Note that using the colorWithPatternImage as you state above made my memory use jump from 1.7M to 9.5M when the app is first loaded - colorWithPatternImage seems to just eat up a ton of memory.
Comment: It's recommended to prepare 3 png files for your Universal app, says Background.png, firstname.lastname@example.com, Background~iPad.png, and set the background using below code:

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Background"]];

iOS will select the correct png file due to your device category.
Hope this help.
Comment: I tried the above approach in a `UINavigation` based application .the problem with with this approach is that setting a image on the window.background set the image properly but making the other view clear color is bad as during push or pop view are overlapping you can see the views pushed in the stack .Any idea how to get it fixed
Comment: I solved the problem from Aiden by setting the background color, as suggested in this answer, to the navigation controller view background. Then, as I'm using Storyboards, I'm replacing the standard push animation (with sliding views) with a custom UIStoryboardSegue that implements a fading effect: the image remains stable and the effect lamented by Aiden is no longer visible. In my case I'm not using navigation bars too, they are all hidden (with the exception of modal views).
Comment: @viggio24 how to create "custom UIStoryboardSegue that implements a fading effect" exactly?
Comment: @Arefly There are plenty of tutorials on how to do this. One of them is: http://blog.jimjh.com/a-short-tutorial-on-custom-storyboard-segues.html where you will replace the flipping animation with an animation on opacity (alpha).
Answer: Depends on what sort of interface you have. Tabbed? Navigation based? But the general answer is: add a UIImageView to your UIWindow before/below your main view. Then make every view handled by your main view controller have a transparent background. Hard to give more specific advice without knowing if you use IB or not, or what your view hierarchy looks like.
Comment: Navigation based, so as view controllers are pushed and popped the background stays
Comment: Combining sudo's and Manni's suggestions makes it easy to accomplish what you need: set the backgroundColor on the window to be an image (colorWithPatternImage:) and make backgroundColor on the navigation controller and all its sub-controllers transparent. You might have to set opaque = NO on them too. Be aware that this might affect performance during animations, but shouldn't be a problem on newer devices.
Answer: In my app, I set a default background color. Maybe you can do this with you background image:
1.: Set the background color of your UIWindow in your AppDelegate:
window.backgroundColor = [UIColor myBackgroundGray]; // own Category

2.: And now, make all other views transparent:
self.view.backgroundColor = [UIColor clearColor]; // = transparent

Comment: This causes a poor ux when presenting modal presenters with animation. You can see the controls from the modal view and the existing view and then the existing view disappears.
Answer: In your AppDelegate in
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

Add this line :
[self.window setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];

After you just have to set your views backgrounds to [UIColor clearColor];
Answer: Your background is a property of any View-inheriting object. Labels, Buttons, Controllers, and the app window, for example, all have backgrounds.  If you want it to be completely a bg for the entire app you must climb the path in your controllers to find the very "top" (bottom-viewed) view, and set its background to be the image you desire.
Answer: I am not sure of the performance implications, but I needed to accomplish something similar, and ended up using a UIImageView which works well (in C#, but works the same in obj-c):
//Add the view controller first, to ensure proper order of views later.
Window.RootViewController = new UIViewController();

//create backdrop image view
var imageView = new UIImageView(Window.Bounds);
imageView.Image = UIImage.FromBundle("backdrop.jpg");

//insert into window.
Window.InsertSubview(imageView, 0);

This doesn't handle orientation changes, but in my case, allowed me to add motion effects to the backdrop (such as parallax).
Answer: just call this assignbackground in viewDidLoad
override func viewDidLoad() {
assignbackground()
}

func assignbackground(){
        let background = UIImage(named: "background")

        var imageview : UIImageView!
        imageview = UIImageView(frame: view.bounds)
        imageview.contentMode =  UIViewContentMode.ScaleAspectFill
        imageview.clipsToBounds = true
        imageview.image = background
        imageview.center = view.center
        view.addSubview(imageview)
        self.view.sendSubviewToBack(imageview)
    }

Answer: I usually use this function to avoid overlaps with navigation bar on iphone.
-(void)setImageBackground:(NSString*)imageName{
    UINavigationController* navigationController = [self navigationController];
    float height = navigationController.toolbar.frame.size.height;
    CGSize size = self.view.frame.size;
    size.height = size.height;
    UIGraphicsBeginImageContext(size);
    CGRect bounds = self.view.bounds;
    bounds.origin.y = bounds.origin.y + height;
    bounds.size.height = bounds.size.height-height;
    [[UIImage imageNamed:imageName] drawInRect:bounds];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    self.view.backgroundColor = [UIColor colorWithPatternImage:image];
}


Are there Christian answers for Jewish / Judaism questions?

Question: For example, I asked a question about what marriage meant in the time of Jesus / Moses / in the bible.  Jesus was Jewish and the Old Testament is probably where the answer would be found.  However are Christian's biblical interpretations of Jewish customs ontopic or should the question be asked else where (for this reason)?  Obviously I'm not asking this question for its "ontopicness", but future questions as well.
Comment: I think in general, yes, but your example question seems to have other issues spelled out in the related meta for it, so it might not be a good example.
Comment: Yes, I'm speaking of one of the many issues
Answer: If the question is about historical Jewish customs then the choices are good this is not the best site to ask even if there is overlap in accepted history.
If the question is clearly about a specific Christian perspective on a practice then it really doesn't matter if the practice is Jewish, early Christian or Hindu, this is the obvious place to get Christianity's commentary if anything official exists.
The problem (one of several actually) with your example question is that it was more of the former that the later pattern.


How does Google's 'showing results for' work?

Question: If I search 'I love to eate my food' on Google then Google will 'show results for' I love to eat my food.... How does this algorithm work?
Answer: First of all, no one knows how google search works except what google officially publishes. But I give you a simple algorithm for query correction (I have implemented this previously in production).
It is a simple prediction based on spell-check. First you detect the (possible) typo. Then you find the query which maximizes the likelihood. This search is done in the huge database of user queries plus some language models.


Oauth2.0 User Password flow combined with delegated authentication

Question: When using the OAuth2.0 User Password flow and having Delegated Authentication Single Sign-on enabled, will Salesforce by default use the Delegated Authentication to validate the user/password?
Answer: Yes. Salesforce.com does not store check the password for users with Delegated Authentication. The mode of authentication does not matter (e.g. OAuth2 versus API versus Apps). Any attempt to log in must be done through the delegated authentication web service. The first two list items describe what you're looking for:

When a user tries to log in—either online or using the API—Salesforce validates the username and checks the user's permissions and access settings.
If the user has the "Is Single Sign-On Enabled" user permission, then Salesforce does not validate the username and password. Instead, a Web services call is made to the user's organization, asking it to validate the username and password.
--(Emphasis added)


XmlDocument type not found even though I've referenced System.XML?

Question: I've referenced System.Xml:
using System.Xml;

Then in this line:
XmlDocument xdoc = new XmlDocument();

I get:

The type or namespace name
  'XmlDocument' could not be found

What could there possibly be wrong ?
Info:
.NET 3.5, C#, triple checked that it's referenced and used in the same document, been able to use similar and even child libraries (System.Linq;System.Xml.Linq;System.Xml.XPath; System.Xml;)
Comment: Have you tried creating a new project from scratch?  I can't seem to get this to happen and wonder if there's some version mismatch or project corruption going on.
Answer: Make sure your project references the System.Xml.dll assembly.  It's possible that you're referencing a different assembly that contains other System.Xml.* classes and that might be why you're seeing the System.Xml namespace but without the classes you need.
If you already have this reference, try removing and re-adding it and see if that irons out some weird VS glitch.
Answer: Are you perhaps working inside a SilverLight project?
Only time I have experienced this was when starting out in SilverLight, I did not realise that not all of the System.XML was in the Silverlight CLR version. I used System.Linq.XML instead.
Comment: Nope it isnt. Surprisingly enough it's a winforms c# .net 3.5 project =(
Answer: I know that the question is already answered, but I want to add the solution for the very similar problem that I had, which might help others:
In my case it was a simple misspelling, well, not even that, it was an uppercase-lowercase-fault:
There are 2 classes: XMLDocument (from msxml.h) and XmlDocument (from System.Xml).
  Make sure that you're not mixing them up! ;-)
Answer: I know this is a very old question but the problem persists nowadays.
I'm on a Xamarin.Forms project and the PCL project targets a profile (Profile111) that doesn't support XmlDocument. I had to use System.Xml.Linq.XDocument.
My projects targets WindowsPhone and XmlDocument doesn't exist on this target.
Answer: If you're using Visual Studio Code, you need to include the .NET Standard package from NuGet. You can also just include the System.Xml.XmlDocument package directly if that's all you need.


Is it possible to retrieve data inside an XAML file?

Question: In an application I need to use some custom object where each have their own properties and these properties coming from a database so in

I must assign values to the properties. Any help will be appreciated.
Thanks,
Amit
Answer: You can use TryFindResource(object key).  For example, if your style is under your window's resources and you want to set the second setter to true, you can put this in the code-behind:
((TryFindResource("key1") as Style).Setters[1] as Setter).Value = true;

You could also use binding.  Just set the value to Value="{Binding Path=path}" and make your path a dependency property.  This also works with multibinding and conversion.
Comment: note that `TryFindResource` returns `null` if the object is not found, thus there is a potential `NullReferenceException` here.
Comment: Yeah, I realize that.  Though I'm using it right now in what I'm working on, and I've never had that problem.
Comment: I'm assuming TryFindResource() has nothing to do with database so binding might be solution to my case. right?
Comment: Probably.  Sorry, I don't know much about databases yet.
Comment: no I appreciate your response now I have learned something about it which I had no idea  before. I am going to look at Mares' link seems close to what I'm looking for. Thanks to you all
Answer: Perhaps MVVM will help you out. Then you have a ViewModel, which exposes your properties to the view. The Model is what the database will deliver. The ViewModel is an adapter between model and view.
Jason Dollinger explains it very good in his video which is available here
Comment: Hello Mare, I'm in the middle of a wpf project and not familiar with MVVM so is that something that I can do in my project or I had to design it base on MVVM in the first place?
Comment: i believe you can start using MVVM at any point. especially to solve that kind of problem. but you will end up using MVVM anywhere then, as it is plain, simple and a good solution for most of these settings.


Why doesn't our body gets crushed due to the atmospheric pressure?

Question: The atmospheric pressure is 101325 Pa,which is good enough to get our bones crushed.But why aren't we crushed due to it?
Comment: Once I saw a cartoon where the main character thought that taking the air out of a sphere would make it float. The sphere collapsed.
Comment: Because the atmosphere also pressurize the body. Diving down 100 meters will pressurize the gasses in the body and they will compress, like the air in our lungs and if the lung volume get below half a litre the lungs can get partly filled with blood plasma. But sorry no bone crushing. But if you take a big breath and hold it while you ascend from 100 meters to the surface, your ribs may start to break
Comment: Bird bones are air filled to save weight, and might break if they are pressurized far beyond 1 atmosphere.
Comment: Vacuum spheres are used on many underwater vessels for constant buoyancy. @PML
Comment: @EnosOye It was a cartoon plus the sphere was made of a very weak material. =p
Answer: The reason is quite simple: the contents of our bodies (blood, bones, muscle, etc) are at the same pressure as the atmosphere.
Even if they were not, atmospheric pressure is certainly not enough to get our bones crushed. When a diver is 10m under water, the pressure is doubled (202650 Pa). Any recreational diver can do that. I have been deeper than that, without any ill effects. At 100m, the pressure is 10 times atmospheric pressure, and only specially trained divers, with special equipment (including breathing gas that has nitrogen reduced and replaced by some other gas like helium) can go there. The deepest verified dive is 318m - about 32x atmospheric pressure.
Fish and other marine creatures have their internal body pressure the same as the water around them. As a result, even in the deepest oceanic trenches there is life.
The reverse is more dangerous. If our body was exposed to vacuum, the internal pressure would quickly kill us, as explained in this question.
Answer: There are five good answers in this link:
Answer 5:

It's true that the weight of the column of air above us is very heavy. We can call this weight an external pressure, because it is pushing down on us. However, the reason we, nor other objects, are crushed by the weight of this air is because this external pressure is balanced by our internal pressure, which arises from various fluids and materials we are composed of. This internal pressure exists because we are largely made up of incompressible solids and liquids. To simplify matters, just think about a balloon filled with water. The external pressure is trying to compress the balloon, while the water inside the balloon is able to balance this external pressure due to the relative incompressibility of water. This incompressibility is responsible for the internal pressure opposing the external pressure.


How to remove only file mode from git index

Question: I ititialized git repository and later realized that git indexes file mode such as 777 or 644, and when file mode changes git shows that mode changing and "wants" file to be commited just because its mode was changed.
How can I remove the file mode "records" of git index (history) of such file while save it "real" changing history - history of changing its contents?
Answer: You can achieve this partially by setting core.fileMode to false:
git config core.fileMode false

This will cause the executable bit (and only that one) to be ignored.
Quoting the git-config documentation:

Tells Git if the executable bit of files in the working tree is to be honored.
Some filesystems lose the executable bit when a file that is marked as executable is checked out, or checks out a non-executable file with executable bit on. git-clone(1) or git-init(1) probe the filesystem to see if it handles the executable bit correctly and this variable is automatically set as necessary.
A repository, however, may be on a filesystem that handles the filemode correctly, and this variable is set to true when created, but later may be made accessible from another environment that loses the filemode (e.g. exporting ext4 via CIFS mount, visiting a Cygwin created repository with Git for Windows or Eclipse). In such a case it may be necessary to set this variable to false. See git-update-index(1).
The default is true (when core.filemode is not specified in the config file).

Whether that's a good idea is another debate...


chord progressions in minor with the 6th degree rasied

Question: The obvious one is using ii as a minor triad and IV as a major triad but are there some progressions where the raised ^6 is in the bass? I guess the ii and IV would be in inversions then but I can't make them seem to sound as good as when I use them in root position. What other common chord progressions are there in minor with the ^6 as a raised note.
Comment: This one has a nice progression in the final bars before each new verse https://www.youtube.com/watch?v=syercy760YQ    There's a sharp 6 chord that's not an inversion of something else. You can look at the progression as V of V of V -> V of V -> V.
Comment: @armani what specific of progressions did you try that didn't sound good to you, and what you disliked about them?
Comment: I think I figured it out thanks to Michaels post. He said that usually when the bass goes from ^6 to ^5 the lowered form should be used so I think this is where I was getting a sound I didn't like. i - VII - IV6 sounds fine but then the move to V sounds not so good but if I turn the major IV6 into a minor iv6 before moving to V then it sounds good. This is easy since it is the bass note that determines whether the IV is major or minor so you can just descend from raised ^6 to b^6 and then to ^5 in the bass.
Comment: similarly i going straight to IV6 also sounds good but I think the point is that you usually would use the IV6 as a major IV chord in 1st inversion only if you were going to go up to the leading tone after thereby using the melodic minor scale in its ascending form. If walking down the scale the natural minor scale sounds best.
Answer: Sort of related question I posted a while back with some examples...
Should the dominant seventh sonority on the subdominant degree in minor get special attention?
I think that you want to look at the ^6 and ^7 degrees, in bass, in minor, from a linear perspective.
Also, while the ^6 degree is part of subdominant harmony (although it can be part of dominant harmony with viio7), you should also pay attention to the handling of the ^7 degree in relation to ^6 and whether ^7 is raised to a leading tone for a dominant chord.
Direction of the bass part is a big factor. If ^6 descends to ^5, then ^6 is usually the lowered form.
When ^7 is raised for a leading tone in dominant harmony the ^6 often is raised for an ascending or auxiliary move to ^7.
Sometimes ^6 is lowered and ^7 raised for dominant harmony, forming an augmented second, and you could say the harmonic minor scale is being used. But you can also look at it as chord tones ^2 ^4 ^5 ♯^7 with ^1 ^3 ♭^6 as various passing tones.
A concise way to see the bass in step-wise motions with common practice harmonization is the minor form of the rule of the octave.

I guess the ii and IV would be in inversions then but I can't make them seem to sound as good as when I use them in root position.

Yes, like in the example rule of the octave the raised ^6 is in the bass, forming inverted chords, and giving IV6 V6/5 i in mm. 6-8.
If you used root position chords for IV V I, minor or major, the basic voice leading for IV V would be to move the upper voices in contrary motion to the bass, so those upper voices will descend, in which case the ^6 will go down to ^5 where the normal treatment is to make ^6 the lowered form for the descent to ^5, like in the last three measures of the example rule of the octave.


How would I run my python code every day without having my computer open?

Question: I am trying to run my web-scraping python code every day at a specific time without having to open my computer. I looked into AWS Lambda but when I tried to set up the layers to include selenium, pandas and chromedriver, the file size limit was exceeded. Is there an alternative approach that I could deploy my python app to run every day without high costs?
Comment: The question is how much CPU does your python need.  Any linux has cron or some version of it that allows you to schedule things.  To edit  **crontab -e** .  Depending on the resource required a Raspberry Pi4 or Pi 5 could be left on 24/7 on a shelf or etc with very low power requirements.  Does this help?
Answer: Let's stick to AWS since you will need a switched-on computer, even if not your own. So, you have a Python (the Pandas gave it away), Selenium and Chromium driver stack:
Set up a small EC2 instance, whichever size suits you. But t2.micro is free if you are on the Free Tier, and t4g.small is on free trial until 31 Dec 2023.
Then either configure a cron job on the instance to start the scraping session or, if you  are feeling adventurous, set up an AWS Lambda job to create the EC2 instance and destroy it again after the session. You may also want to consider the AWS Resource Scheduler service.

With Resource Scheduler, you can choose to automatically stop and
start instances across multiple AWS Regions and AWS accounts according
to a schedule you define. The Quick Setup configuration targets Amazon
EC2 instances using the tag key and value that you specify.


Homology and cohomology of compact vs non compact spaces

Question: What is special about the homology of the compact spaces, what are the most elementary properties that are verified by homology of compact spaces that are not true for the homology of non compact spaces ? I'm asking because i read that Euler characteristic is not easily defined for non compact spaces while it is straightforward for compact spaces and i also read that we have a homology theory that is better suited for noncompact spaces rather than singular homology, what is making this difference between compact and noncompact spaces regarding homology and cohomology ? Thank you for your help !
Comment: When your spaces are compact, you have that various (co)homology groups are finite dimensional (necessary for the usual definitions of Euler characteristic), and also that you can integrate cochains over chains to make a pairing between homology and cohomology.  Depending on what context you are working in (simplicial sets/complexes, CW-complexes, manifolds, topological spaces, etc.), you may be able to talk about (co)homology with compact support, or Borel-Moore (co)homology or some other theory that makes things work better.
Comment: I thought the homology groups are finite dimensional when $X$ is compact **manifold** but when $X$ is a compact space i'm not able to find the result in Hatcher or other references, could you please give me a reference to read on this fact, thanks in advance
Comment: It depends what you mean by space. Take a product of a cantor set and a circle. This space will have infinite rank $H_0$ and $H_1$ and it is clearly compact. Obviously, it is not homotopy equivalent to a CW complex however, so you may want to restrict to this class. (or if you don't like a Cantor set, take the one-point compactification of $\mathbb{N}$ as your first factor for the product).
Comment: My statement might not have been correct in full generality.  I do not have a reference, and so if I misspoke, I apologize.  It has been a long time since I have thought about general topological space.
Answer: There are essentially no special properties of (singular) homology and cohomology of compact spaces, in general.  A concrete result along these lines is that every topological space which is not too large (where "too large" is so large you cannot even prove such a large set exists in ZFC) is weak homotopy equivalent to a compact Hausdorff space.  Since a weak homotopy equivalence induces isomorphisms on singular (co)homology, this means anything you that can happen with them in general spaces can also happen in compact Hausdorff spaces (as long as your spaces aren't ridiculously huge).  To be precise, "not too large" means "smaller than the least measurable cardinal".  This is a theorem of Adam Przeździecki; see this MO post and the comments under it.
When you restrict to sufficiently nice spaces, though, (co)homology of compact spaces tends to be better behaved since it is guaranteed to be finitely generated.  For instance, if your space is a CW-complex, then it is compact iff it has only finitely many cells, and if it has only finitely many cells its (co)homology will be finitely generated since the cellular (co)chain complex is finitely generated.  This finiteness is required, for instance, in order for the usual definition of Euler characteristic to make sense.
Another difference is that sometimes you are interested not in ordinary cohomology but in cohomology with compact support (or other related variations), which arises naturally in studying things like Poincaré duality (in the context of de Rham cohomology, for instance, it arises naturally because you can integrate a form over a compact set but over a non-compact set the integral may diverge).  For compact spaces, cohomology with compact support is the same thing as ordinary cohomology, so you don't need to make a distinction between them.


How to access web service on port other than 80 in vs2008/2010

Question: I tried searching the net, also tried some workarounds I found (like manually executing wsdl.exe) but still I can't access a remote web service running on a port different than 80 (say 1234).
When from Visual Studio 2008 OR 2010 I add a web reference using a url like http://192.168.1.2:1234/WebServices/Test.asmx, the service is found but when I press Continue, VS is unable to create the proxy classes and gives me an error saying that http://192.168.1.2/WebServices/Test.asmx (notice the missing port) was unable to return anything. Is there something I can do apart from creating the web service localy, creating the proxy classes and then manually changing the url?
Thanks in advance!
Answer: You're supposed to set the Url property on the web service proxy class.


What is the precise meaning of the word "avicha"?

Question: I search the meaning of the word "Avicha" (not sure how it is written in hebrew. I have seen it used in the terms "Mussar Avicha", "Birchos Avicha", "elohai avicha" etc. but I can never find the translation of just the word itself "Avicha".
Answer: Your (masculine singular) father
Answer: In some contexts, it could mean "your family" or even "your heritage."


Understanding PAM - why is it greedy?

Question: I've been studying k-medoids for a while but i can't understand the first step or BUILD step: in particular i can't get how the initial medoids would be "greedy". I'm not much confident with the theory behind this notion but i can guess what does it mean. I understand from other answers in here that first medoid is chosen as the medoid of the whole dataset and this is "greedy", but how about the other $k-1$? I really can't consider random choice of the other medoids as "greedy".
So my question is about how the initial $k$ medoids are picked, except the random choice k-means like. And then, is it right to consider PAM an approximation of k-medoids problem that performs a greedy search (that provides an approximate solution, of course)?
Answer: Greedy is not random. Greedy means no backtracking:
https://en.wikipedia.org/wiki/Greedy_algorithm

Greedy choice property
We can make whatever choice seems best at the moment and then solve the subproblems that arise later. The choice made by a greedy algorithm may depend on choices made so far, but not on future choices or all the solutions to the subproblem. It iteratively makes one greedy choice after another, reducing each given problem into a smaller one. In other words, a greedy algorithm never reconsiders its choices.

BUILD seems to make the "current best" decision, but never reconsiders this choice until the second SWAP algorithm later.
You may want to read up on this in p-medians literature which is less applied and more optimization theory oriented.

Understanding PAM - why is it greedy?