Programs & Examples On #Scriptdata

Where is virtualenvwrapper.sh after pip install?

Using

find / -name virtualenvwrapper.sh

I got a TON of "permissions denied"s, and exactly one printout of the file location. I missed it until I found that file location when I uninstall/installed it again with pip.

In case you were curious, it was in

/usr/local/share/python/virtualenvwrapper.sh

How do I change the title of the "back" button on a Navigation Bar

If you have more than one navigation that is

ParentViewController --> ChildViewController1 --> ChildViewController2

you can use below code to change title of back button on navigation bar.

self.navigationController?.navigationBar.topItem?.backBarButtonItem = UIBarButtonItem.init(title: "Back", style: .plain, target: nil, action:nil)

javac error: Class names are only accepted if annotation processing is explicitly requested

chandan@cmaster:~/More$ javac New.java
chandan@cmaster:~/More$ javac New
error: Class names, 'New', are only accepted if annotation processing is explicitly requested
1 error

So if you by mistake after compiling again use javac for running a program.

Change the Right Margin of a View Programmatically?

Update: Android KTX

The Core KTX module provides extensions for common libraries that are part of the Android framework, androidx.core.view among them.

dependencies {
    implementation "androidx.core:core-ktx:{latest-version}"
}

The following extension functions are handy to deal with margins:

Note: they are all extension functions of MarginLayoutParams, so first you need to get and cast the layoutParams of your view:

val params = (myView.layoutParams as ViewGroup.MarginLayoutParams)

Sets the margins of all axes in the ViewGroup's MarginLayoutParams. (The dimension has to be provided in pixels, see the last section if you want to work with dp)

inline fun MarginLayoutParams.setMargins(@Px size: Int): Unit
// E.g. 16px margins
params.setMargins(16)

Updates the margins in the ViewGroup's ViewGroup.MarginLayoutParams.

inline fun MarginLayoutParams.updateMargins(
    @Px left: Int = leftMargin, 
    @Px top: Int = topMargin, 
    @Px right: Int = rightMargin, 
    @Px bottom: Int = bottomMargin
): Unit
// Example: 8px left margin 
params.updateMargins(left = 8)

Updates the relative margins in the ViewGroup's MarginLayoutParams (start/end instead of left/right).

inline fun MarginLayoutParams.updateMarginsRelative(
    @Px start: Int = marginStart, 
    @Px top: Int = topMargin, 
    @Px end: Int = marginEnd, 
    @Px bottom: Int = bottomMargin
): Unit
// E.g: 8px start margin 
params.updateMargins(start = 8)

The following extension properties are handy to get the current margins:

inline val View.marginBottom: Int
inline val View.marginEnd: Int
inline val View.marginLeft: Int
inline val View.marginRight: Int
inline val View.marginStart: Int
inline val View.marginTop: Int
// E.g: get margin bottom
val bottomPx = myView1.marginBottom
  • Using dp instead of px:

If you want to work with dp (density-independent pixels) instead of px, you will need to convert them first. You can easily do that with the following extension property:

val Int.px: Int
    get() = (this * Resources.getSystem().displayMetrics.density).toInt()

Then you can call the previous extension functions like:

params.updateMargins(start = 16.px, end = 16.px, top = 8.px, bottom = 8.px)
val bottomDp = myView1.marginBottom.dp

Old answer:

In Kotlin you can declare an extension function like:

fun View.setMargins(
    leftMarginDp: Int? = null,
    topMarginDp: Int? = null,
    rightMarginDp: Int? = null,
    bottomMarginDp: Int? = null
) {
    if (layoutParams is ViewGroup.MarginLayoutParams) {
        val params = layoutParams as ViewGroup.MarginLayoutParams
        leftMarginDp?.run { params.leftMargin = this.dpToPx(context) }
        topMarginDp?.run { params.topMargin = this.dpToPx(context) }
        rightMarginDp?.run { params.rightMargin = this.dpToPx(context) }
        bottomMarginDp?.run { params.bottomMargin = this.dpToPx(context) }
        requestLayout()
    }
}

fun Int.dpToPx(context: Context): Int {
    val metrics = context.resources.displayMetrics
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), metrics).toInt()
}

Then you can call it like:

myView1.setMargins(8, 16, 34, 42)

Or:

myView2.setMargins(topMarginDp = 8) 

How to prevent ENTER keypress to submit a web form?

This worked for me.
onkeydown="return !(event.keyCode==13)"

    <form id="form1" runat="server" onkeydown="return !(event.keyCode==13)">

   </form>

How do I change Eclipse to use spaces instead of tabs?

Also consider using an .editorconfig file: https://marketplace.eclipse.org/content/editorconfig-eclipse. Someone not using Eclipse may also benefit from this, in the worst case it can serve as a guideline. NOTE: I will not enter the tabs vs space wars but use spaces FTW :-)

How can I close a window with Javascript on Mozilla Firefox 3?

This code will work it out definitely

function closing() {
var answer = confirm("Do you wnat to close this window ?");
    if (answer){
        netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserWrite');
        window.close();
    }
    else{
        stop;
    }
}

Printing the correct number of decimal points with cout

I had an issue for integers while wanting consistent formatting.

A rewrite for completeness:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    //    floating point formatting example
    cout << fixed << setprecision(2) << 122.345 << endl;
    //    Output:  122.34

    //    integer formatting example
    cout << fixed << setprecision(2) << double(122) << endl;
    //    Output:  122.00
}

Compare integer in bash, unary operator expected

Your piece of script works just great. Are you sure you are not assigning anything else before the if to "i"?

A common mistake is also not to leave a space after and before the square brackets.

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

Select column to drop:

ALTER TABLE my_table
DROP column_to_be_deleted;

However, some databases (including SQLite) have limited support, and you may have to create a new table and migrate the data over:

https://www.sqlite.org/faq.html#q11

Easiest way to convert a Blob into a byte array

the mySql blob class has the following function :

blob.getBytes

use it like this:

//(assuming you have a ResultSet named RS)
Blob blob = rs.getBlob("SomeDatabaseField");

int blobLength = (int) blob.length();  
byte[] blobAsBytes = blob.getBytes(1, blobLength);

//release the blob and free up memory. (since JDBC 4.0)
blob.free();

ln (Natural Log) in Python

math.log is the natural logarithm:

From the documentation:

math.log(x[, base]) With one argument, return the natural logarithm of x (to base e).

Your equation is therefore:

n = math.log((1 + (FV * r) / p) / math.log(1 + r)))

Note that in your code you convert n to a str twice which is unnecessary

How to make a simple modal pop up form using jquery and html?

I have placed here complete bins for above query. you can check demo link too.

Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop

HTML

<div id="panel">
  <input type="button" class="button" value="1" id="btn1">
  <input type="button" class="button" value="2" id="btn2">
  <input type="button" class="button" value="3" id="btn3">
  <br>
  <input type="text" id="valueFromMyModal">
  <!-- Dialog Box-->
  <div class="dialog" id="myform">
    <form>
      <label id="valueFromMyButton">
      </label>
      <input type="text" id="name">
      <div align="center">
        <input type="button" value="Ok" id="btnOK">
      </div>
    </form>
  </div>
</div>

JQuery

$(function() {
    $(".button").click(function() {
        $("#myform #valueFromMyButton").text($(this).val().trim());
        $("#myform input[type=text]").val('');
        $("#myform").show(500);
    });
    $("#btnOK").click(function() {
        $("#valueFromMyModal").val($("#myform input[type=text]").val().trim());
        $("#myform").hide(400);
    });
});

CSS

.button{
  border:1px solid #333;
  background:#6479fd;
}
.button:hover{
  background:#a4a9fd;
}
.dialog{
  border:5px solid #666;
  padding:10px;
  background:#3A3A3A;
  position:absolute;
  display:none;
}
.dialog label{
  display:inline-block;
  color:#cecece;
}
input[type=text]{
  border:1px solid #333;
  display:inline-block;
  margin:5px;
}
#btnOK{
  border:1px solid #000;
  background:#ff9999;
  margin:5px;
}

#btnOK:hover{
  border:1px solid #000;
  background:#ffacac;
}

Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop

How to get client's IP address using JavaScript?

Not possible in general unless you use some kind of external service.

How can I debug a .BAT script?

Make sure there are no 'echo off' statements in the scripts and call 'echo on' after calling each script to reset any you have missed.

The reason is that if echo is left on, then the command interpreter will output each command (after parameter processing) before executing it. Makes it look really bad for using in production, but very useful for debugging purposes as you can see where output has gone wrong.

Also, make sure you are checking the ErrorLevels set by the called batch scripts and programs. Remember that there are 2 different methods used in .bat files for this. If you called a program, the Error level is in %ERRORLEVEL%, while from batch files the error level is returned in the ErrorLevel variable and doesn't need %'s around it.

How do I change UIView Size?

You can do this in Interface Builder:

1) Control-drag from a frame view (e.g. questionFrame) to main View, in the pop-up select "Equal heights".

2)Then go to size inspector of the frame, click edit "Equal height to Superview" constraint, set the multiplier to 0.7 and hit return.

You'll see that constraint has changed from "Equal height to..." to "Proportional height to...".

How can I replace text with CSS?

This is simple, short, and effective. No additional HTML is necessary.

.pvw-title { color: transparent; }

.pvw-title:after {
        content: "New Text To Replace Old";
        color: black; /* set color to original text color */
        margin-left: -30px;
        /* margin-left equals length of text we're replacing */
    }

I had to do this for replacing link text, other than home, for WooCommerce breadcrumbs

Sass/Less

body.woocommerce .woocommerce-breadcrumb > a[href$="/shop/"] {
    color: transparent;
    &:after {
        content: "Store";
        color: grey;
        margin-left: -30px;
    }
}

CSS

body.woocommerce .woocommerce-breadcrumb > a[href$="/shop/"] {
    color: transparent;
}

body.woocommerce .woocommerce-breadcrumb > a[href$="/shop/"]&:after {
    content: "Store";
    color: @child-color-grey;
    margin-left: -30px;
}

Why are Python's 'private' methods not actually private?

The name scrambling is used to ensure that subclasses don't accidentally override the private methods and attributes of their superclasses. It's not designed to prevent deliberate access from outside.

For example:

>>> class Foo(object):
...     def __init__(self):
...         self.__baz = 42
...     def foo(self):
...         print self.__baz
...     
>>> class Bar(Foo):
...     def __init__(self):
...         super(Bar, self).__init__()
...         self.__baz = 21
...     def bar(self):
...         print self.__baz
...
>>> x = Bar()
>>> x.foo()
42
>>> x.bar()
21
>>> print x.__dict__
{'_Bar__baz': 21, '_Foo__baz': 42}

Of course, it breaks down if two different classes have the same name.

How to remove files from git staging area?

You could use

git reset HEAD

then add the specific files you want with

git add [directory/]filename

What is secret key for JWT based authentication and how to generate it?

What is the secret key does, you may have already known till now. It is basically HMAC SH256 (Secure Hash). The Secret is a symmetrical key.

Using the same key you can generate, & reverify, edit, etc.

For more secure, you can go with private, public key (asymmetric way). Private key to create token, public key to verify at client level.

Coming to secret key what to give You can give anything, "sudsif", "sdfn2173", any length

you can use online generator, or manually write

I prefer using openssl

C:\Users\xyz\Desktop>openssl rand -base64 12
65JymYzDDqqLW8Eg

generate, then encode with base 64

C:\Users\xyz\Desktop>openssl rand -out openssl-secret.txt -hex 20

The generated value is saved inside the file named "openssl-secret.txt"

generate, & store into a file.

One thing is giving 12 will generate, 12 characters only, but since it is base 64 encoded, it will be (4/3*n) ceiling value.

I recommend reading this article

https://auth0.com/blog/brute-forcing-hs256-is-possible-the-importance-of-using-strong-keys-to-sign-jwts/

C# How do I click a button by hitting Enter whilst textbox has focus?

The simple option is just to set the forms's AcceptButton to the button you want pressed (usually "OK" etc):

    TextBox tb = new TextBox();
    Button btn = new Button { Dock = DockStyle.Bottom };
    btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
    Application.Run(new Form { AcceptButton = btn, Controls = { tb, btn } });

If this isn't an option, you can look at the KeyDown event etc, but that is more work...

    TextBox tb = new TextBox();
    Button btn = new Button { Dock = DockStyle.Bottom };
    btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
    tb.KeyDown += (sender,args) => {
        if (args.KeyCode == Keys.Return)
        {
            btn.PerformClick();
        }
    };
    Application.Run(new Form { Controls = { tb, btn } });

How do I calculate a point on a circle’s circumference?

Here is my implementation in C#:

    public static PointF PointOnCircle(float radius, float angleInDegrees, PointF origin)
    {
        // Convert from degrees to radians via multiplication by PI/180        
        float x = (float)(radius * Math.Cos(angleInDegrees * Math.PI / 180F)) + origin.X;
        float y = (float)(radius * Math.Sin(angleInDegrees * Math.PI / 180F)) + origin.Y;

        return new PointF(x, y);
    }

htaccess redirect to https://www

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R]

How do I specify new lines on Python, when writing on files?

The same way with '\n', though you'd probably not need the '\r'. Is there a reason you have it in your Java version? If you do need/want it, you can use it in the same way in Python too.

graphing an equation with matplotlib

This is because in line

graph(x**3+2*x-4, range(-10, 11))

x is not defined.

The easiest way is to pass the function you want to plot as a string and use eval to evaluate it as an expression.

So your code with minimal modifications will be

import numpy as np  
import matplotlib.pyplot as plt  
def graph(formula, x_range):  
    x = np.array(x_range)  
    y = eval(formula)
    plt.plot(x, y)  
    plt.show()

and you can call it as

graph('x**3+2*x-4', range(-10, 11))

Violation Long running JavaScript task took xx ms

I found a solution in Apache Cordova source code. They implement like this:

var resolvedPromise = typeof Promise == 'undefined' ? null : Promise.resolve();
var nextTick = resolvedPromise ? function(fn) { resolvedPromise.then(fn); } : function(fn) { setTimeout(fn); };

Simple implementation, but smart way.

Over the Android 4.4, use Promise. For older browsers, use setTimeout()


Usage:

nextTick(function() {
  // your code
});

After inserting this trick code, all warning messages are gone.

How do I view the SSIS packages in SQL Server Management Studio?

If you have SQL Server installed there is also a menu option for finding local SSIS packages.

In the Start menu > All Programs > 'Microsoft Sql Server' there should be a menu option for 'Integration Services' > 'Execute Package Utility' (this is available if SSIS was included in your SQLserver installation).

When you open the Execute Package Utility, type your local sql server name in the 'Server Name' textbox and click on the Package button, you will see your saved package in the popup window. From here you can run your previously saved package

How to hide navigation bar permanently in android activity?

I think this code will resolve your issue. Copy and paste this code on your MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {                          
    super.onCreate(savedInstanceState);

    View decorView = getWindow().getDecorView();
    decorView.setOnSystemUiVisibilityChangeListener
    (new View.OnSystemUiVisibilityChangeListener() {
        @Override
        public void onSystemUiVisibilityChange(int visibility) {

            if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                hideNavigationBar();
            } 
        }
    });
}



private void hideNavigationBar() {
   getWindow().getDecorView().setSystemUiVisibility(
        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|
        View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}

It will works on Android-10. I hope it will helps.

How can I get color-int from color resource?

Best Approach

As @sat answer, good approach for getting color is

ResourcesCompat.getColor(getResources(), R.color.your_color, null);

or use below way when you don't have access to getResources() method.

Context context  = getContext(); // like Dialog class
ResourcesCompat.getColor(context.getResources(), R.color.your_color, null);

What i do is

public void someMethod(){
    ...
    ResourcesCompat.getColor(App.getRes(), R.color.your_color, null);
}

It is most simple to use anywhere in your app! Even in Util class or any class where you don't have Context or getResource()

Problem (When you don't have Context)

When you don't have Context access, like a method in your Util class.

Assume below method without Context.

public void someMethod(){
    ...
    // can't use getResource() without Context.
}

Now you will pass Context as a parameter in this method and use getResources().

public void someMethod(Context context){
    ...
    context.getResources...
}

So here is a Bonus unique solution by which you can access resources from anywhere like Util class . Add Resources to your Application class or Create one if does not exist.

import android.app.Application;
import android.content.res.Resources;

public class App extends Application {
    private static App mInstance;
    private static Resources res;


    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        res = getResources();
    }

    public static App getInstance() {
        return mInstance;
    }

    public static Resources getResourses() {
        return res;
    }

}

Add name field to your manifest.xml <application tag. (If not added already)

<application
        android:name=".App"
        ...
        >
        ...
    </application>

Now you are good to go. Use ResourcesCompat.getColor(App.getRes(), R.color.your_color, null); anywhere in app.

How to read the post request parameters using JavaScript

Why not use localStorage or any other way to set the value that you would like to pass?

That way you have access to it from anywhere!

By anywhere I mean within the given domain/context

jQuery Popup Bubble/Tooltip

QTip has bug with jQuery 1.4.2. I had to switch to jQuery Bubble Pop up http://www.vegabit.com/jquery_bubble_popup_v2/#examples and it works great!

In SQL Server, how to create while loop in select

  1. Create function that parses incoming string (say "AABBCC") as a table of strings (in particular "AA", "BB", "CC").
  2. Select IDs from your table and use CROSS APPLY the function with data as argument so you'll have as many rows as values contained in the current row's data. No need of cursors or stored procs.

How to pass a callback as a parameter into another function

If you google for javascript callback function example you will get Getting a better understanding of callback functions in JavaScript

This is how to do a callback function:

function f() {
    alert('f was called!');
}

function callFunction(func) {
    func();
}

callFunction(f);

How to pass in parameters when use resource service?

I think I see your problem, you need to use the @ syntax to define parameters you will pass in this way, also I'm not sure what loginID or password are doing you don't seem to define them anywhere and they are not being used as URL parameters so are they being sent as query parameters?

This is what I can suggest based on what I see so far:

.factory('MagComments', function ($resource) {
    return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
      loginID : organEntity,
      password : organCommpassword,
      id : '@magId'
    });
  })

The @magId string will tell the resource to replace :id with the property magId on the object you pass it as parameters.

I'd suggest reading over the documentation here (I know it's a bit opaque) very carefully and looking at the examples towards the end, this should help a lot.

Memory address of an object in C#

Instead of this code, you should call GetHashCode(), which will return a (hopefully-)unique value for each instance.

You can also use the ObjectIDGenerator class, which is guaranteed to be unique.

Getting the name of the currently executing method

Thread.currentThread().getStackTrace() will usually contain the method you’re calling it from but there are pitfalls (see Javadoc):

Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace. In the extreme case, a virtual machine that has no stack trace information concerning this thread is permitted to return a zero-length array from this method.

Visual Studio Code open tab in new window

You can also hit Win+Shift+[n]. N being the position the app is in the taskbar. Eg if its pinned as the first app hit WIn+Shift+1 and windows will open a new instance. This works for all applications.

I agree tho all of these workarounds shouldn't be necessary. Pretty much every other app can drag tabs out as a window I can't think of anything I used that doesn't and VSCode should be implementing ubiquitous functions we expect to be there.

Remove Blank option from Select Option with AngularJS

For reference : Why does angularjs include an empty option in select?

The empty option is generated when a value referenced by ng-model doesn't exist in a set of options passed to ng-options. This happens to prevent accidental model selection: AngularJS can see that the initial model is either undefined or not in the set of options and don't want to decide model value on its own.

In short: the empty option means that no valid model is selected (by valid I mean: from the set of options). You need to select a valid model value to get rid of this empty option.

Change your code like this

_x000D_
_x000D_
var MyApp=angular.module('MyApp1',[])
MyApp.controller('MyController', function($scope) {
  $scope.feed = {};

  //Configuration
  $scope.feed.configs = [
    {'name': 'Config 1',
     'value': 'config1'},
    {'name': 'Config 2',
     'value': 'config2'},
    {'name': 'Config 3',
     'value': 'config3'}
  ];
  //Setting first option as selected in configuration select
  $scope.feed.config = $scope.feed.configs[0].value;
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="MyApp1">
  <div ng-controller="MyController">
    <input type="text" ng-model="feed.name" placeholder="Name" />
    <!-- <select ng-model="feed.config">
<option ng-repeat="template in configs">{{template.name}}</option>
</select> -->
    <select ng-model="feed.config" ng-options="template.value as template.name for template in feed.configs">
    </select>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Working JSFiddle Demo

UPDATE (Dec 31, 2015)

If You don't want to set a default value and want to remove blank option,

<select ng-model="feed.config" ng-options="template.value as template.name for template in feed.configs">
      <option value="" selected="selected">Choose</option>
</select>

And in JS no need to initialize value.

$scope.feed.config = $scope.feed.configs[0].value;

Best way to check if a drop down list contains a value?

On C# this works:

        if (DDLAlmacen.Items.Count > 0)
        {
            if (DDLAlmacen.Items.FindByValue("AlmacenDefectoAndes").Value == "AlmacenDefectoAndes")
            {
                DDLAlmacen.SelectedValue = "AlmacenDefectoAndes";
            }
        }

Update:

Translating the code above to Visual Basic doesn't work. It throws "System.NullReferenceException: Object reference not set to an instance of an object.."

So. for this to work on Visual Basic, I had to change the code like this:

        If DDLAlmacen.Items.Count > 0 Then
            If DDLAlmacen.Items.Contains(New ListItem("AlmacenDefectoAndes")) Then
                DDLAlmacen.SelectedValue = "AlmacenDefectoAndes"
            End If
        End If

How to pass props to {this.props.children}

The slickest way to do this:

    {React.cloneElement(this.props.children, this.props)}

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>teste4</groupId>
    <artifactId>teste4</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <repositories>
        <repository>
            <id>prime-repo</id>
            <name>PrimeFaces Maven Repository</name>
            <url>http://repository.primefaces.org</url>
            <layout>default</layout>
        </repository>
    </repositories>



    <dependencies>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.2.4</version>
        </dependency>


        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.2.4</version>
        </dependency>



        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>4.0</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces.themes</groupId>
            <artifactId>bootstrap</artifactId>
            <version>1.0.9</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.27</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.2.7.Final</version>
        </dependency>

    </dependencies>


</project>

How to make sure you don't get WCF Faulted state exception?

This error can also be caused by having zero methods tagged with the OperationContract attribute. This was my problem when building a new service and testing it a long the way.

AssertContains on strings in jUnit

assertj variant

import org.assertj.core.api.Assertions;
Assertions.assertThat(actualStr).contains(subStr);

Angularjs - display current date

Template

<span date-now="MM/dd/yyyy"></span>

Directive

.directive('dateNow', ['$filter', function($filter) {
  return {
    link: function( $scope, $element, $attrs) {
      $element.text($filter('date')(new Date(), $attrs.dateNow));
    }
  };
}])

Because you can't access the Date object direcly in a template (for an inline solution), I opteted for this Directive. It also keeps your Controllers clean and is reusable.

Asynchronous Requests with Python requests

I have a lot of issues with most of the answers posted - they either use deprecated libraries that have been ported over with limited features, or provide a solution with too much magic on the execution of the request, making it difficult to error handle. If they do not fall into one of the above categories, they're 3rd party libraries or deprecated.

Some of the solutions works alright purely in http requests, but the solutions fall short for any other kind of request, which is ludicrous. A highly customized solution is not necessary here.

Simply using the python built-in library asyncio is sufficient enough to perform asynchronous requests of any type, as well as providing enough fluidity for complex and usecase specific error handling.

import asyncio

loop = asyncio.get_event_loop()

def do_thing(params):
    async def get_rpc_info_and_do_chores(id):
        # do things
        response = perform_grpc_call(id)
        do_chores(response)

    async def get_httpapi_info_and_do_chores(id):
        # do things
        response = requests.get(URL)
        do_chores(response)

    async_tasks = []
    for element in list(params.list_of_things):
       async_tasks.append(loop.create_task(get_chan_info_and_do_chores(id)))
       async_tasks.append(loop.create_task(get_httpapi_info_and_do_chores(ch_id)))

    loop.run_until_complete(asyncio.gather(*async_tasks))

How it works is simple. You're creating a series of tasks you'd like to occur asynchronously, and then asking a loop to execute those tasks and exit upon completion. No extra libraries subject to lack of maintenance, no lack of functionality required.

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

I used the Visual Studio 2008 Uninstall tool and it worked fine for me.

You can use this tool to uninstall Visual Studio 2008 official release and Visual Studio 2008 Release candidate (Only English version).

Found here, on the MSDN Forum: MSDN forum topic.

I found this answer here

Be sure you run the tool with admin-rights.

HTML/CSS - Adding an Icon to a button

Here's what you can do using font-awesome library.

_x000D_
_x000D_
button.btn.add::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f067\00a0";_x000D_
}_x000D_
_x000D_
button.btn.edit::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f044\00a0";_x000D_
}_x000D_
_x000D_
button.btn.save::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f00c\00a0";_x000D_
}_x000D_
_x000D_
button.btn.cancel::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f00d\00a0";_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<!--FA unicodes here: http://astronautweb.co/snippet/font-awesome/-->_x000D_
<h4>Buttons with text</h4>_x000D_
<button class="btn cancel btn-default">Close</button>_x000D_
<button class="btn add btn-primary">Add</button>_x000D_
<button class="btn add btn-success">Insert</button>_x000D_
<button class="btn save btn-primary">Save</button>_x000D_
<button class="btn save btn-warning">Submit Changes</button>_x000D_
<button class="btn cancel btn-link">Delete</button>_x000D_
<button class="btn edit btn-info">Edit</button>_x000D_
<button class="btn edit btn-danger">Modify</button>_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
<h4>Buttons without text</h4>_x000D_
<button class="btn edit btn-primary" />_x000D_
<button class="btn cancel btn-danger" />_x000D_
<button class="btn add btn-info" />_x000D_
<button class="btn save btn-success" />_x000D_
<button class="btn edit btn-link"/>_x000D_
<button class="btn cancel btn-link"/>
_x000D_
_x000D_
_x000D_

Fiddle here.

Importing csv file into R - numeric values read as characters

In read.table (and its relatives) it is the na.strings argument which specifies which strings are to be interpreted as missing values NA. The default value is na.strings = "NA"

If missing values in an otherwise numeric variable column are coded as something else than "NA", e.g. "." or "N/A", these rows will be interpreted as character, and then the whole column is converted to character.

Thus, if your missing values are some else than "NA", you need to specify them in na.strings.

clearing select using jquery

Assuming a list like below - and assuming some of the options were selected ... (this is a multi select, but this will also work on a single select.

<select multiple='multiple' id='selectListName'> 
    <option>1</option> 
    <option>2</option> 
    <option>3</option> 
    <option>4</option>
</select>

In some function called based on some event, the following code would clear all selected options.

$("#selectListName").prop('selectedIndex', -1);

Do I need to explicitly call the base virtual destructor?

Destructors in C++ automatically gets called in the order of their constructions (Derived then Base) only when the Base class destructor is declared virtual.

If not, then only the base class destructor is invoked at the time of object deletion.

Example: Without virtual Destructor

#include <iostream>

using namespace std;

class Base{
public:
  Base(){
    cout << "Base Constructor \n";
  }

  ~Base(){
    cout << "Base Destructor \n";
  }

};

class Derived: public Base{
public:
  int *n;
  Derived(){
    cout << "Derived Constructor \n";
    n = new int(10);
  }

  void display(){
    cout<< "Value: "<< *n << endl;
  }

  ~Derived(){
    cout << "Derived Destructor \n";
  }
};

int main() {

 Base *obj = new Derived();  //Derived object with base pointer
 delete(obj);   //Deleting object
 return 0;

}

Output

Base Constructor
Derived Constructor
Base Destructor

Example: With Base virtual Destructor

#include <iostream>

using namespace std;

class Base{
public:
  Base(){
    cout << "Base Constructor \n";
  }

  //virtual destructor
  virtual ~Base(){
    cout << "Base Destructor \n";
  }

};

class Derived: public Base{
public:
  int *n;
  Derived(){
    cout << "Derived Constructor \n";
    n = new int(10);
  }

  void display(){
    cout<< "Value: "<< *n << endl;
  }

  ~Derived(){
    cout << "Derived Destructor \n";
    delete(n);  //deleting the memory used by pointer
  }
};

int main() {

 Base *obj = new Derived();  //Derived object with base pointer
 delete(obj);   //Deleting object
 return 0;

}

Output

Base Constructor
Derived Constructor
Derived Destructor
Base Destructor

It is recommended to declare base class destructor as virtual otherwise, it causes undefined behavior.

Reference: Virtual Destructor

How to add plus one (+1) to a SQL Server column in a SQL Query

"UPDATE TableName SET TableField = TableField + 1 WHERE SomeFilterField = @ParameterID"

How to get a list of images on docker registry v2

I had to do the same here and the above works except I had to provide login details as it was a local docker repository.

It is as per the above but with supplying the username/password in the URL.

curl -k -X GET https://yourusername:yourpassword@theregistryURL/v2/_catalog

It comes back as unformatted JSON.

I piped it through the python formatter for ease of human reading, in case you would like to have it in this format.

curl -k -X GET https://yourusername:yourpassword@theregistryURL/v2/_catalog | python -m json.tool

Change select box option background color

Simply change bg color

select { background: #6ac17a; color:#fff; }

BeanFactory vs ApplicationContext

BeanFactory and ApplicationContext both are ways to get beans from your spring IOC container but still there are some difference.

BeanFactory is the actual container which instantiates, configures, and manages a number of bean's. These beans are typically collaborate with one another, and thus have dependencies between themselves. These dependencies are reflected in the configuration data used by the BeanFactory.

BeanFactory and ApplicationContext both are Java interfaces and ApplicationContext extends BeanFactory. Both of them are configuration using XML configuration files. In short BeanFactory provides basic Inversion of control(IoC) and Dependency Injection (DI) features while ApplicationContext provides advanced features.

A BeanFactory is represented by the interface "org.springframework.beans.factory" Where BeanFactory, for which there are multiple implementations.

ClassPathResource resource = new ClassPathResource("appConfig.xml");
XmlBeanFactory factory = new XmlBeanFactory(resource);

DIFFERENCE

  1. BeanFactory instantiate bean when you call getBean() method while ApplicationContext instantiate Singleton bean when container is started, It doesn't wait for getBean() to be called.

  2. BeanFactory doesn't provide support for internationalization but ApplicationContext provides support for it.

  3. Another difference between BeanFactory vs ApplicationContext is ability to publish event to beans that are registered as listener.

  4. One of the popular implementation of BeanFactory interface is XMLBeanFactory while one of the popular implementation of ApplicationContext interface is ClassPathXmlApplicationContext.

  5. If you are using auto wiring and using BeanFactory than you need to register AutoWiredBeanPostProcessor using API which you can configure in XML if you are using ApplicationContext. In summary BeanFactory is OK for testing and non production use but ApplicationContext is more feature rich container implementation and should be favored over BeanFactory

  6. BeanFactory by default its support Lazy loading and ApplicationContext by default support Aggresive loading.

Communicating between a fragment and an activity - best practices

There are severals ways to communicate between activities, fragments, services etc. The obvious one is to communicate using interfaces. However, it is not a productive way to communicate. You have to implement the listeners etc.

My suggestion is to use an event bus. Event bus is a publish/subscribe pattern implementation.

You can subscribe to events in your activity and then you can post that events in your fragments etc.

Here on my blog post you can find more detail about this pattern and also an example project to show the usage.

How do I get the current date and current time only respectively in Django?

A related info, to the question...

In django, use timezone.now() for the datetime field, as django supports timezone, it just returns datetime based on the USE TZ settings, or simply timezone 'aware' datetime objects

For a reference, I've got TIME_ZONE = 'Asia/Kolkata' and USE_TZ = True,

from django.utils import timezone
import datetime

print(timezone.now())  # The UTC time
print(timezone.localtime())  # timezone specified time, 
print(datetime.datetime.now())  # default local time

# output
2020-12-11 09:13:32.430605+00:00
2020-12-11 14:43:32.430605+05:30  # IST is UTC+5:30
2020-12-11 14:43:32.510659

refer timezone settings and Internationalization and localization in django docs for more details.

String to list in Python

You can use the split() function, which returns a list, to separate them.

letters = 'QH QD JC KD JS'

letters_list = letters.split()

Printing letters_list would now format it like this:

['QH', 'QD', 'JC', 'KD', 'JS']

Now you have a list that you can work with, just like you would with any other list. For example accessing elements based on indexes:

print(letters_list[2])

This would print the third element of your list, which is 'JC'

How to make div go behind another div?

One possible could be like this,

HTML

<div class="box-left-mini">
    <div class="front">this div is infront</div>
    <div class="behind">
        this div is behind
    </div>
</div>

CSS

.box-left-mini{
float:left;
background-image:url(website-content/hotcampaign.png);
width:292px;
height:141px;
}
.front{
    background-color:lightgreen;
}
.behind{
    background-color:grey;
    position:absolute;
    width:100%;
    height:100%;
    top:0;
    z-index:-1;
}

http://jsfiddle.net/MgtWS/

But it really depends on the layout of your div elements i.e. if they are floating, or absolute positioned etc.

How to get selected value of a dropdown menu in ReactJS

If you want to get value from a mapped select input then you can refer to this example:

class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          fruit: "banana",
        };
    
        this.handleChange = this.handleChange.bind(this);
      }
    
      handleChange(e) {
        console.log("Fruit Selected!!");
        this.setState({ fruit: e.target.value });
      }
    
      render() {
        return (
          <div id="App">
            <div className="select-container">
              <select value={this.state.fruit} onChange={this.handleChange}>
                {options.map((option) => (
                  <option value={option.value}>{option.label}</option>
                ))}
              </select>
            </div>
          </div>
        );
      }
    }
    
    export default App;

QtCreator: No valid kits found

No valid Kits found The problem occurs because qt-creator don't know the versions of your qt, your compiler or your debugger. First off, let's solve the Qt versions. It may normally solve the others too ;).

You try to create a new project, run select a kit and then there is no kit available in the list.

Follow the steps:

  1. Execute in your terminal the command: sudo apt-get install qt5-default to install qt version 5.
  2. Verify the version of your Qt and the location of your qmake file. Do this by executing in your terminal the command qmake --version. You may have a result similar to this line. QMake version 3.1 Using Qt version 5.9.5 in /usr/lib/x86_64-linux-gnu. What's important here is the location /usr/lib/x86_64-linux-gnu.
  3. Open your Qt-creator.
  4. Go to "Tools>Options" or "Outils>Options"
  5. Select the Qt Versions combobox and select and click "Add" or "Ajouter"
  6. Then find the qmake file in the location of step 2. Here /usr/lib/x86_64-linux-gnu/qt5/bin/ here you have the qmake file for qt5. Open it, click Apply.
  7. Go to "Kits" combobox. Select Desktop(by default) or Desktop(par défaut). Then scroll down to the button to select Qt version: and list down to select the version you just add. 8.Then apply all. Check your compiler and debugger and it's ok. You're done.

Yes I ...

Hope it's help ;)

When is the @JsonProperty property used and what is it used for?

Here's a good example. I use it to rename the variable because the JSON is coming from a .Net environment where properties start with an upper-case letter.

public class Parameter {
  @JsonProperty("Name")
  public String name;
  @JsonProperty("Value")
  public String value; 
}

This correctly parses to/from the JSON:

"Parameter":{
  "Name":"Parameter-Name",
  "Value":"Parameter-Value"
}

TypeScript: Creating an empty typed container array

The issue of correctly pre-allocating a typed array in TypeScript was somewhat obscured for due to the array literal syntax, so it wasn't as intuitive as I first thought.

The correct way would be

var arr : Criminal[] = [];

This will give you a correctly typed, empty array stored in the variable 'arr'

Hope this helps others!

How to add link to flash banner

If you have a flash FLA file that shows the FLV movie you can add a button inside the FLA file. This button can be given an action to load the URL.

on (release) {
  getURL("http://someurl/");
}

To make the button transparent you can place a square inside it that is moved to the hit-area frame of the button.

I think it would go too far to explain into depth with pictures how to go about in stackoverflow.

How to convert HH:mm:ss.SSS to milliseconds?

You can use SimpleDateFormat to do it. You just have to know 2 things.

  1. All dates are internally represented in UTC
  2. .getTime() returns the number of milliseconds since 1970-01-01 00:00:00 UTC.
package se.wederbrand.milliseconds;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class Main {        
    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

        String inputString = "00:01:30.500";

        Date date = sdf.parse("1970-01-01 " + inputString);
        System.out.println("in milliseconds: " + date.getTime());        
    }
}

How to increase Bootstrap Modal Width?

In Bootstrap, the default width of modal-dialog is 600px. But you can explicitly change its width. For instance, if you would like to maximize its width to the value of your choice, 800px for instance, you do as following:

.modal-dialog {
    width: 800px;
    margin: 30px auto;
}

Note: This change sets to all modal dialog you use in your application. Also, my suggestion is it is best to have your own CSS rules defined and not to touch the core of the framework.

If you only want it to be set for specific modal dialog, use your own catchy class name as modal-800 whose width is set to 800px, as following:

HTML

<div class="modal">
   <div class="modal-dialog modal-800">
      <div class="modal-content">

      </div>
   </div>
</div>

CSS

.modal-dialog.modal-800 {
    width: 800px;
    margin: 30px auto;
}

Likewise, you can have class name as based on the width size like modal-700 whose width is 700px.

Hope it's helpful!

Could not load file or assembly Exception from HRESULT: 0x80131040

Finally found the answer!! Go to References --> right cilck on dll file that causing the problem --> select the properties --> check the version --> match the version in properties to web config

<dependentAssembly>
    <assemblyIdentity name="YourDllFile" publicKeyToken="2780ccd10d57b246"               culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-YourDllFileVersion" newVersion="YourDllFileVersion" />
  </dependentAssembly>

How to get all elements which name starts with some string?

You can try using jQuery with the Attribute Contains Prefix Selector.

$('[id|=q1_]')

Haven't tested it though.

Changing button color programmatically

I believe you want bgcolor. Something like this:

document.getElementById("button").bgcolor="#ffffff";

Here are a couple of demos that might help:

Background Color

Background Color Changer

What is PEP8's E128: continuation line under-indented for visual indent?

PEP-8 recommends you indent lines to the opening parentheses if you put anything on the first line, so it should either be indenting to the opening bracket:

urlpatterns = patterns('',
                       url(r'^$', listing, name='investment-listing'))

or not putting any arguments on the starting line, then indenting to a uniform level:

urlpatterns = patterns(
    '',
    url(r'^$', listing, name='investment-listing'),
)

urlpatterns = patterns(
    '', url(r'^$', listing, name='investment-listing'))

I suggest taking a read through PEP-8 - you can skim through a lot of it, and it's pretty easy to understand, unlike some of the more technical PEPs.

Remove multiple whitespaces

Without preg_replace()

$str = "This is   a Text \n and so on \t     Text text.";
$str = str_replace(["\r", "\n", "\t"], " ", $str);
while (strpos($str, "  ") !== false)
{
    $str = str_replace("  ", " ", $str);
}
echo $str;

jQuery table sort

This one does not hang up the browser/s, easy configurable further:

var table = $('table');

$('th.sortable').click(function(){
    var table = $(this).parents('table').eq(0);
    var ths = table.find('tr:gt(0)').toArray().sort(compare($(this).index()));
    this.asc = !this.asc;
    if (!this.asc)
       ths = ths.reverse();
    for (var i = 0; i < ths.length; i++)
       table.append(ths[i]);
});

function compare(idx) {
    return function(a, b) {
       var A = tableCell(a, idx), B = tableCell(b, idx)
       return $.isNumeric(A) && $.isNumeric(B) ? 
          A - B : A.toString().localeCompare(B)
    }
}

function tableCell(tr, index){ 
    return $(tr).children('td').eq(index).text() 
}

How to extract URL parameters from a URL with Ruby or Rails?

I think you want to turn any given URL string into a HASH?

You can try http://www.ruby-doc.org/stdlib/libdoc/cgi/rdoc/classes/CGI.html#M000075

require 'cgi'

CGI::parse('param1=value1&param2=value2&param3=value3')

returns

{"param1"=>["value1"], "param2"=>["value2"], "param3"=>["value3"]}

Including dependencies in a jar with Maven

Thanks I have added below snippet in POM.xml file and Mp problem resolved and create fat jar file that include all dependent jars.

<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
        <executions>
            <execution>
                <phase>package</phase>
                <goals>
                    <goal>single</goal>
                </goals>
            </execution>
        </executions>
        <configuration>
            <descriptorRefs>
                <descriptorRef>dependencies</descriptorRef>
            </descriptorRefs>
        </configuration>
    </plugin>
</plugins>

Sort JavaScript object by key

Pure JavaScript answer to sort an Object. This is the only answer that I know of that will handle negative numbers. This function is for sorting numerical Objects.

Input obj = {1000: {}, -1200: {}, 10000: {}, 200: {}};

function osort(obj) {
var keys = Object.keys(obj);
var len = keys.length;
var rObj = [];
var rK = [];
var t = Object.keys(obj).length;
while(t > rK.length) {
    var l = null;
    for(var x in keys) {
        if(l && parseInt(keys[x]) < parseInt(l)) {
            l = keys[x];
            k = x;
        }
        if(!l) { // Find Lowest
            var l = keys[x];
            var k = x;
        }
    }
    delete keys[k];
    rK.push(l);
}

for (var i = 0; i < len; i++) {

    k = rK[i];
    rObj.push(obj[k]);
}
return rObj;
}

The output will be an object sorted by those numbers with new keys starting at 0.

In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?

I just got this error and i came to know that it is about the local variable alias

at the end of the stored procedure i had like

select @localvariable1,@localvariable2

it was working fine in sql but when i ran this in ssrs it was always throwing error but after I gave alias it is fixed

select @localvariable1 as A,@localvariable2 as B

How to display table data more clearly in oracle sqlplus

In case you have a dump made with sqlplus and the output is garbled as someone did not set those 3 values before, there's a way out.

Just a couple hours ago DB admin send me that ugly looking output of query executed in sqlplus (I dunno, maybe he hates me...). I had to find a way out: this is an awk script to parse that output to make it at least more readable. It's far not perfect, but I did not have enough time to polish it properly. Anyway, it does the job quite well.

awk ' function isDashed(ln){return ln ~ /^---+/};function addLn(){ln2=ln1; ln1=ln0;ln0=$0};function isLoaded(){return l==1||ln2!=""}; function printHeader(){hdr=hnames"\n"hdash;if(hdr!=lastHeader){lastHeader=hdr;print hdr};hnames="";hdash=""};function isHeaderFirstLn(){return isDashed(ln0) && !isDashed(ln1) && !isDashed(ln2) }; function isDataFirstLn(){return isDashed(ln2)&&!isDashed(ln1)&&!isDashed(ln0)}                         BEGIN{_d=1;h=1;hnames="";hdash="";val="";ln2="";ln1="";ln0="";fheadln=""}                                 { addLn();  if(!isLoaded()){next}; l=1;             if(h==1){if(!isDataFirstLn()){if(_d==0){hnames=hnames" "ln1;_d=1;}else{hdash=hdash" "ln1;_d=0}}else{_d=0;h=0;val=ln1;printHeader()}}else{if(!isHeaderFirstLn()){val=val" "ln1}else{print val;val="";_d=1;h=1;hnames=ln1}}   }END{if(val!="")print val}'

In case anyone else would like to try improve this script, below are the variables: hnames -- column names in the header, hdash - dashed below the header, h -- whether I'm currently parsing header (then ==1), val -- the data, _d - - to swap between hnames and hdash, ln0 - last line read, ln1 - line read previously (it's the one i'm actually working with), ln2 - line read before ln1

Happy parsing!

Oh, almost forgot... I use this to prettify sqlplus output myself:

[oracle@ora ~]$ cat prettify_sql 
set lines 256
set trimout on
set tab off
set pagesize 100
set colsep " | "

colsep is optional, but it makes output look like sqlite which is easier to parse using scripts.

EDIT: A little preview of parsed and non-parsed output

A little preview of parsed and non-parsed output

go get results in 'terminal prompts disabled' error for github private repo

I found this extremely helpful, and it solved my problem. This command will allow your 2FA to do its thing (and save you the trouble of entering your username and password):

git config --global --add url."[email protected]:".insteadOf "https://github.com/"

Source: http://albertech.blogspot.com/2016/11/fix-git-error-could-not-read-username.html

If you're not using 2FA, you can still use SSH and this will work.

Edit: added the --add flag as suggested by slatunje.

MySQL Removing Some Foreign keys

Check what's the CONSTRAINT name and the FOREIGN KEY name:

SHOW CREATE TABLE table_name;

Remove both the CONSTRAINT name and the FOREIGN KEY name:

ALTER TABLE table_name
  DROP FOREIGN KEY the_name_after_CONSTRAINT,
  DROP KEY the_name_after_FOREIGN_KEY;

Hope this helps!

What is CDATA in HTML?

CDATA is Obsolete.

Note that CDATA sections should not be used within HTML; they only work in XML.

So do not use it in HTML 5.

https://developer.mozilla.org/en-US/docs/Web/API/CDATASection#Specifications

Screenshot from MDN

How do I escape ampersands in batch files?

& is used to separate commands. Therefore you can use ^ to escape the &.

How do I get formatted JSON in .NET using C#?

You are going to have a hard time accomplishing this with JavaScriptSerializer.

Try JSON.Net.

With minor modifications from JSON.Net example

using System;
using Newtonsoft.Json;

namespace JsonPrettyPrint
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Product product = new Product
                {
                    Name = "Apple",
                    Expiry = new DateTime(2008, 12, 28),
                    Price = 3.99M,
                    Sizes = new[] { "Small", "Medium", "Large" }
                };

            string json = JsonConvert.SerializeObject(product, Formatting.Indented);
            Console.WriteLine(json);

            Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
        }
    }

    internal class Product
    {
        public String[] Sizes { get; set; }
        public decimal Price { get; set; }
        public DateTime Expiry { get; set; }
        public string Name { get; set; }
    }
}

Results

{
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ],
  "Price": 3.99,
  "Expiry": "\/Date(1230447600000-0700)\/",
  "Name": "Apple"
}

Documentation: Serialize an Object

Pandas read_sql with parameters

The read_sql docs say this params argument can be a list, tuple or dict (see docs).

To pass the values in the sql query, there are different syntaxes possible: ?, :1, :name, %s, %(name)s (see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2 in your case I suppose).

In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2 documentation, they support the %(name)s style (and so not the :name I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:

df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
                     'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
                   db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
                   index_col=['Timestamp'])

How to get the parent dir location

A simple way can be:

import os
current_dir =  os.path.abspath(os.path.dirname(__file__))
parent_dir = os.path.abspath(current_dir + "/../")
print parent_dir

Connecting to remote MySQL server using PHP

  • firewall of the server must be set-up to enable incomming connections on port 3306
  • you must have a user in MySQL who is allowed to connect from % (any host) (see manual for details)

The current problem is the first one, but right after you resolve it you will likely get the second one.

How to add comments into a Xaml file in WPF?

Found a nice solution by Laurent Bugnion, it can look something like this:

<UserControl xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:comment="Tag to add comments"
             mc:Ignorable="d comment" d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Button Width="100"
                comment:Width="example comment on Width, will be ignored......">
        </Button>
    </Grid>
</UserControl>

Here's the link: http://blog.galasoft.ch/posts/2010/02/quick-tip-commenting-out-properties-in-xaml/

A commenter on the link provided extra characters for the ignore prefix in lieu of highlighting:

mc:Ignorable=”ØignoreØ”

How to get Map data using JDBCTemplate.queryForMap

I know this is really old, but this is the simplest way to query for Map.

Simply implement the ResultSetExtractor interface to define what type you want to return. Below is an example of how to use this. You'll be mapping it manually, but for a simple map, it should be straightforward.

jdbcTemplate.query("select string1,string2 from table where x=1", new ResultSetExtractor<Map>(){
    @Override
    public Map extractData(ResultSet rs) throws SQLException,DataAccessException {
        HashMap<String,String> mapRet= new HashMap<String,String>();
        while(rs.next()){
            mapRet.put(rs.getString("string1"),rs.getString("string2"));
        }
        return mapRet;
    }
});

This will give you a return type of Map that has multiple rows (however many your query returned) and not a list of Maps. You can view the ResultSetExtractor docs here: http://docs.spring.io/spring-framework/docs/2.5.6/api/org/springframework/jdbc/core/ResultSetExtractor.html

Efficient way to Handle ResultSet in Java

Here is the code little modified that i got it from google -

 List data_table = new ArrayList<>();
    Class.forName("oracle.jdbc.driver.OracleDriver");
            con = DriverManager.getConnection(conn_url, user_id, password);
            Statement stmt = con.createStatement();
            System.out.println("query_string: "+query_string);
            ResultSet rs = stmt.executeQuery(query_string);
            ResultSetMetaData rsmd = rs.getMetaData();


            int row_count = 0;
            while (rs.next()) {
                HashMap<String, String> data_map = new HashMap<>();
                if (row_count == 240001) {
                    break;
                }
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    data_map.put(rsmd.getColumnName(i), rs.getString(i));
                }
                data_table.add(data_map);
                row_count = row_count + 1;
            }
            rs.close();
            stmt.close();
            con.close();

How do you exit from a void function in C++?

void foo() {
  /* do some stuff */
  if (!condition) {
    return;
  }
}

You can just use the return keyword just like you would in any other function.

Resize UIImage and change the size of UIImageView

When you get the width and height of a resized image Get width of a resized image after UIViewContentModeScaleAspectFit, you can resize your imageView:

imageView.frame = CGRectMake(0, 0, resizedWidth, resizedHeight);
imageView.center = imageView.superview.center;

I haven't checked if it works, but I think all should be OK

Create a new TextView programmatically then display it below another TextView

If it's not important to use a RelativeLayout, you could use a LinearLayout, and do this:

LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);

Doing this allows you to avoid the addRule method you've tried. You can simply use addView() to add new TextViews.

Complete code:

String[] textArray = {"One", "Two", "Three", "Four"};
LinearLayout linearLayout = new LinearLayout(this);
setContentView(linearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);        
for( int i = 0; i < textArray.length; i++ )
{
    TextView textView = new TextView(this);
    textView.setText(textArray[i]);
    linearLayout.addView(textView);
}

How to fix Error: this class is not key value coding-compliant for the key tableView.'

Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?

Eclipse IDE: How to zoom in on text?

On Mac you can do Press 'Command' and '+' buttons to zoom in. press 'Command' and '-' buttons to zoom out.

Reference an Element in a List of Tuples

So you have "a list of tuples", let me assume that you are manipulating some 2-dimension matrix, and, in this case, one convenient interface to accomplish what you need is the one numpy provides.

Say you have an array arr = numpy.array([[1, 2], [3, 4], [5, 6]]), you can use arr[:, 0] to get a new array of all the first elements in each "tuple".

What is the difference between char * const and const char *?

Two rules

  1. If const is between char and *, it will affect the left one.
  2. If const is not between char and *, it will affect the nearest one.

e.g.

  1. char const *. This is a pointer points to a constant char.
  2. char * const. This is a constant pointer points to a char.

Enter key in textarea

My scenario is when the user strikes the enter key while typing in textarea i have to include a line break.I achieved this using the below code......Hope it may helps somebody......

function CheckLength()
{
    var keyCode = event.keyCode
    if (keyCode == 13)
    {
        document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value = document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value + "\n<br>";
    }
}

Javascript loading CSV file into an array

If your not overly worried about the size of the file then it may be easier for you to store the data as a JS object in another file and import it in your . Either synchronously or asynchronously using the syntax <script src="countries.js" async></script>. Saves on you needing to import the file and parse it.

However, i can see why you wouldnt want to rewrite 10000 entries so here's a basic object orientated csv parser i wrote.

function requestCSV(f,c){return new CSVAJAX(f,c);};
function CSVAJAX(filepath,callback)
{
    this.request = new XMLHttpRequest();
    this.request.timeout = 10000;
    this.request.open("GET", filepath, true);
    this.request.parent = this;
    this.callback = callback;
    this.request.onload = function() 
    {
        var d = this.response.split('\n'); /*1st separator*/
        var i = d.length;
        while(i--)
        {
            if(d[i] !== "")
                d[i] = d[i].split(','); /*2nd separator*/
            else
                d.splice(i,1);
        }
        this.parent.response = d;
        if(typeof this.parent.callback !== "undefined")
            this.parent.callback(d);
    };
    this.request.send();
};

Which can be used like this;

var foo = requestCSV("csvfile.csv",drawlines(lines)); 

The first parameter is the file, relative to the position of your html file in this case. The second parameter is an optional callback function the runs when the file has been completely loaded.

If your file has non-separating commmas then it wont get on with this, as it just creates 2d arrays by chopping at returns and commas. You might want to look into regexp if you need that functionality.

//THIS works 

"1234","ABCD" \n
"!@£$" \n

//Gives you 
[
 [
  1234,
  'ABCD'
 ],
 [
  '!@£$'
 ]
]

//This DOESN'T!

"12,34","AB,CD" \n
"!@,£$" \n

//Gives you

[
 [
  '"12',
  '34"',
  '"AB',
  'CD'
 ]
 [
  '"!@',
  '£$'
 ]
]

If your not used to the OO methods; they create a new object (like a number, string, array) with their own local functions and variables via a 'constructor' function. Very handy in certain situations. This function could be used to load 10 different files with different callbacks all at the same time(depending on your level of csv love! )

Keytool is not recognized as an internal or external command

Run the cmd as run as administrator this worked for me

Execute a shell script in current shell with sudo permission

Basically sudo expects, an executable (command) to follow & you are providing with a .

Hence the error.

Try this way $ sudo setup.sh


MySQL GROUP BY two columns

First, let's make some test data:

create table client (client_id integer not null primary key auto_increment,
                     name varchar(64));
create table portfolio (portfolio_id integer not null primary key auto_increment,
                        client_id integer references client.id,
                        cash decimal(10,2),
                        stocks decimal(10,2));
insert into client (name) values ('John Doe'), ('Jane Doe');
insert into portfolio (client_id, cash, stocks) values (1, 11.11, 22.22),
                                                       (1, 10.11, 23.22),
                                                       (2, 30.30, 40.40),
                                                       (2, 40.40, 50.50);

If you didn't need the portfolio ID, it would be easy:

select client_id, name, max(cash + stocks)
from client join portfolio using (client_id)
group by client_id

+-----------+----------+--------------------+
| client_id | name     | max(cash + stocks) |
+-----------+----------+--------------------+
|         1 | John Doe |              33.33 | 
|         2 | Jane Doe |              90.90 | 
+-----------+----------+--------------------+

Since you need the portfolio ID, things get more complicated. Let's do it in steps. First, we'll write a subquery that returns the maximal portfolio value for each client:

select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id

+-----------+----------+
| client_id | maxtotal |
+-----------+----------+
|         1 |    33.33 | 
|         2 |    90.90 | 
+-----------+----------+

Then we'll query the portfolio table, but use a join to the previous subquery in order to keep only those portfolios the total value of which is the maximal for the client:

 select portfolio_id, cash + stocks from portfolio 
 join (select client_id, max(cash + stocks) as maxtotal 
       from portfolio
       group by client_id) as maxima
 using (client_id)
 where cash + stocks = maxtotal

+--------------+---------------+
| portfolio_id | cash + stocks |
+--------------+---------------+
|            5 |         33.33 | 
|            6 |         33.33 | 
|            8 |         90.90 | 
+--------------+---------------+

Finally, we can join to the client table (as you did) in order to include the name of each client:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         1 | John Doe |            6 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

Note that this returns two rows for John Doe because he has two portfolios with the exact same total value. To avoid this and pick an arbitrary top portfolio, tag on a GROUP BY clause:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
group by client_id, cash + stocks

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

Android device is not connected to USB for debugging (Android studio)

Check installed drivers. If drivers ok, check device usb-port it could be damaged.

deny directory listing with htaccess

Options -Indexes perfectly works for me ,

here is .htaccess file :

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes <---- This Works for Me :)
    </IfModule>


   ....etc stuff

</IfModule>

Before : enter image description here

After :

enter image description here

How do you detect Credit card type based on number?

Here is an example of some boolean functions written in Python that return True if the card is detected as per the function name.

def is_american_express(cc_number):
    """Checks if the card is an american express. If us billing address country code, & is_amex, use vpos
    https://en.wikipedia.org/wiki/Bank_card_number#cite_note-GenCardFeatures-3
    :param cc_number: unicode card number
    """
    return bool(re.match(r'^3[47][0-9]{13}$', cc_number))


def is_visa(cc_number):
    """Checks if the card is a visa, begins with 4 and 12 or 15 additional digits.
    :param cc_number: unicode card number
    """

    # Standard Visa is 13 or 16, debit can be 19
    if bool(re.match(r'^4', cc_number)) and len(cc_number) in [13, 16, 19]:
        return True

    return False


def is_mastercard(cc_number):
    """Checks if the card is a mastercard. Begins with 51-55 or 2221-2720 and 16 in length.
    :param cc_number: unicode card number
    """
    if len(cc_number) == 16 and cc_number.isdigit():  # Check digit, before cast to int
        return bool(re.match(r'^5[1-5]', cc_number)) or int(cc_number[:4]) in range(2221, 2721)
    return False


def is_discover(cc_number):
    """Checks if the card is discover, re would be too hard to maintain. Not a supported card.
    :param cc_number: unicode card number
    """
    if len(cc_number) == 16:
        try:
            # return bool(cc_number[:4] == '6011' or cc_number[:2] == '65' or cc_number[:6] in range(622126, 622926))
            return bool(cc_number[:4] == '6011' or cc_number[:2] == '65' or 622126 <= int(cc_number[:6]) <= 622925)
        except ValueError:
            return False
    return False


def is_jcb(cc_number):
    """Checks if the card is a jcb. Not a supported card.
    :param cc_number: unicode card number
    """
    # return bool(re.match(r'^(?:2131|1800|35\d{3})\d{11}$', cc_number))  # wikipedia
    return bool(re.match(r'^35(2[89]|[3-8][0-9])[0-9]{12}$', cc_number))  # PawelDecowski


def is_diners_club(cc_number):
    """Checks if the card is a diners club. Not a supported card.
    :param cc_number: unicode card number
    """
    return bool(re.match(r'^3(?:0[0-6]|[68][0-9])[0-9]{11}$', cc_number))  # 0-5 = carte blance, 6 = international


def is_laser(cc_number):
    """Checks if the card is laser. Not a supported card.
    :param cc_number: unicode card number
    """
    return bool(re.match(r'^(6304|670[69]|6771)', cc_number))


def is_maestro(cc_number):
    """Checks if the card is maestro. Not a supported card.
    :param cc_number: unicode card number
    """
    possible_lengths = [12, 13, 14, 15, 16, 17, 18, 19]
    return bool(re.match(r'^(50|5[6-9]|6[0-9])', cc_number)) and len(cc_number) in possible_lengths


# Child cards

def is_visa_electron(cc_number):
    """Child of visa. Checks if the card is a visa electron. Not a supported card.
    :param cc_number: unicode card number
    """
    return bool(re.match(r'^(4026|417500|4508|4844|491(3|7))', cc_number)) and len(cc_number) == 16


def is_total_rewards_visa(cc_number):
    """Child of visa. Checks if the card is a Total Rewards Visa. Not a supported card.
    :param cc_number: unicode card number
    """
    return bool(re.match(r'^41277777[0-9]{8}$', cc_number))


def is_diners_club_carte_blanche(cc_number):
    """Child card of diners. Checks if the card is a diners club carte blance. Not a supported card.
    :param cc_number: unicode card number
    """
    return bool(re.match(r'^30[0-5][0-9]{11}$', cc_number))  # github PawelDecowski, jquery-creditcardvalidator


def is_diners_club_carte_international(cc_number):
    """Child card of diners. Checks if the card is a diners club international. Not a supported card.
    :param cc_number: unicode card number
    """
    return bool(re.match(r'^36[0-9]{12}$', cc_number))  # jquery-creditcardvalidator

Warning: push.default is unset; its implicit value is changing in Git 2.0

I realize this is an old post but as I just ran into the same issue and had trouble finding the answer I thought I'd add a bit.

So @hammar's answer is correct. Using push.default simple is, in a way, like configuring tracking on your branches so you don't need to specify remotes and branches when pushing and pulling. The matching option will push all branches to their corresponding counterparts on the default remote (which is the first one that was set up unless you've configured your repo otherwise).

One thing I hope others find useful in the future is that I was running Git 1.8 on OS X Mountain Lion and never saw this error. Upgrading to Mavericks is what suddenly made it show up (running git --version will show git version 1.8.3.4 (Apple Git-47) which I'd never seen until the update to the OS.

How do you return a JSON object from a Java Servlet

First convert the JSON object to String. Then just write it out to the response writer along with content type of application/json and character encoding of UTF-8.

Here's an example assuming you're using Google Gson to convert a Java object to a JSON string:

protected void doXxx(HttpServletRequest request, HttpServletResponse response) {
    // ...

    String json = new Gson().toJson(someObject);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

That's all.

See also:

vi/vim editor, copy a block (not usual action)

Their Documentation says:

Cut and paste:

  1. Position the cursor where you want to begin cutting.
  2. Press v to select characters (or uppercase V to select whole lines).
  3. Move the cursor to the end of what you want to cut.
  4. Press d to cut (or y to copy).
  5. Move to where you would like to paste.
  6. Press P to paste before the cursor, or p to paste after.

Copy and paste is performed with the same steps except for step 4 where you would press y instead of d:

d = delete = cut

y = yank = copy

How do I keep jQuery UI Accordion collapsed by default?

Add the active: false option (documentation)..

$("#accordion").accordion({ header: "h3", collapsible: true, active: false });

Ruby: How to turn a hash into HTTP parameters?

For basic, non-nested hashes, Rails/ActiveSupport has Object#to_query.

>> {:a => "a", :b => ["c", "d", "e"]}.to_query
=> "a=a&b%5B%5D=c&b%5B%5D=d&b%5B%5D=e"
>> CGI.unescape({:a => "a", :b => ["c", "d", "e"]}.to_query)
=> "a=a&b[]=c&b[]=d&b[]=e"

http://api.rubyonrails.org/classes/Object.html#method-i-to_query

Vertical rulers in Visual Studio Code

Visual Studio Code: Version 1.14.2 (1.14.2)

  1. Press Shift + Command + P to open panel
    • For non-macOS users, press Ctrl+P
  2. Enter "settings.json" to open setting files.
  3. At default setting, you can see this:

    // Columns at which to show vertical rulers
    "editor.rulers": [],
    

    This means the empty array won't show the vertical rulers.

  4. At right window "user setting", add the following:

    "editor.rulers": [140]

Save the file, and you will see the rulers.

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

When I ran into this error on Spyder, I changed from running my code line by line to highlighting my block of plotting code and running that all at once. Voila, the image appeared.

How can I install pip on Windows?

Working as of Feb 04 2014 :):

If you have tried installing pip through the Windows installer file from http://www.lfd.uci.edu/~gohlke/pythonlibs/#pip as suggested by @Colonel Panic, you might have installed the pip package manager successfully, but you might be unable to install any packages with pip. You might also have got the same SSL error as I got when I tried to install Beautiful Soup 4 if you look in the pip.log file:

Downloading/unpacking beautifulsoup4
  Getting page https://pypi.python.org/simple/beautifulsoup4/
  Could not fetch URL https://pypi.python.org/simple/beautifulsoup4/: **connection error: [Errno 1] _ssl.c:504: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed**
  Will skip URL https://pypi.python.org/simple/beautifulsoup4/ when looking for download links for beautifulsoup4

The problem is an issue with an old version of OpenSSL being incompatible with pip 1.3.1 and above versions. The easy workaround for now, is to install pip 1.2.1, which does not require SSL:

Installing Pip on Windows:

  1. Download pip 1.2.1 from https://pypi.python.org/packages/source/p/pip/pip-1.2.1.tar.gz
  2. Extract the pip-1.2.1.tar.gz file
  3. Change directory to the extracted folder: cd <path to extracted folder>/pip-1.2.1
  4. Run python setup.py install
  5. Now make sure C:\Python27\Scripts is in PATH because pip is installed in the C:\Python27\Scripts directory unlike C:\Python27\Lib\site-packages where Python packages are normally installed

Now try to install any package using pip.

For example, to install the requests package using pip, run this from cmd:

pip install requests

Whola! requests will be successfully installed and you will get a success message.

How to import a new font into a project - Angular 5

You need to put the font files in assets folder (may be a fonts sub-folder within assets) and refer to it in the styles:

@font-face {
  font-family: lato;
  src: url(assets/font/Lato.otf) format("opentype");
}

Once done, you can apply this font any where like:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: 'lato', 'arial', sans-serif;
}

You can put the @font-face definition in your global styles.css or styles.scss and you would be able to refer to the font anywhere - even in your component specific CSS/SCSS. styles.css or styles.scss is already defined in angular-cli.json. Or, if you want you can create a separate CSS/SCSS file and declare it in angular-cli.json along with the styles.css or styles.scss like:

"styles": [
  "styles.css",
  "fonts.css"
],

How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

I think this is the most readable solution:

($("div.printArea") as any).printArea();

Creating InetAddress object in Java

ip = InetAddress.getByAddress(new byte[] {
        (byte)192, (byte)168, (byte)0, (byte)102}
);

Remove a modified file from pull request

Removing a file from pull request but not from your local repository.

  1. Go to your branch from where you created the request use the following commands

git checkout -- c:\temp..... next git checkout origin/master -- c:\temp... u replace origin/master with any other branch. Next git commit -m c:\temp..... Next git push origin

Note : no single quote or double quotes for the filepath

Node.js – events js 72 throw er unhandled 'error' event

For what is worth, I got this error doing a clean install of nodejs and npm packages of my current linux-distribution I've installed meteor using

npm install metor

And got the above referenced error. After wasting some time, I found out I should have used meteor's way to update itself:

meteor update

This command output, among others, the message that meteor was severely outdated (over 2 years) and that it was going to install itself using:

curl https://install.meteor.com/ | sh

Which was probably the command I should have run in the first place.

So the solution might be to upgrade/update whatever nodejs package(js) you're using.

Parse JSON from HttpURLConnection object

The JSON string will just be the body of the response you get back from the URL you have called. So add this code

...
BufferedReader in = new BufferedReader(new InputStreamReader(
                            conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) 
    System.out.println(inputLine);
in.close();

That will allow you to see the JSON being returned to the console. The only missing piece you then have is using a JSON library to read that data and provide you with a Java representation.

Here's an example using JSON-LIB

Can I try/catch a warning?

I wanted to try/catch a warning, but at the same time keep the usual warning/error logging (e.g. in /var/log/apache2/error.log); for which the handler has to return false. However, since the "throw new..." statement basically interrupts the execution, one then has to do the "wrap in function" trick, also discussed in:

Is there a static way to throw exception in php

Or, in brief:

  function throwErrorException($errstr = null,$code = null, $errno = null, $errfile = null, $errline = null) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
  }
  function warning_handler($errno, $errstr, $errfile, $errline, array $errcontext) {
    return false && throwErrorException($errstr, 0, $errno, $errfile, $errline);
    # error_log("AAA"); # will never run after throw
    /* Do execute PHP internal error handler */
    # return false; # will never run after throw
  }
  ...
  set_error_handler('warning_handler', E_WARNING);
  ...
  try {
    mkdir($path, 0777, true);
  } catch (Exception $e) {
    echo $e->getMessage();
    // ...
  }

EDIT: after closer inspection, it turns out it doesn't work: the "return false && throwErrorException ..." will, basically, not throw the exception, and just log in the error log; removing the "false &&" part, as in "return throwErrorException ...", will make the exception throwing work, but will then not log in the error_log... I'd still keep this posted, though, as I haven't seen this behavior documented elsewhere.

What is the IntelliJ shortcut key to create a javadoc comment?

You can use the action 'Fix doc comment'. It doesn't have a default shortcut, but you can assign the Alt+Shift+J shortcut to it in the Keymap, because this shortcut isn't used for anything else. By default, you can also press Ctrl+Shift+A two times and begin typing Fix doc comment in order to find the action.

Posting parameters to a url using the POST method without using a form

cURL is an option, using Ajax as well eventhough solving back-end problems with the front-end isn't so neat.

A very useful post about doing it without cURL is this one: http://netevil.org/blog/2006/nov/http-post-from-php-without-curl

The code to do this (untested, unimproved, from the blog post):

function do_post_request($url, $data, $optional_headers = null)
{
   $params = array('http' => array(
                'method' => 'POST',
                'content' => $data
             ));
   if ($optional_headers !== null) {
      $params['http']['header'] = $optional_headers;
   }
   $ctx = stream_context_create($params);
   $fp = @fopen($url, 'rb', false, $ctx);
   if (!$fp) {
      throw new Exception("Problem with $url, $php_errormsg");
   }
   $response = @stream_get_contents($fp);
   if ($response === false) {
      throw new Exception("Problem reading data from $url, $php_errormsg");
   }
   return $response;
}

What is the difference between syntax and semantics in programming languages?

Syntax refers to the structure of a language, tracing its etymology to how things are put together.
For example you might require the code to be put together by declaring a type then a name and then a semicolon, to be syntactically correct.

Type token;

On the other hand, the semantics is about meaning. A compiler or interpreter could complain about syntax errors. Your co-workers will complain about semantics.

When do I need to use Begin / End Blocks and the Go keyword in SQL Server?

After wrestling with this problem today my opinion is this: BEGIN...END brackets code just like {....} does in C languages, e.g. code blocks for if...else and loops

GO is (must be) used when succeeding statements rely on an object defined by a previous statement. USE database is a good example above, but the following will also bite you:

alter table foo add bar varchar(8);
-- if you don't put GO here then the following line will error as it doesn't know what bar is.
update foo set bar = 'bacon';
-- need a GO here to tell the interpreter to execute this statement, otherwise the Parser will lump it together with all successive statements.

It seems to me the problem is this: the SQL Server SQL Parser, unlike the Oracle one, is unable to realise that you're defining a new symbol on the first line and that it's ok to reference in the following lines. It doesn't "see" the symbol until it encounters a GO token which tells it to execute the preceding SQL since the last GO, at which point the symbol is applied to the database and becomes visible to the parser.

Why it doesn't just treat the semi-colon as a semantic break and apply statements individually I don't know and wish it would. Only bonus I can see is that you can put a print() statement just before the GO and if any of the statements fail the print won't execute. Lot of trouble for a minor gain though.

How to access JSON Object name/value?

Here is a friendly piece of advice. Use something like Chrome Developer Tools or Firebug for Firefox to inspect your Ajax calls and results.

You may also want to invest some time in understanding a helper library like Underscore, which complements jQuery and gives you 60+ useful functions for manipulating data objects with JavaScript.

top -c command in linux to filter processes listed based on processname

@perreal's command works great! If you forget, try in two steps...

example: filter top to display only application called yakuake:

$ pgrep yakuake
1755

$ top -p 1755

useful top interactive commands 'c' : toggle full path vs. command name 'k' : kill by PID 'F' : filter by... select with arrows... then press 's' to set the sort

the answer below is good too... I was looking for that today but couldn't find it. Thanks

Ansible: How to delete files and folders inside a directory?

Just a small cleaner copy & paste template of ThorSummoners answer, if you are using Ansible >= 2.3 (distinction between files and dirs not necessary anymore.)

- name: Collect all fs items inside dir
  find:
    path: "{{ target_directory_path }}"
    hidden: true
    file_type: any
  changed_when: false
  register: collected_fsitems
- name: Remove all fs items inside dir
  file:
    path: "{{ item.path }}"
    state: absent
  with_items: "{{ collected_fsitems.files }}"
  when: collected_fsitems.matched|int != 0

Is there a way to iterate over a range of integers?

While I commiserate with your concern about lacking this language feature, you're probably just going to want to use a normal for loop. And you'll probably be more okay with that than you think as you write more Go code.

I wrote this iter package — which is backed by a simple, idiomatic for loop that returns values over a chan int — in an attempt to improve on the design found in https://github.com/bradfitz/iter, which has been pointed out to have caching and performance issues, as well as a clever, but strange and unintuitive implementation. My own version operates the same way:

package main

import (
    "fmt"
    "github.com/drgrib/iter"
)

func main() {
    for i := range iter.N(10) {
        fmt.Println(i)
    }
}

However, benchmarking revealed that the use of a channel was a very expensive option. The comparison of the 3 methods, which can be run from iter_test.go in my package using

go test -bench=. -run=.

quantifies just how poor its performance is

BenchmarkForMany-4                   5000       329956 ns/op           0 B/op          0 allocs/op
BenchmarkDrgribIterMany-4               5    229904527 ns/op         195 B/op          1 allocs/op
BenchmarkBradfitzIterMany-4          5000       337952 ns/op           0 B/op          0 allocs/op

BenchmarkFor10-4                500000000         3.27 ns/op           0 B/op          0 allocs/op
BenchmarkDrgribIter10-4            500000      2907 ns/op             96 B/op          1 allocs/op
BenchmarkBradfitzIter10-4       100000000        12.1 ns/op            0 B/op          0 allocs/op

In the process, this benchmark also shows how the bradfitz solution underperforms in comparison to the built-in for clause for a loop size of 10.

In short, there appears to be no way discovered so far to duplicate the performance of the built-in for clause while providing a simple syntax for [0,n) like the one found in Python and Ruby.

Which is a shame because it would probably be easy for the Go team to add a simple rule to the compiler to change a line like

for i := range 10 {
    fmt.Println(i)
}

to the same machine code as for i := 0; i < 10; i++.

However, to be fair, after writing my own iter.N (but before benchmarking it), I went back through a recently written program to see all the places I could use it. There actually weren't many. There was only one spot, in a non-vital section of my code, where I could get by without the more complete, default for clause.

So while it may look like this is a huge disappointment for the language in principle, you may find — like I did — that you actually don't really need it in practice. Like Rob Pike is known to say for generics, you might not actually miss this feature as much as you think you will.

Create Generic method constraining T to an Enum

It should also be considered that since the release of C# 7.3 using Enum constraints is supported out-of-the-box without having to do additional checking and stuff.

So going forward and given you've changed the language version of your project to C# 7.3 the following code is going to work perfectly fine:

    private static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
    {
        // Your code goes here...
    }

In case you're don't know how to change the language version to C# 7.3 see the following screenshot: enter image description here

EDIT 1 - Required Visual Studio Version and considering ReSharper

For Visual Studio to recognize the new syntax you need at least version 15.7. You can find that also mentioned in Microsoft's release notes, see Visual Studio 2017 15.7 Release Notes. Thanks @MohamedElshawaf for pointing out this valid question.

Pls also note that in my case ReSharper 2018.1 as of writing this EDIT does not yet support C# 7.3. Having ReSharper activated it highlights the Enum constraint as an error telling me Cannot use 'System.Array', 'System.Delegate', 'System.Enum', 'System.ValueType', 'object' as type parameter constraint. ReSharper suggests as a quick fix to Remove 'Enum' constraint of type paramter T of method

However, if you turn off ReSharper temporarily under Tools -> Options -> ReSharper Ultimate -> General you'll see that the syntax is perfectly fine given that you use VS 15.7 or higher and C# 7.3 or higher.

tqdm in Jupyter Notebook prints new progress bars repeatedly

For everyone who is on windows and couldn't solve the duplicating bars issue with any of the solutions mentioned here. I had to install the colorama package as stated in tqdm's known issues which fixed it.

pip install colorama

Try it with this example:

from tqdm import tqdm
from time import sleep

for _ in tqdm(range(5), "All", ncols = 80, position = 0):
    for _ in tqdm(range(100), "Sub", ncols = 80, position = 1, leave = False):
        sleep(0.01)

Which will produce something like:

All:  60%|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦                | 3/5 [00:03<00:02,  1.02s/it]
Sub:  50%|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦                  | 50/100 [00:00<00:00, 97.88it/s]

Count records for every month in a year

Try This query:

SELECT 
  SUM(CASE datepart(month,ARR_DATE) WHEN 1 THEN 1 ELSE 0 END) AS 'January',
  SUM(CASE datepart(month,ARR_DATE) WHEN 2 THEN 1 ELSE 0 END) AS 'February',
  SUM(CASE datepart(month,ARR_DATE) WHEN 3 THEN 1 ELSE 0 END) AS 'March',
  SUM(CASE datepart(month,ARR_DATE) WHEN 4 THEN 1 ELSE 0 END) AS 'April',
  SUM(CASE datepart(month,ARR_DATE) WHEN 5 THEN 1 ELSE 0 END) AS 'May',
  SUM(CASE datepart(month,ARR_DATE) WHEN 6 THEN 1 ELSE 0 END) AS 'June',
  SUM(CASE datepart(month,ARR_DATE) WHEN 7 THEN 1 ELSE 0 END) AS 'July',
  SUM(CASE datepart(month,ARR_DATE) WHEN 8 THEN 1 ELSE 0 END) AS 'August',
  SUM(CASE datepart(month,ARR_DATE) WHEN 9 THEN 1 ELSE 0 END) AS 'September',
  SUM(CASE datepart(month,ARR_DATE) WHEN 10 THEN 1 ELSE 0 END) AS 'October',
  SUM(CASE datepart(month,ARR_DATE) WHEN 11 THEN 1 ELSE 0 END) AS 'November',
  SUM(CASE datepart(month,ARR_DATE) WHEN 12 THEN 1 ELSE 0 END) AS 'December',
  SUM(CASE datepart(year,ARR_DATE) WHEN 2012 THEN 1 ELSE 0 END) AS 'TOTAL'
FROM
    sometable
WHERE
  ARR_DATE BETWEEN '2012/01/01' AND '2012/12/31' 

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

A simple solution is to use Microsoft ASP.NET Web API 2.2 Client from NuGet.

Then you can simply do this and it'll serialize the object to JSON and set the Content-Type header to application/json; charset=utf-8:

var data = new
{
    name = "Foo",
    category = "article"
};

var client = new HttpClient();
client.BaseAddress = new Uri(baseUri);
client.DefaultRequestHeaders.Add("token", token);
var response = await client.PostAsJsonAsync("", data);

What is the difference between GitHub and gist?

You can access Gist by visiting the following url gist.github.com. Alternatively you can access it from within your Github account (after logging in) as shown in the picture below:

how to access gist from within the github console

 

Github: A hosting service that houses a web-based git repository. It includes all the fucntionality of git with additional features added in.

 

Gist: Is an additional feature added to github to allow the sharing of code snippets, notes, to do lists and more. You can save your Gists as secret or public. Secret Gists are hidden from search engines but visible to anyone you share the url with.

For example. If you wanted to write a private to-do list. You could write one using Github Markdown as follows:

how to write a private to do list

NB: It is important to preserve the whitespace as shown above between the dash and brackets. It is also important that you save the file with the extension .md because we want the markdown to format properly. Remember to save this Gist as secret if you do not want others to see it.

 

The end result looks like the image below. The checkboxes are clickable because we saved this Gist with the extension .md

What the to do list looks like if you have formatted it properly

How do I enable C++11 in gcc?

As previously mentioned - in case of a project, Makefile or otherwise, this is a project configuration issue, where you'll likely need to specify other flags too.

But what about one-off programs, where you would normally just write g++ file.cpp && ./a.out?

Well, I would much like to have some #pragma to turn in on at source level, or maybe a default extension - say .cxx or .C11 or whatever, trigger it by default. But as of today, there is no such feature.

But, as you probably are working in a manual environment (i.e. shell), you can just have an alias in you .bashrc (or whatever):

alias g++11="g++ -std=c++0x"

or, for newer G++ (and when you want to feel "real C++11")

alias g++11="g++ -std=c++11"

You can even alias to g++ itself, if you hate C++03 that much ;)

Using jQuery Fancybox or Lightbox to display a contact form

you'll probably want to look into jquery-ui dialog. it's highly customizable and can be made to work exactly like lightbox/fancybox and supports everything you would need for a contact form from a regular link.

there is even an example with a form.

Calling a java method from c++ in Android

Solution posted by Denys S. in the question post:

I quite messed it up with c to c++ conversion (basically env variable stuff), but I got it working with the following code for C++:

#include <string.h>
#include <stdio.h>
#include <jni.h>

jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){

    jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
    jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
    jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);

    const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
    printf("%s\n", str);

    return (*env)->NewStringUTF(env, str);
}

And next code for java methods:

    public class MainActivity extends Activity {
    private static String LIB_NAME = "thelib";

    static {
        System.loadLibrary(LIB_NAME);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.textview);
        tv.setText(this.getJniString());
    }

    // please, let me live even though I used this dark programming technique
    public String messageMe(String text) {
        System.out.println(text);
        return text;
    }

    public native String getJniString();
}

How to make a <ul> display in a horizontal row

Set the display property to inline for the list you want this to apply to. There's a good explanation of displaying lists on A List Apart.

What causes java.lang.IncompatibleClassChangeError?

My answer, I believe, will be Intellij specific.

I had rebuilt clean, even going as far as to manually delete the "out" and "target" dirs. Intellij has a "invalidate caches and restart", which sometimes clears odd errors. This time it didn't work. The dependency versions all looked correct in the project settings->modules menu.

The final answer was to manually delete my problem dependency from my local maven repo. An old version of bouncycastle was the culprit(I knew I had just changed versions and that would be the problem) and although the old version showed up no where in what was being built, it solved my problem. I was using intellij version 14 and then upgraded to 15 during this process.

Landscape printing from HTML

-webkit-transform: rotate(-90deg); -moz-transform:rotate(-90deg);
     filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);

not working in Firefox 16.0.2 but it is working in Chrome

How to create correct JSONArray in Java using JSONObject

Small reusable method can be written for creating person json object to avoid duplicate code

JSONObject  getPerson(String firstName, String lastName){
   JSONObject person = new JSONObject();
   person .put("firstName", firstName);
   person .put("lastName", lastName);
   return person ;
} 

public JSONObject getJsonResponse(){

    JSONArray employees = new JSONArray();
    employees.put(getPerson("John","Doe"));
    employees.put(getPerson("Anna","Smith"));
    employees.put(getPerson("Peter","Jones"));

    JSONArray managers = new JSONArray();
    managers.put(getPerson("John","Doe"));
    managers.put(getPerson("Anna","Smith"));
    managers.put(getPerson("Peter","Jones"));

    JSONObject response= new JSONObject();
    response.put("employees", employees );
    response.put("manager", managers );
    return response;
  }

C# Wait until condition is true

You can use thread waiting handler

private readonly System.Threading.EventWaitHandle waitHandle = new System.Threading.AutoResetEvent(false);
private void btnOk_Click(object sender, EventArgs e)
{
    // Do some work
    Task<string> task = Task.Run(() => GreatBigMethod());
    string GreatBigMethod = await task;

    // Wait until condition is false
    waitHandle.WaitOne();
    Console.WriteLine("Excel is busy");
    waitHandle.Reset();

    // Do work
    Console.WriteLine("YAY");
 }

then some other job need to set your handler

void isExcelInteractive()
{
   /// Do your check
   waitHandle.Set()
}

Update: If you want use this solution, you have to call isExcelInteractive() continuously with specific interval:

var actions = new []{isExcelInteractive, () => Thread.Sleep(25)};
foreach (var action in actions)
{                                      
    action();
}

Converting map to struct

You can do it ... it may get a bit ugly and you'll be faced with some trial and error in terms of mapping types .. but heres the basic gist of it:

func FillStruct(data map[string]interface{}, result interface{}) {
    t := reflect.ValueOf(result).Elem()
    for k, v := range data {
        val := t.FieldByName(k)
        val.Set(reflect.ValueOf(v))
    }
}

Working sample: http://play.golang.org/p/PYHz63sbvL

What should be the values of GOPATH and GOROOT?

Once Go lang is installed, GOROOT is the root directory of the installation.

When I exploded Go Lang binary in Windows C:\ directory, my GOROOT should be C:\go. If Installed with Windows installer, it may be C:\Program Files\go (or C:\Program Files (x86)\go, for 64-bit packages)

 GOROOT = C:\go

while my GOPATH is location of Go lang source code or workspace.

If my Go lang source code is located at C:\Users\\GO_Workspace, your GOPATH would be as below:

 GOPATH = C:\Users\<xyz>\GO_Workspace

How to center an iframe horizontally?

Here I have put snippet for all of you who are suffering to make iframe or image in center of the screen horizontally. Give me THUMBS UP VOTE if you like.?.

style > img & iframe > this is your tag name so change that if you're want any other tag in center

_x000D_
_x000D_
<html >_x000D_
 <head> _x000D_
            <style type=text/css>_x000D_
            div{}_x000D_
            img{_x000D_
                 margin: 0 auto;_x000D_
          display:block;_x000D_
          }_x000D_
  iframe{ _x000D_
  margin: 0 auto;_x000D_
  display:block;_x000D_
  }_x000D_
    _x000D_
            </style>_x000D_
</head>_x000D_
 <body >_x000D_
           _x000D_
   <iframe src="https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4" width="320" height="180" frameborder="0" allowfullscreen="allowfullscreen"></iframe> _x000D_
   _x000D_
   <img src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg" width="320" height="180"  />_x000D_
            </body> _x000D_
            </html>
_x000D_
_x000D_
_x000D_

Replace special characters in a string with _ (underscore)

string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'_');

Alternatively, to change all characters except numbers and letters, try:

string = string.replace(/[^a-zA-Z0-9]/g,'_');

In Flask, What is request.args and how is it used?

It has some interesting behaviour in some cases that is good to be aware of:

from werkzeug.datastructures import MultiDict

d = MultiDict([("ex1", ""), ("ex2", None)])

d.get("ex1", "alternive")
# returns: ''

d.get("ex2", "alternative")
# returns no visible output of any kind
# It is returning literally None, so if you do:
d.get("ex2", "alternative") is None
# it returns: True

d.get("ex3", "alternative")
# returns: 'alternative'

Why is it that "No HTTP resource was found that matches the request URI" here?

I got the similiar issue, and resolved it by the following. The issue looks not related to the Route definition but definition of the parameters, just need to give it a default value.

----Code with issue: Message: "No HTTP resource was found that matches the request URI

    [HttpGet]
    [Route("students/list")]
    public StudentListResponse GetStudents(int? ClassId, int? GradeId)
    {
       ...
    }

----Code without issue.

    [HttpGet]
    [Route("students/list")]
    public StudentListResponse GetStudents(int? ClassId=null, int? GradeId=null)
    {
       ...
    }

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

Here is my answer to a similar question:

I think (not yet entirely sure) that this is because InvokeRequired will always return false if the control has not yet been loaded/shown. I have done a workaround which seems to work for the moment, which is to simple reference the handle of the associated control in its creator, like so:

var x = this.Handle; 

(See http://ikriv.com/en/prog/info/dotnet/MysteriousHang.html)

Under which circumstances textAlign property works in Flutter?

Specify crossAxisAlignment: CrossAxisAlignment.start in your column

NSPhotoLibraryUsageDescription key must be present in Info.plist to use camera roll

You need to paste these two in your info.plist, The only way that worked in iOS 11 for me.

    <key>NSPhotoLibraryUsageDescription</key>
    <string>This app requires access to the photo library.</string>

    <key>NSPhotoLibraryAddUsageDescription</key>
    <string>This app requires access to the photo library.</string>

Comparing two maps

Quick Answer

You should use the equals method since this is implemented to perform the comparison you want. toString() itself uses an iterator just like equals but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).

Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString and equals behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.

See: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

boolean equals(Object o)

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

Implementation in Java Source (java.util.AbstractMap)

Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap which is used by classes such as HashMap:

 // Comparison and hashing

    /**
     * Compares the specified object with this map for equality.  Returns
     * <tt>true</tt> if the given object is also a map and the two maps
     * represent the same mappings.  More formally, two maps <tt>m1</tt> and
     * <tt>m2</tt> represent the same mappings if
     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This ensures that the
     * <tt>equals</tt> method works properly across different implementations
     * of the <tt>Map</tt> interface.
     *
     * <p>This implementation first checks if the specified object is this map;
     * if so it returns <tt>true</tt>.  Then, it checks if the specified
     * object is a map whose size is identical to the size of this map; if
     * not, it returns <tt>false</tt>.  If so, it iterates over this map's
     * <tt>entrySet</tt> collection, and checks that the specified map
     * contains each mapping that this map contains.  If the specified map
     * fails to contain such a mapping, <tt>false</tt> is returned.  If the
     * iteration completes, <tt>true</tt> is returned.
     *
     * @param o object to be compared for equality with this map
     * @return <tt>true</tt> if the specified object is equal to this map
     */
    public boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Map))
            return false;
        Map<K,V> m = (Map<K,V>) o;
        if (m.size() != size())
            return false;

        try {
            Iterator<Entry<K,V>> i = entrySet().iterator();
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                K key = e.getKey();
                V value = e.getValue();
                if (value == null) {
                    if (!(m.get(key)==null && m.containsKey(key)))
                        return false;
                } else {
                    if (!value.equals(m.get(key)))
                        return false;
                }
            }
        } catch (ClassCastException unused) {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }

        return true;
    }

Comparing two different types of Maps

toString fails miserably when comparing a TreeMap and HashMap though equals does compare contents correctly.

Code:

public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");

System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
        + map.toString().equals(map2.toString()));

System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}

Output:

Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}

How to assign an exec result to a sql variable?

I had the same question. While there are good answers here I decided to create a table-valued function. With a table (or scalar) valued function you don't have to change your stored proc. I simply did a select from the table-valued function. Note that the parameter (MyParameter is optional).

CREATE FUNCTION [dbo].[MyDateFunction] 
(@MyParameter varchar(max))
RETURNS TABLE 
AS
RETURN 
(
    --- Query your table or view or whatever and select the results.
    SELECT DateValue FROM MyTable WHERE ID = @MyParameter;
)

To assign to your variable you simply can do something like:

Declare @MyDate datetime;
SET @MyDate = (SELECT DateValue FROM MyDateFunction(@MyParameter));

You can also use a scalar valued function:

CREATE FUNCTION TestDateFunction()  
RETURNS datetime  
BEGIN  
    RETURN (SELECT GetDate());
END

Then you can simply do

Declare @MyDate datetime;
SET @MyDate = (Select dbo.TestDateFunction());
SELECT @MyDate;

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

You probably do not need to be making lists and appending them to make your array. You can likely just do it all at once, which is faster since you can use numpy to do your loops instead of doing them yourself in pure python.

To answer your question, as others have said, you cannot access a nested list with two indices like you did. You can if you convert mean_data to an array before not after you try to slice it:

R = np.array(mean_data)[:,0]

instead of

R = np.array(mean_data[:,0])

But, assuming mean_data has a shape nx3, instead of

R = np.array(mean_data)[:,0]
P = np.array(mean_data)[:,1]
Z = np.array(mean_data)[:,2]

You can simply do

A = np.array(mean_data).mean(axis=0)

which averages over the 0th axis and returns a length-n array

But to my original point, I will make up some data to try to illustrate how you can do this without building any lists one item at a time:

How to write to a file without overwriting current contents?

Instead of "w" use "a" (append) mode with open function:

with open("games.txt", "a") as text_file:

How do the likely/unlikely macros in the Linux kernel work and what is their benefit?

These are GCC functions for the programmer to give a hint to the compiler about what the most likely branch condition will be in a given expression. This allows the compiler to build the branch instructions so that the most common case takes the fewest number of instructions to execute.

How the branch instructions are built are dependent upon the processor architecture.

How is AngularJS different from jQuery

I want to add something regarding AngularJS difference with jQuery from a developer's perspective.

In AngularJS you have to have a very structured view and approach on what you want to accomplish. It is scarcely following a linear fashion to complete a task, but rather, the exchanges between various objects take care of the requests and actions, which, then, is necessary as angular is an MVC-Based framework. It also requires an at least general blueprint of the finalized application, since coding depends much on how you want the interactions to be completed.

jQuery is like a free poetry, you write lines and keep some relations and momentum appropriate for your task to be accomplished.

Though, in Angular JS, you should follow some rules as well as keeping the momentum and relations proper, maybe it is more like classical Spencerian sonnet (a famous classical poet) whose poem is structural and tied to many rules.

Compared against AngularJS, jQuery is more like a collection of codes and functions (which is, as already mentioned, great for DOM manipulation and fast-effect achievement), while AngularJS is a real framework which gives the developer the ability to build an enterprise web-application with a lot of data-binding and exchange within a superbly organized-routing and management.

Furthermore, AngularJS has no dependency on jQuery to complete its task. It has two very superb features which are not found in jQuery in any sense:

1- Angular JS teaches you how to CODE and accomplish a goal, not just accomplish a goal by any means. Worth to mention that AngularJS fully utilizes the core and heart of Javascripts and paves the way for you to incorporate in your app, the techniques such as DI (dependency-injection). To work with angularJS you should (or must) learn more elevated techniques of coding with Javascript.

2- Angular JS is fully independent to handle directives and structure your app; you might then simply claim that jQuery can do the same (independence), but, indeed, AngularJS, as several times mentioned within the above lines, has independence in the most excellent possible structurally MVC-Based way.

A last note is that, there is no war of Names, since it is far disturbing to be biased, or subjective. jQuery's magnitude and greatness has been proved, but their usages and limitations( of any framework or software) are the concerns of the discussion and similar debates around.

Update:

Using AngularJS is decisive as it is expensive in terms of implementation, but founds a strong base for future expansion, transformation and maintenance of the application. AngularJS is for the New World of Web. It is targeted toward building applications which are characterized by their least resource consumption (loading only necessary resources from the server), fast response time and high degree of maintainability and extendability wrapped around a structured system.

How can I define an interface for an array of objects with Typescript?

You can define an interface with an indexer:

interface EnumServiceGetOrderBy {
    [index: number]: { id: number; label: string; key: any };
}

Fit background image to div

you also use this:

background-size:contain;
height: 0;
width: 100%;
padding-top: 66,64%; 

I don't know your div-values, but let's assume you've got those.

height: auto;
max-width: 600px;

Again, those are just random numbers. It could quite hard to make the background-image (if you would want to) with a fixed width for the div, so better use max-width. And actually it isn't complicated to fill a div with an background-image, just make sure you style the parent element the right way, so the image has a place it can go into.

Chris

How do you disable viewport zooming on Mobile Safari?

This one should be working on iphone etc.

<meta name="viewport" content="width=device-width, initial-scale=1 initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

Limit on the WHERE col IN (...) condition

There is a limit, but you can split your values into separate blocks of in()

Select * 
From table 
Where Col IN (123,123,222,....)
or Col IN (456,878,888,....)

program cant start because php5.dll is missing

When you open phpinfo() see if the thread safety is enable or not enable also see the version of php and see MSVC-- what is the number in place of -- and see the architecture these all things help u to get the suitable php driver

here a url help u to get a php driver https://s3.amazonaws.com/drivers.mongodb.org/php/index.html

Angular 2 declaring an array of objects

Another approach that is especially useful if you want to store data coming from an external API or a DB would be this:

  1. Create a class that represent your data model

    export class Data{
        private id:number;
        private text: string;
    
        constructor(id,text) {
            this.id = id;
            this.text = text;
        }
    
  2. In your component class you create an empty array of type Data and populate this array whenever you get a response from API or whatever data source you are using

    export class AppComponent {
        private search_key: string;
        private dataList: Data[] = [];
    
        getWikiData() {
           this.httpService.getDataFromAPI()
            .subscribe(data => {
              this.parseData(data);
            });
         }
    
        parseData(jsonData: string) {
        //considering you get your data in json arrays
        for (let i = 0; i < jsonData[1].length; i++) {
             const data = new WikiData(jsonData[1][i], jsonData[2][i]);
             this.wikiData.push(data);
        }
      }
    }
    

TypeError : Unhashable type

The real reason because set does not work is the fact, that it uses the hash function to distinguish different values. This means that sets only allows hashable objects. Why a list is not hashable is already pointed out.

Read connection string from web.config

In VB : This should work

ConfigurationManager.ConnectionStrings("SQLServer").ConnectionString

In C# it would be (as per comment of Ala)

ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString

How to control the width and height of the default Alert Dialog in Android?

Before trying to adjust the size post-layout, first check what style your dialog is using. Make sure that nothing in the style tree sets

<item name="windowMinWidthMajor">...</item>
<item name="windowMinWidthMinor">...</item>

If that's happening, it's just as simple as supplying your own style to the [builder constructor that takes in a themeResId](http://developer.android.com/reference/android/app/AlertDialog.Builder.html#AlertDialog.Builder(android.content.Context, int)) available API 11+

<style name="WrapEverythingDialog" parent=[whatever you were previously using]>
    <item name="windowMinWidthMajor">0dp</item>
    <item name="windowMinWidthMinor">0dp</item>
</style>

"E: Unable to locate package python-pip" on Ubuntu 18.04

To solve the problem of:

E: Unable to locate package python-pip

you should do this. This works with the python2.7 and you not going to get disappointed by it. follow the steps that are mention below. go to get-pip.py and copy all the code from it.
open the terminal using CTRL + ALT +T

vi get-pip.py

paste the copied code here and then exit from the vi editor by pressing

ESC then :wq => press Enter

lastly, now run the code and see the magic

sudo python get-pip.py

It automatically adds the pip command in your Linux.
you can see the output of my machine

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

If you have previously installed node using brew, then you will have a bunch of extra files that you should clean up before installing node "the right way". Plus, I had to add a few settings to my startup script to make things work smoothly.

I wrote a script to make this easy.

# filename:  install-nvm-npm-node
# author:    Lex Sheehan
# purpose:   To cleanly install NVM, NODE and NPM
# dependencies:  brew

NOW=$(date +%x\ %H:%M:%S)
CR=$'\n'
REV=$(tput rev)
OFF=$(tput sgr0)
BACKUP_DIR=$HOME/backups/nvm-npm-bower-caches/$NOW
MY_NAME=$(basename $0)
NODE_VER_TO_INSTALL=$1
if [ "$NODE_VER_TO_INSTALL" == "" ]; then
    NODE_VER_TO_INSTALL=v0.12.2
fi
if [ "`echo "$NODE_VER_TO_INSTALL" | cut -c1-1`" != "v" ]; then
    echo """$CR""Usage:   $ $MY_NAME <NODE_VERSION_TO_INSALL>"
    echo "Example: $ $MY_NAME v0.12.1"
    echo "Example: $ $MY_NAME $CR"
    exit 1
fi
echo """$CR""First, run:  $ brew update"
echo "Likely, you'll need to do what it suggests."
echo "Likely, you'll need to run: $ brew update$CR"
echo "To install latest node version, run the following command to get the latest version:  $ nvm ls-remote"
echo "... and pass the version number you want as the only param to $MY_NAME. $CR"
echo "Are you ready to install the latest version of nvm and npm and node version $NODE_VER_TO_INSTALL ?$CR"
echo "Press CTL+C to exit --or-- Enter to continue..."
read x

echo """$REV""Uninstalling nvm...$CR$OFF"
# Making backups, but in all likelyhood you'll just reinstall them (and won't need these backups)
if [ ! -d "$BACKUP_DIR" ]; then 
    echo "Creating directory to store $HOME/.nvm .npm and .bower cache backups: $BACKUP_DIR"
    mkdir -p $BACKUP_DIR
fi 
set -x
mv $HOME/.nvm   $BACKUP_DIR  2>/dev/null
mv $HOME/.npm   $BACKUP_DIR  2>/dev/null
mv $HOME/.bower $BACKUP_DIR  2>/dev/null
{ set +x; } &>/dev/null

echo "$REV""$CR""Uninstalling node...$CR$OFF"
echo "Enter your password to remove user some node-related /usr/local directories"
set -x
sudo rm -rf /usr/local/lib/node_modules
rm -rf /usr/local/lib/node
rm -rf /usr/local/include/node
rm -rf /usr/local/include/node_modules
rm /usr/local/bin/npm
rm /usr/local/lib/dtrace/node.d
rm -rf $HOME/.node
rm -rf $HOME/.node-gyp
rm /opt/local/bin/node
rm /opt/local/include/node
rm -rf /opt/local/lib/node_modules
rm -rf /usr/local/Cellar/nvm
brew uninstall node 2>/dev/null
{ set +x; } &>/dev/null

echo "$REV""$CR""Installing nvm...$CR$OFF"

echo "++brew install nvm"
brew install nvm 
echo '$(brew --prefix nvm)/nvm.sh'
source $(brew --prefix nvm)/nvm.sh

echo "$REV""$CR""Insert the following line in your startup script (ex: $HOME/.bashrc):$CR$OFF"
echo "export NVM_DIR=\"\$(brew --prefix nvm)\"; [ -s \"\$NVM_DIR/nvm.sh\" ] && . \"\$NVM_DIR/nvm.sh\"$CR"
NVM_DIR="$(brew --prefix nvm)"

echo """$CR""Using nvm install node...$CR"
echo "++ nvm install $NODE_VER_TO_INSTALL"
nvm install $NODE_VER_TO_INSTALL
NODE_BINARY_PATH="`find /usr/local/Cellar/nvm -name node -type d|head -n 1`/$NODE_VER_TO_INSTALL/bin"
echo "$REV""$CR""Insert the following line in your startup script (ex: $HOME/.bashrc) and then restart your shell:$CR$OFF"
echo "export PATH=\$PATH:$NODE_BINARY_PATH:$HOME/.node/bin"

echo """$CR""Upgrading npm...$CR"
echo '++ install -g npm@latest'
npm install -g npm@latest
{ set +x; } &>/dev/null
echo "$REV""$CR""Insert following line in your $HOME/.npmrc file:$OFF"
echo """$CR""prefix=$HOME/.node$CR"
echo "Now, all is likley well if you can run the following without errors:  npm install -g grunt-cli$CR"
echo "Other recommended global installs: bower, gulp, yo, node-inspector$CR"

I wrote a short article here that details why this is "the right way".

If you need to install iojs, do so using nvm like this:

nvm install iojs-v1.7.1

To install brew, just see its home page.

See alexpods answer for the rest.

How to get a enum value from string in C#?

Alternate solution can be:

baseKey hKeyLocalMachine = baseKey.HKEY_LOCAL_MACHINE;
uint value = (uint)hKeyLocalMachine;

Or just:

uint value = (uint)baseKey.HKEY_LOCAL_MACHINE;

Substitute a comma with a line break in a cell

Use

=SUBSTITUTE(A1,",",CHAR(10) & CHAR(13))

This will replace each comma with a new line. Change A1 to the cell you are referencing.

Bypass invalid SSL certificate errors when calling web services in .Net

I solved it this way:

Call the following just before calling your ssl webservice that cause that error:

using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

/// <summary>
/// solution for exception
/// System.Net.WebException: 
/// The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
/// </summary>
public static void BypassCertificateError()
{
    ServicePointManager.ServerCertificateValidationCallback +=

        delegate(
            Object sender1,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors)
        {
            return true;
        };
}

create multiple tag docker image

How not to do it:

When building an image, you could also tag it this way.

docker build -t ubuntu:14.04 .

Then you build it again with another tag:

docker build -t ubuntu:latest .

If your Dockerfile makes good use of the cache, the same image should come out, and it effectively does the same as retagging the same image. If you do docker images then you will see that they have the same ID.

There's probably a case where this goes wrong though... But like @david-braun said, you can't create tags with Dockerfiles themselves, just with the docker command.

What is the best regular expression to check if a string is a valid URL?

How about this:

^(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})$

These are the test cases:

Test cases

You can try it out in here : https://regex101.com/r/mS9gD7/41

Button button = findViewById(R.id.button) always resolves to null in Android Studio

This is because findViewById() searches in the activity_main layout, while the button is located in the fragment's layout fragment_main.

Move that piece of code in the onCreateView() method of the fragment:

//...

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        onButtonClick((Button) view);
    }
});

Notice that now you access it through rootView view:

Button buttonClick = (Button)rootView.findViewById(R.id.button);

otherwise you would get again NullPointerException.

"Cannot start compilation: the output path is not specified for module..."

None of the suggestions worked for me until I ran the command "gradle cleanIdeaModule ideaModule" info here: https://docs.gradle.org/current/userguide/idea_plugin.html

Fade Effect on Link Hover?

I know in the question you state "I assume JavaScript is used to create this effect" but CSS can be used too, an example is below.

CSS

.fancy-link {
   color: #333333;
   text-decoration: none;
   transition: color 0.3s linear;
   -webkit-transition: color 0.3s linear;
   -moz-transition: color 0.3s linear;
}

.fancy-link:hover {
   color: #F44336;
}

HTML

<a class="fancy-link" href="#">My Link</a>

And here is a JSFIDDLE for the above code!


Marcel in one of the answers points out you can "transition multiple CSS properties" you can also use "all" to effect the element with all your :hover styles like below.

CSS

.fancy-link {
   color: #333333;
   text-decoration: none;
   transition: all 0.3s linear;
   -webkit-transition: all 0.3s linear;
   -moz-transition: all 0.3s linear;
}

.fancy-link:hover {
   color: #F44336;
   padding-left: 10px;
}

HTML

<a class="fancy-link" href="#">My Link</a>

And here is a JSFIDDLE for the "all" example!

Facebook api: (#4) Application request limit reached

The Facebook "Graph API Rate Limiting" docs says that an error with code #4 is an app level rate limit, which is different than user level rate limits. Although it doesn't give any exact numbers, it describes their app level rate-limit as:

This rate limiting is applied globally at the app level. Ads api calls are excluded.

  • Rate limiting happens real time on sliding window for past one hour.
  • Stats is collected for number of calls and queries made, cpu time spent, memory used for each app.
  • There is a limit for each resource multiplied by monthly active users of a given app.
  • When the app uses more than its allowed resources the error is thrown.
  • Error, Code: 4, Message: Application request limit reached

The docs also give recommendations for avoiding the rate limits. For app level limits, they are:

Recommendations:

  • Verify the error code (4) to confirm the throttling type.
  • Do not make burst of calls, spread out the calls throughout the day.
  • Do smart fetching of data (important data, non duplicated data, etc).
    • Real-time insights, make sure API calls are structured in a way that you can read insights for as many as Page posts as possible, with minimum number of requests.
    • Don't fetch users feed twice (in the case that two App users have a specific friend in common)
    • Don't fetch all user's friends feed in a row if the number of friends is more than 250. Separate the fetches over different days. As an option, fetch first the app user's news feed (me/home) in order to detect which friends are more important to the App user. Then, fetch those friends feeds first.
  • Consider to limit/filter the requests by using the following parameters: "since", "until", "limit"
  • For page related calls use realtime updates to subscribe to changes in data.
  • Field expansion allows ton "join" multiple graph queries into a single call.
  • Etags to check if the data querying has changed since the last check.
  • For page management developers who does not have massive user base, have the admins of the page to accept the app to increase the number of users.

Finally, the docs give the following informational tips:

  • Batching calls will not reduce the number of api calls.
  • Making parallel calls will not reduce the number of api calls.

Difference between using Throwable and Exception in a try catch

By catching Throwable it includes things that subclass Error. You should generally not do that, except perhaps at the very highest "catch all" level of a thread where you want to log or otherwise handle absolutely everything that can go wrong. It would be more typical in a framework type application (for example an application server or a testing framework) where it can be running unknown code and should not be affected by anything that goes wrong with that code, as much as possible.

How can I remove the string "\n" from within a Ruby string?

You don't need a regex for this. Use tr:

"some text\nandsomemore".tr("\n","")

What is the difference between Hibernate and Spring Data JPA

There are 3 different things we are using here :

  1. JPA : Java persistence api which provide specification for persisting, reading, managing data from your java object to relations in database.
  2. Hibernate: There are various provider which implement jpa. Hibernate is one of them. So we have other provider as well. But if using jpa with spring it allows you to switch to different providers in future.
  3. Spring Data JPA : This is another layer on top of jpa which spring provide to make your life easy.

So lets understand how spring data jpa and spring + hibernate works-


Spring Data JPA:

Let's say you are using spring + hibernate for your application. Now you need to have dao interface and implementation where you will be writing crud operation using SessionFactory of hibernate. Let say you are writing dao class for Employee class, tomorrow in your application you might need to write similiar crud operation for any other entity. So there is lot of boilerplate code we can see here.

Now Spring data jpa allow us to define dao interfaces by extending its repositories(crudrepository, jparepository) so it provide you dao implementation at runtime. You don't need to write dao implementation anymore.Thats how spring data jpa makes your life easy.

how to fix java.lang.IndexOutOfBoundsException

You do not have any elements in the list so can't access the first element.

How to find serial number of Android device?

String serial = null; 

try {
    Class<?> c = Class.forName("android.os.SystemProperties");
    Method get = c.getMethod("get", String.class);
    serial = (String) get.invoke(c, "ro.serialno");
} catch (Exception ignored) {
}

This code returns device serial number using a hidden Android API.

How do I escape a single quote ( ' ) in JavaScript?

Since the values are actually inside of an HTML attribute, you should use &apos;

"<img src='something' onmouseover='change(&apos;ex1&apos;)' />";

SQL query to get the deadlocks in SQL SERVER 2008

In order to capture deadlock graphs without using a trace (you don't need profiler necessarily), you can enable trace flag 1222. This will write deadlock information to the error log. However, the error log is textual, so you won't get nice deadlock graph pictures - you'll have to read the text of the deadlocks to figure it out.

I would set this as a startup trace flag (in which case you'll need to restart the service). However, you can run it only for the current running instance of the service (which won't require a restart, but which won't resume upon the next restart) using the following global trace flag command:

DBCC TRACEON(1222, -1);

A quick search yielded this tutorial:

http://www.mssqltips.com/sqlservertip/2130/finding-sql-server-deadlocks-using-trace-flag-1222/

Also note that if your system experiences a lot of deadlocks, this can really hammer your error log, and can become quite a lot of noise, drowning out other, important errors.

Have you considered third party monitoring tools? SQL Sentry Performance Advisor, for example, has a much nicer deadlock graph, showing you object / index names as well as the order in which the locks were taken. As a bonus, these are captured for you automatically on monitored servers without having to configure trace flags, run your own traces, etc.:

enter image description here

Disclaimer: I work for SQL Sentry.

Detecting when Iframe content has loaded (Cross browser)

to detect when the iframe has loaded and its document is ready?

It's ideal if you can get the iframe to tell you itself from a script inside the frame. For example it could call a parent function directly to tell it it's ready. Care is always required with cross-frame code execution as things can happen in an order you don't expect. Another alternative is to set ‘var isready= true;’ in its own scope, and have the parent script sniff for ‘contentWindow.isready’ (and add the onload handler if not).

If for some reason it's not practical to have the iframe document co-operate, you've got the traditional load-race problem, namely that even if the elements are right next to each other:

<img id="x" ... />
<script type="text/javascript">
    document.getElementById('x').onload= function() {
        ...
    };
</script>

there is no guarantee that the item won't already have loaded by the time the script executes.

The ways out of load-races are:

  1. on IE, you can use the ‘readyState’ property to see if something's already loaded;

  2. if having the item available only with JavaScript enabled is acceptable, you can create it dynamically, setting the ‘onload’ event function before setting source and appending to the page. In this case it cannot be loaded before the callback is set;

  3. the old-school way of including it in the markup:

    <img onload="callback(this)" ... />

Inline ‘onsomething’ handlers in HTML are almost always the wrong thing and to be avoided, but in this case sometimes it's the least bad option.

How to iterate over each string in a list of strings and operate on it's elements

Try:

for word in words:
    if word[0] == word[-1]:
        c += 1
    print c

for word in words returns the items of words, not the index. If you need the index sometime, try using enumerate:

for idx, word in enumerate(words):
    print idx, word

would output

0, 'aba'
1, 'xyz'
etc.

The -1 in word[-1] above is Python's way of saying "the last element". word[-2] would give you the second last element, and so on.

You can also use a generator to achieve this.

c = sum(1 for word in words if word[0] == word[-1])

How do I get the current mouse screen coordinates in WPF?

If you're looking for a 1 liner, this does well.

new Point(Mouse.GetPosition(mWindow).X + mWindow.Left, Mouse.GetPosition(mWindow).Y + mWindow.Top)

The + mWindow.Left and + mWindow.Top makes sure the position is in the right place even when the user drags the window around.

Routing HTTP Error 404.0 0x80070002

The problem for me was a new server that System.Web.Routing was of version 3.5 while web.config requested version 4.0.0.0. The resolution was

%WINDIR%\Framework\v4.0.30319\aspnet_regiis -i

%WINDIR%\Framework64\v4.0.30319\aspnet_regiis -i

CREATE DATABASE permission denied in database 'master' (EF code-first)

The solution to this problem is as simple as eating a piece of cake.This issue generally arises when your user credentials change and SQL server is not able to identify you .No need to uninstall the existing SQL server instance .You can simply install a new instance with a new instance name . Lets say if your last instance name was 'Sqlexpress' , so this time during installation , name your instance as 'Sqlexpress1' . Also don't forget to select the mix mode (i.e Sql Server Authentication & Windows Authentication) during the installation and provide a system admin password which will be handy if such a problem occurs in future. This solution will definitely resolve this issue. Thanks..

declaring a priority_queue in c++ with a custom comparator

The accepted answer makes you believe that you must use a class or a std::function as comparator. This is not true! As cute_ptr's answer shows, you can pass a function pointer to the constructor. However, the syntax to do so is much simpler than shown there:

class Node;
bool Compare(Node a, Node b);

std::priority_queue<Node, std::vector<Node>, decltype(&Compare)> openSet(Compare);

That is, there is no need to explicitly encode the function's type, you can let the compiler do that for you using decltype.

This is very useful if the comparator is a lambda. You cannot specify the type of a lambda in any other way than using decltype. For example:

auto compare = [](Node a, Node b) { return a.foo < b.foo; }
std::priority_queue<Node, std::vector<Node>, decltype(compare)> openSet(compare);

Converting Date and Time To Unix Timestamp

You can use Date.getTime() function, or the Date object itself which when divided returns the time in milliseconds.

var d = new Date();

d/1000
> 1510329641.84

d.getTime()/1000
> 1510329641.84

The 'Access-Control-Allow-Origin' header contains multiple values

Here's another instance similar to the examples above that you may only have one config file define where CORS is: There were two web.config files on the IIS server on the path in different directories, and one of them was hidden in the virtual directory. To solve it I deleted the root level config file since the path was using the config file in the virtual directory. Have to choose one or the other.

URL called:  'https://example.com/foo/bar'
                     ^              ^
      CORS config file in root      virtual directory with another CORS config file
          deleted this config             other sites using this

VBScript -- Using error handling

VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the results of the last operation performed. You have to explicitly check whether the Err.Number property is non-zero after each operation.

On Error Resume Next

DoStep1

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStep1: " & Err.Description
  Err.Clear
End If

DoStep2

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStop2:" & Err.Description
  Err.Clear
End If

'If you no longer want to continue following an error after that block's completed,
'call this.
On Error Goto 0

The "On Error Goto [label]" syntax is supported by Visual Basic and Visual Basic for Applications (VBA), but VBScript doesn't support this language feature so you have to use On Error Resume Next as described above.

Python dictionary: Get list of values for list of keys

Following closure of Python: efficient way to create a list from dict values with a given order

Retrieving the keys without building the list:

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import collections


class DictListProxy(collections.Sequence):
    def __init__(self, klist, kdict, *args, **kwargs):
        super(DictListProxy, self).__init__(*args, **kwargs)
        self.klist = klist
        self.kdict = kdict

    def __len__(self):
        return len(self.klist)

    def __getitem__(self, key):
        return self.kdict[self.klist[key]]


myDict = {'age': 'value1', 'size': 'value2', 'weigth': 'value3'}
order_list = ['age', 'weigth', 'size']

dlp = DictListProxy(order_list, myDict)

print(','.join(dlp))
print()
print(dlp[1])

The output:

value1,value3,value2

value3

Which matches the order given by the list

What's the UIScrollView contentInset property for?

While jball's answer is an excellent description of content insets, it doesn't answer the question of when to use it. I'll borrow from his diagrams:

  _|?_cW_?_|_?_
   |       | 
---------------
   |content| ?
 ? |content| contentInset.top
cH |content|
 ? |content| contentInset.bottom
   |content| ?
---------------
   |content|    
-------------?-

That's what you get when you do it, but the usefulness of it only shows when you scroll:

  _|?_cW_?_|_?_
   |content| ? content is still visible
---------------
   |content| ?
 ? |content| contentInset.top
cH |content|
 ? |content| contentInset.bottom
   |content| ?
---------------
  _|_______|___ 
             ?

That top row of content will still be visible because it's still inside the frame of the scroll view. One way to think of the top offset is "how much to shift the content down the scroll view when we're scrolled all the way to the top"

To see a place where this is actually used, look at the build-in Photos app on the iphone. The Navigation bar and status bar are transparent, and the contents of the scroll view are visible underneath. That's because the scroll view's frame extends out that far. But if it wasn't for the content inset, you would never be able to have the top of the content clear that transparent navigation bar when you go all the way to the top.

UUID max character length

Most databases have a native UUID type these days to make working with them easier. If yours doesn't, they're just 128-bit numbers, so you can use BINARY(16), and if you need the text format frequently, e.g. for troubleshooting, then add a calculated column to generate it automatically from the binary column. There is no good reason to store the (much larger) text form.

How to shuffle an ArrayList

Try Collections.shuffle(list).If usage of this method is barred for solving the problem, then one can look at the actual implementation.

javax vs java package

java.* packages are the core Java language packages, meaning that programmers using the Java language had to use them in order to make any worthwhile use of the java language.

javax.* packages are optional packages, which provides a standard, scalable way to make custom APIs available to all applications running on the Java platform.

How to submit a form on enter when the textarea has focus?

You can't do this without JavaScript. Stackoverflow is using the jQuery JavaScript library which attachs functions to HTML elements on page load.

Here's how you could do it with vanilla JavaScript:

<textarea onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }"></textarea>

Keycode 13 is the enter key.

Here's how you could do it with jQuery like as Stackoverflow does:

<textarea class="commentarea"></textarea>

with

$(document).ready(function() {
    $('.commentarea').keydown(function(event) {
        if (event.which == 13) {
            this.form.submit();
            event.preventDefault();
         }
    });
});

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

WARNING: Using Access-Control-Allow-Origin: * can make your API/website vulnerable to cross-site request forgery (CSRF) attacks. Make certain you understand the risks before using this code.

It's very simple to solve if you are using PHP. Just add the following script in the beginning of your PHP page which handles the request:

<?php header('Access-Control-Allow-Origin: *'); ?>

If you are using Node-red you have to allow CORS in the node-red/settings.js file by un-commenting the following lines:

// The following property can be used to configure cross-origin resource sharing
// in the HTTP nodes.
// See https://github.com/troygoode/node-cors#configuration-options for
// details on its contents. The following is a basic permissive set of options:
httpNodeCors: {
 origin: "*",
 methods: "GET,PUT,POST,DELETE"
},

If you are using Flask same as the question; you have first to install flask-cors

$ pip install -U flask-cors

Then include the Flask cors in your application.

from flask_cors import CORS

A simple application will look like:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
  return "Hello, cross-origin-world!"

For more details, you can check the Flask documentation.

Best way to test exceptions with Assert to ensure they will be thrown

Suggest using NUnit's clean delegate syntax.

Example for testing ArgumentNullExeption:

[Test]
[TestCase(null)]
public void FooCalculation_InvalidInput_ShouldThrowArgumentNullExeption(string text)
{
    var foo = new Foo();
    Assert.That(() => foo.Calculate(text), Throws.ArgumentNullExeption);

    //Or:
    Assert.That(() => foo.Calculate(text), Throws.Exception.TypeOf<ArgumentNullExeption>);
}

c - warning: implicit declaration of function ‘printf’

the warning or error of kind IMPLICIT DECLARATION is that the compiler is expecting a Function Declaration/Prototype..

It might either be a header file or your own function Declaration..