Programs & Examples On #Object relational model

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

Example:

perfdb-# \df information_schema.*;

List of functions
        Schema      |        Name        | Result data type | Argument data types |  Type  
 information_schema | _pg_char_max_length   | integer | typid oid, typmod integer | normal
 information_schema | _pg_char_octet_length | integer | typid oid, typmod integer | normal
 information_schema | _pg_datetime_precision| integer | typid oid, typmod integer | normal
 .....
 information_schema | _pg_numeric_scale     | integer | typid oid, typmod integer | normal
 information_schema | _pg_truetypid         | oid     | pg_attribute, pg_type     | normal
 information_schema | _pg_truetypmod        | integer | pg_attribute, pg_type     | normal
(11 rows)

SQL Server IIF vs CASE

IIF is a non-standard T-SQL function. It was added to SQL SERVER 2012, so that Access could migrate to SQL Server without refactoring the IIF's to CASE before hand. Once the Access db is fully migrated into SQL Server, you can refactor.

Examples of Algorithms which has O(1), O(n log n) and O(log n) complexities

O(1) - Deleting an element from a doubly linked list. e.g.

typedef struct _node {
    struct _node *next;
    struct _node *prev;
    int data;
} node;


void delete(node **head, node *to_delete)
{
    .
    .
    .
}

Why plt.imshow() doesn't display the image?

The solution was as simple as adding plt.show() at the end of the code snippet:

import numpy as np
np.random.seed(123)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test) = mnist.load_data()
print X_train.shape
from matplotlib import pyplot as plt
plt.imshow(X_train[0])
plt.show()

Find the index of a dict within a list, by matching the dict's value

One liner!?

elm = ([i for i in mylist if i['name'] == 'Tom'] or [None])[0]

Execution failed app:processDebugResources Android Studio

Had the same problem. I changed the file build.gradle inside the app folder from this: compileSdkVersion 23 buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "com.vastsoftware.family.farmingarea"
    minSdkVersion 11
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"

to this:

compileSdkVersion 23 buildToolsVersion "21.0.2"

defaultConfig {
    applicationId "com.vastsoftware.family.farmingarea"
    minSdkVersion 11
    targetSdkVersion 21
    versionCode 1
    versionName "1.0"

and worked perfectly! hope it works for you too!

How to get Activity's content view?

this.getWindow().getDecorView().findViewById(android.R.id.content)

or

this.findViewById(android.R.id.content)

or

this.findViewById(android.R.id.content).getRootView()

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

pandas DataFrame: replace nan values with average of columns

Although, the below code does the job, BUT its performance takes a big hit, as you deal with a DataFrame with # records 100k or more:

df.fillna(df.mean())

In my experience, one should replace NaN values (be it with Mean or Median), only where it is required, rather than applying fillna() all over the DataFrame.

I had a DataFrame with 20 variables, and only 4 of them required NaN values treatment (replacement). I tried the above code (Code 1), along with a slightly modified version of it (code 2), where i ran it selectively .i.e. only on variables which had a NaN value

#------------------------------------------------
#----(Code 1) Treatment on overall DataFrame-----

df.fillna(df.mean())

#------------------------------------------------
#----(Code 2) Selective Treatment----------------

for i in df.columns[df.isnull().any(axis=0)]:     #---Applying Only on variables with NaN values
    df[i].fillna(df[i].mean(),inplace=True)

#---df.isnull().any(axis=0) gives True/False flag (Boolean value series), 
#---which when applied on df.columns[], helps identify variables with NaN values

Below is the performance i observed, as i kept on increasing the # records in DataFrame

DataFrame with ~100k records

  • Code 1: 22.06 Seconds
  • Code 2: 0.03 Seconds

DataFrame with ~200k records

  • Code 1: 180.06 Seconds
  • Code 2: 0.06 Seconds

DataFrame with ~1.6 Million records

  • Code 1: code kept running endlessly
  • Code 2: 0.40 Seconds

DataFrame with ~13 Million records

  • Code 1: --did not even try, after seeing performance on 1.6 Mn records--
  • Code 2: 3.20 Seconds

Apologies for a long answer ! Hope this helps !

How to interactively (visually) resolve conflicts in SourceTree / git

From SourceTree, click on Tools->Options. Then on the "General" tab, make sure to check the box to allow SourceTree to modify your Git config files.

Then switch to the "Diff" tab. On the lower half, use the drop down to select the external program you want to use to do the diffs and merging. I've installed KDiff3 and like it well enough. When you're done, click OK.

Now when there is a merge, you can go under Actions->Resolve Conflicts->Launch External Merge Tool.

EC2 Instance Cloning

Nowadays it is even easier to clone the machine with EBS-backed instances released a while ago. This is how we do it in BitNami Cloud Hosting. Basically you just take a snapshot of the instance which can be used later to launch a new server. You can do it either using AWS console (saving the EBS-backed instance as AWS AMI) or using the EC2 API tools:

Cloning the instance is nothing else but creating the backup and then launching a new server based on that. You can find bunch of articles out there describing this problem, try to find the info about "how to ..." backup or resize the whole EC2 instance, for example this blog is a really good place to start: alestic.com

CMake link to external library

Set libraries search path first:

LINK_DIRECTORIES(${CMAKE_BINARY_DIR}/res)

And then just do

TARGET_LINK_LIBRARIES(GLBall mylib)

C++ - How to append a char to char*?

The specific problem is that you're declaring a new variable instead of assigning to an existing one:

char * ret = new char[strlen(array) + 1 + 1];
^^^^^^ Remove this

and trying to compare string values by comparing pointers:

if (array!="")     // Wrong - compares pointer with address of string literal
if (array[0] == 0) // Better - checks for empty string

although there's no need to make that comparison at all; the first branch will do the right thing whether or not the string is empty.

The more general problem is that you're messing around with nasty, error-prone C-style string manipulation in C++. Use std::string and it will manage all the memory allocation for you:

std::string appendCharToString(std::string const & s, char a) {
    return s + a;
}

Conditional WHERE clause in SQL Server

This seemed easier to think about where either of two parameters could be passed into a stored procedure. It seems to work:

SELECT * 
FROM x 
WHERE CONDITION1
AND ((@pol IS NOT NULL AND x.PolicyNo = @pol) OR (@st IS NOT NULL AND x.State = @st))
AND OTHERCONDITIONS

Java ArrayList replace at specific index

Lets get array list as ArrayList and new value as value all you need to do is pass the parameters to .set method. ArrayList.set(index,value)

Ex -

ArrayList.set(10,"new value or object")

Responsive css background images

background: url(/static/media/group3x.6bb50026.jpg);
background-size: contain;
background-repeat: no-repeat;
background-position: top;

the position property can be used to align top bottom and center as per your need and background-size can be used for center crop(cover) or full image(contain or 100%)

How can I center text (horizontally and vertically) inside a div block?

You can try the following methods:

  1. If you have a single word or one line sentence, then the following code can do the trick.

    Have a text inside a div tag and give it an id. Define the following properties for that id.

    id-name {
      height: 90px;
      line-height: 90px;
      text-align: center;
      border: 2px dashed red;
    }
    

    Note: Make sure the line-height property is same as the height of the division.

    Image

    But, if the content is more than one single word or a line then this doesn’t work. Also, there will be times when you cannot specify the size of a division in px or % (when the division is really small and you want the content to be exactly in the middle).

  2. To solve this issue, we can try the following combination of properties.

    id-name {
      display: flex;
      justify-content: center;
      align-items: center;
      border: 2px dashed red;
    }
    

    Image

    These 3 lines of code sets the content exactly in the middle of a division (irrespective of the size of the display). The "align-items: center" helps in vertical centering while "justify-content: center" will make it horizontally centered.

    Note: Flex does not work in all browsers. Make sure you add appropriate vendor prefixes for additional browser support.

How do I rename a local Git branch?

Just three steps to replicate change in name on remote as well as on GitHub:

Step 1 git branch -m old_branchname new_branchname

Step 2 git push origin :old_branchname new_branchname

Step 3 git push --set-upstream origin new_branchname

align 3 images in same row with equal spaces?

HTML:

<div class="container">
    <span>
        <img ... >
    </span>
    <span>
        <img ... >
    </span>
    <span>
        <img ... >
    </span>
</div>

CSS:

.container{ width:50%; margin:0 auto; text-align:center}
.container span{ width:30%; margin:0 1%;  }

I haven't tested this, but hope this will work.

You can add 'display:inline-block' to .container span to make the span to have fixed 30% width

Java Code for calculating Leap Year

new GregorianCalendar().isLeapYear(year);

Convert boolean to int in Java

int val = b? 1 : 0;

Why would you use Expression<Func<T>> rather than Func<T>?

You would use an expression when you want to treat your function as data and not as code. You can do this if you want to manipulate the code (as data). Most of the time if you don't see a need for expressions then you probably don't need to use one.

Using module 'subprocess' with timeout

https://pypi.python.org/pypi/python-subprocess2 provides extensions to the subprocess module which allow you to wait up to a certain period of time, otherwise terminate.

So, to wait up to 10 seconds for the process to terminate, otherwise kill:

pipe  = subprocess.Popen('...')

timeout =  10

results = pipe.waitOrTerminate(timeout)

This is compatible with both windows and unix. "results" is a dictionary, it contains "returnCode" which is the return of the app (or None if it had to be killed), as well as "actionTaken". which will be "SUBPROCESS2_PROCESS_COMPLETED" if the process completed normally, or a mask of "SUBPROCESS2_PROCESS_TERMINATED" and SUBPROCESS2_PROCESS_KILLED depending on action taken (see documentation for full details)

How to ssh from within a bash script?

  1. If you want the password prompt to go away then use key based authentication (described here).

  2. To run commands remotely over ssh you have to give them as an argument to ssh, like the following:

root@host:~ # ssh root@www 'ps -ef | grep apache | grep -v grep | wc -l'

Getting java.net.SocketTimeoutException: Connection timed out in android

I faced the same problem when connecting to EC2, the issue was with Security Group, I solved by adding the allowed IPs at port 5432

how to set radio option checked onload with jQuery

I think you can assume, that name is unique and all radio in group has the same name. Then you can use jQuery support like that:

$("[name=gender]").val(["Male"]);

Note: Passing array is important.

Conditioned version:

if (!$("[name=gender]:checked").length) {
    $("[name=gender]").val(["Male"]);
}

Android Webview - Completely Clear the Cache

I found the fix you were looking for:

context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db");

For some reason Android makes a bad cache of the url which it keeps returning by accident instead of the new data you need. Sure, you could just delete the entries from the DB but in my case I am only trying to access one URL so blowing away the whole DB is easier.

And don't worry, these DBs are just associated with your app so you aren't clearing the cache of the whole phone.

Oracle SQL update based on subquery between two tables

Try it ..

UPDATE PRODUCTION a
SET (name, count) = (
SELECT name, count
        FROM STAGING b
        WHERE a.ID = b.ID)
WHERE EXISTS (SELECT 1
    FROM STAGING b
    WHERE a.ID=b.ID
 );

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class'

Try to update the package.json file so that "@angular-devkit/build-angular": "^0.800.1" reads "@angular-devkit/build-angular": "^0.12.4"

Then run npm install in the command line.

Reference: https://stackoverflow.com/a/56537342

How to implement a binary tree?

class Node:
    """
    single Node for tree
    """

    def __init__(self, data):
        self.data = data
        self.right = None
        self.left = None


class binaryTree:
    """
    binary tree implementation
    """

    def __init__(self):
        self.root = None

    def push(self, element, node=None):
        if node is None:
            node = self.root

        if self.root is None:
            self.root = Node(element)

        else:
            if element < node.data:
                if node.left is not None:
                    self.push(element, node.left)
                else:
                    node.left = Node(element)
            else:
                if node.right is not None:
                    self.push(element, node.right)
                else:
                    node.right = Node(element)

    def __str__(self):
        self.printInorder(self.root)
        return "\n"

    def printInorder(self, node):
        """
        print tree in inorder
        """
        if node is not None:
            self.printInorder(node.left)
            print(node.data)
            self.printInorder(node.right)


def main():
    """
    Main code and logic comes here
    """
    tree = binaryTree()
    tree.push(5)
    tree.push(3)
    tree.push(1)
    tree.push(3)
    tree.push(0)
    tree.push(2)
    tree.push(9)
    tree.push(10)
    print(tree)


if __name__ == "__main__":
    main()

How to convert file to base64 in JavaScript?

TypeScript version

const file2Base64 = (file:File):Promise<string> => {
    return new Promise<string> ((resolve,reject)=> {
         const reader = new FileReader();
         reader.readAsDataURL(file);
         reader.onload = () => resolve(reader.result.toString());
         reader.onerror = error => reject(error);
     })
    }

font-family is inherit. How to find out the font-family in chrome developer pane?

Your browser's default font-family will be inherited for that case.

You can check the browser default font in chrome: Settings > Web content > Customize fonts...

enter image description here enter image description here

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

I realise that it's been a very long time but thought I'd add anyway. If you just want the table, and not the create table statement you could use

select into x from db.schema.y where 1=0

to copy the table to a new DB

How to pass parameter to function using in addEventListener?

In the first line of your JS code:

select.addEventListener('change', getSelection(this), false);

you're invoking getSelection by placing (this) behind the function reference. That is most likely not what you want, because you're now passing the return value of that call to addEventListener, instead of a reference to the actual function itself.


In a function invoked by addEventListener the value for this will automatically be set to the object the listener is attached to, productLineSelect in this case.

If that is what you want, you can just pass the function reference and this will in this example be select in invocations from addEventListener:

select.addEventListener('change', getSelection, false);

If that is not what you want, you'd best bind your value for this to the function you're passing to addEventListener:

var thisArg = { custom: 'object' };
select.addEventListener('change', getSelection.bind(thisArg), false);

The .bind part is also a call, but this call just returns the same function we're calling bind on, with the value for this inside that function scope fixed to thisArg, effectively overriding the dynamic nature of this-binding.


To get to your actual question: "How to pass parameters to function in addEventListener?"

You would have to use an additional function definition:

var globalVar = 'global';

productLineSelect.addEventListener('change', function(event) {
    var localVar = 'local';
    getSelection(event, this, globalVar, localVar);
}, false);

Now we pass the event object, a reference to the value of this inside the callback of addEventListener, a variable defined and initialised inside that callback, and a variable from outside the entire addEventListener call to your own getSelection function.


We also might again have an object of our choice to be this inside the outer callback:

var thisArg = { custom: 'object' };
var globalVar = 'global';

productLineSelect.addEventListener('change', function(event) {
    var localVar = 'local';
    getSelection(event, this, globalVar, localVar);
}.bind(thisArg), false);

remove / reset inherited css from an element

As long as they are attributes like classes and ids you can remove them by javascript/jQuery class modifiers.

document.getElementById("MyElement").className = "";

There is no way to remove specific tag CSS other than overriding them (or using another element).

Change directory command in Docker?

I was wondering if two times WORKDIR will work or not, but it worked :)

FROM ubuntu:18.04

RUN apt-get update && \
    apt-get install -y python3.6

WORKDIR /usr/src

COPY ./ ./

WORKDIR /usr/src/src

CMD ["python3", "app.py"]

How to modify a CSS display property from JavaScript?

I found the solution.

As said in the EDIT of my answer, a <div> is misfunctioning in a <table>. So I wrote this code instead :

<tr id="hidden" style="display:none;">
    <td class="depot_table_left">
        <label for="sexe">Sexe</label>
    </td>
    <td>
        <select type="text" name="sexe">
            <option value="1">Sexe</option>
            <option value="2">Joueur</option>
            <option value="3">Joueuse</option>
        </select>
    </td>
</tr>

And this is working fine.

Thanks everybody ;)

Difference between abstraction and encapsulation?

class Aeroplane : IFlyable, IFuelable, IMachine
{ // Aeroplane's Design says:
  // Aeroplane is a flying object
  // Aeroplane can be fueled
  // Aeroplane is a Machine
}
// But the code related to Pilot, or Driver of Aeroplane is not bothered 
// about Machine or Fuel. Hence,
// pilot code:
IFlyable flyingObj = new Aeroplane();
flyingObj.Fly();
// fighter Pilot related code
IFlyable flyingObj2 = new FighterAeroplane();
flyingObj2.Fly();
// UFO related code 
IFlyable ufoObj = new UFO();
ufoObj.Fly();
// **All the 3 Above codes are genaralized using IFlyable,
// Interface Abstraction**
// Fly related code knows how to fly, irrespective of the type of 
// flying object they are.

// Similarly, Fuel related code:
// Fueling an Aeroplane
IFuelable fuelableObj = new Aeroplane();
fuelableObj.FillFuel();
// Fueling a Car
IFuelable fuelableObj2 = new Car(); // class Car : IFuelable { }
fuelableObj2.FillFuel();

// ** Fueling code does not need know what kind of vehicle it is, so far 
// as it can Fill Fuel**

Validate that a string is a positive integer

This is how I validate that a string is a positive integer.

_x000D_
_x000D_
var str = "123";
var str1 = "1.5";
var str2 = "-123";

console.log("is str positive integer: ", Number.isInteger(Number(str)) && Number(str) > 0)
console.log("is str1 positive integer: ", Number.isInteger(Number(str1)) && Number(str1) > 0)
console.log("is str2 positive integer: ", Number.isInteger(Number(str2)) && Number(str2) > 0)
_x000D_
_x000D_
_x000D_

Turning off some legends in a ggplot

You can use guide=FALSE in scale_..._...() to suppress legend.

For your example you should use scale_colour_continuous() because length is continuous variable (not discrete).

(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
   scale_colour_continuous(guide = FALSE) +
   geom_point()
)

Or using function guides() you should set FALSE for that element/aesthetic that you don't want to appear as legend, for example, fill, shape, colour.

p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
  geom_point()    
p0+guides(colour=FALSE)

UPDATE

Both provided solutions work in new ggplot2 version 2.0.0 but movies dataset is no longer present in this library. Instead you have to use new package ggplot2movies to check those solutions.

library(ggplot2movies)
data(movies)
mov <- subset(movies, length != "")

SVG Positioning

As mentioned in the other comment, the transform attribute on the g element is what you want. Use transform="translate(x,y)" to move the g around and things within the g will move in relation to the g.

IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager

Another possible workaround, which I'm not sure if helps in all cases (origin here) :

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        final View rootView = findViewById(android.R.id.content);
        if (rootView != null) {
            rootView.cancelPendingInputEvents();
        }
    }
}

HTML form action and onsubmit issues

Try:

onsubmit="checkRegistration(event.preventDefault())"

Google Maps API: open url by clicking on marker

google.maps.event.addListener(marker, 'click', (function(marker, i) {
  return function() {
    window.location.href = marker.url;
  }
})(marker, i));

How to find the php.ini file used by the command line?

Run php --ini in your terminal, you'll get all details about ini files

[root@tamilan src]# php --ini
Configuration File (php.ini) Path: /etc
Loaded Configuration File:         /etc/php.ini
Scan for additional .ini files in: /etc/php.d
Additional .ini files parsed:      /etc/php.d/apc.ini,
/etc/php.d/bcmath.ini,
/etc/php.d/curl.ini,
/etc/php.d/dba.ini,
/etc/php.d/dom.ini,
/etc/php.d/fileinfo.ini,
/etc/php.d/gd.ini,
/etc/php.d/imap.ini,
/etc/php.d/json.ini,
/etc/php.d/mbstring.ini,
/etc/php.d/memcache.ini,
/etc/php.d/mysql.ini,
/etc/php.d/mysqli.ini,
/etc/php.d/pdo.ini,
/etc/php.d/pdo_mysql.ini,
/etc/php.d/pdo_sqlite.ini,
/etc/php.d/phar.ini,
/etc/php.d/posix.ini,
/etc/php.d/sqlite3.ini,
/etc/php.d/ssh2.ini,
/etc/php.d/sysvmsg.ini,
/etc/php.d/sysvsem.ini,
/etc/php.d/sysvshm.ini,
/etc/php.d/wddx.ini,
/etc/php.d/xmlreader.ini,
/etc/php.d/xmlwriter.ini,
/etc/php.d/xsl.ini,
/etc/php.d/zip.ini

For more, use helping command php --help It'll display all the possible options.

How to use onSavedInstanceState example please

A good information: you don't need to check whether the Bundle object is null into the onCreate() method. Use the onRestoreInstanceState() method, which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null

How to download image from url

Try this it worked for me

Write this in your Controller

public class DemoController: Controller

        public async Task<FileStreamResult> GetLogoImage(string logoimage)
        {
            string str = "" ;
            var filePath = Server.MapPath("~/App_Data/" + SubfolderName);//If subfolder exist otherwise leave.
            // DirectoryInfo dir = new DirectoryInfo(filePath);
            string[] filePaths = Directory.GetFiles(@filePath, "*.*");
            foreach (var fileTemp in filePaths)
            {
                  str= fileTemp.ToString();
            }
                return File(new MemoryStream(System.IO.File.ReadAllBytes(str)), System.Web.MimeMapping.GetMimeMapping(str), Path.GetFileName(str));
        }

Here is my view

<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>

sql server invalid object name - but tables are listed in SSMS tables list

did you try: right click the database, and click "refresh"

Google Maps Api v3 - find nearest markers

First you have to add the eventlistener

google.maps.event.addListener(map, 'click', find_closest_marker);

Then create a function that loops through the array of markers and uses the haversine formula to calculate the distance of each marker from the click.

function rad(x) {return x*Math.PI/180;}
function find_closest_marker( event ) {
    var lat = event.latLng.lat();
    var lng = event.latLng.lng();
    var R = 6371; // radius of earth in km
    var distances = [];
    var closest = -1;
    for( i=0;i<map.markers.length; i++ ) {
        var mlat = map.markers[i].position.lat();
        var mlng = map.markers[i].position.lng();
        var dLat  = rad(mlat - lat);
        var dLong = rad(mlng - lng);
        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(rad(lat)) * Math.cos(rad(lat)) * Math.sin(dLong/2) * Math.sin(dLong/2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        var d = R * c;
        distances[i] = d;
        if ( closest == -1 || d < distances[closest] ) {
            closest = i;
        }
    }

    alert(map.markers[closest].title);
}

This keeps track of the closest markers and alerts its title.

I have my markers as an array on my map object

Retrieving the COM class factory for component failed

I have Done the Following Things in IIS 8.5 (Windows Server 2012 R2)Server and its Worked in My Case Without Restart:

  1. Selecting The Application Pool That Connected to The Application in IIS

  2. And Right Click --> Advanced Settings --> Process Model --> Select Local System Instead of Recommended ApplicationPoolIdentity

  3. And Make Sure C:\Windows\SysWOW64\config\systemprofile\desktop Have Enough Access For Users.

  4. Refresh the Website Link that Connected With this Pool


enter image description here

Postgres: SQL to list table foreign keys

You can use the PostgreSQL system catalogs. Maybe you can query pg_constraint to ask for foreign keys. You can also use the Information Schema

How to check if a column exists in a SQL Server table?

Another contribute is the following sample that add the column if not exist.

    USE [Northwind]
    GO

    IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS 
                    WHERE TABLE_NAME = 'Categories'
                        AND COLUMN_NAME = 'Note')
    BEGIN

    ALTER TABLE Categories ADD Note NVARCHAR(800) NULL

    END
    GO

Hope it helps. Simone

How do I add a user when I'm using Alpine as a base image?

Alpine uses the command adduser and addgroup for creating users and groups (rather than useradd and usergroup).

FROM alpine:latest

# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# Tell docker that all future commands should run as the appuser user
USER appuser

The flags for adduser are:

Usage: adduser [OPTIONS] USER [GROUP]

Create new user, or add USER to GROUP

        -h DIR          Home directory
        -g GECOS        GECOS field
        -s SHELL        Login shell
        -G GRP          Group
        -S              Create a system user
        -D              Don't assign a password
        -H              Don't create home directory
        -u UID          User id
        -k SKEL         Skeleton directory (/etc/skel)

Add new user official docs

"Post Image data using POSTMAN"

The accepted answer works if you set the JSON as a key/value pair in the form-data panel (See the image hereunder)

enter image description here

Nevertheless, I am wondering if it is a very clean way to design an API. If it is mandatory for you to upload both image and JSON in a single call maybe it is ok but if you could separate the routes (one for image uploading, the other for JSON body with a proper content-type header), it seems better.

How do I pass multiple ints into a vector at once?

These days (c++17) it's easy:

auto const pusher([](auto& v) noexcept
  {
    return [&](auto&& ...e)
      {
        (
          (
            v.push_back(std::forward<decltype(e)>(e))
          ),
          ...
        );
      };
  }
);

pusher(TestVector)(2, 5, 8, 11, 14);

How to turn on WCF tracing?

Go to your Microsoft SDKs directory. A path like this:

C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools

Open the WCF Configuration Editor (Microsoft Service Configuration Editor) from that directory:

SvcConfigEditor.exe

(another option to open this tool is by navigating in Visual Studio 2017 to "Tools" > "WCF Service Configuration Editor")

wcf configuration editor

Open your .config file or create a new one using the editor and navigate to Diagnostics.

There you can click the "Enable MessageLogging".

enable messagelogging

More info: https://msdn.microsoft.com/en-us/library/ms732009(v=vs.110).aspx

With the trace viewer from the same directory you can open the trace log files:

SvcTraceViewer.exe

You can also enable tracing using WMI. More info: https://msdn.microsoft.com/en-us/library/ms730064(v=vs.110).aspx

What's the difference between StaticResource and DynamicResource in WPF?

  1. StaticResource uses first value. DynamicResource uses last value.
  2. DynamicResource can be used for nested styling, StaticResource cannot.

Suppose you have this nested Style dictionary. LightGreen is at the root level while Pink is nested inside a Grid.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="{x:Type Grid}">
        <Style.Resources>
            <Style TargetType="{x:Type Button}" x:Key="ConflictButton">
                <Setter Property="Background" Value="Pink"/>
            </Style>
        </Style.Resources>
    </Style>
    <Style TargetType="{x:Type Button}" x:Key="ConflictButton">
        <Setter Property="Background" Value="LightGreen"/>
    </Style>
</ResourceDictionary>

In view:

<Window x:Class="WpfStyleDemo.ConflictingStyleWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ConflictingStyleWindow" Height="100" Width="100">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Styles/ConflictingStyle.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Button Style="{DynamicResource ConflictButton}" Content="Test"/>
    </Grid>
</Window>

StaticResource will render the button as LightGreen, the first value it found in the style. DynamicResource will override the LightGreen button as Pink as it renders the Grid.

StaticResource StaticResource

DynamicResource DynamicResource

Keep in mind that VS Designer treats DynamicResource as StaticResource. It will get first value. In this case, VS Designer will render the button as LightGreen although it actually ends up as Pink.

StaticResource will throw an error when the root-level style (LightGreen) is removed.

Collections sort(List<T>,Comparator<? super T>) method example

This might be simplest way -

Collections.sort(listOfStudent,new Comparator<Student>(){
                     public int compare(Student s1,Student s2){
                           // Write your logic here.
                     }});

Using Java 8(lambda expression) -

listOfStudent.sort((s1, s2) -> s1.age - s2.age); 

R Plotting confidence bands with ggplot

require(ggplot2)
require(nlme)

set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)

mp <- within(mp,
         {
             wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
             wow <- rnorm(N)*wav+rnorm(N)*wav^3
         })

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

Get fitted values (the same as m01$fitted)

fit <- predict(m01)

Normally we could use something like predict(...,se.fit=TRUE) to get the confidence intervals on the prediction, but gls doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :

V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))

Put together a "prediction frame":

predframe <- with(mp,data.frame(year,wav,
                                wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))

Now plot with geom_ribbon

(p1 <- ggplot(mp, aes(year, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

year vs wow

It's easier to see that we got the right answer if we plot against wav rather than year:

(p2 <- ggplot(mp, aes(wav, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

wav vs wow

It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly() fits -- see ?makepredictcall.

Redirecting unauthorized controller in ASP.NET MVC

This problem has hounded me for some days now, so on finding the answer that affirmatively works with tvanfosson's answer above, I thought it would be worthwhile to emphasize the core part of the answer, and address some related catch ya's.

The core answer is this, sweet and simple:

filterContext.Result = new HttpUnauthorizedResult();

In my case I inherit from a base controller, so in each controller that inherits from it I override OnAuthorize:

protected override void OnAuthorization(AuthorizationContext filterContext)
{
    base.OnAuthorization(filterContext);
    YourAuth(filterContext); // do your own authorization logic here
}

The problem was that in 'YourAuth', I tried two things that I thought would not only work, but would also immediately terminate the request. Well, that is not how it works. So first, the two things that DO NOT work, unexpectedly:

filterContext.RequestContext.HttpContext.Response.Redirect("/Login"); // doesn't work!
FormsAuthentication.RedirectToLoginPage(); // doesn't work!

Not only do those not work, they don't end the request either. Which means the following:

if (!success) {
    filterContext.Result = new HttpUnauthorizedResult();
}
DoMoreStuffNowThatYouThinkYourAuthorized();

Well, even with the correct answer above, the flow of logic still continues! You will still hit DoMoreStuff... within OnAuthorize. So keep that in mind (DoMore... should be in an else therefore).

But with the correct answer, while OnAuthorize flow of logic continues till the end still, after that you really do get what you expect: a redirect to your login page (if you have one set in Forms auth in your webconfig).

But unexpectedly, 1) Response.Redirect("/Login") does not work: the Action method still gets called, and 2) FormsAuthentication.RedirectToLoginPage(); does the same thing: the Action method still gets called!

Which seems totally wrong to me, particularly with the latter: who would have thought that FormsAuthentication.RedirectToLoginPage does not end the request, or do the equivalant above of what filterContext.Result = new HttpUnauthorizedResult() does?

What is the best way to conditionally apply a class?

My favorite method is using the ternary expression.

ng-class="condition ? 'trueClass' : 'falseClass'"

Note: Incase you're using a older version of Angular you should use this instead,

ng-class="condition && 'trueClass' || 'falseClass'"

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

If you just want to disable App Transport Policy for local dev servers then the following solutions work well. It's useful when you're unable, or it's impractical, to set up HTTPS (e.g. when using the Google App Engine dev server).

As others have said though, ATP should definitely not be turned off for production apps.

1) Use a different plist for Debug

Copy your Plist file and NSAllowsArbitraryLoads. Use this Plist for debugging.

XCode Debug

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

2) Exclude local servers

Alternatively, you can use a single plist file and exclude specific servers. However, it doesn't look like you can exclude IP 4 addresses so you might need to use the server name instead (found in System Preferences -> Sharing, or configured in your local DNS).

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>server.local</key>
        <dict/>
        <key>NSExceptionAllowsInsecureHTTPLoads</key>
        <true/>
    </dict>
</dict>

CSS to select/style first word

What you are looking for is a pseudo-element that doesn't exist. There is :first-letter and :first-line, but no :first-word.

You can of course do this with JavaScript. Here's some code I found that does this: http://www.dynamicsitesolutions.com/javascript/first-word-selector/

How do I change the root directory of an Apache server?

Please note, that this only applies for Ubuntu 14.04 LTS and newer releases.

In my Ubuntu 14.04 LTS, the document root was set to /var/www/html. It was configured in the following file:

/etc/apache2/sites-available/000-default.conf

So just do a

sudo nano /etc/apache2/sites-available/000-default.conf

and change the following line to what you want:

DocumentRoot /var/www/html

Also do a

sudo nano /etc/apache2/apache2.conf

and find this

<Directory /var/www/html/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>

and change /var/www/html to your preferred directory

and save it.

After you saved your changes, just restart the apache2 webserver and you'll be done :)

sudo service apache2 restart


If you prefer a graphical text editor, you can just replace the sudo nano by a gksu gedit.

Get list of data-* attributes using javascript / jQuery

You should be get the data through the dataset attributes

var data = element.dataset;

dataset is useful tool for get data-attribute

What is ToString("N0") format?

This is where the documentation is:

http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

The numeric ("N") format specifier converts a number to a string of the form "-d,ddd,ddd.ddd…", where "-" indicates a negative number symbol if required, "d" indicates a digit (0-9) ...

And this is where they talk about the default (2):

http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.numberdecimaldigits.aspx

      // Displays a negative value with the default number of decimal digits (2).
      Int64 myInt = -1234;
      Console.WriteLine( myInt.ToString( "N", nfi ) );

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

You can't update with a number greater than 1 for datatype number(2,2) is because, the first parameter is the total number of digits in the number and the second one (.i.e 2 here) is the number of digits in decimal part. I guess you can insert or update data < 1. i.e. 0.12, 0.95 etc.

Please check NUMBER DATATYPE in NUMBER Datatype.

Kotlin Ternary Conditional Operator

For myself I use following extension functions:

fun T?.or<T>(default: T): T = if (this == null) default else this 
fun T?.or<T>(compute: () -> T): T = if (this == null) compute() else this

First one will return provided default value in case object equals null. Second will evaluate expression provided in lambda in the same case.

Usage:

1) e?.getMessage().or("unknown")
2) obj?.lastMessage?.timestamp.or { Date() }

Personally for me code above more readable than if construction inlining

How to add button inside input

I found a great code for you:

HTML

<form class="form-wrapper cf">
    <input type="text" placeholder="Search here..." required>
    <button type="submit">Search</button>
</form>

CSS

/*Clearing Floats*/
.cf:before, .cf:after {
    content:"";
    display:table;
}

.cf:after {
    clear:both;
}

.cf {
    zoom:1;
}    
/* Form wrapper styling */
.form-wrapper {
    width: 450px;
    padding: 15px;
    margin: 150px auto 50px auto;
    background: #444;
    background: rgba(0,0,0,.2);
    border-radius: 10px;
    box-shadow: 0 1px 1px rgba(0,0,0,.4) inset, 0 1px 0 rgba(255,255,255,.2);
}

/* Form text input */

.form-wrapper input {
    width: 330px;
    height: 20px;
    padding: 10px 5px;
    float: left;   
    font: bold 15px 'lucida sans', 'trebuchet MS', 'Tahoma';
    border: 0;
    background: #eee;
    border-radius: 3px 0 0 3px;     
}

.form-wrapper input:focus {
    outline: 0;
    background: #fff;
    box-shadow: 0 0 2px rgba(0,0,0,.8) inset;
}

.form-wrapper input::-webkit-input-placeholder {
   color: #999;
   font-weight: normal;
   font-style: italic;
}

.form-wrapper input:-moz-placeholder {
    color: #999;
    font-weight: normal;
    font-style: italic;
}

.form-wrapper input:-ms-input-placeholder {
    color: #999;
    font-weight: normal;
    font-style: italic;
}   

/* Form submit button */
.form-wrapper button {
    overflow: visible;
    position: relative;
    float: right;
    border: 0;
    padding: 0;
    cursor: pointer;
    height: 40px;
    width: 110px;
    font: bold 15px/40px 'lucida sans', 'trebuchet MS', 'Tahoma';
    color: #fff;
    text-transform: uppercase;
    background: #d83c3c;
    border-radius: 0 3px 3px 0;     
    text-shadow: 0 -1px 0 rgba(0, 0 ,0, .3);
}  

.form-wrapper button:hover {    
    background: #e54040;
}  

.form-wrapper button:active,
.form-wrapper button:focus {  
    background: #c42f2f;
    outline: 0;  
}

.form-wrapper button:before { /* left arrow */
    content: '';
    position: absolute;
    border-width: 8px 8px 8px 0;
    border-style: solid solid solid none;
    border-color: transparent #d83c3c transparent;
    top: 12px;
    left: -6px;
}

.form-wrapper button:hover:before {
    border-right-color: #e54040;
}

.form-wrapper button:focus:before,
.form-wrapper button:active:before {
        border-right-color: #c42f2f;
}     

.form-wrapper button::-moz-focus-inner { /* remove extra button spacing for Mozilla Firefox */
    border: 0;
    padding: 0;
}    

Demo: On fiddle Source: Speckyboy

HTML5 required attribute seems not working

Yes, you missed the form encapsulation:

JSFiddle

<form>
   <input id="tbQuestion" type="text" placeholder="Post a question?" required/>
   <input id="btnSubmit" type="submit" />
</form>

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

As another option, you can do look ups like:

class UserAdmin(admin.ModelAdmin):
    list_display = (..., 'get_author')

    def get_author(self, obj):
        return obj.book.author
    get_author.short_description = 'Author'
    get_author.admin_order_field = 'book__author'

Is String.Contains() faster than String.IndexOf()?

Use a benchmark library, like this recent foray from Jon Skeet to measure it.

Caveat Emptor

As all (micro-)performance questions, this depends on the versions of software you are using, the details of the data inspected and the code surrounding the call.

As all (micro-)performance questions, the first step has to be to get a running version which is easily maintainable. Then benchmarking, profiling and tuning can be applied to the measured bottlenecks instead of guessing.

How to get an Android WakeLock to work?

You just have to write this:

 private PowerManager.WakeLock wl;

    protected void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNjfdhotDimScreen");
    }//End of onCreate

            @Override
        protected void onPause() {
            super.onPause();
            wl.release();
        }//End of onPause

        @Override
        protected void onResume() {
            super.onResume();
            wl.acquire();
        }//End of onResume

and then add permission in the manifest file

 <uses-permission android:name="android.permission.WAKE_LOCK" />

Now your activity will always be awake. You can do other things like w1.release() as per your requirement.

Display filename before matching line

No trick necessary.

grep --with-filename 'pattern' file

With line numbers:

grep -n --with-filename 'pattern' file

String delimiter in string.split method

The problem is because you are adding quotes to your delimiter. It should be removed, and it will work fine.

public void setDelimiter(String delimiter) {
    char[] c = delimiter.toCharArray();
    this.delimiter = "\\" + c[0] + "\\" + c[1];
    System.out.println("Delimiter string is: " + this.delimiter);
}

Getting the minimum of two values in SQL

The solutions using CASE, IIF, and UDF are adequate, but impractical when extending the problem to the general case using more than 2 comparison values. The generalized solution in SQL Server 2008+ utilizes a strange application of the VALUES clause:

SELECT
PaidForPast=(SELECT MIN(x) FROM (VALUES (PaidThisMonth),(OwedPast)) AS value(x))

Credit due to this website: http://sqlblog.com/blogs/jamie_thomson/archive/2012/01/20/use-values-clause-to-get-the-maximum-value-from-some-columns-sql-server-t-sql.aspx

Java java.sql.SQLException: Invalid column index on preparing statement

Everywhere inside the query string, the wildcard should be ? instead of '?'. That should solve the problem.

EDIT :

To add to that, you need to change date '?' to to_date(?, 'yyyy-mm-dd'). Please try that and let me know.

Accessing post variables using Java Servlets

Here's a simple example. I didn't get fancy with the html or the servlet, but you should get the idea.

I hope this helps you out.

<html>
<body>
<form method="post" action="/myServlet">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" />
</form>
</body>
</html>

Now for the Servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {
  public void doPost(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {

    String userName = request.getParameter("username");
    String password = request.getParameter("password");
    ....
    ....
  }
}

SQL query with avg and group by

As I understand, you want the average value for each id at each pass. The solution is

SELECT id, pass, avg(value) FROM data_r1
GROUP BY id, pass;

how to copy only the columns in a DataTable to another DataTable?

DataTable.Clone() should do the trick.

DataTable newTable = originalTable.Clone();

How to search text using php if ($text contains "World")

In your case you can just use strpos(), or stripos() for case insensitive search:

if (stripos($text, "world") !== false) {
    echo "True";
}

How to use an output parameter in Java?

Wrap the value passed in different classes that might be helpful doing the trick, check below for more real example:

  class Ref<T>{

    T s;

    public void set(T value){
        s =  value;
    }

    public T get(){
        return s;
    }

    public Ref(T value) {
        s = value;
    }
}


class Out<T>{

    T s;

    public void set(T value){
        s =  value;
    }
    public T get(){
        return s;
    }

    public Out() {
    }
}

public static void doAndChangeRefs (Ref<String> str, Ref<Integer> i, Out<String> str2){
    //refs passed .. set value
    str.set("def");
    i.set(10);

    //out param passed as null .. instantiate and set 
    str2 = new Out<String>();
    str2.set("hello world");
}
public static void main(String args[]) {
        Ref<Integer>  iRef = new Ref<Integer>(11);
        Out<String> strOut = null; 
        doAndChangeRefs(new Ref<String>("test"), iRef, strOut);
        System.out.println(iRef.get());
        System.out.println(strOut.get());

    }

Create a asmx web service in C# using visual studio 2013

on the web site box, you have selected .NETFramework 4.5 and it doesn show, so click there and choose the 3.5...i hope it helps.

rewrite a folder name using .htaccess

mod_rewrite can only rewrite/redirect requested URIs. So you would need to request /apple/… to get it rewritten to a corresponding /folder1/….

Try this:

RewriteEngine on
RewriteRule ^apple/(.*) folder1/$1

This rule will rewrite every request that starts with the URI path /apple/… internally to /folder1/….


Edit    As you are actually looking for the other way round:

RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /apple/$1 [L,R=301]

This rule is designed to work together with the other rule above. Requests of /folder1/… will be redirected externally to /apple/… and requests of /apple/… will then be rewritten internally back to /folder1/….

Convert List into Comma-Separated String

You can refer below example for getting a comma separated string array from list.

Example:

List<string> testList= new List<string>();
testList.Add("Apple"); // Add string 1
testList.Add("Banana"); // 2
testList.Add("Mango"); // 3
testList.Add("Blue Berry"); // 4
testList.Add("Water Melon"); // 5

string JoinDataString = string.Join(",", testList.ToArray());

How to get substring of NSString?

Here's a slightly less complicated answer:

NSString *myString = @"abcdefg";
NSString *mySmallerString = [myString substringToIndex:4];

See also substringWithRange and substringFromIndex

Set default format of datetimepicker as dd-MM-yyyy

Ensure that control Format property is properly set to use a custom format:

DateTimePicker1.Format = DateTimePickerFormat.Custom

Then this is how you can set your desired format:

DateTimePicker1.CustomFormat = "dd-MM-yyyy"

Unzipping files in Python

If you are using Python 3.2 or later:

import zipfile
with zipfile.ZipFile("file.zip","r") as zip_ref:
    zip_ref.extractall("targetdir")

You dont need to use the close or try/catch with this as it uses the context manager construction.

How to convert char* to wchar_t*?

Your problem has nothing to do with encodings, it's a simple matter of understanding basic C++. You are returning a pointer to a local variable from your function, which will have gone out of scope by the time anyone can use it, thus creating undefined behaviour (i.e. a programming error).

Follow this Golden Rule: "If you are using naked char pointers, you're Doing It Wrong. (Except for when you aren't.)"

I've previously posted some code to do the conversion and communicating the input and output in C++ std::string and std::wstring objects.

How can I exclude one word with grep?

If your grep supports Perl regular expression with -P option you can do (if bash; if tcsh you'll need to escape the !):

grep -P '(?!.*unwanted_word)keyword' file

Demo:

$ cat file
foo1
foo2
foo3
foo4
bar
baz

Let us now list all foo except foo3

$ grep -P '(?!.*foo3)foo' file
foo1
foo2
foo4
$ 

window.location.href and window.open () methods in JavaScript

  • window.open will open a new browser with the specified URL.

  • window.location.href will open the URL in the window in which the code is called.

Note also that window.open() is a function on the window object itself whereas window.location is an object that exposes a variety of other methods and properties.

Using ffmpeg to change framerate

With re-encoding:

ffmpeg -y -i seeing_noaudio.mp4 -vf "setpts=1.25*PTS" -r 24 seeing.mp4

Without re-encoding:

First step - extract video to raw bitstream

ffmpeg -y -i seeing_noaudio.mp4 -c copy -f h264 seeing_noaudio.h264

Remux with new framerate

ffmpeg -y -r 24 -i seeing_noaudio.h264 -c copy seeing.mp4

Show special characters in Unix while using 'less' Command

less will look in its environment to see if there is a variable named LESS

You can set LESS in one of your ~/.profile (.bash_rc, etc, etc) and then anytime you run less from the comand line, it will find the LESS.

Try adding this

export LESS="-CQaix4"

This is the setup I use, there are some behaviors embedded in that may confuse you, so you can find out about what all of these mean from the help function in less, just tap the 'h' key and nose around, or run less --help.

Edit:

I looked at the help, and noticed there is also an -r option

-r  -R  ....  --raw-control-chars  --RAW-CONTROL-CHARS
                Output "raw" control characters.

I agree that cat may be the most exact match to your stated needs.

cat -vet file | less

Will add '$' at end of each line and convert tab char to visual '^I'.

cat --help
   (edited)
    -e                       equivalent to -vE
    -E, --show-ends          display $ at end of each line
    -t                       equivalent to -vT
    -T, --show-tabs          display TAB characters as ^I
    -v, --show-nonprinting   use ^ and M- notation, except for LFD and TAB

I hope this helps.

jQuery callback for multiple ajax calls

I got some good hints from the answers on this page. I adapted it a bit for my use and thought I could share.

// lets say we have 2 ajax functions that needs to be "synchronized". 
// In other words, we want to know when both are completed.
function foo1(callback) {
    $.ajax({
        url: '/echo/html/',
        success: function(data) {
            alert('foo1');
            callback();               
        }
    });
}

function foo2(callback) {
    $.ajax({
        url: '/echo/html/',
        success: function(data) {
            alert('foo2');
            callback();
        }
    });
}

// here is my simplified solution
ajaxSynchronizer = function() {
    var funcs = [];
    var funcsCompleted = 0;
    var callback;

    this.add = function(f) {
        funcs.push(f);
    }

    this.synchronizer = function() {
        funcsCompleted++;
        if (funcsCompleted == funcs.length) {
            callback.call(this);
        }
    }

    this.callWhenFinished = function(cb) {
        callback = cb;
        for (var i = 0; i < funcs.length; i++) {
            funcs[i].call(this, this.synchronizer);
        }
    }
}

// this is the function that is called when both ajax calls are completed.
afterFunction = function() {
    alert('All done!');
}

// this is how you set it up
var synchronizer = new ajaxSynchronizer();
synchronizer.add(foo1);
synchronizer.add(foo2);
synchronizer.callWhenFinished(afterFunction);

There are some limitations here, but for my case it was ok. I also found that for more advanced stuff it there is also a AOP plugin (for jQuery) that might be useful: http://code.google.com/p/jquery-aop/

Prevent scroll-bar from adding-up to the Width of page on Chrome

.modal-dialog {
   position: absolute;
   left: calc(50vw - 300px);
}

where 300 px is a half of my dialog window width.

This is actually the only thing that worked for me.

How to split a string by spaces in a Windows batch file?

The following code will split a string with N number of substrings with # separated values. You can use any delimiter

@echo off
if "%1" == "" goto error1

set _myvar="%1"

:FORLOOP
For /F "tokens=1* delims=#" %%A IN (%_myvar%) DO (
    echo %%A
    set _myvar="%%B"
    if NOT "%_myvar%"=="" goto FORLOOP
)

goto endofprogram
:error1
echo You must provide Argument with # separated

goto endofprogram
:endofprogram

Freeing up a TCP/IP port?

To check all ports:

netstat -lnp

To close an open port:

fuser -k port_no/tcp

Example:

fuser -k 8080/tcp

In both cases you can use the sudo command if needed.

Match at every second occurrence

Suppose the pattern you want is abc+d. You want to match the second occurrence of this pattern in a string.

You would construct the following regex:

abc+d.*?(abc+d)

This would match strings of the form: <your-pattern>...<your-pattern>. Since we're using the reluctant qualifier *? we're safe that there cannot be another match of between the two. Using matcher groups which pretty much all regex implementations provide you would then retrieve the string in the bracketed group which is what you want.

Placeholder Mixin SCSS/CSS

You're looking for the @content directive:

@mixin placeholder {
  ::-webkit-input-placeholder {@content}
  :-moz-placeholder           {@content}
  ::-moz-placeholder          {@content}
  :-ms-input-placeholder      {@content}  
}

@include placeholder {
    font-style:italic;
    color: white;
    font-weight:100;
}

SASS Reference has more information, which can be found here: http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#mixin-content


As of Sass 3.4, this mixin can be written like so to work both nested and unnested:

@mixin optional-at-root($sel) {
  @at-root #{if(not &, $sel, selector-append(&, $sel))} {
    @content;
  }
}

@mixin placeholder {
  @include optional-at-root('::-webkit-input-placeholder') {
    @content;
  }

  @include optional-at-root(':-moz-placeholder') {
    @content;
  }

  @include optional-at-root('::-moz-placeholder') {
    @content;
  }

  @include optional-at-root(':-ms-input-placeholder') {
    @content;
  }
}

Usage:

.foo {
  @include placeholder {
    color: green;
  }
}

@include placeholder {
  color: red;
}

Output:

.foo::-webkit-input-placeholder {
  color: green;
}
.foo:-moz-placeholder {
  color: green;
}
.foo::-moz-placeholder {
  color: green;
}
.foo:-ms-input-placeholder {
  color: green;
}

::-webkit-input-placeholder {
  color: red;
}
:-moz-placeholder {
  color: red;
}
::-moz-placeholder {
  color: red;
}
:-ms-input-placeholder {
  color: red;
}

Converting a number with comma as decimal point to float

Using str_replace() to remove the dots is not overkill.

$string_number = '1.512.523,55';
// NOTE: You don't really have to use floatval() here, it's just to prove that it's a legitimate float value.
$number = floatval(str_replace(',', '.', str_replace('.', '', $string_number)));

// At this point, $number is a "natural" float.
print $number;

This is almost certainly the least CPU-intensive way you can do this, and odds are that even if you use some fancy function to do it, that this is what it does under the hood.

Looking for a 'cmake clean' command to clear up CMake output

It's funny to see this question gets so many attentions and complicated solutions, which indeed shows a pain to not have a clean method with cmake.

Well, you can definitely cd build to do you work, then do a rm -rf * when you need to clean. However, rm -rf * is a dangerous command given that many people are often not aware which dir they are in.

If you cd .., rm -rf build and then mkdir build and then cd build, that's just too much typing.

So a good solution is to just stay out of the build folder and tell cmake the path:
to configure: cmake -B build
to build: cmake --build build
to clean: rm -rf build
to recreate build folder: you don't even need mkdir build, just configure it with cmake -B build and cmake will create it

How to build a 2 Column (Fixed - Fluid) Layout with Twitter Bootstrap?

Update 2018

Bootstrap 4

Now that BS4 is flexbox, the fixed-fluid is simple. Just set the width of the fixed column, and use the .col class on the fluid column.

.sidebar {
    width: 180px;
    min-height: 100vh;
}

<div class="row">
    <div class="sidebar p-2">Fixed width</div>
    <div class="col bg-dark text-white pt-2">
        Content
    </div>
</div>

http://www.codeply.com/go/7LzXiPxo6a

Bootstrap 3..

One approach to a fixed-fluid layout is using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens...

@media (min-width:768px) {
  #sidebar {
      min-width: 300px;
      max-width: 300px;
  }
  #main {
      width:calc(100% - 300px);
  }
}

Working Bootstrap 3 Fixed-Fluid Demo

Related Q&A:
Fixed width column with a container-fluid in bootstrap
How to left column fixed and right scrollable in Bootstrap 4, responsive?

How to get a specific output iterating a hash in Ruby?

Calling sort on a hash converts it into nested arrays and then sorts them by key, so all you need is this:

puts h.sort.map {|k,v| ["#{k}----"] + v}

And if you don't actually need the "----" part, it can be just:

puts h.sort

Combining "LIKE" and "IN" for SQL Server

I know this is old but I got a kind of working solution

SELECT Tbla.* FROM Tbla
INNER JOIN Tblb ON
Tblb.col1 Like '%'+Tbla.Col2+'%'

You can expand it further with your where clause etc. I only answered this because this is what I was looking for and I had to figure out a way of doing it.

Difference between DTO, VO, POJO, JavaBeans?

DTO vs VO

DTO - Data transfer objects are just data containers which are used to transport data between layers and tiers.

  • It mainly contains attributes. You can even use public attributes without getters and setters.
  • Data transfer objects do not contain any business logic.

Analogy:
Simple Registration form with attributes username, password and email id.

  • When this form is submitted in RegistrationServlet file you will get all the attributes from view layer to business layer where you pass the attributes to java beans and then to the DAO or the persistence layer.
  • DTO's helps in transporting the attributes from view layer to business layer and finally to the persistence layer.

DTO was mainly used to get data transported across the network efficiently, it may be even from JVM to another JVM.

DTOs are often java.io.Serializable - in order to transfer data across JVM.

VO - A Value Object [1][2] represents itself a fixed set of data and is similar to a Java enum. A Value Object's identity is based on their state rather than on their object identity and is immutable. A real world example would be Color.RED, Color.BLUE, SEX.FEMALE etc.

POJO vs JavaBeans

[1] The Java-Beanness of a POJO is that its private attributes are all accessed via public getters and setters that conform to the JavaBeans conventions. e.g.

    private String foo;
    public String getFoo(){...}
    public void setFoo(String foo){...}; 

[2] JavaBeans must implement Serializable and have a no-argument constructor, whereas in POJO does not have these restrictions.

FFMPEG mp4 from http live streaming m3u8 file?

Aergistal's answer works, but I found that converting to mp4 can make some m3u8 videos broken. If you are stuck with this problem, try to convert them to mkv, and convert them to mp4 later.

Looping through JSON with node.js

I would recommend taking advantage of the fact that nodeJS will always be ES5. Remember this isn't the browser folks you can depend on the language's implementation on being stable. That said I would recommend against ever using a for-in loop in nodeJS, unless you really want to do deep recursion up the prototype chain. For simple, traditional looping I would recommend making good use of Object.keys method, in ES5. If you view the following JSPerf test, especially if you use Chrome (since it has the same engine as nodeJS), you will get a rough idea of how much more performant using this method is than using a for-in loop (roughly 10 times faster). Here's a sample of the code:

 var keys = Object.keys( obj );
 for( var i = 0,length = keys.length; i < length; i++ ) {
     obj[ keys[ i ] ];
 }

html select option separator

another way is to use a css 1x1 background image on option which only seems to work with firefox and have a "----" fallback

<option value="" disabled="disabled" class="SelectSeparator">----</option> 

.SelectSeparator
    {
      background-image:  url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==);
      color:black;
      background-repeat:repeat-x;
      background-position:50% 50%;
      background-attachment:scroll;
}

http://jsfiddle.net/yNecQ/6/

or to use javascript (jquery) to:

-hide the select element and 
-show a div which can be completely styled and 
-reflect the div state onto the select for the form submit

http://tutorialzine.com/2010/11/better-select-jquery-css3/


see also How do I add a horizontal line in a html select control?

How do I remove repeated elements from ArrayList?

If you're willing to use a third-party library, you can use the method distinct() in Eclipse Collections (formerly GS Collections).

ListIterable<Integer> integers = FastList.newListWith(1, 3, 1, 2, 2, 1);
Assert.assertEquals(
    FastList.newListWith(1, 3, 2),
    integers.distinct());

The advantage of using distinct() instead of converting to a Set and then back to a List is that distinct() preserves the order of the original List, retaining the first occurrence of each element. It's implemented by using both a Set and a List.

MutableSet<T> seenSoFar = UnifiedSet.newSet();
int size = list.size();
for (int i = 0; i < size; i++)
{
    T item = list.get(i);
    if (seenSoFar.add(item))
    {
        targetCollection.add(item);
    }
}
return targetCollection;

If you cannot convert your original List into an Eclipse Collections type, you can use ListAdapter to get the same API.

MutableList<Integer> distinct = ListAdapter.adapt(integers).distinct();

Note: I am a committer for Eclipse Collections.

Python Traceback (most recent call last)

In Python2, input is evaluated, input() is equivalent to eval(raw_input()). When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.

Use raw_input to get a string from the user in Python2.

Demo 1: klj is not defined:

>>> input()
klj
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'klj' is not defined

Demo 2: klj is defined:

>>> klj = 'hi'
>>> input()
klj
'hi'

Demo 3: getting a string with raw_input:

>>> raw_input()
klj
'klj'

Random numbers with Math.random() in Java

The first one generates numbers in the wrong range, while the second one is correct.

To show that the first one is incorrect, let's say min is 10 and max is 20. In other words, the result is expected to be greater than or equal to ten, and strictly less than twenty. If Math.random() returns 0.75, the result of the first formula is 25, which is outside the range.

How to increase request timeout in IIS?

Add this to your Web Config

<system.web>
    <httpRuntime executionTimeout="180" />
</system.web>

https://msdn.microsoft.com/en-us/library/e1f13641(v=vs.85).aspx

Optional TimeSpan attribute.

Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.

This time-out applies only if the debug attribute in the compilation element is False. To help to prevent shutting down the application while you are debugging, do not set this time-out to a large value.

The default is "00:01:50" (110 seconds).

Is it possible to make desktop GUI application in .NET Core?

It is now possible to use Qt, QtQuick, and QML with .NET Core, using Qml.Net.

It is highly performant (not "P/Invoke chatty"), fully featured and works across Linux, OS X, and Windows.

Check out my blog post to see how it compares to the other options out there currently.

PS: I'm the author.

Finding the second highest number in array

public class SecondandThirdHighestElement {
    public static void main(String[] args) {
        int[] arr = {1,1,2,3,8,1,2,3,3,3,2,3,101,6,6,7,8,8,1001,99,1,0};
        // create three temp variable and store arr of first element in that temp variable so that it will compare with other element
        int firsttemp = arr[0];
        int secondtemp = arr[0];
        int thirdtemp = arr[0];
        //check and find first highest value from array by comparing with other elements if found than save in the first temp variable 
        for (int i = 0; i < arr.length; i++) {
            if(firsttemp <arr[i]){
                firsttemp =  arr[i];
            }//if

        }//for
        //check and find the second highest variable by comparing with other elements in an array and find the element and that element should be smaller than first element array
        for (int i = 0; i < arr.length; i++) {
            if(secondtemp < arr[i] && firsttemp>arr[i]){
                secondtemp = arr[i];
            }//if
        }//for
        //check and find the third highest variable by comparing with other elements in an array and find the element and that element should be smaller than second element array

        for (int i = 0; i < arr.length; i++) {
            if(thirdtemp < arr[i] && secondtemp>arr[i]){
                thirdtemp = arr[i];
            }//if
        }//for

        System.out.println("First Highest Value:"+firsttemp);
        System.out.println("Second Highest Value:"+secondtemp);
        System.out.println("Third Highest  Value:"+thirdtemp);

    }//main
}//class

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

I don't know that you are going to find a platform-neutral solution.

This is commonly called an "UPSERT".

See some related discussions:

How to update values in a specific row in a Python Pandas DataFrame?

In SQL, I would have do it in one shot as

update table1 set col1 = new_value where col1 = old_value

but in Python Pandas, we could just do this:

data = [['ram', 10], ['sam', 15], ['tam', 15]] 
kids = pd.DataFrame(data, columns = ['Name', 'Age']) 
kids

which will generate the following output :

    Name    Age
0   ram     10
1   sam     15
2   tam     15

now we can run:

kids.loc[kids.Age == 15,'Age'] = 17
kids

which will show the following output

Name    Age
0   ram     10
1   sam     17
2   tam     17

which should be equivalent to the following SQL

update kids set age = 17 where age = 15

Access denied for user 'test'@'localhost' (using password: YES) except root user

Try:

CREATE USER 'golden'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON * . * TO 'golden'@'localhost';
FLUSH PRIVILEGES;

Or even better use: mysql_setpermission to create the user

How do I programmatically determine operating system in Java?

You can use:

System.getProperty("os.name")

P.S. You may find this code useful:

class ShowProperties {
    public static void main(String[] args) {
        System.getProperties().list(System.out);
    }
}

All it does is print out all the properties provided by your Java implementations. It'll give you an idea of what you can find out about your Java environment via properties. :-)

AngularJS. How to call controller function from outside of controller component

It may be worth considering if having your menu without any associated scope is the right way to go. Its not really the angular way.

But, if it is the way you need to go, then you can do it by adding the functions to $rootScope and then within those functions using $broadcast to send events. your controller then uses $on to listen for those events.

Another thing to consider if you do end up having your menu without a scope is that if you have multiple routes, then all of your controllers will have to have their own upate and get functions. (this is assuming you have multiple controllers)

Phone: numeric keyboard for text input

You can do <input type="text" pattern="\d*">. This will cause the numeric keyboard to appear.

See here for more detail: Text, Web, and Editing Programming Guide for iOS

_x000D_
_x000D_
<form>_x000D_
  <input type="text" pattern="\d*">_x000D_
  <button type="submit">Submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

What does the regex \S mean in JavaScript?

/\S/.test(string) returns true if and only if there's a non-space character in string. Tab and newline count as spaces.

How do I pass a class as a parameter in Java?

Construct your method to accept it-

public <T> void printClassNameAndCreateList(Class<T> className){
    //example access 1
    System.out.print(className.getName());

    //example access 2
    ArrayList<T> list = new ArrayList<T>();
    //note that if you create a list this way, you will have to cast input
    list.add((T)nameOfObject);
}

Call the method-

printClassNameAndCreateList(SomeClass.class);

You can also restrict the type of class, for example, this is one of the methods from a library I made-

protected Class postExceptionActivityIn;

protected <T extends PostExceptionActivity>  void  setPostExceptionActivityIn(Class <T> postExceptionActivityIn) {
    this.postExceptionActivityIn = postExceptionActivityIn;
}

For more information, search Reflection and Generics.

How do you clear your Visual Studio cache on Windows Vista?

The accepted answer gave two locations:

here

C:\Documents and Settings\Administrator\Local Settings\Temp\VWDWebCache

and possibly here

C:\Documents and Settings\Administrator\Local Settings\Application Data\Microsoft\WebsiteCache

Did you try those?

Edited to add

On my Windows Vista machine, it's located in

%Temp%\VWDWebCache

and in

%LocalAppData%\Microsoft\WebsiteCache

From your additional information (regarding team edition) this comes from Clear Client TFS Cache:

Clear Client TFS Cache

Visual Studio and Team Explorer provide a caching mechanism which can get out of sync. If I have multiple instances of a single TFS which can be connected to from a single Visual Studio client, that client can become confused.

To solve it..

For Windows Vista delete contents of this folder

%LocalAppData%\Microsoft\Team Foundation\1.0\Cache

IIS: Idle Timeout vs Recycle

Idle Timeout is if no action has been asked from your web app, it the process will drop and release everything from memory

Recycle is a forced action on the application where your processed is closed and started again, for memory leaking purposes and system health

The negative impact of both is usually the use of your Session and Application state is lost if you mess with Recycle to a faster time.(logged in users etc will be logged out, if they where about to "check out" all would have been lost" that's why recycle is at such a large time out value, idle timeout doesn't matter because nobody is logged in anyway and figure 20 minutes an no action they are not still "shopping"

The positive would be get rid of the idle time out as your website will respond faster on its "first" response if its not a highly active site where a user would have to wait for it to load if you have 1 user every 20 minutes lets say. So a website that get his less then 1 time in 20 minutes actually you would want to increase this value as the website has to load up again from scratch for each user. but if you set this to 0 over a long time, any memory leaks in code could over a certain amount of time, entirely take over the server.

How to extract a string between two delimiters

Try as

String s = "ABC[ This is to extract ]";
        Pattern p = Pattern.compile(".*\\[ *(.*) *\\].*");
        Matcher m = p.matcher(s);
        m.find();
        String text = m.group(1);
        System.out.println(text);

Java - Best way to print 2D array?

class MultidimensionalArray {
    public static void main(String[] args) {

        // create a 2d array
        int[][] a = {
                {1, -2, 3},
                {-4, -5, 6, 9},
                {7},
        };

        // first for...each loop access the individual array
        // inside the 2d array
        for (int[] innerArray: a) {
            // second for...each loop access each element inside the row
            for(int data: innerArray) {
                System.out.println(data);
            }
        }
    }
}

You can do it like this for 2D array

How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?

This should also do the job but this is across SQL and not postgres specific.

select avg(cast(mynumber as numeric)) from my table

How to get the current working directory in Java?

Code :

public class JavaApplication {
  public static void main(String[] args) {
    System.out.println("Working Directory = " + System.getProperty("user.dir"));
  }
}

This will print the absolute path of the current directory from where your application was initialized.


Explanation:

From the documentation:

java.io package resolve relative pathnames using current user directory. The current directory is represented as system property, that is, user.dir and is the directory from where the JVM was invoked.

How do I undo 'git add' before commit?

git rm --cached . -r

will "un-add" everything you've added from your current directory recursively

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

Using underscores in Java variables and method names

It's nice to have something to distinguish private vs. public variables, but I don't like '_' in general coding. If I can help it in new code, I avoid their use.

How do I sort a table in Excel if it has cell references in it?

I used "save as" to copy the sheet to a new file as msdos text format. Doing this removes the formulas, replacing the cell contents with just the computed values. Then open the new file as tab delimited and sort after defining the columns. I needed to sort computed values by an associated text string (destination) for mileage log so that I could sum up the mileage for each destination.

date beginning ending distance destination

where in row 2 and successive rows beginning was the previous row ending and distance was ending minus beginning.

Printing out all the objects in array list

Whenever you print any instance of your class, the default toString implementation of Object class is called, which returns the representation that you are getting. It contains two parts: - Type and Hashcode

So, in student.Student@82701e that you get as output ->

  • student.Student is the Type, and
  • 82701e is the HashCode

So, you need to override a toString method in your Student class to get required String representation: -

@Override
public String toString() {
    return "Student No: " + this.getStudentNo() + 
           ", Student Name: " + this.getStudentName();
}

So, when from your main class, you print your ArrayList, it will invoke the toString method for each instance, that you overrided rather than the one in Object class: -

List<Student> students = new ArrayList();

// You can directly print your ArrayList
System.out.println(students); 

// Or, iterate through it to print each instance
for(Student student: students) {
    System.out.println(student);  // Will invoke overrided `toString()` method
}

In both the above cases, the toString method overrided in Student class will be invoked and appropriate representation of each instance will be printed.

What are the differences between Abstract Factory and Factory design patterns?

Abstract factory creates a base class with abstract methods defining methods for the objects that should be created. Each factory class which derives the base class can create their own implementation of each object type.

enter image description here

Factory method is just a simple method used to create objects in a class. It's usually added in the aggregate root (The Order class has a method called CreateOrderLine)

enter image description here

Abstract factory

In the example below we design an interface so that we can decouple queue creation from a messaging system and can therefore create implementations for different queue systems without having to change the code base.

interface IMessageQueueFactory
{
  IMessageQueue CreateOutboundQueue(string name);
  IMessageQueue CreateReplyQueue(string name);
}

public class AzureServiceBusQueueFactory : IMessageQueueFactory
{
      IMessageQueue CreateOutboundQueue(string name)
      {
           //init queue
           return new AzureMessageQueue(/*....*/);
      }

      IMessageQueue CreateReplyQueue(string name)
      {
           //init response queue
           return new AzureResponseMessageQueue(/*....*/);
      }

}

public class MsmqFactory : IMessageQueueFactory
{
      IMessageQueue CreateOutboundQueue(string name)
      {
           //init queue
           return new MsmqMessageQueue(/*....*/);
      }

      IMessageQueue CreateReplyQueue(string name)
      {
           //init response queue
           return new MsmqResponseMessageQueue(/*....*/);
      }
}

Factory method

The problem in HTTP servers is that we always need an response for every request.

public interface IHttpRequest
{
    // .. all other methods ..

    IHttpResponse CreateResponse(int httpStatusCode);
}

Without the factory method, the HTTP server users (i.e. programmers) would be forced to use implementation specific classes which defeat the purpose of the IHttpRequest interface.

Therefore we introduce the factory method so that the creation of the response class also is abstracted away.

Summary

The difference is that the intended purpose of the class containing a factory method is not to create objects, while an abstract factory should only be used to create objects.

One should take care when using factory methods since it's easy to break the LSP (Liskov Substitution principle) when creating objects.

Converting RGB to grayscale/intensity

The specific numbers in the question are from CCIR 601 (see the Wikipedia link below).

If you convert RGB -> grayscale with slightly different numbers / different methods, you won't see much difference at all on a normal computer screen under normal lighting conditions -- try it.

Here are some more links on color in general:

Wikipedia Luma

Bruce Lindbloom 's outstanding web site

chapter 4 on Color in the book by Colin Ware, "Information Visualization", isbn 1-55860-819-2; this long link to Ware in books.google.com may or may not work

cambridgeincolor : excellent, well-written "tutorials on how to acquire, interpret and process digital photographs using a visually-oriented approach that emphasizes concept over procedure"

Should you run into "linear" vs "nonlinear" RGB, here's part of an old note to myself on this. Repeat, in practice you won't see much difference.


RGB -> ^gamma -> Y -> L*

In color science, the common RGB values, as in html rgb( 10%, 20%, 30% ), are called "nonlinear" or Gamma corrected. "Linear" values are defined as

Rlin = R^gamma,  Glin = G^gamma,  Blin = B^gamma

where gamma is 2.2 for many PCs. The usual R G B are sometimes written as R' G' B' (R' = Rlin ^ (1/gamma)) (purists tongue-click) but here I'll drop the '.

Brightness on a CRT display is proportional to RGBlin = RGB ^ gamma, so 50% gray on a CRT is quite dark: .5 ^ 2.2 = 22% of maximum brightness. (LCD displays are more complex; furthermore, some graphics cards compensate for gamma.)

To get the measure of lightness called L* from RGB, first divide R G B by 255, and compute

Y = .2126 * R^gamma + .7152 * G^gamma + .0722 * B^gamma

This is Y in XYZ color space; it is a measure of color "luminance". (The real formulas are not exactly x^gamma, but close; stick with x^gamma for a first pass.)

Finally,

L* = 116 * Y ^ 1/3 - 16

"... aspires to perceptual uniformity [and] closely matches human perception of lightness." -- Wikipedia Lab color space

How to tell if JRE or JDK is installed

according to JAVA documentation, the JDK should be installed in this path:

/Library/Java/JavaVirtualMachines/jdkmajor.minor.macro[_update].jdk

See the uninstall JDK part at https://docs.oracle.com/javase/8/docs/technotes/guides/install/mac_jdk.html

So if you can find such folder then the JDK is installed

How to get input text value from inside td

I'm having a hard time figuring out what exactly you're looking for here, so hope I'm not way off base.

I'm assuming what you mean is that when a keyup event occurs on the input with class "start" you want to get the values of all the inputs in neighbouring <td>s:

    $('.start').keyup(function() {
        var otherInputs = $(this).parents('td').siblings().find('input');

        for(var i = 0; i < otherInputs.length; i++) {
            alert($(otherInputs[i]).val());
        }
        return false;
    });

Generate JSON string from NSDictionary in iOS

You can also do this on-the-fly by entering the following into the debugger

po [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:yourDictionary options:1 error:nil] encoding:4];

Shell script to set environment variables

I cannot solve it with source ./myscript.sh. It says the source not found error.
Failed also when using . ./myscript.sh. It gives can't open myscript.sh.

So my option is put it in a text file to be called in the next script.

#!/bin/sh
echo "Perform Operation in su mode"
echo "ARCH=arm" >> environment.txt
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export "CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?" >> environment.txt
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...

Tnen call it whenever is needed:

while read -r line; do
    line=$(sed -e 's/[[:space:]]*$//' <<<${line})
    var=`echo $line | cut -d '=' -f1`; test=$(echo $var)
    if [ -z "$(test)" ];then eval export "$line";fi
done <environment.txt

Align text in a table header

Try using style for th

th {text-align:center}

Find object by id in an array of JavaScript objects

A generic and more flexible version of the findById function above:

// array = [{key:value},{key:value}]
function objectFindByKey(array, key, value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i][key] === value) {
            return array[i];
        }
    }
    return null;
}

var array = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
var result_obj = objectFindByKey(array, 'id', '45');

PHP class not found but it's included

  1. Check File Permissions
  2. Check File size.

Sometimes an inaccessible or corrupted file would be the problem, as was in my case

GitHub relative link in Markdown file

Just follow the format below.

[TEXT TO SHOW](actual URL to navigate)

angularjs: allows only numbers to be typed into a text box

This answer serves as a simplification and optimisation over Leopoldo's answer.

Trigger a function from your input on every keydown like this:

<input type="text" ng-keydown="onlyNumbers($event);"/>

You can describe the function in this manner in your controller

$scope.onlyNumbers = function(event){    
    // 'up': 38,'right':39,'down':40,'left':37,
    // 'escape':27,'backspace':8,'tab':9,'enter':13,'del':46,
    // '0':48,'1':49,'2':50,'3':51,'4':52,'5':53,'6':54,'7':55,'8':56,'9':57
    var keys = { 38:true,39:true,40:true,37:true,27:true,8:true,9:true,13:true,
                 46:true,48:true,49:true, 50:true,51:true,52:true,53:true,
                 54:true,55:true,56:true,57:true };

    // if the pressed key is not listed, do not perform any action
    if(!keys[event.keyCode]) { event.preventDefault(); }
}

In case you're using Angular 2+, you can call this same function in this manner:

<input type="text" (keydown)="onlyNumbers($event);"/>

Your Angular 2+ function should look something like this:

onlyNumbers(event) { // the logic here }

Generate a range of dates using SQL

A week from 6 months back

SELECT (date'2015-08-03' + (LEVEL-1)) AS DATES
 FROM DUAL 
 where ROWNUM < 8
 connect by level <= (sysdate-date'2015-08-03'); 

if you omit ROWNUM you get 50 rows only, independent of the value.

How to add a local repo and treat it as a remote repo

You have your arguments to the remote add command reversed:

git remote add <NAME> <PATH>

So:

git remote add bak /home/sas/dev/apps/smx/repo/bak/ontologybackend/.git

See git remote --help for more information.

Disabling Chrome cache for website development

  1. F12 to open Chrome DevTools
  2. F1 to open DevTools Settings
  3. Check Disable cache (while DevTools is open) as shown below:

This is currently on the Preferences tab which is the default. You may need to scroll down. This checkbox has been moved at least a couple times since this question was asked. Last I checked, it was in the middle column at the bottom. If you have it open on a thinner screen and there are 2 columns under Preferences, it may be near the top right. Feel free to update this post if it changes or comment and I'll update the post.

enter image description here

jQuery check if Cookie exists, if not create it

I was having alot of trouble with this because I was using:

if($.cookie('token') === null || $.cookie('token') === "")
{
      //no cookie
}
else
{
     //have cookie
}

The above was ALWAYS returning false, no matter what I did in terms of setting the cookie or not. From my tests it seems that the object is therefore undefined before it's set so adding the following to my code fixed it.

if($.cookie('token') === null || $.cookie('token') === "" 
    || $.(cookie('token') === "null" || $.cookie('token') === undefined)
{
      //no cookie
}
else
{
     //have cookie
}

How to check if an element of a list is a list (in Python)?

Probably, more intuitive way would be like this

if type(e) is list:
    print('Found a list element inside the list') 

Asp.net 4.0 has not been registered

To resolve 'ASP.NET 4.0 has not been registered. You need to manually configure your Web server for ASP.NET 4.0 in order for your site to run correctly' error when opening a solution we can:

1 Ensure the IIS feature is turned on with ASP.NET. Go to Control Panel\All Control Panel Items\Programs and Features then click 'Turn Windows Featrues on. Then in the IIS --> WWW servers --> App Dev Features ensure that ASP.NET is checked.

enter image description here

2 And run the following cmd line to install

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis -i

enter image description here

Hope this helps

How to play CSS3 transitions in a loop?

CSS transitions only animate from one set of styles to another; what you're looking for is CSS animations.

You need to define the animation keyframes and apply it to the element:

@keyframes changewidth {
  from {
    width: 100px;
  }

  to {
    width: 300px;
  }
}

div {
  animation-duration: 0.1s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

Check out the link above to figure out how to customize it to your liking, and you'll have to add browser prefixes.

static and extern global variables in C and C++

Global variables are not extern nor static by default on C and C++. When you declare a variable as static, you are restricting it to the current source file. If you declare it as extern, you are saying that the variable exists, but are defined somewhere else, and if you don't have it defined elsewhere (without the extern keyword) you will get a link error (symbol not found).

Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal. If you declare it as static, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal.

What you can do in C++, that you can't in C, is to declare the variable as const on the header, like this:

const int varGlobal = 7;

And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define for constants.

If you need a global variable visible on multiple sources and not const, declare it as extern on the header, and then define it, this time without the extern keyword, on a source file:

Header included by multiple files:

extern int varGlobal;

In one of your source files:

int varGlobal = 7;

How to manually include external aar package using new Gradle Android Build System

before(default)

implementation fileTree(include: ['*.jar'], dir: 'libs')

just add '*.aar' in include array.

implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')

it works well on Android Studio 3.x.

if you want ignore some library? do like this.

implementation fileTree(include: ['*.jar', '*.aar'], exclude: 'test_aar*', dir: 'libs')
debugImplementation files('libs/test_aar-debug.aar')
releaseImplementation files('libs/test_aar-release.aar')

Disable ONLY_FULL_GROUP_BY

with MySQL version 5.7.28 check by using
SELECT @@sql_mode; and update with

SET @@sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'

Setting timezone in Python

It's not an answer, but...

To get datetime components individually, better use datetime.timetuple:

time = datetime.now()
time.timetuple()
#-> time.struct_time(
#    tm_year=2014, tm_mon=9, tm_mday=7, 
#    tm_hour=2, tm_min=38, tm_sec=5, 
#    tm_wday=6, tm_yday=250, tm_isdst=-1
#)

It's now easy to get the parts:

ts = time.timetuple()
ts.tm_year
ts.tm_mon
ts.tm_mday
ts.tm_hour
ts.tm_min
ts.tm_sec

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

On new El Capitan installation where SIP(rootless prevents access to usr/lib/) is on by default and you cannot create the symlink unless you are in recovery mode. As @yannisxu said you can disable SIP and do your symlink to /usr/lib/local and this will work.

you can use the following command on MAC OSX El Capitan instead of turning off SIP:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib

There used to be an option where you can login as root and this can disable SIP but in the final release that is now obsolete, you can read more about it here: https://forums.developer.apple.com/thread/4686

Question:

There is a nvram boot-args command available in Developer Beta 1 which can disable SIP when run with root privileges:

nvram boot-args="rootless=0"

Will this option of disabling SIP also be available in the El Capitan release version? Or is this strictly for the Developer Builds?

Answer:

This nvram boot-args command will be going away. It will not be available in the El Capitan release version and may disappear before the end of the Developer Betas. Keep an eye on the release notes for future Developer Betas.

Disable autocomplete via CSS

As it stands, there is no 'autocomplete off' attribute in CSS. However, html has an easy code for this:

<input type="text" id="foo" value="bar" autocomplete="off" />

If you're looking for a site-wide effector, an easy one would be to simply have a js function to run through all 'input' s and add this tag, or look for the corresponding css class / id.

The autocomplete attribute works fine in Chrome and Firefox (!), but see also Is there a W3C valid way to disable autocomplete in a HTML form?

Getting a union of two arrays in JavaScript

You can try these:

function union(a, b) {
    return a.concat(b).reduce(function(prev, cur) {
        if (prev.indexOf(cur) === -1) prev.push(cur);
        return prev;
    }, []);    
}

or

function union(a, b) {
    return a.concat(b.filter(function(el) {
        return a.indexOf(el) === -1;
    }));
}

SQL Inner join 2 tables with multiple column conditions and update

UPDATE
    T1
SET
    T1.Inci = T2.Inci 
FROM
    T1
INNER JOIN
    T2
ON
    T1.Brands = T2.Brands
AND
    T1.Category= T2.Category
AND
    T1.Date = T2.Date

Extension exists but uuid_generate_v4 fails

The extension is available but not installed in this database.

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

Upgrading Node.js to latest version

sudo npm install n -g sudo n 0.12.2

or

sudo npm install -g n sudo n latest

or

sudo npm cache clean -f sudo npm install -g n sudo n latest

These work well. But for UX term terminal node -v did not show latest version so I have closed and reopened new terminal. I found v10.1.0, output of node-v after installation by sudo n latest

How to simulate a real mouse click using java?

With all respect the most likely thing is that you are mistaken about why the click is being 'rejected'. Why do you think some program is trying to determine if it's human or not? The Robot class (have used it a lot) should send messages that the operating system has no way to distinguish from a user doing the click.

Add zero-padding to a string

You can use PadLeft

var newString = Your_String.PadLeft(4, '0');

How to update ruby on linux (ubuntu)?

First, which version of ubuntu are you using, it might be easiest to just upgrade to one that has it.

Next, enable backports (system menue, adminstration, software sources), and search for in in synaptic.

Last, look for a ppa for it.

Android ADB commands to get the device properties

adb shell getprop ro.build.version.sdk

If you want to see the whole list of parameters just type:

adb shell getprop

Docker: Container keeps on restarting again on again

From personal experience it sounds like there is a problem within your docker container that is not allowing it to restart. So some process within the container is causing the restart to hang or some process is causing the container to crash on start.

When you start the container make sure you start it detached "-d" if you are going to attach to it. (ex. "docker run -d mediawiki_web_1")

How to use mongoose findOne

In my case same error is there , I am using Asyanc / Await functions , for this needs to add AWAIT for findOne

Ex:const foundUser = User.findOne ({ "email" : req.body.email });

above , foundUser always contains Object value in both cases either user found or not because it's returning values before finishing findOne .

const foundUser = await User.findOne ({ "email" : req.body.email });

above , foundUser returns null if user is not there in collection with provided condition . If user found returns user document.

Casting string to enum

.NET 4.0+ has a generic Enum.TryParse

ContentEnum content;
Enum.TryParse(fileContentMessage, out content);

How to set radio button checked as default in radiogroup?

In the XML file set the android:checkedButton field in your RadioGroup, with the id of your default RadioButton:

<RadioGroup
    ....
    android:checkedButton="@+id/button_1">

    <RadioButton
        android:id="@+id/button_1"
        ...../>

    <RadioButton
        android:id="@+id/button_2"
        ...../>

    <RadioButton
        android:id="@+id/button_3"
        ...../>
</RadioGroup>

How do I check two or more conditions in one <c:if>?

If you are using JSP 2.0 and above It will come with the EL support: so that you can write in plain english and use and with empty operators to write your test:

<c:if test="${(empty object_1.attribute_A) and (empty object_2.attribute_B)}">

Strtotime() doesn't work with dd/mm/YYYY format

The simplest solution is this:

$date    = '07/28/2010';
$newdate = date('Y-m-d', strtotime($date));

Make a float only show two decimal places

I made a swift extension based on above answers

extension Float {
    func round(decimalPlace:Int)->Float{
        let format = NSString(format: "%%.%if", decimalPlace)
        let string = NSString(format: format, self)
        return Float(atof(string.UTF8String))
    }
}

usage:

let floatOne:Float = 3.1415926
let floatTwo:Float = 3.1425934
print(floatOne.round(2) == floatTwo.round(2))
// should be true

WPF Datagrid set selected row

// In General to Access all rows //

foreach (var item in dataGrid1.Items)
{
    string str = ((DataRowView)dataGrid1.Items[1]).Row["ColumnName"].ToString();
}

//To Access Selected Rows //

private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    try
    {
        string str = ((DataRowView)dataGrid1.SelectedItem).Row["ColumnName"].ToString();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Java ElasticSearch None of the configured nodes are available

Elasticsearch settings are in $ES_HOME/config/elasticsearch.yml. There, if the cluster.name setting is commented out, it means ES would take just about any cluster name. So, in your code, the cluster.name as "elastictest" might be the problem. Try this:

Client client = new TransportClient()
                .addTransportAddress(new InetSocketTransportAddress(
                        "143.79.236.xxx",
                        9300));

How to compare two dates to find time difference in SQL Server 2005, date manipulation

If you trying to get worked hours with some accuracy, try this (tested in SQL Server 2016)

SELECT DATEDIFF(MINUTE,job_start, job_end)/60.00;

Various DATEDIFF functionalities are:

SELECT DATEDIFF(year,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(quarter,     '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(month,       '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(dayofyear,   '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(day,         '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(week,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(hour,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(minute,      '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(second,      '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(millisecond, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');

Ref: https://docs.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql?view=sql-server-2017

Find position of a node using xpath

Unlike stated previously 'preceding-sibling' is really the axis to use, not 'preceding' which does something completely different, it selects everything in the document that is before the start tag of the current node. (see http://www.w3schools.com/xpath/xpath_axes.asp)

Using PHP to upload file and add the path to MySQL database

mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;

These are deprecated use the following..

 // Connects to your Database
            $link = mysqli_connect("localhost", "root", "", "");

and to insert data use the following

 $sql = "INSERT INTO  Table-Name (Column-Name)
VALUES ('$filename')" ;

install beautiful soup using pip

pip is a command line tool, not Python syntax.

In other words, run the command in your console, not in the Python interpreter:

pip install beautifulsoup4

You may have to use the full path:

C:\Python27\Scripts\pip install beautifulsoup4

or even

C:\Python27\Scripts\pip.exe install beautifulsoup4

Windows will then execute the pip program and that will use Python to install the package.

Another option is to use the Python -m command-line switch to run the pip module, which then operates exactly like the pip command:

python -m pip install beautifulsoup4

or

python.exe -m pip install beautifulsoup4

Split String into an array of String

You need a regular expression like "\\s+", which means: split whenever at least one whitespace is encountered. The full Java code is:

try {
    String[] splitArray = input.split("\\s+");
} catch (PatternSyntaxException ex) {
    // 
}

Get a JSON object from a HTTP response

Do this to get the JSON

String json = EntityUtils.toString(response.getEntity());

More details here : get json from HttpResponse

How to save local data in a Swift app?

Swift 5+

None of the answers really cover in detail the default built in local storage capabilities. It can do far more than just strings.

You have the following options straight from the apple documentation for 'getting' data from the defaults.

func object(forKey: String) -> Any?
//Returns the object associated with the specified key.

func url(forKey: String) -> URL?
//Returns the URL associated with the specified key.

func array(forKey: String) -> [Any]?
//Returns the array associated with the specified key.

func dictionary(forKey: String) -> [String : Any]?
//Returns the dictionary object associated with the specified key.

func string(forKey: String) -> String?
//Returns the string associated with the specified key.

func stringArray(forKey: String) -> [String]?
//Returns the array of strings associated with the specified key.

func data(forKey: String) -> Data?
//Returns the data object associated with the specified key.

func bool(forKey: String) -> Bool
//Returns the Boolean value associated with the specified key.

func integer(forKey: String) -> Int
//Returns the integer value associated with the specified key.

func float(forKey: String) -> Float
//Returns the float value associated with the specified key.

func double(forKey: String) -> Double
//Returns the double value associated with the specified key.

func dictionaryRepresentation() -> [String : Any]
//Returns a dictionary that contains a union of all key-value pairs in the domains in the search list.

Here are the options for 'setting'

func set(Any?, forKey: String)
//Sets the value of the specified default key.

func set(Float, forKey: String)
//Sets the value of the specified default key to the specified float value.

func set(Double, forKey: String)
//Sets the value of the specified default key to the double value.

func set(Int, forKey: String)
//Sets the value of the specified default key to the specified integer value.

func set(Bool, forKey: String)
//Sets the value of the specified default key to the specified Boolean value.

func set(URL?, forKey: String)
//Sets the value of the specified default key to the specified URL.

If are storing things like preferences and not a large data set these are perfectly fine options.

Double Example:

Setting:

let defaults = UserDefaults.standard
var someDouble:Double = 0.5
defaults.set(someDouble, forKey: "someDouble")

Getting:

let defaults = UserDefaults.standard
var someDouble:Double = 0.0
someDouble = defaults.double(forKey: "someDouble")

What is interesting about one of the getters is dictionaryRepresentation, this handy getter will take all your data types regardless what they are and put them into a nice dictionary that you can access by it's string name and give the correct corresponding data type when you ask for it back since it's of type 'any'.

You can store your own classes and objects also using the func set(Any?, forKey: String) and func object(forKey: String) -> Any? setter and getter accordingly.

Hope this clarifies more the power of the UserDefaults class for storing local data.

On the note of how much you should store and how often, Hardy_Germany gave a good answer on that on this post, here is a quote from it

As many already mentioned: I'm not aware of any SIZE limitation (except physical memory) to store data in a .plist (e.g. UserDefaults). So it's not a question of HOW MUCH.

The real question should be HOW OFTEN you write new / changed values... And this is related to the battery drain this writes will cause.

IOS has no chance to avoid a physical write to "disk" if a single value changed, just to keep data integrity. Regarding UserDefaults this cause the whole file rewritten to disk.

This powers up the "disk" and keep it powered up for a longer time and prevent IOS to go to low power state.

Something else to note as mentioned by user Mohammad Reza Farahani from this post is the asynchronous and synchronous nature of userDefaults.

When you set a default value, it’s changed synchronously within your process, and asynchronously to persistent storage and other processes.

For example if you save and quickly close the program you may notice it does not save the results, this is because it's persisting asynchronously. You might not notice this all the time so if you plan on saving before quitting the program you may want to account for this by giving it some time to finish.

Maybe someone has some nice solutions for this they can share in the comments?

How to unnest a nested list

itertools provides the chain function for that:

From http://docs.python.org/library/itertools.html#recipes:

def flatten(listOfLists):
    "Flatten one level of nesting"
    return chain.from_iterable(listOfLists)

Note that the result is an iterable, so you may need list(flatten(...)).

jQuery AJAX Call to PHP Script with JSON Return

Use parseJSON jquery method to covert string into object

var objData = jQuery.parseJSON(data);

Now you can write code

$('#result').html(objData .status +':' + objData .message);

How to properly add 1 month from now to current date in moment.js

According to the latest doc you can do the following-

Add a day

moment().add(1, 'days').calendar();

Add Year

moment().add(1, 'years').calendar();

Add Month

moment().add(1, 'months').calendar();

Error Importing SSL certificate : Not an X.509 Certificate

Does your cacerts.pem file hold a single certificate? Since it is a PEM, have a look at it (with a text editor), it should start with

-----BEGIN CERTIFICATE-----

and end with

-----END CERTIFICATE-----

Finally, to check it is not corrupted, get hold of openssl and print its details using

openssl x509 -in cacerts.pem -text

Java: How to convert List to Map

Just in case this question isn't closed as a duplicate, the right answer is to use Google Collections:

Map<String,Role> mappedRoles = Maps.uniqueIndex(yourList, new Function<Role,String>() {
  public String apply(Role from) {
    return from.getName(); // or something else
  }});

java.io.IOException: Server returned HTTP response code: 500

I had this problem i.e. works fine when pasted into browser but 505s when done through java. It was simply the spaces that needed to be escaped/encoded.

Node.js: for each … in not working

https://github.com/cscott/jsshaper implements a translator from JavaScript 1.8 to ECMAScript 5.1, which would allow you to use 'for each' in code running on webkit or node.

Does a foreign key automatically create an index?

Say you have a big table called orders, and a small table called customers. There is a foreign key from an order to a customer. Now if you delete a customer, Sql Server must check that there are no orphan orders; if there are, it raises an error.

To check if there are any orders, Sql Server has to search the big orders table. Now if there is an index, the search will be fast; if there is not, the search will be slow.

So in this case, the slow delete could be explained by the absence of an index. Especially if Sql Server would have to search 15 big tables without an index.

P.S. If the foreign key has ON DELETE CASCADE, Sql Server still has to search the order table, but then to remove any orders that reference the deleted customer.

How to remove \xa0 from string in Python?

Generic version with the regular expression (It will remove all the control characters):

import re
def remove_control_chart(s):
    return re.sub(r'\\x..', '', s)

Setting values of input fields with Angular 6

As an alternate you can use reactive forms. Here is an example: https://stackblitz.com/edit/angular-pqb2xx

Template

<form [formGroup]="mainForm" ng-submit="submitForm()">
  Global Price: <input type="number" formControlName="globalPrice">
  <button type="button" [disabled]="mainForm.get('globalPrice').value === null" (click)="applyPriceToAll()">Apply to all</button>
  <table border formArrayName="orderLines">
  <ng-container *ngFor="let orderLine of orderLines let i=index" [formGroupName]="i">
    <tr>
       <td>{{orderLine.time | date}}</td>
       <td>{{orderLine.quantity}}</td>
       <td><input formControlName="price" type="number"></td>
    </tr>
</ng-container>
  </table>
</form>

Component

import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
  mainForm: FormGroup;
  orderLines = [
    {price: 10, time: new Date(), quantity: 2},
    {price: 20, time: new Date(), quantity: 3},
    {price: 30, time: new Date(), quantity: 3},
    {price: 40, time: new Date(), quantity: 5}
    ]
  constructor() {
    this.mainForm = this.getForm();
  }

  getForm(): FormGroup {
    return new FormGroup({
      globalPrice: new FormControl(),
      orderLines: new FormArray(this.orderLines.map(this.getFormGroupForLine))
    })
  }

  getFormGroupForLine(orderLine: any): FormGroup {
    return new FormGroup({
      price: new FormControl(orderLine.price)
    })
  }

  applyPriceToAll() {
    const formLines = this.mainForm.get('orderLines') as FormArray;
    const globalPrice = this.mainForm.get('globalPrice').value;
    formLines.controls.forEach(control => control.get('price').setValue(globalPrice));
    // optionally recheck value and validity without emit event.
  }

  submitForm() {

  }
}

Increasing the Command Timeout for SQL command

Add timeout of your SqlCommand. Please note time is in second.

// Setting command timeout to 1 second
scGetruntotals.CommandTimeout = 1;

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

When you need to create a lot of REST API endpoints on Symfony, the best way is to use following stack of bundles:

  1. JMSSerializerBundle for the serialization of Doctrine entities
  2. FOSRestBundle bundle for response view listener. Also it can generate definition of routes based on controller/action name.
  3. NelmioApiDocBundle to auto-generate online documentation and Sandbox(which allows to test endpoint without any external tool).

When you configure everything properly, you entity code will look like:

use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;

/**
 * @ORM\Table(name="company")
 */
class Company
{

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     *
     * @JMS\Expose()
     * @JMS\SerializedName("name")
     * @JMS\Groups({"company_overview"})
     */
    private $name;

    /**
     * @var Campaign[]
     *
     * @ORM\OneToMany(targetEntity="Campaign", mappedBy="company")
     * 
     * @JMS\Expose()
     * @JMS\SerializedName("campaigns")
     * @JMS\Groups({"campaign_overview"})
     */
    private $campaigns;
}

Then, code in controller:

use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use FOS\RestBundle\Controller\Annotations\View;

class CompanyController extends Controller
{

    /**
     * Retrieve all companies
     *
     * @View(serializerGroups={"company_overview"})
     * @ApiDoc()
     *
     * @return Company[]
     */
    public function cgetAction()
    {
        return $this->getDoctrine()->getRepository(Company::class)->findAll();
    }
}

The benefits of such set up are:

  • @JMS\Expose() annotations in entity can be added to simple fields, and to any types of relations. Also there is possibility to expose result of some method execution (use annotation @JMS\VirtualProperty() for that)
  • With serialization groups we can control exposed fields in different situations.
  • Controllers are very simple. Action method can directly return an entity or array of entities, and they will be automatically serialized.
  • And @ApiDoc() allows to test the endpoint directly from browser, without any REST client or JavaScript code

OSError: [Errno 2] No such file or directory while using python subprocess in Django

Use shell=True if you're passing a string to subprocess.call.

From docs:

If passing a single string, either shell must be True or else the string must simply name the program to be executed without specifying any arguments.

subprocess.call(crop, shell=True)

or:

import shlex
subprocess.call(shlex.split(crop))

Java difference between FileWriter and BufferedWriter

In unbuffered Input/Output(FileWriter, FileReader) read or write request is handled directly by the underlying OS. https://hajsoftutorial.com/java/wp-content/uploads/2018/04/Unbuffered.gif

This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive. To reduce this kind of overhead, the Java platform implements buffered I/O streams. The BufferedReader and BufferedWriter classes provide internal character buffers. Text that’s written to a buffered writer is stored in the internal buffer and only written to the underlying writer when the buffer fills up or is flushed. https://hajsoftutorial.com/java/wp-content/uploads/2018/04/bufferedoutput.gif

More https://hajsoftutorial.com/java-bufferedwriter/

Interface vs Abstract Class (general OO)

These answers are all too long.

  • Interfaces are for defining behaviors.

  • Abstract classes are for defining a thing itself, including its behaviors. That's why we sometimes create an abstract class with some extra properties inheriting an interface.

This also explains why Java only supports single inheritance for classes but puts no restriction on interfaces. Because a concrete object can not be different things, but it can have different behaviors.

python's re: return True if string contains regex pattern

You can do something like this:

Using search will return a SRE_match object, if it matches your search string.

>>> import re
>>> m = re.search(u'ba[r|z|d]', 'bar')
>>> m
<_sre.SRE_Match object at 0x02027288>
>>> m.group()
'bar'
>>> n = re.search(u'ba[r|z|d]', 'bas')
>>> n.group()

If not, it will return None

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    n.group()
AttributeError: 'NoneType' object has no attribute 'group'

And just to print it to demonstrate again:

>>> print n
None

Call Python function from MATLAB

A little known (and little documented) fact about MATLAB's system() function: On unixoid systems it uses whatever interpreter is given in the environment variable SHELL or MATLAB_SHELL at the time of starting MATLAB. So if you start MATLAB with

SHELL='/usr/bin/python' matlab

any subsequent system() calls will use Python instead of your default shell as an interpreter.