So, how do i...
- Web development
- Javascript
- PHP
- Git
- Python
- Command-line generic
- Command-line Linux
- Command-line Mac OS X
- Chrome
- Spreadsheets (Google Sheets, Excel, etc)
if ('ActiveXObject' in window) {
document.documentElement.className = 'is-ie';
}
Just add width: 100%
to the elements, or if you're really lazy:
.container > * {
width: 100%;
}
// Transforming jQuery's $.get to a Promise
function get(url) {
return new Promise(function(resolve, reject) {
$.ajax({
method : "GET",
url : url,
success : function(data) {
resolve(data);
},
error : function() {
reject('Something went wrong');
}
}
});
}
get('http://example.com').then(function(data) {
console.log(data);
});
_.mapValues(_.keyBy(data, 'key'), 'value');
Transform this:
[
{ key : 'foo', value : 'bar'},
{ key : 'baz', value : 'qux'}
]
Into this:
{
'foo' : 'bar',
'baz' : 'qux'
}
echo __FILE__;
echo realpath(dirname(__FILE__));
- Try using
127.0.0.1
instead oflocalhost
for DB host - Add a utf-8 charset
Create a .gitignore
with this content:
# Ignore everything in this directory
*
# Except this file
!.gitignore
Use git add
just as you would for a normal commit. Then:
git commit --ammend
git commit --amend -m "New commit message"
Resolve all merge conflicts by overwriting with all local or remote files (source)
To use local files
grep -lr '<<<<<<<' . | xargs git checkout --ours
To use remote files
grep -lr '<<<<<<<' . | xargs git checkout --theirs
git clean -f
Directories as well
git clean -fd
git tag -d yourtag
git push origin :refs/tags/yourtag
git reset --hard HEAD^
If you don't care about the changes, or
git reset --soft HEAD^
If you do.
If you've already pushed, try this:
git revert HEAD
obj = { "key" : val }
# Python 2
for key, val in obj.iteritems():
print key, val
# Python 3
for key, val in obj.items():
print(key, val)
a = { "foo" : 1 }
a.update({ "bar" : 2 })
print(a) # { "foo" : 1, "bar" : 2 }
a = { "a" : {}, "b" : {} }
a.itervalues().next()
my_dict.pop("key", None)
a = { "foo" : "foo" }
a["foo"] // "foo"
a.get("bar", "bar") // "bar"
a["bar"] // KeyError: "bar"
l = [1,2,3]
for index, val in enumerate(l):
print index, val # "0, 1", "1, 2", "2, 3"
a = [ { "foo" : "bar" }, {"foo" : "baz"} ]
a.sort(key = lambda i:i["foo"])
Or
a = sorted(a, key = lambda i:i["foo"])
a = [ { "name" : "Bert" }, { "name" : "Ernie" }
from operator import itemgetter
b = sorted(a, key = itemgetter("name") )
a = [ ["foo", 3], ["foo", 1], ["foo", 2] ]
a.sort(key = lambda i:i[1]) // [ ["foo", 1], ["foo", 2], ["foo", 3] ]
a = { "foo" : 10, "bar" : 20, "baz" : 5 }
max(a, key = (lambda k:a[k])) # 'bar'
from collections import Counter
l = ["foo", "bar", "foo", "baz"]
print Counter(l)
# Prints:
# {'foo': 2, 'baz': 1, 'bar': 1}
The ugly way
sum(l, [])
The slighty more Pythonic (and faster) way
[item for sublist in l for item in sublist]
Convert to a set, then to a list again
list(set(l))
l = [5, 3, 7, 24, 2, 22]
l = [ x for x in l if x > 10 ] # l == [24, 22]
d = {k:v for k,v in dct.iteritems() } # Python 2
d = {k:v for k,v in dct.items() } # Python 3
Either
"Ham, %s and %s" % ("eggs", "spam")
Or
"Ham, {food1} and {food2}".format(food1 = "eggs", food2 = "spam")
If the number is already a string
number.zfill(3)
urllib.quote_plus("Lots of weird charachters:ª•¶•ª¶™•ª¢∆")
target = "a lovely string"
strings = ("nice", "kind", "lovely")
if any(s in target for s in strings):
print(s) # 'lovely'
import re
REGEX = re.compile("…[^…]*…")
# Replace all occurences
text = REGEX.sub(" ", text)
import datetime
datetime.datetime.now().isoformat("T")
import os
PATH = os.path.dirname(os.path.realpath(__file__))
In reverse
a.sort(key = lambda i:i[1], reverse = True) // [ ["foo", 3], ["foo", 2], ["foo", 1] ]
import os.path
os.path.isfile( filename )
import os
os.path.basename(filename)[0]
To also remove the path to the filename
os.path.splitext(os.path.basename(filename))[0]
import logging
logger = logging.getLogger(__name__)
logger.critical("Log with critical level")
logger.error("Log with error level")
logger.warning("Log with warning level")
logger.info("Log with info level")
logger.debug("Log with debug level")
logging.basicConfig(level=logging.DEBUG) # Set default level to DEBUG
class ClassName:
foo = "Unknown"
def __init__(self, foo):
self.foo = foo
def bar(self):
print self.foo
def test():
raise Exception("Something happened")
try:
test()
except Exception, e:
print e.message
else:
# Do something else
Note that you can re-raise an exception
try:
test()
except Exception, e:
raise e
To parse XML use xmltodict, to make it behave like a dict.
import xmltodict
doc = xmltodict.parse("""
<record id="123">
<key>foo</key>
</record>
""")
print doc["record"]["@id"] # '123'
print doc["record"]["key"] # foo
To write back XML you can use xmltodict's unparse
print xmltodict.unparse(doc, pretty = True) # <record id="123">....
Or use lxml.etree.tostring()
from lxml import etree
print etree.tostring(doc)
Use a generator. Instead of
for point in points:
for x in point:
if x > 5:
plot(x)
Do
def iterpoints():
for point in points:
for x in points:
if x > 5:
yield x
for x in iterpoints():
plot(x)
Increment an integer? foo++ doesn't work. (source)
foo += 1
Or
foo = foo + 1
import pdb;pdb.set_trace()
from urllib import quote_plus as encode
encode('Something with spaces and ••ª¶ª•¶∆˙˚∆ charachters')
import csv
# Get the fieldnames first
infile = open("in.csv", "r")
reader = csv.DictReader(infile)
fieldnames = reader.next().keys()
infile.close()
# Now open the in and outfile
infile = open("in.csv", "r")
outfile = open("out.csv", "w")
reader = csv.DictReader(infile)
writer = csv.DictWriter(outfile, fieldnames = fieldnames)
# Print the field names in the first row
writer.writerow(
dict(
(fn, fn) for fn in fieldnames
)
)
for row in reader:
# Do something with the values
# And then write it
writer.writerow(row)
infile.close()
outfile.close()
Check if there's no print
statements in your code.
- See this excellent resource.
Host internal.hostname.tld
User user
HostName internal.hostname.tld
ProxyCommand ssh [email protected] nc %h %p 2> /dev/null
Errors like this could be anything:
rsync error: error in rsync protocol data stream
But make sure your SSH keys have proper permissions
chmod -R 700 ~/.ssh
Use mogrify
to convert a bunch of JPG
files to fit within a 1500x1500 frame (take longest side), and set quality to 60%
mogrify -resize 1500x1500 -quality 60 *.jpg
Same thing, but crop the images as well so they fit in the 1500x1500 frame, cropped from the center of the image.
mogrify -resize 1500x1500^ -crop 1500x1500+0+0 -gravity center *.jpg
Use the rename
command to sequentially number a bunch of JPG
files to 01.jpg, 02.jpg, etc.
rename -N 01 's/.*/$N.jpg/' *
Basic use of ffmpeg
ffmpeg -i source.extension dest.extension
Resize to 600px wide
ffmpeg -i in.mov -vf scale=600:-1 out.mp4
Crop a video with landscape aspect-ratio to a square from the center
ffmpeg -i in.mov -filter:v "crop=in_h:in_h:((in_w/2)-(in_h/2)):0" out.mp4
Framerate to 24fps
ffmpeg -i in.mov -r 24 out.mp4
Bitrate to 2mb/s
ffmpeg -i in.mov -b:v 2000k out.mp4
Grab a frame from 1 second into the video and convert to jpg (note that .png also works)
ffmpeg -i in.mov -ss 00:00:01 -vframes 1 out.jpg
Use the brilliant youtube-dl
.
youtube-dl -f mp4 https://www.youtube.com/watch?v=bMj3Pc5I078
Directly convert a movie at an URL to mp3
youtube-dl -x --audio-format mp3 https://www.youtube.com/watch?v=bMj3Pc5I078
for f in *.ext; do command $f; done
$ vim /etc/locale.gen
Uncomment the en_US.UTF-8 line
$ locale-gen
If you're still getting errors, add these two lines to your bashrc
or bash_profile
on the machine you're connecting from:
# Setting for the new UTF-8 terminal support in Lion
export LC_CTYPE=en_US.UTF-8
export LC_ALL=en_US.UTF-8
ls | pbcopy
mdfind
Highlight the item using keyboard arrows and press Shift and Delete keys.
=AVERAGE(FILTER(A2:A25, A2:A25>0))
=AVERAGE(B:B)
=COUNTA(B:B)
=COUNTIF(B:B, "Yes")
Get the data from a cell with more than one condition (use shift-ctrl-enter to activate formula, note the ampersands)
=INDEX(C:C,MATCH(B2&"value",A:A&B:B,0))