Programs & Examples On #System design

Enum String Name from Value

you can just cast it

int dbValue = 2;
EnumDisplayStatus enumValue = (EnumDisplayStatus)dbValue;
string stringName = enumValue.ToString(); //Visible

ah.. kent beat me to it :)

Getting Google+ profile picture url with user_id

trying to access the /s2/profile/photo url works for most users but not all.

The only full proof method is to use the Google+ API. You don't need user authentication to request public profile data so it's a rather simple method:

  1. Get a Google+ API key on https://cloud.google.com/console

  2. Make a simple GET request to: https://www.googleapis.com/plus/v1/people/+< username >?key=

Note the + before the username. If you use user ids instead (the long string of digits), you don't need the +

  1. you will get a very comprehensive JSON representation of the profile data which includes: "image":{"url": "https://lh4.googleusercontent.com/..... the rest of the picture url...."}

How do I undo a checkout in git?

You probably want git checkout master, or git checkout [branchname].

Compiling LaTex bib source

I am using texmaker as the editor. you have to compile it in terminal as following:

  1. pdflatex filename (with or without extensions)
  2. bibtex filename (without extensions)
  3. pdflatex filename (with or without extensions)
  4. pdflatex filename (with or without extensions)

but sometimes, when you use \citep{}, the names of the references don't show up. In this case, I had to open the references.bib file , so that texmaker could capture the references from the references.bib file. After every edition of the bib file, I had to close and reopen it!! So that texmaker could capture the content of new .bbl file each time. But remember, you have to also run your code in texmaker too.

C++ multiline string literal

A probably convenient way to enter multi-line strings is by using macro's. This only works if quotes and parentheses are balanced and it does not contain 'top level' comma's:

#define MULTI_LINE_STRING(a) #a
const char *text = MULTI_LINE_STRING(
  Using this trick(,) you don't need to use quotes.
  Though newlines and     multiple     white   spaces
  will be replaced by a single whitespace.
);
printf("[[%s]]\n",text);

Compiled with gcc 4.6 or g++ 4.6, this produces: [[Using this trick(,) you don't need to use quotes. Though newlines and multiple white spaces will be replaced by a single whitespace.]]

Note that the , cannot be in the string, unless it is contained within parenthesis or quotes. Single quotes is possible, but creates compiler warnings.

Edit: As mentioned in the comments, #define MULTI_LINE_STRING(...) #__VA_ARGS__ allows the use of ,.

Manifest Merger failed with multiple errors in Android Studio

Put this at the end of your app module build.gradle:

configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
    def requested = details.requested
    if (requested.group == 'com.android.support') {
        if (!requested.name.startsWith("multidex")) {
            details.useVersion '25.3.0'
        }
    }
}}

from this

How to use if statements in underscore.js templates?

To check for null values you could use _.isNull from official documentation

isNull_.isNull(object)

Returns true if the value of object is null.

_.isNull(null);
=> true
_.isNull(undefined);
=> false

Android Error - Open Failed ENOENT

Put the text file in the assets directory. If there isnt an assets dir create one in the root of the project. Then you can use Context.getAssets().open("BlockForTest.txt"); to open a stream to this file.

How do I create ColorStateList programmatically?

Unfortunately none of the solutions works for me.

  1. If you don't set pressed state at first it won't detect it.
  2. If you set it, then you need to define empty state to add default color
ColorStateList themeColorStateList = new ColorStateList(
        new int[][]{
                new int[]{android.R.attr.state_pressed},
                new int[]{android.R.attr.state_enabled},
                new int[]{android.R.attr.state_focused, android.R.attr.state_pressed},
                new int[]{-android.R.attr.state_enabled},
                new int[]{} // this should be empty to make default color as we want
        },
        new int[]{
                pressedFontColor,
                defaultFontColor,
                pressedFontColor,
                disabledFontColor,
                defaultFontColor
        }
);

This is constructor from source code:

/**
 * Creates a ColorStateList that returns the specified mapping from
 * states to colors.
 */
public ColorStateList(int[][] states, int[] colors) {
    mStateSpecs = states;
    mColors = colors;

    if (states.length > 0) {
        mDefaultColor = colors[0];

        for (int i = 0; i < states.length; i++) {
            if (states[i].length == 0) {
                mDefaultColor = colors[i];
            }
        }
    }
}

How do you check if a selector matches something in jQuery?

firstly create a function:

$.fn.is_exists = function(){ return document.getElementById(selector) }

then

if($(selector).is_exists()){ ... }

Authenticating in PHP using LDAP through Active Directory

PHP has libraries: http://ca.php.net/ldap

PEAR also has a number of packages: http://pear.php.net/search.php?q=ldap&in=packages&x=0&y=0

I haven't used either, but I was going to at one point and they seemed like they should work.

Converting integer to binary in python

numpy.binary_repr(num, width=None) has a magic width argument

Relevant examples from the documentation linked above:

>>> np.binary_repr(3, width=4)
'0011'

The two’s complement is returned when the input number is negative and width is specified:

>>> np.binary_repr(-3, width=5)
'11101'

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

This problem may also happen if your project set up to have the same intermediate directories in Project Properties -> Configuration Properties -> General

How to change angular port from 4200 to any other

Run below command for other than 4200

ng serve --port 4500

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

Even though the <head> and <body> tags aren't required, the elements are still there - it's just that the browser can work out where the tags would have been from the rest of the document.

The other elements you're using still have to be inside the <body>

Min / Max Validator in Angular 2 Final

Angular now supports min/max validators by default.

Angular provides the following validators by default. Adding the list here so that new comers can easily get to know what are the current supported default validators and google it further as per their interest.

  • min
  • max
  • required
  • requiredTrue
  • email
  • minLength
  • maxLength
  • pattern
  • nullValidator
  • compose
  • composeAsync

you will get the complete list Angular validators

How to use min/max validator: From the documentation of Angular -

static min(min: number): ValidatorFn 
static max(max: number): ValidatorFn 

min()/max() is a static function that accepts a number parameter and returns A validator function that returns an error map with the min/max property if the validation check fails, otherwise null.

use min validator in formControl, (for further info, click here)

const control = new FormControl(9, Validators.min(10));

use max validator in formControl, (for further info, click here)

const control = new FormControl(11, Validators.max(10));

sometimes we need to add validator dynamically. setValidators() is the saviour. you can use it like the following -

const control = new FormControl(10);
control.setValidators([Validators.min(9), Validators.max(11)]);

How can I get my webapp's base URL in ASP.NET MVC?

I put this in the head of my _Layout.cshtml

 <base href="~/" />

Switch in Laravel 5 - Blade

To overcome the space in 'switch ()', you can use code :

Blade::extend(function($value, $compiler){
    $value = preg_replace('/(\s*)@switch[ ]*\((.*)\)(?=\s)/', '$1<?php switch($2):', $value);
    $value = preg_replace('/(\s*)@endswitch(?=\s)/', '$1endswitch; ?>', $value);
    $value = preg_replace('/(\s*)@case[ ]*\((.*)\)(?=\s)/', '$1case $2: ?>', $value);
    $value = preg_replace('/(?<=\s)@default(?=\s)/', 'default: ?>', $value);
    $value = preg_replace('/(?<=\s)@breakswitch(?=\s)/', '<?php break;', $value);
    return $value;
  });

How to increase an array's length

Item[] newItemList = new  Item[itemList.length+1];
    //for loop to go thorough the list one by one
    for(int i=0; i< itemList.length;i++){
        //value is stored here in the new list from the old one
        newItemList[i]=itemList[i];
    }
    //all the values of the itemLists are stored in a bigger array named newItemList
    itemList=newItemList;

convert iso date to milliseconds in javascript

Try this

_x000D_
_x000D_
var date = new Date("11/21/1987 16:00:00"); // some mock date_x000D_
var milliseconds = date.getTime(); _x000D_
// This will return you the number of milliseconds_x000D_
// elapsed from January 1, 1970 _x000D_
// if your date is less than that date, the value will be negative_x000D_
_x000D_
console.log(milliseconds);
_x000D_
_x000D_
_x000D_

EDIT

You've provided an ISO date. It is also accepted by the constructor of the Date object

_x000D_
_x000D_
var myDate = new Date("2012-02-10T13:19:11+0000");_x000D_
var result = myDate.getTime();_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Edit

The best I've found is to get rid of the offset manually.

_x000D_
_x000D_
var myDate = new Date("2012-02-10T13:19:11+0000");_x000D_
var offset = myDate.getTimezoneOffset() * 60 * 1000;_x000D_
_x000D_
var withOffset = myDate.getTime();_x000D_
var withoutOffset = withOffset - offset;_x000D_
console.log(withOffset);_x000D_
console.log(withoutOffset);
_x000D_
_x000D_
_x000D_

Seems working. As far as problems with converting ISO string into the Date object you may refer to the links provided.

EDIT

Fixed the bug with incorrect conversion to milliseconds according to Prasad19sara's comment.

Web Service vs WCF Service

Basic and primary difference is, ASP.NET web service is designed to exchange SOAP messages over HTTP only while WCF Service can exchange message using any format (SOAP is default) over any transport protocol i.e. HTTP, TCP, MSMQ or NamedPipes etc.

How to display both icon and title of action inside ActionBar?

Follow these steps:

  1. Add the Action Bar instance in the Java Code final ActionBar actionBar = getActionBar();
  2. Enable the Home Display Option actionBar.setDisplayShowHomeEnabled(false);
  3. Add the following code in the respective activity's manifest file android:logo=@drawable/logo and android:label="@string/actionbar_text"

I think this will help you

Dump all tables in CSV format using 'mysqldump'

This worked well for me:

mysqldump <DBNAME> --fields-terminated-by ',' \
--fields-enclosed-by '"' --fields-escaped-by '\' \
--no-create-info --tab /var/lib/mysql-files/

Or if you want to only dump a specific table:

mysqldump <DBNAME> <TABLENAME> --fields-terminated-by ',' \
--fields-enclosed-by '"' --fields-escaped-by '\' \
--no-create-info --tab /var/lib/mysql-files/

I'm dumping to /var/lib/mysql-files/ to avoid this error:

mysqldump: Got error: 1290: The MySQL server is running with the --secure-file-priv option so it cannot execute this statement when executing 'SELECT INTO OUTFILE'

What is the argument for printf that formats a long?

I think you mean:

unsigned long n;
printf("%lu", n);   // unsigned long

or

long n;
printf("%ld", n);   // signed long

Use of Application.DoEvents()

Yes, there is a static DoEvents method in the Application class in the System.Windows.Forms namespace. System.Windows.Forms.Application.DoEvents() can be used to process the messages waiting in the queue on the UI thread when performing a long-running task in the UI thread. This has the benefit of making the UI seem more responsive and not "locked up" while a long task is running. However, this is almost always NOT the best way to do things. According to Microsoft calling DoEvents "...causes the current thread to be suspended while all waiting window messages are processed." If an event is triggered there is a potential for unexpected and intermittent bugs that are difficult to track down. If you have an extensive task it is far better to do it in a separate thread. Running long tasks in a separate thread allows them to be processed without interfering with the UI continuing to run smoothly. Look here for more details.

Here is an example of how to use DoEvents; note that Microsoft also provides a caution against using it.

Invariant Violation: Objects are not valid as a React child

For those who mentioned Stringify() and toString() as solution, I will say that worked for me but we have to understand the problem and why did it occur. In my code it was simple issue. I had 2 buttons which call same function but one button was not passing the argument to that function properly.

Using Jquery AJAX function with datatype HTML

var datos = $("#id_formulario").serialize();
$.ajax({         
    url: "url.php",      
    type: "POST",                   
    dataType: "html",                 
    data: datos,                 
    success: function (prueba) { 
        alert("funciona!");
    }//FIN SUCCES

});//FIN  AJAX

'typeid' versus 'typeof' in C++

You can use Boost demangle to accomplish a nice looking name:

#include <boost/units/detail/utility.hpp>

and something like

To_main_msg_evt ev("Failed to initialize cards in " + boost::units::detail::demangle(typeid(*_IO_card.get()).name()) + ".\n", true, this);

Press any key to continue

I've created a little Powershell function to emulate MSDOS pause. This handles whether running Powershell ISE or non ISE. (ReadKey does not work in powershell ISE). When running Powershell ISE, this function opens a Windows MessageBox. This can sometimes be confusing, because the MessageBox does not always come to the forefront. Anyway, here it goes:

Usage: pause "Press any key to continue"

Function definition:

Function pause ($message)
{
    # Check if running Powershell ISE
    if ($psISE)
    {
        Add-Type -AssemblyName System.Windows.Forms
        [System.Windows.Forms.MessageBox]::Show("$message")
    }
    else
    {
        Write-Host "$message" -ForegroundColor Yellow
        $x = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    }
}

Full path from file input using jQuery

You can't: It's a security feature in all modern browsers.

For IE8, it's off by default, but can be reactivated using a security setting:

When a file is selected by using the input type=file object, the value of the value property depends on the value of the "Include local directory path when uploading files to a server" security setting for the security zone used to display the Web page containing the input object.

The fully qualified filename of the selected file is returned only when this setting is enabled. When the setting is disabled, Internet Explorer 8 replaces the local drive and directory path with the string C:\fakepath\ in order to prevent inappropriate information disclosure.

In all other current mainstream browsers I know of, it is also turned off. The file name is the best you can get.

More detailed info and good links in this question. It refers to getting the value server-side, but the issue is the same in JavaScript before the form's submission.

Set up git to pull and push all branches

To see all the branches with out using git branch -a you should execute:

for remote in `git branch -r`; do git branch --track $remote; done
git fetch --all
git pull --all

Now you can see all the branches:

git branch

To push all the branches try:

git push --all

Case Insensitive String comp in C

Additional pitfalls to watch out for when doing case insensitive compares:


Comparing as lower or as upper case? (common enough issue)

Both below will return 0 with strcicmpL("A", "a") and strcicmpU("A", "a").
Yet strcicmpL("A", "_") and strcicmpU("A", "_") can return different signed results as '_' is often between the upper and lower case letters.

This affects the sort order when used with qsort(..., ..., ..., strcicmp). Non-standard library C functions like the commonly available stricmp() or strcasecmp() tend to be well defined and favor comparing via lowercase. Yet variations exist.

int strcicmpL(char const *a, char const *b) {
  while (*b) {
    int d = tolower(*a) - tolower(*b);
    if (d) {
        return d;
    } 
    a++;
    b++;
  } 
  return tolower(*a);
}

int strcicmpU(char const *a, char const *b) {
  while (*b) {
    int d = toupper(*a) - toupper(*b);
    if (d) {
        return d;
    } 
    a++;
    b++;
  } 
  return toupper(*a);
}

char can have a negative value. (not rare)

touppper(int) and tolower(int) are specified for unsigned char values and the negative EOF. Further, strcmp() returns results as if each char was converted to unsigned char, regardless if char is signed or unsigned.

tolower(*a); // Potential UB
tolower((unsigned char) *a); // Correct (Almost - see following)

char can have a negative value and not 2's complement. (rare)

The above does not handle -0 nor other negative values properly as the bit pattern should be interpreted as unsigned char. To properly handle all integer encodings, change the pointer type first.

// tolower((unsigned char) *a);
tolower(*(const unsigned char *)a); // Correct

Locale (less common)

Although character sets using ASCII code (0-127) are ubiquitous, the remainder codes tend to have locale specific issues. So strcasecmp("\xE4", "a") might return a 0 on one system and non-zero on another.


Unicode (the way of the future)

If a solution needs to handle more than ASCII consider a unicode_strcicmp(). As C lib does not provide such a function, a pre-coded function from some alternate library is recommended. Writing your own unicode_strcicmp() is a daunting task.


Do all letters map one lower to one upper? (pedantic)

[A-Z] maps one-to-one with [a-z], yet various locales map various lower case chracters to one upper and visa-versa. Further, some uppercase characters may lack a lower case equivalent and again, visa-versa.

This obliges code to covert through both tolower() and tolower().

int d = tolower(toupper(*a)) - tolower(toupper(*b));

Again, potential different results for sorting if code did tolower(toupper(*a)) vs. toupper(tolower(*a)).


Portability

@B. Nadolson recommends to avoid rolling your own strcicmp() and this is reasonable, except when code needs high equivalent portable functionality.

Below is an approach that even performed faster than some system provided functions. It does a single compare per loop rather than two by using 2 different tables that differ with '\0'. Your results may vary.

static unsigned char low1[UCHAR_MAX + 1] = {
  0, 1, 2, 3, ...
  '@', 'a', 'b', 'c', ... 'z', `[`, ...  // @ABC... Z[...
  '`', 'a', 'b', 'c', ... 'z', `{`, ...  // `abc... z{...
}
static unsigned char low2[UCHAR_MAX + 1] = {
// v--- Not zero, but A which matches none in `low1[]`
  'A', 1, 2, 3, ...
  '@', 'a', 'b', 'c', ... 'z', `[`, ...
  '`', 'a', 'b', 'c', ... 'z', `{`, ...
}

int strcicmp_ch(char const *a, char const *b) {
  // compare using tables that differ slightly.
  while (low1[*(const unsigned char *)a] == low2[*(const unsigned char *)b]) {
    a++;
    b++;
  }
  // Either strings differ or null character detected.
  // Perform subtraction using same table.
  return (low1[*(const unsigned char *)a] - low1[*(const unsigned char *)b]);
}

Prevent line-break of span element

Put this in your CSS:

white-space:nowrap;

Get more information here: http://www.w3.org/wiki/CSS/Properties/white-space

white-space

The white-space property declares how white space inside the element is handled.

Values

normal This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.

pre This value prevents user agents from collapsing sequences of white space. Lines are only broken at newlines in the source, or at occurrences of "\A" in generated content.

nowrap This value collapses white space as for 'normal', but suppresses line breaks within text.

pre-wrap This value prevents user agents from collapsing sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.

pre-line This value directs user agents to collapse sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.

inherit Takes the same specified value as the property for the element's parent.

Laravel: Using try...catch with DB::transaction()

In the case you need to manually 'exit' a transaction through code (be it through an exception or simply checking an error state) you shouldn't use DB::transaction() but instead wrap your code in DB::beginTransaction and DB::commit/DB::rollback():

DB::beginTransaction();

try {
    DB::insert(...);
    DB::insert(...);
    DB::insert(...);

    DB::commit();
    // all good
} catch (\Exception $e) {
    DB::rollback();
    // something went wrong
}

See the transaction docs.

java - iterating a linked list

Linked list does guarantee sequential order.

Don't use linkedList.get(i), especially inside a sequential loop since it defeats the purpose of having a linked list and will be inefficient code.

Use ListIterator

    ListIterator<Object> iterator = myLinkedList.listIterator();
    while( iterator.hasNext()) {
        System.out.println(iterator.next());
    }

How to get Android GPS location

Worked a day for this project. It maybe useful for u. I compressed and combined both Network and GPS. Plug and play directly in MainActivity.java (There are some DIY function for display result)

 ///////////////////////////////////
////////// LOCATION PACK //////////
// 
//  locationManager: (LocationManager) for getting LOCATION_SERVICE
//  osLocation: (Location) getting location data via standard method
//  dataLocation: class type storage locztion data
//    x,y: (Double) Longtitude, Latitude
//  location: (dataLocation) variable contain absolute location info. Autoupdate after run locationStart();
//  AutoLocation: class help getting provider info
//  tmLocation: (Timer) for running update location over time
//  LocationStart(int interval): start getting location data with setting interval time cycle in milisecond
//  LocationStart(): LocationStart(500)
//  LocationStop(): stop getting location data
//
//  EX:
//    LocationStart(); cycleF(new Runnable() {public void run(){bodyM.text("LOCATION \nLatitude: " + location.y+ "\nLongitude: " + location.x).show();}},500);
//

LocationManager locationManager;
Location osLocation;
public class dataLocation {double x,y;}
dataLocation location=new dataLocation();
public class AutoLocation extends Activity implements LocationListener {
    @Override public void onLocationChanged(Location p1){}
    @Override public void onStatusChanged(String p1, int p2, Bundle p3){}
    @Override public void onProviderEnabled(String p1){}
    @Override public void onProviderDisabled(String p1){}
    public Location getLocation(String provider) {
        if (locationManager.isProviderEnabled(provider)) {
            locationManager.requestLocationUpdates(provider,0,0,this);
            if (locationManager != null) {
                osLocation = locationManager.getLastKnownLocation(provider);
                return osLocation;
            }
        }
        return null;
    }
}
Timer tmLocation=new Timer();
public void LocationStart(int interval){
    locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
    final AutoLocation autoLocation = new AutoLocation();
    tmLocation=cycleF(new Runnable() {public void run(){ 
                Location nwLocation = autoLocation.getLocation(LocationManager.NETWORK_PROVIDER);
                if (nwLocation != null) {
                    location.y = nwLocation.getLatitude();
                    location.x = nwLocation.getLongitude();
                } else {
                    //bodym.text("NETWORK_LOCATION is loading...").show();
                }
                Location gpsLocation = autoLocation.getLocation(LocationManager.GPS_PROVIDER);
                if (gpsLocation != null) {
                    location.y = gpsLocation.getLatitude();
                    location.x = gpsLocation.getLongitude();    
                } else {
                    //bodym.text("GPS_LOCATION is loading...").show();
                }   
            }}, interval);
}
public void LocationStart(){LocationStart(500);};
public void LocationStop(){stopCycleF(tmLocation);}

//////////
///END//// LOCATION PACK //////////
//////////


/////////////////////////////
////////// RUNTIME //////////
//
// Need library:
//  import java.util.*;
//
// delayF(r,d): execute runnable r after d millisecond
//   Halt by execute the return: final Runnable rn=delayF(...); (new Handler()).post(rn);
// cycleF(r,i): execute r repeatedly with i millisecond each cycle
// stopCycleF(t): halt execute cycleF via the Timer return of cycleF
// 
// EX:
//   delayF(new Runnable(){public void run(){ sig("Hi"); }},2000);
//   final Runnable rn=delayF(new Runnable(){public void run(){ sig("Hi"); }},3000);
//     delayF(new Runnable(){public void run(){ (new Handler()).post(rn);sig("Hello"); }},1000);
//   final Timer tm=cycleF(new Runnable() {public void run(){ sig("Neverend"); }}, 1000);
//     delayF(new Runnable(){public void run(){ stopCycleF(tm);sig("Ended"); }},7000);
//
public static Runnable delayF(final Runnable r, long delay) {
    final Handler h = new Handler();
    h.postDelayed(r, delay);
    return new Runnable(){
        @Override
        public void run(){h.removeCallbacks(r);}
    };
}
public static Timer cycleF(final Runnable r, long interval) {
    final Timer t=new Timer();
    final Handler h = new Handler();
    t.scheduleAtFixedRate(new TimerTask() {
            public void run() {h.post(r);}
        }, interval, interval);
    return t;
}
public void stopCycleF(Timer t){t.cancel();t.purge();}
public boolean serviceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}
//////////
///END//// RUNTIME //////////
//////////

Get element inside element by class and ID - JavaScript

If this needs to work in IE 7 or lower you need to remember that getElementsByClassName does not exist in all browsers. Because of this you can create your own getElementsByClassName or you can try this.

var fooDiv = document.getElementById("foo");

for (var i = 0, childNode; i <= fooDiv.childNodes.length; i ++) {
    childNode = fooDiv.childNodes[i];
    if (/bar/.test(childNode.className)) {
        childNode.innerHTML = "Goodbye world!";
    }
}

How to insert a new key value pair in array in php?

foreach($test_package_data as $key=>$data ) {

   $category_detail_arr = $test_package_data[$key]['category_detail'];

   foreach( $category_detail_arr as $i=>$value ) {
     $test_package_data[$key]['category_detail'][$i]['count'] = $some_value;////<----Here
   }

}

How can I solve a connection pool problem between ASP.NET and SQL Server?

I just had the same problem and wanted to share what helped me find the source: Add the Application name to your connection string and then monitor the open connections to the SQL Server

select st.text,
    es.*, 
    ec.*
from sys.dm_exec_sessions as es
    inner join sys.dm_exec_connections as ec on es.session_id = ec.session_id
    cross apply sys.dm_exec_sql_text(ec.most_recent_sql_handle) st
where es.program_name = '<your app name here>'

Should I make HTML Anchors with 'name' or 'id'?

According to the HTML 5 specification, 5.9.8 Navigating to a fragment identifier:

For HTML documents (and the text/html MIME type), the following processing model must be followed to determine what the indicated part of the document is.

  1. Parse the URL, and let fragid be the <fragment> component of the URL.
  2. If fragid is the empty string, then the indicated part of the document is the top of the document.
  3. If there is an element in the DOM that has an ID exactly equal to fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.
  4. If there is an a element in the DOM that has a name attribute whose value is exactly equal to fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.
  5. Otherwise, there is no indicated part of the document.

So, it will look for id="foo", and then will follow to name="foo"

Edit: As pointed out by @hsivonen, in HTML5 the a element has no name attribute. However, the above rules still apply to other named elements.

Execute a file with arguments in Python shell

runfile('abc.py', ['arg1', 'arg2'])

How to give ASP.NET access to a private key in a certificate in the certificate store?

For me, it was nothing more than re-importing the certificate with "Allow private key to be exported" checked.

I guess it is necessary, but it does make me nervous as it is a third party app accessing this certificate.

Vue.js—Difference between v-model and v-bind

There are cases where you don't want to use v-model. If you have two inputs, and each depend on each other, you might have circular referential issues. Common use cases is if you're building an accounting calculator.

In these cases, it's not a good idea to use either watchers or computed properties.

Instead, take your v-model and split it as above answer indicates

<input
   :value="something"
   @input="something = $event.target.value"
>

In practice, if you are decoupling your logic this way, you'll probably be calling a method.

This is what it would look like in a real world scenario:

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  <input :value="extendedCost" @input="_onInputExtendedCost" />_x000D_
  <p> {{ extendedCost }}_x000D_
</div>_x000D_
_x000D_
<script>_x000D_
  var app = new Vue({_x000D_
    el: "#app",_x000D_
    data: function(){_x000D_
      return {_x000D_
        extendedCost: 0,_x000D_
      }_x000D_
    },_x000D_
    methods: {_x000D_
      _onInputExtendedCost: function($event) {_x000D_
        this.extendedCost = parseInt($event.target.value);_x000D_
        // Go update other inputs here_x000D_
    }_x000D_
  }_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

JavaScriptSerializer.Deserialize - how to change field names

Create a class inherited from JavaScriptConverter. You must then implement three things:

Methods-

  1. Serialize
  2. Deserialize

Property-

  1. SupportedTypes

You can use the JavaScriptConverter class when you need more control over the serialization and deserialization process.

JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new JavaScriptConverter[] { new MyCustomConverter() });

DataObject dataObject = serializer.Deserialize<DataObject>(JsonData);

Here is a link for further information

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

Here is how the default implementation (ASP.NET Framework or ASP.NET Core) works. It uses a Key Derivation Function with random salt to produce the hash. The salt is included as part of the output of the KDF. Thus, each time you "hash" the same password you will get different hashes. To verify the hash the output is split back to the salt and the rest, and the KDF is run again on the password with the specified salt. If the result matches to the rest of the initial output the hash is verified.

Hashing:

public static string HashPassword(string password)
{
    byte[] salt;
    byte[] buffer2;
    if (password == null)
    {
        throw new ArgumentNullException("password");
    }
    using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, 0x10, 0x3e8))
    {
        salt = bytes.Salt;
        buffer2 = bytes.GetBytes(0x20);
    }
    byte[] dst = new byte[0x31];
    Buffer.BlockCopy(salt, 0, dst, 1, 0x10);
    Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20);
    return Convert.ToBase64String(dst);
}

Verifying:

public static bool VerifyHashedPassword(string hashedPassword, string password)
{
    byte[] buffer4;
    if (hashedPassword == null)
    {
        return false;
    }
    if (password == null)
    {
        throw new ArgumentNullException("password");
    }
    byte[] src = Convert.FromBase64String(hashedPassword);
    if ((src.Length != 0x31) || (src[0] != 0))
    {
        return false;
    }
    byte[] dst = new byte[0x10];
    Buffer.BlockCopy(src, 1, dst, 0, 0x10);
    byte[] buffer3 = new byte[0x20];
    Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20);
    using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, dst, 0x3e8))
    {
        buffer4 = bytes.GetBytes(0x20);
    }
    return ByteArraysEqual(buffer3, buffer4);
}

What's wrong with foreign keys?

Verifying foreign key constraints takes some CPU time, so some folks omit foreign keys to get some extra performance.

Eclipse/Java code completion not working

I had this problem and like @Marc, only on a particular class. I discovered that I needed to designate Open With = Java Editor. As a Eclipse newbie I hadn't even realized that I was just using a plain text editor.

In the package explorer, right-click the file and chose "Open With".

Location of the mongodb database on mac

I have just installed mongodb 3.4 with homebrew.(brew install mongodb) It looks for /data/db by default.

https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/

Here is the output of mongod execution.

How to get last N records with activerecord?

Solution is here:

SomeModel.last(5).reverse

Since rails is lazy, it will eventually hit the database with SQL like: "SELECT table.* FROM table ORDER BY table.id DESC LIMIT 5".

Docker is in volume in use, but there aren't any Docker containers

You should type this command with flag -f (force):

sudo docker volume rm -f <VOLUME NAME>

Is it possible to get only the first character of a String?

String has a charAt method that returns the character at the specified position. Like arrays and Lists, String is 0-indexed, i.e. the first character is at index 0 and the last character is at index length() - 1.

So, assuming getSymbol() returns a String, to print the first character, you could do:

System.out.println(ld.getSymbol().charAt(0)); // char at index 0

How can I stop Chrome from going into debug mode?

I have made it working...

Please follow the highlighted mark in the attached image.

Enter image description here

Xcode 8 shows error that provisioning profile doesn't include signing certificate

For me, None of the above solutions worked. I was migrating from two older mac's to a new mac, trying to get release/debug profiles working on Xcode WITHOUT Xcode auto managing them.

The solution for me was that when I went and created the two new Certificates, i ALSO had to go into my provisioning profiles, and add (under both the distribution and dev) the new certificates to the provisioning profiles so recognized them. After doing this & downloading, xcode removed all errors and it is good to go.

Hope this helps someone!

How to move columns in a MySQL table?

I had to run this for a column introduced in the later stages of a product, on 10+ tables. So wrote this quick untidy script to generate the alter command for all 'relevant' tables.

SET @NeighboringColumn = '<YOUR COLUMN SHOULD COME AFTER THIS COLUMN>';

SELECT CONCAT("ALTER TABLE `",t.TABLE_NAME,"` CHANGE COLUMN `",COLUMN_NAME,"` 
`",COLUMN_NAME,"` ", c.DATA_TYPE, CASE WHEN c.CHARACTER_MAXIMUM_LENGTH IS NOT 
NULL THEN CONCAT("(", c.CHARACTER_MAXIMUM_LENGTH, ")") ELSE "" END ,"  AFTER 
`",@NeighboringColumn,"`;")
FROM information_schema.COLUMNS c, information_schema.TABLES t
WHERE c.TABLE_SCHEMA = '<YOUR SCHEMA NAME>'
AND c.COLUMN_NAME = '<COLUMN TO MOVE>'
AND c.TABLE_SCHEMA = t.TABLE_SCHEMA
AND c.TABLE_NAME = t.TABLE_NAME
AND t.TABLE_TYPE = 'BASE TABLE'
AND @NeighboringColumn IN (SELECT COLUMN_NAME 
    FROM information_schema.COLUMNS c2 
    WHERE c2.TABLE_NAME = t.TABLE_NAME);

concatenate two database columns into one resultset column

Just Cast Column As Varchar(Size)

If both Column are numeric then use code below.

Example:

Select (Cast(Col1 as Varchar(20)) + '-' + Cast(Col2 as Varchar(20))) As Col3 from Table

What will be the size of col3 it will be 40 or something else

How to change mysql to mysqli?

The ultimate guide to upgrading mysql_* functions to MySQLi API

The reason for the new mysqli extension was to take advantage of new features found in MySQL systems versions 4.1.3 and newer. When changing your existing code from mysql_* to mysqli API you should avail of these improvements, otherwise your upgrade efforts could go in vain.
The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:

  • Object-oriented interface
  • Support for Prepared Statements
  • Enhanced debugging capabilities

When upgrading from mysql_* functions to MySQLi, it is important to take these features into consideration, as well as some changes in the way this API should be used.

1. Object-oriented interface versus procedural functions.

The new mysqli object-oriented interface is a big improvement over the older functions and it can make your code cleaner and less susceptible to typographical errors. There is also the procedural version of this API, but its use is discouraged as it leads to less readable code, which is more prone to errors.

To open new connection to the database with MySQLi you need to create new instance of MySQLi class.

$mysqli = new \mysqli($host, $user, $password, $dbName);
$mysqli->set_charset('utf8mb4');

Using procedural style it would look like this:

$mysqli = mysqli_connect($host, $user, $password, $dbName);
mysqli_set_charset($mysqli, 'utf8mb4');

Keep in mind that only the first 3 parameters are the same as in mysql_connect. The same code in the old API would be:

$link = mysql_connect($host, $user, $password);
mysql_select_db($dbName, $link);
mysql_query('SET NAMES utf8');

If your PHP code relied on implicit connection with default parameters defined in php.ini, you now have to open the MySQLi connection passing the parameters in your code, and then provide the connection link to all procedural functions or use the OOP style.

For more information see the article: How to connect properly using mysqli

2. Support for Prepared Statements

This is a big one. MySQL has added support for native prepared statements in MySQL 4.1 (2004). Prepared statements are the best way to prevent SQL injection. It was only logical that support for native prepared statements was added to PHP. Prepared statements should be used whenever data needs to be passed along with the SQL statement (i.e. WHERE, INSERT or UPDATE are the usual use cases).

The old MySQL API had a function to escape the strings used in SQL called mysql_real_escape_string, but it was never intended for protection against SQL injections and naturally shouldn't be used for the purpose.
The new MySQLi API offers a substitute function mysqli_real_escape_string for backwards compatibility, which suffers from the same problems as the old one and therefore should not be used unless prepared statements are not available.

The old mysql_* way:

$login = mysql_real_escape_string($_POST['login']);
$result = mysql_query("SELECT * FROM users WHERE user='$login'");

The prepared statement way:

$stmt = $mysqli->prepare('SELECT * FROM users WHERE user=?');
$stmt->bind_param('s', $_POST['login']);
$stmt->execute();
$result = $stmt->get_result();

Prepared statements in MySQLi can look a little off-putting to beginners. If you are starting a new project then deciding to use the more powerful and simpler PDO API might be a good idea.

3. Enhanced debugging capabilities

Some old-school PHP developers are used to checking for SQL errors manually and displaying them directly in the browser as means of debugging. However, such practice turned out to be not only cumbersome, but also a security risk. Thankfully MySQLi has improved error reporting capabilities.

MySQLi is able to report any errors it encounters as PHP exceptions. PHP exceptions will bubble up in the script and if unhandled will terminate it instantly, which means that no statement after the erroneous one will ever be executed. The exception will trigger PHP Fatal error and will behave as any error triggered from PHP core obeying the display_errors and log_errors settings. To enable MySQLi exceptions use the line mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT) and insert it right before you open the DB connection.

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli($host, $user, $password, $dbName);
$mysqli->set_charset('utf8mb4');

If you were used to writing code such as:

$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
    die('Invalid query: ' . mysql_error());
}

or

$result = mysql_query('SELECT * WHERE 1=1') or die(mysql_error());

you no longer need to die() in your code.

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli($host, $user, $password, $dbName);
$mysqli->set_charset('utf8mb4');

$result = $mysqli->query('SELECT * FROM non_existent_table');
// The following line will never be executed due to the mysqli_sql_exception being thrown above
foreach ($result as $row) {
    // ...
}

If for some reason you can't use exceptions, MySQLi has equivalent functions for error retrieval. You can use mysqli_connect_error() to check for connection errors and mysqli_error($mysqli) for any other errors. Pay attention to the mandatory argument in mysqli_error($mysqli) or alternatively stick to OOP style and use $mysqli->error.

$result = $mysqli->query('SELECT * FROM non_existent_table') or trigger_error($mysqli->error, E_USER_ERROR);

See these posts for more explanation:
mysqli or die, does it have to die?
How to get MySQLi error information in different environments?

4. Other changes

Unfortunately not every function from mysql_* has its counterpart in MySQLi only with an "i" added in the name and connection link as first parameter. Here is a list of some of them:

  • mysql_client_encoding() has been replaced by mysqli_character_set_name($mysqli)
  • mysql_create_db has no counterpart. Use prepared statements or mysqli_query instead
  • mysql_drop_db has no counterpart. Use prepared statements or mysqli_query instead
  • mysql_db_name & mysql_list_dbs support has been dropped in favour of SQL's SHOW DATABASES
  • mysql_list_tables support has been dropped in favour of SQL's SHOW TABLES FROM dbname
  • mysql_list_fields support has been dropped in favour of SQL's SHOW COLUMNS FROM sometable
  • mysql_db_query -> use mysqli_select_db() then the query or specify the DB name in the query
  • mysql_fetch_field($result, 5) -> the second parameter (offset) is not present in mysqli_fetch_field. You can use mysqli_fetch_field_direct keeping in mind the different results returned
  • mysql_field_flags, mysql_field_len, mysql_field_name, mysql_field_table & mysql_field_type -> has been replaced with mysqli_fetch_field_direct
  • mysql_list_processes has been removed. If you need thread ID use mysqli_thread_id
  • mysql_pconnect has been replaced with mysqli_connect() with p: host prefix
  • mysql_result -> use mysqli_data_seek() in conjunction with mysqli_field_seek() and mysqli_fetch_field()
  • mysql_tablename support has been dropped in favour of SQL's SHOW TABLES
  • mysql_unbuffered_query has been removed. See this article for more information Buffered and Unbuffered queries

Combine or merge JSON on node.js without jQuery

Lodash is a another powerful tool-belt option for these sorts of utilities. See: _.merge() (which is recursive)

var object = {
  'a': [{ 'b': 2 }, { 'd': 4 }]
};
var other = {
  'a': [{ 'c': 3 }, { 'e': 5 }]
}; 
_.merge(object, other);
// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } 

SELECT INTO a table variable in T-SQL

The purpose of SELECT INTO is (per the docs, my emphasis)

To create a new table from values in another table

But you already have a target table! So what you want is

The INSERT statement adds one or more new rows to a table

You can specify the data values in the following ways:

...

By using a SELECT subquery to specify the data values for one or more rows, such as:

  INSERT INTO MyTable 
 (PriKey, Description)
        SELECT ForeignKey, Description
        FROM SomeView

And in this syntax, it's allowed for MyTable to be a table variable.

Conversion from 12 hours time to 24 hours time in java

I was looking for same thing but in number, means from integer xx hour, xx minutes and AM/PM to 24 hour format xx hour and xx minutes, so here what i have done:

private static final int AM = 0;
private static final int PM = 1;
/**
   * Based on concept: day start from 00:00AM and ends at 11:59PM, 
   * afternoon 12 is 12PM, 12:xxAM is basically 00:xxAM
   * @param hour12Format
   * @param amPm
   * @return
   */
  private int get24FormatHour(int hour12Format,int amPm){
    if(hour12Format==12 && amPm==AM){
      hour12Format=0;
    }
    if(amPm == PM && hour12Format!=12){
      hour12Format+=12;
    }
    return hour12Format;
  }`

    private int minutesTillMidnight(int hour12Format,int minutes, int amPm){
        int hour24Format=get24FormatHour(hour12Format,amPm);
        System.out.println("24 Format :"+hour24Format+":"+minutes); 
        return (hour24Format*60)+minutes;
      }

Responsive width Facebook Page Plugin

We have overcome some limitations of the responsiveness of the Facebook plugin by using it as an IFRAME, but bootstrapping at render time with some JavaScript that dynamically sizes the frame (and width/height parameters in the SRC URL) to fill the container element.

If the container is greater than 500px, to avoid having an obvious gutter on the right hand side, we simply add a scale transform with some simple math.

The IFRAME onload event fires when SRC is initially empty (when we bootstrap it) and then again after it finishes loading when we set the SRC, but we simply short-out if SRC attribute already exists.

In our usage, we don't change the width of the Facebook feed for desktop usage, and for handheld/tablet viewports, those widths are fixed by nature (yes, we trap orientation change) but if you want yours to continually adjust if the browser window dimensions change, you could just re-fire the code as an exercise for yourself.

This is tested in with Chrome and Safari, on desktop and iOS/Android:

<script>
    function setupFBframe(frame) {

        if(frame.src) return; // already set up

        // get parent container dimensions to use in src attrib
        var container = frame.parentNode;

        var containerWidth = container.offsetWidth;
        var containerHeight = container.offsetHeight;

        var src = 'https://www.facebook.com/plugins/page.php' +
                '?href=https%3A%2F%2Fwww.facebook.com%2FYourFacebookAddress%2F' +
                '&tabs=timeline' +
                '&width=' + containerWidth +
                '&height=' + containerHeight +
                '&small_header=true' +
                '&adapt_container_width=false' + /* doesn't seem to matter */
                '&hide_cover=true' +
                '&hide_cta=true' +
                '&show_facepile=false' +
                '&appId';

        frame.width = containerWidth;
        frame.height = containerHeight;
        frame.src = src;

        // scale up if container > 500px wide
        if(containerWidth) > 500) {
            var scale = (containerWidth / 500 );
            frame.style.transform = 'scale(' + scale + ')';
        }
    }
</script>
<style>
    #facebook_iframe {
        transform-origin: 0 0;
        -webkit-transform-origin: 0px 0px;
        -moz-transform-origin: 0px 0px;
    }
</style>
<iframe frameborder="0" height="0" width="0" onload="var _this = this; window.setTimeout(function(){ setupFBframe(_this); },500 /* let dom settle before eval parent dimensions */ );"></iframe>

EDIT: Forgot about transform-origin, removed need for adjusting left/top to accommodate scale. Thanks Io Ctaptceb

CSS disable text selection

::selection,::moz-selection {color:currentColor;background:transparent}

How to scroll to top of the page in AngularJS?

use: $anchorScroll();

with $anchorScroll property

Using Apache POI how to read a specific excel column

You could just loop the rows and read the same cell from each row (doesn't this comprise a column?).

Declare an empty two-dimensional array in Javascript?

What's wrong with

var arr2 = new Array(10,20);
    arr2[0,0] = 5;
    arr2[0,1] = 2
    console.log("sum is   " + (arr2[0,0] +  arr2[0,1]))

should read out "sum is 7"

autocomplete ='off' is not working when the input type is password and make the input field above it to enable autocomplete

Adding autocomplete="off" is not gonna cut it - it's ignored by Chrome.

Change input type attribute to type="search".
Google doesn't apply auto-fill to inputs with a type of search.

Truncate a string straight JavaScript

Following code truncates a string and will not split words up, and instead discard the word where the truncation occurred. Totally based on Sugar.js source.

function truncateOnWord(str, limit) {
        var trimmable = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF';
        var reg = new RegExp('(?=[' + trimmable + '])');
        var words = str.split(reg);
        var count = 0;
        return words.filter(function(word) {
            count += word.length;
            return count <= limit;
        }).join('');
    }

Label axes on Seaborn Barplot

One can avoid the AttributeError brought about by set_axis_labels() method by using the matplotlib.pyplot.xlabel and matplotlib.pyplot.ylabel.

matplotlib.pyplot.xlabel sets the x-axis label while the matplotlib.pyplot.ylabel sets the y-axis label of the current axis.

Solution code:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')
plt.xlabel("Colors")
plt.ylabel("Values")
plt.title("Colors vs Values") # You can comment this line out if you don't need title
plt.show(fig)

Output figure:

enter image description here

Adb install failure: INSTALL_CANCELED_BY_USER

For MIUI OS Device

1) Go to Setting

2) Scroll down to Additional Setting

3) You will find Developer option at bottom

4) Turn this on - Install via USB: Toggle On

By turning this on, It is working charm in my MIUI8 device.

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

What do you mean timestamp? If you mean milliseconds since the Unix epoch:

GregorianCalendar cal = new GregorianCalendar(2007, 9 - 1, 23);
long millis = cal.getTimeInMillis();

If you want an actual java.sql.Timestamp object:

Timestamp ts = new Timestamp(millis);

Using if-else in JSP

It's almost always advisable to not use scriptlets in your JSP. They're considered bad form. Instead, try using JSTL (JSP Standard Tag Library) combined with EL (Expression Language) to run the conditional logic you're trying to do. As an added benefit, JSTL also includes other important features like looping.

Instead of:

<%String user=request.getParameter("user"); %>
<%if(user == null || user.length() == 0){
    out.print("I see! You don't have a name.. well.. Hello no name");   
}
else {%>
    <%@ include file="response.jsp" %>
<% } %>

Use:

<c:choose>
    <c:when test="${empty user}">
        I see!  You don't have a name.. well.. Hello no name
    </c:when>
    <c:otherwise>
        <%@ include file="response.jsp" %>
    </c:otherwise>
</c:choose>

Also, unless you plan on using response.jsp somewhere else in your code, it might be easier to just include the html in your otherwise statement:

<c:otherwise>
    <h1>Hello</h1>
    ${user}
</c:otherwise>

Also of note. To use the core tag, you must import it as follows:

 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

You want to make it so the user will receive a message when the user submits a username. The easiest way to do this is to not print a message at all when the "user" param is null. You can do some validation to give an error message when the user submits null. This is a more standard approach to your problem. To accomplish this:

In scriptlet:

<% String user = request.getParameter("user");
   if( user != null && user.length() > 0 ) {
       <%@ include file="response.jsp" %>
   }
%>

In jstl:

<c:if test="${not empty user}">
    <%@ include file="response.jsp" %>
</c:if>

SQL DROP TABLE foreign key constraint

If you want to DROP a table which has been referenced by other table using the foreign key use

DROP TABLE *table_name* CASCADE CONSTRAINTS;
I think it should work for you.

Why is AJAX returning HTTP status code 0?

I found another case where jquery gives you status code 0 -- if for some reason XMLHttpRequest is not defined, you'll get this error.

Obviously this won't normally happen on the web, but a bug in a nightly firefox build caused this to crop up in an add-on I was writing. :)

LINQ extension methods - Any() vs. Where() vs. Exists()

IEnumerable introduces quite a number of extensions to it which helps you to pass your own delegate and invoking the resultant from the IEnumerable back. Most of them are by nature of type Func

The Func takes an argument T and returns TResult.

In case of

Where - Func : So it takes IEnumerable of T and Returns a bool. The where will ultimately returns the IEnumerable of T's for which Func returns true.

So if you have 1,5,3,6,7 as IEnumerable and you write .where(r => r<5) it will return a new IEnumerable of 1,3.

Any - Func basically is similar in signature but returns true only when any of the criteria returns true for the IEnumerable. In our case, it will return true as there are few elements present with r<5.

Exists - Predicate on the other hand will return true only when any one of the predicate returns true. So in our case if you pass .Exists(r => 5) will return true as 5 is an element present in IEnumerable.

Should we pass a shared_ptr by reference or by value?

shared_ptr isn't large enough, nor do its constructor\destructor do enough work for there to be enough overhead from the copy to care about pass by reference vs pass by copy performance.

Android setOnClickListener method - How does it work?

its an implementation of anonymouse class object creation to give ease of writing less code and to save time

java.lang.OutOfMemoryError: Java heap space

To increase the heap size you can use the -Xmx argument when starting Java; e.g.

-Xmx256M

Changing the browser zoom level

Not possible in IE, as the UI Zoom button in the status bar is not scriptable. YMMV for other browsers.

Java - How to create a custom dialog box?

If you use the NetBeans IDE (latest version at this time is 6.5.1), you can use it to create a basic GUI java application using File->New Project and choose the Java category then Java Desktop Application.

Once created, you will have a simple bare bones GUI app which contains an about box that can be opened using a menu selection. You should be able to adapt this to your needs and learn how to open a dialog from a button click.

You will be able to edit the dialog visually. Delete the items that are there and add some text areas. Play around with it and come back with more questions if you get stuck :)

Breadth First Vs Depth First

These two terms differentiate between two different ways of walking a tree.

It is probably easiest just to exhibit the difference. Consider the tree:

    A
   / \
  B   C
 /   / \
D   E   F

A depth first traversal would visit the nodes in this order

A, B, D, C, E, F

Notice that you go all the way down one leg before moving on.

A breadth first traversal would visit the node in this order

A, B, C, D, E, F

Here we work all the way across each level before going down.

(Note that there is some ambiguity in the traversal orders, and I've cheated to maintain the "reading" order at each level of the tree. In either case I could get to B before or after C, and likewise I could get to E before or after F. This may or may not matter, depends on you application...)


Both kinds of traversal can be achieved with the pseudocode:

Store the root node in Container
While (there are nodes in Container)
   N = Get the "next" node from Container
   Store all the children of N in Container
   Do some work on N

The difference between the two traversal orders lies in the choice of Container.

  • For depth first use a stack. (The recursive implementation uses the call-stack...)
  • For breadth-first use a queue.

The recursive implementation looks like

ProcessNode(Node)
   Work on the payload Node
   Foreach child of Node
      ProcessNode(child)
   /* Alternate time to work on the payload Node (see below) */

The recursion ends when you reach a node that has no children, so it is guaranteed to end for finite, acyclic graphs.


At this point, I've still cheated a little. With a little cleverness you can also work-on the nodes in this order:

D, B, E, F, C, A

which is a variation of depth-first, where I don't do the work at each node until I'm walking back up the tree. I have however visited the higher nodes on the way down to find their children.

This traversal is fairly natural in the recursive implementation (use the "Alternate time" line above instead of the first "Work" line), and not too hard if you use a explicit stack, but I'll leave it as an exercise.

WPF Timer Like C# Timer

The timer has special functions.

  1. Call an asynchronous timer or synchronous timer.
  2. Change the time interval
  3. Ability to cancel and resume  

if you use StartAsync () or Start (), the thread does not block the user interface element

     namespace UITimer


     {
        using thread = System.Threading;
        public class Timer
        {

        public event Action<thread::SynchronizationContext> TaskAsyncTick;
        public event Action Tick;
        public event Action AsyncTick;
        public int Interval { get; set; } = 1;
        private bool canceled = false;
        private bool canceling = false;
        public async void Start()
        {
            while(true)
            {

                if (!canceled)
                {
                    if (!canceling)
                    {
                        await Task.Delay(Interval);
                        Tick.Invoke();
                    }
                }
                else
                {
                    canceled = false;
                    break;
                }
            }


        }
        public void Resume()
        {
            canceling = false;
        }
        public void Cancel()
        {
            canceling = true;
        }
        public async void StartAsyncTask(thread::SynchronizationContext 
        context)
        {

                while (true)
                {
                    if (!canceled)
                    {
                    if (!canceling)
                    {
                        await Task.Delay(Interval).ConfigureAwait(false);

                        TaskAsyncTick.Invoke(context);
                    }
                    }
                    else
                    {
                        canceled = false;
                        break;
                    }
                }

        }
        public void StartAsync()
        {
            thread::ThreadPool.QueueUserWorkItem((x) =>
            {
                while (true)
                {

                    if (!canceled)
                    {
                        if (!canceling)
                        {
                            thread::Thread.Sleep(Interval);

                    Application.Current.Dispatcher.Invoke(AsyncTick);
                        }
                    }
                    else
                    {
                        canceled = false;
                        break;
                    }
                }
            });
        }

        public void StartAsync(thread::SynchronizationContext context)
        {
            thread::ThreadPool.QueueUserWorkItem((x) =>
            {
                while(true)
                 {

                    if (!canceled)
                    {
                        if (!canceling)
                        {
                            thread::Thread.Sleep(Interval);
                            context.Post((xfail) => { AsyncTick.Invoke(); }, null);
                        }
                    }
                    else
                    {
                        canceled = false;
                        break;
                    }
                }
            });
        }
        public void Abort()
        {
            canceled = true;
        }
    }


     }

XPath: select text node

your xpath should work . i have tested your xpath and mine in both MarkLogic and Zorba Xquery/ Xpath implementation.

Both should work.

/node/child::text()[1] - should return Text1
/node/child::text()[2] - should return text2


/node/text()[1] - should return Text1
/node/text()[2] - should return text2

Best way to load module/class from lib folder in Rails 3?

Very similar, but I think this is a little more elegant:

config.autoload_paths += Dir["#{config.root}/lib", "#{config.root}/lib/**/"]

apache mod_rewrite is not working or not enabled

It's working.

my solution is:

1.create a test.conf into /etc/httpd/conf.d/test.conf

2.wrote some rule, like:

<Directory "/var/www/html/test">
RewriteEngine On
RewriteRule ^link([^/]*).html$ rewrite.php?link=$1 [L]
</Directory>

3.restart your Apache server.

4.try again yourself.

How to set image in circle in swift

import UIKit

class ViewController: UIViewController {
  @IBOutlet weak var image: UIImageView!

  override func viewDidLoad() {
    super.viewDidLoad()

    image.layer.borderWidth = 1
    image.layer.masksToBounds = false
    image.layer.borderColor = UIColor.black.cgColor
    image.layer.cornerRadius = image.frame.height/2
    image.clipsToBounds = true
}

If you want it on an extension

import UIKit

extension UIImageView {

    func makeRounded() {

        self.layer.borderWidth = 1
        self.layer.masksToBounds = false
        self.layer.borderColor = UIColor.black.cgColor
        self.layer.cornerRadius = self.frame.height / 2
        self.clipsToBounds = true
    }
}

That is all you need....

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

ResultSet exception - before start of result set

You need to move the pointer to the first row, before asking for data:

result.beforeFirst();
result.next();
String foundType = result.getString(1);

Difference between webdriver.Dispose(), .Close() and .Quit()

This is a good question I have seen people use Close() when they shouldn't. I looked in the source code for the Selenium Client & WebDriver C# Bindings and found the following.

  1. webDriver.Close() - Close the browser window that the driver has focus of
  2. webDriver.Quit() - Calls Dispose()
  3. webDriver.Dispose() Closes all browser windows and safely ends the session

The code below will dispose the driver object, ends the session and closes all browsers opened during a test whether the test fails or passes.

public IWebDriver Driver;

[SetUp]
public void SetupTest()
{
    Driver = WebDriverFactory.GetDriver();
}

[TearDown]
public void TearDown()
{
    if (Driver != null)
      Driver.Quit();
}

In summary ensure that Quit() or Dispose() is called before exiting the program, and don't use the Close() method unless you're sure of what you're doing.

Note
I found this question when try to figure out a related problem why my VM's were running out of harddrive space. Turns out an exception was causing Quit() or Dispose() to not be called every run which then caused the appData folder to fill the hard drive. So we were using the Quit() method correctly but the code was unreachable. Summary make sure all code paths will clean up your unmanaged objects by using exception safe patterns or implement IDisposable

Also
In the case of RemoteDriver calling Quit() or Dispose() will also close the session on the Selenium Server. If the session isn't closed the log files for that session remain in memory.

Google reCAPTCHA: How to get user response and validate in the server side?

A method I use in my login servlet to verify reCaptcha responses. Uses classes from the java.json package. Returns the API response in a JsonObject.

Check the success field for true or false

private JsonObject validateCaptcha(String secret, String response, String remoteip)
{
    JsonObject jsonObject = null;
    URLConnection connection = null;
    InputStream is = null;
    String charset = java.nio.charset.StandardCharsets.UTF_8.name();

    String url = "https://www.google.com/recaptcha/api/siteverify";
    try {            
        String query = String.format("secret=%s&response=%s&remoteip=%s", 
        URLEncoder.encode(secret, charset), 
        URLEncoder.encode(response, charset),
        URLEncoder.encode(remoteip, charset));

        connection = new URL(url + "?" + query).openConnection();
        is = connection.getInputStream();
        JsonReader rdr = Json.createReader(is);
        jsonObject = rdr.readObject();

    } catch (IOException ex) {
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
    }
    finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }

        }
    }
    return jsonObject;
}

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

This error is caused when you have enabled paging in Grid view. If you want to delete a record from grid then you have to do something like this.

int index = Convert.ToInt32(e.CommandArgument);
int i = index % 20;
// Here 20 is my GridView's Page Size.
GridViewRow row = gvMainGrid.Rows[i];
int id = Convert.ToInt32(gvMainGrid.DataKeys[i].Value);
new GetData().DeleteRecord(id);
GridView1.DataSource = RefreshGrid();
GridView1.DataBind();

Hope this answers the question.

Tool for comparing 2 binary files in Windows

In Cygwin:

$cmp -bl <file1> <file2>

diffs binary offsets and values are in decimal and octal respectively.. Vladi.

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

If you're OK with using a library that writes the SQL for you, then you can use Upsert (currently Ruby and Python only):

Pet.upsert({:name => 'Jerry'}, :breed => 'beagle')
Pet.upsert({:name => 'Jerry'}, :color => 'brown')

That works across MySQL, Postgres, and SQLite3.

It writes a stored procedure or user-defined function (UDF) in MySQL and Postgres. It uses INSERT OR REPLACE in SQLite3.

How to add a new audio (not mixing) into a video using ffmpeg?

None of these solutions quite worked for me. My original audio was being overwritten, or I was getting an error like "failed to map memory" with the more complex 'amerge' example. It seems I needed -filter_complex amix.

ffmpeg -i videowithaudioyouwanttokeep.mp4 -i audiotooverlay.mp3 -vcodec copy -filter_complex amix -map 0:v -map 0:a -map 1:a -shortest -b:a 144k out.mkv

MySQL: Get column name or alias from query

Looks like MySQLdb doesn't actually provide a translation for that API call. The relevant C API call is mysql_fetch_fields, and there is no MySQLdb translation for that

In NetBeans how do I change the Default JDK?

If I remember correctly, you'll need to set the netbeans_jdkhome property in your netbeans config file. Should be in your etc/netbeans.conf file.

How to get twitter bootstrap modal to close (after initial launch)

I had the same problem in the iphone or desktop, didnt manage to close the dialog when pressing the close button.

i found out that The <button> tag defines a clickable button and is needed to specify the type attribute for a element as follow:

<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

check the example code for bootstrap modals at : BootStrap javascript Page

Django model "doesn't declare an explicit app_label"

in my case I was able to find a fix and by looking at the everyone else's code it may be the same issue.. I simply just had to add 'django.contrib.sites' to the list of installed apps in the settings.py file.

hope this helps someone. this is my first contribution to the coding community

Copy output of a JavaScript variable to the clipboard

function copyToClipboard(text) {
    var dummy = document.createElement("textarea");
    // to avoid breaking orgain page when copying more words
    // cant copy when adding below this code
    // dummy.style.display = 'none'
    document.body.appendChild(dummy);
    //Be careful if you use texarea. setAttribute('value', value), which works with "input" does not work with "textarea". – Eduard
    dummy.value = text;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}
copyToClipboard('hello world')
copyToClipboard('hello\nworld')

How to erase the file contents of text file in Python?

Since text files are sequential, you can't directly erase data on them. Your options are:

  • The most common way is to create a new file. Read from the original file and write everything on the new file, except the part you want to erase. When all the file has been written, delete the old file and rename the new file so it has the original name.
  • You can also truncate and rewrite the entire file from the point you want to change onwards. Seek to point you want to change, and read the rest of file to memory. Seek back to the same point, truncate the file, and write back the contents without the part you want to erase.
  • Another simple option is to overwrite the data with another data of same length. For that, seek to the exact position and write the new data. The limitation is that it must have exact same length.

Look at the seek/truncate function/method to implement any of the ideas above. Both Python and C have those functions.

How to add ID property to Html.BeginForm() in asp.net mvc?

In System.Web.Mvc.Html ( in System.Web.Mvc.dll ) the begin form is defined like:- Details

BeginForm ( this HtmlHelper htmlHelper, string actionName, string
controllerName, object routeValues, FormMethod method, object htmlAttributes)

Means you should use like this :

Html.BeginForm( string actionName, string controllerName,object routeValues, FormMethod method, object htmlAttributes)

So, it worked in MVC 4

@using (Html.BeginForm(null, null, new { @id = string.Empty }, FormMethod.Post,
    new { @id = "signupform" }))
{
    <input id="TRAINER_LIST" name="TRAINER_LIST" type="hidden" value="">
    <input type="submit" value="Create" id="btnSubmit" />
}

When to use Comparable and Comparator

Very simple approach is to assume that the entity class in question be represented in database and then in database table would you need index made up of fields of entity class? If answer is yes then implement comparable and use the index field(s) for natural sorting order. In all other cases use comparator.

iOS start Background Thread

Well that's pretty easy actually with GCD. A typical workflow would be something like this:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
    dispatch_async(queue, ^{
        // Perform async operation
        // Call your method/function here
        // Example:
        // NSString *result = [anObject calculateSomething];
                dispatch_sync(dispatch_get_main_queue(), ^{
                    // Update UI
                    // Example:
                    // self.myLabel.text = result;
                });
    });

For more on GCD you can take a look into Apple's documentation here

Normalize data in pandas

If you don't mind importing the sklearn library, I would recommend the method talked on this blog.

import pandas as pd
from sklearn import preprocessing

data = {'score': [234,24,14,27,-74,46,73,-18,59,160]}
cols = data.columns
df = pd.DataFrame(data)
df

min_max_scaler = preprocessing.MinMaxScaler()
np_scaled = min_max_scaler.fit_transform(df)
df_normalized = pd.DataFrame(np_scaled, columns = cols)
df_normalized

PHP Excel Header

The problem is you typed the wrong file extension for excel file. you used .xsl instead of xls.

I know i came in late but it can help future readers of this post.

How to disable mouse right click on a web page?

window.oncontextmenu = function () {
return false;
}

might help you.

Plotting power spectrum in python

if rate is the sampling rate(Hz), then np.linspace(0, rate/2, n) is the frequency array of every point in fft. You can use rfft to calculate the fft in your data is real values:

import numpy as np
import pylab as pl
rate = 30.0
t = np.arange(0, 10, 1/rate)
x = np.sin(2*np.pi*4*t) + np.sin(2*np.pi*7*t) + np.random.randn(len(t))*0.2
p = 20*np.log10(np.abs(np.fft.rfft(x)))
f = np.linspace(0, rate/2, len(p))
plot(f, p)

enter image description here

signal x contains 4Hz & 7Hz sin wave, so there are two peaks at 4Hz & 7Hz.

Salt and hash a password in Python

The smart thing is not to write the crypto yourself but to use something like passlib: https://bitbucket.org/ecollins/passlib/wiki/Home

It is easy to mess up writing your crypto code in a secure way. The nasty thing is that with non crypto code you often immediately notice it when it is not working since your program crashes. While with crypto code you often only find out after it is to late and your data has been compromised. Therefor I think it is better to use a package written by someone else who is knowledgable about the subject and which is based on battle tested protocols.

Also passlib has some nice features which make it easy to use and also easy to upgrade to a newer password hashing protocol if an old protocol turns out to be broken.

Also just a single round of sha512 is more vulnerable to dictionary attacks. sha512 is designed to be fast and this is actually a bad thing when trying to store passwords securely. Other people have thought long and hard about all this sort issues so you better take advantage of this.

Android Studio: Default project directory

This may be what you want. Settings -> Appearance & Behavior -> System Settings > Project Opening > Default Directory

  1. Open 'Preferences'
  2. Select System Settings -> Project Opening
  3. Set 'Default Directory' where you want.

It worked for me. I tried Android Studio 3.5.

Import file size limit in PHPMyAdmin

In my case, I also had to add the line "FcgidMaxRequestLen 1073741824" (without the quotes) in /etc/apache2/mods-available/fcgid.conf. It's documented here http://forum.ispsystem.com/en/showthread.php?p=6611 . Since mod_fcgid 2.3.6, they changed the default for FcgidMaxRequestLen from 1GB to 128K (see https://svn.apache.org/repos/asf/httpd/mod_fcgid/trunk/CHANGES-FCGID )

"Could not find a version that satisfies the requirement opencv-python"

As there is no proper wheel file in http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv?

Try this:(Worked in Anaconda Prompt or Pycharm)

pip install opencv-contrib-python

pip install opencv-python

Align text in a table header

Try:

text-align: center;

You may be familiar with the HTML align attribute (which has been discontinued as of HTML 5). The align attribute could be used with tags such as

<table>, <td>, and <img> 

to specify the alignment of these elements. This attribute allowed you to align elements horizontally. HTML also has/had a valign attribute for aligning elements vertically. This has also been discontinued from HTML5.

These attributes were discontinued in favor of using CSS to set the alignment of HTML elements.

There isn't actually a CSS align or CSS valign property. Instead, CSS has the text-align which applies to inline content of block-level elements, and vertical-align property which applies to inline level and table cells.

Change MySQL root password in phpMyAdmin

Change It like this, It worked for me. Hope It helps. firs I did

$cfg['Servers'][$i]['verbose'] = 'mysql wampserver';
//$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'changed';
/* Server parameters */
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
/* Select mysql if your server does not have mysqli */
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;

Then I Changed Like this...

$cfg['Servers'][$i]['verbose'] = 'mysql wampserver';
//$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'root';
/* Server parameters */
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
/* Select mysql if your server does not have mysqli */
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;

How to reset the use/password of jenkins on windows?

I got the initial password in the path C:\Program Files(x86)\Jenkins\secrets\initialAdminPassword

Then I login successfully with "administrator" as an user name.

How can I exclude all "permission denied" messages from "find"?

Redirect standard error. For instance, if you're using bash on a unix machine, you can redirect standard error to /dev/null like this:

find . 2>/dev/null >files_and_folders

clearing select using jquery

$('option', '#theSelect').remove();

Maven: add a folder or jar file into current classpath

The classpath setting of the compiler plugin are two args. Changed it like this and it worked for me:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
  <compilerArgs>
     <arg>-cp</arg>
     <arg>${cp}:${basedir}/lib/bad.jar</arg>
  </compilerArgs>
</configuration>

I used the gmavenplus-plugin to read the path and create the property 'cp':

      <plugin>
    <!--
      Use Groovy to read classpath and store into
      file named value of property <cpfile>

      In second step use Groovy to read the contents of
      the file into a new property named <cp>

      In the compiler plugin this is used to create a
      valid classpath
    -->
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.12.0</version>
    <dependencies>
      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <!-- any version of Groovy \>= 1.5.0 should work here -->
        <version>3.0.6</version>
        <type>pom</type>
        <scope>runtime</scope>
      </dependency>
    </dependencies>
    <executions>
      <execution>
        <id>read-classpath</id>
        <phase>validate</phase>
        <goals>
          <goal>execute</goal>
        </goals>
      </execution>

    </executions>
    <configuration>
      <scripts>
        <script><![CDATA[
                def file = new File(project.properties.cpfile)
                /* create a new property named 'cp'*/
                project.properties.cp = file.getText()
                println '<<< Retrieving classpath into new property named <cp> >>>'
                println 'cp = ' + project.properties.cp
              ]]></script>
      </scripts>
    </configuration>
  </plugin>

How to make an element width: 100% minus padding?

Use css calc()

Super simple and awesome.

input {
    width: -moz-calc(100% - 15px);
    width: -webkit-calc(100% - 15px);
    width: calc(100% - 15px);
}?

As seen here: Div width 100% minus fixed amount of pixels
By webvitaly (https://stackoverflow.com/users/713523/webvitaly)
Original source: http://web-profile.com.ua/css/dev/css-width-100prc-minus-100px/

Just copied this over here, because I almost missed it in the other thread.

How to query the permissions on an Oracle directory?

You can see all the privileges for all directories wit the following

SELECT *
from all_tab_privs
where table_name in
  (select directory_name 
   from dba_directories);

The following gives you the sql statements to grant the privileges should you need to backup what you've done or something

select 'Grant '||privilege||' on directory '||table_schema||'.'||table_name||' to '||grantee 
from all_tab_privs 
where table_name in (select directory_name from dba_directories);

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

Cannot use Server.MapPath

You need to add reference (System.Web) Reference to System.Web

Get yesterday's date in bash on Linux, DST-safe

date -d "yesterday" '+%Y-%m-%d'

To use this later:

date=$(date -d "yesterday" '+%Y-%m-%d')

Difference between Running and Starting a Docker container

This is a very important question and the answer is very simple, but fundamental:

  1. Run: create a new container of an image, and execute the container. You can create N clones of the same image. The command is: docker run IMAGE_ID and not docker run CONTAINER_ID

enter image description here

  1. Start: Launch a container previously stopped. For example, if you had stopped a database with the command docker stop CONTAINER_ID, you can relaunch the same container with the command docker start CONTAINER_ID, and the data and settings will be the same.

enter image description here

How are POST and GET variables handled in Python?

suppose you're posting a html form with this:

<input type="text" name="username">

If using raw cgi:

import cgi
form = cgi.FieldStorage()
print form["username"]

If using Django, Pylons, Flask or Pyramid:

print request.GET['username'] # for GET form method
print request.POST['username'] # for POST form method

Using Turbogears, Cherrypy:

from cherrypy import request
print request.params['username']

Web.py:

form = web.input()
print form.username

Werkzeug:

print request.form['username']

If using Cherrypy or Turbogears, you can also define your handler function taking a parameter directly:

def index(self, username):
    print username

Google App Engine:

class SomeHandler(webapp2.RequestHandler):
    def post(self):
        name = self.request.get('username') # this will get the value from the field named username
        self.response.write(name) # this will write on the document

So you really will have to choose one of those frameworks.

AngularJS $resource RESTful example

$resource was meant to retrieve data from an endpoint, manipulate it and send it back. You've got some of that in there, but you're not really leveraging it for what it was made to do.

It's fine to have custom methods on your resource, but you don't want to miss out on the cool features it comes with OOTB.

EDIT: I don't think I explained this well enough originally, but $resource does some funky stuff with returns. Todo.get() and Todo.query() both return the resource object, and pass it into the callback for when the get completes. It does some fancy stuff with promises behind the scenes that mean you can call $save() before the get() callback actually fires, and it will wait. It's probably best just to deal with your resource inside of a promise then() or the callback method.

Standard use

var Todo = $resource('/api/1/todo/:id');

//create a todo
var todo1 = new Todo();
todo1.foo = 'bar';
todo1.something = 123;
todo1.$save();

//get and update a todo
var todo2 = Todo.get({id: 123});
todo2.foo += '!';
todo2.$save();

//which is basically the same as...
Todo.get({id: 123}, function(todo) {
   todo.foo += '!';
   todo.$save();
});

//get a list of todos
Todo.query(function(todos) {
  //do something with todos
  angular.forEach(todos, function(todo) {
     todo.foo += ' something';
     todo.$save();
  });
});

//delete a todo
Todo.$delete({id: 123});

Likewise, in the case of what you posted in the OP, you could get a resource object and then call any of your custom functions on it (theoretically):

var something = src.GetTodo({id: 123});
something.foo = 'hi there';
something.UpdateTodo();

I'd experiment with the OOTB implementation before I went and invented my own however. And if you find you're not using any of the default features of $resource, you should probably just be using $http on it's own.

Update: Angular 1.2 and Promises

As of Angular 1.2, resources support promises. But they didn't change the rest of the behavior.

To leverage promises with $resource, you need to use the $promise property on the returned value.

Example using promises

var Todo = $resource('/api/1/todo/:id');

Todo.get({id: 123}).$promise.then(function(todo) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Todo.query().$promise.then(function(todos) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Just keep in mind that the $promise property is a property on the same values it was returning above. So you can get weird:

These are equivalent

var todo = Todo.get({id: 123}, function() {
   $scope.todo = todo;
});

Todo.get({id: 123}, function(todo) {
   $scope.todo = todo;
});

Todo.get({id: 123}).$promise.then(function(todo) {
   $scope.todo = todo;
});

var todo = Todo.get({id: 123});
todo.$promise.then(function() {
   $scope.todo = todo;
});

How to find where javaw.exe is installed?

For the sake of completeness, let me mention that there are some places (on a Windows PC) to look for javaw.exe in case it is not found in the path: (Still Reimeus' suggestion should be your first attempt.)

1.
Java usually stores it's location in Registry, under the following key:
HKLM\Software\JavaSoft\Java Runtime Environement\<CurrentVersion>\JavaHome

2.
Newer versions of JRE/JDK, seem to also place a copy of javaw.exe in 'C:\Windows\System32', so one might want to check there too (although chances are, if it is there, it will be found in the path as well).

3.
Of course there are the "usual" install locations:

  • 'C:\Program Files\Java\jre*\bin'
  • 'C:\Program Files\Java\jdk*\bin'
  • 'C:\Program Files (x86)\Java\jre*\bin'
  • 'C:\Program Files (x86)\Java\jdk*\bin'

[Note, that for older versions of Windows (XP, Vista(?)), this will only help on english versions of the OS. Fortunately, on later version of Windows "Program Files" will point to the directory regardless of its "display name" (which is language-specific).]

A little while back, I wrote this piece of code to check for javaw.exe in the aforementioned places. Maybe someone finds it useful:

static protected String findJavaw() {
    Path pathToJavaw = null;
    Path temp;

    /* Check in Registry: HKLM\Software\JavaSoft\Java Runtime Environement\<CurrentVersion>\JavaHome */
    String keyNode = "HKLM\\Software\\JavaSoft\\Java Runtime Environment";
    List<String> output = new ArrayList<>();
    executeCommand(new String[] {"REG", "QUERY", "\"" + keyNode + "\"", 
                                 "/v", "CurrentVersion"}, 
                   output);
    Pattern pattern = Pattern.compile("\\s*CurrentVersion\\s+\\S+\\s+(.*)$");
    for (String line : output) {
        Matcher matcher = pattern.matcher(line);
        if (matcher.find()) {
            keyNode += "\\" + matcher.group(1);
            List<String> output2 = new ArrayList<>();
            executeCommand(
                    new String[] {"REG", "QUERY", "\"" + keyNode + "\"", 
                                  "/v", "JavaHome"}, 
                    output2);
            Pattern pattern2 
                    = Pattern.compile("\\s*JavaHome\\s+\\S+\\s+(.*)$");
            for (String line2 : output2) {
                Matcher matcher2 = pattern2.matcher(line2);
                if (matcher2.find()) {
                    pathToJavaw = Paths.get(matcher2.group(1), "bin", 
                                            "javaw.exe");
                    break;
                }
            }
            break;
        }
    }
    try {
        if (Files.exists(pathToJavaw)) {
            return pathToJavaw.toString();
        }
    } catch (Exception ignored) {}

    /* Check in 'C:\Windows\System32' */
    pathToJavaw = Paths.get("C:\\Windows\\System32\\javaw.exe");
    try {
        if (Files.exists(pathToJavaw)) {
            return pathToJavaw.toString();
        }
    } catch (Exception ignored) {}

    /* Check in 'C:\Program Files\Java\jre*' */
    pathToJavaw = null;
    temp = Paths.get("C:\\Program Files\\Java");
    if (Files.exists(temp)) {
        try (DirectoryStream<Path> dirStream 
                = Files.newDirectoryStream(temp, "jre*")) {
            for (Path path : dirStream) {
                temp = Paths.get(path.toString(), "bin", "javaw.exe");
                if (Files.exists(temp)) {
                    pathToJavaw = temp;
                    // Don't "break", in order to find the latest JRE version
                }                    
            }
            if (pathToJavaw != null) {
                return pathToJavaw.toString();
            }
        } catch (Exception ignored) {}
    }

    /* Check in 'C:\Program Files (x86)\Java\jre*' */
    pathToJavaw = null;
    temp = Paths.get("C:\\Program Files (x86)\\Java");
    if (Files.exists(temp)) {
        try (DirectoryStream<Path> dirStream 
                = Files.newDirectoryStream(temp, "jre*")) {
            for (Path path : dirStream) {
                temp = Paths.get(path.toString(), "bin", "javaw.exe");
                if (Files.exists(temp)) {
                    pathToJavaw = temp;
                    // Don't "break", in order to find the latest JRE version
                }                    
            }
            if (pathToJavaw != null) {
                return pathToJavaw.toString();
            }
        } catch (Exception ignored) {}
    }

    /* Check in 'C:\Program Files\Java\jdk*' */
    pathToJavaw = null;
    temp = Paths.get("C:\\Program Files\\Java");
    if (Files.exists(temp)) {
        try (DirectoryStream<Path> dirStream 
                = Files.newDirectoryStream(temp, "jdk*")) {
            for (Path path : dirStream) {
                temp = Paths.get(path.toString(), "jre", "bin", "javaw.exe");
                if (Files.exists(temp)) {
                    pathToJavaw = temp;
                    // Don't "break", in order to find the latest JDK version
                }                    
            }
            if (pathToJavaw != null) {
                return pathToJavaw.toString();
            }
        } catch (Exception ignored) {}
    }

    /* Check in 'C:\Program Files (x86)\Java\jdk*' */
    pathToJavaw = null;
    temp = Paths.get("C:\\Program Files (x86)\\Java");
    if (Files.exists(temp)) {
        try (DirectoryStream<Path> dirStream 
                = Files.newDirectoryStream(temp, "jdk*")) {
            for (Path path : dirStream) {
                temp = Paths.get(path.toString(), "jre", "bin", "javaw.exe");
                if (Files.exists(temp)) {
                    pathToJavaw = temp;
                    // Don't "break", in order to find the latest JDK version
                }                    
            }
            if (pathToJavaw != null) {
                return pathToJavaw.toString();
            }
        } catch (Exception ignored) {}
    }

    return "javaw.exe";   // Let's just hope it is in the path :)
}

Failed to decode downloaded font, OTS parsing error: invalid version tag + rails 4

just in case this is relevant for someone. I got the exact same error using ASP.NET and C# in Visual studio. When I started the app from within the visual studio it worked, but I got this issue. In the meantime, it turned out, that the path to my project contained the character "#" (c:\C#\testapplication). This seems to confuse IIS Express (maybe also IIS) and causes this issue. I guess "#" is a reserved character somewhere in ASP.NET or below. Changing the path helped and now it works as expected.

Regards Christof

Mailto links do nothing in Chrome but work in Firefox?

In my case, chrome was associated as MAILTO protocol in Windows 10.

I changed the association to Outlook using "Default Programs" -> "Associate a file type or protocol with a program".

MAILTO is way below in the list. This screenshot may help.

enter image description here

Mips how to store user input string

# This code works fine in QtSpim simulator

.data
    buffer: .space 20
    str1:  .asciiz "Enter string"
    str2:  .asciiz "You wrote:\n"

.text

main:
    la $a0, str1    # Load and print string asking for string
    li $v0, 4
    syscall

    li $v0, 8       # take in input

    la $a0, buffer  # load byte space into address
    li $a1, 20      # allot the byte space for string

    move $t0, $a0   # save string to t0
    syscall

    la $a0, str2    # load and print "you wrote" string
    li $v0, 4
    syscall

    la $a0, buffer  # reload byte space to primary address
    move $a0, $t0   # primary address = t0 address (load pointer)
    li $v0, 4       # print string
    syscall

    li $v0, 10      # end program
    syscall

How can I account for period (AM/PM) using strftime?

Try replacing %H (Hour on a 24-hour clock) with %I (Hour on a 12-hour clock) ?

Toggle display:none style with JavaScript

you can do this easily by using jquery using .css property... try this one: http://api.jquery.com/css/

How does "FOR" work in cmd batch file?

for /f iterates per line input, so in your program will only output first path.

your program treats %PATH% as one-line input, and deliminate by ;, put first result to %%g, then output %%g (first deliminated path).

Get immediate first child element

Both these will give you the first child node:

console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);

If you need the first child that is an element node then use:

console.log(parentElement.children[0]);

Edit

Ah, I see your problem now; parentElement is an array.

If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0] to dearray (yes, I made that word up) the element:

var parentElement = document.getElementsByClassName("uniqueClassName")[0];

JavaScript equivalent of PHP's in_array()

If you only want to check if a single value is in an array, then Paolo's code will do the job. If you want to check which values are common to both arrays, then you'll want something like this (using Paolo's inArray function):

function arrayIntersect(a, b) {
    var intersection = [];

    for(var i = 0; i < a.length; i++) {
        if(inArray(b, a[i]))
            intersection.push(a[i]);
    }

    return intersection;
}

This wil return an array of values that are in both a and b. (Mathematically, this is an intersection of the two arrays.)

EDIT: See Paolo's Edited Code for the solution to your problem. :)

Shell Script — Get all files modified after <date>

This should show all files modified within the last 7 days.

find . -type f -mtime -7 -print

Pipe that into tar/zip, and you should be good.

XSL xsl:template match="/"

The match attribute indicates on which parts the template transformation is going to be applied. In that particular case the "/" means the root of the xml document. The value you have to provide into the match attribute should be XPath expression. XPath is the language you have to use to refer specific parts of the target xml file.

To gain a meaningful understanding of what else you can put into match attribute you need to understand what xpath is and how to use it. I suggest yo look at links I've provided for youat the bottom of the answer.

Could I write "table" or any other html tag instead of "/" ?

Yes you can. But this depends what exactly you are trying to do. if your target xml file contains HMTL elements and you are triyng to apply this xsl:template on them it makes sense to use table, div or anithing else.

Here a few links:

How to get the index of an item in a list in a single step?

  1. Simple solution to find index for any string value in the List.

Here is code for List Of String:

int indexOfValue = myList.FindIndex(a => a.Contains("insert value from list"));
  1. Simple solution to find index for any Integer value in the List.

Here is Code for List Of Integer:

    int indexOfNumber = myList.IndexOf(/*insert number from list*/);

Can you write virtual functions / methods in Java?

Yes, you can write virtual "functions" in Java.

laravel select where and where condition

Here is shortest way of doing it.

$userRecord = Model::where(['email'=>$email, 'password'=>$password])->first();

array.select() in javascript

There's also Array.find() in ES6 which returns the first matching element it finds.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

const myArray = [1, 2, 3]

const myElement = myArray.find((element) => element === 2)

console.log(myElement)
// => 2

How do I display Ruby on Rails form validation error messages one at a time?

I resolved it like this:

<% @user.errors.each do |attr, msg| %>
  <li>
    <%= @user.errors.full_messages_for(attr).first if @user.errors[attr].first == msg %>
  </li>
<% end %>

This way you are using the locales for the error messages.

Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds

For me I had this problem after I changed the name of one of my raw resources from extra to extra.jet, then all Rs became red and it wouldn't build. I tried all the above solutions and nothing worked, then i tried to make another copy of it with the original name extra and deleted it from within android studio then Rs returned back to normal and build succeeded.

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

If you see those characters you probably just didn’t specify the character encoding properly. Because those characters are the result when an UTF-8 multi-byte string is interpreted with a single-byte encoding like ISO 8859-1 or Windows-1252.

In this case ë could be encoded with 0xC3 0xAB that represents the Unicode character ë (U+00EB) in UTF-8.

How do I make a WPF TextBlock show my text on multiple lines?

Nesting a stackpanel will cause the textbox to wrap properly:

<Viewbox Margin="120,0,120,0">
    <StackPanel Orientation="Vertical" Width="400">
        <TextBlock x:Name="subHeaderText" 
                   FontSize="20" 
                   TextWrapping="Wrap" 
                   Foreground="Black"
                   Text="Lorem ipsum dolor, lorem isum dolor,Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet " />
    </StackPanel>
</Viewbox>

How to add rows dynamically into table layout

The way you have added a row into the table layout you can add multiple TableRow instances into your tableLayout object

tl.addView(row1);
tl.addView(row2);

etc...

How to set column widths to a jQuery datatable?

I found this on 456 Bera St. Man is it a lifesaver!!!

http://www.456bereastreet.com/archive/200704/how_to_prevent_html_tables_from_becoming_too_wide/

But - you don't have a lot of room to spare with your data.

CSS FTW:

<style>
table {
    table-layout:fixed;
}
td{
    overflow:hidden;
    text-overflow: ellipsis;
}
</style>

Support for the experimental syntax 'classProperties' isn't currently enabled

I'm using yarn. I had to do the following to overcome the error.

yarn add @babel/plugin-proposal-class-properties --dev

How do I reference a cell within excel named range?

I've been willing to use something like this in a sheet where all lines are identical and usually refer to other cells in the same line - but as the formulas get complex, the references to other columns get hard to read. I tried the trick given in other answers, with for example column A named as "Sales" I can refers to it as INDEX(Sales;row()) but I found it a bit too long for my tastes.

However, in this particular case, I found that using Sales alone works just as well - Excel (2010 here) just gets the corresponding row automatically.

It appears to work with other ranges too; for example let's say I have values in A2:A11 which I name Sales, I can just use =Sales*0.21 in B2:11 and it will use the same row value, giving out ten different results.


I also found a nice trick on this page: named ranges can also be relative. Going back to your original question, if your value "Age" is in column A and assuming you're using that value in formulas in the same line, you can define Age as being $A2 instead of $A$2, so that when used in B5 or C5 for example, it will actually refer to $A5. (The Name Manager always show the reference relative to the cell currently selected)

erlative named range

How to convert a string to utf-8 in Python

If the methods above don't work, you can also tell Python to ignore portions of a string that it can't convert to utf-8:

stringnamehere.decode('utf-8', 'ignore')

JPA getSingleResult() or null

Here's another extension, this time in Scala.

customerQuery.getSingleOrNone match {
  case Some(c) => // ...
  case None    => // ...
}

With this pimp:

import javax.persistence.{NonUniqueResultException, TypedQuery}
import scala.collection.JavaConversions._

object Implicits {

  class RichTypedQuery[T](q: TypedQuery[T]) {

    def getSingleOrNone : Option[T] = {

      val results = q.setMaxResults(2).getResultList

      if (results.isEmpty)
        None
      else if (results.size == 1)
        Some(results.head)
      else
        throw new NonUniqueResultException()
    }
  }

  implicit def query2RichQuery[T](q: TypedQuery[T]) = new RichTypedQuery[T](q)
}

How to split a single column values to multiple column values?

;WITH Split_Names (Name, xmlname)
AS
(
    SELECT 
    Name,
    CONVERT(XML,'<Names><name>'  
    + REPLACE(Name,' ', '</name><name>') + '</name></Names>') AS xmlname
      FROM somenames
)

 SELECT       
 xmlname.value('/Names[1]/name[1]','varchar(100)') AS first_name,    
 xmlname.value('/Names[1]/name[2]','varchar(100)') AS last_name
 FROM Split_Names

and also check the link below for reference

http://jahaines.blogspot.in/2009/06/converting-delimited-string-of-values.html

How do I get the current absolute URL in Ruby on Rails?

For Rails 3.2 or Rails 4 Simply get in this way "request.original_url" Reference: Original URL Method

For Rails 3 As request.url is deprecated.We can get absolute path by concatenating

"#{request.protocol}#{request.host_with_port}#{request.fullpath}"

For Rails 2

request.url

How to convert a string into double and vice versa?

olliej's rounding method is wrong for negative numbers

  • 2.4 rounded is 2 (olliej's method gets this right)
  • -2.4 rounded is -2 (olliej's method returns -1)

Here's an alternative

  int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5))

You could of course use a rounding function from math.h

Show "loading" animation on button click

If you are using ajax then (making it as simple as possible)

  1. Add your loading gif image to html and make it hidden (using style in html itself now, you can add it to separate CSS):

    <img src="path\to\loading\gif" id="img" style="display:none"/ >
    
  2. Show the image when button is clicked and hide it again on success function

    $('#buttonID').click(function(){
      $('#img').show(); //<----here
      $.ajax({
        ....
       success:function(result){
           $('#img').hide();  //<--- hide again
       }
    }
    

Make sure you hide the image on ajax error callbacks too to make sure the gif hides even if the ajax fails.

How to pass macro definition from "make" command line arguments (-D) to C source code?

Call make command this way:

make CFLAGS=-Dvar=42

And be sure to use $(CFLAGS) in your compile command in the Makefile. As @jørgensen mentioned , putting the variable assignment after the make command will override the CFLAGS value already defined the Makefile.

Alternatively you could set -Dvar=42 in another variable than CFLAGS and then reuse this variable in CFLAGS to avoid completely overriding CFLAGS.

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

You need to delete your old db folder and recreate new one. It will resolve your issue.

Run .jar from batch-file

There is a solution to this that does not require to specify the path of the jar file inside the .bat. This means the jar can be moved around in the filesystem with no changes, as long as the .bat file is always located in the same directory as the jar. The .bat code is:

java -jar %~dp0myjarfile.jar %*

Basically %0 would expand to the .bat full path, and %~dp0 expands to the .bat full path except the filename. So %~dp0myjarfile.jar is the full path of the myjarfile.jar colocated with the .bat file. %* will take all the arguments given to the .bat and pass it to the Java program. (see: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/percent.mspx?mfr=true )

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

You must use the column names and then set the values to insert (both ? marks):

//insert 1st row            
String inserting = "INSERT INTO employee(emp_name ,emp_address) values(?,?)";
System.out.println("insert " + inserting);//
PreparedStatement ps = con.prepareStatement(inserting); 
ps.setString(1, "hans");
ps.setString(2, "germany");
ps.executeUpdate();

Best way to check if a character array is empty

The second one is fastest. Using strlen will be close if the string is indeed empty, but strlen will always iterate through every character of the string, so if it is not empty, it will do much more work than you need it to.

As James mentioned, the third option wipes the string out before checking, so the check will always succeed but it will be meaningless.

Why does Google prepend while(1); to their JSON responses?

It prevents disclosure of the response through JSON hijacking.

In theory, the content of HTTP responses are protected by the Same Origin Policy: pages from one domain cannot get any pieces of information from pages on the other domain (unless explicitly allowed).

An attacker can request pages on other domains on your behalf, e.g. by using a <script src=...> or <img> tag, but it can't get any information about the result (headers, contents).

Thus, if you visit an attacker's page, it couldn't read your email from gmail.com.

Except that when using a script tag to request JSON content, the JSON is executed as JavaScript in an attacker's controlled environment. If the attacker can replace the Array or Object constructor or some other method used during object construction, anything in the JSON would pass through the attacker's code, and be disclosed.

Note that this happens at the time the JSON is executed as JavaScript, not at the time it's parsed.

There are multiple countermeasures:

Making sure the JSON never executes

By placing a while(1); statement before the JSON data, Google makes sure that the JSON data is never executed as JavaScript.

Only a legitimate page could actually get the whole content, strip the while(1);, and parse the remainder as JSON.

Things like for(;;); have been seen at Facebook for instance, with the same results.

Making sure the JSON is not valid JavaScript

Similarly, adding invalid tokens before the JSON, like &&&START&&&, makes sure that it is never executed.

Always return JSON with an Object on the outside

This is OWASP recommended way to protect from JSON hijacking and is the less intrusive one.

Similarly to the previous counter-measures, it makes sure that the JSON is never executed as JavaScript.

A valid JSON object, when not enclosed by anything, is not valid in JavaScript:

eval('{"foo":"bar"}')
// SyntaxError: Unexpected token :

This is however valid JSON:

JSON.parse('{"foo":"bar"}')
// Object {foo: "bar"}

So, making sure you always return an Object at the top level of the response makes sure that the JSON is not valid JavaScript, while still being valid JSON.

As noted by @hvd in the comments, the empty object {} is valid JavaScript, and knowing the object is empty may itself be valuable information.

Comparison of above methods

The OWASP way is less intrusive, as it needs no client library changes, and transfers valid JSON. It is unsure whether past or future browser bugs could defeat this, however. As noted by @oriadam, it is unclear whether data could be leaked in a parse error through an error handling or not (e.g. window.onerror).

Google's way requires a client library in order for it to support automatic de-serialization and can be considered to be safer with regard to browser bugs.

Both methods require server side changes in order to avoid developers accidentally sending vulnerable JSON.

Add image in pdf using jspdf

maybe a little bit late, but I come to this situation recently and found a simple solution, 2 functions are needed.

  1. load the image.

    function getImgFromUrl(logo_url, callback) {
        var img = new Image();
        img.src = logo_url;
        img.onload = function () {
            callback(img);
        };
    } 
    
  2. in onload event on first step, make a callback to use the jspdf doc.

    function generatePDF(img){
        var options = {orientation: 'p', unit: 'mm', format: custom};
        var doc = new jsPDF(options);
        doc.addImage(img, 'JPEG', 0, 0, 100, 50);}
    
  3. use the above functions.

    var logo_url = "/images/logo.jpg";
    getImgFromUrl(logo_url, function (img) {
        generatePDF(img);
    });
    

Can't create handler inside thread that has not called Looper.prepare()

Using lambda:

activity.runOnUiThread(() -> Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show());

Instagram API - How can I retrieve the list of people a user is following on Instagram

Here's a way to get the list of people a user is following with just a browser and some copy-paste (A pure javascript solution based on Deep Seeker's answer):

  1. Get the user's id (In a browser, navigate to https://www.instagram.com/user_name/?__a=1 and look for response -> graphql -> user -> id [from Deep Seeker's answer])

  2. Open another browser window

  3. Open the browser console and paste this in it

    _x000D_
    _x000D_
    options = {
        userId: your_user_id,
        list: 1 //1 for following, 2 for followers
    }
    _x000D_
    _x000D_
    _x000D_

  4. change to your user id and hit enter

  5. paste this in the console and hit enter

    _x000D_
    _x000D_
    `https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=` + encodeURIComponent(JSON.stringify({
            "id": options.userId,
            "include_reel": true,
            "fetch_mutual": true,
            "first": 50
        }))
    _x000D_
    _x000D_
    _x000D_

  6. Navigate to the outputted link

(This sets up the headers for the http request. If you try to run the script on a page where this isn't open, it won't work.)

  1. In the console for the page you just opened, paste this and hit enter
    _x000D_
    _x000D_
    let config = {
      followers: {
        hash: 'c76146de99bb02f6415203be841dd25a',
        path: 'edge_followed_by'
      },
      following: {
        hash: 'd04b0a864b4b54837c0d870b0e77e076',
        path: 'edge_follow'
      }
    };
    
    var allUsers = [];
    
    function getUsernames(data) {
        var userBatch = data.map(element => element.node.username);
        allUsers.push(...userBatch);
    }
    
    async function makeNextRequest(nextCurser, listConfig) {
        var params = {
            "id": options.userId,
            "include_reel": true,
            "fetch_mutual": true,
            "first": 50
        };
        if (nextCurser) {
            params.after = nextCurser;
        }
        var requestUrl = `https://www.instagram.com/graphql/query/?query_hash=` + listConfig.hash + `&variables=` + encodeURIComponent(JSON.stringify(params));
    
        var xhr = new XMLHttpRequest();
        xhr.onload = function(e) {
            var res = JSON.parse(xhr.response);
    
            var userData = res.data.user[listConfig.path].edges;
            getUsernames(userData);
    
            var curser = "";
            try {
                curser = res.data.user[listConfig.path].page_info.end_cursor;
            } catch {
    
            }
            var users = [];
            if (curser) {
                makeNextRequest(curser, listConfig);
            } else {
                var printString =""
                allUsers.forEach(item => printString = printString + item + "\n");
                console.log(printString);
            }
        }
    
        xhr.open("GET", requestUrl);
        xhr.send();
    }
    
    if (options.list === 1) {
    
        console.log('following');
        makeNextRequest("", config.following);
    } else if (options.list === 2) {
    
        console.log('followers');
        makeNextRequest("", config.followers);
    }
    _x000D_
    _x000D_
    _x000D_

After a few seconds it should output the list of users your user is following.

how to return index of a sorted list?

How about

l1 = [2,3,1,4,5]
l2 = [l1.index(x) for x in sorted(l1)]

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

date -j -f "%Y-%m-%d" "2010-10-02" "+%s"

How to upgrade Git to latest version on macOS?

In order to keep both versions, I just changed the value of PATH environment variable by putting the new version's git path "/usr/local/git/bin/" at the beginning, it forces to use the newest version:

$ echo $PATH

/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/git/bin/

$ git --version

git version 2.4.9 (Apple Git-60)

original value: /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/git/bin/

new value: /usr/local/git/bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin

$ export PATH=/usr/local/git/bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin

$ git --version

git version 2.13.0

Java JDBC - How to connect to Oracle using Service Name instead of SID

http://download.oracle.com/docs/cd/B28359_01/java.111/b31224/urls.htm#BEIDHCBA

Thin-style Service Name Syntax

Thin-style service names are supported only by the JDBC Thin driver. The syntax is:

@//host_name:port_number/service_name

For example:

jdbc:oracle:thin:scott/tiger@//myhost:1521/myservicename

So I would try:

jdbc:oracle:thin:@//oracle.hostserver2.mydomain.ca:1522/ABCD

Also, per Robert Greathouse's answer, you can also specify the TNS name in the JDBC URL as below:

jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS =(PROTOCOL=TCP)(HOST=blah.example.com)(PORT=1521)))(CONNECT_DATA=(SID=BLAHSID)(GLOBAL_NAME=BLAHSID.WORLD)(SERVER=DEDICATED)))

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

Unbelievably, in 3 years nobody has answered your excellent question with examples of both ways to map the relationship.

As mentioned by others, the "owner" side contains the pointer (foreign key) in the database. You can designate either side as the owner, however, if you designate the One side as the owner, the relationship will not be bidirectional (the inverse aka "many" side will have no knowledge of its "owner"). This can be desirable for encapsulation/loose coupling:

// "One" Customer owns the associated orders by storing them in a customer_orders join table
public class Customer {
    @OneToMany(cascade = CascadeType.ALL)
    private List<Order> orders;
}

// if the Customer owns the orders using the customer_orders table,
// Order has no knowledge of its Customer
public class Order {
    // @ManyToOne annotation has no "mappedBy" attribute to link bidirectionally
}

The only bidirectional mapping solution is to have the "many" side own its pointer to the "one", and use the @OneToMany "mappedBy" attribute. Without the "mappedBy" attribute Hibernate will expect a double mapping (the database would have both the join column and the join table, which is redundant (usually undesirable)).

// "One" Customer as the inverse side of the relationship
public class Customer {
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "customer")
    private List<Order> orders;
}

// "many" orders each own their pointer to a Customer
public class Order {
    @ManyToOne
    private Customer customer;
}

jQuery autohide element after 5 seconds

Please note you may need to display div text again after it has disappeared. So you will need to also empty and then re-show the element at some point.

You can do this with 1 line of code:

$('#element_id').empty().show().html(message).delay(3000).fadeOut(300);

If you're using jQuery you don't need setTimeout, at least not to autohide an element.

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

Google officially suggests to developers to use Volley library for networking related stuff Here, so Its time to switch to Volley, Happy coding

Image resolution for mdpi, hdpi, xhdpi and xxhdpi

Your inputs lack one important information of device dimension. Suppose now popular phone is 6 inch(the diagonal of the display), you will have following results

enter image description here

DPI: Dots per inch - number of dots(pixels) per segment(line) of 1 inch. DPI=Diagonal/Device size

Scaling Ratio= Real DPI/160. 160 is basic density (MHDPI)

DP: (Density-independent Pixel)=1/160 inch, think of it as a measurement unit

How to force two figures to stay on the same page in LaTeX?

If you want them both on the same page and they'll both take up basically the whole page, then the best idea is to tell LaTeX to put them both on a page of their own!

\begin{figure}[p]

It would probably be against sound typographic principles (e.g., ugly) to have two figures on a page with only a few lines of text above or below them.


By the way, the reason that [!h] works is because it's telling LaTeX to override its usual restrictions on how much space should be devoted to floats on a page with text. As implied above, there's a reason the restrictions are there. Which isn't to say they can be loosened somewhat; see the FAQ on doing that.

Parse JSON response using jQuery

Give this a try:

success: function(json) {
   console.log(JSON.stringify(json.topics));
   $.each(json.topics, function(idx, topic){
     $("#nav").html('<a href="' + topic.link_src + '">' + topic.link_text + "</a>");
   });
},

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

ClusterIP: Services are reachable by pods/services in the Cluster
If I make a service called myservice in the default namespace of type: ClusterIP then the following predictable static DNS address for the service will be created:

myservice.default.svc.cluster.local (or just myservice.default, or by pods in the default namespace just "myservice" will work)

And that DNS name can only be resolved by pods and services inside the cluster.

NodePort: Services are reachable by clients on the same LAN/clients who can ping the K8s Host Nodes (and pods/services in the cluster) (Note for security your k8s host nodes should be on a private subnet, thus clients on the internet won't be able to reach this service)
If I make a service called mynodeportservice in the mynamespace namespace of type: NodePort on a 3 Node Kubernetes Cluster. Then a Service of type: ClusterIP will be created and it'll be reachable by clients inside the cluster at the following predictable static DNS address:

mynodeportservice.mynamespace.svc.cluster.local (or just mynodeportservice.mynamespace)

For each port that mynodeportservice listens on a nodeport in the range of 30000 - 32767 will be randomly chosen. So that External clients that are outside the cluster can hit that ClusterIP service that exists inside the cluster. Lets say that our 3 K8s host nodes have IPs 10.10.10.1, 10.10.10.2, 10.10.10.3, the Kubernetes service is listening on port 80, and the Nodeport picked at random was 31852.

A client that exists outside of the cluster could visit 10.10.10.1:31852, 10.10.10.2:31852, or 10.10.10.3:31852 (as NodePort is listened for by every Kubernetes Host Node) Kubeproxy will forward the request to mynodeportservice's port 80.

LoadBalancer: Services are reachable by everyone connected to the internet* (Common architecture is L4 LB is publicly accessible on the internet by putting it in a DMZ or giving it both a private and public IP and k8s host nodes are on a private subnet)
(Note: This is the only service type that doesn't work in 100% of Kubernetes implementations, like bare metal Kubernetes, it works when Kubernetes has cloud provider integrations.)

If you make mylbservice, then a L4 LB VM will be spawned (a cluster IP service, and a NodePort Service will be implicitly spawned as well). This time our NodePort is 30222. the idea is that the L4 LB will have a public IP of 1.2.3.4 and it will load balance and forward traffic to the 3 K8s host nodes that have private IP addresses. (10.10.10.1:30222, 10.10.10.2:30222, 10.10.10.3:30222) and then Kube Proxy will forward it to the service of type ClusterIP that exists inside the cluster.


You also asked: Does the NodePort service type still use the ClusterIP? Yes*
Or is the NodeIP actually the IP found when you run kubectl get nodes? Also Yes*

Lets draw a parrallel between Fundamentals:
A container is inside a pod. a pod is inside a replicaset. a replicaset is inside a deployment.
Well similarly:
A ClusterIP Service is part of a NodePort Service. A NodePort Service is Part of a Load Balancer Service.


In that diagram you showed, the Client would be a pod inside the cluster.

Build .NET Core console application to output an EXE

If a .bat file is acceptable, you can create a bat file with the same name as the DLL file (and place it in the same folder), then paste in the following content:

dotnet %~n0.dll %*

Obviously, this assumes that the machine has .NET Core installed and globally available.

c:\> "path\to\batch\file" -args blah

(This answer is derived from Chet's comment.)

fatal: could not create work tree dir 'kivy'

If you are working on a mac, then this is probably because you don't have permission to write to the directory. When I had this issue, I followed the following steps:

  • Opened the folder in finder -> right-click -> get info -> click on the lock on the bottom right of the pop up window, enter admin password -> then change the Sharing and Permissions to Read and Write for wheel, and everyone -> click lock again to save

Installing Google Protocol Buffers on mac

If you landed here looking for how to install Protocol Buffers on Mac, it can be done using Homebrew by running the command below

brew install protobuf

It installs the latest version of protobuf available. For me, at the time of writing, this installed the v3.7.1

If you'd like to install an older version, please look up the available ones from the package page Protobuf Package - Homebrew and install that specific version of the package.

The oldest available protobuf version in this package is v3.6.1.3

SQL Row_Number() function in Where Clause

 select salary from (
 select  Salary, ROW_NUMBER() over (order by Salary desc) rn from Employee 
 ) t where t.rn = 2

Only variable references should be returned by reference - Codeigniter

this has been modified in codeigniter 2.2.1...usually not best practice to modify core files, I would always check for updates and 2.2.1 came out in Jan 2015

How to assert greater than using JUnit Assert?

Alternatively if adding extra library such as hamcrest is not desirable, the logic can be implemented as utility method using junit dependency only:

public static void assertGreaterThan(int greater, int lesser) {
    assertGreaterThan(greater, lesser, null);
}

public static void assertGreaterThan(int greater, int lesser, String message) {
    if (greater <= lesser) {
        fail((StringUtils.isNotBlank(message) ? message + " ==> " : "") +
                "Expected: a value greater than <" + lesser + ">\n" +
                "But <" + greater + "> was " + (greater == lesser ? "equal to" : "less than") + " <" + lesser + ">");
    }
}

ImportError: No module named PyQt4.QtCore

I got the same error, when I was trying to import matplotlib.pyplot

In [1]: import matplotlib.pyplot as plt
...
...
ImportError: No module named PyQt4.QtCore

But in my case the problem was due to a missing linux library libGL.so.1

OS : Cent OS 64 bit

Python version : 3.5.2

$> locate libGL.so.1

If this command returns a value, your problem could be different, so please ignore my answer. If it does not return any value and your environment is same as mine, below steps would fix your problem.

$> yum install mesa-libGL.x86_64

This installs the necessary OpenGL libraries for 64 bit Cent OS.

$> locate libGL.so.1
/usr/lib/libGL.so.1

Now go back to iPython and try to import

In [1]: import matplotlib.pyplot as plt

This time it imported successfully.

Extract images from PDF without resampling, in python?

  1. First Install pdf2image

    pip install pdf2image==1.14.0

  2. Follow the below code for extraction of pages from PDF.

    file_path="file path of PDF"
    info = pdfinfo_from_path(file_path, userpw=None, poppler_path=None)
    maxPages = info["Pages"]
    image_counter = 0
    if maxPages > 10:
        for page in range(1, maxPages, 10):
            pages = convert_from_path(file_path, dpi=300, first_page=page, 
                    last_page=min(page+10-1, maxPages))
            for page in pages:
                page.save(image_path+'/' + str(image_counter) + '.png', 'PNG')
                image_counter += 1
    else:
        pages = convert_from_path(file_path, 300)
        for i, j in enumerate(pages):
            j.save(image_path+'/' + str(i) + '.png', 'PNG')
    

Hope it helps coders looking for easy conversion of PDF files to Images as per pages of PDF.

How do you connect to multiple MySQL databases on a single webpage?

$dbh1 = mysql_connect($hostname, $username, $password);  
$dbh2 = mysql_connect($hostname, $username, $password, true); 

mysql_select_db('database1', $dbh1); 
mysql_select_db('database2',$dbh2); 

mysql_query('select * from tablename', $dbh1);
mysql_query('select * from tablename', $dbh2);

This is the most obvious solution that I use but just remember, if the username / password for both the database is exactly same in the same host, this solution will always be using the first connection. So don't be confused that this is not working in such case. What you need to do is, create 2 different users for the 2 databases and it will work.

How to restrict the selectable date ranges in Bootstrap Datepicker?

i am using v3.1.3 and i had to use data('DateTimePicker') like this

var fromE = $( "#" + fromInput );
var toE = $( "#" + toInput );
$('.form-datepicker').datetimepicker(dtOpts);

$('.form-datepicker').on('change', function(e){
   var isTo = $(this).attr('name') === 'to';

   $( "#" + ( isTo ? fromInput : toInput  ) )
      .data('DateTimePicker')[ isTo ? 'setMaxDate' : 'setMinDate' ](moment($(this).val(), 'DD/MM/YYYY'))
});

Global variables in R

I found a solution for how to set a global variable in a mailinglist posting via assign:

a <- "old"
test <- function () {
   assign("a", "new", envir = .GlobalEnv)
}
test()
a  # display the new value

How do I search within an array of hashes by hash values in ruby?

(Adding to previous answers (hope that helps someone):)

Age is simpler but in case of string and with ignoring case:

  • Just to verify the presence:

@fathers.any? { |father| father[:name].casecmp("john") == 0 } should work for any case in start or anywhere in the string i.e. for "John", "john" or "JoHn" and so on.

  • To find first instance/index:

@fathers.find { |father| father[:name].casecmp("john") == 0 }

  • To select all such indices:

@fathers.select { |father| father[:name].casecmp("john") == 0 }

How do I use a regular expression to match any string, but at least 3 characters?

This is python regex, but it probably works in other languages that implement it, too.

I guess it depends on what you consider a character to be. If it's letters, numbers, and underscores:

\w{3,}

if just letters and digits:

[a-zA-Z0-9]{3,}

Python also has a regex method to return all matches from a string.

>>> import re
>>> re.findall(r'\w{3,}', 'This is a long string, yes it is.')
['This', 'long', 'string', 'yes']

Center content vertically on Vuetify

For me, align="center" was enough to center FOO vertically:

<v-row align="center">
  <v-col>FOO</v-col>
</row>

internet explorer 10 - how to apply grayscale filter?

Inline SVG can be used in IE 10 and 11 and Edge 12.

I've created a project called gray which includes a polyfill for these browsers. The polyfill switches out <img> tags with inline SVG: https://github.com/karlhorky/gray

To implement, the short version is to download the jQuery plugin at the GitHub link above and add after jQuery at the end of your body:

<script src="/js/jquery.gray.min.js"></script>

Then every image with the class grayscale will appear as gray.

<img src="/img/color.jpg" class="grayscale">

You can see a demo too if you like.

Access Tomcat Manager App from different host

Each deployed webapp has a context.xml file that lives in

$CATALINA_BASE/conf/[enginename]/[hostname]

(conf/Catalina/localhost by default)

and has the same name as the webapp (manager.xml in this case). If no file is present, default values are used.

So, you need to create a file conf/Catalina/localhost/manager.xml and specify the rule you want to allow remote access. For example, the following content of manager.xml will allow access from all machines:

<Context privileged="true" antiResourceLocking="false" 
         docBase="${catalina.home}/webapps/manager">
    <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="^YOUR.IP.ADDRESS.HERE$" />
</Context>

Note that the allow attribute of the Valve element is a regular expression that matches the IP address of the connecting host. So substitute your IP address for YOUR.IP.ADDRESS.HERE (or some other useful expression).

Other Valve classes cater for other rules (e.g. RemoteHostValve for matching host names). Earlier versions of Tomcat use a valve class org.apache.catalina.valves.RemoteIpValve for IP address matching.

Once the changes above have been made, you should be presented with an authentication dialog when accessing the manager URL. If you enter the details you have supplied in tomcat-users.xml you should have access to the Manager.

get an element's id

This gets and alerts the id of the element with the id "ele".

var id = document.getElementById("ele").id;
alert("ID: " + id);

Colorplot of 2D array matplotlib

I'm afraid your posted example is not working, since X and Y aren't defined. So instead of pcolormesh let's use imshow:

import numpy as np
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12],
              [13, 14, 15, 16]])  # added some commas and array creation code

fig = plt.figure(figsize=(6, 3.2))

ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(H)
ax.set_aspect('equal')

cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()

Correct way to remove plugin from Eclipse

Eclipse Photon user here, found it under the toolbar's Windows > Preferences > Install/Update > "Uninstall or update" link > Click stuff and hit the "Uninstall" button.

Screenshot

Difference between Visibility.Collapsed and Visibility.Hidden

Visibility : Hidden Vs Collapsed

Consider following code which only shows three Labels and has second Label visibility as Collapsed:

 <StackPanel Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Center">
    <StackPanel.Resources>
        <Style TargetType="Label">
            <Setter Property="Height" Value="30" />
            <Setter Property="Margin" Value="0"/>
            <Setter Property="BorderBrush" Value="Black"/>
            <Setter Property="BorderThickness" Value="1" />
        </Style>
    </StackPanel.Resources>
    <Label Width="50" Content="First"/>
    <Label Width="50" Content="Second" Visibility="Collapsed"/>
    <Label Width="50" Content="Third"/>
</StackPanel>

Output Collapsed:

Collapsed

Now change the second Label visibility to Hiddden.

<Label Width="50" Content="Second" Visibility="Hidden"/>

Output Hidden:

Hidden

As simple as that.

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

The correct format for IE8 is:

  $("#ActionBox").css({ 'margin-top': '10px' });  

with this work.

How to loop through all elements of a form jQuery

As taken from the #jquery Freenode IRC channel:

$.each($(form).serializeArray(), function(_, field) { /* use field.name, field.value */ });

Thanks to @Cork on the channel.

How is __eq__ handled in Python and in what order?

I'm writing an updated answer for Python 3 to this question.

How is __eq__ handled in Python and in what order?

a == b

It is generally understood, but not always the case, that a == b invokes a.__eq__(b), or type(a).__eq__(a, b).

Explicitly, the order of evaluation is:

  1. if b's type is a strict subclass (not the same type) of a's type and has an __eq__, call it and return the value if the comparison is implemented,
  2. else, if a has __eq__, call it and return it if the comparison is implemented,
  3. else, see if we didn't call b's __eq__ and it has it, then call and return it if the comparison is implemented,
  4. else, finally, do the comparison for identity, the same comparison as is.

We know if a comparison isn't implemented if the method returns NotImplemented.

(In Python 2, there was a __cmp__ method that was looked for, but it was deprecated and removed in Python 3.)

Let's test the first check's behavior for ourselves by letting B subclass A, which shows that the accepted answer is wrong on this count:

class A:
    value = 3
    def __eq__(self, other):
        print('A __eq__ called')
        return self.value == other.value

class B(A):
    value = 4
    def __eq__(self, other):
        print('B __eq__ called')
        return self.value == other.value

a, b = A(), B()
a == b

which only prints B __eq__ called before returning False.

How do we know this full algorithm?

The other answers here seem incomplete and out of date, so I'm going to update the information and show you how how you could look this up for yourself.

This is handled at the C level.

We need to look at two different bits of code here - the default __eq__ for objects of class object, and the code that looks up and calls the __eq__ method regardless of whether it uses the default __eq__ or a custom one.

Default __eq__

Looking __eq__ up in the relevant C api docs shows us that __eq__ is handled by tp_richcompare - which in the "object" type definition in cpython/Objects/typeobject.c is defined in object_richcompare for case Py_EQ:.

    case Py_EQ:
        /* Return NotImplemented instead of False, so if two
           objects are compared, both get a chance at the
           comparison.  See issue #1393. */
        res = (self == other) ? Py_True : Py_NotImplemented;
        Py_INCREF(res);
        break;

So here, if self == other we return True, else we return the NotImplemented object. This is the default behavior for any subclass of object that does not implement its own __eq__ method.

How __eq__ gets called

Then we find the C API docs, the PyObject_RichCompare function, which calls do_richcompare.

Then we see that the tp_richcompare function, created for the "object" C definition is called by do_richcompare, so let's look at that a little more closely.

The first check in this function is for the conditions the objects being compared:

  • are not the same type, but
  • the second's type is a subclass of the first's type, and
  • the second's type has an __eq__ method,

then call the other's method with the arguments swapped, returning the value if implemented. If that method isn't implemented, we continue...

    if (!Py_IS_TYPE(v, Py_TYPE(w)) &&
        PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v)) &&
        (f = Py_TYPE(w)->tp_richcompare) != NULL) {
        checked_reverse_op = 1;
        res = (*f)(w, v, _Py_SwappedOp[op]);
        if (res != Py_NotImplemented)
            return res;
        Py_DECREF(res);

Next we see if we can lookup the __eq__ method from the first type and call it. As long as the result is not NotImplemented, that is, it is implemented, we return it.

    if ((f = Py_TYPE(v)->tp_richcompare) != NULL) {
        res = (*f)(v, w, op);
        if (res != Py_NotImplemented)
            return res;
        Py_DECREF(res);

Else if we didn't try the other type's method and it's there, we then try it, and if the comparison is implemented, we return it.

    if (!checked_reverse_op && (f = Py_TYPE(w)->tp_richcompare) != NULL) {
        res = (*f)(w, v, _Py_SwappedOp[op]);
        if (res != Py_NotImplemented)
            return res;
        Py_DECREF(res);
    }

Finally, we get a fallback in case it isn't implemented for either one's type.

The fallback checks for the identity of the object, that is, whether it is the same object at the same place in memory - this is the same check as for self is other:

    /* If neither object implements it, provide a sensible default
       for == and !=, but raise an exception for ordering. */
    switch (op) {
    case Py_EQ:
        res = (v == w) ? Py_True : Py_False;
        break;

Conclusion

In a comparison, we respect the subclass implementation of comparison first.

Then we attempt the comparison with the first object's implementation, then with the second's if it wasn't called.

Finally we use a test for identity for comparison for equality.

sed whole word search and replace

On Mac OS X, neither of these regex syntaxes work inside sed for matching whole words

  • \bmyWord\b
  • \<myWord\>

Hear me now and believe me later, this ugly syntax is what you need to use:

  • /[[:<:]]myWord[[:>:]]/

So, for example, to replace mint with minty for whole words only:

  • sed "s/[[:<:]]mint[[:>:]]/minty/g"

Source: re_format man page

Freemarker iterating over hashmap keys

Since 2.3.25, do it like this:

<#list user as propName, propValue>
  ${propName} = ${propValue}
</#list>

Note that this also works with non-string keys (unlike map[key], which had to be written as map?api.get(key) then).

Before 2.3.25 the standard solution was:

<#list user?keys as prop>
  ${prop} = ${user[prop]}
</#list>

However, some really old FreeMarker integrations use a strange configuration, where the public Map methods (like getClass) appear as keys. That happens as they are using a pure BeansWrapper (instead of DefaultObjectWrapper) whose simpleMapWrapper property was left on false. You should avoid such a setup, as it mixes the methods with real Map entries. But if you run into such unfortunate setup, the way to escape the situation is using the exposed Java methods, such as user.entrySet(), user.get(key), etc., and not using the template language constructs like ?keys or user[key].

"Exception has been thrown by the target of an invocation" error (mscorlib)

This is may have 2 reasons

1.I found the connection string error in my web.config file i had changed the connection string and its working.

  1. Connection string is proper then check with the control panel>services> SQL Server Browser > start or not