Programs & Examples On #Passwd

How to automatically add user account AND password with a Bash script?

--stdin doesn't work on Debian. It says:

`passwd: unrecognized option '--stdin'`

This worked for me:

#useradd $USER
#echo "$USER:$SENHA" | chpasswd

Here we can find some other good ways:

How do I completely remove root password

Did you try passwd -d root? Most likely, this will do what you want.


You can also manually edit /etc/shadow: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to

root:$X$SK5xfLB1ZW:0:0...

There, delete the second field (everything between the first and second colon):

root::0:0...

Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)

root:*:0:0...

Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd, and use mkpasswd to create the second field for the /etc/shadow.)

List of all users that can connect via SSH

Read man sshd_config for more details, but you can use the AllowUsers directive in /etc/ssh/sshd_config to limit the set of users who can login.

e.g.

AllowUsers boris

would mean that only the boris user could login via ssh.

What does [STAThread] do?

The STAThreadAttribute marks a thread to use the Single-Threaded COM Apartment if COM is needed. By default, .NET won't initialize COM at all. It's only when COM is needed, like when a COM object or COM Control is created or when drag 'n' drop is needed, that COM is initialized. When that happens, .NET calls the underlying CoInitializeEx function, which takes a flag indicating whether to join the thread to a multi-threaded or single-threaded apartment.

Read more info here (Archived, June 2009)

and

Why is STAThread required?

Warning: Found conflicts between different versions of the same dependent assembly

If using NuGet all I had to do was:

  1. right click project and click Manage NuGet Packages..

  2. click the cog in top right

  3. click General tab in NuGet Package Manager above Package Sources

  4. check "Skip Applying binding redirects" in Binding Redirects

  5. Clean and rebuild and the warning's gone

Easy peasy

How to load property file from classpath?

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}

What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?

On my system (OSX 10.6) that package is at

/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/pkg_resources.py

I hope that helps you figure out if it's missing or just not on your path.

Configure active profile in SpringBoot via Maven

Or rather easily:

mvn spring-boot:run -Dspring-boot.run.profiles={profile_name}

Angular2, what is the correct way to disable an anchor element?

Just use

<a [ngClass]="{'disabled': your_condition}"> This a tag is disabled</a>

Example:

 <a [ngClass]="{'disabled': name=='junaid'}"> This a tag is disabled</a>

Convert PDF to image with high resolution

The following python script will work on any Mac (Snow Leopard and upward). It can be used on the command line with successive PDF files as arguments, or you can put in into a Run Shell Script action in Automator, and make a Service (Quick Action in Mojave).

You can set the resolution of the output image in the script.

The script and a Quick Action can be downloaded from github.

#!/usr/bin/python
# coding: utf-8

import os, sys
import Quartz as Quartz
from LaunchServices import (kUTTypeJPEG, kUTTypeTIFF, kUTTypePNG, kCFAllocatorDefault) 

resolution = 300.0 #dpi
scale = resolution/72.0

cs = Quartz.CGColorSpaceCreateWithName(Quartz.kCGColorSpaceSRGB)
whiteColor = Quartz.CGColorCreate(cs, (1, 1, 1, 1))
# Options: kCGImageAlphaNoneSkipLast (no trans), kCGImageAlphaPremultipliedLast 
transparency = Quartz.kCGImageAlphaNoneSkipLast

#Save image to file
def writeImage (image, url, type, options):
    destination = Quartz.CGImageDestinationCreateWithURL(url, type, 1, None)
    Quartz.CGImageDestinationAddImage(destination, image, options)
    Quartz.CGImageDestinationFinalize(destination)
    return

def getFilename(filepath):
    i=0
    newName = filepath
    while os.path.exists(newName):
        i += 1
        newName = filepath + " %02d"%i
    return newName

if __name__ == '__main__':

    for filename in sys.argv[1:]:
        pdf = Quartz.CGPDFDocumentCreateWithProvider(Quartz.CGDataProviderCreateWithFilename(filename))
        numPages = Quartz.CGPDFDocumentGetNumberOfPages(pdf)
        shortName = os.path.splitext(filename)[0]
        prefix = os.path.splitext(os.path.basename(filename))[0]
        folderName = getFilename(shortName)
        try:
            os.mkdir(folderName)
        except:
            print "Can't create directory '%s'"%(folderName)
            sys.exit()

        # For each page, create a file
        for i in range (1, numPages+1):
            page = Quartz.CGPDFDocumentGetPage(pdf, i)
            if page:
        #Get mediabox
                mediaBox = Quartz.CGPDFPageGetBoxRect(page, Quartz.kCGPDFMediaBox)
                x = Quartz.CGRectGetWidth(mediaBox)
                y = Quartz.CGRectGetHeight(mediaBox)
                x *= scale
                y *= scale
                r = Quartz.CGRectMake(0,0,x, y)
        # Create a Bitmap Context, draw a white background and add the PDF
                writeContext = Quartz.CGBitmapContextCreate(None, int(x), int(y), 8, 0, cs, transparency)
                Quartz.CGContextSaveGState (writeContext)
                Quartz.CGContextScaleCTM(writeContext, scale,scale)
                Quartz.CGContextSetFillColorWithColor(writeContext, whiteColor)
                Quartz.CGContextFillRect(writeContext, r)
                Quartz.CGContextDrawPDFPage(writeContext, page)
                Quartz.CGContextRestoreGState(writeContext)
        # Convert to an "Image"
                image = Quartz.CGBitmapContextCreateImage(writeContext) 
        # Create unique filename per page
                outFile = folderName +"/" + prefix + " %03d.png"%i
                url = Quartz.CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, outFile, len(outFile), False)
        # kUTTypeJPEG, kUTTypeTIFF, kUTTypePNG
                type = kUTTypePNG
        # See the full range of image properties on Apple's developer pages.
                options = {
                    Quartz.kCGImagePropertyDPIHeight: resolution,
                    Quartz.kCGImagePropertyDPIWidth: resolution
                    }
                writeImage (image, url, type, options)
                del page

Minimum and maximum date

From the spec, §15.9.1.1:

A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. A time value may also be NaN, indicating that the Date object does not represent a specific instant of time.

Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values can represent all integers from –9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC.

The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly –100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.

The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0.

The third paragraph being the most relevant. Based on that paragraph, we can get the precise earliest date per spec from new Date(-8640000000000000), which is Tuesday, April 20th, 271,821 BCE (BCE = Before Common Era, e.g., the year -271,821).

IIS Express Windows Authentication

Building upon the answer from booij boy, check if you checked the "windows authentication" feature in Control Panel -> Programs -> Turn windows features on or of -> Internet Information Services -> World Wide Web Services -> Security

Also, there seems to be a big difference when using firefox or internet explorer. After enabeling the "windows authentication" it works for me but only in IE.

How to debug in Django, the good way?

use pdb or ipdb. Diffrence between these two is ipdb supports auto complete.

for pdb

import pdb
pdb.set_trace()

for ipdb

import ipdb
ipdb.set_trace()

For executing new line hit n key, for continue hit c key. check more options by using help(pdb)

Alternative to google finance api

I'd suggest using TradeKing's developer API. It is very good and free to use. All that is required is that you have an account with them and to my knowledge you don't have to carry a balance ... only to be registered.

AngularJS is rendering <br> as text not as a newline

I've used like this

function chatSearchCtrl($scope, $http,$sce) {
 // some more my code

// take this 
data['message'] = $sce.trustAsHtml(data['message']);

$scope.searchresults = data;

and in html I did

<p class="clsPyType clsChatBoxPadding" ng-bind-html="searchresults.message"></p>

thats it I get my <br/> tag rendered

What is the return value of os.system() in Python?

Based on the answer of @AlokThakur (thanks!):

def run_system_command(command):
    return_value = os.system(command)
    # Calculate the return value code
    return_value = int(bin(return_value).replace("0b", "").rjust(16, '0')[:8], 2)
    if return_value != 0:
        raise RuntimeError(f'The system command\n{command}\nexited with return code {return_value}')

How do I read image data from a URL in Python?

Use StringIO to turn the read string into a file-like object:

from StringIO import StringIO
import urllib

Image.open(StringIO(urllib.requests.urlopen(url).read()))

Run a batch file with Windows task scheduler

Under Windows7 Pro, I found that Arun's solution worked for me: I could get this to work even with "no user logged on", I did choose use highest priveledges.

From past experience, you must have an account with a password (blank passwords are no good), and if the program doesn't prompt you for the password when you finish the wizard, go back in and edit something till it does!

This is the method in case its not clear which worked

Action: start a program
Program/script : cmd
      (doesn't need the .exe bit!)
Add arguments:
    /c start "" "E:\Django-1.4.1\setup.bat" 

How to update and order by using ms sql

WITH    q AS
        (
        SELECT  TOP 10 *
        FROM    messages
        WHERE   status = 0
        ORDER BY
                priority DESC
        )
UPDATE  q
SET     status = 10

PHP Parse error: syntax error, unexpected end of file in a CodeIgniter View

Check your short_open_tag setting (use <?php phpinfo() ?> to see its current setting).

Eclipse JPA Project Change Event Handler (waiting)

The issue seems to be resolved with the new Eclipse. The plugin isn't available with Java Enterprise suite.

Shell - How to find directory of some command?

In the TENEX C Shell, tcsh, one can list a command's location(s), or if it is a built-in command, using the where command e.g.:

tcsh% where python
/usr/local/bin/python
/usr/bin/python

tcsh% where cd
cd is a shell built-in
/usr/bin/cd

How do I preserve line breaks when getting text from a textarea?

I suppose you don't want your textarea-content to be parsed as HTML. In this case, you can just set it as plaintext so the browser doesn't treat it as HTML and doesn't remove newlines No CSS or preprocessing required.

_x000D_
_x000D_
<script>_x000D_
function copycontent(){_x000D_
 var content = document.getElementById('ta').value;_x000D_
 document.getElementById('target').innerText = content;_x000D_
}_x000D_
</script>_x000D_
<textarea id='ta' rows='3'>_x000D_
  line 1_x000D_
  line 2_x000D_
  line 3_x000D_
</textarea>_x000D_
<button id='btn' onclick='copycontent();'>_x000D_
Copy_x000D_
</button>_x000D_
<p id='target'></p>
_x000D_
_x000D_
_x000D_

Spring default behavior for lazy-init

The default behaviour is false:

By default, ApplicationContext implementations eagerly create and configure all singleton beans as part of the initialization process. Generally, this pre-instantiation is desirable, because errors in the configuration or surrounding environment are discovered immediately, as opposed to hours or even days later. When this behavior is not desirable, you can prevent pre-instantiation of a singleton bean by marking the bean definition as lazy-initialized. A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.

I suggest reading up

Add attribute 'checked' on click jquery

If .attr() isn't working for you (especially when checking and unchecking boxes in succession), use .prop() instead of .attr().

How to split a string with angularJS

You can try something like this:

$scope.test = "test1,test2";
{{test.split(',')[0]}}

now you will get "test1" while you try {{test.split(',')[0]}}

and you will get "test2" while you try {{test.split(',')[1]}}

here is my plnkr:

http://plnkr.co/edit/jaXOrZX9UO9kmdRMImdN?p=preview

How to specify function types for void (not Void) methods in Java8?

Set return type to Void instead of void and return null

// Modify existing method
public static Void displayInt(Integer i) {
    System.out.println(i);
    return null;
}

OR

// Or use Lambda
myForEach(theList, i -> {System.out.println(i);return null;});

Remove CSS class from element with JavaScript (no jQuery)

document.getElementById("MyID").className =
    document.getElementById("MyID").className.replace(/\bMyClass\b/,'');

where MyID is the ID of the element and MyClass is the name of the class you wish to remove.


UPDATE: To support class names containing dash character, such as "My-Class", use

document.getElementById("MyID").className =
  document.getElementById("MyID").className
    .replace(new RegExp('(?:^|\\s)'+ 'My-Class' + '(?:\\s|$)'), ' ');

How to rotate x-axis tick labels in Pandas barplot

You can use set_xticklabels()

ax.set_xticklabels(df['Names'], rotation=90, ha='right')

Create a list with initial capacity in Python

The Pythonic way for this is:

x = [None] * numElements

Or whatever default value you wish to prepopulate with, e.g.

bottles = [Beer()] * 99
sea = [Fish()] * many
vegetarianPizzas = [None] * peopleOrderingPizzaNotQuiche

(Caveat Emptor: The [Beer()] * 99 syntax creates one Beer and then populates an array with 99 references to the same single instance)

Python's default approach can be pretty efficient, although that efficiency decays as you increase the number of elements.

Compare

import time

class Timer(object):
    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, *args):
        end = time.time()
        secs = end - self.start
        msecs = secs * 1000  # Millisecs
        print('%fms' % msecs)

Elements   = 100000
Iterations = 144

print('Elements: %d, Iterations: %d' % (Elements, Iterations))


def doAppend():
    result = []
    i = 0
    while i < Elements:
        result.append(i)
        i += 1

def doAllocate():
    result = [None] * Elements
    i = 0
    while i < Elements:
        result[i] = i
        i += 1

def doGenerator():
    return list(i for i in range(Elements))


def test(name, fn):
    print("%s: " % name, end="")
    with Timer() as t:
        x = 0
        while x < Iterations:
            fn()
            x += 1


test('doAppend', doAppend)
test('doAllocate', doAllocate)
test('doGenerator', doGenerator)

with

#include <vector>
typedef std::vector<unsigned int> Vec;

static const unsigned int Elements = 100000;
static const unsigned int Iterations = 144;

void doAppend()
{
    Vec v;
    for (unsigned int i = 0; i < Elements; ++i) {
        v.push_back(i);
    }
}

void doReserve()
{
    Vec v;
    v.reserve(Elements);
    for (unsigned int i = 0; i < Elements; ++i) {
        v.push_back(i);
    }
}

void doAllocate()
{
    Vec v;
    v.resize(Elements);
    for (unsigned int i = 0; i < Elements; ++i) {
        v[i] = i;
    }
}

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

void test(const char* name, void(*fn)(void))
{
    cout << name << ": ";

    auto start = chrono::high_resolution_clock::now();
    for (unsigned int i = 0; i < Iterations; ++i) {
        fn();
    }
    auto end = chrono::high_resolution_clock::now();

    auto elapsed = end - start;
    cout << chrono::duration<double, milli>(elapsed).count() << "ms\n";
}

int main()
{
    cout << "Elements: " << Elements << ", Iterations: " << Iterations << '\n';

    test("doAppend", doAppend);
    test("doReserve", doReserve);
    test("doAllocate", doAllocate);
}

On my Windows 7 Core i7, 64-bit Python gives

Elements: 100000, Iterations: 144
doAppend: 3587.204933ms
doAllocate: 2701.154947ms
doGenerator: 1721.098185ms

While C++ gives (built with Microsoft Visual C++, 64-bit, optimizations enabled)

Elements: 100000, Iterations: 144
doAppend: 74.0042ms
doReserve: 27.0015ms
doAllocate: 5.0003ms

C++ debug build produces:

Elements: 100000, Iterations: 144
doAppend: 2166.12ms
doReserve: 2082.12ms
doAllocate: 273.016ms

The point here is that with Python you can achieve a 7-8% performance improvement, and if you think you're writing a high-performance application (or if you're writing something that is used in a web service or something) then that isn't to be sniffed at, but you may need to rethink your choice of language.

Also, the Python code here isn't really Python code. Switching to truly Pythonesque code here gives better performance:

import time

class Timer(object):
    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, *args):
        end = time.time()
        secs = end - self.start
        msecs = secs * 1000  # millisecs
        print('%fms' % msecs)

Elements   = 100000
Iterations = 144

print('Elements: %d, Iterations: %d' % (Elements, Iterations))


def doAppend():
    for x in range(Iterations):
        result = []
        for i in range(Elements):
            result.append(i)

def doAllocate():
    for x in range(Iterations):
        result = [None] * Elements
        for i in range(Elements):
            result[i] = i

def doGenerator():
    for x in range(Iterations):
        result = list(i for i in range(Elements))


def test(name, fn):
    print("%s: " % name, end="")
    with Timer() as t:
        fn()


test('doAppend', doAppend)
test('doAllocate', doAllocate)
test('doGenerator', doGenerator)

Which gives

Elements: 100000, Iterations: 144
doAppend: 2153.122902ms
doAllocate: 1346.076965ms
doGenerator: 1614.092112ms

(in 32-bit, doGenerator does better than doAllocate).

Here the gap between doAppend and doAllocate is significantly larger.

Obviously, the differences here really only apply if you are doing this more than a handful of times or if you are doing this on a heavily loaded system where those numbers are going to get scaled out by orders of magnitude, or if you are dealing with considerably larger lists.

The point here: Do it the Pythonic way for the best performance.

But if you are worrying about general, high-level performance, Python is the wrong language. The most fundamental problem being that Python function calls has traditionally been up to 300x slower than other languages due to Python features like decorators, etc. (PythonSpeed/PerformanceTips, Data Aggregation).

How do I get the last four characters from a string in C#?

A simple solution would be:

string mystring = "34234234d124";
string last4 = mystring.Substring(mystring.Length - 4, 4);

What is the bower (and npm) version syntax?

If there is no patch number, ~ is equivalent to appending .x to the non-tilde version. If there is a patch number, ~ allows all patch numbers >= the specified one.

~1     := 1.x
~1.2   := 1.2.x
~1.2.3 := (>=1.2.3 <1.3.0)

I don't have enough points to comment on the accepted answer, but some of the tilde information is at odds with the linked semver documentation: "angular": "~1.2" will not match 1.3, 1.4, 1.4.9. Also "angular": "~1" and "angular": "~1.0" are not equivalent. This can be verified with the npm semver calculator.

MySQL - count total number of rows in php

Use COUNT in a SELECT query.

$result = mysql_query('SELECT COUNT(1) FROM table');
$num_rows = mysql_result($result, 0, 0);

How to use Oracle's LISTAGG function with a unique filter?

Super simple answer - solved!

my full answer here it is now built in in some oracle versions.

select group_id, 
regexp_replace(
    listagg(name, ',') within group (order by name)
    ,'([^,]+)(,\1)*(,|$)', '\1\3')
from demotable
group by group_id;  

This only works if you specify the delimiter to ',' not ', ' ie works only for no spaces after the comma. If you want spaces after the comma - here is a example how.

select 
replace(
    regexp_replace(
     regexp_replace('BBall, BBall, BBall, Football, Ice Hockey ',',\s*',',')            
    ,'([^,]+)(,\1)*(,|$)', '\1\3')
,',',', ') 
from dual

gives BBall, Football, Ice Hockey

How to decide when to use Node.js?

I can share few points where&why to use node js.

  1. For realtime applications like chat,collaborative editing better we go with nodejs as it is event base where fire event and data to clients from server.
  2. Simple and easy to understand as it is javascript base where most of people have idea.
  3. Most of current web applications going towards angular js&backbone, with node it is easy to interact with client side code as both will use json data.
  4. Lot of plugins available.

Drawbacks:-

  1. Node will support most of databases but best is mongodb which won't support complex joins and others.
  2. Compilation Errors...developer should handle each and every exceptions other wise if any error accord application will stop working where again we need to go and start it manually or using any automation tool.

Conclusion:- Nodejs best to use for simple and real time applications..if you have very big business logic and complex functionality better should not use nodejs. If you want to build an application along with chat and any collaborative functionality.. node can be used in specific parts and remain should go with your convenience technology.

How to convert an int to string in C?

You can use sprintf to do it, or maybe snprintf if you have it:

char str[ENOUGH];
sprintf(str, "%d", 42);

Where the number of characters (plus terminating char) in the str can be calculated using:

(int)((ceil(log10(num))+1)*sizeof(char))

How to switch to other branch in Source Tree to commit the code?

Hi I'm also relatively new but I can give you basic help.

  1. To switch to another branch use "Checkout". Just click on your branch and then on the button "checkout" at the top.

UPDATE 12.01.2016:

The bold line is the current branch.

You can also just double click a branch to use checkout.


  1. Your first answer I think depends on the repository you use (like github or bitbucket). Maybe the "Show hosted repository"-Button can help you (Left panel, bottom, right button = database with cog)

And here some helpful links:

Easy Git Guide

Git-flow - Git branching model

Tips on branching with sourcetree

Hive: Filtering Data between Specified Dates when Date is a String

Hive has a lot of good date parsing UDFs: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions

Just doing the string comparison as Nigel Tufnel suggests is probably the easiest solution, although technically it's unsafe. But you probably don't need to worry about that unless your tables have historical data about the medieval ages (dates with only 3 year digits) or dates from scifi novels (dates with more than 4 year digits).

Anyway, if you ever find yourself in a situation where you would want to do fancier date comparisons, or if your date format is not in a "biggest to smallest" order, e.g. the American convention of "mm/dd/yyyy", then you could use unix_timestamp with two arguments:

select *
from your_table
where unix_timestamp(your_date_column, 'yyyy-MM-dd') >= unix_timestamp('2010-09-01', 'yyyy-MM-dd')
and unix_timestamp(your_date_column, 'yyyy-MM-dd') <= unix_timestamp('2013-08-31', 'yyyy-MM-dd')

Copy mysql database from remote server to local computer

Assuming the following command works successfully:

mysql -u username -p -h remote.site.com

The syntax for mysqldump is identical, and outputs the database dump to stdout. Redirect the output to a local file on the computer:

mysqldump -u username -p -h remote.site.com DBNAME > backup.sql

Replace DBNAME with the name of the database you'd like to download to your computer.

Angular.js How to change an elements css class on click and to remove all others

Typically with Angular you would be outputting these spans using the ngRepeat directive and (like in your case) each item would have an id. I know this is not true for all situations but it is typical if requesting data from a backend - objects in an array tend to have unique identifiers.

You can use this id to facilitate the toggling of classes on items in your list (see plunkr or code below).

Using the objects id's can also eliminate the undesirable effect when the $index (described in other answers) is messed up due to sorting in Angular.

Example Plunkr: http://plnkr.co/edit/na0gUec6cdMABK9L6drV

(basically apply the .active-selection class if the person.id is equal to $scope.activeClass - which we set when the user clicks an item.

Hope this helps someone, I've found expressions in ng-class to be very useful!

HTML

<ul>
  <li ng-repeat="person in people" 
  data-ng-class="{'active-selection': person.id == activeClass}">
    <a data-ng-click="selectPerson(person.id)">
      {{person.name}}
    </a>
  </li>
</ul>

JS

app.controller('MainCtrl', function($scope) {
  $scope.people = [{
    id: "1",
    name: "John",
  }, {
    id: "2",
    name: "Lucy"
  }, {
    id: "3",
    name: "Mark"
  }, {
    id: "4",
    name: "Sam"
  }];

  $scope.selectPerson = function(id) {
    $scope.activeClass = id;
    console.log(id);
  };
});    

CSS:

.active-selection {
  background-color: #eee;
}

ORA-01652 Unable to extend temp segment by in tablespace

I encountered the same error message but don't have any access to the table like "dba_free_space" because I am not a dba. I use some previous answers to check available space and I still have a lot of space. However, after reducing the full table scan as many as possible. The problem is solved. My guess is that Oracle uses temp table to store the full table scan data. It the data size exceeds the limit, it will show the error. Hope this helps someone with the same issue

Convert digits into words with JavaScript

Cleanest and easiest approach that came to mind:

const numberText = {
  1: 'one',
  2: 'two',
  3: 'three',
  4: 'four',
  5: 'five',
  6: 'six',
  7: 'seven',
  8: 'eight',
  9: 'nine',
  10: 'ten',
  11: 'eleven',
  12: 'twelve',
  13: 'thirteen',
  14: 'fourteen',
  15: 'fifteen',
  16: 'sixteen',
  17: 'seventeen',
  18: 'eighteen',
  19: 'nineteen',
  20: 'twenty',
  30: 'thirty',
  40: 'forty',
  50: 'fifty',
  60: 'sixty',
  70: 'seventy',
  80: 'eighty',
  90: 'ninety',
  100: 'hundred',
  1000: 'thousand',
}

const numberValues = Object.keys(numberText)
  .map((val) => Number(val))
  .sort((a, b) => b - a)

const convertNumberToEnglishText = (n) => {
  if (n === 0) return 'zero'
  if (n < 0) return 'negative ' + convertNumberToEnglishText(-n)

  let num = n
  let text = ''

  for (const numberValue of numberValues) {
    const count = Math.trunc(num / numberValue)

    if (count < 1) continue

    if (numberValue >= 100) text += convertNumberToEnglishText(count) + ' '

    text += numberText[numberValue] + ' '
    num -= count * numberValue
  }

  if (num !== 0) throw Error('Something went wrong!')

  return text.trim()
}

Correct location of openssl.cnf file

/usr/local/ssl/openssl.cnf

This is a local installation. You downloaded and built OpenSSL taking the default prefix, of you configured with ./config --prefix=/usr/local/ssl or ./config --openssldir=/usr/local/ssl.

You will use this if you use the OpenSSL in /usr/local/ssl/bin. That is, /usr/local/ssl/openssl.cnf will be used when you issue:

/usr/local/ssl/bin/openssl s_client -connect localhost:443 -tls1 -servername localhost

/usr/lib/ssl/openssl.cnf

This is where Ubuntu places openssl.cnf for the OpenSSL they provide.

You will use this if you use the OpenSSL in /usr/bin. That is, /usr/lib/ssl/openssl.cnf will be used when you issue:

openssl s_client -connect localhost:443 -tls1 -servername localhost

/etc/ssl/openssl.cnf

I don't know when this is used. The stuff in /etc/ssl is usually certificates and private keys, and it sometimes contains a copy of openssl.cnf. But I've never seen it used for anything.


Which is the main/correct one that I should use to make changes?

From the sounds of it, you should probably add the engine to /usr/lib/ssl/openssl.cnf. That ensures most "off the shelf" gear will use the new engine.

After you do that, add it to /usr/local/ssl/openssl.cnf also because copy/paste is easy.


Here's how to see which openssl.cnf directory is associated with a OpenSSL installation. The library and programs look for openssl.cnf in OPENSSLDIR. OPENSSLDIR is a configure option, and its set with --openssldir.

I'm on a MacBook with 3 different OpenSSL's (Apple's, MacPort's and the one I build):

# Apple    
$ /usr/bin/openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/System/Library/OpenSSL"

# MacPorts
$ /opt/local/bin/openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/opt/local/etc/openssl"

# My build of OpenSSL
$ openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/usr/local/ssl/darwin"

I have an Ubuntu system and I have installed openssl.

Just bike shedding, but be careful of Ubuntu's version of OpenSSL. It disables TLSv1.1 and TLSv1.2, so you will only have clients capable of older cipher suites; and you will not be able to use newer ciphers like AES/CTR (to replace RC4) and elliptic curve gear (like ECDHE_ECDSA_* and ECDHE_RSA_*). See Ubuntu 12.04 LTS: OpenSSL downlevel version is 1.0.0, and does not support TLS 1.2 in Launchpad.

EDIT: Ubuntu enabled TLS 1.1 and TLS 1.2 recently. See Comment 17 on the bug report.

Replace tabs with spaces in vim

This worked for me:

you can see tabs with first doing this:

:set list

then to make it possible to replace tabs then do this:

:set expandtab

then

:retab

now all tabs have been replaced with spaces you can then go back to normal viewing like this :

:set nolist

Android lollipop change navigation bar color

You can also modify your theme using theme Editor by clicking :

Tools -> Android -> Theme Editor

Then, you don't even need to put some extra content in your .xml or .class files.

When is TCP option SO_LINGER (0) required?

For my suggestion, please read the last section: “When to use SO_LINGER with timeout 0”.

Before we come to that a little lecture about:

  • Normal TCP termination
  • TIME_WAIT
  • FIN, ACK and RST

Normal TCP termination

The normal TCP termination sequence looks like this (simplified):

We have two peers: A and B

  1. A calls close()
    • A sends FIN to B
    • A goes into FIN_WAIT_1 state
  2. B receives FIN
    • B sends ACK to A
    • B goes into CLOSE_WAIT state
  3. A receives ACK
    • A goes into FIN_WAIT_2 state
  4. B calls close()
    • B sends FIN to A
    • B goes into LAST_ACK state
  5. A receives FIN
    • A sends ACK to B
    • A goes into TIME_WAIT state
  6. B receives ACK
    • B goes to CLOSED state – i.e. is removed from the socket tables

TIME_WAIT

So the peer that initiates the termination – i.e. calls close() first – will end up in the TIME_WAIT state.

To understand why the TIME_WAIT state is our friend, please read section 2.7 in "UNIX Network Programming" third edition by Stevens et al (page 43).

However, it can be a problem with lots of sockets in TIME_WAIT state on a server as it could eventually prevent new connections from being accepted.

To work around this problem, I have seen many suggesting to set the SO_LINGER socket option with timeout 0 before calling close(). However, this is a bad solution as it causes the TCP connection to be terminated with an error.

Instead, design your application protocol so the connection termination is always initiated from the client side. If the client always knows when it has read all remaining data it can initiate the termination sequence. As an example, a browser knows from the Content-Length HTTP header when it has read all data and can initiate the close. (I know that in HTTP 1.1 it will keep it open for a while for a possible reuse, and then close it.)

If the server needs to close the connection, design the application protocol so the server asks the client to call close().

When to use SO_LINGER with timeout 0

Again, according to "UNIX Network Programming" third edition page 202-203, setting SO_LINGER with timeout 0 prior to calling close() will cause the normal termination sequence not to be initiated.

Instead, the peer setting this option and calling close() will send a RST (connection reset) which indicates an error condition and this is how it will be perceived at the other end. You will typically see errors like "Connection reset by peer".

Therefore, in the normal situation it is a really bad idea to set SO_LINGER with timeout 0 prior to calling close() – from now on called abortive close – in a server application.

However, certain situation warrants doing so anyway:

  • If the a client of your server application misbehaves (times out, returns invalid data, etc.) an abortive close makes sense to avoid being stuck in CLOSE_WAIT or ending up in the TIME_WAIT state.
  • If you must restart your server application which currently has thousands of client connections you might consider setting this socket option to avoid thousands of server sockets in TIME_WAIT (when calling close() from the server end) as this might prevent the server from getting available ports for new client connections after being restarted.
  • On page 202 in the aforementioned book it specifically says: "There are certain circumstances which warrant using this feature to send an abortive close. One example is an RS-232 terminal server, which might hang forever in CLOSE_WAIT trying to deliver data to a stuck terminal port, but would properly reset the stuck port if it got an RST to discard the pending data."

I would recommend this long article which I believe gives a very good answer to your question.

first-child and last-child with IE8

If you want to carry on using CSS3 selectors but need to support older browsers I would suggest using a polyfill such as Selectivizr.js

Convert text into number in MySQL query

This should work:

SELECT field,CONVERT(SUBSTRING_INDEX(field,'-',-1),UNSIGNED INTEGER) AS num
FROM table
ORDER BY num;

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

Little sum up for searching by row:

This can be useful if you don't know the column values ??or if columns have non-numeric values

if u want get index number as integer u can also do:

item = df[4:5].index.item()
print(item)
4

it also works in numpy / list:

numpy = df[4:7].index.to_numpy()[0]
lista = df[4:7].index.to_list()[0]

in [x] u pick number in range [4:7], for example if u want 6:

numpy = df[4:7].index.to_numpy()[2]
print(numpy)
6

for DataFrame:

df[4:7]

    A          B
4   5   0.894525
5   6   0.978174
6   7   0.859449

or:

df[(df.index>=4) & (df.index<7)]

    A          B
4   5   0.894525
5   6   0.978174
6   7   0.859449   

Get device information (such as product, model) from adb command

The correct way to do it would be:

adb -s 123abc12 shell getprop

Which will give you a list of all available properties and their values. Once you know which property you want, you can give the name as an argument to getprop to access its value directly, like this:

adb -s 123abc12 shell getprop ro.product.model

The details in adb devices -l consist of the following three properties: ro.product.name, ro.product.model and ro.product.device.

Note that ADB shell ends lines with \r\n, which depending on your platform might or might not make it more difficult to access the exact value (e.g. instead of Nexus 7 you might get Nexus 7\r).

How different is Objective-C from C++?

They're completely different. Objective C has more in common with Smalltalk than with C++ (well, except for the syntax, really).

How to check if object has any properties in JavaScript?

You can use the following:

Double bang !! property lookup

var a = !![]; // true
var a = !!null; // false

hasOwnProperty This is something that I used to use:

var myObject = {
  name: 'John',
  address: null
};
if (myObject.hasOwnProperty('address')) { // true
  // do something if it exists.
}

However, JavaScript decided not to protect the method’s name, so it could be tampered with.

var myObject = {
  hasOwnProperty: 'I will populate it myself!'
};

prop in myObject

var myObject = {
  name: 'John',
  address: null,
  developer: false
};
'developer' in myObject; // true, remember it's looking for exists, not value.

typeof

if (typeof myObject.name !== 'undefined') {
  // do something
}

However, it doesn't check for null.

I think this is the best way.

in operator

var myObject = {
  name: 'John',
  address: null
};

if('name' in myObject) {
  console.log("Name exists in myObject");
}else{
  console.log("Name does not exist in myObject");
}

result:

Name exists in myObject

Here is a link that goes into more detail on the in operator: Determining if an object property exists

Android: Background Image Size (in Pixel) which Support All Devices

The following are the best dimensions for the app to run in all devices. For understanding multiple supporting screens you have to read http://developer.android.com/guide/practices/screens_support.html

xxxhdpi: 1280x1920 px
xxhdpi: 960x1600 px
xhdpi: 640x960 px
hdpi: 480x800 px
mdpi: 320x480 px
ldpi: 240x320 px

How to find schema name in Oracle ? when you are connected in sql session using read only user

Call SYS_CONTEXT to get the current schema. From Ask Tom "How to get current schema:

select sys_context( 'userenv', 'current_schema' ) from dual;

jQuery form validation on button click

You can also achieve other way using button tag

According new html5 attribute you also can add a form attribute like

<form id="formId">
    <input type="text" name="fname">
</form>

<button id="myButton" form='#formId'>My Awesome Button</button>

So the button will be attached to the form.

This should work with the validate() plugin of jQuery like :

var validator = $( "#formId" ).validate();
validator.element( "#myButton" );

It's working too with input tag

Source :

https://developer.mozilla.org/docs/Web/HTML/Element/Button

if arguments is equal to this string, define a variable like this string

It seems that you are looking to parse commandline arguments into your bash script. I have searched for this recently myself. I came across the following which I think will assist you in parsing the arguments:

http://rsalveti.wordpress.com/2007/04/03/bash-parsing-arguments-with-getopts/

I added the snippet below as a tl;dr

#using : after a switch variable means it requires some input (ie, t: requires something after t to validate while h requires nothing.
while getopts “ht:r:p:v” OPTION
do
     case $OPTION in
         h)
             usage
             exit 1
             ;;
         t)
             TEST=$OPTARG
             ;;
         r)
             SERVER=$OPTARG
             ;;
         p)
             PASSWD=$OPTARG
             ;;
         v)
             VERBOSE=1
             ;;
         ?)
             usage
             exit
             ;;
     esac
done

if [[ -z $TEST ]] || [[ -z $SERVER ]] || [[ -z $PASSWD ]]
then
     usage
     exit 1
fi

./script.sh -t test -r server -p password -v

Remove last 3 characters of string or number in javascript

you just need to divide the Date Time stamp by 1000 like:

var a = 1437203995000;
a = (a)/1000;

How to Correctly handle Weak Self in Swift Blocks with Arguments

[Closure and strong reference cycles]

As you know Swift's closure can capture the instance. It means that you are able to use self inside a closure. Especially escaping closure[About] can create a strong reference cycle[About]. By the way you have to explicitly use self inside escaping closure.

Swift closure has Capture List feature which allows you to avoid such situation and break a reference cycle because do not have a strong reference to captured instance. Capture List element is a pair of weak/unowned and a reference to class or variable.

For example

class A {
    private var completionHandler: (() -> Void)!
    private var completionHandler2: ((String) -> Bool)!
    
    func nonescapingClosure(completionHandler: () -> Void) {
        print("Hello World")
    }
    
    func escapingClosure(completionHandler: @escaping () -> Void) {
        self.completionHandler = completionHandler
    }
    
    func escapingClosureWithPArameter(completionHandler: @escaping (String) -> Bool) {
        self.completionHandler2 = completionHandler
    }
}

class B {
    var variable = "Var"
    
    func foo() {
        let a = A()
        
        //nonescapingClosure
        a.nonescapingClosure {
            variable = "nonescapingClosure"
        }
        
        //escapingClosure
        //strong reference cycle
        a.escapingClosure {
            self.variable = "escapingClosure"
        }
        
        //Capture List - [weak self]
        a.escapingClosure {[weak self] in
            self?.variable = "escapingClosure"
        }
        
        //Capture List - [unowned self]
        a.escapingClosure {[unowned self] in
            self.variable = "escapingClosure"
        }
        
        //escapingClosureWithPArameter
        a.escapingClosureWithPArameter { [weak self] (str) -> Bool in
            self?.variable = "escapingClosureWithPArameter"
            return true
        }
    }
}
  • weak - more preferable, use it when it is possible
  • unowned - use it when you are sure that lifetime of instance owner is bigger than closure

[weak vs unowned]

Return Boolean Value on SQL Select Statement

DECLARE @isAvailable      BIT = 0;

IF EXISTS(SELECT 1  FROM [User] WHERE (UserID = 20070022))
BEGIN
 SET @isAvailable = 1
END

initially isAvailable boolean value is set to 0

How to view file history in Git?

git log --all -- path/to/file should work

Setting default value in select drop-down using Angularjs

<select ng-init="somethingHere = options[0]" ng-model="somethingHere" ng-options="option.name for option in options"></select>

This would get you desired result Dude :) Cheers

Android check null or empty string in Android

Incase all the answer given does not work, kindly try

String myString = null;

if(myString.trim().equalsIgnoreCase("null")){
    //do something
}

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

I noticed this commit comment in AOSP, the solution will be to exclude some files using DSL. Probably when 0.7.1 is released.

commit e7669b24c1f23ba457fdee614ef7161b33feee69
Author: Xavier Ducrohet <--->
Date:   Thu Dec 19 10:21:04 2013 -0800

    Add DSL to exclude some files from packaging.

    This only applies to files coming from jar dependencies.
    The DSL is:

    android {
      packagingOptions {
        exclude 'META-INF/LICENSE.txt'
      }
    }

Fade Effect on Link Hover?

Try this in your css:

.a {
    transition: color 0.3s ease-in-out;
}
.a {
    color:turquoise;
}
.a:hover {
    color: #454545;
}

Target Unreachable, identifier resolved to null in JSF 2.2

  1. You need

    @ManagedBean(name="userBean")

  2. Make sure you have getUser() method.

  3. Type of setUser() method should be void.

  4. Make sure that User class has proper setters and getters as well.

Python 3 Online Interpreter / Shell

Ideone supports Python 2.6 and Python 3

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

Create a File object in memory from a string in Java

FileReader r = new FileReader(file);

Use a file reader load the file and then write its contents to a string buffer.

example

The link above shows you an example of how to accomplish this. As other post to this answer say to load a file into memory you do not need write access as long as you do not plan on making changes to the actual file.

Exporting functions from a DLL with dllexport

I think _naked might get what you want, but it also prevents the compiler from generating the stack management code for the function. extern "C" causes C style name decoration. Remove that and that should get rid of your _'s. The linker doesn't add the underscores, the compiler does. stdcall causes the argument stack size to be appended.

For more, see: http://en.wikipedia.org/wiki/X86_calling_conventions http://www.codeproject.com/KB/cpp/calling_conventions_demystified.aspx

The bigger question is why do you want to do that? What's wrong with the mangled names?

How to quickly drop a user with existing privileges

How about

DROP USER <username>

This is actually an alias for DROP ROLE.

You have to explicity drop any privileges associated with that user, also to move its ownership to other roles (or drop the object).

This is best achieved by

REASSIGN OWNED BY <olduser> TO <newuser>

and

DROP OWNED BY <olduser>

The latter will remove any privileges granted to the user.

See the postgres docs for DROP ROLE and the more detailed description of this.


Addition:

Apparently, trying to drop a user by using the commands mentioned here will only work if you are executing them while being connected to the same database that the original GRANTS were made from, as discussed here:

https://www.postgresql.org/message-id/83894A1821034948BA27FE4DAA47427928F7C29922%40apde03.APD.Satcom.Local

Concatenate two NumPy arrays vertically

a = np.array([1,2,3])
b = np.array([4,5,6])
np.array((a,b))

works just as well as

np.array([[1,2,3], [4,5,6]])

Regardless of whether it is a list of lists or a list of 1d arrays, np.array tries to create a 2d array.

But it's also a good idea to understand how np.concatenate and its family of stack functions work. In this context concatenate needs a list of 2d arrays (or any anything that np.array will turn into a 2d array) as inputs.

np.vstack first loops though the inputs making sure they are at least 2d, then does concatenate. Functionally it's the same as expanding the dimensions of the arrays yourself.

np.stack is a new function that joins the arrays on a new dimension. Default behaves just like np.array.

Look at the code for these functions. If written in Python you can learn quite a bit. For vstack:

return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)

How to display a jpg file in Python?

from PIL import Image

image = Image.open('File.jpg')
image.show()

Send data from a textbox into Flask?

Assuming you already know how to write a view in Flask that responds to a url, create one that reads the request.post data. To add the input box to this post data create a form on your page with the text box. You can then use jquery to do

var data = $('#<form-id>').serialize()

and then post to your view asynchronously using something like the below.

$.post('<your view url>', function(data) {
  $('.result').html(data);
});

Difference in months between two dates

This worked for what I needed it for. The day of month didn't matter in my case because it always happens to be the last day of the month.

public static int MonthDiff(DateTime d1, DateTime d2){
    int retVal = 0;

    if (d1.Month<d2.Month)
    {
        retVal = (d1.Month + 12) - d2.Month;
        retVal += ((d1.Year - 1) - d2.Year)*12;
    }
    else
    {
        retVal = d1.Month - d2.Month;
        retVal += (d1.Year - d2.Year)*12;
    }
    //// Calculate the number of years represented and multiply by 12
    //// Substract the month number from the total
    //// Substract the difference of the second month and 12 from the total
    //retVal = (d1.Year - d2.Year) * 12;
    //retVal = retVal - d1.Month;
    //retVal = retVal - (12 - d2.Month);

    return retVal;
}

How do I move an existing Git submodule within a Git repository?

The given solution did not work for me, however a similar version did...

This is with a cloned repository, hence the submodule git repos are contained in the top repositories .git dir. All cations are from the top repository:

  1. Edit .gitmodules and change the "path =" setting for the submodule in question. (No need to change the label, nor to add this file to index.)

  2. Edit .git/modules/name/config and change the "worktree =" setting for the submodule in question

  3. run:

    mv submodule newpath/submodule
    git add -u
    git add newpath/submodule
    

I wonder if it makes a difference if the repositories are atomic, or relative submodules, in my case it was relative (submodule/.git is a ref back to topproject/.git/modules/submodule)

How to Create a real one-to-one relationship in SQL Server

A 1 to 1 relationship is very much possible. Even if the relationship diagram doesn't show the 1 to 1 relationship explicitly. If you implement it as below, it will function as a one to one relationship.

I will use a basic example to explain the concept where a single person can only have a single passport. This example works perfectly in MS Access. For the SQL Server version follow this link.

Remember that in MS Access, SQL scripts can only be run one at a time and not as displayed here in sequence.

CREATE TABLE Person
(
Pk_Person_Id INT PRIMARY KEY,
Name VARCHAR(255),
EmailId VARCHAR(255),
);

CREATE TABLE PassportDetails
(
Pk_Passport_Id INT PRIMARY KEY,
Passport_Number VARCHAR(255),
Fk_Person_Id INT NOT NULL UNIQUE, 
FOREIGN KEY(Fk_Person_Id) REFERENCES Person(Pk_Person_Id)
);

Implementing Singleton with an Enum (in Java)

Like all enum instances, Java instantiates each object when the class is loaded, with some guarantee that it's instantiated exactly once per JVM. Think of the INSTANCE declaration as a public static final field: Java will instantiate the object the first time the class is referred to.

The instances are created during static initialization, which is defined in the Java Language Specification, section 12.4.

For what it's worth, Joshua Bloch describes this pattern in detail as item 3 of Effective Java Second Edition.

Vim clear last search highlighting

One more solution by combining 2 top answers:

"To clear the last used search pattern:
nnoremap <F3> :let @/ = ""<CR>

Has been compiled by a more recent version of the Java Runtime (class file version 57.0)

This is a setting in IntelliJ IDEA ($JAVA_HOME and language level were set to 1.8):

File > Settings > Build, Execution, Deployment > Gradle > Gradle JVM

Select eg. Project SDK (corretto-1.8) (or any other compatible version).

Then delete the build directory and restart the IDE.

binning data in python with scipy/numpy

Not sure why this thread got necroed; but here is a 2014 approved answer, which should be far faster:

import numpy as np

data = np.random.rand(100)
bins = 10
slices = np.linspace(0, 100, bins+1, True).astype(np.int)
counts = np.diff(slices)

mean = np.add.reduceat(data, slices[:-1]) / counts
print mean

Uncaught SyntaxError: Unexpected token < On Chrome

I have commented my this code : // $('#description').val('<?php echo $_POST['description']; ?>'); and I got that error.

What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?

The size of storage required and how big the numbers can be.

On SQL Server:

  • tinyint 1 byte, 0 to 255
  • smallint 2 bytes, -215 (-32,768) to 215-1 (32,767)
  • int 4 bytes, -231 (-2,147,483,648) to 231-1 (2,147,483,647)
  • bigint 8 bytes, -263 (-9,223,372,036,854,775,808) to 263-1 (9,223,372,036,854,775,807)

You can store the number 1 in all 4, but a bigint will use 8 bytes, while a tinyint will use 1 byte.

Select All Rows Using Entity Framework

You can use this code to select all rows :

C# :

var allStudents = [modelname].[tablename].Select(x => x).ToList();

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

jQuery's underlying code passes these strings to the DOM, which allows you to specify the CSS property name or the DOM property name in a very similar way:

element.style.marginLeft = "10px";

is equivalent to:

element.style["margin-left"] = "10px";

Why has jQuery allowed for marginLeft as well as margin-left? It seems pointless and uses more resources to be converted to the CSS margin-left?

jQuery's not really doing anything special. It may alter or proxy some strings that you pass to .css(), but in reality there was no work put in from the jQuery team to allow either string to be passed. There's no extra resources used because the DOM does the work.

Python: How to increase/reduce the fontsize of x and y tick labels?

One shouldn't use set_yticklabels to change the fontsize, since this will also set the labels (i.e. it will replace any automatic formatter by a FixedFormatter), which is usually undesired. The easiest is to set the respective tick_params:

ax.tick_params(axis="x", labelsize=8)
ax.tick_params(axis="y", labelsize=20)

or

ax.tick_params(labelsize=8)

in case both axes shall have the same size.

Of course using the rcParams as in @tmdavison's answer is possible as well.

Default username password for Tomcat Application Manager

To reset your keyring.

  1. Go into your home folder.

  2. Press ctrl & h to show your hidden folders.

  3. Now look in your .gnome2/keyrings directory.

  4. Find the default.keyring file.

  5. Move that file to a different folder.

  6. Once done, reboot your computer.

How to launch jQuery Fancybox on page load?

Fancybox currently does not directly support a way to automatically launch. The work around I was able to get working is creating a hidden anchor tag and triggering it's click event. Make sure your call to trigger the click event is included after the jQuery and Fancybox JS files are included. The code I used is as follows:

This sample script is embedded directly in the HTML, but it could also be included in a JS file.

<script type="text/javascript">
    $(document).ready(function() {
        $("#hidden_link").fancybox().trigger('click');
    });
</script>

Random number generator only generating one random number

There are a lot of solutions, here one: if you want only number erase the letters and the method receives a random and the result length.

public String GenerateRandom(Random oRandom, int iLongitudPin)
{
    String sCharacters = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
    int iLength = sCharacters.Length;
    char cCharacter;
    int iLongitudNuevaCadena = iLongitudPin; 
    String sRandomResult = "";
    for (int i = 0; i < iLongitudNuevaCadena; i++)
    {
        cCharacter = sCharacters[oRandom.Next(iLength)];
        sRandomResult += cCharacter.ToString();
    }
    return (sRandomResult);
}

How to set TextView textStyle such as bold, italic

Programmatically:

You can do programmatically using setTypeface() method:

Below is the code for default Typeface

textView.setTypeface(null, Typeface.NORMAL);      // for Normal Text
textView.setTypeface(null, Typeface.BOLD);        // for Bold only
textView.setTypeface(null, Typeface.ITALIC);      // for Italic
textView.setTypeface(null, Typeface.BOLD_ITALIC); // for Bold and Italic

and if you want to set custom Typeface:

textView.setTypeface(textView.getTypeface(), Typeface.NORMAL);      // for Normal Text
textView.setTypeface(textView.getTypeface(), Typeface.BOLD);        // for Bold only
textView.setTypeface(textView.getTypeface(), Typeface.ITALIC);      // for Italic
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC); // for Bold and Italic

XML:

You can set directly in XML file in <TextView /> like this:

android:textStyle="normal"
android:textStyle="normal|bold"
android:textStyle="normal|italic"
android:textStyle="bold"
android:textStyle="bold|italic"

Or you can set your fav font (from assets). for more info see link

Append file contents to the bottom of existing file in Bash

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

Free easy way to draw graphs and charts in C++?

I've used this "portable plotter". It's very small, multiplatform, easy to use and you can plug it into different graphical libraries. pplot

(Only for the plots part)

If you use or plan to use Qt, another multiplatform solution is Qwt and Qchart

Git copy file preserving history

I've slightly modified Peter's answer here to create a reusable, non-interactive shell script called git-split.sh:

#!/bin/sh

if [[ $# -ne 2 ]] ; then
  echo "Usage: git-split.sh original copy"
  exit 0
fi

git mv "$1" "$2"
git commit -n -m "Split history $1 to $2 - rename file to target-name"
REV=`git rev-parse HEAD`
git reset --hard HEAD^
git mv "$1" temp
git commit -n -m "Split history $1 to $2 - rename source-file to temp"
git merge $REV
git commit -a -n -m "Split history $1 to $2 - resolve conflict and keep both files"
git mv temp "$1"
git commit -n -m "Split history $1 to $2 - restore name of source-file"

Why XML-Serializable class need a parameterless constructor

This is a limitation of XmlSerializer. Note that BinaryFormatter and DataContractSerializer do not require this - they can create an uninitialized object out of the ether and initialize it during deserialization.

Since you are using xml, you might consider using DataContractSerializer and marking your class with [DataContract]/[DataMember], but note that this changes the schema (for example, there is no equivalent of [XmlAttribute] - everything becomes elements).

Update: if you really want to know, BinaryFormatter et al use FormatterServices.GetUninitializedObject() to create the object without invoking the constructor. Probably dangerous; I don't recommend using it too often ;-p See also the remarks on MSDN:

Because the new instance of the object is initialized to zero and no constructors are run, the object might not represent a state that is regarded as valid by that object. The current method should only be used for deserialization when the user intends to immediately populate all fields. It does not create an uninitialized string, since creating an empty instance of an immutable type serves no purpose.

I have my own serialization engine, but I don't intend making it use FormatterServices; I quite like knowing that a constructor (any constructor) has actually executed.

How do I get an apk file from an Android device?

If you know (or if you can "guess") the path to the .apk (it seems to be of the format /data/app/com.example.someapp-{1,2,..}.apk to , then you can just copy it from /data/app as well. This worked even on my non-rooted, stock Android phone.

Just use a Terminal Emulator app (such as this one) and run:

# step 1: confirm path
ls /data/app/com.example.someapp-1.apk
# if it doesn't show up, try -2, -3. Note that globbing (using *) doesn't work here.
# step 2: copy (make sure you adapt the path to match what you discovered above)
cp /data/app/com.example.someapp-1.apk /mnt/sdcard/

Then you can move it from the SD-card to wherever you want (or attach it to an email etc). The last bit might be technically optional, but it makes your life a lot easier when trying to do something with the .apk file.

What's the quickest way to multiply multiple cells by another number?

If it doesn't need to be a macro, then just put =A1*1.1 into (say) D7, then drag the formula fill handle across, then down.

How to get the input from the Tkinter Text Widget?

To get Tkinter input from the text box, you must add a few more attributes to the normal .get() function. If we have a text box myText_Box, then this is the method for retrieving its input.

def retrieve_input():
    input = self.myText_Box.get("1.0",END)

The first part, "1.0" means that the input should be read from line one, character zero (ie: the very first character). END is an imported constant which is set to the string "end". The END part means to read until the end of the text box is reached. The only issue with this is that it actually adds a newline to our input. So, in order to fix it we should change END to end-1c(Thanks Bryan Oakley) The -1c deletes 1 character, while -2c would mean delete two characters, and so on.

def retrieve_input():
    input = self.myText_Box.get("1.0",'end-1c')

How can I calculate divide and modulo for integers in C#?

Division is performed using the / operator:

result = a / b;

Modulo division is done using the % operator:

result = a % b;

How to send an email from JavaScript

If and only if i had to use some js library, i would do that with SMTPJs library.It offers encryption to your credentials such as username, password etc.

concat scope variables into string in angular directive expression

<a ngHref="/path/{{obj.val1}}/{{obj.val2}}">{{obj.val1}}, {{obj.val2}}</a>

JSON.parse unexpected token s

valid json string must have double quote.

JSON.parse({"u1":1000,"u2":1100})       // will be ok

no quote cause error

JSON.parse({u1:1000,u2:1100})    
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2

single quote cause error

JSON.parse({'u1':1000,'u2':1100})    
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2

You must valid json string at https://jsonlint.com

How to comment multiple lines with space or indent

  • You can customize every short cut operation according to your habbit.

Just go to Tools > Options > Environment > Keyboard > Find the action you want to set key board short-cut and change according to keyboard habbit.

Get Current date in epoch from Unix shell script

echo $(($(date +%s) / 60 / 60 / 24))

How can I add JAR files to the web-inf/lib folder in Eclipse?

add the jar to WEB-INF/lib from file structure refresh the project, you should see the jar now visible under the WEB-INF/lib folder.

this is the best solution that worked for me

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

One possible explanation is a database trigger that fires for each DROP TABLE statement. To find the trigger, query the _TRIGGERS dictionary views:

select * from all_triggers
where trigger_type in ('AFTER EVENT', 'BEFORE EVENT')

disable any suspicious trigger with

   alter trigger <trigger_name> disable;

and try re-running your DROP TABLE statement

How can I get dict from sqlite query?

Or you could convert the sqlite3.Rows to a dictionary as follows. This will give a dictionary with a list for each row.

    def from_sqlite_Row_to_dict(list_with_rows):
    ''' Turn a list with sqlite3.Row objects into a dictionary'''
    d ={} # the dictionary to be filled with the row data and to be returned

    for i, row in enumerate(list_with_rows): # iterate throw the sqlite3.Row objects            
        l = [] # for each Row use a separate list
        for col in range(0, len(row)): # copy over the row date (ie. column data) to a list
            l.append(row[col])
        d[i] = l # add the list to the dictionary   
    return d

Whitespaces in java

From sun docs:

\s A whitespace character: [ \t\n\x0B\f\r]

The simplest way is to use it with regex.

How do I rename a repository on GitHub?

  • Navigate to your repository path.
  • Click on setting button which is there in right panne.
  • Replace old repository name to new name.
  • Click on Rename button

Removing Data From ElasticSearch

You have to send a DELETE request to

http://[your_host]:9200/[your_index_name_here]

You can also delete a single document:

http://[your_host]:9200/[your_index_name_here]/[your_type_here]/[your_doc_id]

I suggest you to use elastichammer.

After deleting you can look up if the index still exists with the following URL: http://[your_host]:9200/_stats/

Good luck!

How to hide close button in WPF window?

Use WindowStyle="SingleBorderWindow" , this will hide max and min button from WPF Window.

How to make git mark a deleted and a new file as a file move?

When I edit, rename, and move a file at the same time, none of these solutions work. The solution is to do it in two commits (edit and rename/move seperate) and then fixup the second commit via git rebase -i to have it in one commit.

Combining "LIKE" and "IN" for SQL Server

You need multiple LIKE clauses connected by OR.

SELECT * FROM table WHERE 
column LIKE 'Text%' OR 
column LIKE 'Link%' OR 
column LIKE 'Hello%' OR 
column LIKE '%World%' OR 

Adding text to a cell in Excel using VBA

Range("$A$1").Value = "'01/01/13 00:00" will do it.

Note the single quote; this will defeat automatic conversion to a number type. But is that what you really want? An alternative would be to format the cell to take a date-time value. Then drop the single quote from the string.

How do I make a dictionary with multiple keys to one value?

Your example creates multiple key: value pairs if using fromkeys. If you don't want this, you can use one key and create an alias for the key. For example if you are using a register map, your key can be the register address and the alias can be register name. That way you can perform read/write operations on the correct register.

>>> mydict = {}
>>> mydict[(1,2)] = [30, 20]
>>> alias1 = (1,2)
>>> print mydict[alias1]
[30, 20]
>>> mydict[(1,3)] = [30, 30]
>>> print mydict
{(1, 2): [30, 20], (1, 3): [30, 30]}
>>> alias1 in mydict
True

Output grep results to text file, need cleaner output

Redirection of program output is performed by the shell.

grep ... > output.txt

grep has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1) man page for details, specifically the -C and --color options.

How to calculate an angle from three points?

I ran into a similar problem recently, only I needed to differentiate between a positive and negative angles. In case this is of use to anyone, I recommend the code snippet I grabbed from this mailing list about detecting rotation over a touch event for Android:

 @Override
 public boolean onTouchEvent(MotionEvent e) {
    float x = e.getX();
    float y = e.getY();
    switch (e.getAction()) {
    case MotionEvent.ACTION_MOVE:
       //find an approximate angle between them.

       float dx = x-cx;
       float dy = y-cy;
       double a=Math.atan2(dy,dx);

       float dpx= mPreviousX-cx;
       float dpy= mPreviousY-cy;
       double b=Math.atan2(dpy, dpx);

       double diff  = a-b;
       this.bearing -= Math.toDegrees(diff);
       this.invalidate();
    }
    mPreviousX = x;
    mPreviousY = y;
    return true;
 }

C# Checking if button was clicked

Click is an event that fires immediately after you release the mouse button. So if you want to check in the handler for button2.Click if button1 was clicked before, all you could do is have a handler for button1.Click which sets a bool flag of your own making to true.

private bool button1WasClicked = false;

private void button1_Click(object sender, EventArgs e)
{
    button1WasClicked = true;
}

private void button2_Click(object sender, EventArgs e)
{
    if (textBox2.Text == textBox3.Text && button1WasClicked)
    { 
        StreamWriter myWriter = File.CreateText(@"c:\Program Files\text.txt");
        myWriter.WriteLine(textBox1.Text);
        myWriter.WriteLine(textBox2.Text);
        button1WasClicked = false;
    }
}

How to change fonts in matplotlib (python)?

The Helvetica font does not come included with Windows, so to use it you must download it as a .ttf file. Then you can refer matplotlib to it like this (replace "crm10.ttf" with your file):

import os
from matplotlib import font_manager as fm, rcParams
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

fpath = os.path.join(rcParams["datapath"], "fonts/ttf/cmr10.ttf")
prop = fm.FontProperties(fname=fpath)
fname = os.path.split(fpath)[1]
ax.set_title('This is a special font: {}'.format(fname), fontproperties=prop)
ax.set_xlabel('This is the default font')

plt.show()

print(fpath) will show you where you should put the .ttf.

You can see the output here: https://matplotlib.org/gallery/api/font_file.html

Run Command Line & Command From VBS

The problem is on this line:

oShell.run "cmd.exe /C copy "S:Claims\Sound.wav" "C:\WINDOWS\Media\Sound.wav"

Your first quote next to "S:Claims" ends the string; you need to escape the quotes around your files with a second quote, like this:

oShell.run "cmd.exe /C copy ""S:\Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "

You also have a typo in S:Claims\Sound.wav, should be S:\Claims\Sound.wav.

I also assume the apostrophe before Dim oShell and after Set oShell = Nothing are typos as well.

Horizontal Scroll Table in Bootstrap/CSS

Here is one possiblity for you if you are using Bootstrap 3

live view: http://fiddle.jshell.net/panchroma/vPH8N/10/show/

edit view: http://jsfiddle.net/panchroma/vPH8N/

I'm using the resposive table code from http://getbootstrap.com/css/#tables-responsive

ie:

<div class="table-responsive">
<table class="table">
...
</table>
</div>

Creating C formatted strings (not printing them)

If you have the code to log_out(), rewrite it. Most likely, you can do:

static FILE *logfp = ...;

void log_out(const char *fmt, ...)
{
    va_list args;

    va_start(args, fmt);
    vfprintf(logfp, fmt, args);
    va_end(args);
}

If there is extra logging information needed, that can be printed before or after the message shown. This saves memory allocation and dubious buffer sizes and so on and so forth. You probably need to initialize logfp to zero (null pointer) and check whether it is null and open the log file as appropriate - but the code in the existing log_out() should be dealing with that anyway.

The advantage to this solution is that you can simply call it as if it was a variant of printf(); indeed, it is a minor variant on printf().

If you don't have the code to log_out(), consider whether you can replace it with a variant such as the one outlined above. Whether you can use the same name will depend on your application framework and the ultimate source of the current log_out() function. If it is in the same object file as another indispensable function, you would have to use a new name. If you cannot work out how to replicate it exactly, you will have to use some variant like those given in other answers that allocates an appropriate amount of memory.

void log_out_wrapper(const char *fmt, ...)
{
    va_list args;
    size_t  len;
    char   *space;

    va_start(args, fmt);
    len = vsnprintf(0, 0, fmt, args);
    va_end(args);
    if ((space = malloc(len + 1)) != 0)
    {
         va_start(args, fmt);
         vsnprintf(space, len+1, fmt, args);
         va_end(args);
         log_out(space);
         free(space);
    }
    /* else - what to do if memory allocation fails? */
}

Obviously, you now call the log_out_wrapper() instead of log_out() - but the memory allocation and so on is done once. I reserve the right to be over-allocating space by one unnecessary byte - I've not double-checked whether the length returned by vsnprintf() includes the terminating null or not.

How to style the option of an html "select" element?

You can style the option elements to some extent.

Using the * CSS tag you can style the options inside the box that is drawn by the system.

Example:

#ddlProducts *
{
 border-radius:15px;
 background-color:red;
}

That will look like this:

enter image description here

python encoding utf-8

Unfortunately, the string.encode() method is not always reliable. Check out this thread for more information: What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python

How to generate XML from an Excel VBA macro?

Credit to: curiousmind.jlion.com/exceltotextfile (Link no longer exists)

Script:

Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFileName As String)
    Dim Q As String
    Q = Chr$(34)

    Dim sXML As String

    sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
    sXML = sXML & "<rows>"


    ''--determine count of columns
    Dim iColCount As Integer
    iColCount = 1
    While Trim$(Cells(iCaptionRow, iColCount)) > ""
        iColCount = iColCount + 1
    Wend

    Dim iRow As Integer
    iRow = iDataStartRow

    While Cells(iRow, 1) > ""
        sXML = sXML & "<row id=" & Q & iRow & Q & ">"

        For icol = 1 To iColCount - 1
           sXML = sXML & "<" & Trim$(Cells(iCaptionRow, icol)) & ">"
           sXML = sXML & Trim$(Cells(iRow, icol))
           sXML = sXML & "</" & Trim$(Cells(iCaptionRow, icol)) & ">"
        Next

        sXML = sXML & "</row>"
        iRow = iRow + 1
    Wend
    sXML = sXML & "</rows>"

    Dim nDestFile As Integer, sText As String

    ''Close any open text files
    Close

    ''Get the number of the next free text file
    nDestFile = FreeFile

    ''Write the entire file to sText
    Open sOutputFileName For Output As #nDestFile
    Print #nDestFile, sXML
    Close
End Sub

Sub test()
    MakeXML 1, 2, "C:\Users\jlynds\output2.xml"
End Sub

How to set adaptive learning rate for GradientDescentOptimizer?

If you want to set specific learning rates for intervals of epochs like 0 < a < b < c < .... Then you can define your learning rate as a conditional tensor, conditional on the global step, and feed this as normal to the optimiser.

You could achieve this with a bunch of nested tf.cond statements, but its easier to build the tensor recursively:

def make_learning_rate_tensor(reduction_steps, learning_rates, global_step):
    assert len(reduction_steps) + 1 == len(learning_rates)
    if len(reduction_steps) == 1:
        return tf.cond(
            global_step < reduction_steps[0],
            lambda: learning_rates[0],
            lambda: learning_rates[1]
        )
    else:
        return tf.cond(
            global_step < reduction_steps[0],
            lambda: learning_rates[0],
            lambda: make_learning_rate_tensor(
                reduction_steps[1:],
                learning_rates[1:],
                global_step,)
            )

Then to use it you need to know how many training steps there are in a single epoch, so that we can use the global step to switch at the right time, and finally define the epochs and learning rates you want. So if I want the learning rates [0.1, 0.01, 0.001, 0.0001] during the epoch intervals of [0, 19], [20, 59], [60, 99], [100, \infty] respectively, I would do:

global_step = tf.train.get_or_create_global_step()
learning_rates = [0.1, 0.01, 0.001, 0.0001]
steps_per_epoch = 225
epochs_to_switch_at = [20, 60, 100]
epochs_to_switch_at = [x*steps_per_epoch for x in epochs_to_switch_at ]
learning_rate = make_learning_rate_tensor(epochs_to_switch_at , learning_rates, global_step)

How to programmatically send a 404 response with Express/Node?

From the Express site, define a NotFound exception and throw it whenever you want to have a 404 page OR redirect to /404 in the below case:

function NotFound(msg){
  this.name = 'NotFound';
  Error.call(this, msg);
  Error.captureStackTrace(this, arguments.callee);
}

NotFound.prototype.__proto__ = Error.prototype;

app.get('/404', function(req, res){
  throw new NotFound;
});

app.get('/500', function(req, res){
  throw new Error('keyboard cat!');
});

Tkinter module not found on Ubuntu

requirement for tkinter:

python 3.6+

and go to shell write the test code like :

from tkinter import *

root = Tk()

root.mainloop()

enter image description here

Is it possible to set UIView border properties from interface builder?

You can make a category of UIView and add this in .h file of category

@property (nonatomic) IBInspectable UIColor *borderColor;
@property (nonatomic) IBInspectable CGFloat borderWidth;
@property (nonatomic) IBInspectable CGFloat cornerRadius;

Now add this in .m file

@dynamic borderColor,borderWidth,cornerRadius;

and this as well in . m file

-(void)setBorderColor:(UIColor *)borderColor{
    [self.layer setBorderColor:borderColor.CGColor];
}

-(void)setBorderWidth:(CGFloat)borderWidth{
    [self.layer setBorderWidth:borderWidth];
}

-(void)setCornerRadius:(CGFloat)cornerRadius{
    [self.layer setCornerRadius:cornerRadius];
}

now you will see this in your storyboard for all UIView subclasses (UILabel, UITextField, UIImageView etc)

enter image description here

Thats it.. No Need to import category anywhere, just add the category's files in the project and see these properties in the storyboard.

Find the item with maximum occurrences in a list

may something like this:

testList = [1, 2, 3, 4, 2, 2, 1, 4, 4] print(max(set(testList), key = testList.count))

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

Cause you need to add jQuery library to your file:

jQuery UI is just an addon to jQuery which means that
first you need to include the jQuery library → and then the UI.

<script src="path/to/your/jquery.min.js"></script>
<script src="path/to/your/jquery.ui.min.js"></script>

setTimeout or setInterval?

When you run some function inside setInterval, which works more time than timeout-> the browser will be stuck.

- E.g., doStuff() takes 1500 sec. to be execute and you do: setInterval(doStuff, 1000);
1) Browser run doStuff() which takes 1.5 sec. to be executed;
2) After ~1 second it tries to run doStuff() again. But previous doStuff() is still executed-> so browser adds this run to the queue (to run after first is done).
3,4,..) The same adding to the queue of execution for next iterations, but doStuff() from previous are still in progress...
As the result- the browser is stuck.

To prevent this behavior, the best way is to run setTimeout inside setTimeout to emulate setInterval.
To correct timeouts between setTimeout calls, you can use self-correcting alternative to JavaScript's setInterval technique.

Fixing slow initial load for IIS

Writing a ping service/script to hit your idle website is rather a best way to go because you will have a complete control. Other options that you have mentioned would be available if you have leased a dedicated hosting box.

In a shared hosting space, warmup scripts are the best first level defense (self help is the best help). Here is an article which shares an idea on how to do it from your own web application.

getSupportActionBar() The method getSupportActionBar() is undefined for the type TaskActivity. Why?

Here is another solution you could have used. It is working in my app.

      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        android.support.v7.app.ActionBar actionBar =getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);            
        setContentView(R.layout.activity_main)

Then you can get rid of that import for the one line ActionBar use.

Overcoming "Display forbidden by X-Frame-Options"

<form target="_parent" ... />

Using Kevin Vella's idea, I tried using the above on the form element made by PayPal's button generator. Worked for me so that Paypal does not open in a new browser window/tab.

Update

Here's an example:

Generating a button as of today (01-19-2021), PayPal automatically includes target="_top" on the form element, but if that doesn't work for your context, try a different target value. I suggest _parent -- at least that worked when I was using this PayPal button.

See Form Target Values for more info.

<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_parent">
  <input type="hidden" name="cmd" value="_xclick">
  <input type="hidden" name="business" value="[email protected]">
  <input type="hidden" name="lc" value="US">
  <input type="hidden" name="button_subtype" value="services">
  <input type="hidden" name="no_note" value="0">
  <input type="hidden" name="currency_code" value="USD">
  <input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynowCC_LG.gif:NonHostedGuest">
  <input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
  <img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>

How should I read a file line-by-line in Python?

Yes,

with open('filename.txt') as fp:
    for line in fp:
        print line

is the way to go.

It is not more verbose. It is more safe.

How can I stop python.exe from closing immediately after I get an output?

You can't - globally, i.e. for every python program. And this is a good thing - Python is great for scripting (automating stuff), and scripts should be able to run without any user interaction at all.

However, you can always ask for input at the end of your program, effectively keeping the program alive until you press return. Use input("prompt: ") in Python 3 (or raw_input("promt: ") in Python 2). Or get used to running your programs from the command line (i.e. python mine.py), the program will exit but its output remains visible.

Should I size a textarea with CSS width / height or HTML cols / rows attributes?

I recommend to use both. Rows and cols are required and useful if the client does not support CSS. But as a designer I overwrite them to get exactly the size I wish.

The recommended way to do it is via an external stylesheet e.g.

_x000D_
_x000D_
textarea {_x000D_
  width: 300px;_x000D_
  height: 150px;_x000D_
}
_x000D_
<textarea> </textarea>
_x000D_
_x000D_
_x000D_

SelectedValue vs SelectedItem.Value of DropDownList

Be careful using SelectedItem.Text... If there is no item selected, then SelectedItem will be null and SelectedItem.Text will generate a null-value exception.

.NET should have provided a SelectedText property like the SelectedValue property that returns String.Empty when there is no selected item.

Decimal precision and scale in EF Code First

Using

System.ComponentModel.DataAnnotations;

You can simply put that attribute in your model :

[DataType("decimal(18,5)")]

Delete element in a slice

There are two options:

A: You care about retaining array order:

a = append(a[:i], a[i+1:]...)
// or
a = a[:i+copy(a[i:], a[i+1:])]

B: You don't care about retaining order (this is probably faster):

a[i] = a[len(a)-1] // Replace it with the last one. CAREFUL only works if you have enough elements.
a = a[:len(a)-1]   // Chop off the last one.

See the link to see implications re memory leaks if your array is of pointers.

https://github.com/golang/go/wiki/SliceTricks

jQuery Set Selected Option Using Next

$('option:selected', 'select').removeAttr('selected').next('option').attr('selected', 'selected');

Check out working code here http://jsbin.com/ipewe/edit

XML Parsing - Read a Simple XML File and Retrieve Values

class Program
{

    static void Main(string[] args)
    {

        //Load XML from local
        string sourceFileName="";
        string element=string.Empty;
        var FolderPath=@"D:\Test\RenameFileWithXmlAttribute";

            string[] files = Directory.GetFiles(FolderPath, "*.xml");
            foreach (string xmlfile in files)
            {
                try
                {
                    sourceFileName = xmlfile;
                    XElement xele = XElement.Load(sourceFileName);
                    string convertToString = xele.ToString();
                    XElement parseXML = XElement.Parse(convertToString);
                    element = parseXML.Descendants("Meta").Where(x => (string)x.Attribute("name") == "XMLTAG").Last().Value;
                    DirectoryInfo CurrentDate = Directory.CreateDirectory(DateTime.Now.ToString("yyyy-MM-dd"));
                    string saveWithThisName= Path.Combine(CurrentDate.FullName, element);
                    File.Copy(sourceFileName, saveWithThisName,true);                      
                }
                catch(Exception ex)
                {

                }      
            }       
    }
}

How do I get the current date and time in PHP?

The time would go by your server time. An easy workaround for this is to manually set the timezone by using date_default_timezone_set before the date() or time() functions are called to.

I'm in Melbourne, Australia so I have something like this:

date_default_timezone_set('Australia/Melbourne');

Or another example is LA - US:

date_default_timezone_set('America/Los_Angeles');

You can also see what timezone the server is currently in via:

date_default_timezone_get();

So something like:

$timezone = date_default_timezone_get();
echo "The current server timezone is: " . $timezone;

So the short answer for your question would be:

// Change the line below to your timezone!
date_default_timezone_set('Australia/Melbourne');
$date = date('m/d/Y h:i:s a', time());

Then all the times would be to the timezone you just set :)

How to add local jar files to a Maven project?

The really quick and dirty way is to point to a local file:

<dependency>
      <groupId>sample</groupId>  
       <artifactId>com.sample</artifactId>  
       <version>1.0</version> 
      <scope>system</scope>
      <systemPath>C:\DEV\myfunnylib\yourJar.jar</systemPath>
</dependency>

However this will only live on your machine (obviously), for sharing it usually makes sense to use a proper m2 archive (nexus/artifactory) or if you do not have any of these or don't want to set one up a local maven structured archive and configure a "repository" in your pom: local:

<repositories>
    <repository>
        <id>my-local-repo</id>
        <url>file://C:/DEV//mymvnrepo</url>
    </repository>
</repositories>

remote:

<repositories>
    <repository>
        <id>my-remote-repo</id>
        <url>http://192.168.0.1/whatever/mavenserver/youwant/repo</url>
    </repository>
</repositories>

for this a relative path is also possible using the basedir variable:

<url>file:${basedir}</url>

How to reset selected file with input tag file type in Angular 2?

In my case I did it as below:

 <input #fileInput hidden (change)="uploadFile($event.target.files)" type="file" />
 <button mat-button color="warn" (click)="fileInput.value=''; fileInput.click()"> Upload File</button>

I am resetting it using #fileInput in HTML rather than creating a ViewChild in component.ts . Whenever the "Upload File" button is being clicked, first it resets the #fileInput and then triggers #fileInput.click() function. If any separate button needed to reset then on click #fileInput.value='' can be executed.

How can I check if a value is of type Integer?

If input value can be in numeric form other than integer , check by

if (x == (int)x)
{
   // Number is integer
}

If string value is being passed , use Integer.parseInt(string_var). Please ensure error handling using try catch in case conversion fails.

GridView Hide Column by code

This was the code that worked for me when the column Id is unknown and the AutoGenerateColumns == true;

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Drawing" %>
<html>
<head runat="server">
    <script runat="server">
        protected void Page_Load(object sender, EventArgs eventArgs)
        {
            DataTable data = new DataTable();
            data.Columns.Add("Id", typeof(int));
            data.Columns.Add("Notes", typeof(string));
            data.Columns.Add("RequestedDate", typeof(DateTime));
            for (int idx = 0; idx < 5; idx++)
            {
                DataRow row = data.NewRow();
                row["Id"] = idx;
                row["Notes"] = string.Format("Note {0}", idx);
                row["RequestedDate"] = DateTime.Now.Subtract(new TimeSpan(idx, 0, 0, 0, 0));
                data.Rows.Add(row);
            }
            listData.DataSource = data;
            listData.DataBind();
        }

        private void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            foreach (TableCell tableCell in e.Row.Cells)
            {
                DataControlFieldCell cell = (DataControlFieldCell)tableCell;
                if (cell.ContainingField.HeaderText == "Id")
                {
                    cell.Visible = false;
                    continue;
                }
                if (cell.ContainingField.HeaderText == "Notes")
                {
                    cell.Width = 400;
                    cell.BackColor = Color.Blue;
                    continue;
                }
                if (cell.ContainingField.HeaderText == "RequestedDate")
                {
                    cell.Width = 130;
                    continue;
                }
            }
        }

    </script>
</head>
<body>
    <form runat="server">
        <asp:GridView runat="server" ID="listData" AutoGenerateColumns="True" HorizontalAlign="Left"
            PageSize="20" OnRowDataBound="GridView_RowDataBound" EmptyDataText="No Data Available."
            Width="95%">
        </asp:GridView>
    </form>
</body>
</html>

Excel: replace part of cell's string value

What you need to do is as follows:

  1. List item
  2. Select the entire column by clicking once on the corresponding letter or by simply selecting the cells with your mouse.
  3. Press Ctrl+H.
  4. You are now in the "Find and Replace" dialog. Write "Author" in the "Find what" text box.
  5. Write "Authoring" in the "Replace with" text box.
  6. Click the "Replace All" button.

That's it!

java.lang.OutOfMemoryError: Java heap space in Maven

Not only heap memory. also increase perm size to resolve that exception in maven use these variables in environment variable.

variable name: MAVEN_OPTS
variable value: -Xmx512m -XX:MaxPermSize=256m

Example :

export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=500m"

jQuery $(this) keyword

I'm going to show you an example that will help you to understand why it's important.

Such as you have some Box Widgets and you want to show some hidden content inside every single widget. You can do this easily when you have a different CSS class for the single widget but when it has the same class how can you do that?
Actually, that's why we use $(this)

**Please check the code and run it :) ** enter image description here

_x000D_
_x000D_
  (function(){ _x000D_
_x000D_
            jQuery(".single-content-area").hover(function(){_x000D_
                jQuery(this).find(".hidden-content").slideDown();_x000D_
            })_x000D_
_x000D_
            jQuery(".single-content-area").mouseleave(function(){_x000D_
                jQuery(this).find(".hidden-content").slideUp();_x000D_
            })_x000D_
             _x000D_
        })();
_x000D_
  .mycontent-wrapper {_x000D_
      display: flex;_x000D_
      width: 800px;_x000D_
      margin: auto;_x000D_
    }     _x000D_
    .single-content-area  {_x000D_
        background-color: #34495e;_x000D_
        color: white;  _x000D_
        text-align: center;_x000D_
        padding: 20px;_x000D_
        margin: 15px;_x000D_
        display: block;_x000D_
        width: 33%;_x000D_
    }_x000D_
    .hidden-content {_x000D_
        display: none;_x000D_
    }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="mycontent-wrapper">_x000D_
    <div class="single-content-area">_x000D_
        <div class="content">_x000D_
            Name: John Doe <br/>_x000D_
            Age: 33  <br/>_x000D_
            Addres: Bangladesh_x000D_
        </div> <!--/.normal-content-->_x000D_
        <div class="hidden-content">_x000D_
            This is hidden content_x000D_
        </div> <!--/.hidden-content-->_x000D_
    </div><!--/.single-content-area-->_x000D_
_x000D_
    <div class="single-content-area">_x000D_
        <div class="content">_x000D_
            Name: John Doe <br/>_x000D_
            Age: 33  <br/>_x000D_
            Addres: Bangladesh_x000D_
        </div> <!--/.normal-content-->_x000D_
        <div class="hidden-content">_x000D_
            This is hidden content_x000D_
        </div> <!--/.hidden-content-->_x000D_
    </div><!--/.single-content-area-->_x000D_
_x000D_
_x000D_
    <div class="single-content-area">_x000D_
        <div class="content">_x000D_
            Name: John Doe <br/>_x000D_
            Age: 33  <br/>_x000D_
            Addres: Bangladesh_x000D_
        </div> <!--/.normal-content-->_x000D_
        <div class="hidden-content">_x000D_
            This is hidden content_x000D_
        </div> <!--/.hidden-content-->_x000D_
    </div><!--/.single-content-area-->_x000D_
_x000D_
</div><!--/.mycontent-wrapper-->
_x000D_
_x000D_
_x000D_

Uncaught Typeerror: cannot read property 'innerHTML' of null

If the script is in the head of your HTML document, the body of your HTML document has not yet been created by the browser, regardless of what will eventually be there (the same result occurs if your script is in the HTML file but above the element). When your variable tries to find document.getElementById("status") it does not yet exist, and so it returns a value of null. When you then use the variable later in your code, the initial value (null) is used and not the current one, because nothing has updated the variable.

I didn't want to move my script link out of the HTML head, so instead I did this in my JS file:

var idPost //define a global variable
function updateVariables(){
    idPost = document.getElementById("status").innerHTML; //update the global variable
}

And this in the HTML file:

<body onload="updateVariables()">

If you already have an onload function in place, you can just add the additional line to it or call the function.

If you don't want the variable to be global, define it locally in the function that you are trying to run and make sure the function is not called before the page has fully loaded.

Django Cookies, how can I set them?

UPDATE : check Peter's answer below for a builtin solution :

This is a helper to set a persistent cookie:

import datetime

def set_cookie(response, key, value, days_expire=7):
    if days_expire is None:
        max_age = 365 * 24 * 60 * 60  # one year
    else:
        max_age = days_expire * 24 * 60 * 60
    expires = datetime.datetime.strftime(
        datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age),
        "%a, %d-%b-%Y %H:%M:%S GMT",
    )
    response.set_cookie(
        key,
        value,
        max_age=max_age,
        expires=expires,
        domain=settings.SESSION_COOKIE_DOMAIN,
        secure=settings.SESSION_COOKIE_SECURE or None,
    )

Use the following code before sending a response.

def view(request):
    response = HttpResponse("hello")
    set_cookie(response, 'name', 'jujule')
    return response

UPDATE : check Peter's answer below for a builtin solution :

CSS background-size: cover replacement for Mobile Safari

I've had this issue on a lot of mobile views I've recently built.

My solution is still a pure CSS Fallback

http://css-tricks.com/perfect-full-page-background-image/ as three great methods, the latter two are fall backs for when CSS3's cover doesn't work.

HTML

<img src="images/bg.jpg" id="bg" alt="">

CSS

#bg {
  position: fixed; 
  top: 0; 
  left: 0; 

  /* Preserve aspect ratio */
  min-width: 100%;
  min-height: 100%;
}

VBA using ubound on a multidimensional array

ubound(arr, 1) 

and

ubound(arr, 2) 

Is there a cross-domain iframe height auto-resizer that works?

I have a script that drops in the iframe with it's content. It also makes sure that iFrameResizer exists (it injects it as a script) and then does the resizing.

I'll drop in a simplified example below.

// /js/embed-iframe-content.js

(function(){
    // Note the id, we need to set this correctly on the script tag responsible for
    // requesting this file.
    var me = document.getElementById('my-iframe-content-loader-script-tag');

    function loadIFrame() {
        var ifrm = document.createElement('iframe');
        ifrm.id = 'my-iframe-identifier';
        ifrm.setAttribute('src', 'http://www.google.com');
        ifrm.style.width = '100%';
        ifrm.style.border = 0;
        // we initially hide the iframe to avoid seeing the iframe resizing
        ifrm.style.opacity = 0;
        ifrm.onload = function () {
            // this will resize our iframe
            iFrameResize({ log: true }, '#my-iframe-identifier');
            // make our iframe visible
            ifrm.style.opacity = 1;
        };

        me.insertAdjacentElement('afterend', ifrm);
    }

    if (!window.iFrameResize) {
        // We first need to ensure we inject the js required to resize our iframe.

        var resizerScriptTag = document.createElement('script');
        resizerScriptTag.type = 'text/javascript';

        // IMPORTANT: insert the script tag before attaching the onload and setting the src.
        me.insertAdjacentElement('afterend', ifrm);

        // IMPORTANT: attach the onload before setting the src.
        resizerScriptTag.onload = loadIFrame;

        // This a CDN resource to get the iFrameResizer code.
        // NOTE: You must have the below "coupled" script hosted by the content that
        // is loaded within the iframe:
        // https://unpkg.com/[email protected]/js/iframeResizer.contentWindow.min.js
        resizerScriptTag.src = 'https://unpkg.com/[email protected]/js/iframeResizer.min.js';
    } else {
        // Cool, the iFrameResizer exists so we can just load our iframe.
        loadIFrame();
    }    
}())

Then the iframe content can be injected anywhere within another page/site by using the script like so:

<script
  id="my-iframe-content-loader-script-tag"
  type="text/javascript"
  src="/js/embed-iframe-content.js"
></script>

The iframe content will be injected below wherever you place the script tag.

Hope this is helpful to someone.

What is the default stack size, can it grow, how does it work with garbage collection?

As you say, local variables and references are stored on the stack. When a method returns, the stack pointer is simply moved back to where it was before the method started, that is, all local data is "removed from the stack". Therefore, there is no garbage collection needed on the stack, that only happens in the heap.

To answer your specific questions:

  • See this question on how to increase the stack size.
  • You can limit the stack growth by:
    • grouping many local variables in an object: that object will be stored in the heap and only the reference is stored on the stack
    • limit the number of nested function calls (typically by not using recursion)
  • For windows, the default stack size is 320k for 32bit and 1024k for 64bit, see this link.

How to add browse file button to Windows Form using C#

var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
    string fileToOpen = FD.FileName;

    System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);

    //OR

    System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
    //etc
}

How to use ScrollView in Android?

As said above you can put it inside a ScrollView... and if you want the Scroll View to be horizontal put it inside HorizontalScrollView... and if you want your component (or layout) to support both put inside both of them like this:

  <HorizontalScrollView>
        <ScrollView>
            <!-- SOME THING -->
        </ScrollView>
    </HorizontalScrollView>

and with setting the layout_width and layout_height ofcourse.

Flask SQLAlchemy query, specify column names

An example here:

movies = Movie.query.filter(Movie.rating != 0).order_by(desc(Movie.rating)).all()

I query the db for movies with rating <> 0, and then I order them by rating with the higest rating first.

Take a look here: Select, Insert, Delete in Flask-SQLAlchemy

How to copy selected files from Android with adb pull

Pull multiple files using regex:

Create pullFiles.sh:

#!/bin/bash
HOST_DIR=<pull-to>
DEVICE_DIR=/sdcard/<pull-from>
EXTENSION=".jpg"

for file in $(adb shell ls $DEVICE_DIR | grep $EXTENSION'$')
do
    file=$(echo -e $file | tr -d "\r\n"); # EOL fix
    adb pull $DEVICE_DIR/$file $HOST_DIR/$file;
done

Run it:

Make it executable: chmod +x pullFiles.sh

Run it: ./pullFiles.sh

Notes:

  • as is, won't work when filenames have spaces
  • includes a fix for end-of-line (EOL) on Android, which is a "\r\n"

Return Max Value of range that is determined by an Index & Match lookup

You don't need an index match formula. You can use this array formula. You have to press CTL + SHIFT + ENTER after you enter the formula.

=MAX(IF((A1:A6=A10)*(B1:B6=B10),C1:F6))

SNAPSHOT

enter image description here

How to send a pdf file directly to the printer using JavaScript?

a function to house the print trigger...

function printTrigger(elementId) {
    var getMyFrame = document.getElementById(elementId);
    getMyFrame.focus();
    getMyFrame.contentWindow.print();
}

an button to give the user access...

(an onClick on an a or button or input or whatever you wish)

<input type="button" value="Print" onclick="printTrigger('iFramePdf');" />
an iframe pointing to your PDF...

<iframe id="iFramePdf" src="myPdfUrl.pdf" style="dispaly:none;"></iframe>

More : http://www.fpdf.org/en/script/script36.php

Use SELECT inside an UPDATE query

I did want to add one more answer that utilizes a VBA function, but it does get the job done in one SQL statement. Though, it can be slow.

UPDATE FUNCTIONS
SET FUNCTIONS.Func_TaxRef = DLookUp("MinOfTax_Code", "SELECT
FUNCTIONS.Func_ID,Min(TAX.Tax_Code) AS MinOfTax_Code
FROM TAX, FUNCTIONS
WHERE (((FUNCTIONS.Func_Pure)<=[Tax_ToPrice]) AND ((FUNCTIONS.Func_Year)=[Tax_Year]))
GROUP BY FUNCTIONS.Func_ID;", "FUNCTIONS.Func_ID=" & Func_ID)

Modifying a subset of rows in a pandas dataframe

Here is from pandas docs on advanced indexing:

The section will explain exactly what you need! Turns out df.loc (as .ix has been deprecated -- as many have pointed out below) can be used for cool slicing/dicing of a dataframe. And. It can also be used to set things.

df.loc[selection criteria, columns I want] = value

So Bren's answer is saying 'find me all the places where df.A == 0, select column B and set it to np.nan'

Rails 4: List of available datatypes

It is important to know not only the types but the mapping of these types to the database types, too:

enter image description here

enter image description here


Source added - Agile Web Development with Rails 4

How to change ViewPager's page?

Supplemental answer

I was originally having trouble getting a reference to the ViewPager from other class methods because the addOnTabSelectedListener made an anonymous inner class, which in turn required the ViewPager variable to be declared final. The solution was to use a class member variable and not use the anonymous inner class.

public class MainActivity extends AppCompatActivity {

    TabLayout tabLayout;
    ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        viewPager = (ViewPager) findViewById(R.id.pager);
        final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        // don't use an anonymous inner class here
        tabLayout.addOnTabSelectedListener(tabListener);

    }

    TabLayout.OnTabSelectedListener tabListener = new TabLayout.OnTabSelectedListener() {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };

    // The view pager can now be accessed here, too.
    public void someMethod() {
        viewPager.setCurrentItem(0);
    }

}

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

This has happened to me. My issue was caused when I didn't mount Docker file system correctly, so I configured the Disk Image Location and re-bind File sharing mount, and this now worked correctly. For reference, I use Docker Desktop in Windows.

VBA Check if variable is empty

How you test depends on the Property's DataType:

| Type                                 | Test                            | Test2
| Numeric (Long, Integer, Double etc.) | If obj.Property = 0 Then        | 
| Boolen (True/False)                  | If Not obj.Property Then        | If obj.Property = False Then
| Object                               | If obj.Property Is Nothing Then |
| String                               | If obj.Property = "" Then       | If LenB(obj.Property) = 0 Then
| Variant                              | If obj.Property = Empty Then    |

You can tell the DataType by pressing F2 to launch the Object Browser and looking up the Object. Another way would be to just use the TypeName function:MsgBox TypeName(obj.Property)

jQuery - replace all instances of a character in a string

'some+multi+word+string'.replace(/\+/g, ' ');
                                   ^^^^^^

'g' = "global"

Cheers

VSCode: How to Split Editor Vertically

By default, editor groups are laid out in vertical columns (e.g. when you split an editor to open it to the side). You can easily arrange editor groups in any layout you like, both vertically and horizontally:

To support flexible layouts, you can create empty editor groups. By default, closing the last editor of an editor group will also close the group itself, but you can change this behavior with the new setting workbench.editor.closeEmptyGroups: false:

enter image description here

There are a predefined set of editor layouts in the new View > Editor Layout menu:

enter image description here

Editors that open to the side (for example by clicking the editor toolbar Split Editor action) will by default open to the right hand side of the active editor. If you prefer to open editors below the active one, configure the new setting workbench.editor.openSideBySideDirection: down.

There are many keyboard commands for adjusting the editor layout with the keyboard alone, but if you prefer to use the mouse, drag and drop is a fast way to split the editor into any direction:

enter image description here

Keyboard shortcuts# Here are some handy keyboard shortcuts to quickly navigate between editors and editor groups.

If you'd like to modify the default keyboard shortcuts, see Key Bindings for details.

??? go to the right editor.
??? go to the left editor.
^Tab open the next editor in the editor group MRU list.
^?Tab open the previous editor in the editor group MRU list.
?1 go to the leftmost editor group.
?2 go to the center editor group.
?3 go to the rightmost editor group.
unassigned go to the previous editor group.
unassigned go to the next editor group.
?W close the active editor.
?K W close all editors in the editor group.
?K ?W close all editors.

Bootstrap 4, How do I center-align a button?

Try this with bootstrap

CODE:

<div class="row justify-content-center">
  <button type="submit" class="btn btn-primary">btnText</button>
</div>

LINK:

https://getbootstrap.com/docs/4.1/layout/grid/#variable-width-content

How to remove all null elements from a ArrayList or String Array?

 for (Iterator<Tourist> itr = tourists.iterator(); itr.hasNext();) {
      if (itr.next() == null) { itr.remove(); }
 }

Reading Excel files from C#

If you have multiple tables in the same worksheet you can give each table an object name and read the table using the OleDb method as shown here: http://vbktech.wordpress.com/2011/05/10/c-net-reading-and-writing-to-multiple-tables-in-the-same-microsoft-excel-worksheet/

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

add this at the top of file,

header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");

How to get a list column names and datatypes of a table in PostgreSQL?

SELECT
        a.attname as "Column",
        pg_catalog.format_type(a.atttypid, a.atttypmod) as "Datatype"
    FROM
        pg_catalog.pg_attribute a
    WHERE
        a.attnum > 0
        AND NOT a.attisdropped
        AND a.attrelid = (
            SELECT c.oid
            FROM pg_catalog.pg_class c
                LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
            WHERE c.relname ~ '^(hello world)$'
                AND pg_catalog.pg_table_is_visible(c.oid)
        );

Change the hello world with your table name

More info on it : http://www.postgresql.org/docs/9.3/static/catalog-pg-attribute.html

How to list AD group membership for AD users using input list?

Get-ADPrincipalGroupMembership username | select name

Got it from another answer but the script works magic. :)

Visual Studio 2015 or 2017 does not discover unit tests

Disable Windows Defender Service. Turning this off immediately caused all of my unit tests to show up in Test Explorer.

How do you wait for input on the same Console.WriteLine() line?

As Matt has said, use Console.Write. I would also recommend explicitly flushing the output, however - I believe WriteLine does this automatically, but I'd seen oddities when just using Console.Write and then waiting. So Matt's code becomes:

Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();

Delete duplicate elements from an array

Try following from Removing duplicates from an Array(simple):

Array.prototype.removeDuplicates = function (){
  var temp=new Array();
  this.sort();
  for(i=0;i<this.length;i++){
    if(this[i]==this[i+1]) {continue}
    temp[temp.length]=this[i];
  }
  return temp;
} 

Edit:

This code doesn't need sort:

Array.prototype.removeDuplicates = function (){
  var temp=new Array();
  label:for(i=0;i<this.length;i++){
        for(var j=0; j<temp.length;j++ ){//check duplicates
            if(temp[j]==this[i])//skip if already present 
               continue label;      
        }
        temp[temp.length] = this[i];
  }
  return temp;
 } 

(But not a tested code!)

Write to custom log file from a Bash script

If you see the man page of logger:

$ man logger

LOGGER(1) BSD General Commands Manual LOGGER(1)

NAME logger — a shell command interface to the syslog(3) system log module

SYNOPSIS logger [-isd] [-f file] [-p pri] [-t tag] [-u socket] [message ...]

DESCRIPTION Logger makes entries in the system log. It provides a shell command interface to the syslog(3) system log module.

It Clearly says that it will log to system log. If you want to log to file, you can use ">>" to redirect to log file.

Django database query: How to get object by id?

I got here for the same problem, but for a different reason:

Class.objects.get(id=1)

This code was raising an ImportError exception. What was confusing me was that the code below executed fine and returned a result set as expected:

Class.objects.all()

Tail of the traceback for the get() method:

File "django/db/models/loading.py", line 197, in get_models
    self._populate()
File "django/db/models/loading.py", line 72, in _populate
    self.load_app(app_name, True)
File "django/db/models/loading.py", line 94, in load_app
    app_module = import_module(app_name)
File "django/utils/importlib.py", line 35, in import_module
    __import__(name)
ImportError: No module named myapp

Reading the code inside Django's loading.py, I came to the conclusion that my settings.py had a bad path to my app which contains my Class model definition. All I had to do was correct the path to the app and the get() method executed fine.

Here is my settings.py with the corrected path:

INSTALLED_APPS = (
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    # ...
    'mywebproject.myapp',

)

All the confusion was caused because I am using Django's ORM as a standalone, so the namespace had to reflect that.

Applying an ellipsis to multiline text

I have just been playing around a little bit with this concept. Basically, if you are ok with potentially having a pixel or so cut off from your last character, here is a pure css and html solution:

The way this works is by absolutely positioning a div below the viewable region of a viewport. We want the div to offset up into the visible region as our content grows. If the content grows too much, our div will offset too high, so upper bound the height our content can grow.

HTML:

<div class="text-container">
  <span class="text-content">
    PUT YOUR TEXT HERE
    <div class="ellipsis">...</div> // You could even make this a pseudo-element
  </span>
</div>

CSS:

.text-container {
    position: relative;
    display: block;
    color: #838485;
    width: 24em;
    height: calc(2em + 5px); // This is the max height you want to show of the text. A little extra space is for characters that extend below the line like 'j'
    overflow: hidden;
    white-space: normal;
}

.text-content {
  word-break: break-all;
  position: relative;
  display: block;
  max-height: 3em;       // This prevents the ellipsis element from being offset too much. It should be 1 line height greater than the viewport 
}

.ellipsis {
  position: absolute;
  right: 0;
  top: calc(4em + 2px - 100%); // Offset grows inversely with content height. Initially extends below the viewport, as content grows it offsets up, and reaches a maximum due to max-height of the content
  text-align: left;
  background: white;
}

I have tested this in Chrome, FF, Safari, and IE 11.

You can check it out here: http://codepen.io/puopg/pen/vKWJwK

You might even be able to alleviate the abrupt cut off of the character with some CSS magic.

EDIT: I guess one thing that this imposes is word-break: break-all since otherwise the content would not extend to the very end of the viewport. :(

How can I pass a parameter to a Java Thread?

One further option; this approach lets you use the Runnable item like an asynchronous function call. If your task does not need to return a result, e.g. it just performs some action you don't need to worry about how you pass back an "outcome".

This pattern lets you reuse an item, where you need some kind of internal state. When not passing parameter(s) in the constructor care is needed to mediate the programs access to parameters. You may need more checks if your use-case involves different callers, etc.

public class MyRunnable implements Runnable 
{
  private final Boolean PARAMETER_LOCK  = false;
  private X parameter;

  public MyRunnable(X parameter) {
     this.parameter = parameter;
  }

  public void setParameter( final X newParameter ){

      boolean done = false;
      synchronize( PARAMETER_LOCK )
      {
          if( null == parameter )
          {
              parameter = newParameter;
              done = true;
          }
      }
      if( ! done )
      {
          throw new RuntimeException("MyRunnable - Parameter not cleared." );
      }
  }


  public void clearParameter(){

      synchronize( PARAMETER_LOCK )
      {
          parameter = null;
      }
  }


  public void run() {

      X localParameter;

      synchronize( PARAMETER_LOCK )
      {
          localParameter = parameter;
      }

      if( null != localParameter )
      {
         clearParameter();   //-- could clear now, or later, or not at all ...
         doSomeStuff( localParameter );
      }

  }

}

Thread t = new Thread(new MyRunnable(parameter)); t.start();

If you need a result of processing, you will also need to coordinate completion of MyRunnable when the sub-task finishes. You could pass a call back or just wait on the Thread 't', etc.

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

In my case, the drive I was storing my workspace on had become full downloading SDK updates full and I just needed to clear some space on it.

Paging with LINQ for objects

I use this extension method:

public static IQueryable<T> Page<T, TResult>(this IQueryable<T> obj, int page, int pageSize, System.Linq.Expressions.Expression<Func<T, TResult>> keySelector, bool asc, out int rowsCount)
{
    rowsCount = obj.Count();
    int innerRows = rowsCount - (page * pageSize);
    if (innerRows < 0)
    {
        innerRows = 0;
    }
    if (asc)
        return obj.OrderByDescending(keySelector).Take(innerRows).OrderBy(keySelector).Take(pageSize).AsQueryable();
    else
        return obj.OrderBy(keySelector).Take(innerRows).OrderByDescending(keySelector).Take(pageSize).AsQueryable();
}

public IEnumerable<Data> GetAll(int RowIndex, int PageSize, string SortExpression)
{
    int totalRows;
    int pageIndex = RowIndex / PageSize;

    List<Data> data= new List<Data>();
    IEnumerable<Data> dataPage;

    bool asc = !SortExpression.Contains("DESC");
    switch (SortExpression.Split(' ')[0])
    {
        case "ColumnName":
            dataPage = DataContext.Data.Page(pageIndex, PageSize, p => p.ColumnName, asc, out totalRows);
            break;
        default:
            dataPage = DataContext.vwClientDetails1s.Page(pageIndex, PageSize, p => p.IdColumn, asc, out totalRows);
            break;
    }

    foreach (var d in dataPage)
    {
        clients.Add(d);
    }

    return data;
}
public int CountAll()
{
    return DataContext.Data.Count();
}

How to display the string html contents into webbrowser control?

For some reason the code supplied by m3z (with the DisplayHtml(string) method) is not working in my case (except first time). I'm always displaying html from string. Here is my version after the battle with the WebBrowser control:

webBrowser1.Navigate("about:blank");
while (webBrowser1.Document == null || webBrowser1.Document.Body == null)
    Application.DoEvents();
webBrowser1.Document.OpenNew(true).Write(html);

Working every time for me. I hope it helps someone.

Inserting HTML elements with JavaScript

Instead of directly messing with innerHTML it might be better to create a fragment and then insert that:

function create(htmlStr) {
    var frag = document.createDocumentFragment(),
        temp = document.createElement('div');
    temp.innerHTML = htmlStr;
    while (temp.firstChild) {
        frag.appendChild(temp.firstChild);
    }
    return frag;
}

var fragment = create('<div>Hello!</div><p>...</p>');
// You can use native DOM methods to insert the fragment:
document.body.insertBefore(fragment, document.body.childNodes[0]);

Benefits:

  1. You can use native DOM methods for insertion such as insertBefore, appendChild etc.
  2. You have access to the actual DOM nodes before they're inserted; you can access the fragment's childNodes object.
  3. Using document fragments is very quick; faster than creating elements outside of the DOM and in certain situations faster than innerHTML.

Even though innerHTML is used within the function, it's all happening outside of the DOM so it's much faster than you'd think...

How to ensure a <select> form field is submitted when it is disabled?

Disable the fields and then enable them before the form is submitted:

jQuery code:

jQuery(function ($) {        
  $('form').bind('submit', function () {
    $(this).find(':input').prop('disabled', false);
  });
});

Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

{"a":"\u00e1"} and {"a":"á"} are different ways to write the same JSON document; The JSON decoder will decode the unicode escape.

In php 5.4+, php's json_encode does have the JSON_UNESCAPED_UNICODE option for plain output. On older php versions, you can roll out your own JSON encoder that does not encode non-ASCII characters, or use Pear's JSON encoder and remove line 349 to 433.

Maven: mvn command not found

Maven setup:

a. install maven from https://maven.apache.org/download.cgi

b. unzip maven and keep in C drive.

c. Set MAVEN_HOME in system variable. enter image description here

d. Set path for maven enter image description here

Oracle Add 1 hour in SQL

Old way:

SELECT DATE_COLUMN + 1 is adding a day
SELECT DATE_COLUMN + N /24 to add hour(s) - N being number of hours
SELECT DATE_COLUMN + N /1440 to add minute(s) - N being number of minutes
SELECT DATE_COLUMN + N /86400 to add second(s) - N being number of seconds

Using INTERVAL:

SELECT DATE_COLUMN + INTERVAL 'N' HOUR or MINUTE or SECOND - N being a number of hours or minutes or seconds.

What is the difference between localStorage, sessionStorage, session and cookies?

  1. LocalStorage

    Pros:

    1. Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. If you look at the Mozilla source code we can see that 5120KB (5MB which equals 2.5 Million chars on Chrome) is the default storage size for an entire domain. This gives you considerably more space to work with than a typical 4KB cookie.
    2. The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.
    3. The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

    Cons:

    1. It works on same-origin policy. So, data stored will only be available on the same origin.
  2. Cookies

    Pros:

    1. Compared to others, there's nothing AFAIK.

    Cons:

    1. The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.
    2. The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.

      Typically, the following are allowed:

      • 300 cookies in total
      • 4096 bytes per cookie
      • 20 cookies per domain
      • 81920 bytes per domain(Given 20 cookies of max size 4096 = 81920 bytes.)
  3. sessionStorage

    Pros:

    1. It is similar to localStorage.
    2. The data is not persistent i.e. data is only available per window (or tab in browsers like Chrome and Firefox). Data is only available during the page session. Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted.

    Cons:

    1. The data is available only inside the window/tab in which it was set.
    2. Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.

Checkout across-tabs - how to facilitate easy communication between cross-origin browser tabs.

Powershell Log Off Remote Session

I've modified Casey's answer to only logoff disconnected sessions by doing the following:

   foreach($Server in $Servers) {
    try {
        query user /server:$Server 2>&1 | select -skip 1 | ? {($_ -split "\s+")[-5] -eq 'Disc'} | % {logoff ($_ -split "\s+")[-6] /server:$Server /V}
    }
    catch {}
    }

JavaScript: remove event listener

   canvas.addEventListener('click', function(event) {
      click++;
      if(click == 50) {
          this.removeEventListener('click',arguments.callee,false);
      }

Should do it.

Referenced Project gets "lost" at Compile Time

Make sure that both projects have same target framework version here: right click on project -> properties -> application (tab) -> target framework

Also, make sure that the project "logger" (which you want to include in the main project) has the output type "Class Library" in: right click on project -> properties -> application (tab) -> output type

Finally, Rebuild the solution.

How to configure Fiddler to listen to localhost?

Replace localhost by lvh.me in your URL

For example if you had http://localhost:24448/HomePage.aspx

Change it to http://lvh.me:24448/HomePage.aspx

how to get the 30 days before date from Todays Date

SELECT (column name) FROM (table name) WHERE (column name) < DATEADD(Day,-30,GETDATE());

Example.

SELECT `name`, `phone`, `product` FROM `tbmMember` WHERE `dateofServicw` < (Day,-30,GETDATE()); 

Build Eclipse Java Project from Command Line

To complete André's answer, an ant solution could be like the one described in Emacs, JDEE, Ant, and the Eclipse Java Compiler, as in:

      <javac
          srcdir="${src}"
          destdir="${build.dir}/classes"> 
        <compilerarg 
           compiler="org.eclipse.jdt.core.JDTCompilerAdapter" 
           line="-warn:+unused -Xemacs"/>
        <classpath refid="compile.classpath" />
      </javac>

The compilerarg element also allows you to pass in additional command line args to the eclipse compiler.

You can find a full ant script example here which would be invoked in a command line with:

java -cp C:/eclipse-SDK-3.4-win32/eclipse/plugins/org.eclipse.equinox.launcher_1.0.100.v20080509-1800.jar org.eclipse.core.launcher.Main -data "C:\Documents and Settings\Administrator\workspace" -application org.eclipse.ant.core.antRunner -buildfile build.xml -verbose

BUT all that involves ant, which is not what Keith is after.

For a batch compilation, please refer to Compiling Java code, especially the section "Using the batch compiler"

The batch compiler class is located in the JDT Core plug-in. The name of the class is org.eclipse.jdt.compiler.batch.BatchCompiler. It is packaged into plugins/org.eclipse.jdt.core_3.4.0..jar. Since 3.2, it is also available as a separate download. The name of the file is ecj.jar.
Since 3.3, this jar also contains the support for jsr199 (Compiler API) and the support for jsr269 (Annotation processing). In order to use the annotations processing support, a 1.6 VM is required.

Running the batch compiler From the command line would give

java -jar org.eclipse.jdt.core_3.4.0<qualifier>.jar -classpath rt.jar A.java

or:

java -jar ecj.jar -classpath rt.jar A.java

All java compilation options are detailed in that section as well.

The difference with the Visual Studio command line compilation feature is that Eclipse does not seem to directly read its .project and .classpath in a command-line argument. You have to report all information contained in the .project and .classpath in various command-line options in order to achieve the very same compilation result.

So, then short answer is: "yes, Eclipse kind of does." ;)

What is the purpose and uniqueness SHTML?

SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).

(HTML is...you know what it is, and DHTML is Microsoft's name for Javascript+HTML+CSS or something).

You can use SSI to include a common header and footer in your pages, so you don't have to repeat code as much. Changing one included file updates all of your pages at once. You just put it in your HTML page as per normal.

It's embedded in a standard XML comment, and looks like this:

<!--#include virtual="top.shtml" -->

It's been largely superseded by other mechanisms, such as PHP includes, but some hosting packages still support it and nothing else.

You can read more in this Wikipedia article.

position: fixed doesn't work on iPad and iPhone

The simple way to fix this problem just types transform property for your element. and it will be fixed. Happy Coding :-)

.classname{
  position: fixed;
  transform: translate3d(0,0,0);
}

Also you can try his way as well this is also work fine.

.classname{
      position: -webkit-sticky;
    }

View JSON file in Browser

If you don't want to install extensions, you can simply prepend the URL with view-source:, e.g. view-source:http://content.dimestore.com/prod/survey_data/4535/4535.json. This usually works in Firefox and Chrome (will still offer to download the file however if Content-Disposition: attachment header is present).