Programs & Examples On #Iplimage

iplimage is one of the basic data structures used in OpenCV to store information about the images.

How does Java import work?

javac (or java during runtime) looks for the classes being imported in the classpath. If they are not there in the classpath then classnotfound exceptions are thrown.

classpath is just like the path variable in a shell, which is used by the shell to find a command or executable.

Entire directories or individual jar files can be put in the classpath. Also, yes a classpath can perhaps include a path which is not local but is somewhere on the internet. Please read more about classpath to resolve your doubts.

How to resize an image to a specific size in OpenCV?

For your information, the python equivalent is:

imageBuffer = cv.LoadImage( strSrc )
nW = new X size
nH = new Y size
smallerImage = cv.CreateImage( (nH, nW), imageBuffer.depth, imageBuffer.nChannels )
cv.Resize( imageBuffer, smallerImage , interpolation=cv.CV_INTER_CUBIC )
cv.SaveImage( strDst, smallerImage )

Accessing certain pixel RGB value in openCV

const double pi = boost::math::constants::pi<double>();

cv::Mat distance2ellipse(cv::Mat image, cv::RotatedRect ellipse){
    float distance = 2.0f;
    float angle = ellipse.angle;
    cv::Point ellipse_center = ellipse.center;
    float major_axis = ellipse.size.width/2;
    float minor_axis = ellipse.size.height/2;
    cv::Point pixel;
    float a,b,c,d;

    for(int x = 0; x < image.cols; x++)
    {
        for(int y = 0; y < image.rows; y++) 
        {
        auto u =  cos(angle*pi/180)*(x-ellipse_center.x) + sin(angle*pi/180)*(y-ellipse_center.y);
        auto v = -sin(angle*pi/180)*(x-ellipse_center.x) + cos(angle*pi/180)*(y-ellipse_center.y);

        distance = (u/major_axis)*(u/major_axis) + (v/minor_axis)*(v/minor_axis);  

        if(distance<=1)
        {
            image.at<cv::Vec3b>(y,x)[1] = 255;
        }
      }
  }
  return image;  
}

how to convert an RGB image to numpy array?

load the image by using following syntax:-

from keras.preprocessing import image

X_test=image.load_img('four.png',target_size=(28,28),color_mode="grayscale"); #loading image and then convert it into grayscale and with it's target size 
X_test=image.img_to_array(X_test); #convert image into array

Converting cv::Mat to IplImage*

In case of gray image, I am using this function and it works fine! however you must take care about the function features ;)

CvMat * src=  cvCreateMat(300,300,CV_32FC1);      
IplImage *dist= cvCreateImage(cvGetSize(dist),IPL_DEPTH_32F,3);

cvConvertScale(src, dist, 1, 0);

How to resize an image with OpenCV2.0 and Python2.6

def rescale_by_height(image, target_height, method=cv2.INTER_LANCZOS4):
    """Rescale `image` to `target_height` (preserving aspect ratio)."""
    w = int(round(target_height * image.shape[1] / image.shape[0]))
    return cv2.resize(image, (w, target_height), interpolation=method)

def rescale_by_width(image, target_width, method=cv2.INTER_LANCZOS4):
    """Rescale `image` to `target_width` (preserving aspect ratio)."""
    h = int(round(target_width * image.shape[0] / image.shape[1]))
    return cv2.resize(image, (target_width, h), interpolation=method)

OpenCV - DLL missing, but it's not?

I have had numerous problems with opencv and only succeded after a gruesome 4-6 months. This is the last problem I have had, but all of the above didn't work. What worked for me was just copying and pasting the opencv_core2*.dll (and opencv_highgui2*.dll which it will ask for since you included this as well) into the release (or debug folder - I'm assuming. Haven't tested this) folder of your project, where your application file is.

Hope this helps!

Easiest way to rotate by 90 degrees an image using OpenCV?

Here's my EmguCV (a C# port of OpenCV) solution:

public static Image<TColor, TDepth> Rotate90<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    var rot = new Image<TColor, TDepth>(img.Height, img.Width);
    CvInvoke.cvTranspose(img.Ptr, rot.Ptr);
    rot._Flip(FLIP.HORIZONTAL);
    return rot;
}

public static Image<TColor, TDepth> Rotate180<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    var rot = img.CopyBlank();
    rot = img.Flip(FLIP.VERTICAL);
    rot._Flip(FLIP.HORIZONTAL);
    return rot;
}

public static void _Rotate180<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    img._Flip(FLIP.VERTICAL);
    img._Flip(FLIP.HORIZONTAL);
}

public static Image<TColor, TDepth> Rotate270<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    var rot = new Image<TColor, TDepth>(img.Height, img.Width);
    CvInvoke.cvTranspose(img.Ptr, rot.Ptr);
    rot._Flip(FLIP.VERTICAL);
    return rot;
}

Shouldn't be too hard to translate it back into C++.

Saving an image in OpenCV

I know the problem! You just put a dot after "test.jpg"!

cvSaveImage("test.jpg". ,pSaveImg);

I may be wrong but I think its not good!

Read and write a text file in typescript

import { readFileSync } from 'fs';

const file = readFileSync('./filename.txt', 'utf-8');

This worked for me. You may need to wrap the second command in any function or you may need to declare inside a class without keyword const.

How to convert column with dtype as object to string in Pandas Dataframe

since strings data types have variable length, it is by default stored as object dtype. If you want to store them as string type, you can do something like this.

df['column'] = df['column'].astype('|S80') #where the max length is set at 80 bytes,

or alternatively

df['column'] = df['column'].astype('|S') # which will by default set the length to the max len it encounters

Launch custom android application from android browser

There should also be <category android:name="android.intent.category.BROWSABLE"/> added to the intent filter to make the activity recognized properly from the link.

How to get client IP address using jQuery

A simple AJAX call to your server, and then the serverside logic to get the ip address should do the trick.

$.getJSON('getip.php', function(data){
  alert('Your ip is: ' +  data.ip);
});

Then in php you might do:

<?php
/* getip.php */
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
  $ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
  $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
  $ip=$_SERVER['REMOTE_ADDR'];
}
print json_encode(array('ip' => $ip));

Validate email with a regex in jQuery

function mailValidation(val) {
    var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

    if (!expr.test(val)) {
        $('#errEmail').text('Please enter valid email.');
    }
    else {
        $('#errEmail').hide();
    }
}

"Application tried to present modally an active controller"?

I had same problem.I solve it. You can try This code:

[tabBarController setSelectedIndex:1];
[self dismissModalViewControllerAnimated:YES];

get value from DataTable

You can try changing it to this:

If myTableData.Rows.Count > 0 Then
  For i As Integer = 0 To myTableData.Rows.Count - 1
    ''Dim DataType() As String = myTableData.Rows(i).Item(1)
    ListBox2.Items.Add(myTableData.Rows(i)(1))
  Next
End If

Note: Your loop needs to be one less than the row count since it's a zero-based index.

NPM clean modules

For windows environment:

"scripts": {
    "clean": "rmdir /s /q node_modules",
    ...
}

How to pass multiple checkboxes using jQuery ajax post

Just came across this trying to find a solution for the same problem. Implementing Paul's solution I've made a few tweaks to make this function properly.

var data = { 'venue[]' : []};

$("input:checked").each(function() {
   data['venue[]'].push($(this).val());
});

In short the addition of input:checked as opposed to :checked limits the fields input into the array to just the checkboxes on the form. Paul is indeed correct with this needing to be enclosed as $(this)

Best C# API to create PDF

Update:

I'm not sure when or if the license changed for the iText# library, but it is licensed under AGPL which means it must be licensed if included with a closed-source product. The question does not (currently) require free or open-source libraries. One should always investigate the license type of any library used in a project.


I have used iText# with success in .NET C# 3.5; it is a port of the open source Java library for PDF generation and it's free.

There is a NuGet package available for iTextSharp version 5 and the official developer documentation, as well as C# examples, can be found at itextpdf.com

@UniqueConstraint annotation in Java

The value of the length property must be greater than or equal to name atribute length, else throwing an error.

Works

@Column(name = "typ e", length = 4, unique = true)
private String type;

Not works, type.length: 4 != length property: 3

@Column(name = "type", length = 3, unique = true)
private String type;

Hook up Raspberry Pi via Ethernet to laptop without router?

configure static ip on the raspberry pi:

sudo nano /etc/network/interfaces

and then add:

iface eth0 inet static
     address 169.254.0.2
     netmask 255.255.255.0
     broadcast 169.254.0.255

then you can acces your raspberry via ssh

ssh [email protected]

How can I store the result of a system command in a Perl variable?

Also for eg. you can use IPC::Run:

use IPC::Run qw(run);

my $pid = 5892;
run [qw(top -H -n 1 -p), $pid],
    '|', sub { print grep { /myprocess/ } <STDIN> },
    '|', [qw(wc -l)],
    '>', \my $out;

print $out;
  • processes are running without bash subprocess
  • can be piped to perl subs
  • very similar to shell

Ruby capitalize every word first letter

If you are trying to capitalize the first letter of each word in an array you can simply put this:

array_name.map(&:capitalize)

Twitter bootstrap scrollable table

.span3 {  
    height: 100px !important;
    overflow: scroll;
}?

You'll want to wrap it in it's own div or give that span3 an id of it's own so you don't affect your whole layout.

Here's a fiddle: http://jsfiddle.net/zm6rf/

Changing the git user inside Visual Studio Code

From VSCode Commande Palette select :

GitHub Pull Requests : Sign out of GitHub.

Then Sign in with your new credential.

How do I escape spaces in path for scp copy in Linux?

Also you can do something like:

scp foo@bar:"\"apath/with spaces in it/\""

The first level of quotes will be interpreted by scp and then the second level of quotes will preserve the spaces.

How can I get CMake to find my alternative Boost installation?

The short version

You only need BOOST_ROOT, but you're going to want to disable searching the system for your local Boost if you have multiple installations or cross-compiling for iOS or Android. In which case add Boost_NO_SYSTEM_PATHS is set to false.

set( BOOST_ROOT "" CACHE PATH "Boost library path" )
set( Boost_NO_SYSTEM_PATHS on CACHE BOOL "Do not search system for Boost" )

Normally this is passed on the CMake command-line using the syntax -D<VAR>=value.

The longer version

Officially speaking the FindBoost page states these variables should be used to 'hint' the location of Boost.

This module reads hints about search locations from variables:

BOOST_ROOT             - Preferred installation prefix
 (or BOOSTROOT)
BOOST_INCLUDEDIR       - Preferred include directory e.g. <prefix>/include
BOOST_LIBRARYDIR       - Preferred library directory e.g. <prefix>/lib
Boost_NO_SYSTEM_PATHS  - Set to ON to disable searching in locations not
                         specified by these hint variables. Default is OFF.
Boost_ADDITIONAL_VERSIONS
                       - List of Boost versions not known to this module
                         (Boost install locations may contain the version)

This makes a theoretically correct incantation:

cmake -DBoost_NO_SYSTEM_PATHS=TRUE \
      -DBOOST_ROOT=/path/to/boost-dir

When you compile from source

include( ExternalProject )

set( boost_URL "http://sourceforge.net/projects/boost/files/boost/1.63.0/boost_1_63_0.tar.bz2" )
set( boost_SHA1 "9f1dd4fa364a3e3156a77dc17aa562ef06404ff6" )
set( boost_INSTALL ${CMAKE_CURRENT_BINARY_DIR}/third_party/boost )
set( boost_INCLUDE_DIR ${boost_INSTALL}/include )
set( boost_LIB_DIR ${boost_INSTALL}/lib )

ExternalProject_Add( boost
        PREFIX boost
        URL ${boost_URL}
        URL_HASH SHA1=${boost_SHA1}
        BUILD_IN_SOURCE 1
        CONFIGURE_COMMAND
        ./bootstrap.sh
        --with-libraries=filesystem
        --with-libraries=system
        --with-libraries=date_time
        --prefix=<INSTALL_DIR>
        BUILD_COMMAND
        ./b2 install link=static variant=release threading=multi runtime-link=static
        INSTALL_COMMAND ""
        INSTALL_DIR ${boost_INSTALL} )

set( Boost_LIBRARIES
        ${boost_LIB_DIR}/libboost_filesystem.a
        ${boost_LIB_DIR}/libboost_system.a
        ${boost_LIB_DIR}/libboost_date_time.a )
message( STATUS "Boost static libs: " ${Boost_LIBRARIES} )

Then when you call this script you'll need to include the boost.cmake script (mine is in the a subdirectory), include the headers, indicate the dependency, and link the libraries.

include( boost )
include_directories( ${boost_INCLUDE_DIR} )
add_dependencies( MyProject boost )
target_link_libraries( MyProject
                       ${Boost_LIBRARIES} )

How to fix Terminal not loading ~/.bashrc on OS X Lion

Renaming .bashrc to .profile (or soft-linking the latter to the former) should also do the trick. See here.

PHP Constants Containing Arrays?

Doing some sort of ser/deser or encode/decode trick seems ugly and requires you to remember what exactly you did when you are trying to use the constant. I think the class private static variable with accessor is a decent solution, but I'll do you one better. Just have a public static getter method that returns the definition of the constant array. This requires a minimum of extra code and the array definition cannot be accidentally modified.

class UserRoles {
    public static function getDefaultRoles() {
        return array('guy', 'development team');
    }
}

initMyRoles( UserRoles::getDefaultRoles() );

If you want to really make it look like a defined constant you could give it an all caps name, but then it would be confusing to remember to add the '()' parentheses after the name.

class UserRoles {
    public static function DEFAULT_ROLES() { return array('guy', 'development team'); }
}

//but, then the extra () looks weird...
initMyRoles( UserRoles::DEFAULT_ROLES() );

I suppose you could make the method global to be closer to the define() functionality you were asking for, but you really should scope the constant name anyhow and avoid globals.

How to convert String to long in Java?

There are a few ways to convert String to long:

1)

long l = Long.parseLong("200"); 
String numberAsString = "1234";
long number = Long.valueOf(numberAsString).longValue();
String numberAsString = "1234";
Long longObject = new Long(numberAsString);
long number = longObject.longValue();

We can shorten to:

String numberAsString = "1234";
long number = new Long(numberAsString).longValue();

Or just

long number = new Long("1234").longValue();
  1. Using Decimal format:
String numberAsString = "1234";
DecimalFormat decimalFormat = new DecimalFormat("#");
try {
    long number = decimalFormat.parse(numberAsString).longValue();
    System.out.println("The number is: " + number);
} catch (ParseException e) {
    System.out.println(numberAsString + " is not a valid number.");
}

How to switch Python versions in Terminal?

The simplest way would be to add an alias to python3 to always point to the native python installed. Add this line to the .bash_profile file in your $HOME directory at the last,

alias python="python3"

Doing so makes the changes to be reflected on every interactive shell opened.

Download File Using Javascript/jQuery

Works on Chrome, Firefox and IE8 and above.

var link=document.createElement('a');
document.body.appendChild(link);
link.href=url ;
link.click();

Can I make a <button> not submit a form?

Just use good old HTML:

<input type="button" value="Submit" />

Wrap it as the subject of a link, if you so desire:

<a href="http://somewhere.com"><input type="button" value="Submit" /></a>

Or if you decide you want javascript to provide some other functionality:

<input type="button" value="Cancel" onclick="javascript: someFunctionThatCouldIncludeRedirect();"/>

Can I delete a git commit but keep the changes?

For those using zsh, you'll have to use the following:

git reset --soft HEAD\^

Explained here: https://github.com/robbyrussell/oh-my-zsh/issues/449

In case the URL becomes dead, the important part is:

Escape the ^ in your command

You can alternatively can use HEAD~ so that you don't have to escape it each time.

What is the difference between prefix and postfix operators?

There are two examples illustrates difference

int a , b , c = 0 ; 
a = ++c ; 
b = c++ ;
printf (" %d %d %d " , a , b , c++);
  • Here c has value 0 c increment by 1 then assign value 1 to a so value of a = 1 and value of c = 1
  • next statement assiagn value of c = 1 to b then increment c by 1 so value of b = 1 and value of c = 2

  • in printf statement we have c++ this mean that orginal value of c which is 2 will printed then increment c by 1 so printf statement will print 1 1 2 and value of c now is 3

you can use http://pythontutor.com/c.html

int a , b , c = 0 ; 
a = ++c ; 
b = c++ ;
printf (" %d %d %d " , a , b , ++c);
  • Here in printf statement ++c will increment value of c by 1 first then assign new value 3 to c so printf statement will print 1 1 3

How unique is UUID?

If by "given enough time" you mean 100 years and you're creating them at a rate of a billion a second, then yes, you have a 50% chance of having a collision after 100 years.

Docker CE on RHEL - Requires: container-selinux >= 2.9

Docker CE is not supported on RHEL. Any way you are trying to get around that is not a supported way. You can see the supported platforms in the Docker Documentation. I suggest you either use a supported OS, or switch to Enterprise Edition.

How to get response body using HttpURLConnection, when code other than 2xx is returned?

Wrong method was used for errors, here is the working code:

BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}

npm ERR! Error: EPERM: operation not permitted, rename

Closing PHPStorm fixed the issue for me.

Java Swing - how to show a panel on top of another panel?

Use a 1 by 1 GridLayout on the existing JPanel, then add your Panel to that JPanel. The only problem with a GridLayout that's 1 by 1 is that you won't be able to place other items on the JPanel. In this case, you will have to figure out a layout that is suitable. Each panel that you use can use their own layout so that wouldn't be a problem.

Am I understanding this question correctly?

What is LD_LIBRARY_PATH and how to use it?

LD_LIBRARY_PATH is the default library path which is accessed to check for available dynamic and shared libraries. It is specific to linux distributions.

It is similar to environment variable PATH in windows that linker checks for possible implementations during linking time.

Fastest way to compute entropy in Python

def entropy(base, prob_a, prob_b ):
  import math
  base=2
  x=prob_a
  y=prob_b
  expression =-((x*math.log(x,base)+(y*math.log(y,base))))    
  return [expression]

Echo tab characters in bash script

res="\t\tx"
echo -e "[${res}]"

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

A foreign key with a cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete.

You are saying in a opposite way, this is not that when you delete from child table then records will be deleted from parent table.

UPDATE 1:

ON DELETE CASCADE option is to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behaviour of the database server prevents you from deleting data in a table if other tables reference it.

If you specify this option, later when you delete a row in the parent table, the database server also deletes any rows associated with that row (foreign keys) in a child table. The principal advantage to the cascading-deletes feature is that it allows you to reduce the quantity of SQL statements you need to perform delete actions.

So it's all about what will happen when you delete rows from Parent table not from child table.

So in your case when user removes entries from CATs table then rows will be deleted from books table. :)

Hope this helps you :)

Why am I getting an error "Object literal may only specify known properties"?

As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.

Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash is incorrect and should have been callbackOnLocationHash (note the mis-spelling of "Location").

This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.

Example:

interface TextOptions {
    alignment?: string;
    color?: string;
    padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'

But I meant to do that

There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes

Type-checking only some properties

Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v or v as T) do not check for extra properties, so you can use them in place of a type annotation:

interface Options {
    x?: string;
    y?: number;
}

// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;

These properties and maybe more

Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking

Before

interface Model {
  name: string;
}
function createModel(x: Model) { ... }

// Error
createModel({name: 'hello', length: 100});

After

interface Model {
  name: string;
  [others: string]: any;
}
function createModel(x: Model) { ... }

// OK
createModel({name: 'hello', length: 100});

This is a dog or a cat or a horse, not sure yet

interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }

let x: Animal;
if(...) {
  x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
  x = { move: 'catwalk', meow: 'mrar' };
} else {
  x = { move: 'gallop', neigh: 'wilbur' };
}

Two good solutions come to mind here

Specify a closed set for x

// Removes all errors
let x: Dog|Cat|Horse;

or Type assert each thing

// For each initialization
  x = { move: 'doggy paddle', woof: 'bark' } as Dog;

This type is sometimes open and sometimes not

A clean solution to the "data model" problem using intersection types:

interface DataModelOptions {
  name?: string;
  id?: number;
}
interface UserProperties {
  [key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
 /* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
 /* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });

See also https://github.com/Microsoft/TypeScript/issues/3755

How can I enable Assembly binding logging?

  1. Create a new Application Pool

  2. Go to the Advanced Settings of this application pool

  3. Set the Enable 32-Bit Application to True

  4. Point your web application to use this new Pool

Screenshot (IIS-ApplicationPool)

How to overcome "datetime.datetime not JSON serializable"?

A quick fix if you want your own formatting

for key,val in sample.items():
    if isinstance(val, datetime):
        sample[key] = '{:%Y-%m-%d %H:%M:%S}'.format(val) #you can add different formating here
json.dumps(sample)

Egit rejected non-fast-forward

I have found that you must be on the latest commit of the git. So these are the steps to take: 1) make sure you have not been working on the same files, otherwise you will run into a DITY_WORK_TREE error. 2) pull the latest changes. 3) commit your updates.

Hope this helps.

How to do scanf for single char in C

neither fgets nor getchar works to solve the problem. the only workaround is keeping a space before %c while using scanf scanf(" %c",ch); // will only work

In the follwing fgets also not work..

char line[256];
char ch;
int i;

printf("Enter a num : ");
scanf("%d",&i);
printf("Enter a char : ");

if (fgets(line, sizeof line, stdin) == NULL) {
    printf("Input error.\n");
    exit(1);
}

ch = line[0];
printf("Character read: %c\n", ch);

How do I use variables in Oracle SQL Developer?

Simple answer NO.

However you can achieve something similar by running the following version using bind variables:

SELECT * FROM Employees WHERE EmployeeID = :EmpIDVar 

Once you run the query above in SQL Developer you will be prompted to enter value for the bind variable EmployeeID.

How to perform grep operation on all files in a directory?

In Linux, I normally use this command to recursively grep for a particular text within a dir

grep -rni "string" *

where,

r = recursive i.e, search subdirectories within the current directory
n = to print the line numbers to stdout
i = case insensitive search

HTTP Error 500.19 and error code : 0x80070021

Please <staticContent /> line and erased it from the web.config.

MVC 4 Razor File Upload

View Page

@using (Html.BeginForm("ActionmethodName", "ControllerName", FormMethod.Post, new { id = "formid" }))
 { 
   <input type="file" name="file" />
   <input type="submit" value="Upload" class="save" id="btnid" />
 }

script file

$(document).on("click", "#btnid", function (event) {
        event.preventDefault();
        var fileOptions = {
            success: res,
            dataType: "json"
        }
        $("#formid").ajaxSubmit(fileOptions);
    });

In Controller

    [HttpPost]
    public ActionResult UploadFile(HttpPostedFileBase file)
    {

    }

Increment a Integer's int value?

Integer objects are immutable, so you cannot modify the value once they have been created. You will need to create a new Integer and replace the existing one.

playerID = new Integer(playerID.intValue() + 1);

How to find longest string in the table column data

If column datatype is text you should use DataLength function like:

select top 1 CR, DataLength(CR)
from tbl
order by DataLength(CR) desc

Git error when trying to push -- pre-receive hook declined

The error for me was that the project did not have any branches created, and my role was developer, so I could not create any branch, request that they give me the pertinent permissions and everything in order now!

Live-stream video from one android phone to another over WiFi

You can use IP Webcam, or perhaps use DLNA. For example Samsung devices come with an app called AllShare which can share and access DLNA enabled devices on the network. I think IP Webcam is your best bet, though. You should be able to open the stream it creates using MX Video player or something like that.

require(vendor/autoload.php): failed to open stream

Create composer.json file with requisite library for ex:

{
    "require": {
        "mpdf/mpdf": "^6.1"
    }
}

Execute the below command where composer.json exists:

composer install

In case of Drupal :

Use the web root folder of drupal to include autoload for ex:

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/vendor/autoload.php';

In case of other systems: Use the root folder variable or location to include the autoload.php

MVC: How to Return a String as JSON

The issue, I believe, is that the Json action result is intended to take an object (your model) and create an HTTP response with content as the JSON-formatted data from your model object.

What you are passing to the controller's Json method, though, is a JSON-formatted string object, so it is "serializing" the string object to JSON, which is why the content of the HTTP response is surrounded by double-quotes (I'm assuming that is the problem).

I think you can look into using the Content action result as an alternative to the Json action result, since you essentially already have the raw content for the HTTP response available.

return this.Content(returntext, "application/json");
// not sure off-hand if you should also specify "charset=utf-8" here, 
//  or if that is done automatically

Another alternative would be to deserialize the JSON result from the service into an object and then pass that object to the controller's Json method, but the disadvantage there is that you would be de-serializing and then re-serializing the data, which may be unnecessary for your purposes.

How can I get the full/absolute URL (with domain) in Django?

Use handy request.build_absolute_uri() method on request, pass it the relative url and it'll give you full one.

By default, the absolute URL for request.get_full_path() is returned, but you can pass it a relative URL as the first argument to convert it to an absolute URL.

Trigger an action after selection select2

It works for me:

$('#yourselect').on("change", function(e) { 
   // what you would like to happen
});

How to create major and minor gridlines with different linestyles in Python

Actually, it is as simple as setting major and minor separately:

In [9]: plot([23, 456, 676, 89, 906, 34, 2345])
Out[9]: [<matplotlib.lines.Line2D at 0x6112f90>]

In [10]: yscale('log')

In [11]: grid(b=True, which='major', color='b', linestyle='-')

In [12]: grid(b=True, which='minor', color='r', linestyle='--')

The gotcha with minor grids is that you have to have minor tick marks turned on too. In the above code this is done by yscale('log'), but it can also be done with plt.minorticks_on().

enter image description here

How to connect to mysql with laravel?

It's also much more better to not modify the app/config/database.php file itself... otherwise modify .env file and put your DB info there. (.env file is available in Laravel 5, not sure if it was there in previous versions...)

NOTE: Of course you should have already set mysql as your default database connection in the app/config/database.php file.

What is 0x10 in decimal?

0xNNNN (not necessarily four digits) represents, in C at least, a hexadecimal (base-16 because 'hex' is 6 and 'dec' is 10 in Latin-derived languages) number, where N is one of the digits 0 through 9 or A through F (or their lower case equivalents, either representing 10 through 15), and there may be 1 or more of those digits in the number. The other way of representing it is NNNN16.

It's very useful in the computer world as a single hex digit represents four bits (binary digits). That's because four bits, each with two possible values, gives you a total of 2 x 2 x 2 x 2 or 16 (24) values. In other words:

  _____________________________________bits____________________________________
 /                                                                             \
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
| bF | bE | bD | bC | bB | bA | b9 | b8 | b7 | b6 | b5 | b4 | b3 | b2 | b1 | b0 |
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
 \_________________/ \_________________/ \_________________/ \_________________/ 
      Hex digit           Hex digit           Hex digit           Hex digit

A base-X number is a number where each position represents a multiple of a power of X.


In base 10, which we humans are used to, the digits used are 0 through 9, and the number 730410 is:

  • (7 x 103) = 700010 ; plus
  • (3 x 102) = 30010 ; plus
  • (0 x 101) = 010 ; plus
  • (4 x 100) = 410 ; equals 7304.

In octal, where the digits are 0 through 7. the number 7548 is:

  • (7 x 82) = 44810 ; plus
  • (5 x 81) = 4010 ; plus
  • (4 x 80) = 410 ; equals 49210.

Octal numbers in C are preceded by the character 0 so 0123 is not 123 but is instead (1 * 64) + (2 * 8) + 3, or 83.


In binary, where the digits are 0 and 1. the number 10112 is:

  • (1 x 23) = 810 ; plus
  • (0 x 22) = 010 ; plus
  • (1 x 21) = 210 ; plus
  • (1 x 20) = 110 ; equals 1110.

In hexadecimal, where the digits are 0 through 9 and A through F (which represent the "digits" 10 through 15). the number 7F2416 is:

  • (7 x 163) = 2867210 ; plus
  • (F x 162) = 384010 ; plus
  • (2 x 161) = 3210 ; plus
  • (4 x 160) = 410 ; equals 3254810.

Your relatively simple number 0x10, which is the way C represents 1016, is simply:

  • (1 x 161) = 1610 ; plus
  • (0 x 160) = 010 ; equals 1610.

As an aside, the different bases of numbers are used for many things.

  • base 10 is used, as previously mentioned, by we humans with 10 digits on our hands.
  • base 2 is used by computers due to the relative ease of representing the two binary states with electrical circuits.
  • base 8 is used almost exclusively in UNIX file permissions so that each octal digit represents a 3-tuple of binary permissions (read/write/execute). It's also used in C-based languages and UNIX utilities to inject binary characters into an otherwise printable-character-only data stream.
  • base 16 is a convenient way to represent four bits to a digit, especially as most architectures nowadays have a word size which is a multiple of four bits.
  • base 64 is used in encoding mail so that binary files may be sent using only printable characters. Each digit represents six binary digits so you can pack three eight-bit characters into four six-bit digits (25% increased file size but guaranteed to get through the mail gateways untouched).
  • as a semi-useful snippet, base 60 comes from some very old civilisation (Babylon, Sumeria, Mesopotamia or something like that) and is the source of 60 seconds/minutes in the minute/hour, 360 degrees in a circle, 60 minutes (of arc) in a degree and so on [not really related to the computer industry, but interesting nonetheless].
  • as an even less-useful snippet, the ultimate question and answer in The Hitchhikers Guide To The Galaxy was "What do you get when you multiply 6 by 9?" and "42". Whilst same say this is because the Earth computer was faulty, others see it as proof that the creator has 13 fingers :-)

mongodb: insert if not exists

Sounds like you want to do an "upsert". MongoDB has built-in support for this. Pass an extra parameter to your update() call: {upsert:true}. For example:

key = {'key':'value'}
data = {'key2':'value2', 'key3':'value3'};
coll.update(key, data, upsert=True); #In python upsert must be passed as a keyword argument

This replaces your if-find-else-update block entirely. It will insert if the key doesn't exist and will update if it does.

Before:

{"key":"value", "key2":"Ohai."}

After:

{"key":"value", "key2":"value2", "key3":"value3"}

You can also specify what data you want to write:

data = {"$set":{"key2":"value2"}}

Now your selected document will update the value of "key2" only and leave everything else untouched.

There can be only one auto column

Note also that "key" does not necessarily mean primary key. Something like this will work:

CREATE TABLE book (
    isbn             BIGINT NOT NULL PRIMARY KEY,
    id               INT    NOT NULL AUTO_INCREMENT,
    accepted_terms   BIT(1) NOT NULL,
    accepted_privacy BIT(1) NOT NULL,
    INDEX(id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

This is a contrived example and probably not the best idea, but it can be very useful in certain cases.

Visual Studio move project to a different folder

Summary: rename-and-move in VS2019 with git, retaining git history, leveraging R# a bit, automatic dependent project reference updating (important for sln's with many projects, we have >200)

I have been using the following steps to rename-and-move C# projects in Visual Studio 2019. This process uses R# to adjust namespaces. The git history is retained by doing a "git mv" (avoiding add/delete history drop).

Two phases: 1) rename the project in place and 2) move the project.

(Uses tip from base2 re unloading projects.)

Rename

  1. VS | Solution Explorer | right-click project | Rename (e.g., Utils.Foo to Foo).
  2. VS | Solution Explorer | right-click project | Properties | change assembly name, default namespace and Assembly Information fields
  3. Do 1 and 2 for corresponding test project (e.g., Utils.Foo.Tests)
  4. VS | Solution Explorer | right-click projects (production and test) | Refactor | Adjust Namespaces
  5. XAML files that use the project may need to be updated (manually or with an appropriate global search and replace)
  6. Rebuild All
  7. Commit!! (to commit changes before moves)

Note: The folder in Windows Explorer remains the old name to this point (e.g., Utils.Foo). This is fixed in the move steps.

Move

This method: 1) retains git history, 2) leverages R# to adjust namespaces atomically and 3) updates dependent projects en masse (avoids tedious manual editing of dependent sln and csproj files).

  1. unload all the projects in the solution (so that removal of the target project does not trigger changes in dependent projects)

    VS | select all solution folders under the Solution | right-click Unload Projects

  2. move folders using git (so history is maintained)

a) open Developer Command Prompt for 2019

b) git status (to illustrate “nothing to commit, working tree clean”)

c) git mv the project e.g., git mv "C:\Code\foo\foo\Utils.Foo" "C:\Code\Foo"

d) git status to view/verify change

  1. remove the project

VS | Solution Explorer | select project | right-click | Remove (since all projects are unloaded, this will correctly NOT remove the references to it in dependent projects)

  1. re-add the project (to the new location in the tree in Solution Explorer)

a) VS | Solution Explorer | select target parent folder | right-click | Add | Existing Project

  1. reload all projects

IMPORTANT: Confirm that *.csproj files for dependent projects have been updated.

(VS | Team Explorer | Changes | double-click any dependent csproj listed | inspect-verify ProjectReference path change)

  1. Manually fix paths in the single moved *.csproj file

Use Notepad++ (or other text editor) to fix the paths. Often this can be done with a simple search-and-replace (e.g., ../../../../ to ../../).

This will update...

a) GlobalAssmeblyInfo.cs references

b) paths to packages

c) paths to Dependency Validation diagram files

d) paths to ruleset paths (e.g., <CodeAnalysisRuleSet>..\..\..\..\SolutionDependencyValidation\IgnoreWarnings.ruleset</CodeAnalysisRuleSet>)

  1. Close and re-Open the solution (to get the project references into good shape)

Save All, Close Solution, I prefer to delete bin and obj folders to be clean of history, Re-open Solution

  1. Validate

a) VS | Team Explorer | Changes

i) should see Staged Changes that reveal the files that moved ii) should see dependent projects (*.csproj) that were nicely updated review the csproj diffs and notice that the paths have been beautifully updated!! (this is the magic that avoids laboriously manually updating the csproj files using a text editor)

b) in Windows Explorer, verify old location is empty

c) Clean Solution, Rebuild Solution, Run unit tests, Launch apps in sln.

  1. Commit!!

Visual Studio Code compile on save

If pressing Ctrl+Shift+B seems like a lot of effort, you can switch on "Auto Save" (File > Auto Save) and use NodeJS to watch all the files in your project, and run TSC automatically.

Open a Node.JS command prompt, change directory to your project root folder and type the following;

tsc -w

And hey presto, each time VS Code auto saves the file, TSC will recompile it.

This technique is mentioned in a blog post;

http://www.typescriptguy.com/getting-started/angularjs-typescript/

Scroll down to "Compile on save"

window.onunload is not working properly in Chrome browser. Can any one help me?

There are some actions which are not working in chrome, inside of the unload event. Alert or confirm boxes are such things.

But what is possible (AFAIK):

  1. Open popups (with window.open) - but this will just work, if the popup blocker is disabled for your site
  2. Return a simple string (in beforeunload event), which triggers a confirm box, which asks the user if s/he want to leave the page.

Example for #2:

$(window).on('beforeunload', function() {
    return 'Your own message goes here...';
});

Demo: http://jsfiddle.net/PQz5k/

Open link in new tab or window

You can simply do that by setting target="_blank", w3schools has an example.

jQuery Mobile Page refresh mechanism

I found this thread looking to create an ajax page refresh button with jQuery Mobile.

@sgissinger had the closest answer to what I was looking for, but it was outdated.

I updated for jQuery Mobile 1.4

function refreshPage() {
  jQuery.mobile.pageContainer.pagecontainer('change', window.location.href, {
    allowSamePageTransition: true,
    transition: 'none',
    reloadPage: true 
    // 'reload' parameter not working yet: //github.com/jquery/jquery-mobile/issues/7406
  });
}

// Run it with .on
$(document).on( "click", '#refresh', function() {
  refreshPage();
});

how to get bounding box for div element in jquery

You can get the bounding box of any element by calling getBoundingClientRect

var rect = document.getElementById("myElement").getBoundingClientRect();

That will return an object with left, top, width and height fields.

Force IE9 to emulate IE8. Possible?

On the client side you can add and remove websites to be displayed in Compatibility View from Compatibility View Settings window of IE:

Tools-> Compatibility View Settings

Embed a PowerPoint presentation into HTML

I don't know of a way to embed PowerPoint slides directly into HTML. However, there are a number of solutions online for converting a PPT file into a SWF, which can be embedded into HTML just like any other Flash movie.

Googling for 'ppt to swf' seems to give a lot of hits. Some are free, others aren't. Some handle things like animations, others just do still images. There's got to be one out there that does what you need. :)

Create new project on Android, Error: Studio Unknown host 'services.gradle.org'

Go to setting option which is on upper strip of android studio and follow the below steps to solve the problem.

setting > Appearance&behavior > HTTP and proxy > click on Auto detect Enable option.(The option with radio box)select this one...

Regex to extract URLs from href attribute in HTML with Python

import re

url = '<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://example2.com">Even More Examples</a>'

urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', url)

>>> print urls
['http://example.com', 'http://example2.com']

Owl Carousel, making custom navigation

I did it with css, ie: adding classes for arrows, but you can use images as well.

Bellow is an example with fontAwesome:

JS:

owl.owlCarousel({
    ...
    // should be empty otherwise you'll still see prev and next text,
    // which is defined in js
    navText : ["",""],
    rewindNav : true,
    ...
});

CSS

.owl-carousel .owl-nav .owl-prev,
  .owl-carousel .owl-nav .owl-next,
  .owl-carousel .owl-dot {
    font-family: 'fontAwesome';

}
.owl-carousel .owl-nav .owl-prev:before{
    // fa-chevron-left
    content: "\f053";
    margin-right:10px;
}
.owl-carousel .owl-nav .owl-next:after{
    //fa-chevron-right
    content: "\f054";
    margin-right:10px;
}

Using images:

.owl-carousel .owl-nav .owl-prev,
  .owl-carousel .owl-nav .owl-next,
  .owl-carousel .owl-dot {
    //width, height
    width:30px;
    height:30px;
    ...
}
.owl-carousel .owl-nav .owl-prev{
    background: url('left-icon.png') no-repeat;
}
.owl-carousel .owl-nav .owl-next{
    background: url('right-icon.png') no-repeat;
}

Maybe someone will find this helpful :)

How can I expand and collapse a <div> using javascript?

Take a look at toggle() jQuery function :

http://api.jquery.com/toggle/

Also, innerHTML jQuery Function is .html().

What's the difference between unit tests and integration tests?

A unit test is done in (as far as possible) total isolation.

An integration test is done when the tested object or module is working like it should be, with other bits of code.

Using OR operator in a jquery if statement

Think about what

if ((state != 10) || (state != 15) || (state != 19) || (state != 22) || (state != 33) || (state != 39) || (state != 47) || (state != 48) || (state != 49) || (state != 51))

means. || means "or." The negation of this is (by DeMorgan's Laws):

state == 10 && state == 15 && state == 19...

In other words, the only way that this could be false if if a state equals 10, 15, and 19 (and the rest of the numbers in your or statement) at the same time, which is impossible.

Thus, this statement will always be true. State 15 will never equal state 10, for example, so it's always true that state will either not equal 10 or not equal 15.

Change || to &&.

Also, in most languages, the following:

if (x) {
  return true;
}
else {
  return false;
}

is not necessary. In this case, the method returns true exactly when x is true and false exactly when x is false. You can just do:

return x;

"unrecognized import path" with go get

Because GFW forbidden you to access golang.org ! And when i use the proxy , it can work well.

you can look at the information using command go get -v -u golang.org/x/oauth2

show all tables in DB2 using the LIST command

Run this command line on your preferred shell session:

db2 "select tabname from syscat.tables where owner = 'DB2INST1'"

Maybe you'd like to modify the owner name, and need to check the list of current owners?

db2 "select distinct owner from syscat.tables"

Convert XLS to CSV on command line

:: For UTF-8 works for Microsoft Office 2016 and higher!

Try this code:

if WScript.Arguments.Count < 2 Then
    WScript.Echo "Please specify the source and the destination files. Usage: ExcelToCsv <xls/xlsx source file> <csv destination file>"
    Wscript.Quit
End If

csv_format = 62

Set objFSO = CreateObject("Scripting.FileSystemObject")

src_file = objFSO.GetAbsolutePathName(Wscript.Arguments.Item(0))
dest_file = objFSO.GetAbsolutePathName(WScript.Arguments.Item(1))


Dim oExcel
Set oExcel = CreateObject("Excel.Application")

Dim oBook
Set oBook = oExcel.Workbooks.Open(src_file)

oBook.SaveAs dest_file, csv_format

oBook.Close False
oExcel.Quit

Mockito: Inject real objects into private @Autowired fields

I know this is an old question, but we were faced with the same problem when trying to inject Strings. So we invented a JUnit5/Mockito extension that does exactly what you want: https://github.com/exabrial/mockito-object-injection

EDIT:

@InjectionMap
 private Map<String, Object> injectionMap = new HashMap<>();

 @BeforeEach
 public void beforeEach() throws Exception {
  injectionMap.put("securityEnabled", Boolean.TRUE);
 }

 @AfterEach
 public void afterEach() throws Exception {
  injectionMap.clear();
 }

Centering a Twitter Bootstrap button

.span7.btn { display: block;   margin-left: auto;   margin-right: auto; }

I am not completely familiar with bootstrap, but something like the above should do the trick. It may not be necessary to include all of the classes. This should center the button within its parent, the span7.

Initializing select with AngularJS and ng-repeat

If you are using md-select and ng-repeat ing md-option from angular material then you can add ng-model-options="{trackBy: '$value.id'}" to the md-select tag ash shown in this pen

Code:

_x000D_
_x000D_
<md-select ng-model="user" style="min-width: 200px;" ng-model-options="{trackBy: '$value.id'}">_x000D_
  <md-select-label>{{ user ? user.name : 'Assign to user' }}</md-select-label>_x000D_
  <md-option ng-value="user" ng-repeat="user in users">{{user.name}}</md-option>_x000D_
</md-select>
_x000D_
_x000D_
_x000D_

Making macOS Installer Packages which are Developer ID ready

Our example project has two build targets: HelloWorld.app and Helper.app. We make a component package for each and combine them into a product archive.

A component package contains payload to be installed by the OS X Installer. Although a component package can be installed on its own, it is typically incorporated into a product archive.

Our tools: pkgbuild, productbuild, and pkgutil

After a successful "Build and Archive" open $BUILT_PRODUCTS_DIR in the Terminal.

$ cd ~/Library/Developer/Xcode/DerivedData/.../InstallationBuildProductsLocation
$ pkgbuild --analyze --root ./HelloWorld.app HelloWorldAppComponents.plist
$ pkgbuild --analyze --root ./Helper.app HelperAppComponents.plist

This give us the component-plist, you find the value description in the "Component Property List" section. pkgbuild -root generates the component packages, if you don't need to change any of the default properties you can omit the --component-plist parameter in the following command.

productbuild --synthesize results in a Distribution Definition.

$ pkgbuild --root ./HelloWorld.app \
    --component-plist HelloWorldAppComponents.plist \
    HelloWorld.pkg
$ pkgbuild --root ./Helper.app \
    --component-plist HelperAppComponents.plist \
    Helper.pkg
$ productbuild --synthesize \
    --package HelloWorld.pkg --package Helper.pkg \
    Distribution.xml 

In the Distribution.xml you can change things like title, background, welcome, readme, license, and so on. You turn your component packages and distribution definition with this command into a product archive:

$ productbuild --distribution ./Distribution.xml \
    --package-path . \
    ./Installer.pkg

I recommend to take a look at iTunes Installers Distribution.xml to see what is possible. You can extract "Install iTunes.pkg" with:

$ pkgutil --expand "Install iTunes.pkg" "Install iTunes"

Lets put it together

I usually have a folder named Package in my project which includes things like Distribution.xml, component-plists, resources and scripts.

Add a Run Script Build Phase named "Generate Package", which is set to Run script only when installing:

VERSION=$(defaults read "${BUILT_PRODUCTS_DIR}/${FULL_PRODUCT_NAME}/Contents/Info" CFBundleVersion)

PACKAGE_NAME=`echo "$PRODUCT_NAME" | sed "s/ /_/g"`
TMP1_ARCHIVE="${BUILT_PRODUCTS_DIR}/$PACKAGE_NAME-tmp1.pkg"
TMP2_ARCHIVE="${BUILT_PRODUCTS_DIR}/$PACKAGE_NAME-tmp2"
TMP3_ARCHIVE="${BUILT_PRODUCTS_DIR}/$PACKAGE_NAME-tmp3.pkg"
ARCHIVE_FILENAME="${BUILT_PRODUCTS_DIR}/${PACKAGE_NAME}.pkg"

pkgbuild --root "${INSTALL_ROOT}" \
    --component-plist "./Package/HelloWorldAppComponents.plist" \
    --scripts "./Package/Scripts" \
    --identifier "com.test.pkg.HelloWorld" \
    --version "$VERSION" \
    --install-location "/" \
    "${BUILT_PRODUCTS_DIR}/HelloWorld.pkg"
pkgbuild --root "${BUILT_PRODUCTS_DIR}/Helper.app" \
    --component-plist "./Package/HelperAppComponents.plist" \
    --identifier "com.test.pkg.Helper" \
    --version "$VERSION" \
    --install-location "/" \
    "${BUILT_PRODUCTS_DIR}/Helper.pkg"
productbuild --distribution "./Package/Distribution.xml"  \
    --package-path "${BUILT_PRODUCTS_DIR}" \
    --resources "./Package/Resources" \
    "${TMP1_ARCHIVE}"

pkgutil --expand "${TMP1_ARCHIVE}" "${TMP2_ARCHIVE}"
    
# Patches and Workarounds

pkgutil --flatten "${TMP2_ARCHIVE}" "${TMP3_ARCHIVE}"

productsign --sign "Developer ID Installer: John Doe" \
    "${TMP3_ARCHIVE}" "${ARCHIVE_FILENAME}"

If you don't have to change the package after it's generated with productbuild you could get rid of the pkgutil --expand and pkgutil --flatten steps. Also you could use the --sign paramenter on productbuild instead of running productsign.

Sign an OS X Installer

Packages are signed with the Developer ID Installer certificate which you can download from Developer Certificate Utility.

They signing is done with the --sign "Developer ID Installer: John Doe" parameter of pkgbuild, productbuild or productsign.

Note that if you are going to create a signed product archive using productbuild, there is no reason to sign the component packages.

Developer Certificate Utility

All the way: Copy Package into Xcode Archive

To copy something into the Xcode Archive we can't use the Run Script Build Phase. For this we need to use a Scheme Action.

Edit Scheme and expand Archive. Then click post-actions and add a New Run Script Action:

In Xcode 6:

#!/bin/bash

PACKAGES="${ARCHIVE_PATH}/Packages"
  
PACKAGE_NAME=`echo "$PRODUCT_NAME" | sed "s/ /_/g"`
ARCHIVE_FILENAME="$PACKAGE_NAME.pkg"
PKG="${OBJROOT}/../BuildProductsPath/${CONFIGURATION}/${ARCHIVE_FILENAME}"

if [ -f "${PKG}" ]; then
    mkdir "${PACKAGES}"
    cp -r "${PKG}" "${PACKAGES}"
fi

In Xcode 5, use this value for PKG instead:

PKG="${OBJROOT}/ArchiveIntermediates/${TARGET_NAME}/BuildProductsPath/${CONFIGURATION}/${ARCHIVE_FILENAME}"

In case your version control doesn't store Xcode Scheme information I suggest to add this as shell script to your project so you can simple restore the action by dragging the script from the workspace into the post-action.

Scripting

There are two different kinds of scripting: JavaScript in Distribution Definition Files and Shell Scripts.

The best documentation about Shell Scripts I found in WhiteBox - PackageMaker How-to, but read this with caution because it refers to the old package format.

Apple Silicon

In order for the package to run as arm64, the Distribution file has to specify in its hostArchitectures section that it supports arm64 in addition to x86_64:

<options hostArchitectures="arm64,x86_64" />

Additional Reading

Known Issues and Workarounds

Destination Select Pane

The user is presented with the destination select option with only a single choice - "Install for all users of this computer". The option appears visually selected, but the user needs to click on it in order to proceed with the installation, causing some confusion.

Example showing the installer bug

Apples Documentation recommends to use <domains enable_anywhere ... /> but this triggers the new more buggy Destination Select Pane which Apple doesn't use in any of their Packages.

Using the deprecate <options rootVolumeOnly="true" /> give you the old Destination Select Pane. Example showing old Destination Select Pane


You want to install items into the current user’s home folder.

Short answer: DO NOT TRY IT!

Long answer: REALLY; DO NOT TRY IT! Read Installer Problems and Solutions. You know what I did even after reading this? I was stupid enough to try it. Telling myself I'm sure that they fixed the issues in 10.7 or 10.8.

First of all I saw from time to time the above mentioned Destination Select Pane Bug. That should have stopped me, but I ignored it. If you don't want to spend the week after you released your software answering support e-mails that they have to click once the nice blue selection DO NOT use this.

You are now thinking that your users are smart enough to figure the panel out, aren't you? Well here is another thing about home folder installation, THEY DON'T WORK!

I tested it for two weeks on around 10 different machines with different OS versions and what not, and it never failed. So I shipped it. Within an hour of the release I heart back from users who just couldn't install it. The logs hinted to permission issues you are not gonna be able to fix.

So let's repeat it one more time: We do not use the Installer for home folder installations!


RTFD for Welcome, Read-me, License and Conclusion is not accepted by productbuild.

Installer supported since the beginning RTFD files to make pretty Welcome screens with images, but productbuild doesn't accept them.

Workarounds: Use a dummy rtf file and replace it in the package by after productbuild is done.

Note: You can also have Retina images inside the RTFD file. Use multi-image tiff files for this: tiffutil -cat Welcome.tif Welcome_2x.tif -out FinalWelcome.tif. More details.


Starting an application when the installation is done with a BundlePostInstallScriptPath script:

#!/bin/bash

LOGGED_IN_USER_ID=`id -u "${USER}"`

if [ "${COMMAND_LINE_INSTALL}" = "" ]
then
    /bin/launchctl asuser "${LOGGED_IN_USER_ID}" /usr/bin/open -g PATH_OR_BUNDLE_ID
fi

exit 0

It is important to run the app as logged in user, not as the installer user. This is done with launchctl asuser uid path. Also we only run it when it is not a command line installation, done with installer tool or Apple Remote Desktop.


PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

I'm not sure if I am correct, but from the request header that you post:

Request headers

Accept: Application/json

Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo

User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36

Content-Type: application/x-www-form-urlencoded

Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8

it seems like you didn't config your request body to JSON type.

How do I concatenate multiple C++ strings on one line?

Your code can be written as1,

s = "Hello world," "nice to see you," "or not."

...but I doubt that's what you're looking for. In your case, you are probably looking for streams:

std::stringstream ss;
ss << "Hello world, " << 42 << "nice to see you.";
std::string s = ss.str();

1 "can be written as" : This only works for string literals. The concatenation is done by the compiler.

How to query for Xml values and attributes from table in SQL Server?

use value instead of query (must specify index of node to return in the XQuery as well as passing the sql data type to return as the second parameter):

select
    xt.Id
    , x.m.value( '@id[1]', 'varchar(max)' ) MetricId
from
    XmlTest xt
    cross apply xt.XmlData.nodes( '/Sqm/Metrics/Metric' ) x(m)

python: How do I know what type of exception occurred?

try: someFunction() except Exception, exc:

#this is how you get the type
excType = exc.__class__.__name__

#here we are printing out information about the Exception
print 'exception type', excType
print 'exception msg', str(exc)

#It's easy to reraise an exception with more information added to it
msg = 'there was a problem with someFunction'
raise Exception(msg + 'because of %s: %s' % (excType, exc))

ERROR: Cannot open source file " "

One thing that caught me out and surprised me was, in an inherited project, the files it was referring to were referred to on a relative path outside of the project folder but yet existed in the project folder.

In solution explorer, single click each file with the error, bring up the Properties window (right-click, Properties), and ensure the "Relative Path" is just the file name (e.g. MyMissingFile.cpp) if it is in the project folder. In my case it was set to: ..\..\Some Other Folder\MyMissingFile.cpp.

How to import multiple csv files in a single load?

Using Spark 2.0+, we can load multiple CSV files from different directories using df = spark.read.csv(['directory_1','directory_2','directory_3'.....], header=True). For more information, refer the documentation here

std::string formatting like sprintf

Very-very simple solution.

std::string strBuf;
strBuf.resize(256);
int iCharsPrinted = sprintf_s((char *)strPath.c_str(), strPath.size(), ...);
strBuf.resize(iCharsPrinted);

Convert HTML + CSS to PDF

In terms of cost, using a web-service (API) may in many cases be the more sensible approach. Plus, by outsourcing this process you unburden your own infrastructure/backend and - provided you are using a reputable service - ensure compatibility with adjusting web standards, uptime, short processing times and quick content delivery.

I've done some research on most of the web services currently on the market, please find below the APIs that I feel are worth mentioning on this thread, in an order based on price/value ratio. All of them are offering pre-composed PHP classes and packages.

  1. pdflayer.com - Cost: $ - Quality: ????
  2. docraptor.com - Cost: $$$ - Quality: ?????
  3. pdfcrowd.com - Cost: $$ - Quality: ???

Quality:

Having the high-quality engine PrinceXML as a backbone, DocRaptor clearly offers the best PDF quality, returning highly polished and well converted PDF documents. However, the pdflayer API service gets pretty close here. Pdfcrowd does not necessarily score with quality, but with processing speed.

Cost:

pdflayer.com - As indicated above, the most cost-effective option here is pdflayer.com, offering an entirely free subscription plan for 100 monthly PDFs and premium subscriptions ranging between $9.99-$119.99. The price for 10,000 monthly PDF documents is $39.99.

docraptor.com - Offering a 7-Day Free Trial period. Premium subscription plans range from $15-$2250. The price for 10,000 monthly PDF documents is ~ $300.00.

pdfcrowd.com - Offering 100 PDFs once for free. Premium subscription plans range from $9-$89. The price for 10,000 monthly PDF documents is ~ $49.00.

I've used all three of them and this text is supposed to help anyone decide without having to pay for all of them. This text has not been written to endorse any one product and I have no affiliation with any of the products.

.htaccess deny from all

This syntax has changed with the newer Apache HTTPd server, please see upgrade to apache 2.4 doc for full details.

2.2 configuration syntax was

Order deny,allow
Deny from all

2.4 configuration now is

Require all denied

Thus, this 2.2 syntax

order deny,allow
deny from all
allow from 127.0.0.1

Would ne now written

Require local

substring of an entire column in pandas dataframe

Use the str accessor with square brackets:

df['col'] = df['col'].str[:9]

Or str.slice:

df['col'] = df['col'].str.slice(0, 9)

Apache Cordova - uninstall globally

Try this for Windows:

    npm uninstall -g cordova

Try this for MAC:

    sudo npm uninstall -g cordova

You can also add Cordova like this:

  1. If You Want To install the previous version of Cordova through the Node Package Manager (npm):

    npm install -g [email protected]
    
  2. If You Want To install the latest version of Cordova:

    npm install -g cordova 
    

Enjoy!

How do I get a file's last modified time in Perl?

Calling the built-in function stat($fh) returns an array with the following information about the file handle passed in (from the perlfunc man page for stat):

  0 dev      device number of filesystem
  1 ino      inode number
  2 mode     file mode  (type and permissions)
  3 nlink    number of (hard) links to the file
  4 uid      numeric user ID of file's owner
  5 gid      numeric group ID of file's owner
  6 rdev     the device identifier (special files only)
  7 size     total size of file, in bytes
  8 atime    last access time since the epoch
  9 mtime    last modify time since the epoch
 10 ctime    inode change time (NOT creation time!) since the epoch
 11 blksize  preferred block size for file system I/O
 12 blocks   actual number of blocks allocated

Element number 9 in this array will give you the last modified time since the epoch (00:00 January 1, 1970 GMT). From that you can determine the local time:

my $epoch_timestamp = (stat($fh))[9];
my $timestamp       = localtime($epoch_timestamp);

Alternatively, you can use the built-in module File::stat (included as of Perl 5.004) for a more object-oriented interface.

And to avoid the magic number 9 needed in the previous example, additionally use Time::localtime, another built-in module (also included as of Perl 5.004). Together these lead to some (arguably) more legible code:

use File::stat;
use Time::localtime;
my $timestamp = ctime(stat($fh)->mtime);

fatal error LNK1104: cannot open file 'kernel32.lib'

For command line (i.e. - makefile) users only:

  1. When you install VC++ Express, it is 32-bit only. So, things go into C:\Program Files (x86).
  2. Then, you decide to upgrade to 64-bit capabillities. So, you install the SDK. But it is 64-bit capable. So, things go into C:\Program Files.

You (like me) probably "tuned" your makefile to #1, above, via something like this:

MS_SDK_BASE_DOS := C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A
ENV_SET         := LIB="$(MS_SDK_BASE_DOS)\Lib\x64"

But, now, you need to change that tuning to #2, above, like this:

MS_SDK_BASE_DOS := C:\Program Files\Microsoft SDKs\Windows\v7.1

(Don't miss the "v7.0A" to "v7.1" change, as well.)

How do I get an empty array of any size in python?

also you can extend that with extend method of list.

a= []
a.extend([None]*10)
a.extend([None]*20)

startForeground fail after upgrade to Android 8.1

Here is my solution

private static final int NOTIFICATION_ID = 200;
private static final String CHANNEL_ID = "myChannel";
private static final String CHANNEL_NAME = "myChannelName";

private void startForeground() {

    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            getApplicationContext(), CHANNEL_ID);

    Notification notification;



        notification = mBuilder.setTicker(getString(R.string.app_name)).setWhen(0)
                .setOngoing(true)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("Send SMS gateway is running background")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setShowWhen(true)
                .build();

        NotificationManager notificationManager = (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE);

        //All notifications should go through NotificationChannel on Android 26 & above
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                    CHANNEL_NAME,
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);

        }
        notificationManager.notify(NOTIFICATION_ID, notification);

    }

Hope it will help :)

SQL Server String or binary data would be truncated

I am going to add one other possible cause of this error just because no one has mentioned it and it might help some future person (since the OP has found his answer). If the table you are inserting into has triggers, it could be the trigger is generating the error. I have seen this happen when table field definitions were changed, but audit tables were not.

Can table columns with a Foreign Key be NULL?

I also stuck on this issue. But I solved simply by defining the foreign key as unsigned integer. Find the below example-

CREATE TABLE parent (
   id int(10) UNSIGNED NOT NULL,
    PRIMARY KEY (id)
) ENGINE=INNODB;

CREATE TABLE child (
    id int(10) UNSIGNED NOT NULL,
    parent_id int(10) UNSIGNED DEFAULT NULL,
    FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE
) ENGINE=INNODB;

jquery click event not firing?

I was wasting my time on this for hours. Fortunately, I found the solution. If you are using bootstrap admin templates (AdminLTE), this problem may show up. Thing is we have to use adminLTE framework plugins.

example: ifChecked event:

$('input').on('ifChecked', function(event){
   alert(event.type + ' callback');
});

For more information click here.

Hope it helps you too.

Why am I getting a FileNotFoundError?

As noted above the problem is in specifying the path to your file. The default path in OS X is your home directory (/Users/macbook represented by ~ in terminal ...you can change or rename the home directory with the advanced options in System Preferences > Users & Groups).

Or you can specify the path from the drive to your file in the filename:

path = "/Users/macbook/Documents/MyPython/"
myFile = path + fileName

You can also catch the File Not Found Error and give another response using try:

try:
    with open(filename) as f:
        sequences = pick_lines(f)
except FileNotFoundError:
    print("File not found. Check the path variable and filename")
    exit()

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

I ended up deleting my references (I had added them properly using the projects tab, and they used to build just fine), hand editing my .csproj files and removing bizarre entries that didn't belong -- and setting my outputs for debug and release, x86 and x64 and any cpu to all be "\bin" -- I built it once, then re-added the reference (again, using the projects tab), and everything started working again for me. Didn't have to restart Visual Studio at all.

Entity Framework vs LINQ to SQL

Is LINQ to SQL Truly Dead? by Jonathan Allen for InfoQ.com

Matt Warren describes [LINQ to SQL] as something that "was never even supposed to exist." Essentially, it was just supposed to be stand-in to help them develop LINQ until the real ORM was ready.

...

The scale of Entity Framework caused it to miss the .NET 3.5/Visual Studio 2008 deadline. It was completed in time for the unfortunately named ".NET 3.5 Service Pack 1", which was more like a major release than a service pack.

...

Developers do not like [ADO.NET Entity Framework] because of the complexity.

...

as of .NET 4.0, LINQ to Entities will be the recommended data access solution for LINQ to relational scenarios.

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

UPDATE: Since 2.8 this no longer works because assetic is no longer included by default. Although if you're using assetic this will work.

You can use the variable %assetic.write_to%.

$this->getParameter('assetic.write_to');

Since your assets depend on this variable to be dumped to your web directory, it's safe to assume and use to locate your web folder.

http://symfony.com/doc/current/reference/configuration/assetic.html

Simple function to sort an array of objects

How about this?

var people = [
{
    name: 'a75',
    item1: false,
    item2: false
},
{
    name: 'z32',
    item1: true,
    item2: false
},
{
    name: 'e77',
    item1: false,
    item2: false
}];

function sort_by_key(array, key)
{
 return array.sort(function(a, b)
 {
  var x = a[key]; var y = b[key];
  return ((x < y) ? -1 : ((x > y) ? 1 : 0));
 });
}

people = sort_by_key(people, 'name');

This allows you to specify the key by which you want to sort the array so that you are not limited to a hard-coded name sort. It will work to sort any array of objects that all share the property which is used as they key. I believe that is what you were looking for?

And here is a jsFiddle: http://jsfiddle.net/6Dgbu/

Shell Script Syntax Error: Unexpected End of File

Unrelated to the OP's problem, but my issue was that I'm a noob shell scripter. All the other languages I've used require parentheses to invoke methods, whereas shell doesn't seem to like that.

function do_something() {
  # do stuff here
}

# bad
do_something()

# works
do_something

Java maximum memory on Windows XP

Keep in mind that Windows has virtual memory management and the JVM only needs memory that is contiguous in its address space. So, other programs running on the system shouldn't necessarily impact your heap size. What will get in your way are DLL's that get loaded in to your address space. Unfortunately optimizations in Windows that minimize the relocation of DLL's during linking make it more likely you'll have a fragmented address space. Things that are likely to cut in to your address space aside from the usual stuff include security software, CBT software, spyware and other forms of malware. Likely causes of the variances are different security patches, C runtime versions, etc. Device drivers and other kernel bits have their own address space (the other 2GB of the 4GB 32-bit space).

You could try going through your DLL bindings in your JVM process and look at trying to rebase your DLL's in to a more compact address space. Not fun, but if you are desperate...

Alternatively, you can just switch to 64-bit Windows and a 64-bit JVM. Despite what others have suggested, while it will chew up more RAM, you will have much more contiguous virtual address space, and allocating 2GB contiguously would be trivial.

How to get all Windows service names starting with a common word?

Using PowerShell, you can use the following

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Select name

This will show a list off all services which displayname starts with "NATION-".

You can also directly stop or start the services;

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Stop-Service
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Start-Service

or simply

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Restart-Service

How to make JQuery-AJAX request synchronous

It's as simple as the one below, and works like a charm.

My solution perfectly answers your question: How to make JQuery-AJAX request synchronous

Set ajax to synchronous before the ajax call, and then reset it after your ajax call:

$.ajaxSetup({async: false});

$ajax({ajax call....});

$.ajaxSetup({async: true});

In your case it would look like this:

$.ajaxSetup({async: false});

$.ajax({
        type: "POST",
        async: "false",
        url: "checkpass.php",
        data: "password="+password,
        success: function(html) {
            var arr=$.parseJSON(html);
            if(arr == "Successful") {
                return true;
            } else {
                return false;
            }
        }
    });


$.ajaxSetup({async: true});

I hope it helps :)

Sql Server : How to use an aggregate function like MAX in a WHERE clause

yes you need to use a having clause after the Group by clause , as the where is just to filter the data on simple parameters , but group by followed by a Having statement is the idea to group the data and filter it on basis of some aggregate function......

How would you do a "not in" query with LINQ?

You can use a combination of Where and Any for finding not in:

var NotInRecord =list1.Where(p => !list2.Any(p2 => p2.Email  == p.Email));

How to control the line spacing in UILabel

I thought about adding something new to this answer, so I don't feel as bad... Here is a Swift answer:

import Cocoa

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 40

let attrString = NSMutableAttributedString(string: "Swift Answer")
attrString.addAttribute(.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))

var tableViewCell = NSTableCellView()
tableViewCell.textField.attributedStringValue = attrString

"Short answer: you can't. To change the spacing between lines of text, you will have to subclass UILabel and roll your own drawTextInRect, or create multiple labels."

See: Set UILabel line spacing


This is a really old answer, and other have already addded the new and better way to handle this.. Please see the up to date answers provided below.

Remove last commit from remote git repository

Be careful that this will create an "alternate reality" for people who have already fetch/pulled/cloned from the remote repository. But in fact, it's quite simple:

git reset HEAD^ # remove commit locally
git push origin +HEAD # force-push the new HEAD commit

If you want to still have it in your local repository and only remove it from the remote, then you can use:

git push origin +HEAD^:<name of your branch, most likely 'master'>

How to use OpenFileDialog to select a folder?

As a note for future users who would like to avoid using FolderBrowserDialog, Microsoft once released an API called the WindowsAPICodePack that had a helpful dialog called CommonOpenFileDialog, that could be set into a IsFolderPicker mode. The API is available from Microsoft as a NuGet package.

This is all I needed to install and use the CommonOpenFileDialog. (NuGet handled the dependencies)

Install-Package Microsoft.WindowsAPICodePack-Shell

For the include line:

using Microsoft.WindowsAPICodePack.Dialogs;

Usage:

CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.InitialDirectory = "C:\\Users";
dialog.IsFolderPicker = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
    MessageBox.Show("You selected: " + dialog.FileName);
}

How to get SQL from Hibernate Criteria API (*not* for logging)

Here is a method I used and worked for me

public static String toSql(Session session, Criteria criteria){
    String sql="";
    Object[] parameters = null;
    try{
        CriteriaImpl c = (CriteriaImpl) criteria;
        SessionImpl s = (SessionImpl)c.getSession();
        SessionFactoryImplementor factory = (SessionFactoryImplementor)s.getSessionFactory();
        String[] implementors = factory.getImplementors( c.getEntityOrClassName() );
        CriteriaLoader loader = new CriteriaLoader((OuterJoinLoadable)factory.getEntityPersister(implementors[0]), factory, c, implementors[0], s.getEnabledFilters());
        Field f = OuterJoinLoader.class.getDeclaredField("sql");
        f.setAccessible(true);
        sql = (String)f.get(loader);
        Field fp = CriteriaLoader.class.getDeclaredField("traslator");
        fp.setAccessible(true);
        CriteriaQueryTranslator translator = (CriteriaQueryTranslator) fp.get(loader);
        parameters = translator.getQueryParameters().getPositionalParameterValues();
    }
    catch(Exception e){
        throw new RuntimeException(e);
    }
    if (sql !=null){
        int fromPosition = sql.indexOf(" from ");
        sql = "SELECT * "+ sql.substring(fromPosition);

        if (parameters!=null && parameters.length>0){
            for (Object val : parameters) {
                String value="%";
                if(val instanceof Boolean){
                    value = ((Boolean)val)?"1":"0";
                }else if (val instanceof String){
                    value = "'"+val+"'";
                }
                sql = sql.replaceFirst("\\?", value);
            }
        }
    }
    return sql.replaceAll("left outer join", "\nleft outer join").replace(" and ", "\nand ").replace(" on ", "\non ");
}

How to load html string in a webview?

read from assets html file

ViewGroup webGroup;
  String content = readContent("content/ganji.html");

        final WebView webView = new WebView(this);
        webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);

        webGroup.addView(webView);

Get selected option from select element

Here is a shorter version that should also work:

 $('#ddlCodes').change(function() {
      $('#txtEntry2').text(this.val());
    });

Visual Studio debugging/loading very slow

Turning off intelliTrace fixed this for me.

In Visual Studio, Tools -> Options -> IntelliTrace

Then, uncheck the checkbox for "Enable IntelliTrace".

Disable IntelliTrace in Visual Studio 2012

using scp in terminal

You can download in the current directory with a . :

cd # by default, goes to $HOME
scp me@host:/path/to/file .

or in you HOME directly with :

scp me@host:/path/to/file ~

ImportError: No module named 'MySQL'

I just moved source folder connector from folder mysql to site-packages. And run import connector

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

For AF_UNIX you can use call unlink (path); after close() socket in "server" app

Sort a List of objects by multiple fields

Yes, you absolutely can do this. For example:

public class PersonComparator implements Comparator<Person>
{
    public int compare(Person p1, Person p2)
    {
        // Assume no nulls, and simple ordinal comparisons

        // First by campus - stop if this gives a result.
        int campusResult = p1.getCampus().compareTo(p2.getCampus());
        if (campusResult != 0)
        {
            return campusResult;
        }

        // Next by faculty
        int facultyResult = p1.getFaculty().compareTo(p2.getFaculty());
        if (facultyResult != 0)
        {
            return facultyResult;
        }

        // Finally by building
        return p1.getBuilding().compareTo(p2.getBuilding());
    }
}

Basically you're saying, "If I can tell which one comes first just by looking at the campus (before they come from different campuses, and the campus is the most important field) then I'll just return that result. Otherwise, I'll continue on to compare faculties. Again, stop if that's enough to tell them apart. Otherwise, (if the campus and faculty are the same for both people) just use the result of comparing them by building."

How do you align left / right a div without using float?

No need to add extra elements. While flexbox uses very non-intuitive property names if you know what it can do you'll find yourself using it quite often.

<div style="display: flex; justify-content: space-between;">
<span>Item Left</span>
<span>Item Right</span>
</div>

Plan on needing this often?

.align_between {display: flex; justify-content: space-between;}

I see other people using secondary words in the primary position which makes a mess of information hierarchy. If align is the primary task and right, left, and/or between are the secondary the class should be .align_outer, not .outer_align as it will make sense as you vertically scan your code:

.align_between {}
.align_left {}
.align_outer {}
.align_right {}

Good habits over time will allow you to get to bed sooner than later.

difference between width auto and width 100 percent

It's about margins and border. If you use width: auto, then add border, your div won't become bigger than its container. On the other hand, if you use width: 100% and some border, the element's width will be 100% + border or margin. For more info see this.

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

I had the opposite problem and finally had to create my own bash shell script for the company to migrate the hundred of repos from Github to Gitlab due to a change in the company policy.
The script use the Gitlab API to remotely create a repo, and push the Github repo into it. There is no README.md file yet, but the sh is well documented.
The same thing can be done opposite way I imagine. Hope this could help.
https://github.com/mahmalsami/migrate-github-gitlab/blob/master/migrate.sh

How can I get a channel ID from YouTube?

You can use this website to obtain a channelId

https://commentpicker.com/youtube-channel-id.php

Redis strings vs Redis hashes to represent JSON: efficiency?

Some additions to a given set of answers:

First of all if you going to use Redis hash efficiently you must know a keys count max number and values max size - otherwise if they break out hash-max-ziplist-value or hash-max-ziplist-entries Redis will convert it to practically usual key/value pairs under a hood. ( see hash-max-ziplist-value, hash-max-ziplist-entries ) And breaking under a hood from a hash options IS REALLY BAD, because each usual key/value pair inside Redis use +90 bytes per pair.

It means that if you start with option two and accidentally break out of max-hash-ziplist-value you will get +90 bytes per EACH ATTRIBUTE you have inside user model! ( actually not the +90 but +70 see console output below )

 # you need me-redis and awesome-print gems to run exact code
 redis = Redis.include(MeRedis).configure( hash_max_ziplist_value: 64, hash_max_ziplist_entries: 512 ).new 
  => #<Redis client v4.0.1 for redis://127.0.0.1:6379/0> 
 > redis.flushdb
  => "OK" 
 > ap redis.info(:memory)
    {
                "used_memory" => "529512",
          **"used_memory_human" => "517.10K"**,
            ....
    }
  => nil 
 # me_set( 't:i' ... ) same as hset( 't:i/512', i % 512 ... )    
 # txt is some english fictionary book around 56K length, 
 # so we just take some random 63-symbols string from it 
 > redis.pipelined{ 10000.times{ |i| redis.me_set( "t:#{i}", txt[rand(50000), 63] ) } }; :done
 => :done 
 > ap redis.info(:memory)
  {
               "used_memory" => "1251944",
         **"used_memory_human" => "1.19M"**, # ~ 72b per key/value
            .....
  }
  > redis.flushdb
  => "OK" 
  # setting **only one value** +1 byte per hash of 512 values equal to set them all +1 byte 
  > redis.pipelined{ 10000.times{ |i| redis.me_set( "t:#{i}", txt[rand(50000), i % 512 == 0 ? 65 : 63] ) } }; :done 
  > ap redis.info(:memory)
   {
               "used_memory" => "1876064",
         "used_memory_human" => "1.79M",   # ~ 134 bytes per pair  
          ....
   }
    redis.pipelined{ 10000.times{ |i| redis.set( "t:#{i}", txt[rand(50000), 65] ) } };
    ap redis.info(:memory)
    {
             "used_memory" => "2262312",
          "used_memory_human" => "2.16M", #~155 byte per pair i.e. +90 bytes    
           ....
    }

For TheHippo answer, comments on Option one are misleading:

hgetall/hmset/hmget to the rescue if you need all fields or multiple get/set operation.

For BMiner answer.

Third option is actually really fun, for dataset with max(id) < has-max-ziplist-value this solution has O(N) complexity, because, surprise, Reddis store small hashes as array-like container of length/key/value objects!

But many times hashes contain just a few fields. When hashes are small we can instead just encode them in an O(N) data structure, like a linear array with length-prefixed key value pairs. Since we do this only when N is small, the amortized time for HGET and HSET commands is still O(1): the hash will be converted into a real hash table as soon as the number of elements it contains will grow too much

But you should not worry, you'll break hash-max-ziplist-entries very fast and there you go you are now actually at solution number 1.

Second option will most likely go to the fourth solution under a hood because as question states:

Keep in mind that if I use a hash, the value length isn't predictable. They're not all short such as the bio example above.

And as you already said: the fourth solution is the most expensive +70 byte per each attribute for sure.

My suggestion how to optimize such dataset:

You've got two options:

  1. If you cannot guarantee max size of some user attributes than you go for first solution and if memory matter is crucial than compress user json before store in redis.

  2. If you can force max size of all attributes. Than you can set hash-max-ziplist-entries/value and use hashes either as one hash per user representation OR as hash memory optimization from this topic of a Redis guide: https://redis.io/topics/memory-optimization and store user as json string. Either way you may also compress long user attributes.

Contain an image within a div?

Use max width and max height. It will keep the aspect ratio

#container img 
{
 max-width: 250px;
 max-height: 250px;
}

http://jsfiddle.net/rV77g/

Definition of int64_t

int64_t is guaranteed by the C99 standard to be exactly 64 bits wide on platforms that implement it, there's no such guarantee for a long which is at least 32 bits so it could be more.

§7.18.1.3 Exact-width integer types 1 The typedef name intN_t designates a signed integer type with width N , no padding bits, and a two’s complement representation. Thus, int8_t denotes a signed integer type with a width of exactly 8 bits.

Wait until page is loaded with Selenium WebDriver for Python

You can do that very simple by this function:

def page_is_loading(driver):
    while True:
        x = driver.execute_script("return document.readyState")
        if x == "complete":
            return True
        else:
            yield False

and when you want do something after page loading complete,you can use:

Driver = webdriver.Firefox(options=Options, executable_path='geckodriver.exe')
Driver.get("https://www.google.com/")

while not page_is_loading(Driver):
    continue

Driver.execute_script("alert('page is loaded')")

"Cannot instantiate the type..."

You can use

Queue thequeue = new linkedlist();

or

Queue thequeue = new Priorityqueue();

Reason: Queue is an interface. So you can instantiate only its concrete subclass.

How do I get a decimal value when using the division operator in Python?

You need to tell Python to use floating point values, not integers. You can do that simply by using a decimal point yourself in the inputs:

>>> 4/100.0
0.040000000000000001

List changes unexpectedly after assignment. How do I clone or copy it to prevent this?

A slight practical perspective to look into memory through id and gc.

>>> b = a = ['hell', 'word']
>>> c = ['hell', 'word']

>>> id(a), id(b), id(c)
(4424020872, 4424020872, 4423979272) 
     |           |
      -----------

>>> id(a[0]), id(b[0]), id(c[0])
(4424018328, 4424018328, 4424018328) # all referring to same 'hell'
     |           |           |
      -----------------------

>>> id(a[0][0]), id(b[0][0]), id(c[0][0])
(4422785208, 4422785208, 4422785208) # all referring to same 'h'
     |           |           |
      -----------------------

>>> a[0] += 'o'
>>> a,b,c
(['hello', 'word'], ['hello', 'word'], ['hell', 'word'])  # b changed too
>>> id(a[0]), id(b[0]), id(c[0])
(4424018384, 4424018384, 4424018328) # augmented assignment changed a[0],b[0]
     |           |
      -----------

>>> b = a = ['hell', 'word']
>>> id(a[0]), id(b[0]), id(c[0])
(4424018328, 4424018328, 4424018328) # the same hell
     |           |           |
      -----------------------

>>> import gc
>>> gc.get_referrers(a[0]) 
[['hell', 'word'], ['hell', 'word']]  # one copy belong to a,b, the another for c
>>> gc.get_referrers(('hell'))
[['hell', 'word'], ['hell', 'word'], ('hell', None)] # ('hello', None) 

How to create a jQuery plugin with methods?

The following plugin-structure utilizes the jQuery-data()-method to provide a public interface to internal plugin-methods/-settings (while preserving jQuery-chainability):

(function($, window, undefined) { 
  const defaults = {
    elementId   : null,
    shape       : "square",
    color       : "aqua",
    borderWidth : "10px",
    borderColor : "DarkGray"
  };

  $.fn.myPlugin = function(options) {
    // settings, e.g.:  
    var settings = $.extend({}, defaults, options);

    // private methods, e.g.:
    var setBorder = function(color, width) {        
      settings.borderColor = color;
      settings.borderWidth = width;          
      drawShape();
    };

    var drawShape = function() {         
      $('#' + settings.elementId).attr('class', settings.shape + " " + "center"); 
      $('#' + settings.elementId).css({
        'background-color': settings.color,
        'border': settings.borderWidth + ' solid ' + settings.borderColor      
      });
      $('#' + settings.elementId).html(settings.color + " " + settings.shape);            
    };

    return this.each(function() { // jQuery chainability     
      // set stuff on ini, e.g.:
      settings.elementId = $(this).attr('id'); 
      drawShape();

      // PUBLIC INTERFACE 
      // gives us stuff like: 
      //
      //    $("#...").data('myPlugin').myPublicPluginMethod();
      //
      var myPlugin = {
        element: $(this),
        // access private plugin methods, e.g.: 
        setBorder: function(color, width) {        
          setBorder(color, width);
          return this.element; // To ensure jQuery chainability 
        },
        // access plugin settings, e.g.: 
        color: function() {
          return settings.color;
        },        
        // access setting "shape" 
        shape: function() {
          return settings.shape;
        },     
        // inspect settings 
        inspectSettings: function() {
          msg = "inspecting settings for element '" + settings.elementId + "':";   
          msg += "\n--- shape: '" + settings.shape + "'";
          msg += "\n--- color: '" + settings.color + "'";
          msg += "\n--- border: '" + settings.borderWidth + ' solid ' + settings.borderColor + "'";
          return msg;
        },               
        // do stuff on element, e.g.:  
        change: function(shape, color) {        
          settings.shape = shape;
          settings.color = color;
          drawShape();   
          return this.element; // To ensure jQuery chainability 
        }
      };
      $(this).data("myPlugin", myPlugin);
    }); // return this.each 
  }; // myPlugin
}(jQuery));

Now you can call internal plugin-methods to access or modify plugin data or the relevant element using this syntax:

$("#...").data('myPlugin').myPublicPluginMethod(); 

As long as you return the current element (this) from inside your implementation of myPublicPluginMethod() jQuery-chainability will be preserved - so the following works:

$("#...").data('myPlugin').myPublicPluginMethod().css("color", "red").html("...."); 

Here are some examples (for details checkout this fiddle):

// initialize plugin on elements, e.g.:
$("#shape1").myPlugin({shape: 'square', color: 'blue', borderColor: 'SteelBlue'});
$("#shape2").myPlugin({shape: 'rectangle', color: 'red', borderColor: '#ff4d4d'});
$("#shape3").myPlugin({shape: 'circle', color: 'green', borderColor: 'LimeGreen'});

// calling plugin methods to read element specific plugin settings:
console.log($("#shape1").data('myPlugin').inspectSettings());    
console.log($("#shape2").data('myPlugin').inspectSettings());    
console.log($("#shape3").data('myPlugin').inspectSettings());      

// calling plugin methods to modify elements, e.g.:
// (OMG! And they are chainable too!) 
$("#shape1").data('myPlugin').change("circle", "green").fadeOut(2000).fadeIn(2000);      
$("#shape1").data('myPlugin').setBorder('LimeGreen', '30px');

$("#shape2").data('myPlugin').change("rectangle", "red"); 
$("#shape2").data('myPlugin').setBorder('#ff4d4d', '40px').css({
  'width': '350px',
  'font-size': '2em' 
}).slideUp(2000).slideDown(2000);              

$("#shape3").data('myPlugin').change("square", "blue").fadeOut(2000).fadeIn(2000);   
$("#shape3").data('myPlugin').setBorder('SteelBlue', '30px');

// etc. ...     

How to remove "href" with Jquery?

If you remove the href attribute the anchor will be not focusable and it will look like simple text, but it will still be clickable.

gcc warning" 'will be initialized after'

Class C {
   int a;
   int b;
   C():b(1),a(2){} //warning, should be C():a(2),b(1)
}

the order is important because if a is initialized before b , and a is depend on b. undefined behavior will appear.

How do I find out my root MySQL password?

Hmm Mysql 5.7.13 to reset all I did was:

$ sudo service mysql stop To stop mysql

$ mysqld_safe --skip-grant-tables & Start mysql

$ mysql -u root

Just like the correct answer. Then all I did was do what @eebbesen did.

mysql> SET PASSWORD FOR root@'localhost' = PASSWORD('NEW-password-HERE');

Hope it helps anyone out there :)

How can I select all elements without a given class in jQuery?

You could use this to pick all li elements without class:

$('ul#list li:not([class])')

Function or sub to add new row and data to table

This should help you.

Dim Ws As Worksheet
Set Ws = Sheets("Sheet-Name")
Dim tbl As ListObject
Set tbl = Ws.ListObjects("Table-Name")
Dim newrow As ListRow
Set newrow = tbl.ListRows.Add

With newrow

        .Range(1, Ws.Range("Table-Name[Table-Column-Name]").Column) = "Your Data"

End With

Setting onClickListener for the Drawable right of an EditText

public class CustomEditText extends androidx.appcompat.widget.AppCompatEditText {

    private Drawable drawableRight;
    private Drawable drawableLeft;
    private Drawable drawableTop;
    private Drawable drawableBottom;

    int actionX, actionY;

    private DrawableClickListener clickListener;

    public CustomEditText (Context context, AttributeSet attrs) {
        super(context, attrs);
        // this Contructure required when you are using this view in xml
    }

    public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);        
    }

    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    public void setCompoundDrawables(Drawable left, Drawable top,
            Drawable right, Drawable bottom) {
        if (left != null) {
            drawableLeft = left;
        }
        if (right != null) {
            drawableRight = right;
        }
        if (top != null) {
            drawableTop = top;
        }
        if (bottom != null) {
            drawableBottom = bottom;
        }
        super.setCompoundDrawables(left, top, right, bottom);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Rect bounds;
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            actionX = (int) event.getX();
            actionY = (int) event.getY();
            if (drawableBottom != null
                    && drawableBottom.getBounds().contains(actionX, actionY)) {
                clickListener.onClick(DrawablePosition.BOTTOM);
                return super.onTouchEvent(event);
            }

            if (drawableTop != null
                    && drawableTop.getBounds().contains(actionX, actionY)) {
                clickListener.onClick(DrawablePosition.TOP);
                return super.onTouchEvent(event);
            }

            // this works for left since container shares 0,0 origin with bounds
            if (drawableLeft != null) {
                bounds = null;
                bounds = drawableLeft.getBounds();

                int x, y;
                int extraTapArea = (int) (13 * getResources().getDisplayMetrics().density  + 0.5);

                x = actionX;
                y = actionY;

                if (!bounds.contains(actionX, actionY)) {
                    /** Gives the +20 area for tapping. */
                    x = (int) (actionX - extraTapArea);
                    y = (int) (actionY - extraTapArea);

                    if (x <= 0)
                        x = actionX;
                    if (y <= 0)
                        y = actionY;

                    /** Creates square from the smallest value */
                    if (x < y) {
                        y = x;
                    }
                }

                if (bounds.contains(x, y) && clickListener != null) {
                    clickListener
                            .onClick(DrawableClickListener.DrawablePosition.LEFT);
                    event.setAction(MotionEvent.ACTION_CANCEL);
                    return false;

                }
            }

            if (drawableRight != null) {

                bounds = null;
                bounds = drawableRight.getBounds();

                int x, y;
                int extraTapArea = 13;

                /**
                 * IF USER CLICKS JUST OUT SIDE THE RECTANGLE OF THE DRAWABLE
                 * THAN ADD X AND SUBTRACT THE Y WITH SOME VALUE SO THAT AFTER
                 * CALCULATING X AND Y CO-ORDINATE LIES INTO THE DRAWBABLE
                 * BOUND. - this process help to increase the tappable area of
                 * the rectangle.
                 */
                x = (int) (actionX + extraTapArea);
                y = (int) (actionY - extraTapArea);

                /**Since this is right drawable subtract the value of x from the width 
                * of view. so that width - tappedarea will result in x co-ordinate in drawable bound. 
                */
                x = getWidth() - x;
                
                 /*x can be negative if user taps at x co-ordinate just near the width.
                 * e.g views width = 300 and user taps 290. Then as per previous calculation
                 * 290 + 13 = 303. So subtract X from getWidth() will result in negative value.
                 * So to avoid this add the value previous added when x goes negative.
                 */
                 
                if(x <= 0){
                    x += extraTapArea;
                }
                
                 /* If result after calculating for extra tappable area is negative.
                 * assign the original value so that after subtracting
                 * extratapping area value doesn't go into negative value.
                 */               
                 
                if (y <= 0)
                    y = actionY;                

                /**If drawble bounds contains the x and y points then move ahead.*/
                if (bounds.contains(x, y) && clickListener != null) {
                    clickListener
                            .onClick(DrawableClickListener.DrawablePosition.RIGHT);
                    event.setAction(MotionEvent.ACTION_CANCEL);
                    return false;
                }
                return super.onTouchEvent(event);
            }           

        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void finalize() throws Throwable {
        drawableRight = null;
        drawableBottom = null;
        drawableLeft = null;
        drawableTop = null;
        super.finalize();
    }

    public void setDrawableClickListener(DrawableClickListener listener) {
        this.clickListener = listener;
    }

}

Also Create an Interface with

public interface DrawableClickListener {

    public static enum DrawablePosition { TOP, BOTTOM, LEFT, RIGHT };
    public void onClick(DrawablePosition target); 
    }

Still if u need any help, comment

Also set the drawableClickListener on the view in activity file.

editText.setDrawableClickListener(new DrawableClickListener() {
        
         
        public void onClick(DrawablePosition target) {
            switch (target) {
            case LEFT:
                //Do something here
                break;

            default:
                break;
            }
        }
        
    });

Disable Copy or Paste action for text box?

See this example. You need to bind the event key propagation

$(document).ready(function () {
    $('#confirmEmail').keydown(function (e) {
        if (e.ctrlKey && (e.keyCode == 88 || e.keyCode == 67 || e.keyCode == 86)) {
            return false;
        }
    });
});

How do I use .toLocaleTimeString() without displaying seconds?

With locales :

var date = new Date();
date.toLocaleTimeString('fr-FR', {hour: '2-digit', minute: '2-digit'})

Check/Uncheck a checkbox on datagridview

Simple code for you it will work

private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (dgv.CurrentRow.Cells["ColumnNumber"].Value != null && (bool)dgv.CurrentRow.Cells["ColumnNumber"].Value)
    {
        dgv.CurrentRow.Cells["ColumnNumber"].Value = false;
        dgv.CurrentRow.Cells["ColumnNumber"].Value = null;
    }
    else if (dgv.CurrentRow.Cells["ColumnNumber"].Value == null )
    {
        dgv.CurrentRow.Cells["ColumnNumber"].Value = true;
    }
}

How to bind to a PasswordBox in MVVM

If you want it combined it all in only one control and one command

<PasswordBox Name="PasswordBoxPin" PasswordChar="*">
    <PasswordBox.InputBindings>
        <KeyBinding Key="Return" Command="{Binding AuthentifyEmpCommand}" CommandParameter="{Binding ElementName=PasswordBoxPin}"/>
    </PasswordBox.InputBindings>
</PasswordBox>

And on your Vm (like Konamiman showed)

public void AuthentifyEmp(object obj)
{
    var passwordBox = obj as PasswordBox;
    var password = passwordBox.Password;
}
private RelayCommand _authentifyEmpCommand;
public RelayCommand AuthentifyEmpCommand => _authentifyEmpCommand ?? (_authentifyEmpCommand = new RelayCommand(AuthentifyEmp, null));

EDIT: Based on comments I feel the need to specify that this is a violation of MVVM pattern, use it only if that is not one of your primary concerns.

How to append data to div using JavaScript?

The following method is less general than others however it's great when you are sure that your last child node of the div is already a text node. In this way you won't create a new text node using appendData MDN Reference AppendData

let mydiv = document.getElementById("divId");
let lastChild = mydiv.lastChild;

if(lastChild && lastChild.nodeType === Node.TEXT_NODE ) //test if there is at least a node and the last is a text node
   lastChild.appendData("YOUR TEXT CONTENT");

How to add elements of a string array to a string array list?

You already have built-in method for that: -

List<String> species = Arrays.asList(speciesArr);

NOTE: - You should use List<String> species not ArrayList<String> species.

Arrays.asList returns a different ArrayList -> java.util.Arrays.ArrayList which cannot be typecasted to java.util.ArrayList.

Then you would have to use addAll method, which is not so good. So just use List<String>

NOTE: - The list returned by Arrays.asList is a fixed size list. If you want to add something to the list, you would need to create another list, and use addAll to add elements to it. So, then you would better go with the 2nd way as below: -

    String[] arr = new String[1];
    arr[0] = "rohit";
    List<String> newList = Arrays.asList(arr);

    // Will throw `UnsupportedOperationException
    // newList.add("jain"); // Can't do this.

    ArrayList<String> updatableList = new ArrayList<String>();

    updatableList.addAll(newList); 

    updatableList.add("jain"); // OK this is fine. 

    System.out.println(newList);       // Prints [rohit]
    System.out.println(updatableList); //Prints [rohit, jain]

How to create custom button in Android using XML Styles

Have you ever tried to create the background shape for any buttons?

Check this out below:

Below is the separated image from your image of a button.

enter image description here

Now, put that in your ImageButton for android:src "source" like so:

android:src="@drawable/twitter"

Now, just create shape of the ImageButton to have a black shader background.

android:background="@drawable/button_shape"

and the button_shape is the xml file in drawable resource:

    <?xml version="1.0" encoding="UTF-8"?>
<shape 
    xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke 
        android:width="1dp" 
        android:color="#505050"/>
    <corners 
        android:radius="7dp" />

    <padding 
        android:left="1dp"
        android:right="1dp"
        android:top="1dp"
        android:bottom="1dp"/>

    <solid android:color="#505050"/>

</shape>

Just try to implement it with this. You might need to change the color value as per your requirement.

Let me know if it doesn't work.

C++ correct way to return pointer to array from function

In a real app, the way you returned the array is called using an out parameter. Of course you don't actually have to return a pointer to the array, because the caller already has it, you just need to fill in the array. It's also common to pass another argument specifying the size of the array so as to not overflow it.

Using an out parameter has the disadvantage that the caller may not know how large the array needs to be to store the result. In that case, you can return a std::vector or similar array class instance.

How to fetch FetchType.LAZY associations with JPA and Hibernate in a Spring Controller

it can only be lazily loaded whilst within a transaction. So you could access the collection in your repository, which has a transaction - or what I normally do is a get with association, or set fetchmode to eager.

Return datetime object of previous month

def month_sub(year, month, sub_month):
    result_month = 0
    result_year = 0
    if month > (sub_month % 12):
        result_month = month - (sub_month % 12)
        result_year = year - (sub_month / 12)
    else:
        result_month = 12 - (sub_month % 12) + month
        result_year = year - (sub_month / 12 + 1)
    return (result_year, result_month)

>>> month_sub(2015, 7, 1)    
(2015, 6)
>>> month_sub(2015, 7, -1)
(2015, 8)
>>> month_sub(2015, 7, 13)
(2014, 6)
>>> month_sub(2015, 7, -14)
(2016, 9)

How to redirect the output of an application in background to /dev/null

These will also redirect both:

yourcommand  &> /dev/null

yourcommand  >& /dev/null

though the bash manual says the first is preferred.

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

See Apple’s Info.plist reference for full details (thanks @gnasher729).

You can add exceptions for specific domains in your Info.plist:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>testdomain.com</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSExceptionRequiresForwardSecrecy</key>
            <true/>
            <key>NSExceptionMinimumTLSVersion</key>
            <string>TLSv1.2</string>
            <key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
            <false/>
            <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
            <true/>
            <key>NSThirdPartyExceptionMinimumTLSVersion</key>
            <string>TLSv1.2</string>
            <key>NSRequiresCertificateTransparency</key>
            <false/>
        </dict>
    </dict>
</dict>

All the keys for each excepted domain are optional. The speaker did not elaborate on any of the keys, but I think they’re all reasonably obvious.

(Source: WWDC 2015 session 703, “Privacy and Your App”, 30:18)

You can also ignore all app transport security restrictions with a single key, if your app has a good reason to do so:

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

If your app does not have a good reason, you may risk rejection:

Setting NSAllowsArbitraryLoads to true will allow it to work, but Apple was very clear in that they intend to reject apps who use this flag without a specific reason. The main reason to use NSAllowsArbitraryLoads I can think of would be user created content (link sharing, custom web browser, etc). And in this case, Apple still expects you to include exceptions that enforce the ATS for the URLs you are in control of.

If you do need access to specific URLs that are not served over TLS 1.2, you need to write specific exceptions for those domains, not use NSAllowsArbitraryLoads set to yes. You can find more info in the NSURLSesssion WWDC session.

Please be careful in sharing the NSAllowsArbitraryLoads solution. It is not the recommended fix from Apple.

kcharwood (thanks @marco-tolman)

How to get a list of column names on Sqlite3 database?

I know it's too late but this will help other.

To find the column name of the table, you should execute select * from tbl_name and you will get the result in sqlite3_stmt *. and check the column iterate over the total fetched column. Please refer following code for the same.

// sqlite3_stmt *statement ;
int totalColumn = sqlite3_column_count(statement);
for (int iterator = 0; iterator<totalColumn; iterator++) {
   NSLog(@"%s", sqlite3_column_name(statement, iterator));
}

This will print all the column names of the result set.

Why does pycharm propose to change method to static

The reason why Pycharm make it as a warning because Python will pass self as the first argument when calling a none static method (not add @staticmethod). Pycharm knows it.

Example:

class T:
    def test():
        print "i am a normal method!"

t = T()
t.test()
output:
Traceback (most recent call last):
  File "F:/Workspace/test_script/test.py", line 28, in <module>
    T().test()
TypeError: test() takes no arguments (1 given)

I'm from Java, in Java "self" is called "this", you don't need write self(or this) as argument in class method. You can just call self as you need inside the method. But Python "has to" pass self as a method argument.

By understanding this you don't need any Workaround as @BobStein answer.

Split string based on regex

I suggest

l = re.compile("(?<!^)\s+(?=[A-Z])(?!.\s)").split(s)

Check this demo.

Git: How to commit a manually deleted file?

The answer's here, I think.

It's better if you do git rm <fileName>, though.

Linux / Bash, using ps -o to get process by specific name?

Sorry, much late to the party, but I'll add here that if you wanted to capture processes with names identical to your search string, you could do

pgrep -x PROCESS_NAME

-x          Require an exact match of the process name, or argument list if -f is given.
             The default is to match any substring.

This is extremely useful if your original process created child processes (possibly zombie when you query) which prefix the original process' name in their own name and you are trying to exclude them from your results. There are many UNIX daemons which do this. My go-to example is ninja-dev-sync.

Why Would I Ever Need to Use C# Nested Classes

what I don't get is why I would ever need to do this

I think you never need to do this. Given a nested class like this ...

class A
{
  //B is used to help implement A
  class B
  {
    ...etc...
  }
  ...etc...
}

... you can always move the inner/nested class to global scope, like this ...

class A
{
  ...etc...
}

//B is used to help implement A
class B
{
  ...etc...
}

However, when B is only used to help implement A, then making B an inner/nested class has two advantages:

  • It doesn't pollute the global scope (e.g. client code which can see A doesn't know that the B class even exists)
  • The methods of B implicitly have access to private members of A; whereas if B weren't nested inside A, B wouldn't be able to access members of A unless those members were internal or public; but then making those members internal or public would expose them to other classes too (not just B); so instead, keep those methods of A private and let B access them by declaring B as a nested class. If you know C++, this is like saying that in C# all nested classes are automatically a 'friend' of the class in which they're contained (and, that declaring a class as nested is the only way to declare friendship in C#, since C# doesn't have a friend keyword).

When I say that B can access private members of A, that's assuming that B has a reference to A; which it often does, since nested classes are often declared like this ...

class A
{
  //used to help implement A
  class B
  {
    A m_a;
    internal B(A a) { m_a = a; }
    ...methods of B can access private members of the m_a instance...
  }
  ...etc...
}

... and constructed from a method of A using code like this ...

//create an instance of B, whose implementation can access members of self
B b = new B(this);

You can see an example in Mehrdad's reply.

Properly escape a double quote in CSV

Use 2 quotes:

"Samsung U600 24"""

Android center view in FrameLayout doesn't work

To center a view in Framelayout, there are some available tricks. The simplest one I used for my Webview and Progressbar(very similar to your two object layout), I just added android:layout_gravity="center"

Here is complete XML in case if someone else needs the same thing to do

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".WebviewPDFActivity"
    android:layout_gravity="center"
    >
    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        />
    <ProgressBar
        android:id="@+id/progress_circular"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:visibility="visible"
        android:layout_gravity="center"
        />


</FrameLayout>

Here is my output

screenshot

How to insert an item into an array at a specific index (JavaScript)?

Append Single Element at a specific index

//Append at specific position(here at index 1)
arrName.splice(1, 0,'newName1');
//1: index number, 0: number of element to remove, newName1: new element


//Append at specific position (here at index 3)
arrName[3] = 'newName1';

Append Multiple Element at a specific index

//Append from index number 1
arrName.splice(1, 0,'newElemenet1', 'newElemenet2', 'newElemenet3');
//1: index number from where append start, 
//0: number of element to remove, 
//newElemenet1,2,3: new elements

How to create a popup window (PopupWindow) in Android

are you done with the layout inflating? maybe you can try this!!

View myPoppyView = pw.getContentView();
Button myBelovedButton = (Button)myPoppyView.findViewById(R.id.my_beloved_button);
//do something with my beloved button? :p

How to install 2 Anacondas (Python 2 and 3) on Mac OS

Edit!: Please be sure that you should have both Python installed on your computer.

Maybe my answer is late for you but I can help someone who has the same problem!

You don't have to download both Anaconda.

If you are using Spyder and Jupyter in Anaconda environmen and,

If you have already Anaconda 2 type in Terminal:

    python3 -m pip install ipykernel

    python3 -m ipykernel install --user

If you have already Anaconda 3 then type in terminal:

    python2 -m pip install ipykernel

    python2 -m ipykernel install --user

Then before use Spyder you can choose Python environment like below! Sometimes only you can see root and your new Python environment, so root is your first anaconda environment!

Anaconda spyder Python 2.7 or 3.5

Also this is Jupyter. You can choose python version like this!

Jupyter Notebook

I hope it will help.

View tabular file such as CSV from command line

Yet another multi-functional CSV (and not only) manipulation tool: Miller. From its own description, it is like awk, sed, cut, join, and sort for name-indexed data such as CSV, TSV, and tabular JSON. (link to github repository: https://github.com/johnkerl/miller)

What does "The following object is masked from 'package:xxx'" mean?

I have the same problem. I avoid it with remove.packages("Package making this confusion") and it works. In my case, I don't need the second package, so that is not a very good idea.

Bash conditionals: how to "and" expressions? (if [ ! -z $VAR && -e $VAR ])

if [ -n "$var" -a -e "$var" ]; then
    do something ...
fi

 

Can you write virtual functions / methods in Java?

All non-private instance methods are virtual by default in Java.

In C++, private methods can be virtual. This can be exploited for the non-virtual-interface (NVI) idiom. In Java, you'd need to make the NVI overridable methods protected.

From the Java Language Specification, v3:

8.4.8.1 Overriding (by Instance Methods) An instance method m1 declared in a class C overrides another instance method, m2, declared in class A iff all of the following are true:

  1. C is a subclass of A.
  2. The signature of m1 is a subsignature (§8.4.2) of the signature of m2.
  3. Either * m2 is public, protected or declared with default access in the same package as C, or * m1 overrides a method m3, m3 distinct from m1, m3 distinct from m2, such that m3 overrides m2.

How to change visibility of layout programmatically

this is a programatical approach:

 view.setVisibility(View.GONE); //For GONE
 view.setVisibility(View.INVISIBLE); //For INVISIBLE
 view.setVisibility(View.VISIBLE); //For VISIBLE

Why is my CSS bundling not working with a bin deployed MVC4 app?

Omitting runAllManagedModulesForAllRequests="true" also worked for me. Add the following configuration in web.config:

<modules>
  <remove name="BundleModule" />
  <add name="BundleModule" type="System.Web.Optimization.BundleModule" />
</modules>

runAllManagedModulesForAllRequests will impose a performance hit on your website if not used appropriately. Check out this article.

Creating a directory in /sdcard fails

The correct path to the sdcard is

/mnt/sdcard/

but, as answered before, you shouldn't hardcode it. If you are on Android 2.1 or after, use

getExternalFilesDir(String type) 

Otherwise:

Environment.getExternalStorageDirectory()

Read carefully https://developer.android.com/guide/topics/data/data-storage.html#filesExternal

Also, you'll need to use this method or something similar

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}

then check if you can access the sdcard. As said, read the official documentation.

Another option, maybe you need to use mkdirs instead of mkdir

file.mkdirs()

Creates the directory named by the trailing filename of this file, including the complete directory path required to create this directory.

How do I fit an image (img) inside a div and keep the aspect ratio?

Here's an all JavaScript approach. It scales an image incrementally down until it fits correctly. You choose how much to shrink it each time it fails. This example shrinks it 10% each time it fails:

let fit = function (el, w, h, percentage, step)
{
    let newH = h;
    let newW = w;

    // fail safe
    if (percentage < 0 || step < 0) return { h: h, w: w };
    if (h > w)
    {
        newH = el.height() * percentage;
        newW = (w / h) * newH;
        if (newW > el.width())
        {
            return fit(el, w, h, percentage - step, step);
        }
    }
    else
    {
        newW = el.width() * percentage;
        newH = (h / w) * newW;
        if (newH > el.height())
        {
            return fit(el, w, h, percentage - step, step);
        }
    }

    return { h: newH, w: newW };
};

img.bind('load', function ()
{
    let h = img.height();
    let w = img.width();
    let newFit = fit($('<img-wrapper-selector>'), w, h, 1, 0.1);

    img.width(newFit.w);
    img.height(newFit.h);
});

Feel free to copy and paste directly.

heroku - how to see all the logs

For cedar stack see:

https://devcenter.heroku.com/articles/oneoff-admin-ps

you need to run:

heroku run bash ...

Recommended date format for REST GET API

Check this article for the 5 laws of API dates and times HERE:

  • Law #1: Use ISO-8601 for your dates
  • Law #2: Accept any timezone
  • Law #3: Store it in UTC
  • Law #4: Return it in UTC
  • Law #5: Don’t use time if you don’t need it

More info in the docs.

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

How to avoid HTTP error 429 (Too Many Requests) python

As MRA said, you shouldn't try to dodge a 429 Too Many Requests but instead handle it accordingly. You have several options depending on your use-case:

1) Sleep your process. The server usually includes a Retry-after header in the response with the number of seconds you are supposed to wait before retrying. Keep in mind that sleeping a process might cause problems, e.g. in a task queue, where you should instead retry the task at a later time to free up the worker for other things.

2) Exponential backoff. If the server does not tell you how long to wait, you can retry your request using increasing pauses in between. The popular task queue Celery has this feature built right-in.

3) Token bucket. This technique is useful if you know in advance how many requests you are able to make in a given time. Each time you access the API you first fetch a token from the bucket. The bucket is refilled at a constant rate. If the bucket is empty, you know you'll have to wait before hitting the API again. Token buckets are usually implemented on the other end (the API) but you can also use them as a proxy to avoid ever getting a 429 Too Many Requests. Celery's rate_limit feature uses a token bucket algorithm.

Here is an example of a Python/Celery app using exponential backoff and rate-limiting/token bucket:

class TooManyRequests(Exception):
"""Too many requests"""

@task(
   rate_limit='10/s',
   autoretry_for=(ConnectTimeout, TooManyRequests,),
   retry_backoff=True)
def api(*args, **kwargs):
  r = requests.get('placeholder-external-api')

  if r.status_code == 429:
    raise TooManyRequests()

MVC pattern on Android

After some searching, the most reasonable answer is the following:

MVC is already implemented in Android as:

  1. View = layout, resources and built-in classes like Button derived from android.view.View.
  2. Controller = Activity
  3. Model = the classes that implement the application logic

(This by the way implies no application domain logic in the activity.)

The most reasonable thing for a small developer is to follow this pattern and not to try to do what Google decided not to do.

PS Note that Activity is sometimes restarted, so it's no place for model data (the easiest way to cause a restart is to omit android:configChanges="keyboardHidden|orientation" from the XML and turn your device).

EDIT

We may be talking about MVC, but it will be so to say FMVC, Framework--Model--View--Controller. The Framework (the Android OS) imposes its idea of component life cycle and related events, and in practice the Controller (Activity/Service/BroadcastReceiver) is first of all responsible for coping with these Framework-imposed events (such as onCreate()). Should user input be processed separately? Even if it should, you cannot separate it, user input events also come from Android.

Anyway, the less code that is not Android-specific you put into your Activity/Service/BroadcastReceiver, the better.

Creating a batch file, for simple javac and java command execution

I've also faced a similar situation where I needed a script which can take care of javac and then java(ing) my java program. So, I came up with this BATCH script.

::  @author Rudhin Menon
::  Created on 09/06/2015
::
::  Auto-Concrete is a build tool, which monitor the file under
::  scrutiny for any changes, and compiles or runs the same once
::  it got changed.
::  
::  ========================================
::  md5sum and gawk programs are prerequisites for this script.
::  Please download them before running auto-concrete.
::  ========================================
::  
::  Happy coding ...

@echo off

:: if filename is missing
if [%1] EQU [] goto usage_message

:: Set cmd window name
title Auto-Concrete v0.2

cd versions

if %errorlevel% NEQ 0 (
    echo creating versions directory
    mkdir versions
    cd versions
)

cd ..

javac "%1"

:loop
    :: Get OLD HASH of file
    md5sum "%1" | gawk '{print $1}' > old
    set /p oldHash=<old
    copy "%1" "versions\%oldHash%.java"

    :inner_loop
    :: Get NEW HASH of the same file
    md5sum "%1" | gawk '{print $1}' > new
    set /p newHash=<new

    :: While OLD HASH and NEW HASH are the same
    :: keep comparing OLD HASH and NEW HASH
    if "%newHash%" EQU "%oldHash%" (
        :: Take rest before proceeding
        ping -w 200 0.0.0.0 >nul
        goto inner_loop
    )

    :: Once they differ, compile the source file
    :: and repeat everything again
    echo.
    echo ========= %1 changed on %DATE% at %TIME% ===========
    echo.       
    javac "%1"
goto loop

:usage_message
echo Usage : auto-concrete FILENAME.java

Above batch script will check the file for any changes and compile if any changes are done, you can tweak it for compiling whenever you want. Happy coding :)

How can I delete all of my Git stashes at once?

this command enables you to look all stashed changes.

git stash list

Here is the following command use it to clear all of your stashed Changes

git stash clear

Now if you want to delete one of the stashed changes from stash area

git stash drop stash@{index}   // here index will be shown after getting stash list.

Note : git stash list enables you to get index from stash area of git.

How to use a table type in a SELECT FROM statement?

Prior to Oracle 12C you cannot select from PL/SQL-defined tables, only from tables based on SQL types like this:

CREATE OR REPLACE TYPE exch_row AS OBJECT(
currency_cd VARCHAR2(9),
exch_rt_eur NUMBER,
exch_rt_usd NUMBER);


CREATE OR REPLACE TYPE exch_tbl AS TABLE OF exch_row;

In Oracle 12C it is now possible to select from PL/SQL tables that are defined in a package spec.

SQL ORDER BY date problem

This may help you in mysql, php.

//your date in any format
$date = $this->input->post('txtCouponExpiry');

$day = (int)substr($date, 3, 2);
$month = (int)substr($date, 0, 2);
$year = (int)substr($date, 7, 4);

$unixTimestamp = mktime(0, 0, 0, $year, $day, $month);

// insert it into database
'date'->$unixTimestamp;

//query for selecting  order by date ASC or DESC
select * from table order_by date asc;

Use nginx to serve static files from subdirectories of a given directory

It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:

When location matches the last part of the directive’s value: it is better to use the root directive instead:

which would yield:

server {
  listen        8080;
  server_name   www.mysite.com mysite.com;
  error_log     /home/www-data/logs/nginx_www.error.log;
  error_page    404    /404.html;

  location /public/doc/ {
    autoindex on;
    root  /home/www-data/mysite;
  } 

  location = /404.html {
    root /home/www-data/mysite/static/html;
  }       
}

How to set a Postgresql default value datestamp like 'YYYYMM'?

Thanks for everyone who answered, and thanks for those who gave me the function-format idea, i'll really study it for future using.

But for this explicit case, the 'special yyyymm field' is not to be considered as a date field, but just as a tag, o whatever would be used for matching the exactly year-month researched value; there is already another date field, with the full timestamp, but if i need all the rows of january 2008, i think that is faster a select like

SELECT  [columns] FROM table WHERE yearmonth = '200801'

instead of

SELECT  [columns] FROM table WHERE date BETWEEN DATE('2008-01-01') AND DATE('2008-01-31')

Url to a google maps page to show a pin given a latitude / longitude?

From my notes:

http://maps.google.com/maps?q=37.4185N+122.08774W+(label)&ll=37.419731,-122.088715&spn=0.004250,0.011579&t=h&iwloc=A&hl=en

Which parses like this:

    q=latN+lonW+(label)     location of teardrop

    t=k             keyhole (satelite map)
    t=h             hybrid

    ll=lat,-lon     center of map
    spn=w.w,h.h     span of map, degrees

iwloc has something to do with the info window. hl is obviously language.

See also: http://www.seomoz.org/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters

Data structure for maintaining tabular data in memory?

Having a "table" in memory that needs lookups, sorting, and arbitrary aggregation really does call out for SQL. You said you tried SQLite, but did you realize that SQLite can use an in-memory-only database?

connection = sqlite3.connect(':memory:')

Then you can create/drop/query/update tables in memory with all the functionality of SQLite and no files left over when you're done. And as of Python 2.5, sqlite3 is in the standard library, so it's not really "overkill" IMO.

Here is a sample of how one might create and populate the database:

import csv
import sqlite3

db = sqlite3.connect(':memory:')

def init_db(cur):
    cur.execute('''CREATE TABLE foo (
        Row INTEGER,
        Name TEXT,
        Year INTEGER,
        Priority INTEGER)''')

def populate_db(cur, csv_fp):
    rdr = csv.reader(csv_fp)
    cur.executemany('''
        INSERT INTO foo (Row, Name, Year, Priority)
        VALUES (?,?,?,?)''', rdr)

cur = db.cursor()
init_db(cur)
populate_db(cur, open('my_csv_input_file.csv'))
db.commit()

If you'd really prefer not to use SQL, you should probably use a list of dictionaries:

lod = [ ] # "list of dicts"

def populate_lod(lod, csv_fp):
    rdr = csv.DictReader(csv_fp, ['Row', 'Name', 'Year', 'Priority'])
    lod.extend(rdr)

def query_lod(lod, filter=None, sort_keys=None):
    if filter is not None:
        lod = (r for r in lod if filter(r))
    if sort_keys is not None:
        lod = sorted(lod, key=lambda r:[r[k] for k in sort_keys])
    else:
        lod = list(lod)
    return lod

def lookup_lod(lod, **kw):
    for row in lod:
        for k,v in kw.iteritems():
            if row[k] != str(v): break
        else:
            return row
    return None

Testing then yields:

>>> lod = []
>>> populate_lod(lod, csv_fp)
>>> 
>>> pprint(lookup_lod(lod, Row=1))
{'Name': 'Cat', 'Priority': '1', 'Row': '1', 'Year': '1998'}
>>> pprint(lookup_lod(lod, Name='Aardvark'))
{'Name': 'Aardvark', 'Priority': '1', 'Row': '4', 'Year': '2000'}
>>> pprint(query_lod(lod, sort_keys=('Priority', 'Year')))
[{'Name': 'Cat', 'Priority': '1', 'Row': '1', 'Year': '1998'},
 {'Name': 'Dog', 'Priority': '1', 'Row': '3', 'Year': '1999'},
 {'Name': 'Aardvark', 'Priority': '1', 'Row': '4', 'Year': '2000'},
 {'Name': 'Wallaby', 'Priority': '1', 'Row': '5', 'Year': '2000'},
 {'Name': 'Fish', 'Priority': '2', 'Row': '2', 'Year': '1998'},
 {'Name': 'Zebra', 'Priority': '3', 'Row': '6', 'Year': '2001'}]
>>> pprint(query_lod(lod, sort_keys=('Year', 'Priority')))
[{'Name': 'Cat', 'Priority': '1', 'Row': '1', 'Year': '1998'},
 {'Name': 'Fish', 'Priority': '2', 'Row': '2', 'Year': '1998'},
 {'Name': 'Dog', 'Priority': '1', 'Row': '3', 'Year': '1999'},
 {'Name': 'Aardvark', 'Priority': '1', 'Row': '4', 'Year': '2000'},
 {'Name': 'Wallaby', 'Priority': '1', 'Row': '5', 'Year': '2000'},
 {'Name': 'Zebra', 'Priority': '3', 'Row': '6', 'Year': '2001'}]
>>> print len(query_lod(lod, lambda r:1997 <= int(r['Year']) <= 2002))
6
>>> print len(query_lod(lod, lambda r:int(r['Year'])==1998 and int(r['Priority']) > 2))
0

Personally I like the SQLite version better since it preserves your types better (without extra conversion code in Python) and easily grows to accommodate future requirements. But then again, I'm quite comfortable with SQL, so YMMV.

How can I convert a Unix timestamp to DateTime and vice versa?

The latest version of .NET (v4.6) has added built-in support for Unix time conversions. That includes both to and from Unix time represented by either seconds or milliseconds.

  • Unix time in seconds to UTC DateTimeOffset:

DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(1000);
  • DateTimeOffset to Unix time in seconds:

long unixTimeStampInSeconds = dateTimeOffset.ToUnixTimeSeconds();
  • Unix time in milliseconds to UTC DateTimeOffset:

DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(1000000);
  • DateTimeOffset to Unix time in milliseconds:

long unixTimeStampInMilliseconds = dateTimeOffset.ToUnixTimeMilliseconds();

Note: These methods convert to and from a UTC DateTimeOffset. To get a DateTime representation simply use the DateTimeOffset.UtcDateTime or DateTimeOffset.LocalDateTime properties:

DateTime dateTime = dateTimeOffset.UtcDateTime;

Bootstrap datetimepicker is not a function

Try to use datepicker/ timepicker instead of datetimepicker like:

replace:

$('#datetimepicker1').datetimepicker();

with:

$('#datetimepicker1').datepicker(); // or timepicker for time picker

Get all object attributes in Python?

What you probably want is dir().

The catch is that classes are able to override the special __dir__ method, which causes dir() to return whatever the class wants (though they are encouraged to return an accurate list, this is not enforced). Furthermore, some objects may implement dynamic attributes by overriding __getattr__, may be RPC proxy objects, or may be instances of C-extension classes. If your object is one these examples, they may not have a __dict__ or be able to provide a comprehensive list of attributes via __dir__: many of these objects may have so many dynamic attrs it doesn't won't actually know what it has until you try to access it.

In the short run, if dir() isn't sufficient, you could write a function which traverses __dict__ for an object, then __dict__ for all the classes in obj.__class__.__mro__; though this will only work for normal python objects. In the long run, you may have to use duck typing + assumptions - if it looks like a duck, cross your fingers, and hope it has .feathers.

HQL Hibernate INNER JOIN

You can do it without having to create a real Hibernate mapping. Try this:

SELECT * FROM Employee e, Team t WHERE e.Id_team=t.Id_team

Make an Installation program for C# applications and include .NET Framework installer into the setup

WiX is the way to go for new installers. If WiX alone is too complicated or not flexible enough on the GUI side consider using SharpSetup - it allows you to create installer GUI in WinForms of WPF and has other nice features like translations, autoupdater, built-in prerequisites, improved autocompletion in VS and more.

(Disclaimer: I am the author of SharpSetup.)

How to show shadow around the linearlayout in Android?

Well, this is easy to achieve .

Just build a GradientDrawable that comes from black and goes to a transparent color, than use parent relationship to place your shape close to the View that you want to have a shadow, then you just have to give any values to height or width .

Here is an example, this file have to be created inside res/drawable , I name it as shadow.xml :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <gradient
        android:startColor="#9444"
        android:endColor="#0000"
        android:type="linear"
        android:angle="90"> <!-- Change this value to have the correct shadow angle, must be multiple from 45 -->
    </gradient>

</shape>

Place the following code above from a LinearLayout , for example, set the android:layout_width and android:layout_height to fill_parent and 2.3dp, you'll have a nice shadow effect on your LinearLayout .

<View
    android:id="@+id/shadow"
    android:layout_width="fill_parent"
    android:layout_height="2.3dp"  
    android:layout_above="@+id/id_from_your_LinearLayout" 
    android:background="@drawable/shadow">
</View>

Note 1: If you increase android:layout_height more shadow will be shown .

Note 2: Use android:layout_above="@+id/id_from_your_LinearLayout" attribute if you are placing this code inside a RelativeLayout, otherwise ignore it.

Hope it help someone.

Insert into C# with SQLCommand

Use AddWithValue(), but be aware of the possibility of the wrong implicit type conversion.
like this:

cmd.Parameters.AddWithValue("@param1", klantId);
    cmd.Parameters.AddWithValue("@param2", klantNaam);
    cmd.Parameters.AddWithValue("@param3", klantVoornaam);

How to stop VBA code running?

what jamietre said, but

Private Sub SomeVBASub
    Cancel=False
    DoStuff
    If not Cancel Then DoAnotherStuff
    If not Cancel Then AndFinallyDothis
End Sub

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

The offending lines are the following:

MaxConnections=90
InitialConnections=80

You can increase the values to allow more connections.

C# Passing Function as Argument

public static T Runner<T>(Func<T> funcToRun)
{
    //Do stuff before running function as normal
    return funcToRun();
}

Usage:

var ReturnValue = Runner(() => GetUser(99));

List files with certain extensions with ls and grep

Here is one example that worked for me.

find <mainfolder path> -name '*myfiles.java' | xargs -n 1 basename

How to convert date in to yyyy-MM-dd Format?

UPDATE My Answer here is now outdated. The Joda-Time project is now in maintenance mode, advising migration to the java.time classes. See the modern solution in the Answer by Ole V.V..

Joda-Time

The accepted answer by NidhishKrishnan is correct.

For fun, here is the same kind of code in Joda-Time 2.3.

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

java.util.Date date = new Date(); // A Date object coming from other code.

// Pass the java.util.Date object to constructor of Joda-Time DateTime object.
DateTimeZone kolkataTimeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeInKolkata = new DateTime( date, kolkataTimeZone );

DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyy-MM-dd");
System.out.println( "dateTimeInKolkata formatted for date: " + formatter.print( dateTimeInKolkata ) );
System.out.println( "dateTimeInKolkata formatted for ISO 8601: " + dateTimeInKolkata );

When run…

dateTimeInKolkata formatted for date: 2013-12-17
dateTimeInKolkata formatted for ISO 8601: 2013-12-17T14:56:46.658+05:30

Why does Java have an "unreachable statement" compiler error?

Because unreachable code is meaningless to the compiler. Whilst making code meaningful to people is both paramount and harder than making it meaningful to a compiler, the compiler is the essential consumer of code. The designers of Java take the viewpoint that code that is not meaningful to the compiler is an error. Their stance is that if you have some unreachable code, you have made a mistake that needs to be fixed.

There is a similar question here: Unreachable code: error or warning?, in which the author says "Personally I strongly feel it should be an error: if the programmer writes a piece of code, it should always be with the intention of actually running it in some scenario." Obviously the language designers of Java agree.

Whether unreachable code should prevent compilation is a question on which there will never be consensus. But this is why the Java designers did it.


A number of people in comments point out that there are many classes of unreachable code Java doesn't prevent compiling. If I understand the consequences of Gödel correctly, no compiler can possibly catch all classes of unreachable code.

Unit tests cannot catch every single bug. We don't use this as an argument against their value. Likewise a compiler can't catch all problematic code, but it is still valuable for it to prevent compilation of bad code when it can.

The Java language designers consider unreachable code an error. So preventing it compiling when possible is reasonable.


(Before you downvote: the question is not whether or not Java should have an unreachable statement compiler error. The question is why Java has an unreachable statement compiler error. Don't downvote me just because you think Java made the wrong design decision.)

Pinging servers in Python

I resolve this with:

def ping(self, host):
    res = False

    ping_param = "-n 1" if system_name().lower() == "windows" else "-c 1"

    resultado = os.popen("ping " + ping_param + " " + host).read()

    if "TTL=" in resultado:
        res = True
    return res

"TTL" is the way to know if the ping is correctly. Saludos

C# Telnet Library

Best C# Telnet Lib I've found is called Minimalistic Telnet. Very easy to understand, use and modify. It works great for the Cisco routers I need to configure.

http://www.codeproject.com/KB/IP/MinimalisticTelnet.aspx

Best practices for catching and re-throwing .NET exceptions

You should always use "throw;" to rethrow the exceptions in .NET,

Refer this, http://weblogs.asp.net/bhouse/archive/2004/11/30/272297.aspx

Basically MSIL (CIL) has two instructions - "throw" and "rethrow":

  • C#'s "throw ex;" gets compiled into MSIL's "throw"
  • C#'s "throw;" - into MSIL "rethrow"!

Basically I can see the reason why "throw ex" overrides the stack trace.

What is the difference between substr and substring?

The main difference is that

substr() allows you to specify the maximum length to return

substring() allows you to specify the indices and the second argument is NOT inclusive

There are some additional subtleties between substr() and substring() such as the handling of equal arguments and negative arguments. Also note substring() and slice() are similar but not always the same.

  //*** length vs indices:
    "string".substring(2,4);  // "ri"   (start, end) indices / second value is NOT inclusive
    "string".substr(2,4);     // "ring" (start, length) length is the maximum length to return
    "string".slice(2,4);      // "ri"   (start, end) indices / second value is NOT inclusive

  //*** watch out for substring swap:
    "string".substring(3,2);  // "r"    (swaps the larger and the smaller number)
    "string".substr(3,2);     // "in"
    "string".slice(3,2);      // ""     (just returns "")

  //*** negative second argument:
    "string".substring(2,-4); // "st"   (converts negative numbers to 0, then swaps first and second position)
    "string".substr(2,-4);    // ""
    "string".slice(2,-4);     // ""

  //*** negative first argument:
    "string".substring(-3);   // "string"        
    "string".substr(-3);      // "ing"  (read from end of string)
    "string".slice(-3);       // "ing"