Programs & Examples On #Bulk email

how to make password textbox value visible when hover an icon

You will need to get the textbox via javascript when moving the mouse over it and change its type to text. And when moving it out, you will want to change it back to password. No chance of doing this in pure CSS.

HTML:

<input type="password" name="password" id="myPassword" size="30" />
<img src="theicon" onmouseover="mouseoverPass();" onmouseout="mouseoutPass();" />

JS:

function mouseoverPass(obj) {
  var obj = document.getElementById('myPassword');
  obj.type = "text";
}
function mouseoutPass(obj) {
  var obj = document.getElementById('myPassword');
  obj.type = "password";
}

How to get row count in sqlite using Android?

c.getCount() returns 1 because the cursor contains a single row (the one with the real COUNT(*)). The count you need is the int value of first row in cursor.

public int getTaskCount(long tasklist_Id) {

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor= db.rawQuery(
        "SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
         new String[] { String.valueOf(tasklist_Id) }
    );
    int count = 0;
    if(null != cursor)
        if(cursor.getCount() > 0){
          cursor.moveToFirst();    
          count = cursor.getInt(0);
        }
        cursor.close();
    }

    db.close();
    return count;
}   

Bootstrap alert in a fixed floating div at the top of page

You can use this class : class="sticky-top alert alert-dismissible"

Removing object properties with Lodash

You can use _.omit() for emitting the key from a JSON array if you have fewer objects:

_.forEach(data, (d) => {
    _.omit(d, ['keyToEmit1', 'keyToEmit2'])
});

If you have more objects, you can use the reverse of it which is _.pick():

_.forEach(data, (d) => {
    _.pick(d, ['keyToPick1', 'keyToPick2'])
});

Origin null is not allowed by Access-Control-Allow-Origin

I was looking for an solution to make an XHR request to a server from a local html file and found a solution using Chrome and PHP. (no Jquery)

Javascripts:

var x = new XMLHttpRequest(); 
if(x) x.onreadystatechange=function(){ 
    if (x.readyState === 4 && x.status===200){
        console.log(x.responseText); //Success
    }else{ 
        console.log(x); //Failed
    }
};
x.open(GET, 'http://example.com/', true);
x.withCredentials = true;
x.send();

My Chrome's request header Origin: null

My PHP response header (Note that 'null' is a string). HTTP_REFERER allow cross-origin from a remote server to another.

header('Access-Control-Allow-Origin: '.(trim($_SERVER['HTTP_REFERER'],'/')?:'null'),true);
header('Access-Control-Allow-Credentials:true',true);

I was able to successfully connect to my server. You can disregards the Credentials headers, but this works for me with Apache's AuthType Basic enabled

I tested compatibility with FF and Opera, It works in many cases such as:

From a VM LAN IP (192.168.0.x) back to the VM'S WAN (public) IP:port
From a VM LAN IP back to a remote server domain name.
From a local .HTML file to the VM LAN IP and/or VM WAN IP:port,
From a local .HTML file to a remote server domain name.
And so on.

Browser back button handling

You can also add hash when page is loading:

location.hash = "noBack";

Then just handle location hash change to add another hash:

$(window).on('hashchange', function() {
    location.hash = "noBack";
});

That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.

How to get time difference in minutes in PHP

My solution to find the difference between two dates is here. With this function you can find differences like seconds, minutes, hours, days, years and months.

function alihan_diff_dates($date = null, $diff = "minutes") {
 $start_date = new DateTime($date);
 $since_start = $start_date->diff(new DateTime( date('Y-m-d H:i:s') )); // date now
 print_r($since_start);
 switch ($diff) {
    case 'seconds':
        return $since_start->s;
        break;
    case 'minutes':
        return $since_start->i;
        break;
    case 'hours':
        return $since_start->h;
        break;
    case 'days':
        return $since_start->d;
        break;      
    default:
        # code...
        break;
 }
}

You can develop this function. I tested and works for me. DateInterval object output is here:

/*
DateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 0 [i] => 5 [s] => 13 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 0 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 ) 
*/

Function Usage:

$date = the past date, $diff = type eg: "minutes", "days", "seconds"

$diff_mins = alihan_diff_dates("2019-03-24 13:24:19", "minutes");

Good Luck.

java collections - keyset() vs entrySet() in map

To make things simple , please note that every time you do itr2.next() the pointer moves to the next element i.e. here if you notice carefully, then the output is perfectly fine according to the logic you have written .
This may help you in understanding better:

1st Iteration of While loop(pointer is before the 1st element):
Key: if ,value: 2 {itr2.next()=if; m.get(itr2.next()=it)=>2}

2nd Iteration of While loop(pointer is before the 3rd element):
Key: is ,value: 2 {itr2.next()=is; m.get(itr2.next()=to)=>2}

3rd Iteration of While loop(pointer is before the 5th element):
Key: be ,value: 1 {itr2.next()="be"; m.get(itr2.next()="up")=>"1"}

4th Iteration of While loop(pointer is before the 7th element):
Key: me ,value: 1 {itr2.next()="me"; m.get(itr2.next()="delegate")=>"1"}

Key: if ,value: 1
Key: it ,value: 2
Key: is ,value: 2
Key: to ,value: 2
Key: be ,value: 1
Key: up ,value: 1
Key: me ,value: 1
Key: delegate ,value: 1

It prints:

Key: if ,value: 2
Key: is ,value: 2
Key: be ,value: 1
Key: me ,value: 1

How can I determine whether a specific file is open in Windows?

Use Process Explorer from the Sysinternals Suite, the Find Handle or DLL function will let you search for the process with that file open.

Why doesn't Java offer operator overloading?

There are a lot of posts complaining about operator overloading.

I felt I had to clarify the "operator overloading" concepts, offering an alternative viewpoint on this concept.

#Code obfuscating?

This argument is a fallacy.

##Obfuscating is possible in all languages...

It is as easy to obfuscate code in C or Java through functions/methods as it is in C++ through operator overloads:

// C++
T operator + (const T & a, const T & b) // add ?
{
   T c ;
   c.value = a.value - b.value ; // subtract !!!
   return c ;
}

// Java
static T add (T a, T b) // add ?
{
   T c = new T() ;
   c.value = a.value - b.value ; // subtract !!!
   return c ;
}

/* C */
T add (T a, T b) /* add ? */
{
   T c ;
   c.value = a.value - b.value ; /* subtract !!! */
   return c ;
}

##...Even in Java's standard interfaces

For another example, let's see the Cloneable interface in Java:

You are supposed to clone the object implementing this interface. But you could lie. And create a different object. In fact, this interface is so weak you could return another type of object altogether, just for the fun of it:

class MySincereHandShake implements Cloneable
{
    public Object clone()
    {
       return new MyVengefulKickInYourHead() ;
    }
}

As the Cloneable interface can be abused/obfuscated, should it be banned on the same grounds C++ operator overloading is supposed to be?

We could overload the toString() method of a MyComplexNumber class to have it return the stringified hour of the day. Should the toString() overloading be banned, too? We could sabotage MyComplexNumber.equals to have it return a random value, modify the operands... etc. etc. etc..

In Java, as in C++, or whatever language, the programmer must respect a minimum of semantics when writing code. This means implementing a add function that adds, and Cloneable implementation method that clones, and a ++ operator than increments.

#What's obfuscating anyway?

Now that we know that code can be sabotaged even through the pristine Java methods, we can ask ourselves about the real use of operator overloading in C++?

##Clear and natural notation: methods vs. operator overloading?

We'll compare below, for different cases, the "same" code in Java and C++, to have an idea of which kind of coding style is clearer.

###Natural comparisons:

// C++ comparison for built-ins and user-defined types
bool    isEqual          = A == B ;
bool    isNotEqual       = A != B ;
bool    isLesser         = A <  B ;
bool    isLesserOrEqual  = A <= B ;

// Java comparison for user-defined types
boolean isEqual          = A.equals(B) ;
boolean isNotEqual       = ! A.equals(B) ;
boolean isLesser         = A.comparesTo(B) < 0 ;
boolean isLesserOrEqual  = A.comparesTo(B) <= 0 ;

Please note that A and B could be of any type in C++, as long as the operator overloads are provided. In Java, when A and B are not primitives, the code can become very confusing, even for primitive-like objects (BigInteger, etc.)...

###Natural array/container accessors and subscripting:

// C++ container accessors, more natural
value        = myArray[25] ;         // subscript operator
value        = myVector[25] ;        // subscript operator
value        = myString[25] ;        // subscript operator
value        = myMap["25"] ;         // subscript operator
myArray[25]  = value ;               // subscript operator
myVector[25] = value ;               // subscript operator
myString[25] = value ;               // subscript operator
myMap["25"]  = value ;               // subscript operator

// Java container accessors, each one has its special notation
value        = myArray[25] ;         // subscript operator
value        = myVector.get(25) ;    // method get
value        = myString.charAt(25) ; // method charAt
value        = myMap.get("25") ;     // method get
myArray[25]  = value ;               // subscript operator
myVector.set(25, value) ;            // method set
myMap.put("25", value) ;             // method put

In Java, we see that for each container to do the same thing (access its content through an index or identifier), we have a different way to do it, which is confusing.

In C++, each container uses the same way to access its content, thanks to operator overloading.

###Natural advanced types manipulation

The examples below use a Matrix object, found using the first links found on Google for "Java Matrix object" and "C++ Matrix object":

// C++ YMatrix matrix implementation on CodeProject
// http://www.codeproject.com/KB/architecture/ymatrix.aspx
// A, B, C, D, E, F are Matrix objects;
E =  A * (B / 2) ;
E += (A - B) * (C + D) ;
F =  E ;                  // deep copy of the matrix

// Java JAMA matrix implementation (seriously...)
// http://math.nist.gov/javanumerics/jama/doc/
// A, B, C, D, E, F are Matrix objects;
E = A.times(B.times(0.5)) ;
E.plusEquals(A.minus(B).times(C.plus(D))) ;
F = E.copy() ;            // deep copy of the matrix

And this is not limited to matrices. The BigInteger and BigDecimal classes of Java suffer from the same confusing verbosity, whereas their equivalents in C++ are as clear as built-in types.

###Natural iterators:

// C++ Random Access iterators
++it ;                  // move to the next item
--it ;                  // move to the previous item
it += 5 ;               // move to the next 5th item (random access)
value = *it ;           // gets the value of the current item
*it = 3.1415 ;          // sets the value 3.1415 to the current item
(*it).foo() ;           // call method foo() of the current item

// Java ListIterator<E> "bi-directional" iterators
value = it.next() ;     // move to the next item & return the value
value = it.previous() ; // move to the previous item & return the value
it.set(3.1415) ;        // sets the value 3.1415 to the current item

###Natural functors:

// C++ Functors
myFunctorObject("Hello World", 42) ;

// Java Functors ???
myFunctorObject.execute("Hello World", 42) ;

###Text concatenation:

// C++ stream handling (with the << operator)
                    stringStream   << "Hello " << 25 << " World" ;
                    fileStream     << "Hello " << 25 << " World" ;
                    outputStream   << "Hello " << 25 << " World" ;
                    networkStream  << "Hello " << 25 << " World" ;
anythingThatOverloadsShiftOperator << "Hello " << 25 << " World" ;

// Java concatenation
myStringBuffer.append("Hello ").append(25).append(" World") ;

Ok, in Java you can use MyString = "Hello " + 25 + " World" ; too... But, wait a second: This is operator overloading, isn't it? Isn't it cheating???

:-D

##Generic code?

The same generic code modifying operands should be usable both for built-ins/primitives (which have no interfaces in Java), standard objects (which could not have the right interface), and user-defined objects.

For example, calculating the average value of two values of arbitrary types:

// C++ primitive/advanced types
template<typename T>
T getAverage(const T & p_lhs, const T & p_rhs)
{
   return (p_lhs + p_rhs) / 2 ;
}

int     intValue     = getAverage(25, 42) ;
double  doubleValue  = getAverage(25.25, 42.42) ;
complex complexValue = getAverage(cA, cB) ; // cA, cB are complex
Matrix  matrixValue  = getAverage(mA, mB) ; // mA, mB are Matrix

// Java primitive/advanced types
// It won't really work in Java, even with generics. Sorry.

#Discussing operator overloading

Now that we have seen fair comparisons between C++ code using operator overloading, and the same code in Java, we can now discuss "operator overloading" as a concept.

##Operator overloading existed since before computers

Even outside of computer science, there is operator overloading: For example, in mathematics, operators like +, -, *, etc. are overloaded.

Indeed, the signification of +, -, *, etc. changes depending on the types of the operands (numerics, vectors, quantum wave functions, matrices, etc.).

Most of us, as part of our science courses, learned multiple significations for operators, depending on the types of the operands. Did we find them confusing, them?

##Operator overloading depends on its operands

This is the most important part of operator overloading: Like in mathematics, or in physics, the operation depends on its operands' types.

So, know the type of the operand, and you will know the effect of the operation.

##Even C and Java have (hard-coded) operator overloading

In C, the real behavior of an operator will change according to its operands. For example, adding two integers is different than adding two doubles, or even one integer and one double. There is even the whole pointer arithmetic domain (without casting, you can add to a pointer an integer, but you cannot add two pointers...).

In Java, there is no pointer arithmetic, but someone still found string concatenation without the + operator would be ridiculous enough to justify an exception in the "operator overloading is evil" creed.

It's just that you, as a C (for historical reasons) or Java (for personal reasons, see below) coder, you can't provide your own.

##In C++, operator overloading is not optional...

In C++, operator overloading for built-in types is not possible (and this is a good thing), but user-defined types can have user-defined operator overloads.

As already said earlier, in C++, and to the contrary to Java, user-types are not considered second-class citizens of the language, when compared to built-in types. So, if built-in types have operators, user types should be able to have them, too.

The truth is that, like the toString(), clone(), equals() methods are for Java (i.e. quasi-standard-like), C++ operator overloading is so much part of C++ that it becomes as natural as the original C operators, or the before mentioned Java methods.

Combined with template programming, operator overloading becomes a well known design pattern. In fact, you cannot go very far in STL without using overloaded operators, and overloading operators for your own class.

##...but it should not be abused

Operator overloading should strive to respect the semantics of the operator. Do not subtract in a + operator (as in "do not subtract in a add function", or "return crap in a clone method").

Cast overloading can be very dangerous because they can lead to ambiguities. So they should really be reserved for well defined cases. As for && and ||, do not ever overload them unless you really know what you're doing, as you'll lose the the short circuit evaluation that the native operators && and || enjoy.

#So... Ok... Then why it is not possible in Java?

Because James Gosling said so:

I left out operator overloading as a fairly personal choice because I had seen too many people abuse it in C++.

James Gosling. Source: http://www.gotw.ca/publications/c_family_interview.htm

Please compare Gosling's text above with Stroustrup's below:

Many C++ design decisions have their roots in my dislike for forcing people to do things in some particular way [...] Often, I was tempted to outlaw a feature I personally disliked, I refrained from doing so because I did not think I had the right to force my views on others.

Bjarne Stroustrup. Source: The Design and Evolution of C++ (1.3 General Background)

##Would operator overloading benefit Java?

Some objects would greatly benefit from operator overloading (concrete or numerical types, like BigDecimal, complex numbers, matrices, containers, iterators, comparators, parsers etc.).

In C++, you can profit from this benefit because of Stroustrup's humility. In Java, you're simply screwed because of Gosling's personal choice.

##Could it be added to Java?

The reasons for not adding operator overloading now in Java could be a mix of internal politics, allergy to the feature, distrust of developers (you know, the saboteur ones that seem to haunt Java teams...), compatibility with the previous JVMs, time to write a correct specification, etc..

So don't hold your breath waiting for this feature...

##But they do it in C#!!!

Yeah...

While this is far from being the only difference between the two languages, this one never fails to amuse me.

Apparently, the C# folks, with their "every primitive is a struct, and a struct derives from Object", got it right at first try.

##And they do it in other languages!!!

Despite all the FUD against used defined operator overloading, the following languages support it: Kotlin, Scala, Dart, Python, F#, C#, D, Algol 68, Smalltalk, Groovy, Perl 6, C++, Ruby, Haskell, MATLAB, Eiffel, Lua, Clojure, Fortran 90, Swift, Ada, Delphi 2005...

So many languages, with so many different (and sometimes opposing) philosophies, and yet they all agree on that point.

Food for thought...

bind/unbind service example (android)

Add these methods to your Activity:

private MyService myServiceBinder;
public ServiceConnection myConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className, IBinder binder) {
        myServiceBinder = ((MyService.MyBinder) binder).getService();
        Log.d("ServiceConnection","connected");
        showServiceData();
    }

    public void onServiceDisconnected(ComponentName className) {
        Log.d("ServiceConnection","disconnected");
        myService = null;
    }
};

public Handler myHandler = new Handler() {
    public void handleMessage(Message message) {
        Bundle data = message.getData();
    }
};

public void doBindService() {
    Intent intent = null;
    intent = new Intent(this, BTService.class);
    // Create a new Messenger for the communication back
    // From the Service to the Activity
    Messenger messenger = new Messenger(myHandler);
    intent.putExtra("MESSENGER", messenger);

    bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
}

And you can bind to service by ovverriding onResume(), and onPause() at your Activity class.

@Override
protected void onResume() {

    Log.d("activity", "onResume");
    if (myService == null) {
        doBindService();
    }
    super.onResume();
}

@Override
protected void onPause() {
    //FIXME put back

    Log.d("activity", "onPause");
    if (myService != null) {
        unbindService(myConnection);
        myService = null;
    }
    super.onPause();
}

Note, that when binding to a service only the onCreate() method is called in the service class. In your Service class you need to define the myBinder method:

private final IBinder mBinder = new MyBinder();
private Messenger outMessenger;

@Override
public IBinder onBind(Intent arg0) {
    Bundle extras = arg0.getExtras();
    Log.d("service","onBind");
    // Get messager from the Activity
    if (extras != null) {
        Log.d("service","onBind with extra");
        outMessenger = (Messenger) extras.get("MESSENGER");
    }
    return mBinder;
}

public class MyBinder extends Binder {
    MyService getService() {
        return MyService.this;
    }
}

After you defined these methods you can reach the methods of your service at your Activity:

private void showServiceData() {  
    myServiceBinder.myMethod();
}

and finally you can start your service when some event occurs like _BOOT_COMPLETED_

public class MyReciever  extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals("android.intent.action.BOOT_COMPLETED")) {
            Intent service = new Intent(context, myService.class);
            context.startService(service);
        }
    }
}

note that when starting a service the onCreate() and onStartCommand() is called in service class and you can stop your service when another event occurs by stopService() note that your event listener should be registerd in your Android manifest file:

<receiver android:name="MyReciever" android:enabled="true" android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
</receiver>

Convert Enum to String

I don't know what the "preferred" method is (ask 100 people and get 100 different opinions) but do what's simplest and what works. GetName works but requires a lot more keystrokes. ToString() seems to do the job very well.

CSS ''background-color" attribute not working on checkbox inside <div>

A checkbox does not have background color.

But to add the effect, you may wrap each checkbox with a div that has color:

<div class="evenRow">
    <input type="checkbox" />
</div>
<div class="oddRow">
    <input type="checkbox" />
</div>
<div class="evenRow">
    <input type="checkbox" />
</div>
<div class="oddRow">
    <input type="checkbox" />
</div>

'NOT LIKE' in an SQL query

You need to specify the column in both expressions.

SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'

How to show form input fields based on select value?

You have to use val() instead of value() and you have missed starting quote id=dbType" should be id="dbType"

Live Demo

Change

selection = $('this').value();

To

selection = $(this).val();

or

selection = this.value;

IE6/IE7 css border on select element

You'd need a custom-designed select box with CSS and JavaScript. You'd need to make absolutely sure it degrades perfectly to a standard select element should a user have JavaScript disabled.

IMO, it's just not worth the effort. Stick with font stylings within the select to make it close to your site's design; leave the borders, etc., to the box elements.

What is the difference between JavaScript and ECMAScript?

I doubt we'd ever use the word "ECMAScript" if not for the fact that the name "JavaScript" is owned by Sun. For all intents and purposes, the language is JavaScript. You don't go to the bookstore looking for ECMAScript books, do you?

It's a bit too simple to say that "JavaScript" is the implementation. JScript is Microsoft's implementation.

Jquery button click() function is not working

After making the id unique across the document ,You have to use event delegation

$("#container").on("click", "buttonid", function () {
  alert("Hi");
});

Why boolean in Java takes only true or false? Why not 1 or 0 also?

One thing that other answers haven't pointed out is that one advantage of not treating integers as truth values is that it avoids this C / C++ bug syndrome:

int i = 0;
if (i = 1) {
    print("the sky is falling!\n");
} 

In C / C++, the mistaken use of = rather than == causes the condition to unexpectedly evaluate to "true" and update i as an accidental side-effect.

In Java, that is a compilation error, because the value of the assigment i = 1 has type int and a boolean is required at that point. The only case where you'd get into trouble in Java is if you write lame code like this:

boolean ok = false;
if (ok = true) {  // bug and lame style
    print("the sky is falling!\n");
}

... which anyone with an ounce of "good taste" would write as ...

boolean ok = false;
if (ok) {
    print("the sky is falling!\n");
}

Dependency injection with Jersey 2.0

You need to define an AbstractBinder and register it in your JAX-RS application. The binder specifies how the dependency injection should create your classes.

public class MyApplicationBinder extends AbstractBinder {
    @Override
    protected void configure() {
        bind(MyService.class).to(MyService.class);
    }
}

When @Inject is detected on a parameter or field of type MyService.class it is instantiated using the class MyService. To use this binder, it need to be registered with the JAX-RS application. In your web.xml, define a JAX-RS application like this:

<servlet>
  <servlet-name>MyApplication</servlet-name>
  <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
  <init-param>
    <param-name>javax.ws.rs.Application</param-name>
    <param-value>com.mypackage.MyApplication</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>MyApplication</servlet-name>
  <url-pattern>/*</url-pattern>
</servlet-mapping>

Implement the MyApplication class (specified above in the init-param).

public class MyApplication extends ResourceConfig {
    public MyApplication() {
        register(new MyApplicationBinder());
        packages(true, "com.mypackage.rest");
    }
}

The binder specifying dependency injection is registered in the constructor of the class, and we also tell the application where to find the REST resources (in your case, MyResource) using the packages() method call.

Java out.println() how is this possible?

Or simply:

System.out.println("Some text");

Setting a minimum/maximum character count for any character using a regular expression

If you also want to match newlines, then you might want to use "^[\s\S]{1,35}$" (depending on the regex engine). Otherwise, as others have said, you should used "^.{1,35}$"

AngularJS - Animate ng-view transitions

Angularjs 1.1.4 has now introduced the ng-animate directive to help animating different elements, in particular ng-view.

You can also watch the video about this new featue

UPDATE as of angularjs 1.2, the way animations work has changed drastically, most of it is now controlled with CSS, without having to setup javascript callbacks, etc.. You can check the updated tutorial on Year Of Moo. @dfsq pointed out in the comments a nice set of examples.

How to get the device's IMEI/ESN programmatically in android?

Kotlin Code for getting DeviceId ( IMEI ) with handling permission & comparability check for all android versions :

 val  telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
        == PackageManager.PERMISSION_GRANTED) {
        // Permission is  granted
        val imei : String? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)  telephonyManager.imei
        // older OS  versions
        else  telephonyManager.deviceId

        imei?.let {
            Log.i("Log", "DeviceId=$it" )
        }

    } else {  // Permission is not granted

    }

Also add this permission to AndroidManifest.xml :

<uses-permission android:name="android.permission.READ_PHONE_STATE"/> <!-- IMEI-->

Error: getaddrinfo ENOTFOUND in nodejs for get call

for me it was because in /etc/hosts file the hostname is not added

javax.faces.application.ViewExpiredException: View could not be restored

Please add this line in your web.xml It works for me

<context-param>
        <param-name>org.ajax4jsf.handleViewExpiredOnClient</param-name> 
        <param-value>true</param-value>     
    </context-param>

Fatal error: Call to undefined function pg_connect()

On Gentoo, use USE flag postgres in /etc/portage/make.conf and re emerge "emerge php"

How can I add items to an empty set in python

>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>

What you've made is a dictionary and not a Set.

The update method in dictionary is used to update the new dictionary from a previous one, like so,

>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}

Whereas in sets, it is used to add elements to the set.

>>> D.update([1, 2])
>>> D
set([1, 2])

No server in Eclipse; trying to install Tomcat

You have probably installed Eclipse for Java Developers instead of Eclipse IDE for Enterprise Java Developers, server tab and some other are not available.

You don't have to uninstall. Just rerun eclipse-inst-win64.exe and choose Java EE IDE

JAVA EE IDE Installation

How to bind Close command to a button

One option that I've found to work is to set this function up as a Behavior.

The Behavior:

    public class WindowCloseBehavior : Behavior<Window>
{
    public bool Close
    {
        get { return (bool) GetValue(CloseTriggerProperty); }
        set { SetValue(CloseTriggerProperty, value); }
    }

    public static readonly DependencyProperty CloseTriggerProperty =
        DependencyProperty.Register("Close", typeof(bool), typeof(WindowCloseBehavior),
            new PropertyMetadata(false, OnCloseTriggerChanged));

    private static void OnCloseTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var behavior = d as WindowCloseBehavior;

        if (behavior != null)
        {
            behavior.OnCloseTriggerChanged();
        }
    }

    private void OnCloseTriggerChanged()
    {
        // when closetrigger is true, close the window
        if (this.Close)
        {
            this.AssociatedObject.Close();
        }
    }
}

On the XAML Window, you set up a reference to it and bind the Behavior's Close property to a Boolean "Close" property on your ViewModel:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
<i:Interaction.Behaviors>
    <behavior:WindowCloseBehavior Close="{Binding Close}" />
</i:Interaction.Behaviors>

So, from the View assign an ICommand to change the Close property on the ViewModel which is bound to the Behavior's Close property. When the PropertyChanged event is fired the Behavior fires the OnCloseTriggerChanged event and closes the AssociatedObject... which is the Window.

How to use this boolean in an if statement?

if(stop == true)

or

if(stop)

= is for assignment.

== is for checking condition.

if(stop = true) 

It will assign true to stop and evaluates if(true). So it will always execute the code inside if because stop will always being assigned with true.

Regex empty string or email

this will solve, it will accept empty string or exact an email id

"^$|^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"

Add external libraries to CMakeList.txt c++

I would start with upgrade of CMAKE version.

You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)

note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

Order by in Inner Join

SQL doesn't return any ordering by default because it's faster this way. It doesn't have to go through your data first and then decide what to do.

You need to add an order by clause, and probably order by which ever ID you expect. (There's a duplicate of names, thus I'd assume you want One.ID)

select * From one
inner join two
ON one.one_name = two.one_name
ORDER BY one.ID

how to use List<WebElement> webdriver

List<WebElement> myElements = driver.findElements(By.xpath("some/path//a"));
        System.out.println("Size of List: "+myElements.size());
        for(WebElement e : myElements) 
        {        
            System.out.print("Text within the Anchor tab"+e.getText()+"\t");
            System.out.println("Anchor: "+e.getAttribute("href"));
        }

//NOTE: "//a" will give you all the anchors there on after the point your XPATH has reached.

How to pass form input value to php function

This is pretty basic, just put in the php file you want to use for processing in the element.

For example

<form action="process.php" method="post">

Then in process.php you would get the form values using $_POST['name of the variable]

Create a tag in a GitHub repository

It all depends what type of tag you want to create:

  • If you want to create Annotated tags, to show extra metadata, you can do it in the following way: git tag -a v1.0.0.
  • On the other hand, Lightweight tags are used to "bookmark" your commits for private use: git tag v1.0.0.

There are a few other tag functionalities such as:

  • Listing tags - git tag -l -n3. The command lists all existing tags with maximum 3 lines of their tag message. By default -n only shows the first line.
  • Tag details - git show <tag_identifier>. It shows all you need to know about a specific tag.
  • Sorting tags - git tag --sort=<type>
  • Publishing tags - git push origin v1.0. You can git push the tag individually, or you can run git push --tags which will push all tags at once.

Be sure to check this tag related article for more relevant information.

Weird PHP error: 'Can't use function return value in write context'

The problem is in the () you have to go []

if (isset($_POST('sms_code') == TRUE)

by

if (isset($_POST['sms_code'] == TRUE)

Has an event handler already been added?

i agree with alf's answer,but little modification to it is,, to use,

           try
            {
                control_name.Click -= event_Click;
                main_browser.Document.Click += Document_Click;
            }
            catch(Exception exce)
            {
                main_browser.Document.Click += Document_Click;
            }

Can I do Model->where('id', ARRAY) multiple where conditions?

WHERE AND SELECT Condition In Array Format Laravel

use DB;

$conditions = array(
    array('email', '=', '[email protected]')
);
$selected = array('id','name','email','mobile','created');
$result = DB::table('users')->select($selected)->where($conditions)->get();

Add two textbox values and display the sum in a third textbox automatically

i didn't find who made elegant answer , that's why let me say :

Array.from(
   document.querySelectorAll('#txt1,#txt2')
).map(e => parseInt(e.value) || 0) // to avoid NaN
.reduce((a, b) => a+b, 0)

_x000D_
_x000D_
window.sum= () => _x000D_
 document.getElementById('result').innerHTML=    _x000D_
   Array.from(_x000D_
     document.querySelectorAll('#txt1,#txt2')_x000D_
   ).map(e=>parseInt(e.value)||0)_x000D_
   .reduce((a,b)=>a+b,0)
_x000D_
<input type="text" id="txt1" onkeyup="sum()"/>_x000D_
<input type="text" id="txt2" onkeyup="sum()"  style="margin-right:10px;"/><span id="result"></span>
_x000D_
_x000D_
_x000D_

Get index of a row of a pandas dataframe as an integer

The nature of wanting to include the row where A == 5 and all rows upto but not including the row where A == 8 means we will end up using iloc (loc includes both ends of slice).

In order to get the index labels we use idxmax. This will return the first position of the maximum value. I run this on a boolean series where A == 5 (then when A == 8) which returns the index value of when A == 5 first happens (same thing for A == 8).

Then I use searchsorted to find the ordinal position of where the index label (that I found above) occurs. This is what I use in iloc.

i5, i8 = df.index.searchsorted([df.A.eq(5).idxmax(), df.A.eq(8).idxmax()])
df.iloc[i5:i8]

enter image description here


numpy

you can further enhance this by using the underlying numpy objects the analogous numpy functions. I wrapped it up into a handy function.

def find_between(df, col, v1, v2):
    vals = df[col].values
    mx1, mx2 = (vals == v1).argmax(), (vals == v2).argmax()
    idx = df.index.values
    i1, i2 = idx.searchsorted([mx1, mx2])
    return df.iloc[i1:i2]

find_between(df, 'A', 5, 8)

enter image description here


timing
enter image description here

In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda?

Map<String, Integer> map = new HashMap<>();
map.put("test1", 1);
map.put("test2", 2);

Map<String, Integer> map2 = new HashMap<>();
map.forEach(map2::put);

System.out.println("map: " + map);
System.out.println("map2: " + map2);
// Output:
// map:  {test2=2, test1=1}
// map2: {test2=2, test1=1}

You can use the forEach method to do what you want.

What you're doing there is:

map.forEach(new BiConsumer<String, Integer>() {
    @Override
    public void accept(String s, Integer integer) {
        map2.put(s, integer);     
    }
});

Which we can simplify into a lambda:

map.forEach((s, integer) ->  map2.put(s, integer));

And because we're just calling an existing method we can use a method reference, which gives us:

map.forEach(map2::put);

Set Canvas size using javascript

Try this:

var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
xS = w.innerWidth || e.clientWidth || g.clientWidth,
yS = w.innerHeight|| e.clientHeight|| g.clientHeight;
alert(xS + ' × ' + yS);

document.write('')

works for iframe and well.

Disable form auto submit on button click

Buttons like <button>Click to do something</button> are submit buttons.

Set type="button" to change that. type="submit" is the default (as specified by the HTML recommendation).

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

Doing it in one bulk read:

import re

textfile = open(filename, 'r')
filetext = textfile.read()
textfile.close()
matches = re.findall("(<(\d{4,5})>)?", filetext)

Line by line:

import re

textfile = open(filename, 'r')
matches = []
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
    matches += reg.findall(line)
textfile.close()

But again, the matches that returns will not be useful for anything except counting unless you added an offset counter:

import re

textfile = open(filename, 'r')
matches = []
offset = 0
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
    matches += [(reg.findall(line),offset)]
    offset += len(line)
textfile.close()

But it still just makes more sense to read the whole file in at once.

git ignore exception

Since Git 2.7.0 Git will take exceptions into account. From the official release notes:

  • Allow a later "!/abc/def" to override an earlier "/abc" that appears in the same .gitignore file to make it easier to express "everything in /abc directory is ignored, except for ...".

https://raw.githubusercontent.com/git/git/master/Documentation/RelNotes/2.7.0.txt

edit: apparently this doesn't work any more since Git 2.8.0

How to pass extra variables in URL with WordPress

To make the round trip "The WordPress Way" on the "front-end" (doesn't work in the context of wp-admin), you need to use 3 WordPress functions:

  • add_query_arg() - to create the URL with your new query variable ('c' in your example)
  • the query_vars filter - to modify the list of public query variables that WordPress knows about (this only works on the front-end, because the WP Query is not used on the back end - wp-admin - so this will also not be available in admin-ajax)
  • get_query_var() - to retrieve the value of your custom query variable passed in your URL.

Note: there's no need to even touch the superglobals ($_GET) if you do it this way.

Example

On the page where you need to create the link / set the query variable:

if it's a link back to this page, just adding the query variable

<a href="<?php echo esc_url( add_query_arg( 'c', $my_value_for_c ) )?>">

if it's a link to some other page

<a href="<?php echo esc_url( add_query_arg( 'c', $my_value_for_c, site_url( '/some_other_page/' ) ) )?>">

In your functions.php, or some plugin file or custom class (front-end only):

function add_custom_query_var( $vars ){
  $vars[] = "c";
  return $vars;
}
add_filter( 'query_vars', 'add_custom_query_var' );

On the page / function where you wish to retrieve and work with the query var set in your URL:

$my_c = get_query_var( 'c' );

On the Back End (wp-admin)

On the back end we don't ever run wp(), so the main WP Query does not get run. As a result, there are no query vars and the query_vars hook is not run.

In this case, you'll need to revert to the more standard approach of examining your $_GET superglobal. The best way to do this is probably:

$my_c = filter_input( INPUT_GET, "c", FILTER_SANITIZE_STRING );

though in a pinch you could do the tried and true

$my_c = isset( $_GET['c'] ? $_GET['c'] : "";

or some variant thereof.

How to use QueryPerformanceCounter?

Assuming you're on Windows (if so you should tag your question as such!), on this MSDN page you can find the source for a simple, useful HRTimer C++ class that wraps the needed system calls to do something very close to what you require (it would be easy to add a GetTicks() method to it, in particular, to do exactly what you require).

On non-Windows platforms, there's no QueryPerformanceCounter function, so the solution won't be directly portable. However, if you do wrap it in a class such as the above-mentioned HRTimer, it will be easier to change the class's implementation to use what the current platform is indeed able to offer (maybe via Boost or whatever!).

How to commit a change with both "message" and "description" from the command line?

git commit -a -m "Your commit message here"

will quickly commit all changes with the commit message. Git commit "title" and "description" (as you call them) are nothing more than just the first line, and the rest of the lines in the commit message, usually separated by a blank line, by convention. So using this command will just commit the "title" and no description.

If you want to commit a longer message, you can do that, but it depends on which shell you use.

In bash the quick way would be:

git commit -a -m $'Commit title\n\nRest of commit message...'

How do I repair an InnoDB table?

First of all stop the server and image the disc. There's no point only having one shot at this. Then take a look here.

Using reCAPTCHA on localhost

As per Google recaptcha documentation

localhost domains are no longer supported by default. If you wish to continue supporting them for development you can add them to the list of supported domains for your site key. Go to the admin console to update your list of supported domains. We advise to use a separate key for development and production and to not allow localhost on your production site key

argparse module How to add option without any argument?

As @Felix Kling suggested use action='store_true':

>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True

pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

I'm not sure if this is related, but I had a similar problem which was fixed by copying these files from Anaconda3/Library/bin to Anaconda3/DLLs :

libcrypto-1_1-x64.dll

libssl-1_1-x64.dll

Convert comma separated string to array in PL/SQL

declare
seprator varchar2(1):=',';
dosweeklist varchar2(4000):='a,b,c';
begin
for i in (SELECT  SUBSTR(dosweeklist,
                         case when level=1 then 1 else INSTR(dosweeklist,seprator,1,LEVEL-1)+1 end,
                         NVL(NULLIF(INSTR(dosweeklist,seprator,1,LEVEL),0),length(dosweeklist)+1) - case when level=1 then 1 else INSTR(dosweeklist,seprator,1,LEVEL-1)+1 end) dat 
          FROM dual
          CONNECT BY LEVEL <= LENGTH(dosweeklist) - LENGTH(REPLACE(dosweeklist,seprator,'')) +1)
loop
dbms_output.put_line(i.dat);
end loop;
end;
/

so select query only in for loop can do the trick, by replacing dosweeklist as your delimited string and seprator as your delimited character.

Lets see output

a

b

c

Already defined in .obj - no double inclusions

You probably don't want to do this:

#include "client.cpp"

A *.cpp file will have been compiled by the compiler as part of your build. By including it in other files, it will be compiled again (and again!) in every file in which you include it.

Now here's the thing: You are guarding it with #ifndef SOCKET_CLIENT_CLASS, however, each file that has #include "client.cpp" is built independently and as such will find SOCKET_CLIENT_CLASS not yet defined. Therefore it's contents will be included, not #ifdef'd out.

If it contains any definitions at all (rather than just declarations) then these definitions will be repeated in every file where it's included.

How can I use MS Visual Studio for Android Development?

Besides, you can use VS for Android development too, because in the end, the IDE is nothing but a fancy text editor with shortcuts to command line tools, so most popular IDE's can be used.

However, if you want to develop fully native without restrictions, you'll have all kinds of issues, such as those related to file system case insensitivity and missing libraries on Windows platform..

If you try to build windows mobile apps on Linux platform, you'll have bigger problems than other way around, but still makes most sense to use Linux with Eclipse for Android OS.

ERROR 1049 (42000): Unknown database 'mydatabasename'

when u import database from workbench or other method ,should be give same name as your dump to avoid this kind of error

Select row and element in awk

To expand on Dennis's answer, use awk's -v option to pass the i and j values:

# print the j'th field of the i'th line
awk -v i=5 -v j=3 'FNR == i {print $j}'

Regex match text between tags

Try

str.match(/<b>(.*?)<\/b>/g);

Entity Framework rollback and remove bad migration

For those using EF Core with ASP.NET Core v1.0.0 I had a similar problem and used the following commands to correct it (@DavidSopko's post pointed me in the right direction, but the details are slightly different for EF Core):

Update-Database <Name of last good migration>
Remove-Migration

For example, in my current development the command became

PM> Update-Database CreateInitialDatabase
Done.
PM> Remove-Migration
Done.
PM> 

The Remove-Migration will remove the last migration you applied. If you have a more complex scenario with multiple migrations to remove (I only had 2, the initial and the bad one), I suggest you test the steps in a dummy project.

There doesn't currently appear to be a Get-Migrations command in EF Core (v1.0.0) so you must look in your migrations folder and be familiar with what you have done. However, there is a nice help command:

PM> get-help entityframework

Refreshing dastabase in VS2015 SQL Server Object Explorer, all of my data was preserved and the migration that I wanted to revert was gone :)

Initially I tried Remove-Migration by itself and found the error command confusing:

System.InvalidOperationException: The migration '...' has already been applied to the database. Unapply it and try again. If the migration has been applied to other databases, consider reverting its changes using a new migration.

There are already suggestions on improving this wording, but I'd like the error to say something like this:

Run Update-Database (last good migration name) to revert the database schema back to to that state. This command will unapply all migrations that occurred after the migration specified to Update-Database. You may then run Remove-Migration (migration name to remove)

Output from the EF Core help command follows:

 PM> get-help entityframework
                     _/\__
               ---==/    \\
         ___  ___   |.    \|\
        | __|| __|  |  )   \\\
        | _| | _|   \_/ |  //|\\
        |___||_|       /   \\\/\\

TOPIC
    about_EntityFrameworkCore

SHORT DESCRIPTION
    Provides information about Entity Framework Core commands.

LONG DESCRIPTION
    This topic describes the Entity Framework Core commands. See https://docs.efproject.net for information on Entity Framework Core.

    The following Entity Framework cmdlets are included.

        Cmdlet                      Description
        --------------------------  ---------------------------------------------------
        Add-Migration               Adds a new migration.

        Remove-Migration            Removes the last migration.

        Scaffold-DbContext          Scaffolds a DbContext and entity type classes for a specified database.

        Script-Migration            Generates a SQL script from migrations.

        Update-Database             Updates the database to a specified migration.

        Use-DbContext               Sets the default DbContext to use.

SEE ALSO
    Add-Migration
    Remove-Migration
    Scaffold-DbContext
    Script-Migration
    Update-Database
    Use-DbContext

How can I debug what is causing a connection refused or a connection time out?

The problem

The problem is in the network layer. Here are the status codes explained:

  • Connection refused: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.

  • Connection timed out: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.

In context

That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.

Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.

It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.

Debugging this

As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.

To rule out network congestion as a problem you could use a tool like mtr or traceroute or even ping to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.

Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).

If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp is definetly recommended then.

How to check if variable is array?... or something array-like

Since PHP 7.1 there is a pseudo-type iterable for exactly this purpose. Type-hinting iterable accepts any array as well as any implementation of the Traversable interface. PHP 7.1 also introduced the function is_iterable(). For older versions, see other answers here for accomplishing the equivalent type enforcement without the newer built-in features.

Fair play: As BlackHole pointed out, this question appears to be a duplicate of Iterable objects and array type hinting? and his or her answer goes into further detail than mine.

What algorithms compute directions from point A to point B on a map?

Here's the world's fastest routing algorithms compared and proven for correctness:

http://algo2.iti.uka.de/schultes/hwy/schultes_diss.pdf

Here's a google tech talk on the subject:

http://www.youtube.com/watch?v=-0ErpE8tQbw

Here's a implementation of the highway-hierarchies algorithm as discussed by schultes (currently in berlin only, I'm writing the interface and a mobile version is being developed as well):

http://tom.mapsforge.org/

How can I clone a private GitLab repository?

You might need a ~/.ssh/config:

Host gitlab.YOURDOMAIN.DOMAIN
    Port 1111
    IdentityFile ~/.ssh/id_rsa

and then you can use git clone git@DOMAINandREPOSITORY. This means you always use the user git.

How to get the Google Map based on Latitude on Longitude?

Firstly add a div with id.

<div id="my_map_add" style="width:100%;height:300px;"></div>

<script type="text/javascript">
function my_map_add() {
var myMapCenter = new google.maps.LatLng(28.5383866, 77.34916609);
var myMapProp = {center:myMapCenter, zoom:12, scrollwheel:false, draggable:false, mapTypeId:google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("my_map_add"),myMapProp);
var marker = new google.maps.Marker({position:myMapCenter});
marker.setMap(map);
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=your_key&callback=my_map_add"></script>

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

View array in Visual Studio debugger?

Are you trying to view an array with memory allocated dynamically? If not, you can view an array for C++ and C# by putting it in the watch window in the debugger, with its contents visible when you expand the array on the little (+) in the watch window by a left mouse-click.

If it's a pointer to a dynamically allocated array, to view N contents of the pointer, type "pointer, N" in the watch window of the debugger. Note, N must be an integer or the debugger will give you an error saying it can't access the contents. Then, left click on the little (+) icon that appears to view the contents.

Call An Asynchronous Javascript Function Synchronously

Take a look at JQuery Promises:

http://api.jquery.com/promise/

http://api.jquery.com/jQuery.when/

http://api.jquery.com/deferred.promise/

Refactor the code:


    var dfd = new jQuery.Deferred();


    function callBack(data) {
       dfd.notify(data);
    }

    // do the async call.
    myAsynchronousCall(param1, callBack);

    function doSomething(data) {
     // do stuff with data...
    }

    $.when(dfd).then(doSomething);


Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return k1.zip(k2, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];
       }
     }).all();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...

MySQL wait_timeout Variable - GLOBAL vs SESSION

SHOW SESSION VARIABLES LIKE "wait_timeout"; -- 28800
SHOW GLOBAL VARIABLES LIKE "wait_timeout"; -- 28800

At first, wait_timeout = 28800 which is the default value. To change the session value, you need to set the global variable because the session variable is read-only.

SET @@GLOBAL.wait_timeout=300

After you set the global variable, the session variable automatically grabs the value.

SHOW SESSION VARIABLES LIKE "wait_timeout"; -- 300
SHOW GLOBAL VARIABLES LIKE "wait_timeout"; -- 300

Next time when the server restarts, the session variables will be set to the default value i.e. 28800.

P.S. I m using MySQL 5.6.16

Android change SDK version in Eclipse? Unable to resolve target android-x

This can happen when you mistakenly import an Android project into your Eclipse workspace as a Java project. The solution in this case: delete the project from the workspace in the Package Explorer, then go to File -> Import -> Android -> Existing Android code into workspace.

How to use JavaScript to change div backgroundColor

This one might be a bit weird because I am really not a serious programmer and I am discovering things in programming the way penicillin was invented - sheer accident. So how to change an element on mouseover? Use the :hover attribute just like with a elements.

Example:

div.classname:hover
{
    background-color: black;
}

This changes any div with the class classname to have a black background on mousover. You can basically change any attribute. Tested in IE and Firefox

Happy programming!

How do I list all loaded assemblies?

Using Visual Studio

  1. Attach a debugger to the process (e.g. start with debugging or Debug > Attach to process)
  2. While debugging, show the Modules window (Debug > Windows > Modules)

This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).

enter image description here

Using Process Explorer

If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)

Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.

Programmatically

Check this SO question that explains how to do it.

Disable building workspace process in Eclipse

Building workspace is about incremental build of any evolution detected in one of the opened projects in the currently used workspace.

You can also disable it through the menu "Project / Build automatically".

But I would recommend first to check:

  • if a Project Clean all / Build result in the same kind of long wait (after disabling this option)
  • if you have (this time with building automatically activated) some validation options you could disable to see if they have an influence on the global compilation time (Preferences / Validations, or Preferences / XML / ... if you have WTP installed)
  • if a fresh eclipse installation referencing the same workspace (see this eclipse.ini for more) results in the same issue (with building automatically activated)

Note that bug 329657 (open in 2011, in progress in 2014) is about interrupting a (too lengthy) build, instead of cancelling it:

There is an important difference between build interrupt and cancel.

  • When a build is cancelled, it typically handles this by discarding incremental build state and letting the next build be a full rebuild. This can be quite expensive in some projects.
    As a user I think I would rather wait for the 5 second incremental build to finish rather than cancel and result in a 30 second rebuild afterwards.

  • The idea with interrupt is that a builder could more efficiently handle interrupt by saving its intermediate state and resuming on the next invocation.
    In practice this is hard to implement so the most common boundary is when we check for interrupt before/after calling each builder in the chain.

 

Python Pandas replicate rows in dataframe

Other way is using concat() function:

import pandas as pd

In [603]: df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))

In [604]: df
Out[604]: 
  col1  col2
0    a     0
1    b     1
2    c     2

In [605]: pd.concat([df]*3, ignore_index=True) # Ignores the index
Out[605]: 
  col1  col2
0    a     0
1    b     1
2    c     2
3    a     0
4    b     1
5    c     2
6    a     0
7    b     1
8    c     2

In [606]: pd.concat([df]*3)
Out[606]: 
  col1  col2
0    a     0
1    b     1
2    c     2
0    a     0
1    b     1
2    c     2
0    a     0
1    b     1
2    c     2

Linux command line howto accept pairing for bluetooth device without pin

Entering a PIN is actually an outdated method of pairing, now called Legacy Pairing. Secure Simple Pairing Mode is available in Bluetooth v2.1 and later, which comprises most modern Bluetooth devices. SSPMode authentication is handled by the Bluetooth protocol stack and thus works without user interaction.

Here is how one might go about connecting to a device:

# hciconfig hci0 sspmode 1
# hciconfig hci0 sspmode
hci0:   Type: BR/EDR  Bus: USB
BD Address: AA:BB:CC:DD:EE:FF  ACL MTU: 1021:8  SCO MTU: 64:1
Simple Pairing mode: Enabled
# hciconfig hci0 piscan
# sdptool add SP
# hcitool scan
    00:11:22:33:44:55    My_Device
# rfcomm connect /dev/rfcomm0 00:11:22:33:44:55 1 &
Connected /dev/rfcomm0 to 00:11:22:33:44:55 on channel 1
Press CTRL-C for hangup

This would establish a serial connection to the device.

Cannot serve WCF services in IIS on Windows 8

For Windows Server 2012, the solution is very similar to faester's (see above). From the Server Manager, click on Add roles and features, select the appropriate server, then select Features. Under .NET Framework 4.5 Features, you'll see WCF Services, and under that, you'll find HTTP Activation.

Removing border from table cells

Change your table declaration to:

<table style="border: 1px dashed; width: 500px;">

Here is the sample in action: http://jsfiddle.net/kc48k/

Select count(*) from result query

You can wrap your query in another SELECT:

select count(*)
from
(
  select count(SID) tot  -- add alias
  from Test 
  where Date = '2012-12-10' 
  group by SID
) src;  -- add alias

See SQL Fiddle with Demo

In order for it to work, the count(SID) need a column alias and you have to provide an alias to the subquery itself.

how to get domain name from URL

A little late to the party, but:

_x000D_
_x000D_
const urls = [_x000D_
  'www.abc.au.uk',_x000D_
  'https://github.com',_x000D_
  'http://github.ca',_x000D_
  'https://www.google.ru',_x000D_
  'http://www.google.co.uk',_x000D_
  'www.yandex.com',_x000D_
  'yandex.ru',_x000D_
  'yandex'_x000D_
]_x000D_
_x000D_
urls.forEach(url => console.log(url.replace(/.+\/\/|www.|\..+/g, '')))
_x000D_
_x000D_
_x000D_

Call to a member function fetch_assoc() on boolean in <path>

OK, i just fixed this error.

This happens when there is an error in query or table doesn't exist.

Try debugging the query buy running it directly on phpmyadmin to confirm the validity of the mysql Query

How to make a list of n numbers in Python and randomly select any number?

You don't need to count stuff if you want to pick a random element. Just use random.choice() and pass your iterable:

import random
items = ['foo', 'bar', 'baz']
print random.choice(items)

If you really have to count them, use random.randint(1, count+1).

GDB: Listing all mapped memory regions for a crashed process

(gdb) maintenance info sections 
Exec file:
    `/path/to/app.out', file type elf32-littlearm.
    0x0000->0x0360 at 0x00008000: .intvecs ALLOC LOAD READONLY DATA HAS_CONTENTS

This is from comment by phihag above, deserves a separate answer. This works but info proc does not on the arm-none-eabi-gdb v7.4.1.20130913-cvs from the gcc-arm-none-eabi Ubuntu package.

Merge up to a specific commit

Recently we had a similar problem and had to solve it in a different way. We had to merge two branches up to two commits, which were not the heads of either branches:

branch A: A1 -> A2 -> A3 -> A4
branch B: B1 -> B2 -> B3 -> B4
branch C: C1 -> A2 -> B3 -> C2

For example, we had to merge branch A up to A2 and branch B up to B3. But branch C had cherry-picks from A and B. When using the SHA of A2 and B3 it looked like there was confusion because of the local branch C which had the same SHA.

To avoid any kind of ambiguity we removed branch C locally, and then created a branch AA starting from commit A2:

git co A
git co SHA-of-A2
git co -b AA

Then we created a branch BB from commit B3:

git co B
git co SHA-of-B3
git co -b BB

At that point we merged the two branches AA and BB. By removing branch C and then referencing the branches instead of the commits it worked.

It's not clear to me how much of this was superstition or what actually made it work, but this "long approach" may be helpful.

How to avoid pressing Enter with getchar() for reading a single character only?

"How to avoid pressing Enter with getchar()?"

First of all, terminal input is commonly either line or fully buffered. This means that the operation system stores the actual input from the terminal into a buffer. Usually, this buffer is flushed to the program when f.e. \n was signalized/provided in stdin. This is f.e. made by a press to Enter.

getchar() is just at the end of the chain. It has no ability to actually influence the buffering process.


"How can I do this?"

Ditch getchar() in the first place, if you don´t want to use specific system calls to change the behavior of the terminal explicitly like well explained in the other answers.

There is unfortunately no standard library function and with that no portable way to flush the buffer at single character input. However, there are implementation-based and non-portable solutions.


In Windows/MS-DOS, there are the getch() and getche() functions in the conio.h header file, which do exactly the thing you want - read a single character without the need to wait for the newline to flush the buffer.

The main difference between getch() and getche() is that getch() does not immediately output the actual input character in the console, while getche() does. The additional "e" stands for echo.

Example:

#include <stdio.h>
#include <conio.h>   

int main (void) 
{
    int c;

    while ((c = getche()) != EOF)
    {
        if (c == '\n')
        {
            break;
        }

        printf("\n");
    }

    return 0;
}

In Linux, a way to obtain direct character processing and output is to use the cbreak() and echo() options and the getch() and refresh() routines in the ncurses-library.

Note, that you need to initialize the so called standard screen with the initscr() and close the same with the endwin() routines.

Example:

#include <stdio.h>
#include <ncurses.h>   

int main (void) 
{
    int c;

    cbreak(); 
    echo();

    initscr();

    while ((c = getch()) != ERR)
    {
        if (c == '\n')
        {
            break;
        }

        printf("\n");
        refresh();
    }

    endwin();

    return 0;
}

Note: You need to invoke the compiler with the -lncurses option, so that the linker can search and find the ncurses-library.

Is it possible to install another version of Python to Virtualenv?

Now a days, the easiest way I found to have a more updated version of Python is to install it via conda into a conda environment.


Install conda(you may need a virtualenv for this)

pip install conda

Installing a new Python version inside a conda environent

I'm adding this answer here because no manual download is needed. conda will do that for you.

Now create an environment for the Python version you want. In this example I will use 3.5.2, because it it the latest version at this time of writing (Aug 2016).

conda create -n py35 python=3.5.2

Will create a environment for conda to install packages


To activate this environment(I'm assuming linux otherwise check the conda docs):

source activate py35

Now install what you need either via pip or conda in the environemnt(conda has better binary package support).

conda install <package_name>

Validating URL in Java

Using only standard API, pass the string to a URL object then convert it to a URI object. This will accurately determine the validity of the URL according to the RFC2396 standard.

Example:

public boolean isValidURL(String url) {

    try {
        new URL(url).toURI();
    } catch (MalformedURLException | URISyntaxException e) {
        return false;
    }

    return true;
}

Why do people say that Ruby is slow?

The answer is simple: people say ruby is slow because it is slow based on measured comparisons to other languages. Bear in mind, though, "slow" is relative. Often, ruby and other "slow" languages are plenty fast enough.

Add querystring parameters to link_to

The API docs on link_to show some examples of adding querystrings to both named and oldstyle routes. Is this what you want?

link_to can also produce links with anchors or query strings:

link_to "Comment wall", profile_path(@profile, :anchor => "wall")
#=> <a href="/profiles/1#wall">Comment wall</a>

link_to "Ruby on Rails search", :controller => "searches", :query => "ruby on rails"
#=> <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>

link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux")
#=> <a href="/searches?foo=bar&amp;baz=quux">Nonsense search</a>

How can I wait for a thread to finish with .NET?

I took a little different approach. There is a counter option in previous answers, and I just applied it a bit differently. I was spinning off numerous threads and incremented a counter and decremented a counter as a thread started and stopped. Then in the main method I wanted to pause and wait for threads to complete I did.

while (threadCounter > 0)
{
    Thread.Sleep(500); // Make it pause for half second so that we don’t spin the CPU out of control.
}

This is documented in my blog post: http://www.adamthings.com/post/2012/07/11/ensure-threads-have-finished-before-method-continues-in-c/

Finding the type of an object in C++

Use overloaded functions. Does not require dynamic_cast or even RTTI support:

class A {};
class B : public A {};

class Foo {
public:
    void Bar(A& a) {
        // do something
    }
    void Bar(B& b) {
        Bar(static_cast<A&>(b));
        // do B specific stuff
    }
};

(SC) DeleteService FAILED 1072

I had the same error due to a typo in the service name, i was trying to delete the service display name instead of the service name. Once I used the right service name it worked fine

How can I do width = 100% - 100px in CSS?

Could you do:

margin-right: 50px;
margin-left: 50px;

Edit: My solution is wrong. The solution posted by Aric TenEyck suggesting using a div with width 100% and then nesting another div using the margins seems more correct.

Automatically start forever (node) on system restart

An alternative crontab method inspired by this answer and this blog post.

1. Create a bash script file (change bob to desired user).

vi /home/bob/node_server_init.sh

2. Copy and paste this inside the file you've just created.

#!/bin/sh

export NODE_ENV=production
export PATH=/usr/local/bin:$PATH
forever start /node/server/path/server.js > /dev/null

Make sure to edit the paths above according to your config!

3. Make sure the bash script can be executed.

chmod 700 /home/bob/node_server_init.sh

4. Test the bash script.

sh /home/bob/node_server_init.sh

5. Replace "bob" with the runtime user for node.

crontab -u bob -e

6. Copy and paste (change bob to desired user).

@reboot /bin/sh /home/bob/node_server_init.sh

Save the crontab.

You've made it to the end, your prize is a reboot (to test) :)

T-SQL and the WHERE LIKE %Parameter% clause

you may try this one, used CONCAT

WHERE LastName LIKE Concat('%',@LastName,'%')

How to see full query from SHOW PROCESSLIST

I just read in the MySQL documentation that SHOW FULL PROCESSLIST by default only lists the threads from your current user connection.

Quote from the MySQL SHOW FULL PROCESSLIST documentation:

If you have the PROCESS privilege, you can see all threads.

So you can enable the Process_priv column in your mysql.user table. Remember to execute FLUSH PRIVILEGES afterwards :)

How to get the first 2 letters of a string in Python?

All previous examples will raise an exception in case your string is not long enough.

Another approach is to use 'yourstring'.ljust(100)[:100].strip().

This will give you first 100 chars. You might get a shorter string in case your string last chars are spaces.

HttpURLConnection timeout settings

If the HTTP Connection doesn't timeout, You can implement the timeout checker in the background thread itself (AsyncTask, Service, etc), the following class is an example for Customize AsyncTask which timeout after certain period

public abstract class AsyncTaskWithTimer<Params, Progress, Result> extends
    AsyncTask<Params, Progress, Result> {

private static final int HTTP_REQUEST_TIMEOUT = 30000;

@Override
protected Result doInBackground(Params... params) {
    createTimeoutListener();
    return doInBackgroundImpl(params);
}

private void createTimeoutListener() {
    Thread timeout = new Thread() {
        public void run() {
            Looper.prepare();

            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    if (AsyncTaskWithTimer.this != null
                            && AsyncTaskWithTimer.this.getStatus() != Status.FINISHED)
                        AsyncTaskWithTimer.this.cancel(true);
                    handler.removeCallbacks(this);
                    Looper.myLooper().quit();
                }
            }, HTTP_REQUEST_TIMEOUT);

            Looper.loop();
        }
    };
    timeout.start();
}

abstract protected Result doInBackgroundImpl(Params... params);
}

A Sample for this

public class AsyncTaskWithTimerSample extends AsyncTaskWithTimer<Void, Void, Void> {

    @Override
    protected void onCancelled(Void void) {
        Log.d(TAG, "Async Task onCancelled With Result");
        super.onCancelled(result);
    }

    @Override
    protected void onCancelled() {
        Log.d(TAG, "Async Task onCancelled");
        super.onCancelled();
    }

    @Override
    protected Void doInBackgroundImpl(Void... params) {
        // Do background work
        return null;
    };
 }

About catching ANY exception

You can but you probably shouldn't:

try:
    do_something()
except:
    print "Caught it!"

However, this will also catch exceptions like KeyboardInterrupt and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example from the docs:

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

What is mod_php?

It means that you have to have PHP installed as a module in Apache, instead of starting it as a CGI script.

How to recursively download a folder via FTP on Linux

If you can, I strongly suggest you tar and bzip (or gzip, whatever floats your boat) the directory on the remote machine—for a directory of any significant size, the bandwidth savings will probably be worth the time to zip/unzip.

How can I make a button redirect my page to another page?

Just add an onclick event to the button:

<button onclick="location.href = 'www.yoursite.com';" id="myButton" class="float-left submit-button" >Home</button>

But you shouldn't really have it inline like that, instead, put it in a JS block and give the button an ID:

<button id="myButton" class="float-left submit-button" >Home</button>

<script type="text/javascript">
    document.getElementById("myButton").onclick = function () {
        location.href = "www.yoursite.com";
    };
</script>

How to build PDF file from binary string returned from a web-service using javascript

Detect the browser and use Data-URI for Chrome and use PDF.js as below for other browsers.

PDFJS.getDocument(url_of_pdf)
.then(function(pdf) {
    return pdf.getPage(1);
})
.then(function(page) {
    // get a viewport
    var scale = 1.5;
    var viewport = page.getViewport(scale);
    // get or create a canvas
    var canvas = ...;
    canvas.width = viewport.width;
    canvas.height = viewport.height;

    // render a page
    page.render({
        canvasContext: canvas.getContext('2d'),
        viewport: viewport
    });
})
.catch(function(err) {
    // deal with errors here!
});

Laravel - check if Ajax request

You are using the wrong Request class. If you want to use the Facade like: Request::ajax() you have to import this class:

use Illuminate\Support\Facades\Request;

And not Illumiante\Http\Request


Another solution would be injecting an instance of the real request class:

public function index(Request $request){
    if($request->ajax()){
        return "AJAX";
    }

(Now here you have to import Illuminate\Http\Request)

tkinter: Open a new window with a button prompt

Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import to Tkinter rather than tkinter (the difference being the capitalization):

import tkinter as tk
#import Tkinter as tk  # for python 2
    
def create_window():
    window = tk.Toplevel(root)

root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()

root.mainloop()

This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.

How to make MySQL handle UTF-8 properly

These tips on MySQL and UTF-8 may be helpful. Unfortunately, they don't constitute a full solution, just common gotchas.

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

Fixed it with -no-pie option in linker stage:

g++-8 -L"/home/pedro/workspace/project/lib" -no-pie ...

Command to list all files in a folder as well as sub-folders in windows

Following commands we can use for Linux or Mac. For Windows we can use below on git bash.

List all files, first level folders, and their contents

ls * -r

List all first-level subdirectories and files

file */*

Save file list to text

file */* *>> ../files.txt
file */* -r *>> ../files-recursive.txt

Get everything

find . -type f

Save everything to file

find . -type f > ../files-all.txt

How to read a line from a text file in c/c++?

In c, you could use fopen, and getch. Usually, if you can't be exactly sure of the length of the longest line, you could allocate a large buffer (e.g. 8kb) and almost be guaranteed of getting all lines.

If there's a chance you may have really really long lines and you have to process line by line, you could malloc a resonable buffer, and use realloc to double it's size each time you get close to filling it.

#include <stdio.h>
#include <stdlib.h>

void handle_line(char *line) {
  printf("%s", line);
}

int main(int argc, char *argv[]) {
    int size = 1024, pos;
    int c;
    char *buffer = (char *)malloc(size);

    FILE *f = fopen("myfile.txt", "r");
    if(f) {
      do { // read all lines in file
        pos = 0;
        do{ // read one line
          c = fgetc(f);
          if(c != EOF) buffer[pos++] = (char)c;
          if(pos >= size - 1) { // increase buffer length - leave room for 0
            size *=2;
            buffer = (char*)realloc(buffer, size);
          }
        }while(c != EOF && c != '\n');
        buffer[pos] = 0;
        // line is now in buffer
        handle_line(buffer);
      } while(c != EOF); 
      fclose(f);           
    }
    free(buffer);
    return 0;
}

Properties file with a list as the value for an individual key

If this is for some configuration file processing, consider using Apache configuration. https://commons.apache.org/proper/commons-configuration/javadocs/v1.10/apidocs/index.html?org/apache/commons/configuration/PropertiesConfiguration.html It has way to multiple values to single key- The format is bit different though

key=value1,value2,valu3 gives three values against same key.

Alter column, add default constraint

Try this

alter table TableName 
 add constraint df_ConstraintNAme 
 default getutcdate() for [Date]

example

create table bla (id int)

alter table bla add constraint dt_bla default 1 for id



insert bla default values

select * from bla

also make sure you name the default constraint..it will be a pain in the neck to drop it later because it will have one of those crazy system generated names...see also How To Name Default Constraints And How To Drop Default Constraint Without A Name In SQL Server

$.focus() not working

I tested code from Chrome's DevTool Console and the focus part not worked. I found out later the issue is only present if i run it from DevTool and if i implement the code to the website it works fine. Actually, the element got focused but the DevTool removed it immediately.

Java FileOutputStream Create File if not exists

new FileOutputStream(f) will create a file in most cases, but unfortunately you will get a FileNotFoundException

if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason

from Javadoc

I other word there might be plenty of cases where you would get FileNotFoundException meaning "Could not create your file", but you would not be able to find the reason of why the file creation failed.

A solution is to remove any call to the File API and use the Files API instead as it provides much better error handling. Typically replace any new FileOutputStream(f) with Files.newOutputStream(p).

In cases where you do need to use the File API (because you use an external interface using File for example), using Files.createFile(p) is a good way to make sure your file is created properly and if not you would know why it didn't work. Some people commented above that this is redundant. It is true, but you get better error handling which might be necessary in some cases.

Why Would I Ever Need to Use C# Nested Classes

A nested class can have private, protected and protected internal access modifiers along with public and internal.

For example, you are implementing the GetEnumerator() method that returns an IEnumerator<T> object. The consumers wouldn't care about the actual type of the object. All they know about it is that it implements that interface. The class you want to return doesn't have any direct use. You can declare that class as a private nested class and return an instance of it (this is actually how the C# compiler implements iterators):

class MyUselessList : IEnumerable<int> {
    // ...
    private List<int> internalList;
    private class UselessListEnumerator : IEnumerator<int> {
        private MyUselessList obj;
        public UselessListEnumerator(MyUselessList o) {
           obj = o;
        }
        private int currentIndex = -1;
        public int Current {
           get { return obj.internalList[currentIndex]; }
        }
        public bool MoveNext() { 
           return ++currentIndex < obj.internalList.Count;
        }
    }
    public IEnumerator<int> GetEnumerator() {
        return new UselessListEnumerator(this);
    }
}

How to set cookies in laravel 5 independently inside controller

Here is a sample code with explanation.

 //Create a response instance
 $response = new Illuminate\Http\Response('Hello World');

 //Call the withCookie() method with the response method
 $response->withCookie(cookie('name', 'value', $minutes));

 //return the response
 return $response;

Cookie can be set forever by using the forever method as shown in the below code.

$response->withCookie(cookie()->forever('name', 'value'));

Retrieving a Cookie

//’name’ is the name of the cookie to retrieve the value of
$value = $request->cookie('name');

Convert bytes to bits in python

Use ord when reading reading bytes:

byte_binary = bin(ord(f.read(1))) # Add [2:] to remove the "0b" prefix

Or

Using str.format():

'{:08b}'.format(ord(f.read(1)))

C++ multiline string literal

You can just do this:

const char *text = "This is my string it is "
     "very long";

How can I pop-up a print dialog box using Javascript?

I like this, so that you can add whatever fields you want and print it that way.

function printPage() {
    var w = window.open();

    var headers =  $("#headers").html();
    var field= $("#field1").html();
    var field2= $("#field2").html();

    var html = "<!DOCTYPE HTML>";
    html += '<html lang="en-us">';
    html += '<head><style></style></head>';
    html += "<body>";

    //check to see if they are null so "undefined" doesnt print on the page. <br>s optional, just to give space
    if(headers != null) html += headers + "<br/><br/>";
    if(field != null) html += field + "<br/><br/>";
    if(field2 != null) html += field2 + "<br/><br/>";

    html += "</body>";
    w.document.write(html);
    w.window.print();
    w.document.close();
};

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

Query to list all users of a certain group

And the more complex query if you need to search in a several groups:

(&(objectCategory=user)(|(memberOf=CN=GroupOne,OU=Security Groups,OU=Groups,DC=example,DC=com)(memberOf=CN=GroupTwo,OU=Security Groups,OU=Groups,DC=example,DC=com)(memberOf=CN=GroupThree,OU=Security Groups,OU=Groups,DC=example,DC=com)))

The same example with recursion:

(&(objectCategory=user)(|(memberOf:1.2.840.113556.1.4.1941:=CN=GroupOne,OU=Security Groups,OU=Groups,DC=example,DC=com)(memberOf:1.2.840.113556.1.4.1941:=CN=GroupTwo,OU=Security Groups,OU=Groups,DC=example,DC=com)(memberOf:1.2.840.113556.1.4.1941:=CN=GroupThree,OU=Security Groups,OU=Groups,DC=example,DC=com)))

Could not load file or assembly 'System.Net.Http.Formatting' or one of its dependencies. The system cannot find the path specified

As originally suggested in a comment by GeoMac and documented on NuGet's docs the following worked for me when none of the other answers worked:

Tools / NuGet Package Manager / Package Manager Console

Update-Package -ProjectName MyProjectName -reinstall

adb command not found in linux environment

I found the solution to my problem. In my ~/.bashrc:

export PATH=${PATH}:/path/to/android-sdk/tools

However adb is not located in the android-sdk/tools/, rather in android-sdk/platform-tools/. So I added the following

export PATH=${PATH}:/path/to/android-sdk/tools:/path/to/android-sdk/platform-tools

And that solved the problem for me.

how to add super privileges to mysql database?

In Sequel Pro, access the User Accounts window. Note that any MySQL administration program could be substituted in place of Sequel Pro.

Add the following accounts and privileges:

GRANT SUPER ON *.* TO 'user'@'%' IDENTIFIED BY PASSWORD

Java: print contents of text file to screen

With Java 7's try-with-resources Jiri's answer can be improved upon:

try (BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) {
   String line = null;
   while ((line = br.readLine()) != null) {
       System.out.println(line);
   }
}

Add exception handling at the place of your choice, either in this try or elsewhere.

MySQL: Error dropping database (errno 13; errno 17; errno 39)

In my case it was due to 'lower_case_table_names' parameter.

The error number 39 thrown out when I tried to drop the databases which consists upper case table names with lower_case_table_names parameter is enabled.

This is fixed by reverting back the lower case parameter changes to the previous state.

Getting the parent div of element

I had to do recently something similar, I used this snippet:

const getNode = () =>
  for (let el = this.$el; el && el.parentNode; el = el.parentNode){
    if (/* insert your condition here */) return el;
  }
  return null
})

The function will returns the element that fulfills your condition. It was a CSS class on the element that I was looking for. If there isn't such element then it will return null

In case somebody would look for multiple elements it only returns closest parent to the element that you provided.

My example was:

if (el.classList?.contains('o-modal')) return el;

I used it in a vue component (this.$el) change that to your document.getElementById function and you're good to go. Hope it will be useful for some people ??

Get a list of all git commits, including the 'lost' ones

What saved my life was the following command:

git reflog

There you find a screen with history commits done to git like this one:

enter image description here

At this point, you only have to find the HEAD@{X} that you need, create a temporary branch and move to it like this:

git checkout -b temp_branch HEAD@{X}

That way you will have a temporary branch with your lost commit without rebasing or breaking even more your git repository.

Hope this helps...

How to force child div to be 100% of parent div's height without specifying parent's height?

.row-eq-height {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display:         flex;
 }

From:

http://getbootstrap.com.vn/examples/equal-height-columns/equal-height-columns.css

states bootstrap but you do not need bootstrap to use this. Answering this old question, as this worked for me, and seems pretty easy to implement.

This was the same answer I provided to this Question

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

Using Moshi:

When building your Retrofit Service add .asLenient() to your MoshiConverterFactory. You don't need a ScalarsConverter. It should look something like this:

return Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(ENDPOINT)
                .addConverterFactory(MoshiConverterFactory.create().asLenient())
                .build()
                .create(UserService::class.java)

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [c++]

char a[2] defines an array of char's. a is a pointer to the memory at the beginning of the array and using == won't actually compare the contents of a with 'ab' because they aren't actually the same types, 'ab' is integer type. Also 'ab' should be "ab" otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.

Something that might be illustrative is looking at the typeid of 'ab':

#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
    int some_int =5;
    std::cout << typeid('ab').name() << std::endl;
    std::cout << typeid(some_int).name() << std::endl;
    return 0;
}

on my system this returns:

i
i

showing that 'ab' is actually evaluated as an int.

If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator == overloaded and will do a comparison check when called this way.

If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cout<<"enter ab ";
    cin>>a;
    if(a=="ab"){
         cout<<"correct";
    }
    return 0;
}

This one is due to:

if(a=='ab') , here, a is const char* type (ie : array of char)

'ab' is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.

Since char is a primitive type inherited from C, no operator == is defined.

the good code should be:

if(strcmp(a,"ab")==0) , then you'll compare a const char* to another const char* using strcmp.

How do I replace part of a string in PHP?

Simply use str_replace:

$text = str_replace(' ', '_', $text);

You would do this after your previous substr and strtolower calls, like so:

$text = substr($text,0,10);
$text = strtolower($text);
$text = str_replace(' ', '_', $text);

If you want to get fancy, though, you can do it in one line:

$text = strtolower(str_replace(' ', '_', substr($text, 0, 10)));

Create a directory if it does not exist and then create the files in that directory as well

Using java.nio.Path it would be quite simple -

public static Path createFileWithDir(String directory, String filename) {
        File dir = new File(directory);
        if (!dir.exists()) dir.mkdirs();
        return Paths.get(directory + File.separatorChar + filename);
    }

How to add some non-standard font to a website?

You can add some fonts via Google Web Fonts.

Technically, the fonts are hosted at Google and you link them in the HTML header. Then, you can use them freely in CSS with @font-face (read about it).

For example:

In the <head> section:

 <link href=' http://fonts.googleapis.com/css?family=Droid+Sans' rel='stylesheet' type='text/css'>

Then in CSS:

h1 { font-family: 'Droid Sans', arial, serif; }

The solution seems quite reliable (even Smashing Magazine uses it for an article title.). There are, however, not so many fonts available so far in Google Font Directory.

How to pip or easy_install tkinter on Windows

if your using python 3.4.1 just write this line from tkinter import * this will put everything in the module into the default namespace of your program. in fact instead of referring to say a button like tkinter.Button you just type Button

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

add this to your stylesheet. line-height should match the height of your logo

.navbar-nav li a {
 line-height: 50px;
}

Check out the fiddle at: http://jsfiddle.net/nD4tW/

how to get date of yesterday using php?

try this

        $tz    = new DateTimeZone('Your Time Zone');
        $date  = new DateTime($today,$tz);
        $interval = new DateInterval('P1D');
        $date->sub($interval); 

        echo $date->format('d.m.y');

        ?>           

How can I use xargs to copy files that have spaces and quotes in their names?

I ran into the same problem. Here's how I solved it:

find . -name '*FoooBar*' | sed 's/.*/"&"/' | xargs cp ~/foo/bar

I used sed to substitute each line of input with the same line, but surrounded by double quotes. From the sed man page, "...An ampersand (``&'') appearing in the replacement is replaced by the string matching the RE..." -- in this case, .*, the entire line.

This solves the xargs: unterminated quote error.

Difference between IISRESET and IIS Stop-Start command

I know this is quite an old post, but I would like to point out the following for people who will read it in the future: As per MS:

Do not use the IISReset.exe tool to restart the IIS services. Instead, use the NET STOP and NET START commands. For example, to stop and start the World Wide Web Publishing Service, run the following commands:

  • NET STOP iisadmin /y
  • NET START w3svc

There are two benefits to using the NET STOP/NET START commands to restart the IIS Services as opposed to using the IISReset.exe tool. First, it is possible for IIS configuration changes that are in the process of being saved when the IISReset.exe command is run to be lost. Second, using IISReset.exe can make it difficult to identify which dependent service or services failed to stop when this problem occurs. Using the NET STOP commands to stop each individual dependent service will allow you to identify which service fails to stop, so you can then troubleshoot its failure accordingly.

KB:https://support.microsoft.com/en-ca/help/969864/using-iisreset-exe-to-restart-internet-information-services-iis-result

How can I fix MySQL error #1064?

For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can't figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.

For example, Before it was:

DROP PROCEDURE IF EXISTS getStats;
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;

After putting DELIMITER it was like this:

DROP PROCEDURE IF EXISTS getStats;
DELIMITER $$
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;
$$
DELIMITER ;

How do I get a div to float to the bottom of its container?

I had been find this solution for a long time as well. This is what I get:

align-self: flex-end;

link: https://philipwalton.github.io/solved-by-flexbox/demos/vertical-centering/ However, I can't remember from where I opened this link. Hope it helps

How can I create a unique constraint on my column (SQL Server 2008 R2)?

One thing not clearly covered is that microsoft sql is creating in the background an unique index for the added constraint

create table Customer ( id int primary key identity (1,1) , name nvarchar(128) ) 

--Commands completed successfully.

sp_help Customer

---> index
--index_name    index_description   index_keys
--PK__Customer__3213E83FCC4A1DFA    clustered, unique, primary key located on PRIMARY   id

---> constraint
--constraint_type   constraint_name delete_action   update_action   status_enabled  status_for_replication  constraint_keys
--PRIMARY KEY (clustered)   PK__Customer__3213E83FCC4A1DFA  (n/a)   (n/a)   (n/a)   (n/a)   id


---- now adding the unique constraint

ALTER TABLE Customer ADD CONSTRAINT U_Name UNIQUE(Name)

-- Commands completed successfully.

sp_help Customer

---> index
---index_name   index_description   index_keys
---PK__Customer__3213E83FCC4A1DFA   clustered, unique, primary key located on PRIMARY   id
---U_Name   nonclustered, unique, unique key located on PRIMARY name

---> constraint
---constraint_type  constraint_name delete_action   update_action   status_enabled  status_for_replication  constraint_keys
---PRIMARY KEY (clustered)  PK__Customer__3213E83FCC4A1DFA  (n/a)   (n/a)   (n/a)   (n/a)   id
---UNIQUE (non-clustered)   U_Name  (n/a)   (n/a)   (n/a)   (n/a)   name

as you can see , there is a new constraint and a new index U_Name

Disable-web-security in Chrome 48+

The chosen answer is good, but for those who are still struggling with what they are talking about(your first time dealing with this issue), the following worked for me.

I created a new shortcut to Chrome on my desktop, right clicked it, and set the "Target" field to the following,

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="c:/chromedev"

The directory can be anything you want, I decided to make an empty folder called chrome dev in my C: directory. It has nothing to do where chrome is installed on your computer. It's just a fluff type thing.

This link also has clear directions for other OSes. How to disable web securityin Chrome

How can I handle the warning of file_get_contents() function in PHP?

Step 1: check the return code: if($content === FALSE) { // handle error here... }

Step 2: suppress the warning by putting an error control operator (i.e. @) in front of the call to file_get_contents(): $content = @file_get_contents($site);

PHP "php://input" vs $_POST

Simple example of how to use it

 <?php  
     if(!isset($_POST) || empty($_POST)) { 
     ?> 
        <form name="form1" method="post" action=""> 
          <input type="text" name="textfield"><br /> 
          <input type="submit" name="Submit" value="submit"> 
        </form> 
   <?php  
        } else { 
        $example = file_get_contents("php://input");
        echo $example;  }  
   ?>

Keras input explanation: input_shape, units, batch_size, dim, etc

Input Dimension Clarified:

Not a direct answer, but I just realized the word Input Dimension could be confusing enough, so be wary:

It (the word dimension alone) can refer to:

a) The dimension of Input Data (or stream) such as # N of sensor axes to beam the time series signal, or RGB color channel (3): suggested word=> "InputStream Dimension"

b) The total number /length of Input Features (or Input layer) (28 x 28 = 784 for the MINST color image) or 3000 in the FFT transformed Spectrum Values, or

"Input Layer / Input Feature Dimension"

c) The dimensionality (# of dimension) of the input (typically 3D as expected in Keras LSTM) or (#RowofSamples, #of Senors, #of Values..) 3 is the answer.

"N Dimensionality of Input"

d) The SPECIFIC Input Shape (eg. (30,50,50,3) in this unwrapped input image data, or (30, 250, 3) if unwrapped Keras:

Keras has its input_dim refers to the Dimension of Input Layer / Number of Input Feature

model = Sequential()
model.add(Dense(32, input_dim=784))  #or 3 in the current posted example above
model.add(Activation('relu'))

In Keras LSTM, it refers to the total Time Steps

The term has been very confusing, is correct and we live in a very confusing world!!

I find one of the challenge in Machine Learning is to deal with different languages or dialects and terminologies (like if you have 5-8 highly different versions of English, then you need to very high proficiency to converse with different speakers). Probably this is the same in programming languages too.

MySQL Update Column +1?

You can do:

UPDATE categories SET posts = posts + 1 WHERE category_id = 42;

What is the best way to add options to a select from a JavaScript object with jQuery?

The JSON format:

[{
    "org_name": "Asset Management"
}, {
    "org_name": "Debt Equity Foreign services"
}, {
    "org_name": "Credit Services"
}]

And the jQuery code to populate the values to the Dropdown on Ajax success:

success: function(json) {
    var options = [];
    $('#org_category').html('');  // Set the Dropdown as Blank before new Data
    options.push('<option>-- Select Category --</option>');
    $.each(JSON.parse(json), function(i, item) {
        options.push($('<option/>',
        {
           value: item.org_name, text: item.org_name
        }));
    });
    $('#org_category').append(options);  // Set the Values to Dropdown
}

Plot width settings in ipython notebook

If you use %pylab inline you can (on a new line) insert the following command:

%pylab inline
pylab.rcParams['figure.figsize'] = (10, 6)

This will set all figures in your document (unless otherwise specified) to be of the size (10, 6), where the first entry is the width and the second is the height.

See this SO post for more details. https://stackoverflow.com/a/17231361/1419668

Twitter Bootstrap Form File Element Upload Button

I use http://gregpike.net/demos/bootstrap-file-input/demo.html:

$('input[type=file]').bootstrapFileInput();

or

$('.file-inputs').bootstrapFileInput();

How to change href of <a> tag on button click through javascript

Here's my take on it. I needed to create a URL by collecting the value from a text box , when the user presses a Submit button.

_x000D_
_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
Hi everyone_x000D_
_x000D_
<p id="result"></p>_x000D_
_x000D_
<textarea cols="40" id="SearchText" rows="2"></textarea>_x000D_
_x000D_
<button onclick="myFunction()" type="button">Submit!</button>_x000D_
_x000D_
<script>_x000D_
function myFunction() {_x000D_
    var result = document.getElementById("SearchText").value;_x000D_
 document.getElementById("result").innerHTML = result;_x000D_
 document.getElementById("abc").href="http://arindam31.pythonanywhere.com/hello/" + result;_x000D_
}  _x000D_
</script>_x000D_
_x000D_
_x000D_
<a href="#" id="abc">abc</a>_x000D_
_x000D_
</body>_x000D_
<html>
_x000D_
_x000D_
_x000D_

PHP date() with timezone?

Not mentioned above. You could also crate a DateTime object by providing a timestamp as string in the constructor with a leading @ sign.

$dt = new DateTime('@123456789');
$dt->setTimezone(new DateTimeZone('America/New_York'));
echo $dt->format('F j, Y - G:i');

See the documentation about compound formats: https://www.php.net/manual/en/datetime.formats.compound.php

How to view .img files?

.IMG files are ususally filesystems, not pictures. The easiest way to access them is to install VMWare, install Windows in VMWare, and then add the .img file as some kind of disk device (floppy, cdrom, hard disk). If you guess the right kind, Windows might be able to open it.

Does C# have a String Tokenizer like Java's?

read this, split function has an overload takes an array consist of seperators http://msdn.microsoft.com/en-us/library/system.stringsplitoptions.aspx

How to convert an xml string to a dictionary?

Disclaimer: This modified XML parser was inspired by Adam Clark The original XML parser works for most of simple cases. However, it didn't work for some complicated XML files. I debugged the code line by line and finally fixed some issues. If you find some bugs, please let me know. I am glad to fix it.

class XmlDictConfig(dict):  
    '''   
    Note: need to add a root into if no exising    
    Example usage:
    >>> tree = ElementTree.parse('your_file.xml')
    >>> root = tree.getroot()
    >>> xmldict = XmlDictConfig(root)
    Or, if you want to use an XML string:
    >>> root = ElementTree.XML(xml_string)
    >>> xmldict = XmlDictConfig(root)
    And then use xmldict for what it is... a dict.
    '''
    def __init__(self, parent_element):
        if parent_element.items():
            self.updateShim( dict(parent_element.items()) )
        for element in parent_element:
            if len(element):
                aDict = XmlDictConfig(element)
            #   if element.items():
            #   aDict.updateShim(dict(element.items()))
                self.updateShim({element.tag: aDict})
            elif element.items():    # items() is specialy for attribtes
                elementattrib= element.items()
                if element.text:           
                    elementattrib.append((element.tag,element.text ))     # add tag:text if there exist
                self.updateShim({element.tag: dict(elementattrib)})
            else:
                self.updateShim({element.tag: element.text})

    def updateShim (self, aDict ):
        for key in aDict.keys():   # keys() includes tag and attributes
            if key in self:
                value = self.pop(key)
                if type(value) is not list:
                    listOfDicts = []
                    listOfDicts.append(value)
                    listOfDicts.append(aDict[key])
                    self.update({key: listOfDicts})
                else:
                    value.append(aDict[key])
                    self.update({key: value})
            else:
                self.update({key:aDict[key]})  # it was self.update(aDict)    

How to get the server path to the web directory in Symfony2 from inside the controller?

$host = $request->server->get('HTTP_HOST');
$base = (!empty($request->server->get('BASE'))) ? $request->server->get('BASE') : '';
$getBaseUrl = $host.$base;

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

Go through C:\apache-tomcat-7.0.47\lib path (this path may be differ based on where you installed the Tomcat server) then past ojdbc14.jar if its not contain.

Then restart the server in eclipse then run your app on server

Eclipse EGit Checkout conflict with files: - EGit doesn't want to continue

This is the way I solved my problem:

  1. Right click the folder that has uncommitted changes on your local
  2. Click Team > Advanced > Assume Unchanged
  3. Pull from master.

UPDATE:

As Hugo Zuleta rightly pointed out, you should be careful while applying this. He says that it might end up saying the branch is up to date, but the changes aren't shown, resulting in desync from the branch.

Howto: Clean a mysql InnoDB storage engine?

The InnoDB engine does not store deleted data. As you insert and delete rows, unused space is left allocated within the InnoDB storage files. Over time, the overall space will not decrease, but over time the 'deleted and freed' space will be automatically reused by the DB server.

You can further tune and manage the space used by the engine through an manual re-org of the tables. To do this, dump the data in the affected tables using mysqldump, drop the tables, restart the mysql service, and then recreate the tables from the dump files.

How can I get last characters of a string

You can use the substr() method with a negative starting position to retrieve the last n characters. For example, this gets the last 5:

var lastFiveChars = id.substr(-5);

Is it possible to use jQuery to read meta tags

$("meta")

Should give you back an array of elements whose tag name is META and then you can iterate over the collection to pick out whatever attributes of the elements you are interested in.

How to change font size in Eclipse for Java text editors?

I tend to use menu Windows ? Preferences ? General ? Appearances ? Colors and Fonts ? Java Text Editors ? Change ? Apply.

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

Make sure that you have installed the correct NuGet package in your console application:

<package id="Microsoft.AspNet.WebApi.Client" version="4.0.20710.0" />

and that you are targeting at least .NET 4.0.

This being said, your GetAllFoos function is defined to return an IEnumerable<Prospect> whereas in your ReadAsAsync method you are passing IEnumerable<Foo> which obviously are not compatible types.

Install-Package Microsoft.AspNet.WebApi.Client

Select project in project manager console

get list of pandas dataframe columns based on data type

I use infer_objects()

Docstring: Attempt to infer better dtypes for object columns.

Attempts soft conversion of object-dtyped columns, leaving non-object and unconvertible columns unchanged. The inference rules are the same as during normal Series/DataFrame construction.

df.infer_objects().dtypes

Could not open ServletContext resource [/WEB-INF/applicationContext.xml]

ContextLoaderListener has its own context which is shared by all servlets and filters. By default it will search /WEB-INF/applicationContext.xml

You can customize this by using

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/somewhere-else/root-context.xml</param-value>
</context-param>

on web.xml, or remove this listener if you don't need one.

convert '1' to '0001' in JavaScript

I use the following object:

function Padder(len, pad) {
  if (len === undefined) {
    len = 1;
  } else if (pad === undefined) {
    pad = '0';
  }

  var pads = '';
  while (pads.length < len) {
    pads += pad;
  }

  this.pad = function (what) {
    var s = what.toString();
    return pads.substring(0, pads.length - s.length) + s;
  };
}

With it you can easily define different "paddings":

var zero4 = new Padder(4);
zero4.pad(12); // "0012"
zero4.pad(12345); // "12345"
zero4.pad("xx"); // "00xx"
var x3 = new Padder(3, "x");
x3.pad(12); // "x12"

How to fix Subversion lock error

I tried all suggestion from this thread but the only one that worked is:

  1. go to the folder on which the project locked folder is stored
  2. execute svn cleanup

How do I disable form resizing for users?

Change this property and try this at design time:

FormBorderStyle = FormBorderStyle.FixedDialog;

Designer view before the change:

Enter image description here

How to edit an Android app?

Generally speaking, a software product isn't your "property already", as you said in the comment. Most of the times (I won't be irresponsible to say anything in open), it's licensed to you. A license to use some thing is not the same thing as owning (property rights) that very same thing.

That's because there are authorship, copyright, intellectual property rights applicable to it. I don't know how things work in United States (or in your country), but it's generally accepted that the work of a mind, a creative work, must not be changed in its nature as such to make the expression of art to be different than that expression that the author intended. That applies for example, in some cases, to architectural work (in most countries, you can't change the appearance of a building to "desfigure" the work of art of the architect, without his prior consent). Exceptions are made, obviously, when the author expressly authorizes such changes (e.g., Creative Commons licenses, open source licenses etc.).

Anyway, that's why you see in most EULAs the typical sentence: "this software is licensed, not sold". That's the purpose and reason why.

Now that you understand the reasons why you can't wander around changing other people's art, let me be technical.

There are possible ways to decompile Java programs. You can use dex2jar, it provides a somewhat good start for you to start looking for things and changes. And perhaps rebuild the code by mounting back the pieces together. Good luck, as most people obfuscate their codes to make that harder.

However, let me say that it's still forbidden to change programs, as I said above. And it's extremely unethical. It makes me sad that people do that with no scruples (not saying it's your case, just warning you). It shouldn't need people to be at the other side to understand that. Or maybe that's just me, who lives in a country where piracy is rampant.

The tools are always out there. But the conscience, unfortunately, not always.

edit: in case it isn't clear enough already, I do NOT approve the use of these programs. I use them myself to check how hard my own applications are to be reverse engineered. But I also think that explaning is always better than denial (better be here).

How to concatenate strings in windows batch file for loop?

Try this, with strings:

set "var=string1string2string3"

and with string variables:

set "var=%string1%%string2%%string3%"

Deleting all records in a database table

If you are looking for a way to it without SQL you should be able to use delete_all.

Post.delete_all

or with a criteria

Post.delete_all "person_id = 5 AND (category = 'Something' OR category = 'Else')"

See here for more information.

The records are deleted without loading them first which makes it very fast but will break functionality like counter cache that depends on rails code to be executed upon deletion.

How to deny access to a file in .htaccess

Well you could use the <Directory> tag for example:

<Directory /inscription>
  <Files log.txt>
    Order allow,deny
    Deny from all
  </Files>
</Directory>

Do not use ./ because if you just use / it looks at the root directory of your site.

For a more detailed example visit http://httpd.apache.org/docs/2.2/sections.html

How to detect scroll position of page using jQuery

$('.div').scroll(function (event) {
 event.preventDefault()
 var scroll = $(this).scrollTop();
 if(scroll == 0){
   alert(123)
 }
});

This code for chat_boxes for loading previous messages

Maximize a window programmatically and prevent the user from changing the windows state

To programmatically maximize the windowstate you can use:

 this.WindowState = FormWindowState.Maximized;
 this.MaximizeBox = false;

jQuery.css() - marginLeft vs. margin-left?

Late to answer, but no-one has specified that css property with dash won't work in object declaration in jquery:

.css({margin-left:'200px'});//won't work
.css({marginLeft:'200px'});//works

So, do not forget to use quotes if you prefer to use dash style property in jquery code.

.css({'margin-left':'200px'});//works

Postgres: clear entire database before re-creating / re-populating from bash script

If you don't actually need a backup of the database dumped onto disk in a plain-text .sql script file format, you could connect pg_dump and pg_restore directly together over a pipe.

To drop and recreate tables, you could use the --clean command-line option for pg_dump to emit SQL commands to clean (drop) database objects prior to (the commands for) creating them. (This will not drop the whole database, just each table/sequence/index/etc. before recreating them.)

The above two would look something like this:

pg_dump -U username --clean | pg_restore -U username

Unable to read repository at http://download.eclipse.org/releases/indigo

In Windows 7 32-bit version, I started the eclipse with as an administrator. This worked for me.

How to make Apache serve index.php instead of index.html?

PHP will work only on the .php file extension.

If you are on Apache you can also set, in your httpd.conf file, the extensions for PHP. You'll have to find the line:

AddType application/x-httpd-php .php .html
                                     ^^^^^

and add how many extensions, that should be read with the PHP interpreter, as you want.

How do I call an Angular 2 pipe with multiple arguments?

You're missing the actual pipe.

{{ myData | date:'fullDate' }}

Multiple parameters can be separated by a colon (:).

{{ myData | myPipe:'arg1':'arg2':'arg3' }}

Also you can chain pipes, like so:

{{ myData | date:'fullDate' | myPipe:'arg1':'arg2':'arg3' }}

What's a good IDE for Python on Mac OS X?

Visual Studio Code + Official Python Plugin

Here you see an overview of its current Python features:

https://code.visualstudio.com/docs/languages/python

Chocolat

http://chocolatapp.com

It's lightweight and offers Code Completion. Costs money.

EDIT: Apparently Chocolat was an interesting option in 2013 but since then many others came up and development stalled. Nowadays I recommend Visual Studio Code + Python Plugin.

How to exclude a directory from ant fileset, based on directories contents

You need to add a '/' after the dir name

<exclude name="WEB-INF/" />

What is the question mark for in a Typescript parameter name

parameter?: type is a shorthand for parameter: type | undefined

How to retrieve data from sqlite database in android and display it in TextView

First cast your Edit text like this:

TextView tekst = (TextView) findViewById(R.id.editText1);
tekst.setText(text);

And after that close the DB not befor this line...

 myDataBaseHelper.close(); 

Creating an abstract class in Objective-C

The solution I came up with is:

  1. Create a protocol for everything you want in your "abstract" class
  2. Create a base class (or maybe call it abstract) that implements the protocol. For all the methods you want "abstract" implement them in the .m file, but not the .h file.
  3. Have your child class inherit from the base class AND implement the protocol.

This way the compiler will give you a warning for any method in the protocol that isn't implemented by your child class.

It's not as succinct as in Java, but you do get the desired compiler warning.

Using partial views in ASP.net MVC 4

You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet of Notes, where you need to pass in a single Note.

You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

Git Server Like GitHub?

You can even install GitHub on your local server (but not for free):

https://enterprise.github.com/

How do I rotate the Android emulator display?

I have checked on Windows: Ctrl + F11 and Ctrl + F12 both are working to change the orientation of the Android simulator.

For other shortcut keys:

In the Eclipse toolbar go to "Help-->key Assist.. "

You can also use Ctrl + Shift + L here, so many shortcut keys of Eclipse are given.

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

The query below will result in dd-mmm-yy format.

select 
cast(DAY(getdate()) as varchar)+'-'+left(DATEname(m,getdate()),3)+'-'+  
Right(Year(getdate()),2)

Python: finding lowest integer

Python has a built in min function to help you with finding the smallest.

However, you need to convert your list items to numbers before you can find the lowest integer( what, isn't that float? )

min(float(i) for i in l)

ExecuteNonQuery doesn't return results

From MSDN: SqlCommand.ExecuteNonQuery Method

You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.

Although the ExecuteNonQuery returns no rows, any output parameters or return values mapped to parameters are populated with data.

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.

You are using SELECT query, thus you get -1

How to download file from database/folder using php

I have changed to your code with little modification will works well. Here is the code:

butangDonload.php

<?php
$file = "logo_ldg.png"; //Let say If I put the file name Bang.png
echo "<a href='download1.php?nama=".$file."'>download</a> ";
?>

download.php

<?php
$name= $_GET['nama'];

    header('Content-Description: File Transfer');
    header('Content-Type: application/force-download');
    header("Content-Disposition: attachment; filename=\"" . basename($name) . "\";");
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($name));
    ob_clean();
    flush();
    readfile("your_file_path/".$name); //showing the path to the server where the file is to be download
    exit;
?>

Here you need to show the path from where the file to be download. i.e. will just give the file name but need to give the file path for reading that file. So, it should be replaced by I have tested by using your code and modifying also will works.

How do I access an access array item by index in handlebars?

The following, with an additional dot before the index, works just as expected. Here, the square brackets are optional when the index is followed by another property:

{{people.[1].name}}
{{people.1.name}}

However, the square brackets are required in:

{{#with people.[1]}}
  {{name}}
{{/with}}

In the latter, using the index number without the square brackets would get one:

Error: Parse error on line ...:
...     {{#with people.1}}                
-----------------------^
Expecting 'ID', got 'INTEGER'

As an aside: the brackets are (also) used for segment-literal syntax, to refer to actual identifiers (not index numbers) that would otherwise be invalid. More details in What is a valid identifier?

(Tested with Handlebars in YUI.)

2.xx Update

You can now use the get helper for this:

(get people index)

although if you get an error about index needing to be a string, do:

(get people (concat index ""))

How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer?

See the code below, this is the complete code about getting a mouse event(rightclick, leftclick) And you can DIY this code and make it on your own.

using System; 
using System.Drawing; 
using System.Windows.Forms; 
using System.Runtime.InteropServices; 

namespace Demo_mousehook_csdn
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        MouseHook mh;

        private void Form1_Load(object sender, EventArgs e)
        {
            mh = new MouseHook();
            mh.SetHook();
            mh.MouseMoveEvent += mh_MouseMoveEvent;
            mh.MouseClickEvent += mh_MouseClickEvent;
            mh.MouseDownEvent += mh_MouseDownEvent;
            mh.MouseUpEvent += mh_MouseUpEvent;
        }
        private void mh_MouseDownEvent(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                richTextBox1.AppendText("Left Button Press\n");
            }
            if (e.Button == MouseButtons.Right)
            {
                richTextBox1.AppendText("Right Button Press\n");
            }
        }

        private void mh_MouseUpEvent(object sender, MouseEventArgs e)
        {

            if (e.Button == MouseButtons.Left)
            {
                richTextBox1.AppendText("Left Button Release\n");
            }
            if (e.Button == MouseButtons.Right)
            {
                richTextBox1.AppendText("Right Button Release\n");
            }

        }
        private void mh_MouseClickEvent(object sender, MouseEventArgs e)
        {
            //MessageBox.Show(e.X + "-" + e.Y);
            if (e.Button == MouseButtons.Left)
            {
                string sText = "(" + e.X.ToString() + "," + e.Y.ToString() + ")";
                label1.Text = sText;
            }
        }

        private void mh_MouseMoveEvent(object sender, MouseEventArgs e)
        {
            int x = e.Location.X;
            int y = e.Location.Y;
            textBox1.Text = x + "";
            textBox2.Text = y + "";
        }
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            mh.UnHook();
        }

        private void Form1_FormClosed_1(object sender, FormClosedEventArgs e)
        {
            mh.UnHook();
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }

    public class Win32Api
    {
        [StructLayout(LayoutKind.Sequential)]
        public class POINT
        {
            public int x;
            public int y;
        }
        [StructLayout(LayoutKind.Sequential)]
        public class MouseHookStruct
        {
            public POINT pt;
            public int hwnd;
            public int wHitTestCode;
            public int dwExtraInfo;
        }
        public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern bool UnhookWindowsHookEx(int idHook);
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);
    }

    public class MouseHook
    {
        private Point point;
        private Point Point
        {
            get { return point; }
            set
            {
                if (point != value)
                {
                    point = value;
                    if (MouseMoveEvent != null)
                    {
                        var e = new MouseEventArgs(MouseButtons.None, 0, point.X, point.Y, 0);
                        MouseMoveEvent(this, e);
                    }
                }
            }
        }
        private int hHook;
        private const int WM_MOUSEMOVE = 0x200;
        private const int WM_LBUTTONDOWN = 0x201;
        private const int WM_RBUTTONDOWN = 0x204;
        private const int WM_MBUTTONDOWN = 0x207;
        private const int WM_LBUTTONUP = 0x202;
        private const int WM_RBUTTONUP = 0x205;
        private const int WM_MBUTTONUP = 0x208;
        private const int WM_LBUTTONDBLCLK = 0x203;
        private const int WM_RBUTTONDBLCLK = 0x206;
        private const int WM_MBUTTONDBLCLK = 0x209;
        public const int WH_MOUSE_LL = 14;
        public Win32Api.HookProc hProc;
        public MouseHook()
        {
            this.Point = new Point();
        }
        public int SetHook()
        {
            hProc = new Win32Api.HookProc(MouseHookProc);
            hHook = Win32Api.SetWindowsHookEx(WH_MOUSE_LL, hProc, IntPtr.Zero, 0);
            return hHook;
        }
        public void UnHook()
        {
            Win32Api.UnhookWindowsHookEx(hHook);
        }
        private int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam)
        {
            Win32Api.MouseHookStruct MyMouseHookStruct = (Win32Api.MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(Win32Api.MouseHookStruct));
            if (nCode < 0)
            {
                return Win32Api.CallNextHookEx(hHook, nCode, wParam, lParam);
            }
            else
            {
                if (MouseClickEvent != null)
                {
                    MouseButtons button = MouseButtons.None;
                    int clickCount = 0;
                    switch ((Int32)wParam)
                    {
                        case WM_LBUTTONDOWN:
                            button = MouseButtons.Left;
                            clickCount = 1;
                            MouseDownEvent(this, new MouseEventArgs(button, clickCount, point.X, point.Y, 0));
                            break;
                        case WM_RBUTTONDOWN:
                            button = MouseButtons.Right;
                            clickCount = 1;
                            MouseDownEvent(this, new MouseEventArgs(button, clickCount, point.X, point.Y, 0));
                            break;
                        case WM_MBUTTONDOWN:
                            button = MouseButtons.Middle;
                            clickCount = 1;
                            MouseDownEvent(this, new MouseEventArgs(button, clickCount, point.X, point.Y, 0));
                            break;
                        case WM_LBUTTONUP:
                            button = MouseButtons.Left;
                            clickCount = 1;
                            MouseUpEvent(this, new MouseEventArgs(button, clickCount, point.X, point.Y, 0));
                            break;
                        case WM_RBUTTONUP:
                            button = MouseButtons.Right;
                            clickCount = 1;
                            MouseUpEvent(this, new MouseEventArgs(button, clickCount, point.X, point.Y, 0));
                            break;
                        case WM_MBUTTONUP:
                            button = MouseButtons.Middle;
                            clickCount = 1;
                            MouseUpEvent(this, new MouseEventArgs(button, clickCount, point.X, point.Y, 0));
                            break;
                    }

                    var e = new MouseEventArgs(button, clickCount, point.X, point.Y, 0);
                    MouseClickEvent(this, e);
                }
                this.Point = new Point(MyMouseHookStruct.pt.x, MyMouseHookStruct.pt.y);
                return Win32Api.CallNextHookEx(hHook, nCode, wParam, lParam);
            }
        }

        public delegate void MouseMoveHandler(object sender, MouseEventArgs e);
        public event MouseMoveHandler MouseMoveEvent;

        public delegate void MouseClickHandler(object sender, MouseEventArgs e);
        public event MouseClickHandler MouseClickEvent;

        public delegate void MouseDownHandler(object sender, MouseEventArgs e);
        public event MouseDownHandler MouseDownEvent;

        public delegate void MouseUpHandler(object sender, MouseEventArgs e);
        public event MouseUpHandler MouseUpEvent;

    }
}

You can download the demo And the tutorial here : C# Mouse Hook Demo

How can I get double quotes into a string literal?

Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.

printf("She said \"time flies like an arrow, but fruit flies like a banana\".");

Becomes:

printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");

With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:

any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)

How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

Check your MySQL Port number 3306.

Is there any other MySQL Install in your system on same port ?

If any installation found the change the port number to any number between 3301-3309 (except 3306)

user name : root
password : ' ' (Empty)