INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
For each edge expecting a word of this category here extend the edge. | def scanner(self, j, word):
"For each edge expecting a word of this category here, extend the edge."
for (i, j, A, alpha, Bb) in self.chart[j]:
if Bb and self.grammar.isa(word, Bb[0]):
self.add_edge([i, j+1, A, alpha + [(Bb[0], word)], Bb[1:]]) |
Add to chart any rules for B that could help extend this edge. | def predictor(self, (i, j, A, alpha, Bb)):
"Add to chart any rules for B that could help extend this edge."
B = Bb[0]
if B in self.grammar.rules:
for rhs in self.grammar.rewrites_for(B):
self.add_edge([j, j, B, [], rhs]) |
See what edges can be extended by this edge. | def extender(self, edge):
"See what edges can be extended by this edge."
(j, k, B, _, _) = edge
for (i, j, A, alpha, B1b) in self.chart[j]:
if B1b and B == B1b[0]:
self.add_edge([i, k, A, alpha + [edge], B1b[1:]]) |
Adds a SettingDict object for the Setting model to the context as SETTINGS. Automatically creates non - existent settings with an empty string as the default value. | def settings(request):
"""
Adds a ``SettingDict`` object for the ``Setting`` model to the context as
``SETTINGS``. Automatically creates non-existent settings with an empty
string as the default value.
"""
settings = Setting.objects.all().as_dict(default='')
context = {
'SETTINGS': s... |
Returns a list of ( Model ModelAdmin ) tuples for base_model subclasses. | def get_child_models(self):
"""
Returns a list of ``(Model, ModelAdmin)`` tuples for ``base_model``
subclasses.
"""
child_models = []
# Loop through all models with FKs back to `base_model`.
for related_object in get_all_related_objects(self.base_model._meta):
... |
A decision - theoretic agent. [ Fig. 13. 1 ] | def DTAgentProgram(belief_state):
"A decision-theoretic agent. [Fig. 13.1]"
def program(percept):
belief_state.observe(program.action, percept)
program.action = argmax(belief_state.actions(),
belief_state.expected_outcome_utility)
return program.action
... |
Return a tuple of the values of variables vars in event. >>> event_values ( { A: 10 B: 9 C: 8 } [ C A ] ) ( 8 10 ) >>> event_values (( 1 2 ) [ C A ] ) ( 1 2 ) | def event_values(event, vars):
"""Return a tuple of the values of variables vars in event.
>>> event_values ({'A': 10, 'B': 9, 'C': 8}, ['C', 'A'])
(8, 10)
>>> event_values ((1, 2), ['C', 'A'])
(1, 2)
"""
if isinstance(event, tuple) and len(event) == len(vars):
return event
else:... |
Return a probability distribution over the values of the variable X given the { var: val } observations e in the JointProbDist P. [ Section 13. 3 ] >>> P = JointProbDist ( [ X Y ] ) >>> P [ 0 0 ] = 0. 25 ; P [ 0 1 ] = 0. 5 ; P [ 1 1 ] = P [ 2 1 ] = 0. 125 >>> enumerate_joint_ask ( X dict ( Y = 1 ) P ). show_approx () 0... | def enumerate_joint_ask(X, e, P):
"""Return a probability distribution over the values of the variable X,
given the {var:val} observations e, in the JointProbDist P. [Section 13.3]
>>> P = JointProbDist(['X', 'Y'])
>>> P[0,0] = 0.25; P[0,1] = 0.5; P[1,1] = P[2,1] = 0.125
>>> enumerate_joint_ask('X',... |
Return the sum of those entries in P consistent with e provided vars is P s remaining variables ( the ones not in e ). | def enumerate_joint(vars, e, P):
"""Return the sum of those entries in P consistent with e,
provided vars is P's remaining variables (the ones not in e)."""
if not vars:
return P[e]
Y, rest = vars[0], vars[1:]
return sum([enumerate_joint(rest, extend(e, Y, y), P)
for y in P.v... |
Return the conditional probability distribution of variable X given evidence e from BayesNet bn. [ Fig. 14. 9 ] >>> enumeration_ask ( Burglary dict ( JohnCalls = T MaryCalls = T ) burglary... ). show_approx () False: 0. 716 True: 0. 284 | def enumeration_ask(X, e, bn):
"""Return the conditional probability distribution of variable X
given evidence e, from BayesNet bn. [Fig. 14.9]
>>> enumeration_ask('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary
... ).show_approx()
'False: 0.716, True: 0.284'"""
assert X not in e, "Query v... |
Return the sum of those entries in P ( vars | e { others } ) consistent with e where P is the joint distribution represented by bn and e { others } means e restricted to bn s other variables ( the ones other than vars ). Parents must precede children in vars. | def enumerate_all(vars, e, bn):
"""Return the sum of those entries in P(vars | e{others})
consistent with e, where P is the joint distribution represented
by bn, and e{others} means e restricted to bn's other variables
(the ones other than vars). Parents must precede children in vars."""
if not vars... |
Compute bn s P ( X|e ) by variable elimination. [ Fig. 14. 11 ] >>> elimination_ask ( Burglary dict ( JohnCalls = T MaryCalls = T ) burglary... ). show_approx () False: 0. 716 True: 0. 284 | def elimination_ask(X, e, bn):
"""Compute bn's P(X|e) by variable elimination. [Fig. 14.11]
>>> elimination_ask('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary
... ).show_approx()
'False: 0.716, True: 0.284'"""
assert X not in e, "Query variable must be distinct from evidence"
factors = []... |
Return the factor for var in bn s joint distribution given e. That is bn s full joint distribution projected to accord with e is the pointwise product of these factors for bn s variables. | def make_factor(var, e, bn):
"""Return the factor for var in bn's joint distribution given e.
That is, bn's full joint distribution, projected to accord with e,
is the pointwise product of these factors for bn's variables."""
node = bn.variable_node(var)
vars = [X for X in [var] + node.parents if X ... |
Eliminate var from all factors by summing over its values. | def sum_out(var, factors, bn):
"Eliminate var from all factors by summing over its values."
result, var_factors = [], []
for f in factors:
(var_factors if var in f.vars else result).append(f)
result.append(pointwise_product(var_factors, bn).sum_out(var, bn))
return result |
Yield every way of extending e with values for all vars. | def all_events(vars, bn, e):
"Yield every way of extending e with values for all vars."
if not vars:
yield e
else:
X, rest = vars[0], vars[1:]
for e1 in all_events(rest, bn, e):
for x in bn.variable_values(X):
yield extend(e1, X, x) |
Randomly sample from bn s full joint distribution. The result is a { variable: value } dict. [ Fig. 14. 13 ] | def prior_sample(bn):
"""Randomly sample from bn's full joint distribution. The result
is a {variable: value} dict. [Fig. 14.13]"""
event = {}
for node in bn.nodes:
event[node.variable] = node.sample(event)
return event |
Estimate the probability distribution of variable X given evidence e in BayesNet bn using N samples. [ Fig. 14. 14 ] Raises a ZeroDivisionError if all the N samples are rejected i. e. inconsistent with e. >>> seed ( 47 ) >>> rejection_sampling ( Burglary dict ( JohnCalls = T MaryCalls = T )... burglary 10000 ). show_ap... | def rejection_sampling(X, e, bn, N):
"""Estimate the probability distribution of variable X given
evidence e in BayesNet bn, using N samples. [Fig. 14.14]
Raises a ZeroDivisionError if all the N samples are rejected,
i.e., inconsistent with e.
>>> seed(47)
>>> rejection_sampling('Burglary', dic... |
Is event consistent with the given evidence? | def consistent_with(event, evidence):
"Is event consistent with the given evidence?"
return every(lambda (k, v): evidence.get(k, v) == v,
event.items()) |
Estimate the probability distribution of variable X given evidence e in BayesNet bn. [ Fig. 14. 15 ] >>> seed ( 1017 ) >>> likelihood_weighting ( Burglary dict ( JohnCalls = T MaryCalls = T )... burglary 10000 ). show_approx () False: 0. 702 True: 0. 298 | def likelihood_weighting(X, e, bn, N):
"""Estimate the probability distribution of variable X given
evidence e in BayesNet bn. [Fig. 14.15]
>>> seed(1017)
>>> likelihood_weighting('Burglary', dict(JohnCalls=T, MaryCalls=T),
... burglary, 10000).show_approx()
'False: 0.702, True: 0.298'
""... |
Sample an event from bn that s consistent with the evidence e ; return the event and its weight the likelihood that the event accords to the evidence. | def weighted_sample(bn, e):
"""Sample an event from bn that's consistent with the evidence e;
return the event and its weight, the likelihood that the event
accords to the evidence."""
w = 1
event = dict(e) # boldface x in Fig. 14.15
for node in bn.nodes:
Xi = node.variable
if Xi... |
[ Fig. 14. 16 ] >>> seed ( 1017 ) >>> gibbs_ask ( Burglary dict ( JohnCalls = T MaryCalls = T ) burglary 1000... ). show_approx () False: 0. 738 True: 0. 262 | def gibbs_ask(X, e, bn, N):
"""[Fig. 14.16]
>>> seed(1017)
>>> gibbs_ask('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary, 1000
... ).show_approx()
'False: 0.738, True: 0.262'
"""
assert X not in e, "Query variable must be distinct from evidence"
counts = dict((x, 0) for x in bn.var... |
Return a sample from P ( X | mb ) where mb denotes that the variables in the Markov blanket of X take their values from event e ( which must assign a value to each ). The Markov blanket of X is X s parents children and children s parents. | def markov_blanket_sample(X, e, bn):
"""Return a sample from P(X | mb) where mb denotes that the
variables in the Markov blanket of X take their values from event
e (which must assign a value to each). The Markov blanket of X is
X's parents, children, and children's parents."""
Xnode = bn.variable_n... |
Make sure the probabilities of all values sum to 1. Returns the normalized distribution. Raises a ZeroDivisionError if the sum of the values is 0. >>> P = ProbDist ( Flip ) ; P [ H ] P [ T ] = 35 65 >>> P = P. normalize () >>> print %5. 3f %5. 3f % ( P. prob [ H ] P. prob [ T ] ) 0. 350 0. 650 | def normalize(self):
"""Make sure the probabilities of all values sum to 1.
Returns the normalized distribution.
Raises a ZeroDivisionError if the sum of the values is 0.
>>> P = ProbDist('Flip'); P['H'], P['T'] = 35, 65
>>> P = P.normalize()
>>> print '%5.3f %5.3f' % (P.... |
Show the probabilities rounded and sorted by key for the sake of portable doctests. | def show_approx(self, numfmt='%.3g'):
"""Show the probabilities rounded and sorted by key, for the
sake of portable doctests."""
return ', '.join([('%s: ' + numfmt) % (v, p)
for (v, p) in sorted(self.prob.items())]) |
Add a node to the net. Its parents must already be in the net and its variable must not. | def add(self, node_spec):
"""Add a node to the net. Its parents must already be in the
net, and its variable must not."""
node = BayesNode(*node_spec)
assert node.variable not in self.vars
assert every(lambda parent: parent in self.vars, node.parents)
self.nodes.append(no... |
Return the node for the variable named var. >>> burglary. variable_node ( Burglary ). variable Burglary | def variable_node(self, var):
"""Return the node for the variable named var.
>>> burglary.variable_node('Burglary').variable
'Burglary'"""
for n in self.nodes:
if n.variable == var:
return n
raise Exception("No such variable: %s" % var) |
Return the conditional probability P ( X = value | parents = parent_values ) where parent_values are the values of parents in event. ( event must assign each parent a value. ) >>> bn = BayesNode ( X Burglary { T: 0. 2 F: 0. 625 } ) >>> bn. p ( False { Burglary: False Earthquake: True } ) 0. 375 | def p(self, value, event):
"""Return the conditional probability
P(X=value | parents=parent_values), where parent_values
are the values of parents in event. (event must assign each
parent a value.)
>>> bn = BayesNode('X', 'Burglary', {T: 0.2, F: 0.625})
>>> bn.p(False, {'... |
Multiply two factors combining their variables. | def pointwise_product(self, other, bn):
"Multiply two factors, combining their variables."
vars = list(set(self.vars) | set(other.vars))
cpt = dict((event_values(e, vars), self.p(e) * other.p(e))
for e in all_events(vars, bn, {}))
return Factor(vars, cpt) |
Make a factor eliminating var by summing over its values. | def sum_out(self, var, bn):
"Make a factor eliminating var by summing over its values."
vars = [X for X in self.vars if X != var]
cpt = dict((event_values(e, vars),
sum(self.p(extend(e, var, val))
for val in bn.variable_values(var)))
... |
Return my probabilities ; must be down to one variable. | def normalize(self):
"Return my probabilities; must be down to one variable."
assert len(self.vars) == 1
return ProbDist(self.vars[0],
dict((k, v) for ((k,), v) in self.cpt.items())) |
Computes the next chunk boundaries within buf. | def next_chunk_boundaries(self, buf, prepend_bytes=0):
"""Computes the next chunk boundaries within `buf`.
See :meth:`.BaseChunker.next_chunk_boundaries`.
"""
return (boundary for boundary, _ in self.next_chunk_boundaries_levels(buf, prepend_bytes)) |
Computes the next chunk boundaries within buf. | def next_chunk_boundaries_levels(self, buf, prepend_bytes=0):
"""Computes the next chunk boundaries within `buf`.
Similar to :meth:`.next_chunk_boundaries`, but information about which chunker led to a respective boundary is
included in the returned value.
Args:
buf (bytes)... |
Create a chunker performing content - defined chunking ( CDC ) using Rabin Karp s rolling hash scheme with a specific expected chunk size. | def create_chunker(self, chunk_size):
"""Create a chunker performing content-defined chunking (CDC) using Rabin Karp's rolling hash scheme with a
specific, expected chunk size.
Args:
chunk_size (int): (Expected) target chunk size.
Returns:
BaseChunker: A chunker... |
Create a multi - level chunker performing content - defined chunking ( CDC ) using Rabin Karp s rolling hash scheme with different specific expected chunk sizes. | def create_multilevel_chunker(self, chunk_sizes):
"""Create a multi-level chunker performing content-defined chunking (CDC) using Rabin Karp's rolling hash scheme
with different specific, expected chunk sizes.
Args:
chunk_sizes (list): List of (expected) target chunk sizes.
... |
Assumes level is out of 100 | def brightness(level=100, group=0):
""" Assumes level is out of 100 """
if level not in range(0,101):
raise Exception("Brightness must be value between 0 and 100")
b = int(floor(level / 4.0) + 2) #lights want values 2-27
return (COMMANDS['ON'][group], Command(0x4E, b)) |
Strips all whitespace from a minidom XML node and its children | def strip_minidom_whitespace(node):
"""Strips all whitespace from a minidom XML node and its children
This operation is made in-place."""
for child in node.childNodes:
if child.nodeType == Node.TEXT_NODE:
if child.nodeValue:
child.nodeValue = child.nodeValue.strip()
... |
Assumes level is out of 100 | def brightness(level=100, group=0):
""" Assumes level is out of 100 """
if level not in range(0,101):
raise Exception("Brightness must be value between 0 and 100")
b = int(floor(level / 10.0)) #lights have 10 levels of brightness
commands = list(darkest(group))
for i in range(0, b):
... |
Assumes level is out of 100 | def warmness(level=100, group=0):
""" Assumes level is out of 100 """
if level not in range(0,101):
raise Exception("Warmness must be value between 0 and 100")
b = int(floor(level / 10.0)) #lights have 10 levels of warmness
commands = list(coolest(group))
for i in range(0, b):
comman... |
Takes a hls color and converts to proper hue Bulbs use a BGR order instead of RGB | def color_from_hls(hue, light, sat):
""" Takes a hls color and converts to proper hue
Bulbs use a BGR order instead of RGB """
if light > 0.95: #too bright, let's just switch to white
return 256
elif light < 0.05: #too dark, let's shut it off
return -1
else:
hue = (-hue ... |
Takes your standard rgb color and converts it to a proper hue value | def color_from_rgb(red, green, blue):
""" Takes your standard rgb color
and converts it to a proper hue value """
r = min(red, 255)
g = min(green, 255)
b = min(blue, 255)
if r > 1 or g > 1 or b > 1:
r = r / 255.0
g = g / 255.0
b = b / 255.0
return color_fro... |
Takes an HTML hex code and converts it to a proper hue value | def color_from_hex(value):
""" Takes an HTML hex code
and converts it to a proper hue value """
if "#" in value:
value = value[1:]
try:
unhexed = bytes.fromhex(value)
except:
unhexed = binascii.unhexlify(value) # Fallback for 2.7 compatibility
return color_from_r... |
Wait for x seconds each wait command is 100ms | def wait(self, sec=0.1):
""" Wait for x seconds
each wait command is 100ms """
sec = max(sec, 0)
reps = int(floor(sec / 0.1))
commands = []
for i in range(0, reps):
commands.append(Command(0x00, wait=True))
return tuple(commands) |
ex1 ) tic () # save start time - time1 toc () # print elapsed time from last calling tic () toc () # print elapsed time from last calling tic () | def toc(t=None, name='tictoc'):
"""
ex1)
tic() # save start time - time1
toc() # print elapsed time from last calling tic()
toc() # print elapsed time from last calling tic()
ex2)
t0 = tic() # simple
t1 = tic()
toc(t1) # print time from t1
toc(t0) # print time from t0
... |
with tictoc ( any string or not ): print cool~~~ cool~~~ 2015 - 12 - 30 14: 39: 28 458 [ INFO ] tictoc Elapsed: 7. 10487365723e - 05 secs: param name: str | def tictoc(name='tictoc'):
"""
with tictoc('any string or not'):
print 'cool~~~'
cool~~~
2015-12-30 14:39:28,458 [INFO] tictoc Elapsed: 7.10487365723e-05 secs
:param name: str
"""
t = time.time()
yield
logg.info('%s Elapsed: %s secs' % (name, time.time() - t)) |
data ( 1 - ratio ) data ( with ratio ) = split_rand ( data_or_size ratio seed ): param data_or_size: data or count: param ratio:: param seed:: return: | def split_rand(data_or_size, ratio, seed):
"""
data(1-ratio), data(with ratio) = split_rand(data_or_size, ratio, seed)
:param data_or_size: data or count
:param ratio:
:param seed:
:return:
"""
if not isinstance(data_or_size, int):
sz = len(data_or_size)
data = np.asarray... |
return train valid [ test ] testset if p_testset: param n:: param k:: param sz:: param p_testset:: param seed:: return: | def kfolds(n, k, sz, p_testset=None, seed=7238):
"""
return train, valid [,test]
testset if p_testset
:param n:
:param k:
:param sz:
:param p_testset:
:param seed:
:return:
"""
trains, tests = split_rand(sz, p_testset, seed)
ntrain = len(trains)
# np.random.seed(se... |
An decorator checking whether date parameter is passing in or not. If not default date value is all PTT data. Else return PTT data with right date. Args: func: function you want to decorate. request: WSGI request parameter getten from django. | def date_proc(func):
""" An decorator checking whether date parameter is passing in or not. If not, default date value is all PTT data.
Else, return PTT data with right date.
Args:
func: function you want to decorate.
request: WSGI request parameter getten from django.
Returns:
date:
a datetime variable,... |
An decorator checking whether queryString key is valid or not Args: str: allowed queryString key | def queryString_required(strList):
""" An decorator checking whether queryString key is valid or not
Args:
str: allowed queryString key
Returns:
if contains invalid queryString key, it will raise exception.
"""
def _dec(function):
@wraps(function)
def _wrap(request, *args, **kwargs):
for i in strList:
... |
An decorator checking whether queryString key is valid or not Args: str: allowed queryString key | def queryString_required_ClassVersion(strList):
""" An decorator checking whether queryString key is valid or not
Args:
str: allowed queryString key
Returns:
if contains invalid queryString key, it will raise exception.
"""
def _dec(function):
@wraps(function)
def _wrap(classInstance, request, *args, **kw... |
Return json from querying Web Api | def getJsonFromApi(view, request):
"""Return json from querying Web Api
Args:
view: django view function.
request: http request object got from django.
Returns: json format dictionary
"""
jsonText = view(request)
jsonText = json.loads(jsonText.content.decode('utf-8'))
return jsonText |
프로그래스 bar for i in progress ( 10 ): print i | def progress(iter, **kwargs):
"""
프로그래스 bar
for i in progress(10):
print i
for i in progress(iter):
print i
"""
if isinstance(iter, int):
iter = xrange(iter)
if hasattr(iter, '__len__') or 'target' in kwargs:
cls = Progress
else:
cls = ProgressBas... |
function decorator | def threaded(f, *args, **kwargs):
"""function decorator
"""
if args or kwargs:
return Threaded(f, *args, **kwargs)
@wraps(f)
def wrapped(*wargs, **wkwargs):
return Threaded(f, *wargs, **wkwargs)
return wrapped |
decorator | def spawn(f, *args, **kwargs):
"""decorator
"""
if args or kwargs:
return Spawn(f, *args, **kwargs)
@wraps(f)
def wrapped(*args, **kwargs):
return Spawn(f, *args, **kwargs)
return wrapped |
self와 other 키가 동일한 아이템의 dictobj: type other: dict: rtype: dictobj: | def intersect(self, other):
"""
self와 other 키가 동일한 아이템의 dictobj
:type other: dict
:rtype: dictobj:
"""
return ODict((k, self[k]) for k in self if k in other) |
recursive dict to dictobj 컨버트: param dic:: return: | def from_dict(dic):
"""
recursive dict to dictobj 컨버트
:param dic:
:return:
"""
return ODict((k, ODict.convert_ifdic(v)) for k, v in dic.items()) |
simple wrapper plot with labels and skip x: param yonly_or_xy:: param kwargs:: return: | def plots(data, **kwargs):
"""
simple wrapper plot with labels and skip x
:param yonly_or_xy:
:param kwargs:
:return:
"""
labels = kwargs.pop('labels', '')
loc = kwargs.pop('loc', 1)
# if len(yonly_or_xy) == 1:
# x = range(len(yonly_or_xy))
# y = yonly_or_xy
# el... |
: param images: nhwc: return: | def imshow_grid(images, grid=None, showfun=None, **opt):
"""
:param images: nhwc
:return:
"""
# assert images.ndim == 4 or list
showfun = showfun or plt.imshow
count = len(images)
grid = grid or grid_recommend(count, sorted(images[0].shape[:2]))
res = []
for i, img in enumerate... |
for i in plot_range ( n ): plt. imshow ( imgs [ i ] ) | def plt_range(*args, **kwargs):
"""
for i in plot_range(n):
plt.imshow(imgs[i])
left arrow yield prev value
other key yield next value
:param args:
:return:
"""
wait = kwargs.pop('wait', True)
if not wait:
# no interactive just pass range
for i in progress(ra... |
todo: add some example: param timeout: wait time. if None blocking: param msg:: return: | def plot_pause(timeout=None, msg=''):
"""
todo : add some example
:param timeout: wait time. if None, blocking
:param msg:
:return:
"""
if timeout is not None:
print(msg or 'Press key for continue in time {}'.format(timeout))
plt.waitforbuttonpress(timeout=timeout)
r... |
convert batch image to flat image with margin inserted [ B h w c ] = > [ H W c ]: param images:: param grid: patch grid cell size of ( Row Col ): param bfill: board filling value: param bsz: int or ( int int ) board size: return: flatted image | def flat_images(images, grid=None, bfill=1.0, bsz=(1, 1)):
"""
convert batch image to flat image with margin inserted
[B,h,w,c] => [H,W,c]
:param images:
:param grid: patch grid cell size of (Row, Col)
:param bfill: board filling value
:param bsz: int or (int, int) board size
:return: fl... |
imshow after applying flat_images: param images: [ bhwc ]: param grid: None for auto grid: param showfun: plt. imshow: param bfill: color for board fill: param bsz: size of board: param opt: option for showfun: return: | def imshow_flat(images, grid=None, showfun=None, bfill=1.0, bsz=(1,1), **opt):
"""
imshow after applying flat_images
:param images: [bhwc]
:param grid: None for auto grid
:param showfun: plt.imshow
:param bfill: color for board fill
:param bsz: size of board
:param opt: option for showfu... |
imshow without interpolation like as matshow: param args:: param kwargs:: return: | def matshow(*args, **kwargs):
"""
imshow without interpolation like as matshow
:param args:
:param kwargs:
:return:
"""
kwargs['interpolation'] = kwargs.pop('interpolation', 'none')
return plt.imshow(*args, **kwargs) |
draw boundary box: param xy: start index xy ( ji ): param w: width: param h: height: param angle:: param kwargs:: return: | def imbox(xy, w, h, angle=0.0, **kwargs):
"""
draw boundary box
:param xy: start index xy (ji)
:param w: width
:param h: height
:param angle:
:param kwargs:
:return:
"""
from matplotlib.patches import Rectangle
return imbound(Rectangle, xy, w, h, angle, **kwargs) |
: param clspatch:: param args:: param kwargs:: return: | def imbound(clspatch, *args, **kwargs):
"""
:param clspatch:
:param args:
:param kwargs:
:return:
"""
# todo : add example
c = kwargs.pop('color', kwargs.get('edgecolor', None))
kwargs.update(facecolor='none', edgecolor=c)
return impatch(clspatch, *args, **kwargs) |
slic args: n_segments = 100 compactness = 10. max_iter = 10 sigma = 0 spacing = None multichannel = True convert2lab = None enforce_connectivity = True min_size_factor = 0. 5 max_size_factor = 3 slic_zero = False | def imslic(img, n_segments=100, aspect=None):
"""
slic args :
n_segments=100, compactness=10., max_iter=10,
sigma=0, spacing=None,
multichannel=True, convert2lab=None, enforce_connectivity=True,
min_size_factor=0.5, max_size_factor=3, slic_zero=False
mark_boundaries args:
label_img, col... |
slic args: n_segments = 100 compactness = 10. max_iter = 10 sigma = 0 spacing = None multichannel = True convert2lab = None enforce_connectivity = True min_size_factor = 0. 5 max_size_factor = 3 slic_zero = False | def imslic2(img, n_segments=100, color=None, outline_color=None, mode='thick', **kwargs):
"""
slic args :
n_segments=100, compactness=10., max_iter=10,
sigma=0, spacing=None,
multichannel=True, convert2lab=None, enforce_connectivity=True,
min_size_factor=0.5, max_size_factor=3, slic_zero=False
... |
contextmanager for PlotMovieWriter Example: | def movie_saving(outfile, showfun=imshow, fig=None, tight=True, drawopt=None, dpi=100, **movieopt):
"""
contextmanager for PlotMovieWriter
Example:
with movie_saving('output.mp4', dpi=100) as plot:
for i in range(10):
plot(data[i])
:param outfile:
:param showfun... |
put text on on screen a tuple as first argument tells absolute position for the text does not change TermCursor position args = list of optional position formatting tokens and strings | def put(xy, *args):
"""
put text on on screen
a tuple as first argument tells absolute position for the text
does not change TermCursor position
args = list of optional position, formatting tokens and strings
"""
cmd = [TermCursor.save, TermCursor.move(*xy), ''.join(args), TermCursor.restore... |
get user input without echo | def getpassword(prompt="Password: "):
"""
get user input without echo
"""
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3] &= ~termios.ECHO # lflags
try:
termios.tcsetattr(fd, termios.TCSADRAIN, new)
passwd = raw_input(promp... |
get character. waiting for key | def getch():
"""
get character. waiting for key
"""
try:
termios.tcsetattr(_fd, termios.TCSANOW, _new_settings)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(_fd, termios.TCSADRAIN, _old_settings)
return ch |
패키지 혹은 채널 로거 logging. getLogger ( package_name ) or logg. getLogger (): param pkg: str | def getlogger(pkg='', handler=None):
"""
패키지 혹은 채널 로거
logging.getLogger(package_name) or logg.getLogger()
:param pkg: str
"""
from .caller import caller
if not pkg:
m = caller.modulename()
s = m.split('.', 1)
if len(s) > 1:
pkg = s[0]
if haslogger(pk... |
logging의 로그를 한번 호출하면 basicConfig가 안먹으므로. 기존 핸들러 삭제후 재설정. http:// stackoverflow. com/ questions/ 1943747/ python - logging - before - you - run - logging - basicconfig ex ) basicConfig ( format = % ( asctime ) s % ( message ) s level = logging. DEBUG ): param filename: Specifies that a FileHandler be created using the s... | def basicConfig(**kw):
"""logging의 로그를 한번 호출하면 basicConfig가 안먹으므로. 기존 핸들러 삭제후 재설정.
http://stackoverflow.com/questions/1943747/python-logging-before-you-run-logging-basicconfig
ex)
basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)
:param filename: Specifies that a FileHandler be crea... |
tweaked from source of base | def format(self, record):
"""tweaked from source of base"""
try:
record.message = record.getMessage()
except TypeError:
# if error during msg = msg % self.args
if record.args:
if isinstance(record.args, collections.Mapping):
... |
getProcessOwner - Get the process owner of a pid | def getProcessOwner(pid):
'''
getProcessOwner - Get the process owner of a pid
@param pid <int> - process id
@return - None if process not found or can't be determined. Otherwise, a dict:
{
uid - Owner UID
name - Owner name, or None if one cann... |
getProcessOwner - Get Process owner of a pid as a string instead of components ( #getProcessOwner ) | def getProcessOwnerStr(pid):
'''
getProcessOwner - Get Process owner of a pid as a string instead of components (#getProcessOwner)
@return - Returns username if it can be determined, otherwise uid, otherwise "unknown"
'''
ownerInfo = getProcessOwner(pid)
if ownerInfo:
if ownerIn... |
getProcessCommandLineStr - Gets a the commandline ( program + arguments ) of a given pid | def getProcessCommandLineStr(pid):
'''
getProcessCommandLineStr - Gets a the commandline (program + arguments) of a given pid
@param pid <int> - Process ID
@return - None if process not found or can't be determined. Otherwise a string of commandline.
@note Caution, args may have s... |
getProcessCommandLineList - Gets the commandline ( program + argumentS ) of a given pid as a list. | def getProcessCommandLineList(pid):
'''
getProcessCommandLineList - Gets the commandline (program + argumentS) of a given pid as a list.
@param pid <int> - Process ID
@return - None if process not found or can't be determined. Otherwise a list representing argv. First argument is process n... |
scanProcessForCwd - Searches a given pid s cwd for a given pattern | def scanProcessForCwd(pid, searchPortion, isExactMatch=False):
'''
scanProcessForCwd - Searches a given pid's cwd for a given pattern
@param pid <int> - A running process ID on this system
@param searchPortion <str> - Any portion of directory to search
@param isExactMatc... |
scanAllProcessesForCwd - Scans all processes on the system for a given search pattern. | def scanAllProcessesForCwd(searchPortion, isExactMatch=False):
'''
scanAllProcessesForCwd - Scans all processes on the system for a given search pattern.
@param searchPortion <str> - Any portion of directory to search
@param isExactMatch <bool> Default False - If match should be exa... |
scanProcessForMapping - Searches a given pid s mappings for a certain pattern. | def scanProcessForMapping(pid, searchPortion, isExactMatch=False, ignoreCase=False):
'''
scanProcessForMapping - Searches a given pid's mappings for a certain pattern.
@param pid <int> - A running process ID on this system
@param searchPortion <str> - A mapping for which to search, ... |
scanAllProcessesForMapping - Scans all processes on the system for a given search pattern. | def scanAllProcessesForMapping(searchPortion, isExactMatch=False, ignoreCase=False):
'''
scanAllProcessesForMapping - Scans all processes on the system for a given search pattern.
@param searchPortion <str> - A mapping for which to search, example: libc or python or libz.so.1. Give empty string... |
scanProcessForOpenFile - Scans open FDs for a given pid to see if any are the provided searchPortion | def scanProcessForOpenFile(pid, searchPortion, isExactMatch=True, ignoreCase=False):
'''
scanProcessForOpenFile - Scans open FDs for a given pid to see if any are the provided searchPortion
@param searchPortion <str> - Filename to check
@param isExactMatch <bool> Default True - If m... |
scanAllProcessessForOpenFile - Scans all processes on the system for a given filename | def scanAllProcessesForOpenFile(searchPortion, isExactMatch=True, ignoreCase=False):
'''
scanAllProcessessForOpenFile - Scans all processes on the system for a given filename
@param searchPortion <str> - Filename to check
@param isExactMatch <bool> Default True - If match should be ... |
class buider | def enum(name, *members, **withvalue):
"""class buider"""
if len(members) == 1:
if isinstance(members[0], str):
members = members[0].split()
elif isinstance(members[0], (list, tuple)):
members = members[0]
dic = {v: v for v in members}
dic.update(withvalue)
... |
usage: with database ( my_db ) as conn: c = conn. cursor ().... database 커넥션 with 문과 같이 사용하고 알아서 close하기: param db: str: db스키마: param kwargs:: return: | def database(db='', **kwargs):
"""
usage:
with database('my_db') as conn:
c = conn.cursor()
....
database 커넥션 with 문과 같이 사용하고, 알아서 close하기
:param db: str: db스키마
:param kwargs:
:return:
"""
db = kwargs.pop('db', db)
arg = db_config(db)
arg.update(kwargs)
r... |
db 접속 공통 인자들 채워서 접속 schema만 넣으면 됩니다. db connection 객체 반환이지만 with 문과 같이 쓰이면 cursor임에 주의 ( MySQLdb의 구현이 그렇습니다. ) ex1 ) import snipy. database as db conn = db. connect ( my_db ) cursor = conn. cursor () | def connect(db='', **kwargs):
"""
db 접속 공통 인자들 채워서 접속, schema만 넣으면 됩니다.
db connection 객체 반환이지만
with 문과 같이 쓰이면 cursor임에 주의 (MySQLdb의 구현이 그렇습니다.)
ex1)
import snipy.database as db
conn = db.connect('my_db')
cursor = conn.cursor()
ex2)
import snipy.database as db
with db.connect... |
cursor with문과 쓸수 있게 __exit__에 바인딩: param cursor:: param exc_type:: param exc_value:: param traceback:: return: | def _cursor_exit(cursor, exc_type, exc_value, traceback):
"""
cursor with문과 쓸수 있게 __exit__에 바인딩
:param cursor:
:param exc_type:
:param exc_value:
:param traceback:
:return:
"""
if exc_type is not None:
print(exc_value, traceback)
cursor.connection.close() |
for record in fetch ( query args ** configs ): print record: param args:: param db: str: db 스키마: param query: 쿼리 스트링: param kwargs: db connection 추가 인자. 보통 생략: return: iterator | def fetch(query, args=None, **kwargs):
"""
for record in fetch(query, args, **configs):
print record
:param args:
:param db: str: db 스키마
:param query: 쿼리 스트링
:param kwargs: db connection 추가 인자. 보통 생략
:return: iterator
"""
cur = execute(kwargs.pop('db', ''), query, args, **kwa... |
format insert query: param table: str: param fields: list [ str ]: param field_count: int: return: str | def get_insert_query(table, fields=None, field_count=None):
"""
format insert query
:param table: str
:param fields: list[str]
:param field_count: int
:return: str
"""
if fields:
q = 'insert into %s ({0}) values ({1});' % table
l = len(fields)
q = q.format(','.joi... |
db에 레코드 집어넣기 ex ) cursor. insert ( table v1 v2... ) ex ) cursor. insert ( table id = v1 word = v2 commit = True ): param commit:: param cursor:: param table:: param args:: param field_values:: return: | def insert(cursor, table, *args, **field_values):
"""
db에 레코드 집어넣기
ex)
cursor.insert(table, v1, v2,...)
ex)
cursor.insert(table, id=v1, word=v2, commit=True)
:param commit:
:param cursor:
:param table:
:param args:
:param field_values:
:return:
"""
commit = field_... |
db update 쿼리 빌딩 및 실행 단 commit은: param cursor: 커서: type cursor: Cursor: param table: 테이블 이름: type table: str: param where_kv: 업데이트 where 조건 dictionary key: field value: equal condition only: type where_kv: dict: param field_values: kwarg 업데이트용: type field_values: dict: param commit: 커밋 여부: type commit: bool: return: | def update(cursor, table, where_kv, commit=True, **field_values):
"""
db update 쿼리 빌딩 및 실행, 단, commit은
:param cursor: 커서
:type cursor: Cursor
:param table: 테이블 이름
:type table: str
:param where_kv: 업데이트 where 조건 dictionary, key:field, value:equal condition only
:type where_kv: dict
:p... |
db update 쿼리 빌딩 및 실행 단 commit은: param cursor: 커서: type cursor: Cursor: param table: 테이블이름: type table: str: param commit: 커밋 여부: type commit: bool: param field_values: insert 또는 업데이트 할 필드 및 값 dict pairs: type field_values: dict: return: | def insert_or_update(cursor, table, commit=True, **field_values):
"""
db update 쿼리 빌딩 및 실행, 단, commit은
:param cursor: 커서
:type cursor: Cursor
:param table: 테이블이름
:type table: str
:param commit: 커밋 여부
:type commit: bool
:param field_values: insert 또는 업데이트 할 필드 및 값 dict pairs
:type... |
recursive implementation | def tojson(o):
"""
recursive implementation
"""
try:
return json.encode(o)
except json.EncodeError:
pass
try:
return o.tojson()
except AttributeError as e:
pass
t = type(o)
if isinstance(o, list):
return '[%s]' % ', '.join([tojson(e) for e in ... |
namedtuple with default values named ( typename fields | * fields default = x [ ** defaults ] ): param typename:: param fieldnames:: param defaults:: return: | def named(typename, *fieldnames, **defaults):
"""
namedtuple with default values
named('typename', fields | *fields, default=x, [**defaults])
:param typename:
:param fieldnames:
:param defaults:
:return:
"""
if len(fieldnames) == 1:
if isinstance(fieldnames[0], str):
... |
numpy random seed context: param seed:: return: | def np_seed(seed):
"""
numpy random seed context
:param seed:
:return:
"""
if seed is not None:
state = np.random.get_state()
np.random.seed(seed)
yield
np.random.set_state(state)
else:
yield |
Create and connect to socket for TCP communication with hub. | def connect(self):
"""Create and connect to socket for TCP communication with hub."""
try:
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.settimeout(TIMEOUT_SECONDS)
self._socket.connect((self._ip, self._port))
_LOGGER.debug(... |
Send TCP command to hub and return response. | def send_command(self, command):
"""Send TCP command to hub and return response."""
# use lock to make TCP send/receive thread safe
with self._lock:
try:
self._socket.send(command.encode("utf8"))
result = self.receive()
# hub may send "... |
Receive TCP response looping to get whole thing or timeout. | def receive(self):
"""Receive TCP response, looping to get whole thing or timeout."""
try:
buffer = self._socket.recv(BUFFER_SIZE)
except socket.timeout as error:
# Something is wrong, assume it's offline temporarily
_LOGGER.error("Error receiving: %s", error)... |
Get current light data as dictionary with light zids as keys. | def get_data(self):
"""Get current light data as dictionary with light zids as keys."""
response = self.send_command(GET_LIGHTS_COMMAND)
_LOGGER.debug("get_data response: %s", repr(response))
if not response:
_LOGGER.debug("Empty response: %s", response)
return {}... |
Get current light data set and return as list of Bulb objects. | def get_lights(self):
"""Get current light data, set and return as list of Bulb objects."""
# Throttle updates. Use cached data if within UPDATE_INTERVAL_SECONDS
now = datetime.datetime.now()
if (now - self._last_updated) < datetime.timedelta(
seconds=UPDATE_INTERVAL_SECO... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.