id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
249,700
minhhoit/yacms
yacms/core/models.py
ContentTyped.set_content_model
def set_content_model(self): """ Set content_model to the child class's related name, or None if this is the base class. """ if not self.content_model: is_base_class = ( base_concrete_model(ContentTyped, self) == self.__class__) self.content_model = ( None if is_base_class else self.get_content_model_name())
python
def set_content_model(self): """ Set content_model to the child class's related name, or None if this is the base class. """ if not self.content_model: is_base_class = ( base_concrete_model(ContentTyped, self) == self.__class__) self.content_model = ( None if is_base_class else self.get_content_model_name())
[ "def", "set_content_model", "(", "self", ")", ":", "if", "not", "self", ".", "content_model", ":", "is_base_class", "=", "(", "base_concrete_model", "(", "ContentTyped", ",", "self", ")", "==", "self", ".", "__class__", ")", "self", ".", "content_model", "=", "(", "None", "if", "is_base_class", "else", "self", ".", "get_content_model_name", "(", ")", ")" ]
Set content_model to the child class's related name, or None if this is the base class.
[ "Set", "content_model", "to", "the", "child", "class", "s", "related", "name", "or", "None", "if", "this", "is", "the", "base", "class", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/models.py#L532-L541
249,701
zeaphoo/budoc
budoc/budoc.py
indent
def indent(s, spaces=4): """ Inserts `spaces` after each string of new lines in `s` and before the start of the string. """ new = re.sub('(\n+)', '\\1%s' % (' ' * spaces), s) return (' ' * spaces) + new.strip()
python
def indent(s, spaces=4): """ Inserts `spaces` after each string of new lines in `s` and before the start of the string. """ new = re.sub('(\n+)', '\\1%s' % (' ' * spaces), s) return (' ' * spaces) + new.strip()
[ "def", "indent", "(", "s", ",", "spaces", "=", "4", ")", ":", "new", "=", "re", ".", "sub", "(", "'(\\n+)'", ",", "'\\\\1%s'", "%", "(", "' '", "*", "spaces", ")", ",", "s", ")", "return", "(", "' '", "*", "spaces", ")", "+", "new", ".", "strip", "(", ")" ]
Inserts `spaces` after each string of new lines in `s` and before the start of the string.
[ "Inserts", "spaces", "after", "each", "string", "of", "new", "lines", "in", "s", "and", "before", "the", "start", "of", "the", "string", "." ]
28f3aea4ad72ac90605ced012ed20e61af90c23a
https://github.com/zeaphoo/budoc/blob/28f3aea4ad72ac90605ced012ed20e61af90c23a/budoc/budoc.py#L15-L21
249,702
spookey/photon
photon/util/files.py
read_yaml
def read_yaml(filename, add_constructor=None): ''' Reads YAML files :param filename: The full path to the YAML file :param add_constructor: A list of yaml constructors (loaders) :returns: Loaded YAML content as represented data structure .. seealso:: :func:`util.structures.yaml_str_join`, :func:`util.structures.yaml_loc_join` ''' y = read_file(filename) if add_constructor: if not isinstance(add_constructor, list): add_constructor = [add_constructor] for a in add_constructor: _yaml.add_constructor(*a) if y: return _yaml.load(y)
python
def read_yaml(filename, add_constructor=None): ''' Reads YAML files :param filename: The full path to the YAML file :param add_constructor: A list of yaml constructors (loaders) :returns: Loaded YAML content as represented data structure .. seealso:: :func:`util.structures.yaml_str_join`, :func:`util.structures.yaml_loc_join` ''' y = read_file(filename) if add_constructor: if not isinstance(add_constructor, list): add_constructor = [add_constructor] for a in add_constructor: _yaml.add_constructor(*a) if y: return _yaml.load(y)
[ "def", "read_yaml", "(", "filename", ",", "add_constructor", "=", "None", ")", ":", "y", "=", "read_file", "(", "filename", ")", "if", "add_constructor", ":", "if", "not", "isinstance", "(", "add_constructor", ",", "list", ")", ":", "add_constructor", "=", "[", "add_constructor", "]", "for", "a", "in", "add_constructor", ":", "_yaml", ".", "add_constructor", "(", "*", "a", ")", "if", "y", ":", "return", "_yaml", ".", "load", "(", "y", ")" ]
Reads YAML files :param filename: The full path to the YAML file :param add_constructor: A list of yaml constructors (loaders) :returns: Loaded YAML content as represented data structure .. seealso:: :func:`util.structures.yaml_str_join`, :func:`util.structures.yaml_loc_join`
[ "Reads", "YAML", "files" ]
57212a26ce713ab7723910ee49e3d0ba1697799f
https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/util/files.py#L29-L52
249,703
spookey/photon
photon/util/files.py
write_yaml
def write_yaml(filename, content): ''' Writes YAML files :param filename: The full path to the YAML file :param content: The content to dump :returns: The size written ''' y = _yaml.dump(content, indent=4, default_flow_style=False) if y: return write_file(filename, y)
python
def write_yaml(filename, content): ''' Writes YAML files :param filename: The full path to the YAML file :param content: The content to dump :returns: The size written ''' y = _yaml.dump(content, indent=4, default_flow_style=False) if y: return write_file(filename, y)
[ "def", "write_yaml", "(", "filename", ",", "content", ")", ":", "y", "=", "_yaml", ".", "dump", "(", "content", ",", "indent", "=", "4", ",", "default_flow_style", "=", "False", ")", "if", "y", ":", "return", "write_file", "(", "filename", ",", "y", ")" ]
Writes YAML files :param filename: The full path to the YAML file :param content: The content to dump :returns: The size written
[ "Writes", "YAML", "files" ]
57212a26ce713ab7723910ee49e3d0ba1697799f
https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/util/files.py#L88-L102
249,704
spookey/photon
photon/util/files.py
write_json
def write_json(filename, content): ''' Writes json files :param filename: The full path to the json file :param content: The content to dump :returns: The size written ''' j = _dumps(content, indent=4, sort_keys=True) if j: return write_file(filename, j)
python
def write_json(filename, content): ''' Writes json files :param filename: The full path to the json file :param content: The content to dump :returns: The size written ''' j = _dumps(content, indent=4, sort_keys=True) if j: return write_file(filename, j)
[ "def", "write_json", "(", "filename", ",", "content", ")", ":", "j", "=", "_dumps", "(", "content", ",", "indent", "=", "4", ",", "sort_keys", "=", "True", ")", "if", "j", ":", "return", "write_file", "(", "filename", ",", "j", ")" ]
Writes json files :param filename: The full path to the json file :param content: The content to dump :returns: The size written
[ "Writes", "json", "files" ]
57212a26ce713ab7723910ee49e3d0ba1697799f
https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/util/files.py#L105-L119
249,705
ulf1/oxyba
oxyba/block_idxmat_shuffle.py
block_idxmat_shuffle
def block_idxmat_shuffle(numdraws, numblocks, random_state=None): """Create K columns with unique random integers from 0 to N-1 Purpose: -------- - Create K blocks for k-fold cross-validation Parameters: ----------- numdraws : int number of observations N or sample size N numblocks : int number of blocks K Example: -------- import pandas as pd import numpy as np import oxyba as ox X = np.random.normal(size=(7,5), scale=50).round(1) N,_ = X.shape K = 3; #number of blocks idxmat, dropped = ox.block_idxmat_shuffle(N,K) for b in range(K): print('\nBlock:',b) print(pd.DataFrame(X[idxmat[:,b],:], index=idxmat[:,b])) print('\nDropped observations\n', X[dropped,:] ) print('\nrow indicies of dropped observations:', dropped, '\') Why is this useful? ------------------- - Avoid creating copies of dataset X during run time - Shuffle the indicies of a data point rather than the data points themselve Links: ------ - How numpy's permutation works, https://stackoverflow.com/a/15474335 """ # load modules import numpy as np # minimum block size: bz=int(N/K) blocksize = int(numdraws / numblocks) # shuffle vector indicies: from 0 to N-1 if random_state: np.random.seed(random_state) obsidx = np.random.permutation(numdraws) # how many to drop? i.e. "numdrop = N - bz*K" numdrop = numdraws % numblocks dropped = obsidx[:numdrop] obsidx = obsidx[numdrop:] # reshape the remaing vector indicies into a matrix idxmat = obsidx.reshape((blocksize, numblocks)) # output the indicies for the blocks, and indicies of dropped obserations return idxmat, dropped
python
def block_idxmat_shuffle(numdraws, numblocks, random_state=None): """Create K columns with unique random integers from 0 to N-1 Purpose: -------- - Create K blocks for k-fold cross-validation Parameters: ----------- numdraws : int number of observations N or sample size N numblocks : int number of blocks K Example: -------- import pandas as pd import numpy as np import oxyba as ox X = np.random.normal(size=(7,5), scale=50).round(1) N,_ = X.shape K = 3; #number of blocks idxmat, dropped = ox.block_idxmat_shuffle(N,K) for b in range(K): print('\nBlock:',b) print(pd.DataFrame(X[idxmat[:,b],:], index=idxmat[:,b])) print('\nDropped observations\n', X[dropped,:] ) print('\nrow indicies of dropped observations:', dropped, '\') Why is this useful? ------------------- - Avoid creating copies of dataset X during run time - Shuffle the indicies of a data point rather than the data points themselve Links: ------ - How numpy's permutation works, https://stackoverflow.com/a/15474335 """ # load modules import numpy as np # minimum block size: bz=int(N/K) blocksize = int(numdraws / numblocks) # shuffle vector indicies: from 0 to N-1 if random_state: np.random.seed(random_state) obsidx = np.random.permutation(numdraws) # how many to drop? i.e. "numdrop = N - bz*K" numdrop = numdraws % numblocks dropped = obsidx[:numdrop] obsidx = obsidx[numdrop:] # reshape the remaing vector indicies into a matrix idxmat = obsidx.reshape((blocksize, numblocks)) # output the indicies for the blocks, and indicies of dropped obserations return idxmat, dropped
[ "def", "block_idxmat_shuffle", "(", "numdraws", ",", "numblocks", ",", "random_state", "=", "None", ")", ":", "# load modules", "import", "numpy", "as", "np", "# minimum block size: bz=int(N/K)", "blocksize", "=", "int", "(", "numdraws", "/", "numblocks", ")", "# shuffle vector indicies: from 0 to N-1", "if", "random_state", ":", "np", ".", "random", ".", "seed", "(", "random_state", ")", "obsidx", "=", "np", ".", "random", ".", "permutation", "(", "numdraws", ")", "# how many to drop? i.e. \"numdrop = N - bz*K\"", "numdrop", "=", "numdraws", "%", "numblocks", "dropped", "=", "obsidx", "[", ":", "numdrop", "]", "obsidx", "=", "obsidx", "[", "numdrop", ":", "]", "# reshape the remaing vector indicies into a matrix", "idxmat", "=", "obsidx", ".", "reshape", "(", "(", "blocksize", ",", "numblocks", ")", ")", "# output the indicies for the blocks, and indicies of dropped obserations", "return", "idxmat", ",", "dropped" ]
Create K columns with unique random integers from 0 to N-1 Purpose: -------- - Create K blocks for k-fold cross-validation Parameters: ----------- numdraws : int number of observations N or sample size N numblocks : int number of blocks K Example: -------- import pandas as pd import numpy as np import oxyba as ox X = np.random.normal(size=(7,5), scale=50).round(1) N,_ = X.shape K = 3; #number of blocks idxmat, dropped = ox.block_idxmat_shuffle(N,K) for b in range(K): print('\nBlock:',b) print(pd.DataFrame(X[idxmat[:,b],:], index=idxmat[:,b])) print('\nDropped observations\n', X[dropped,:] ) print('\nrow indicies of dropped observations:', dropped, '\') Why is this useful? ------------------- - Avoid creating copies of dataset X during run time - Shuffle the indicies of a data point rather than the data points themselve Links: ------ - How numpy's permutation works, https://stackoverflow.com/a/15474335
[ "Create", "K", "columns", "with", "unique", "random", "integers", "from", "0", "to", "N", "-", "1" ]
b3043116050de275124365cb11e7df91fb40169d
https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/block_idxmat_shuffle.py#L1-L65
249,706
treycucco/bidon
bidon/spreadsheet/base.py
WorksheetBase.to_cell_table
def to_cell_table(self, merged=True): """Returns a list of lists of Cells with the cooked value and note for each cell.""" new_rows = [] for row_index, row in enumerate(self.rows(CellMode.cooked)): new_row = [] for col_index, cell_value in enumerate(row): new_row.append(Cell(cell_value, self.get_note((col_index, row_index)))) new_rows.append(new_row) if merged: for cell_low, cell_high in self.merged_cell_ranges(): anchor_cell = new_rows[cell_low[1]][cell_low[0]] for row_index in range(cell_low[1], cell_high[1]): for col_index in range(cell_low[0], cell_high[0]): # NOTE: xlrd occassionally returns ranges that don't have cells. try: new_rows[row_index][col_index] = anchor_cell.copy() except IndexError: pass return new_rows
python
def to_cell_table(self, merged=True): """Returns a list of lists of Cells with the cooked value and note for each cell.""" new_rows = [] for row_index, row in enumerate(self.rows(CellMode.cooked)): new_row = [] for col_index, cell_value in enumerate(row): new_row.append(Cell(cell_value, self.get_note((col_index, row_index)))) new_rows.append(new_row) if merged: for cell_low, cell_high in self.merged_cell_ranges(): anchor_cell = new_rows[cell_low[1]][cell_low[0]] for row_index in range(cell_low[1], cell_high[1]): for col_index in range(cell_low[0], cell_high[0]): # NOTE: xlrd occassionally returns ranges that don't have cells. try: new_rows[row_index][col_index] = anchor_cell.copy() except IndexError: pass return new_rows
[ "def", "to_cell_table", "(", "self", ",", "merged", "=", "True", ")", ":", "new_rows", "=", "[", "]", "for", "row_index", ",", "row", "in", "enumerate", "(", "self", ".", "rows", "(", "CellMode", ".", "cooked", ")", ")", ":", "new_row", "=", "[", "]", "for", "col_index", ",", "cell_value", "in", "enumerate", "(", "row", ")", ":", "new_row", ".", "append", "(", "Cell", "(", "cell_value", ",", "self", ".", "get_note", "(", "(", "col_index", ",", "row_index", ")", ")", ")", ")", "new_rows", ".", "append", "(", "new_row", ")", "if", "merged", ":", "for", "cell_low", ",", "cell_high", "in", "self", ".", "merged_cell_ranges", "(", ")", ":", "anchor_cell", "=", "new_rows", "[", "cell_low", "[", "1", "]", "]", "[", "cell_low", "[", "0", "]", "]", "for", "row_index", "in", "range", "(", "cell_low", "[", "1", "]", ",", "cell_high", "[", "1", "]", ")", ":", "for", "col_index", "in", "range", "(", "cell_low", "[", "0", "]", ",", "cell_high", "[", "0", "]", ")", ":", "# NOTE: xlrd occassionally returns ranges that don't have cells.", "try", ":", "new_rows", "[", "row_index", "]", "[", "col_index", "]", "=", "anchor_cell", ".", "copy", "(", ")", "except", "IndexError", ":", "pass", "return", "new_rows" ]
Returns a list of lists of Cells with the cooked value and note for each cell.
[ "Returns", "a", "list", "of", "lists", "of", "Cells", "with", "the", "cooked", "value", "and", "note", "for", "each", "cell", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/spreadsheet/base.py#L44-L62
249,707
treycucco/bidon
bidon/spreadsheet/base.py
WorksheetBase.rows
def rows(self, cell_mode=CellMode.cooked): """Generates a sequence of parsed rows from the worksheet. The cells are parsed according to the cell_mode argument. """ for row_index in range(self.nrows): yield self.parse_row(self.get_row(row_index), row_index, cell_mode)
python
def rows(self, cell_mode=CellMode.cooked): """Generates a sequence of parsed rows from the worksheet. The cells are parsed according to the cell_mode argument. """ for row_index in range(self.nrows): yield self.parse_row(self.get_row(row_index), row_index, cell_mode)
[ "def", "rows", "(", "self", ",", "cell_mode", "=", "CellMode", ".", "cooked", ")", ":", "for", "row_index", "in", "range", "(", "self", ".", "nrows", ")", ":", "yield", "self", ".", "parse_row", "(", "self", ".", "get_row", "(", "row_index", ")", ",", "row_index", ",", "cell_mode", ")" ]
Generates a sequence of parsed rows from the worksheet. The cells are parsed according to the cell_mode argument.
[ "Generates", "a", "sequence", "of", "parsed", "rows", "from", "the", "worksheet", ".", "The", "cells", "are", "parsed", "according", "to", "the", "cell_mode", "argument", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/spreadsheet/base.py#L64-L69
249,708
treycucco/bidon
bidon/spreadsheet/base.py
WorksheetBase.parse_row
def parse_row(self, row, row_index, cell_mode=CellMode.cooked): """Parse a row according to the given cell_mode.""" return [self.parse_cell(cell, (col_index, row_index), cell_mode) \ for col_index, cell in enumerate(row)]
python
def parse_row(self, row, row_index, cell_mode=CellMode.cooked): """Parse a row according to the given cell_mode.""" return [self.parse_cell(cell, (col_index, row_index), cell_mode) \ for col_index, cell in enumerate(row)]
[ "def", "parse_row", "(", "self", ",", "row", ",", "row_index", ",", "cell_mode", "=", "CellMode", ".", "cooked", ")", ":", "return", "[", "self", ".", "parse_cell", "(", "cell", ",", "(", "col_index", ",", "row_index", ")", ",", "cell_mode", ")", "for", "col_index", ",", "cell", "in", "enumerate", "(", "row", ")", "]" ]
Parse a row according to the given cell_mode.
[ "Parse", "a", "row", "according", "to", "the", "given", "cell_mode", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/spreadsheet/base.py#L71-L74
249,709
treycucco/bidon
bidon/spreadsheet/base.py
WorksheetBase.tuple_to_datetime
def tuple_to_datetime(self, date_tuple): """Converts a tuple to a either a date, time or datetime object. If the Y, M and D parts of the tuple are all 0, then a time object is returned. If the h, m and s aprts of the tuple are all 0, then a date object is returned. Otherwise a datetime object is returned. """ year, month, day, hour, minute, second = date_tuple if year == month == day == 0: return time(hour, minute, second) elif hour == minute == second == 0: return date(year, month, day) else: return datetime(year, month, day, hour, minute, second)
python
def tuple_to_datetime(self, date_tuple): """Converts a tuple to a either a date, time or datetime object. If the Y, M and D parts of the tuple are all 0, then a time object is returned. If the h, m and s aprts of the tuple are all 0, then a date object is returned. Otherwise a datetime object is returned. """ year, month, day, hour, minute, second = date_tuple if year == month == day == 0: return time(hour, minute, second) elif hour == minute == second == 0: return date(year, month, day) else: return datetime(year, month, day, hour, minute, second)
[ "def", "tuple_to_datetime", "(", "self", ",", "date_tuple", ")", ":", "year", ",", "month", ",", "day", ",", "hour", ",", "minute", ",", "second", "=", "date_tuple", "if", "year", "==", "month", "==", "day", "==", "0", ":", "return", "time", "(", "hour", ",", "minute", ",", "second", ")", "elif", "hour", "==", "minute", "==", "second", "==", "0", ":", "return", "date", "(", "year", ",", "month", ",", "day", ")", "else", ":", "return", "datetime", "(", "year", ",", "month", ",", "day", ",", "hour", ",", "minute", ",", "second", ")" ]
Converts a tuple to a either a date, time or datetime object. If the Y, M and D parts of the tuple are all 0, then a time object is returned. If the h, m and s aprts of the tuple are all 0, then a date object is returned. Otherwise a datetime object is returned.
[ "Converts", "a", "tuple", "to", "a", "either", "a", "date", "time", "or", "datetime", "object", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/spreadsheet/base.py#L82-L95
249,710
treycucco/bidon
bidon/spreadsheet/base.py
WorkbookBase.sheets
def sheets(self, index=None): """Return either a list of all sheets if index is None, or the sheet at the given index.""" if self._sheets is None: self._sheets = [self.get_worksheet(s, i) for i, s in enumerate(self.iterate_sheets())] if index is None: return self._sheets else: return self._sheets[index]
python
def sheets(self, index=None): """Return either a list of all sheets if index is None, or the sheet at the given index.""" if self._sheets is None: self._sheets = [self.get_worksheet(s, i) for i, s in enumerate(self.iterate_sheets())] if index is None: return self._sheets else: return self._sheets[index]
[ "def", "sheets", "(", "self", ",", "index", "=", "None", ")", ":", "if", "self", ".", "_sheets", "is", "None", ":", "self", ".", "_sheets", "=", "[", "self", ".", "get_worksheet", "(", "s", ",", "i", ")", "for", "i", ",", "s", "in", "enumerate", "(", "self", ".", "iterate_sheets", "(", ")", ")", "]", "if", "index", "is", "None", ":", "return", "self", ".", "_sheets", "else", ":", "return", "self", ".", "_sheets", "[", "index", "]" ]
Return either a list of all sheets if index is None, or the sheet at the given index.
[ "Return", "either", "a", "list", "of", "all", "sheets", "if", "index", "is", "None", "or", "the", "sheet", "at", "the", "given", "index", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/spreadsheet/base.py#L125-L132
249,711
rerb/django-fortune
fortune/models.py
get_fortunes_path
def get_fortunes_path(): """Return the path to the fortunes data packs. """ app_config = apps.get_app_config("fortune") return Path(os.sep.join([app_config.path, "fortunes"]))
python
def get_fortunes_path(): """Return the path to the fortunes data packs. """ app_config = apps.get_app_config("fortune") return Path(os.sep.join([app_config.path, "fortunes"]))
[ "def", "get_fortunes_path", "(", ")", ":", "app_config", "=", "apps", ".", "get_app_config", "(", "\"fortune\"", ")", "return", "Path", "(", "os", ".", "sep", ".", "join", "(", "[", "app_config", ".", "path", ",", "\"fortunes\"", "]", ")", ")" ]
Return the path to the fortunes data packs.
[ "Return", "the", "path", "to", "the", "fortunes", "data", "packs", "." ]
f84d34f616ecabd4fab8351ad7d3062cc9d6b127
https://github.com/rerb/django-fortune/blob/f84d34f616ecabd4fab8351ad7d3062cc9d6b127/fortune/models.py#L35-L39
249,712
minhhoit/yacms
yacms/accounts/templatetags/accounts_tags.py
profile_fields
def profile_fields(user): """ Returns profile fields as a dict for the given user. Used in the profile view template when the ``ACCOUNTS_PROFILE_VIEWS_ENABLED`` setting is set to ``True``, and also in the account approval emails sent to administrators when the ``ACCOUNTS_APPROVAL_REQUIRED`` setting is set to ``True``. """ fields = OrderedDict() try: profile = get_profile_for_user(user) user_fieldname = get_profile_user_fieldname() exclude = tuple(settings.ACCOUNTS_PROFILE_FORM_EXCLUDE_FIELDS) for field in profile._meta.fields: if field.name not in ("id", user_fieldname) + exclude: value = getattr(profile, field.name) fields[field.verbose_name.title()] = value except ProfileNotConfigured: pass return list(fields.items())
python
def profile_fields(user): """ Returns profile fields as a dict for the given user. Used in the profile view template when the ``ACCOUNTS_PROFILE_VIEWS_ENABLED`` setting is set to ``True``, and also in the account approval emails sent to administrators when the ``ACCOUNTS_APPROVAL_REQUIRED`` setting is set to ``True``. """ fields = OrderedDict() try: profile = get_profile_for_user(user) user_fieldname = get_profile_user_fieldname() exclude = tuple(settings.ACCOUNTS_PROFILE_FORM_EXCLUDE_FIELDS) for field in profile._meta.fields: if field.name not in ("id", user_fieldname) + exclude: value = getattr(profile, field.name) fields[field.verbose_name.title()] = value except ProfileNotConfigured: pass return list(fields.items())
[ "def", "profile_fields", "(", "user", ")", ":", "fields", "=", "OrderedDict", "(", ")", "try", ":", "profile", "=", "get_profile_for_user", "(", "user", ")", "user_fieldname", "=", "get_profile_user_fieldname", "(", ")", "exclude", "=", "tuple", "(", "settings", ".", "ACCOUNTS_PROFILE_FORM_EXCLUDE_FIELDS", ")", "for", "field", "in", "profile", ".", "_meta", ".", "fields", ":", "if", "field", ".", "name", "not", "in", "(", "\"id\"", ",", "user_fieldname", ")", "+", "exclude", ":", "value", "=", "getattr", "(", "profile", ",", "field", ".", "name", ")", "fields", "[", "field", ".", "verbose_name", ".", "title", "(", ")", "]", "=", "value", "except", "ProfileNotConfigured", ":", "pass", "return", "list", "(", "fields", ".", "items", "(", ")", ")" ]
Returns profile fields as a dict for the given user. Used in the profile view template when the ``ACCOUNTS_PROFILE_VIEWS_ENABLED`` setting is set to ``True``, and also in the account approval emails sent to administrators when the ``ACCOUNTS_APPROVAL_REQUIRED`` setting is set to ``True``.
[ "Returns", "profile", "fields", "as", "a", "dict", "for", "the", "given", "user", ".", "Used", "in", "the", "profile", "view", "template", "when", "the", "ACCOUNTS_PROFILE_VIEWS_ENABLED", "setting", "is", "set", "to", "True", "and", "also", "in", "the", "account", "approval", "emails", "sent", "to", "administrators", "when", "the", "ACCOUNTS_APPROVAL_REQUIRED", "setting", "is", "set", "to", "True", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/accounts/templatetags/accounts_tags.py#L60-L79
249,713
minhhoit/yacms
yacms/accounts/templatetags/accounts_tags.py
username_or
def username_or(user, attr): """ Returns the user's username for display, or an alternate attribute if ``ACCOUNTS_NO_USERNAME`` is set to ``True``. """ if not settings.ACCOUNTS_NO_USERNAME: attr = "username" value = getattr(user, attr) if callable(value): value = value() return value
python
def username_or(user, attr): """ Returns the user's username for display, or an alternate attribute if ``ACCOUNTS_NO_USERNAME`` is set to ``True``. """ if not settings.ACCOUNTS_NO_USERNAME: attr = "username" value = getattr(user, attr) if callable(value): value = value() return value
[ "def", "username_or", "(", "user", ",", "attr", ")", ":", "if", "not", "settings", ".", "ACCOUNTS_NO_USERNAME", ":", "attr", "=", "\"username\"", "value", "=", "getattr", "(", "user", ",", "attr", ")", "if", "callable", "(", "value", ")", ":", "value", "=", "value", "(", ")", "return", "value" ]
Returns the user's username for display, or an alternate attribute if ``ACCOUNTS_NO_USERNAME`` is set to ``True``.
[ "Returns", "the", "user", "s", "username", "for", "display", "or", "an", "alternate", "attribute", "if", "ACCOUNTS_NO_USERNAME", "is", "set", "to", "True", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/accounts/templatetags/accounts_tags.py#L83-L93
249,714
inspirehep/plotextractor
plotextractor/api.py
process_tarball
def process_tarball(tarball, output_directory=None, context=False): """Process one tarball end-to-end. If output directory is given, the tarball will be extracted there. Otherwise, it will extract it in a folder next to the tarball file. The function returns a list of dictionaries: .. code-block:: python [{ 'url': '/path/to/tarball_files/d15-120f3d.png', 'captions': ['The $\\rho^0$ meson properties: (a) Mass ...'], 'name': 'd15-120f3d', 'label': 'fig:mass' }, ... ] :param: tarball (string): the absolute location of the tarball we wish to process :param: output_directory (string): path of file processing and extraction (optional) :param: context: if True, also try to extract context where images are referenced in the text. (optional) :return: images(list): list of dictionaries for each image with captions. """ if not output_directory: # No directory given, so we use the same path as the tarball output_directory = os.path.abspath("{0}_files".format(tarball)) extracted_files_list = untar(tarball, output_directory) image_list, tex_files = detect_images_and_tex(extracted_files_list) if tex_files == [] or tex_files is None: raise NoTexFilesFound("No TeX files found in {0}".format(tarball)) converted_image_mapping = convert_images(image_list) return map_images_in_tex( tex_files, converted_image_mapping, output_directory, context )
python
def process_tarball(tarball, output_directory=None, context=False): """Process one tarball end-to-end. If output directory is given, the tarball will be extracted there. Otherwise, it will extract it in a folder next to the tarball file. The function returns a list of dictionaries: .. code-block:: python [{ 'url': '/path/to/tarball_files/d15-120f3d.png', 'captions': ['The $\\rho^0$ meson properties: (a) Mass ...'], 'name': 'd15-120f3d', 'label': 'fig:mass' }, ... ] :param: tarball (string): the absolute location of the tarball we wish to process :param: output_directory (string): path of file processing and extraction (optional) :param: context: if True, also try to extract context where images are referenced in the text. (optional) :return: images(list): list of dictionaries for each image with captions. """ if not output_directory: # No directory given, so we use the same path as the tarball output_directory = os.path.abspath("{0}_files".format(tarball)) extracted_files_list = untar(tarball, output_directory) image_list, tex_files = detect_images_and_tex(extracted_files_list) if tex_files == [] or tex_files is None: raise NoTexFilesFound("No TeX files found in {0}".format(tarball)) converted_image_mapping = convert_images(image_list) return map_images_in_tex( tex_files, converted_image_mapping, output_directory, context )
[ "def", "process_tarball", "(", "tarball", ",", "output_directory", "=", "None", ",", "context", "=", "False", ")", ":", "if", "not", "output_directory", ":", "# No directory given, so we use the same path as the tarball", "output_directory", "=", "os", ".", "path", ".", "abspath", "(", "\"{0}_files\"", ".", "format", "(", "tarball", ")", ")", "extracted_files_list", "=", "untar", "(", "tarball", ",", "output_directory", ")", "image_list", ",", "tex_files", "=", "detect_images_and_tex", "(", "extracted_files_list", ")", "if", "tex_files", "==", "[", "]", "or", "tex_files", "is", "None", ":", "raise", "NoTexFilesFound", "(", "\"No TeX files found in {0}\"", ".", "format", "(", "tarball", ")", ")", "converted_image_mapping", "=", "convert_images", "(", "image_list", ")", "return", "map_images_in_tex", "(", "tex_files", ",", "converted_image_mapping", ",", "output_directory", ",", "context", ")" ]
Process one tarball end-to-end. If output directory is given, the tarball will be extracted there. Otherwise, it will extract it in a folder next to the tarball file. The function returns a list of dictionaries: .. code-block:: python [{ 'url': '/path/to/tarball_files/d15-120f3d.png', 'captions': ['The $\\rho^0$ meson properties: (a) Mass ...'], 'name': 'd15-120f3d', 'label': 'fig:mass' }, ... ] :param: tarball (string): the absolute location of the tarball we wish to process :param: output_directory (string): path of file processing and extraction (optional) :param: context: if True, also try to extract context where images are referenced in the text. (optional) :return: images(list): list of dictionaries for each image with captions.
[ "Process", "one", "tarball", "end", "-", "to", "-", "end", "." ]
12a65350fb9f32d496f9ea57908d9a2771b20474
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/api.py#L42-L83
249,715
inspirehep/plotextractor
plotextractor/api.py
map_images_in_tex
def map_images_in_tex(tex_files, image_mapping, output_directory, context=False): """Return caption and context for image references found in TeX sources.""" extracted_image_data = [] for tex_file in tex_files: # Extract images, captions and labels based on tex file and images partly_extracted_image_data = extract_captions( tex_file, output_directory, image_mapping.keys() ) if partly_extracted_image_data: # Convert to dict, add proper filepaths and do various cleaning cleaned_image_data = prepare_image_data( partly_extracted_image_data, output_directory, image_mapping, ) if context: # Using prev. extracted info, get contexts for each image found extract_context(tex_file, cleaned_image_data) extracted_image_data.extend(cleaned_image_data) return extracted_image_data
python
def map_images_in_tex(tex_files, image_mapping, output_directory, context=False): """Return caption and context for image references found in TeX sources.""" extracted_image_data = [] for tex_file in tex_files: # Extract images, captions and labels based on tex file and images partly_extracted_image_data = extract_captions( tex_file, output_directory, image_mapping.keys() ) if partly_extracted_image_data: # Convert to dict, add proper filepaths and do various cleaning cleaned_image_data = prepare_image_data( partly_extracted_image_data, output_directory, image_mapping, ) if context: # Using prev. extracted info, get contexts for each image found extract_context(tex_file, cleaned_image_data) extracted_image_data.extend(cleaned_image_data) return extracted_image_data
[ "def", "map_images_in_tex", "(", "tex_files", ",", "image_mapping", ",", "output_directory", ",", "context", "=", "False", ")", ":", "extracted_image_data", "=", "[", "]", "for", "tex_file", "in", "tex_files", ":", "# Extract images, captions and labels based on tex file and images", "partly_extracted_image_data", "=", "extract_captions", "(", "tex_file", ",", "output_directory", ",", "image_mapping", ".", "keys", "(", ")", ")", "if", "partly_extracted_image_data", ":", "# Convert to dict, add proper filepaths and do various cleaning", "cleaned_image_data", "=", "prepare_image_data", "(", "partly_extracted_image_data", ",", "output_directory", ",", "image_mapping", ",", ")", "if", "context", ":", "# Using prev. extracted info, get contexts for each image found", "extract_context", "(", "tex_file", ",", "cleaned_image_data", ")", "extracted_image_data", ".", "extend", "(", "cleaned_image_data", ")", "return", "extracted_image_data" ]
Return caption and context for image references found in TeX sources.
[ "Return", "caption", "and", "context", "for", "image", "references", "found", "in", "TeX", "sources", "." ]
12a65350fb9f32d496f9ea57908d9a2771b20474
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/api.py#L86-L110
249,716
b3j0f/conf
b3j0f/conf/driver/file/base.py
_addconfig
def _addconfig(config, *paths): """Add path to CONF_DIRS if exists.""" for path in paths: if path is not None and exists(path): config.append(path)
python
def _addconfig(config, *paths): """Add path to CONF_DIRS if exists.""" for path in paths: if path is not None and exists(path): config.append(path)
[ "def", "_addconfig", "(", "config", ",", "*", "paths", ")", ":", "for", "path", "in", "paths", ":", "if", "path", "is", "not", "None", "and", "exists", "(", "path", ")", ":", "config", ".", "append", "(", "path", ")" ]
Add path to CONF_DIRS if exists.
[ "Add", "path", "to", "CONF_DIRS", "if", "exists", "." ]
18dd6d5d6560f9b202793739e2330a2181163511
https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/driver/file/base.py#L46-L51
249,717
heikomuller/sco-client
scocli/funcdata.py
FunctionalDataHandle.create
def create(url, filename): """Create new fMRI for given experiment by uploading local file. Expects an tar-archive. Parameters ---------- url : string Url to POST fMRI create request filename : string Path to tar-archive on local disk Returns ------- string Url of created functional data resource """ # Upload file to create fMRI resource. If response is not 201 the # uploaded file is not a valid functional data archive files = {'file': open(filename, 'rb')} response = requests.post(url, files=files) if response.status_code != 201: raise ValueError('invalid file: ' + filename) return references_to_dict(response.json()['links'])[REF_SELF]
python
def create(url, filename): """Create new fMRI for given experiment by uploading local file. Expects an tar-archive. Parameters ---------- url : string Url to POST fMRI create request filename : string Path to tar-archive on local disk Returns ------- string Url of created functional data resource """ # Upload file to create fMRI resource. If response is not 201 the # uploaded file is not a valid functional data archive files = {'file': open(filename, 'rb')} response = requests.post(url, files=files) if response.status_code != 201: raise ValueError('invalid file: ' + filename) return references_to_dict(response.json()['links'])[REF_SELF]
[ "def", "create", "(", "url", ",", "filename", ")", ":", "# Upload file to create fMRI resource. If response is not 201 the", "# uploaded file is not a valid functional data archive", "files", "=", "{", "'file'", ":", "open", "(", "filename", ",", "'rb'", ")", "}", "response", "=", "requests", ".", "post", "(", "url", ",", "files", "=", "files", ")", "if", "response", ".", "status_code", "!=", "201", ":", "raise", "ValueError", "(", "'invalid file: '", "+", "filename", ")", "return", "references_to_dict", "(", "response", ".", "json", "(", ")", "[", "'links'", "]", ")", "[", "REF_SELF", "]" ]
Create new fMRI for given experiment by uploading local file. Expects an tar-archive. Parameters ---------- url : string Url to POST fMRI create request filename : string Path to tar-archive on local disk Returns ------- string Url of created functional data resource
[ "Create", "new", "fMRI", "for", "given", "experiment", "by", "uploading", "local", "file", ".", "Expects", "an", "tar", "-", "archive", "." ]
c4afab71297f73003379bba4c1679be9dcf7cef8
https://github.com/heikomuller/sco-client/blob/c4afab71297f73003379bba4c1679be9dcf7cef8/scocli/funcdata.py#L51-L73
249,718
cbrand/vpnchooser
src/vpnchooser/resources/user.py
UserResource.get
def get(self, user_name: str) -> User: """ Gets the User Resource. """ user = current_user() if user.is_admin or user.name == user_name: return self._get_or_abort(user_name) else: abort(403)
python
def get(self, user_name: str) -> User: """ Gets the User Resource. """ user = current_user() if user.is_admin or user.name == user_name: return self._get_or_abort(user_name) else: abort(403)
[ "def", "get", "(", "self", ",", "user_name", ":", "str", ")", "->", "User", ":", "user", "=", "current_user", "(", ")", "if", "user", ".", "is_admin", "or", "user", ".", "name", "==", "user_name", ":", "return", "self", ".", "_get_or_abort", "(", "user_name", ")", "else", ":", "abort", "(", "403", ")" ]
Gets the User Resource.
[ "Gets", "the", "User", "Resource", "." ]
d153e3d05555c23cf5e8e15e507eecad86465923
https://github.com/cbrand/vpnchooser/blob/d153e3d05555c23cf5e8e15e507eecad86465923/src/vpnchooser/resources/user.py#L83-L91
249,719
cbrand/vpnchooser
src/vpnchooser/resources/user.py
UserResource.put
def put(self, user_name: str) -> User: """ Updates the User Resource with the name. """ current = current_user() if current.name == user_name or current.is_admin: user = self._get_or_abort(user_name) self.update(user) session.commit() session.add(user) return user else: abort(403)
python
def put(self, user_name: str) -> User: """ Updates the User Resource with the name. """ current = current_user() if current.name == user_name or current.is_admin: user = self._get_or_abort(user_name) self.update(user) session.commit() session.add(user) return user else: abort(403)
[ "def", "put", "(", "self", ",", "user_name", ":", "str", ")", "->", "User", ":", "current", "=", "current_user", "(", ")", "if", "current", ".", "name", "==", "user_name", "or", "current", ".", "is_admin", ":", "user", "=", "self", ".", "_get_or_abort", "(", "user_name", ")", "self", ".", "update", "(", "user", ")", "session", ".", "commit", "(", ")", "session", ".", "add", "(", "user", ")", "return", "user", "else", ":", "abort", "(", "403", ")" ]
Updates the User Resource with the name.
[ "Updates", "the", "User", "Resource", "with", "the", "name", "." ]
d153e3d05555c23cf5e8e15e507eecad86465923
https://github.com/cbrand/vpnchooser/blob/d153e3d05555c23cf5e8e15e507eecad86465923/src/vpnchooser/resources/user.py#L95-L108
249,720
diefans/objective
src/objective/core.py
Field._resolve_value
def _resolve_value(self, value, environment=None): """Resolve the value. Either apply missing or leave the value as is. :param value: the value either from deserialize or serialize :param environment: an optional environment """ # here we care about Undefined values if value == values.Undefined: if isinstance(self._missing, type) and issubclass(self._missing, Missing): # instantiate the missing thing missing = self._missing(self, environment) # invoke missing callback # the default is to raise a MissingValue() exception value = missing(value) elif hasattr(self._missing, "__call__"): value = self._missing() else: # we just assign any value value = self._missing return value
python
def _resolve_value(self, value, environment=None): """Resolve the value. Either apply missing or leave the value as is. :param value: the value either from deserialize or serialize :param environment: an optional environment """ # here we care about Undefined values if value == values.Undefined: if isinstance(self._missing, type) and issubclass(self._missing, Missing): # instantiate the missing thing missing = self._missing(self, environment) # invoke missing callback # the default is to raise a MissingValue() exception value = missing(value) elif hasattr(self._missing, "__call__"): value = self._missing() else: # we just assign any value value = self._missing return value
[ "def", "_resolve_value", "(", "self", ",", "value", ",", "environment", "=", "None", ")", ":", "# here we care about Undefined values", "if", "value", "==", "values", ".", "Undefined", ":", "if", "isinstance", "(", "self", ".", "_missing", ",", "type", ")", "and", "issubclass", "(", "self", ".", "_missing", ",", "Missing", ")", ":", "# instantiate the missing thing", "missing", "=", "self", ".", "_missing", "(", "self", ",", "environment", ")", "# invoke missing callback", "# the default is to raise a MissingValue() exception", "value", "=", "missing", "(", "value", ")", "elif", "hasattr", "(", "self", ".", "_missing", ",", "\"__call__\"", ")", ":", "value", "=", "self", ".", "_missing", "(", ")", "else", ":", "# we just assign any value", "value", "=", "self", ".", "_missing", "return", "value" ]
Resolve the value. Either apply missing or leave the value as is. :param value: the value either from deserialize or serialize :param environment: an optional environment
[ "Resolve", "the", "value", "." ]
e2de37f1cd4f5ad147ab3a5dee7dffd6806f2f88
https://github.com/diefans/objective/blob/e2de37f1cd4f5ad147ab3a5dee7dffd6806f2f88/src/objective/core.py#L283-L309
249,721
diefans/objective
src/objective/core.py
Field.serialize
def serialize(self, value, environment=None): """Serialze a value into a transportable and interchangeable format. The default assumption is that the value is JSON e.g. string or number. Some encoders also support datetime by default. Serialization should not be validated, since the developer app would be bounced, since the mistake comes from there - use unittests for this! """ value = self._resolve_value(value, environment) value = self._serialize(value, environment) return value
python
def serialize(self, value, environment=None): """Serialze a value into a transportable and interchangeable format. The default assumption is that the value is JSON e.g. string or number. Some encoders also support datetime by default. Serialization should not be validated, since the developer app would be bounced, since the mistake comes from there - use unittests for this! """ value = self._resolve_value(value, environment) value = self._serialize(value, environment) return value
[ "def", "serialize", "(", "self", ",", "value", ",", "environment", "=", "None", ")", ":", "value", "=", "self", ".", "_resolve_value", "(", "value", ",", "environment", ")", "value", "=", "self", ".", "_serialize", "(", "value", ",", "environment", ")", "return", "value" ]
Serialze a value into a transportable and interchangeable format. The default assumption is that the value is JSON e.g. string or number. Some encoders also support datetime by default. Serialization should not be validated, since the developer app would be bounced, since the mistake comes from there - use unittests for this!
[ "Serialze", "a", "value", "into", "a", "transportable", "and", "interchangeable", "format", "." ]
e2de37f1cd4f5ad147ab3a5dee7dffd6806f2f88
https://github.com/diefans/objective/blob/e2de37f1cd4f5ad147ab3a5dee7dffd6806f2f88/src/objective/core.py#L316-L330
249,722
diefans/objective
src/objective/core.py
Field.deserialize
def deserialize(self, value, environment=None): """Deserialize a value into a special application specific format or type. `value` can be `Missing`, `None` or something else. :param value: the value to be deserialized :param environment: additional environment """ value = self._resolve_value(value, environment) try: value = self._deserialize(value, environment) if self._validator is not None: value = self._validator(self, value, environment) # pylint: disable=E1102 except exc.InvalidValue as ex: # just reraise raise except (exc.Invalid, ValueError, TypeError) as ex: # we convert a bare Invalid into InvalidValue raise exc.InvalidValue(self, value=value, origin=ex) return value
python
def deserialize(self, value, environment=None): """Deserialize a value into a special application specific format or type. `value` can be `Missing`, `None` or something else. :param value: the value to be deserialized :param environment: additional environment """ value = self._resolve_value(value, environment) try: value = self._deserialize(value, environment) if self._validator is not None: value = self._validator(self, value, environment) # pylint: disable=E1102 except exc.InvalidValue as ex: # just reraise raise except (exc.Invalid, ValueError, TypeError) as ex: # we convert a bare Invalid into InvalidValue raise exc.InvalidValue(self, value=value, origin=ex) return value
[ "def", "deserialize", "(", "self", ",", "value", ",", "environment", "=", "None", ")", ":", "value", "=", "self", ".", "_resolve_value", "(", "value", ",", "environment", ")", "try", ":", "value", "=", "self", ".", "_deserialize", "(", "value", ",", "environment", ")", "if", "self", ".", "_validator", "is", "not", "None", ":", "value", "=", "self", ".", "_validator", "(", "self", ",", "value", ",", "environment", ")", "# pylint: disable=E1102", "except", "exc", ".", "InvalidValue", "as", "ex", ":", "# just reraise", "raise", "except", "(", "exc", ".", "Invalid", ",", "ValueError", ",", "TypeError", ")", "as", "ex", ":", "# we convert a bare Invalid into InvalidValue", "raise", "exc", ".", "InvalidValue", "(", "self", ",", "value", "=", "value", ",", "origin", "=", "ex", ")", "return", "value" ]
Deserialize a value into a special application specific format or type. `value` can be `Missing`, `None` or something else. :param value: the value to be deserialized :param environment: additional environment
[ "Deserialize", "a", "value", "into", "a", "special", "application", "specific", "format", "or", "type", "." ]
e2de37f1cd4f5ad147ab3a5dee7dffd6806f2f88
https://github.com/diefans/objective/blob/e2de37f1cd4f5ad147ab3a5dee7dffd6806f2f88/src/objective/core.py#L337-L362
249,723
necrolyte2/filehandle
filehandle.py
open
def open(filepath, mode='rb', buffcompress=None): ''' Open a file based on the extension of the file if the filepath ends in .gz then use gzip module's open otherwise use the normal builtin open :param str filepath: Path to .gz or any other file :param str mode: mode to open file :param int buffcompress: 3rd option for builtin.open or gzip.open :return: tuple(filehandle, fileextension) ''' root, ext = splitext(filepath.replace('.gz', '')) # get rid of period ext = ext[1:] if filepath.endswith('.gz'): compress = buffcompress if compress is None: compress = 9 handle = gzip.open(filepath, mode, compress) else: buffer = buffcompress if buffer is None: buffer = -1 handle = builtins.open(filepath, mode, buffer) return (handle, ext)
python
def open(filepath, mode='rb', buffcompress=None): ''' Open a file based on the extension of the file if the filepath ends in .gz then use gzip module's open otherwise use the normal builtin open :param str filepath: Path to .gz or any other file :param str mode: mode to open file :param int buffcompress: 3rd option for builtin.open or gzip.open :return: tuple(filehandle, fileextension) ''' root, ext = splitext(filepath.replace('.gz', '')) # get rid of period ext = ext[1:] if filepath.endswith('.gz'): compress = buffcompress if compress is None: compress = 9 handle = gzip.open(filepath, mode, compress) else: buffer = buffcompress if buffer is None: buffer = -1 handle = builtins.open(filepath, mode, buffer) return (handle, ext)
[ "def", "open", "(", "filepath", ",", "mode", "=", "'rb'", ",", "buffcompress", "=", "None", ")", ":", "root", ",", "ext", "=", "splitext", "(", "filepath", ".", "replace", "(", "'.gz'", ",", "''", ")", ")", "# get rid of period", "ext", "=", "ext", "[", "1", ":", "]", "if", "filepath", ".", "endswith", "(", "'.gz'", ")", ":", "compress", "=", "buffcompress", "if", "compress", "is", "None", ":", "compress", "=", "9", "handle", "=", "gzip", ".", "open", "(", "filepath", ",", "mode", ",", "compress", ")", "else", ":", "buffer", "=", "buffcompress", "if", "buffer", "is", "None", ":", "buffer", "=", "-", "1", "handle", "=", "builtins", ".", "open", "(", "filepath", ",", "mode", ",", "buffer", ")", "return", "(", "handle", ",", "ext", ")" ]
Open a file based on the extension of the file if the filepath ends in .gz then use gzip module's open otherwise use the normal builtin open :param str filepath: Path to .gz or any other file :param str mode: mode to open file :param int buffcompress: 3rd option for builtin.open or gzip.open :return: tuple(filehandle, fileextension)
[ "Open", "a", "file", "based", "on", "the", "extension", "of", "the", "file", "if", "the", "filepath", "ends", "in", ".", "gz", "then", "use", "gzip", "module", "s", "open", "otherwise", "use", "the", "normal", "builtin", "open" ]
48218ffae1915c28f26ff270400f29ee8e379ca9
https://github.com/necrolyte2/filehandle/blob/48218ffae1915c28f26ff270400f29ee8e379ca9/filehandle.py#L11-L35
249,724
cdumay/cdumay-result
src/cdumay_result/__init__.py
Result.from_exception
def from_exception(exc, uuid=None): """ Serialize an exception into a result :param Exception exc: Exception raised :param str uuid: Current Kafka :class:`kser.transport.Message` uuid :rtype: :class:`kser.result.Result` """ if not isinstance(exc, Error): exc = Error(code=500, message=str(exc)) return Result( uuid=exc.extra.get("uuid", uuid or random_uuid()), retcode=exc.code, stderr=exc.message, retval=dict(error=ErrorSchema().dump(exc)) )
python
def from_exception(exc, uuid=None): """ Serialize an exception into a result :param Exception exc: Exception raised :param str uuid: Current Kafka :class:`kser.transport.Message` uuid :rtype: :class:`kser.result.Result` """ if not isinstance(exc, Error): exc = Error(code=500, message=str(exc)) return Result( uuid=exc.extra.get("uuid", uuid or random_uuid()), retcode=exc.code, stderr=exc.message, retval=dict(error=ErrorSchema().dump(exc)) )
[ "def", "from_exception", "(", "exc", ",", "uuid", "=", "None", ")", ":", "if", "not", "isinstance", "(", "exc", ",", "Error", ")", ":", "exc", "=", "Error", "(", "code", "=", "500", ",", "message", "=", "str", "(", "exc", ")", ")", "return", "Result", "(", "uuid", "=", "exc", ".", "extra", ".", "get", "(", "\"uuid\"", ",", "uuid", "or", "random_uuid", "(", ")", ")", ",", "retcode", "=", "exc", ".", "code", ",", "stderr", "=", "exc", ".", "message", ",", "retval", "=", "dict", "(", "error", "=", "ErrorSchema", "(", ")", ".", "dump", "(", "exc", ")", ")", ")" ]
Serialize an exception into a result :param Exception exc: Exception raised :param str uuid: Current Kafka :class:`kser.transport.Message` uuid :rtype: :class:`kser.result.Result`
[ "Serialize", "an", "exception", "into", "a", "result" ]
b6db33813025641620fa1a3b19809a0ccb7c6dd2
https://github.com/cdumay/cdumay-result/blob/b6db33813025641620fa1a3b19809a0ccb7c6dd2/src/cdumay_result/__init__.py#L51-L65
249,725
cdumay/cdumay-result
src/cdumay_result/__init__.py
Result.search_value
def search_value(self, xpath, default=None, single_value=True): """ Try to find a value in the result :param str xpath: a xpath filter see https://github.com/kennknowles/python-jsonpath-rw#jsonpath-syntax :param any default: default value if not found :param bool single_value: is the result is multivalued :return: the value found or None """ matches = [match.value for match in parse(xpath).find(self.retval)] if len(matches) == 0: return default return matches[0] if single_value is True else matches
python
def search_value(self, xpath, default=None, single_value=True): """ Try to find a value in the result :param str xpath: a xpath filter see https://github.com/kennknowles/python-jsonpath-rw#jsonpath-syntax :param any default: default value if not found :param bool single_value: is the result is multivalued :return: the value found or None """ matches = [match.value for match in parse(xpath).find(self.retval)] if len(matches) == 0: return default return matches[0] if single_value is True else matches
[ "def", "search_value", "(", "self", ",", "xpath", ",", "default", "=", "None", ",", "single_value", "=", "True", ")", ":", "matches", "=", "[", "match", ".", "value", "for", "match", "in", "parse", "(", "xpath", ")", ".", "find", "(", "self", ".", "retval", ")", "]", "if", "len", "(", "matches", ")", "==", "0", ":", "return", "default", "return", "matches", "[", "0", "]", "if", "single_value", "is", "True", "else", "matches" ]
Try to find a value in the result :param str xpath: a xpath filter see https://github.com/kennknowles/python-jsonpath-rw#jsonpath-syntax :param any default: default value if not found :param bool single_value: is the result is multivalued :return: the value found or None
[ "Try", "to", "find", "a", "value", "in", "the", "result" ]
b6db33813025641620fa1a3b19809a0ccb7c6dd2
https://github.com/cdumay/cdumay-result/blob/b6db33813025641620fa1a3b19809a0ccb7c6dd2/src/cdumay_result/__init__.py#L67-L78
249,726
jeff-regier/authortoolkit
authortoolkit/utils.py
compatible_names
def compatible_names(e1, e2): """This function takes either PartitionParts or Mentions as arguments """ if e1.ln() != e2.ln(): return False short, long = list(e1.mns()), e2.mns() if len(short) > len(long): return compatible_names(e2, e1) # the front first names must be compatible if not compatible_name_part(e1.fn(), e2.fn()): return False # try finding each middle name of long in short, and remove the # middle name from short if found for wl in long: if not short: break ws = short.pop(0) if not compatible_name_part(ws, wl): short.insert(0, ws) # true iff short is a compatible substring of long return short == []
python
def compatible_names(e1, e2): """This function takes either PartitionParts or Mentions as arguments """ if e1.ln() != e2.ln(): return False short, long = list(e1.mns()), e2.mns() if len(short) > len(long): return compatible_names(e2, e1) # the front first names must be compatible if not compatible_name_part(e1.fn(), e2.fn()): return False # try finding each middle name of long in short, and remove the # middle name from short if found for wl in long: if not short: break ws = short.pop(0) if not compatible_name_part(ws, wl): short.insert(0, ws) # true iff short is a compatible substring of long return short == []
[ "def", "compatible_names", "(", "e1", ",", "e2", ")", ":", "if", "e1", ".", "ln", "(", ")", "!=", "e2", ".", "ln", "(", ")", ":", "return", "False", "short", ",", "long", "=", "list", "(", "e1", ".", "mns", "(", ")", ")", ",", "e2", ".", "mns", "(", ")", "if", "len", "(", "short", ")", ">", "len", "(", "long", ")", ":", "return", "compatible_names", "(", "e2", ",", "e1", ")", "# the front first names must be compatible", "if", "not", "compatible_name_part", "(", "e1", ".", "fn", "(", ")", ",", "e2", ".", "fn", "(", ")", ")", ":", "return", "False", "# try finding each middle name of long in short, and remove the", "# middle name from short if found", "for", "wl", "in", "long", ":", "if", "not", "short", ":", "break", "ws", "=", "short", ".", "pop", "(", "0", ")", "if", "not", "compatible_name_part", "(", "ws", ",", "wl", ")", ":", "short", ".", "insert", "(", "0", ",", "ws", ")", "# true iff short is a compatible substring of long", "return", "short", "==", "[", "]" ]
This function takes either PartitionParts or Mentions as arguments
[ "This", "function", "takes", "either", "PartitionParts", "or", "Mentions", "as", "arguments" ]
b119a953d46b2e23ad346927a0fb5c5047f28b9b
https://github.com/jeff-regier/authortoolkit/blob/b119a953d46b2e23ad346927a0fb5c5047f28b9b/authortoolkit/utils.py#L17-L42
249,727
clearclaw/qeventlog
qeventlog/tasks.py
sentry_exception
def sentry_exception (e, request, message = None): """Yes, this eats exceptions""" try: logtool.log_fault (e, message = message, level = logging.INFO) data = { "task": task, "request": { "args": task.request.args, "callbacks": task.request.callbacks, "called_directly": task.request.called_directly, "correlation_id": task.request.correlation_id, "delivery_info": task.request.delivery_info, "errbacks": task.request.errbacks, "eta": task.request.eta, "expires": task.request.expires, "headers": task.request.headers, "hostname": task.request.hostname, "id": task.request.id, "is_eager": task.request.is_eager, "kwargs": task.request.kwargs, "origin": task.request.origin, "parent_id": task.request.parent_id, "reply_to": task.request.reply_to, "retries": task.request.retries, "root_id": task.request.root_id, "task": task.request.task, "taskset": task.request.taskset, "timelimit": task.request.timelimit, "utc": task.request.utc, }, } if message: data["message"] = message SENTRY.extra_context (data) einfo = sys.exc_info () rc = SENTRY.captureException (einfo) del einfo LOG.error ("Sentry filed: %s", rc) except Exception as ee: logtool.log_fault (ee, message = "FAULT: Problem logging exception.", level = logging.INFO)
python
def sentry_exception (e, request, message = None): """Yes, this eats exceptions""" try: logtool.log_fault (e, message = message, level = logging.INFO) data = { "task": task, "request": { "args": task.request.args, "callbacks": task.request.callbacks, "called_directly": task.request.called_directly, "correlation_id": task.request.correlation_id, "delivery_info": task.request.delivery_info, "errbacks": task.request.errbacks, "eta": task.request.eta, "expires": task.request.expires, "headers": task.request.headers, "hostname": task.request.hostname, "id": task.request.id, "is_eager": task.request.is_eager, "kwargs": task.request.kwargs, "origin": task.request.origin, "parent_id": task.request.parent_id, "reply_to": task.request.reply_to, "retries": task.request.retries, "root_id": task.request.root_id, "task": task.request.task, "taskset": task.request.taskset, "timelimit": task.request.timelimit, "utc": task.request.utc, }, } if message: data["message"] = message SENTRY.extra_context (data) einfo = sys.exc_info () rc = SENTRY.captureException (einfo) del einfo LOG.error ("Sentry filed: %s", rc) except Exception as ee: logtool.log_fault (ee, message = "FAULT: Problem logging exception.", level = logging.INFO)
[ "def", "sentry_exception", "(", "e", ",", "request", ",", "message", "=", "None", ")", ":", "try", ":", "logtool", ".", "log_fault", "(", "e", ",", "message", "=", "message", ",", "level", "=", "logging", ".", "INFO", ")", "data", "=", "{", "\"task\"", ":", "task", ",", "\"request\"", ":", "{", "\"args\"", ":", "task", ".", "request", ".", "args", ",", "\"callbacks\"", ":", "task", ".", "request", ".", "callbacks", ",", "\"called_directly\"", ":", "task", ".", "request", ".", "called_directly", ",", "\"correlation_id\"", ":", "task", ".", "request", ".", "correlation_id", ",", "\"delivery_info\"", ":", "task", ".", "request", ".", "delivery_info", ",", "\"errbacks\"", ":", "task", ".", "request", ".", "errbacks", ",", "\"eta\"", ":", "task", ".", "request", ".", "eta", ",", "\"expires\"", ":", "task", ".", "request", ".", "expires", ",", "\"headers\"", ":", "task", ".", "request", ".", "headers", ",", "\"hostname\"", ":", "task", ".", "request", ".", "hostname", ",", "\"id\"", ":", "task", ".", "request", ".", "id", ",", "\"is_eager\"", ":", "task", ".", "request", ".", "is_eager", ",", "\"kwargs\"", ":", "task", ".", "request", ".", "kwargs", ",", "\"origin\"", ":", "task", ".", "request", ".", "origin", ",", "\"parent_id\"", ":", "task", ".", "request", ".", "parent_id", ",", "\"reply_to\"", ":", "task", ".", "request", ".", "reply_to", ",", "\"retries\"", ":", "task", ".", "request", ".", "retries", ",", "\"root_id\"", ":", "task", ".", "request", ".", "root_id", ",", "\"task\"", ":", "task", ".", "request", ".", "task", ",", "\"taskset\"", ":", "task", ".", "request", ".", "taskset", ",", "\"timelimit\"", ":", "task", ".", "request", ".", "timelimit", ",", "\"utc\"", ":", "task", ".", "request", ".", "utc", ",", "}", ",", "}", "if", "message", ":", "data", "[", "\"message\"", "]", "=", "message", "SENTRY", ".", "extra_context", "(", "data", ")", "einfo", "=", "sys", ".", "exc_info", "(", ")", "rc", "=", "SENTRY", ".", "captureException", "(", "einfo", ")", "del", "einfo", "LOG", ".", "error", "(", "\"Sentry filed: %s\"", ",", "rc", ")", "except", "Exception", "as", "ee", ":", "logtool", ".", "log_fault", "(", "ee", ",", "message", "=", "\"FAULT: Problem logging exception.\"", ",", "level", "=", "logging", ".", "INFO", ")" ]
Yes, this eats exceptions
[ "Yes", "this", "eats", "exceptions" ]
bcd6184a9df0c91c0a881a3ae594bcdbf08b2ca8
https://github.com/clearclaw/qeventlog/blob/bcd6184a9df0c91c0a881a3ae594bcdbf08b2ca8/qeventlog/tasks.py#L20-L60
249,728
Othernet-Project/hwd
hwd/wrapper.py
Wrapper._get_first
def _get_first(self, keys, default=None): """ For given keys, return value for first key that isn't ``None``. If such a key is not found, ``default`` is returned. """ d = self.device for k in keys: v = d.get(k) if not v is None: return v return default
python
def _get_first(self, keys, default=None): """ For given keys, return value for first key that isn't ``None``. If such a key is not found, ``default`` is returned. """ d = self.device for k in keys: v = d.get(k) if not v is None: return v return default
[ "def", "_get_first", "(", "self", ",", "keys", ",", "default", "=", "None", ")", ":", "d", "=", "self", ".", "device", "for", "k", "in", "keys", ":", "v", "=", "d", ".", "get", "(", "k", ")", "if", "not", "v", "is", "None", ":", "return", "v", "return", "default" ]
For given keys, return value for first key that isn't ``None``. If such a key is not found, ``default`` is returned.
[ "For", "given", "keys", "return", "value", "for", "first", "key", "that", "isn", "t", "None", ".", "If", "such", "a", "key", "is", "not", "found", "default", "is", "returned", "." ]
7f4445bac61aa2305806aa80338e2ce5baa1093c
https://github.com/Othernet-Project/hwd/blob/7f4445bac61aa2305806aa80338e2ce5baa1093c/hwd/wrapper.py#L118-L128
249,729
darkfeline/mir.sqlite3m
mir/sqlite3m/__init__.py
CheckForeignKeysWrapper
def CheckForeignKeysWrapper(conn): """Migration wrapper that checks foreign keys. Note that this may raise different exceptions depending on the underlying database API. """ yield cur = conn.cursor() cur.execute('PRAGMA foreign_key_check') errors = cur.fetchall() if errors: raise ForeignKeyError(errors)
python
def CheckForeignKeysWrapper(conn): """Migration wrapper that checks foreign keys. Note that this may raise different exceptions depending on the underlying database API. """ yield cur = conn.cursor() cur.execute('PRAGMA foreign_key_check') errors = cur.fetchall() if errors: raise ForeignKeyError(errors)
[ "def", "CheckForeignKeysWrapper", "(", "conn", ")", ":", "yield", "cur", "=", "conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "'PRAGMA foreign_key_check'", ")", "errors", "=", "cur", ".", "fetchall", "(", ")", "if", "errors", ":", "raise", "ForeignKeyError", "(", "errors", ")" ]
Migration wrapper that checks foreign keys. Note that this may raise different exceptions depending on the underlying database API.
[ "Migration", "wrapper", "that", "checks", "foreign", "keys", "." ]
9080c3347c8f0f59ec6117f33ba9ad07c6ca0afc
https://github.com/darkfeline/mir.sqlite3m/blob/9080c3347c8f0f59ec6117f33ba9ad07c6ca0afc/mir/sqlite3m/__init__.py#L157-L168
249,730
darkfeline/mir.sqlite3m
mir/sqlite3m/__init__.py
MigrationManager.register_migration
def register_migration(self, migration: 'Migration'): """Register a migration. You can only register migrations in order. For example, you can register migrations from version 1 to 2, then 2 to 3, then 3 to 4. You cannot register 1 to 2 followed by 3 to 4. """ if migration.from_ver >= migration.to_ver: raise ValueError('Migration cannot downgrade verson') if migration.from_ver != self._final_ver: raise ValueError('Cannot register disjoint migration') self._migrations[migration.from_ver] = migration self._final_ver = migration.to_ver
python
def register_migration(self, migration: 'Migration'): """Register a migration. You can only register migrations in order. For example, you can register migrations from version 1 to 2, then 2 to 3, then 3 to 4. You cannot register 1 to 2 followed by 3 to 4. """ if migration.from_ver >= migration.to_ver: raise ValueError('Migration cannot downgrade verson') if migration.from_ver != self._final_ver: raise ValueError('Cannot register disjoint migration') self._migrations[migration.from_ver] = migration self._final_ver = migration.to_ver
[ "def", "register_migration", "(", "self", ",", "migration", ":", "'Migration'", ")", ":", "if", "migration", ".", "from_ver", ">=", "migration", ".", "to_ver", ":", "raise", "ValueError", "(", "'Migration cannot downgrade verson'", ")", "if", "migration", ".", "from_ver", "!=", "self", ".", "_final_ver", ":", "raise", "ValueError", "(", "'Cannot register disjoint migration'", ")", "self", ".", "_migrations", "[", "migration", ".", "from_ver", "]", "=", "migration", "self", ".", "_final_ver", "=", "migration", ".", "to_ver" ]
Register a migration. You can only register migrations in order. For example, you can register migrations from version 1 to 2, then 2 to 3, then 3 to 4. You cannot register 1 to 2 followed by 3 to 4.
[ "Register", "a", "migration", "." ]
9080c3347c8f0f59ec6117f33ba9ad07c6ca0afc
https://github.com/darkfeline/mir.sqlite3m/blob/9080c3347c8f0f59ec6117f33ba9ad07c6ca0afc/mir/sqlite3m/__init__.py#L56-L68
249,731
darkfeline/mir.sqlite3m
mir/sqlite3m/__init__.py
MigrationManager.migration
def migration(self, from_ver: int, to_ver: int): """Decorator to create and register a migration. >>> manager = MigrationManager() >>> @manager.migration(0, 1) ... def migrate(conn): ... pass """ def decorator(func): migration = Migration(from_ver, to_ver, func) self.register_migration(migration) return func return decorator
python
def migration(self, from_ver: int, to_ver: int): """Decorator to create and register a migration. >>> manager = MigrationManager() >>> @manager.migration(0, 1) ... def migrate(conn): ... pass """ def decorator(func): migration = Migration(from_ver, to_ver, func) self.register_migration(migration) return func return decorator
[ "def", "migration", "(", "self", ",", "from_ver", ":", "int", ",", "to_ver", ":", "int", ")", ":", "def", "decorator", "(", "func", ")", ":", "migration", "=", "Migration", "(", "from_ver", ",", "to_ver", ",", "func", ")", "self", ".", "register_migration", "(", "migration", ")", "return", "func", "return", "decorator" ]
Decorator to create and register a migration. >>> manager = MigrationManager() >>> @manager.migration(0, 1) ... def migrate(conn): ... pass
[ "Decorator", "to", "create", "and", "register", "a", "migration", "." ]
9080c3347c8f0f59ec6117f33ba9ad07c6ca0afc
https://github.com/darkfeline/mir.sqlite3m/blob/9080c3347c8f0f59ec6117f33ba9ad07c6ca0afc/mir/sqlite3m/__init__.py#L70-L82
249,732
darkfeline/mir.sqlite3m
mir/sqlite3m/__init__.py
MigrationManager.migrate
def migrate(self, conn): """Migrate a database as needed. This method is safe to call on an up-to-date database, on an old database, on a newer database, or an uninitialized database (version 0). This method is idempotent. """ while self.should_migrate(conn): current_version = get_user_version(conn) migration = self._get_migration(current_version) assert migration.from_ver == current_version logger.info(f'Migrating database from {migration.from_ver}' f' to {migration.to_ver}') self._migrate_single(conn, migration) set_user_version(conn, migration.to_ver) logger.info(f'Migrated database to {migration.to_ver}')
python
def migrate(self, conn): """Migrate a database as needed. This method is safe to call on an up-to-date database, on an old database, on a newer database, or an uninitialized database (version 0). This method is idempotent. """ while self.should_migrate(conn): current_version = get_user_version(conn) migration = self._get_migration(current_version) assert migration.from_ver == current_version logger.info(f'Migrating database from {migration.from_ver}' f' to {migration.to_ver}') self._migrate_single(conn, migration) set_user_version(conn, migration.to_ver) logger.info(f'Migrated database to {migration.to_ver}')
[ "def", "migrate", "(", "self", ",", "conn", ")", ":", "while", "self", ".", "should_migrate", "(", "conn", ")", ":", "current_version", "=", "get_user_version", "(", "conn", ")", "migration", "=", "self", ".", "_get_migration", "(", "current_version", ")", "assert", "migration", ".", "from_ver", "==", "current_version", "logger", ".", "info", "(", "f'Migrating database from {migration.from_ver}'", "f' to {migration.to_ver}'", ")", "self", ".", "_migrate_single", "(", "conn", ",", "migration", ")", "set_user_version", "(", "conn", ",", "migration", ".", "to_ver", ")", "logger", ".", "info", "(", "f'Migrated database to {migration.to_ver}'", ")" ]
Migrate a database as needed. This method is safe to call on an up-to-date database, on an old database, on a newer database, or an uninitialized database (version 0). This method is idempotent.
[ "Migrate", "a", "database", "as", "needed", "." ]
9080c3347c8f0f59ec6117f33ba9ad07c6ca0afc
https://github.com/darkfeline/mir.sqlite3m/blob/9080c3347c8f0f59ec6117f33ba9ad07c6ca0afc/mir/sqlite3m/__init__.py#L92-L109
249,733
darkfeline/mir.sqlite3m
mir/sqlite3m/__init__.py
MigrationManager._migrate_single
def _migrate_single(self, conn, migration): """Perform a single migration starting from the given version.""" with contextlib.ExitStack() as stack: for wrapper in self._wrappers: stack.enter_context(wrapper(conn)) migration.func(conn)
python
def _migrate_single(self, conn, migration): """Perform a single migration starting from the given version.""" with contextlib.ExitStack() as stack: for wrapper in self._wrappers: stack.enter_context(wrapper(conn)) migration.func(conn)
[ "def", "_migrate_single", "(", "self", ",", "conn", ",", "migration", ")", ":", "with", "contextlib", ".", "ExitStack", "(", ")", "as", "stack", ":", "for", "wrapper", "in", "self", ".", "_wrappers", ":", "stack", ".", "enter_context", "(", "wrapper", "(", "conn", ")", ")", "migration", ".", "func", "(", "conn", ")" ]
Perform a single migration starting from the given version.
[ "Perform", "a", "single", "migration", "starting", "from", "the", "given", "version", "." ]
9080c3347c8f0f59ec6117f33ba9ad07c6ca0afc
https://github.com/darkfeline/mir.sqlite3m/blob/9080c3347c8f0f59ec6117f33ba9ad07c6ca0afc/mir/sqlite3m/__init__.py#L115-L120
249,734
dr4ke616/pinky
twisted/plugins/broker.py
BrokerServiceMaker.makeService
def makeService(self, options): """ Construct a Broker Server """ return BrokerService( port=options['port'], debug=options['debug'], activate_ssh_server=options['activate-ssh-server'], ssh_user=options['ssh-user'], ssh_password=options['ssh-password'], ssh_port=options['ssh-port'] )
python
def makeService(self, options): """ Construct a Broker Server """ return BrokerService( port=options['port'], debug=options['debug'], activate_ssh_server=options['activate-ssh-server'], ssh_user=options['ssh-user'], ssh_password=options['ssh-password'], ssh_port=options['ssh-port'] )
[ "def", "makeService", "(", "self", ",", "options", ")", ":", "return", "BrokerService", "(", "port", "=", "options", "[", "'port'", "]", ",", "debug", "=", "options", "[", "'debug'", "]", ",", "activate_ssh_server", "=", "options", "[", "'activate-ssh-server'", "]", ",", "ssh_user", "=", "options", "[", "'ssh-user'", "]", ",", "ssh_password", "=", "options", "[", "'ssh-password'", "]", ",", "ssh_port", "=", "options", "[", "'ssh-port'", "]", ")" ]
Construct a Broker Server
[ "Construct", "a", "Broker", "Server" ]
35c165f5a1d410be467621f3152df1dbf458622a
https://github.com/dr4ke616/pinky/blob/35c165f5a1d410be467621f3152df1dbf458622a/twisted/plugins/broker.py#L31-L41
249,735
jroyal/pyIDS
pyIDS/ids.py
IDS.get_work_item_by_id
def get_work_item_by_id(self, wi_id): ''' Retrieves a single work item based off of the supplied ID :param wi_id: The work item ID number :return: Workitem or None ''' work_items = self.get_work_items(id=wi_id) if work_items is not None: return work_items[0] return None
python
def get_work_item_by_id(self, wi_id): ''' Retrieves a single work item based off of the supplied ID :param wi_id: The work item ID number :return: Workitem or None ''' work_items = self.get_work_items(id=wi_id) if work_items is not None: return work_items[0] return None
[ "def", "get_work_item_by_id", "(", "self", ",", "wi_id", ")", ":", "work_items", "=", "self", ".", "get_work_items", "(", "id", "=", "wi_id", ")", "if", "work_items", "is", "not", "None", ":", "return", "work_items", "[", "0", "]", "return", "None" ]
Retrieves a single work item based off of the supplied ID :param wi_id: The work item ID number :return: Workitem or None
[ "Retrieves", "a", "single", "work", "item", "based", "off", "of", "the", "supplied", "ID" ]
3c2d3ff4bdc7bfe116dfd02152dadd26f92f74b5
https://github.com/jroyal/pyIDS/blob/3c2d3ff4bdc7bfe116dfd02152dadd26f92f74b5/pyIDS/ids.py#L82-L92
249,736
mikejarrett/pipcheck
pipcheck/clients.py
PyPIClient.package_releases
def package_releases(self, project_name): """ Retrieve the versions from PyPI by ``project_name``. Args: project_name (str): The name of the project we wish to retrieve the versions of. Returns: list: Of string versions. """ try: return self._connection.package_releases(project_name) except Exception as err: raise PyPIClientError(err)
python
def package_releases(self, project_name): """ Retrieve the versions from PyPI by ``project_name``. Args: project_name (str): The name of the project we wish to retrieve the versions of. Returns: list: Of string versions. """ try: return self._connection.package_releases(project_name) except Exception as err: raise PyPIClientError(err)
[ "def", "package_releases", "(", "self", ",", "project_name", ")", ":", "try", ":", "return", "self", ".", "_connection", ".", "package_releases", "(", "project_name", ")", "except", "Exception", "as", "err", ":", "raise", "PyPIClientError", "(", "err", ")" ]
Retrieve the versions from PyPI by ``project_name``. Args: project_name (str): The name of the project we wish to retrieve the versions of. Returns: list: Of string versions.
[ "Retrieve", "the", "versions", "from", "PyPI", "by", "project_name", "." ]
2ff47b9fd8914e1764c6e659ef39b77c1b1a12ad
https://github.com/mikejarrett/pipcheck/blob/2ff47b9fd8914e1764c6e659ef39b77c1b1a12ad/pipcheck/clients.py#L17-L30
249,737
mikejarrett/pipcheck
pipcheck/clients.py
PyPIClientPureMemory.set_package_releases
def set_package_releases(self, project_name, versions): """ Storage package information in ``self.packages`` Args: project_name (str): This will be used as a the key in the dictionary. versions (list): List of ``str`` representing the available versions of a project. """ self.packages[project_name] = sorted(versions, reverse=True)
python
def set_package_releases(self, project_name, versions): """ Storage package information in ``self.packages`` Args: project_name (str): This will be used as a the key in the dictionary. versions (list): List of ``str`` representing the available versions of a project. """ self.packages[project_name] = sorted(versions, reverse=True)
[ "def", "set_package_releases", "(", "self", ",", "project_name", ",", "versions", ")", ":", "self", ".", "packages", "[", "project_name", "]", "=", "sorted", "(", "versions", ",", "reverse", "=", "True", ")" ]
Storage package information in ``self.packages`` Args: project_name (str): This will be used as a the key in the dictionary. versions (list): List of ``str`` representing the available versions of a project.
[ "Storage", "package", "information", "in", "self", ".", "packages" ]
2ff47b9fd8914e1764c6e659ef39b77c1b1a12ad
https://github.com/mikejarrett/pipcheck/blob/2ff47b9fd8914e1764c6e659ef39b77c1b1a12ad/pipcheck/clients.py#L60-L69
249,738
zerc/django-vest
django_vest/utils.py
load_object
def load_object(s): """ Load backend by dotted path. """ try: m_path, o_name = s.rsplit('.', 1) except ValueError: raise ImportError('Cant import backend from path: {}'.format(s)) module = import_module(m_path) return getattr(module, o_name)
python
def load_object(s): """ Load backend by dotted path. """ try: m_path, o_name = s.rsplit('.', 1) except ValueError: raise ImportError('Cant import backend from path: {}'.format(s)) module = import_module(m_path) return getattr(module, o_name)
[ "def", "load_object", "(", "s", ")", ":", "try", ":", "m_path", ",", "o_name", "=", "s", ".", "rsplit", "(", "'.'", ",", "1", ")", "except", "ValueError", ":", "raise", "ImportError", "(", "'Cant import backend from path: {}'", ".", "format", "(", "s", ")", ")", "module", "=", "import_module", "(", "m_path", ")", "return", "getattr", "(", "module", ",", "o_name", ")" ]
Load backend by dotted path.
[ "Load", "backend", "by", "dotted", "path", "." ]
39dbd0cd4de59ad8f5d06d1cc4d5fbcd210ab764
https://github.com/zerc/django-vest/blob/39dbd0cd4de59ad8f5d06d1cc4d5fbcd210ab764/django_vest/utils.py#L11-L20
249,739
zerc/django-vest
django_vest/utils.py
get_available_themes
def get_available_themes(): """ Iterator on available themes """ for d in settings.TEMPLATE_DIRS: for _d in os.listdir(d): if os.path.isdir(os.path.join(d, _d)) and is_theme_dir(_d): yield _d
python
def get_available_themes(): """ Iterator on available themes """ for d in settings.TEMPLATE_DIRS: for _d in os.listdir(d): if os.path.isdir(os.path.join(d, _d)) and is_theme_dir(_d): yield _d
[ "def", "get_available_themes", "(", ")", ":", "for", "d", "in", "settings", ".", "TEMPLATE_DIRS", ":", "for", "_d", "in", "os", ".", "listdir", "(", "d", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "d", ",", "_d", ")", ")", "and", "is_theme_dir", "(", "_d", ")", ":", "yield", "_d" ]
Iterator on available themes
[ "Iterator", "on", "available", "themes" ]
39dbd0cd4de59ad8f5d06d1cc4d5fbcd210ab764
https://github.com/zerc/django-vest/blob/39dbd0cd4de59ad8f5d06d1cc4d5fbcd210ab764/django_vest/utils.py#L23-L29
249,740
minhhoit/yacms
yacms/pages/admin.py
PageAdmin.check_permission
def check_permission(self, request, page, permission): """ Runs the custom permission check and raises an exception if False. """ if not getattr(page, "can_" + permission)(request): raise PermissionDenied
python
def check_permission(self, request, page, permission): """ Runs the custom permission check and raises an exception if False. """ if not getattr(page, "can_" + permission)(request): raise PermissionDenied
[ "def", "check_permission", "(", "self", ",", "request", ",", "page", ",", "permission", ")", ":", "if", "not", "getattr", "(", "page", ",", "\"can_\"", "+", "permission", ")", "(", "request", ")", ":", "raise", "PermissionDenied" ]
Runs the custom permission check and raises an exception if False.
[ "Runs", "the", "custom", "permission", "check", "and", "raises", "an", "exception", "if", "False", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/admin.py#L51-L57
249,741
minhhoit/yacms
yacms/pages/admin.py
PageAdmin.add_view
def add_view(self, request, **kwargs): """ For the ``Page`` model, redirect to the add view for the first page model, based on the ``ADD_PAGE_ORDER`` setting. """ if self.model is Page: return HttpResponseRedirect(self.get_content_models()[0].add_url) return super(PageAdmin, self).add_view(request, **kwargs)
python
def add_view(self, request, **kwargs): """ For the ``Page`` model, redirect to the add view for the first page model, based on the ``ADD_PAGE_ORDER`` setting. """ if self.model is Page: return HttpResponseRedirect(self.get_content_models()[0].add_url) return super(PageAdmin, self).add_view(request, **kwargs)
[ "def", "add_view", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "model", "is", "Page", ":", "return", "HttpResponseRedirect", "(", "self", ".", "get_content_models", "(", ")", "[", "0", "]", ".", "add_url", ")", "return", "super", "(", "PageAdmin", ",", "self", ")", ".", "add_view", "(", "request", ",", "*", "*", "kwargs", ")" ]
For the ``Page`` model, redirect to the add view for the first page model, based on the ``ADD_PAGE_ORDER`` setting.
[ "For", "the", "Page", "model", "redirect", "to", "the", "add", "view", "for", "the", "first", "page", "model", "based", "on", "the", "ADD_PAGE_ORDER", "setting", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/admin.py#L59-L66
249,742
minhhoit/yacms
yacms/pages/admin.py
PageAdmin.change_view
def change_view(self, request, object_id, **kwargs): """ Enforce custom permissions for the page instance. """ page = get_object_or_404(Page, pk=object_id) content_model = page.get_content_model() kwargs.setdefault("extra_context", {}) kwargs["extra_context"].update({ "hide_delete_link": not content_model.can_delete(request), "hide_slug_field": content_model.overridden(), }) return super(PageAdmin, self).change_view(request, object_id, **kwargs)
python
def change_view(self, request, object_id, **kwargs): """ Enforce custom permissions for the page instance. """ page = get_object_or_404(Page, pk=object_id) content_model = page.get_content_model() kwargs.setdefault("extra_context", {}) kwargs["extra_context"].update({ "hide_delete_link": not content_model.can_delete(request), "hide_slug_field": content_model.overridden(), }) return super(PageAdmin, self).change_view(request, object_id, **kwargs)
[ "def", "change_view", "(", "self", ",", "request", ",", "object_id", ",", "*", "*", "kwargs", ")", ":", "page", "=", "get_object_or_404", "(", "Page", ",", "pk", "=", "object_id", ")", "content_model", "=", "page", ".", "get_content_model", "(", ")", "kwargs", ".", "setdefault", "(", "\"extra_context\"", ",", "{", "}", ")", "kwargs", "[", "\"extra_context\"", "]", ".", "update", "(", "{", "\"hide_delete_link\"", ":", "not", "content_model", ".", "can_delete", "(", "request", ")", ",", "\"hide_slug_field\"", ":", "content_model", ".", "overridden", "(", ")", ",", "}", ")", "return", "super", "(", "PageAdmin", ",", "self", ")", ".", "change_view", "(", "request", ",", "object_id", ",", "*", "*", "kwargs", ")" ]
Enforce custom permissions for the page instance.
[ "Enforce", "custom", "permissions", "for", "the", "page", "instance", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/admin.py#L68-L81
249,743
minhhoit/yacms
yacms/pages/admin.py
PageAdmin.delete_view
def delete_view(self, request, object_id, **kwargs): """ Enforce custom delete permissions for the page instance. """ page = get_object_or_404(Page, pk=object_id) content_model = page.get_content_model() self.check_permission(request, content_model, "delete") return super(PageAdmin, self).delete_view(request, object_id, **kwargs)
python
def delete_view(self, request, object_id, **kwargs): """ Enforce custom delete permissions for the page instance. """ page = get_object_or_404(Page, pk=object_id) content_model = page.get_content_model() self.check_permission(request, content_model, "delete") return super(PageAdmin, self).delete_view(request, object_id, **kwargs)
[ "def", "delete_view", "(", "self", ",", "request", ",", "object_id", ",", "*", "*", "kwargs", ")", ":", "page", "=", "get_object_or_404", "(", "Page", ",", "pk", "=", "object_id", ")", "content_model", "=", "page", ".", "get_content_model", "(", ")", "self", ".", "check_permission", "(", "request", ",", "content_model", ",", "\"delete\"", ")", "return", "super", "(", "PageAdmin", ",", "self", ")", ".", "delete_view", "(", "request", ",", "object_id", ",", "*", "*", "kwargs", ")" ]
Enforce custom delete permissions for the page instance.
[ "Enforce", "custom", "delete", "permissions", "for", "the", "page", "instance", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/admin.py#L83-L90
249,744
minhhoit/yacms
yacms/pages/admin.py
PageAdmin.save_model
def save_model(self, request, obj, form, change): """ Set the ID of the parent page if passed in via querystring, and make sure the new slug propagates to all descendant pages. """ if change and obj._old_slug != obj.slug: # _old_slug was set in PageAdminForm.clean_slug(). new_slug = obj.slug or obj.generate_unique_slug() obj.slug = obj._old_slug obj.set_slug(new_slug) # Force parent to be saved to trigger handling of ordering and slugs. parent = request.GET.get("parent") if parent is not None and not change: obj.parent_id = parent obj.save() super(PageAdmin, self).save_model(request, obj, form, change)
python
def save_model(self, request, obj, form, change): """ Set the ID of the parent page if passed in via querystring, and make sure the new slug propagates to all descendant pages. """ if change and obj._old_slug != obj.slug: # _old_slug was set in PageAdminForm.clean_slug(). new_slug = obj.slug or obj.generate_unique_slug() obj.slug = obj._old_slug obj.set_slug(new_slug) # Force parent to be saved to trigger handling of ordering and slugs. parent = request.GET.get("parent") if parent is not None and not change: obj.parent_id = parent obj.save() super(PageAdmin, self).save_model(request, obj, form, change)
[ "def", "save_model", "(", "self", ",", "request", ",", "obj", ",", "form", ",", "change", ")", ":", "if", "change", "and", "obj", ".", "_old_slug", "!=", "obj", ".", "slug", ":", "# _old_slug was set in PageAdminForm.clean_slug().", "new_slug", "=", "obj", ".", "slug", "or", "obj", ".", "generate_unique_slug", "(", ")", "obj", ".", "slug", "=", "obj", ".", "_old_slug", "obj", ".", "set_slug", "(", "new_slug", ")", "# Force parent to be saved to trigger handling of ordering and slugs.", "parent", "=", "request", ".", "GET", ".", "get", "(", "\"parent\"", ")", "if", "parent", "is", "not", "None", "and", "not", "change", ":", "obj", ".", "parent_id", "=", "parent", "obj", ".", "save", "(", ")", "super", "(", "PageAdmin", ",", "self", ")", ".", "save_model", "(", "request", ",", "obj", ",", "form", ",", "change", ")" ]
Set the ID of the parent page if passed in via querystring, and make sure the new slug propagates to all descendant pages.
[ "Set", "the", "ID", "of", "the", "parent", "page", "if", "passed", "in", "via", "querystring", "and", "make", "sure", "the", "new", "slug", "propagates", "to", "all", "descendant", "pages", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/admin.py#L92-L108
249,745
minhhoit/yacms
yacms/pages/admin.py
PageAdmin._maintain_parent
def _maintain_parent(self, request, response): """ Maintain the parent ID in the querystring for response_add and response_change. """ location = response._headers.get("location") parent = request.GET.get("parent") if parent and location and "?" not in location[1]: url = "%s?parent=%s" % (location[1], parent) return HttpResponseRedirect(url) return response
python
def _maintain_parent(self, request, response): """ Maintain the parent ID in the querystring for response_add and response_change. """ location = response._headers.get("location") parent = request.GET.get("parent") if parent and location and "?" not in location[1]: url = "%s?parent=%s" % (location[1], parent) return HttpResponseRedirect(url) return response
[ "def", "_maintain_parent", "(", "self", ",", "request", ",", "response", ")", ":", "location", "=", "response", ".", "_headers", ".", "get", "(", "\"location\"", ")", "parent", "=", "request", ".", "GET", ".", "get", "(", "\"parent\"", ")", "if", "parent", "and", "location", "and", "\"?\"", "not", "in", "location", "[", "1", "]", ":", "url", "=", "\"%s?parent=%s\"", "%", "(", "location", "[", "1", "]", ",", "parent", ")", "return", "HttpResponseRedirect", "(", "url", ")", "return", "response" ]
Maintain the parent ID in the querystring for response_add and response_change.
[ "Maintain", "the", "parent", "ID", "in", "the", "querystring", "for", "response_add", "and", "response_change", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/admin.py#L110-L120
249,746
minhhoit/yacms
yacms/pages/admin.py
PageAdmin.get_content_models
def get_content_models(self): """ Return all Page subclasses that are admin registered, ordered based on the ``ADD_PAGE_ORDER`` setting. """ models = super(PageAdmin, self).get_content_models() order = [name.lower() for name in settings.ADD_PAGE_ORDER] def sort_key(page): name = "%s.%s" % (page._meta.app_label, page._meta.object_name) unordered = len(order) try: return (order.index(name.lower()), "") except ValueError: return (unordered, page.meta_verbose_name) return sorted(models, key=sort_key)
python
def get_content_models(self): """ Return all Page subclasses that are admin registered, ordered based on the ``ADD_PAGE_ORDER`` setting. """ models = super(PageAdmin, self).get_content_models() order = [name.lower() for name in settings.ADD_PAGE_ORDER] def sort_key(page): name = "%s.%s" % (page._meta.app_label, page._meta.object_name) unordered = len(order) try: return (order.index(name.lower()), "") except ValueError: return (unordered, page.meta_verbose_name) return sorted(models, key=sort_key)
[ "def", "get_content_models", "(", "self", ")", ":", "models", "=", "super", "(", "PageAdmin", ",", "self", ")", ".", "get_content_models", "(", ")", "order", "=", "[", "name", ".", "lower", "(", ")", "for", "name", "in", "settings", ".", "ADD_PAGE_ORDER", "]", "def", "sort_key", "(", "page", ")", ":", "name", "=", "\"%s.%s\"", "%", "(", "page", ".", "_meta", ".", "app_label", ",", "page", ".", "_meta", ".", "object_name", ")", "unordered", "=", "len", "(", "order", ")", "try", ":", "return", "(", "order", ".", "index", "(", "name", ".", "lower", "(", ")", ")", ",", "\"\"", ")", "except", "ValueError", ":", "return", "(", "unordered", ",", "page", ".", "meta_verbose_name", ")", "return", "sorted", "(", "models", ",", "key", "=", "sort_key", ")" ]
Return all Page subclasses that are admin registered, ordered based on the ``ADD_PAGE_ORDER`` setting.
[ "Return", "all", "Page", "subclasses", "that", "are", "admin", "registered", "ordered", "based", "on", "the", "ADD_PAGE_ORDER", "setting", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/admin.py#L138-L154
249,747
minhhoit/yacms
yacms/pages/admin.py
LinkAdmin.formfield_for_dbfield
def formfield_for_dbfield(self, db_field, **kwargs): """ Make slug mandatory. """ if db_field.name == "slug": kwargs["required"] = True kwargs["help_text"] = None return super(LinkAdmin, self).formfield_for_dbfield(db_field, **kwargs)
python
def formfield_for_dbfield(self, db_field, **kwargs): """ Make slug mandatory. """ if db_field.name == "slug": kwargs["required"] = True kwargs["help_text"] = None return super(LinkAdmin, self).formfield_for_dbfield(db_field, **kwargs)
[ "def", "formfield_for_dbfield", "(", "self", ",", "db_field", ",", "*", "*", "kwargs", ")", ":", "if", "db_field", ".", "name", "==", "\"slug\"", ":", "kwargs", "[", "\"required\"", "]", "=", "True", "kwargs", "[", "\"help_text\"", "]", "=", "None", "return", "super", "(", "LinkAdmin", ",", "self", ")", ".", "formfield_for_dbfield", "(", "db_field", ",", "*", "*", "kwargs", ")" ]
Make slug mandatory.
[ "Make", "slug", "mandatory", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/admin.py#L166-L173
249,748
minhhoit/yacms
yacms/pages/admin.py
LinkAdmin.save_form
def save_form(self, request, form, change): """ Don't show links in the sitemap. """ obj = form.save(commit=False) if not obj.id and "in_sitemap" not in form.fields: obj.in_sitemap = False return super(LinkAdmin, self).save_form(request, form, change)
python
def save_form(self, request, form, change): """ Don't show links in the sitemap. """ obj = form.save(commit=False) if not obj.id and "in_sitemap" not in form.fields: obj.in_sitemap = False return super(LinkAdmin, self).save_form(request, form, change)
[ "def", "save_form", "(", "self", ",", "request", ",", "form", ",", "change", ")", ":", "obj", "=", "form", ".", "save", "(", "commit", "=", "False", ")", "if", "not", "obj", ".", "id", "and", "\"in_sitemap\"", "not", "in", "form", ".", "fields", ":", "obj", ".", "in_sitemap", "=", "False", "return", "super", "(", "LinkAdmin", ",", "self", ")", ".", "save_form", "(", "request", ",", "form", ",", "change", ")" ]
Don't show links in the sitemap.
[ "Don", "t", "show", "links", "in", "the", "sitemap", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/admin.py#L175-L182
249,749
darkfeline/mir.anidb
mir/anidb/titles.py
_request_titles_xml
def _request_titles_xml() -> ET.ElementTree: """Request AniDB titles file.""" response = api.titles_request() return api.unpack_xml(response.text)
python
def _request_titles_xml() -> ET.ElementTree: """Request AniDB titles file.""" response = api.titles_request() return api.unpack_xml(response.text)
[ "def", "_request_titles_xml", "(", ")", "->", "ET", ".", "ElementTree", ":", "response", "=", "api", ".", "titles_request", "(", ")", "return", "api", ".", "unpack_xml", "(", "response", ".", "text", ")" ]
Request AniDB titles file.
[ "Request", "AniDB", "titles", "file", "." ]
a0d25908f85fb1ff4bc595954bfc3f223f1b5acc
https://github.com/darkfeline/mir.anidb/blob/a0d25908f85fb1ff4bc595954bfc3f223f1b5acc/mir/anidb/titles.py#L157-L160
249,750
darkfeline/mir.anidb
mir/anidb/titles.py
_unpack_titles
def _unpack_titles(etree: ET.ElementTree) -> 'Generator': """Unpack Titles from titles XML.""" for anime in etree.getroot(): yield Titles( aid=int(anime.get('aid')), titles=tuple(unpack_anime_title(title) for title in anime), )
python
def _unpack_titles(etree: ET.ElementTree) -> 'Generator': """Unpack Titles from titles XML.""" for anime in etree.getroot(): yield Titles( aid=int(anime.get('aid')), titles=tuple(unpack_anime_title(title) for title in anime), )
[ "def", "_unpack_titles", "(", "etree", ":", "ET", ".", "ElementTree", ")", "->", "'Generator'", ":", "for", "anime", "in", "etree", ".", "getroot", "(", ")", ":", "yield", "Titles", "(", "aid", "=", "int", "(", "anime", ".", "get", "(", "'aid'", ")", ")", ",", "titles", "=", "tuple", "(", "unpack_anime_title", "(", "title", ")", "for", "title", "in", "anime", ")", ",", ")" ]
Unpack Titles from titles XML.
[ "Unpack", "Titles", "from", "titles", "XML", "." ]
a0d25908f85fb1ff4bc595954bfc3f223f1b5acc
https://github.com/darkfeline/mir.anidb/blob/a0d25908f85fb1ff4bc595954bfc3f223f1b5acc/mir/anidb/titles.py#L163-L169
249,751
darkfeline/mir.anidb
mir/anidb/titles.py
CachedTitlesGetter.get
def get(self, force=False) -> 'List[Titles]': """Get list of Titles. Pass force=True to bypass the cache. """ try: if force: raise CacheMissingError return self._cache.load() except CacheMissingError: titles = self._requester() self._cache.save(titles) return titles
python
def get(self, force=False) -> 'List[Titles]': """Get list of Titles. Pass force=True to bypass the cache. """ try: if force: raise CacheMissingError return self._cache.load() except CacheMissingError: titles = self._requester() self._cache.save(titles) return titles
[ "def", "get", "(", "self", ",", "force", "=", "False", ")", "->", "'List[Titles]'", ":", "try", ":", "if", "force", ":", "raise", "CacheMissingError", "return", "self", ".", "_cache", ".", "load", "(", ")", "except", "CacheMissingError", ":", "titles", "=", "self", ".", "_requester", "(", ")", "self", ".", "_cache", ".", "save", "(", "titles", ")", "return", "titles" ]
Get list of Titles. Pass force=True to bypass the cache.
[ "Get", "list", "of", "Titles", "." ]
a0d25908f85fb1ff4bc595954bfc3f223f1b5acc
https://github.com/darkfeline/mir.anidb/blob/a0d25908f85fb1ff4bc595954bfc3f223f1b5acc/mir/anidb/titles.py#L61-L73
249,752
pydsigner/taskit
taskit/frontend.py
FrontEnd._sending_task
def _sending_task(self, backend): """ Used internally to safely increment `backend`s task count. Returns the overall count of tasks for `backend`. """ with self.backend_mutex: self.backends[backend] += 1 self.task_counter[backend] += 1 this_task = self.task_counter[backend] return this_task
python
def _sending_task(self, backend): """ Used internally to safely increment `backend`s task count. Returns the overall count of tasks for `backend`. """ with self.backend_mutex: self.backends[backend] += 1 self.task_counter[backend] += 1 this_task = self.task_counter[backend] return this_task
[ "def", "_sending_task", "(", "self", ",", "backend", ")", ":", "with", "self", ".", "backend_mutex", ":", "self", ".", "backends", "[", "backend", "]", "+=", "1", "self", ".", "task_counter", "[", "backend", "]", "+=", "1", "this_task", "=", "self", ".", "task_counter", "[", "backend", "]", "return", "this_task" ]
Used internally to safely increment `backend`s task count. Returns the overall count of tasks for `backend`.
[ "Used", "internally", "to", "safely", "increment", "backend", "s", "task", "count", ".", "Returns", "the", "overall", "count", "of", "tasks", "for", "backend", "." ]
3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f
https://github.com/pydsigner/taskit/blob/3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f/taskit/frontend.py#L73-L82
249,753
pydsigner/taskit
taskit/frontend.py
FrontEnd._canceling_task
def _canceling_task(self, backend): """ Used internally to decrement `backend`s current and total task counts when `backend` could not be reached. """ with self.backend_mutex: self.backends[backend] -= 1 self.task_counter[backend] -= 1
python
def _canceling_task(self, backend): """ Used internally to decrement `backend`s current and total task counts when `backend` could not be reached. """ with self.backend_mutex: self.backends[backend] -= 1 self.task_counter[backend] -= 1
[ "def", "_canceling_task", "(", "self", ",", "backend", ")", ":", "with", "self", ".", "backend_mutex", ":", "self", ".", "backends", "[", "backend", "]", "-=", "1", "self", ".", "task_counter", "[", "backend", "]", "-=", "1" ]
Used internally to decrement `backend`s current and total task counts when `backend` could not be reached.
[ "Used", "internally", "to", "decrement", "backend", "s", "current", "and", "total", "task", "counts", "when", "backend", "could", "not", "be", "reached", "." ]
3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f
https://github.com/pydsigner/taskit/blob/3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f/taskit/frontend.py#L84-L91
249,754
pydsigner/taskit
taskit/frontend.py
FrontEnd._expand_host
def _expand_host(self, host): """ Used internally to add the default port to hosts not including portnames. """ if isinstance(host, basestring): return (host, self.default_port) return tuple(host)
python
def _expand_host(self, host): """ Used internally to add the default port to hosts not including portnames. """ if isinstance(host, basestring): return (host, self.default_port) return tuple(host)
[ "def", "_expand_host", "(", "self", ",", "host", ")", ":", "if", "isinstance", "(", "host", ",", "basestring", ")", ":", "return", "(", "host", ",", "self", ".", "default_port", ")", "return", "tuple", "(", "host", ")" ]
Used internally to add the default port to hosts not including portnames.
[ "Used", "internally", "to", "add", "the", "default", "port", "to", "hosts", "not", "including", "portnames", "." ]
3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f
https://github.com/pydsigner/taskit/blob/3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f/taskit/frontend.py#L100-L107
249,755
pydsigner/taskit
taskit/frontend.py
FrontEnd._package
def _package(self, task, *args, **kw): """ Used internally. Simply wraps the arguments up in a list and encodes the list. """ # Implementation note: it is faster to use a tuple than a list here, # because json does the list-like check like so (json/encoder.py:424): # isinstance(o, (list, tuple)) # Because of this order, it is actually faster to create a list: # >>> timeit.timeit('L = [1,2,3]\nisinstance(L, (list, tuple))') # 0.41077208518981934 # >>> timeit.timeit('L = (1,2,3)\nisinstance(L, (list, tuple))') # 0.49509215354919434 # Whereas if it were the other way around, using a tuple would be # faster: # >>> timeit.timeit('L = (1,2,3)\nisinstance(L, (tuple, list))') # 0.3031749725341797 # >>> timeit.timeit('L = [1,2,3]\nisinstance(L, (tuple, list))') # 0.6147568225860596 return self.codec.encode([task, args, kw])
python
def _package(self, task, *args, **kw): """ Used internally. Simply wraps the arguments up in a list and encodes the list. """ # Implementation note: it is faster to use a tuple than a list here, # because json does the list-like check like so (json/encoder.py:424): # isinstance(o, (list, tuple)) # Because of this order, it is actually faster to create a list: # >>> timeit.timeit('L = [1,2,3]\nisinstance(L, (list, tuple))') # 0.41077208518981934 # >>> timeit.timeit('L = (1,2,3)\nisinstance(L, (list, tuple))') # 0.49509215354919434 # Whereas if it were the other way around, using a tuple would be # faster: # >>> timeit.timeit('L = (1,2,3)\nisinstance(L, (tuple, list))') # 0.3031749725341797 # >>> timeit.timeit('L = [1,2,3]\nisinstance(L, (tuple, list))') # 0.6147568225860596 return self.codec.encode([task, args, kw])
[ "def", "_package", "(", "self", ",", "task", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "# Implementation note: it is faster to use a tuple than a list here, ", "# because json does the list-like check like so (json/encoder.py:424):", "# isinstance(o, (list, tuple))", "# Because of this order, it is actually faster to create a list:", "# >>> timeit.timeit('L = [1,2,3]\\nisinstance(L, (list, tuple))')", "# 0.41077208518981934", "# >>> timeit.timeit('L = (1,2,3)\\nisinstance(L, (list, tuple))')", "# 0.49509215354919434", "# Whereas if it were the other way around, using a tuple would be ", "# faster:", "# >>> timeit.timeit('L = (1,2,3)\\nisinstance(L, (tuple, list))')", "# 0.3031749725341797", "# >>> timeit.timeit('L = [1,2,3]\\nisinstance(L, (tuple, list))')", "# 0.6147568225860596", "return", "self", ".", "codec", ".", "encode", "(", "[", "task", ",", "args", ",", "kw", "]", ")" ]
Used internally. Simply wraps the arguments up in a list and encodes the list.
[ "Used", "internally", ".", "Simply", "wraps", "the", "arguments", "up", "in", "a", "list", "and", "encodes", "the", "list", "." ]
3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f
https://github.com/pydsigner/taskit/blob/3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f/taskit/frontend.py#L131-L150
249,756
pydsigner/taskit
taskit/frontend.py
FrontEnd.send_signal
def send_signal(self, backend, signal): """ Sends the `signal` signal to `backend`. Raises ValueError if `backend` is not registered with the client. Returns the result. """ backend = self._expand_host(backend) if backend in self.backends: try: return self._work(backend, self._package(signal), log=False) except socket.error: raise BackendNotAvailableError else: raise ValueError('No such backend!')
python
def send_signal(self, backend, signal): """ Sends the `signal` signal to `backend`. Raises ValueError if `backend` is not registered with the client. Returns the result. """ backend = self._expand_host(backend) if backend in self.backends: try: return self._work(backend, self._package(signal), log=False) except socket.error: raise BackendNotAvailableError else: raise ValueError('No such backend!')
[ "def", "send_signal", "(", "self", ",", "backend", ",", "signal", ")", ":", "backend", "=", "self", ".", "_expand_host", "(", "backend", ")", "if", "backend", "in", "self", ".", "backends", ":", "try", ":", "return", "self", ".", "_work", "(", "backend", ",", "self", ".", "_package", "(", "signal", ")", ",", "log", "=", "False", ")", "except", "socket", ".", "error", ":", "raise", "BackendNotAvailableError", "else", ":", "raise", "ValueError", "(", "'No such backend!'", ")" ]
Sends the `signal` signal to `backend`. Raises ValueError if `backend` is not registered with the client. Returns the result.
[ "Sends", "the", "signal", "signal", "to", "backend", ".", "Raises", "ValueError", "if", "backend", "is", "not", "registered", "with", "the", "client", ".", "Returns", "the", "result", "." ]
3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f
https://github.com/pydsigner/taskit/blob/3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f/taskit/frontend.py#L185-L197
249,757
minhhoit/yacms
yacms/pages/context_processors.py
page
def page(request): """ Adds the current page to the template context and runs its ``set_helper`` method. This was previously part of ``PageMiddleware``, but moved to a context processor so that we could assign these template context variables without the middleware depending on Django's ``TemplateResponse``. """ context = {} page = getattr(request, "page", None) if isinstance(page, Page): # set_helpers has always expected the current template context, # but here we're just passing in our context dict with enough # variables to satisfy it. context = {"request": request, "page": page, "_current_page": page} page.set_helpers(context) return context
python
def page(request): """ Adds the current page to the template context and runs its ``set_helper`` method. This was previously part of ``PageMiddleware``, but moved to a context processor so that we could assign these template context variables without the middleware depending on Django's ``TemplateResponse``. """ context = {} page = getattr(request, "page", None) if isinstance(page, Page): # set_helpers has always expected the current template context, # but here we're just passing in our context dict with enough # variables to satisfy it. context = {"request": request, "page": page, "_current_page": page} page.set_helpers(context) return context
[ "def", "page", "(", "request", ")", ":", "context", "=", "{", "}", "page", "=", "getattr", "(", "request", ",", "\"page\"", ",", "None", ")", "if", "isinstance", "(", "page", ",", "Page", ")", ":", "# set_helpers has always expected the current template context,", "# but here we're just passing in our context dict with enough", "# variables to satisfy it.", "context", "=", "{", "\"request\"", ":", "request", ",", "\"page\"", ":", "page", ",", "\"_current_page\"", ":", "page", "}", "page", ".", "set_helpers", "(", "context", ")", "return", "context" ]
Adds the current page to the template context and runs its ``set_helper`` method. This was previously part of ``PageMiddleware``, but moved to a context processor so that we could assign these template context variables without the middleware depending on Django's ``TemplateResponse``.
[ "Adds", "the", "current", "page", "to", "the", "template", "context", "and", "runs", "its", "set_helper", "method", ".", "This", "was", "previously", "part", "of", "PageMiddleware", "but", "moved", "to", "a", "context", "processor", "so", "that", "we", "could", "assign", "these", "template", "context", "variables", "without", "the", "middleware", "depending", "on", "Django", "s", "TemplateResponse", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/context_processors.py#L4-L20
249,758
20c/xbahn
xbahn/connection/zmq.py
config_from_url
def config_from_url(u, **kwargs): """ Returns dict containing zmq configuration arguments parsed from xbahn url Arguments: - u (urlparse.urlparse result) Returns: dict: - id (str): connection index key - typ_str (str): string representation of zmq socket type - typ (int): zmq socket type (PUB, SUB, REQ, REP, PUSH, PULL) - topic (str): subscription topic - url (str): url to use with zmq's bind function """ path = u.path.lstrip("/").split("/") if len(path) > 2 or not path: raise AssertionError("zmq url format: zmq://<host>:<port>/<pub|sub>/<topic>") typ = path[0].upper() try: topic = path[1] except IndexError as _: topic = '' param = dict(urllib.parse.parse_qsl(u.query)) #FIXME: should come from schema, maybe zmq+tcp:// ? transport = param.get("transport", "tcp") _id = "%s-%s-%s-%s" % (typ, topic, transport, u.netloc) if kwargs.get("prefix") is not None: _id = "%s-%s" % (kwargs.get("prefix"), _id) return { "id" : _id, "typ_str" : typ, "typ" : getattr(zmq, typ), "topic" : topic, "transport" : transport, "url" : "%s://%s" % (transport, u.netloc) }
python
def config_from_url(u, **kwargs): """ Returns dict containing zmq configuration arguments parsed from xbahn url Arguments: - u (urlparse.urlparse result) Returns: dict: - id (str): connection index key - typ_str (str): string representation of zmq socket type - typ (int): zmq socket type (PUB, SUB, REQ, REP, PUSH, PULL) - topic (str): subscription topic - url (str): url to use with zmq's bind function """ path = u.path.lstrip("/").split("/") if len(path) > 2 or not path: raise AssertionError("zmq url format: zmq://<host>:<port>/<pub|sub>/<topic>") typ = path[0].upper() try: topic = path[1] except IndexError as _: topic = '' param = dict(urllib.parse.parse_qsl(u.query)) #FIXME: should come from schema, maybe zmq+tcp:// ? transport = param.get("transport", "tcp") _id = "%s-%s-%s-%s" % (typ, topic, transport, u.netloc) if kwargs.get("prefix") is not None: _id = "%s-%s" % (kwargs.get("prefix"), _id) return { "id" : _id, "typ_str" : typ, "typ" : getattr(zmq, typ), "topic" : topic, "transport" : transport, "url" : "%s://%s" % (transport, u.netloc) }
[ "def", "config_from_url", "(", "u", ",", "*", "*", "kwargs", ")", ":", "path", "=", "u", ".", "path", ".", "lstrip", "(", "\"/\"", ")", ".", "split", "(", "\"/\"", ")", "if", "len", "(", "path", ")", ">", "2", "or", "not", "path", ":", "raise", "AssertionError", "(", "\"zmq url format: zmq://<host>:<port>/<pub|sub>/<topic>\"", ")", "typ", "=", "path", "[", "0", "]", ".", "upper", "(", ")", "try", ":", "topic", "=", "path", "[", "1", "]", "except", "IndexError", "as", "_", ":", "topic", "=", "''", "param", "=", "dict", "(", "urllib", ".", "parse", ".", "parse_qsl", "(", "u", ".", "query", ")", ")", "#FIXME: should come from schema, maybe zmq+tcp:// ?", "transport", "=", "param", ".", "get", "(", "\"transport\"", ",", "\"tcp\"", ")", "_id", "=", "\"%s-%s-%s-%s\"", "%", "(", "typ", ",", "topic", ",", "transport", ",", "u", ".", "netloc", ")", "if", "kwargs", ".", "get", "(", "\"prefix\"", ")", "is", "not", "None", ":", "_id", "=", "\"%s-%s\"", "%", "(", "kwargs", ".", "get", "(", "\"prefix\"", ")", ",", "_id", ")", "return", "{", "\"id\"", ":", "_id", ",", "\"typ_str\"", ":", "typ", ",", "\"typ\"", ":", "getattr", "(", "zmq", ",", "typ", ")", ",", "\"topic\"", ":", "topic", ",", "\"transport\"", ":", "transport", ",", "\"url\"", ":", "\"%s://%s\"", "%", "(", "transport", ",", "u", ".", "netloc", ")", "}" ]
Returns dict containing zmq configuration arguments parsed from xbahn url Arguments: - u (urlparse.urlparse result) Returns: dict: - id (str): connection index key - typ_str (str): string representation of zmq socket type - typ (int): zmq socket type (PUB, SUB, REQ, REP, PUSH, PULL) - topic (str): subscription topic - url (str): url to use with zmq's bind function
[ "Returns", "dict", "containing", "zmq", "configuration", "arguments", "parsed", "from", "xbahn", "url" ]
afb27b0576841338a366d7cac0200a782bd84be6
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/zmq.py#L30-L77
249,759
KnowledgeLinks/rdfframework
rdfframework/utilities/statistics.py
DictionaryCounter._record_blank
def _record_blank(self, current, dict_obj): """ records the dictionay in the the 'blank' attribute based on the 'list_blank' path args: ----- current: the current dictionay counts dict_obj: the original dictionary object """ if not self.list_blank: return if self.list_blank not in current: self.blank.append(dict_obj)
python
def _record_blank(self, current, dict_obj): """ records the dictionay in the the 'blank' attribute based on the 'list_blank' path args: ----- current: the current dictionay counts dict_obj: the original dictionary object """ if not self.list_blank: return if self.list_blank not in current: self.blank.append(dict_obj)
[ "def", "_record_blank", "(", "self", ",", "current", ",", "dict_obj", ")", ":", "if", "not", "self", ".", "list_blank", ":", "return", "if", "self", ".", "list_blank", "not", "in", "current", ":", "self", ".", "blank", ".", "append", "(", "dict_obj", ")" ]
records the dictionay in the the 'blank' attribute based on the 'list_blank' path args: ----- current: the current dictionay counts dict_obj: the original dictionary object
[ "records", "the", "dictionay", "in", "the", "the", "blank", "attribute", "based", "on", "the", "list_blank", "path" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/statistics.py#L54-L67
249,760
KnowledgeLinks/rdfframework
rdfframework/utilities/statistics.py
DictionaryCounter._count_objs
def _count_objs(self, obj, path=None, **kwargs): """ cycles through the object and adds in count values Args: ----- obj: the object to parse path: the current path kwargs: ------- current: a dictionary of counts for current call sub_val: the value to use for subtotal aggregation """ sub_val = None # pdb.set_trace() if isinstance(obj, dict): for key, value in obj.items(): if isinstance(value, (list, dict)): kwargs = self._count_objs(value, self.make_path(key, path), **kwargs) else: if self.make_path(key, path) == self.sub_total: # pdb.set_trace() sub_val = value kwargs['current'] = self._increment_prop(key, path, **kwargs) elif isinstance(obj, list): for item in obj: if isinstance(item, (list, dict)): kwargs = self._count_objs(item, path, **kwargs) else: if path == self.sub_total: pdb.set_trace() sub_val = item kwargs['current'] = self._increment_prop(path, **kwargs) else: kwargs['current'] = self._increment_prop(path, **kwargs) if path == self.sub_total: pdb.set_trace() sub_val = item if kwargs.get('sub_val') is None: kwargs['sub_val'] = sub_val return kwargs
python
def _count_objs(self, obj, path=None, **kwargs): """ cycles through the object and adds in count values Args: ----- obj: the object to parse path: the current path kwargs: ------- current: a dictionary of counts for current call sub_val: the value to use for subtotal aggregation """ sub_val = None # pdb.set_trace() if isinstance(obj, dict): for key, value in obj.items(): if isinstance(value, (list, dict)): kwargs = self._count_objs(value, self.make_path(key, path), **kwargs) else: if self.make_path(key, path) == self.sub_total: # pdb.set_trace() sub_val = value kwargs['current'] = self._increment_prop(key, path, **kwargs) elif isinstance(obj, list): for item in obj: if isinstance(item, (list, dict)): kwargs = self._count_objs(item, path, **kwargs) else: if path == self.sub_total: pdb.set_trace() sub_val = item kwargs['current'] = self._increment_prop(path, **kwargs) else: kwargs['current'] = self._increment_prop(path, **kwargs) if path == self.sub_total: pdb.set_trace() sub_val = item if kwargs.get('sub_val') is None: kwargs['sub_val'] = sub_val return kwargs
[ "def", "_count_objs", "(", "self", ",", "obj", ",", "path", "=", "None", ",", "*", "*", "kwargs", ")", ":", "sub_val", "=", "None", "# pdb.set_trace()", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "for", "key", ",", "value", "in", "obj", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "dict", ")", ")", ":", "kwargs", "=", "self", ".", "_count_objs", "(", "value", ",", "self", ".", "make_path", "(", "key", ",", "path", ")", ",", "*", "*", "kwargs", ")", "else", ":", "if", "self", ".", "make_path", "(", "key", ",", "path", ")", "==", "self", ".", "sub_total", ":", "# pdb.set_trace()", "sub_val", "=", "value", "kwargs", "[", "'current'", "]", "=", "self", ".", "_increment_prop", "(", "key", ",", "path", ",", "*", "*", "kwargs", ")", "elif", "isinstance", "(", "obj", ",", "list", ")", ":", "for", "item", "in", "obj", ":", "if", "isinstance", "(", "item", ",", "(", "list", ",", "dict", ")", ")", ":", "kwargs", "=", "self", ".", "_count_objs", "(", "item", ",", "path", ",", "*", "*", "kwargs", ")", "else", ":", "if", "path", "==", "self", ".", "sub_total", ":", "pdb", ".", "set_trace", "(", ")", "sub_val", "=", "item", "kwargs", "[", "'current'", "]", "=", "self", ".", "_increment_prop", "(", "path", ",", "*", "*", "kwargs", ")", "else", ":", "kwargs", "[", "'current'", "]", "=", "self", ".", "_increment_prop", "(", "path", ",", "*", "*", "kwargs", ")", "if", "path", "==", "self", ".", "sub_total", ":", "pdb", ".", "set_trace", "(", ")", "sub_val", "=", "item", "if", "kwargs", ".", "get", "(", "'sub_val'", ")", "is", "None", ":", "kwargs", "[", "'sub_val'", "]", "=", "sub_val", "return", "kwargs" ]
cycles through the object and adds in count values Args: ----- obj: the object to parse path: the current path kwargs: ------- current: a dictionary of counts for current call sub_val: the value to use for subtotal aggregation
[ "cycles", "through", "the", "object", "and", "adds", "in", "count", "values" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/statistics.py#L69-L115
249,761
KnowledgeLinks/rdfframework
rdfframework/utilities/statistics.py
DictionaryCounter._increment_prop
def _increment_prop(self, prop, path=None, **kwargs): """ increments the property path count args: ----- prop: the key for the prop path: the path to the prop kwargs: ------- current: dictionary count for the current dictionay """ new_path = self.make_path(prop, path) if self.method == 'simple': counter = kwargs['current'] else: counter = self.counts try: counter[new_path] += 1 except KeyError: counter[new_path] = 1 return counter
python
def _increment_prop(self, prop, path=None, **kwargs): """ increments the property path count args: ----- prop: the key for the prop path: the path to the prop kwargs: ------- current: dictionary count for the current dictionay """ new_path = self.make_path(prop, path) if self.method == 'simple': counter = kwargs['current'] else: counter = self.counts try: counter[new_path] += 1 except KeyError: counter[new_path] = 1 return counter
[ "def", "_increment_prop", "(", "self", ",", "prop", ",", "path", "=", "None", ",", "*", "*", "kwargs", ")", ":", "new_path", "=", "self", ".", "make_path", "(", "prop", ",", "path", ")", "if", "self", ".", "method", "==", "'simple'", ":", "counter", "=", "kwargs", "[", "'current'", "]", "else", ":", "counter", "=", "self", ".", "counts", "try", ":", "counter", "[", "new_path", "]", "+=", "1", "except", "KeyError", ":", "counter", "[", "new_path", "]", "=", "1", "return", "counter" ]
increments the property path count args: ----- prop: the key for the prop path: the path to the prop kwargs: ------- current: dictionary count for the current dictionay
[ "increments", "the", "property", "path", "count" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/statistics.py#L120-L142
249,762
KnowledgeLinks/rdfframework
rdfframework/utilities/statistics.py
DictionaryCounter.update_counts
def update_counts(self, current): """ updates counts for the class instance based on the current dictionary counts args: ----- current: current dictionary counts """ for item in current: try: self.counts[item] += 1 except KeyError: self.counts[item] = 1
python
def update_counts(self, current): """ updates counts for the class instance based on the current dictionary counts args: ----- current: current dictionary counts """ for item in current: try: self.counts[item] += 1 except KeyError: self.counts[item] = 1
[ "def", "update_counts", "(", "self", ",", "current", ")", ":", "for", "item", "in", "current", ":", "try", ":", "self", ".", "counts", "[", "item", "]", "+=", "1", "except", "KeyError", ":", "self", ".", "counts", "[", "item", "]", "=", "1" ]
updates counts for the class instance based on the current dictionary counts args: ----- current: current dictionary counts
[ "updates", "counts", "for", "the", "class", "instance", "based", "on", "the", "current", "dictionary", "counts" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/statistics.py#L144-L157
249,763
KnowledgeLinks/rdfframework
rdfframework/utilities/statistics.py
DictionaryCounter.update_subtotals
def update_subtotals(self, current, sub_key): """ updates sub_total counts for the class instance based on the current dictionary counts args: ----- current: current dictionary counts sub_key: the key/value to use for the subtotals """ if not self.sub_counts.get(sub_key): self.sub_counts[sub_key] = {} for item in current: try: self.sub_counts[sub_key][item] += 1 except KeyError: self.sub_counts[sub_key][item] = 1
python
def update_subtotals(self, current, sub_key): """ updates sub_total counts for the class instance based on the current dictionary counts args: ----- current: current dictionary counts sub_key: the key/value to use for the subtotals """ if not self.sub_counts.get(sub_key): self.sub_counts[sub_key] = {} for item in current: try: self.sub_counts[sub_key][item] += 1 except KeyError: self.sub_counts[sub_key][item] = 1
[ "def", "update_subtotals", "(", "self", ",", "current", ",", "sub_key", ")", ":", "if", "not", "self", ".", "sub_counts", ".", "get", "(", "sub_key", ")", ":", "self", ".", "sub_counts", "[", "sub_key", "]", "=", "{", "}", "for", "item", "in", "current", ":", "try", ":", "self", ".", "sub_counts", "[", "sub_key", "]", "[", "item", "]", "+=", "1", "except", "KeyError", ":", "self", ".", "sub_counts", "[", "sub_key", "]", "[", "item", "]", "=", "1" ]
updates sub_total counts for the class instance based on the current dictionary counts args: ----- current: current dictionary counts sub_key: the key/value to use for the subtotals
[ "updates", "sub_total", "counts", "for", "the", "class", "instance", "based", "on", "the", "current", "dictionary", "counts" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/statistics.py#L159-L176
249,764
KnowledgeLinks/rdfframework
rdfframework/utilities/statistics.py
DictionaryCounter.print
def print(self): """ prints to terminal the summray statistics """ print("TOTALS -------------------------------------------") print(json.dumps(self.counts, indent=4, sort_keys=True)) if self.sub_total: print("\nSUB TOTALS --- based on '%s' ---------" % self.sub_total) print(json.dumps(self.sub_counts, indent=4, sort_keys=True)) if self.list_blank: print("\nMISSING nodes for '%s':" % self.list_blank, len(self.blank))
python
def print(self): """ prints to terminal the summray statistics """ print("TOTALS -------------------------------------------") print(json.dumps(self.counts, indent=4, sort_keys=True)) if self.sub_total: print("\nSUB TOTALS --- based on '%s' ---------" % self.sub_total) print(json.dumps(self.sub_counts, indent=4, sort_keys=True)) if self.list_blank: print("\nMISSING nodes for '%s':" % self.list_blank, len(self.blank))
[ "def", "print", "(", "self", ")", ":", "print", "(", "\"TOTALS -------------------------------------------\"", ")", "print", "(", "json", ".", "dumps", "(", "self", ".", "counts", ",", "indent", "=", "4", ",", "sort_keys", "=", "True", ")", ")", "if", "self", ".", "sub_total", ":", "print", "(", "\"\\nSUB TOTALS --- based on '%s' ---------\"", "%", "self", ".", "sub_total", ")", "print", "(", "json", ".", "dumps", "(", "self", ".", "sub_counts", ",", "indent", "=", "4", ",", "sort_keys", "=", "True", ")", ")", "if", "self", ".", "list_blank", ":", "print", "(", "\"\\nMISSING nodes for '%s':\"", "%", "self", ".", "list_blank", ",", "len", "(", "self", ".", "blank", ")", ")" ]
prints to terminal the summray statistics
[ "prints", "to", "terminal", "the", "summray", "statistics" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/statistics.py#L178-L189
249,765
daknuett/py_register_machine2
tools/assembler/assembler.py
Assembler.add_ref
def add_ref(self, wordlist): """ Adds a reference. """ refname = wordlist[0][:-1] if(refname in self.refs): raise ReferenceError("[line {}]:{} already defined here (word) {} (line) {}".format(self.line_count, refname, self.refs[refname][0], self.refs[refname][1])) self.refs[refname] = (self.word_count, self.line_count)
python
def add_ref(self, wordlist): """ Adds a reference. """ refname = wordlist[0][:-1] if(refname in self.refs): raise ReferenceError("[line {}]:{} already defined here (word) {} (line) {}".format(self.line_count, refname, self.refs[refname][0], self.refs[refname][1])) self.refs[refname] = (self.word_count, self.line_count)
[ "def", "add_ref", "(", "self", ",", "wordlist", ")", ":", "refname", "=", "wordlist", "[", "0", "]", "[", ":", "-", "1", "]", "if", "(", "refname", "in", "self", ".", "refs", ")", ":", "raise", "ReferenceError", "(", "\"[line {}]:{} already defined here (word) {} (line) {}\"", ".", "format", "(", "self", ".", "line_count", ",", "refname", ",", "self", ".", "refs", "[", "refname", "]", "[", "0", "]", ",", "self", ".", "refs", "[", "refname", "]", "[", "1", "]", ")", ")", "self", ".", "refs", "[", "refname", "]", "=", "(", "self", ".", "word_count", ",", "self", ".", "line_count", ")" ]
Adds a reference.
[ "Adds", "a", "reference", "." ]
599c53cd7576297d0d7a53344ed5d9aa98acc751
https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/tools/assembler/assembler.py#L117-L126
249,766
daknuett/py_register_machine2
tools/assembler/assembler.py
Assembler.checkargs
def checkargs(self, lineno, command, args): """ Check if the arguments fit the requirements of the command. Raises ArgumentError_, if an argument does not fit. """ for wanted, arg in zip(command.argtypes(), args): wanted = wanted.type_ if(wanted == "register" and (not arg in self.register)): raise ArgumentError("[line {}]: Command '{}' wants argument of type register, but {} is not a register".format(lineno, command.mnemonic(), arg)) if(wanted == "const" and (arg in self.register)): raise ArgumentError("[line {}]: Command '{}' wants argument of type const, but {} is a register.".format(lineno, command.mnemonic(), arg))
python
def checkargs(self, lineno, command, args): """ Check if the arguments fit the requirements of the command. Raises ArgumentError_, if an argument does not fit. """ for wanted, arg in zip(command.argtypes(), args): wanted = wanted.type_ if(wanted == "register" and (not arg in self.register)): raise ArgumentError("[line {}]: Command '{}' wants argument of type register, but {} is not a register".format(lineno, command.mnemonic(), arg)) if(wanted == "const" and (arg in self.register)): raise ArgumentError("[line {}]: Command '{}' wants argument of type const, but {} is a register.".format(lineno, command.mnemonic(), arg))
[ "def", "checkargs", "(", "self", ",", "lineno", ",", "command", ",", "args", ")", ":", "for", "wanted", ",", "arg", "in", "zip", "(", "command", ".", "argtypes", "(", ")", ",", "args", ")", ":", "wanted", "=", "wanted", ".", "type_", "if", "(", "wanted", "==", "\"register\"", "and", "(", "not", "arg", "in", "self", ".", "register", ")", ")", ":", "raise", "ArgumentError", "(", "\"[line {}]: Command '{}' wants argument of type register, but {} is not a register\"", ".", "format", "(", "lineno", ",", "command", ".", "mnemonic", "(", ")", ",", "arg", ")", ")", "if", "(", "wanted", "==", "\"const\"", "and", "(", "arg", "in", "self", ".", "register", ")", ")", ":", "raise", "ArgumentError", "(", "\"[line {}]: Command '{}' wants argument of type const, but {} is a register.\"", ".", "format", "(", "lineno", ",", "command", ".", "mnemonic", "(", ")", ",", "arg", ")", ")" ]
Check if the arguments fit the requirements of the command. Raises ArgumentError_, if an argument does not fit.
[ "Check", "if", "the", "arguments", "fit", "the", "requirements", "of", "the", "command", "." ]
599c53cd7576297d0d7a53344ed5d9aa98acc751
https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/tools/assembler/assembler.py#L181-L192
249,767
daknuett/py_register_machine2
tools/assembler/assembler.py
Assembler.convert_args
def convert_args(self, command, args): """ Converts ``str -> int`` or ``register -> int``. """ for wanted, arg in zip(command.argtypes(), args): wanted = wanted.type_ if(wanted == "const"): try: yield to_int(arg) except: if(arg in self.processor.constants): yield self.processor.constants[arg] else: yield arg if(wanted == "register"): yield self.register_indices[arg]
python
def convert_args(self, command, args): """ Converts ``str -> int`` or ``register -> int``. """ for wanted, arg in zip(command.argtypes(), args): wanted = wanted.type_ if(wanted == "const"): try: yield to_int(arg) except: if(arg in self.processor.constants): yield self.processor.constants[arg] else: yield arg if(wanted == "register"): yield self.register_indices[arg]
[ "def", "convert_args", "(", "self", ",", "command", ",", "args", ")", ":", "for", "wanted", ",", "arg", "in", "zip", "(", "command", ".", "argtypes", "(", ")", ",", "args", ")", ":", "wanted", "=", "wanted", ".", "type_", "if", "(", "wanted", "==", "\"const\"", ")", ":", "try", ":", "yield", "to_int", "(", "arg", ")", "except", ":", "if", "(", "arg", "in", "self", ".", "processor", ".", "constants", ")", ":", "yield", "self", ".", "processor", ".", "constants", "[", "arg", "]", "else", ":", "yield", "arg", "if", "(", "wanted", "==", "\"register\"", ")", ":", "yield", "self", ".", "register_indices", "[", "arg", "]" ]
Converts ``str -> int`` or ``register -> int``.
[ "Converts", "str", "-", ">", "int", "or", "register", "-", ">", "int", "." ]
599c53cd7576297d0d7a53344ed5d9aa98acc751
https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/tools/assembler/assembler.py#L194-L210
249,768
minhhoit/yacms
yacms/utils/models.py
upload_to
def upload_to(field_path, default): """ Used as the ``upload_to`` arg for file fields - allows for custom handlers to be implemented on a per field basis defined by the ``UPLOAD_TO_HANDLERS`` setting. """ from yacms.conf import settings for k, v in settings.UPLOAD_TO_HANDLERS.items(): if k.lower() == field_path.lower(): return import_dotted_path(v) return default
python
def upload_to(field_path, default): """ Used as the ``upload_to`` arg for file fields - allows for custom handlers to be implemented on a per field basis defined by the ``UPLOAD_TO_HANDLERS`` setting. """ from yacms.conf import settings for k, v in settings.UPLOAD_TO_HANDLERS.items(): if k.lower() == field_path.lower(): return import_dotted_path(v) return default
[ "def", "upload_to", "(", "field_path", ",", "default", ")", ":", "from", "yacms", ".", "conf", "import", "settings", "for", "k", ",", "v", "in", "settings", ".", "UPLOAD_TO_HANDLERS", ".", "items", "(", ")", ":", "if", "k", ".", "lower", "(", ")", "==", "field_path", ".", "lower", "(", ")", ":", "return", "import_dotted_path", "(", "v", ")", "return", "default" ]
Used as the ``upload_to`` arg for file fields - allows for custom handlers to be implemented on a per field basis defined by the ``UPLOAD_TO_HANDLERS`` setting.
[ "Used", "as", "the", "upload_to", "arg", "for", "file", "fields", "-", "allows", "for", "custom", "handlers", "to", "be", "implemented", "on", "a", "per", "field", "basis", "defined", "by", "the", "UPLOAD_TO_HANDLERS", "setting", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/models.py#L81-L91
249,769
daknuett/py_register_machine2
core/register.py
StreamIORegister.read
def read(self): """ Read a ``str`` from ``open_stream_in`` and convert it to an integer using ``ord``. The result will be truncated according to Integer_. """ self.repr_.setvalue(ord(self.open_stream_in.read(1))) return self.value.getvalue()
python
def read(self): """ Read a ``str`` from ``open_stream_in`` and convert it to an integer using ``ord``. The result will be truncated according to Integer_. """ self.repr_.setvalue(ord(self.open_stream_in.read(1))) return self.value.getvalue()
[ "def", "read", "(", "self", ")", ":", "self", ".", "repr_", ".", "setvalue", "(", "ord", "(", "self", ".", "open_stream_in", ".", "read", "(", "1", ")", ")", ")", "return", "self", ".", "value", ".", "getvalue", "(", ")" ]
Read a ``str`` from ``open_stream_in`` and convert it to an integer using ``ord``. The result will be truncated according to Integer_.
[ "Read", "a", "str", "from", "open_stream_in", "and", "convert", "it", "to", "an", "integer", "using", "ord", ".", "The", "result", "will", "be", "truncated", "according", "to", "Integer_", "." ]
599c53cd7576297d0d7a53344ed5d9aa98acc751
https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/core/register.py#L67-L73
249,770
daknuett/py_register_machine2
core/register.py
BStreamIORegister.write
def write(self, word): """ Converts the ``int`` ``word`` to a ``bytes`` object and writes them to ``open_stream_out``. See ``int_to_bytes``. """ bytes_ = int_to_bytes(word, self.width) self.open_stream_out.write(bytes_)
python
def write(self, word): """ Converts the ``int`` ``word`` to a ``bytes`` object and writes them to ``open_stream_out``. See ``int_to_bytes``. """ bytes_ = int_to_bytes(word, self.width) self.open_stream_out.write(bytes_)
[ "def", "write", "(", "self", ",", "word", ")", ":", "bytes_", "=", "int_to_bytes", "(", "word", ",", "self", ".", "width", ")", "self", ".", "open_stream_out", ".", "write", "(", "bytes_", ")" ]
Converts the ``int`` ``word`` to a ``bytes`` object and writes them to ``open_stream_out``. See ``int_to_bytes``.
[ "Converts", "the", "int", "word", "to", "a", "bytes", "object", "and", "writes", "them", "to", "open_stream_out", "." ]
599c53cd7576297d0d7a53344ed5d9aa98acc751
https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/core/register.py#L109-L117
249,771
jmatt/threepio
threepio/__init__.py
initialize
def initialize(logger_name=LOGGER_NAME, log_filename=LOG_FILENAME, app_logging_level=APP_LOGGING_LEVEL, dep_logging_level=DEP_LOGGING_LEVEL, format=None, logger_class=None, handlers=[], global_logger=True): """ Constructs and initializes a `logging.Logger` object. Returns :class:`logging.Logger` object. :param logger_name: name of the new logger. :param log_filename: The log file location :class:`str` or None. :param app_logging_level: The logging level to use for the application. :param dep_logging_level: The logging level to use for dependencies. :param format: The format string to use :class: `str` or None. :param logger_class: The logger class to use :param handlers: List of handler instances to add. :param global_logger: If true set threepio's global logger variable to this logger. """ # If there is no format, use a default format. if not format: format = "%(asctime)s %(name)s-%(levelname)s "\ + "[%(pathname)s %(lineno)d] %(message)s" formatter = logging.Formatter(format) # Setup the root logging for dependencies, etc. if log_filename: logging.basicConfig( level=dep_logging_level, format=format, filename=log_filename, filemode='a+') else: logging.basicConfig( level=dep_logging_level, format=format) # Setup and add separate application logging. if logger_class: original_class = logging.getLoggerClass() logging.setLoggerClass(logger_class) new_logger = logging.getLogger(logger_name) logging.setLoggerClass(original_class) else: new_logger = logging.getLogger(logger_name) # Set the app logging level. new_logger.setLevel(app_logging_level) # required to get level to apply. # Set the global_logger by default. if global_logger: global logger logger = new_logger for handler in handlers: handler.setFormatter(formatter) handler.setLevel(app_logging_level) new_logger.addHandler(handler) return new_logger
python
def initialize(logger_name=LOGGER_NAME, log_filename=LOG_FILENAME, app_logging_level=APP_LOGGING_LEVEL, dep_logging_level=DEP_LOGGING_LEVEL, format=None, logger_class=None, handlers=[], global_logger=True): """ Constructs and initializes a `logging.Logger` object. Returns :class:`logging.Logger` object. :param logger_name: name of the new logger. :param log_filename: The log file location :class:`str` or None. :param app_logging_level: The logging level to use for the application. :param dep_logging_level: The logging level to use for dependencies. :param format: The format string to use :class: `str` or None. :param logger_class: The logger class to use :param handlers: List of handler instances to add. :param global_logger: If true set threepio's global logger variable to this logger. """ # If there is no format, use a default format. if not format: format = "%(asctime)s %(name)s-%(levelname)s "\ + "[%(pathname)s %(lineno)d] %(message)s" formatter = logging.Formatter(format) # Setup the root logging for dependencies, etc. if log_filename: logging.basicConfig( level=dep_logging_level, format=format, filename=log_filename, filemode='a+') else: logging.basicConfig( level=dep_logging_level, format=format) # Setup and add separate application logging. if logger_class: original_class = logging.getLoggerClass() logging.setLoggerClass(logger_class) new_logger = logging.getLogger(logger_name) logging.setLoggerClass(original_class) else: new_logger = logging.getLogger(logger_name) # Set the app logging level. new_logger.setLevel(app_logging_level) # required to get level to apply. # Set the global_logger by default. if global_logger: global logger logger = new_logger for handler in handlers: handler.setFormatter(formatter) handler.setLevel(app_logging_level) new_logger.addHandler(handler) return new_logger
[ "def", "initialize", "(", "logger_name", "=", "LOGGER_NAME", ",", "log_filename", "=", "LOG_FILENAME", ",", "app_logging_level", "=", "APP_LOGGING_LEVEL", ",", "dep_logging_level", "=", "DEP_LOGGING_LEVEL", ",", "format", "=", "None", ",", "logger_class", "=", "None", ",", "handlers", "=", "[", "]", ",", "global_logger", "=", "True", ")", ":", "# If there is no format, use a default format.", "if", "not", "format", ":", "format", "=", "\"%(asctime)s %(name)s-%(levelname)s \"", "+", "\"[%(pathname)s %(lineno)d] %(message)s\"", "formatter", "=", "logging", ".", "Formatter", "(", "format", ")", "# Setup the root logging for dependencies, etc.", "if", "log_filename", ":", "logging", ".", "basicConfig", "(", "level", "=", "dep_logging_level", ",", "format", "=", "format", ",", "filename", "=", "log_filename", ",", "filemode", "=", "'a+'", ")", "else", ":", "logging", ".", "basicConfig", "(", "level", "=", "dep_logging_level", ",", "format", "=", "format", ")", "# Setup and add separate application logging.", "if", "logger_class", ":", "original_class", "=", "logging", ".", "getLoggerClass", "(", ")", "logging", ".", "setLoggerClass", "(", "logger_class", ")", "new_logger", "=", "logging", ".", "getLogger", "(", "logger_name", ")", "logging", ".", "setLoggerClass", "(", "original_class", ")", "else", ":", "new_logger", "=", "logging", ".", "getLogger", "(", "logger_name", ")", "# Set the app logging level.", "new_logger", ".", "setLevel", "(", "app_logging_level", ")", "# required to get level to apply.", "# Set the global_logger by default.", "if", "global_logger", ":", "global", "logger", "logger", "=", "new_logger", "for", "handler", "in", "handlers", ":", "handler", ".", "setFormatter", "(", "formatter", ")", "handler", ".", "setLevel", "(", "app_logging_level", ")", "new_logger", ".", "addHandler", "(", "handler", ")", "return", "new_logger" ]
Constructs and initializes a `logging.Logger` object. Returns :class:`logging.Logger` object. :param logger_name: name of the new logger. :param log_filename: The log file location :class:`str` or None. :param app_logging_level: The logging level to use for the application. :param dep_logging_level: The logging level to use for dependencies. :param format: The format string to use :class: `str` or None. :param logger_class: The logger class to use :param handlers: List of handler instances to add. :param global_logger: If true set threepio's global logger variable to this logger.
[ "Constructs", "and", "initializes", "a", "logging", ".", "Logger", "object", "." ]
91e2835c85c1618fcc4a1357dbb398353e662d1a
https://github.com/jmatt/threepio/blob/91e2835c85c1618fcc4a1357dbb398353e662d1a/threepio/__init__.py#L32-L93
249,772
20tab/twentytab-tree
tree/utility.py
getUrlList
def getUrlList(): """ This function get the Page List from the DB and return the tuple to use in the urls.py, urlpatterns """ """ IF YOU WANT REBUILD YOUR STRUCTURE UNCOMMENT THE FOLLOWING LINE """ #Node.rebuild() set_to_return = [] set_url = [] roots = Node.objects.filter(parent__isnull=True) for root in roots: nodes = root.get_descendants() for node in nodes: if node.page: page = node.page view = page.view regex = r'^{0}$'.format(node.get_pattern()) regex_path = '{0}'.format(node.get_pattern()) view = u'{0}.{1}.{2}'.format(view.app_name, view.module_name, view.func_name) """ check_static_vars add UPY_CONTEXT to page """ page.check_static_vars(node) app_url = url(regex, view, page.static_vars, page.scheme_name) set_to_return.append(app_url) set_url.append(regex_path) if node.is_index: regex = r'^$' regex_path = '' app_url = url(regex, view, page.static_vars, page.scheme_name) set_to_return.append(app_url) set_url.append(regex_path) return set_to_return, set_url
python
def getUrlList(): """ This function get the Page List from the DB and return the tuple to use in the urls.py, urlpatterns """ """ IF YOU WANT REBUILD YOUR STRUCTURE UNCOMMENT THE FOLLOWING LINE """ #Node.rebuild() set_to_return = [] set_url = [] roots = Node.objects.filter(parent__isnull=True) for root in roots: nodes = root.get_descendants() for node in nodes: if node.page: page = node.page view = page.view regex = r'^{0}$'.format(node.get_pattern()) regex_path = '{0}'.format(node.get_pattern()) view = u'{0}.{1}.{2}'.format(view.app_name, view.module_name, view.func_name) """ check_static_vars add UPY_CONTEXT to page """ page.check_static_vars(node) app_url = url(regex, view, page.static_vars, page.scheme_name) set_to_return.append(app_url) set_url.append(regex_path) if node.is_index: regex = r'^$' regex_path = '' app_url = url(regex, view, page.static_vars, page.scheme_name) set_to_return.append(app_url) set_url.append(regex_path) return set_to_return, set_url
[ "def", "getUrlList", "(", ")", ":", "\"\"\"\n IF YOU WANT REBUILD YOUR STRUCTURE UNCOMMENT THE FOLLOWING LINE\n \"\"\"", "#Node.rebuild()", "set_to_return", "=", "[", "]", "set_url", "=", "[", "]", "roots", "=", "Node", ".", "objects", ".", "filter", "(", "parent__isnull", "=", "True", ")", "for", "root", "in", "roots", ":", "nodes", "=", "root", ".", "get_descendants", "(", ")", "for", "node", "in", "nodes", ":", "if", "node", ".", "page", ":", "page", "=", "node", ".", "page", "view", "=", "page", ".", "view", "regex", "=", "r'^{0}$'", ".", "format", "(", "node", ".", "get_pattern", "(", ")", ")", "regex_path", "=", "'{0}'", ".", "format", "(", "node", ".", "get_pattern", "(", ")", ")", "view", "=", "u'{0}.{1}.{2}'", ".", "format", "(", "view", ".", "app_name", ",", "view", ".", "module_name", ",", "view", ".", "func_name", ")", "\"\"\"\n check_static_vars add UPY_CONTEXT to page\n \"\"\"", "page", ".", "check_static_vars", "(", "node", ")", "app_url", "=", "url", "(", "regex", ",", "view", ",", "page", ".", "static_vars", ",", "page", ".", "scheme_name", ")", "set_to_return", ".", "append", "(", "app_url", ")", "set_url", ".", "append", "(", "regex_path", ")", "if", "node", ".", "is_index", ":", "regex", "=", "r'^$'", "regex_path", "=", "''", "app_url", "=", "url", "(", "regex", ",", "view", ",", "page", ".", "static_vars", ",", "page", ".", "scheme_name", ")", "set_to_return", ".", "append", "(", "app_url", ")", "set_url", ".", "append", "(", "regex_path", ")", "return", "set_to_return", ",", "set_url" ]
This function get the Page List from the DB and return the tuple to use in the urls.py, urlpatterns
[ "This", "function", "get", "the", "Page", "List", "from", "the", "DB", "and", "return", "the", "tuple", "to", "use", "in", "the", "urls", ".", "py", "urlpatterns" ]
f2c1ced33e6c211bb52a25a7d48155e39fbdc088
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/utility.py#L9-L45
249,773
sternoru/goscalecms
goscale/utils/__init__.py
get_plugins
def get_plugins(sites=None): """ Returns all GoScale plugins It ignored all other django-cms plugins """ plugins = [] # collect GoScale plugins for plugin in CMSPlugin.objects.all(): if plugin: cl = plugin.get_plugin_class().model if 'posts' in cl._meta.get_all_field_names(): instance = plugin.get_plugin_instance()[0] plugins.append(instance) # Filter by sites if sites and len(sites) > 0: onsite = [] for plugin in plugins: try: if plugin.page.site in sites: onsite.append(plugin) except AttributeError: continue return onsite return plugins
python
def get_plugins(sites=None): """ Returns all GoScale plugins It ignored all other django-cms plugins """ plugins = [] # collect GoScale plugins for plugin in CMSPlugin.objects.all(): if plugin: cl = plugin.get_plugin_class().model if 'posts' in cl._meta.get_all_field_names(): instance = plugin.get_plugin_instance()[0] plugins.append(instance) # Filter by sites if sites and len(sites) > 0: onsite = [] for plugin in plugins: try: if plugin.page.site in sites: onsite.append(plugin) except AttributeError: continue return onsite return plugins
[ "def", "get_plugins", "(", "sites", "=", "None", ")", ":", "plugins", "=", "[", "]", "# collect GoScale plugins", "for", "plugin", "in", "CMSPlugin", ".", "objects", ".", "all", "(", ")", ":", "if", "plugin", ":", "cl", "=", "plugin", ".", "get_plugin_class", "(", ")", ".", "model", "if", "'posts'", "in", "cl", ".", "_meta", ".", "get_all_field_names", "(", ")", ":", "instance", "=", "plugin", ".", "get_plugin_instance", "(", ")", "[", "0", "]", "plugins", ".", "append", "(", "instance", ")", "# Filter by sites", "if", "sites", "and", "len", "(", "sites", ")", ">", "0", ":", "onsite", "=", "[", "]", "for", "plugin", "in", "plugins", ":", "try", ":", "if", "plugin", ".", "page", ".", "site", "in", "sites", ":", "onsite", ".", "append", "(", "plugin", ")", "except", "AttributeError", ":", "continue", "return", "onsite", "return", "plugins" ]
Returns all GoScale plugins It ignored all other django-cms plugins
[ "Returns", "all", "GoScale", "plugins" ]
7eee50357c47ebdfe3e573a8b4be3b67892d229e
https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/utils/__init__.py#L30-L54
249,774
sternoru/goscalecms
goscale/utils/__init__.py
update_plugin
def update_plugin(plugin_id): """ Updates a single plugin by ID Returns a plugin instance and posts count """ try: instance = CMSPlugin.objects.get(id=plugin_id).get_plugin_instance()[0] instance.update() except: return None, 0 return instance, instance.posts.count()
python
def update_plugin(plugin_id): """ Updates a single plugin by ID Returns a plugin instance and posts count """ try: instance = CMSPlugin.objects.get(id=plugin_id).get_plugin_instance()[0] instance.update() except: return None, 0 return instance, instance.posts.count()
[ "def", "update_plugin", "(", "plugin_id", ")", ":", "try", ":", "instance", "=", "CMSPlugin", ".", "objects", ".", "get", "(", "id", "=", "plugin_id", ")", ".", "get_plugin_instance", "(", ")", "[", "0", "]", "instance", ".", "update", "(", ")", "except", ":", "return", "None", ",", "0", "return", "instance", ",", "instance", ".", "posts", ".", "count", "(", ")" ]
Updates a single plugin by ID Returns a plugin instance and posts count
[ "Updates", "a", "single", "plugin", "by", "ID" ]
7eee50357c47ebdfe3e573a8b4be3b67892d229e
https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/utils/__init__.py#L56-L67
249,775
sternoru/goscalecms
goscale/utils/__init__.py
dict2obj
def dict2obj(d): """A helper function which convert a dict to an object. """ if isinstance(d, (list, tuple)): d = [dict2obj(x) for x in d] if not isinstance(d, dict): return d class ObjectFromDict(object): pass o = ObjectFromDict() #an object created from a dict for k in d: o.__dict__[k] = dict2obj(d[k]) return o
python
def dict2obj(d): """A helper function which convert a dict to an object. """ if isinstance(d, (list, tuple)): d = [dict2obj(x) for x in d] if not isinstance(d, dict): return d class ObjectFromDict(object): pass o = ObjectFromDict() #an object created from a dict for k in d: o.__dict__[k] = dict2obj(d[k]) return o
[ "def", "dict2obj", "(", "d", ")", ":", "if", "isinstance", "(", "d", ",", "(", "list", ",", "tuple", ")", ")", ":", "d", "=", "[", "dict2obj", "(", "x", ")", "for", "x", "in", "d", "]", "if", "not", "isinstance", "(", "d", ",", "dict", ")", ":", "return", "d", "class", "ObjectFromDict", "(", "object", ")", ":", "pass", "o", "=", "ObjectFromDict", "(", ")", "#an object created from a dict", "for", "k", "in", "d", ":", "o", ".", "__dict__", "[", "k", "]", "=", "dict2obj", "(", "d", "[", "k", "]", ")", "return", "o" ]
A helper function which convert a dict to an object.
[ "A", "helper", "function", "which", "convert", "a", "dict", "to", "an", "object", "." ]
7eee50357c47ebdfe3e573a8b4be3b67892d229e
https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/utils/__init__.py#L601-L613
249,776
sandwichcloud/ingredients.db
ingredients_db/database.py
Database._add_process_guards
def _add_process_guards(self, engine): """Add multiprocessing guards. Forces a connection to be reconnected if it is detected as having been shared to a sub-process. """ @sqlalchemy.event.listens_for(engine, "connect") def connect(dbapi_connection, connection_record): connection_record.info['pid'] = os.getpid() @sqlalchemy.event.listens_for(engine, "checkout") def checkout(dbapi_connection, connection_record, connection_proxy): pid = os.getpid() if connection_record.info['pid'] != pid: self.logger.debug( "Parent process %(orig)s forked (%(newproc)s) with an open database connection, " "which is being discarded and recreated." % {"newproc": pid, "orig": connection_record.info['pid']}) connection_record.connection = connection_proxy.connection = None raise exc.DisconnectionError( "Connection record belongs to pid %s, attempting to check out in pid %s" % ( connection_record.info['pid'], pid) )
python
def _add_process_guards(self, engine): """Add multiprocessing guards. Forces a connection to be reconnected if it is detected as having been shared to a sub-process. """ @sqlalchemy.event.listens_for(engine, "connect") def connect(dbapi_connection, connection_record): connection_record.info['pid'] = os.getpid() @sqlalchemy.event.listens_for(engine, "checkout") def checkout(dbapi_connection, connection_record, connection_proxy): pid = os.getpid() if connection_record.info['pid'] != pid: self.logger.debug( "Parent process %(orig)s forked (%(newproc)s) with an open database connection, " "which is being discarded and recreated." % {"newproc": pid, "orig": connection_record.info['pid']}) connection_record.connection = connection_proxy.connection = None raise exc.DisconnectionError( "Connection record belongs to pid %s, attempting to check out in pid %s" % ( connection_record.info['pid'], pid) )
[ "def", "_add_process_guards", "(", "self", ",", "engine", ")", ":", "@", "sqlalchemy", ".", "event", ".", "listens_for", "(", "engine", ",", "\"connect\"", ")", "def", "connect", "(", "dbapi_connection", ",", "connection_record", ")", ":", "connection_record", ".", "info", "[", "'pid'", "]", "=", "os", ".", "getpid", "(", ")", "@", "sqlalchemy", ".", "event", ".", "listens_for", "(", "engine", ",", "\"checkout\"", ")", "def", "checkout", "(", "dbapi_connection", ",", "connection_record", ",", "connection_proxy", ")", ":", "pid", "=", "os", ".", "getpid", "(", ")", "if", "connection_record", ".", "info", "[", "'pid'", "]", "!=", "pid", ":", "self", ".", "logger", ".", "debug", "(", "\"Parent process %(orig)s forked (%(newproc)s) with an open database connection, \"", "\"which is being discarded and recreated.\"", "%", "{", "\"newproc\"", ":", "pid", ",", "\"orig\"", ":", "connection_record", ".", "info", "[", "'pid'", "]", "}", ")", "connection_record", ".", "connection", "=", "connection_proxy", ".", "connection", "=", "None", "raise", "exc", ".", "DisconnectionError", "(", "\"Connection record belongs to pid %s, attempting to check out in pid %s\"", "%", "(", "connection_record", ".", "info", "[", "'pid'", "]", ",", "pid", ")", ")" ]
Add multiprocessing guards. Forces a connection to be reconnected if it is detected as having been shared to a sub-process.
[ "Add", "multiprocessing", "guards", "." ]
e91602fbece74290e051016439346fd4a3f1524e
https://github.com/sandwichcloud/ingredients.db/blob/e91602fbece74290e051016439346fd4a3f1524e/ingredients_db/database.py#L53-L76
249,777
sandwichcloud/ingredients.db
ingredients_db/database.py
Database.current
def current(self): """ Display the current database revision """ config = self.alembic_config() script = ScriptDirectory.from_config(config) revision = 'base' def display_version(rev, context): for rev in script.get_all_current(rev): nonlocal revision revision = rev.cmd_format(False) return [] with EnvironmentContext(config, script, fn=display_version): script.run_env() return revision
python
def current(self): """ Display the current database revision """ config = self.alembic_config() script = ScriptDirectory.from_config(config) revision = 'base' def display_version(rev, context): for rev in script.get_all_current(rev): nonlocal revision revision = rev.cmd_format(False) return [] with EnvironmentContext(config, script, fn=display_version): script.run_env() return revision
[ "def", "current", "(", "self", ")", ":", "config", "=", "self", ".", "alembic_config", "(", ")", "script", "=", "ScriptDirectory", ".", "from_config", "(", "config", ")", "revision", "=", "'base'", "def", "display_version", "(", "rev", ",", "context", ")", ":", "for", "rev", "in", "script", ".", "get_all_current", "(", "rev", ")", ":", "nonlocal", "revision", "revision", "=", "rev", ".", "cmd_format", "(", "False", ")", "return", "[", "]", "with", "EnvironmentContext", "(", "config", ",", "script", ",", "fn", "=", "display_version", ")", ":", "script", ".", "run_env", "(", ")", "return", "revision" ]
Display the current database revision
[ "Display", "the", "current", "database", "revision" ]
e91602fbece74290e051016439346fd4a3f1524e
https://github.com/sandwichcloud/ingredients.db/blob/e91602fbece74290e051016439346fd4a3f1524e/ingredients_db/database.py#L115-L135
249,778
sandwichcloud/ingredients.db
ingredients_db/database.py
Database.revision
def revision(self, message): """ Create a new revision file :param message: """ alembic.command.revision(self.alembic_config(), message=message)
python
def revision(self, message): """ Create a new revision file :param message: """ alembic.command.revision(self.alembic_config(), message=message)
[ "def", "revision", "(", "self", ",", "message", ")", ":", "alembic", ".", "command", ".", "revision", "(", "self", ".", "alembic_config", "(", ")", ",", "message", "=", "message", ")" ]
Create a new revision file :param message:
[ "Create", "a", "new", "revision", "file" ]
e91602fbece74290e051016439346fd4a3f1524e
https://github.com/sandwichcloud/ingredients.db/blob/e91602fbece74290e051016439346fd4a3f1524e/ingredients_db/database.py#L157-L163
249,779
clld/cdstarcat
src/cdstarcat/__main__.py
add
def add(args): """ cdstarcat add SPEC Add metadata about objects (specified by SPEC) in CDSTAR to the catalog. SPEC: Either a CDSTAR object ID or a query. """ spec = args.args[0] with _catalog(args) as cat: n = len(cat) if OBJID_PATTERN.match(spec): cat.add_objids(spec) else: results = cat.add_query(spec) args.log.info('{0} hits for query {1}'.format(results, spec)) args.log.info('{0} objects added'.format(len(cat) - n)) return len(cat) - n
python
def add(args): """ cdstarcat add SPEC Add metadata about objects (specified by SPEC) in CDSTAR to the catalog. SPEC: Either a CDSTAR object ID or a query. """ spec = args.args[0] with _catalog(args) as cat: n = len(cat) if OBJID_PATTERN.match(spec): cat.add_objids(spec) else: results = cat.add_query(spec) args.log.info('{0} hits for query {1}'.format(results, spec)) args.log.info('{0} objects added'.format(len(cat) - n)) return len(cat) - n
[ "def", "add", "(", "args", ")", ":", "spec", "=", "args", ".", "args", "[", "0", "]", "with", "_catalog", "(", "args", ")", "as", "cat", ":", "n", "=", "len", "(", "cat", ")", "if", "OBJID_PATTERN", ".", "match", "(", "spec", ")", ":", "cat", ".", "add_objids", "(", "spec", ")", "else", ":", "results", "=", "cat", ".", "add_query", "(", "spec", ")", "args", ".", "log", ".", "info", "(", "'{0} hits for query {1}'", ".", "format", "(", "results", ",", "spec", ")", ")", "args", ".", "log", ".", "info", "(", "'{0} objects added'", ".", "format", "(", "len", "(", "cat", ")", "-", "n", ")", ")", "return", "len", "(", "cat", ")", "-", "n" ]
cdstarcat add SPEC Add metadata about objects (specified by SPEC) in CDSTAR to the catalog. SPEC: Either a CDSTAR object ID or a query.
[ "cdstarcat", "add", "SPEC" ]
41f33f59cdde5e30835d2f3accf2d1fbe5332cab
https://github.com/clld/cdstarcat/blob/41f33f59cdde5e30835d2f3accf2d1fbe5332cab/src/cdstarcat/__main__.py#L75-L91
249,780
clld/cdstarcat
src/cdstarcat/__main__.py
create
def create(args): """ cdstarcat create PATH Create objects in CDSTAR specified by PATH. When PATH is a file, a single object (possibly with multiple bitstreams) is created; When PATH is a directory, an object will be created for each file in the directory (recursing into subdirectories). """ with _catalog(args) as cat: for fname, created, obj in cat.create(args.args[0], {}): args.log.info('{0} -> {1} object {2.id}'.format( fname, 'new' if created else 'existing', obj))
python
def create(args): """ cdstarcat create PATH Create objects in CDSTAR specified by PATH. When PATH is a file, a single object (possibly with multiple bitstreams) is created; When PATH is a directory, an object will be created for each file in the directory (recursing into subdirectories). """ with _catalog(args) as cat: for fname, created, obj in cat.create(args.args[0], {}): args.log.info('{0} -> {1} object {2.id}'.format( fname, 'new' if created else 'existing', obj))
[ "def", "create", "(", "args", ")", ":", "with", "_catalog", "(", "args", ")", "as", "cat", ":", "for", "fname", ",", "created", ",", "obj", "in", "cat", ".", "create", "(", "args", ".", "args", "[", "0", "]", ",", "{", "}", ")", ":", "args", ".", "log", ".", "info", "(", "'{0} -> {1} object {2.id}'", ".", "format", "(", "fname", ",", "'new'", "if", "created", "else", "'existing'", ",", "obj", ")", ")" ]
cdstarcat create PATH Create objects in CDSTAR specified by PATH. When PATH is a file, a single object (possibly with multiple bitstreams) is created; When PATH is a directory, an object will be created for each file in the directory (recursing into subdirectories).
[ "cdstarcat", "create", "PATH" ]
41f33f59cdde5e30835d2f3accf2d1fbe5332cab
https://github.com/clld/cdstarcat/blob/41f33f59cdde5e30835d2f3accf2d1fbe5332cab/src/cdstarcat/__main__.py#L95-L107
249,781
clld/cdstarcat
src/cdstarcat/__main__.py
delete
def delete(args): """ cdstarcat delete OID Delete an object specified by OID from CDSTAR. """ with _catalog(args) as cat: n = len(cat) cat.delete(args.args[0]) args.log.info('{0} objects deleted'.format(n - len(cat))) return n - len(cat)
python
def delete(args): """ cdstarcat delete OID Delete an object specified by OID from CDSTAR. """ with _catalog(args) as cat: n = len(cat) cat.delete(args.args[0]) args.log.info('{0} objects deleted'.format(n - len(cat))) return n - len(cat)
[ "def", "delete", "(", "args", ")", ":", "with", "_catalog", "(", "args", ")", "as", "cat", ":", "n", "=", "len", "(", "cat", ")", "cat", ".", "delete", "(", "args", ".", "args", "[", "0", "]", ")", "args", ".", "log", ".", "info", "(", "'{0} objects deleted'", ".", "format", "(", "n", "-", "len", "(", "cat", ")", ")", ")", "return", "n", "-", "len", "(", "cat", ")" ]
cdstarcat delete OID Delete an object specified by OID from CDSTAR.
[ "cdstarcat", "delete", "OID" ]
41f33f59cdde5e30835d2f3accf2d1fbe5332cab
https://github.com/clld/cdstarcat/blob/41f33f59cdde5e30835d2f3accf2d1fbe5332cab/src/cdstarcat/__main__.py#L111-L121
249,782
coghost/izen
izen/schedule.py
Scheduler.run_continuously
def run_continuously(self, interval=1): """Continuously run, while executing pending jobs at each elapsed time interval. @return cease_continuous_run: threading.Event which can be set to cease continuous run. Please note that it is *intended behavior that run_continuously() does not run missed jobs*. For example, if you've registered a job that should run every minute and you set a continuous run interval of one hour then your job won't be run 60 times at each interval but only once. """ cease_continuous_run = threading.Event() class ScheduleThread(threading.Thread): @classmethod def run(cls): while not cease_continuous_run.is_set(): self.run_pending() time.sleep(interval) continuous_thread = ScheduleThread() continuous_thread.start() return cease_continuous_run
python
def run_continuously(self, interval=1): """Continuously run, while executing pending jobs at each elapsed time interval. @return cease_continuous_run: threading.Event which can be set to cease continuous run. Please note that it is *intended behavior that run_continuously() does not run missed jobs*. For example, if you've registered a job that should run every minute and you set a continuous run interval of one hour then your job won't be run 60 times at each interval but only once. """ cease_continuous_run = threading.Event() class ScheduleThread(threading.Thread): @classmethod def run(cls): while not cease_continuous_run.is_set(): self.run_pending() time.sleep(interval) continuous_thread = ScheduleThread() continuous_thread.start() return cease_continuous_run
[ "def", "run_continuously", "(", "self", ",", "interval", "=", "1", ")", ":", "cease_continuous_run", "=", "threading", ".", "Event", "(", ")", "class", "ScheduleThread", "(", "threading", ".", "Thread", ")", ":", "@", "classmethod", "def", "run", "(", "cls", ")", ":", "while", "not", "cease_continuous_run", ".", "is_set", "(", ")", ":", "self", ".", "run_pending", "(", ")", "time", ".", "sleep", "(", "interval", ")", "continuous_thread", "=", "ScheduleThread", "(", ")", "continuous_thread", ".", "start", "(", ")", "return", "cease_continuous_run" ]
Continuously run, while executing pending jobs at each elapsed time interval. @return cease_continuous_run: threading.Event which can be set to cease continuous run. Please note that it is *intended behavior that run_continuously() does not run missed jobs*. For example, if you've registered a job that should run every minute and you set a continuous run interval of one hour then your job won't be run 60 times at each interval but only once.
[ "Continuously", "run", "while", "executing", "pending", "jobs", "at", "each", "elapsed", "time", "interval", "." ]
432db017f99dd2ba809e1ba1792145ab6510263d
https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/schedule.py#L66-L90
249,783
coghost/izen
izen/schedule.py
Job.at
def at(self, time_str): """ Schedule the job every day at a specific time. Calling this is only valid for jobs scheduled to run every N day(s). :param time_str: A string in `XX:YY` format. :return: The invoked job instance """ assert self.unit in ('days', 'hours') or self.start_day hour, minute = time_str.split(':') minute = int(minute) if self.unit == 'days' or self.start_day: hour = int(hour) assert 0 <= hour <= 23 elif self.unit == 'hours': hour = 0 assert 0 <= minute <= 59 self.at_time = datetime.time(hour, minute) return self
python
def at(self, time_str): """ Schedule the job every day at a specific time. Calling this is only valid for jobs scheduled to run every N day(s). :param time_str: A string in `XX:YY` format. :return: The invoked job instance """ assert self.unit in ('days', 'hours') or self.start_day hour, minute = time_str.split(':') minute = int(minute) if self.unit == 'days' or self.start_day: hour = int(hour) assert 0 <= hour <= 23 elif self.unit == 'hours': hour = 0 assert 0 <= minute <= 59 self.at_time = datetime.time(hour, minute) return self
[ "def", "at", "(", "self", ",", "time_str", ")", ":", "assert", "self", ".", "unit", "in", "(", "'days'", ",", "'hours'", ")", "or", "self", ".", "start_day", "hour", ",", "minute", "=", "time_str", ".", "split", "(", "':'", ")", "minute", "=", "int", "(", "minute", ")", "if", "self", ".", "unit", "==", "'days'", "or", "self", ".", "start_day", ":", "hour", "=", "int", "(", "hour", ")", "assert", "0", "<=", "hour", "<=", "23", "elif", "self", ".", "unit", "==", "'hours'", ":", "hour", "=", "0", "assert", "0", "<=", "minute", "<=", "59", "self", ".", "at_time", "=", "datetime", ".", "time", "(", "hour", ",", "minute", ")", "return", "self" ]
Schedule the job every day at a specific time. Calling this is only valid for jobs scheduled to run every N day(s). :param time_str: A string in `XX:YY` format. :return: The invoked job instance
[ "Schedule", "the", "job", "every", "day", "at", "a", "specific", "time", "." ]
432db017f99dd2ba809e1ba1792145ab6510263d
https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/schedule.py#L340-L360
249,784
flo-compbio/gopca-server
gpserver/job.py
GSJob.update_status
def update_status(self): """ returns True if status has changed """ # this function should be part of the server if (self.status is not None) and self.status > 0: # status is already final return False old_status = self.status job_dir = self.run_dir + os.sep + self.id if os.path.isfile(run_dir + os.sep + 'FAILURE'): self.status = self.FAILED elif os.path.isfile(run_dir + os.sep + 'FINISHED'): self.status = self.FINISHED else: self.status = self.RUNNING if self.status != old_status: return True else: return False
python
def update_status(self): """ returns True if status has changed """ # this function should be part of the server if (self.status is not None) and self.status > 0: # status is already final return False old_status = self.status job_dir = self.run_dir + os.sep + self.id if os.path.isfile(run_dir + os.sep + 'FAILURE'): self.status = self.FAILED elif os.path.isfile(run_dir + os.sep + 'FINISHED'): self.status = self.FINISHED else: self.status = self.RUNNING if self.status != old_status: return True else: return False
[ "def", "update_status", "(", "self", ")", ":", "# this function should be part of the server", "if", "(", "self", ".", "status", "is", "not", "None", ")", "and", "self", ".", "status", ">", "0", ":", "# status is already final", "return", "False", "old_status", "=", "self", ".", "status", "job_dir", "=", "self", ".", "run_dir", "+", "os", ".", "sep", "+", "self", ".", "id", "if", "os", ".", "path", ".", "isfile", "(", "run_dir", "+", "os", ".", "sep", "+", "'FAILURE'", ")", ":", "self", ".", "status", "=", "self", ".", "FAILED", "elif", "os", ".", "path", ".", "isfile", "(", "run_dir", "+", "os", ".", "sep", "+", "'FINISHED'", ")", ":", "self", ".", "status", "=", "self", ".", "FINISHED", "else", ":", "self", ".", "status", "=", "self", ".", "RUNNING", "if", "self", ".", "status", "!=", "old_status", ":", "return", "True", "else", ":", "return", "False" ]
returns True if status has changed
[ "returns", "True", "if", "status", "has", "changed" ]
4fe396b12c39c0f156ce3bc4538cade54c9d7ffe
https://github.com/flo-compbio/gopca-server/blob/4fe396b12c39c0f156ce3bc4538cade54c9d7ffe/gpserver/job.py#L145-L167
249,785
carlosp420/primer-designer
primer_designer/utils.py
is_fasta
def is_fasta(filename): """Check if filename is FASTA based on extension Return: Boolean """ if re.search("\.fa*s[ta]*$", filename, flags=re.I): return True elif re.search("\.fa$", filename, flags=re.I): return True else: return False
python
def is_fasta(filename): """Check if filename is FASTA based on extension Return: Boolean """ if re.search("\.fa*s[ta]*$", filename, flags=re.I): return True elif re.search("\.fa$", filename, flags=re.I): return True else: return False
[ "def", "is_fasta", "(", "filename", ")", ":", "if", "re", ".", "search", "(", "\"\\.fa*s[ta]*$\"", ",", "filename", ",", "flags", "=", "re", ".", "I", ")", ":", "return", "True", "elif", "re", ".", "search", "(", "\"\\.fa$\"", ",", "filename", ",", "flags", "=", "re", ".", "I", ")", ":", "return", "True", "else", ":", "return", "False" ]
Check if filename is FASTA based on extension Return: Boolean
[ "Check", "if", "filename", "is", "FASTA", "based", "on", "extension" ]
586cb7fecf41fedbffe6563c8b79a3156c6066ae
https://github.com/carlosp420/primer-designer/blob/586cb7fecf41fedbffe6563c8b79a3156c6066ae/primer_designer/utils.py#L4-L15
249,786
mlaprise/genSpline
genSpline/genSpline.py
IndividualReal.plotGene
def plotGene(self): ''' Plot the gene ''' pl.plot(self.x, self.y, '.') pl.grid(True) pl.show()
python
def plotGene(self): ''' Plot the gene ''' pl.plot(self.x, self.y, '.') pl.grid(True) pl.show()
[ "def", "plotGene", "(", "self", ")", ":", "pl", ".", "plot", "(", "self", ".", "x", ",", "self", ".", "y", ",", "'.'", ")", "pl", ".", "grid", "(", "True", ")", "pl", ".", "show", "(", ")" ]
Plot the gene
[ "Plot", "the", "gene" ]
cedfb45bd6afde47042dd71292549493f27cd136
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L100-L106
249,787
mlaprise/genSpline
genSpline/genSpline.py
IndividualReal.plotIndividual
def plotIndividual(self): ''' Plot the individual ''' pl.plot(self.x_int, self.y_int) pl.grid(True) pl.show()
python
def plotIndividual(self): ''' Plot the individual ''' pl.plot(self.x_int, self.y_int) pl.grid(True) pl.show()
[ "def", "plotIndividual", "(", "self", ")", ":", "pl", ".", "plot", "(", "self", ".", "x_int", ",", "self", ".", "y_int", ")", "pl", ".", "grid", "(", "True", ")", "pl", ".", "show", "(", ")" ]
Plot the individual
[ "Plot", "the", "individual" ]
cedfb45bd6afde47042dd71292549493f27cd136
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L108-L114
249,788
mlaprise/genSpline
genSpline/genSpline.py
IndividualReal.plot
def plot(self): ''' Plot the individual and the gene ''' pl.plot(self.x, self.y, '.') pl.plot(self.x_int, self.y_int) pl.grid(True) pl.show()
python
def plot(self): ''' Plot the individual and the gene ''' pl.plot(self.x, self.y, '.') pl.plot(self.x_int, self.y_int) pl.grid(True) pl.show()
[ "def", "plot", "(", "self", ")", ":", "pl", ".", "plot", "(", "self", ".", "x", ",", "self", ".", "y", ",", "'.'", ")", "pl", ".", "plot", "(", "self", ".", "x_int", ",", "self", ".", "y_int", ")", "pl", ".", "grid", "(", "True", ")", "pl", ".", "show", "(", ")" ]
Plot the individual and the gene
[ "Plot", "the", "individual", "and", "the", "gene" ]
cedfb45bd6afde47042dd71292549493f27cd136
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L116-L123
249,789
mlaprise/genSpline
genSpline/genSpline.py
IndividualReal.mutation
def mutation(self, strength = 0.1): ''' Single gene mutation ''' mutStrengthReal = strength mutMaxSizeReal = self.gLength/2 mutSizeReal = int(numpy.random.random_integers(1,mutMaxSizeReal)) mutationPosReal = int(numpy.random.random_integers(0+mutSizeReal-1,self.y.shape[0]-1-mutSizeReal)) mutationSignReal = pl.rand() mutationReal = pl.rand() if mutationSignReal > 0.5: for i in range(-mutSizeReal/2, mutSizeReal/2): self.y.real[mutationPosReal+i] = self.y.real[mutationPosReal+i] + mutStrengthReal*self.y.real[mutationPosReal+i]*mutationReal else: for i in range(-mutSizeReal/2, mutSizeReal/2): self.y.real[mutationPosReal+i] = self.y.real[mutationPosReal+i] - mutStrengthReal*self.y.real[mutationPosReal+i]*mutationReal self.birth()
python
def mutation(self, strength = 0.1): ''' Single gene mutation ''' mutStrengthReal = strength mutMaxSizeReal = self.gLength/2 mutSizeReal = int(numpy.random.random_integers(1,mutMaxSizeReal)) mutationPosReal = int(numpy.random.random_integers(0+mutSizeReal-1,self.y.shape[0]-1-mutSizeReal)) mutationSignReal = pl.rand() mutationReal = pl.rand() if mutationSignReal > 0.5: for i in range(-mutSizeReal/2, mutSizeReal/2): self.y.real[mutationPosReal+i] = self.y.real[mutationPosReal+i] + mutStrengthReal*self.y.real[mutationPosReal+i]*mutationReal else: for i in range(-mutSizeReal/2, mutSizeReal/2): self.y.real[mutationPosReal+i] = self.y.real[mutationPosReal+i] - mutStrengthReal*self.y.real[mutationPosReal+i]*mutationReal self.birth()
[ "def", "mutation", "(", "self", ",", "strength", "=", "0.1", ")", ":", "mutStrengthReal", "=", "strength", "mutMaxSizeReal", "=", "self", ".", "gLength", "/", "2", "mutSizeReal", "=", "int", "(", "numpy", ".", "random", ".", "random_integers", "(", "1", ",", "mutMaxSizeReal", ")", ")", "mutationPosReal", "=", "int", "(", "numpy", ".", "random", ".", "random_integers", "(", "0", "+", "mutSizeReal", "-", "1", ",", "self", ".", "y", ".", "shape", "[", "0", "]", "-", "1", "-", "mutSizeReal", ")", ")", "mutationSignReal", "=", "pl", ".", "rand", "(", ")", "mutationReal", "=", "pl", ".", "rand", "(", ")", "if", "mutationSignReal", ">", "0.5", ":", "for", "i", "in", "range", "(", "-", "mutSizeReal", "/", "2", ",", "mutSizeReal", "/", "2", ")", ":", "self", ".", "y", ".", "real", "[", "mutationPosReal", "+", "i", "]", "=", "self", ".", "y", ".", "real", "[", "mutationPosReal", "+", "i", "]", "+", "mutStrengthReal", "*", "self", ".", "y", ".", "real", "[", "mutationPosReal", "+", "i", "]", "*", "mutationReal", "else", ":", "for", "i", "in", "range", "(", "-", "mutSizeReal", "/", "2", ",", "mutSizeReal", "/", "2", ")", ":", "self", ".", "y", ".", "real", "[", "mutationPosReal", "+", "i", "]", "=", "self", ".", "y", ".", "real", "[", "mutationPosReal", "+", "i", "]", "-", "mutStrengthReal", "*", "self", ".", "y", ".", "real", "[", "mutationPosReal", "+", "i", "]", "*", "mutationReal", "self", ".", "birth", "(", ")" ]
Single gene mutation
[ "Single", "gene", "mutation" ]
cedfb45bd6afde47042dd71292549493f27cd136
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L125-L143
249,790
mlaprise/genSpline
genSpline/genSpline.py
IndividualReal.mutations
def mutations(self, nbr, strength): ''' Multiple gene mutations ''' for i in range(nbr): self.mutation(strength)
python
def mutations(self, nbr, strength): ''' Multiple gene mutations ''' for i in range(nbr): self.mutation(strength)
[ "def", "mutations", "(", "self", ",", "nbr", ",", "strength", ")", ":", "for", "i", "in", "range", "(", "nbr", ")", ":", "self", ".", "mutation", "(", "strength", ")" ]
Multiple gene mutations
[ "Multiple", "gene", "mutations" ]
cedfb45bd6afde47042dd71292549493f27cd136
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L145-L150
249,791
mlaprise/genSpline
genSpline/genSpline.py
IndividualComp.mutation
def mutation(self,strength = 0.1): ''' Single gene mutation - Complex version ''' # Mutation du gene - real mutStrengthReal = strength mutMaxSizeReal = self.gLength/2 mutSizeReal = int(numpy.random.random_integers(1,mutMaxSizeReal)) mutationPosReal = int(numpy.random.random_integers(0+mutSizeReal-1,self.y.shape[0]-1-mutSizeReal)) mutationSignReal = pl.rand() mutationReal = pl.rand() # Mutation du gene - imag mutStrengthImag = strength mutMaxSizeImag = self.gLength/2 mutSizeImag = int(numpy.random.random_integers(1,mutMaxSizeImag)) mutationPosImag = int(numpy.random.random_integers(0+mutSizeImag-1,self.y.shape[0]-1-mutSizeImag)) mutationSignImag = pl.rand() mutationImag = pl.rand() if mutationSignReal > 0.5: for i in range(-mutSizeReal/2, mutSizeReal/2): self.y.real[mutationPosReal+i] = self.y.real[mutationPosReal+i] + mutStrengthReal*self.y.real[mutationPosReal+i]*mutationReal else: for i in range(-mutSizeReal/2, mutSizeReal/2): self.y.real[mutationPosReal+i] = self.y.real[mutationPosReal+i] - mutStrengthReal*self.y.real[mutationPosReal+i]*mutationReal if mutationSignImag > 0.5: for i in range(-mutSizeImag/2, mutSizeImag/2): self.y.imag[mutationPosImag+i] = self.y.imag[mutationPosImag+i] + mutStrengthImag*self.y.imag[mutationPosImag+i]*mutationImag else: for i in range(-mutSizeImag/2, mutSizeImag/2): self.y.imag[mutationPosImag+i] = self.y.imag[mutationPosImag+i] - mutStrengthImag*self.y.imag[mutationPosImag+i]*mutationImag # Compute the individual self.birth()
python
def mutation(self,strength = 0.1): ''' Single gene mutation - Complex version ''' # Mutation du gene - real mutStrengthReal = strength mutMaxSizeReal = self.gLength/2 mutSizeReal = int(numpy.random.random_integers(1,mutMaxSizeReal)) mutationPosReal = int(numpy.random.random_integers(0+mutSizeReal-1,self.y.shape[0]-1-mutSizeReal)) mutationSignReal = pl.rand() mutationReal = pl.rand() # Mutation du gene - imag mutStrengthImag = strength mutMaxSizeImag = self.gLength/2 mutSizeImag = int(numpy.random.random_integers(1,mutMaxSizeImag)) mutationPosImag = int(numpy.random.random_integers(0+mutSizeImag-1,self.y.shape[0]-1-mutSizeImag)) mutationSignImag = pl.rand() mutationImag = pl.rand() if mutationSignReal > 0.5: for i in range(-mutSizeReal/2, mutSizeReal/2): self.y.real[mutationPosReal+i] = self.y.real[mutationPosReal+i] + mutStrengthReal*self.y.real[mutationPosReal+i]*mutationReal else: for i in range(-mutSizeReal/2, mutSizeReal/2): self.y.real[mutationPosReal+i] = self.y.real[mutationPosReal+i] - mutStrengthReal*self.y.real[mutationPosReal+i]*mutationReal if mutationSignImag > 0.5: for i in range(-mutSizeImag/2, mutSizeImag/2): self.y.imag[mutationPosImag+i] = self.y.imag[mutationPosImag+i] + mutStrengthImag*self.y.imag[mutationPosImag+i]*mutationImag else: for i in range(-mutSizeImag/2, mutSizeImag/2): self.y.imag[mutationPosImag+i] = self.y.imag[mutationPosImag+i] - mutStrengthImag*self.y.imag[mutationPosImag+i]*mutationImag # Compute the individual self.birth()
[ "def", "mutation", "(", "self", ",", "strength", "=", "0.1", ")", ":", "# Mutation du gene - real", "mutStrengthReal", "=", "strength", "mutMaxSizeReal", "=", "self", ".", "gLength", "/", "2", "mutSizeReal", "=", "int", "(", "numpy", ".", "random", ".", "random_integers", "(", "1", ",", "mutMaxSizeReal", ")", ")", "mutationPosReal", "=", "int", "(", "numpy", ".", "random", ".", "random_integers", "(", "0", "+", "mutSizeReal", "-", "1", ",", "self", ".", "y", ".", "shape", "[", "0", "]", "-", "1", "-", "mutSizeReal", ")", ")", "mutationSignReal", "=", "pl", ".", "rand", "(", ")", "mutationReal", "=", "pl", ".", "rand", "(", ")", "# Mutation du gene - imag", "mutStrengthImag", "=", "strength", "mutMaxSizeImag", "=", "self", ".", "gLength", "/", "2", "mutSizeImag", "=", "int", "(", "numpy", ".", "random", ".", "random_integers", "(", "1", ",", "mutMaxSizeImag", ")", ")", "mutationPosImag", "=", "int", "(", "numpy", ".", "random", ".", "random_integers", "(", "0", "+", "mutSizeImag", "-", "1", ",", "self", ".", "y", ".", "shape", "[", "0", "]", "-", "1", "-", "mutSizeImag", ")", ")", "mutationSignImag", "=", "pl", ".", "rand", "(", ")", "mutationImag", "=", "pl", ".", "rand", "(", ")", "if", "mutationSignReal", ">", "0.5", ":", "for", "i", "in", "range", "(", "-", "mutSizeReal", "/", "2", ",", "mutSizeReal", "/", "2", ")", ":", "self", ".", "y", ".", "real", "[", "mutationPosReal", "+", "i", "]", "=", "self", ".", "y", ".", "real", "[", "mutationPosReal", "+", "i", "]", "+", "mutStrengthReal", "*", "self", ".", "y", ".", "real", "[", "mutationPosReal", "+", "i", "]", "*", "mutationReal", "else", ":", "for", "i", "in", "range", "(", "-", "mutSizeReal", "/", "2", ",", "mutSizeReal", "/", "2", ")", ":", "self", ".", "y", ".", "real", "[", "mutationPosReal", "+", "i", "]", "=", "self", ".", "y", ".", "real", "[", "mutationPosReal", "+", "i", "]", "-", "mutStrengthReal", "*", "self", ".", "y", ".", "real", "[", "mutationPosReal", "+", "i", "]", "*", "mutationReal", "if", "mutationSignImag", ">", "0.5", ":", "for", "i", "in", "range", "(", "-", "mutSizeImag", "/", "2", ",", "mutSizeImag", "/", "2", ")", ":", "self", ".", "y", ".", "imag", "[", "mutationPosImag", "+", "i", "]", "=", "self", ".", "y", ".", "imag", "[", "mutationPosImag", "+", "i", "]", "+", "mutStrengthImag", "*", "self", ".", "y", ".", "imag", "[", "mutationPosImag", "+", "i", "]", "*", "mutationImag", "else", ":", "for", "i", "in", "range", "(", "-", "mutSizeImag", "/", "2", ",", "mutSizeImag", "/", "2", ")", ":", "self", ".", "y", ".", "imag", "[", "mutationPosImag", "+", "i", "]", "=", "self", ".", "y", ".", "imag", "[", "mutationPosImag", "+", "i", "]", "-", "mutStrengthImag", "*", "self", ".", "y", ".", "imag", "[", "mutationPosImag", "+", "i", "]", "*", "mutationImag", "# Compute the individual", "self", ".", "birth", "(", ")" ]
Single gene mutation - Complex version
[ "Single", "gene", "mutation", "-", "Complex", "version" ]
cedfb45bd6afde47042dd71292549493f27cd136
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L253-L288
249,792
mlaprise/genSpline
genSpline/genSpline.py
Population.rankingEval
def rankingEval(self): ''' Sorting the pop. base on the fitnessEval result ''' fitnessAll = numpy.zeros(self.length) fitnessNorm = numpy.zeros(self.length) for i in range(self.length): self.Ind[i].fitnessEval() fitnessAll[i] = self.Ind[i].fitness maxFitness = fitnessAll.max() for i in range(self.length): fitnessNorm[i] = (maxFitness - fitnessAll[i]) / maxFitness fitnessSorted = fitnessNorm.argsort() # Compute the selection probabilities of each individual probability = numpy.zeros(self.length) S = 2.0 for i in range(self.length): probability[fitnessSorted[i]] = ((2-S)/self.length) + (2*i*(S-1))/(self.length*(self.length-1)) self.rankingComputed = 1 self.fitness = fitnessAll return [fitnessAll, fitnessSorted[::-1], probability]
python
def rankingEval(self): ''' Sorting the pop. base on the fitnessEval result ''' fitnessAll = numpy.zeros(self.length) fitnessNorm = numpy.zeros(self.length) for i in range(self.length): self.Ind[i].fitnessEval() fitnessAll[i] = self.Ind[i].fitness maxFitness = fitnessAll.max() for i in range(self.length): fitnessNorm[i] = (maxFitness - fitnessAll[i]) / maxFitness fitnessSorted = fitnessNorm.argsort() # Compute the selection probabilities of each individual probability = numpy.zeros(self.length) S = 2.0 for i in range(self.length): probability[fitnessSorted[i]] = ((2-S)/self.length) + (2*i*(S-1))/(self.length*(self.length-1)) self.rankingComputed = 1 self.fitness = fitnessAll return [fitnessAll, fitnessSorted[::-1], probability]
[ "def", "rankingEval", "(", "self", ")", ":", "fitnessAll", "=", "numpy", ".", "zeros", "(", "self", ".", "length", ")", "fitnessNorm", "=", "numpy", ".", "zeros", "(", "self", ".", "length", ")", "for", "i", "in", "range", "(", "self", ".", "length", ")", ":", "self", ".", "Ind", "[", "i", "]", ".", "fitnessEval", "(", ")", "fitnessAll", "[", "i", "]", "=", "self", ".", "Ind", "[", "i", "]", ".", "fitness", "maxFitness", "=", "fitnessAll", ".", "max", "(", ")", "for", "i", "in", "range", "(", "self", ".", "length", ")", ":", "fitnessNorm", "[", "i", "]", "=", "(", "maxFitness", "-", "fitnessAll", "[", "i", "]", ")", "/", "maxFitness", "fitnessSorted", "=", "fitnessNorm", ".", "argsort", "(", ")", "# Compute the selection probabilities of each individual", "probability", "=", "numpy", ".", "zeros", "(", "self", ".", "length", ")", "S", "=", "2.0", "for", "i", "in", "range", "(", "self", ".", "length", ")", ":", "probability", "[", "fitnessSorted", "[", "i", "]", "]", "=", "(", "(", "2", "-", "S", ")", "/", "self", ".", "length", ")", "+", "(", "2", "*", "i", "*", "(", "S", "-", "1", ")", ")", "/", "(", "self", ".", "length", "*", "(", "self", ".", "length", "-", "1", ")", ")", "self", ".", "rankingComputed", "=", "1", "self", ".", "fitness", "=", "fitnessAll", "return", "[", "fitnessAll", ",", "fitnessSorted", "[", ":", ":", "-", "1", "]", ",", "probability", "]" ]
Sorting the pop. base on the fitnessEval result
[ "Sorting", "the", "pop", ".", "base", "on", "the", "fitnessEval", "result" ]
cedfb45bd6afde47042dd71292549493f27cd136
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L394-L418
249,793
mlaprise/genSpline
genSpline/genSpline.py
Population.sortedbyAge
def sortedbyAge(self): ''' Sorting the pop. base of the age ''' ageAll = numpy.zeros(self.length) for i in range(self.length): ageAll[i] = self.Ind[i].age ageSorted = ageAll.argsort() return ageSorted[::-1]
python
def sortedbyAge(self): ''' Sorting the pop. base of the age ''' ageAll = numpy.zeros(self.length) for i in range(self.length): ageAll[i] = self.Ind[i].age ageSorted = ageAll.argsort() return ageSorted[::-1]
[ "def", "sortedbyAge", "(", "self", ")", ":", "ageAll", "=", "numpy", ".", "zeros", "(", "self", ".", "length", ")", "for", "i", "in", "range", "(", "self", ".", "length", ")", ":", "ageAll", "[", "i", "]", "=", "self", ".", "Ind", "[", "i", "]", ".", "age", "ageSorted", "=", "ageAll", ".", "argsort", "(", ")", "return", "ageSorted", "[", ":", ":", "-", "1", "]" ]
Sorting the pop. base of the age
[ "Sorting", "the", "pop", ".", "base", "of", "the", "age" ]
cedfb45bd6afde47042dd71292549493f27cd136
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L420-L428
249,794
mlaprise/genSpline
genSpline/genSpline.py
Population.RWSelection
def RWSelection(self, mating_pool_size): ''' Make Selection of the mating pool with the roulette wheel algorithm ''' A = numpy.zeros(self.length) mating_pool = numpy.zeros(mating_pool_size) [F,S,P] = self.rankingEval() P_Sorted = numpy.zeros(self.length) for i in range(self.length): P_Sorted[i] = P[S[i]] for i in range(self.length): A[i] = P_Sorted[0:(i+1)].sum() i = 0 j = 0 while j < mating_pool_size: r = numpy.random.random() i = 0 while A[i] < r: i += 1 if numpy.shape(numpy.where(mating_pool==i))[1] == 0: mating_pool[j] =S[i] j += 1 return mating_pool
python
def RWSelection(self, mating_pool_size): ''' Make Selection of the mating pool with the roulette wheel algorithm ''' A = numpy.zeros(self.length) mating_pool = numpy.zeros(mating_pool_size) [F,S,P] = self.rankingEval() P_Sorted = numpy.zeros(self.length) for i in range(self.length): P_Sorted[i] = P[S[i]] for i in range(self.length): A[i] = P_Sorted[0:(i+1)].sum() i = 0 j = 0 while j < mating_pool_size: r = numpy.random.random() i = 0 while A[i] < r: i += 1 if numpy.shape(numpy.where(mating_pool==i))[1] == 0: mating_pool[j] =S[i] j += 1 return mating_pool
[ "def", "RWSelection", "(", "self", ",", "mating_pool_size", ")", ":", "A", "=", "numpy", ".", "zeros", "(", "self", ".", "length", ")", "mating_pool", "=", "numpy", ".", "zeros", "(", "mating_pool_size", ")", "[", "F", ",", "S", ",", "P", "]", "=", "self", ".", "rankingEval", "(", ")", "P_Sorted", "=", "numpy", ".", "zeros", "(", "self", ".", "length", ")", "for", "i", "in", "range", "(", "self", ".", "length", ")", ":", "P_Sorted", "[", "i", "]", "=", "P", "[", "S", "[", "i", "]", "]", "for", "i", "in", "range", "(", "self", ".", "length", ")", ":", "A", "[", "i", "]", "=", "P_Sorted", "[", "0", ":", "(", "i", "+", "1", ")", "]", ".", "sum", "(", ")", "i", "=", "0", "j", "=", "0", "while", "j", "<", "mating_pool_size", ":", "r", "=", "numpy", ".", "random", ".", "random", "(", ")", "i", "=", "0", "while", "A", "[", "i", "]", "<", "r", ":", "i", "+=", "1", "if", "numpy", ".", "shape", "(", "numpy", ".", "where", "(", "mating_pool", "==", "i", ")", ")", "[", "1", "]", "==", "0", ":", "mating_pool", "[", "j", "]", "=", "S", "[", "i", "]", "j", "+=", "1", "return", "mating_pool" ]
Make Selection of the mating pool with the roulette wheel algorithm
[ "Make", "Selection", "of", "the", "mating", "pool", "with", "the", "roulette", "wheel", "algorithm" ]
cedfb45bd6afde47042dd71292549493f27cd136
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L430-L457
249,795
mlaprise/genSpline
genSpline/genSpline.py
Population.SUSSelection
def SUSSelection(self, mating_pool_size): ''' Make Selection of the mating pool with the stochastic universal sampling algorithm ''' A = numpy.zeros(self.length) mating_pool = numpy.zeros(mating_pool_size) r = numpy.random.random()/float(mating_pool_size) [F,S,P] = self.rankingEval() P_Sorted = numpy.zeros(self.length) for i in range(self.length): P_Sorted[i] = P[S[i]] for i in range(self.length): A[i] = P_Sorted[0:(i+1)].sum() i = 0 j = 0 while j < mating_pool_size: i = 0 while A[i] <= r: i += 1 mating_pool[j] = S[i] j += 1 r += (1/float(mating_pool_size)) return mating_pool
python
def SUSSelection(self, mating_pool_size): ''' Make Selection of the mating pool with the stochastic universal sampling algorithm ''' A = numpy.zeros(self.length) mating_pool = numpy.zeros(mating_pool_size) r = numpy.random.random()/float(mating_pool_size) [F,S,P] = self.rankingEval() P_Sorted = numpy.zeros(self.length) for i in range(self.length): P_Sorted[i] = P[S[i]] for i in range(self.length): A[i] = P_Sorted[0:(i+1)].sum() i = 0 j = 0 while j < mating_pool_size: i = 0 while A[i] <= r: i += 1 mating_pool[j] = S[i] j += 1 r += (1/float(mating_pool_size)) return mating_pool
[ "def", "SUSSelection", "(", "self", ",", "mating_pool_size", ")", ":", "A", "=", "numpy", ".", "zeros", "(", "self", ".", "length", ")", "mating_pool", "=", "numpy", ".", "zeros", "(", "mating_pool_size", ")", "r", "=", "numpy", ".", "random", ".", "random", "(", ")", "/", "float", "(", "mating_pool_size", ")", "[", "F", ",", "S", ",", "P", "]", "=", "self", ".", "rankingEval", "(", ")", "P_Sorted", "=", "numpy", ".", "zeros", "(", "self", ".", "length", ")", "for", "i", "in", "range", "(", "self", ".", "length", ")", ":", "P_Sorted", "[", "i", "]", "=", "P", "[", "S", "[", "i", "]", "]", "for", "i", "in", "range", "(", "self", ".", "length", ")", ":", "A", "[", "i", "]", "=", "P_Sorted", "[", "0", ":", "(", "i", "+", "1", ")", "]", ".", "sum", "(", ")", "i", "=", "0", "j", "=", "0", "while", "j", "<", "mating_pool_size", ":", "i", "=", "0", "while", "A", "[", "i", "]", "<=", "r", ":", "i", "+=", "1", "mating_pool", "[", "j", "]", "=", "S", "[", "i", "]", "j", "+=", "1", "r", "+=", "(", "1", "/", "float", "(", "mating_pool_size", ")", ")", "return", "mating_pool" ]
Make Selection of the mating pool with the stochastic universal sampling algorithm
[ "Make", "Selection", "of", "the", "mating", "pool", "with", "the", "stochastic", "universal", "sampling", "algorithm" ]
cedfb45bd6afde47042dd71292549493f27cd136
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L459-L486
249,796
dstufft/storages
storages/utils.py
safe_join
def safe_join(base, *paths): """ Joins one or more path components to the base path component intelligently. Returns a normalized, absolute version of the final path. The final path must be located inside of the base path component (otherwise a ValueError is raised). """ base = base paths = [p for p in paths] final_path = abspath(os.path.join(base, *paths)) base_path = abspath(base) base_path_len = len(base_path) # Ensure final_path starts with base_path (using normcase to ensure we # don't false-negative on case insensitive operating systems like Windows) # and that the next character after the final path is os.sep (or nothing, # in which case final_path must be equal to base_path). if not os.path.normcase(final_path).startswith(os.path.normcase(base_path)) \ or final_path[base_path_len:base_path_len + 1] not in ("", os.path.sep): raise ValueError("The joined path (%s) is located outside of the base " "path component (%s)" % (final_path, base_path)) return final_path
python
def safe_join(base, *paths): """ Joins one or more path components to the base path component intelligently. Returns a normalized, absolute version of the final path. The final path must be located inside of the base path component (otherwise a ValueError is raised). """ base = base paths = [p for p in paths] final_path = abspath(os.path.join(base, *paths)) base_path = abspath(base) base_path_len = len(base_path) # Ensure final_path starts with base_path (using normcase to ensure we # don't false-negative on case insensitive operating systems like Windows) # and that the next character after the final path is os.sep (or nothing, # in which case final_path must be equal to base_path). if not os.path.normcase(final_path).startswith(os.path.normcase(base_path)) \ or final_path[base_path_len:base_path_len + 1] not in ("", os.path.sep): raise ValueError("The joined path (%s) is located outside of the base " "path component (%s)" % (final_path, base_path)) return final_path
[ "def", "safe_join", "(", "base", ",", "*", "paths", ")", ":", "base", "=", "base", "paths", "=", "[", "p", "for", "p", "in", "paths", "]", "final_path", "=", "abspath", "(", "os", ".", "path", ".", "join", "(", "base", ",", "*", "paths", ")", ")", "base_path", "=", "abspath", "(", "base", ")", "base_path_len", "=", "len", "(", "base_path", ")", "# Ensure final_path starts with base_path (using normcase to ensure we", "# don't false-negative on case insensitive operating systems like Windows)", "# and that the next character after the final path is os.sep (or nothing,", "# in which case final_path must be equal to base_path).", "if", "not", "os", ".", "path", ".", "normcase", "(", "final_path", ")", ".", "startswith", "(", "os", ".", "path", ".", "normcase", "(", "base_path", ")", ")", "or", "final_path", "[", "base_path_len", ":", "base_path_len", "+", "1", "]", "not", "in", "(", "\"\"", ",", "os", ".", "path", ".", "sep", ")", ":", "raise", "ValueError", "(", "\"The joined path (%s) is located outside of the base \"", "\"path component (%s)\"", "%", "(", "final_path", ",", "base_path", ")", ")", "return", "final_path" ]
Joins one or more path components to the base path component intelligently. Returns a normalized, absolute version of the final path. The final path must be located inside of the base path component (otherwise a ValueError is raised).
[ "Joins", "one", "or", "more", "path", "components", "to", "the", "base", "path", "component", "intelligently", ".", "Returns", "a", "normalized", "absolute", "version", "of", "the", "final", "path", "." ]
0d893afc1db32cd83eaf8e2ad4ed51b37933d5f0
https://github.com/dstufft/storages/blob/0d893afc1db32cd83eaf8e2ad4ed51b37933d5f0/storages/utils.py#L48-L70
249,797
dstufft/storages
storages/utils.py
filepath_to_uri
def filepath_to_uri(path): """ Convert an file system path to a URI portion that is suitable for inclusion in a URL. We are assuming input is either UTF-8 or unicode already. This method will encode certain chars that would normally be recognized as special chars for URIs. Note that this method does not encode the ' character, as it is a valid character within URIs. See encodeURIComponent() JavaScript function for more details. Returns an ASCII string containing the encoded result. """ if path is None: return path # I know about `os.sep` and `os.altsep` but I want to leave # some flexibility for hardcoding separators. return urllib.quote(path.replace("\\", "/"), safe=b"/~!*()'")
python
def filepath_to_uri(path): """ Convert an file system path to a URI portion that is suitable for inclusion in a URL. We are assuming input is either UTF-8 or unicode already. This method will encode certain chars that would normally be recognized as special chars for URIs. Note that this method does not encode the ' character, as it is a valid character within URIs. See encodeURIComponent() JavaScript function for more details. Returns an ASCII string containing the encoded result. """ if path is None: return path # I know about `os.sep` and `os.altsep` but I want to leave # some flexibility for hardcoding separators. return urllib.quote(path.replace("\\", "/"), safe=b"/~!*()'")
[ "def", "filepath_to_uri", "(", "path", ")", ":", "if", "path", "is", "None", ":", "return", "path", "# I know about `os.sep` and `os.altsep` but I want to leave", "# some flexibility for hardcoding separators.", "return", "urllib", ".", "quote", "(", "path", ".", "replace", "(", "\"\\\\\"", ",", "\"/\"", ")", ",", "safe", "=", "b\"/~!*()'\"", ")" ]
Convert an file system path to a URI portion that is suitable for inclusion in a URL. We are assuming input is either UTF-8 or unicode already. This method will encode certain chars that would normally be recognized as special chars for URIs. Note that this method does not encode the ' character, as it is a valid character within URIs. See encodeURIComponent() JavaScript function for more details. Returns an ASCII string containing the encoded result.
[ "Convert", "an", "file", "system", "path", "to", "a", "URI", "portion", "that", "is", "suitable", "for", "inclusion", "in", "a", "URL", "." ]
0d893afc1db32cd83eaf8e2ad4ed51b37933d5f0
https://github.com/dstufft/storages/blob/0d893afc1db32cd83eaf8e2ad4ed51b37933d5f0/storages/utils.py#L73-L92
249,798
fmd/lazyconf
lazyconf/lazyconf.py
Lazyconf.schema_file
def schema_file(self): """ Gets the full path to the file in which to load configuration schema. """ path = os.getcwd() + '/' + self.lazy_folder return path + self.schema_filename
python
def schema_file(self): """ Gets the full path to the file in which to load configuration schema. """ path = os.getcwd() + '/' + self.lazy_folder return path + self.schema_filename
[ "def", "schema_file", "(", "self", ")", ":", "path", "=", "os", ".", "getcwd", "(", ")", "+", "'/'", "+", "self", ".", "lazy_folder", "return", "path", "+", "self", ".", "schema_filename" ]
Gets the full path to the file in which to load configuration schema.
[ "Gets", "the", "full", "path", "to", "the", "file", "in", "which", "to", "load", "configuration", "schema", "." ]
78e94320c7ff2c08988df04b4e43968f0a7ae06e
https://github.com/fmd/lazyconf/blob/78e94320c7ff2c08988df04b4e43968f0a7ae06e/lazyconf/lazyconf.py#L25-L28
249,799
fmd/lazyconf
lazyconf/lazyconf.py
Lazyconf.add_ignore
def add_ignore(self): """ Writes a .gitignore file to ignore the generated data file. """ path = self.lazy_folder + self.ignore_filename # If the file exists, return. if os.path.isfile(os.path.realpath(path)): return None sp, sf = os.path.split(self.data_file) #Write the file. try: handle = open(path,'w') handle.write(sf + '\n') except IOError as e: raise e # Close the handle and return. handle.close() return None
python
def add_ignore(self): """ Writes a .gitignore file to ignore the generated data file. """ path = self.lazy_folder + self.ignore_filename # If the file exists, return. if os.path.isfile(os.path.realpath(path)): return None sp, sf = os.path.split(self.data_file) #Write the file. try: handle = open(path,'w') handle.write(sf + '\n') except IOError as e: raise e # Close the handle and return. handle.close() return None
[ "def", "add_ignore", "(", "self", ")", ":", "path", "=", "self", ".", "lazy_folder", "+", "self", ".", "ignore_filename", "# If the file exists, return.", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "realpath", "(", "path", ")", ")", ":", "return", "None", "sp", ",", "sf", "=", "os", ".", "path", ".", "split", "(", "self", ".", "data_file", ")", "#Write the file.", "try", ":", "handle", "=", "open", "(", "path", ",", "'w'", ")", "handle", ".", "write", "(", "sf", "+", "'\\n'", ")", "except", "IOError", "as", "e", ":", "raise", "e", "# Close the handle and return.", "handle", ".", "close", "(", ")", "return", "None" ]
Writes a .gitignore file to ignore the generated data file.
[ "Writes", "a", ".", "gitignore", "file", "to", "ignore", "the", "generated", "data", "file", "." ]
78e94320c7ff2c08988df04b4e43968f0a7ae06e
https://github.com/fmd/lazyconf/blob/78e94320c7ff2c08988df04b4e43968f0a7ae06e/lazyconf/lazyconf.py#L35-L54