Programs & Examples On #Two columns

flow 2 columns of text automatically with CSS

Not an expert here, but this is what I did and it worked

<html>
<style>
/*Style your div container, must specify height*/
.content {width:1000px; height:210px; margin:20px auto; font-size:16px;}
/*Style the p tag inside your div container with half the with of your container, and float left*/
.content p {width:490px; margin-right:10px; float:left;}
</style>

<body>
<!--Put your text inside a div with a class-->
<div class="content">
            <h1>Title</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus gravida laoreet lectus. Pellentesque ultrices consequat placerat. Etiam luctus euismod tempus. In sed eros dignissim tortor faucibus dapibus ut non neque. Ut ante odio, luctus eu pharetra vitae, consequat sit amet nunc. Aenean dolor felis, fringilla sagittis hendrerit vel, egestas eget eros. Mauris suscipit bibendum massa, nec mattis lorem dignissim sit amet. </p>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer eget dolor neque. Phasellus tellus odio, egestas ut blandit sed, egestas sit amet velit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;</p>
</div>     
</body>
</html>

Once the text inside the <p> tags has reached the height of the container div, the other text will flow to the right of the container.

How to get only the last part of a path in Python?

path = "/folderA/folderB/folderC/folderD/"
last = path.split('/').pop()

..The underlying connection was closed: An unexpected error occurred on a receive

The underlying connection was closed: An unexpected error occurred on a receive.

This problem occurs when the server or another network device unexpectedly closes an existing Transmission Control Protocol (TCP) connection. This problem may occur when a time-out value on the server or on the network device is set too low. To resolve this problem, see resolutions A, D, E, F, and O. The problem can also occur if the server resets the connection unexpectedly, such as if an unhandled exception crashes the server process. Analyze the server logs to see if this may be the issue.

Resolution

To resolve this problem, make sure that you are using the most recent version of the .NET Framework.

Add a method to the class to override the GetWebRequest method. This change lets you access the HttpWebRequest object. If you are using Microsoft Visual C#, the new method must be similar to the following.

class MyTestService:TestService.TestService
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
        HttpWebRequest webRequest = (HttpWebRequest) base.GetWebRequest(uri);
        //Setting KeepAlive to false
        webRequest.KeepAlive = false;
        return webRequest;
    }
}

Excerpt from KB915599: You receive one or more error messages when you try to make an HTTP request in an application that is built on the .NET Framework 1.1 Service Pack 1.

How is a non-breaking space represented in a JavaScript string?

Remember that .text() strips out markup, thus I don't believe you're going to find &nbsp; in a non-markup result.

Made in to an answer....

var p = $('<p>').html('&nbsp;');
if (p.text() == String.fromCharCode(160) && p.text() == '\xA0')
    alert('Character 160');

Shows an alert, as the ASCII equivalent of the markup is returned instead.

How to check Oracle patches are installed?

Here is an article on how to check and or install new patches :


To find the OPatch tool setup your database enviroment variables and then issue this comand:

cd $ORACLE_HOME/OPatch 
> pwd
/oracle/app/product/10.2.0/db_1/OPatch

To list all the patches applies to your database use the lsinventory option:

[oracle@DCG023 8828328]$ opatch lsinventory
Oracle Interim Patch Installer version 11.2.0.3.4
Copyright (c) 2012, Oracle Corporation. All rights reserved.

Oracle Home : /u00/product/11.2.0/dbhome_1
Central Inventory : /u00/oraInventory
from : /u00/product/11.2.0/dbhome_1/oraInst.loc
OPatch version : 11.2.0.3.4
OUI version : 11.2.0.1.0
Log file location : /u00/product/11.2.0/dbhome_1/cfgtoollogs/opatch/opatch2013-11-13_13-55-22PM_1.log
Lsinventory Output file location : /u00/product/11.2.0/dbhome_1/cfgtoollogs/opatch/lsinv/lsinventory2013-11-13_13-55-22PM.txt


Installed Top-level Products (1):
Oracle Database 11g 11.2.0.1.0
There are 1 products installed in this Oracle Home.

Interim patches (1) :
Patch 8405205 : applied on Mon Aug 19 15:18:04 BRT 2013
Unique Patch ID: 11805160
Created on 23 Sep 2009, 02:41:32 hrs PST8PDT
Bugs fixed:
8405205

OPatch succeeded.

To list the patches using sql :

select * from registry$history;

Is it safe to store a JWT in localStorage with ReactJS?

In most of the modern single page applications, we indeed have to store the token somewhere on the client side (most common use case - to keep the user logged in after a page refresh).

There are a total of 2 options available: Web Storage (session storage, local storage) and a client side cookie. Both options are widely used, but this doesn't mean they are very secure.

Tom Abbott summarizes well the JWT sessionStorage and localStorage security:

Web Storage (localStorage/sessionStorage) is accessible through JavaScript on the same domain. This means that any JavaScript running on your site will have access to web storage, and because of this can be vulnerable to cross-site scripting (XSS) attacks. XSS, in a nutshell, is a type of vulnerability where an attacker can inject JavaScript that will run on your page. Basic XSS attacks attempt to inject JavaScript through form inputs, where the attacker puts <script>alert('You are Hacked');</script> into a form to see if it is run by the browser and can be viewed by other users.

To prevent XSS, the common response is to escape and encode all untrusted data. React (mostly) does that for you! Here's a great discussion about how much XSS vulnerability protection is React responsible for.

But that doesn't cover all possible vulnerabilities! Another potential threat is the usage of JavaScript hosted on CDNs or outside infrastructure.

Here's Tom again:

Modern web apps include 3rd party JavaScript libraries for A/B testing, funnel/market analysis, and ads. We use package managers like Bower to import other peoples’ code into our apps.

What if only one of the scripts you use is compromised? Malicious JavaScript can be embedded on the page, and Web Storage is compromised. These types of XSS attacks can get everyone’s Web Storage that visits your site, without their knowledge. This is probably why a bunch of organizations advise not to store anything of value or trust any information in web storage. This includes session identifiers and tokens.

Therefore, my conclusion is that as a storage mechanism, Web Storage does not enforce any secure standards during transfer. Whoever reads Web Storage and uses it must do their due diligence to ensure they always send the JWT over HTTPS and never HTTP.

Get index of array element faster than O(n)

If your array has a natural order use binary search.

Use binary search.

Binary search has O(log n) access time.

Here are the steps on how to use binary search,

  • What is the ordering of you array? For example, is it sorted by name?
  • Use bsearch to find elements or indices

Code example

# assume array is sorted by name!

array.bsearch { |each| "Jamie" <=> each.name } # returns element
(0..array.size).bsearch { |n| "Jamie" <=> array[n].name } # returns index

How to run php files on my computer

I just put the content in the question in a file called test.php and ran php test.php. (In the folder where the test.php is.)

$ php foo.php                                                                                                                                                                                                                                                                                                                                    
15

How to get current location in Android

First you need to define a LocationListener to handle location changes.

private final LocationListener mLocationListener = new LocationListener() {
    @Override
    public void onLocationChanged(final Location location) {
        //your code here
    }
};

Then get the LocationManager and ask for location updates

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

    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
            LOCATION_REFRESH_DISTANCE, mLocationListener);
}

And finally make sure that you have added the permission on the Manifest,

For using only network based location use this one

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

For GPS based location, this one

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

Convert Iterator to ArrayList

In Java 8, you can use the new forEachRemaining method that's been added to the Iterator interface:

List<Element> list = new ArrayList<>();
iterator.forEachRemaining(list::add);

Angular 4 - Select default value in dropdown [Reactive Forms]

You can use the patch function for setting defaults with some of the values in your form group.

component.html

<form [formGroup]="countryForm">
    <select id="country" formControlName="country">
        <option *ngFor="let c of countries" [ngValue]="c">{{ c }}</option>
    </select>
</form>

component.ts

import { FormControl, FormGroup, Validators } from '@angular/forms';

export class Component implements OnInit{

    countries: string[] = ['USA', 'UK', 'Canada'];
    default: string = 'UK';

    countryForm: FormGroup;

    constructor() {

        this.countryForm.controls['country'].setValue(this.default, {onlySelf: true});
    }
}

ngOnInit() {
    this.countryForm = new FormGroup({
      'country': new FormControl(null)
    }); 

    this.countryForm.patchValue({
      'country': default
    });

  }

Inline JavaScript onclick function

you can use Self-Executing Anonymous Functions. this code will work:

<a href="#" onClick="(function(){
    alert('Hey i am calling');
    return false;
})();return false;">click here</a>

see JSfiddle

jquery, selector for class within id

You can use find() :

$('#my_id').find('my_class');

Or maybe:

$('#my_id').find('span');

Both methods will word for what you want

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

First cast your Edit text like this:

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

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

 myDataBaseHelper.close(); 

Disable all dialog boxes in Excel while running VB script?

Have you tried using the ConflictResolution:=xlLocalSessionChanges parameter in the SaveAs method?

As so:

Public Sub example()
Application.DisplayAlerts = False
Application.EnableEvents = False

For Each element In sArray
    XLSMToXLSX(element)
Next element

Application.DisplayAlerts = False
Application.EnableEvents = False
End Sub

Sub XLSMToXLSX(ByVal file As String)
    Do While WorkFile <> ""
        If Right(WorkFile, 4) <> "xlsx" Then
            Workbooks.Open Filename:=myPath & WorkFile

            Application.DisplayAlerts = False
            Application.EnableEvents = False

            ActiveWorkbook.SaveAs Filename:= _
            modifiedFileName, FileFormat:= _
            xlOpenXMLWorkbook, CreateBackup:=False, _
            ConflictResolution:=xlLocalSessionChanges

            Application.DisplayAlerts = True
            Application.EnableEvents = True

            ActiveWorkbook.Close
        End If
        WorkFile = Dir()
    Loop
End Sub

How should I throw a divide by zero exception in Java without actually dividing by zero?

Something like:

if(divisor == 0) {
  throw new ArithmeticException("Division by zero!");
}

Use PHP to create, edit and delete crontab jobs?

Depends where you store your crontab:

shell_exec('echo "'. $job .'" >> crontab');

What is a vertical tab?

The ASCII vertical tab (\x0B)is still used in some databases and file formats as a new line WITHIN a field. For example:

JOIN queries vs multiple queries

This question is old, but is missing some benchmarks. I benchmarked JOIN against its 2 competitors:

  • N+1 queries
  • 2 queries, the second one using a WHERE IN(...) or equivalent

The result is clear: on MySQL, JOIN is much faster. N+1 queries can drop the performance of an application drastically:

JOIN vs WHERE IN vs N+1

That is, unless you select a lot of records that point to a very small number of distinct, foreign records. Here is a benchmark for the extreme case:

JOIN vs N+1 - all records pointing to the same foreign record

This is very unlikely to happen in a typical application, unless you're joining a -to-many relationship, in which case the foreign key is on the other table, and you're duplicating the main table data many times.

Takeaway:

  • For *-to-one relationships, always use JOIN
  • For *-to-many relationships, a second query might be faster

See my article on Medium for more information.

OpenCV - Saving images to a particular folder of choice

You can do it with OpenCV's function imwrite:

import cv2
cv2.imwrite('Path/Image.jpg', image_name)

Scraping data from website using vba

This question asked long before. But I thought following information will useful for newbies. Actually you can easily get the values from class name like this.

Sub ExtractLastValue()

Set objIE = CreateObject("InternetExplorer.Application")

objIE.Top = 0
objIE.Left = 0
objIE.Width = 800
objIE.Height = 600

objIE.Visible = True

objIE.Navigate ("https://uk.investing.com/rates-bonds/financial-futures/")

Do
DoEvents
Loop Until objIE.readystate = 4

MsgBox objIE.document.getElementsByClassName("pid-8907-last")(0).innerText

End Sub

And if you are new to web scraping please read this blog post.

Web Scraping - Basics

And also there are various techniques to extract data from web pages. This article explain few of them with examples.

Web Scraping - Collecting Data From a Webpage

How to calculate moving average without keeping the count and data-total?

A neat Python solution based on the above answers:

class RunningAverage():
    def __init__(self):
        self.average = 0
        self.n = 0
        
    def __call__(self, new_value):
        self.n += 1
        self.average = (self.average * (self.n-1) + new_value) / self.n 
        
    def __float__(self):
        return self.average
    
    def __repr__(self):
        return "average: " + str(self.average)

usage:

x = RunningAverage()
x(0)
x(2)
x(4)
print(x)

How to determine if a String has non-alphanumeric characters?

If you can use the Apache Commons library, then Commons-Lang StringUtils has a method called isAlphanumeric() that does what you're looking for.

nvarchar(max) still being truncated

Use this PRINT BIG function to output everything:

IF OBJECT_ID('tempdb..#printBig') IS NOT NULL
  DROP PROCEDURE #printBig

GO

CREATE PROCEDURE #printBig (
   @text NVARCHAR(MAX)
 )
AS

--DECLARE @text NVARCHAR(MAX) = 'YourTextHere'
DECLARE @lineSep NVARCHAR(2) = CHAR(13) + CHAR(10)  -- Windows \r\n

DECLARE @off INT = 1
DECLARE @maxLen INT = 4000
DECLARE @len INT

WHILE @off < LEN(@text)
BEGIN

  SELECT @len =
    CASE
      WHEN LEN(@text) - @off - 1 <= @maxLen THEN LEN(@text)
      ELSE @maxLen
             - CHARINDEX(REVERSE(@lineSep),  REVERSE(SUBSTRING(@text, @off, @maxLen)))
             - LEN(@lineSep)
             + 1
    END
  PRINT SUBSTRING(@text, @off, @len)
  --PRINT '@off=' + CAST(@off AS VARCHAR) + ' @len=' + CAST(@len AS VARCHAR)
  SET @off += @len + LEN(@lineSep)

END

Source:

https://www.richardswinbank.net/doku.php?id=tsql:print_big

Removing a non empty directory programmatically in C or C++

If you are using a POSIX compliant OS, you could use nftw() for file tree traversal and remove (removes files or directories). If you are in C++ and your project uses boost, it is not a bad idea to use the Boost.Filesystem as suggested by Manuel.

In the code example below I decided not to traverse symbolic links and mount points (just to avoid a grand removal:) ):

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

static int rmFiles(const char *pathname, const struct stat *sbuf, int type, struct FTW *ftwb)
{
    if(remove(pathname) < 0)
    {
        perror("ERROR: remove");
        return -1;
    }
    return 0;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr,"usage: %s path\n",argv[0]);
        exit(1);
    }

    // Delete the directory and its contents by traversing the tree in reverse order, without crossing mount boundaries and symbolic links

    if (nftw(argv[1], rmFiles,10, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) < 0)
    {
        perror("ERROR: ntfw");
        exit(1);
    }

    return 0;
}

Concatenate a list of pandas dataframes together

You also can do it with functional programming:

from functools import reduce
reduce(lambda df1, df2: df1.merge(df2, "outer"), mydfs)

What exactly is an instance in Java?

I think that Object = Instance. Reference is a "link" to an Object.

Car c = new Car();

variable c stores a reference to an object of type Car.

How do I run a program with commandline arguments using GDB within a Bash script?

You could create a file with context:

run arg1 arg2 arg3 etc

program input

And call gdb like

gdb prog < file

How do I check if there are duplicates in a flat list?

If the list contains unhashable items, you can use Alex Martelli's solution but with a list instead of a set, though it's slower for larger inputs: O(N^2).

def has_duplicates(iterable):
    seen = []
    for x in iterable:
        if x in seen:
            return True
        seen.append(x)
    return False

How to put a jar in classpath in Eclipse?

Right click on the project in which you want to put jar file. A window will open like this

enter image description here

Click on the AddExternal Jars there you can give the path to that jar file

DLL load failed error when importing cv2

Under Winpython : the Winpython-64bit-.../python_.../DLLs directory the file cv2.pyd should be renamed to _cv2.pyd

python pandas remove duplicate columns

Note that Gene Burinsky's answer (at the time of writing the selected answer) keeps the first of each duplicated column. To keep the last:

df=df.loc[:, ~df.columns[::-1].duplicated()[::-1]]

How can I specify a branch/tag when adding a Git submodule?

git submodule add -b develop --name branch-name -- https://branch.git

How to use source: function()... and AJAX in JQuery UI autocomplete

Inside your AJAX callback you need to call the response function; passing the array that contains items to display.

jQuery("input.suggest-user").autocomplete({
    source: function (request, response) {
        jQuery.get("usernames.action", {
            query: request.term
        }, function (data) {
            // assuming data is a JavaScript array such as
            // ["[email protected]", "[email protected]","[email protected]"]
            // and not a string
            response(data);
        });
    },
    minLength: 3
});

If the response JSON does not match the formats accepted by jQuery UI autocomplete then you must transform the result inside the AJAX callback before passing it to the response callback. See this question and the accepted answer.

Javascript objects: get parent

To further iterate on Mik's answer, you could also recursivey attach a parent to all nested objects.

var myApp = {

    init: function() {
        for (var i in this) {
            if (typeof this[i] == 'object') {
                    this[i].init = this.init;
                    this[i].init();
                    this[i].parent = this;
            }
        }
        return this;
    },

    obj1: {
        obj2: {
            notify: function() {
                console.log(this.parent.parent.obj3.msg);
            }
        }
    },

    obj3: {
        msg: 'Hello'
    }

}.init();

myApp.obj1.obj2.notify();

http://jsbin.com/zupepelaciya/1/watch?js,console

Dynamically create an array of strings with malloc

You should assign an array of char pointers, and then, for each pointer assign enough memory for the string:

char **orderedIds;

orderedIds = malloc(variableNumberOfElements * sizeof(char*));
for (int i = 0; i < variableNumberOfElements; i++)
    orderedIds[i] = malloc((ID_LEN+1) * sizeof(char)); // yeah, I know sizeof(char) is 1, but to make it clear...

Seems like a good way to me. Although you perform many mallocs, you clearly assign memory for a specific string, and you can free one block of memory without freeing the whole "string array"

How to create a generic array in Java?

private E a[];
private int size;

public GenSet(int elem)
{
    size = elem;
    a = (E[]) new E[size];
}

How to prevent robots from automatically filling up a form?

Robots cannot execute JavaScript so you do something like injecting some kind of hidden element into the page with JavaScript and then detecting it's presence prior to form submission but beware because some of your users will also have JavaScript disabled

Otherwise I think you will be forced to use a form of client proof of "humanness"

How to get Latitude and Longitude of the mobile device in android?

Use the LocationManager.

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();

The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to the requestLocationUpdates() method instead, which will give you asynchronous updates of your location.

private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        longitude = location.getLongitude();
        latitude = location.getLatitude();
    }
}

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);

You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.

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

You may also want to add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.

How do I make a C++ macro behave like a function?

As others have mentioned, you should avoid macros whenever possible. They are dangerous in the presence of side effects if the macro arguments are evaluated more than once. If you know the type of the arguments (or can use C++0x auto feature), you could use temporaries to enforce single evaluation.

Another problem: the order in which multiple evaluations happen may not be what you expect!

Consider this code:

#include <iostream>
using namespace std;

int foo( int & i ) { return i *= 10; }
int bar( int & i ) { return i *= 100; }

#define BADMACRO( X, Y ) do { \
    cout << "X=" << (X) << ", Y=" << (Y) << ", X+Y=" << ((X)+(Y)) << endl; \
    } while (0)

#define MACRO( X, Y ) do { \
    int x = X; int y = Y; \
    cout << "X=" << x << ", Y=" << y << ", X+Y=" << ( x + y ) << endl; \
    } while (0)

int main() {
    int a = 1; int b = 1;
    BADMACRO( foo(a), bar(b) );
    a = 1; b = 1;
    MACRO( foo(a), bar(b) );
    return 0;
}

And it's output as compiled and run on my machine:

X=100, Y=10000, X+Y=110
X=10, Y=100, X+Y=110

How to get a Fragment to remove itself, i.e. its equivalent of finish()?

You should let the Activity deal with adding and removing Fragments, as CommonsWare says, use a listener. Here is an example:

public class MyActivity extends FragmentActivity implements SuicidalFragmentListener {

    // onCreate etc

    @Override
    public void onFragmentSuicide(String tag) {
        // Check tag if you do this with more than one fragmen, then:
        getSupportFragmentManager().popBackStack();
    }
}

public interface SuicidalFragmentListener {
    void onFragmentSuicide(String tag);
}

public class MyFragment extends Fragment {

    // onCreateView etc

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
           suicideListener = (SuicidalFragmentListener) activity;
        } catch (ClassCastException e) {
           throw new RuntimeException(getActivity().getClass().getSimpleName() + " must implement the suicide listener to use this fragment", e);
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Attach the close listener to whatever action on the fragment you want
        addSuicideTouchListener();
    }

    private void addSuicideTouchListener() {
        getView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              suicideListener.onFragmentSuicide(getTag());
            }
        });
    }
}

How do I count the number of occurrences of a char in a String?

here is a solution without a loop:

public static int countOccurrences(String haystack, char needle, int i){
    return ((i=haystack.indexOf(needle, i)) == -1)?0:1+countOccurrences(haystack, needle, i+1);}


System.out.println("num of dots is "+countOccurrences("a.b.c.d",'.',0));

well, there is a loop, but it is invisible :-)

-- Yonatan

Remove all special characters from a string in R?

You need to use regular expressions to identify the unwanted characters. For the most easily readable code, you want the str_replace_all from the stringr package, though gsub from base R works just as well.

The exact regular expression depends upon what you are trying to do. You could just remove those specific characters that you gave in the question, but it's much easier to remove all punctuation characters.

x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever
str_replace_all(x, "[[:punct:]]", " ")

(The base R equivalent is gsub("[[:punct:]]", " ", x).)

An alternative is to swap out all non-alphanumeric characters.

str_replace_all(x, "[^[:alnum:]]", " ")

Note that the definition of what constitutes a letter or a number or a punctuatution mark varies slightly depending upon your locale, so you may need to experiment a little to get exactly what you want.

How to remove unused C/C++ symbols with GCC and ld?

You can use strip binary on object file(eg. executable) to strip all symbols from it.

Note: it changes file itself and don't create copy.

Java Replace Line In Text File

just how to replace strings :) as i do first arg will be filename second target string third one the string to be replaced instead of targe

public class ReplaceString{
      public static void main(String[] args)throws Exception {
        if(args.length<3)System.exit(0);
        String targetStr = args[1];
        String altStr = args[2];
        java.io.File file = new java.io.File(args[0]);
        java.util.Scanner scanner = new java.util.Scanner(file);
        StringBuilder buffer = new StringBuilder();
        while(scanner.hasNext()){
          buffer.append(scanner.nextLine().replaceAll(targetStr, altStr));
          if(scanner.hasNext())buffer.append("\n");
        }
        scanner.close();
        java.io.PrintWriter printer = new java.io.PrintWriter(file);
        printer.print(buffer);
        printer.close();
      }
    }

What are the use cases for selecting CHAR over VARCHAR in SQL?

I would choose varchar unless the column stores fixed value like US state code -- which is always 2 chars long and the list of valid US states code doesn't change often :).

In every other case, even like storing hashed password (which is fixed length), I would choose varchar.

Why -- char type column is always fulfilled with spaces, which makes for column my_column defined as char(5) with value 'ABC' inside comparation:

my_column = 'ABC' -- my_column stores 'ABC  ' value which is different then 'ABC'

false.

This feature could lead to many irritating bugs during development and makes testing harder.

How do I tell a Python script to use a particular version

For those using pyenv to control their virtual environments, I have found this to work in a script:

#!/home/<user>/.pyenv/versions/<virt_name>/bin/python

DO_STUFF

How do I reverse an int array in Java?

Simple for loop!

for (int start = 0, end = array.length - 1; start <= end; start++, end--) {
    int aux = array[start];
    array[start]=array[end];
    array[end]=aux;
}

How to create range in Swift?

Updated for Swift 4

Swift ranges are more complex than NSRange, and they didn't get any easier in Swift 3. If you want to try to understand the reasoning behind some of this complexity, read this and this. I'll just show you how to create them and when you might use them.

Closed Ranges: a...b

This range operator creates a Swift range which includes both element a and element b, even if b is the maximum possible value for a type (like Int.max). There are two different types of closed ranges: ClosedRange and CountableClosedRange.

1. ClosedRange

The elements of all ranges in Swift are comparable (ie, they conform to the Comparable protocol). That allows you to access the elements in the range from a collection. Here is an example:

let myRange: ClosedRange = 1...3

let myArray = ["a", "b", "c", "d", "e"]
myArray[myRange] // ["b", "c", "d"]

However, a ClosedRange is not countable (ie, it does not conform to the Sequence protocol). That means you can't iterate over the elements with a for loop. For that you need the CountableClosedRange.

2. CountableClosedRange

This is similar to the last one except now the range can also be iterated over.

let myRange: CountableClosedRange = 1...3

let myArray = ["a", "b", "c", "d", "e"]
myArray[myRange] // ["b", "c", "d"]

for index in myRange {
    print(myArray[index])
}

Half-Open Ranges: a..<b

This range operator includes element a but not element b. Like above, there are two different types of half-open ranges: Range and CountableRange.

1. Range

As with ClosedRange, you can access the elements of a collection with a Range. Example:

let myRange: Range = 1..<3

let myArray = ["a", "b", "c", "d", "e"]
myArray[myRange] // ["b", "c"]

Again, though, you cannot iterate over a Range because it is only comparable, not stridable.

2. CountableRange

A CountableRange allows iteration.

let myRange: CountableRange = 1..<3

let myArray = ["a", "b", "c", "d", "e"]
myArray[myRange] // ["b", "c"]

for index in myRange {
    print(myArray[index])
}

NSRange

You can (must) still use NSRange at times in Swift (when making attributed strings, for example), so it is helpful to know how to make one.

let myNSRange = NSRange(location: 3, length: 2)

Note that this is location and length, not start index and end index. The example here is similar in meaning to the Swift range 3..<5. However, since the types are different, they are not interchangeable.

Ranges with Strings

The ... and ..< range operators are a shorthand way of creating ranges. For example:

let myRange = 1..<3

The long hand way to create the same range would be

let myRange = CountableRange<Int>(uncheckedBounds: (lower: 1, upper: 3)) // 1..<3

You can see that the index type here is Int. That doesn't work for String, though, because Strings are made of Characters and not all characters are the same size. (Read this for more info.) An emoji like , for example, takes more space than the letter "b".

Problem with NSRange

Try experimenting with NSRange and an NSString with emoji and you'll see what I mean. Headache.

let myNSRange = NSRange(location: 1, length: 3)

let myNSString: NSString = "abcde"
myNSString.substring(with: myNSRange) // "bcd"

let myNSString2: NSString = "acde"
myNSString2.substring(with: myNSRange) // "c"    Where is the "d"!?

The smiley face takes two UTF-16 code units to store, so it gives the unexpected result of not including the "d".

Swift Solution

Because of this, with Swift Strings you use Range<String.Index>, not Range<Int>. The String Index is calculated based on a particular string so that it knows if there are any emoji or extended grapheme clusters.

Example

var myString = "abcde"
let start = myString.index(myString.startIndex, offsetBy: 1)
let end = myString.index(myString.startIndex, offsetBy: 4)
let myRange = start..<end
myString[myRange] // "bcd"

myString = "acde"
let start2 = myString.index(myString.startIndex, offsetBy: 1)
let end2 = myString.index(myString.startIndex, offsetBy: 4)
let myRange2 = start2..<end2
myString[myRange2] // "cd"

One-sided Ranges: a... and ...b and ..<b

In Swift 4 things were simplified a bit. Whenever the starting or ending point of a range can be inferred, you can leave it off.

Int

You can use one-sided integer ranges to iterate over collections. Here are some examples from the documentation.

// iterate from index 2 to the end of the array
for name in names[2...] {
    print(name)
}

// iterate from the beginning of the array to index 2
for name in names[...2] {
    print(name)
}

// iterate from the beginning of the array up to but not including index 2
for name in names[..<2] {
    print(name)
}

// the range from negative infinity to 5. You can't iterate forward
// over this because the starting point in unknown.
let range = ...5
range.contains(7)   // false
range.contains(4)   // true
range.contains(-1)  // true

// You can iterate over this but it will be an infinate loop 
// so you have to break out at some point.
let range = 5...

String

This also works with String ranges. If you are making a range with str.startIndex or str.endIndex at one end, you can leave it off. The compiler will infer it.

Given

var str = "Hello, playground"
let index = str.index(str.startIndex, offsetBy: 5)

let myRange = ..<index    // Hello

You can go from the index to str.endIndex by using ...

var str = "Hello, playground"
let index = str.index(str.endIndex, offsetBy: -10)
let myRange = index...        // playground

See also:

Notes

  • You can't use a range you created with one string on a different string.
  • As you can see, String ranges are a pain in Swift, but they do make it possibly to deal better with emoji and other Unicode scalars.

Further Study

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

Could you use an insert trigger? If it fails, do an update.

How to serve static files in Flask

What I use (and it's been working great) is a "templates" directory and a "static" directory. I place all my .html files/Flask templates inside the templates directory, and static contains CSS/JS. render_template works fine for generic html files to my knowledge, regardless of the extent at which you used Flask's templating syntax. Below is a sample call in my views.py file.

@app.route('/projects')
def projects():
    return render_template("projects.html", title = 'Projects')

Just make sure you use url_for() when you do want to reference some static file in the separate static directory. You'll probably end up doing this anyways in your CSS/JS file links in html. For instance...

<script src="{{ url_for('static', filename='styles/dist/js/bootstrap.js') }}"></script>

Here's a link to the "canonical" informal Flask tutorial - lots of great tips in here to help you hit the ground running.

http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world

Embed Google Map code in HTML with marker

I would suggest this way, one line iframe. no javascript needed at all. In query ?q=,

_x000D_
_x000D_
<iframe src="http://maps.google.com/maps?q=12.927923,77.627108&z=15&output=embed"></iframe>
_x000D_
_x000D_
_x000D_

How to have multiple colors in a Windows batch file?

If your console supports ANSI colour codes (e.g. ConEmu, Clink or ANSICON) you can do this:

SET    GRAY=%ESC%[0m
SET     RED=%ESC%[1;31m
SET   GREEN=%ESC%[1;32m
SET  ORANGE=%ESC%[0;33m
SET    BLUE=%ESC%[0;34m
SET MAGENTA=%ESC%[0;35m
SET    CYAN=%ESC%[1;36m
SET   WHITE=%ESC%[1;37m

where ESC variable contains ASCII character 27.

I found a way to populate the ESC variable here: http://www.dostips.com/forum/viewtopic.php?p=6827#p6827 and using tasklist it's possible to test what DLLs are loaded into a process.

The following script gets the process ID of the cmd.exe that the script is running in. Checks if it has a dll that will add ANSI support injected, and then sets colour variables to contain escape sequences or be empty depending on whether colour is supported or not.

@echo off

call :INIT_COLORS

echo %RED%RED %GREEN%GREEN %ORANGE%ORANGE %BLUE%BLUE %MAGENTA%MAGENTA %CYAN%CYAN %WHITE%WHITE %GRAY%GRAY

:: pause if double clicked on instead of run from command line.
SET interactive=0
ECHO %CMDCMDLINE% | FINDSTR /L %COMSPEC% >NUL 2>&1
IF %ERRORLEVEL% == 0 SET interactive=1
@rem ECHO %CMDCMDLINE% %COMSPEC% %interactive%
IF "%interactive%"=="1" PAUSE
EXIT /B 0
Goto :EOF

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
: SUBROUTINES                                                          :
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

::::::::::::::::::::::::::::::::
:INIT_COLORS
::::::::::::::::::::::::::::::::

call :supportsANSI
if ERRORLEVEL 1 (
  SET GREEN=
  SET RED=
  SET GRAY=
  SET WHITE=
  SET ORANGE=
  SET CYAN=
) ELSE (

  :: If you can, insert ASCII CHAR 27 after equals and remove BL.String.CreateDEL_ESC routine
  set "ESC="
  :: use this if can't type ESC CHAR, it's more verbose, but you can copy and paste it
  call :BL.String.CreateDEL_ESC

  SET    GRAY=%ESC%[0m
  SET     RED=%ESC%[1;31m
  SET   GREEN=%ESC%[1;32m
  SET  ORANGE=%ESC%[0;33m
  SET    BLUE=%ESC%[0;34m
  SET MAGENTA=%ESC%[0;35m
  SET    CYAN=%ESC%[1;36m
  SET   WHITE=%ESC%[1;37m
)

exit /b

::::::::::::::::::::::::::::::::
:BL.String.CreateDEL_ESC
::::::::::::::::::::::::::::::::
:: http://www.dostips.com/forum/viewtopic.php?t=1733
::
:: Creates two variables with one character DEL=Ascii-08 and ESC=Ascii-27
:: DEL and ESC can be used  with and without DelayedExpansion
setlocal
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
  ENDLOCAL
  set "DEL=%%a"
  set "ESC=%%b"
  goto :EOF
)

::::::::::::::::::::::::::::::::
:supportsANSI
::::::::::::::::::::::::::::::::
:: returns ERRORLEVEL 0 - YES, 1 - NO
::
:: - Tests for ConEmu, ANSICON and Clink
:: - Returns 1 - NO support, when called via "CMD /D" (i.e. no autoruns / DLL injection)
::   on a system that would otherwise support ANSI.

if "%ConEmuANSI%" == "ON" exit /b 0

call :getPID PID

setlocal

for /f usebackq^ delims^=^"^ tokens^=^* %%a in (`tasklist /fi "PID eq %PID%" /m /fo CSV`) do set "MODULES=%%a"

set MODULES=%MODULES:"=%
set NON_ANSI_MODULES=%MODULES%

:: strip out ANSI dlls from module list:
:: ANSICON adds ANSI64.dll or ANSI32.dll
set "NON_ANSI_MODULES=%NON_ANSI_MODULES:ANSI=%"
:: ConEmu attaches ConEmuHk but ConEmu also sets ConEmuANSI Environment VAR
:: so we've already checked for that above and returned early.
@rem set "NON_ANSI_MODULES=%NON_ANSI_MODULES:ConEmuHk=%"
:: Clink supports ANSI https://github.com/mridgers/clink/issues/54
set "NON_ANSI_MODULES=%NON_ANSI_MODULES:clink_dll=%"

if "%MODULES%" == "%NON_ANSI_MODULES%" endlocal & exit /b 1
endlocal

exit /b 0

::::::::::::::::::::::::::::::::
:getPID  [RtnVar]
::::::::::::::::::::::::::::::::
:: REQUIREMENTS:
::
:: Determine the Process ID of the currently executing script,
:: but in a way that is multiple execution safe especially when the script can be executing multiple times
::   - at the exact same time in the same millisecond,
::   - by multiple users,
::   - in multiple window sessions (RDP),
::   - by privileged and non-privileged (e.g. Administrator) accounts,
::   - interactively or in the background.
::   - work when the cmd.exe window cannot appear
::     e.g. running from TaskScheduler as LOCAL SERVICE or using the "Run whether user is logged on or not" setting
::
:: https://social.msdn.microsoft.com/Forums/vstudio/en-US/270f0842-963d-4ed9-b27d-27957628004c/what-is-the-pid-of-the-current-cmdexe?forum=msbuild
::
:: http://serverfault.com/a/654029/306
::
:: Store the Process ID (PID) of the currently running script in environment variable RtnVar.
:: If called without any argument, then simply write the PID to stdout.
::
::
setlocal disableDelayedExpansion
:getLock
set "lock=%temp%\%~nx0.%time::=.%.lock"
set "uid=%lock:\=:b%"
set "uid=%uid:,=:c%"
set "uid=%uid:'=:q%"
set "uid=%uid:_=:u%"
setlocal enableDelayedExpansion
set "uid=!uid:%%=:p!"
endlocal & set "uid=%uid%"
2>nul ( 9>"%lock%" (
  for /f "skip=1" %%A in (
    'wmic process where "name='cmd.exe' and CommandLine like '%%<%uid%>%%'" get ParentProcessID'
  ) do for %%B in (%%A) do set "PID=%%B"
  (call )
))||goto :getLock
del "%lock%" 2>nul
endlocal & if "%~1" equ "" (echo(%PID%) else set "%~1=%PID%"
exit /b

Apache server keeps crashing, "caught SIGTERM, shutting down"

from this page:

I found this info:

The mod_fastcgi process manager isn't particularly patient though (there's room for improvement here) and since it has to shutdown too, sends a SIGTERM to all of the FastCGI applications it is responsible for. Apache will restart the process manager and it will restart its managed applications (as if the server was just started). SIGTERM is, well, SIGTERM - your application should exit quickly.

What this implies to me is that if Database I/O, or some other part of the CGI script, fails to respond in a timely fashion (ie getting slower with data-volume growth), that mod_fastcgi is killing the script......is that how other people interpret these docs or what am I missing..

Search for one value in any column of any table inside a database

There is a nice script available on http://www.reddyss.com/SQLDownloads.aspx

To be able to use it on any database you can create it like in: http://nickstips.wordpress.com/2010/10/18/sql-making-a-stored-procedure-available-to-all-databases/

Not sure if there is other way.

To use it then use something like this:

use name_of_database

EXEC spUtil_SearchText 'value_searched', 0, 0

PHP - find entry by object property from an array of objects

Try

$entry = current(array_filter($array, function($e) use($v){ return $e->ID==$v; }));

working example here

How do I install a module globally using npm?

You need to have superuser privileges,

 sudo npm install -g <package name>

Print very long string completely in pandas dataframe

Is this what you meant to do ?

In [7]: x =  pd.DataFrame({'one' : ['one', 'two', 'This is very long string very long string very long string veryvery long string']})

In [8]: x
Out[8]: 
                                                 one
0                                                one
1                                                two
2  This is very long string very long string very...

In [9]: x['one'][2]
Out[9]: 'This is very long string very long string very long string veryvery long string'

Set environment variables from file of key/value pairs

Simpler:

  1. grab the content of the file
  2. remove any blank lines (just incase you separated some stuff)
  3. remove any comments (just incase you added some...)
  4. add export to all the lines
  5. eval the whole thing

eval $(cat .env | sed -e /^$/d -e /^#/d -e 's/^/export /')

Another option (you don't have to run eval (thanks to @Jaydeep)):

export $(cat .env | sed -e /^$/d -e /^#/d | xargs)

Lastly, if you want to make your life REALLY easy, add this to your ~/.bash_profile:

function source_envfile() { export $(cat $1 | sed -e /^$/d -e /^#/d | xargs); }

(MAKE SURE YOU RELOAD YOUR BASH SETTINGS!!! source ~/.bash_profile or.. just make a new tab/window and problem solved) you call it like this: source_envfile .env

Pandas get the most frequent values of a column

Here's one way:

df['name'].value_counts()[df['name'].value_counts() == df['name'].value_counts().max()]

which prints:

helen    2
alex     2
Name: name, dtype: int64

How to secure an ASP.NET Web API

If you want to secure your API in a server to server fashion (no redirection to website for 2 legged authentication). You can look at OAuth2 Client Credentials Grant protocol.

https://dev.twitter.com/docs/auth/application-only-auth

I have developed a library that can help you easily add this kind of support to your WebAPI. You can install it as a NuGet package:

https://nuget.org/packages/OAuth2ClientCredentialsGrant/1.0.0.0

The library targets .NET Framework 4.5.

Once you add the package to your project, it will create a readme file in the root of your project. You can look at that readme file to see how to configure/use this package.

Cheers!

How do I Validate the File Type of a File Upload?

Your only option seems to be client-side validation, because server side means the file was already uploaded. Also the MIME type is usually dictated by the file extension.

use a JavaScript Framework like jQuery to overload the onsubmit event of the form. Then check the extension. This will limit most attempts. However if a person changes an image to extension XLS then you will have a problem.

I don't know if this is an option for you, but you have more client side control when using something like Silverlight or Flash to upload. You may consider using one of these technologies for your upload process.

where to place CASE WHEN column IS NULL in this query

Not able to understand your actual problem but your case statement is incorrect

CASE 
WHEN 
TABLE3.COL3 IS NULL
THEN TABLE2.COL3
ELSE
TABLE3.COL3
END 
AS
COL4

deleting rows in numpy array

The simplest way to delete rows and columns from arrays is the numpy.delete method.

Suppose I have the following array x:

x = array([[1,2,3],
        [4,5,6],
        [7,8,9]])

To delete the first row, do this:

x = numpy.delete(x, (0), axis=0)

To delete the third column, do this:

x = numpy.delete(x,(2), axis=1)

So you could find the indices of the rows which have a 0 in them, put them in a list or a tuple and pass this as the second argument of the function.

Add an index (numeric ID) column to large data frame

Using alternative dplyr package:

library("dplyr") # or library("tidyverse")

df <- df %>% mutate(id = row_number())

non static method cannot be referenced from a static context

Violating the Java naming conventions (variable names and method names start with lowercase, class names start with uppercase) is contributing to your confusion.

The variable Random is only "in scope" inside the main method. It's not accessible to any methods called by main. When you return from main, the variable disappears (it's part of the stack frame).

If you want all of the methods of your class to use the same Random instance, declare a member variable:

class MyObj {
  private final Random random = new Random();
  public void compTurn() {
    while (true) {
      int a = random.nextInt(10);
      if (possibles[a] == 1) 
        break;
    }
  }
}

Inconsistent accessibility: property type is less accessible

Your Delivery class is internal (the default visibility for classes), however the property (and presumably the containing class) are public, so the property is more accessible than the Delivery class. You need to either make Delivery public, or restrict the visibility of the thelivery property.

Go build: "Cannot find package" (even though GOPATH is set)

Have you tried adding the absolute directory of go to your 'path'?

export PATH=$PATH:/directory/to/go/

How can I get table names from an MS Access Database?

Best not to mess with msysObjects (IMHO).

CurrentDB.TableDefs
CurrentDB.QueryDefs
CurrentProject.AllForms
CurrentProject.AllReports
CurrentProject.AllMacros

How does java do modulus calculations with negative numbers?

Your result is wrong for Java. Please provide some context how you arrived at it (your program, implementation and version of Java).

From the Java Language Specification

15.17.3 Remainder Operator %
[...]
The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a.
15.17.2 Division Operator /
[...]
Integer division rounds toward 0.

Since / is rounded towards zero (resulting in zero), the result of % should be negative in this case.

Combining C++ and C - how does #ifdef __cplusplus work?

A couple of gotchas that are colloraries to Andrew Shelansky's excellent answer and to disagree a little with doesn't really change the way that the compiler reads the code

Because your function prototypes are compiled as C, you can't have overloading of the same function names with different parameters - that's one of the key features of the name mangling of the compiler. It is described as a linkage issue but that is not quite true - you will get errors from both the compiler and the linker.

The compiler errors will be if you try to use C++ features of prototype declaration such as overloading.

The linker errors will occur later because your function will appear to not be found, if you do not have the extern "C" wrapper around declarations and the header is included in a mixture of C and C++ source.

One reason to discourage people from using the compile C as C++ setting is because this means their source code is no longer portable. That setting is a project setting and so if a .c file is dropped into another project, it will not be compiled as c++. I would rather people take the time to rename file suffixes to .cpp.

Fetch: POST json data

The top answer doesn't work for PHP7, because it has wrong encoding, but I could figure the right encoding out with the other answers. This code also sends authentication cookies, which you probably want when dealing with e.g. PHP forums:

julia = function(juliacode) {
    fetch('julia.php', {
        method: "POST",
        credentials: "include", // send cookies
        headers: {
            'Accept': 'application/json, text/plain, */*',
            //'Content-Type': 'application/json'
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" // otherwise $_POST is empty
        },
        body: "juliacode=" + encodeURIComponent(juliacode)
    })
    .then(function(response) {
        return response.json(); // .text();
    })
    .then(function(myJson) {
        console.log(myJson);
    });
}

SQL Server equivalent to MySQL enum data type?

Found this interesting approach when I wanted to implement enums in SQL Server.

The approach mentioned below in the link is quite compelling, considering all your database enum needs could be satisfied with 2 central tables.

http://blog.sqlauthority.com/2010/03/22/sql-server-enumerations-in-relational-database-best-practice/

formGroup expects a FormGroup instance

I had this error when I had specified fromGroupName instead of formArrayName.

Make sure you correctly specify if it is a form array or form group.

<div formGroupName="formInfo"/>

<div formArrayName="formInfo"/>

How to get the correct range to set the value to a cell?

Use setValue method of Range class to set the value of particular cell.

function storeValue() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  // ss is now the spreadsheet the script is associated with
  var sheet = ss.getSheets()[0]; // sheets are counted starting from 0
  // sheet is the first worksheet in the spreadsheet
  var cell = sheet.getRange("B2"); 
  cell.setValue(100);
}

You can also select a cell using row and column numbers.

var cell = sheet.getRange(2, 3); // here cell is C2

It's also possible to set value of multiple cells at once.

var values = [
  ["2.000", "1,000,000", "$2.99"]
];

var range = sheet.getRange("B2:D2");
range.setValues(values);

Richtextbox wpf binding

Guys why bother with all the faff. This works perfectly. No code required

<RichTextBox>
    <FlowDocument>
        <Paragraph>
            <Run Text="{Binding Mytextbinding}"/>
        </Paragraph>
    </FlowDocument>
</RichTextBox>

How to dynamically allocate memory space for a string and get that string from user?

This is a function snippet I wrote to scan the user input for a string and then store that string on an array of the same size as the user input. Note that I initialize j to the value of 2 to be able to store the '\0' character.

char* dynamicstring() {
    char *str = NULL;
    int i = 0, j = 2, c;
    str = (char*)malloc(sizeof(char));
    //error checking
    if (str == NULL) {
        printf("Error allocating memory\n");
        exit(EXIT_FAILURE);
    }

    while((c = getc(stdin)) && c != '\n')
    {
        str[i] = c;
        str = realloc(str,j*sizeof(char));
        //error checking
        if (str == NULL) {
            printf("Error allocating memory\n");
            free(str);
            exit(EXIT_FAILURE);
        }

        i++;
        j++;
    }
    str[i] = '\0';
    return str;
}

In main(), you can declare another char* variable to store the return value of dynamicstring() and then free that char* variable when you're done using it.

Explaining Apache ZooKeeper

My approach to understand zookeeper was, to play around with the CLI client. as described in Getting Started Guide and Command line interface

From this I learned that zookeeper's surface looks very similar to a filesystem and clients can create and delete objects and read or write data.

Example CLI commands

create /myfirstnode mydata
ls /
get /myfirstnode
delete /myfirstnode

Try yourself

How to spin up a zookeper environment within minutes on docker for windows, linux or mac:

One time set up:

docker network create dn

Run server in a terminal window:

docker run --network dn --name zook -d zookeeper
docker logs -f zookeeper

Run client in a second terminal window:

docker run -it --rm --network dn zookeeper zkCli.sh -server zook

See also documentation of image on dockerhub

How to randomly select an item from a list?

This may already be an answer but you could use random.shuffle. Example:

import random
foo = ['a', 'b', 'c', 'd', 'e']
random.shuffle(foo)

Convert an integer to a float number

There is no float type. Looks like you want float64. You could also use float32 if you only need a single-precision floating point value.

package main

import "fmt"

func main() {
    i := 5
    f := float64(i)
    fmt.Printf("f is %f\n", f)
}

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

I've found out a nice workaround to IP blocking when scraping sites. It lets you run a Scraper indefinitely by running it from Google App Engine and redeploying it automatically when you get a 429.

Check out this article

Eclipse CDT project built but "Launch Failed. Binary Not Found"

My experience is that after building your project (CTRL+B), you need to create a run (or debug) configuration in the Run or Debug dropdown menu from the main toolbar. Then in the main page, click the

Search Project...

button.

This will find all executable files you have built and show them in a dialog box. You can choose the right one and then hit the Run (or

How to display text in pygame?

There's also the pygame.freetype module which is more modern, works with more fonts and offers additional functionality.

Create a font object with pygame.freetype.SysFont() or pygame.freetype.Font if the font is inside of your game directory.

You can render the text either with the render method similarly to the old pygame.font.Font.render or directly onto the target surface with render_to.

import pygame
import pygame.freetype  # Import the freetype module.


pygame.init()
screen = pygame.display.set_mode((800, 600))
GAME_FONT = pygame.freetype.Font("your_font.ttf", 24)
running =  True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((255,255,255))
    # You can use `render` and then blit the text surface ...
    text_surface, rect = GAME_FONT.render("Hello World!", (0, 0, 0))
    screen.blit(text_surface, (40, 250))
    # or just `render_to` the target surface.
    GAME_FONT.render_to(screen, (40, 350), "Hello World!", (0, 0, 0))

    pygame.display.flip()

pygame.quit()

Check that an email address is valid on iOS

Good cocoa function:

-(BOOL) NSStringIsValidEmail:(NSString *)checkString
{
   BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
   NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
   NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
   NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
   NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
   return [emailTest evaluateWithObject:checkString];
}

Discussion on Lax vs. Strict - http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/

And because categories are just better, you could also add an interface:

@interface NSString (emailValidation) 
  - (BOOL)isValidEmail;
@end

Implement

@implementation NSString (emailValidation)
-(BOOL)isValidEmail
{
  BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
  NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
  NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
  NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
  NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
  return [emailTest evaluateWithObject:self];
}
@end

And then utilize:

if([@"[email protected]" isValidEmail]) { /* True */ }
if([@"InvalidEmail@notreallyemailbecausenosuffix" isValidEmail]) { /* False */ }

How to change the background-color of jumbrotron?

Try this:

<div style="background:transparent !important" class="jumbotron">
    <h1>Welcome!</h1>
    <p>We're an awesome company that creates virtual things for portable devices.</p>
    <p><a class="btn btn-primary btn-lg" role="button">Learn more</a></p>
</div>

Inline CSS gets preference over classes defined in a .css file and the classes declared inside <style>

Adding a regression line on a ggplot

In general, to provide your own formula you should use arguments x and y that will correspond to values you provided in ggplot() - in this case x will be interpreted as x.plot and y as y.plot. You can find more information about smoothing methods and formula via the help page of function stat_smooth() as it is the default stat used by geom_smooth().

ggplot(data,aes(x.plot, y.plot)) +
  stat_summary(fun.data=mean_cl_normal) + 
  geom_smooth(method='lm', formula= y~x)

If you are using the same x and y values that you supplied in the ggplot() call and need to plot the linear regression line then you don't need to use the formula inside geom_smooth(), just supply the method="lm".

ggplot(data,aes(x.plot, y.plot)) +
  stat_summary(fun.data= mean_cl_normal) + 
  geom_smooth(method='lm')

How to rename with prefix/suffix?

I've seen people mention a rename command, but it is not routinely available on Unix systems (as opposed to Linux systems, say, or Cygwin - on both of which, rename is an executable rather than a script). That version of rename has a fairly limited functionality:

rename from to file ...

It replaces the from part of the file names with the to, and the example given in the man page is:

rename foo foo0 foo? foo??

This renames foo1 to foo01, and foo10 to foo010, etc.

I use a Perl script called rename, which I originally dug out from the first edition Camel book, circa 1992, and then extended, to rename files.

#!/bin/perl -w
#
# @(#)$Id: rename.pl,v 1.7 2008/02/16 07:53:08 jleffler Exp $
#
# Rename files using a Perl substitute or transliterate command

use strict;
use Getopt::Std;

my(%opts);
my($usage) = "Usage: $0 [-fnxV] perlexpr [filenames]\n";
my($force) = 0;
my($noexc) = 0;
my($trace) = 0;

die $usage unless getopts('fnxV', \%opts);

if ($opts{V})
{
    printf "%s\n", q'RENAME Version $Revision: 1.7 $ ($Date: 2008/02/16 07:53:08 $)';
    exit 0;
}
$force = 1 if ($opts{f});
$noexc = 1 if ($opts{n});
$trace = 1 if ($opts{x});

my($op) = shift;
die $usage unless defined $op;

if (!@ARGV) {
    @ARGV = <STDIN>;
    chop(@ARGV);
}

for (@ARGV)
{
    if (-e $_ || -l $_)
    {
        my($was) = $_;
        eval $op;
        die $@ if $@;
        next if ($was eq $_);
        if ($force == 0 && -f $_)
        {
            print STDERR "rename failed: $was - $_ exists\n";
        }
        else
        {
            print "+ $was --> $_\n" if $trace;
            print STDERR "rename failed: $was - $!\n"
                unless ($noexc || rename($was, $_));
        }
    }
    else
    {
        print STDERR "$_ - $!\n";
    }
}

This allows you to write any Perl substitute or transliterate command to map file names. In the specific example requested, you'd use:

rename 's/^/new./' original.filename

Is there a way to take a screenshot using Java and save it to some sort of image?

Believe it or not, you can actually use java.awt.Robot to "create an image containing pixels read from the screen." You can then write that image to a file on disk.

I just tried it, and the whole thing ends up like:

Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "bmp", new File(args[0]));

NOTE: This will only capture the primary monitor. See GraphicsConfiguration for multi-monitor support.

CSS background image in :after element

As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:

background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;

Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).

No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.

How do I get the path to the current script with Node.js?

Use the basename method of the path module:

var path = require('path');
var filename = path.basename(__filename);
console.log(filename);

Here is the documentation the above example is taken from.

As Dan pointed out, Node is working on ECMAScript modules with the "--experimental-modules" flag. Node 12 still supports __dirname and __filename as above.


If you are using the --experimental-modules flag, there is an alternative approach.

The alternative is to get the path to the current ES module:

const __filename = new URL(import.meta.url).pathname;

And for the directory containing the current module:

import path from 'path';

const __dirname = path.dirname(new URL(import.meta.url).pathname);

There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key

You need either

  • A unique index on Title in BookTitle
  • An ISBN column in BookCopy and the FK is on both columns

A foreign key needs to uniquely identify the parent row: you currently have no way to do that because Title is not unique.

How do I remove background-image in css?

div#a {
  background-image: none !important;
}

Although the "!important" might not be necessary, because "div#a" has a higher specificity than just "div".

How to open local file on Jupyter?

I would suggest you to test it firstly: copy this train.csv to the same directory as this jupyter script in and then change the path to train.csv to test whether this can be loaded successfully.

If yes, that means the previous path input is a problem

If not, that means the file it self denied your access to it, or its real filename can be something else like: train.csv.<hidden extension>

Converting an integer to a string in PHP

Use:

$intValue = 1;
$string = sprintf('%d', $intValue);

Or it could be:

$string = (string)$intValue;

Or:

settype(&$intValue, 'string');

Write a file in external storage in Android

Supplemental Answer

After writing to external storage, some file managers don't see the file right away. This can be confusing if a user thinks they copied something to the SD card, but then can't find it there. So after you copy the file, run the following code to notify file managers of its presence.

MediaScannerConnection.scanFile(
        context,
        new String[]{myFile.getAbsolutePath()},
        null,
        null);

See the documentation and this answer for more.

Mac OS X - EnvironmentError: mysql_config not found

This answer is for MacOS users who did not install from brew but rather from the official .dmg/.pkg. That installer fails to edit your PATH, causing things to break out of the box:

  1. All MySQL commands like mysql, mysqladmin, mysql_config, etc cannot be found, and as a result:
  2. the "MySQL Preference Pane" fails to appear in System Preferences, and
  3. you cannot install any API that communicates with MySQL, including mysqlclient

What you have to do is appending the MySQL bin folder (typically /usr/local/mysql/bin in your PATH by adding this line in your ~/.bash_profile file:

export PATH="/usr/local/mysql/bin/:$PATH"

You should then reload your ~/.bash_profile for the change to take effect in your current Terminal session:

source ~/.bash_profile

Before installing mysqlclient, however, you need to accept the XcodeBuild license:

sudo xcodebuild -license

Follow their directions to sign away your family, after which you should be able to install mysqlclient without issue:

pip install mysqlclient

After installing that, you must do one more thing to fix a runtime bug that ships with MySQL (Dynamic Library libmysqlclient.dylib not found), by adding this line to your system dynamic libraries path:

export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/:$DYLD_LIBRARY_PATH

How to download files using axios

My answer is a total hack- I just created a link that looks like a button and add the URL to that.

<a class="el-button"
  style="color: white; background-color: #58B7FF;"
  :href="<YOUR URL ENDPOINT HERE>"
  :download="<FILE NAME NERE>">
<i class="fa fa-file-excel-o"></i>&nbsp;Excel
</a>

I'm using the excellent VueJs hence the odd anotations, however, this solution is framework agnostic. The idea would work for any HTML based design.

How to expand textarea width to 100% of parent (or how to expand any HTML element to 100% of parent width)?

_x000D_
_x000D_
<div>_x000D_
  <div style="width: 20%; float: left;">_x000D_
    <p>Some Contentsssssssssss</p>_x000D_
  </div>_x000D_
  <div style="float: left; width: 80%;">_x000D_
    <textarea style="width: 100%; max-width: 100%;"></textarea>_x000D_
  </div>_x000D_
  <div style="clear: both;"></div>_x000D_
</div>_x000D_
_x000D_
 
_x000D_
_x000D_
_x000D_

Superscript in Python plots

Alternatively, in python 3.6+, you can generate Unicode superscript and copy paste that in your code:

ax1.set_ylabel('Rate (min?¹)')

FIFO based Queue implementations?

A LinkedList can be used as a Queue - but you need to use it right. Here is an example code :

@Test
public void testQueue() {
    LinkedList<Integer> queue = new LinkedList<>();
    queue.add(1);
    queue.add(2);
    System.out.println(queue.pop());
    System.out.println(queue.pop());
}

Output :

1
2

Remember, if you use push instead of add ( which you will very likely do intuitively ), this will add element at the front of the list, making it behave like a stack.

So this is a Queue only if used in conjunction with add.

Try this :

@Test
public void testQueue() {
    LinkedList<Integer> queue = new LinkedList<>();
    queue.push(1);
    queue.push(2);
    System.out.println(queue.pop());
    System.out.println(queue.pop());
}

Output :

2
1

Android - How to achieve setOnClickListener in Kotlin?

Suppose you have textView to click

text_view.text = "Hello Kotlin";

text_view.setOnClickListener {
    val intent = Intent(this@MainActivity, SecondActivity::class.java)
    intent.putExtra("key", "Kotlin")
    startActivity(intent)
}

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

Example query: SELECT TO_CHAR(TO_DATE('2017-08-23','YYYY-MM-DD'), 'MM/DD/YYYY') FROM dual;

How do I simulate a low bandwidth, high latency environment?

For Windows you can use this application: http://www.softperfect.com/products/connectionemulator/

WAN Connection Emulator for Windows 2000, XP, 2003, Vista, Seven and 2008.

Perhaps the only one available for Windows.

What does git push -u mean?

"Upstream" would refer to the main repo that other people will be pulling from, e.g. your GitHub repo. The -u option automatically sets that upstream for you, linking your repo to a central one. That way, in the future, Git "knows" where you want to push to and where you want to pull from, so you can use git pull or git push without arguments. A little bit down, this article explains and demonstrates this concept.

How to remove rows with any zero value

I prefer a simple adaptation of csgillespie's method, foregoing the need of a function definition:

d[apply(d!=0, 1, all),]

where d is your data frame.

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

For me the problem was with my targets tests. I already had the $(inherited) flag in my main app target.

I added it to MyAppTests Other Linker flags. After that when I ran pod install the warning message was gone. enter image description here

Most efficient way to prepend a value to an array

Example of prepending in-place:

_x000D_
_x000D_
var A = [7,8,9]_x000D_
var B = [1,2,3]_x000D_
_x000D_
A.unshift(...B)_x000D_
_x000D_
console.log(A) // [1,2,3,7,8,9]
_x000D_
_x000D_
_x000D_

"SyntaxError: Unexpected token < in JSON at position 0"

I experienced this error "SyntaxError: Unexpected token m in JSON at position", where the token 'm' can be any other characters.

It turned out that I missed one of the double quotes in the JSON object when I was using RESTconsole for DB test, as {"name: "math"}, the correct one should be {"name": "math"}

It took me a lot effort to figure out this clumsy mistake. I am afraid others would run into similar bummers.

String formatting in Python 3

That line works as-is in Python 3.

>>> sys.version
'3.2 (r32:88445, Oct 20 2012, 14:09:29) \n[GCC 4.5.2]'
>>> "(%d goals, $%d)" % (self.goals, self.penalties)
'(1 goals, $2)'

Showing alert in angularjs when user leaves a page

The code for the confirmation dialogue can be written shorter this way:

$scope.$on('$locationChangeStart', function( event ) {
    var answer = confirm("Are you sure you want to leave this page?")
    if (!answer) {
        event.preventDefault();
    }
});

Matplotlib-Animation "No MovieWriters Available"

(be sure to follow JPH feedback above about the proper ffmpeg download) Not sure why, but in my case here is the one that worked (in my case was on windows).

Initialize a writer:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
Writer = animation.FFMpegWriter(fps=30, codec='libx264')  #or 
Writer = animation.FFMpegWriter(fps=20, metadata=dict(artist='Me'), bitrate=1800) ==> This is WORKED FINE ^_^

Writer = animation.writers['ffmpeg'] ==> GIVES ERROR ""RuntimeError: Requested MovieWriter (ffmpeg) not available""

What does ==$0 (double equals dollar zero) mean in Chrome Developer Tools?

This is Chrome's hint to tell you that if you type $0 on the console, it will be equivalent to that specific element.

Internally, Chrome maintains a stack, where $0 is the selected element, $1 is the element that was last selected, $2 would be the one that was selected before $1 and so on.

Here are some of its applications:

  • Accessing DOM elements from console: $0
  • Accessing their properties from console: $0.parentElement
  • Updating their properties from console: $1.classList.add(...)
  • Updating CSS elements from console: $0.styles.backgroundColor="aqua"
  • Triggering CSS events from console: $0.click()
  • And doing a lot more complex stuffs, like: $0.appendChild(document.createElement("div"))

Watch all of this in action:

enter image description here

Backing statement:

Yes, I agree there are better ways to perform these actions, but this feature can come out handy in certain intricate scenarios, like when a DOM element needs to be clicked but it is not possible to do so from the UI because it is covered by other elements or, for some reason, is not visible on UI at that moment.

Crop image in PHP

$image = imagecreatefromjpeg($_GET['src']);

Needs to be replaced with this:

$image = imagecreatefromjpeg('images/thumbnails/myimage.jpg');

Because imagecreatefromjpeg() is expecting a string.
This worked for me.

ref:
http://php.net/manual/en/function.imagecreatefromjpeg.php

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Git is a version control system; think of it as a series of snapshots (commits) of your code. You see a path of these snapshots, in which order they where created. You can make branches to experiment and come back to snapshots you took.

    GitHub, is a web-page on which you can publish your Git repositories and collaborate with other people.

  2. Is Git saving every repository locally (in the user's machine) and in GitHub?

    No, it's only local. You can decide to push (publish) some branches on GitHub.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    Yes, Git runs local if you don't use GitHub. An alternative to using GitHub could be running Git on files hosted on Dropbox, but GitHub is a more streamlined service as it was made especially for Git.

  4. How does Git compare to a backup system such as Time Machine?

    It's a different thing, Git lets you track changes and your development process. If you use Git with GitHub, it becomes effectively a backup. However usually you would not push all the time to GitHub, at which point you do not have a full backup if things go wrong. I use git in a folder that is synchronized with Dropbox.

  5. Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?

    Yes, committing and pushing are both manual.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    • If you encounter an error between commits you can use the command git diff to see the differences between the current code and the last working commit, helping you to locate your error.

    • You can also just go back to the last working commit.

    • If you want to try a change, but are not sure that it will work. You create a branch to test you code change. If it works fine, you merge it to the main branch. If it does not you just throw the branch away and go back to the main branch.

    • You did some debugging. Before you commit you always look at the changes from the last commit. You see your debug print statement that you forgot to delete.

Make sure you check gitimmersion.com.

What is a serialVersionUID and why should I use it?

Why use SerialVersionUID inside Serializable class in Java?

During serialization, Java runtime creates a version number for a class, so that it can de-serialize it later. This version number is known as SerialVersionUID in Java.

SerialVersionUID is used to version serialized data. You can only de-serialize a class if it's SerialVersionUID matches with the serialized instance. When we don't declare SerialVersionUID in our class, Java runtime generates it for us but its not recommended. It's recommended to declare SerialVersionUID as private static final long variable to avoid default mechanism.

When you declare a class as Serializable by implementing marker interface java.io.Serializable, Java runtime persist instance of that class into disk by using default Serialization mechanism, provided you have not customized the process using Externalizable interface.

see also Why use SerialVersionUID inside Serializable class in Java

How to center a (background) image within a div?

#doit {
    background: url(url) no-repeat center;
}

How to display Oracle schema size with SQL query?

You probably want

SELECT sum(bytes)
  FROM dba_segments
 WHERE owner = <<owner of schema>>

If you are logged in as the schema owner, you can also

SELECT SUM(bytes)
  FROM user_segments

That will give you the space allocated to the objects owned by the user in whatever tablespaces they are in. There may be empty space allocated to the tables that is counted as allocated by these queries.

SonarQube Exclude a directory

If you're an Azure DevOps user looking for both where and how to exclude files and folders, here ya go:

  1. Edit your pipeline
  2. Make sure you have the "Prepare analysis on SonarQube" task added. You'll need to look elsewhere if you need help configuring this. Suggestion: Use the UI pipeline editor vs the yaml editor if you are missing the manage link. At present, there is no way to convert to UI from yaml. Just recreate the pipeline. If using git, you can delete the yaml from the root of your repo.
  3. Under the 'Advanced' section of the "Prepare analysis on SonarQube" task, you can add exclusions. See advice given by others for specific exclusion formats.

Example:

# Additional properties that will be passed to the scanner, 
# Put one key=value per line, example:
# sonar.exclusions=**/*.bin
sonar.exclusions=MyProjectName/MyWebContentFolder/**

Note: If you're not sure on the path, you can go into sonarqube, view your project, look at all or new 'Code Smells' and the path you need is listed above each grouping of issues. You can grab the full path to a file or use wilds like these examples:

  • MyProjectName/MyCodeFile.cs
  • MyProjectName/**

If you don't have the 'Run Code Analysis' task added, do that and place it somewhere after the 'Build solution **/*.sln' task.

Save and Queue and then check out your sonarqube server to see if the exclusions worked.

Get free disk space

I was looking for the size in GB, so I just improved the code from Superman above with the following changes:

public double GetTotalHDDSize(string driveName)
{
    foreach (DriveInfo drive in DriveInfo.GetDrives())
    {
        if (drive.IsReady && drive.Name == driveName)
        {
            return drive.TotalSize / (1024 * 1024 * 1024);
        }
    }
    return -1;
}

How do I to insert data into an SQL table using C# as well as implement an upload function?

You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--' as one of the values.

string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief,  ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
query += " VALUES (@ArticleTitle, @ArticleContent, @ArticleType, @ArticleImg, @ArticleBrief, @ArticleDateTime, @ArticleAuthor, @ArticlePublished, @ArticleHomeDisplay, @ArticleViews)";

SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@ArticleTitle", ArticleTitleTextBox.Text);
myCommand.Parameters.AddWithValue("@ArticleContent", ArticleContentTextBox.Text);
// ... other parameters
myCommand.ExecuteNonQuery();

Exploits of a Mom

(xkcd)

Java : Sort integer array without using Arrays.sort()

Here is one simple solution

public static void main(String[] args) {        
        //Without using Arrays.sort function
        int i;
        int nos[] = {12,9,-4,-1,3,10,34,12,11};
        System.out.print("Values before sorting: \n");
        for(i = 0; i < nos.length; i++)
            System.out.println( nos[i]+"  ");               
        sort(nos, nos.length);
        System.out.print("Values after sorting: \n");       
        for(i = 0; i <nos.length; i++){
            System.out.println(nos[i]+"  ");
        }
    }

    private static void sort(int nos[], int n) {
     for (int i = 1; i < n; i++){
          int j = i;
          int B = nos[i];
          while ((j > 0) && (nos[j-1] > B)){
            nos[j] = nos[j-1];
            j--;
          }
          nos[j] = B;
        }
    }

And the output is:

Values before sorting:

12
9
-4
-1
3
10
34
12
11

Values after sorting:

-4
-1
3
9
10
11
12
12
34

"Could not find bundler" error

I had the same problem. This worked for me:

  1. run rvm/script/rvm and also add it to your .profile or .bash_profile as shown in https://rvm.io/rvm/install/

  2. use bundle without sudo

Error message "Linter pylint is not installed"

I also had this problem. If you also have Visual Studio installed with the Python extension, the system will want to use Studio's version of Python. Set the Environment Path to the version in Studio's Shared folder. For me, that was:

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\

After that, run

python -m pip install pylint

from a command prompt with Administrator rights.

How do I limit the number of returned items?

models.Post.find({published: true}, {sort: {'date': -1}, limit: 20}, function(err, posts) {
 // `posts` with sorted length of 20
});

Any good, visual HTML5 Editor or IDE?

Update

Use Aptana Studio 3, it's upgraded now.

You can either choose

Try online Aloha WYSIWYG Editor

But as a web-developer, I still prefer Notepad++, it has necessary code assists.


Outdated info, please don't refer.


This might be late answer, yeah very late answer, but surely will help someone
Download "Eclipse IDE for Java EE Developers" Latest Stable Version

Download Google Plugin for Eclipse.zip
Select your download according to your Eclipse Version
After Downloading (don't Unzip)
Open Eclipse
Help > Install New Software > Add > Archive > Select the Downloaded Plug-in.zip
in the field "Name" enter "Google Plugin" Click ok.

Ignore the Warnings, After Competion of Installation, Restart Eclipse.


How to use Google Plugin for Eclipse
    File > New > Other > Web > Static Web Project > Enter Project name

Create New Web Project


    Create New HTML File

Create New HTML File


    Name to index.html

index.html

    Select Properties of HTML File

Set Properties to HTML5

    Hit Ctrl+Space

Cheat Sheet HTML5

similarly create new *.css file
Right Click on the css file > Properties > Web Content Settings > Select CSS3 Profile > ok
Hit CTRL+Space
CSS3 Cheat Sheet
Wooo, Yeah Start Coding.!

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

With C#6.0 you also have a new way of formatting date when using string interpolation e.g.

$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"

Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.

More about string interpolation.

How to find the socket connection state in C?

you can use SS_ISCONNECTED macro in getsockopt() function. SS_ISCONNECTED is define in socketvar.h.

What should a JSON service return on failure / error

See this question for some insight into best-practices for your situation.

The topline suggestion (from said link) is to standardize a response structure (for both success and failure) that your handler looks for, catching all Exceptions at the server layer and converting them to the same structure. For example (from this answer):

{
    success:false,
    general_message:"You have reached your max number of Foos for the day",
    errors: {
        last_name:"This field is required",
        mrn:"Either SSN or MRN must be entered",
        zipcode:"996852 is not in Bernalillo county. Only Bernalillo residents are eligible"
    }
} 

This is the approach stackoverflow uses (in case you were wondering how others do this kind of thing); write operations like voting have "Success" and "Message" fields, regardless of if the vote was allowed or not:

{ Success:true, NewScore:1, Message:"", LastVoteTypeId:3 }

As @Phil.H pointed out, you should be consistent in whatever you choose. This is easier said than done (as is everything in development!).

For example, if you submit comments too quickly on SO, instead of being consistent and returning

{ Success: false, Message: "Can only comment once every blah..." }

SO will throw a server exception (HTTP 500) and catch it in their error callback.

As much as it "feels right" to use jQuery + .ashx + HTTP [status codes] IMO it will add more complexity to your client-side code base than it's worth. Realize that jQuery does not "detect" error codes but rather the lack of a success code. This is an important distinction when trying to design a client around http response codes with jQuery. You only get two choices (was it a "success" or "error"?), which you have to branch further on your own. If you have a small number of WebServices driving a small number of pages then it might be okay, but anything larger scale may get messy.

It's much more natural in a .asmx WebService (or WCF for that matter) to return a custom object than to customize the HTTP status code. Plus you get the JSON serialization for free.

Android Studio don't generate R.java for my import project

Go to Menu-Tab -> Project -> Build -> Automatically(check this option). and than reopen a new project.

How to resize an image to fit in the browser window?

I had a similar requirement, and had to do it it basic CSS and JavaScript. No JQuery available.

This is what I got working.

<html>
      <head>
            <style>
                   img {
                          max-width: 95% !important;
                          max-height: 95% !important;
                       }
            </style>
            <script>
                   function FitImagesToScreen() {
                      var images = document.getElementsByTagName('img');
                      if(images.length > 0){
                         for(var i=0; i < images.length; i++){
                             if(images[i].width >= (window.innerWidth - 10)){
                                 images[i].style.width = 'auto';
                               }
                            }
                         }
                   }
             </script>
      </head>
      <body onload='FitImagesToScreen()'>
      ----    
      </body>
</html>

Note : I haven't used 100% for image width as there was always a bit of padding to be considered.

Java: Date from unix timestamp

This is the right way:

Date date = new Date ();
date.setTime((long)unix_time*1000);

Installing Android Studio, does not point to a valid JVM installation error

Updated android studio to 1.2.1. Even though I was getting the same error. Nothing worked, finally replaced JAVA_HOME with JDK_HOME and it did the magic.

Warning :-Presenting view controllers on detached view controllers is discouraged

Try this code

UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:<your ViewController object>];

[self.view.window.rootViewController presentViewController:navigationController animated:YES completion:nil];

Oracle Sql get only month and year in date datatype

"FEB-2010" is not a Date, so it would not make a lot of sense to store it in a date column.

You can always extract the string part you need , in your case "MON-YYYY" using the TO_CHAR logic you showed above.

If this is for a DIMENSION table in a Data warehouse environment and you want to include these as separate columns in the Dimension table (as Data attributes), you will need to store the month and Year in two different columns, with appropriate Datatypes...

Example..

Month varchar2(3) --Month code in Alpha..
Year  NUMBER      -- Year in number

or

Month number(2)    --Month Number in Year.
Year  NUMBER      -- Year in number

Get JSON Data from URL Using Android?

My fairly short code to read JSON from an URL. (requires Guava due to usage of CharStreams).

    private static class VersionTask extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... strings) {
            String result = null;
            URL url;
            HttpURLConnection connection = null;
            try {
                url = new URL("https://api.github.com/repos/user_name/repo_name/releases/latest");
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                result = CharStreams.toString(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8));
            } catch (IOException e) {
                Log.d("VersionTask", Log.getStackTraceString(e));
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result != null) {
                String version = "";
                try {
                    version = new JSONObject(result).optString("tag_name").trim();
                } catch (JSONException e) {
                    Log.e("VersionTask", Log.getStackTraceString(e));
                }
                if (version.startsWith("v")) {
                    //process version
                }
            }
        }
    }

PS: This code gets the latest release version (based on tag name) for a given GitHub repo.

Clear form after submission with jQuery

You can add this to the callback from $.post

$( '#newsletterform' ).each(function(){
    this.reset();
});

You can't just call $( '#newsletterform' ).reset() because .reset() is a form object and not a jquery object, or something to that effect. You can read more about it here about half way down the page.

Textarea to resize based on content length

You can achieve this by using a span and a textarea.

You have to update the span with the text in textarea each time the text is changed. Then set the css width and height of the textarea to the span's clientWidth and clientHeight property.

Eg:

.textArea {
    border: #a9a9a9 1px solid;
    overflow: hidden;
    width:  expression( document.getElementById("spnHidden").clientWidth );
    height: expression( document.getElementById("spnHidden").clientHeight );
}

Why are Python lambdas useful?

In Python, lambda is just a way of defining functions inline,

a = lambda x: x + 1
print a(1)

and..

def a(x): return x + 1
print a(1)

..are the exact same.

There is nothing you can do with lambda which you cannot do with a regular function—in Python functions are an object just like anything else, and lambdas simply define a function:

>>> a = lambda x: x + 1
>>> type(a)
<type 'function'>

I honestly think the lambda keyword is redundant in Python—I have never had the need to use them (or seen one used where a regular function, a list-comprehension or one of the many builtin functions could have been better used instead)

For a completely random example, from the article "Python’s lambda is broken!":

To see how lambda is broken, try generating a list of functions fs=[f0,...,f9] where fi(n)=i+n. First attempt:

>>> fs = [(lambda n: i + n) for i in range(10)]
>>> fs[3](4)
13

I would argue, even if that did work, it's horribly and "unpythonic", the same functionality could be written in countless other ways, for example:

>>> n = 4
>>> [i + n for i in range(10)]
[4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

Yes, it's not the same, but I have never seen a cause where generating a group of lambda functions in a list has been required. It might make sense in other languages, but Python is not Haskell (or Lisp, or ...)

Please note that we can use lambda and still achieve the desired results in this way :

>>> fs = [(lambda n,i=i: i + n) for i in range(10)]
>>> fs[3](4)
7

Edit:

There are a few cases where lambda is useful, for example it's often convenient when connecting up signals in PyQt applications, like this:

w = PyQt4.QtGui.QLineEdit()
w.textChanged.connect(lambda event: dothing())

Just doing w.textChanged.connect(dothing) would call the dothing method with an extra event argument and cause an error. Using the lambda means we can tidily drop the argument without having to define a wrapping function.

How to pass a parameter like title, summary and image in a Facebook sharer URL

Looks like Facebook disabled passing parameters to the sharer.

We have changed the behavior of the sharer plugin to be consistent with other plugins and features on our platform.

The sharer will no longer accept custom parameters and facebook will pull the information that is being displayed in the preview the same way that it would appear on facebook as a post from the url OG meta tags.

Here's the URL to the post: https://developers.facebook.com/x/bugs/357750474364812/

Spaces in URLs?

They are indeed fools. If you look at RFC 3986 Appendix A, you will see that "space" is simply not mentioned anywhere in the grammar for defining a URL. Since it's not mentioned anywhere in the grammar, the only way to encode a space is with percent-encoding (%20).

In fact, the RFC even states that spaces are delimiters and should be ignored:

In some cases, extra whitespace (spaces, line-breaks, tabs, etc.) may have to be added to break a long URI across lines. The whitespace should be ignored when the URI is extracted.

and

For robustness, software that accepts user-typed URI should attempt to recognize and strip both delimiters and embedded whitespace.

Curiously, the use of + as an encoding for space isn't mentioned in the RFC, although it is reserved as a sub-delimeter. I suspect that its use is either just convention or covered by a different RFC (possibly HTTP).

jQuery.click() vs onClick

Most of the time, native JavaScript methods are a better choice over jQuery when performance is the only criteria, but jQuery makes use of JavaScript and makes the development easy. You can use jQuery as it does not degrade performance too much. In your specific case, the difference of performance is ignorable.

How to send parameters from a notification-click to an activity?

If you use

android:taskAffinity="myApp.widget.notify.activity"
android:excludeFromRecents="true"

in your AndroidManifest.xml file for the Activity to launch, you have to use the following in your intent:

Intent notificationClick = new Intent(context, NotifyActivity.class);
    Bundle bdl = new Bundle();
    bdl.putSerializable(NotifyActivity.Bundle_myItem, myItem);
    notificationClick.putExtras(bdl);
    notificationClick.setData(Uri.parse(notificationClick.toUri(Intent.URI_INTENT_SCHEME) + myItem.getId()));
    notificationClick.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);  // schließt tasks der app und startet einen seperaten neuen

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(NotifyActivity.class);
    stackBuilder.addNextIntent(notificationClick);

    PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(notificationPendingIntent);

Important is to set unique data e.g. using an unique id like:

notificationClick.setData(Uri.parse(notificationClick.toUri(Intent.URI_INTENT_SCHEME) + myItem.getId()));

How do I get current URL in Selenium Webdriver 2 Python?

Selenium2Library has get_location():

import Selenium2Library
s = Selenium2Library.Selenium2Library()
url = s.get_location()

! [rejected] master -> master (fetch first)

--force option worked for me I used git push origin master --force

How can I see the size of a GitHub repository before cloning it?

To summarize @larowlan, @VMTrooper, and @vahid chakoshy solutions:

#!/usr/bin/env bash


if [ "$#" -eq 2 ]; then
    echo "$(echo "scale=2; $(curl https://api.github.com/repos/$1/$2 2>/dev/null \
    | grep size | head -1 | tr -dc '[:digit:]') / 1024" | bc)MB"
elif [ "$#" -eq 3 ] && [ "$1" == "-z" ]; then
    # For some reason Content-Length header is returned only on second try
    curl -I https://codeload.github.com/$2/$3/zip/master &>/dev/null  
    echo "$(echo "scale=2; $(curl -I https://codeload.github.com/$2/$3/zip/master \
    2>/dev/null | grep Content-Length | cut -d' ' -f2 | tr -d '\r') / 1024 / 1024" \
    | bc)MB"
else
    printf "Usage: $(basename $0) [-z] OWNER REPO\n\n"
    printf "Get github repository size or, optionally [-z], the size of the zipped\n"
    printf "master branch (`Download ZIP` link on repo page).\n"
    exit 1
fi

Passing functions with arguments to another function in Python?

This is what lambda is for:

def perform(f):
    f()

perform(lambda: action1())
perform(lambda: action2(p))
perform(lambda: action3(p, r))

Restoring MySQL database from physical files

With MySql 5.1 (Win7). To recreate DBs (InnoDbs) I've replaced all contents of following dirs (my.ini params):

datadir="C:/ProgramData/MySQL/MySQL Server 5.1/Data/"
innodb_data_home_dir="C:/MySQL Datafiles/"

After that I started MySql Service and all works fine.

Add image to left of text via css

Try something like:

.create
 { 
  margin: 0px;
  padding-left: 20px;
  background-image: url('yourpic.gif');
    background-repeat: no-repeat;

}

Force youtube embed to start in 720p

The first example below does not work for me, but the second one does (in Chrome).

<iframe width="720" height="405" src="//www.youtube.com/embed/GX_c566xYcQ?rel=0&vq=hd1080" frameborder="0" allowfullscreen="1"></iframe>
<iframe width="720" height="405" src="//youtube.com/v/IplDUxTQxsE?rel=0&vq=hd1080" frameborder="0" allowfullscreen="1"></iframe>

I believe the first one uses the new HTML5 youtube player whereas the bottom one (which works) uses the older flash player. However, the second one doesn't seem to load correctly in Safari/Firefox etc so probably not usable.

Image resizing client-side with JavaScript before upload to the server

In my experience, this example has been the best solution for uploading a resized picture: https://zocada.com/compress-resize-images-javascript-browser/

It uses the HTML5 Canvas feature.

The code is as 'simple' as this:

compress(e) {
    const fileName = e.target.files[0].name;
    const reader = new FileReader();
    reader.readAsDataURL(e.target.files[0]);
    reader.onload = event => {
        const img = new Image();
        img.src = event.target.result;
        img.onload = () => {
                const elem = document.createElement('canvas');
                const width = Math.min(800, img.width);
                const scaleFactor = width / img.width;
                elem.width = width;
                elem.height = img.height * scaleFactor;

                const ctx = elem.getContext('2d');
                // img.width and img.height will contain the original dimensions
                ctx.drawImage(img, 0, 0, width, img.height * scaleFactor);
                ctx.canvas.toBlob((blob) => {
                    const file = new File([blob], fileName, {
                        type: 'image/jpeg',
                        lastModified: Date.now()
                    });
                }, 'image/jpeg', 1);
            },
            reader.onerror = error => console.log(error);
    };
}

There are two downsides with this solution.

The first one is related with the image rotation, due to ignoring EXIF data. I couldn't tackle this issue, and wasn't so important in my use case, but will be glad to hear any feedback.

The second downside is the lack of support foe IE/Edge (not the Chrome based version though), and I won't put any time on that.

Request Permission for Camera and Library in iOS 10 - Info.plist

Great way of implementing Camera session in Swift 5, iOS 13

https://github.com/egzonpllana/CameraSession

Camera Session is an iOS app that tries to make the simplest possible way of implementation of AVCaptureSession.

Through the app you can find these camera session implemented:

  • Native camera to take a picture or record a video.
  • Native way of importing photos and videos.
  • The custom way to select assets like photos and videos, with an option to select one or more assets from the Library.
  • Custom camera to take a photo(s) or video(s), with options to hold down the button and record.
  • Separated camera permission requests.

The custom camera features like torch and rotate camera options.

Gradle, Android and the ANDROID_HOME SDK location

That question is from November 2013 (while Android Studio was still in Developer Preview mode),

Currently (AS v2.2, Aug-2016) during instalation AS asks to choose the SDK folder (or install on their default) and it automatically applies to which ever project you're opening.

That means any possible workaround or fix is irrelevant as the issue is not reproducible anymore.

How can I exclude $(this) from a jQuery selector?

You should use the "siblings()" method, and prevent from running the ".content a" selector over and over again just for applying that effect:

HTML

<div class="content">
    <a href="#">A</a>
</div>
<div class="content">
    <a href="#">B</a>
</div>
<div class="content">
    <a href="#">C</a>
</div>

CSS

.content {
    background-color:red;
    margin:10px;
}
.content.other {
    background-color:yellow;
}

Javascript

$(".content a").click(function() {
  var current = $(this).parent();
  current.removeClass('other')
    .siblings()
    .addClass('other');
});

See here: http://jsfiddle.net/3bzLV/1/

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

If you would like to purposely link your project A in Release against another project B in Debug, say to keep the overall performance benefits of your application while debugging, then you will likely hit this error. You can fix this by temporarily modifying the preprocessor flags of project B to disable iterator debugging (and make it match project A):

In Project B's "Debug" properties, Configuration Properties -> C/C++ -> Preprocessor, add the following to Preprocessor Definitions:

_HAS_ITERATOR_DEBUGGING=0;_ITERATOR_DEBUG_LEVEL=0;

Rebuild project B in Debug, then build project A in Release and it should link correctly.

How to use (install) dblink in PostgreSQL?

It can be added by using:

$psql -d databaseName -c "CREATE EXTENSION dblink"

javascript node.js next()

It's basically like a callback that express.js use after a certain part of the code is executed and done, you can use it to make sure that part of code is done and what you wanna do next thing, but always be mindful you only can do one res.send in your each REST block...

So you can do something like this as a simple next() example:

app.get("/", (req, res, next) => {
  console.log("req:", req, "res:", res);
  res.send(["data": "whatever"]);
  next();
},(req, res) =>
  console.log("it's all done!");
);

It's also very useful when you'd like to have a middleware in your app...

To load the middleware function, call app.use(), specifying the middleware function. For example, the following code loads the myLogger middleware function before the route to the root path (/).

var express = require('express');
var app = express();

var myLogger = function (req, res, next) {
  console.log('LOGGED');
  next();
}

app.use(myLogger);

app.get('/', function (req, res) {
  res.send('Hello World!');
})

app.listen(3000);

How to render an ASP.NET MVC view as a string?

Additional tip for ASP NET CORE:

Interface:

public interface IViewRenderer
{
  Task<string> RenderAsync<TModel>(Controller controller, string name, TModel model);
}

Implementation:

public class ViewRenderer : IViewRenderer
{
  private readonly IRazorViewEngine viewEngine;

  public ViewRenderer(IRazorViewEngine viewEngine) => this.viewEngine = viewEngine;

  public async Task<string> RenderAsync<TModel>(Controller controller, string name, TModel model)
  {
    ViewEngineResult viewEngineResult = this.viewEngine.FindView(controller.ControllerContext, name, false);

    if (!viewEngineResult.Success)
    {
      throw new InvalidOperationException(string.Format("Could not find view: {0}", name));
    }

    IView view = viewEngineResult.View;
    controller.ViewData.Model = model;

    await using var writer = new StringWriter();
    var viewContext = new ViewContext(
       controller.ControllerContext,
       view,
       controller.ViewData,
       controller.TempData,
       writer,
       new HtmlHelperOptions());

       await view.RenderAsync(viewContext);

       return writer.ToString();
  }
}

Registration in Startup.cs

...
 services.AddSingleton<IViewRenderer, ViewRenderer>();
...

And usage in controller:

public MyController: Controller
{
  private readonly IViewRenderer renderer;
  public MyController(IViewRendere renderer) => this.renderer = renderer;
  public async Task<IActionResult> MyViewTest
  {
    var view = await this.renderer.RenderAsync(this, "MyView", model);
    return new OkObjectResult(view);
  }
}

How to store printStackTrace into a string

Guava makes this easy with Throwables.getStackTraceAsString(Throwable):

Exception e = ...
String stackTrace = Throwables.getStackTraceAsString(e);

Internally, this does what @Zach L suggests.

How do I create a slug in Django?

If you don't want to set the slugfield to Not be editable, then I believe you'll want to set the Null and Blank properties to False. Otherwise you'll get an error when trying to save in Admin.

So a modification to the above example would be::

class test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField(null=True, blank=True) # Allow blank submission in admin.

    def save(self):
        if not self.id:
            self.s = slugify(self.q)

        super(test, self).save()

Error - trustAnchors parameter must be non-empty

Slim chance this will help anyone but....for anyone running Java 8 from a Docker Image on a Raspberry Pi (using AMD CPU) I got the following Dockerfile to build and run successfully for me

FROM hypriot/rpi-java
USER root

WORKDIR /usr/build/

RUN /usr/bin/printf '\xfe\xed\xfe\xed\x00\x00\x00\x02\x00\x00\x00\x00\xe2\x68\x6e\x45\xfb\x43\xdf\xa4\xd9\x92\xdd\x41\xce\xb6\xb2\x1c\x63\x30\xd7\x92' > /etc/ssl/certs/java/cacerts
RUN update-ca-certificates -f
RUN /var/lib/dpkg/info/ca-certificates-java.postinst configure

EXPOSE 8080

ARG JAR_FILE=target/app-0.0.1-SNAPSHOT.jar

ADD ${JAR_FILE} app.jar

ENTRYPOINT ["java", "-Djavax.net.ssl.trustStorePassword=changeit", "-Djavax.net.ssl.trustStore=/etc/ssl/certs/java/cacerts", "-jar", "app.jar"]

Run script on mac prompt "Permission denied"

Please read the whole answer before attempting to run with sudo

Try running sudo /dvtcolorconvert.rb ~/Themes/ObsidianCode.xccolortheme

The sudo command executes the commands which follow it with 'superuser' or 'root' privileges. This should allow you to execute almost anything from the command line. That said, DON'T DO THIS! If you are running a script on your computer and don't need it to access core components of your operating system (I'm guessing you're not since you are invoking the script on something inside your home directory (~/)), then it should be running from your home directory, ie:

~/dvtcolorconvert.rb ~/Themes/ObsidianCode.xccolortheme

Move it to ~/ or a sub directory and execute from there. You should never have permission issues there and there wont be a risk of it accessing or modifying anything critical to your OS.

If you are still having problems you can check the permissions on the file by running ls -l while in the same directory as the ruby script. You will get something like this:

$ ls -l  
total 13  
drwxr-xr-x    4 or019268 Administ    12288 Apr 10 18:14 TestWizard  
drwxr-xr-x    4 or019268 Administ     4096 Aug 27 12:41 Wizard.Controls  
drwxr-xr-x    5 or019268 Administ     8192 Sep  5 00:03 Wizard.UI  
-rw-r--r--    1 or019268 Administ     1375 Sep  5 00:03 readme.txt

You will notice that the readme.txt file says -rw-r--r-- on the left. This shows the permissions for that file. The 9 characters from the right can be split into groups of 3 characters of 'rwx' (read, write, execute). If I want to add execute rights to this file I would execute chmod 755 readme.txt and that permissions portion would become rwxr-xr-x. I can now execute this file if I want to by running ./readme.txt (./ tells the bash to look in the current directory for the intended command rather that search the $PATH variable).

schluchc alludes to looking at the man page for chmod, do this by running man chmod. This is the best way to get documentation on a given command, man <command>

Top 5 time-consuming SQL queries in Oracle

While searching I got the following query which does the job with one assumption(query execution time >6 seconds)


SELECT username, sql_text, sofar, totalwork, units

FROM v$sql,v$session_longops

WHERE sql_address = address AND sql_hash_value = hash_value

ORDER BY address, hash_value, child_number;


I think above query will list the details for current user.

Comments are welcome!!

PHP Fatal error: Cannot redeclare class

Just do one thing whenever you include or require filename namely class.login.php. You can include it this way:

include_once class.login.php or 
require_once class.login.php

This way it never throws an error.

Find oldest/youngest datetime object in a list

The datetime module has its own versions of min and max as available methods. https://docs.python.org/2/library/datetime.html

Cloud Firestore collection count

As far as I know there is no build-in solution for this and it is only possible in the node sdk right now. If you have a

db.collection('someCollection')

you can use

.select([fields])

to define which field you want to select. If you do an empty select() you will just get an array of document references.

example:

db.collection('someCollection').select().get().then( (snapshot) => console.log(snapshot.docs.length) );

This solution is only a optimization for the worst case of downloading all documents and does not scale on large collections!

Also have a look at this:
How to get a count of number of documents in a collection with Cloud Firestore

XCOPY: Overwrite all without prompt in BATCH

The solution is the /Y switch:

xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y

command to remove row from a data frame

eldNew <- eld[-14,]

See ?"[" for a start ...

For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.

(emphasis added)

edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?

edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame ...

Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame

Press Enter to move to next control

A couple of code examples in C# using SelectNextControl.

The first moves to the next control when ENTER is pressed.

    private void Control_KeyUp( object sender, KeyEventArgs e )
    {
        if( (e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return) )
        {
            this.SelectNextControl( (Control)sender, true, true, true, true );
        }
    }

The second uses the UP and DOWN arrows to move through the controls.

    private void Control_KeyUp( object sender, KeyEventArgs e )
    {
        if( e.KeyCode == Keys.Up )
        {
            this.SelectNextControl( (Control)sender, false, true, true, true );
        }
        else if( e.KeyCode == Keys.Down )
        {
            this.SelectNextControl( (Control)sender, true, true, true, true );
        }
    }

See MSDN SelectNextControl Method

How to hide a button programmatically?

Hidde:

BUTTON.setVisibility(View.GONE);

Show:

BUTTON.setVisibility(View.VISIBLE);

How to access at request attributes in JSP?

EL expression:

${requestScope.Error_Message}

There are several implicit objects in JSP EL. See Expression Language under the "Implicit Objects" heading.

Downloading a large file using curl

<?php
set_time_limit(0);
//This is the file where we save the    information
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');
//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
// write curl response to file
curl_setopt($ch, CURLOPT_FILE, $fp); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// get curl response
curl_exec($ch); 
curl_close($ch);
fclose($fp);
?>

Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern

Instead of handcranking your models try using something like the Json2csharp.com website. Paste In an example JSON response, the fuller the better and then pull in the resultant generated classes. This, at least, takes away some moving parts, will get you the shape of the JSON in csharp giving the serialiser an easier time and you shouldnt have to add attributes.

Just get it working and then make amendments to your class names, to conform to your naming conventions, and add in attributes later.

EDIT: Ok after a little messing around I have successfully deserialised the result into a List of Job (I used Json2csharp.com to create the class for me)

public class Job
{
        public string id { get; set; }
        public string position_title { get; set; }
        public string organization_name { get; set; }
        public string rate_interval_code { get; set; }
        public int minimum { get; set; }
        public int maximum { get; set; }
        public string start_date { get; set; }
        public string end_date { get; set; }
        public List<string> locations { get; set; }
        public string url { get; set; }
}

And an edit to your code:

        List<Job> model = null;
        var client = new HttpClient();
        var task = client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs")
          .ContinueWith((taskwithresponse) =>
          {
              var response = taskwithresponse.Result;
              var jsonString = response.Content.ReadAsStringAsync();
              jsonString.Wait();
              model = JsonConvert.DeserializeObject<List<Job>>(jsonString.Result);

          });
        task.Wait();

This means you can get rid of your containing object. Its worth noting that this isn't a Task related issue but rather a deserialisation issue.

EDIT 2:

There is a way to take a JSON object and generate classes in Visual Studio. Simply copy the JSON of choice and then Edit> Paste Special > Paste JSON as Classes. A whole page is devoted to this here:

http://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/

Make a borderless form movable?

Ref. video Link

This is tested and easy to understand.

protected override void WndProc(ref Message m)
{
    switch (m.Msg)
    {
        case 0x84:
            base.WndProc(ref m);
            if((int)m.Result == 0x1)
                m.Result = (IntPtr)0x2;
            return;
    }

    base.WndProc(ref m);
}

Cause of a process being a deadlock victim

Although @Remus Rusanu's is already an excelent answer, in case one is looking forward a better insight on SQL Server's Deadlock causes and trace strategies, I would suggest you to read Brad McGehee's How to Track Down Deadlocks Using SQL Server 2005 Profiler

MacOSX homebrew mysql root password

Try with sudo to avoid the "Access denied" error:

sudo $(brew --prefix mariadb)/bin/mysqladmin -u root password NEWPASS

Ruby: How to iterate over a range, but in set increments?

Here's another, perhaps more familiar-looking way to do it:

for i in (0..10).step(2) do
    puts i
end

Generate Java classes from .XSD files...?

The well-known JAXB

There is a maven plugin that could do this for you at any build phase you want.

You could do this stuff in both ways: xsd <-> Java

How do you cast a List of supertypes to a List of subtypes?

I think you are casting in the wrong direction though... if the method returns a list of TestA objects, then it really isn't safe to cast them to TestB.

Basically you are asking the compiler to let you perform TestB operations on a type TestA that does not support them.

How do I put an already-running process under nohup?

Node's answer is really great, but it left open the question how can get stdout and stderr redirected. I found a solution on Unix & Linux, but it is also not complete. I would like to merge these two solutions. Here it is:

For my test I made a small bash script called loop.sh, which prints the pid of itself with a minute sleep in an infinite loop.

$./loop.sh

Now get the PID of this process somehow. Usually ps -C loop.sh is good enough, but it is printed in my case.

Now we can switch to another terminal (or press ^Z and in the same terminal). Now gdb should be attached to this process.

$ gdb -p <PID>

This stops the script (if running). Its state can be checked by ps -f <PID>, where the STAT field is 'T+' (or in case of ^Z 'T'), which means (man ps(1))

    T Stopped, either by a job control signal or because it is being traced
    + is in the foreground process group

(gdb) call close(1)
$1 = 0

Close(1) returns zero on success.

(gdb) call open("loop.out", 01102, 0600)
$6 = 1

Open(1) returns the new file descriptor if successful.

This open is equal with open(path, O_TRUNC|O_CREAT|O_RDWR, S_IRUSR|S_IWUSR). Instead of O_RDWR O_WRONLY could be applied, but /usr/sbin/lsof says 'u' for all std* file handlers (FD column), which is O_RDWR.

I checked the values in /usr/include/bits/fcntl.h header file.

The output file could be opened with O_APPEND, as nohup would do, but this is not suggested by man open(2), because of possible NFS problems.

If we get -1 as a return value, then call perror("") prints the error message. If we need the errno, use p errno gdb comand.

Now we can check the newly redirected file. /usr/sbin/lsof -p <PID> prints:

loop.sh <PID> truey    1u   REG   0,26        0 15008411 /home/truey/loop.out

If we want, we can redirect stderr to another file, if we want to using call close(2) and call open(...) again using a different file name.

Now the attached bash has to be released and we can quit gdb:

(gdb) detach
Detaching from program: /bin/bash, process <PID>
(gdb) q

If the script was stopped by gdb from an other terminal it continues to run. We can switch back to loop.sh's terminal. Now it does not write anything to the screen, but running and writing into the file. We have to put it into the background. So press ^Z.

^Z
[1]+  Stopped                 ./loop.sh

(Now we are in the same state as if ^Z was pressed at the beginning.)

Now we can check the state of the job:

$ ps -f 24522
UID        PID  PPID  C STIME TTY      STAT   TIME CMD
<UID>    <PID><PPID>  0 11:16 pts/36   S      0:00 /bin/bash ./loop.sh
$ jobs
[1]+  Stopped                 ./loop.sh

So process should be running in the background and detached from the terminal. The number in the jobs command's output in square brackets identifies the job inside bash. We can use in the following built in bash commands applying a '%' sign before the job number :

$ bg %1
[1]+ ./loop.sh &
$ disown -h %1
$ ps -f <PID>
UID        PID  PPID  C STIME TTY      STAT   TIME CMD
<UID>    <PID><PPID>  0 11:16 pts/36   S      0:00 /bin/bash ./loop.sh

And now we can quit from the calling bash. The process continues running in the background. If we quit its PPID become 1 (init(1) process) and the control terminal become unknown.

$ ps -f <PID>
UID        PID  PPID  C STIME TTY      STAT   TIME CMD
<UID>    <PID>     1  0 11:16 ?        S      0:00 /bin/bash ./loop.sh
$ /usr/bin/lsof -p <PID>
...
loop.sh <PID> truey    0u   CHR 136,36                38 /dev/pts/36 (deleted)
loop.sh <PID> truey    1u   REG   0,26     1127 15008411 /home/truey/loop.out
loop.sh <PID> truey    2u   CHR 136,36                38 /dev/pts/36 (deleted)

COMMENT

The gdb stuff can be automatized creating a file (e.g. loop.gdb) containing the commands and run gdb -q -x loop.gdb -p <PID>. My loop.gdb looks like this:

call close(1)
call open("loop.out", 01102, 0600)
# call close(2)
# call open("loop.err", 01102, 0600)
detach
quit

Or one can use the following one liner instead:

gdb -q -ex 'call close(1)' -ex 'call open("loop.out", 01102, 0600)' -ex detach -ex quit -p <PID>

I hope this is a fairly complete description of the solution.

Angular 2 - Checking for server errors from subscribe

You can achieve with following way

    this.projectService.create(project)
    .subscribe(
        result => {
         console.log(result);
        },
        error => {
            console.log(error);
            this.errors = error
        }
    ); 
}

if (!this.errors) {
    //route to new page
}

Curl error: Operation timed out

$curl = curl_init();

  curl_setopt_array($curl, array(
  CURLOPT_URL => "", // Server Path
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 3000, // increase this
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\"email\":\"[email protected]\",\"password\":\"markus William\",\"username\":\"Daryl Brown\",\"mobile\":\"013132131112\","msg":"No more SSRIs." }",
  CURLOPT_HTTPHEADER => array(
    "Content-Type: application/json",
    "Postman-Token: 4867c7a3-2b3d-4e9a-9791-ed6dedb046b1",
    "cache-control: no-cache"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

initialize array index "CURLOPT_TIMEOUT" with a value in seconds according to time required for response .

Convert Java Date to UTC String

If XStream is a dependency, try:

new com.thoughtworks.xstream.converters.basic.DateConverter().toString(date)

Is it possible to declare two variables of different types in a for loop?

No - but technically there is a work-around (not that i'd actually use it unless forced to):

for(struct { int a; char b; } s = { 0, 'a' } ; s.a < 5 ; ++s.a) 
{
    std::cout << s.a << " " << s.b << std::endl;
}

org.hibernate.MappingException: Unknown entity: annotations.Users

I did not find the accepted answer helpful in resolving the exception encountered in my code. And while not technically incorrect, I was also not satisfied with others' suggestions to introduce redundancy:

  • programmatically re-add the mapped class using configuration.addAnnotatedClass(...)
  • create a hbm.xml file and resource mapping in hibernate_test.cfg.xml that were redundant to the existing annotations
  • scan the package where the (already mapped) class exists using external dependencies not mentioned in the original question

However, I found 2 possible solutions that I wanted to share, both of which independently resolved the exception I encountered in my own code.

I was having the same MappingException as @ron (using a very nearly identical HibernateUtil class):

public final class HibernateUtil {

    private static SessionFactory sessionFactory = null;
    private static ServiceRegistry serviceRegistry = null;

    private HibernateUtil() {}

    public static synchronized SessionFactory getSessionFactory() {
        if ( sessionFactory == null ) {
            Configuration configuration = new Configuration().configure("hibernate_test.cfg.xml");
            serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties())
                    .build();
            sessionFactory = configuration.buildSessionFactory( serviceRegistry );
        }
        return sessionFactory;
    }
// exception handling and closeSessionFactory() omitted for brevity
}

Within my hibernate_test.cfg.xml configuration file, I have the required class mapping:

<mapping class="myPackage.Device"/>

And my Device class is properly annotated with the javax.persistence.Entity annotation:

package myPackage.core;
import javax.persistence.*;

@Entity
@Table( name = "devices" )
public class Device {
    //body omitted for brevity
}

Two Possible Solutions:

First, I am using Hibernate 5.2, and for those using Hibernate 5 this solution using a Metadata object to build a SessionFactory should work. It also appears to be the currently recommended native bootstrap mechanism in the Hibernate Getting Started Guide :

public static synchronized SessionFactory getSessionFactory() {
    if ( sessionFactory == null ) {

        // exception handling omitted for brevity

        serviceRegistry = new StandardServiceRegistryBuilder()
                .configure("hibernate_test.cfg.xml")
                .build();

        sessionFactory = new MetadataSources( serviceRegistry )
                    .buildMetadata()
                    .buildSessionFactory();
    }
    return sessionFactory;
}

Second, while Configuration is semi-deprecated in Hibernate 5, @ron didn't say which version of Hibernate he was using, so this solution could also be of value to some.

I found a very subtle change in the order of operations when instantiating and configuring Configuration and ServiceRegistry objects to make all the difference in my own code.

Original order (Configuration created and configured prior to ServiceRegistry):

public static synchronized SessionFactory getSessionFactory() {
    if ( sessionFactory == null ) {

        // exception handling omitted for brevity

        Configuration configuration = new Configuration().configure("hibernate_test.cfg.xml");

        serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings( configuration.getProperties() )
                .build();

        sessionFactory = configuration.buildSessionFactory( serviceRegistry );
    }
    return sessionFactory;
}

New order (ServiceRegistry created and configured prior to Configuration):

public static synchronized SessionFactory getSessionFactory() {
    if ( sessionFactory == null ) {

        // exception handling omitted for brevity

        serviceRegistry = new StandardServiceRegistryBuilder()
                .configure("hibernate_test.cfg.xml")
                .build();

        sessionFactory = new Configuration().buildSessionFactory( serviceRegistry );
    }
    return sessionFactory;
}

At the risk of TLDR, I will also point out that with respect to hibernate_test.cfg.xml my testing suggests that the configuration.getProperties() method only returns <property /> elements, and <mapping /> elements are excluded. This appears consistent with the specific use of the terms 'property' and 'mapping' within the API documentation for Configuration. I will concede that this behaviour may have something to do with the failure of applySettings() to yield the mapping data to the StandardServiceRegistryBuilder. However, this mapping data should already have been parsed during configuration of the Configuration object and available to it when buildSessionFactory() is called. Therefore, I suspect this may be due to implementation-specific details regarding resource precedence when a ServiceRegistry is passed to a Configuration object's buildSessionFactory() method.

I know this question is several years old now, but I hope this answer saves somebody the hours of research I spent in deriving it. Cheers!

How to make script execution wait until jquery is loaded

You can try onload event. It raised when all scripts has been loaded :

window.onload = function () {
   //jquery ready for use here
}

But keep in mind, that you may override others scripts where window.onload using.

Show all tables inside a MySQL database using PHP?

Try this:

SHOW TABLES FROM nameOfDatabase;

sudo: port: command not found

if you use zsh.please add flowing string to the line 'export PATH="..."' in file '~/.zshrc'

:/opt/local/bin:/opt/local/sbin

Jquery button click() function is not working

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

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

When should I use git pull --rebase?

Perhaps the best way to explain it is with an example:

  1. Alice creates topic branch A, and works on it
  2. Bob creates unrelated topic branch B, and works on it
  3. Alice does git checkout master && git pull. Master is already up to date.
  4. Bob does git checkout master && git pull. Master is already up to date.
  5. Alice does git merge topic-branch-A
  6. Bob does git merge topic-branch-B
  7. Bob does git push origin master before Alice
  8. Alice does git push origin master, which is rejected because it's not a fast-forward merge.
  9. Alice looks at origin/master's log, and sees that the commit is unrelated to hers.
  10. Alice does git pull --rebase origin master
  11. Alice's merge commit is unwound, Bob's commit is pulled, and Alice's commit is applied after Bob's commit.
  12. Alice does git push origin master, and everyone is happy they don't have to read a useless merge commit when they look at the logs in the future.

Note that the specific branch being merged into is irrelevant to the example. Master in this example could just as easily be a release branch or dev branch. The key point is that Alice & Bob are simultaneously merging their local branches to a shared remote branch.

Why is __dirname not defined in node REPL?

Though its not the solution to this problem I would like to add it as it may help others.

You should have two underscores before dirname, not one underscore (__dirname not _dirname).

NodeJS Docs

RegEx: Grabbing values between quotation marks

In general, the following regular expression fragment is what you are looking for:

"(.*?)"

This uses the non-greedy *? operator to capture everything up to but not including the next double quote. Then, you use a language-specific mechanism to extract the matched text.

In Python, you could do:

>>> import re
>>> string = '"Foo Bar" "Another Value"'
>>> print re.findall(r'"(.*?)"', string)
['Foo Bar', 'Another Value']

public static const in TypeScript

Here's what's this TS snippet compiled into (via TS Playground):

define(["require", "exports"], function(require, exports) {
    var Library = (function () {
        function Library() {
        }
        Library.BOOK_SHELF_NONE = "None";
        Library.BOOK_SHELF_FULL = "Full";
        return Library;
    })();
    exports.Library = Library;
});

As you see, both properties defined as public static are simply attached to the exported function (as its properties); therefore they should be accessible as long as you properly access the function itself.

What is the difference between bottom-up and top-down?

Lets take fibonacci series as an example

1,1,2,3,5,8,13,21....

first number: 1
Second number: 1
Third Number: 2

Another way to put it,

Bottom(first) number: 1
Top (Eighth) number on the given sequence: 21

In case of first five fibonacci number

Bottom(first) number :1
Top (fifth) number: 5 

Now lets take a look of recursive Fibonacci series algorithm as an example

public int rcursive(int n) {
    if ((n == 1) || (n == 2)) {
        return 1;
    } else {
        return rcursive(n - 1) + rcursive(n - 2);
    }
}

Now if we execute this program with following commands

rcursive(5);

if we closely look into the algorithm, in-order to generate fifth number it requires 3rd and 4th numbers. So my recursion actually start from top(5) and then goes all the way to bottom/lower numbers. This approach is actually top-down approach.

To avoid doing same calculation multiple times we use Dynamic Programming techniques. We store previously computed value and reuse it. This technique is called memoization. There are more to Dynamic programming other then memoization which is not needed to discuss current problem.

Top-Down

Lets rewrite our original algorithm and add memoized techniques.

public int memoized(int n, int[] memo) {
    if (n <= 2) {
        return 1;
    } else if (memo[n] != -1) {
        return memo[n];
    } else {
        memo[n] = memoized(n - 1, memo) + memoized(n - 2, memo);
    }
    return memo[n];
}

And we execute this method like following

   int n = 5;
    int[] memo = new int[n + 1];
    Arrays.fill(memo, -1);
    memoized(n, memo);

This solution is still top-down as algorithm start from top value and go to bottom each step to get our top value.

Bottom-Up

But, question is, can we start from bottom, like from first fibonacci number then walk our way to up. Lets rewrite it using this techniques,

public int dp(int n) {
    int[] output = new int[n + 1];
    output[1] = 1;
    output[2] = 1;
    for (int i = 3; i <= n; i++) {
        output[i] = output[i - 1] + output[i - 2];
    }
    return output[n];
}

Now if we look into this algorithm it actually start from lower values then go to top. If i need 5th fibonacci number i am actually calculating 1st, then second then third all the way to up 5th number. This techniques actually called bottom-up techniques.

Last two, algorithms full-fill dynamic programming requirements. But one is top-down and another one is bottom-up. Both algorithm has similar space and time complexity.

Convert JSON to Map

Use JSON lib E.g. http://www.json.org/java/

// Assume you have a Map<String, String> in JSONObject jdata
@SuppressWarnings("unchecked")
Iterator<String> nameItr = jdata.keys();
Map<String, String> outMap = new HashMap<String, String>();
while(nameItr.hasNext()) {
    String name = nameItr.next();
    outMap.put(name, jdata.getString(name));

}