JavaScript Base

window.innerWidth
window.innerHeight
window.screen.availWidth
window.screen.availHeigh
window.screen.width
window.screen.height

Code:

elementList = parentNode.querySelectorAll(selectors);

elementList.forEach(function(element) {
    console.log(element)
});

Element Property:

ParentNode.childElementCount

ParentNode.firstElementChild

ParentNode.lastElementChild

ParentNode.children

Element.tagName

Code:

const div = document.createElement('div')
div.className = "big"
div.innerHTML = "Hello World!"
div.style = "color: green;"
console.log(div.outerHTML)
document.body.appendChild(div)

let loop
loop = setInterval(() => {
    div.classList.toggle("big")
}, 1000)

let bt = document.createElement("button")
bt.className = "bt"
bt.innerHTML = "Stop Color Toggle"
document.body.appendChild(bt)

let stopinterval = function() {
    clearInterval(loop);
}
document.querySelector(".bt").addEventListener("click", stopinterval)

JavaScript

这篇文章: 有用 无用
创建 2018-11-13 01:51:58 / 更新 2018-12-03 18:14:02

Python中的异常

如何引发异常

使用raise语句

>>> raise
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType
>>> 
>>> raise Exception("Unknown Error")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception: Unknown Error

如何显示所有的内建异常

>>> import exceptions
>>> dir(exceptions) 

自定义异常

继承Exception这个异常的基类即可

>>> class CustomerException(Exception): pass    

如何捕捉异常

>>> 1/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> 
>>> try:
...   1/0
... except ZeroDivisionError:
...   print("zero division error")
... 
zero division error

如何捕捉到异常并重新引发它

调用不带参数的raise

>>> try:
...   1/0
... except Exception:
...   print("got exception")
...   raise
... 
got exception
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero 

多个except子句

try:
  x = input("x:")
  y = input("y:")
  int(x)/int(y)
except ZeroDivisionError:
  print("division by zero {}/{}".format(x, y))
except ValueError:
  print("value error {}/{}".format(x, y))       

用一个块捕捉两个异常

try:
  x = input("x:")
  y = input("y:")
  int(x)/int(y)
except (ZeroDivisionError, ValueError) as e:
  print(e)
  print("error: {}/{}".format(x, y))

else

try:
  print("Hello World!")
except:
  print("Got Error!")
else:
  print("Everything is OK!")      

# Hello World!
# Everything is OK!

finally

Example 1:

try: 
  1/0
finally:
  print("Cleaning Up")  

'''   
Cleaning Up
Traceback (most recent call last):
  File "test4.py", line 2, in <module>
    1/0
ZeroDivisionError: division by zero
'''

Example 2:

try: 
  1/0
except:
  print("Unknow")
else:
  print("Well")
finally:
  print("Cleaning Up")

# Unknow
# Cleaning Up     

Python

这篇文章: 有用 无用
创建 2018-10-22 17:00:52 / 更新 2018-10-22 17:00:52

Python中的参数传递

基本参数

def hello(greeting, name):
    print('{0}, {1}!'.format(greeting, name))

hello("Hello", "World")

默认参数

def hello2(name="World", greeting="Hello"):
  print('{0}, {1}!'.format(greeting, name))

hello2() # Hello, World!
hello2("Noah") # Hello, Noah!
hello2(name="Noah") # Hello, Noah!
hello2(greeting="Hi") # Hi, World!
hello2("Beata", "Hi") # Hi, Beata!

收集参数

def print_params(*params):
   print(params)

print_params(1,2,3) # (1, 2, 3)

def print_params(title, *params):
    print(title)
    print(params) 

print_params("Title", 1, 2, 3) 
# Title
# (1, 2, 3)

def print_pair(**kp):
    print(kp)

print_pair(x=1, y=2, z=3) # {'x': 1, 'y': 2, 'z': 3}

def print_all(title, *params, **kp):
    print(title)
    print(*params)
    print(kp)

print_all("Title", 1, 2, 3, x=1, y=2, z=3)
# Title
# 1 2 3
# {'x': 1, 'y': 2, 'z': 3}      

反转参数

def add(x, y):
    'Add x and y and print it'
    print("{0}+{1}={2}".format(x, y, x+y))

add(4, 5)
nums = [4, 5]
add(*nums)

params = {"greeting": "Hi", "name": "Dear"}

hello(**params)
hello2(**params)

方法相关

print(callable(nums)) # False
print(callable(hello)) # True

print("-"*100)
print(add.__doc__)
print("-"*100)
help(add)
print("-"*100)  

Python

这篇文章: 有用 无用
创建 2018-10-16 16:45:05 / 更新 2018-10-16 16:45:05

SQL Server Date

Subtract one day from datetime

DATEADD(day, -1, GETDATE())
DATEADD(hour, 1, GETDATE())

DATEDIFF

DATEDIFF ( [day|hour|minute|second|millisecond] , startdate , enddate )

SELECT DATEDIFF(DAY,  '2012-12-12 12:00:00', '2012-12-13 16:00:00') -- return 1

DECLARE @Start datetime
DECLARE @End datetime
SET @Start = GETDATE()
SET @End = GETDATE()
SELECT DATEDIFF(millisecond, @Start, @End)

Convert String to DateTime

CONVERT(datetime, '2012/12/12 08:30:00')

SELECT CONVERT(varchar, GETDATE(), 1) 

SELECT CONVERT(varchar, CONVERT(datetime, '2012-12-01'), 101) -- 12/01/2012

DATEPART

SELECT DATEPART(YEAR, GETDATE())
SELECT DATEPART(dd, GETDATE())
SELECT DATEPART(ms, GETDATE())

Query time zone

DECLARE @TimeZone VARCHAR(50)
EXEC MASTER.dbo.xp_regread 
'HKEY_LOCAL_MACHINE','SYSTEM\CurrentControlSet\Control\TimeZoneInformation','TimeZoneKeyName',@TimeZone OUT
SELECT @TimeZone

Query time and time zone offset

SELECT SYSDATETIMEOFFSET() 

Convert DateTime to Date

SELECT CONVERT(date, getdate())

Query UTC time

SELECT GETUTCDATE()  -- 2019-04-04 05:42:45.170

Query more precision date

SELECT SYSDATETIME(), SYSUTCDATETIME() -- Returns a datetime2(7) value, e.g.: 2019-04-04 00:43:41.7743182

SQLServer

这篇文章: 有用 无用
创建 2018-09-28 22:35:37 / 更新 2019-04-06 20:55:33

Python中的基本操作

sys

import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
paths = sys.path # return lib paths

os

import os
os.system() # Execute a shell command
os.getcwd() # Returns the current working directory.
os.getgid() # Return the real group id of the current process.
os.getuid() # Return the current process’s user id.
os.getpid() # Returns the real process ID of the current process.
os.uname() # Return information identifying the current operating system.
os.chroot(path) # Change the root directory of the current process to path.
os.listdir(path) # Return a list of the entries in the directory given by path.
os.mkdir(path) # Create a directory named path with numeric mode mode.
os.makedirs(path) # Recursive directory creation function.
os.remove(path) # Remove (delete) the file path.
os.removedirs(path) # Remove directories recursively.
os.rename(src, dst) # Rename the file or directory src to dst.
os.rmdir(path) # Remove (delete) the directory path.

os.path

import os.path
os.path.isfile('my_settings.dat')
os.path.isdir('src')
os.path.exists('tumblr')

string

import string
string.ascii_lowercase # 'abcdefghijklmnopqrstuvwxyz'

Python

这篇文章: 有用 无用
创建 2018-08-05 23:11:35 / 更新 2018-10-16 02:54:42