repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
mjirik/imcut | imcut/image_manipulation.py | uncrop | def uncrop(data, crinfo, orig_shape, resize=False, outside_mode="constant", cval=0):
"""
Put some boundary to input image.
:param data: input data
:param crinfo: array with minimum and maximum index along each axis
[[minX, maxX],[minY, maxY],[minZ, maxZ]]. If crinfo is None, the whole input im... | python | def uncrop(data, crinfo, orig_shape, resize=False, outside_mode="constant", cval=0):
"""
Put some boundary to input image.
:param data: input data
:param crinfo: array with minimum and maximum index along each axis
[[minX, maxX],[minY, maxY],[minZ, maxZ]]. If crinfo is None, the whole input im... | [
"def",
"uncrop",
"(",
"data",
",",
"crinfo",
",",
"orig_shape",
",",
"resize",
"=",
"False",
",",
"outside_mode",
"=",
"\"constant\"",
",",
"cval",
"=",
"0",
")",
":",
"if",
"crinfo",
"is",
"None",
":",
"crinfo",
"=",
"list",
"(",
"zip",
"(",
"[",
... | Put some boundary to input image.
:param data: input data
:param crinfo: array with minimum and maximum index along each axis
[[minX, maxX],[minY, maxY],[minZ, maxZ]]. If crinfo is None, the whole input image is placed into [0, 0, 0].
If crinfo is just series of three numbers, it is used as an... | [
"Put",
"some",
"boundary",
"to",
"input",
"image",
"."
] | 1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3 | https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/image_manipulation.py#L444-L522 | train |
mjirik/imcut | imcut/image_manipulation.py | fix_crinfo | def fix_crinfo(crinfo, to="axis"):
"""
Function recognize order of crinfo and convert it to proper format.
"""
crinfo = np.asarray(crinfo)
if crinfo.shape[0] == 2:
crinfo = crinfo.T
return crinfo | python | def fix_crinfo(crinfo, to="axis"):
"""
Function recognize order of crinfo and convert it to proper format.
"""
crinfo = np.asarray(crinfo)
if crinfo.shape[0] == 2:
crinfo = crinfo.T
return crinfo | [
"def",
"fix_crinfo",
"(",
"crinfo",
",",
"to",
"=",
"\"axis\"",
")",
":",
"crinfo",
"=",
"np",
".",
"asarray",
"(",
"crinfo",
")",
"if",
"crinfo",
".",
"shape",
"[",
"0",
"]",
"==",
"2",
":",
"crinfo",
"=",
"crinfo",
".",
"T",
"return",
"crinfo"
] | Function recognize order of crinfo and convert it to proper format. | [
"Function",
"recognize",
"order",
"of",
"crinfo",
"and",
"convert",
"it",
"to",
"proper",
"format",
"."
] | 1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3 | https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/image_manipulation.py#L525-L534 | train |
mjirik/imcut | imcut/graph.py | grid_edges | def grid_edges(shape, inds=None, return_directions=True):
"""
Get list of grid edges
:param shape:
:param inds:
:param return_directions:
:return:
"""
if inds is None:
inds = np.arange(np.prod(shape)).reshape(shape)
# if not self.segparams['use_boundary_penalties'] and \
... | python | def grid_edges(shape, inds=None, return_directions=True):
"""
Get list of grid edges
:param shape:
:param inds:
:param return_directions:
:return:
"""
if inds is None:
inds = np.arange(np.prod(shape)).reshape(shape)
# if not self.segparams['use_boundary_penalties'] and \
... | [
"def",
"grid_edges",
"(",
"shape",
",",
"inds",
"=",
"None",
",",
"return_directions",
"=",
"True",
")",
":",
"if",
"inds",
"is",
"None",
":",
"inds",
"=",
"np",
".",
"arange",
"(",
"np",
".",
"prod",
"(",
"shape",
")",
")",
".",
"reshape",
"(",
... | Get list of grid edges
:param shape:
:param inds:
:param return_directions:
:return: | [
"Get",
"list",
"of",
"grid",
"edges",
":",
"param",
"shape",
":",
":",
"param",
"inds",
":",
":",
"param",
"return_directions",
":",
":",
"return",
":"
] | 1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3 | https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/graph.py#L524-L568 | train |
mjirik/imcut | imcut/graph.py | gen_grid_2d | def gen_grid_2d(shape, voxelsize):
"""
Generate list of edges for a base grid.
"""
nr, nc = shape
nrm1, ncm1 = nr - 1, nc - 1
# sh = nm.asarray(shape)
# calculate number of edges, in 2D: (nrows * (ncols - 1)) + ((nrows - 1) * ncols)
nedges = 0
for direction in range(len(shape)):
... | python | def gen_grid_2d(shape, voxelsize):
"""
Generate list of edges for a base grid.
"""
nr, nc = shape
nrm1, ncm1 = nr - 1, nc - 1
# sh = nm.asarray(shape)
# calculate number of edges, in 2D: (nrows * (ncols - 1)) + ((nrows - 1) * ncols)
nedges = 0
for direction in range(len(shape)):
... | [
"def",
"gen_grid_2d",
"(",
"shape",
",",
"voxelsize",
")",
":",
"nr",
",",
"nc",
"=",
"shape",
"nrm1",
",",
"ncm1",
"=",
"nr",
"-",
"1",
",",
"nc",
"-",
"1",
"# sh = nm.asarray(shape)",
"# calculate number of edges, in 2D: (nrows * (ncols - 1)) + ((nrows - 1) * ncol... | Generate list of edges for a base grid. | [
"Generate",
"list",
"of",
"edges",
"for",
"a",
"base",
"grid",
"."
] | 1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3 | https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/graph.py#L586-L636 | train |
mjirik/imcut | imcut/graph.py | write_grid_to_vtk | def write_grid_to_vtk(fname, nodes, edges, node_flag=None, edge_flag=None):
"""
Write nodes and edges to VTK file
:param fname: VTK filename
:param nodes:
:param edges:
:param node_flag: set if this node is really used in output
:param edge_flag: set if this flag is used in output
:retur... | python | def write_grid_to_vtk(fname, nodes, edges, node_flag=None, edge_flag=None):
"""
Write nodes and edges to VTK file
:param fname: VTK filename
:param nodes:
:param edges:
:param node_flag: set if this node is really used in output
:param edge_flag: set if this flag is used in output
:retur... | [
"def",
"write_grid_to_vtk",
"(",
"fname",
",",
"nodes",
",",
"edges",
",",
"node_flag",
"=",
"None",
",",
"edge_flag",
"=",
"None",
")",
":",
"if",
"node_flag",
"is",
"None",
":",
"node_flag",
"=",
"np",
".",
"ones",
"(",
"[",
"nodes",
".",
"shape",
... | Write nodes and edges to VTK file
:param fname: VTK filename
:param nodes:
:param edges:
:param node_flag: set if this node is really used in output
:param edge_flag: set if this flag is used in output
:return: | [
"Write",
"nodes",
"and",
"edges",
"to",
"VTK",
"file",
":",
"param",
"fname",
":",
"VTK",
"filename",
":",
"param",
"nodes",
":",
":",
"param",
"edges",
":",
":",
"param",
"node_flag",
":",
"set",
"if",
"this",
"node",
"is",
"really",
"used",
"in",
"... | 1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3 | https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/graph.py#L646-L683 | train |
mjirik/imcut | imcut/graph.py | Graph.add_nodes | def add_nodes(self, coors, node_low_or_high=None):
"""
Add new nodes at the end of the list.
"""
last = self.lastnode
if type(coors) is nm.ndarray:
if len(coors.shape) == 1:
coors = coors.reshape((1, coors.size))
nadd = coors.shape[0]
... | python | def add_nodes(self, coors, node_low_or_high=None):
"""
Add new nodes at the end of the list.
"""
last = self.lastnode
if type(coors) is nm.ndarray:
if len(coors.shape) == 1:
coors = coors.reshape((1, coors.size))
nadd = coors.shape[0]
... | [
"def",
"add_nodes",
"(",
"self",
",",
"coors",
",",
"node_low_or_high",
"=",
"None",
")",
":",
"last",
"=",
"self",
".",
"lastnode",
"if",
"type",
"(",
"coors",
")",
"is",
"nm",
".",
"ndarray",
":",
"if",
"len",
"(",
"coors",
".",
"shape",
")",
"==... | Add new nodes at the end of the list. | [
"Add",
"new",
"nodes",
"at",
"the",
"end",
"of",
"the",
"list",
"."
] | 1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3 | https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/graph.py#L153-L171 | train |
mjirik/imcut | imcut/graph.py | Graph.add_edges | def add_edges(self, conn, edge_direction, edge_group=None, edge_low_or_high=None):
"""
Add new edges at the end of the list.
:param edge_direction: direction flag
:param edge_group: describes group of edges from same low super node and same direction
:param edge_low_or_high: zero... | python | def add_edges(self, conn, edge_direction, edge_group=None, edge_low_or_high=None):
"""
Add new edges at the end of the list.
:param edge_direction: direction flag
:param edge_group: describes group of edges from same low super node and same direction
:param edge_low_or_high: zero... | [
"def",
"add_edges",
"(",
"self",
",",
"conn",
",",
"edge_direction",
",",
"edge_group",
"=",
"None",
",",
"edge_low_or_high",
"=",
"None",
")",
":",
"last",
"=",
"self",
".",
"lastedge",
"if",
"type",
"(",
"conn",
")",
"is",
"nm",
".",
"ndarray",
":",
... | Add new edges at the end of the list.
:param edge_direction: direction flag
:param edge_group: describes group of edges from same low super node and same direction
:param edge_low_or_high: zero for low to low resolution, one for high to high or high to low resolution.
It is used to set w... | [
"Add",
"new",
"edges",
"at",
"the",
"end",
"of",
"the",
"list",
".",
":",
"param",
"edge_direction",
":",
"direction",
"flag",
":",
"param",
"edge_group",
":",
"describes",
"group",
"of",
"edges",
"from",
"same",
"low",
"super",
"node",
"and",
"same",
"d... | 1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3 | https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/graph.py#L173-L207 | train |
mjirik/imcut | imcut/graph.py | Graph._edge_group_substitution | def _edge_group_substitution(
self, ndid, nsplit, idxs, sr_tab, ndoffset, ed_remove, into_or_from
):
"""
Reconnect edges.
:param ndid: id of low resolution edges
:param nsplit: number of split
:param idxs: indexes of low resolution
:param sr_tab:
:para... | python | def _edge_group_substitution(
self, ndid, nsplit, idxs, sr_tab, ndoffset, ed_remove, into_or_from
):
"""
Reconnect edges.
:param ndid: id of low resolution edges
:param nsplit: number of split
:param idxs: indexes of low resolution
:param sr_tab:
:para... | [
"def",
"_edge_group_substitution",
"(",
"self",
",",
"ndid",
",",
"nsplit",
",",
"idxs",
",",
"sr_tab",
",",
"ndoffset",
",",
"ed_remove",
",",
"into_or_from",
")",
":",
"# this is useful for type(idxs) == np.ndarray",
"eidxs",
"=",
"idxs",
"[",
"nm",
".",
"wher... | Reconnect edges.
:param ndid: id of low resolution edges
:param nsplit: number of split
:param idxs: indexes of low resolution
:param sr_tab:
:param ndoffset:
:param ed_remove:
:param into_or_from: if zero, connection of input edges is done. If one, connection of ... | [
"Reconnect",
"edges",
".",
":",
"param",
"ndid",
":",
"id",
"of",
"low",
"resolution",
"edges",
":",
"param",
"nsplit",
":",
"number",
"of",
"split",
":",
"param",
"idxs",
":",
"indexes",
"of",
"low",
"resolution",
":",
"param",
"sr_tab",
":",
":",
"pa... | 1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3 | https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/graph.py#L264-L321 | train |
mjirik/imcut | imcut/graph.py | Graph.generate_base_grid | def generate_base_grid(self, vtk_filename=None):
"""
Run first step of algorithm. Next step is split_voxels
:param vtk_filename:
:return:
"""
nd, ed, ed_dir = self.gen_grid_fcn(self.data.shape, self.voxelsize)
self.add_nodes(nd)
self.add_edges(ed, ed_dir, ... | python | def generate_base_grid(self, vtk_filename=None):
"""
Run first step of algorithm. Next step is split_voxels
:param vtk_filename:
:return:
"""
nd, ed, ed_dir = self.gen_grid_fcn(self.data.shape, self.voxelsize)
self.add_nodes(nd)
self.add_edges(ed, ed_dir, ... | [
"def",
"generate_base_grid",
"(",
"self",
",",
"vtk_filename",
"=",
"None",
")",
":",
"nd",
",",
"ed",
",",
"ed_dir",
"=",
"self",
".",
"gen_grid_fcn",
"(",
"self",
".",
"data",
".",
"shape",
",",
"self",
".",
"voxelsize",
")",
"self",
".",
"add_nodes"... | Run first step of algorithm. Next step is split_voxels
:param vtk_filename:
:return: | [
"Run",
"first",
"step",
"of",
"algorithm",
".",
"Next",
"step",
"is",
"split_voxels",
":",
"param",
"vtk_filename",
":",
":",
"return",
":"
] | 1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3 | https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/graph.py#L404-L415 | train |
mjirik/imcut | imcut/graph.py | Graph.split_voxels | def split_voxels(self, vtk_filename=None):
"""
Second step of algorithm
:return:()
"""
self.cache = {}
self.stats["t graph 10"] = time.time() - self.start_time
self.msi = MultiscaleArray(self.data.shape, block_size=self.nsplit)
# old implementation
... | python | def split_voxels(self, vtk_filename=None):
"""
Second step of algorithm
:return:()
"""
self.cache = {}
self.stats["t graph 10"] = time.time() - self.start_time
self.msi = MultiscaleArray(self.data.shape, block_size=self.nsplit)
# old implementation
... | [
"def",
"split_voxels",
"(",
"self",
",",
"vtk_filename",
"=",
"None",
")",
":",
"self",
".",
"cache",
"=",
"{",
"}",
"self",
".",
"stats",
"[",
"\"t graph 10\"",
"]",
"=",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"start_time",
"self",
".",
... | Second step of algorithm
:return:() | [
"Second",
"step",
"of",
"algorithm",
":",
"return",
":",
"()"
] | 1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3 | https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/graph.py#L417-L453 | train |
mjirik/imcut | imcut/graph.py | MultiscaleArray.mul_block | def mul_block(self, index, val):
"""Multiply values in block"""
self._prepare_cache_slice(index)
self.msinds[self.cache_slice] *= val | python | def mul_block(self, index, val):
"""Multiply values in block"""
self._prepare_cache_slice(index)
self.msinds[self.cache_slice] *= val | [
"def",
"mul_block",
"(",
"self",
",",
"index",
",",
"val",
")",
":",
"self",
".",
"_prepare_cache_slice",
"(",
"index",
")",
"self",
".",
"msinds",
"[",
"self",
".",
"cache_slice",
"]",
"*=",
"val"
] | Multiply values in block | [
"Multiply",
"values",
"in",
"block"
] | 1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3 | https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/graph.py#L714-L717 | train |
mjirik/imcut | imcut/features.py | select_from_fv_by_seeds | def select_from_fv_by_seeds(fv, seeds, unique_cls):
"""
Tool to make simple feature functions take features from feature array by seeds.
:param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number
of features
:param seeds: ndarray with seeds. Doe... | python | def select_from_fv_by_seeds(fv, seeds, unique_cls):
"""
Tool to make simple feature functions take features from feature array by seeds.
:param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number
of features
:param seeds: ndarray with seeds. Doe... | [
"def",
"select_from_fv_by_seeds",
"(",
"fv",
",",
"seeds",
",",
"unique_cls",
")",
":",
"logger",
".",
"debug",
"(",
"\"seeds\"",
"+",
"str",
"(",
"seeds",
")",
")",
"# fvlin = fv.reshape(-1, int(fv.size/seeds.size))",
"expected_shape",
"=",
"[",
"seeds",
".",
"... | Tool to make simple feature functions take features from feature array by seeds.
:param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number
of features
:param seeds: ndarray with seeds. Does not to be linear.
:param unique_cls: number of used seeds ... | [
"Tool",
"to",
"make",
"simple",
"feature",
"functions",
"take",
"features",
"from",
"feature",
"array",
"by",
"seeds",
".",
":",
"param",
"fv",
":",
"ndarray",
"with",
"lineariezed",
"feature",
".",
"It",
"s",
"shape",
"is",
"MxN",
"where",
"M",
"is",
"n... | 1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3 | https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/features.py#L39-L58 | train |
mjirik/imcut | imcut/features.py | return_fv_by_seeds | def return_fv_by_seeds(fv, seeds=None, unique_cls=None):
"""
Return features selected by seeds and unique_cls or selection from features and corresponding seed classes.
:param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number
of features
:par... | python | def return_fv_by_seeds(fv, seeds=None, unique_cls=None):
"""
Return features selected by seeds and unique_cls or selection from features and corresponding seed classes.
:param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number
of features
:par... | [
"def",
"return_fv_by_seeds",
"(",
"fv",
",",
"seeds",
"=",
"None",
",",
"unique_cls",
"=",
"None",
")",
":",
"if",
"seeds",
"is",
"not",
"None",
":",
"if",
"unique_cls",
"is",
"not",
"None",
":",
"return",
"select_from_fv_by_seeds",
"(",
"fv",
",",
"seed... | Return features selected by seeds and unique_cls or selection from features and corresponding seed classes.
:param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number
of features
:param seeds: ndarray with seeds. Does not to be linear.
:param uniqu... | [
"Return",
"features",
"selected",
"by",
"seeds",
"and",
"unique_cls",
"or",
"selection",
"from",
"features",
"and",
"corresponding",
"seed",
"classes",
"."
] | 1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3 | https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/features.py#L60-L76 | train |
chitamoor/Rester | rester/manifest.py | Variables.expand | def expand(self, expression):
"""Expands logical constructions."""
self.logger.debug("expand : expression %s", str(expression))
if not is_string(expression):
return expression
result = self._pattern.sub(lambda var: str(self._variables[var.group(1)]), expression)
res... | python | def expand(self, expression):
"""Expands logical constructions."""
self.logger.debug("expand : expression %s", str(expression))
if not is_string(expression):
return expression
result = self._pattern.sub(lambda var: str(self._variables[var.group(1)]), expression)
res... | [
"def",
"expand",
"(",
"self",
",",
"expression",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"expand : expression %s\"",
",",
"str",
"(",
"expression",
")",
")",
"if",
"not",
"is_string",
"(",
"expression",
")",
":",
"return",
"expression",
"resu... | Expands logical constructions. | [
"Expands",
"logical",
"constructions",
"."
] | 1865b17f70b7c597aeadde2d0907cb1b59f10c0f | https://github.com/chitamoor/Rester/blob/1865b17f70b7c597aeadde2d0907cb1b59f10c0f/rester/manifest.py#L34-L52 | train |
disqus/gutter | gutter/client/__init__.py | get_gutter_client | def get_gutter_client(
alias='default',
cache=CLIENT_CACHE,
**kwargs
):
"""
Creates gutter clients and memoizes them in a registry for future quick access.
Args:
alias (str or None): Name of the client. Used for caching.
If name is falsy then do not use the cache... | python | def get_gutter_client(
alias='default',
cache=CLIENT_CACHE,
**kwargs
):
"""
Creates gutter clients and memoizes them in a registry for future quick access.
Args:
alias (str or None): Name of the client. Used for caching.
If name is falsy then do not use the cache... | [
"def",
"get_gutter_client",
"(",
"alias",
"=",
"'default'",
",",
"cache",
"=",
"CLIENT_CACHE",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"gutter",
".",
"client",
".",
"models",
"import",
"Manager",
"if",
"not",
"alias",
":",
"return",
"Manager",
"(",
"*... | Creates gutter clients and memoizes them in a registry for future quick access.
Args:
alias (str or None): Name of the client. Used for caching.
If name is falsy then do not use the cache.
cache (dict): cache to store gutter managers in.
**kwargs: kwargs to be passed the Manger ... | [
"Creates",
"gutter",
"clients",
"and",
"memoizes",
"them",
"in",
"a",
"registry",
"for",
"future",
"quick",
"access",
"."
] | d686fa3cd0551cacfc5630c8e7b5fa75e6dcfdf5 | https://github.com/disqus/gutter/blob/d686fa3cd0551cacfc5630c8e7b5fa75e6dcfdf5/gutter/client/__init__.py#L17-L42 | train |
disqus/gutter | gutter/client/operators/misc.py | PercentRange._modulo | def _modulo(self, decimal_argument):
"""
The mod operator is prone to floating point errors, so use decimal.
101.1 % 100
>>> 1.0999999999999943
decimal_context.divmod(Decimal('100.1'), 100)
>>> (Decimal('1'), Decimal('0.1'))
"""
_times, remainder = self.... | python | def _modulo(self, decimal_argument):
"""
The mod operator is prone to floating point errors, so use decimal.
101.1 % 100
>>> 1.0999999999999943
decimal_context.divmod(Decimal('100.1'), 100)
>>> (Decimal('1'), Decimal('0.1'))
"""
_times, remainder = self.... | [
"def",
"_modulo",
"(",
"self",
",",
"decimal_argument",
")",
":",
"_times",
",",
"remainder",
"=",
"self",
".",
"_context",
".",
"divmod",
"(",
"decimal_argument",
",",
"100",
")",
"# match the builtin % behavior by adding the N to the result if negative",
"return",
"... | The mod operator is prone to floating point errors, so use decimal.
101.1 % 100
>>> 1.0999999999999943
decimal_context.divmod(Decimal('100.1'), 100)
>>> (Decimal('1'), Decimal('0.1')) | [
"The",
"mod",
"operator",
"is",
"prone",
"to",
"floating",
"point",
"errors",
"so",
"use",
"decimal",
"."
] | d686fa3cd0551cacfc5630c8e7b5fa75e6dcfdf5 | https://github.com/disqus/gutter/blob/d686fa3cd0551cacfc5630c8e7b5fa75e6dcfdf5/gutter/client/operators/misc.py#L16-L29 | train |
disqus/gutter | gutter/client/models.py | Switch.enabled_for | def enabled_for(self, inpt):
"""
Checks to see if this switch is enabled for the provided input.
If ``compounded``, all switch conditions must be ``True`` for the switch
to be enabled. Otherwise, *any* condition needs to be ``True`` for the
switch to be enabled.
The sw... | python | def enabled_for(self, inpt):
"""
Checks to see if this switch is enabled for the provided input.
If ``compounded``, all switch conditions must be ``True`` for the switch
to be enabled. Otherwise, *any* condition needs to be ``True`` for the
switch to be enabled.
The sw... | [
"def",
"enabled_for",
"(",
"self",
",",
"inpt",
")",
":",
"signals",
".",
"switch_checked",
".",
"call",
"(",
"self",
")",
"signal_decorated",
"=",
"partial",
"(",
"self",
".",
"__signal_and_return",
",",
"inpt",
")",
"if",
"self",
".",
"state",
"is",
"s... | Checks to see if this switch is enabled for the provided input.
If ``compounded``, all switch conditions must be ``True`` for the switch
to be enabled. Otherwise, *any* condition needs to be ``True`` for the
switch to be enabled.
The switch state is then checked to see if it is ``GLOB... | [
"Checks",
"to",
"see",
"if",
"this",
"switch",
"is",
"enabled",
"for",
"the",
"provided",
"input",
"."
] | d686fa3cd0551cacfc5630c8e7b5fa75e6dcfdf5 | https://github.com/disqus/gutter/blob/d686fa3cd0551cacfc5630c8e7b5fa75e6dcfdf5/gutter/client/models.py#L150-L187 | train |
disqus/gutter | gutter/client/models.py | Condition.call | def call(self, inpt):
"""
Returns if the condition applies to the ``inpt``.
If the class ``inpt`` is an instance of is not the same class as the
condition's own ``argument``, then ``False`` is returned. This also
applies to the ``NONE`` input.
Otherwise, ``argument`` i... | python | def call(self, inpt):
"""
Returns if the condition applies to the ``inpt``.
If the class ``inpt`` is an instance of is not the same class as the
condition's own ``argument``, then ``False`` is returned. This also
applies to the ``NONE`` input.
Otherwise, ``argument`` i... | [
"def",
"call",
"(",
"self",
",",
"inpt",
")",
":",
"if",
"inpt",
"is",
"Manager",
".",
"NONE_INPUT",
":",
"return",
"False",
"# Call (construct) the argument with the input object",
"argument_instance",
"=",
"self",
".",
"argument",
"(",
"inpt",
")",
"if",
"not"... | Returns if the condition applies to the ``inpt``.
If the class ``inpt`` is an instance of is not the same class as the
condition's own ``argument``, then ``False`` is returned. This also
applies to the ``NONE`` input.
Otherwise, ``argument`` is called, with ``inpt`` as the instance an... | [
"Returns",
"if",
"the",
"condition",
"applies",
"to",
"the",
"inpt",
"."
] | d686fa3cd0551cacfc5630c8e7b5fa75e6dcfdf5 | https://github.com/disqus/gutter/blob/d686fa3cd0551cacfc5630c8e7b5fa75e6dcfdf5/gutter/client/models.py#L333-L362 | train |
disqus/gutter | gutter/client/models.py | Manager.switches | def switches(self):
"""
List of all switches currently registered.
"""
results = [
switch for name, switch in self.storage.iteritems()
if name.startswith(self.__joined_namespace)
]
return results | python | def switches(self):
"""
List of all switches currently registered.
"""
results = [
switch for name, switch in self.storage.iteritems()
if name.startswith(self.__joined_namespace)
]
return results | [
"def",
"switches",
"(",
"self",
")",
":",
"results",
"=",
"[",
"switch",
"for",
"name",
",",
"switch",
"in",
"self",
".",
"storage",
".",
"iteritems",
"(",
")",
"if",
"name",
".",
"startswith",
"(",
"self",
".",
"__joined_namespace",
")",
"]",
"return"... | List of all switches currently registered. | [
"List",
"of",
"all",
"switches",
"currently",
"registered",
"."
] | d686fa3cd0551cacfc5630c8e7b5fa75e6dcfdf5 | https://github.com/disqus/gutter/blob/d686fa3cd0551cacfc5630c8e7b5fa75e6dcfdf5/gutter/client/models.py#L438-L447 | train |
disqus/gutter | gutter/client/models.py | Manager.switch | def switch(self, name):
"""
Returns the switch with the provided ``name``.
If ``autocreate`` is set to ``True`` and no switch with that name
exists, a ``DISABLED`` switch will be with that name.
Keyword Arguments:
name -- A name of a switch.
"""
try:
... | python | def switch(self, name):
"""
Returns the switch with the provided ``name``.
If ``autocreate`` is set to ``True`` and no switch with that name
exists, a ``DISABLED`` switch will be with that name.
Keyword Arguments:
name -- A name of a switch.
"""
try:
... | [
"def",
"switch",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"switch",
"=",
"self",
".",
"storage",
"[",
"self",
".",
"__namespaced",
"(",
"name",
")",
"]",
"except",
"KeyError",
":",
"if",
"not",
"self",
".",
"autocreate",
":",
"raise",
"ValueEr... | Returns the switch with the provided ``name``.
If ``autocreate`` is set to ``True`` and no switch with that name
exists, a ``DISABLED`` switch will be with that name.
Keyword Arguments:
name -- A name of a switch. | [
"Returns",
"the",
"switch",
"with",
"the",
"provided",
"name",
"."
] | d686fa3cd0551cacfc5630c8e7b5fa75e6dcfdf5 | https://github.com/disqus/gutter/blob/d686fa3cd0551cacfc5630c8e7b5fa75e6dcfdf5/gutter/client/models.py#L449-L468 | train |
disqus/gutter | gutter/client/models.py | Manager.register | def register(self, switch, signal=signals.switch_registered):
'''
Register a switch and persist it to the storage.
'''
if not switch.name:
raise ValueError('Switch name cannot be blank')
switch.manager = self
self.__persist(switch)
signal.call(switch... | python | def register(self, switch, signal=signals.switch_registered):
'''
Register a switch and persist it to the storage.
'''
if not switch.name:
raise ValueError('Switch name cannot be blank')
switch.manager = self
self.__persist(switch)
signal.call(switch... | [
"def",
"register",
"(",
"self",
",",
"switch",
",",
"signal",
"=",
"signals",
".",
"switch_registered",
")",
":",
"if",
"not",
"switch",
".",
"name",
":",
"raise",
"ValueError",
"(",
"'Switch name cannot be blank'",
")",
"switch",
".",
"manager",
"=",
"self"... | Register a switch and persist it to the storage. | [
"Register",
"a",
"switch",
"and",
"persist",
"it",
"to",
"the",
"storage",
"."
] | d686fa3cd0551cacfc5630c8e7b5fa75e6dcfdf5 | https://github.com/disqus/gutter/blob/d686fa3cd0551cacfc5630c8e7b5fa75e6dcfdf5/gutter/client/models.py#L479-L489 | train |
kaste/mockito-python | mockito/mockito.py | verify | def verify(obj, times=1, atleast=None, atmost=None, between=None,
inorder=False):
"""Central interface to verify interactions.
`verify` uses a fluent interface::
verify(<obj>, times=2).<method_name>(<args>)
`args` can be as concrete as necessary. Often a catch-all is enough,
especi... | python | def verify(obj, times=1, atleast=None, atmost=None, between=None,
inorder=False):
"""Central interface to verify interactions.
`verify` uses a fluent interface::
verify(<obj>, times=2).<method_name>(<args>)
`args` can be as concrete as necessary. Often a catch-all is enough,
especi... | [
"def",
"verify",
"(",
"obj",
",",
"times",
"=",
"1",
",",
"atleast",
"=",
"None",
",",
"atmost",
"=",
"None",
",",
"between",
"=",
"None",
",",
"inorder",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"obj",
"=",
... | Central interface to verify interactions.
`verify` uses a fluent interface::
verify(<obj>, times=2).<method_name>(<args>)
`args` can be as concrete as necessary. Often a catch-all is enough,
especially if you're working with strict mocks, bc they throw at call
time on unwanted, unconfigured a... | [
"Central",
"interface",
"to",
"verify",
"interactions",
"."
] | d6b22b003f56ee5b156dbd9d8ba209faf35b6713 | https://github.com/kaste/mockito-python/blob/d6b22b003f56ee5b156dbd9d8ba209faf35b6713/mockito/mockito.py#L100-L140 | train |
kaste/mockito-python | mockito/mockito.py | when | def when(obj, strict=None):
"""Central interface to stub functions on a given `obj`
`obj` should be a module, a class or an instance of a class; it can be
a Dummy you created with :func:`mock`. ``when`` exposes a fluent interface
where you configure a stub in three steps::
when(<obj>).<method_... | python | def when(obj, strict=None):
"""Central interface to stub functions on a given `obj`
`obj` should be a module, a class or an instance of a class; it can be
a Dummy you created with :func:`mock`. ``when`` exposes a fluent interface
where you configure a stub in three steps::
when(<obj>).<method_... | [
"def",
"when",
"(",
"obj",
",",
"strict",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"obj",
"=",
"get_obj",
"(",
"obj",
")",
"if",
"strict",
"is",
"None",
":",
"strict",
"=",
"True",
"theMock",
"=",
"_get_mock",
... | Central interface to stub functions on a given `obj`
`obj` should be a module, a class or an instance of a class; it can be
a Dummy you created with :func:`mock`. ``when`` exposes a fluent interface
where you configure a stub in three steps::
when(<obj>).<method_name>(<args>).thenReturn(<value>)
... | [
"Central",
"interface",
"to",
"stub",
"functions",
"on",
"a",
"given",
"obj"
] | d6b22b003f56ee5b156dbd9d8ba209faf35b6713 | https://github.com/kaste/mockito-python/blob/d6b22b003f56ee5b156dbd9d8ba209faf35b6713/mockito/mockito.py#L151-L227 | train |
kaste/mockito-python | mockito/mockito.py | when2 | def when2(fn, *args, **kwargs):
"""Stub a function call with the given arguments
Exposes a more pythonic interface than :func:`when`. See :func:`when` for
more documentation.
Returns `AnswerSelector` interface which exposes `thenReturn`,
`thenRaise`, and `thenAnswer` as usual. Always `strict`.
... | python | def when2(fn, *args, **kwargs):
"""Stub a function call with the given arguments
Exposes a more pythonic interface than :func:`when`. See :func:`when` for
more documentation.
Returns `AnswerSelector` interface which exposes `thenReturn`,
`thenRaise`, and `thenAnswer` as usual. Always `strict`.
... | [
"def",
"when2",
"(",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
",",
"name",
"=",
"get_obj_attr_tuple",
"(",
"fn",
")",
"theMock",
"=",
"_get_mock",
"(",
"obj",
",",
"strict",
"=",
"True",
")",
"return",
"invocation",
".",
"S... | Stub a function call with the given arguments
Exposes a more pythonic interface than :func:`when`. See :func:`when` for
more documentation.
Returns `AnswerSelector` interface which exposes `thenReturn`,
`thenRaise`, and `thenAnswer` as usual. Always `strict`.
Usage::
# Given `dog` is an ... | [
"Stub",
"a",
"function",
"call",
"with",
"the",
"given",
"arguments"
] | d6b22b003f56ee5b156dbd9d8ba209faf35b6713 | https://github.com/kaste/mockito-python/blob/d6b22b003f56ee5b156dbd9d8ba209faf35b6713/mockito/mockito.py#L230-L250 | train |
kaste/mockito-python | mockito/mockito.py | patch | def patch(fn, attr_or_replacement, replacement=None):
"""Patch/Replace a function.
This is really like monkeypatching, but *note* that all interactions
will be recorded and can be verified. That is, using `patch` you stay in
the domain of mockito.
Two ways to call this. Either::
patch(os.... | python | def patch(fn, attr_or_replacement, replacement=None):
"""Patch/Replace a function.
This is really like monkeypatching, but *note* that all interactions
will be recorded and can be verified. That is, using `patch` you stay in
the domain of mockito.
Two ways to call this. Either::
patch(os.... | [
"def",
"patch",
"(",
"fn",
",",
"attr_or_replacement",
",",
"replacement",
"=",
"None",
")",
":",
"if",
"replacement",
"is",
"None",
":",
"replacement",
"=",
"attr_or_replacement",
"return",
"when2",
"(",
"fn",
",",
"Ellipsis",
")",
".",
"thenAnswer",
"(",
... | Patch/Replace a function.
This is really like monkeypatching, but *note* that all interactions
will be recorded and can be verified. That is, using `patch` you stay in
the domain of mockito.
Two ways to call this. Either::
patch(os.path.exists, lambda str: True) # two arguments
# OR
... | [
"Patch",
"/",
"Replace",
"a",
"function",
"."
] | d6b22b003f56ee5b156dbd9d8ba209faf35b6713 | https://github.com/kaste/mockito-python/blob/d6b22b003f56ee5b156dbd9d8ba209faf35b6713/mockito/mockito.py#L253-L280 | train |
kaste/mockito-python | mockito/mockito.py | expect | def expect(obj, strict=None,
times=None, atleast=None, atmost=None, between=None):
"""Stub a function call, and set up an expected call count.
Usage::
# Given `dog` is an instance of a `Dog`
expect(dog, times=1).bark('Wuff').thenReturn('Miau')
dog.bark('Wuff')
dog.ba... | python | def expect(obj, strict=None,
times=None, atleast=None, atmost=None, between=None):
"""Stub a function call, and set up an expected call count.
Usage::
# Given `dog` is an instance of a `Dog`
expect(dog, times=1).bark('Wuff').thenReturn('Miau')
dog.bark('Wuff')
dog.ba... | [
"def",
"expect",
"(",
"obj",
",",
"strict",
"=",
"None",
",",
"times",
"=",
"None",
",",
"atleast",
"=",
"None",
",",
"atmost",
"=",
"None",
",",
"between",
"=",
"None",
")",
":",
"if",
"strict",
"is",
"None",
":",
"strict",
"=",
"True",
"theMock",... | Stub a function call, and set up an expected call count.
Usage::
# Given `dog` is an instance of a `Dog`
expect(dog, times=1).bark('Wuff').thenReturn('Miau')
dog.bark('Wuff')
dog.bark('Wuff') # will throw at call time: too many invocations
# maybe if you need to ensure th... | [
"Stub",
"a",
"function",
"call",
"and",
"set",
"up",
"an",
"expected",
"call",
"count",
"."
] | d6b22b003f56ee5b156dbd9d8ba209faf35b6713 | https://github.com/kaste/mockito-python/blob/d6b22b003f56ee5b156dbd9d8ba209faf35b6713/mockito/mockito.py#L284-L317 | train |
kaste/mockito-python | mockito/mockito.py | unstub | def unstub(*objs):
"""Unstubs all stubbed methods and functions
If you don't pass in any argument, *all* registered mocks and
patched modules, classes etc. will be unstubbed.
Note that additionally, the underlying registry will be cleaned.
After an `unstub` you can't :func:`verify` anymore because... | python | def unstub(*objs):
"""Unstubs all stubbed methods and functions
If you don't pass in any argument, *all* registered mocks and
patched modules, classes etc. will be unstubbed.
Note that additionally, the underlying registry will be cleaned.
After an `unstub` you can't :func:`verify` anymore because... | [
"def",
"unstub",
"(",
"*",
"objs",
")",
":",
"if",
"objs",
":",
"for",
"obj",
"in",
"objs",
":",
"mock_registry",
".",
"unstub",
"(",
"obj",
")",
"else",
":",
"mock_registry",
".",
"unstub_all",
"(",
")"
] | Unstubs all stubbed methods and functions
If you don't pass in any argument, *all* registered mocks and
patched modules, classes etc. will be unstubbed.
Note that additionally, the underlying registry will be cleaned.
After an `unstub` you can't :func:`verify` anymore because all
interactions will... | [
"Unstubs",
"all",
"stubbed",
"methods",
"and",
"functions"
] | d6b22b003f56ee5b156dbd9d8ba209faf35b6713 | https://github.com/kaste/mockito-python/blob/d6b22b003f56ee5b156dbd9d8ba209faf35b6713/mockito/mockito.py#L321-L336 | train |
kaste/mockito-python | mockito/mockito.py | verifyZeroInteractions | def verifyZeroInteractions(*objs):
"""Verify that no methods have been called on given objs.
Note that strict mocks usually throw early on unexpected, unstubbed
invocations. Partial mocks ('monkeypatched' objects or modules) do not
support this functionality at all, bc only for the stubbed invocations
... | python | def verifyZeroInteractions(*objs):
"""Verify that no methods have been called on given objs.
Note that strict mocks usually throw early on unexpected, unstubbed
invocations. Partial mocks ('monkeypatched' objects or modules) do not
support this functionality at all, bc only for the stubbed invocations
... | [
"def",
"verifyZeroInteractions",
"(",
"*",
"objs",
")",
":",
"for",
"obj",
"in",
"objs",
":",
"theMock",
"=",
"_get_mock_or_raise",
"(",
"obj",
")",
"if",
"len",
"(",
"theMock",
".",
"invocations",
")",
">",
"0",
":",
"raise",
"VerificationError",
"(",
"... | Verify that no methods have been called on given objs.
Note that strict mocks usually throw early on unexpected, unstubbed
invocations. Partial mocks ('monkeypatched' objects or modules) do not
support this functionality at all, bc only for the stubbed invocations
the actual usage gets recorded. So thi... | [
"Verify",
"that",
"no",
"methods",
"have",
"been",
"called",
"on",
"given",
"objs",
"."
] | d6b22b003f56ee5b156dbd9d8ba209faf35b6713 | https://github.com/kaste/mockito-python/blob/d6b22b003f56ee5b156dbd9d8ba209faf35b6713/mockito/mockito.py#L364-L379 | train |
kaste/mockito-python | mockito/mockito.py | verifyNoUnwantedInteractions | def verifyNoUnwantedInteractions(*objs):
"""Verifies that expectations set via `expect` are met
E.g.::
expect(os.path, times=1).exists(...).thenReturn(True)
os.path('/foo')
verifyNoUnwantedInteractions(os.path) # ok, called once
If you leave out the argument *all* registered obje... | python | def verifyNoUnwantedInteractions(*objs):
"""Verifies that expectations set via `expect` are met
E.g.::
expect(os.path, times=1).exists(...).thenReturn(True)
os.path('/foo')
verifyNoUnwantedInteractions(os.path) # ok, called once
If you leave out the argument *all* registered obje... | [
"def",
"verifyNoUnwantedInteractions",
"(",
"*",
"objs",
")",
":",
"if",
"objs",
":",
"theMocks",
"=",
"map",
"(",
"_get_mock_or_raise",
",",
"objs",
")",
"else",
":",
"theMocks",
"=",
"mock_registry",
".",
"get_registered_mocks",
"(",
")",
"for",
"mock",
"i... | Verifies that expectations set via `expect` are met
E.g.::
expect(os.path, times=1).exists(...).thenReturn(True)
os.path('/foo')
verifyNoUnwantedInteractions(os.path) # ok, called once
If you leave out the argument *all* registered objects will
be checked.
.. note:: **DANGER... | [
"Verifies",
"that",
"expectations",
"set",
"via",
"expect",
"are",
"met"
] | d6b22b003f56ee5b156dbd9d8ba209faf35b6713 | https://github.com/kaste/mockito-python/blob/d6b22b003f56ee5b156dbd9d8ba209faf35b6713/mockito/mockito.py#L383-L409 | train |
kaste/mockito-python | mockito/mockito.py | verifyStubbedInvocationsAreUsed | def verifyStubbedInvocationsAreUsed(*objs):
"""Ensure stubs are actually used.
This functions just ensures that stubbed methods are actually used. Its
purpose is to detect interface changes after refactorings. It is meant
to be invoked usually without arguments just before :func:`unstub`.
"""
... | python | def verifyStubbedInvocationsAreUsed(*objs):
"""Ensure stubs are actually used.
This functions just ensures that stubbed methods are actually used. Its
purpose is to detect interface changes after refactorings. It is meant
to be invoked usually without arguments just before :func:`unstub`.
"""
... | [
"def",
"verifyStubbedInvocationsAreUsed",
"(",
"*",
"objs",
")",
":",
"if",
"objs",
":",
"theMocks",
"=",
"map",
"(",
"_get_mock_or_raise",
",",
"objs",
")",
"else",
":",
"theMocks",
"=",
"mock_registry",
".",
"get_registered_mocks",
"(",
")",
"for",
"mock",
... | Ensure stubs are actually used.
This functions just ensures that stubbed methods are actually used. Its
purpose is to detect interface changes after refactorings. It is meant
to be invoked usually without arguments just before :func:`unstub`. | [
"Ensure",
"stubs",
"are",
"actually",
"used",
"."
] | d6b22b003f56ee5b156dbd9d8ba209faf35b6713 | https://github.com/kaste/mockito-python/blob/d6b22b003f56ee5b156dbd9d8ba209faf35b6713/mockito/mockito.py#L411-L428 | train |
kaste/mockito-python | mockito/utils.py | get_function_host | def get_function_host(fn):
"""Destructure a given function into its host and its name.
The 'host' of a function is a module, for methods it is usually its
instance or its class. This is safe only for methods, for module wide,
globally declared names it must be considered experimental.
For all reas... | python | def get_function_host(fn):
"""Destructure a given function into its host and its name.
The 'host' of a function is a module, for methods it is usually its
instance or its class. This is safe only for methods, for module wide,
globally declared names it must be considered experimental.
For all reas... | [
"def",
"get_function_host",
"(",
"fn",
")",
":",
"obj",
"=",
"None",
"try",
":",
"name",
"=",
"fn",
".",
"__name__",
"obj",
"=",
"fn",
".",
"__self__",
"except",
"AttributeError",
":",
"pass",
"if",
"obj",
"is",
"None",
":",
"# Due to how python imports wo... | Destructure a given function into its host and its name.
The 'host' of a function is a module, for methods it is usually its
instance or its class. This is safe only for methods, for module wide,
globally declared names it must be considered experimental.
For all reasonable fn: ``getattr(*get_function... | [
"Destructure",
"a",
"given",
"function",
"into",
"its",
"host",
"and",
"its",
"name",
"."
] | d6b22b003f56ee5b156dbd9d8ba209faf35b6713 | https://github.com/kaste/mockito-python/blob/d6b22b003f56ee5b156dbd9d8ba209faf35b6713/mockito/utils.py#L23-L66 | train |
kaste/mockito-python | mockito/utils.py | get_obj | def get_obj(path):
"""Return obj for given dotted path.
Typical inputs for `path` are 'os' or 'os.path' in which case you get a
module; or 'os.path.exists' in which case you get a function from that
module.
Just returns the given input in case it is not a str.
Note: Relative imports not suppo... | python | def get_obj(path):
"""Return obj for given dotted path.
Typical inputs for `path` are 'os' or 'os.path' in which case you get a
module; or 'os.path.exists' in which case you get a function from that
module.
Just returns the given input in case it is not a str.
Note: Relative imports not suppo... | [
"def",
"get_obj",
"(",
"path",
")",
":",
"# Since we usually pass in mocks here; duck typing is not appropriate",
"# (mocks respond to every attribute).",
"if",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"return",
"path",
"if",
"path",
".",
"startswith",
"(... | Return obj for given dotted path.
Typical inputs for `path` are 'os' or 'os.path' in which case you get a
module; or 'os.path.exists' in which case you get a function from that
module.
Just returns the given input in case it is not a str.
Note: Relative imports not supported.
Raises ImportErr... | [
"Return",
"obj",
"for",
"given",
"dotted",
"path",
"."
] | d6b22b003f56ee5b156dbd9d8ba209faf35b6713 | https://github.com/kaste/mockito-python/blob/d6b22b003f56ee5b156dbd9d8ba209faf35b6713/mockito/utils.py#L107-L150 | train |
kaste/mockito-python | mockito/utils.py | get_obj_attr_tuple | def get_obj_attr_tuple(path):
"""Split path into (obj, attribute) tuple.
Given `path` is 'os.path.exists' will thus return `(os.path, 'exists')`
If path is not a str, delegates to `get_function_host(path)`
"""
if not isinstance(path, str):
return get_function_host(path)
if path.start... | python | def get_obj_attr_tuple(path):
"""Split path into (obj, attribute) tuple.
Given `path` is 'os.path.exists' will thus return `(os.path, 'exists')`
If path is not a str, delegates to `get_function_host(path)`
"""
if not isinstance(path, str):
return get_function_host(path)
if path.start... | [
"def",
"get_obj_attr_tuple",
"(",
"path",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"return",
"get_function_host",
"(",
"path",
")",
"if",
"path",
".",
"startswith",
"(",
"'.'",
")",
":",
"raise",
"TypeError",
"(",
"'relativ... | Split path into (obj, attribute) tuple.
Given `path` is 'os.path.exists' will thus return `(os.path, 'exists')`
If path is not a str, delegates to `get_function_host(path)` | [
"Split",
"path",
"into",
"(",
"obj",
"attribute",
")",
"tuple",
"."
] | d6b22b003f56ee5b156dbd9d8ba209faf35b6713 | https://github.com/kaste/mockito-python/blob/d6b22b003f56ee5b156dbd9d8ba209faf35b6713/mockito/utils.py#L152-L171 | train |
kaste/mockito-python | mockito/spying.py | spy | def spy(object):
"""Spy an object.
Spying means that all functions will behave as before, so they will
be side effects, but the interactions can be verified afterwards.
Returns Dummy-like, almost empty object as proxy to `object`.
The *returned* object must be injected and used by the code under ... | python | def spy(object):
"""Spy an object.
Spying means that all functions will behave as before, so they will
be side effects, but the interactions can be verified afterwards.
Returns Dummy-like, almost empty object as proxy to `object`.
The *returned* object must be injected and used by the code under ... | [
"def",
"spy",
"(",
"object",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"object",
")",
"or",
"inspect",
".",
"ismodule",
"(",
"object",
")",
":",
"class_",
"=",
"None",
"else",
":",
"class_",
"=",
"object",
".",
"__class__",
"class",
"Spy",
"(",... | Spy an object.
Spying means that all functions will behave as before, so they will
be side effects, but the interactions can be verified afterwards.
Returns Dummy-like, almost empty object as proxy to `object`.
The *returned* object must be injected and used by the code under test;
after that all... | [
"Spy",
"an",
"object",
"."
] | d6b22b003f56ee5b156dbd9d8ba209faf35b6713 | https://github.com/kaste/mockito-python/blob/d6b22b003f56ee5b156dbd9d8ba209faf35b6713/mockito/spying.py#L33-L78 | train |
kaste/mockito-python | mockito/spying.py | spy2 | def spy2(fn): # type: (...) -> None
"""Spy usage of given `fn`.
Patches the module, class or object `fn` lives in, so that all
interactions can be recorded; otherwise executes `fn` as before, so
that all side effects happen as before.
E.g.::
import time
spy(time.time)
do_... | python | def spy2(fn): # type: (...) -> None
"""Spy usage of given `fn`.
Patches the module, class or object `fn` lives in, so that all
interactions can be recorded; otherwise executes `fn` as before, so
that all side effects happen as before.
E.g.::
import time
spy(time.time)
do_... | [
"def",
"spy2",
"(",
"fn",
")",
":",
"# type: (...) -> None",
"if",
"isinstance",
"(",
"fn",
",",
"str",
")",
":",
"answer",
"=",
"get_obj",
"(",
"fn",
")",
"else",
":",
"answer",
"=",
"fn",
"when2",
"(",
"fn",
",",
"Ellipsis",
")",
".",
"thenAnswer",... | Spy usage of given `fn`.
Patches the module, class or object `fn` lives in, so that all
interactions can be recorded; otherwise executes `fn` as before, so
that all side effects happen as before.
E.g.::
import time
spy(time.time)
do_work(...) # nothing injected, uses global p... | [
"Spy",
"usage",
"of",
"given",
"fn",
"."
] | d6b22b003f56ee5b156dbd9d8ba209faf35b6713 | https://github.com/kaste/mockito-python/blob/d6b22b003f56ee5b156dbd9d8ba209faf35b6713/mockito/spying.py#L81-L104 | train |
kaste/mockito-python | mockito/mocking.py | mock | def mock(config_or_spec=None, spec=None, strict=OMITTED):
"""Create 'empty' objects ('Mocks').
Will create an empty unconfigured object, that you can pass
around. All interactions (method calls) will be recorded and can be
verified using :func:`verify` et.al.
A plain `mock()` will be not `strict`,... | python | def mock(config_or_spec=None, spec=None, strict=OMITTED):
"""Create 'empty' objects ('Mocks').
Will create an empty unconfigured object, that you can pass
around. All interactions (method calls) will be recorded and can be
verified using :func:`verify` et.al.
A plain `mock()` will be not `strict`,... | [
"def",
"mock",
"(",
"config_or_spec",
"=",
"None",
",",
"spec",
"=",
"None",
",",
"strict",
"=",
"OMITTED",
")",
":",
"if",
"type",
"(",
"config_or_spec",
")",
"is",
"dict",
":",
"config",
"=",
"config_or_spec",
"else",
":",
"config",
"=",
"{",
"}",
... | Create 'empty' objects ('Mocks').
Will create an empty unconfigured object, that you can pass
around. All interactions (method calls) will be recorded and can be
verified using :func:`verify` et.al.
A plain `mock()` will be not `strict`, and thus all methods regardless
of the arguments will return... | [
"Create",
"empty",
"objects",
"(",
"Mocks",
")",
"."
] | d6b22b003f56ee5b156dbd9d8ba209faf35b6713 | https://github.com/kaste/mockito-python/blob/d6b22b003f56ee5b156dbd9d8ba209faf35b6713/mockito/mocking.py#L193-L279 | train |
davidblaisonneau-orange/foreman | foreman/smartProxies.py | SmartProxies.importPuppetClasses | def importPuppetClasses(self, smartProxyId):
""" Function importPuppetClasses
Force the reload of puppet classes
@param smartProxyId: smartProxy Id
@return RETURN: the API result
"""
return self.api.create('{}/{}/import_puppetclasses'
.form... | python | def importPuppetClasses(self, smartProxyId):
""" Function importPuppetClasses
Force the reload of puppet classes
@param smartProxyId: smartProxy Id
@return RETURN: the API result
"""
return self.api.create('{}/{}/import_puppetclasses'
.form... | [
"def",
"importPuppetClasses",
"(",
"self",
",",
"smartProxyId",
")",
":",
"return",
"self",
".",
"api",
".",
"create",
"(",
"'{}/{}/import_puppetclasses'",
".",
"format",
"(",
"self",
".",
"objName",
",",
"smartProxyId",
")",
",",
"'{}'",
")"
] | Function importPuppetClasses
Force the reload of puppet classes
@param smartProxyId: smartProxy Id
@return RETURN: the API result | [
"Function",
"importPuppetClasses",
"Force",
"the",
"reload",
"of",
"puppet",
"classes"
] | acb8fd8d74657cfac3b25c82e9c6028b93eb6c92 | https://github.com/davidblaisonneau-orange/foreman/blob/acb8fd8d74657cfac3b25c82e9c6028b93eb6c92/foreman/smartProxies.py#L29-L37 | train |
developersociety/django-glitter | glitter/templates.py | get_templates | def get_templates(model):
""" Return a list of templates usable by a model. """
for template_name, template in templates.items():
if issubclass(template.model, model):
yield (template_name, template.layout._meta.verbose_name) | python | def get_templates(model):
""" Return a list of templates usable by a model. """
for template_name, template in templates.items():
if issubclass(template.model, model):
yield (template_name, template.layout._meta.verbose_name) | [
"def",
"get_templates",
"(",
"model",
")",
":",
"for",
"template_name",
",",
"template",
"in",
"templates",
".",
"items",
"(",
")",
":",
"if",
"issubclass",
"(",
"template",
".",
"model",
",",
"model",
")",
":",
"yield",
"(",
"template_name",
",",
"templ... | Return a list of templates usable by a model. | [
"Return",
"a",
"list",
"of",
"templates",
"usable",
"by",
"a",
"model",
"."
] | 2c0280ec83afee80deee94ee3934fc54239c2e87 | https://github.com/developersociety/django-glitter/blob/2c0280ec83afee80deee94ee3934fc54239c2e87/glitter/templates.py#L26-L30 | train |
developersociety/django-glitter | glitter/templates.py | attach | def attach(*layouts, **kwargs):
"""
Registers the given layout(s) classes
admin site:
@pages.register(Page)
class Default(PageLayout):
pass
"""
def _model_admin_wrapper(layout_class):
register(layout_class, layouts[0])
return layout_class
return _model_admin_wra... | python | def attach(*layouts, **kwargs):
"""
Registers the given layout(s) classes
admin site:
@pages.register(Page)
class Default(PageLayout):
pass
"""
def _model_admin_wrapper(layout_class):
register(layout_class, layouts[0])
return layout_class
return _model_admin_wra... | [
"def",
"attach",
"(",
"*",
"layouts",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_model_admin_wrapper",
"(",
"layout_class",
")",
":",
"register",
"(",
"layout_class",
",",
"layouts",
"[",
"0",
"]",
")",
"return",
"layout_class",
"return",
"_model_admin_wrap... | Registers the given layout(s) classes
admin site:
@pages.register(Page)
class Default(PageLayout):
pass | [
"Registers",
"the",
"given",
"layout",
"(",
"s",
")",
"classes",
"admin",
"site",
":"
] | 2c0280ec83afee80deee94ee3934fc54239c2e87 | https://github.com/developersociety/django-glitter/blob/2c0280ec83afee80deee94ee3934fc54239c2e87/glitter/templates.py#L38-L51 | train |
davidblaisonneau-orange/foreman | foreman/itemOperatingSystem.py | ItemOperatingSystem.enhance | def enhance(self):
""" Function enhance
Enhance the object with new item or enhanced items
"""
self.update({'os_default_templates':
SubDict(self.api, self.objName,
self.payloadObj, self.key,
SubItemOsDefaultTe... | python | def enhance(self):
""" Function enhance
Enhance the object with new item or enhanced items
"""
self.update({'os_default_templates':
SubDict(self.api, self.objName,
self.payloadObj, self.key,
SubItemOsDefaultTe... | [
"def",
"enhance",
"(",
"self",
")",
":",
"self",
".",
"update",
"(",
"{",
"'os_default_templates'",
":",
"SubDict",
"(",
"self",
".",
"api",
",",
"self",
".",
"objName",
",",
"self",
".",
"payloadObj",
",",
"self",
".",
"key",
",",
"SubItemOsDefaultTempl... | Function enhance
Enhance the object with new item or enhanced items | [
"Function",
"enhance",
"Enhance",
"the",
"object",
"with",
"new",
"item",
"or",
"enhanced",
"items"
] | acb8fd8d74657cfac3b25c82e9c6028b93eb6c92 | https://github.com/davidblaisonneau-orange/foreman/blob/acb8fd8d74657cfac3b25c82e9c6028b93eb6c92/foreman/itemOperatingSystem.py#L40-L63 | train |
quizl/quizler | quizler/lib.py | get_api_envs | def get_api_envs():
"""Get required API keys from environment variables."""
client_id = os.environ.get('CLIENT_ID')
user_id = os.environ.get('USER_ID')
if not client_id or not user_id:
raise ValueError('API keys are not found in the environment')
return client_id, user_id | python | def get_api_envs():
"""Get required API keys from environment variables."""
client_id = os.environ.get('CLIENT_ID')
user_id = os.environ.get('USER_ID')
if not client_id or not user_id:
raise ValueError('API keys are not found in the environment')
return client_id, user_id | [
"def",
"get_api_envs",
"(",
")",
":",
"client_id",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'CLIENT_ID'",
")",
"user_id",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'USER_ID'",
")",
"if",
"not",
"client_id",
"or",
"not",
"user_id",
":",
"raise",
... | Get required API keys from environment variables. | [
"Get",
"required",
"API",
"keys",
"from",
"environment",
"variables",
"."
] | 44b3fd91f7074e7013ffde8147455f45ebdccc46 | https://github.com/quizl/quizler/blob/44b3fd91f7074e7013ffde8147455f45ebdccc46/quizler/lib.py#L8-L14 | train |
quizl/quizler | quizler/lib.py | api_call | def api_call(method, end_point, params=None, client_id=None, access_token=None):
"""Call given API end_point with API keys.
:param method: HTTP method (e.g. 'get', 'delete').
:param end_point: API endpoint (e.g. 'users/john/sets').
:param params: Dictionary to be sent in the query string (e.g. {'myparam... | python | def api_call(method, end_point, params=None, client_id=None, access_token=None):
"""Call given API end_point with API keys.
:param method: HTTP method (e.g. 'get', 'delete').
:param end_point: API endpoint (e.g. 'users/john/sets').
:param params: Dictionary to be sent in the query string (e.g. {'myparam... | [
"def",
"api_call",
"(",
"method",
",",
"end_point",
",",
"params",
"=",
"None",
",",
"client_id",
"=",
"None",
",",
"access_token",
"=",
"None",
")",
":",
"if",
"bool",
"(",
"client_id",
")",
"==",
"bool",
"(",
"access_token",
")",
":",
"raise",
"Value... | Call given API end_point with API keys.
:param method: HTTP method (e.g. 'get', 'delete').
:param end_point: API endpoint (e.g. 'users/john/sets').
:param params: Dictionary to be sent in the query string (e.g. {'myparam': 'myval'})
:param client_id: Quizlet client ID as string.
:param access_token:... | [
"Call",
"given",
"API",
"end_point",
"with",
"API",
"keys",
".",
":",
"param",
"method",
":",
"HTTP",
"method",
"(",
"e",
".",
"g",
".",
"get",
"delete",
")",
".",
":",
"param",
"end_point",
":",
"API",
"endpoint",
"(",
"e",
".",
"g",
".",
"users",... | 44b3fd91f7074e7013ffde8147455f45ebdccc46 | https://github.com/quizl/quizler/blob/44b3fd91f7074e7013ffde8147455f45ebdccc46/quizler/lib.py#L17-L55 | train |
qubell/contrib-python-qubell-client | qubell/api/private/service.py | ServiceMixin.request_upload_secret | def request_upload_secret(self, secret_id):
"""
:return: json with "keyId" as secret and "url" for posting key
"""
return self._router.post_request_upload_secret(org_id=self.organizationId,
instance_id=self.instanceId,
... | python | def request_upload_secret(self, secret_id):
"""
:return: json with "keyId" as secret and "url" for posting key
"""
return self._router.post_request_upload_secret(org_id=self.organizationId,
instance_id=self.instanceId,
... | [
"def",
"request_upload_secret",
"(",
"self",
",",
"secret_id",
")",
":",
"return",
"self",
".",
"_router",
".",
"post_request_upload_secret",
"(",
"org_id",
"=",
"self",
".",
"organizationId",
",",
"instance_id",
"=",
"self",
".",
"instanceId",
",",
"secret_id",... | :return: json with "keyId" as secret and "url" for posting key | [
":",
"return",
":",
"json",
"with",
"keyId",
"as",
"secret",
"and",
"url",
"for",
"posting",
"key"
] | 4586ea11d5103c2ff9607d3ed922b5a0991b8845 | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/api/private/service.py#L119-L125 | train |
davidblaisonneau-orange/foreman | foreman/subnets.py | Subnets.checkAndCreate | def checkAndCreate(self, key, payload, domainId):
""" Function checkAndCreate
Check if a subnet exists and create it if not
@param key: The targeted subnet
@param payload: The targeted subnet description
@param domainId: The domainId to be attached wiuth the subnet
@retu... | python | def checkAndCreate(self, key, payload, domainId):
""" Function checkAndCreate
Check if a subnet exists and create it if not
@param key: The targeted subnet
@param payload: The targeted subnet description
@param domainId: The domainId to be attached wiuth the subnet
@retu... | [
"def",
"checkAndCreate",
"(",
"self",
",",
"key",
",",
"payload",
",",
"domainId",
")",
":",
"if",
"key",
"not",
"in",
"self",
":",
"self",
"[",
"key",
"]",
"=",
"payload",
"oid",
"=",
"self",
"[",
"key",
"]",
"[",
"'id'",
"]",
"if",
"not",
"oid"... | Function checkAndCreate
Check if a subnet exists and create it if not
@param key: The targeted subnet
@param payload: The targeted subnet description
@param domainId: The domainId to be attached wiuth the subnet
@return RETURN: The id of the subnet | [
"Function",
"checkAndCreate",
"Check",
"if",
"a",
"subnet",
"exists",
"and",
"create",
"it",
"if",
"not"
] | acb8fd8d74657cfac3b25c82e9c6028b93eb6c92 | https://github.com/davidblaisonneau-orange/foreman/blob/acb8fd8d74657cfac3b25c82e9c6028b93eb6c92/foreman/subnets.py#L29-L52 | train |
davidblaisonneau-orange/foreman | foreman/subnets.py | Subnets.removeDomain | def removeDomain(self, subnetId, domainId):
""" Function removeDomain
Delete a domain from a subnet
@param subnetId: The subnet Id
@param domainId: The domainId to be attached wiuth the subnet
@return RETURN: boolean
"""
subnetDomainIds = []
for domain in... | python | def removeDomain(self, subnetId, domainId):
""" Function removeDomain
Delete a domain from a subnet
@param subnetId: The subnet Id
@param domainId: The domainId to be attached wiuth the subnet
@return RETURN: boolean
"""
subnetDomainIds = []
for domain in... | [
"def",
"removeDomain",
"(",
"self",
",",
"subnetId",
",",
"domainId",
")",
":",
"subnetDomainIds",
"=",
"[",
"]",
"for",
"domain",
"in",
"self",
"[",
"subnetId",
"]",
"[",
"'domains'",
"]",
":",
"subnetDomainIds",
".",
"append",
"(",
"domain",
"[",
"'id'... | Function removeDomain
Delete a domain from a subnet
@param subnetId: The subnet Id
@param domainId: The domainId to be attached wiuth the subnet
@return RETURN: boolean | [
"Function",
"removeDomain",
"Delete",
"a",
"domain",
"from",
"a",
"subnet"
] | acb8fd8d74657cfac3b25c82e9c6028b93eb6c92 | https://github.com/davidblaisonneau-orange/foreman/blob/acb8fd8d74657cfac3b25c82e9c6028b93eb6c92/foreman/subnets.py#L54-L67 | train |
MatterMiners/cobald | cobald/daemon/runners/guard.py | exclusive | def exclusive(via=threading.Lock):
"""
Mark a callable as exclusive
:param via: factory for a Lock to guard the callable
Guards the callable against being entered again before completion.
Explicitly raises a :py:exc:`RuntimeError` on violation.
:note: If applied to a method, it is exclusive a... | python | def exclusive(via=threading.Lock):
"""
Mark a callable as exclusive
:param via: factory for a Lock to guard the callable
Guards the callable against being entered again before completion.
Explicitly raises a :py:exc:`RuntimeError` on violation.
:note: If applied to a method, it is exclusive a... | [
"def",
"exclusive",
"(",
"via",
"=",
"threading",
".",
"Lock",
")",
":",
"def",
"make_exclusive",
"(",
"fnc",
")",
":",
"fnc_guard",
"=",
"via",
"(",
")",
"@",
"functools",
".",
"wraps",
"(",
"fnc",
")",
"def",
"exclusive_call",
"(",
"*",
"args",
","... | Mark a callable as exclusive
:param via: factory for a Lock to guard the callable
Guards the callable against being entered again before completion.
Explicitly raises a :py:exc:`RuntimeError` on violation.
:note: If applied to a method, it is exclusive across all instances. | [
"Mark",
"a",
"callable",
"as",
"exclusive"
] | 264138de4382d1c9b53fabcbc6660e10b33a914d | https://github.com/MatterMiners/cobald/blob/264138de4382d1c9b53fabcbc6660e10b33a914d/cobald/daemon/runners/guard.py#L5-L29 | train |
MatterMiners/cobald | cobald/daemon/runners/service.py | service | def service(flavour):
r"""
Mark a class as implementing a Service
Each Service class must have a ``run`` method, which does not take any arguments.
This method is :py:meth:`~.ServiceRunner.adopt`\ ed after the daemon starts, unless
* the Service has been garbage collected, or
* the ServiceUnit... | python | def service(flavour):
r"""
Mark a class as implementing a Service
Each Service class must have a ``run`` method, which does not take any arguments.
This method is :py:meth:`~.ServiceRunner.adopt`\ ed after the daemon starts, unless
* the Service has been garbage collected, or
* the ServiceUnit... | [
"def",
"service",
"(",
"flavour",
")",
":",
"def",
"service_unit_decorator",
"(",
"raw_cls",
")",
":",
"__new__",
"=",
"raw_cls",
".",
"__new__",
"def",
"__new_service__",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"__new__",
... | r"""
Mark a class as implementing a Service
Each Service class must have a ``run`` method, which does not take any arguments.
This method is :py:meth:`~.ServiceRunner.adopt`\ ed after the daemon starts, unless
* the Service has been garbage collected, or
* the ServiceUnit has been :py:meth:`~.Serv... | [
"r",
"Mark",
"a",
"class",
"as",
"implementing",
"a",
"Service"
] | 264138de4382d1c9b53fabcbc6660e10b33a914d | https://github.com/MatterMiners/cobald/blob/264138de4382d1c9b53fabcbc6660e10b33a914d/cobald/daemon/runners/service.py#L54-L82 | train |
MatterMiners/cobald | cobald/daemon/runners/service.py | ServiceRunner.execute | def execute(self, payload, *args, flavour: ModuleType, **kwargs):
"""
Synchronously run ``payload`` and provide its output
If ``*args*`` and/or ``**kwargs`` are provided, pass them to ``payload`` upon execution.
"""
if args or kwargs:
payload = functools.partial(payl... | python | def execute(self, payload, *args, flavour: ModuleType, **kwargs):
"""
Synchronously run ``payload`` and provide its output
If ``*args*`` and/or ``**kwargs`` are provided, pass them to ``payload`` upon execution.
"""
if args or kwargs:
payload = functools.partial(payl... | [
"def",
"execute",
"(",
"self",
",",
"payload",
",",
"*",
"args",
",",
"flavour",
":",
"ModuleType",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
"or",
"kwargs",
":",
"payload",
"=",
"functools",
".",
"partial",
"(",
"payload",
",",
"*",
"args",
... | Synchronously run ``payload`` and provide its output
If ``*args*`` and/or ``**kwargs`` are provided, pass them to ``payload`` upon execution. | [
"Synchronously",
"run",
"payload",
"and",
"provide",
"its",
"output"
] | 264138de4382d1c9b53fabcbc6660e10b33a914d | https://github.com/MatterMiners/cobald/blob/264138de4382d1c9b53fabcbc6660e10b33a914d/cobald/daemon/runners/service.py#L97-L105 | train |
MatterMiners/cobald | cobald/daemon/runners/service.py | ServiceRunner.adopt | def adopt(self, payload, *args, flavour: ModuleType, **kwargs):
"""
Concurrently run ``payload`` in the background
If ``*args*`` and/or ``**kwargs`` are provided, pass them to ``payload`` upon execution.
"""
if args or kwargs:
payload = functools.partial(payload, *ar... | python | def adopt(self, payload, *args, flavour: ModuleType, **kwargs):
"""
Concurrently run ``payload`` in the background
If ``*args*`` and/or ``**kwargs`` are provided, pass them to ``payload`` upon execution.
"""
if args or kwargs:
payload = functools.partial(payload, *ar... | [
"def",
"adopt",
"(",
"self",
",",
"payload",
",",
"*",
"args",
",",
"flavour",
":",
"ModuleType",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
"or",
"kwargs",
":",
"payload",
"=",
"functools",
".",
"partial",
"(",
"payload",
",",
"*",
"args",
"... | Concurrently run ``payload`` in the background
If ``*args*`` and/or ``**kwargs`` are provided, pass them to ``payload`` upon execution. | [
"Concurrently",
"run",
"payload",
"in",
"the",
"background"
] | 264138de4382d1c9b53fabcbc6660e10b33a914d | https://github.com/MatterMiners/cobald/blob/264138de4382d1c9b53fabcbc6660e10b33a914d/cobald/daemon/runners/service.py#L107-L115 | train |
MatterMiners/cobald | cobald/daemon/runners/service.py | ServiceRunner.accept | def accept(self):
"""
Start accepting synchronous, asynchronous and service payloads
Since services are globally defined, only one :py:class:`ServiceRunner`
may :py:meth:`accept` payloads at any time.
"""
if self._meta_runner:
raise RuntimeError('payloads sch... | python | def accept(self):
"""
Start accepting synchronous, asynchronous and service payloads
Since services are globally defined, only one :py:class:`ServiceRunner`
may :py:meth:`accept` payloads at any time.
"""
if self._meta_runner:
raise RuntimeError('payloads sch... | [
"def",
"accept",
"(",
"self",
")",
":",
"if",
"self",
".",
"_meta_runner",
":",
"raise",
"RuntimeError",
"(",
"'payloads scheduled for %s before being started'",
"%",
"self",
")",
"self",
".",
"_must_shutdown",
"=",
"False",
"self",
".",
"_logger",
".",
"info",
... | Start accepting synchronous, asynchronous and service payloads
Since services are globally defined, only one :py:class:`ServiceRunner`
may :py:meth:`accept` payloads at any time. | [
"Start",
"accepting",
"synchronous",
"asynchronous",
"and",
"service",
"payloads"
] | 264138de4382d1c9b53fabcbc6660e10b33a914d | https://github.com/MatterMiners/cobald/blob/264138de4382d1c9b53fabcbc6660e10b33a914d/cobald/daemon/runners/service.py#L118-L133 | train |
MatterMiners/cobald | cobald/daemon/runners/service.py | ServiceRunner.shutdown | def shutdown(self):
"""Shutdown the accept loop and stop running payloads"""
self._must_shutdown = True
self._is_shutdown.wait()
self._meta_runner.stop() | python | def shutdown(self):
"""Shutdown the accept loop and stop running payloads"""
self._must_shutdown = True
self._is_shutdown.wait()
self._meta_runner.stop() | [
"def",
"shutdown",
"(",
"self",
")",
":",
"self",
".",
"_must_shutdown",
"=",
"True",
"self",
".",
"_is_shutdown",
".",
"wait",
"(",
")",
"self",
".",
"_meta_runner",
".",
"stop",
"(",
")"
] | Shutdown the accept loop and stop running payloads | [
"Shutdown",
"the",
"accept",
"loop",
"and",
"stop",
"running",
"payloads"
] | 264138de4382d1c9b53fabcbc6660e10b33a914d | https://github.com/MatterMiners/cobald/blob/264138de4382d1c9b53fabcbc6660e10b33a914d/cobald/daemon/runners/service.py#L135-L139 | train |
quantmind/agile-toolkit | agiletoolkit/github/milestones.py | milestones | def milestones(ctx, list, close):
"""View/edit/close milestones on github
"""
repos = get_repos(ctx.parent.agile.get('labels'))
if list:
_list_milestones(repos)
elif close:
click.echo('Closing milestones "%s"' % close)
_close_milestone(repos, close)
else:
click.ec... | python | def milestones(ctx, list, close):
"""View/edit/close milestones on github
"""
repos = get_repos(ctx.parent.agile.get('labels'))
if list:
_list_milestones(repos)
elif close:
click.echo('Closing milestones "%s"' % close)
_close_milestone(repos, close)
else:
click.ec... | [
"def",
"milestones",
"(",
"ctx",
",",
"list",
",",
"close",
")",
":",
"repos",
"=",
"get_repos",
"(",
"ctx",
".",
"parent",
".",
"agile",
".",
"get",
"(",
"'labels'",
")",
")",
"if",
"list",
":",
"_list_milestones",
"(",
"repos",
")",
"elif",
"close"... | View/edit/close milestones on github | [
"View",
"/",
"edit",
"/",
"close",
"milestones",
"on",
"github"
] | 96028e36a842c57b171907c20583a60d1045fec1 | https://github.com/quantmind/agile-toolkit/blob/96028e36a842c57b171907c20583a60d1045fec1/agiletoolkit/github/milestones.py#L13-L23 | train |
aroberge/experimental | experimental/core/console.py | start_console | def start_console(local_vars={}):
'''Starts a console; modified from code.interact'''
transforms.CONSOLE_ACTIVE = True
transforms.remove_not_allowed_in_console()
sys.ps1 = prompt
console = ExperimentalInteractiveConsole(locals=local_vars)
console.interact(banner=banner) | python | def start_console(local_vars={}):
'''Starts a console; modified from code.interact'''
transforms.CONSOLE_ACTIVE = True
transforms.remove_not_allowed_in_console()
sys.ps1 = prompt
console = ExperimentalInteractiveConsole(locals=local_vars)
console.interact(banner=banner) | [
"def",
"start_console",
"(",
"local_vars",
"=",
"{",
"}",
")",
":",
"transforms",
".",
"CONSOLE_ACTIVE",
"=",
"True",
"transforms",
".",
"remove_not_allowed_in_console",
"(",
")",
"sys",
".",
"ps1",
"=",
"prompt",
"console",
"=",
"ExperimentalInteractiveConsole",
... | Starts a console; modified from code.interact | [
"Starts",
"a",
"console",
";",
"modified",
"from",
"code",
".",
"interact"
] | 031a9be10698b429998436da748b8fdb86f18b47 | https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/core/console.py#L66-L72 | train |
aroberge/experimental | experimental/core/console.py | ExperimentalInteractiveConsole.push | def push(self, line):
"""Transform and push a line to the interpreter.
The line should not have a trailing newline; it may have
internal newlines. The line is appended to a buffer and the
interpreter's runsource() method is called with the
concatenated contents of the buffer as... | python | def push(self, line):
"""Transform and push a line to the interpreter.
The line should not have a trailing newline; it may have
internal newlines. The line is appended to a buffer and the
interpreter's runsource() method is called with the
concatenated contents of the buffer as... | [
"def",
"push",
"(",
"self",
",",
"line",
")",
":",
"if",
"transforms",
".",
"FROM_EXPERIMENTAL",
".",
"match",
"(",
"line",
")",
":",
"transforms",
".",
"add_transformers",
"(",
"line",
")",
"self",
".",
"buffer",
".",
"append",
"(",
"\"\\n\"",
")",
"e... | Transform and push a line to the interpreter.
The line should not have a trailing newline; it may have
internal newlines. The line is appended to a buffer and the
interpreter's runsource() method is called with the
concatenated contents of the buffer as source. If this
indicat... | [
"Transform",
"and",
"push",
"a",
"line",
"to",
"the",
"interpreter",
"."
] | 031a9be10698b429998436da748b8fdb86f18b47 | https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/core/console.py#L21-L63 | train |
frostming/atoml | atoml/encoder.py | dump | def dump(obj, f, preserve=False):
"""Write dict object into file
:param obj: the object to be dumped into toml
:param f: the file object
:param preserve: optional flag to preserve the inline table in result
"""
if not f.write:
raise TypeError('You can only dump an object into a file obj... | python | def dump(obj, f, preserve=False):
"""Write dict object into file
:param obj: the object to be dumped into toml
:param f: the file object
:param preserve: optional flag to preserve the inline table in result
"""
if not f.write:
raise TypeError('You can only dump an object into a file obj... | [
"def",
"dump",
"(",
"obj",
",",
"f",
",",
"preserve",
"=",
"False",
")",
":",
"if",
"not",
"f",
".",
"write",
":",
"raise",
"TypeError",
"(",
"'You can only dump an object into a file object'",
")",
"encoder",
"=",
"Encoder",
"(",
"f",
",",
"preserve",
"="... | Write dict object into file
:param obj: the object to be dumped into toml
:param f: the file object
:param preserve: optional flag to preserve the inline table in result | [
"Write",
"dict",
"object",
"into",
"file"
] | 85414ef77777366887a819a05b496d5279296cd2 | https://github.com/frostming/atoml/blob/85414ef77777366887a819a05b496d5279296cd2/atoml/encoder.py#L180-L190 | train |
frostming/atoml | atoml/encoder.py | dumps | def dumps(obj, preserve=False):
"""Stringifies a dict as toml
:param obj: the object to be dumped into toml
:param preserve: optional flag to preserve the inline table in result
"""
f = StringIO()
dump(obj, f, preserve)
return f.getvalue() | python | def dumps(obj, preserve=False):
"""Stringifies a dict as toml
:param obj: the object to be dumped into toml
:param preserve: optional flag to preserve the inline table in result
"""
f = StringIO()
dump(obj, f, preserve)
return f.getvalue() | [
"def",
"dumps",
"(",
"obj",
",",
"preserve",
"=",
"False",
")",
":",
"f",
"=",
"StringIO",
"(",
")",
"dump",
"(",
"obj",
",",
"f",
",",
"preserve",
")",
"return",
"f",
".",
"getvalue",
"(",
")"
] | Stringifies a dict as toml
:param obj: the object to be dumped into toml
:param preserve: optional flag to preserve the inline table in result | [
"Stringifies",
"a",
"dict",
"as",
"toml"
] | 85414ef77777366887a819a05b496d5279296cd2 | https://github.com/frostming/atoml/blob/85414ef77777366887a819a05b496d5279296cd2/atoml/encoder.py#L193-L201 | train |
alixedi/palal | palal/license.py | license_loader | def license_loader(lic_dir=LIC_DIR):
"""Loads licenses from the given directory."""
lics = []
for ln in os.listdir(lic_dir):
lp = os.path.join(lic_dir, ln)
with open(lp) as lf:
txt = lf.read()
lic = License(txt)
lics.append(lic)
return lics | python | def license_loader(lic_dir=LIC_DIR):
"""Loads licenses from the given directory."""
lics = []
for ln in os.listdir(lic_dir):
lp = os.path.join(lic_dir, ln)
with open(lp) as lf:
txt = lf.read()
lic = License(txt)
lics.append(lic)
return lics | [
"def",
"license_loader",
"(",
"lic_dir",
"=",
"LIC_DIR",
")",
":",
"lics",
"=",
"[",
"]",
"for",
"ln",
"in",
"os",
".",
"listdir",
"(",
"lic_dir",
")",
":",
"lp",
"=",
"os",
".",
"path",
".",
"join",
"(",
"lic_dir",
",",
"ln",
")",
"with",
"open"... | Loads licenses from the given directory. | [
"Loads",
"licenses",
"from",
"the",
"given",
"directory",
"."
] | 325359f66ac48a9f96efea0489aec353f8a40837 | https://github.com/alixedi/palal/blob/325359f66ac48a9f96efea0489aec353f8a40837/palal/license.py#L46-L55 | train |
alixedi/palal | palal/license.py | License.get_vector | def get_vector(self, max_choice=3):
"""Return pseudo-choice vectors."""
vec = {}
for dim in ['forbidden', 'required', 'permitted']:
if self.meta[dim] is None:
continue
dim_vec = map(lambda x: (x, max_choice), self.meta[dim])
vec[dim] = dict(dim... | python | def get_vector(self, max_choice=3):
"""Return pseudo-choice vectors."""
vec = {}
for dim in ['forbidden', 'required', 'permitted']:
if self.meta[dim] is None:
continue
dim_vec = map(lambda x: (x, max_choice), self.meta[dim])
vec[dim] = dict(dim... | [
"def",
"get_vector",
"(",
"self",
",",
"max_choice",
"=",
"3",
")",
":",
"vec",
"=",
"{",
"}",
"for",
"dim",
"in",
"[",
"'forbidden'",
",",
"'required'",
",",
"'permitted'",
"]",
":",
"if",
"self",
".",
"meta",
"[",
"dim",
"]",
"is",
"None",
":",
... | Return pseudo-choice vectors. | [
"Return",
"pseudo",
"-",
"choice",
"vectors",
"."
] | 325359f66ac48a9f96efea0489aec353f8a40837 | https://github.com/alixedi/palal/blob/325359f66ac48a9f96efea0489aec353f8a40837/palal/license.py#L35-L43 | train |
qubell/contrib-python-qubell-client | qubell/cli/__main__.py | entity | def entity(ctx, debug, uncolorize, **kwargs):
"""
CLI for tonomi.com using contrib-python-qubell-client
To enable completion:
eval "$(_NOMI_COMPLETE=source nomi)"
"""
global PROVIDER_CONFIG
if debug:
log.basicConfig(level=log.DEBUG)
log.getLogger("requests.packages.urlli... | python | def entity(ctx, debug, uncolorize, **kwargs):
"""
CLI for tonomi.com using contrib-python-qubell-client
To enable completion:
eval "$(_NOMI_COMPLETE=source nomi)"
"""
global PROVIDER_CONFIG
if debug:
log.basicConfig(level=log.DEBUG)
log.getLogger("requests.packages.urlli... | [
"def",
"entity",
"(",
"ctx",
",",
"debug",
",",
"uncolorize",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"PROVIDER_CONFIG",
"if",
"debug",
":",
"log",
".",
"basicConfig",
"(",
"level",
"=",
"log",
".",
"DEBUG",
")",
"log",
".",
"getLogger",
"(",
"\... | CLI for tonomi.com using contrib-python-qubell-client
To enable completion:
eval "$(_NOMI_COMPLETE=source nomi)" | [
"CLI",
"for",
"tonomi",
".",
"com",
"using",
"contrib",
"-",
"python",
"-",
"qubell",
"-",
"client"
] | 4586ea11d5103c2ff9607d3ed922b5a0991b8845 | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/cli/__main__.py#L128-L182 | train |
qubell/contrib-python-qubell-client | qubell/cli/__main__.py | import_app | def import_app(files, category, overwrite, id, name):
""" Upload application from file.
By default, file name will be used as application name, with "-vXX.YYY" suffix stripped.
Application is looked up by one of these classifiers, in order of priority:
app-id, app-name, filename.
If app-id is prov... | python | def import_app(files, category, overwrite, id, name):
""" Upload application from file.
By default, file name will be used as application name, with "-vXX.YYY" suffix stripped.
Application is looked up by one of these classifiers, in order of priority:
app-id, app-name, filename.
If app-id is prov... | [
"def",
"import_app",
"(",
"files",
",",
"category",
",",
"overwrite",
",",
"id",
",",
"name",
")",
":",
"platform",
"=",
"_get_platform",
"(",
")",
"org",
"=",
"platform",
".",
"get_organization",
"(",
"QUBELL",
"[",
"\"organization\"",
"]",
")",
"if",
"... | Upload application from file.
By default, file name will be used as application name, with "-vXX.YYY" suffix stripped.
Application is looked up by one of these classifiers, in order of priority:
app-id, app-name, filename.
If app-id is provided, looks up existing application and updates its manifest.
... | [
"Upload",
"application",
"from",
"file",
"."
] | 4586ea11d5103c2ff9607d3ed922b5a0991b8845 | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/cli/__main__.py#L351-L405 | train |
qubell/contrib-python-qubell-client | qubell/cli/__main__.py | show_account | def show_account():
"""
Exports current account configuration in
shell-friendly form. Takes into account
explicit top-level flags like --organization.
"""
click.echo("# tonomi api")
for (key, env) in REVERSE_MAPPING.items():
value = QUBELL.get(key, None)
if value:
... | python | def show_account():
"""
Exports current account configuration in
shell-friendly form. Takes into account
explicit top-level flags like --organization.
"""
click.echo("# tonomi api")
for (key, env) in REVERSE_MAPPING.items():
value = QUBELL.get(key, None)
if value:
... | [
"def",
"show_account",
"(",
")",
":",
"click",
".",
"echo",
"(",
"\"# tonomi api\"",
")",
"for",
"(",
"key",
",",
"env",
")",
"in",
"REVERSE_MAPPING",
".",
"items",
"(",
")",
":",
"value",
"=",
"QUBELL",
".",
"get",
"(",
"key",
",",
"None",
")",
"i... | Exports current account configuration in
shell-friendly form. Takes into account
explicit top-level flags like --organization. | [
"Exports",
"current",
"account",
"configuration",
"in",
"shell",
"-",
"friendly",
"form",
".",
"Takes",
"into",
"account",
"explicit",
"top",
"-",
"level",
"flags",
"like",
"--",
"organization",
"."
] | 4586ea11d5103c2ff9607d3ed922b5a0991b8845 | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/cli/__main__.py#L1210-L1226 | train |
qubell/contrib-python-qubell-client | qubell/cli/__main__.py | generate_session_token | def generate_session_token(refresh_token, verbose):
"""
Generates new session token from the given refresh token.
:param refresh_token: refresh token to generate from
:param verbose: whether expiration time should be added to output
"""
platform = _get_platform(authenticated=False)
session_... | python | def generate_session_token(refresh_token, verbose):
"""
Generates new session token from the given refresh token.
:param refresh_token: refresh token to generate from
:param verbose: whether expiration time should be added to output
"""
platform = _get_platform(authenticated=False)
session_... | [
"def",
"generate_session_token",
"(",
"refresh_token",
",",
"verbose",
")",
":",
"platform",
"=",
"_get_platform",
"(",
"authenticated",
"=",
"False",
")",
"session_token",
",",
"expires_in",
"=",
"platform",
".",
"generate_session_token",
"(",
"refresh_token",
")",... | Generates new session token from the given refresh token.
:param refresh_token: refresh token to generate from
:param verbose: whether expiration time should be added to output | [
"Generates",
"new",
"session",
"token",
"from",
"the",
"given",
"refresh",
"token",
".",
":",
"param",
"refresh_token",
":",
"refresh",
"token",
"to",
"generate",
"from",
":",
"param",
"verbose",
":",
"whether",
"expiration",
"time",
"should",
"be",
"added",
... | 4586ea11d5103c2ff9607d3ed922b5a0991b8845 | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/cli/__main__.py#L1232-L1245 | train |
astroduff/commah | examples.py | runcommand | def runcommand(cosmology='WMAP5'):
""" Example interface commands """
# Return the WMAP5 cosmology concentration predicted for
# z=0 range of masses
Mi = [1e8, 1e9, 1e10]
zi = 0
print("Concentrations for haloes of mass %s at z=%s" % (Mi, zi))
output = commah.run(cosmology=cosmology, zi=zi, ... | python | def runcommand(cosmology='WMAP5'):
""" Example interface commands """
# Return the WMAP5 cosmology concentration predicted for
# z=0 range of masses
Mi = [1e8, 1e9, 1e10]
zi = 0
print("Concentrations for haloes of mass %s at z=%s" % (Mi, zi))
output = commah.run(cosmology=cosmology, zi=zi, ... | [
"def",
"runcommand",
"(",
"cosmology",
"=",
"'WMAP5'",
")",
":",
"# Return the WMAP5 cosmology concentration predicted for",
"# z=0 range of masses",
"Mi",
"=",
"[",
"1e8",
",",
"1e9",
",",
"1e10",
"]",
"zi",
"=",
"0",
"print",
"(",
"\"Concentrations for haloes of mas... | Example interface commands | [
"Example",
"interface",
"commands"
] | 3ec70338c5123a053c79ddcf2cb3beac26bc9137 | https://github.com/astroduff/commah/blob/3ec70338c5123a053c79ddcf2cb3beac26bc9137/examples.py#L9-L90 | train |
astroduff/commah | examples.py | plotcommand | def plotcommand(cosmology='WMAP5', plotname=None):
""" Example ways to interrogate the dataset and plot the commah output """
# Plot the c-M relation as a functon of redshift
xarray = 10**(np.arange(1, 15, 0.2))
yval = 'c'
# Specify the redshift range
zarray = np.arange(0, 5, 0.5)
xtitle ... | python | def plotcommand(cosmology='WMAP5', plotname=None):
""" Example ways to interrogate the dataset and plot the commah output """
# Plot the c-M relation as a functon of redshift
xarray = 10**(np.arange(1, 15, 0.2))
yval = 'c'
# Specify the redshift range
zarray = np.arange(0, 5, 0.5)
xtitle ... | [
"def",
"plotcommand",
"(",
"cosmology",
"=",
"'WMAP5'",
",",
"plotname",
"=",
"None",
")",
":",
"# Plot the c-M relation as a functon of redshift",
"xarray",
"=",
"10",
"**",
"(",
"np",
".",
"arange",
"(",
"1",
",",
"15",
",",
"0.2",
")",
")",
"yval",
"=",... | Example ways to interrogate the dataset and plot the commah output | [
"Example",
"ways",
"to",
"interrogate",
"the",
"dataset",
"and",
"plot",
"the",
"commah",
"output"
] | 3ec70338c5123a053c79ddcf2cb3beac26bc9137 | https://github.com/astroduff/commah/blob/3ec70338c5123a053c79ddcf2cb3beac26bc9137/examples.py#L93-L466 | train |
davidblaisonneau-orange/foreman | foreman/itemHostsGroup.py | ItemHostsGroup.enhance | def enhance(self):
""" Function enhance
Enhance the object with new item or enhanced items
"""
self.update({'puppetclasses':
SubDict(self.api, self.objName,
self.payloadObj, self.key,
SubItemPuppetClasses)})
... | python | def enhance(self):
""" Function enhance
Enhance the object with new item or enhanced items
"""
self.update({'puppetclasses':
SubDict(self.api, self.objName,
self.payloadObj, self.key,
SubItemPuppetClasses)})
... | [
"def",
"enhance",
"(",
"self",
")",
":",
"self",
".",
"update",
"(",
"{",
"'puppetclasses'",
":",
"SubDict",
"(",
"self",
".",
"api",
",",
"self",
".",
"objName",
",",
"self",
".",
"payloadObj",
",",
"self",
".",
"key",
",",
"SubItemPuppetClasses",
")"... | Function enhance
Enhance the object with new item or enhanced items | [
"Function",
"enhance",
"Enhance",
"the",
"object",
"with",
"new",
"item",
"or",
"enhanced",
"items"
] | acb8fd8d74657cfac3b25c82e9c6028b93eb6c92 | https://github.com/davidblaisonneau-orange/foreman/blob/acb8fd8d74657cfac3b25c82e9c6028b93eb6c92/foreman/itemHostsGroup.py#L38-L53 | train |
aroberge/experimental | experimental/core/transforms.py | add_transformers | def add_transformers(line):
'''Extract the transformers names from a line of code of the form
from __experimental__ import transformer1 [,...]
and adds them to the globally known dict
'''
assert FROM_EXPERIMENTAL.match(line)
line = FROM_EXPERIMENTAL.sub(' ', line)
# we now have: " tra... | python | def add_transformers(line):
'''Extract the transformers names from a line of code of the form
from __experimental__ import transformer1 [,...]
and adds them to the globally known dict
'''
assert FROM_EXPERIMENTAL.match(line)
line = FROM_EXPERIMENTAL.sub(' ', line)
# we now have: " tra... | [
"def",
"add_transformers",
"(",
"line",
")",
":",
"assert",
"FROM_EXPERIMENTAL",
".",
"match",
"(",
"line",
")",
"line",
"=",
"FROM_EXPERIMENTAL",
".",
"sub",
"(",
"' '",
",",
"line",
")",
"# we now have: \" transformer1 [,...]\"",
"line",
"=",
"line",
".",
"s... | Extract the transformers names from a line of code of the form
from __experimental__ import transformer1 [,...]
and adds them to the globally known dict | [
"Extract",
"the",
"transformers",
"names",
"from",
"a",
"line",
"of",
"code",
"of",
"the",
"form",
"from",
"__experimental__",
"import",
"transformer1",
"[",
"...",
"]",
"and",
"adds",
"them",
"to",
"the",
"globally",
"known",
"dict"
] | 031a9be10698b429998436da748b8fdb86f18b47 | https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/core/transforms.py#L19-L31 | train |
aroberge/experimental | experimental/core/transforms.py | import_transformer | def import_transformer(name):
'''If needed, import a transformer, and adds it to the globally known dict
The code inside a module where a transformer is defined should be
standard Python code, which does not need any transformation.
So, we disable the import hook, and let the normal module impo... | python | def import_transformer(name):
'''If needed, import a transformer, and adds it to the globally known dict
The code inside a module where a transformer is defined should be
standard Python code, which does not need any transformation.
So, we disable the import hook, and let the normal module impo... | [
"def",
"import_transformer",
"(",
"name",
")",
":",
"if",
"name",
"in",
"transformers",
":",
"return",
"transformers",
"[",
"name",
"]",
"# We are adding a transformer built from normal/standard Python code.",
"# As we are not performing transformations, we temporarily disable",
... | If needed, import a transformer, and adds it to the globally known dict
The code inside a module where a transformer is defined should be
standard Python code, which does not need any transformation.
So, we disable the import hook, and let the normal module import
do its job - which is faste... | [
"If",
"needed",
"import",
"a",
"transformer",
"and",
"adds",
"it",
"to",
"the",
"globally",
"known",
"dict",
"The",
"code",
"inside",
"a",
"module",
"where",
"a",
"transformer",
"is",
"defined",
"should",
"be",
"standard",
"Python",
"code",
"which",
"does",
... | 031a9be10698b429998436da748b8fdb86f18b47 | https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/core/transforms.py#L34-L70 | train |
aroberge/experimental | experimental/core/transforms.py | extract_transformers_from_source | def extract_transformers_from_source(source):
'''Scan a source for lines of the form
from __experimental__ import transformer1 [,...]
identifying transformers to be used. Such line is passed to the
add_transformer function, after which it is removed from the
code to be executed.
'''
... | python | def extract_transformers_from_source(source):
'''Scan a source for lines of the form
from __experimental__ import transformer1 [,...]
identifying transformers to be used. Such line is passed to the
add_transformer function, after which it is removed from the
code to be executed.
'''
... | [
"def",
"extract_transformers_from_source",
"(",
"source",
")",
":",
"lines",
"=",
"source",
".",
"split",
"(",
"'\\n'",
")",
"linenumbers",
"=",
"[",
"]",
"for",
"number",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"if",
"FROM_EXPERIMENTAL",
"... | Scan a source for lines of the form
from __experimental__ import transformer1 [,...]
identifying transformers to be used. Such line is passed to the
add_transformer function, after which it is removed from the
code to be executed. | [
"Scan",
"a",
"source",
"for",
"lines",
"of",
"the",
"form",
"from",
"__experimental__",
"import",
"transformer1",
"[",
"...",
"]",
"identifying",
"transformers",
"to",
"be",
"used",
".",
"Such",
"line",
"is",
"passed",
"to",
"the",
"add_transformer",
"function... | 031a9be10698b429998436da748b8fdb86f18b47 | https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/core/transforms.py#L72-L89 | train |
aroberge/experimental | experimental/core/transforms.py | remove_not_allowed_in_console | def remove_not_allowed_in_console():
'''This function should be called from the console, when it starts.
Some transformers are not allowed in the console and they could have
been loaded prior to the console being activated. We effectively remove them
and print an information message specific to that tr... | python | def remove_not_allowed_in_console():
'''This function should be called from the console, when it starts.
Some transformers are not allowed in the console and they could have
been loaded prior to the console being activated. We effectively remove them
and print an information message specific to that tr... | [
"def",
"remove_not_allowed_in_console",
"(",
")",
":",
"not_allowed_in_console",
"=",
"[",
"]",
"if",
"CONSOLE_ACTIVE",
":",
"for",
"name",
"in",
"transformers",
":",
"tr_module",
"=",
"import_transformer",
"(",
"name",
")",
"if",
"hasattr",
"(",
"tr_module",
",... | This function should be called from the console, when it starts.
Some transformers are not allowed in the console and they could have
been loaded prior to the console being activated. We effectively remove them
and print an information message specific to that transformer
as written in the transformer ... | [
"This",
"function",
"should",
"be",
"called",
"from",
"the",
"console",
"when",
"it",
"starts",
"."
] | 031a9be10698b429998436da748b8fdb86f18b47 | https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/core/transforms.py#L91-L111 | train |
aroberge/experimental | experimental/core/transforms.py | transform | def transform(source):
'''Used to convert the source code, making use of known transformers.
"transformers" are modules which must contain a function
transform_source(source)
which returns a tranformed source.
Some transformers (for example, those found in the standard library
... | python | def transform(source):
'''Used to convert the source code, making use of known transformers.
"transformers" are modules which must contain a function
transform_source(source)
which returns a tranformed source.
Some transformers (for example, those found in the standard library
... | [
"def",
"transform",
"(",
"source",
")",
":",
"source",
"=",
"extract_transformers_from_source",
"(",
"source",
")",
"# Some transformer fail when multiple non-Python constructs",
"# are present. So, we loop multiple times keeping track of",
"# which transformations have been unsuccessful... | Used to convert the source code, making use of known transformers.
"transformers" are modules which must contain a function
transform_source(source)
which returns a tranformed source.
Some transformers (for example, those found in the standard library
module lib2to3) cannot cop... | [
"Used",
"to",
"convert",
"the",
"source",
"code",
"making",
"use",
"of",
"known",
"transformers",
"."
] | 031a9be10698b429998436da748b8fdb86f18b47 | https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/core/transforms.py#L114-L160 | train |
bradmontgomery/django-chosenadmin | chosenadmin/middleware.py | ChosenAdminMiddleware._match | def _match(self, request, response):
"""Match all requests/responses that satisfy the following conditions:
* An Admin App; i.e. the path is something like /admin/some_app/
* The ``include_flag`` is not in the response's content
"""
is_html = 'text/html' in response.get('Conten... | python | def _match(self, request, response):
"""Match all requests/responses that satisfy the following conditions:
* An Admin App; i.e. the path is something like /admin/some_app/
* The ``include_flag`` is not in the response's content
"""
is_html = 'text/html' in response.get('Conten... | [
"def",
"_match",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"is_html",
"=",
"'text/html'",
"in",
"response",
".",
"get",
"(",
"'Content-Type'",
",",
"''",
")",
"if",
"is_html",
"and",
"hasattr",
"(",
"response",
",",
"'rendered_content'",
")",... | Match all requests/responses that satisfy the following conditions:
* An Admin App; i.e. the path is something like /admin/some_app/
* The ``include_flag`` is not in the response's content | [
"Match",
"all",
"requests",
"/",
"responses",
"that",
"satisfy",
"the",
"following",
"conditions",
":"
] | 23fad0151d1175d751599a7ee3a1ff35b2d61299 | https://github.com/bradmontgomery/django-chosenadmin/blob/23fad0151d1175d751599a7ee3a1ff35b2d61299/chosenadmin/middleware.py#L24-L36 | train |
bradmontgomery/django-chosenadmin | chosenadmin/middleware.py | ChosenAdminMiddleware._chosen_css | def _chosen_css(self):
"""Read the minified CSS file including STATIC_URL in the references
to the sprite images."""
css = render_to_string(self.css_template, {})
for sprite in self.chosen_sprites: # rewrite path to sprites in the css
css = css.replace(sprite, settings.STATI... | python | def _chosen_css(self):
"""Read the minified CSS file including STATIC_URL in the references
to the sprite images."""
css = render_to_string(self.css_template, {})
for sprite in self.chosen_sprites: # rewrite path to sprites in the css
css = css.replace(sprite, settings.STATI... | [
"def",
"_chosen_css",
"(",
"self",
")",
":",
"css",
"=",
"render_to_string",
"(",
"self",
".",
"css_template",
",",
"{",
"}",
")",
"for",
"sprite",
"in",
"self",
".",
"chosen_sprites",
":",
"# rewrite path to sprites in the css",
"css",
"=",
"css",
".",
"rep... | Read the minified CSS file including STATIC_URL in the references
to the sprite images. | [
"Read",
"the",
"minified",
"CSS",
"file",
"including",
"STATIC_URL",
"in",
"the",
"references",
"to",
"the",
"sprite",
"images",
"."
] | 23fad0151d1175d751599a7ee3a1ff35b2d61299 | https://github.com/bradmontgomery/django-chosenadmin/blob/23fad0151d1175d751599a7ee3a1ff35b2d61299/chosenadmin/middleware.py#L38-L44 | train |
bradmontgomery/django-chosenadmin | chosenadmin/middleware.py | ChosenAdminMiddleware._embed | def _embed(self, request, response):
"""Embed Chosen.js directly in html of the response."""
if self._match(request, response):
# Render the <link> and the <script> tags to include Chosen.
head = render_to_string(
"chosenadmin/_head_css.html",
{"ch... | python | def _embed(self, request, response):
"""Embed Chosen.js directly in html of the response."""
if self._match(request, response):
# Render the <link> and the <script> tags to include Chosen.
head = render_to_string(
"chosenadmin/_head_css.html",
{"ch... | [
"def",
"_embed",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"if",
"self",
".",
"_match",
"(",
"request",
",",
"response",
")",
":",
"# Render the <link> and the <script> tags to include Chosen.",
"head",
"=",
"render_to_string",
"(",
"\"chosenadmin/_hea... | Embed Chosen.js directly in html of the response. | [
"Embed",
"Chosen",
".",
"js",
"directly",
"in",
"html",
"of",
"the",
"response",
"."
] | 23fad0151d1175d751599a7ee3a1ff35b2d61299 | https://github.com/bradmontgomery/django-chosenadmin/blob/23fad0151d1175d751599a7ee3a1ff35b2d61299/chosenadmin/middleware.py#L50-L68 | train |
fchorney/rpI2C | rpI2C.py | I2C.clean_up | def clean_up(self):
"""
Close the I2C bus
"""
self.log.debug("Closing I2C bus for address: 0x%02X" % self.address)
self.bus.close() | python | def clean_up(self):
"""
Close the I2C bus
"""
self.log.debug("Closing I2C bus for address: 0x%02X" % self.address)
self.bus.close() | [
"def",
"clean_up",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Closing I2C bus for address: 0x%02X\"",
"%",
"self",
".",
"address",
")",
"self",
".",
"bus",
".",
"close",
"(",
")"
] | Close the I2C bus | [
"Close",
"the",
"I2C",
"bus"
] | 7c60f82fa8c91496a74182373da0b95a13919d6e | https://github.com/fchorney/rpI2C/blob/7c60f82fa8c91496a74182373da0b95a13919d6e/rpI2C.py#L30-L35 | train |
fchorney/rpI2C | rpI2C.py | I2C.write_quick | def write_quick(self):
"""
Send only the read / write bit
"""
self.bus.write_quick(self.address)
self.log.debug("write_quick: Sent the read / write bit") | python | def write_quick(self):
"""
Send only the read / write bit
"""
self.bus.write_quick(self.address)
self.log.debug("write_quick: Sent the read / write bit") | [
"def",
"write_quick",
"(",
"self",
")",
":",
"self",
".",
"bus",
".",
"write_quick",
"(",
"self",
".",
"address",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"write_quick: Sent the read / write bit\"",
")"
] | Send only the read / write bit | [
"Send",
"only",
"the",
"read",
"/",
"write",
"bit"
] | 7c60f82fa8c91496a74182373da0b95a13919d6e | https://github.com/fchorney/rpI2C/blob/7c60f82fa8c91496a74182373da0b95a13919d6e/rpI2C.py#L39-L44 | train |
fchorney/rpI2C | rpI2C.py | I2C.write_byte | def write_byte(self, cmd, value):
"""
Writes an 8-bit byte to the specified command register
"""
self.bus.write_byte_data(self.address, cmd, value)
self.log.debug(
"write_byte: Wrote 0x%02X to command register 0x%02X" % (
value, cmd
)
... | python | def write_byte(self, cmd, value):
"""
Writes an 8-bit byte to the specified command register
"""
self.bus.write_byte_data(self.address, cmd, value)
self.log.debug(
"write_byte: Wrote 0x%02X to command register 0x%02X" % (
value, cmd
)
... | [
"def",
"write_byte",
"(",
"self",
",",
"cmd",
",",
"value",
")",
":",
"self",
".",
"bus",
".",
"write_byte_data",
"(",
"self",
".",
"address",
",",
"cmd",
",",
"value",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"write_byte: Wrote 0x%02X to command regi... | Writes an 8-bit byte to the specified command register | [
"Writes",
"an",
"8",
"-",
"bit",
"byte",
"to",
"the",
"specified",
"command",
"register"
] | 7c60f82fa8c91496a74182373da0b95a13919d6e | https://github.com/fchorney/rpI2C/blob/7c60f82fa8c91496a74182373da0b95a13919d6e/rpI2C.py#L46-L55 | train |
fchorney/rpI2C | rpI2C.py | I2C.write_word | def write_word(self, cmd, value):
"""
Writes a 16-bit word to the specified command register
"""
self.bus.write_word_data(self.address, cmd, value)
self.log.debug(
"write_word: Wrote 0x%04X to command register 0x%02X" % (
value, cmd
)
... | python | def write_word(self, cmd, value):
"""
Writes a 16-bit word to the specified command register
"""
self.bus.write_word_data(self.address, cmd, value)
self.log.debug(
"write_word: Wrote 0x%04X to command register 0x%02X" % (
value, cmd
)
... | [
"def",
"write_word",
"(",
"self",
",",
"cmd",
",",
"value",
")",
":",
"self",
".",
"bus",
".",
"write_word_data",
"(",
"self",
".",
"address",
",",
"cmd",
",",
"value",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"write_word: Wrote 0x%04X to command regi... | Writes a 16-bit word to the specified command register | [
"Writes",
"a",
"16",
"-",
"bit",
"word",
"to",
"the",
"specified",
"command",
"register"
] | 7c60f82fa8c91496a74182373da0b95a13919d6e | https://github.com/fchorney/rpI2C/blob/7c60f82fa8c91496a74182373da0b95a13919d6e/rpI2C.py#L57-L66 | train |
fchorney/rpI2C | rpI2C.py | I2C.write_raw_byte | def write_raw_byte(self, value):
"""
Writes an 8-bit byte directly to the bus
"""
self.bus.write_byte(self.address, value)
self.log.debug("write_raw_byte: Wrote 0x%02X" % value) | python | def write_raw_byte(self, value):
"""
Writes an 8-bit byte directly to the bus
"""
self.bus.write_byte(self.address, value)
self.log.debug("write_raw_byte: Wrote 0x%02X" % value) | [
"def",
"write_raw_byte",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"bus",
".",
"write_byte",
"(",
"self",
".",
"address",
",",
"value",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"write_raw_byte: Wrote 0x%02X\"",
"%",
"value",
")"
] | Writes an 8-bit byte directly to the bus | [
"Writes",
"an",
"8",
"-",
"bit",
"byte",
"directly",
"to",
"the",
"bus"
] | 7c60f82fa8c91496a74182373da0b95a13919d6e | https://github.com/fchorney/rpI2C/blob/7c60f82fa8c91496a74182373da0b95a13919d6e/rpI2C.py#L68-L73 | train |
fchorney/rpI2C | rpI2C.py | I2C.write_block_data | def write_block_data(self, cmd, block):
"""
Writes a block of bytes to the bus using I2C format to the specified
command register
"""
self.bus.write_i2c_block_data(self.address, cmd, block)
self.log.debug(
"write_block_data: Wrote [%s] to command register 0x%0... | python | def write_block_data(self, cmd, block):
"""
Writes a block of bytes to the bus using I2C format to the specified
command register
"""
self.bus.write_i2c_block_data(self.address, cmd, block)
self.log.debug(
"write_block_data: Wrote [%s] to command register 0x%0... | [
"def",
"write_block_data",
"(",
"self",
",",
"cmd",
",",
"block",
")",
":",
"self",
".",
"bus",
".",
"write_i2c_block_data",
"(",
"self",
".",
"address",
",",
"cmd",
",",
"block",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"write_block_data: Wrote [%s] ... | Writes a block of bytes to the bus using I2C format to the specified
command register | [
"Writes",
"a",
"block",
"of",
"bytes",
"to",
"the",
"bus",
"using",
"I2C",
"format",
"to",
"the",
"specified",
"command",
"register"
] | 7c60f82fa8c91496a74182373da0b95a13919d6e | https://github.com/fchorney/rpI2C/blob/7c60f82fa8c91496a74182373da0b95a13919d6e/rpI2C.py#L75-L86 | train |
fchorney/rpI2C | rpI2C.py | I2C.read_raw_byte | def read_raw_byte(self):
"""
Read an 8-bit byte directly from the bus
"""
result = self.bus.read_byte(self.address)
self.log.debug("read_raw_byte: Read 0x%02X from the bus" % result)
return result | python | def read_raw_byte(self):
"""
Read an 8-bit byte directly from the bus
"""
result = self.bus.read_byte(self.address)
self.log.debug("read_raw_byte: Read 0x%02X from the bus" % result)
return result | [
"def",
"read_raw_byte",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"bus",
".",
"read_byte",
"(",
"self",
".",
"address",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"read_raw_byte: Read 0x%02X from the bus\"",
"%",
"result",
")",
"return",
"result"... | Read an 8-bit byte directly from the bus | [
"Read",
"an",
"8",
"-",
"bit",
"byte",
"directly",
"from",
"the",
"bus"
] | 7c60f82fa8c91496a74182373da0b95a13919d6e | https://github.com/fchorney/rpI2C/blob/7c60f82fa8c91496a74182373da0b95a13919d6e/rpI2C.py#L90-L96 | train |
fchorney/rpI2C | rpI2C.py | I2C.read_block_data | def read_block_data(self, cmd, length):
"""
Read a block of bytes from the bus from the specified command register
Amount of bytes read in is defined by length
"""
results = self.bus.read_i2c_block_data(self.address, cmd, length)
self.log.debug(
"read_block_da... | python | def read_block_data(self, cmd, length):
"""
Read a block of bytes from the bus from the specified command register
Amount of bytes read in is defined by length
"""
results = self.bus.read_i2c_block_data(self.address, cmd, length)
self.log.debug(
"read_block_da... | [
"def",
"read_block_data",
"(",
"self",
",",
"cmd",
",",
"length",
")",
":",
"results",
"=",
"self",
".",
"bus",
".",
"read_i2c_block_data",
"(",
"self",
".",
"address",
",",
"cmd",
",",
"length",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"read_bloc... | Read a block of bytes from the bus from the specified command register
Amount of bytes read in is defined by length | [
"Read",
"a",
"block",
"of",
"bytes",
"from",
"the",
"bus",
"from",
"the",
"specified",
"command",
"register",
"Amount",
"of",
"bytes",
"read",
"in",
"is",
"defined",
"by",
"length"
] | 7c60f82fa8c91496a74182373da0b95a13919d6e | https://github.com/fchorney/rpI2C/blob/7c60f82fa8c91496a74182373da0b95a13919d6e/rpI2C.py#L98-L110 | train |
fchorney/rpI2C | rpI2C.py | I2C.read_unsigned_byte | def read_unsigned_byte(self, cmd):
"""
Read an unsigned byte from the specified command register
"""
result = self.bus.read_byte_data(self.address, cmd)
self.log.debug(
"read_unsigned_byte: Read 0x%02X from command register 0x%02X" % (
result, cmd
... | python | def read_unsigned_byte(self, cmd):
"""
Read an unsigned byte from the specified command register
"""
result = self.bus.read_byte_data(self.address, cmd)
self.log.debug(
"read_unsigned_byte: Read 0x%02X from command register 0x%02X" % (
result, cmd
... | [
"def",
"read_unsigned_byte",
"(",
"self",
",",
"cmd",
")",
":",
"result",
"=",
"self",
".",
"bus",
".",
"read_byte_data",
"(",
"self",
".",
"address",
",",
"cmd",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"read_unsigned_byte: Read 0x%02X from command regis... | Read an unsigned byte from the specified command register | [
"Read",
"an",
"unsigned",
"byte",
"from",
"the",
"specified",
"command",
"register"
] | 7c60f82fa8c91496a74182373da0b95a13919d6e | https://github.com/fchorney/rpI2C/blob/7c60f82fa8c91496a74182373da0b95a13919d6e/rpI2C.py#L112-L122 | train |
fchorney/rpI2C | rpI2C.py | I2C.read_unsigned_word | def read_unsigned_word(self, cmd, little_endian=True):
"""
Read an unsigned word from the specified command register
We assume the data is in little endian mode, if it is in big endian
mode then set little_endian to False
"""
result = self.bus.read_word_data(self.address,... | python | def read_unsigned_word(self, cmd, little_endian=True):
"""
Read an unsigned word from the specified command register
We assume the data is in little endian mode, if it is in big endian
mode then set little_endian to False
"""
result = self.bus.read_word_data(self.address,... | [
"def",
"read_unsigned_word",
"(",
"self",
",",
"cmd",
",",
"little_endian",
"=",
"True",
")",
":",
"result",
"=",
"self",
".",
"bus",
".",
"read_word_data",
"(",
"self",
".",
"address",
",",
"cmd",
")",
"if",
"not",
"little_endian",
":",
"result",
"=",
... | Read an unsigned word from the specified command register
We assume the data is in little endian mode, if it is in big endian
mode then set little_endian to False | [
"Read",
"an",
"unsigned",
"word",
"from",
"the",
"specified",
"command",
"register",
"We",
"assume",
"the",
"data",
"is",
"in",
"little",
"endian",
"mode",
"if",
"it",
"is",
"in",
"big",
"endian",
"mode",
"then",
"set",
"little_endian",
"to",
"False"
] | 7c60f82fa8c91496a74182373da0b95a13919d6e | https://github.com/fchorney/rpI2C/blob/7c60f82fa8c91496a74182373da0b95a13919d6e/rpI2C.py#L141-L157 | train |
fchorney/rpI2C | rpI2C.py | I2C.__connect_to_bus | def __connect_to_bus(self, bus):
"""
Attempt to connect to an I2C bus
"""
def connect(bus_num):
try:
self.log.debug("Attempting to connect to bus %s..." % bus_num)
self.bus = smbus.SMBus(bus_num)
self.log.debug("Success")
... | python | def __connect_to_bus(self, bus):
"""
Attempt to connect to an I2C bus
"""
def connect(bus_num):
try:
self.log.debug("Attempting to connect to bus %s..." % bus_num)
self.bus = smbus.SMBus(bus_num)
self.log.debug("Success")
... | [
"def",
"__connect_to_bus",
"(",
"self",
",",
"bus",
")",
":",
"def",
"connect",
"(",
"bus_num",
")",
":",
"try",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Attempting to connect to bus %s...\"",
"%",
"bus_num",
")",
"self",
".",
"bus",
"=",
"smbus",
... | Attempt to connect to an I2C bus | [
"Attempt",
"to",
"connect",
"to",
"an",
"I2C",
"bus"
] | 7c60f82fa8c91496a74182373da0b95a13919d6e | https://github.com/fchorney/rpI2C/blob/7c60f82fa8c91496a74182373da0b95a13919d6e/rpI2C.py#L181-L213 | train |
developersociety/django-glitter | glitter/reminders/admin.py | ReminderInline.get_formset | def get_formset(self, request, obj=None, **kwargs):
""" Default user to the current version owner. """
data = super().get_formset(request, obj, **kwargs)
if obj:
data.form.base_fields['user'].initial = request.user.id
return data | python | def get_formset(self, request, obj=None, **kwargs):
""" Default user to the current version owner. """
data = super().get_formset(request, obj, **kwargs)
if obj:
data.form.base_fields['user'].initial = request.user.id
return data | [
"def",
"get_formset",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"super",
"(",
")",
".",
"get_formset",
"(",
"request",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
"if",
"obj",
":",
"data",... | Default user to the current version owner. | [
"Default",
"user",
"to",
"the",
"current",
"version",
"owner",
"."
] | 2c0280ec83afee80deee94ee3934fc54239c2e87 | https://github.com/developersociety/django-glitter/blob/2c0280ec83afee80deee94ee3934fc54239c2e87/glitter/reminders/admin.py#L15-L20 | train |
davidblaisonneau-orange/foreman | foreman/objects.py | ForemanObjects.reload | def reload(self):
""" Function reload
Reload the full object to ensure sync
"""
realData = self.load()
self.clear()
self.update(realData) | python | def reload(self):
""" Function reload
Reload the full object to ensure sync
"""
realData = self.load()
self.clear()
self.update(realData) | [
"def",
"reload",
"(",
"self",
")",
":",
"realData",
"=",
"self",
".",
"load",
"(",
")",
"self",
".",
"clear",
"(",
")",
"self",
".",
"update",
"(",
"realData",
")"
] | Function reload
Reload the full object to ensure sync | [
"Function",
"reload",
"Reload",
"the",
"full",
"object",
"to",
"ensure",
"sync"
] | acb8fd8d74657cfac3b25c82e9c6028b93eb6c92 | https://github.com/davidblaisonneau-orange/foreman/blob/acb8fd8d74657cfac3b25c82e9c6028b93eb6c92/foreman/objects.py#L61-L67 | train |
davidblaisonneau-orange/foreman | foreman/objects.py | ForemanObjects.updateAfterDecorator | def updateAfterDecorator(function):
""" Function updateAfterDecorator
Decorator to ensure local dict is sync with remote foreman
"""
def _updateAfterDecorator(self, *args, **kwargs):
ret = function(self, *args, **kwargs)
self.reload()
return ret
... | python | def updateAfterDecorator(function):
""" Function updateAfterDecorator
Decorator to ensure local dict is sync with remote foreman
"""
def _updateAfterDecorator(self, *args, **kwargs):
ret = function(self, *args, **kwargs)
self.reload()
return ret
... | [
"def",
"updateAfterDecorator",
"(",
"function",
")",
":",
"def",
"_updateAfterDecorator",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"function",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
"... | Function updateAfterDecorator
Decorator to ensure local dict is sync with remote foreman | [
"Function",
"updateAfterDecorator",
"Decorator",
"to",
"ensure",
"local",
"dict",
"is",
"sync",
"with",
"remote",
"foreman"
] | acb8fd8d74657cfac3b25c82e9c6028b93eb6c92 | https://github.com/davidblaisonneau-orange/foreman/blob/acb8fd8d74657cfac3b25c82e9c6028b93eb6c92/foreman/objects.py#L70-L78 | train |
davidblaisonneau-orange/foreman | foreman/objects.py | ForemanObjects.updateBeforeDecorator | def updateBeforeDecorator(function):
""" Function updateAfterDecorator
Decorator to ensure local dict is sync with remote foreman
"""
def _updateBeforeDecorator(self, *args, **kwargs):
if self.forceFullSync:
self.reload()
return function(self, *arg... | python | def updateBeforeDecorator(function):
""" Function updateAfterDecorator
Decorator to ensure local dict is sync with remote foreman
"""
def _updateBeforeDecorator(self, *args, **kwargs):
if self.forceFullSync:
self.reload()
return function(self, *arg... | [
"def",
"updateBeforeDecorator",
"(",
"function",
")",
":",
"def",
"_updateBeforeDecorator",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"forceFullSync",
":",
"self",
".",
"reload",
"(",
")",
"return",
"function",
... | Function updateAfterDecorator
Decorator to ensure local dict is sync with remote foreman | [
"Function",
"updateAfterDecorator",
"Decorator",
"to",
"ensure",
"local",
"dict",
"is",
"sync",
"with",
"remote",
"foreman"
] | acb8fd8d74657cfac3b25c82e9c6028b93eb6c92 | https://github.com/davidblaisonneau-orange/foreman/blob/acb8fd8d74657cfac3b25c82e9c6028b93eb6c92/foreman/objects.py#L80-L88 | train |
davidblaisonneau-orange/foreman | foreman/objects.py | ForemanObjects.load | def load(self):
""" Function load
Get the list of all objects
@return RETURN: A ForemanItem list
"""
return {x[self.index]: self.itemType(self.api, x['id'],
self.objName, self.payloadObj,
x... | python | def load(self):
""" Function load
Get the list of all objects
@return RETURN: A ForemanItem list
"""
return {x[self.index]: self.itemType(self.api, x['id'],
self.objName, self.payloadObj,
x... | [
"def",
"load",
"(",
"self",
")",
":",
"return",
"{",
"x",
"[",
"self",
".",
"index",
"]",
":",
"self",
".",
"itemType",
"(",
"self",
".",
"api",
",",
"x",
"[",
"'id'",
"]",
",",
"self",
".",
"objName",
",",
"self",
".",
"payloadObj",
",",
"x",
... | Function load
Get the list of all objects
@return RETURN: A ForemanItem list | [
"Function",
"load",
"Get",
"the",
"list",
"of",
"all",
"objects"
] | acb8fd8d74657cfac3b25c82e9c6028b93eb6c92 | https://github.com/davidblaisonneau-orange/foreman/blob/acb8fd8d74657cfac3b25c82e9c6028b93eb6c92/foreman/objects.py#L141-L151 | train |
davidblaisonneau-orange/foreman | foreman/objects.py | ForemanObjects.checkAndCreate | def checkAndCreate(self, key, payload):
""" Function checkAndCreate
Check if an object exists and create it if not
@param key: The targeted object
@param payload: The targeted object description
@return RETURN: The id of the object
"""
if key not in self:
... | python | def checkAndCreate(self, key, payload):
""" Function checkAndCreate
Check if an object exists and create it if not
@param key: The targeted object
@param payload: The targeted object description
@return RETURN: The id of the object
"""
if key not in self:
... | [
"def",
"checkAndCreate",
"(",
"self",
",",
"key",
",",
"payload",
")",
":",
"if",
"key",
"not",
"in",
"self",
":",
"self",
"[",
"key",
"]",
"=",
"payload",
"return",
"self",
"[",
"key",
"]",
"[",
"'id'",
"]"
] | Function checkAndCreate
Check if an object exists and create it if not
@param key: The targeted object
@param payload: The targeted object description
@return RETURN: The id of the object | [
"Function",
"checkAndCreate",
"Check",
"if",
"an",
"object",
"exists",
"and",
"create",
"it",
"if",
"not"
] | acb8fd8d74657cfac3b25c82e9c6028b93eb6c92 | https://github.com/davidblaisonneau-orange/foreman/blob/acb8fd8d74657cfac3b25c82e9c6028b93eb6c92/foreman/objects.py#L163-L173 | train |
qubell/contrib-python-qubell-client | qubell/api/private/__init__.py | operations | def operations():
"""
Class decorator stores all calls into list.
Can be used until .invalidate() is called.
:return: decorated class
"""
def decorator(func):
@wraps(func)
def wrapped_func(*args, **kwargs):
self = args[0]
assert self.__can_use, "User oper... | python | def operations():
"""
Class decorator stores all calls into list.
Can be used until .invalidate() is called.
:return: decorated class
"""
def decorator(func):
@wraps(func)
def wrapped_func(*args, **kwargs):
self = args[0]
assert self.__can_use, "User oper... | [
"def",
"operations",
"(",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"args",
"[",
"0",
"]",
"assert",
"self",
".",
... | Class decorator stores all calls into list.
Can be used until .invalidate() is called.
:return: decorated class | [
"Class",
"decorator",
"stores",
"all",
"calls",
"into",
"list",
".",
"Can",
"be",
"used",
"until",
".",
"invalidate",
"()",
"is",
"called",
".",
":",
"return",
":",
"decorated",
"class"
] | 4586ea11d5103c2ff9607d3ed922b5a0991b8845 | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/api/private/__init__.py#L39-L76 | train |
developersociety/django-glitter | glitter/publisher/utils.py | process_actions | def process_actions(action_ids=None):
"""
Process actions in the publishing schedule.
Returns the number of actions processed.
"""
actions_taken = 0
action_list = PublishAction.objects.prefetch_related(
'content_object',
).filter(
scheduled_time__lte=timezone.now(),
)
... | python | def process_actions(action_ids=None):
"""
Process actions in the publishing schedule.
Returns the number of actions processed.
"""
actions_taken = 0
action_list = PublishAction.objects.prefetch_related(
'content_object',
).filter(
scheduled_time__lte=timezone.now(),
)
... | [
"def",
"process_actions",
"(",
"action_ids",
"=",
"None",
")",
":",
"actions_taken",
"=",
"0",
"action_list",
"=",
"PublishAction",
".",
"objects",
".",
"prefetch_related",
"(",
"'content_object'",
",",
")",
".",
"filter",
"(",
"scheduled_time__lte",
"=",
"timez... | Process actions in the publishing schedule.
Returns the number of actions processed. | [
"Process",
"actions",
"in",
"the",
"publishing",
"schedule",
"."
] | 2c0280ec83afee80deee94ee3934fc54239c2e87 | https://github.com/developersociety/django-glitter/blob/2c0280ec83afee80deee94ee3934fc54239c2e87/glitter/publisher/utils.py#L7-L28 | train |
developersociety/django-glitter | glitter/publisher/utils.py | celery_enabled | def celery_enabled():
"""
Return a boolean if Celery tasks are enabled for this app.
If the ``GLITTER_PUBLISHER_CELERY`` setting is ``True`` or ``False`` - then that value will be
used. However if the setting isn't defined, then this will be enabled automatically if Celery
is installed.
"""
... | python | def celery_enabled():
"""
Return a boolean if Celery tasks are enabled for this app.
If the ``GLITTER_PUBLISHER_CELERY`` setting is ``True`` or ``False`` - then that value will be
used. However if the setting isn't defined, then this will be enabled automatically if Celery
is installed.
"""
... | [
"def",
"celery_enabled",
"(",
")",
":",
"enabled",
"=",
"getattr",
"(",
"settings",
",",
"'GLITTER_PUBLISHER_CELERY'",
",",
"None",
")",
"if",
"enabled",
"is",
"None",
":",
"try",
":",
"import",
"celery",
"# noqa",
"enabled",
"=",
"True",
"except",
"ImportEr... | Return a boolean if Celery tasks are enabled for this app.
If the ``GLITTER_PUBLISHER_CELERY`` setting is ``True`` or ``False`` - then that value will be
used. However if the setting isn't defined, then this will be enabled automatically if Celery
is installed. | [
"Return",
"a",
"boolean",
"if",
"Celery",
"tasks",
"are",
"enabled",
"for",
"this",
"app",
"."
] | 2c0280ec83afee80deee94ee3934fc54239c2e87 | https://github.com/developersociety/django-glitter/blob/2c0280ec83afee80deee94ee3934fc54239c2e87/glitter/publisher/utils.py#L31-L48 | train |
davidblaisonneau-orange/foreman | foreman/operatingsystems.py | OperatingSystems.checkAndCreate | def checkAndCreate(self, key, payload):
""" Function checkAndCreate
Check if an object exists and create it if not
@param key: The targeted object
@param payload: The targeted object description
@return RETURN: The id of the object
"""
if key not in self:
... | python | def checkAndCreate(self, key, payload):
""" Function checkAndCreate
Check if an object exists and create it if not
@param key: The targeted object
@param payload: The targeted object description
@return RETURN: The id of the object
"""
if key not in self:
... | [
"def",
"checkAndCreate",
"(",
"self",
",",
"key",
",",
"payload",
")",
":",
"if",
"key",
"not",
"in",
"self",
":",
"if",
"'templates'",
"in",
"payload",
":",
"templates",
"=",
"payload",
".",
"pop",
"(",
"'templates'",
")",
"self",
"[",
"key",
"]",
"... | Function checkAndCreate
Check if an object exists and create it if not
@param key: The targeted object
@param payload: The targeted object description
@return RETURN: The id of the object | [
"Function",
"checkAndCreate",
"Check",
"if",
"an",
"object",
"exists",
"and",
"create",
"it",
"if",
"not"
] | acb8fd8d74657cfac3b25c82e9c6028b93eb6c92 | https://github.com/davidblaisonneau-orange/foreman/blob/acb8fd8d74657cfac3b25c82e9c6028b93eb6c92/foreman/operatingsystems.py#L51-L64 | train |
qubell/contrib-python-qubell-client | qubell/api/private/instance.py | Instance.__collect_interfaces_return | def __collect_interfaces_return(interfaces):
"""Collect new style (44.1+) return values to old-style kv-list"""
acc = []
for (interfaceName, interfaceData) in interfaces.items():
signalValues = interfaceData.get("signals", {})
for (signalName, signalValue) in signalValues... | python | def __collect_interfaces_return(interfaces):
"""Collect new style (44.1+) return values to old-style kv-list"""
acc = []
for (interfaceName, interfaceData) in interfaces.items():
signalValues = interfaceData.get("signals", {})
for (signalName, signalValue) in signalValues... | [
"def",
"__collect_interfaces_return",
"(",
"interfaces",
")",
":",
"acc",
"=",
"[",
"]",
"for",
"(",
"interfaceName",
",",
"interfaceData",
")",
"in",
"interfaces",
".",
"items",
"(",
")",
":",
"signalValues",
"=",
"interfaceData",
".",
"get",
"(",
"\"signal... | Collect new style (44.1+) return values to old-style kv-list | [
"Collect",
"new",
"style",
"(",
"44",
".",
"1",
"+",
")",
"return",
"values",
"to",
"old",
"-",
"style",
"kv",
"-",
"list"
] | 4586ea11d5103c2ff9607d3ed922b5a0991b8845 | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/api/private/instance.py#L113-L121 | train |
qubell/contrib-python-qubell-client | qubell/api/private/instance.py | Instance.return_values | def return_values(self):
""" Guess what api we are using and return as public api does.
Private has {'id':'key', 'value':'keyvalue'} format, public has {'key':'keyvalue'}
"""
j = self.json()
#TODO: FIXME: get rid of old API when its support will be removed
public_api_val... | python | def return_values(self):
""" Guess what api we are using and return as public api does.
Private has {'id':'key', 'value':'keyvalue'} format, public has {'key':'keyvalue'}
"""
j = self.json()
#TODO: FIXME: get rid of old API when its support will be removed
public_api_val... | [
"def",
"return_values",
"(",
"self",
")",
":",
"j",
"=",
"self",
".",
"json",
"(",
")",
"#TODO: FIXME: get rid of old API when its support will be removed",
"public_api_value",
"=",
"j",
".",
"get",
"(",
"'returnValues'",
")",
"old_private_value",
"=",
"j",
".",
"... | Guess what api we are using and return as public api does.
Private has {'id':'key', 'value':'keyvalue'} format, public has {'key':'keyvalue'} | [
"Guess",
"what",
"api",
"we",
"are",
"using",
"and",
"return",
"as",
"public",
"api",
"does",
".",
"Private",
"has",
"{",
"id",
":",
"key",
"value",
":",
"keyvalue",
"}",
"format",
"public",
"has",
"{",
"key",
":",
"keyvalue",
"}"
] | 4586ea11d5103c2ff9607d3ed922b5a0991b8845 | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/api/private/instance.py#L124-L139 | train |
qubell/contrib-python-qubell-client | qubell/api/private/instance.py | Instance.get_activitylog | def get_activitylog(self, after=None, severity=None, start=None, end=None):
"""
Returns activitylog object
severity - filter severity ('INFO', DEBUG')
start/end - time or log text
"""
if after:
log_raw = self._router.get_instance_activitylog(org_id=self.organ... | python | def get_activitylog(self, after=None, severity=None, start=None, end=None):
"""
Returns activitylog object
severity - filter severity ('INFO', DEBUG')
start/end - time or log text
"""
if after:
log_raw = self._router.get_instance_activitylog(org_id=self.organ... | [
"def",
"get_activitylog",
"(",
"self",
",",
"after",
"=",
"None",
",",
"severity",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"if",
"after",
":",
"log_raw",
"=",
"self",
".",
"_router",
".",
"get_instance_activitylog",
"... | Returns activitylog object
severity - filter severity ('INFO', DEBUG')
start/end - time or log text | [
"Returns",
"activitylog",
"object",
"severity",
"-",
"filter",
"severity",
"(",
"INFO",
"DEBUG",
")",
"start",
"/",
"end",
"-",
"time",
"or",
"log",
"text"
] | 4586ea11d5103c2ff9607d3ed922b5a0991b8845 | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/api/private/instance.py#L149-L164 | train |
qubell/contrib-python-qubell-client | qubell/api/private/instance.py | Instance.json | def json(self):
"""
return __cached_json, if accessed withing 300 ms.
This allows to optimize calls when many parameters of entity requires withing short time.
"""
if self.fresh():
return self.__cached_json
# noinspection PyAttributeOutsideInit
self._... | python | def json(self):
"""
return __cached_json, if accessed withing 300 ms.
This allows to optimize calls when many parameters of entity requires withing short time.
"""
if self.fresh():
return self.__cached_json
# noinspection PyAttributeOutsideInit
self._... | [
"def",
"json",
"(",
"self",
")",
":",
"if",
"self",
".",
"fresh",
"(",
")",
":",
"return",
"self",
".",
"__cached_json",
"# noinspection PyAttributeOutsideInit",
"self",
".",
"__last_read_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"__cached_json... | return __cached_json, if accessed withing 300 ms.
This allows to optimize calls when many parameters of entity requires withing short time. | [
"return",
"__cached_json",
"if",
"accessed",
"withing",
"300",
"ms",
".",
"This",
"allows",
"to",
"optimize",
"calls",
"when",
"many",
"parameters",
"of",
"entity",
"requires",
"withing",
"short",
"time",
"."
] | 4586ea11d5103c2ff9607d3ed922b5a0991b8845 | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/api/private/instance.py#L264-L276 | train |
qubell/contrib-python-qubell-client | qubell/api/private/instance.py | Instance.get_most_recent_update_time | def get_most_recent_update_time(self):
"""
Indicated most recent update of the instance, assumption based on:
- if currentWorkflow exists, its startedAt time is most recent update.
- else max of workflowHistory startedAt is most recent update.
"""
def parse_time(t):
... | python | def get_most_recent_update_time(self):
"""
Indicated most recent update of the instance, assumption based on:
- if currentWorkflow exists, its startedAt time is most recent update.
- else max of workflowHistory startedAt is most recent update.
"""
def parse_time(t):
... | [
"def",
"get_most_recent_update_time",
"(",
"self",
")",
":",
"def",
"parse_time",
"(",
"t",
")",
":",
"if",
"t",
":",
"return",
"time",
".",
"gmtime",
"(",
"t",
"/",
"1000",
")",
"return",
"None",
"try",
":",
"max_wf_started_at",
"=",
"max",
"(",
"[",
... | Indicated most recent update of the instance, assumption based on:
- if currentWorkflow exists, its startedAt time is most recent update.
- else max of workflowHistory startedAt is most recent update. | [
"Indicated",
"most",
"recent",
"update",
"of",
"the",
"instance",
"assumption",
"based",
"on",
":",
"-",
"if",
"currentWorkflow",
"exists",
"its",
"startedAt",
"time",
"is",
"most",
"recent",
"update",
".",
"-",
"else",
"max",
"of",
"workflowHistory",
"started... | 4586ea11d5103c2ff9607d3ed922b5a0991b8845 | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/api/private/instance.py#L508-L522 | train |
qubell/contrib-python-qubell-client | qubell/api/private/instance.py | Instance._is_projection_updated_instance | def _is_projection_updated_instance(self):
"""
This method tries to guess if instance was update since last time.
If return True, definitely Yes, if False, this means more unknown
:return: bool
"""
last = self._last_workflow_started_time
if not self._router.public... | python | def _is_projection_updated_instance(self):
"""
This method tries to guess if instance was update since last time.
If return True, definitely Yes, if False, this means more unknown
:return: bool
"""
last = self._last_workflow_started_time
if not self._router.public... | [
"def",
"_is_projection_updated_instance",
"(",
"self",
")",
":",
"last",
"=",
"self",
".",
"_last_workflow_started_time",
"if",
"not",
"self",
".",
"_router",
".",
"public_api_in_use",
":",
"most_recent",
"=",
"self",
".",
"get_most_recent_update_time",
"(",
")",
... | This method tries to guess if instance was update since last time.
If return True, definitely Yes, if False, this means more unknown
:return: bool | [
"This",
"method",
"tries",
"to",
"guess",
"if",
"instance",
"was",
"update",
"since",
"last",
"time",
".",
"If",
"return",
"True",
"definitely",
"Yes",
"if",
"False",
"this",
"means",
"more",
"unknown",
":",
"return",
":",
"bool"
] | 4586ea11d5103c2ff9607d3ed922b5a0991b8845 | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/api/private/instance.py#L524-L537 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.