repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
pydata/numexpr | numexpr/necompiler.py | setRegisterNumbersForTemporaries | def setRegisterNumbersForTemporaries(ast, start):
"""Assign register numbers for temporary registers, keeping track of
aliases and handling immediate operands.
"""
seen = 0
signature = ''
aliases = []
for node in ast.postorderWalk():
if node.astType == 'alias':
aliases.append(node)
node = node.value
if node.reg.immediate:
node.reg.n = node.value
continue
reg = node.reg
if reg.n is None:
reg.n = start + seen
seen += 1
signature += reg.node.typecode()
for node in aliases:
node.reg = node.value.reg
return start + seen, signature | python | def setRegisterNumbersForTemporaries(ast, start):
"""Assign register numbers for temporary registers, keeping track of
aliases and handling immediate operands.
"""
seen = 0
signature = ''
aliases = []
for node in ast.postorderWalk():
if node.astType == 'alias':
aliases.append(node)
node = node.value
if node.reg.immediate:
node.reg.n = node.value
continue
reg = node.reg
if reg.n is None:
reg.n = start + seen
seen += 1
signature += reg.node.typecode()
for node in aliases:
node.reg = node.value.reg
return start + seen, signature | [
"def",
"setRegisterNumbersForTemporaries",
"(",
"ast",
",",
"start",
")",
":",
"seen",
"=",
"0",
"signature",
"=",
"''",
"aliases",
"=",
"[",
"]",
"for",
"node",
"in",
"ast",
".",
"postorderWalk",
"(",
")",
":",
"if",
"node",
".",
"astType",
"==",
"'al... | Assign register numbers for temporary registers, keeping track of
aliases and handling immediate operands. | [
"Assign",
"register",
"numbers",
"for",
"temporary",
"registers",
"keeping",
"track",
"of",
"aliases",
"and",
"handling",
"immediate",
"operands",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L450-L471 | train | 226,800 |
pydata/numexpr | numexpr/necompiler.py | convertASTtoThreeAddrForm | def convertASTtoThreeAddrForm(ast):
"""Convert an AST to a three address form.
Three address form is (op, reg1, reg2, reg3), where reg1 is the
destination of the result of the instruction.
I suppose this should be called three register form, but three
address form is found in compiler theory.
"""
return [(node.value, node.reg) + tuple([c.reg for c in node.children])
for node in ast.allOf('op')] | python | def convertASTtoThreeAddrForm(ast):
"""Convert an AST to a three address form.
Three address form is (op, reg1, reg2, reg3), where reg1 is the
destination of the result of the instruction.
I suppose this should be called three register form, but three
address form is found in compiler theory.
"""
return [(node.value, node.reg) + tuple([c.reg for c in node.children])
for node in ast.allOf('op')] | [
"def",
"convertASTtoThreeAddrForm",
"(",
"ast",
")",
":",
"return",
"[",
"(",
"node",
".",
"value",
",",
"node",
".",
"reg",
")",
"+",
"tuple",
"(",
"[",
"c",
".",
"reg",
"for",
"c",
"in",
"node",
".",
"children",
"]",
")",
"for",
"node",
"in",
"... | Convert an AST to a three address form.
Three address form is (op, reg1, reg2, reg3), where reg1 is the
destination of the result of the instruction.
I suppose this should be called three register form, but three
address form is found in compiler theory. | [
"Convert",
"an",
"AST",
"to",
"a",
"three",
"address",
"form",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L474-L484 | train | 226,801 |
pydata/numexpr | numexpr/necompiler.py | compileThreeAddrForm | def compileThreeAddrForm(program):
"""Given a three address form of the program, compile it a string that
the VM understands.
"""
def nToChr(reg):
if reg is None:
return b'\xff'
elif reg.n < 0:
raise ValueError("negative value for register number %s" % reg.n)
else:
if sys.version_info[0] < 3:
return chr(reg.n)
else:
# int.to_bytes is not available in Python < 3.2
#return reg.n.to_bytes(1, sys.byteorder)
return bytes([reg.n])
def quadrupleToString(opcode, store, a1=None, a2=None):
cop = chr(interpreter.opcodes[opcode]).encode('ascii')
cs = nToChr(store)
ca1 = nToChr(a1)
ca2 = nToChr(a2)
return cop + cs + ca1 + ca2
def toString(args):
while len(args) < 4:
args += (None,)
opcode, store, a1, a2 = args[:4]
s = quadrupleToString(opcode, store, a1, a2)
l = [s]
args = args[4:]
while args:
s = quadrupleToString(b'noop', *args[:3])
l.append(s)
args = args[3:]
return b''.join(l)
prog_str = b''.join([toString(t) for t in program])
return prog_str | python | def compileThreeAddrForm(program):
"""Given a three address form of the program, compile it a string that
the VM understands.
"""
def nToChr(reg):
if reg is None:
return b'\xff'
elif reg.n < 0:
raise ValueError("negative value for register number %s" % reg.n)
else:
if sys.version_info[0] < 3:
return chr(reg.n)
else:
# int.to_bytes is not available in Python < 3.2
#return reg.n.to_bytes(1, sys.byteorder)
return bytes([reg.n])
def quadrupleToString(opcode, store, a1=None, a2=None):
cop = chr(interpreter.opcodes[opcode]).encode('ascii')
cs = nToChr(store)
ca1 = nToChr(a1)
ca2 = nToChr(a2)
return cop + cs + ca1 + ca2
def toString(args):
while len(args) < 4:
args += (None,)
opcode, store, a1, a2 = args[:4]
s = quadrupleToString(opcode, store, a1, a2)
l = [s]
args = args[4:]
while args:
s = quadrupleToString(b'noop', *args[:3])
l.append(s)
args = args[3:]
return b''.join(l)
prog_str = b''.join([toString(t) for t in program])
return prog_str | [
"def",
"compileThreeAddrForm",
"(",
"program",
")",
":",
"def",
"nToChr",
"(",
"reg",
")",
":",
"if",
"reg",
"is",
"None",
":",
"return",
"b'\\xff'",
"elif",
"reg",
".",
"n",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"negative value for register number %s... | Given a three address form of the program, compile it a string that
the VM understands. | [
"Given",
"a",
"three",
"address",
"form",
"of",
"the",
"program",
"compile",
"it",
"a",
"string",
"that",
"the",
"VM",
"understands",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L487-L526 | train | 226,802 |
pydata/numexpr | numexpr/necompiler.py | precompile | def precompile(ex, signature=(), context={}):
"""Compile the expression to an intermediate form.
"""
types = dict(signature)
input_order = [name for (name, type_) in signature]
if isinstance(ex, (str, unicode)):
ex = stringToExpression(ex, types, context)
# the AST is like the expression, but the node objects don't have
# any odd interpretations
ast = expressionToAST(ex)
if ex.astType != 'op':
ast = ASTNode('op', value='copy', astKind=ex.astKind, children=(ast,))
ast = typeCompileAst(ast)
aliases = collapseDuplicateSubtrees(ast)
assignLeafRegisters(ast.allOf('raw'), Immediate)
assignLeafRegisters(ast.allOf('variable', 'constant'), Register)
assignBranchRegisters(ast.allOf('op'), Register)
# assign registers for aliases
for a in aliases:
a.reg = a.value.reg
input_order = getInputOrder(ast, input_order)
constants_order, constants = getConstants(ast)
if isReduction(ast):
ast.reg.temporary = False
optimizeTemporariesAllocation(ast)
ast.reg.temporary = False
r_output = 0
ast.reg.n = 0
r_inputs = r_output + 1
r_constants = setOrderedRegisterNumbers(input_order, r_inputs)
r_temps = setOrderedRegisterNumbers(constants_order, r_constants)
r_end, tempsig = setRegisterNumbersForTemporaries(ast, r_temps)
threeAddrProgram = convertASTtoThreeAddrForm(ast)
input_names = tuple([a.value for a in input_order])
signature = ''.join(type_to_typecode[types.get(x, default_type)]
for x in input_names)
return threeAddrProgram, signature, tempsig, constants, input_names | python | def precompile(ex, signature=(), context={}):
"""Compile the expression to an intermediate form.
"""
types = dict(signature)
input_order = [name for (name, type_) in signature]
if isinstance(ex, (str, unicode)):
ex = stringToExpression(ex, types, context)
# the AST is like the expression, but the node objects don't have
# any odd interpretations
ast = expressionToAST(ex)
if ex.astType != 'op':
ast = ASTNode('op', value='copy', astKind=ex.astKind, children=(ast,))
ast = typeCompileAst(ast)
aliases = collapseDuplicateSubtrees(ast)
assignLeafRegisters(ast.allOf('raw'), Immediate)
assignLeafRegisters(ast.allOf('variable', 'constant'), Register)
assignBranchRegisters(ast.allOf('op'), Register)
# assign registers for aliases
for a in aliases:
a.reg = a.value.reg
input_order = getInputOrder(ast, input_order)
constants_order, constants = getConstants(ast)
if isReduction(ast):
ast.reg.temporary = False
optimizeTemporariesAllocation(ast)
ast.reg.temporary = False
r_output = 0
ast.reg.n = 0
r_inputs = r_output + 1
r_constants = setOrderedRegisterNumbers(input_order, r_inputs)
r_temps = setOrderedRegisterNumbers(constants_order, r_constants)
r_end, tempsig = setRegisterNumbersForTemporaries(ast, r_temps)
threeAddrProgram = convertASTtoThreeAddrForm(ast)
input_names = tuple([a.value for a in input_order])
signature = ''.join(type_to_typecode[types.get(x, default_type)]
for x in input_names)
return threeAddrProgram, signature, tempsig, constants, input_names | [
"def",
"precompile",
"(",
"ex",
",",
"signature",
"=",
"(",
")",
",",
"context",
"=",
"{",
"}",
")",
":",
"types",
"=",
"dict",
"(",
"signature",
")",
"input_order",
"=",
"[",
"name",
"for",
"(",
"name",
",",
"type_",
")",
"in",
"signature",
"]",
... | Compile the expression to an intermediate form. | [
"Compile",
"the",
"expression",
"to",
"an",
"intermediate",
"form",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L554-L604 | train | 226,803 |
pydata/numexpr | numexpr/necompiler.py | disassemble | def disassemble(nex):
"""
Given a NumExpr object, return a list which is the program disassembled.
"""
rev_opcodes = {}
for op in interpreter.opcodes:
rev_opcodes[interpreter.opcodes[op]] = op
r_constants = 1 + len(nex.signature)
r_temps = r_constants + len(nex.constants)
def getArg(pc, offset):
if sys.version_info[0] < 3:
arg = ord(nex.program[pc + offset])
op = rev_opcodes.get(ord(nex.program[pc]))
else:
arg = nex.program[pc + offset]
op = rev_opcodes.get(nex.program[pc])
try:
code = op.split(b'_')[1][offset - 1]
except IndexError:
return None
if sys.version_info[0] > 2:
# int.to_bytes is not available in Python < 3.2
#code = code.to_bytes(1, sys.byteorder)
code = bytes([code])
if arg == 255:
return None
if code != b'n':
if arg == 0:
return b'r0'
elif arg < r_constants:
return ('r%d[%s]' % (arg, nex.input_names[arg - 1])).encode('ascii')
elif arg < r_temps:
return ('c%d[%s]' % (arg, nex.constants[arg - r_constants])).encode('ascii')
else:
return ('t%d' % (arg,)).encode('ascii')
else:
return arg
source = []
for pc in range(0, len(nex.program), 4):
if sys.version_info[0] < 3:
op = rev_opcodes.get(ord(nex.program[pc]))
else:
op = rev_opcodes.get(nex.program[pc])
dest = getArg(pc, 1)
arg1 = getArg(pc, 2)
arg2 = getArg(pc, 3)
source.append((op, dest, arg1, arg2))
return source | python | def disassemble(nex):
"""
Given a NumExpr object, return a list which is the program disassembled.
"""
rev_opcodes = {}
for op in interpreter.opcodes:
rev_opcodes[interpreter.opcodes[op]] = op
r_constants = 1 + len(nex.signature)
r_temps = r_constants + len(nex.constants)
def getArg(pc, offset):
if sys.version_info[0] < 3:
arg = ord(nex.program[pc + offset])
op = rev_opcodes.get(ord(nex.program[pc]))
else:
arg = nex.program[pc + offset]
op = rev_opcodes.get(nex.program[pc])
try:
code = op.split(b'_')[1][offset - 1]
except IndexError:
return None
if sys.version_info[0] > 2:
# int.to_bytes is not available in Python < 3.2
#code = code.to_bytes(1, sys.byteorder)
code = bytes([code])
if arg == 255:
return None
if code != b'n':
if arg == 0:
return b'r0'
elif arg < r_constants:
return ('r%d[%s]' % (arg, nex.input_names[arg - 1])).encode('ascii')
elif arg < r_temps:
return ('c%d[%s]' % (arg, nex.constants[arg - r_constants])).encode('ascii')
else:
return ('t%d' % (arg,)).encode('ascii')
else:
return arg
source = []
for pc in range(0, len(nex.program), 4):
if sys.version_info[0] < 3:
op = rev_opcodes.get(ord(nex.program[pc]))
else:
op = rev_opcodes.get(nex.program[pc])
dest = getArg(pc, 1)
arg1 = getArg(pc, 2)
arg2 = getArg(pc, 3)
source.append((op, dest, arg1, arg2))
return source | [
"def",
"disassemble",
"(",
"nex",
")",
":",
"rev_opcodes",
"=",
"{",
"}",
"for",
"op",
"in",
"interpreter",
".",
"opcodes",
":",
"rev_opcodes",
"[",
"interpreter",
".",
"opcodes",
"[",
"op",
"]",
"]",
"=",
"op",
"r_constants",
"=",
"1",
"+",
"len",
"... | Given a NumExpr object, return a list which is the program disassembled. | [
"Given",
"a",
"NumExpr",
"object",
"return",
"a",
"list",
"which",
"is",
"the",
"program",
"disassembled",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L633-L682 | train | 226,804 |
pydata/numexpr | numexpr/necompiler.py | getArguments | def getArguments(names, local_dict=None, global_dict=None):
"""Get the arguments based on the names."""
call_frame = sys._getframe(2)
clear_local_dict = False
if local_dict is None:
local_dict = call_frame.f_locals
clear_local_dict = True
try:
frame_globals = call_frame.f_globals
if global_dict is None:
global_dict = frame_globals
# If `call_frame` is the top frame of the interpreter we can't clear its
# `local_dict`, because it is actually the `global_dict`.
clear_local_dict = clear_local_dict and not frame_globals is local_dict
arguments = []
for name in names:
try:
a = local_dict[name]
except KeyError:
a = global_dict[name]
arguments.append(numpy.asarray(a))
finally:
# If we generated local_dict via an explicit reference to f_locals,
# clear the dict to prevent creating extra ref counts in the caller's scope
# See https://github.com/pydata/numexpr/issues/310
if clear_local_dict:
local_dict.clear()
return arguments | python | def getArguments(names, local_dict=None, global_dict=None):
"""Get the arguments based on the names."""
call_frame = sys._getframe(2)
clear_local_dict = False
if local_dict is None:
local_dict = call_frame.f_locals
clear_local_dict = True
try:
frame_globals = call_frame.f_globals
if global_dict is None:
global_dict = frame_globals
# If `call_frame` is the top frame of the interpreter we can't clear its
# `local_dict`, because it is actually the `global_dict`.
clear_local_dict = clear_local_dict and not frame_globals is local_dict
arguments = []
for name in names:
try:
a = local_dict[name]
except KeyError:
a = global_dict[name]
arguments.append(numpy.asarray(a))
finally:
# If we generated local_dict via an explicit reference to f_locals,
# clear the dict to prevent creating extra ref counts in the caller's scope
# See https://github.com/pydata/numexpr/issues/310
if clear_local_dict:
local_dict.clear()
return arguments | [
"def",
"getArguments",
"(",
"names",
",",
"local_dict",
"=",
"None",
",",
"global_dict",
"=",
"None",
")",
":",
"call_frame",
"=",
"sys",
".",
"_getframe",
"(",
"2",
")",
"clear_local_dict",
"=",
"False",
"if",
"local_dict",
"is",
"None",
":",
"local_dict"... | Get the arguments based on the names. | [
"Get",
"the",
"arguments",
"based",
"on",
"the",
"names",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L724-L755 | train | 226,805 |
pydata/numexpr | numexpr/necompiler.py | evaluate | def evaluate(ex, local_dict=None, global_dict=None,
out=None, order='K', casting='safe', **kwargs):
"""Evaluate a simple array expression element-wise, using the new iterator.
ex is a string forming an expression, like "2*a+3*b". The values for "a"
and "b" will by default be taken from the calling function's frame
(through use of sys._getframe()). Alternatively, they can be specifed
using the 'local_dict' or 'global_dict' arguments.
Parameters
----------
local_dict : dictionary, optional
A dictionary that replaces the local operands in current frame.
global_dict : dictionary, optional
A dictionary that replaces the global operands in current frame.
out : NumPy array, optional
An existing array where the outcome is going to be stored. Care is
required so that this array has the same shape and type than the
actual outcome of the computation. Useful for avoiding unnecessary
new array allocations.
order : {'C', 'F', 'A', or 'K'}, optional
Controls the iteration order for operands. 'C' means C order, 'F'
means Fortran order, 'A' means 'F' order if all the arrays are
Fortran contiguous, 'C' order otherwise, and 'K' means as close to
the order the array elements appear in memory as possible. For
efficient computations, typically 'K'eep order (the default) is
desired.
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur when making a copy or
buffering. Setting this to 'unsafe' is not recommended, as it can
adversely affect accumulations.
* 'no' means the data types should not be cast at all.
* 'equiv' means only byte-order changes are allowed.
* 'safe' means only casts which can preserve values are allowed.
* 'same_kind' means only safe casts or casts within a kind,
like float64 to float32, are allowed.
* 'unsafe' means any data conversions may be done.
"""
global _numexpr_last
if not isinstance(ex, (str, unicode)):
raise ValueError("must specify expression as a string")
# Get the names for this expression
context = getContext(kwargs, frame_depth=1)
expr_key = (ex, tuple(sorted(context.items())))
if expr_key not in _names_cache:
_names_cache[expr_key] = getExprNames(ex, context)
names, ex_uses_vml = _names_cache[expr_key]
arguments = getArguments(names, local_dict, global_dict)
# Create a signature
signature = [(name, getType(arg)) for (name, arg) in
zip(names, arguments)]
# Look up numexpr if possible.
numexpr_key = expr_key + (tuple(signature),)
try:
compiled_ex = _numexpr_cache[numexpr_key]
except KeyError:
compiled_ex = _numexpr_cache[numexpr_key] = NumExpr(ex, signature, **context)
kwargs = {'out': out, 'order': order, 'casting': casting,
'ex_uses_vml': ex_uses_vml}
_numexpr_last = dict(ex=compiled_ex, argnames=names, kwargs=kwargs)
with evaluate_lock:
return compiled_ex(*arguments, **kwargs) | python | def evaluate(ex, local_dict=None, global_dict=None,
out=None, order='K', casting='safe', **kwargs):
"""Evaluate a simple array expression element-wise, using the new iterator.
ex is a string forming an expression, like "2*a+3*b". The values for "a"
and "b" will by default be taken from the calling function's frame
(through use of sys._getframe()). Alternatively, they can be specifed
using the 'local_dict' or 'global_dict' arguments.
Parameters
----------
local_dict : dictionary, optional
A dictionary that replaces the local operands in current frame.
global_dict : dictionary, optional
A dictionary that replaces the global operands in current frame.
out : NumPy array, optional
An existing array where the outcome is going to be stored. Care is
required so that this array has the same shape and type than the
actual outcome of the computation. Useful for avoiding unnecessary
new array allocations.
order : {'C', 'F', 'A', or 'K'}, optional
Controls the iteration order for operands. 'C' means C order, 'F'
means Fortran order, 'A' means 'F' order if all the arrays are
Fortran contiguous, 'C' order otherwise, and 'K' means as close to
the order the array elements appear in memory as possible. For
efficient computations, typically 'K'eep order (the default) is
desired.
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur when making a copy or
buffering. Setting this to 'unsafe' is not recommended, as it can
adversely affect accumulations.
* 'no' means the data types should not be cast at all.
* 'equiv' means only byte-order changes are allowed.
* 'safe' means only casts which can preserve values are allowed.
* 'same_kind' means only safe casts or casts within a kind,
like float64 to float32, are allowed.
* 'unsafe' means any data conversions may be done.
"""
global _numexpr_last
if not isinstance(ex, (str, unicode)):
raise ValueError("must specify expression as a string")
# Get the names for this expression
context = getContext(kwargs, frame_depth=1)
expr_key = (ex, tuple(sorted(context.items())))
if expr_key not in _names_cache:
_names_cache[expr_key] = getExprNames(ex, context)
names, ex_uses_vml = _names_cache[expr_key]
arguments = getArguments(names, local_dict, global_dict)
# Create a signature
signature = [(name, getType(arg)) for (name, arg) in
zip(names, arguments)]
# Look up numexpr if possible.
numexpr_key = expr_key + (tuple(signature),)
try:
compiled_ex = _numexpr_cache[numexpr_key]
except KeyError:
compiled_ex = _numexpr_cache[numexpr_key] = NumExpr(ex, signature, **context)
kwargs = {'out': out, 'order': order, 'casting': casting,
'ex_uses_vml': ex_uses_vml}
_numexpr_last = dict(ex=compiled_ex, argnames=names, kwargs=kwargs)
with evaluate_lock:
return compiled_ex(*arguments, **kwargs) | [
"def",
"evaluate",
"(",
"ex",
",",
"local_dict",
"=",
"None",
",",
"global_dict",
"=",
"None",
",",
"out",
"=",
"None",
",",
"order",
"=",
"'K'",
",",
"casting",
"=",
"'safe'",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"_numexpr_last",
"if",
"not"... | Evaluate a simple array expression element-wise, using the new iterator.
ex is a string forming an expression, like "2*a+3*b". The values for "a"
and "b" will by default be taken from the calling function's frame
(through use of sys._getframe()). Alternatively, they can be specifed
using the 'local_dict' or 'global_dict' arguments.
Parameters
----------
local_dict : dictionary, optional
A dictionary that replaces the local operands in current frame.
global_dict : dictionary, optional
A dictionary that replaces the global operands in current frame.
out : NumPy array, optional
An existing array where the outcome is going to be stored. Care is
required so that this array has the same shape and type than the
actual outcome of the computation. Useful for avoiding unnecessary
new array allocations.
order : {'C', 'F', 'A', or 'K'}, optional
Controls the iteration order for operands. 'C' means C order, 'F'
means Fortran order, 'A' means 'F' order if all the arrays are
Fortran contiguous, 'C' order otherwise, and 'K' means as close to
the order the array elements appear in memory as possible. For
efficient computations, typically 'K'eep order (the default) is
desired.
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur when making a copy or
buffering. Setting this to 'unsafe' is not recommended, as it can
adversely affect accumulations.
* 'no' means the data types should not be cast at all.
* 'equiv' means only byte-order changes are allowed.
* 'safe' means only casts which can preserve values are allowed.
* 'same_kind' means only safe casts or casts within a kind,
like float64 to float32, are allowed.
* 'unsafe' means any data conversions may be done. | [
"Evaluate",
"a",
"simple",
"array",
"expression",
"element",
"-",
"wise",
"using",
"the",
"new",
"iterator",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L765-L834 | train | 226,806 |
pydata/numexpr | numexpr/necompiler.py | re_evaluate | def re_evaluate(local_dict=None):
"""Re-evaluate the previous executed array expression without any check.
This is meant for accelerating loops that are re-evaluating the same
expression repeatedly without changing anything else than the operands.
If unsure, use evaluate() which is safer.
Parameters
----------
local_dict : dictionary, optional
A dictionary that replaces the local operands in current frame.
"""
try:
compiled_ex = _numexpr_last['ex']
except KeyError:
raise RuntimeError("not a previous evaluate() execution found")
argnames = _numexpr_last['argnames']
args = getArguments(argnames, local_dict)
kwargs = _numexpr_last['kwargs']
with evaluate_lock:
return compiled_ex(*args, **kwargs) | python | def re_evaluate(local_dict=None):
"""Re-evaluate the previous executed array expression without any check.
This is meant for accelerating loops that are re-evaluating the same
expression repeatedly without changing anything else than the operands.
If unsure, use evaluate() which is safer.
Parameters
----------
local_dict : dictionary, optional
A dictionary that replaces the local operands in current frame.
"""
try:
compiled_ex = _numexpr_last['ex']
except KeyError:
raise RuntimeError("not a previous evaluate() execution found")
argnames = _numexpr_last['argnames']
args = getArguments(argnames, local_dict)
kwargs = _numexpr_last['kwargs']
with evaluate_lock:
return compiled_ex(*args, **kwargs) | [
"def",
"re_evaluate",
"(",
"local_dict",
"=",
"None",
")",
":",
"try",
":",
"compiled_ex",
"=",
"_numexpr_last",
"[",
"'ex'",
"]",
"except",
"KeyError",
":",
"raise",
"RuntimeError",
"(",
"\"not a previous evaluate() execution found\"",
")",
"argnames",
"=",
"_num... | Re-evaluate the previous executed array expression without any check.
This is meant for accelerating loops that are re-evaluating the same
expression repeatedly without changing anything else than the operands.
If unsure, use evaluate() which is safer.
Parameters
----------
local_dict : dictionary, optional
A dictionary that replaces the local operands in current frame. | [
"Re",
"-",
"evaluate",
"the",
"previous",
"executed",
"array",
"expression",
"without",
"any",
"check",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L837-L859 | train | 226,807 |
pydata/numexpr | bench/poly.py | compute | def compute():
"""Compute the polynomial."""
if what == "numpy":
y = eval(expr)
else:
y = ne.evaluate(expr)
return len(y) | python | def compute():
"""Compute the polynomial."""
if what == "numpy":
y = eval(expr)
else:
y = ne.evaluate(expr)
return len(y) | [
"def",
"compute",
"(",
")",
":",
"if",
"what",
"==",
"\"numpy\"",
":",
"y",
"=",
"eval",
"(",
"expr",
")",
"else",
":",
"y",
"=",
"ne",
".",
"evaluate",
"(",
"expr",
")",
"return",
"len",
"(",
"y",
")"
] | Compute the polynomial. | [
"Compute",
"the",
"polynomial",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/bench/poly.py#L34-L40 | train | 226,808 |
MaxHalford/prince | prince/mfa.py | MFA.partial_row_coordinates | def partial_row_coordinates(self, X):
"""Returns the row coordinates for each group."""
utils.validation.check_is_fitted(self, 's_')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
# Define the projection matrix P
P = len(X) ** 0.5 * self.U_ / self.s_
# Get the projections for each group
coords = {}
for name, cols in sorted(self.groups.items()):
X_partial = X.loc[:, cols]
if not self.all_nums_[name]:
X_partial = self.cat_one_hots_[name].transform(X_partial)
Z_partial = X_partial / self.partial_factor_analysis_[name].s_[0]
coords[name] = len(self.groups) * (Z_partial @ Z_partial.T) @ P
# Convert coords to a MultiIndex DataFrame
coords = pd.DataFrame({
(name, i): group_coords.loc[:, i]
for name, group_coords in coords.items()
for i in range(group_coords.shape[1])
})
return coords | python | def partial_row_coordinates(self, X):
"""Returns the row coordinates for each group."""
utils.validation.check_is_fitted(self, 's_')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
# Define the projection matrix P
P = len(X) ** 0.5 * self.U_ / self.s_
# Get the projections for each group
coords = {}
for name, cols in sorted(self.groups.items()):
X_partial = X.loc[:, cols]
if not self.all_nums_[name]:
X_partial = self.cat_one_hots_[name].transform(X_partial)
Z_partial = X_partial / self.partial_factor_analysis_[name].s_[0]
coords[name] = len(self.groups) * (Z_partial @ Z_partial.T) @ P
# Convert coords to a MultiIndex DataFrame
coords = pd.DataFrame({
(name, i): group_coords.loc[:, i]
for name, group_coords in coords.items()
for i in range(group_coords.shape[1])
})
return coords | [
"def",
"partial_row_coordinates",
"(",
"self",
",",
"X",
")",
":",
"utils",
".",
"validation",
".",
"check_is_fitted",
"(",
"self",
",",
"'s_'",
")",
"# Check input",
"if",
"self",
".",
"check_input",
":",
"utils",
".",
"check_array",
"(",
"X",
",",
"dtype... | Returns the row coordinates for each group. | [
"Returns",
"the",
"row",
"coordinates",
"for",
"each",
"group",
"."
] | 714c9cdfc4d9f8823eabf550a23ad01fe87c50d7 | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/mfa.py#L158-L190 | train | 226,809 |
MaxHalford/prince | prince/mfa.py | MFA.column_correlations | def column_correlations(self, X):
"""Returns the column correlations."""
utils.validation.check_is_fitted(self, 's_')
X_global = self._build_X_global(X)
row_pc = self._row_coordinates_from_global(X_global)
return pd.DataFrame({
component: {
feature: row_pc[component].corr(X_global[feature].to_dense())
for feature in X_global.columns
}
for component in row_pc.columns
}) | python | def column_correlations(self, X):
"""Returns the column correlations."""
utils.validation.check_is_fitted(self, 's_')
X_global = self._build_X_global(X)
row_pc = self._row_coordinates_from_global(X_global)
return pd.DataFrame({
component: {
feature: row_pc[component].corr(X_global[feature].to_dense())
for feature in X_global.columns
}
for component in row_pc.columns
}) | [
"def",
"column_correlations",
"(",
"self",
",",
"X",
")",
":",
"utils",
".",
"validation",
".",
"check_is_fitted",
"(",
"self",
",",
"'s_'",
")",
"X_global",
"=",
"self",
".",
"_build_X_global",
"(",
"X",
")",
"row_pc",
"=",
"self",
".",
"_row_coordinates_... | Returns the column correlations. | [
"Returns",
"the",
"column",
"correlations",
"."
] | 714c9cdfc4d9f8823eabf550a23ad01fe87c50d7 | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/mfa.py#L192-L205 | train | 226,810 |
MaxHalford/prince | prince/ca.py | CA.eigenvalues_ | def eigenvalues_(self):
"""The eigenvalues associated with each principal component."""
utils.validation.check_is_fitted(self, 's_')
return np.square(self.s_).tolist() | python | def eigenvalues_(self):
"""The eigenvalues associated with each principal component."""
utils.validation.check_is_fitted(self, 's_')
return np.square(self.s_).tolist() | [
"def",
"eigenvalues_",
"(",
"self",
")",
":",
"utils",
".",
"validation",
".",
"check_is_fitted",
"(",
"self",
",",
"'s_'",
")",
"return",
"np",
".",
"square",
"(",
"self",
".",
"s_",
")",
".",
"tolist",
"(",
")"
] | The eigenvalues associated with each principal component. | [
"The",
"eigenvalues",
"associated",
"with",
"each",
"principal",
"component",
"."
] | 714c9cdfc4d9f8823eabf550a23ad01fe87c50d7 | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/ca.py#L82-L85 | train | 226,811 |
MaxHalford/prince | prince/ca.py | CA.explained_inertia_ | def explained_inertia_(self):
"""The percentage of explained inertia per principal component."""
utils.validation.check_is_fitted(self, 'total_inertia_')
return [eig / self.total_inertia_ for eig in self.eigenvalues_] | python | def explained_inertia_(self):
"""The percentage of explained inertia per principal component."""
utils.validation.check_is_fitted(self, 'total_inertia_')
return [eig / self.total_inertia_ for eig in self.eigenvalues_] | [
"def",
"explained_inertia_",
"(",
"self",
")",
":",
"utils",
".",
"validation",
".",
"check_is_fitted",
"(",
"self",
",",
"'total_inertia_'",
")",
"return",
"[",
"eig",
"/",
"self",
".",
"total_inertia_",
"for",
"eig",
"in",
"self",
".",
"eigenvalues_",
"]"
... | The percentage of explained inertia per principal component. | [
"The",
"percentage",
"of",
"explained",
"inertia",
"per",
"principal",
"component",
"."
] | 714c9cdfc4d9f8823eabf550a23ad01fe87c50d7 | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/ca.py#L88-L91 | train | 226,812 |
MaxHalford/prince | prince/ca.py | CA.row_coordinates | def row_coordinates(self, X):
"""The row principal coordinates."""
utils.validation.check_is_fitted(self, 'V_')
_, row_names, _, _ = util.make_labels_and_names(X)
if isinstance(X, pd.SparseDataFrame):
X = X.to_coo().astype(float)
elif isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = X.copy()
# Normalise the rows so that they sum up to 1
if isinstance(X, np.ndarray):
X = X / X.sum(axis=1)[:, None]
else:
X = X / X.sum(axis=1)
return pd.DataFrame(
data=X @ sparse.diags(self.col_masses_.to_numpy() ** -0.5) @ self.V_.T,
index=row_names
) | python | def row_coordinates(self, X):
"""The row principal coordinates."""
utils.validation.check_is_fitted(self, 'V_')
_, row_names, _, _ = util.make_labels_and_names(X)
if isinstance(X, pd.SparseDataFrame):
X = X.to_coo().astype(float)
elif isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = X.copy()
# Normalise the rows so that they sum up to 1
if isinstance(X, np.ndarray):
X = X / X.sum(axis=1)[:, None]
else:
X = X / X.sum(axis=1)
return pd.DataFrame(
data=X @ sparse.diags(self.col_masses_.to_numpy() ** -0.5) @ self.V_.T,
index=row_names
) | [
"def",
"row_coordinates",
"(",
"self",
",",
"X",
")",
":",
"utils",
".",
"validation",
".",
"check_is_fitted",
"(",
"self",
",",
"'V_'",
")",
"_",
",",
"row_names",
",",
"_",
",",
"_",
"=",
"util",
".",
"make_labels_and_names",
"(",
"X",
")",
"if",
"... | The row principal coordinates. | [
"The",
"row",
"principal",
"coordinates",
"."
] | 714c9cdfc4d9f8823eabf550a23ad01fe87c50d7 | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/ca.py#L93-L116 | train | 226,813 |
MaxHalford/prince | prince/ca.py | CA.column_coordinates | def column_coordinates(self, X):
"""The column principal coordinates."""
utils.validation.check_is_fitted(self, 'V_')
_, _, _, col_names = util.make_labels_and_names(X)
if isinstance(X, pd.SparseDataFrame):
X = X.to_coo()
elif isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = X.copy()
# Transpose and make sure the rows sum up to 1
if isinstance(X, np.ndarray):
X = X.T / X.T.sum(axis=1)[:, None]
else:
X = X.T / X.T.sum(axis=1)
return pd.DataFrame(
data=X @ sparse.diags(self.row_masses_.to_numpy() ** -0.5) @ self.U_,
index=col_names
) | python | def column_coordinates(self, X):
"""The column principal coordinates."""
utils.validation.check_is_fitted(self, 'V_')
_, _, _, col_names = util.make_labels_and_names(X)
if isinstance(X, pd.SparseDataFrame):
X = X.to_coo()
elif isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = X.copy()
# Transpose and make sure the rows sum up to 1
if isinstance(X, np.ndarray):
X = X.T / X.T.sum(axis=1)[:, None]
else:
X = X.T / X.T.sum(axis=1)
return pd.DataFrame(
data=X @ sparse.diags(self.row_masses_.to_numpy() ** -0.5) @ self.U_,
index=col_names
) | [
"def",
"column_coordinates",
"(",
"self",
",",
"X",
")",
":",
"utils",
".",
"validation",
".",
"check_is_fitted",
"(",
"self",
",",
"'V_'",
")",
"_",
",",
"_",
",",
"_",
",",
"col_names",
"=",
"util",
".",
"make_labels_and_names",
"(",
"X",
")",
"if",
... | The column principal coordinates. | [
"The",
"column",
"principal",
"coordinates",
"."
] | 714c9cdfc4d9f8823eabf550a23ad01fe87c50d7 | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/ca.py#L118-L141 | train | 226,814 |
MaxHalford/prince | prince/ca.py | CA.plot_coordinates | def plot_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
show_row_labels=True, show_col_labels=True, **kwargs):
"""Plot the principal coordinates."""
utils.validation.check_is_fitted(self, 's_')
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
# Add style
ax = plot.stylize_axis(ax)
# Get labels and names
row_label, row_names, col_label, col_names = util.make_labels_and_names(X)
# Plot row principal coordinates
row_coords = self.row_coordinates(X)
ax.scatter(
row_coords[x_component],
row_coords[y_component],
**kwargs,
label=row_label
)
# Plot column principal coordinates
col_coords = self.column_coordinates(X)
ax.scatter(
col_coords[x_component],
col_coords[y_component],
**kwargs,
label=col_label
)
# Add row labels
if show_row_labels:
x = row_coords[x_component]
y = row_coords[y_component]
for i, label in enumerate(row_names):
ax.annotate(label, (x[i], y[i]))
# Add column labels
if show_col_labels:
x = col_coords[x_component]
y = col_coords[y_component]
for i, label in enumerate(col_names):
ax.annotate(label, (x[i], y[i]))
# Legend
ax.legend()
# Text
ax.set_title('Principal coordinates')
ei = self.explained_inertia_
ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component]))
ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component]))
return ax | python | def plot_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
show_row_labels=True, show_col_labels=True, **kwargs):
"""Plot the principal coordinates."""
utils.validation.check_is_fitted(self, 's_')
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
# Add style
ax = plot.stylize_axis(ax)
# Get labels and names
row_label, row_names, col_label, col_names = util.make_labels_and_names(X)
# Plot row principal coordinates
row_coords = self.row_coordinates(X)
ax.scatter(
row_coords[x_component],
row_coords[y_component],
**kwargs,
label=row_label
)
# Plot column principal coordinates
col_coords = self.column_coordinates(X)
ax.scatter(
col_coords[x_component],
col_coords[y_component],
**kwargs,
label=col_label
)
# Add row labels
if show_row_labels:
x = row_coords[x_component]
y = row_coords[y_component]
for i, label in enumerate(row_names):
ax.annotate(label, (x[i], y[i]))
# Add column labels
if show_col_labels:
x = col_coords[x_component]
y = col_coords[y_component]
for i, label in enumerate(col_names):
ax.annotate(label, (x[i], y[i]))
# Legend
ax.legend()
# Text
ax.set_title('Principal coordinates')
ei = self.explained_inertia_
ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component]))
ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component]))
return ax | [
"def",
"plot_coordinates",
"(",
"self",
",",
"X",
",",
"ax",
"=",
"None",
",",
"figsize",
"=",
"(",
"6",
",",
"6",
")",
",",
"x_component",
"=",
"0",
",",
"y_component",
"=",
"1",
",",
"show_row_labels",
"=",
"True",
",",
"show_col_labels",
"=",
"Tru... | Plot the principal coordinates. | [
"Plot",
"the",
"principal",
"coordinates",
"."
] | 714c9cdfc4d9f8823eabf550a23ad01fe87c50d7 | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/ca.py#L143-L199 | train | 226,815 |
MaxHalford/prince | prince/mca.py | MCA.plot_coordinates | def plot_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
show_row_points=True, row_points_size=10, show_row_labels=False,
show_column_points=True, column_points_size=30,
show_column_labels=False, legend_n_cols=1):
"""Plot row and column principal coordinates.
Args:
ax (matplotlib.Axis): A fresh one will be created and returned if not provided.
figsize ((float, float)): The desired figure size if `ax` is not provided.
x_component (int): Number of the component used for the x-axis.
y_component (int): Number of the component used for the y-axis.
show_row_points (bool): Whether to show row principal components or not.
row_points_size (float): Row principal components point size.
show_row_labels (bool): Whether to show row labels or not.
show_column_points (bool): Whether to show column principal components or not.
column_points_size (float): Column principal components point size.
show_column_labels (bool): Whether to show column labels or not.
legend_n_cols (int): Number of columns used for the legend.
Returns:
matplotlib.Axis
"""
utils.validation.check_is_fitted(self, 'total_inertia_')
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
# Add style
ax = plot.stylize_axis(ax)
# Plot row principal coordinates
if show_row_points or show_row_labels:
row_coords = self.row_coordinates(X)
if show_row_points:
ax.scatter(
row_coords.iloc[:, x_component],
row_coords.iloc[:, y_component],
s=row_points_size,
label=None,
color=plot.GRAY['dark'],
alpha=0.6
)
if show_row_labels:
for _, row in row_coords.iterrows():
ax.annotate(row.name, (row[x_component], row[y_component]))
# Plot column principal coordinates
if show_column_points or show_column_labels:
col_coords = self.column_coordinates(X)
x = col_coords[x_component]
y = col_coords[y_component]
prefixes = col_coords.index.str.split('_').map(lambda x: x[0])
for prefix in prefixes.unique():
mask = prefixes == prefix
if show_column_points:
ax.scatter(x[mask], y[mask], s=column_points_size, label=prefix)
if show_column_labels:
for i, label in enumerate(col_coords[mask].index):
ax.annotate(label, (x[mask][i], y[mask][i]))
ax.legend(ncol=legend_n_cols)
# Text
ax.set_title('Row and column principal coordinates')
ei = self.explained_inertia_
ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component]))
ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component]))
return ax | python | def plot_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
show_row_points=True, row_points_size=10, show_row_labels=False,
show_column_points=True, column_points_size=30,
show_column_labels=False, legend_n_cols=1):
"""Plot row and column principal coordinates.
Args:
ax (matplotlib.Axis): A fresh one will be created and returned if not provided.
figsize ((float, float)): The desired figure size if `ax` is not provided.
x_component (int): Number of the component used for the x-axis.
y_component (int): Number of the component used for the y-axis.
show_row_points (bool): Whether to show row principal components or not.
row_points_size (float): Row principal components point size.
show_row_labels (bool): Whether to show row labels or not.
show_column_points (bool): Whether to show column principal components or not.
column_points_size (float): Column principal components point size.
show_column_labels (bool): Whether to show column labels or not.
legend_n_cols (int): Number of columns used for the legend.
Returns:
matplotlib.Axis
"""
utils.validation.check_is_fitted(self, 'total_inertia_')
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
# Add style
ax = plot.stylize_axis(ax)
# Plot row principal coordinates
if show_row_points or show_row_labels:
row_coords = self.row_coordinates(X)
if show_row_points:
ax.scatter(
row_coords.iloc[:, x_component],
row_coords.iloc[:, y_component],
s=row_points_size,
label=None,
color=plot.GRAY['dark'],
alpha=0.6
)
if show_row_labels:
for _, row in row_coords.iterrows():
ax.annotate(row.name, (row[x_component], row[y_component]))
# Plot column principal coordinates
if show_column_points or show_column_labels:
col_coords = self.column_coordinates(X)
x = col_coords[x_component]
y = col_coords[y_component]
prefixes = col_coords.index.str.split('_').map(lambda x: x[0])
for prefix in prefixes.unique():
mask = prefixes == prefix
if show_column_points:
ax.scatter(x[mask], y[mask], s=column_points_size, label=prefix)
if show_column_labels:
for i, label in enumerate(col_coords[mask].index):
ax.annotate(label, (x[mask][i], y[mask][i]))
ax.legend(ncol=legend_n_cols)
# Text
ax.set_title('Row and column principal coordinates')
ei = self.explained_inertia_
ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component]))
ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component]))
return ax | [
"def",
"plot_coordinates",
"(",
"self",
",",
"X",
",",
"ax",
"=",
"None",
",",
"figsize",
"=",
"(",
"6",
",",
"6",
")",
",",
"x_component",
"=",
"0",
",",
"y_component",
"=",
"1",
",",
"show_row_points",
"=",
"True",
",",
"row_points_size",
"=",
"10"... | Plot row and column principal coordinates.
Args:
ax (matplotlib.Axis): A fresh one will be created and returned if not provided.
figsize ((float, float)): The desired figure size if `ax` is not provided.
x_component (int): Number of the component used for the x-axis.
y_component (int): Number of the component used for the y-axis.
show_row_points (bool): Whether to show row principal components or not.
row_points_size (float): Row principal components point size.
show_row_labels (bool): Whether to show row labels or not.
show_column_points (bool): Whether to show column principal components or not.
column_points_size (float): Column principal components point size.
show_column_labels (bool): Whether to show column labels or not.
legend_n_cols (int): Number of columns used for the legend.
Returns:
matplotlib.Axis | [
"Plot",
"row",
"and",
"column",
"principal",
"coordinates",
"."
] | 714c9cdfc4d9f8823eabf550a23ad01fe87c50d7 | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/mca.py#L49-L126 | train | 226,816 |
MaxHalford/prince | prince/svd.py | compute_svd | def compute_svd(X, n_components, n_iter, random_state, engine):
"""Computes an SVD with k components."""
# Determine what SVD engine to use
if engine == 'auto':
engine = 'sklearn'
# Compute the SVD
if engine == 'fbpca':
if FBPCA_INSTALLED:
U, s, V = fbpca.pca(X, k=n_components, n_iter=n_iter)
else:
raise ValueError('fbpca is not installed; please install it if you want to use it')
elif engine == 'sklearn':
U, s, V = extmath.randomized_svd(
X,
n_components=n_components,
n_iter=n_iter,
random_state=random_state
)
else:
raise ValueError("engine has to be one of ('auto', 'fbpca', 'sklearn')")
U, V = extmath.svd_flip(U, V)
return U, s, V | python | def compute_svd(X, n_components, n_iter, random_state, engine):
"""Computes an SVD with k components."""
# Determine what SVD engine to use
if engine == 'auto':
engine = 'sklearn'
# Compute the SVD
if engine == 'fbpca':
if FBPCA_INSTALLED:
U, s, V = fbpca.pca(X, k=n_components, n_iter=n_iter)
else:
raise ValueError('fbpca is not installed; please install it if you want to use it')
elif engine == 'sklearn':
U, s, V = extmath.randomized_svd(
X,
n_components=n_components,
n_iter=n_iter,
random_state=random_state
)
else:
raise ValueError("engine has to be one of ('auto', 'fbpca', 'sklearn')")
U, V = extmath.svd_flip(U, V)
return U, s, V | [
"def",
"compute_svd",
"(",
"X",
",",
"n_components",
",",
"n_iter",
",",
"random_state",
",",
"engine",
")",
":",
"# Determine what SVD engine to use",
"if",
"engine",
"==",
"'auto'",
":",
"engine",
"=",
"'sklearn'",
"# Compute the SVD",
"if",
"engine",
"==",
"'... | Computes an SVD with k components. | [
"Computes",
"an",
"SVD",
"with",
"k",
"components",
"."
] | 714c9cdfc4d9f8823eabf550a23ad01fe87c50d7 | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/svd.py#L10-L35 | train | 226,817 |
MaxHalford/prince | prince/pca.py | PCA.row_standard_coordinates | def row_standard_coordinates(self, X):
"""Returns the row standard coordinates.
The row standard coordinates are obtained by dividing each row principal coordinate by it's
associated eigenvalue.
"""
utils.validation.check_is_fitted(self, 's_')
return self.row_coordinates(X).div(self.eigenvalues_, axis='columns') | python | def row_standard_coordinates(self, X):
"""Returns the row standard coordinates.
The row standard coordinates are obtained by dividing each row principal coordinate by it's
associated eigenvalue.
"""
utils.validation.check_is_fitted(self, 's_')
return self.row_coordinates(X).div(self.eigenvalues_, axis='columns') | [
"def",
"row_standard_coordinates",
"(",
"self",
",",
"X",
")",
":",
"utils",
".",
"validation",
".",
"check_is_fitted",
"(",
"self",
",",
"'s_'",
")",
"return",
"self",
".",
"row_coordinates",
"(",
"X",
")",
".",
"div",
"(",
"self",
".",
"eigenvalues_",
... | Returns the row standard coordinates.
The row standard coordinates are obtained by dividing each row principal coordinate by it's
associated eigenvalue. | [
"Returns",
"the",
"row",
"standard",
"coordinates",
"."
] | 714c9cdfc4d9f8823eabf550a23ad01fe87c50d7 | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/pca.py#L106-L113 | train | 226,818 |
MaxHalford/prince | prince/pca.py | PCA.row_cosine_similarities | def row_cosine_similarities(self, X):
"""Returns the cosine similarities between the rows and their principal components.
The row cosine similarities are obtained by calculating the cosine of the angle shaped by
the row principal coordinates and the row principal components. This is calculated by
squaring each row projection coordinate and dividing each squared coordinate by the sum of
the squared coordinates, which results in a ratio comprised between 0 and 1 representing the
squared cosine.
"""
utils.validation.check_is_fitted(self, 's_')
squared_coordinates = np.square(self.row_coordinates(X))
total_squares = squared_coordinates.sum(axis='columns')
return squared_coordinates.div(total_squares, axis='rows') | python | def row_cosine_similarities(self, X):
"""Returns the cosine similarities between the rows and their principal components.
The row cosine similarities are obtained by calculating the cosine of the angle shaped by
the row principal coordinates and the row principal components. This is calculated by
squaring each row projection coordinate and dividing each squared coordinate by the sum of
the squared coordinates, which results in a ratio comprised between 0 and 1 representing the
squared cosine.
"""
utils.validation.check_is_fitted(self, 's_')
squared_coordinates = np.square(self.row_coordinates(X))
total_squares = squared_coordinates.sum(axis='columns')
return squared_coordinates.div(total_squares, axis='rows') | [
"def",
"row_cosine_similarities",
"(",
"self",
",",
"X",
")",
":",
"utils",
".",
"validation",
".",
"check_is_fitted",
"(",
"self",
",",
"'s_'",
")",
"squared_coordinates",
"=",
"np",
".",
"square",
"(",
"self",
".",
"row_coordinates",
"(",
"X",
")",
")",
... | Returns the cosine similarities between the rows and their principal components.
The row cosine similarities are obtained by calculating the cosine of the angle shaped by
the row principal coordinates and the row principal components. This is calculated by
squaring each row projection coordinate and dividing each squared coordinate by the sum of
the squared coordinates, which results in a ratio comprised between 0 and 1 representing the
squared cosine. | [
"Returns",
"the",
"cosine",
"similarities",
"between",
"the",
"rows",
"and",
"their",
"principal",
"components",
"."
] | 714c9cdfc4d9f8823eabf550a23ad01fe87c50d7 | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/pca.py#L125-L137 | train | 226,819 |
MaxHalford/prince | prince/pca.py | PCA.column_correlations | def column_correlations(self, X):
"""Returns the column correlations with each principal component."""
utils.validation.check_is_fitted(self, 's_')
# Convert numpy array to pandas DataFrame
if isinstance(X, np.ndarray):
X = pd.DataFrame(X)
row_pc = self.row_coordinates(X)
return pd.DataFrame({
component: {
feature: row_pc[component].corr(X[feature])
for feature in X.columns
}
for component in row_pc.columns
}) | python | def column_correlations(self, X):
"""Returns the column correlations with each principal component."""
utils.validation.check_is_fitted(self, 's_')
# Convert numpy array to pandas DataFrame
if isinstance(X, np.ndarray):
X = pd.DataFrame(X)
row_pc = self.row_coordinates(X)
return pd.DataFrame({
component: {
feature: row_pc[component].corr(X[feature])
for feature in X.columns
}
for component in row_pc.columns
}) | [
"def",
"column_correlations",
"(",
"self",
",",
"X",
")",
":",
"utils",
".",
"validation",
".",
"check_is_fitted",
"(",
"self",
",",
"'s_'",
")",
"# Convert numpy array to pandas DataFrame",
"if",
"isinstance",
"(",
"X",
",",
"np",
".",
"ndarray",
")",
":",
... | Returns the column correlations with each principal component. | [
"Returns",
"the",
"column",
"correlations",
"with",
"each",
"principal",
"component",
"."
] | 714c9cdfc4d9f8823eabf550a23ad01fe87c50d7 | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/pca.py#L139-L155 | train | 226,820 |
MaxHalford/prince | prince/plot.py | build_ellipse | def build_ellipse(X, Y):
"""Construct ellipse coordinates from two arrays of numbers.
Args:
X (1D array_like)
Y (1D array_like)
Returns:
float: The mean of `X`.
float: The mean of `Y`.
float: The width of the ellipse.
float: The height of the ellipse.
float: The angle of orientation of the ellipse.
"""
x_mean = np.mean(X)
y_mean = np.mean(Y)
cov_matrix = np.cov(np.vstack((X, Y)))
U, s, V = linalg.svd(cov_matrix, full_matrices=False)
chi_95 = np.sqrt(4.61) # 90% quantile of the chi-square distribution
width = np.sqrt(cov_matrix[0][0]) * chi_95 * 2
height = np.sqrt(cov_matrix[1][1]) * chi_95 * 2
eigenvector = V.T[0]
angle = np.arctan(eigenvector[1] / eigenvector[0])
return x_mean, y_mean, width, height, angle | python | def build_ellipse(X, Y):
"""Construct ellipse coordinates from two arrays of numbers.
Args:
X (1D array_like)
Y (1D array_like)
Returns:
float: The mean of `X`.
float: The mean of `Y`.
float: The width of the ellipse.
float: The height of the ellipse.
float: The angle of orientation of the ellipse.
"""
x_mean = np.mean(X)
y_mean = np.mean(Y)
cov_matrix = np.cov(np.vstack((X, Y)))
U, s, V = linalg.svd(cov_matrix, full_matrices=False)
chi_95 = np.sqrt(4.61) # 90% quantile of the chi-square distribution
width = np.sqrt(cov_matrix[0][0]) * chi_95 * 2
height = np.sqrt(cov_matrix[1][1]) * chi_95 * 2
eigenvector = V.T[0]
angle = np.arctan(eigenvector[1] / eigenvector[0])
return x_mean, y_mean, width, height, angle | [
"def",
"build_ellipse",
"(",
"X",
",",
"Y",
")",
":",
"x_mean",
"=",
"np",
".",
"mean",
"(",
"X",
")",
"y_mean",
"=",
"np",
".",
"mean",
"(",
"Y",
")",
"cov_matrix",
"=",
"np",
".",
"cov",
"(",
"np",
".",
"vstack",
"(",
"(",
"X",
",",
"Y",
... | Construct ellipse coordinates from two arrays of numbers.
Args:
X (1D array_like)
Y (1D array_like)
Returns:
float: The mean of `X`.
float: The mean of `Y`.
float: The width of the ellipse.
float: The height of the ellipse.
float: The angle of orientation of the ellipse. | [
"Construct",
"ellipse",
"coordinates",
"from",
"two",
"arrays",
"of",
"numbers",
"."
] | 714c9cdfc4d9f8823eabf550a23ad01fe87c50d7 | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/plot.py#L27-L55 | train | 226,821 |
projecthamster/hamster | src/hamster/widgets/timeinput.py | TimeInput.set_start_time | def set_start_time(self, start_time):
""" set the start time. when start time is set, drop down list
will start from start time and duration will be displayed in
brackets
"""
start_time = start_time or dt.time()
if isinstance(start_time, dt.time): # ensure that we operate with time
self.start_time = dt.time(start_time.hour, start_time.minute)
else:
self.start_time = dt.time(start_time.time().hour, start_time.time().minute) | python | def set_start_time(self, start_time):
""" set the start time. when start time is set, drop down list
will start from start time and duration will be displayed in
brackets
"""
start_time = start_time or dt.time()
if isinstance(start_time, dt.time): # ensure that we operate with time
self.start_time = dt.time(start_time.hour, start_time.minute)
else:
self.start_time = dt.time(start_time.time().hour, start_time.time().minute) | [
"def",
"set_start_time",
"(",
"self",
",",
"start_time",
")",
":",
"start_time",
"=",
"start_time",
"or",
"dt",
".",
"time",
"(",
")",
"if",
"isinstance",
"(",
"start_time",
",",
"dt",
".",
"time",
")",
":",
"# ensure that we operate with time",
"self",
".",... | set the start time. when start time is set, drop down list
will start from start time and duration will be displayed in
brackets | [
"set",
"the",
"start",
"time",
".",
"when",
"start",
"time",
"is",
"set",
"drop",
"down",
"list",
"will",
"start",
"from",
"start",
"time",
"and",
"duration",
"will",
"be",
"displayed",
"in",
"brackets"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/widgets/timeinput.py#L85-L94 | train | 226,822 |
projecthamster/hamster | src/hamster/lib/__init__.py | extract_time | def extract_time(match):
"""extract time from a time_re match."""
hour = int(match.group('hour'))
minute = int(match.group('minute'))
return dt.time(hour, minute) | python | def extract_time(match):
"""extract time from a time_re match."""
hour = int(match.group('hour'))
minute = int(match.group('minute'))
return dt.time(hour, minute) | [
"def",
"extract_time",
"(",
"match",
")",
":",
"hour",
"=",
"int",
"(",
"match",
".",
"group",
"(",
"'hour'",
")",
")",
"minute",
"=",
"int",
"(",
"match",
".",
"group",
"(",
"'minute'",
")",
")",
"return",
"dt",
".",
"time",
"(",
"hour",
",",
"m... | extract time from a time_re match. | [
"extract",
"time",
"from",
"a",
"time_re",
"match",
"."
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/__init__.py#L40-L44 | train | 226,823 |
projecthamster/hamster | src/hamster/lib/__init__.py | default_logger | def default_logger(name):
"""Return a toplevel logger.
This should be used only in the toplevel file.
Files deeper in the hierarchy should use
``logger = logging.getLogger(__name__)``,
in order to considered as children of the toplevel logger.
Beware that without a setLevel() somewhere,
the default value (warning) will be used, so no debug message will be shown.
Args:
name (str): usually `__name__` in the package toplevel __init__.py, or
`__file__` in a script file
(because __name__ would be "__main__" in this case).
"""
# https://docs.python.org/3/howto/logging.html#logging-advanced-tutorial
logger = logging.getLogger(name)
# this is a basic handler, with output to stderr
logger_handler = logging.StreamHandler()
formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
logger_handler.setFormatter(formatter)
logger.addHandler(logger_handler)
return logger | python | def default_logger(name):
"""Return a toplevel logger.
This should be used only in the toplevel file.
Files deeper in the hierarchy should use
``logger = logging.getLogger(__name__)``,
in order to considered as children of the toplevel logger.
Beware that without a setLevel() somewhere,
the default value (warning) will be used, so no debug message will be shown.
Args:
name (str): usually `__name__` in the package toplevel __init__.py, or
`__file__` in a script file
(because __name__ would be "__main__" in this case).
"""
# https://docs.python.org/3/howto/logging.html#logging-advanced-tutorial
logger = logging.getLogger(name)
# this is a basic handler, with output to stderr
logger_handler = logging.StreamHandler()
formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
logger_handler.setFormatter(formatter)
logger.addHandler(logger_handler)
return logger | [
"def",
"default_logger",
"(",
"name",
")",
":",
"# https://docs.python.org/3/howto/logging.html#logging-advanced-tutorial",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"# this is a basic handler, with output to stderr",
"logger_handler",
"=",
"logging",
".",
... | Return a toplevel logger.
This should be used only in the toplevel file.
Files deeper in the hierarchy should use
``logger = logging.getLogger(__name__)``,
in order to considered as children of the toplevel logger.
Beware that without a setLevel() somewhere,
the default value (warning) will be used, so no debug message will be shown.
Args:
name (str): usually `__name__` in the package toplevel __init__.py, or
`__file__` in a script file
(because __name__ would be "__main__" in this case). | [
"Return",
"a",
"toplevel",
"logger",
"."
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/__init__.py#L355-L381 | train | 226,824 |
projecthamster/hamster | src/hamster/lib/__init__.py | Fact.serialized | def serialized(self, prepend_date=True):
"""Return a string fully representing the fact."""
name = self.serialized_name()
datetime = self.serialized_time(prepend_date)
return "%s %s" % (datetime, name) | python | def serialized(self, prepend_date=True):
"""Return a string fully representing the fact."""
name = self.serialized_name()
datetime = self.serialized_time(prepend_date)
return "%s %s" % (datetime, name) | [
"def",
"serialized",
"(",
"self",
",",
"prepend_date",
"=",
"True",
")",
":",
"name",
"=",
"self",
".",
"serialized_name",
"(",
")",
"datetime",
"=",
"self",
".",
"serialized_time",
"(",
"prepend_date",
")",
"return",
"\"%s %s\"",
"%",
"(",
"datetime",
","... | Return a string fully representing the fact. | [
"Return",
"a",
"string",
"fully",
"representing",
"the",
"fact",
"."
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/__init__.py#L200-L204 | train | 226,825 |
projecthamster/hamster | src/hamster/lib/layout.py | Widget._with_rotation | def _with_rotation(self, w, h):
"""calculate the actual dimensions after rotation"""
res_w = abs(w * math.cos(self.rotation) + h * math.sin(self.rotation))
res_h = abs(h * math.cos(self.rotation) + w * math.sin(self.rotation))
return res_w, res_h | python | def _with_rotation(self, w, h):
"""calculate the actual dimensions after rotation"""
res_w = abs(w * math.cos(self.rotation) + h * math.sin(self.rotation))
res_h = abs(h * math.cos(self.rotation) + w * math.sin(self.rotation))
return res_w, res_h | [
"def",
"_with_rotation",
"(",
"self",
",",
"w",
",",
"h",
")",
":",
"res_w",
"=",
"abs",
"(",
"w",
"*",
"math",
".",
"cos",
"(",
"self",
".",
"rotation",
")",
"+",
"h",
"*",
"math",
".",
"sin",
"(",
"self",
".",
"rotation",
")",
")",
"res_h",
... | calculate the actual dimensions after rotation | [
"calculate",
"the",
"actual",
"dimensions",
"after",
"rotation"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/layout.py#L195-L199 | train | 226,826 |
projecthamster/hamster | src/hamster/lib/layout.py | Widget.queue_resize | def queue_resize(self):
"""request the element to re-check it's child sprite sizes"""
self._children_resize_queued = True
parent = getattr(self, "parent", None)
if parent and isinstance(parent, graphics.Sprite) and hasattr(parent, "queue_resize"):
parent.queue_resize() | python | def queue_resize(self):
"""request the element to re-check it's child sprite sizes"""
self._children_resize_queued = True
parent = getattr(self, "parent", None)
if parent and isinstance(parent, graphics.Sprite) and hasattr(parent, "queue_resize"):
parent.queue_resize() | [
"def",
"queue_resize",
"(",
"self",
")",
":",
"self",
".",
"_children_resize_queued",
"=",
"True",
"parent",
"=",
"getattr",
"(",
"self",
",",
"\"parent\"",
",",
"None",
")",
"if",
"parent",
"and",
"isinstance",
"(",
"parent",
",",
"graphics",
".",
"Sprite... | request the element to re-check it's child sprite sizes | [
"request",
"the",
"element",
"to",
"re",
"-",
"check",
"it",
"s",
"child",
"sprite",
"sizes"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/layout.py#L241-L246 | train | 226,827 |
projecthamster/hamster | src/hamster/lib/layout.py | Widget.get_min_size | def get_min_size(self):
"""returns size required by the widget"""
if self.visible == False:
return 0, 0
else:
return ((self.min_width or 0) + self.horizontal_padding + self.margin_left + self.margin_right,
(self.min_height or 0) + self.vertical_padding + self.margin_top + self.margin_bottom) | python | def get_min_size(self):
"""returns size required by the widget"""
if self.visible == False:
return 0, 0
else:
return ((self.min_width or 0) + self.horizontal_padding + self.margin_left + self.margin_right,
(self.min_height or 0) + self.vertical_padding + self.margin_top + self.margin_bottom) | [
"def",
"get_min_size",
"(",
"self",
")",
":",
"if",
"self",
".",
"visible",
"==",
"False",
":",
"return",
"0",
",",
"0",
"else",
":",
"return",
"(",
"(",
"self",
".",
"min_width",
"or",
"0",
")",
"+",
"self",
".",
"horizontal_padding",
"+",
"self",
... | returns size required by the widget | [
"returns",
"size",
"required",
"by",
"the",
"widget"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/layout.py#L249-L255 | train | 226,828 |
projecthamster/hamster | src/hamster/lib/layout.py | Widget.insert | def insert(self, index = 0, *widgets):
"""insert widget in the sprites list at the given index.
by default will prepend."""
for widget in widgets:
self._add(widget, index)
index +=1 # as we are moving forwards
self._sort() | python | def insert(self, index = 0, *widgets):
"""insert widget in the sprites list at the given index.
by default will prepend."""
for widget in widgets:
self._add(widget, index)
index +=1 # as we are moving forwards
self._sort() | [
"def",
"insert",
"(",
"self",
",",
"index",
"=",
"0",
",",
"*",
"widgets",
")",
":",
"for",
"widget",
"in",
"widgets",
":",
"self",
".",
"_add",
"(",
"widget",
",",
"index",
")",
"index",
"+=",
"1",
"# as we are moving forwards",
"self",
".",
"_sort",
... | insert widget in the sprites list at the given index.
by default will prepend. | [
"insert",
"widget",
"in",
"the",
"sprites",
"list",
"at",
"the",
"given",
"index",
".",
"by",
"default",
"will",
"prepend",
"."
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/layout.py#L259-L265 | train | 226,829 |
projecthamster/hamster | src/hamster/lib/layout.py | Widget.insert_before | def insert_before(self, target):
"""insert this widget into the targets parent before the target"""
if not target.parent:
return
target.parent.insert(target.parent.sprites.index(target), self) | python | def insert_before(self, target):
"""insert this widget into the targets parent before the target"""
if not target.parent:
return
target.parent.insert(target.parent.sprites.index(target), self) | [
"def",
"insert_before",
"(",
"self",
",",
"target",
")",
":",
"if",
"not",
"target",
".",
"parent",
":",
"return",
"target",
".",
"parent",
".",
"insert",
"(",
"target",
".",
"parent",
".",
"sprites",
".",
"index",
"(",
"target",
")",
",",
"self",
")... | insert this widget into the targets parent before the target | [
"insert",
"this",
"widget",
"into",
"the",
"targets",
"parent",
"before",
"the",
"target"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/layout.py#L268-L272 | train | 226,830 |
projecthamster/hamster | src/hamster/lib/layout.py | Widget.insert_after | def insert_after(self, target):
"""insert this widget into the targets parent container after the target"""
if not target.parent:
return
target.parent.insert(target.parent.sprites.index(target) + 1, self) | python | def insert_after(self, target):
"""insert this widget into the targets parent container after the target"""
if not target.parent:
return
target.parent.insert(target.parent.sprites.index(target) + 1, self) | [
"def",
"insert_after",
"(",
"self",
",",
"target",
")",
":",
"if",
"not",
"target",
".",
"parent",
":",
"return",
"target",
".",
"parent",
".",
"insert",
"(",
"target",
".",
"parent",
".",
"sprites",
".",
"index",
"(",
"target",
")",
"+",
"1",
",",
... | insert this widget into the targets parent container after the target | [
"insert",
"this",
"widget",
"into",
"the",
"targets",
"parent",
"container",
"after",
"the",
"target"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/layout.py#L274-L278 | train | 226,831 |
projecthamster/hamster | src/hamster/lib/layout.py | Widget.width | def width(self):
"""width in pixels"""
alloc_w = self.alloc_w
if self.parent and isinstance(self.parent, graphics.Scene):
alloc_w = self.parent.width
def res(scene, event):
if self.parent:
self.queue_resize()
else:
scene.disconnect(self._scene_resize_handler)
self._scene_resize_handler = None
if not self._scene_resize_handler:
# TODO - disconnect on reparenting
self._scene_resize_handler = self.parent.connect("on-resize", res)
min_width = (self.min_width or 0) + self.margin_left + self.margin_right
w = alloc_w if alloc_w is not None and self.fill else min_width
w = max(w or 0, self.get_min_size()[0])
return w - self.margin_left - self.margin_right | python | def width(self):
"""width in pixels"""
alloc_w = self.alloc_w
if self.parent and isinstance(self.parent, graphics.Scene):
alloc_w = self.parent.width
def res(scene, event):
if self.parent:
self.queue_resize()
else:
scene.disconnect(self._scene_resize_handler)
self._scene_resize_handler = None
if not self._scene_resize_handler:
# TODO - disconnect on reparenting
self._scene_resize_handler = self.parent.connect("on-resize", res)
min_width = (self.min_width or 0) + self.margin_left + self.margin_right
w = alloc_w if alloc_w is not None and self.fill else min_width
w = max(w or 0, self.get_min_size()[0])
return w - self.margin_left - self.margin_right | [
"def",
"width",
"(",
"self",
")",
":",
"alloc_w",
"=",
"self",
".",
"alloc_w",
"if",
"self",
".",
"parent",
"and",
"isinstance",
"(",
"self",
".",
"parent",
",",
"graphics",
".",
"Scene",
")",
":",
"alloc_w",
"=",
"self",
".",
"parent",
".",
"width",... | width in pixels | [
"width",
"in",
"pixels"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/layout.py#L282-L305 | train | 226,832 |
projecthamster/hamster | src/hamster/lib/layout.py | Widget.height | def height(self):
"""height in pixels"""
alloc_h = self.alloc_h
if self.parent and isinstance(self.parent, graphics.Scene):
alloc_h = self.parent.height
min_height = (self.min_height or 0) + self.margin_top + self.margin_bottom
h = alloc_h if alloc_h is not None and self.fill else min_height
h = max(h or 0, self.get_min_size()[1])
return h - self.margin_top - self.margin_bottom | python | def height(self):
"""height in pixels"""
alloc_h = self.alloc_h
if self.parent and isinstance(self.parent, graphics.Scene):
alloc_h = self.parent.height
min_height = (self.min_height or 0) + self.margin_top + self.margin_bottom
h = alloc_h if alloc_h is not None and self.fill else min_height
h = max(h or 0, self.get_min_size()[1])
return h - self.margin_top - self.margin_bottom | [
"def",
"height",
"(",
"self",
")",
":",
"alloc_h",
"=",
"self",
".",
"alloc_h",
"if",
"self",
".",
"parent",
"and",
"isinstance",
"(",
"self",
".",
"parent",
",",
"graphics",
".",
"Scene",
")",
":",
"alloc_h",
"=",
"self",
".",
"parent",
".",
"height... | height in pixels | [
"height",
"in",
"pixels"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/layout.py#L308-L318 | train | 226,833 |
projecthamster/hamster | src/hamster/lib/layout.py | Widget.enabled | def enabled(self):
"""whether the user is allowed to interact with the
widget. Item is enabled only if all it's parent elements are"""
enabled = self._enabled
if not enabled:
return False
if self.parent and isinstance(self.parent, Widget):
if self.parent.enabled == False:
return False
return True | python | def enabled(self):
"""whether the user is allowed to interact with the
widget. Item is enabled only if all it's parent elements are"""
enabled = self._enabled
if not enabled:
return False
if self.parent and isinstance(self.parent, Widget):
if self.parent.enabled == False:
return False
return True | [
"def",
"enabled",
"(",
"self",
")",
":",
"enabled",
"=",
"self",
".",
"_enabled",
"if",
"not",
"enabled",
":",
"return",
"False",
"if",
"self",
".",
"parent",
"and",
"isinstance",
"(",
"self",
".",
"parent",
",",
"Widget",
")",
":",
"if",
"self",
"."... | whether the user is allowed to interact with the
widget. Item is enabled only if all it's parent elements are | [
"whether",
"the",
"user",
"is",
"allowed",
"to",
"interact",
"with",
"the",
"widget",
".",
"Item",
"is",
"enabled",
"only",
"if",
"all",
"it",
"s",
"parent",
"elements",
"are"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/layout.py#L321-L332 | train | 226,834 |
projecthamster/hamster | src/hamster/lib/layout.py | Container.resize_children | def resize_children(self):
"""default container alignment is to pile stuff just up, respecting only
padding, margin and element's alignment properties"""
width = self.width - self.horizontal_padding
height = self.height - self.vertical_padding
for sprite, props in (get_props(sprite) for sprite in self.sprites if sprite.visible):
sprite.alloc_w = width
sprite.alloc_h = height
w, h = getattr(sprite, "width", 0), getattr(sprite, "height", 0)
if hasattr(sprite, "get_height_for_width_size"):
w2, h2 = sprite.get_height_for_width_size()
w, h = max(w, w2), max(h, h2)
w = w * sprite.scale_x + props["margin_left"] + props["margin_right"]
h = h * sprite.scale_y + props["margin_top"] + props["margin_bottom"]
sprite.x = self.padding_left + props["margin_left"] + (max(sprite.alloc_w * sprite.scale_x, w) - w) * getattr(sprite, "x_align", 0)
sprite.y = self.padding_top + props["margin_top"] + (max(sprite.alloc_h * sprite.scale_y, h) - h) * getattr(sprite, "y_align", 0)
self.__dict__['_children_resize_queued'] = False | python | def resize_children(self):
"""default container alignment is to pile stuff just up, respecting only
padding, margin and element's alignment properties"""
width = self.width - self.horizontal_padding
height = self.height - self.vertical_padding
for sprite, props in (get_props(sprite) for sprite in self.sprites if sprite.visible):
sprite.alloc_w = width
sprite.alloc_h = height
w, h = getattr(sprite, "width", 0), getattr(sprite, "height", 0)
if hasattr(sprite, "get_height_for_width_size"):
w2, h2 = sprite.get_height_for_width_size()
w, h = max(w, w2), max(h, h2)
w = w * sprite.scale_x + props["margin_left"] + props["margin_right"]
h = h * sprite.scale_y + props["margin_top"] + props["margin_bottom"]
sprite.x = self.padding_left + props["margin_left"] + (max(sprite.alloc_w * sprite.scale_x, w) - w) * getattr(sprite, "x_align", 0)
sprite.y = self.padding_top + props["margin_top"] + (max(sprite.alloc_h * sprite.scale_y, h) - h) * getattr(sprite, "y_align", 0)
self.__dict__['_children_resize_queued'] = False | [
"def",
"resize_children",
"(",
"self",
")",
":",
"width",
"=",
"self",
".",
"width",
"-",
"self",
".",
"horizontal_padding",
"height",
"=",
"self",
".",
"height",
"-",
"self",
".",
"vertical_padding",
"for",
"sprite",
",",
"props",
"in",
"(",
"get_props",
... | default container alignment is to pile stuff just up, respecting only
padding, margin and element's alignment properties | [
"default",
"container",
"alignment",
"is",
"to",
"pile",
"stuff",
"just",
"up",
"respecting",
"only",
"padding",
"margin",
"and",
"element",
"s",
"alignment",
"properties"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/layout.py#L474-L496 | train | 226,835 |
projecthamster/hamster | src/hamster/lib/desktop.py | DesktopIntegrations.check_hamster | def check_hamster(self):
"""refresh hamster every x secs - load today, check last activity etc."""
try:
# can't use the client because then we end up in a dbus loop
# as this is initiated in storage
todays_facts = self.storage._Storage__get_todays_facts()
self.check_user(todays_facts)
except Exception as e:
logger.error("Error while refreshing: %s" % e)
finally: # we want to go on no matter what, so in case of any error we find out about it sooner
return True | python | def check_hamster(self):
"""refresh hamster every x secs - load today, check last activity etc."""
try:
# can't use the client because then we end up in a dbus loop
# as this is initiated in storage
todays_facts = self.storage._Storage__get_todays_facts()
self.check_user(todays_facts)
except Exception as e:
logger.error("Error while refreshing: %s" % e)
finally: # we want to go on no matter what, so in case of any error we find out about it sooner
return True | [
"def",
"check_hamster",
"(",
"self",
")",
":",
"try",
":",
"# can't use the client because then we end up in a dbus loop",
"# as this is initiated in storage",
"todays_facts",
"=",
"self",
".",
"storage",
".",
"_Storage__get_todays_facts",
"(",
")",
"self",
".",
"check_user... | refresh hamster every x secs - load today, check last activity etc. | [
"refresh",
"hamster",
"every",
"x",
"secs",
"-",
"load",
"today",
"check",
"last",
"activity",
"etc",
"."
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/desktop.py#L52-L62 | train | 226,836 |
projecthamster/hamster | src/hamster/lib/desktop.py | DesktopIntegrations.check_user | def check_user(self, todays_facts):
"""check if we need to notify user perhaps"""
interval = self.conf_notify_interval
if interval <= 0 or interval >= 121:
return
now = dt.datetime.now()
message = None
last_activity = todays_facts[-1] if todays_facts else None
# update duration of current task
if last_activity and not last_activity['end_time']:
delta = now - last_activity['start_time']
duration = delta.seconds / 60
if duration and duration % interval == 0:
message = _("Working on %s") % last_activity['name']
self.notify_user(message)
elif self.conf_notify_on_idle:
#if we have no last activity, let's just calculate duration from 00:00
if (now.minute + now.hour * 60) % interval == 0:
self.notify_user(_("No activity")) | python | def check_user(self, todays_facts):
"""check if we need to notify user perhaps"""
interval = self.conf_notify_interval
if interval <= 0 or interval >= 121:
return
now = dt.datetime.now()
message = None
last_activity = todays_facts[-1] if todays_facts else None
# update duration of current task
if last_activity and not last_activity['end_time']:
delta = now - last_activity['start_time']
duration = delta.seconds / 60
if duration and duration % interval == 0:
message = _("Working on %s") % last_activity['name']
self.notify_user(message)
elif self.conf_notify_on_idle:
#if we have no last activity, let's just calculate duration from 00:00
if (now.minute + now.hour * 60) % interval == 0:
self.notify_user(_("No activity")) | [
"def",
"check_user",
"(",
"self",
",",
"todays_facts",
")",
":",
"interval",
"=",
"self",
".",
"conf_notify_interval",
"if",
"interval",
"<=",
"0",
"or",
"interval",
">=",
"121",
":",
"return",
"now",
"=",
"dt",
".",
"datetime",
".",
"now",
"(",
")",
"... | check if we need to notify user perhaps | [
"check",
"if",
"we",
"need",
"to",
"notify",
"user",
"perhaps"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/desktop.py#L65-L88 | train | 226,837 |
projecthamster/hamster | src/hamster/storage/storage.py | Storage.stop_tracking | def stop_tracking(self, end_time):
"""Stops tracking the current activity"""
facts = self.__get_todays_facts()
if facts and not facts[-1]['end_time']:
self.__touch_fact(facts[-1], end_time)
self.facts_changed() | python | def stop_tracking(self, end_time):
"""Stops tracking the current activity"""
facts = self.__get_todays_facts()
if facts and not facts[-1]['end_time']:
self.__touch_fact(facts[-1], end_time)
self.facts_changed() | [
"def",
"stop_tracking",
"(",
"self",
",",
"end_time",
")",
":",
"facts",
"=",
"self",
".",
"__get_todays_facts",
"(",
")",
"if",
"facts",
"and",
"not",
"facts",
"[",
"-",
"1",
"]",
"[",
"'end_time'",
"]",
":",
"self",
".",
"__touch_fact",
"(",
"facts",... | Stops tracking the current activity | [
"Stops",
"tracking",
"the",
"current",
"activity"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/storage.py#L67-L72 | train | 226,838 |
projecthamster/hamster | src/hamster/storage/storage.py | Storage.remove_fact | def remove_fact(self, fact_id):
"""Remove fact from storage by it's ID"""
self.start_transaction()
fact = self.__get_fact(fact_id)
if fact:
self.__remove_fact(fact_id)
self.facts_changed()
self.end_transaction() | python | def remove_fact(self, fact_id):
"""Remove fact from storage by it's ID"""
self.start_transaction()
fact = self.__get_fact(fact_id)
if fact:
self.__remove_fact(fact_id)
self.facts_changed()
self.end_transaction() | [
"def",
"remove_fact",
"(",
"self",
",",
"fact_id",
")",
":",
"self",
".",
"start_transaction",
"(",
")",
"fact",
"=",
"self",
".",
"__get_fact",
"(",
"fact_id",
")",
"if",
"fact",
":",
"self",
".",
"__remove_fact",
"(",
"fact_id",
")",
"self",
".",
"fa... | Remove fact from storage by it's ID | [
"Remove",
"fact",
"from",
"storage",
"by",
"it",
"s",
"ID"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/storage.py#L75-L82 | train | 226,839 |
projecthamster/hamster | src/hamster/lib/configuration.py | load_ui_file | def load_ui_file(name):
"""loads interface from the glade file; sorts out the path business"""
ui = gtk.Builder()
ui.add_from_file(os.path.join(runtime.data_dir, name))
return ui | python | def load_ui_file(name):
"""loads interface from the glade file; sorts out the path business"""
ui = gtk.Builder()
ui.add_from_file(os.path.join(runtime.data_dir, name))
return ui | [
"def",
"load_ui_file",
"(",
"name",
")",
":",
"ui",
"=",
"gtk",
".",
"Builder",
"(",
")",
"ui",
".",
"add_from_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"runtime",
".",
"data_dir",
",",
"name",
")",
")",
"return",
"ui"
] | loads interface from the glade file; sorts out the path business | [
"loads",
"interface",
"from",
"the",
"glade",
"file",
";",
"sorts",
"out",
"the",
"path",
"business"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/configuration.py#L87-L91 | train | 226,840 |
projecthamster/hamster | src/hamster/lib/configuration.py | GConfStore._fix_key | def _fix_key(self, key):
"""
Appends the GCONF_PREFIX to the key if needed
@param key: The key to check
@type key: C{string}
@returns: The fixed key
@rtype: C{string}
"""
if not key.startswith(self.GCONF_DIR):
return self.GCONF_DIR + key
else:
return key | python | def _fix_key(self, key):
"""
Appends the GCONF_PREFIX to the key if needed
@param key: The key to check
@type key: C{string}
@returns: The fixed key
@rtype: C{string}
"""
if not key.startswith(self.GCONF_DIR):
return self.GCONF_DIR + key
else:
return key | [
"def",
"_fix_key",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"key",
".",
"startswith",
"(",
"self",
".",
"GCONF_DIR",
")",
":",
"return",
"self",
".",
"GCONF_DIR",
"+",
"key",
"else",
":",
"return",
"key"
] | Appends the GCONF_PREFIX to the key if needed
@param key: The key to check
@type key: C{string}
@returns: The fixed key
@rtype: C{string} | [
"Appends",
"the",
"GCONF_PREFIX",
"to",
"the",
"key",
"if",
"needed"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/configuration.py#L224-L236 | train | 226,841 |
projecthamster/hamster | src/hamster/lib/configuration.py | GConfStore._key_changed | def _key_changed(self, client, cnxn_id, entry, data=None):
"""
Callback when a gconf key changes
"""
key = self._fix_key(entry.key)[len(self.GCONF_DIR):]
value = self._get_value(entry.value, self.DEFAULTS[key])
self.emit('conf-changed', key, value) | python | def _key_changed(self, client, cnxn_id, entry, data=None):
"""
Callback when a gconf key changes
"""
key = self._fix_key(entry.key)[len(self.GCONF_DIR):]
value = self._get_value(entry.value, self.DEFAULTS[key])
self.emit('conf-changed', key, value) | [
"def",
"_key_changed",
"(",
"self",
",",
"client",
",",
"cnxn_id",
",",
"entry",
",",
"data",
"=",
"None",
")",
":",
"key",
"=",
"self",
".",
"_fix_key",
"(",
"entry",
".",
"key",
")",
"[",
"len",
"(",
"self",
".",
"GCONF_DIR",
")",
":",
"]",
"va... | Callback when a gconf key changes | [
"Callback",
"when",
"a",
"gconf",
"key",
"changes"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/configuration.py#L238-L245 | train | 226,842 |
projecthamster/hamster | src/hamster/lib/configuration.py | GConfStore._get_value | def _get_value(self, value, default):
"""calls appropriate gconf function by the default value"""
vtype = type(default)
if vtype is bool:
return value.get_bool()
elif vtype is str:
return value.get_string()
elif vtype is int:
return value.get_int()
elif vtype in (list, tuple):
l = []
for i in value.get_list():
l.append(i.get_string())
return l
return None | python | def _get_value(self, value, default):
"""calls appropriate gconf function by the default value"""
vtype = type(default)
if vtype is bool:
return value.get_bool()
elif vtype is str:
return value.get_string()
elif vtype is int:
return value.get_int()
elif vtype in (list, tuple):
l = []
for i in value.get_list():
l.append(i.get_string())
return l
return None | [
"def",
"_get_value",
"(",
"self",
",",
"value",
",",
"default",
")",
":",
"vtype",
"=",
"type",
"(",
"default",
")",
"if",
"vtype",
"is",
"bool",
":",
"return",
"value",
".",
"get_bool",
"(",
")",
"elif",
"vtype",
"is",
"str",
":",
"return",
"value",... | calls appropriate gconf function by the default value | [
"calls",
"appropriate",
"gconf",
"function",
"by",
"the",
"default",
"value"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/configuration.py#L248-L264 | train | 226,843 |
projecthamster/hamster | src/hamster/lib/configuration.py | GConfStore.get | def get(self, key, default=None):
"""
Returns the value of the key or the default value if the key is
not yet in gconf
"""
#function arguments override defaults
if default is None:
default = self.DEFAULTS.get(key, None)
vtype = type(default)
#we now have a valid key and type
if default is None:
logger.warn("Unknown key: %s, must specify default value" % key)
return None
if vtype not in self.VALID_KEY_TYPES:
logger.warn("Invalid key type: %s" % vtype)
return None
#for gconf refer to the full key path
key = self._fix_key(key)
if key not in self._notifications:
self._client.notify_add(key, self._key_changed, None)
self._notifications.append(key)
value = self._client.get(key)
if value is None:
self.set(key, default)
return default
value = self._get_value(value, default)
if value is not None:
return value
logger.warn("Unknown gconf key: %s" % key)
return None | python | def get(self, key, default=None):
"""
Returns the value of the key or the default value if the key is
not yet in gconf
"""
#function arguments override defaults
if default is None:
default = self.DEFAULTS.get(key, None)
vtype = type(default)
#we now have a valid key and type
if default is None:
logger.warn("Unknown key: %s, must specify default value" % key)
return None
if vtype not in self.VALID_KEY_TYPES:
logger.warn("Invalid key type: %s" % vtype)
return None
#for gconf refer to the full key path
key = self._fix_key(key)
if key not in self._notifications:
self._client.notify_add(key, self._key_changed, None)
self._notifications.append(key)
value = self._client.get(key)
if value is None:
self.set(key, default)
return default
value = self._get_value(value, default)
if value is not None:
return value
logger.warn("Unknown gconf key: %s" % key)
return None | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"#function arguments override defaults",
"if",
"default",
"is",
"None",
":",
"default",
"=",
"self",
".",
"DEFAULTS",
".",
"get",
"(",
"key",
",",
"None",
")",
"vtype",
"=",
... | Returns the value of the key or the default value if the key is
not yet in gconf | [
"Returns",
"the",
"value",
"of",
"the",
"key",
"or",
"the",
"default",
"value",
"if",
"the",
"key",
"is",
"not",
"yet",
"in",
"gconf"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/configuration.py#L266-L303 | train | 226,844 |
projecthamster/hamster | src/hamster/lib/configuration.py | GConfStore.set | def set(self, key, value):
"""
Sets the key value in gconf and connects adds a signal
which is fired if the key changes
"""
logger.debug("Settings %s -> %s" % (key, value))
if key in self.DEFAULTS:
vtype = type(self.DEFAULTS[key])
else:
vtype = type(value)
if vtype not in self.VALID_KEY_TYPES:
logger.warn("Invalid key type: %s" % vtype)
return False
#for gconf refer to the full key path
key = self._fix_key(key)
if vtype is bool:
self._client.set_bool(key, value)
elif vtype is str:
self._client.set_string(key, value)
elif vtype is int:
self._client.set_int(key, value)
elif vtype in (list, tuple):
#Save every value as a string
strvalues = [str(i) for i in value]
#self._client.set_list(key, gconf.VALUE_STRING, strvalues)
return True | python | def set(self, key, value):
"""
Sets the key value in gconf and connects adds a signal
which is fired if the key changes
"""
logger.debug("Settings %s -> %s" % (key, value))
if key in self.DEFAULTS:
vtype = type(self.DEFAULTS[key])
else:
vtype = type(value)
if vtype not in self.VALID_KEY_TYPES:
logger.warn("Invalid key type: %s" % vtype)
return False
#for gconf refer to the full key path
key = self._fix_key(key)
if vtype is bool:
self._client.set_bool(key, value)
elif vtype is str:
self._client.set_string(key, value)
elif vtype is int:
self._client.set_int(key, value)
elif vtype in (list, tuple):
#Save every value as a string
strvalues = [str(i) for i in value]
#self._client.set_list(key, gconf.VALUE_STRING, strvalues)
return True | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"logger",
".",
"debug",
"(",
"\"Settings %s -> %s\"",
"%",
"(",
"key",
",",
"value",
")",
")",
"if",
"key",
"in",
"self",
".",
"DEFAULTS",
":",
"vtype",
"=",
"type",
"(",
"self",
".",
... | Sets the key value in gconf and connects adds a signal
which is fired if the key changes | [
"Sets",
"the",
"key",
"value",
"in",
"gconf",
"and",
"connects",
"adds",
"a",
"signal",
"which",
"is",
"fired",
"if",
"the",
"key",
"changes"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/configuration.py#L305-L334 | train | 226,845 |
projecthamster/hamster | src/hamster/lib/configuration.py | GConfStore.day_start | def day_start(self):
"""Start of the hamster day."""
day_start_minutes = self.get("day_start_minutes")
hours, minutes = divmod(day_start_minutes, 60)
return dt.time(hours, minutes) | python | def day_start(self):
"""Start of the hamster day."""
day_start_minutes = self.get("day_start_minutes")
hours, minutes = divmod(day_start_minutes, 60)
return dt.time(hours, minutes) | [
"def",
"day_start",
"(",
"self",
")",
":",
"day_start_minutes",
"=",
"self",
".",
"get",
"(",
"\"day_start_minutes\"",
")",
"hours",
",",
"minutes",
"=",
"divmod",
"(",
"day_start_minutes",
",",
"60",
")",
"return",
"dt",
".",
"time",
"(",
"hours",
",",
... | Start of the hamster day. | [
"Start",
"of",
"the",
"hamster",
"day",
"."
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/configuration.py#L337-L341 | train | 226,846 |
projecthamster/hamster | src/hamster/edit_activity.py | CustomFactController.localized_fact | def localized_fact(self):
"""Make sure fact has the correct start_time."""
fact = Fact(self.activity.get_text())
if fact.start_time:
fact.date = self.date
else:
fact.start_time = dt.datetime.now()
return fact | python | def localized_fact(self):
"""Make sure fact has the correct start_time."""
fact = Fact(self.activity.get_text())
if fact.start_time:
fact.date = self.date
else:
fact.start_time = dt.datetime.now()
return fact | [
"def",
"localized_fact",
"(",
"self",
")",
":",
"fact",
"=",
"Fact",
"(",
"self",
".",
"activity",
".",
"get_text",
"(",
")",
")",
"if",
"fact",
".",
"start_time",
":",
"fact",
".",
"date",
"=",
"self",
".",
"date",
"else",
":",
"fact",
".",
"start... | Make sure fact has the correct start_time. | [
"Make",
"sure",
"fact",
"has",
"the",
"correct",
"start_time",
"."
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/edit_activity.py#L124-L131 | train | 226,847 |
projecthamster/hamster | src/hamster/widgets/activityentry.py | CompleteTree.set_row_positions | def set_row_positions(self):
"""creates a list of row positions for simpler manipulation"""
self.row_positions = [i * self.row_height for i in range(len(self.rows))]
self.set_size_request(0, self.row_positions[-1] + self.row_height if self.row_positions else 0) | python | def set_row_positions(self):
"""creates a list of row positions for simpler manipulation"""
self.row_positions = [i * self.row_height for i in range(len(self.rows))]
self.set_size_request(0, self.row_positions[-1] + self.row_height if self.row_positions else 0) | [
"def",
"set_row_positions",
"(",
"self",
")",
":",
"self",
".",
"row_positions",
"=",
"[",
"i",
"*",
"self",
".",
"row_height",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"rows",
")",
")",
"]",
"self",
".",
"set_size_request",
"(",
"0",... | creates a list of row positions for simpler manipulation | [
"creates",
"a",
"list",
"of",
"row",
"positions",
"for",
"simpler",
"manipulation"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/widgets/activityentry.py#L157-L160 | train | 226,848 |
projecthamster/hamster | src/hamster/client.py | from_dbus_fact | def from_dbus_fact(fact):
"""unpack the struct into a proper dict"""
return Fact(fact[4],
start_time = dt.datetime.utcfromtimestamp(fact[1]),
end_time = dt.datetime.utcfromtimestamp(fact[2]) if fact[2] else None,
description = fact[3],
activity_id = fact[5],
category = fact[6],
tags = fact[7],
date = dt.datetime.utcfromtimestamp(fact[8]).date(),
id = fact[0]
) | python | def from_dbus_fact(fact):
"""unpack the struct into a proper dict"""
return Fact(fact[4],
start_time = dt.datetime.utcfromtimestamp(fact[1]),
end_time = dt.datetime.utcfromtimestamp(fact[2]) if fact[2] else None,
description = fact[3],
activity_id = fact[5],
category = fact[6],
tags = fact[7],
date = dt.datetime.utcfromtimestamp(fact[8]).date(),
id = fact[0]
) | [
"def",
"from_dbus_fact",
"(",
"fact",
")",
":",
"return",
"Fact",
"(",
"fact",
"[",
"4",
"]",
",",
"start_time",
"=",
"dt",
".",
"datetime",
".",
"utcfromtimestamp",
"(",
"fact",
"[",
"1",
"]",
")",
",",
"end_time",
"=",
"dt",
".",
"datetime",
".",
... | unpack the struct into a proper dict | [
"unpack",
"the",
"struct",
"into",
"a",
"proper",
"dict"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/client.py#L28-L39 | train | 226,849 |
projecthamster/hamster | src/hamster/client.py | Storage.get_tags | def get_tags(self, only_autocomplete = False):
"""returns list of all tags. by default only those that have been set for autocomplete"""
return self._to_dict(('id', 'name', 'autocomplete'), self.conn.GetTags(only_autocomplete)) | python | def get_tags(self, only_autocomplete = False):
"""returns list of all tags. by default only those that have been set for autocomplete"""
return self._to_dict(('id', 'name', 'autocomplete'), self.conn.GetTags(only_autocomplete)) | [
"def",
"get_tags",
"(",
"self",
",",
"only_autocomplete",
"=",
"False",
")",
":",
"return",
"self",
".",
"_to_dict",
"(",
"(",
"'id'",
",",
"'name'",
",",
"'autocomplete'",
")",
",",
"self",
".",
"conn",
".",
"GetTags",
"(",
"only_autocomplete",
")",
")"... | returns list of all tags. by default only those that have been set for autocomplete | [
"returns",
"list",
"of",
"all",
"tags",
".",
"by",
"default",
"only",
"those",
"that",
"have",
"been",
"set",
"for",
"autocomplete"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/client.py#L151-L153 | train | 226,850 |
projecthamster/hamster | src/hamster/client.py | Storage.stop_tracking | def stop_tracking(self, end_time = None):
"""Stop tracking current activity. end_time can be passed in if the
activity should have other end time than the current moment"""
end_time = timegm((end_time or dt.datetime.now()).timetuple())
return self.conn.StopTracking(end_time) | python | def stop_tracking(self, end_time = None):
"""Stop tracking current activity. end_time can be passed in if the
activity should have other end time than the current moment"""
end_time = timegm((end_time or dt.datetime.now()).timetuple())
return self.conn.StopTracking(end_time) | [
"def",
"stop_tracking",
"(",
"self",
",",
"end_time",
"=",
"None",
")",
":",
"end_time",
"=",
"timegm",
"(",
"(",
"end_time",
"or",
"dt",
".",
"datetime",
".",
"now",
"(",
")",
")",
".",
"timetuple",
"(",
")",
")",
"return",
"self",
".",
"conn",
".... | Stop tracking current activity. end_time can be passed in if the
activity should have other end time than the current moment | [
"Stop",
"tracking",
"current",
"activity",
".",
"end_time",
"can",
"be",
"passed",
"in",
"if",
"the",
"activity",
"should",
"have",
"other",
"end",
"time",
"than",
"the",
"current",
"moment"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/client.py#L201-L205 | train | 226,851 |
projecthamster/hamster | src/hamster/client.py | Storage.get_category_activities | def get_category_activities(self, category_id = None):
"""Return activities for category. If category is not specified, will
return activities that have no category"""
category_id = category_id or -1
return self._to_dict(('id', 'name', 'category_id', 'category'), self.conn.GetCategoryActivities(category_id)) | python | def get_category_activities(self, category_id = None):
"""Return activities for category. If category is not specified, will
return activities that have no category"""
category_id = category_id or -1
return self._to_dict(('id', 'name', 'category_id', 'category'), self.conn.GetCategoryActivities(category_id)) | [
"def",
"get_category_activities",
"(",
"self",
",",
"category_id",
"=",
"None",
")",
":",
"category_id",
"=",
"category_id",
"or",
"-",
"1",
"return",
"self",
".",
"_to_dict",
"(",
"(",
"'id'",
",",
"'name'",
",",
"'category_id'",
",",
"'category'",
")",
"... | Return activities for category. If category is not specified, will
return activities that have no category | [
"Return",
"activities",
"for",
"category",
".",
"If",
"category",
"is",
"not",
"specified",
"will",
"return",
"activities",
"that",
"have",
"no",
"category"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/client.py#L232-L236 | train | 226,852 |
projecthamster/hamster | src/hamster/client.py | Storage.get_activity_by_name | def get_activity_by_name(self, activity, category_id = None, resurrect = True):
"""returns activity dict by name and optionally filtering by category.
if activity is found but is marked as deleted, it will be resurrected
unless told otherwise in the resurrect param
"""
category_id = category_id or 0
return self.conn.GetActivityByName(activity, category_id, resurrect) | python | def get_activity_by_name(self, activity, category_id = None, resurrect = True):
"""returns activity dict by name and optionally filtering by category.
if activity is found but is marked as deleted, it will be resurrected
unless told otherwise in the resurrect param
"""
category_id = category_id or 0
return self.conn.GetActivityByName(activity, category_id, resurrect) | [
"def",
"get_activity_by_name",
"(",
"self",
",",
"activity",
",",
"category_id",
"=",
"None",
",",
"resurrect",
"=",
"True",
")",
":",
"category_id",
"=",
"category_id",
"or",
"0",
"return",
"self",
".",
"conn",
".",
"GetActivityByName",
"(",
"activity",
","... | returns activity dict by name and optionally filtering by category.
if activity is found but is marked as deleted, it will be resurrected
unless told otherwise in the resurrect param | [
"returns",
"activity",
"dict",
"by",
"name",
"and",
"optionally",
"filtering",
"by",
"category",
".",
"if",
"activity",
"is",
"found",
"but",
"is",
"marked",
"as",
"deleted",
"it",
"will",
"be",
"resurrected",
"unless",
"told",
"otherwise",
"in",
"the",
"res... | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/client.py#L242-L248 | train | 226,853 |
projecthamster/hamster | src/hamster/idle.py | DbusIdleListener.bus_inspector | def bus_inspector(self, bus, message):
"""
Inspect the bus for screensaver messages of interest
"""
# We only care about stuff on this interface. We did filter
# for it above, but even so we still hear from ourselves
# (hamster messages).
if message.get_interface() != self.screensaver_uri:
return True
member = message.get_member()
if member in ("SessionIdleChanged", "ActiveChanged"):
logger.debug("%s -> %s" % (member, message.get_args_list()))
idle_state = message.get_args_list()[0]
if idle_state:
self.idle_from = dt.datetime.now()
# from gnome screensaver 2.24 to 2.28 they have switched
# configuration keys and signal types.
# luckily we can determine key by signal type
if member == "SessionIdleChanged":
delay_key = "/apps/gnome-screensaver/idle_delay"
else:
delay_key = "/desktop/gnome/session/idle_delay"
client = gconf.Client.get_default()
self.timeout_minutes = client.get_int(delay_key)
else:
self.screen_locked = False
self.idle_from = None
if member == "ActiveChanged":
# ActiveChanged comes before SessionIdleChanged signal
# as a workaround for pre 2.26, we will wait a second - maybe
# SessionIdleChanged signal kicks in
def dispatch_active_changed(idle_state):
if not self.idle_was_there:
self.emit('idle-changed', idle_state)
self.idle_was_there = False
gobject.timeout_add_seconds(1, dispatch_active_changed, idle_state)
else:
# dispatch idle status change to interested parties
self.idle_was_there = True
self.emit('idle-changed', idle_state)
elif member == "Lock":
# in case of lock, lock signal will be sent first, followed by
# ActiveChanged and SessionIdle signals
logger.debug("Screen Lock Requested")
self.screen_locked = True
return | python | def bus_inspector(self, bus, message):
"""
Inspect the bus for screensaver messages of interest
"""
# We only care about stuff on this interface. We did filter
# for it above, but even so we still hear from ourselves
# (hamster messages).
if message.get_interface() != self.screensaver_uri:
return True
member = message.get_member()
if member in ("SessionIdleChanged", "ActiveChanged"):
logger.debug("%s -> %s" % (member, message.get_args_list()))
idle_state = message.get_args_list()[0]
if idle_state:
self.idle_from = dt.datetime.now()
# from gnome screensaver 2.24 to 2.28 they have switched
# configuration keys and signal types.
# luckily we can determine key by signal type
if member == "SessionIdleChanged":
delay_key = "/apps/gnome-screensaver/idle_delay"
else:
delay_key = "/desktop/gnome/session/idle_delay"
client = gconf.Client.get_default()
self.timeout_minutes = client.get_int(delay_key)
else:
self.screen_locked = False
self.idle_from = None
if member == "ActiveChanged":
# ActiveChanged comes before SessionIdleChanged signal
# as a workaround for pre 2.26, we will wait a second - maybe
# SessionIdleChanged signal kicks in
def dispatch_active_changed(idle_state):
if not self.idle_was_there:
self.emit('idle-changed', idle_state)
self.idle_was_there = False
gobject.timeout_add_seconds(1, dispatch_active_changed, idle_state)
else:
# dispatch idle status change to interested parties
self.idle_was_there = True
self.emit('idle-changed', idle_state)
elif member == "Lock":
# in case of lock, lock signal will be sent first, followed by
# ActiveChanged and SessionIdle signals
logger.debug("Screen Lock Requested")
self.screen_locked = True
return | [
"def",
"bus_inspector",
"(",
"self",
",",
"bus",
",",
"message",
")",
":",
"# We only care about stuff on this interface. We did filter",
"# for it above, but even so we still hear from ourselves",
"# (hamster messages).",
"if",
"message",
".",
"get_interface",
"(",
")",
"!=",... | Inspect the bus for screensaver messages of interest | [
"Inspect",
"the",
"bus",
"for",
"screensaver",
"messages",
"of",
"interest"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/idle.py#L77-L134 | train | 226,854 |
projecthamster/hamster | src/hamster/lib/i18n.py | C_ | def C_(ctx, s):
"""Provide qualified translatable strings via context.
Taken from gnome-games.
"""
translated = gettext.gettext('%s\x04%s' % (ctx, s))
if '\x04' in translated:
# no translation found, return input string
return s
return translated | python | def C_(ctx, s):
"""Provide qualified translatable strings via context.
Taken from gnome-games.
"""
translated = gettext.gettext('%s\x04%s' % (ctx, s))
if '\x04' in translated:
# no translation found, return input string
return s
return translated | [
"def",
"C_",
"(",
"ctx",
",",
"s",
")",
":",
"translated",
"=",
"gettext",
".",
"gettext",
"(",
"'%s\\x04%s'",
"%",
"(",
"ctx",
",",
"s",
")",
")",
"if",
"'\\x04'",
"in",
"translated",
":",
"# no translation found, return input string",
"return",
"s",
"ret... | Provide qualified translatable strings via context.
Taken from gnome-games. | [
"Provide",
"qualified",
"translatable",
"strings",
"via",
"context",
".",
"Taken",
"from",
"gnome",
"-",
"games",
"."
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/i18n.py#L34-L42 | train | 226,855 |
projecthamster/hamster | wafadmin/Scripting.py | clean | def clean(bld):
'''removes the build files'''
try:
proj=Environment.Environment(Options.lockfile)
except IOError:
raise Utils.WafError('Nothing to clean (project not configured)')
bld.load_dirs(proj[SRCDIR],proj[BLDDIR])
bld.load_envs()
bld.is_install=0
bld.add_subdirs([os.path.split(Utils.g_module.root_path)[0]])
try:
bld.clean()
finally:
bld.save() | python | def clean(bld):
'''removes the build files'''
try:
proj=Environment.Environment(Options.lockfile)
except IOError:
raise Utils.WafError('Nothing to clean (project not configured)')
bld.load_dirs(proj[SRCDIR],proj[BLDDIR])
bld.load_envs()
bld.is_install=0
bld.add_subdirs([os.path.split(Utils.g_module.root_path)[0]])
try:
bld.clean()
finally:
bld.save() | [
"def",
"clean",
"(",
"bld",
")",
":",
"try",
":",
"proj",
"=",
"Environment",
".",
"Environment",
"(",
"Options",
".",
"lockfile",
")",
"except",
"IOError",
":",
"raise",
"Utils",
".",
"WafError",
"(",
"'Nothing to clean (project not configured)'",
")",
"bld",... | removes the build files | [
"removes",
"the",
"build",
"files"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/wafadmin/Scripting.py#L188-L201 | train | 226,856 |
projecthamster/hamster | wafadmin/Scripting.py | install | def install(bld):
'''installs the build files'''
bld=check_configured(bld)
Options.commands['install']=True
Options.commands['uninstall']=False
Options.is_install=True
bld.is_install=INSTALL
build_impl(bld)
bld.install() | python | def install(bld):
'''installs the build files'''
bld=check_configured(bld)
Options.commands['install']=True
Options.commands['uninstall']=False
Options.is_install=True
bld.is_install=INSTALL
build_impl(bld)
bld.install() | [
"def",
"install",
"(",
"bld",
")",
":",
"bld",
"=",
"check_configured",
"(",
"bld",
")",
"Options",
".",
"commands",
"[",
"'install'",
"]",
"=",
"True",
"Options",
".",
"commands",
"[",
"'uninstall'",
"]",
"=",
"False",
"Options",
".",
"is_install",
"=",... | installs the build files | [
"installs",
"the",
"build",
"files"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/wafadmin/Scripting.py#L248-L256 | train | 226,857 |
projecthamster/hamster | wafadmin/Scripting.py | uninstall | def uninstall(bld):
'''removes the installed files'''
Options.commands['install']=False
Options.commands['uninstall']=True
Options.is_install=True
bld.is_install=UNINSTALL
try:
def runnable_status(self):
return SKIP_ME
setattr(Task.Task,'runnable_status_back',Task.Task.runnable_status)
setattr(Task.Task,'runnable_status',runnable_status)
build_impl(bld)
bld.install()
finally:
setattr(Task.Task,'runnable_status',Task.Task.runnable_status_back) | python | def uninstall(bld):
'''removes the installed files'''
Options.commands['install']=False
Options.commands['uninstall']=True
Options.is_install=True
bld.is_install=UNINSTALL
try:
def runnable_status(self):
return SKIP_ME
setattr(Task.Task,'runnable_status_back',Task.Task.runnable_status)
setattr(Task.Task,'runnable_status',runnable_status)
build_impl(bld)
bld.install()
finally:
setattr(Task.Task,'runnable_status',Task.Task.runnable_status_back) | [
"def",
"uninstall",
"(",
"bld",
")",
":",
"Options",
".",
"commands",
"[",
"'install'",
"]",
"=",
"False",
"Options",
".",
"commands",
"[",
"'uninstall'",
"]",
"=",
"True",
"Options",
".",
"is_install",
"=",
"True",
"bld",
".",
"is_install",
"=",
"UNINST... | removes the installed files | [
"removes",
"the",
"installed",
"files"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/wafadmin/Scripting.py#L257-L271 | train | 226,858 |
projecthamster/hamster | wafadmin/Scripting.py | distclean | def distclean(ctx=None):
'''removes the build directory'''
global commands
lst=os.listdir('.')
for f in lst:
if f==Options.lockfile:
try:
proj=Environment.Environment(f)
except:
Logs.warn('could not read %r'%f)
continue
try:
shutil.rmtree(proj[BLDDIR])
except IOError:
pass
except OSError,e:
if e.errno!=errno.ENOENT:
Logs.warn('project %r cannot be removed'%proj[BLDDIR])
try:
os.remove(f)
except OSError,e:
if e.errno!=errno.ENOENT:
Logs.warn('file %r cannot be removed'%f)
if not commands and f.startswith('.waf'):
shutil.rmtree(f,ignore_errors=True) | python | def distclean(ctx=None):
'''removes the build directory'''
global commands
lst=os.listdir('.')
for f in lst:
if f==Options.lockfile:
try:
proj=Environment.Environment(f)
except:
Logs.warn('could not read %r'%f)
continue
try:
shutil.rmtree(proj[BLDDIR])
except IOError:
pass
except OSError,e:
if e.errno!=errno.ENOENT:
Logs.warn('project %r cannot be removed'%proj[BLDDIR])
try:
os.remove(f)
except OSError,e:
if e.errno!=errno.ENOENT:
Logs.warn('file %r cannot be removed'%f)
if not commands and f.startswith('.waf'):
shutil.rmtree(f,ignore_errors=True) | [
"def",
"distclean",
"(",
"ctx",
"=",
"None",
")",
":",
"global",
"commands",
"lst",
"=",
"os",
".",
"listdir",
"(",
"'.'",
")",
"for",
"f",
"in",
"lst",
":",
"if",
"f",
"==",
"Options",
".",
"lockfile",
":",
"try",
":",
"proj",
"=",
"Environment",
... | removes the build directory | [
"removes",
"the",
"build",
"directory"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/wafadmin/Scripting.py#L318-L342 | train | 226,859 |
projecthamster/hamster | wafadmin/Scripting.py | dist | def dist(appname='',version=''):
'''makes a tarball for redistributing the sources'''
import tarfile
if not appname:appname=Utils.g_module.APPNAME
if not version:version=Utils.g_module.VERSION
tmp_folder=appname+'-'+version
if g_gz in['gz','bz2']:
arch_name=tmp_folder+'.tar.'+g_gz
else:
arch_name=tmp_folder+'.'+'zip'
try:
shutil.rmtree(tmp_folder)
except(OSError,IOError):
pass
try:
os.remove(arch_name)
except(OSError,IOError):
pass
blddir=getattr(Utils.g_module,BLDDIR,None)
if not blddir:
blddir=getattr(Utils.g_module,'out',None)
copytree('.',tmp_folder,blddir)
dist_hook=getattr(Utils.g_module,'dist_hook',None)
if dist_hook:
back=os.getcwd()
os.chdir(tmp_folder)
try:
dist_hook()
finally:
os.chdir(back)
if g_gz in['gz','bz2']:
tar=tarfile.open(arch_name,'w:'+g_gz)
tar.add(tmp_folder)
tar.close()
else:
Utils.zip_folder(tmp_folder,arch_name,tmp_folder)
try:from hashlib import sha1 as sha
except ImportError:from sha import sha
try:
digest=" (sha=%r)"%sha(Utils.readf(arch_name)).hexdigest()
except:
digest=''
info('New archive created: %s%s'%(arch_name,digest))
if os.path.exists(tmp_folder):shutil.rmtree(tmp_folder)
return arch_name | python | def dist(appname='',version=''):
'''makes a tarball for redistributing the sources'''
import tarfile
if not appname:appname=Utils.g_module.APPNAME
if not version:version=Utils.g_module.VERSION
tmp_folder=appname+'-'+version
if g_gz in['gz','bz2']:
arch_name=tmp_folder+'.tar.'+g_gz
else:
arch_name=tmp_folder+'.'+'zip'
try:
shutil.rmtree(tmp_folder)
except(OSError,IOError):
pass
try:
os.remove(arch_name)
except(OSError,IOError):
pass
blddir=getattr(Utils.g_module,BLDDIR,None)
if not blddir:
blddir=getattr(Utils.g_module,'out',None)
copytree('.',tmp_folder,blddir)
dist_hook=getattr(Utils.g_module,'dist_hook',None)
if dist_hook:
back=os.getcwd()
os.chdir(tmp_folder)
try:
dist_hook()
finally:
os.chdir(back)
if g_gz in['gz','bz2']:
tar=tarfile.open(arch_name,'w:'+g_gz)
tar.add(tmp_folder)
tar.close()
else:
Utils.zip_folder(tmp_folder,arch_name,tmp_folder)
try:from hashlib import sha1 as sha
except ImportError:from sha import sha
try:
digest=" (sha=%r)"%sha(Utils.readf(arch_name)).hexdigest()
except:
digest=''
info('New archive created: %s%s'%(arch_name,digest))
if os.path.exists(tmp_folder):shutil.rmtree(tmp_folder)
return arch_name | [
"def",
"dist",
"(",
"appname",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"import",
"tarfile",
"if",
"not",
"appname",
":",
"appname",
"=",
"Utils",
".",
"g_module",
".",
"APPNAME",
"if",
"not",
"version",
":",
"version",
"=",
"Utils",
".",
"g_m... | makes a tarball for redistributing the sources | [
"makes",
"a",
"tarball",
"for",
"redistributing",
"the",
"sources"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/wafadmin/Scripting.py#L343-L387 | train | 226,860 |
projecthamster/hamster | src/hamster/widgets/reportchooserdialog.py | ReportChooserDialog.show | def show(self, start_date, end_date):
"""setting suggested name to something readable, replace backslashes
with dots so the name is valid in linux"""
# title in the report file name
vars = {"title": _("Time track"),
"start": start_date.strftime("%x").replace("/", "."),
"end": end_date.strftime("%x").replace("/", ".")}
if start_date != end_date:
filename = "%(title)s, %(start)s - %(end)s.html" % vars
else:
filename = "%(title)s, %(start)s.html" % vars
self.dialog.set_current_name(filename)
response = self.dialog.run()
if response != gtk.ResponseType.OK:
self.emit("report-chooser-closed")
self.dialog.destroy()
self.dialog = None
else:
self.on_save_button_clicked() | python | def show(self, start_date, end_date):
"""setting suggested name to something readable, replace backslashes
with dots so the name is valid in linux"""
# title in the report file name
vars = {"title": _("Time track"),
"start": start_date.strftime("%x").replace("/", "."),
"end": end_date.strftime("%x").replace("/", ".")}
if start_date != end_date:
filename = "%(title)s, %(start)s - %(end)s.html" % vars
else:
filename = "%(title)s, %(start)s.html" % vars
self.dialog.set_current_name(filename)
response = self.dialog.run()
if response != gtk.ResponseType.OK:
self.emit("report-chooser-closed")
self.dialog.destroy()
self.dialog = None
else:
self.on_save_button_clicked() | [
"def",
"show",
"(",
"self",
",",
"start_date",
",",
"end_date",
")",
":",
"# title in the report file name",
"vars",
"=",
"{",
"\"title\"",
":",
"_",
"(",
"\"Time track\"",
")",
",",
"\"start\"",
":",
"start_date",
".",
"strftime",
"(",
"\"%x\"",
")",
".",
... | setting suggested name to something readable, replace backslashes
with dots so the name is valid in linux | [
"setting",
"suggested",
"name",
"to",
"something",
"readable",
"replace",
"backslashes",
"with",
"dots",
"so",
"the",
"name",
"is",
"valid",
"in",
"linux"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/widgets/reportchooserdialog.py#L90-L112 | train | 226,861 |
projecthamster/hamster | src/hamster/lib/pytweener.py | Tweener.kill_tweens | def kill_tweens(self, obj = None):
"""Stop tweening an object, without completing the motion or firing the
on_complete"""
if obj is not None:
try:
del self.current_tweens[obj]
except:
pass
else:
self.current_tweens = collections.defaultdict(set) | python | def kill_tweens(self, obj = None):
"""Stop tweening an object, without completing the motion or firing the
on_complete"""
if obj is not None:
try:
del self.current_tweens[obj]
except:
pass
else:
self.current_tweens = collections.defaultdict(set) | [
"def",
"kill_tweens",
"(",
"self",
",",
"obj",
"=",
"None",
")",
":",
"if",
"obj",
"is",
"not",
"None",
":",
"try",
":",
"del",
"self",
".",
"current_tweens",
"[",
"obj",
"]",
"except",
":",
"pass",
"else",
":",
"self",
".",
"current_tweens",
"=",
... | Stop tweening an object, without completing the motion or firing the
on_complete | [
"Stop",
"tweening",
"an",
"object",
"without",
"completing",
"the",
"motion",
"or",
"firing",
"the",
"on_complete"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/pytweener.py#L72-L81 | train | 226,862 |
projecthamster/hamster | src/hamster/lib/pytweener.py | Tweener.remove_tween | def remove_tween(self, tween):
""""remove given tween without completing the motion or firing the on_complete"""
if tween.target in self.current_tweens and tween in self.current_tweens[tween.target]:
self.current_tweens[tween.target].remove(tween)
if not self.current_tweens[tween.target]:
del self.current_tweens[tween.target] | python | def remove_tween(self, tween):
""""remove given tween without completing the motion or firing the on_complete"""
if tween.target in self.current_tweens and tween in self.current_tweens[tween.target]:
self.current_tweens[tween.target].remove(tween)
if not self.current_tweens[tween.target]:
del self.current_tweens[tween.target] | [
"def",
"remove_tween",
"(",
"self",
",",
"tween",
")",
":",
"if",
"tween",
".",
"target",
"in",
"self",
".",
"current_tweens",
"and",
"tween",
"in",
"self",
".",
"current_tweens",
"[",
"tween",
".",
"target",
"]",
":",
"self",
".",
"current_tweens",
"[",... | remove given tween without completing the motion or firing the on_complete | [
"remove",
"given",
"tween",
"without",
"completing",
"the",
"motion",
"or",
"firing",
"the",
"on_complete"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/pytweener.py#L83-L88 | train | 226,863 |
projecthamster/hamster | src/hamster/lib/pytweener.py | Tweener.finish | def finish(self):
"""jump the the last frame of all tweens"""
for obj in self.current_tweens:
for tween in self.current_tweens[obj]:
tween.finish()
self.current_tweens = {} | python | def finish(self):
"""jump the the last frame of all tweens"""
for obj in self.current_tweens:
for tween in self.current_tweens[obj]:
tween.finish()
self.current_tweens = {} | [
"def",
"finish",
"(",
"self",
")",
":",
"for",
"obj",
"in",
"self",
".",
"current_tweens",
":",
"for",
"tween",
"in",
"self",
".",
"current_tweens",
"[",
"obj",
"]",
":",
"tween",
".",
"finish",
"(",
")",
"self",
".",
"current_tweens",
"=",
"{",
"}"
... | jump the the last frame of all tweens | [
"jump",
"the",
"the",
"last",
"frame",
"of",
"all",
"tweens"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/pytweener.py#L90-L95 | train | 226,864 |
projecthamster/hamster | src/hamster/lib/pytweener.py | Tweener.update | def update(self, delta_seconds):
"""update tweeners. delta_seconds is time in seconds since last frame"""
for obj in tuple(self.current_tweens):
for tween in tuple(self.current_tweens[obj]):
done = tween.update(delta_seconds)
if done:
self.current_tweens[obj].remove(tween)
if tween.on_complete: tween.on_complete(tween.target)
if not self.current_tweens[obj]:
del self.current_tweens[obj]
return self.current_tweens | python | def update(self, delta_seconds):
"""update tweeners. delta_seconds is time in seconds since last frame"""
for obj in tuple(self.current_tweens):
for tween in tuple(self.current_tweens[obj]):
done = tween.update(delta_seconds)
if done:
self.current_tweens[obj].remove(tween)
if tween.on_complete: tween.on_complete(tween.target)
if not self.current_tweens[obj]:
del self.current_tweens[obj]
return self.current_tweens | [
"def",
"update",
"(",
"self",
",",
"delta_seconds",
")",
":",
"for",
"obj",
"in",
"tuple",
"(",
"self",
".",
"current_tweens",
")",
":",
"for",
"tween",
"in",
"tuple",
"(",
"self",
".",
"current_tweens",
"[",
"obj",
"]",
")",
":",
"done",
"=",
"tween... | update tweeners. delta_seconds is time in seconds since last frame | [
"update",
"tweeners",
".",
"delta_seconds",
"is",
"time",
"in",
"seconds",
"since",
"last",
"frame"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/pytweener.py#L97-L110 | train | 226,865 |
projecthamster/hamster | src/hamster/lib/pytweener.py | Tween.update | def update(self, ptime):
"""Update tween with the time since the last frame"""
delta = self.delta + ptime
total_duration = self.delay + self.duration
if delta > total_duration:
delta = total_duration
if delta < self.delay:
pass
elif delta == total_duration:
for key, tweenable in self.tweenables:
setattr(self.target, key, tweenable.target_value)
else:
fraction = self.ease((delta - self.delay) / (total_duration - self.delay))
for key, tweenable in self.tweenables:
res = tweenable.update(fraction)
if isinstance(res, float) and self.round:
res = int(res)
setattr(self.target, key, res)
if delta == total_duration or len(self.tweenables) == 0:
self.complete = True
self.delta = delta
if self.on_update:
self.on_update(self.target)
return self.complete | python | def update(self, ptime):
"""Update tween with the time since the last frame"""
delta = self.delta + ptime
total_duration = self.delay + self.duration
if delta > total_duration:
delta = total_duration
if delta < self.delay:
pass
elif delta == total_duration:
for key, tweenable in self.tweenables:
setattr(self.target, key, tweenable.target_value)
else:
fraction = self.ease((delta - self.delay) / (total_duration - self.delay))
for key, tweenable in self.tweenables:
res = tweenable.update(fraction)
if isinstance(res, float) and self.round:
res = int(res)
setattr(self.target, key, res)
if delta == total_duration or len(self.tweenables) == 0:
self.complete = True
self.delta = delta
if self.on_update:
self.on_update(self.target)
return self.complete | [
"def",
"update",
"(",
"self",
",",
"ptime",
")",
":",
"delta",
"=",
"self",
".",
"delta",
"+",
"ptime",
"total_duration",
"=",
"self",
".",
"delay",
"+",
"self",
".",
"duration",
"if",
"delta",
">",
"total_duration",
":",
"delta",
"=",
"total_duration",
... | Update tween with the time since the last frame | [
"Update",
"tween",
"with",
"the",
"time",
"since",
"the",
"last",
"frame"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/pytweener.py#L154-L184 | train | 226,866 |
projecthamster/hamster | src/hamster/overview.py | StackedBar.set_items | def set_items(self, items):
"""expects a list of key, value to work with"""
res = []
max_value = max(sum((rec[1] for rec in items)), 1)
for key, val in items:
res.append((key, val, val * 1.0 / max_value))
self._items = res | python | def set_items(self, items):
"""expects a list of key, value to work with"""
res = []
max_value = max(sum((rec[1] for rec in items)), 1)
for key, val in items:
res.append((key, val, val * 1.0 / max_value))
self._items = res | [
"def",
"set_items",
"(",
"self",
",",
"items",
")",
":",
"res",
"=",
"[",
"]",
"max_value",
"=",
"max",
"(",
"sum",
"(",
"(",
"rec",
"[",
"1",
"]",
"for",
"rec",
"in",
"items",
")",
")",
",",
"1",
")",
"for",
"key",
",",
"val",
"in",
"items",... | expects a list of key, value to work with | [
"expects",
"a",
"list",
"of",
"key",
"value",
"to",
"work",
"with"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/overview.py#L138-L144 | train | 226,867 |
projecthamster/hamster | src/hamster/overview.py | HorizontalBarChart.set_values | def set_values(self, values):
"""expects a list of 2-tuples"""
self.values = values
self.height = len(self.values) * 14
self._max = max(rec[1] for rec in values) if values else dt.timedelta(0) | python | def set_values(self, values):
"""expects a list of 2-tuples"""
self.values = values
self.height = len(self.values) * 14
self._max = max(rec[1] for rec in values) if values else dt.timedelta(0) | [
"def",
"set_values",
"(",
"self",
",",
"values",
")",
":",
"self",
".",
"values",
"=",
"values",
"self",
".",
"height",
"=",
"len",
"(",
"self",
".",
"values",
")",
"*",
"14",
"self",
".",
"_max",
"=",
"max",
"(",
"rec",
"[",
"1",
"]",
"for",
"... | expects a list of 2-tuples | [
"expects",
"a",
"list",
"of",
"2",
"-",
"tuples"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/overview.py#L221-L225 | train | 226,868 |
projecthamster/hamster | src/hamster/lib/stuff.py | datetime_to_hamsterday | def datetime_to_hamsterday(civil_date_time):
"""Return the hamster day corresponding to a given civil datetime.
The hamster day start is taken into account.
"""
# work around cyclic imports
from hamster.lib.configuration import conf
if civil_date_time.time() < conf.day_start:
# early morning, between midnight and day_start
# => the hamster day is the previous civil day
hamster_date_time = civil_date_time - dt.timedelta(days=1)
else:
hamster_date_time = civil_date_time
# return only the date
return hamster_date_time.date() | python | def datetime_to_hamsterday(civil_date_time):
"""Return the hamster day corresponding to a given civil datetime.
The hamster day start is taken into account.
"""
# work around cyclic imports
from hamster.lib.configuration import conf
if civil_date_time.time() < conf.day_start:
# early morning, between midnight and day_start
# => the hamster day is the previous civil day
hamster_date_time = civil_date_time - dt.timedelta(days=1)
else:
hamster_date_time = civil_date_time
# return only the date
return hamster_date_time.date() | [
"def",
"datetime_to_hamsterday",
"(",
"civil_date_time",
")",
":",
"# work around cyclic imports",
"from",
"hamster",
".",
"lib",
".",
"configuration",
"import",
"conf",
"if",
"civil_date_time",
".",
"time",
"(",
")",
"<",
"conf",
".",
"day_start",
":",
"# early m... | Return the hamster day corresponding to a given civil datetime.
The hamster day start is taken into account. | [
"Return",
"the",
"hamster",
"day",
"corresponding",
"to",
"a",
"given",
"civil",
"datetime",
"."
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/stuff.py#L43-L59 | train | 226,869 |
projecthamster/hamster | src/hamster/lib/stuff.py | hamsterday_time_to_datetime | def hamsterday_time_to_datetime(hamsterday, time):
"""Return the civil datetime corresponding to a given hamster day and time.
The hamster day start is taken into account.
"""
# work around cyclic imports
from hamster.lib.configuration import conf
if time < conf.day_start:
# early morning, between midnight and day_start
# => the hamster day is the previous civil day
civil_date = hamsterday + dt.timedelta(days=1)
else:
civil_date = hamsterday
return dt.datetime.combine(civil_date, time) | python | def hamsterday_time_to_datetime(hamsterday, time):
"""Return the civil datetime corresponding to a given hamster day and time.
The hamster day start is taken into account.
"""
# work around cyclic imports
from hamster.lib.configuration import conf
if time < conf.day_start:
# early morning, between midnight and day_start
# => the hamster day is the previous civil day
civil_date = hamsterday + dt.timedelta(days=1)
else:
civil_date = hamsterday
return dt.datetime.combine(civil_date, time) | [
"def",
"hamsterday_time_to_datetime",
"(",
"hamsterday",
",",
"time",
")",
":",
"# work around cyclic imports",
"from",
"hamster",
".",
"lib",
".",
"configuration",
"import",
"conf",
"if",
"time",
"<",
"conf",
".",
"day_start",
":",
"# early morning, between midnight ... | Return the civil datetime corresponding to a given hamster day and time.
The hamster day start is taken into account. | [
"Return",
"the",
"civil",
"datetime",
"corresponding",
"to",
"a",
"given",
"hamster",
"day",
"and",
"time",
"."
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/stuff.py#L67-L82 | train | 226,870 |
projecthamster/hamster | src/hamster/lib/stuff.py | format_duration | def format_duration(minutes, human = True):
"""formats duration in a human readable format.
accepts either minutes or timedelta"""
if isinstance(minutes, dt.timedelta):
minutes = duration_minutes(minutes)
if not minutes:
if human:
return ""
else:
return "00:00"
if minutes < 0:
# format_duration did not work for negative values anyway
# return a warning
return "NEGATIVE"
hours = minutes / 60
minutes = minutes % 60
formatted_duration = ""
if human:
if minutes % 60 == 0:
# duration in round hours
formatted_duration += ("%dh") % (hours)
elif hours == 0:
# duration less than hour
formatted_duration += ("%dmin") % (minutes % 60.0)
else:
# x hours, y minutes
formatted_duration += ("%dh %dmin") % (hours, minutes % 60)
else:
formatted_duration += "%02d:%02d" % (hours, minutes)
return formatted_duration | python | def format_duration(minutes, human = True):
"""formats duration in a human readable format.
accepts either minutes or timedelta"""
if isinstance(minutes, dt.timedelta):
minutes = duration_minutes(minutes)
if not minutes:
if human:
return ""
else:
return "00:00"
if minutes < 0:
# format_duration did not work for negative values anyway
# return a warning
return "NEGATIVE"
hours = minutes / 60
minutes = minutes % 60
formatted_duration = ""
if human:
if minutes % 60 == 0:
# duration in round hours
formatted_duration += ("%dh") % (hours)
elif hours == 0:
# duration less than hour
formatted_duration += ("%dmin") % (minutes % 60.0)
else:
# x hours, y minutes
formatted_duration += ("%dh %dmin") % (hours, minutes % 60)
else:
formatted_duration += "%02d:%02d" % (hours, minutes)
return formatted_duration | [
"def",
"format_duration",
"(",
"minutes",
",",
"human",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"minutes",
",",
"dt",
".",
"timedelta",
")",
":",
"minutes",
"=",
"duration_minutes",
"(",
"minutes",
")",
"if",
"not",
"minutes",
":",
"if",
"human",... | formats duration in a human readable format.
accepts either minutes or timedelta | [
"formats",
"duration",
"in",
"a",
"human",
"readable",
"format",
".",
"accepts",
"either",
"minutes",
"or",
"timedelta"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/stuff.py#L85-L121 | train | 226,871 |
projecthamster/hamster | src/hamster/lib/stuff.py | duration_minutes | def duration_minutes(duration):
"""returns minutes from duration, otherwise we keep bashing in same math"""
if isinstance(duration, list):
res = dt.timedelta()
for entry in duration:
res += entry
return duration_minutes(res)
elif isinstance(duration, dt.timedelta):
return duration.total_seconds() / 60
else:
return duration | python | def duration_minutes(duration):
"""returns minutes from duration, otherwise we keep bashing in same math"""
if isinstance(duration, list):
res = dt.timedelta()
for entry in duration:
res += entry
return duration_minutes(res)
elif isinstance(duration, dt.timedelta):
return duration.total_seconds() / 60
else:
return duration | [
"def",
"duration_minutes",
"(",
"duration",
")",
":",
"if",
"isinstance",
"(",
"duration",
",",
"list",
")",
":",
"res",
"=",
"dt",
".",
"timedelta",
"(",
")",
"for",
"entry",
"in",
"duration",
":",
"res",
"+=",
"entry",
"return",
"duration_minutes",
"("... | returns minutes from duration, otherwise we keep bashing in same math | [
"returns",
"minutes",
"from",
"duration",
"otherwise",
"we",
"keep",
"bashing",
"in",
"same",
"math"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/stuff.py#L172-L183 | train | 226,872 |
projecthamster/hamster | src/hamster/lib/stuff.py | locale_first_weekday | def locale_first_weekday():
"""figure if week starts on monday or sunday"""
first_weekday = 6 #by default settle on monday
try:
process = os.popen("locale first_weekday week-1stday")
week_offset, week_start = process.read().split('\n')[:2]
process.close()
week_start = dt.date(*time.strptime(week_start, "%Y%m%d")[:3])
week_offset = dt.timedelta(int(week_offset) - 1)
beginning = week_start + week_offset
first_weekday = int(beginning.strftime("%w"))
except:
logger.warn("WARNING - Failed to get first weekday from locale")
return first_weekday | python | def locale_first_weekday():
"""figure if week starts on monday or sunday"""
first_weekday = 6 #by default settle on monday
try:
process = os.popen("locale first_weekday week-1stday")
week_offset, week_start = process.read().split('\n')[:2]
process.close()
week_start = dt.date(*time.strptime(week_start, "%Y%m%d")[:3])
week_offset = dt.timedelta(int(week_offset) - 1)
beginning = week_start + week_offset
first_weekday = int(beginning.strftime("%w"))
except:
logger.warn("WARNING - Failed to get first weekday from locale")
return first_weekday | [
"def",
"locale_first_weekday",
"(",
")",
":",
"first_weekday",
"=",
"6",
"#by default settle on monday",
"try",
":",
"process",
"=",
"os",
".",
"popen",
"(",
"\"locale first_weekday week-1stday\"",
")",
"week_offset",
",",
"week_start",
"=",
"process",
".",
"read",
... | figure if week starts on monday or sunday | [
"figure",
"if",
"week",
"starts",
"on",
"monday",
"or",
"sunday"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/stuff.py#L206-L221 | train | 226,873 |
projecthamster/hamster | src/hamster/lib/stuff.py | totals | def totals(iter, keyfunc, sumfunc):
"""groups items by field described in keyfunc and counts totals using value
from sumfunc
"""
data = sorted(iter, key=keyfunc)
res = {}
for k, group in groupby(data, keyfunc):
res[k] = sum([sumfunc(entry) for entry in group])
return res | python | def totals(iter, keyfunc, sumfunc):
"""groups items by field described in keyfunc and counts totals using value
from sumfunc
"""
data = sorted(iter, key=keyfunc)
res = {}
for k, group in groupby(data, keyfunc):
res[k] = sum([sumfunc(entry) for entry in group])
return res | [
"def",
"totals",
"(",
"iter",
",",
"keyfunc",
",",
"sumfunc",
")",
":",
"data",
"=",
"sorted",
"(",
"iter",
",",
"key",
"=",
"keyfunc",
")",
"res",
"=",
"{",
"}",
"for",
"k",
",",
"group",
"in",
"groupby",
"(",
"data",
",",
"keyfunc",
")",
":",
... | groups items by field described in keyfunc and counts totals using value
from sumfunc | [
"groups",
"items",
"by",
"field",
"described",
"in",
"keyfunc",
"and",
"counts",
"totals",
"using",
"value",
"from",
"sumfunc"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/stuff.py#L224-L234 | train | 226,874 |
projecthamster/hamster | src/hamster/lib/stuff.py | dateDict | def dateDict(date, prefix = ""):
"""converts date into dictionary, having prefix for all the keys"""
res = {}
res[prefix+"a"] = date.strftime("%a")
res[prefix+"A"] = date.strftime("%A")
res[prefix+"b"] = date.strftime("%b")
res[prefix+"B"] = date.strftime("%B")
res[prefix+"c"] = date.strftime("%c")
res[prefix+"d"] = date.strftime("%d")
res[prefix+"H"] = date.strftime("%H")
res[prefix+"I"] = date.strftime("%I")
res[prefix+"j"] = date.strftime("%j")
res[prefix+"m"] = date.strftime("%m")
res[prefix+"M"] = date.strftime("%M")
res[prefix+"p"] = date.strftime("%p")
res[prefix+"S"] = date.strftime("%S")
res[prefix+"U"] = date.strftime("%U")
res[prefix+"w"] = date.strftime("%w")
res[prefix+"W"] = date.strftime("%W")
res[prefix+"x"] = date.strftime("%x")
res[prefix+"X"] = date.strftime("%X")
res[prefix+"y"] = date.strftime("%y")
res[prefix+"Y"] = date.strftime("%Y")
res[prefix+"Z"] = date.strftime("%Z")
for i, value in res.items():
res[i] = locale_to_utf8(value)
return res | python | def dateDict(date, prefix = ""):
"""converts date into dictionary, having prefix for all the keys"""
res = {}
res[prefix+"a"] = date.strftime("%a")
res[prefix+"A"] = date.strftime("%A")
res[prefix+"b"] = date.strftime("%b")
res[prefix+"B"] = date.strftime("%B")
res[prefix+"c"] = date.strftime("%c")
res[prefix+"d"] = date.strftime("%d")
res[prefix+"H"] = date.strftime("%H")
res[prefix+"I"] = date.strftime("%I")
res[prefix+"j"] = date.strftime("%j")
res[prefix+"m"] = date.strftime("%m")
res[prefix+"M"] = date.strftime("%M")
res[prefix+"p"] = date.strftime("%p")
res[prefix+"S"] = date.strftime("%S")
res[prefix+"U"] = date.strftime("%U")
res[prefix+"w"] = date.strftime("%w")
res[prefix+"W"] = date.strftime("%W")
res[prefix+"x"] = date.strftime("%x")
res[prefix+"X"] = date.strftime("%X")
res[prefix+"y"] = date.strftime("%y")
res[prefix+"Y"] = date.strftime("%Y")
res[prefix+"Z"] = date.strftime("%Z")
for i, value in res.items():
res[i] = locale_to_utf8(value)
return res | [
"def",
"dateDict",
"(",
"date",
",",
"prefix",
"=",
"\"\"",
")",
":",
"res",
"=",
"{",
"}",
"res",
"[",
"prefix",
"+",
"\"a\"",
"]",
"=",
"date",
".",
"strftime",
"(",
"\"%a\"",
")",
"res",
"[",
"prefix",
"+",
"\"A\"",
"]",
"=",
"date",
".",
"s... | converts date into dictionary, having prefix for all the keys | [
"converts",
"date",
"into",
"dictionary",
"having",
"prefix",
"for",
"all",
"the",
"keys"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/stuff.py#L237-L266 | train | 226,875 |
projecthamster/hamster | src/hamster/storage/db.py | Storage.__get_tag_ids | def __get_tag_ids(self, tags):
"""look up tags by their name. create if not found"""
db_tags = self.fetchall("select * from tags where name in (%s)"
% ",".join(["?"] * len(tags)), tags) # bit of magic here - using sqlites bind variables
changes = False
# check if any of tags needs resurrection
set_complete = [str(tag["id"]) for tag in db_tags if tag["autocomplete"] == "false"]
if set_complete:
changes = True
self.execute("update tags set autocomplete='true' where id in (%s)" % ", ".join(set_complete))
found_tags = [tag["name"] for tag in db_tags]
add = set(tags) - set(found_tags)
if add:
statement = "insert into tags(name) values(?)"
self.execute([statement] * len(add), [(tag,) for tag in add])
return self.__get_tag_ids(tags)[0], True # all done, recurse
else:
return db_tags, changes | python | def __get_tag_ids(self, tags):
"""look up tags by their name. create if not found"""
db_tags = self.fetchall("select * from tags where name in (%s)"
% ",".join(["?"] * len(tags)), tags) # bit of magic here - using sqlites bind variables
changes = False
# check if any of tags needs resurrection
set_complete = [str(tag["id"]) for tag in db_tags if tag["autocomplete"] == "false"]
if set_complete:
changes = True
self.execute("update tags set autocomplete='true' where id in (%s)" % ", ".join(set_complete))
found_tags = [tag["name"] for tag in db_tags]
add = set(tags) - set(found_tags)
if add:
statement = "insert into tags(name) values(?)"
self.execute([statement] * len(add), [(tag,) for tag in add])
return self.__get_tag_ids(tags)[0], True # all done, recurse
else:
return db_tags, changes | [
"def",
"__get_tag_ids",
"(",
"self",
",",
"tags",
")",
":",
"db_tags",
"=",
"self",
".",
"fetchall",
"(",
"\"select * from tags where name in (%s)\"",
"%",
"\",\"",
".",
"join",
"(",
"[",
"\"?\"",
"]",
"*",
"len",
"(",
"tags",
")",
")",
",",
"tags",
")",... | look up tags by their name. create if not found | [
"look",
"up",
"tags",
"by",
"their",
"name",
".",
"create",
"if",
"not",
"found"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L161-L186 | train | 226,876 |
projecthamster/hamster | src/hamster/storage/db.py | Storage.__get_activity_by_name | def __get_activity_by_name(self, name, category_id = None, resurrect = True):
"""get most recent, preferably not deleted activity by it's name"""
if category_id:
query = """
SELECT a.id, a.name, a.deleted, coalesce(b.name, ?) as category
FROM activities a
LEFT JOIN categories b ON category_id = b.id
WHERE lower(a.name) = lower(?)
AND category_id = ?
ORDER BY a.deleted, a.id desc
LIMIT 1
"""
res = self.fetchone(query, (self._unsorted_localized, name, category_id))
else:
query = """
SELECT a.id, a.name, a.deleted, coalesce(b.name, ?) as category
FROM activities a
LEFT JOIN categories b ON category_id = b.id
WHERE lower(a.name) = lower(?)
ORDER BY a.deleted, a.id desc
LIMIT 1
"""
res = self.fetchone(query, (self._unsorted_localized, name, ))
if res:
keys = ('id', 'name', 'deleted', 'category')
res = dict([(key, res[key]) for key in keys])
res['deleted'] = res['deleted'] or False
# if the activity was marked as deleted, resurrect on first call
# and put in the unsorted category
if res['deleted'] and resurrect:
update = """
UPDATE activities
SET deleted = null, category_id = -1
WHERE id = ?
"""
self.execute(update, (res['id'], ))
return res
return None | python | def __get_activity_by_name(self, name, category_id = None, resurrect = True):
"""get most recent, preferably not deleted activity by it's name"""
if category_id:
query = """
SELECT a.id, a.name, a.deleted, coalesce(b.name, ?) as category
FROM activities a
LEFT JOIN categories b ON category_id = b.id
WHERE lower(a.name) = lower(?)
AND category_id = ?
ORDER BY a.deleted, a.id desc
LIMIT 1
"""
res = self.fetchone(query, (self._unsorted_localized, name, category_id))
else:
query = """
SELECT a.id, a.name, a.deleted, coalesce(b.name, ?) as category
FROM activities a
LEFT JOIN categories b ON category_id = b.id
WHERE lower(a.name) = lower(?)
ORDER BY a.deleted, a.id desc
LIMIT 1
"""
res = self.fetchone(query, (self._unsorted_localized, name, ))
if res:
keys = ('id', 'name', 'deleted', 'category')
res = dict([(key, res[key]) for key in keys])
res['deleted'] = res['deleted'] or False
# if the activity was marked as deleted, resurrect on first call
# and put in the unsorted category
if res['deleted'] and resurrect:
update = """
UPDATE activities
SET deleted = null, category_id = -1
WHERE id = ?
"""
self.execute(update, (res['id'], ))
return res
return None | [
"def",
"__get_activity_by_name",
"(",
"self",
",",
"name",
",",
"category_id",
"=",
"None",
",",
"resurrect",
"=",
"True",
")",
":",
"if",
"category_id",
":",
"query",
"=",
"\"\"\"\n SELECT a.id, a.name, a.deleted, coalesce(b.name, ?) as category\n ... | get most recent, preferably not deleted activity by it's name | [
"get",
"most",
"recent",
"preferably",
"not",
"deleted",
"activity",
"by",
"it",
"s",
"name"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L297-L340 | train | 226,877 |
projecthamster/hamster | src/hamster/storage/db.py | Storage.__get_category_id | def __get_category_id(self, name):
"""returns category by it's name"""
query = """
SELECT id from categories
WHERE lower(name) = lower(?)
ORDER BY id desc
LIMIT 1
"""
res = self.fetchone(query, (name, ))
if res:
return res['id']
return None | python | def __get_category_id(self, name):
"""returns category by it's name"""
query = """
SELECT id from categories
WHERE lower(name) = lower(?)
ORDER BY id desc
LIMIT 1
"""
res = self.fetchone(query, (name, ))
if res:
return res['id']
return None | [
"def",
"__get_category_id",
"(",
"self",
",",
"name",
")",
":",
"query",
"=",
"\"\"\"\n SELECT id from categories\n WHERE lower(name) = lower(?)\n ORDER BY id desc\n LIMIT 1\n \"\"\"",
"res",
"=",
"self",
".",... | returns category by it's name | [
"returns",
"category",
"by",
"it",
"s",
"name"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L342-L357 | train | 226,878 |
projecthamster/hamster | src/hamster/storage/db.py | Storage.__group_tags | def __group_tags(self, facts):
"""put the fact back together and move all the unique tags to an array"""
if not facts: return facts #be it None or whatever
grouped_facts = []
for fact_id, fact_tags in itertools.groupby(facts, lambda f: f["id"]):
fact_tags = list(fact_tags)
# first one is as good as the last one
grouped_fact = fact_tags[0]
# we need dict so we can modify it (sqlite.Row is read only)
# in python 2.5, sqlite does not have keys() yet, so we hardcode them (yay!)
keys = ["id", "start_time", "end_time", "description", "name",
"activity_id", "category", "tag"]
grouped_fact = dict([(key, grouped_fact[key]) for key in keys])
grouped_fact["tags"] = [ft["tag"] for ft in fact_tags if ft["tag"]]
grouped_facts.append(grouped_fact)
return grouped_facts | python | def __group_tags(self, facts):
"""put the fact back together and move all the unique tags to an array"""
if not facts: return facts #be it None or whatever
grouped_facts = []
for fact_id, fact_tags in itertools.groupby(facts, lambda f: f["id"]):
fact_tags = list(fact_tags)
# first one is as good as the last one
grouped_fact = fact_tags[0]
# we need dict so we can modify it (sqlite.Row is read only)
# in python 2.5, sqlite does not have keys() yet, so we hardcode them (yay!)
keys = ["id", "start_time", "end_time", "description", "name",
"activity_id", "category", "tag"]
grouped_fact = dict([(key, grouped_fact[key]) for key in keys])
grouped_fact["tags"] = [ft["tag"] for ft in fact_tags if ft["tag"]]
grouped_facts.append(grouped_fact)
return grouped_facts | [
"def",
"__group_tags",
"(",
"self",
",",
"facts",
")",
":",
"if",
"not",
"facts",
":",
"return",
"facts",
"#be it None or whatever",
"grouped_facts",
"=",
"[",
"]",
"for",
"fact_id",
",",
"fact_tags",
"in",
"itertools",
".",
"groupby",
"(",
"facts",
",",
"... | put the fact back together and move all the unique tags to an array | [
"put",
"the",
"fact",
"back",
"together",
"and",
"move",
"all",
"the",
"unique",
"tags",
"to",
"an",
"array"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L379-L398 | train | 226,879 |
projecthamster/hamster | src/hamster/storage/db.py | Storage.__squeeze_in | def __squeeze_in(self, start_time):
""" tries to put task in the given date
if there are conflicts, we will only truncate the ongoing task
and replace it's end part with our activity """
# we are checking if our start time is in the middle of anything
# or maybe there is something after us - so we know to adjust end time
# in the latter case go only few hours ahead. everything else is madness, heh
query = """
SELECT a.*, b.name
FROM facts a
LEFT JOIN activities b on b.id = a.activity_id
WHERE ((start_time < ? and end_time > ?)
OR (start_time > ? and start_time < ? and end_time is null)
OR (start_time > ? and start_time < ?))
ORDER BY start_time
LIMIT 1
"""
fact = self.fetchone(query, (start_time, start_time,
start_time - dt.timedelta(hours = 12),
start_time, start_time,
start_time + dt.timedelta(hours = 12)))
end_time = None
if fact:
if start_time > fact["start_time"]:
#we are in middle of a fact - truncate it to our start
self.execute("UPDATE facts SET end_time=? WHERE id=?",
(start_time, fact["id"]))
else: #otherwise we have found a task that is after us
end_time = fact["start_time"]
return end_time | python | def __squeeze_in(self, start_time):
""" tries to put task in the given date
if there are conflicts, we will only truncate the ongoing task
and replace it's end part with our activity """
# we are checking if our start time is in the middle of anything
# or maybe there is something after us - so we know to adjust end time
# in the latter case go only few hours ahead. everything else is madness, heh
query = """
SELECT a.*, b.name
FROM facts a
LEFT JOIN activities b on b.id = a.activity_id
WHERE ((start_time < ? and end_time > ?)
OR (start_time > ? and start_time < ? and end_time is null)
OR (start_time > ? and start_time < ?))
ORDER BY start_time
LIMIT 1
"""
fact = self.fetchone(query, (start_time, start_time,
start_time - dt.timedelta(hours = 12),
start_time, start_time,
start_time + dt.timedelta(hours = 12)))
end_time = None
if fact:
if start_time > fact["start_time"]:
#we are in middle of a fact - truncate it to our start
self.execute("UPDATE facts SET end_time=? WHERE id=?",
(start_time, fact["id"]))
else: #otherwise we have found a task that is after us
end_time = fact["start_time"]
return end_time | [
"def",
"__squeeze_in",
"(",
"self",
",",
"start_time",
")",
":",
"# we are checking if our start time is in the middle of anything",
"# or maybe there is something after us - so we know to adjust end time",
"# in the latter case go only few hours ahead. everything else is madness, heh",
"query... | tries to put task in the given date
if there are conflicts, we will only truncate the ongoing task
and replace it's end part with our activity | [
"tries",
"to",
"put",
"task",
"in",
"the",
"given",
"date",
"if",
"there",
"are",
"conflicts",
"we",
"will",
"only",
"truncate",
"the",
"ongoing",
"task",
"and",
"replace",
"it",
"s",
"end",
"part",
"with",
"our",
"activity"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L415-L447 | train | 226,880 |
projecthamster/hamster | src/hamster/storage/db.py | Storage.__get_activities | def __get_activities(self, search):
"""returns list of activities for autocomplete,
activity names converted to lowercase"""
query = """
SELECT a.name AS name, b.name AS category
FROM activities a
LEFT JOIN categories b ON coalesce(b.id, -1) = a.category_id
LEFT JOIN facts f ON a.id = f.activity_id
WHERE deleted IS NULL
AND a.search_name LIKE ? ESCAPE '\\'
GROUP BY a.id
ORDER BY max(f.start_time) DESC, lower(a.name)
LIMIT 50
"""
search = search.lower()
search = search.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_')
activities = self.fetchall(query, ('%s%%' % search, ))
return activities | python | def __get_activities(self, search):
"""returns list of activities for autocomplete,
activity names converted to lowercase"""
query = """
SELECT a.name AS name, b.name AS category
FROM activities a
LEFT JOIN categories b ON coalesce(b.id, -1) = a.category_id
LEFT JOIN facts f ON a.id = f.activity_id
WHERE deleted IS NULL
AND a.search_name LIKE ? ESCAPE '\\'
GROUP BY a.id
ORDER BY max(f.start_time) DESC, lower(a.name)
LIMIT 50
"""
search = search.lower()
search = search.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_')
activities = self.fetchall(query, ('%s%%' % search, ))
return activities | [
"def",
"__get_activities",
"(",
"self",
",",
"search",
")",
":",
"query",
"=",
"\"\"\"\n SELECT a.name AS name, b.name AS category\n FROM activities a\n LEFT JOIN categories b ON coalesce(b.id, -1) = a.category_id\n LEFT JOIN fa... | returns list of activities for autocomplete,
activity names converted to lowercase | [
"returns",
"list",
"of",
"activities",
"for",
"autocomplete",
"activity",
"names",
"converted",
"to",
"lowercase"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L760-L779 | train | 226,881 |
projecthamster/hamster | src/hamster/storage/db.py | Storage.__remove_activity | def __remove_activity(self, id):
""" check if we have any facts with this activity and behave accordingly
if there are facts - sets activity to deleted = True
else, just remove it"""
query = "select count(*) as count from facts where activity_id = ?"
bound_facts = self.fetchone(query, (id,))['count']
if bound_facts > 0:
self.execute("UPDATE activities SET deleted = 1 WHERE id = ?", (id,))
else:
self.execute("delete from activities where id = ?", (id,)) | python | def __remove_activity(self, id):
""" check if we have any facts with this activity and behave accordingly
if there are facts - sets activity to deleted = True
else, just remove it"""
query = "select count(*) as count from facts where activity_id = ?"
bound_facts = self.fetchone(query, (id,))['count']
if bound_facts > 0:
self.execute("UPDATE activities SET deleted = 1 WHERE id = ?", (id,))
else:
self.execute("delete from activities where id = ?", (id,)) | [
"def",
"__remove_activity",
"(",
"self",
",",
"id",
")",
":",
"query",
"=",
"\"select count(*) as count from facts where activity_id = ?\"",
"bound_facts",
"=",
"self",
".",
"fetchone",
"(",
"query",
",",
"(",
"id",
",",
")",
")",
"[",
"'count'",
"]",
"if",
"b... | check if we have any facts with this activity and behave accordingly
if there are facts - sets activity to deleted = True
else, just remove it | [
"check",
"if",
"we",
"have",
"any",
"facts",
"with",
"this",
"activity",
"and",
"behave",
"accordingly",
"if",
"there",
"are",
"facts",
"-",
"sets",
"activity",
"to",
"deleted",
"=",
"True",
"else",
"just",
"remove",
"it"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L781-L792 | train | 226,882 |
projecthamster/hamster | src/hamster/storage/db.py | Storage.__remove_category | def __remove_category(self, id):
"""move all activities to unsorted and remove category"""
affected_query = """
SELECT id
FROM facts
WHERE activity_id in (SELECT id FROM activities where category_id=?)
"""
affected_ids = [res[0] for res in self.fetchall(affected_query, (id,))]
update = "update activities set category_id = -1 where category_id = ?"
self.execute(update, (id, ))
self.execute("delete from categories where id = ?", (id, ))
self.__remove_index(affected_ids) | python | def __remove_category(self, id):
"""move all activities to unsorted and remove category"""
affected_query = """
SELECT id
FROM facts
WHERE activity_id in (SELECT id FROM activities where category_id=?)
"""
affected_ids = [res[0] for res in self.fetchall(affected_query, (id,))]
update = "update activities set category_id = -1 where category_id = ?"
self.execute(update, (id, ))
self.execute("delete from categories where id = ?", (id, ))
self.__remove_index(affected_ids) | [
"def",
"__remove_category",
"(",
"self",
",",
"id",
")",
":",
"affected_query",
"=",
"\"\"\"\n SELECT id\n FROM facts\n WHERE activity_id in (SELECT id FROM activities where category_id=?)\n \"\"\"",
"affected_ids",
"=",
"[",
"res",
"[",
"0"... | move all activities to unsorted and remove category | [
"move",
"all",
"activities",
"to",
"unsorted",
"and",
"remove",
"category"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L795-L810 | train | 226,883 |
projecthamster/hamster | src/hamster/storage/db.py | Storage.__remove_index | def __remove_index(self, ids):
"""remove affected ids from the index"""
if not ids:
return
ids = ",".join((str(id) for id in ids))
self.execute("DELETE FROM fact_index where id in (%s)" % ids) | python | def __remove_index(self, ids):
"""remove affected ids from the index"""
if not ids:
return
ids = ",".join((str(id) for id in ids))
self.execute("DELETE FROM fact_index where id in (%s)" % ids) | [
"def",
"__remove_index",
"(",
"self",
",",
"ids",
")",
":",
"if",
"not",
"ids",
":",
"return",
"ids",
"=",
"\",\"",
".",
"join",
"(",
"(",
"str",
"(",
"id",
")",
"for",
"id",
"in",
"ids",
")",
")",
"self",
".",
"execute",
"(",
"\"DELETE FROM fact_i... | remove affected ids from the index | [
"remove",
"affected",
"ids",
"from",
"the",
"index"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L834-L840 | train | 226,884 |
projecthamster/hamster | src/hamster/storage/db.py | Storage.execute | def execute(self, statement, params = ()):
"""
execute sql statement. optionally you can give multiple statements
to save on cursor creation and closure
"""
con = self.__con or self.connection
cur = self.__cur or con.cursor()
if isinstance(statement, list) == False: # we expect to receive instructions in list
statement = [statement]
params = [params]
for state, param in zip(statement, params):
logger.debug("%s %s" % (state, param))
cur.execute(state, param)
if not self.__con:
con.commit()
cur.close()
self.register_modification() | python | def execute(self, statement, params = ()):
"""
execute sql statement. optionally you can give multiple statements
to save on cursor creation and closure
"""
con = self.__con or self.connection
cur = self.__cur or con.cursor()
if isinstance(statement, list) == False: # we expect to receive instructions in list
statement = [statement]
params = [params]
for state, param in zip(statement, params):
logger.debug("%s %s" % (state, param))
cur.execute(state, param)
if not self.__con:
con.commit()
cur.close()
self.register_modification() | [
"def",
"execute",
"(",
"self",
",",
"statement",
",",
"params",
"=",
"(",
")",
")",
":",
"con",
"=",
"self",
".",
"__con",
"or",
"self",
".",
"connection",
"cur",
"=",
"self",
".",
"__cur",
"or",
"con",
".",
"cursor",
"(",
")",
"if",
"isinstance",
... | execute sql statement. optionally you can give multiple statements
to save on cursor creation and closure | [
"execute",
"sql",
"statement",
".",
"optionally",
"you",
"can",
"give",
"multiple",
"statements",
"to",
"save",
"on",
"cursor",
"creation",
"and",
"closure"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L913-L932 | train | 226,885 |
projecthamster/hamster | src/hamster/storage/db.py | Storage.run_fixtures | def run_fixtures(self):
self.start_transaction()
"""upgrade DB to hamster version"""
version = self.fetchone("SELECT version FROM version")["version"]
current_version = 9
if version < 8:
# working around sqlite's utf-f case sensitivity (bug 624438)
# more info: http://www.gsak.net/help/hs23820.htm
self.execute("ALTER TABLE activities ADD COLUMN search_name varchar2")
activities = self.fetchall("select * from activities")
statement = "update activities set search_name = ? where id = ?"
for activity in activities:
self.execute(statement, (activity['name'].lower(), activity['id']))
# same for categories
self.execute("ALTER TABLE categories ADD COLUMN search_name varchar2")
categories = self.fetchall("select * from categories")
statement = "update categories set search_name = ? where id = ?"
for category in categories:
self.execute(statement, (category['name'].lower(), category['id']))
if version < 9:
# adding full text search
self.execute("""CREATE VIRTUAL TABLE fact_index
USING fts3(id, name, category, description, tag)""")
# at the happy end, update version number
if version < current_version:
#lock down current version
self.execute("UPDATE version SET version = %d" % current_version)
print("updated database from version %d to %d" % (version, current_version))
self.end_transaction() | python | def run_fixtures(self):
self.start_transaction()
"""upgrade DB to hamster version"""
version = self.fetchone("SELECT version FROM version")["version"]
current_version = 9
if version < 8:
# working around sqlite's utf-f case sensitivity (bug 624438)
# more info: http://www.gsak.net/help/hs23820.htm
self.execute("ALTER TABLE activities ADD COLUMN search_name varchar2")
activities = self.fetchall("select * from activities")
statement = "update activities set search_name = ? where id = ?"
for activity in activities:
self.execute(statement, (activity['name'].lower(), activity['id']))
# same for categories
self.execute("ALTER TABLE categories ADD COLUMN search_name varchar2")
categories = self.fetchall("select * from categories")
statement = "update categories set search_name = ? where id = ?"
for category in categories:
self.execute(statement, (category['name'].lower(), category['id']))
if version < 9:
# adding full text search
self.execute("""CREATE VIRTUAL TABLE fact_index
USING fts3(id, name, category, description, tag)""")
# at the happy end, update version number
if version < current_version:
#lock down current version
self.execute("UPDATE version SET version = %d" % current_version)
print("updated database from version %d to %d" % (version, current_version))
self.end_transaction() | [
"def",
"run_fixtures",
"(",
"self",
")",
":",
"self",
".",
"start_transaction",
"(",
")",
"version",
"=",
"self",
".",
"fetchone",
"(",
"\"SELECT version FROM version\"",
")",
"[",
"\"version\"",
"]",
"current_version",
"=",
"9",
"if",
"version",
"<",
"8",
"... | upgrade DB to hamster version | [
"upgrade",
"DB",
"to",
"hamster",
"version"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L959-L995 | train | 226,886 |
projecthamster/hamster | src/hamster/widgets/facttree.py | FactTree.current_fact_index | def current_fact_index(self):
"""Current fact index in the self.facts list."""
facts_ids = [fact.id for fact in self.facts]
return facts_ids.index(self.current_fact.id) | python | def current_fact_index(self):
"""Current fact index in the self.facts list."""
facts_ids = [fact.id for fact in self.facts]
return facts_ids.index(self.current_fact.id) | [
"def",
"current_fact_index",
"(",
"self",
")",
":",
"facts_ids",
"=",
"[",
"fact",
".",
"id",
"for",
"fact",
"in",
"self",
".",
"facts",
"]",
"return",
"facts_ids",
".",
"index",
"(",
"self",
".",
"current_fact",
".",
"id",
")"
] | Current fact index in the self.facts list. | [
"Current",
"fact",
"index",
"in",
"the",
"self",
".",
"facts",
"list",
"."
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/widgets/facttree.py#L258-L261 | train | 226,887 |
projecthamster/hamster | src/hamster/lib/graphics.py | chain | def chain(*steps):
"""chains the given list of functions and object animations into a callback string.
Expects an interlaced list of object and params, something like:
object, {params},
callable, {params},
object, {},
object, {params}
Assumes that all callees accept on_complete named param.
The last item in the list can omit that.
XXX - figure out where to place these guys as they are quite useful
"""
if not steps:
return
def on_done(sprite=None):
chain(*steps[2:])
obj, params = steps[:2]
if len(steps) > 2:
params['on_complete'] = on_done
if callable(obj):
obj(**params)
else:
obj.animate(**params) | python | def chain(*steps):
"""chains the given list of functions and object animations into a callback string.
Expects an interlaced list of object and params, something like:
object, {params},
callable, {params},
object, {},
object, {params}
Assumes that all callees accept on_complete named param.
The last item in the list can omit that.
XXX - figure out where to place these guys as they are quite useful
"""
if not steps:
return
def on_done(sprite=None):
chain(*steps[2:])
obj, params = steps[:2]
if len(steps) > 2:
params['on_complete'] = on_done
if callable(obj):
obj(**params)
else:
obj.animate(**params) | [
"def",
"chain",
"(",
"*",
"steps",
")",
":",
"if",
"not",
"steps",
":",
"return",
"def",
"on_done",
"(",
"sprite",
"=",
"None",
")",
":",
"chain",
"(",
"*",
"steps",
"[",
"2",
":",
"]",
")",
"obj",
",",
"params",
"=",
"steps",
"[",
":",
"2",
... | chains the given list of functions and object animations into a callback string.
Expects an interlaced list of object and params, something like:
object, {params},
callable, {params},
object, {},
object, {params}
Assumes that all callees accept on_complete named param.
The last item in the list can omit that.
XXX - figure out where to place these guys as they are quite useful | [
"chains",
"the",
"given",
"list",
"of",
"functions",
"and",
"object",
"animations",
"into",
"a",
"callback",
"string",
"."
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L160-L185 | train | 226,888 |
projecthamster/hamster | src/hamster/lib/graphics.py | full_pixels | def full_pixels(space, data, gap_pixels=1):
"""returns the given data distributed in the space ensuring it's full pixels
and with the given gap.
this will result in minor sub-pixel inaccuracies.
XXX - figure out where to place these guys as they are quite useful
"""
available = space - (len(data) - 1) * gap_pixels # 8 recs 7 gaps
res = []
for i, val in enumerate(data):
# convert data to 0..1 scale so we deal with fractions
data_sum = sum(data[i:])
norm = val * 1.0 / data_sum
w = max(int(round(available * norm)), 1)
res.append(w)
available -= w
return res | python | def full_pixels(space, data, gap_pixels=1):
"""returns the given data distributed in the space ensuring it's full pixels
and with the given gap.
this will result in minor sub-pixel inaccuracies.
XXX - figure out where to place these guys as they are quite useful
"""
available = space - (len(data) - 1) * gap_pixels # 8 recs 7 gaps
res = []
for i, val in enumerate(data):
# convert data to 0..1 scale so we deal with fractions
data_sum = sum(data[i:])
norm = val * 1.0 / data_sum
w = max(int(round(available * norm)), 1)
res.append(w)
available -= w
return res | [
"def",
"full_pixels",
"(",
"space",
",",
"data",
",",
"gap_pixels",
"=",
"1",
")",
":",
"available",
"=",
"space",
"-",
"(",
"len",
"(",
"data",
")",
"-",
"1",
")",
"*",
"gap_pixels",
"# 8 recs 7 gaps",
"res",
"=",
"[",
"]",
"for",
"i",
",",
"val",... | returns the given data distributed in the space ensuring it's full pixels
and with the given gap.
this will result in minor sub-pixel inaccuracies.
XXX - figure out where to place these guys as they are quite useful | [
"returns",
"the",
"given",
"data",
"distributed",
"in",
"the",
"space",
"ensuring",
"it",
"s",
"full",
"pixels",
"and",
"with",
"the",
"given",
"gap",
".",
"this",
"will",
"result",
"in",
"minor",
"sub",
"-",
"pixel",
"inaccuracies",
".",
"XXX",
"-",
"fi... | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L187-L205 | train | 226,889 |
projecthamster/hamster | src/hamster/lib/graphics.py | ColorUtils.gdk | def gdk(self, color):
"""returns gdk.Color object of the given color"""
c = self.parse(color)
return gdk.Color.from_floats(c) | python | def gdk(self, color):
"""returns gdk.Color object of the given color"""
c = self.parse(color)
return gdk.Color.from_floats(c) | [
"def",
"gdk",
"(",
"self",
",",
"color",
")",
":",
"c",
"=",
"self",
".",
"parse",
"(",
"color",
")",
"return",
"gdk",
".",
"Color",
".",
"from_floats",
"(",
"c",
")"
] | returns gdk.Color object of the given color | [
"returns",
"gdk",
".",
"Color",
"object",
"of",
"the",
"given",
"color"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L95-L98 | train | 226,890 |
projecthamster/hamster | src/hamster/lib/graphics.py | ColorUtils.contrast | def contrast(self, color, step):
"""if color is dark, will return a lighter one, otherwise darker"""
hls = colorsys.rgb_to_hls(*self.rgb(color))
if self.is_light(color):
return colorsys.hls_to_rgb(hls[0], hls[1] - step, hls[2])
else:
return colorsys.hls_to_rgb(hls[0], hls[1] + step, hls[2]) | python | def contrast(self, color, step):
"""if color is dark, will return a lighter one, otherwise darker"""
hls = colorsys.rgb_to_hls(*self.rgb(color))
if self.is_light(color):
return colorsys.hls_to_rgb(hls[0], hls[1] - step, hls[2])
else:
return colorsys.hls_to_rgb(hls[0], hls[1] + step, hls[2]) | [
"def",
"contrast",
"(",
"self",
",",
"color",
",",
"step",
")",
":",
"hls",
"=",
"colorsys",
".",
"rgb_to_hls",
"(",
"*",
"self",
".",
"rgb",
"(",
"color",
")",
")",
"if",
"self",
".",
"is_light",
"(",
"color",
")",
":",
"return",
"colorsys",
".",
... | if color is dark, will return a lighter one, otherwise darker | [
"if",
"color",
"is",
"dark",
"will",
"return",
"a",
"lighter",
"one",
"otherwise",
"darker"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L121-L127 | train | 226,891 |
projecthamster/hamster | src/hamster/lib/graphics.py | ColorUtils.mix | def mix(self, ca, cb, xb):
"""Mix colors.
Args:
ca (gdk.RGBA): first color
cb (gdk.RGBA): second color
xb (float): between 0.0 and 1.0
Return:
gdk.RGBA: linear interpolation between ca and cb,
0 or 1 return the unaltered 1st or 2nd color respectively,
as in CSS.
"""
r = (1 - xb) * ca.red + xb * cb.red
g = (1 - xb) * ca.green + xb * cb.green
b = (1 - xb) * ca.blue + xb * cb.blue
a = (1 - xb) * ca.alpha + xb * cb.alpha
return gdk.RGBA(red=r, green=g, blue=b, alpha=a) | python | def mix(self, ca, cb, xb):
"""Mix colors.
Args:
ca (gdk.RGBA): first color
cb (gdk.RGBA): second color
xb (float): between 0.0 and 1.0
Return:
gdk.RGBA: linear interpolation between ca and cb,
0 or 1 return the unaltered 1st or 2nd color respectively,
as in CSS.
"""
r = (1 - xb) * ca.red + xb * cb.red
g = (1 - xb) * ca.green + xb * cb.green
b = (1 - xb) * ca.blue + xb * cb.blue
a = (1 - xb) * ca.alpha + xb * cb.alpha
return gdk.RGBA(red=r, green=g, blue=b, alpha=a) | [
"def",
"mix",
"(",
"self",
",",
"ca",
",",
"cb",
",",
"xb",
")",
":",
"r",
"=",
"(",
"1",
"-",
"xb",
")",
"*",
"ca",
".",
"red",
"+",
"xb",
"*",
"cb",
".",
"red",
"g",
"=",
"(",
"1",
"-",
"xb",
")",
"*",
"ca",
".",
"green",
"+",
"xb",... | Mix colors.
Args:
ca (gdk.RGBA): first color
cb (gdk.RGBA): second color
xb (float): between 0.0 and 1.0
Return:
gdk.RGBA: linear interpolation between ca and cb,
0 or 1 return the unaltered 1st or 2nd color respectively,
as in CSS. | [
"Mix",
"colors",
"."
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L130-L147 | train | 226,892 |
projecthamster/hamster | src/hamster/lib/graphics.py | Graphics.set_line_style | def set_line_style(self, width = None, dash = None, dash_offset = 0):
"""change width and dash of a line"""
if width is not None:
self._add_instruction("set_line_width", width)
if dash is not None:
self._add_instruction("set_dash", dash, dash_offset) | python | def set_line_style(self, width = None, dash = None, dash_offset = 0):
"""change width and dash of a line"""
if width is not None:
self._add_instruction("set_line_width", width)
if dash is not None:
self._add_instruction("set_dash", dash, dash_offset) | [
"def",
"set_line_style",
"(",
"self",
",",
"width",
"=",
"None",
",",
"dash",
"=",
"None",
",",
"dash_offset",
"=",
"0",
")",
":",
"if",
"width",
"is",
"not",
"None",
":",
"self",
".",
"_add_instruction",
"(",
"\"set_line_width\"",
",",
"width",
")",
"... | change width and dash of a line | [
"change",
"width",
"and",
"dash",
"of",
"a",
"line"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L328-L334 | train | 226,893 |
projecthamster/hamster | src/hamster/lib/graphics.py | Graphics._set_color | def _set_color(self, context, r, g, b, a):
"""the alpha has to changed based on the parent, so that happens at the
time of drawing"""
if a < 1:
context.set_source_rgba(r, g, b, a)
else:
context.set_source_rgb(r, g, b) | python | def _set_color(self, context, r, g, b, a):
"""the alpha has to changed based on the parent, so that happens at the
time of drawing"""
if a < 1:
context.set_source_rgba(r, g, b, a)
else:
context.set_source_rgb(r, g, b) | [
"def",
"_set_color",
"(",
"self",
",",
"context",
",",
"r",
",",
"g",
",",
"b",
",",
"a",
")",
":",
"if",
"a",
"<",
"1",
":",
"context",
".",
"set_source_rgba",
"(",
"r",
",",
"g",
",",
"b",
",",
"a",
")",
"else",
":",
"context",
".",
"set_so... | the alpha has to changed based on the parent, so that happens at the
time of drawing | [
"the",
"alpha",
"has",
"to",
"changed",
"based",
"on",
"the",
"parent",
"so",
"that",
"happens",
"at",
"the",
"time",
"of",
"drawing"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L338-L344 | train | 226,894 |
projecthamster/hamster | src/hamster/lib/graphics.py | Graphics.arc | def arc(self, x, y, radius, start_angle, end_angle):
"""draw arc going counter-clockwise from start_angle to end_angle"""
self._add_instruction("arc", x, y, radius, start_angle, end_angle) | python | def arc(self, x, y, radius, start_angle, end_angle):
"""draw arc going counter-clockwise from start_angle to end_angle"""
self._add_instruction("arc", x, y, radius, start_angle, end_angle) | [
"def",
"arc",
"(",
"self",
",",
"x",
",",
"y",
",",
"radius",
",",
"start_angle",
",",
"end_angle",
")",
":",
"self",
".",
"_add_instruction",
"(",
"\"arc\"",
",",
"x",
",",
"y",
",",
"radius",
",",
"start_angle",
",",
"end_angle",
")"
] | draw arc going counter-clockwise from start_angle to end_angle | [
"draw",
"arc",
"going",
"counter",
"-",
"clockwise",
"from",
"start_angle",
"to",
"end_angle"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L360-L362 | train | 226,895 |
projecthamster/hamster | src/hamster/lib/graphics.py | Graphics.ellipse | def ellipse(self, x, y, width, height, edges = None):
"""draw 'perfect' ellipse, opposed to squashed circle. works also for
equilateral polygons"""
# the automatic edge case is somewhat arbitrary
steps = edges or max((32, width, height)) / 2
angle = 0
step = math.pi * 2 / steps
points = []
while angle < math.pi * 2:
points.append((width / 2.0 * math.cos(angle),
height / 2.0 * math.sin(angle)))
angle += step
min_x = min((point[0] for point in points))
min_y = min((point[1] for point in points))
self.move_to(points[0][0] - min_x + x, points[0][1] - min_y + y)
for p_x, p_y in points:
self.line_to(p_x - min_x + x, p_y - min_y + y)
self.line_to(points[0][0] - min_x + x, points[0][1] - min_y + y) | python | def ellipse(self, x, y, width, height, edges = None):
"""draw 'perfect' ellipse, opposed to squashed circle. works also for
equilateral polygons"""
# the automatic edge case is somewhat arbitrary
steps = edges or max((32, width, height)) / 2
angle = 0
step = math.pi * 2 / steps
points = []
while angle < math.pi * 2:
points.append((width / 2.0 * math.cos(angle),
height / 2.0 * math.sin(angle)))
angle += step
min_x = min((point[0] for point in points))
min_y = min((point[1] for point in points))
self.move_to(points[0][0] - min_x + x, points[0][1] - min_y + y)
for p_x, p_y in points:
self.line_to(p_x - min_x + x, p_y - min_y + y)
self.line_to(points[0][0] - min_x + x, points[0][1] - min_y + y) | [
"def",
"ellipse",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"edges",
"=",
"None",
")",
":",
"# the automatic edge case is somewhat arbitrary",
"steps",
"=",
"edges",
"or",
"max",
"(",
"(",
"32",
",",
"width",
",",
"height",
")",
... | draw 'perfect' ellipse, opposed to squashed circle. works also for
equilateral polygons | [
"draw",
"perfect",
"ellipse",
"opposed",
"to",
"squashed",
"circle",
".",
"works",
"also",
"for",
"equilateral",
"polygons"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L368-L388 | train | 226,896 |
projecthamster/hamster | src/hamster/lib/graphics.py | Graphics.arc_negative | def arc_negative(self, x, y, radius, start_angle, end_angle):
"""draw arc going clockwise from start_angle to end_angle"""
self._add_instruction("arc_negative", x, y, radius, start_angle, end_angle) | python | def arc_negative(self, x, y, radius, start_angle, end_angle):
"""draw arc going clockwise from start_angle to end_angle"""
self._add_instruction("arc_negative", x, y, radius, start_angle, end_angle) | [
"def",
"arc_negative",
"(",
"self",
",",
"x",
",",
"y",
",",
"radius",
",",
"start_angle",
",",
"end_angle",
")",
":",
"self",
".",
"_add_instruction",
"(",
"\"arc_negative\"",
",",
"x",
",",
"y",
",",
"radius",
",",
"start_angle",
",",
"end_angle",
")"
... | draw arc going clockwise from start_angle to end_angle | [
"draw",
"arc",
"going",
"clockwise",
"from",
"start_angle",
"to",
"end_angle"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L390-L392 | train | 226,897 |
projecthamster/hamster | src/hamster/lib/graphics.py | Graphics.rectangle | def rectangle(self, x, y, width, height, corner_radius = 0):
"""draw a rectangle. if corner_radius is specified, will draw
rounded corners. corner_radius can be either a number or a tuple of
four items to specify individually each corner, starting from top-left
and going clockwise"""
if corner_radius <= 0:
self._add_instruction("rectangle", x, y, width, height)
return
# convert into 4 border and make sure that w + h are larger than 2 * corner_radius
if isinstance(corner_radius, (int, float)):
corner_radius = [corner_radius] * 4
corner_radius = [min(r, min(width, height) / 2) for r in corner_radius]
x2, y2 = x + width, y + height
self._rounded_rectangle(x, y, x2, y2, corner_radius) | python | def rectangle(self, x, y, width, height, corner_radius = 0):
"""draw a rectangle. if corner_radius is specified, will draw
rounded corners. corner_radius can be either a number or a tuple of
four items to specify individually each corner, starting from top-left
and going clockwise"""
if corner_radius <= 0:
self._add_instruction("rectangle", x, y, width, height)
return
# convert into 4 border and make sure that w + h are larger than 2 * corner_radius
if isinstance(corner_radius, (int, float)):
corner_radius = [corner_radius] * 4
corner_radius = [min(r, min(width, height) / 2) for r in corner_radius]
x2, y2 = x + width, y + height
self._rounded_rectangle(x, y, x2, y2, corner_radius) | [
"def",
"rectangle",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"corner_radius",
"=",
"0",
")",
":",
"if",
"corner_radius",
"<=",
"0",
":",
"self",
".",
"_add_instruction",
"(",
"\"rectangle\"",
",",
"x",
",",
"y",
",",
"width"... | draw a rectangle. if corner_radius is specified, will draw
rounded corners. corner_radius can be either a number or a tuple of
four items to specify individually each corner, starting from top-left
and going clockwise | [
"draw",
"a",
"rectangle",
".",
"if",
"corner_radius",
"is",
"specified",
"will",
"draw",
"rounded",
"corners",
".",
"corner_radius",
"can",
"be",
"either",
"a",
"number",
"or",
"a",
"tuple",
"of",
"four",
"items",
"to",
"specify",
"individually",
"each",
"co... | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L400-L415 | train | 226,898 |
projecthamster/hamster | src/hamster/lib/graphics.py | Graphics.fill_area | def fill_area(self, x, y, width, height, color, opacity = 1):
"""fill rectangular area with specified color"""
self.save_context()
self.rectangle(x, y, width, height)
self._add_instruction("clip")
self.rectangle(x, y, width, height)
self.fill(color, opacity)
self.restore_context() | python | def fill_area(self, x, y, width, height, color, opacity = 1):
"""fill rectangular area with specified color"""
self.save_context()
self.rectangle(x, y, width, height)
self._add_instruction("clip")
self.rectangle(x, y, width, height)
self.fill(color, opacity)
self.restore_context() | [
"def",
"fill_area",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"color",
",",
"opacity",
"=",
"1",
")",
":",
"self",
".",
"save_context",
"(",
")",
"self",
".",
"rectangle",
"(",
"x",
",",
"y",
",",
"width",
",",
"height",
... | fill rectangular area with specified color | [
"fill",
"rectangular",
"area",
"with",
"specified",
"color"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L444-L451 | train | 226,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.