repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
makinacorpus/django-tracking-fields
tracking_fields/decorators.py
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/decorators.py#L90-L107
def _track_class(cls, fields): """ Track fields on the specified model """ # Small tests to ensure everything is all right assert not getattr(cls, '_is_tracked', False) for field in fields: _track_class_field(cls, field) _add_signals_to_cls(cls) # Mark the class as tracked cls._is_tracked = True # Do not directly track related fields (tracked on related model) # or m2m fields (tracked by another signal) cls._tracked_fields = [ field for field in fields if '__' not in field ]
[ "def", "_track_class", "(", "cls", ",", "fields", ")", ":", "# Small tests to ensure everything is all right", "assert", "not", "getattr", "(", "cls", ",", "'_is_tracked'", ",", "False", ")", "for", "field", "in", "fields", ":", "_track_class_field", "(", "cls", ...
Track fields on the specified model
[ "Track", "fields", "on", "the", "specified", "model" ]
python
train
wtolson/gnsq
gnsq/nsqd.py
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L442-L445
def ready(self, count): """Indicate you are ready to receive ``count`` messages.""" self.ready_count = count self.send(nsq.ready(count))
[ "def", "ready", "(", "self", ",", "count", ")", ":", "self", ".", "ready_count", "=", "count", "self", ".", "send", "(", "nsq", ".", "ready", "(", "count", ")", ")" ]
Indicate you are ready to receive ``count`` messages.
[ "Indicate", "you", "are", "ready", "to", "receive", "count", "messages", "." ]
python
train
maaku/python-bitcoin
bitcoin/authtree.py
https://github.com/maaku/python-bitcoin/blob/1b80c284170fd3f547cc45f4700ce169f3f99641/bitcoin/authtree.py#L429-L440
def _forward_iterator(self): "Returns a forward iterator over the trie" path = [(self, 0, Bits())] while path: node, idx, prefix = path.pop() if idx==0 and node.value is not None and not node.prune_value: yield (self._unpickle_key(prefix), self._unpickle_value(node.value)) if idx<len(node.children): path.append((node, idx+1, prefix)) link = node.children[idx] if not link.pruned: path.append((link.node, 0, prefix + link.prefix))
[ "def", "_forward_iterator", "(", "self", ")", ":", "path", "=", "[", "(", "self", ",", "0", ",", "Bits", "(", ")", ")", "]", "while", "path", ":", "node", ",", "idx", ",", "prefix", "=", "path", ".", "pop", "(", ")", "if", "idx", "==", "0", "...
Returns a forward iterator over the trie
[ "Returns", "a", "forward", "iterator", "over", "the", "trie" ]
python
train
shmir/PyIxNetwork
ixnetwork/ixn_app.py
https://github.com/shmir/PyIxNetwork/blob/e7d7a89c08a5d3a1382b4dcfd915bbfc7eedd33f/ixnetwork/ixn_app.py#L34-L52
def init_ixn(api, logger, install_dir=None): """ Create IXN object. :param api: tcl/python/rest :type api: trafficgenerator.tgn_utils.ApiType :param logger: logger object :param install_dir: IXN installation directory :return: IXN object """ if api == ApiType.tcl: api_wrapper = IxnTclWrapper(logger, install_dir) elif api == ApiType.python: api_wrapper = IxnPythonWrapper(logger, install_dir) elif api == ApiType.rest: api_wrapper = IxnRestWrapper(logger) else: raise TgnError('{} API not supported - use Tcl, python or REST'.format(api)) return IxnApp(logger, api_wrapper)
[ "def", "init_ixn", "(", "api", ",", "logger", ",", "install_dir", "=", "None", ")", ":", "if", "api", "==", "ApiType", ".", "tcl", ":", "api_wrapper", "=", "IxnTclWrapper", "(", "logger", ",", "install_dir", ")", "elif", "api", "==", "ApiType", ".", "p...
Create IXN object. :param api: tcl/python/rest :type api: trafficgenerator.tgn_utils.ApiType :param logger: logger object :param install_dir: IXN installation directory :return: IXN object
[ "Create", "IXN", "object", "." ]
python
train
minrk/findspark
findspark.py
https://github.com/minrk/findspark/blob/20c945d5136269ca56b1341786c49087faa7c75e/findspark.py#L41-L65
def change_rc(spark_home, spark_python, py4j): """Persists changes to environment by changing shell config. Adds lines to .bashrc to set environment variables including the adding of dependencies to the system path. Will only edit this file if they already exist. Currently only works for bash. Parameters ---------- spark_home : str Path to Spark installation. spark_python : str Path to python subdirectory of Spark installation. py4j : str Path to py4j library. """ bashrc_location = os.path.expanduser("~/.bashrc") if os.path.isfile(bashrc_location): with open(bashrc_location, 'a') as bashrc: bashrc.write("\n# Added by findspark\n") bashrc.write("export SPARK_HOME=" + spark_home + "\n") bashrc.write("export PYTHONPATH=" + spark_python + ":" + py4j + ":$PYTHONPATH\n\n")
[ "def", "change_rc", "(", "spark_home", ",", "spark_python", ",", "py4j", ")", ":", "bashrc_location", "=", "os", ".", "path", ".", "expanduser", "(", "\"~/.bashrc\"", ")", "if", "os", ".", "path", ".", "isfile", "(", "bashrc_location", ")", ":", "with", ...
Persists changes to environment by changing shell config. Adds lines to .bashrc to set environment variables including the adding of dependencies to the system path. Will only edit this file if they already exist. Currently only works for bash. Parameters ---------- spark_home : str Path to Spark installation. spark_python : str Path to python subdirectory of Spark installation. py4j : str Path to py4j library.
[ "Persists", "changes", "to", "environment", "by", "changing", "shell", "config", "." ]
python
train
open-homeautomation/pknx
knxip/core.py
https://github.com/open-homeautomation/pknx/blob/a8aed8271563923c447aa330ba7c1c2927286f7a/knxip/core.py#L165-L193
def from_frame(cls, frame): """Create a KNXMessage object from the frame format.""" message = cls() # Check checksum first checksum = 0 for i in range(0, len(frame) - 1): checksum += frame[i] if (checksum % 0x100) != frame[len(frame) - 1]: raise KNXException('Checksum error in frame {}, ' 'expected {} but got {}' .format(tohex(frame), frame[len(frame) - 1], checksum % 0x100)) message.repeat = (frame[0] >> 5) & 0x01 message.priority = (frame[0] >> 2) & 0x03 message.src_addr = (frame[1] << 8) + frame[2] message.dst_addr = (frame[3] << 8) + frame[4] message.multicast = (frame[5] >> 7) message.routing = (frame[5] >> 4) & 0x03 message.length = frame[5] & 0x0f message.data = frame[6:-1] if len(message.data) + 1 != message.length: raise KNXException( 'Frame {} has not the correct length'.format(tohex(frame))) return message
[ "def", "from_frame", "(", "cls", ",", "frame", ")", ":", "message", "=", "cls", "(", ")", "# Check checksum first", "checksum", "=", "0", "for", "i", "in", "range", "(", "0", ",", "len", "(", "frame", ")", "-", "1", ")", ":", "checksum", "+=", "fra...
Create a KNXMessage object from the frame format.
[ "Create", "a", "KNXMessage", "object", "from", "the", "frame", "format", "." ]
python
train
mfitzp/padua
padua/analysis.py
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/analysis.py#L26-L48
def correlation(df, rowvar=False): """ Calculate column-wise Pearson correlations using ``numpy.ma.corrcoef`` Input data is masked to ignore NaNs when calculating correlations. Data is returned as a Pandas ``DataFrame`` of column_n x column_n dimensions, with column index copied to both axes. :param df: Pandas DataFrame :return: Pandas DataFrame (n_columns x n_columns) of column-wise correlations """ # Create a correlation matrix for all correlations # of the columns (filled with na for all values) df = df.copy() maskv = np.ma.masked_where(np.isnan(df.values), df.values) cdf = np.ma.corrcoef(maskv, rowvar=False) cdf = pd.DataFrame(np.array(cdf)) cdf.columns = df.columns cdf.index = df.columns cdf = cdf.sort_index(level=0, axis=1) cdf = cdf.sort_index(level=0) return cdf
[ "def", "correlation", "(", "df", ",", "rowvar", "=", "False", ")", ":", "# Create a correlation matrix for all correlations", "# of the columns (filled with na for all values)", "df", "=", "df", ".", "copy", "(", ")", "maskv", "=", "np", ".", "ma", ".", "masked_wher...
Calculate column-wise Pearson correlations using ``numpy.ma.corrcoef`` Input data is masked to ignore NaNs when calculating correlations. Data is returned as a Pandas ``DataFrame`` of column_n x column_n dimensions, with column index copied to both axes. :param df: Pandas DataFrame :return: Pandas DataFrame (n_columns x n_columns) of column-wise correlations
[ "Calculate", "column", "-", "wise", "Pearson", "correlations", "using", "numpy", ".", "ma", ".", "corrcoef" ]
python
train
rackerlabs/rackspace-python-neutronclient
neutronclient/v2_0/client.py
https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/v2_0/client.py#L1085-L1088
def show_lbaas_healthmonitor(self, lbaas_healthmonitor, **_params): """Fetches information for a lbaas_healthmonitor.""" return self.get(self.lbaas_healthmonitor_path % (lbaas_healthmonitor), params=_params)
[ "def", "show_lbaas_healthmonitor", "(", "self", ",", "lbaas_healthmonitor", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "get", "(", "self", ".", "lbaas_healthmonitor_path", "%", "(", "lbaas_healthmonitor", ")", ",", "params", "=", "_params", ")"...
Fetches information for a lbaas_healthmonitor.
[ "Fetches", "information", "for", "a", "lbaas_healthmonitor", "." ]
python
train
enkore/i3pystatus
i3pystatus/core/modules.py
https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/modules.py#L254-L276
def text_to_pango(self): """ Replaces all ampersands in `full_text` and `short_text` attributes of `self.output` with `&amp;`. It is called internally when pango markup is used. Can be called multiple times (`&amp;` won't change to `&amp;amp;`). """ def replace(s): s = s.split("&") out = s[0] for i in range(len(s) - 1): if s[i + 1].startswith("amp;"): out += "&" + s[i + 1] else: out += "&amp;" + s[i + 1] return out if "full_text" in self.output.keys(): self.output["full_text"] = replace(self.output["full_text"]) if "short_text" in self.output.keys(): self.output["short_text"] = replace(self.output["short_text"])
[ "def", "text_to_pango", "(", "self", ")", ":", "def", "replace", "(", "s", ")", ":", "s", "=", "s", ".", "split", "(", "\"&\"", ")", "out", "=", "s", "[", "0", "]", "for", "i", "in", "range", "(", "len", "(", "s", ")", "-", "1", ")", ":", ...
Replaces all ampersands in `full_text` and `short_text` attributes of `self.output` with `&amp;`. It is called internally when pango markup is used. Can be called multiple times (`&amp;` won't change to `&amp;amp;`).
[ "Replaces", "all", "ampersands", "in", "full_text", "and", "short_text", "attributes", "of", "self", ".", "output", "with", "&amp", ";", "." ]
python
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/build_request.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/build_request.py#L31-L37
def __x_product (property_sets): """ Return the cross-product of all elements of property_sets, less any that would contain conflicting values for single-valued features. """ assert is_iterable_typed(property_sets, property_set.PropertySet) x_product_seen = set() return __x_product_aux (property_sets, x_product_seen)[0]
[ "def", "__x_product", "(", "property_sets", ")", ":", "assert", "is_iterable_typed", "(", "property_sets", ",", "property_set", ".", "PropertySet", ")", "x_product_seen", "=", "set", "(", ")", "return", "__x_product_aux", "(", "property_sets", ",", "x_product_seen",...
Return the cross-product of all elements of property_sets, less any that would contain conflicting values for single-valued features.
[ "Return", "the", "cross", "-", "product", "of", "all", "elements", "of", "property_sets", "less", "any", "that", "would", "contain", "conflicting", "values", "for", "single", "-", "valued", "features", "." ]
python
train
opengisch/pum
pum/core/upgrader.py
https://github.com/opengisch/pum/blob/eaf6af92d723ace60b9e982d7f69b98e00606959/pum/core/upgrader.py#L429-L462
def set_baseline(self, version): """Set the baseline into the creation information table version: str The version of the current database to set in the information table. The baseline must be in the format x.x.x where x are numbers. """ pattern = re.compile(r"^\d+\.\d+\.\d+$") if not re.match(pattern, version): raise ValueError('Wrong version format') query = """ INSERT INTO {} ( version, description, type, script, checksum, installed_by, execution_time, success ) VALUES( '{}', '{}', {}, '{}', '{}', '{}', 1, TRUE ) """.format(self.upgrades_table, version, 'baseline', 0, '', '', self.__get_dbuser()) self.cursor.execute(query) self.connection.commit()
[ "def", "set_baseline", "(", "self", ",", "version", ")", ":", "pattern", "=", "re", ".", "compile", "(", "r\"^\\d+\\.\\d+\\.\\d+$\"", ")", "if", "not", "re", ".", "match", "(", "pattern", ",", "version", ")", ":", "raise", "ValueError", "(", "'Wrong versio...
Set the baseline into the creation information table version: str The version of the current database to set in the information table. The baseline must be in the format x.x.x where x are numbers.
[ "Set", "the", "baseline", "into", "the", "creation", "information", "table" ]
python
train
boriel/zxbasic
asmparse.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/asmparse.py#L1191-L1207
def p_jrjp(p): """ asm : JP expr | JR expr | CALL expr | DJNZ expr | JP pexpr | JR pexpr | CALL pexpr | DJNZ pexpr """ if p[1] in ('JR', 'DJNZ'): op = 'N' p[2] = Expr.makenode(Container('-', p.lineno(1)), p[2], Expr.makenode(Container(MEMORY.org + 2, p.lineno(1)))) else: op = 'NN' p[0] = Asm(p.lineno(1), p[1] + ' ' + op, p[2])
[ "def", "p_jrjp", "(", "p", ")", ":", "if", "p", "[", "1", "]", "in", "(", "'JR'", ",", "'DJNZ'", ")", ":", "op", "=", "'N'", "p", "[", "2", "]", "=", "Expr", ".", "makenode", "(", "Container", "(", "'-'", ",", "p", ".", "lineno", "(", "1", ...
asm : JP expr | JR expr | CALL expr | DJNZ expr | JP pexpr | JR pexpr | CALL pexpr | DJNZ pexpr
[ "asm", ":", "JP", "expr", "|", "JR", "expr", "|", "CALL", "expr", "|", "DJNZ", "expr", "|", "JP", "pexpr", "|", "JR", "pexpr", "|", "CALL", "pexpr", "|", "DJNZ", "pexpr" ]
python
train
mdgoldberg/sportsref
sportsref/nfl/pbp.py
https://github.com/mdgoldberg/sportsref/blob/09f11ac856a23c96d666d1d510bb35d6f050b5c3/sportsref/nfl/pbp.py#L361-L480
def _clean_features(struct): """Cleans up the features collected in parse_play_details. :struct: Pandas Series of features parsed from details string. :returns: the same dict, but with cleaner features (e.g., convert bools, ints, etc.) """ struct = dict(struct) # First, clean up play type bools ptypes = ['isKickoff', 'isTimeout', 'isFieldGoal', 'isPunt', 'isKneel', 'isSpike', 'isXP', 'isTwoPoint', 'isPresnapPenalty', 'isPass', 'isRun'] for pt in ptypes: struct[pt] = struct[pt] if pd.notnull(struct.get(pt)) else False # Second, clean up other existing variables on a one-off basis struct['callUpheld'] = struct.get('callUpheld') == 'upheld' struct['fgGood'] = struct.get('fgGood') == 'good' struct['isBlocked'] = struct.get('isBlocked') == 'blocked' struct['isComplete'] = struct.get('isComplete') == 'complete' struct['isFairCatch'] = struct.get('isFairCatch') == 'fair catch' struct['isMuffedCatch'] = pd.notnull(struct.get('isMuffedCatch')) struct['isNoPlay'] = ( ' (no play)' in struct['detail'] and 'penalty enforced in end zone' not in struct['detail'] if struct.get('detail') else False) struct['isOnside'] = struct.get('isOnside') == 'onside' struct['isSack'] = pd.notnull(struct.get('sackYds')) struct['isSafety'] = (struct.get('isSafety') == ', safety' or (struct.get('detail') and 'enforced in end zone, safety' in struct['detail'])) struct['isTD'] = struct.get('isTD') == ', touchdown' struct['isTouchback'] = struct.get('isTouchback') == ', touchback' struct['oob'] = pd.notnull(struct.get('oob')) struct['passLoc'] = PASS_OPTS.get(struct.get('passLoc'), np.nan) if struct['isPass']: pyds = struct['passYds'] struct['passYds'] = pyds if pd.notnull(pyds) else 0 if pd.notnull(struct['penalty']): struct['penalty'] = struct['penalty'].strip() struct['penDeclined'] = struct.get('penDeclined') == 'Declined' if struct['quarter'] == 'OT': struct['quarter'] = 5 struct['rushDir'] = RUSH_OPTS.get(struct.get('rushDir'), np.nan) if struct['isRun']: ryds = struct['rushYds'] struct['rushYds'] = ryds if pd.notnull(ryds) else 0 year = struct.get('season', np.nan) struct['timeoutTeam'] = sportsref.nfl.teams.team_ids(year).get( struct.get('timeoutTeam'), np.nan ) struct['twoPointSuccess'] = struct.get('twoPointSuccess') == 'succeeds' struct['xpGood'] = struct.get('xpGood') == 'good' # Third, ensure types are correct bool_vars = [ 'fgGood', 'isBlocked', 'isChallenge', 'isComplete', 'isFairCatch', 'isFieldGoal', 'isKickoff', 'isKneel', 'isLateral', 'isNoPlay', 'isPass', 'isPresnapPenalty', 'isPunt', 'isRun', 'isSack', 'isSafety', 'isSpike', 'isTD', 'isTimeout', 'isTouchback', 'isTwoPoint', 'isXP', 'isMuffedCatch', 'oob', 'penDeclined', 'twoPointSuccess', 'xpGood' ] int_vars = [ 'down', 'fgBlockRetYds', 'fgDist', 'fumbRecYdLine', 'fumbRetYds', 'intRetYds', 'intYdLine', 'koRetYds', 'koYds', 'muffRetYds', 'pbp_score_aw', 'pbp_score_hm', 'passYds', 'penYds', 'puntBlockRetYds', 'puntRetYds', 'puntYds', 'quarter', 'rushYds', 'sackYds', 'timeoutNum', 'ydLine', 'yds_to_go' ] float_vars = [ 'exp_pts_after', 'exp_pts_before', 'home_wp' ] string_vars = [ 'challenger', 'detail', 'fairCatcher', 'fgBlockRecoverer', 'fgBlocker', 'fgKicker', 'fieldSide', 'fumbForcer', 'fumbRecFieldSide', 'fumbRecoverer', 'fumbler', 'intFieldSide', 'interceptor', 'kneelQB', 'koKicker', 'koReturner', 'muffRecoverer', 'muffedBy', 'passLoc', 'passer', 'penOn', 'penalty', 'puntBlockRecoverer', 'puntBlocker', 'puntReturner', 'punter', 'qtr_time_remain', 'rushDir', 'rusher', 'sacker1', 'sacker2', 'spikeQB', 'tackler1', 'tackler2', 'target', 'timeoutTeam', 'xpKicker' ] for var in bool_vars: struct[var] = struct.get(var) is True for var in int_vars: try: struct[var] = int(struct.get(var)) except (ValueError, TypeError): struct[var] = np.nan for var in float_vars: try: struct[var] = float(struct.get(var)) except (ValueError, TypeError): struct[var] = np.nan for var in string_vars: if var not in struct or pd.isnull(struct[var]) or var == '': struct[var] = np.nan # Fourth, create new helper variables based on parsed variables # creating fieldSide and ydline from location if struct['isXP']: struct['fieldSide'] = struct['ydLine'] = np.nan else: fieldSide, ydline = _loc_to_features(struct.get('location')) struct['fieldSide'] = fieldSide struct['ydLine'] = ydline # creating secsElapsed (in entire game) from qtr_time_remain and quarter if pd.notnull(struct.get('qtr_time_remain')): qtr = struct['quarter'] mins, secs = map(int, struct['qtr_time_remain'].split(':')) struct['secsElapsed'] = qtr * 900 - mins * 60 - secs # creating columns for turnovers struct['isInt'] = pd.notnull(struct.get('interceptor')) struct['isFumble'] = pd.notnull(struct.get('fumbler')) # create column for isPenalty struct['isPenalty'] = pd.notnull(struct.get('penalty')) # create columns for EPA struct['team_epa'] = struct['exp_pts_after'] - struct['exp_pts_before'] struct['opp_epa'] = struct['exp_pts_before'] - struct['exp_pts_after'] return pd.Series(struct)
[ "def", "_clean_features", "(", "struct", ")", ":", "struct", "=", "dict", "(", "struct", ")", "# First, clean up play type bools", "ptypes", "=", "[", "'isKickoff'", ",", "'isTimeout'", ",", "'isFieldGoal'", ",", "'isPunt'", ",", "'isKneel'", ",", "'isSpike'", "...
Cleans up the features collected in parse_play_details. :struct: Pandas Series of features parsed from details string. :returns: the same dict, but with cleaner features (e.g., convert bools, ints, etc.)
[ "Cleans", "up", "the", "features", "collected", "in", "parse_play_details", "." ]
python
test
joyent/python-manta
manta/client.py
https://github.com/joyent/python-manta/blob/f68ef142bdbac058c981e3b28e18d77612f5b7c6/manta/client.py#L165-L220
def _request(self, path, method="GET", query=None, body=None, headers=None): """Make a Manta request ... @returns (res, content) """ assert path.startswith('/'), "bogus path: %r" % path # Presuming utf-8 encoding here for requests. Not sure if that is # technically correct. if not isinstance(path, bytes): spath = path.encode('utf-8') else: spath = path qpath = urlquote(spath) if query: qpath += '?' + urlencode(query) url = self.url + qpath http = self._get_http() ubody = body if body is not None and isinstance(body, dict): ubody = urlencode(body) if headers is None: headers = {} headers["User-Agent"] = self.user_agent if self.signer: # Signature auth. if "Date" not in headers: headers["Date"] = http_date() sigstr = 'date: ' + headers["Date"] algorithm, fingerprint, signature = self.signer.sign(sigstr.encode( 'utf-8')) auth = 'Signature keyId="/%s/keys/%s",algorithm="%s",signature="%s"'\ % ('/'.join(filter(None, [self.account, self.subuser])), fingerprint, algorithm, signature.decode('utf-8')) headers["Authorization"] = auth if self.role: headers['Role'] = self.role # python 3 try: url = url.decode('utf-8') # encoding='utf-8' except: pass return http.request(url, method, ubody, headers)
[ "def", "_request", "(", "self", ",", "path", ",", "method", "=", "\"GET\"", ",", "query", "=", "None", ",", "body", "=", "None", ",", "headers", "=", "None", ")", ":", "assert", "path", ".", "startswith", "(", "'/'", ")", ",", "\"bogus path: %r\"", "...
Make a Manta request ... @returns (res, content)
[ "Make", "a", "Manta", "request" ]
python
train
cs50/lib50
lib50/_api.py
https://github.com/cs50/lib50/blob/941767f6c0a3b81af0cdea48c25c8d5a761086eb/lib50/_api.py#L260-L306
def prepare(tool, branch, user, included): """ Prepare git for pushing Check that there are no permission errors Add necessities to git config Stage files Stage files via lfs if necessary Check that atleast one file is staged """ with ProgressBar(_("Preparing")) as progress_bar, working_area(included) as area: Git.working_area = f"-C {area}" git = Git(Git.working_area) # Clone just .git folder try: _run(git.set(Git.cache)(f"clone --bare {user.repo} .git")) except Error: raise Error(_("Looks like {} isn't enabled for your account yet. " "Go to https://cs50.me/authorize and make sure you accept any pending invitations!".format(tool))) _run(git("config --bool core.bare false")) _run(git(f"config --path core.worktree {area}")) try: _run(git("checkout --force {} .gitattributes".format(branch))) except Error: pass # Set user name/email in repo config _run(git(f"config user.email {shlex.quote(user.email)}")) _run(git(f"config user.name {shlex.quote(user.name)}")) # Switch to branch without checkout _run(git(f"symbolic-ref HEAD refs/heads/{branch}")) # Git add all included files for f in included: _run(git(f"add {f}")) # Remove gitattributes from included if Path(".gitattributes").exists() and ".gitattributes" in included: included.remove(".gitattributes") # Add any oversized files through git-lfs _lfs_add(included, git) progress_bar.stop() yield
[ "def", "prepare", "(", "tool", ",", "branch", ",", "user", ",", "included", ")", ":", "with", "ProgressBar", "(", "_", "(", "\"Preparing\"", ")", ")", "as", "progress_bar", ",", "working_area", "(", "included", ")", "as", "area", ":", "Git", ".", "work...
Prepare git for pushing Check that there are no permission errors Add necessities to git config Stage files Stage files via lfs if necessary Check that atleast one file is staged
[ "Prepare", "git", "for", "pushing", "Check", "that", "there", "are", "no", "permission", "errors", "Add", "necessities", "to", "git", "config", "Stage", "files", "Stage", "files", "via", "lfs", "if", "necessary", "Check", "that", "atleast", "one", "file", "i...
python
train
cqlengine/cqlengine
cqlengine/query.py
https://github.com/cqlengine/cqlengine/blob/7079eaf7071cbf5a045e1d1ab57f6d1b5ba3f9dc/cqlengine/query.py#L420-L461
def iff(self, *args, **kwargs): """Adds IF statements to queryset""" if len([x for x in kwargs.values() if x is None]): raise CQLEngineException("None values on iff are not allowed") clone = copy.deepcopy(self) for operator in args: if not isinstance(operator, TransactionClause): raise QueryException('{} is not a valid query operator'.format(operator)) clone._transaction.append(operator) for col_name, val in kwargs.items(): exists = False try: column = self.model._get_column(col_name) except KeyError: if col_name == 'pk__token': if not isinstance(val, Token): raise QueryException("Virtual column 'pk__token' may only be compared to Token() values") column = columns._PartitionKeysToken(self.model) quote_field = False else: raise QueryException("Can't resolve column name: '{}'".format(col_name)) if isinstance(val, Token): if col_name != 'pk__token': raise QueryException("Token() values may only be compared to the 'pk__token' virtual column") partition_columns = column.partition_columns if len(partition_columns) != len(val.value): raise QueryException( 'Token() received {} arguments but model has {} partition keys'.format( len(val.value), len(partition_columns))) val.set_columns(partition_columns) if isinstance(val, BaseQueryFunction) or exists is True: query_val = val else: query_val = column.to_database(val) clone._transaction.append(TransactionClause(col_name, query_val)) return clone
[ "def", "iff", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "[", "x", "for", "x", "in", "kwargs", ".", "values", "(", ")", "if", "x", "is", "None", "]", ")", ":", "raise", "CQLEngineException", "(", "\"None...
Adds IF statements to queryset
[ "Adds", "IF", "statements", "to", "queryset" ]
python
train
dslackw/slpkg
slpkg/pkg/manager.py
https://github.com/dslackw/slpkg/blob/dd2e08a80e944d337d157b992167ba631a4343de/slpkg/pkg/manager.py#L429-L448
def display(self): """Print the Slackware packages contents """ for pkg in self.binary: name = GetFromInstalled(pkg).name() ver = GetFromInstalled(pkg).version() find = find_package("{0}{1}{2}".format(name, ver, self.meta.sp), self.meta.pkg_path) if find: package = Utils().read_file( self.meta.pkg_path + "".join(find)) print(package) else: message = "Can't dislpay" if len(self.binary) > 1: bol = eol = "" else: bol = eol = "\n" self.msg.pkg_not_found(bol, pkg, message, eol) raise SystemExit(1)
[ "def", "display", "(", "self", ")", ":", "for", "pkg", "in", "self", ".", "binary", ":", "name", "=", "GetFromInstalled", "(", "pkg", ")", ".", "name", "(", ")", "ver", "=", "GetFromInstalled", "(", "pkg", ")", ".", "version", "(", ")", "find", "="...
Print the Slackware packages contents
[ "Print", "the", "Slackware", "packages", "contents" ]
python
train
senaite/senaite.core
bika/lims/content/batch.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/batch.py#L344-L353
def BatchLabelVocabulary(self): """Return all batch labels as a display list """ bsc = getToolByName(self, 'bika_setup_catalog') ret = [] for p in bsc(portal_type='BatchLabel', is_active=True, sort_on='sortable_title'): ret.append((p.UID, p.Title)) return DisplayList(ret)
[ "def", "BatchLabelVocabulary", "(", "self", ")", ":", "bsc", "=", "getToolByName", "(", "self", ",", "'bika_setup_catalog'", ")", "ret", "=", "[", "]", "for", "p", "in", "bsc", "(", "portal_type", "=", "'BatchLabel'", ",", "is_active", "=", "True", ",", ...
Return all batch labels as a display list
[ "Return", "all", "batch", "labels", "as", "a", "display", "list" ]
python
train
ahobsonsayers/bthomehub5-devicelist
bthomehub5_devicelist/bthomehub5_devicelist.py
https://github.com/ahobsonsayers/bthomehub5-devicelist/blob/941b553fab7ce49b0c7ff7f1e10023d0a212d455/bthomehub5_devicelist/bthomehub5_devicelist.py#L25-L39
def parse_devicelist(data_str): """Parse the BT Home Hub 5 data format.""" p = HTMLTableParser() p.feed(data_str) known_devices = p.tables[9] devices = {} for device in known_devices: if len(device) == 5 and device[2] != '': devices[device[2]] = device[1] return devices
[ "def", "parse_devicelist", "(", "data_str", ")", ":", "p", "=", "HTMLTableParser", "(", ")", "p", ".", "feed", "(", "data_str", ")", "known_devices", "=", "p", ".", "tables", "[", "9", "]", "devices", "=", "{", "}", "for", "device", "in", "known_device...
Parse the BT Home Hub 5 data format.
[ "Parse", "the", "BT", "Home", "Hub", "5", "data", "format", "." ]
python
train
delph-in/pydelphin
delphin/interfaces/base.py
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/base.py#L100-L111
def mrs(self): """ Deserialize and return an Mrs object for simplemrs or JSON-formatted MRS data; otherwise return the original string. """ mrs = self.get('mrs') if mrs is not None: if isinstance(mrs, dict): mrs = Mrs.from_dict(mrs) elif isinstance(mrs, stringtypes): mrs = simplemrs.loads_one(mrs) return mrs
[ "def", "mrs", "(", "self", ")", ":", "mrs", "=", "self", ".", "get", "(", "'mrs'", ")", "if", "mrs", "is", "not", "None", ":", "if", "isinstance", "(", "mrs", ",", "dict", ")", ":", "mrs", "=", "Mrs", ".", "from_dict", "(", "mrs", ")", "elif", ...
Deserialize and return an Mrs object for simplemrs or JSON-formatted MRS data; otherwise return the original string.
[ "Deserialize", "and", "return", "an", "Mrs", "object", "for", "simplemrs", "or", "JSON", "-", "formatted", "MRS", "data", ";", "otherwise", "return", "the", "original", "string", "." ]
python
train
CyberZHG/keras-transformer
keras_transformer/transformer.py
https://github.com/CyberZHG/keras-transformer/blob/4c42baa030539c62ef5ace92df0408b13f26d928/keras_transformer/transformer.py#L418-L461
def decode(model, tokens, start_token, end_token, pad_token, max_len=10000, max_repeat=10, max_repeat_block=10): """Decode with the given model and input tokens. :param model: The trained model. :param tokens: The input tokens of encoder. :param start_token: The token that represents the start of a sentence. :param end_token: The token that represents the end of a sentence. :param pad_token: The token that represents padding. :param max_len: Maximum length of decoded list. :param max_repeat: Maximum number of repeating blocks. :param max_repeat_block: Maximum length of the repeating block. :return: Decoded tokens. """ is_single = not isinstance(tokens[0], list) if is_single: tokens = [tokens] batch_size = len(tokens) decoder_inputs = [[start_token] for _ in range(batch_size)] outputs = [None for _ in range(batch_size)] output_len = 1 while len(list(filter(lambda x: x is None, outputs))) > 0: output_len += 1 batch_inputs, batch_outputs = [], [] max_input_len = 0 index_map = {} for i in range(batch_size): if outputs[i] is None: index_map[len(batch_inputs)] = i batch_inputs.append(tokens[i][:]) batch_outputs.append(decoder_inputs[i]) max_input_len = max(max_input_len, len(tokens[i])) for i in range(len(batch_inputs)): batch_inputs[i] += [pad_token] * (max_input_len - len(batch_inputs[i])) predicts = model.predict([np.asarray(batch_inputs), np.asarray(batch_outputs)]) for i in range(len(predicts)): last_token = np.argmax(predicts[i][-1]) decoder_inputs[index_map[i]].append(last_token) if last_token == end_token or\ (max_len is not None and output_len >= max_len) or\ _get_max_suffix_repeat_times(decoder_inputs, max_repeat * max_repeat_block) >= max_repeat: outputs[index_map[i]] = decoder_inputs[index_map[i]] if is_single: outputs = outputs[0] return outputs
[ "def", "decode", "(", "model", ",", "tokens", ",", "start_token", ",", "end_token", ",", "pad_token", ",", "max_len", "=", "10000", ",", "max_repeat", "=", "10", ",", "max_repeat_block", "=", "10", ")", ":", "is_single", "=", "not", "isinstance", "(", "t...
Decode with the given model and input tokens. :param model: The trained model. :param tokens: The input tokens of encoder. :param start_token: The token that represents the start of a sentence. :param end_token: The token that represents the end of a sentence. :param pad_token: The token that represents padding. :param max_len: Maximum length of decoded list. :param max_repeat: Maximum number of repeating blocks. :param max_repeat_block: Maximum length of the repeating block. :return: Decoded tokens.
[ "Decode", "with", "the", "given", "model", "and", "input", "tokens", "." ]
python
train
Unity-Technologies/ml-agents
ml-agents-envs/mlagents/envs/environment.py
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents-envs/mlagents/envs/environment.py#L281-L451
def step(self, vector_action=None, memory=None, text_action=None, value=None, custom_action=None) -> AllBrainInfo: """ Provides the environment with an action, moves the environment dynamics forward accordingly, and returns observation, state, and reward information to the agent. :param value: Value estimates provided by agents. :param vector_action: Agent's vector action. Can be a scalar or vector of int/floats. :param memory: Vector corresponding to memory used for recurrent policies. :param text_action: Text action to send to environment for. :param custom_action: Optional instance of a CustomAction protobuf message. :return: AllBrainInfo : A Data structure corresponding to the new state of the environment. """ vector_action = {} if vector_action is None else vector_action memory = {} if memory is None else memory text_action = {} if text_action is None else text_action value = {} if value is None else value custom_action = {} if custom_action is None else custom_action # Check that environment is loaded, and episode is currently running. if self._loaded and not self._global_done and self._global_done is not None: if isinstance(vector_action, self.SINGLE_BRAIN_ACTION_TYPES): if self._num_external_brains == 1: vector_action = {self._external_brain_names[0]: vector_action} elif self._num_external_brains > 1: raise UnityActionException( "You have {0} brains, you need to feed a dictionary of brain names a keys, " "and vector_actions as values".format(self._num_brains)) else: raise UnityActionException( "There are no external brains in the environment, " "step cannot take a vector_action input") if isinstance(memory, self.SINGLE_BRAIN_ACTION_TYPES): if self._num_external_brains == 1: memory = {self._external_brain_names[0]: memory} elif self._num_external_brains > 1: raise UnityActionException( "You have {0} brains, you need to feed a dictionary of brain names as keys " "and memories as values".format(self._num_brains)) else: raise UnityActionException( "There are no external brains in the environment, " "step cannot take a memory input") if isinstance(text_action, self.SINGLE_BRAIN_TEXT_TYPES): if self._num_external_brains == 1: text_action = {self._external_brain_names[0]: text_action} elif self._num_external_brains > 1: raise UnityActionException( "You have {0} brains, you need to feed a dictionary of brain names as keys " "and text_actions as values".format(self._num_brains)) else: raise UnityActionException( "There are no external brains in the environment, " "step cannot take a value input") if isinstance(value, self.SINGLE_BRAIN_ACTION_TYPES): if self._num_external_brains == 1: value = {self._external_brain_names[0]: value} elif self._num_external_brains > 1: raise UnityActionException( "You have {0} brains, you need to feed a dictionary of brain names as keys " "and state/action value estimates as values".format(self._num_brains)) else: raise UnityActionException( "There are no external brains in the environment, " "step cannot take a value input") if isinstance(custom_action, CustomAction): if self._num_external_brains == 1: custom_action = {self._external_brain_names[0]: custom_action} elif self._num_external_brains > 1: raise UnityActionException( "You have {0} brains, you need to feed a dictionary of brain names as keys " "and CustomAction instances as values".format(self._num_brains)) else: raise UnityActionException( "There are no external brains in the environment, " "step cannot take a custom_action input") for brain_name in list(vector_action.keys()) + list(memory.keys()) + list( text_action.keys()): if brain_name not in self._external_brain_names: raise UnityActionException( "The name {0} does not correspond to an external brain " "in the environment".format(brain_name)) for brain_name in self._external_brain_names: n_agent = self._n_agents[brain_name] if brain_name not in vector_action: if self._brains[brain_name].vector_action_space_type == "discrete": vector_action[brain_name] = [0.0] * n_agent * len( self._brains[brain_name].vector_action_space_size) else: vector_action[brain_name] = [0.0] * n_agent * \ self._brains[ brain_name].vector_action_space_size[0] else: vector_action[brain_name] = self._flatten(vector_action[brain_name]) if brain_name not in memory: memory[brain_name] = [] else: if memory[brain_name] is None: memory[brain_name] = [] else: memory[brain_name] = self._flatten(memory[brain_name]) if brain_name not in text_action: text_action[brain_name] = [""] * n_agent else: if text_action[brain_name] is None: text_action[brain_name] = [""] * n_agent if isinstance(text_action[brain_name], str): text_action[brain_name] = [text_action[brain_name]] * n_agent if brain_name not in custom_action: custom_action[brain_name] = [None] * n_agent else: if custom_action[brain_name] is None: custom_action[brain_name] = [None] * n_agent if isinstance(custom_action[brain_name], CustomAction): custom_action[brain_name] = [custom_action[brain_name]] * n_agent number_text_actions = len(text_action[brain_name]) if not ((number_text_actions == n_agent) or number_text_actions == 0): raise UnityActionException( "There was a mismatch between the provided text_action and " "the environment's expectation: " "The brain {0} expected {1} text_action but was given {2}".format( brain_name, n_agent, number_text_actions)) discrete_check = self._brains[brain_name].vector_action_space_type == "discrete" expected_discrete_size = n_agent * len( self._brains[brain_name].vector_action_space_size) continuous_check = self._brains[brain_name].vector_action_space_type == "continuous" expected_continuous_size = self._brains[brain_name].vector_action_space_size[ 0] * n_agent if not ((discrete_check and len( vector_action[brain_name]) == expected_discrete_size) or (continuous_check and len( vector_action[brain_name]) == expected_continuous_size)): raise UnityActionException( "There was a mismatch between the provided action and " "the environment's expectation: " "The brain {0} expected {1} {2} action(s), but was provided: {3}" .format(brain_name, str(expected_discrete_size) if discrete_check else str(expected_continuous_size), self._brains[brain_name].vector_action_space_type, str(vector_action[brain_name]))) outputs = self.communicator.exchange( self._generate_step_input(vector_action, memory, text_action, value, custom_action)) if outputs is None: raise KeyboardInterrupt rl_output = outputs.rl_output state = self._get_state(rl_output) self._global_done = state[1] for _b in self._external_brain_names: self._n_agents[_b] = len(state[0][_b].agents) return state[0] elif not self._loaded: raise UnityEnvironmentException("No Unity environment is loaded.") elif self._global_done: raise UnityActionException( "The episode is completed. Reset the environment with 'reset()'") elif self.global_done is None: raise UnityActionException( "You cannot conduct step without first calling reset. " "Reset the environment with 'reset()'")
[ "def", "step", "(", "self", ",", "vector_action", "=", "None", ",", "memory", "=", "None", ",", "text_action", "=", "None", ",", "value", "=", "None", ",", "custom_action", "=", "None", ")", "->", "AllBrainInfo", ":", "vector_action", "=", "{", "}", "i...
Provides the environment with an action, moves the environment dynamics forward accordingly, and returns observation, state, and reward information to the agent. :param value: Value estimates provided by agents. :param vector_action: Agent's vector action. Can be a scalar or vector of int/floats. :param memory: Vector corresponding to memory used for recurrent policies. :param text_action: Text action to send to environment for. :param custom_action: Optional instance of a CustomAction protobuf message. :return: AllBrainInfo : A Data structure corresponding to the new state of the environment.
[ "Provides", "the", "environment", "with", "an", "action", "moves", "the", "environment", "dynamics", "forward", "accordingly", "and", "returns", "observation", "state", "and", "reward", "information", "to", "the", "agent", ".", ":", "param", "value", ":", "Value...
python
train
MozillaSecurity/fuzzfetch
src/fuzzfetch/fetch.py
https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L81-L89
def _get_url(url): """Retrieve requested URL""" try: data = HTTP_SESSION.get(url, stream=True) data.raise_for_status() except requests.exceptions.RequestException as exc: raise FetcherException(exc) return data
[ "def", "_get_url", "(", "url", ")", ":", "try", ":", "data", "=", "HTTP_SESSION", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "data", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "RequestException", "as", ...
Retrieve requested URL
[ "Retrieve", "requested", "URL" ]
python
train
duniter/duniter-python-api
duniterpy/documents/transaction.py
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/documents/transaction.py#L321-L337
def from_parameter(cls: Type[UnlockParameterType], parameter: str) -> Optional[Union[SIGParameter, XHXParameter]]: """ Return UnlockParameter instance from parameter string :param parameter: Parameter string :return: """ sig_param = SIGParameter.from_parameter(parameter) if sig_param: return sig_param else: xhx_param = XHXParameter.from_parameter(parameter) if xhx_param: return xhx_param return None
[ "def", "from_parameter", "(", "cls", ":", "Type", "[", "UnlockParameterType", "]", ",", "parameter", ":", "str", ")", "->", "Optional", "[", "Union", "[", "SIGParameter", ",", "XHXParameter", "]", "]", ":", "sig_param", "=", "SIGParameter", ".", "from_parame...
Return UnlockParameter instance from parameter string :param parameter: Parameter string :return:
[ "Return", "UnlockParameter", "instance", "from", "parameter", "string" ]
python
train
log2timeline/dfvfs
dfvfs/vfs/ntfs_file_entry.py
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/ntfs_file_entry.py#L414-L417
def change_time(self): """dfdatetime.DateTimeValues: change time or None if not available.""" timestamp = self._fsntfs_file_entry.get_entry_modification_time_as_integer() return dfdatetime_filetime.Filetime(timestamp=timestamp)
[ "def", "change_time", "(", "self", ")", ":", "timestamp", "=", "self", ".", "_fsntfs_file_entry", ".", "get_entry_modification_time_as_integer", "(", ")", "return", "dfdatetime_filetime", ".", "Filetime", "(", "timestamp", "=", "timestamp", ")" ]
dfdatetime.DateTimeValues: change time or None if not available.
[ "dfdatetime", ".", "DateTimeValues", ":", "change", "time", "or", "None", "if", "not", "available", "." ]
python
train
ecordell/pymacaroons
pymacaroons/serializers/json_serializer.py
https://github.com/ecordell/pymacaroons/blob/c941614df15fe732ea432a62788e45410bcb868d/pymacaroons/serializers/json_serializer.py#L157-L169
def _add_json_binary_field(b, serialized, field): ''' Set the given field to the given val (a bytearray) in the serialized dictionary. If the value isn't valid utf-8, we base64 encode it and use field+"64" as the field name. ''' try: val = b.decode("utf-8") serialized[field] = val except UnicodeDecodeError: val = utils.raw_urlsafe_b64encode(b).decode('utf-8') serialized[field + '64'] = val
[ "def", "_add_json_binary_field", "(", "b", ",", "serialized", ",", "field", ")", ":", "try", ":", "val", "=", "b", ".", "decode", "(", "\"utf-8\"", ")", "serialized", "[", "field", "]", "=", "val", "except", "UnicodeDecodeError", ":", "val", "=", "utils"...
Set the given field to the given val (a bytearray) in the serialized dictionary. If the value isn't valid utf-8, we base64 encode it and use field+"64" as the field name.
[ "Set", "the", "given", "field", "to", "the", "given", "val", "(", "a", "bytearray", ")", "in", "the", "serialized", "dictionary", "." ]
python
train
duniter/duniter-python-api
examples/create_and_publish_identity.py
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/examples/create_and_publish_identity.py#L20-L51
def get_identity_document(current_block: dict, uid: str, salt: str, password: str) -> Identity: """ Get an Identity document :param current_block: Current block data :param uid: Unique IDentifier :param salt: Passphrase of the account :param password: Password of the account :rtype: Identity """ # get current block BlockStamp timestamp = BlockUID(current_block['number'], current_block['hash']) # create keys from credentials key = SigningKey.from_credentials(salt, password) # create identity document identity = Identity( version=10, currency=current_block['currency'], pubkey=key.pubkey, uid=uid, ts=timestamp, signature=None ) # sign document identity.sign([key]) return identity
[ "def", "get_identity_document", "(", "current_block", ":", "dict", ",", "uid", ":", "str", ",", "salt", ":", "str", ",", "password", ":", "str", ")", "->", "Identity", ":", "# get current block BlockStamp", "timestamp", "=", "BlockUID", "(", "current_block", "...
Get an Identity document :param current_block: Current block data :param uid: Unique IDentifier :param salt: Passphrase of the account :param password: Password of the account :rtype: Identity
[ "Get", "an", "Identity", "document" ]
python
train
PyCQA/pylint
pylint/checkers/base.py
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L997-L1001
def open(self): """initialize visit variables and statistics """ self._tryfinallys = [] self.stats = self.linter.add_stats(module=0, function=0, method=0, class_=0)
[ "def", "open", "(", "self", ")", ":", "self", ".", "_tryfinallys", "=", "[", "]", "self", ".", "stats", "=", "self", ".", "linter", ".", "add_stats", "(", "module", "=", "0", ",", "function", "=", "0", ",", "method", "=", "0", ",", "class_", "=",...
initialize visit variables and statistics
[ "initialize", "visit", "variables", "and", "statistics" ]
python
test
RRZE-HPC/kerncraft
kerncraft/intervals.py
https://github.com/RRZE-HPC/kerncraft/blob/c60baf8043e4da8d8d66da7575021c2f4c6c78af/kerncraft/intervals.py#L20-L32
def _enforce_no_overlap(self, start_at=0): """Enforce that no ranges overlap in internal storage.""" i = start_at while i+1 < len(self.data): if self.data[i][1] >= self.data[i+1][0]: # beginning of i+1-th range is contained in i-th range if self.data[i][1] < self.data[i+1][1]: # i+1-th range is longer, thus enlarge i-th range self.data[i][1] = self.data[i+1][1] # removed contained range del self.data[i+1] i += 1
[ "def", "_enforce_no_overlap", "(", "self", ",", "start_at", "=", "0", ")", ":", "i", "=", "start_at", "while", "i", "+", "1", "<", "len", "(", "self", ".", "data", ")", ":", "if", "self", ".", "data", "[", "i", "]", "[", "1", "]", ">=", "self",...
Enforce that no ranges overlap in internal storage.
[ "Enforce", "that", "no", "ranges", "overlap", "in", "internal", "storage", "." ]
python
test
Alignak-monitoring/alignak
alignak/basemodule.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L189-L210
def create_queues(self, manager=None): """ Create the shared queues that will be used by alignak daemon process and this module process. But clear queues if they were already set before recreating new one. Note: If manager is None, then we are running the unit tests for the modules and we must create some queues for the external modules without a SyncManager :param manager: Manager() object :type manager: None | object :return: None """ self.clear_queues(manager) # If no Manager() object, go with classic Queue() if not manager: self.from_q = Queue() self.to_q = Queue() else: self.from_q = manager.Queue() self.to_q = manager.Queue()
[ "def", "create_queues", "(", "self", ",", "manager", "=", "None", ")", ":", "self", ".", "clear_queues", "(", "manager", ")", "# If no Manager() object, go with classic Queue()", "if", "not", "manager", ":", "self", ".", "from_q", "=", "Queue", "(", ")", "self...
Create the shared queues that will be used by alignak daemon process and this module process. But clear queues if they were already set before recreating new one. Note: If manager is None, then we are running the unit tests for the modules and we must create some queues for the external modules without a SyncManager :param manager: Manager() object :type manager: None | object :return: None
[ "Create", "the", "shared", "queues", "that", "will", "be", "used", "by", "alignak", "daemon", "process", "and", "this", "module", "process", ".", "But", "clear", "queues", "if", "they", "were", "already", "set", "before", "recreating", "new", "one", "." ]
python
train
bpsmith/tia
tia/analysis/perf.py
https://github.com/bpsmith/tia/blob/a7043b6383e557aeea8fc7112bbffd6e36a230e9/tia/analysis/perf.py#L339-L359
def downside_deviation(rets, mar=0, expanding=0, full=0, ann=0): """Compute the downside deviation for the specifed return series :param rets: periodic return series :param mar: minimum acceptable rate of return (MAR) :param full: If True, use the lenght of full series. If False, use only values below MAR :param expanding: :param ann: True if result should be annualized """ below = rets[rets < mar] if expanding: n = pd.expanding_count(rets)[below.index] if full else pd.expanding_count(below) dd = np.sqrt(((below - mar) ** 2).cumsum() / n) if ann: dd *= np.sqrt(periods_in_year(rets)) return dd.reindex(rets.index).ffill() else: n = rets.count() if full else below.count() dd = np.sqrt(((below - mar) ** 2).sum() / n) if ann: dd *= np.sqrt(periods_in_year(rets)) return dd
[ "def", "downside_deviation", "(", "rets", ",", "mar", "=", "0", ",", "expanding", "=", "0", ",", "full", "=", "0", ",", "ann", "=", "0", ")", ":", "below", "=", "rets", "[", "rets", "<", "mar", "]", "if", "expanding", ":", "n", "=", "pd", ".", ...
Compute the downside deviation for the specifed return series :param rets: periodic return series :param mar: minimum acceptable rate of return (MAR) :param full: If True, use the lenght of full series. If False, use only values below MAR :param expanding: :param ann: True if result should be annualized
[ "Compute", "the", "downside", "deviation", "for", "the", "specifed", "return", "series", ":", "param", "rets", ":", "periodic", "return", "series", ":", "param", "mar", ":", "minimum", "acceptable", "rate", "of", "return", "(", "MAR", ")", ":", "param", "f...
python
train
odrling/peony-twitter
peony/utils.py
https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/utils.py#L202-L232
async def get_media_metadata(data, path=None): """ Get all the file's metadata and read any kind of file object Parameters ---------- data : bytes first bytes of the file (the mimetype shoudl be guessed from the file headers path : str, optional path to the file Returns ------- str The mimetype of the media str The category of the media on Twitter """ if isinstance(data, bytes): media_type = await get_type(data, path) else: raise TypeError("get_metadata input must be a bytes") media_category = get_category(media_type) _logger.info("media_type: %s, media_category: %s" % (media_type, media_category)) return media_type, media_category
[ "async", "def", "get_media_metadata", "(", "data", ",", "path", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "bytes", ")", ":", "media_type", "=", "await", "get_type", "(", "data", ",", "path", ")", "else", ":", "raise", "TypeError", "(...
Get all the file's metadata and read any kind of file object Parameters ---------- data : bytes first bytes of the file (the mimetype shoudl be guessed from the file headers path : str, optional path to the file Returns ------- str The mimetype of the media str The category of the media on Twitter
[ "Get", "all", "the", "file", "s", "metadata", "and", "read", "any", "kind", "of", "file", "object" ]
python
valid
mbedmicro/pyOCD
pyocd/utility/server.py
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/utility/server.py#L131-L146
def _get_input(self, length): """! @brief Extract requested amount of data from the read buffer.""" self._buffer_lock.acquire() try: if length == -1: actualLength = len(self._buffer) else: actualLength = min(length, len(self._buffer)) if actualLength: data = self._buffer[:actualLength] self._buffer = self._buffer[actualLength:] else: data = bytearray() return data finally: self._buffer_lock.release()
[ "def", "_get_input", "(", "self", ",", "length", ")", ":", "self", ".", "_buffer_lock", ".", "acquire", "(", ")", "try", ":", "if", "length", "==", "-", "1", ":", "actualLength", "=", "len", "(", "self", ".", "_buffer", ")", "else", ":", "actualLengt...
! @brief Extract requested amount of data from the read buffer.
[ "!" ]
python
train
BlueBrain/nat
nat/scigraph_client.py
https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/scigraph_client.py#L399-L422
def annotatePost(self, content, includeCat=None, excludeCat=None, minLength=4, longestOnly='false', includeAbbrev='false', includeAcronym='false', includeNumbers='false', ignoreTag=None, stylesheet=None, scripts=None, targetId=None, targetClass=None): """ Annotate text from: /annotations Arguments: content: The content to annotate includeCat: A set of categories to include excludeCat: A set of categories to exclude minLength: The minimum number of characters in annotated entities longestOnly: Should only the longest entity be returned for an overlapping group includeAbbrev: Should abbreviations be included includeAcronym: Should acronyms be included includeNumbers: Should numbers be included ignoreTag: HTML tags that should not be annotated stylesheet: CSS stylesheets to add to the HEAD scripts: JavaScripts that should to add to the HEAD targetId: A set of element IDs to annotate targetClass: A set of CSS class names to annotate """ kwargs = {'content':content, 'includeCat':includeCat, 'excludeCat':excludeCat, 'minLength':minLength, 'longestOnly':longestOnly, 'includeAbbrev':includeAbbrev, 'includeAcronym':includeAcronym, 'includeNumbers':includeNumbers, 'ignoreTag':ignoreTag, 'stylesheet':stylesheet, 'scripts':scripts, 'targetId':targetId, 'targetClass':targetClass} kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.items()} param_rest = self._make_rest('content', **kwargs) url = self._basePath + ('/annotations').format(**kwargs) requests_params = {k:v for k, v in kwargs.items() if k != 'content'} return self._get('POST', url, requests_params)
[ "def", "annotatePost", "(", "self", ",", "content", ",", "includeCat", "=", "None", ",", "excludeCat", "=", "None", ",", "minLength", "=", "4", ",", "longestOnly", "=", "'false'", ",", "includeAbbrev", "=", "'false'", ",", "includeAcronym", "=", "'false'", ...
Annotate text from: /annotations Arguments: content: The content to annotate includeCat: A set of categories to include excludeCat: A set of categories to exclude minLength: The minimum number of characters in annotated entities longestOnly: Should only the longest entity be returned for an overlapping group includeAbbrev: Should abbreviations be included includeAcronym: Should acronyms be included includeNumbers: Should numbers be included ignoreTag: HTML tags that should not be annotated stylesheet: CSS stylesheets to add to the HEAD scripts: JavaScripts that should to add to the HEAD targetId: A set of element IDs to annotate targetClass: A set of CSS class names to annotate
[ "Annotate", "text", "from", ":", "/", "annotations", "Arguments", ":", "content", ":", "The", "content", "to", "annotate", "includeCat", ":", "A", "set", "of", "categories", "to", "include", "excludeCat", ":", "A", "set", "of", "categories", "to", "exclude",...
python
train
googleapis/google-cloud-python
logging/docs/snippets.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/docs/snippets.py#L104-L112
def client_list_entries_multi_project( client, to_delete ): # pylint: disable=unused-argument """List entries via client across multiple projects.""" # [START client_list_entries_multi_project] PROJECT_IDS = ["one-project", "another-project"] for entry in client.list_entries(project_ids=PROJECT_IDS): # API call(s) do_something_with(entry)
[ "def", "client_list_entries_multi_project", "(", "client", ",", "to_delete", ")", ":", "# pylint: disable=unused-argument", "# [START client_list_entries_multi_project]", "PROJECT_IDS", "=", "[", "\"one-project\"", ",", "\"another-project\"", "]", "for", "entry", "in", "clien...
List entries via client across multiple projects.
[ "List", "entries", "via", "client", "across", "multiple", "projects", "." ]
python
train
bitlabstudio/django-development-fabfile
development_fabfile/fabfile/remote.py
https://github.com/bitlabstudio/django-development-fabfile/blob/a135c6eb5bdd0b496a7eccfd271aca558dd99243/development_fabfile/fabfile/remote.py#L287-L306
def run_rsync_project(): """ Copies the project from the git repository to it's destination folder. This has the nice side effect of rsync deleting all ``.pyc`` files and removing other files that might have been left behind by sys admins messing around on the server. Usage:: fab <server> run_rsync_project """ excludes = '' for exclude in settings.RSYNC_EXCLUDES: excludes += " --exclude '{0}'".format(exclude) command = "rsync -avz --stats --delete {0} {1} {2}".format( excludes, settings.FAB_SETTING('SERVER_REPO_PROJECT_ROOT'), settings.FAB_SETTING('SERVER_APP_ROOT')) run(command)
[ "def", "run_rsync_project", "(", ")", ":", "excludes", "=", "''", "for", "exclude", "in", "settings", ".", "RSYNC_EXCLUDES", ":", "excludes", "+=", "\" --exclude '{0}'\"", ".", "format", "(", "exclude", ")", "command", "=", "\"rsync -avz --stats --delete {0} {1} {2}...
Copies the project from the git repository to it's destination folder. This has the nice side effect of rsync deleting all ``.pyc`` files and removing other files that might have been left behind by sys admins messing around on the server. Usage:: fab <server> run_rsync_project
[ "Copies", "the", "project", "from", "the", "git", "repository", "to", "it", "s", "destination", "folder", "." ]
python
train
PyMLGame/pymlgame
pymlgame/surface.py
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/pymlgame/surface.py#L128-L142
def blit(self, surface, pos=(0, 0)): """ Blits a surface on this surface at pos :param surface: Surface to blit :param pos: Top left point to start blitting :type surface: Surface :type pos: tuple """ for x in range(surface.width): for y in range(surface.height): px = x + pos[0] py = y + pos[1] if 0 < px < self.width and 0 < py < self.height: self.matrix[px][py] = surface.matrix[x][y]
[ "def", "blit", "(", "self", ",", "surface", ",", "pos", "=", "(", "0", ",", "0", ")", ")", ":", "for", "x", "in", "range", "(", "surface", ".", "width", ")", ":", "for", "y", "in", "range", "(", "surface", ".", "height", ")", ":", "px", "=", ...
Blits a surface on this surface at pos :param surface: Surface to blit :param pos: Top left point to start blitting :type surface: Surface :type pos: tuple
[ "Blits", "a", "surface", "on", "this", "surface", "at", "pos" ]
python
train
DLR-RM/RAFCON
source/rafcon/core/states/container_state.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/container_state.py#L1431-L1446
def remove_scoped_variable(self, scoped_variable_id, destroy=True): """Remove a scoped variable from the container state :param scoped_variable_id: the id of the scoped variable to remove :raises exceptions.AttributeError: if the id of the scoped variable already exists """ if scoped_variable_id not in self._scoped_variables: raise AttributeError("A scoped variable with id %s does not exist" % str(scoped_variable_id)) # delete all data flows connected to scoped_variable if destroy: self.remove_data_flows_with_data_port_id(scoped_variable_id) # delete scoped variable self._scoped_variables[scoped_variable_id].parent = None return self._scoped_variables.pop(scoped_variable_id)
[ "def", "remove_scoped_variable", "(", "self", ",", "scoped_variable_id", ",", "destroy", "=", "True", ")", ":", "if", "scoped_variable_id", "not", "in", "self", ".", "_scoped_variables", ":", "raise", "AttributeError", "(", "\"A scoped variable with id %s does not exist...
Remove a scoped variable from the container state :param scoped_variable_id: the id of the scoped variable to remove :raises exceptions.AttributeError: if the id of the scoped variable already exists
[ "Remove", "a", "scoped", "variable", "from", "the", "container", "state" ]
python
train
Robpol86/libnl
libnl/nl.py
https://github.com/Robpol86/libnl/blob/274e9fdaa39822d06ef70b799ed4a95937a4d923/libnl/nl.py#L646-L669
def nl_recvmsgs(sk, cb): """Receive a set of messages from a Netlink socket. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L1023 Repeatedly calls nl_recv() or the respective replacement if provided by the application (see nl_cb_overwrite_recv()) and parses the received data as Netlink messages. Stops reading if one of the callbacks returns NL_STOP or nl_recv returns either 0 or a negative error code. A non-blocking sockets causes the function to return immediately if no data is available. See nl_recvmsgs_report(). Positional arguments: sk -- Netlink socket (nl_sock class instance). cb -- set of callbacks to control behaviour (nl_cb class instance). Returns: 0 on success or a negative error code from nl_recv(). """ err = nl_recvmsgs_report(sk, cb) if err > 0: return 0 return int(err)
[ "def", "nl_recvmsgs", "(", "sk", ",", "cb", ")", ":", "err", "=", "nl_recvmsgs_report", "(", "sk", ",", "cb", ")", "if", "err", ">", "0", ":", "return", "0", "return", "int", "(", "err", ")" ]
Receive a set of messages from a Netlink socket. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L1023 Repeatedly calls nl_recv() or the respective replacement if provided by the application (see nl_cb_overwrite_recv()) and parses the received data as Netlink messages. Stops reading if one of the callbacks returns NL_STOP or nl_recv returns either 0 or a negative error code. A non-blocking sockets causes the function to return immediately if no data is available. See nl_recvmsgs_report(). Positional arguments: sk -- Netlink socket (nl_sock class instance). cb -- set of callbacks to control behaviour (nl_cb class instance). Returns: 0 on success or a negative error code from nl_recv().
[ "Receive", "a", "set", "of", "messages", "from", "a", "Netlink", "socket", "." ]
python
train
sernst/cauldron
cauldron/session/display/__init__.py
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L275-L298
def image( filename: str, width: int = None, height: int = None, justify: str = 'left' ): """ Adds an image to the display. The image must be located within the assets directory of the Cauldron notebook's folder. :param filename: Name of the file within the assets directory, :param width: Optional width in pixels for the image. :param height: Optional height in pixels for the image. :param justify: One of 'left', 'center' or 'right', which specifies how the image is horizontally justified within the notebook display. """ r = _get_report() path = '/'.join(['reports', r.project.uuid, 'latest', 'assets', filename]) r.append_body(render.image(path, width, height, justify)) r.stdout_interceptor.write_source('[ADDED] Image\n')
[ "def", "image", "(", "filename", ":", "str", ",", "width", ":", "int", "=", "None", ",", "height", ":", "int", "=", "None", ",", "justify", ":", "str", "=", "'left'", ")", ":", "r", "=", "_get_report", "(", ")", "path", "=", "'/'", ".", "join", ...
Adds an image to the display. The image must be located within the assets directory of the Cauldron notebook's folder. :param filename: Name of the file within the assets directory, :param width: Optional width in pixels for the image. :param height: Optional height in pixels for the image. :param justify: One of 'left', 'center' or 'right', which specifies how the image is horizontally justified within the notebook display.
[ "Adds", "an", "image", "to", "the", "display", ".", "The", "image", "must", "be", "located", "within", "the", "assets", "directory", "of", "the", "Cauldron", "notebook", "s", "folder", "." ]
python
train
jmbeach/KEP.py
src/keppy/simulator_device.py
https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/simulator_device.py#L166-L174
def process_string(self, tag): """Process string type tags""" tag.set_address(self.string_register.current_address) if self.is_sixteen_bit: # each string address needs 1 byte = 1/2 an address self.string_register.move_to_next_address(1) return # each string address needs 1 byte = 1 address self.string_register.move_to_next_address(1)
[ "def", "process_string", "(", "self", ",", "tag", ")", ":", "tag", ".", "set_address", "(", "self", ".", "string_register", ".", "current_address", ")", "if", "self", ".", "is_sixteen_bit", ":", "# each string address needs 1 byte = 1/2 an address", "self", ".", "...
Process string type tags
[ "Process", "string", "type", "tags" ]
python
train
jay-johnson/celery-loaders
celery_loaders/work_tasks/custom_task.py
https://github.com/jay-johnson/celery-loaders/blob/aca8169c774582af42a377c27cb3980020080814/celery_loaders/work_tasks/custom_task.py#L14-L32
def on_success(self, retval, task_id, args, kwargs): """on_success http://docs.celeryproject.org/en/latest/reference/celery.app.task.html :param retval: return value :param task_id: celery task id :param args: arguments passed into task :param kwargs: keyword arguments passed into task """ log.info(("{} SUCCESS - retval={} task_id={} " "args={} kwargs={}") .format( self.log_label, retval, task_id, args, kwargs))
[ "def", "on_success", "(", "self", ",", "retval", ",", "task_id", ",", "args", ",", "kwargs", ")", ":", "log", ".", "info", "(", "(", "\"{} SUCCESS - retval={} task_id={} \"", "\"args={} kwargs={}\"", ")", ".", "format", "(", "self", ".", "log_label", ",", "r...
on_success http://docs.celeryproject.org/en/latest/reference/celery.app.task.html :param retval: return value :param task_id: celery task id :param args: arguments passed into task :param kwargs: keyword arguments passed into task
[ "on_success" ]
python
train
materialsproject/pymatgen
pymatgen/core/structure.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/structure.py#L283-L300
def is_valid(self, tol: float = DISTANCE_TOLERANCE) -> bool: """ True if SiteCollection does not contain atoms that are too close together. Note that the distance definition is based on type of SiteCollection. Cartesian distances are used for non-periodic Molecules, while PBC is taken into account for periodic structures. Args: tol (float): Distance tolerance. Default is 0.5A. Returns: (bool) True if SiteCollection does not contain atoms that are too close together. """ if len(self.sites) == 1: return True all_dists = self.distance_matrix[np.triu_indices(len(self), 1)] return bool(np.min(all_dists) > tol)
[ "def", "is_valid", "(", "self", ",", "tol", ":", "float", "=", "DISTANCE_TOLERANCE", ")", "->", "bool", ":", "if", "len", "(", "self", ".", "sites", ")", "==", "1", ":", "return", "True", "all_dists", "=", "self", ".", "distance_matrix", "[", "np", "...
True if SiteCollection does not contain atoms that are too close together. Note that the distance definition is based on type of SiteCollection. Cartesian distances are used for non-periodic Molecules, while PBC is taken into account for periodic structures. Args: tol (float): Distance tolerance. Default is 0.5A. Returns: (bool) True if SiteCollection does not contain atoms that are too close together.
[ "True", "if", "SiteCollection", "does", "not", "contain", "atoms", "that", "are", "too", "close", "together", ".", "Note", "that", "the", "distance", "definition", "is", "based", "on", "type", "of", "SiteCollection", ".", "Cartesian", "distances", "are", "used...
python
train
gleitz/howdoi
howdoi/howdoi.py
https://github.com/gleitz/howdoi/blob/94f0429b4e99cb914aadfca0f27257ea801471ac/howdoi/howdoi.py#L157-L163
def get_text(element): ''' return inner text in pyquery element ''' _add_links_to_text(element) try: return element.text(squash_space=False) except TypeError: return element.text()
[ "def", "get_text", "(", "element", ")", ":", "_add_links_to_text", "(", "element", ")", "try", ":", "return", "element", ".", "text", "(", "squash_space", "=", "False", ")", "except", "TypeError", ":", "return", "element", ".", "text", "(", ")" ]
return inner text in pyquery element
[ "return", "inner", "text", "in", "pyquery", "element" ]
python
train
RusticiSoftware/TinCanPython
tincan/lrs_response.py
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/lrs_response.py#L111-L119
def data(self, value): """Setter for the _data attribute. Should be set from response.read() :param value: The body of the response object for the LRSResponse :type value: unicode """ if value is not None and not isinstance(value, unicode): value = value.decode('utf-8') self._data = value
[ "def", "data", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", "and", "not", "isinstance", "(", "value", ",", "unicode", ")", ":", "value", "=", "value", ".", "decode", "(", "'utf-8'", ")", "self", ".", "_data", "=", "value...
Setter for the _data attribute. Should be set from response.read() :param value: The body of the response object for the LRSResponse :type value: unicode
[ "Setter", "for", "the", "_data", "attribute", ".", "Should", "be", "set", "from", "response", ".", "read", "()" ]
python
train
tBuLi/symfit
symfit/distributions.py
https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/distributions.py#L11-L19
def Gaussian(x, mu, sig): """ Gaussian pdf. :param x: free variable. :param mu: mean of the distribution. :param sig: standard deviation of the distribution. :return: sympy.Expr for a Gaussian pdf. """ return sympy.exp(-(x - mu)**2/(2*sig**2))/sympy.sqrt(2*sympy.pi*sig**2)
[ "def", "Gaussian", "(", "x", ",", "mu", ",", "sig", ")", ":", "return", "sympy", ".", "exp", "(", "-", "(", "x", "-", "mu", ")", "**", "2", "/", "(", "2", "*", "sig", "**", "2", ")", ")", "/", "sympy", ".", "sqrt", "(", "2", "*", "sympy",...
Gaussian pdf. :param x: free variable. :param mu: mean of the distribution. :param sig: standard deviation of the distribution. :return: sympy.Expr for a Gaussian pdf.
[ "Gaussian", "pdf", ".", ":", "param", "x", ":", "free", "variable", ".", ":", "param", "mu", ":", "mean", "of", "the", "distribution", ".", ":", "param", "sig", ":", "standard", "deviation", "of", "the", "distribution", ".", ":", "return", ":", "sympy"...
python
train
Azure/azure-cosmos-table-python
azure-cosmosdb-table/azure/cosmosdb/table/tableservice.py
https://github.com/Azure/azure-cosmos-table-python/blob/a7b618f6bddc465c9fdf899ea2971dfe4d04fcf0/azure-cosmosdb-table/azure/cosmosdb/table/tableservice.py#L935-L967
def update_entity(self, table_name, entity, if_match='*', timeout=None): ''' Updates an existing entity in a table. Throws if the entity does not exist. The update_entity operation replaces the entire entity and can be used to remove properties. :param str table_name: The name of the table containing the entity to update. :param entity: The entity to update. Could be a dict or an entity object. Must contain a PartitionKey and a RowKey. :type entity: dict or :class:`~azure.storage.table.models.Entity` :param str if_match: The client may specify the ETag for the entity on the request in order to compare to the ETag maintained by the service for the purpose of optimistic concurrency. The update operation will be performed only if the ETag sent by the client matches the value maintained by the server, indicating that the entity has not been modified since it was retrieved by the client. To force an unconditional update, set If-Match to the wildcard character (*). :param int timeout: The server timeout, expressed in seconds. :return: The etag of the entity. :rtype: str ''' _validate_not_none('table_name', table_name) request = _update_entity(entity, if_match, self.require_encryption, self.key_encryption_key, self.encryption_resolver_function) request.host_locations = self._get_host_locations() request.path = _get_entity_path(table_name, entity['PartitionKey'], entity['RowKey']) request.query['timeout'] = _int_to_str(timeout) return self._perform_request(request, _extract_etag)
[ "def", "update_entity", "(", "self", ",", "table_name", ",", "entity", ",", "if_match", "=", "'*'", ",", "timeout", "=", "None", ")", ":", "_validate_not_none", "(", "'table_name'", ",", "table_name", ")", "request", "=", "_update_entity", "(", "entity", ","...
Updates an existing entity in a table. Throws if the entity does not exist. The update_entity operation replaces the entire entity and can be used to remove properties. :param str table_name: The name of the table containing the entity to update. :param entity: The entity to update. Could be a dict or an entity object. Must contain a PartitionKey and a RowKey. :type entity: dict or :class:`~azure.storage.table.models.Entity` :param str if_match: The client may specify the ETag for the entity on the request in order to compare to the ETag maintained by the service for the purpose of optimistic concurrency. The update operation will be performed only if the ETag sent by the client matches the value maintained by the server, indicating that the entity has not been modified since it was retrieved by the client. To force an unconditional update, set If-Match to the wildcard character (*). :param int timeout: The server timeout, expressed in seconds. :return: The etag of the entity. :rtype: str
[ "Updates", "an", "existing", "entity", "in", "a", "table", ".", "Throws", "if", "the", "entity", "does", "not", "exist", ".", "The", "update_entity", "operation", "replaces", "the", "entire", "entity", "and", "can", "be", "used", "to", "remove", "properties"...
python
train
hazelcast/hazelcast-python-client
hazelcast/proxy/list.py
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/list.py#L35-L44
def add(self, item): """ Adds the specified item to the end of this list. :param item: (object), the specified item to be appended to this list. :return: (bool), ``true`` if item is added, ``false`` otherwise. """ check_not_none(item, "Value can't be None") element_data = self._to_data(item) return self._encode_invoke(list_add_codec, value=element_data)
[ "def", "add", "(", "self", ",", "item", ")", ":", "check_not_none", "(", "item", ",", "\"Value can't be None\"", ")", "element_data", "=", "self", ".", "_to_data", "(", "item", ")", "return", "self", ".", "_encode_invoke", "(", "list_add_codec", ",", "value"...
Adds the specified item to the end of this list. :param item: (object), the specified item to be appended to this list. :return: (bool), ``true`` if item is added, ``false`` otherwise.
[ "Adds", "the", "specified", "item", "to", "the", "end", "of", "this", "list", "." ]
python
train
dunovank/jupyter-themes
jupyterthemes/jtplot.py
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/jtplot.py#L215-L223
def figsize(x=8, y=7., aspect=1.): """ manually set the default figure size of plots ::Arguments:: x (float): x-axis size y (float): y-axis size aspect (float): aspect ratio scalar """ # update rcparams with adjusted figsize params mpl.rcParams.update({'figure.figsize': (x*aspect, y)})
[ "def", "figsize", "(", "x", "=", "8", ",", "y", "=", "7.", ",", "aspect", "=", "1.", ")", ":", "# update rcparams with adjusted figsize params", "mpl", ".", "rcParams", ".", "update", "(", "{", "'figure.figsize'", ":", "(", "x", "*", "aspect", ",", "y", ...
manually set the default figure size of plots ::Arguments:: x (float): x-axis size y (float): y-axis size aspect (float): aspect ratio scalar
[ "manually", "set", "the", "default", "figure", "size", "of", "plots", "::", "Arguments", "::", "x", "(", "float", ")", ":", "x", "-", "axis", "size", "y", "(", "float", ")", ":", "y", "-", "axis", "size", "aspect", "(", "float", ")", ":", "aspect",...
python
train
treycucco/bidon
bidon/experimental/transfer_tracker.py
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/experimental/transfer_tracker.py#L144-L150
def id_getter(self, relation_name, strict=False): """Returns a function that accepts an old_id and returns the new ID for the enclosed relation name.""" def get_id(old_id): """Get the new ID for the enclosed relation, given an old ID.""" return self.get_new_id(relation_name, old_id, strict) return get_id
[ "def", "id_getter", "(", "self", ",", "relation_name", ",", "strict", "=", "False", ")", ":", "def", "get_id", "(", "old_id", ")", ":", "\"\"\"Get the new ID for the enclosed relation, given an old ID.\"\"\"", "return", "self", ".", "get_new_id", "(", "relation_name",...
Returns a function that accepts an old_id and returns the new ID for the enclosed relation name.
[ "Returns", "a", "function", "that", "accepts", "an", "old_id", "and", "returns", "the", "new", "ID", "for", "the", "enclosed", "relation", "name", "." ]
python
train
saltstack/salt
salt/utils/jinja.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L85-L90
def cache_file(self, template): ''' Cache a file from the salt master ''' saltpath = salt.utils.url.create(template) self.file_client().get_file(saltpath, '', True, self.saltenv)
[ "def", "cache_file", "(", "self", ",", "template", ")", ":", "saltpath", "=", "salt", ".", "utils", ".", "url", ".", "create", "(", "template", ")", "self", ".", "file_client", "(", ")", ".", "get_file", "(", "saltpath", ",", "''", ",", "True", ",", ...
Cache a file from the salt master
[ "Cache", "a", "file", "from", "the", "salt", "master" ]
python
train
rushter/heamy
heamy/feature.py
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/feature.py#L155-L166
def xgb_to_features(model, X_train, X_test): """Converts xgboost model into categorical features. Reference: "Practical Lessons from Predicting Clicks on Ads at Facebook" https://research.fb.com/publications/practical-lessons-from-predicting-clicks-on-ads-at-facebook/ """ import xgboost as xgb f_train = model.predict(xgb.DMatrix(X_train), pred_leaf=True) f_test = model.predict(xgb.DMatrix(X_test), pred_leaf=True) enc = OneHotEncoder() enc.fit(f_train) return enc.transform(f_train), enc.transform(f_test)
[ "def", "xgb_to_features", "(", "model", ",", "X_train", ",", "X_test", ")", ":", "import", "xgboost", "as", "xgb", "f_train", "=", "model", ".", "predict", "(", "xgb", ".", "DMatrix", "(", "X_train", ")", ",", "pred_leaf", "=", "True", ")", "f_test", "...
Converts xgboost model into categorical features. Reference: "Practical Lessons from Predicting Clicks on Ads at Facebook" https://research.fb.com/publications/practical-lessons-from-predicting-clicks-on-ads-at-facebook/
[ "Converts", "xgboost", "model", "into", "categorical", "features", ".", "Reference", ":", "Practical", "Lessons", "from", "Predicting", "Clicks", "on", "Ads", "at", "Facebook", "https", ":", "//", "research", ".", "fb", ".", "com", "/", "publications", "/", ...
python
train
AndrewAnnex/SpiceyPy
spiceypy/spiceypy.py
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L7383-L7405
def isrchi(value, ndim, array): """ Search for a given value within an integer array. Return the index of the first matching array entry, or -1 if the key value was not found. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isrchi_c.html :param value: Key value to be found in array. :type value: int :param ndim: Dimension of array. :type ndim: int :param array: Integer array to search. :type array: Array of ints :return: The index of the first matching array element or -1 if the value is not found. :rtype: int """ value = ctypes.c_int(value) ndim = ctypes.c_int(ndim) array = stypes.toIntVector(array) return libspice.isrchi_c(value, ndim, array)
[ "def", "isrchi", "(", "value", ",", "ndim", ",", "array", ")", ":", "value", "=", "ctypes", ".", "c_int", "(", "value", ")", "ndim", "=", "ctypes", ".", "c_int", "(", "ndim", ")", "array", "=", "stypes", ".", "toIntVector", "(", "array", ")", "retu...
Search for a given value within an integer array. Return the index of the first matching array entry, or -1 if the key value was not found. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isrchi_c.html :param value: Key value to be found in array. :type value: int :param ndim: Dimension of array. :type ndim: int :param array: Integer array to search. :type array: Array of ints :return: The index of the first matching array element or -1 if the value is not found. :rtype: int
[ "Search", "for", "a", "given", "value", "within", "an", "integer", "array", ".", "Return", "the", "index", "of", "the", "first", "matching", "array", "entry", "or", "-", "1", "if", "the", "key", "value", "was", "not", "found", "." ]
python
train
dslackw/slpkg
slpkg/__metadata__.py
https://github.com/dslackw/slpkg/blob/dd2e08a80e944d337d157b992167ba631a4343de/slpkg/__metadata__.py#L39-L52
def update_repositories(repositories, conf_path): """ Upadate with user custom repositories """ repo_file = "{0}custom-repositories".format(conf_path) if os.path.isfile(repo_file): f = open(repo_file, "r") repositories_list = f.read() f.close() for line in repositories_list.splitlines(): line = line.lstrip() if line and not line.startswith("#"): repositories.append(line.split()[0]) return repositories
[ "def", "update_repositories", "(", "repositories", ",", "conf_path", ")", ":", "repo_file", "=", "\"{0}custom-repositories\"", ".", "format", "(", "conf_path", ")", "if", "os", ".", "path", ".", "isfile", "(", "repo_file", ")", ":", "f", "=", "open", "(", ...
Upadate with user custom repositories
[ "Upadate", "with", "user", "custom", "repositories" ]
python
train
Alignak-monitoring/alignak
alignak/stats.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/stats.py#L224-L255
def load_statsd(self): """Create socket connection to statsd host Note that because of the UDP protocol used by StatsD, if no server is listening the socket connection will be accepted anyway :) :return: True if socket got created else False and an exception log is raised """ if not self.statsd_enabled: logger.info('Stats reporting is not enabled, connection is not allowed') return False if self.statsd_enabled and self.carbon: self.my_metrics.append(('.'.join([self.statsd_prefix, self.name, 'connection-test']), (int(time.time()), int(time.time())))) self.carbon.add_data_list(self.my_metrics) self.flush(log=True) else: try: logger.info('Trying to contact StatsD server...') self.statsd_addr = (socket.gethostbyname(self.statsd_host.encode('utf-8')), self.statsd_port) self.statsd_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) except (socket.error, socket.gaierror) as exp: logger.warning('Cannot create StatsD socket: %s', exp) return False except Exception as exp: # pylint: disable=broad-except logger.exception('Cannot create StatsD socket (other): %s', exp) return False logger.info('StatsD server contacted') return True
[ "def", "load_statsd", "(", "self", ")", ":", "if", "not", "self", ".", "statsd_enabled", ":", "logger", ".", "info", "(", "'Stats reporting is not enabled, connection is not allowed'", ")", "return", "False", "if", "self", ".", "statsd_enabled", "and", "self", "."...
Create socket connection to statsd host Note that because of the UDP protocol used by StatsD, if no server is listening the socket connection will be accepted anyway :) :return: True if socket got created else False and an exception log is raised
[ "Create", "socket", "connection", "to", "statsd", "host" ]
python
train
bxlab/bx-python
lib/bx_extras/stats.py
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1054-L1069
def lchisquare(f_obs,f_exp=None): """ Calculates a one-way chi square for list of observed frequencies and returns the result. If no expected frequencies are given, the total N is assumed to be equally distributed across all groups. Usage: lchisquare(f_obs, f_exp=None) f_obs = list of observed cell freq. Returns: chisquare-statistic, associated p-value """ k = len(f_obs) # number of groups if f_exp == None: f_exp = [sum(f_obs)/float(k)] * len(f_obs) # create k bins with = freq. chisq = 0 for i in range(len(f_obs)): chisq = chisq + (f_obs[i]-f_exp[i])**2 / float(f_exp[i]) return chisq, chisqprob(chisq, k-1)
[ "def", "lchisquare", "(", "f_obs", ",", "f_exp", "=", "None", ")", ":", "k", "=", "len", "(", "f_obs", ")", "# number of groups", "if", "f_exp", "==", "None", ":", "f_exp", "=", "[", "sum", "(", "f_obs", ")", "/", "float", "(", "k", ")", "]", "*"...
Calculates a one-way chi square for list of observed frequencies and returns the result. If no expected frequencies are given, the total N is assumed to be equally distributed across all groups. Usage: lchisquare(f_obs, f_exp=None) f_obs = list of observed cell freq. Returns: chisquare-statistic, associated p-value
[ "Calculates", "a", "one", "-", "way", "chi", "square", "for", "list", "of", "observed", "frequencies", "and", "returns", "the", "result", ".", "If", "no", "expected", "frequencies", "are", "given", "the", "total", "N", "is", "assumed", "to", "be", "equally...
python
train
PyGithub/PyGithub
github/GitRelease.py
https://github.com/PyGithub/PyGithub/blob/f716df86bbe7dc276c6596699fa9712b61ef974c/github/GitRelease.py#L219-L241
def upload_asset(self, path, label="", content_type=""): """ :calls: `POST https://<upload_url>/repos/:owner/:repo/releases/:release_id/assets?name=foo.zip <https://developer.github.com/v3/repos/releases/#upload-a-release-asset>`_ :rtype: :class:`github.GitReleaseAsset.GitReleaseAsset` """ assert isinstance(path, (str, unicode)), path assert isinstance(label, (str, unicode)), label post_parameters = { "name": basename(path), "label": label } headers = {} if len(content_type) > 0: headers["Content-Type"] = content_type resp_headers, data = self._requester.requestBlobAndCheck( "POST", self.upload_url.split("{?")[0], parameters=post_parameters, headers=headers, input=path ) return github.GitReleaseAsset.GitReleaseAsset(self._requester, resp_headers, data, completed=True)
[ "def", "upload_asset", "(", "self", ",", "path", ",", "label", "=", "\"\"", ",", "content_type", "=", "\"\"", ")", ":", "assert", "isinstance", "(", "path", ",", "(", "str", ",", "unicode", ")", ")", ",", "path", "assert", "isinstance", "(", "label", ...
:calls: `POST https://<upload_url>/repos/:owner/:repo/releases/:release_id/assets?name=foo.zip <https://developer.github.com/v3/repos/releases/#upload-a-release-asset>`_ :rtype: :class:`github.GitReleaseAsset.GitReleaseAsset`
[ ":", "calls", ":", "POST", "https", ":", "//", "<upload_url", ">", "/", "repos", "/", ":", "owner", "/", ":", "repo", "/", "releases", "/", ":", "release_id", "/", "assets?name", "=", "foo", ".", "zip", "<https", ":", "//", "developer", ".", "github"...
python
train
tanghaibao/jcvi
jcvi/algorithms/lpsolve.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/algorithms/lpsolve.py#L274-L283
def edges_to_path(edges): """ Connect edges and return a path. """ if not edges: return None G = edges_to_graph(edges) path = nx.topological_sort(G) return path
[ "def", "edges_to_path", "(", "edges", ")", ":", "if", "not", "edges", ":", "return", "None", "G", "=", "edges_to_graph", "(", "edges", ")", "path", "=", "nx", ".", "topological_sort", "(", "G", ")", "return", "path" ]
Connect edges and return a path.
[ "Connect", "edges", "and", "return", "a", "path", "." ]
python
train
materialsvirtuallab/monty
monty/termcolor.py
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/termcolor.py#L115-L145
def colored(text, color=None, on_color=None, attrs=None): """Colorize text. Available text colors: red, green, yellow, blue, magenta, cyan, white. Available text highlights: on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white. Available attributes: bold, dark, underline, blink, reverse, concealed. Example: colored('Hello, World!', 'red', 'on_grey', ['blue', 'blink']) colored('Hello, World!', 'green') """ if __ISON and os.getenv('ANSI_COLORS_DISABLED') is None: fmt_str = '\033[%dm%s' if color is not None: text = fmt_str % (COLORS[color], text) if on_color is not None: text = fmt_str % (HIGHLIGHTS[on_color], text) if attrs is not None: for attr in attrs: text = fmt_str % (ATTRIBUTES[attr], text) text += RESET return text
[ "def", "colored", "(", "text", ",", "color", "=", "None", ",", "on_color", "=", "None", ",", "attrs", "=", "None", ")", ":", "if", "__ISON", "and", "os", ".", "getenv", "(", "'ANSI_COLORS_DISABLED'", ")", "is", "None", ":", "fmt_str", "=", "'\\033[%dm%...
Colorize text. Available text colors: red, green, yellow, blue, magenta, cyan, white. Available text highlights: on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white. Available attributes: bold, dark, underline, blink, reverse, concealed. Example: colored('Hello, World!', 'red', 'on_grey', ['blue', 'blink']) colored('Hello, World!', 'green')
[ "Colorize", "text", "." ]
python
train
saltstack/salt
salt/modules/lxc.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L702-L874
def _network_conf(conf_tuples=None, **kwargs): ''' Network configuration defaults network_profile as for containers, we can either call this function either with a network_profile dict or network profile name in the kwargs nic_opts overrides or extra nics in the form {nic_name: {set: tings} ''' nic = kwargs.get('network_profile', None) ret = [] nic_opts = kwargs.get('nic_opts', {}) if nic_opts is None: # coming from elsewhere nic_opts = {} if not conf_tuples: conf_tuples = [] old = _get_veths(conf_tuples) if not old: old = {} # if we have a profile name, get the profile and load the network settings # this will obviously by default look for a profile called "eth0" # or by what is defined in nic_opts # and complete each nic settings by sane defaults if nic and isinstance(nic, (six.string_types, dict)): nicp = get_network_profile(nic) else: nicp = {} if DEFAULT_NIC not in nicp: nicp[DEFAULT_NIC] = {} kwargs = copy.deepcopy(kwargs) gateway = kwargs.pop('gateway', None) bridge = kwargs.get('bridge', None) if nic_opts: for dev, args in six.iteritems(nic_opts): ethx = nicp.setdefault(dev, {}) try: ethx = salt.utils.dictupdate.update(ethx, args) except AttributeError: raise SaltInvocationError('Invalid nic_opts configuration') ifs = [a for a in nicp] ifs += [a for a in old if a not in nicp] ifs.sort() gateway_set = False for dev in ifs: args = nicp.get(dev, {}) opts = nic_opts.get(dev, {}) if nic_opts else {} old_if = old.get(dev, {}) disable = opts.get('disable', args.get('disable', False)) if disable: continue mac = opts.get('mac', opts.get('hwaddr', args.get('mac', args.get('hwaddr', '')))) type_ = opts.get('type', args.get('type', '')) flags = opts.get('flags', args.get('flags', '')) link = opts.get('link', args.get('link', '')) ipv4 = opts.get('ipv4', args.get('ipv4', '')) ipv6 = opts.get('ipv6', args.get('ipv6', '')) infos = salt.utils.odict.OrderedDict([ ('lxc.network.type', { 'test': not type_, 'value': type_, 'old': old_if.get('lxc.network.type'), 'default': 'veth'}), ('lxc.network.name', { 'test': False, 'value': dev, 'old': dev, 'default': dev}), ('lxc.network.flags', { 'test': not flags, 'value': flags, 'old': old_if.get('lxc.network.flags'), 'default': 'up'}), ('lxc.network.link', { 'test': not link, 'value': link, 'old': old_if.get('lxc.network.link'), 'default': search_lxc_bridge()}), ('lxc.network.hwaddr', { 'test': not mac, 'value': mac, 'old': old_if.get('lxc.network.hwaddr'), 'default': salt.utils.network.gen_mac()}), ('lxc.network.ipv4', { 'test': not ipv4, 'value': ipv4, 'old': old_if.get('lxc.network.ipv4', ''), 'default': None}), ('lxc.network.ipv6', { 'test': not ipv6, 'value': ipv6, 'old': old_if.get('lxc.network.ipv6', ''), 'default': None})]) # for each parameter, if not explicitly set, the # config value present in the LXC configuration should # take precedence over the profile configuration for info in list(infos.keys()): bundle = infos[info] if bundle['test']: if bundle['old']: bundle['value'] = bundle['old'] elif bundle['default']: bundle['value'] = bundle['default'] for info, data in six.iteritems(infos): if data['value']: ret.append({info: data['value']}) for key, val in six.iteritems(args): if key == 'link' and bridge: val = bridge val = opts.get(key, val) if key in [ 'type', 'flags', 'name', 'gateway', 'mac', 'link', 'ipv4', 'ipv6' ]: continue ret.append({'lxc.network.{0}'.format(key): val}) # gateway (in automode) must be appended following network conf ! if not gateway: gateway = args.get('gateway', None) if gateway is not None and not gateway_set: ret.append({'lxc.network.ipv4.gateway': gateway}) # only one network gateway ;) gateway_set = True # normally, this won't happen # set the gateway if specified even if we did # not managed the network underlying if gateway is not None and not gateway_set: ret.append({'lxc.network.ipv4.gateway': gateway}) # only one network gateway ;) gateway_set = True new = _get_veths(ret) # verify that we did not loose the mac settings for iface in [a for a in new]: ndata = new[iface] nmac = ndata.get('lxc.network.hwaddr', '') ntype = ndata.get('lxc.network.type', '') omac, otype = '', '' if iface in old: odata = old[iface] omac = odata.get('lxc.network.hwaddr', '') otype = odata.get('lxc.network.type', '') # default for network type is setted here # attention not to change the network type # without a good and explicit reason to. if otype and not ntype: ntype = otype if not ntype: ntype = 'veth' new[iface]['lxc.network.type'] = ntype if omac and not nmac: new[iface]['lxc.network.hwaddr'] = omac ret = [] for val in six.itervalues(new): for row in val: ret.append(salt.utils.odict.OrderedDict([(row, val[row])])) # on old versions of lxc, still support the gateway auto mode # if we didn't explicitly say no to # (lxc.network.ipv4.gateway: auto) if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \ True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \ True in ['lxc.network.ipv4' in a for a in ret]: ret.append({'lxc.network.ipv4.gateway': 'auto'}) return ret
[ "def", "_network_conf", "(", "conf_tuples", "=", "None", ",", "*", "*", "kwargs", ")", ":", "nic", "=", "kwargs", ".", "get", "(", "'network_profile'", ",", "None", ")", "ret", "=", "[", "]", "nic_opts", "=", "kwargs", ".", "get", "(", "'nic_opts'", ...
Network configuration defaults network_profile as for containers, we can either call this function either with a network_profile dict or network profile name in the kwargs nic_opts overrides or extra nics in the form {nic_name: {set: tings}
[ "Network", "configuration", "defaults" ]
python
train
datacats/datacats
datacats/cli/manage.py
https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/cli/manage.py#L74-L140
def reload_(environment, opts): """Reload environment source and configuration Usage: datacats reload [-b] [-p|--no-watch] [--syslog] [-s NAME] [--site-url=SITE_URL] [-i] [--address=IP] [ENVIRONMENT [PORT]] datacats reload -r [-b] [--syslog] [-s NAME] [--address=IP] [--site-url=SITE_URL] [-i] [ENVIRONMENT] Options: --address=IP Address to listen on (Linux-only) -i --interactive Calls out to docker via the command line, allowing for interactivity with the web image. --site-url=SITE_URL The site_url to use in API responses. Can use Python template syntax to insert the port and address (e.g. http://example.org:{port}/) -b --background Don't wait for response from web server --no-watch Do not automatically reload templates and .py files on change -p --production Reload with apache and debug=false -s --site=NAME Specify a site to reload [default: primary] --syslog Log to the syslog ENVIRONMENT may be an environment name or a path to an environment directory. Default: '.' """ if opts['--interactive']: # We can't wait for the server if we're tty'd opts['--background'] = True if opts['--address'] and is_boot2docker(): raise DatacatsError('Cannot specify address on boot2docker.') environment.require_data() environment.stop_ckan() if opts['PORT'] or opts['--address'] or opts['--site-url']: if opts['PORT']: environment.port = int(opts['PORT']) if opts['--address']: environment.address = opts['--address'] if opts['--site-url']: site_url = opts['--site-url'] # TODO: Check it against a regex or use urlparse try: site_url = site_url.format(address=environment.address, port=environment.port) environment.site_url = site_url environment.save_site(False) except (KeyError, IndexError, ValueError) as e: raise DatacatsError('Could not parse site_url: {}'.format(e)) environment.save() for container in environment.extra_containers: require_extra_image(EXTRA_IMAGE_MAPPING[container]) environment.stop_supporting_containers() environment.start_supporting_containers() environment.start_ckan( production=opts['--production'], paster_reload=not opts['--no-watch'], log_syslog=opts['--syslog'], interactive=opts['--interactive']) write('Starting web server at {0} ...'.format(environment.web_address())) if opts['--background']: write('\n') return try: environment.wait_for_web_available() finally: write('\n')
[ "def", "reload_", "(", "environment", ",", "opts", ")", ":", "if", "opts", "[", "'--interactive'", "]", ":", "# We can't wait for the server if we're tty'd", "opts", "[", "'--background'", "]", "=", "True", "if", "opts", "[", "'--address'", "]", "and", "is_boot2...
Reload environment source and configuration Usage: datacats reload [-b] [-p|--no-watch] [--syslog] [-s NAME] [--site-url=SITE_URL] [-i] [--address=IP] [ENVIRONMENT [PORT]] datacats reload -r [-b] [--syslog] [-s NAME] [--address=IP] [--site-url=SITE_URL] [-i] [ENVIRONMENT] Options: --address=IP Address to listen on (Linux-only) -i --interactive Calls out to docker via the command line, allowing for interactivity with the web image. --site-url=SITE_URL The site_url to use in API responses. Can use Python template syntax to insert the port and address (e.g. http://example.org:{port}/) -b --background Don't wait for response from web server --no-watch Do not automatically reload templates and .py files on change -p --production Reload with apache and debug=false -s --site=NAME Specify a site to reload [default: primary] --syslog Log to the syslog ENVIRONMENT may be an environment name or a path to an environment directory. Default: '.'
[ "Reload", "environment", "source", "and", "configuration" ]
python
train
sanger-pathogens/Fastaq
pyfastaq/tasks.py
https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/tasks.py#L686-L721
def split_by_base_count(infile, outfiles_prefix, max_bases, max_seqs=None): '''Splits a fasta/q file into separate files, file size determined by number of bases. Puts <= max_bases in each split file The exception is a single sequence >=max_bases is put in its own file. This does not split sequences. ''' seq_reader = sequences.file_reader(infile) base_count = 0 file_count = 1 seq_count = 0 fout = None if max_seqs is None: max_seqs = float('inf') for seq in seq_reader: if base_count == 0: fout = utils.open_file_write(outfiles_prefix + '.' + str(file_count)) file_count += 1 if base_count + len(seq) > max_bases or seq_count >= max_seqs: if base_count == 0: print(seq, file=fout) utils.close(fout) else: utils.close(fout) fout = utils.open_file_write(outfiles_prefix + '.' + str(file_count)) print(seq, file=fout) base_count = len(seq) file_count += 1 seq_count = 1 else: base_count += len(seq) seq_count += 1 print(seq, file=fout) utils.close(fout)
[ "def", "split_by_base_count", "(", "infile", ",", "outfiles_prefix", ",", "max_bases", ",", "max_seqs", "=", "None", ")", ":", "seq_reader", "=", "sequences", ".", "file_reader", "(", "infile", ")", "base_count", "=", "0", "file_count", "=", "1", "seq_count", ...
Splits a fasta/q file into separate files, file size determined by number of bases. Puts <= max_bases in each split file The exception is a single sequence >=max_bases is put in its own file. This does not split sequences.
[ "Splits", "a", "fasta", "/", "q", "file", "into", "separate", "files", "file", "size", "determined", "by", "number", "of", "bases", "." ]
python
valid
earwig/mwparserfromhell
mwparserfromhell/wikicode.py
https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/wikicode.py#L390-L411
def insert_before(self, obj, value, recursive=True): """Insert *value* immediately before *obj*. *obj* can be either a string, a :class:`.Node`, or another :class:`.Wikicode` object (as created by :meth:`get_sections`, for example). If *obj* is a string, we will operate on all instances of that string within the code, otherwise only on the specific instance given. *value* can be anything parsable by :func:`.parse_anything`. If *recursive* is ``True``, we will try to find *obj* within our child nodes even if it is not a direct descendant of this :class:`.Wikicode` object. If *obj* is not found, :exc:`ValueError` is raised. """ if isinstance(obj, (Node, Wikicode)): context, index = self._do_strong_search(obj, recursive) context.insert(index.start, value) else: for exact, context, index in self._do_weak_search(obj, recursive): if exact: context.insert(index.start, value) else: obj = str(obj) self._slice_replace(context, index, obj, str(value) + obj)
[ "def", "insert_before", "(", "self", ",", "obj", ",", "value", ",", "recursive", "=", "True", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "Node", ",", "Wikicode", ")", ")", ":", "context", ",", "index", "=", "self", ".", "_do_strong_search", ...
Insert *value* immediately before *obj*. *obj* can be either a string, a :class:`.Node`, or another :class:`.Wikicode` object (as created by :meth:`get_sections`, for example). If *obj* is a string, we will operate on all instances of that string within the code, otherwise only on the specific instance given. *value* can be anything parsable by :func:`.parse_anything`. If *recursive* is ``True``, we will try to find *obj* within our child nodes even if it is not a direct descendant of this :class:`.Wikicode` object. If *obj* is not found, :exc:`ValueError` is raised.
[ "Insert", "*", "value", "*", "immediately", "before", "*", "obj", "*", "." ]
python
train
rigetti/quantumflow
examples/state_prep_w16.py
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/examples/state_prep_w16.py#L27-L114
def w16_circuit() -> qf.Circuit: """ Return a circuit that prepares the the 16-qubit W state using\ sqrt(iswaps) and local gates, respecting linear topology """ gates = [ qf.X(7), qf.ISWAP(7, 8) ** 0.5, qf.S(8), qf.Z(8), qf.SWAP(7, 6), qf.SWAP(6, 5), qf.SWAP(5, 4), qf.SWAP(8, 9), qf.SWAP(9, 10), qf.SWAP(10, 11), qf.ISWAP(4, 3) ** 0.5, qf.S(3), qf.Z(3), qf.ISWAP(11, 12) ** 0.5, qf.S(12), qf.Z(12), qf.SWAP(3, 2), qf.SWAP(4, 5), qf.SWAP(11, 10), qf.SWAP(12, 13), qf.ISWAP(2, 1) ** 0.5, qf.S(1), qf.Z(1), qf.ISWAP(5, 6) ** 0.5, qf.S(6), qf.Z(6), qf.ISWAP(10, 9) ** 0.5, qf.S(9), qf.Z(9), qf.ISWAP(13, 14) ** 0.5, qf.S(14), qf.Z(14), qf.ISWAP(1, 0) ** 0.5, qf.S(0), qf.Z(0), qf.ISWAP(2, 3) ** 0.5, qf.S(3), qf.Z(3), qf.ISWAP(5, 4) ** 0.5, qf.S(4), qf.Z(4), qf.ISWAP(6, 7) ** 0.5, qf.S(7), qf.Z(7), qf.ISWAP(9, 8) ** 0.5, qf.S(8), qf.Z(8), qf.ISWAP(10, 11) ** 0.5, qf.S(11), qf.Z(11), qf.ISWAP(13, 12) ** 0.5, qf.S(12), qf.Z(12), qf.ISWAP(14, 15) ** 0.5, qf.S(15), qf.Z(15), ] circ = qf.Circuit(gates) return circ
[ "def", "w16_circuit", "(", ")", "->", "qf", ".", "Circuit", ":", "gates", "=", "[", "qf", ".", "X", "(", "7", ")", ",", "qf", ".", "ISWAP", "(", "7", ",", "8", ")", "**", "0.5", ",", "qf", ".", "S", "(", "8", ")", ",", "qf", ".", "Z", "...
Return a circuit that prepares the the 16-qubit W state using\ sqrt(iswaps) and local gates, respecting linear topology
[ "Return", "a", "circuit", "that", "prepares", "the", "the", "16", "-", "qubit", "W", "state", "using", "\\", "sqrt", "(", "iswaps", ")", "and", "local", "gates", "respecting", "linear", "topology" ]
python
train
rorr73/LifeSOSpy
lifesospy/util.py
https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/util.py#L30-L49
def from_ascii_hex(text: str) -> int: """Converts to an int value from both ASCII and regular hex. The format used appears to vary based on whether the command was to get an existing value (regular hex) or set a new value (ASCII hex mirrored back from original command). Regular hex: 0123456789abcdef ASCII hex: 0123456789:;<=>? """ value = 0 for index in range(0, len(text)): char_ord = ord(text[index:index + 1]) if char_ord in range(ord('0'), ord('?') + 1): digit = char_ord - ord('0') elif char_ord in range(ord('a'), ord('f') + 1): digit = 0xa + (char_ord - ord('a')) else: raise ValueError( "Response contains invalid character.") value = (value * 0x10) + digit return value
[ "def", "from_ascii_hex", "(", "text", ":", "str", ")", "->", "int", ":", "value", "=", "0", "for", "index", "in", "range", "(", "0", ",", "len", "(", "text", ")", ")", ":", "char_ord", "=", "ord", "(", "text", "[", "index", ":", "index", "+", "...
Converts to an int value from both ASCII and regular hex. The format used appears to vary based on whether the command was to get an existing value (regular hex) or set a new value (ASCII hex mirrored back from original command). Regular hex: 0123456789abcdef ASCII hex: 0123456789:;<=>?
[ "Converts", "to", "an", "int", "value", "from", "both", "ASCII", "and", "regular", "hex", ".", "The", "format", "used", "appears", "to", "vary", "based", "on", "whether", "the", "command", "was", "to", "get", "an", "existing", "value", "(", "regular", "h...
python
train
log2timeline/dfwinreg
dfwinreg/fake.py
https://github.com/log2timeline/dfwinreg/blob/9d488bb1db562197dbfb48de9613d6b29dea056e/dfwinreg/fake.py#L208-L225
def AddSubkey(self, registry_key): """Adds a subkey. Args: registry_key (WinRegistryKey): Windows Registry subkey. Raises: KeyError: if the subkey already exists. """ name = registry_key.name.upper() if name in self._subkeys: raise KeyError( 'Subkey: {0:s} already exists.'.format(registry_key.name)) self._subkeys[name] = registry_key key_path = key_paths.JoinKeyPath([self._key_path, registry_key.name]) registry_key._key_path = key_path
[ "def", "AddSubkey", "(", "self", ",", "registry_key", ")", ":", "name", "=", "registry_key", ".", "name", ".", "upper", "(", ")", "if", "name", "in", "self", ".", "_subkeys", ":", "raise", "KeyError", "(", "'Subkey: {0:s} already exists.'", ".", "format", ...
Adds a subkey. Args: registry_key (WinRegistryKey): Windows Registry subkey. Raises: KeyError: if the subkey already exists.
[ "Adds", "a", "subkey", "." ]
python
train
openstack/networking-cisco
networking_cisco/ml2_drivers/ucsm/ucsm_network_driver.py
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/ucsm/ucsm_network_driver.py#L747-L790
def _remove_vlan_from_all_service_profiles(self, handle, vlan_id, ucsm_ip): """Deletes VLAN Profile config from server's ethernet ports.""" service_profile_list = [] for key, value in six.iteritems(self.ucsm_sp_dict): if (ucsm_ip in key) and value: service_profile_list.append(value) if not service_profile_list: # Nothing to do return try: for service_profile in service_profile_list: virtio_port_list = ( CONF.ml2_cisco_ucsm.ucsms[ucsm_ip].ucsm_virtio_eth_ports) eth_port_paths = ["%s%s" % (service_profile, ep) for ep in virtio_port_list] # 1. From the Service Profile config, access the # configuration for its ports. # 2. Check if that Vlan has been configured on each port # 3. If Vlan config found, remove it. obj = handle.query_dn(service_profile) if obj: # Check if this vlan_id has been configured on the # ports in this Service profile for eth_port_path in eth_port_paths: eth = handle.query_dn(eth_port_path) if eth: vlan_name = self.make_vlan_name(vlan_id) vlan_path = eth_port_path + "/if-" + vlan_name vlan = handle.query_dn(vlan_path) if vlan: # Found vlan config. Now remove it. handle.remove_mo(vlan) handle.commit() except Exception as e: # Raise a Neutron exception. Include a description of # the original exception. raise cexc.UcsmConfigDeleteFailed(config=vlan_id, ucsm_ip=ucsm_ip, exc=e)
[ "def", "_remove_vlan_from_all_service_profiles", "(", "self", ",", "handle", ",", "vlan_id", ",", "ucsm_ip", ")", ":", "service_profile_list", "=", "[", "]", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "self", ".", "ucsm_sp_dict", ")", ":...
Deletes VLAN Profile config from server's ethernet ports.
[ "Deletes", "VLAN", "Profile", "config", "from", "server", "s", "ethernet", "ports", "." ]
python
train
IAMconsortium/pyam
pyam/core.py
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L709-L747
def check_aggregate(self, variable, components=None, exclude_on_fail=False, multiplier=1, **kwargs): """Check whether a timeseries matches the aggregation of its components Parameters ---------- variable: str variable to be checked for matching aggregation of sub-categories components: list of str, default None list of variables, defaults to all sub-categories of `variable` exclude_on_fail: boolean, default False flag scenarios failing validation as `exclude: True` multiplier: number, default 1 factor when comparing variable and sum of components kwargs: passed to `np.isclose()` """ # compute aggregate from components, return None if no components df_components = self.aggregate(variable, components) if df_components is None: return # filter and groupby data, use `pd.Series.align` for matching index rows = self._apply_filters(variable=variable) df_variable, df_components = ( _aggregate(self.data[rows], 'variable').align(df_components) ) # use `np.isclose` for checking match diff = df_variable[~np.isclose(df_variable, multiplier * df_components, **kwargs)] if len(diff): msg = '`{}` - {} of {} rows are not aggregates of components' logger().info(msg.format(variable, len(diff), len(df_variable))) if exclude_on_fail: self._exclude_on_fail(diff.index.droplevel([2, 3, 4])) return IamDataFrame(diff, variable=variable).timeseries()
[ "def", "check_aggregate", "(", "self", ",", "variable", ",", "components", "=", "None", ",", "exclude_on_fail", "=", "False", ",", "multiplier", "=", "1", ",", "*", "*", "kwargs", ")", ":", "# compute aggregate from components, return None if no components", "df_com...
Check whether a timeseries matches the aggregation of its components Parameters ---------- variable: str variable to be checked for matching aggregation of sub-categories components: list of str, default None list of variables, defaults to all sub-categories of `variable` exclude_on_fail: boolean, default False flag scenarios failing validation as `exclude: True` multiplier: number, default 1 factor when comparing variable and sum of components kwargs: passed to `np.isclose()`
[ "Check", "whether", "a", "timeseries", "matches", "the", "aggregation", "of", "its", "components" ]
python
train
monkeython/scriba
scriba/schemes/scriba_ftps.py
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/schemes/scriba_ftps.py#L27-L30
def write(url, content, **args): """Put an object into a ftps URL.""" with FTPSResource(url, **args) as resource: resource.write(content)
[ "def", "write", "(", "url", ",", "content", ",", "*", "*", "args", ")", ":", "with", "FTPSResource", "(", "url", ",", "*", "*", "args", ")", "as", "resource", ":", "resource", ".", "write", "(", "content", ")" ]
Put an object into a ftps URL.
[ "Put", "an", "object", "into", "a", "ftps", "URL", "." ]
python
train
ajyoon/blur
blur/rand.py
https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/rand.py#L106-L140
def _clamp_value(value, minimum, maximum): """ Clamp a value to fit between a minimum and a maximum. * If ``value`` is between ``minimum`` and ``maximum``, return ``value`` * If ``value`` is below ``minimum``, return ``minimum`` * If ``value is above ``maximum``, return ``maximum`` Args: value (float or int): The number to clamp minimum (float or int): The lowest allowed return value maximum (float or int): The highest allowed return value Returns: float or int: the clamped value Raises: ValueError: if maximum < minimum Example: >>> _clamp_value(3, 5, 10) 5 >>> _clamp_value(11, 5, 10) 10 >>> _clamp_value(8, 5, 10) 8 """ if maximum < minimum: raise ValueError if value < minimum: return minimum elif value > maximum: return maximum else: return value
[ "def", "_clamp_value", "(", "value", ",", "minimum", ",", "maximum", ")", ":", "if", "maximum", "<", "minimum", ":", "raise", "ValueError", "if", "value", "<", "minimum", ":", "return", "minimum", "elif", "value", ">", "maximum", ":", "return", "maximum", ...
Clamp a value to fit between a minimum and a maximum. * If ``value`` is between ``minimum`` and ``maximum``, return ``value`` * If ``value`` is below ``minimum``, return ``minimum`` * If ``value is above ``maximum``, return ``maximum`` Args: value (float or int): The number to clamp minimum (float or int): The lowest allowed return value maximum (float or int): The highest allowed return value Returns: float or int: the clamped value Raises: ValueError: if maximum < minimum Example: >>> _clamp_value(3, 5, 10) 5 >>> _clamp_value(11, 5, 10) 10 >>> _clamp_value(8, 5, 10) 8
[ "Clamp", "a", "value", "to", "fit", "between", "a", "minimum", "and", "a", "maximum", "." ]
python
train
radjkarl/imgProcessor
imgProcessor/features/PatternRecognition.py
https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/features/PatternRecognition.py#L108-L196
def findHomography(self, img, drawMatches=False): ''' Find homography of the image through pattern comparison with the base image ''' print("\t Finding points...") # Find points in the next frame img = self._prepareImage(img) features, descs = self.detector.detectAndCompute(img, None) ###################### # TODO: CURRENTLY BROKEN IN OPENCV3.1 - WAITNG FOR NEW RELEASE 3.2 # matches = self.matcher.knnMatch(descs,#.astype(np.float32), # self.base_descs, # k=3) # print("\t Match Count: ", len(matches)) # matches_subset = self._filterMatches(matches) # its working alternative (for now): bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) matches_subset = bf.match(descs, self.base_descs) ###################### # matches = bf.knnMatch(descs,self.base_descs, k=2) # # Apply ratio test # matches_subset = [] # medDist = np.median([m.distance for m in matches]) # matches_subset = [m for m in matches if m.distance < medDist] # for m in matches: # print(m.distance) # for m,n in matches: # if m.distance < 0.75*n.distance: # matches_subset.append([m]) if not len(matches_subset): raise Exception('no matches found') print("\t Filtered Match Count: ", len(matches_subset)) distance = sum([m.distance for m in matches_subset]) print("\t Distance from Key Image: ", distance) averagePointDistance = distance / (len(matches_subset)) print("\t Average Distance: ", averagePointDistance) kp1 = [] kp2 = [] for match in matches_subset: kp1.append(self.base_features[match.trainIdx]) kp2.append(features[match.queryIdx]) # /self._fH #scale with _fH, if image was resized p1 = np.array([k.pt for k in kp1]) p2 = np.array([k.pt for k in kp2]) # /self._fH H, status = cv2.findHomography(p1, p2, cv2.RANSAC, # method 5.0 # max reprojection error (1...10) ) if status is None: raise Exception('no homography found') else: inliers = np.sum(status) print('%d / %d inliers/matched' % (inliers, len(status))) inlierRatio = inliers / len(status) if self.minInlierRatio > inlierRatio or inliers < self.minInliers: raise Exception('bad fit!') # scale with _fH, if image was resized # see # http://answers.opencv.org/question/26173/the-relationship-between-homography-matrix-and-scaling-images/ s = np.eye(3, 3) s[0, 0] = 1 / self._fH s[1, 1] = 1 / self._fH H = s.dot(H).dot(np.linalg.inv(s)) if drawMatches: # s0,s1 = img.shape # out = np.empty(shape=(s0,s1,3), dtype=np.uint8) img = draw_matches(self.base8bit, self.base_features, img, features, matches_subset[:20], # None,#out, # flags=2 thickness=5 ) return (H, inliers, inlierRatio, averagePointDistance, img, features, descs, len(matches_subset))
[ "def", "findHomography", "(", "self", ",", "img", ",", "drawMatches", "=", "False", ")", ":", "print", "(", "\"\\t Finding points...\"", ")", "# Find points in the next frame\r", "img", "=", "self", ".", "_prepareImage", "(", "img", ")", "features", ",", "descs"...
Find homography of the image through pattern comparison with the base image
[ "Find", "homography", "of", "the", "image", "through", "pattern", "comparison", "with", "the", "base", "image" ]
python
train
gagneurlab/concise
concise/metrics.py
https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/metrics.py#L76-L80
def fdr(y, z): """False discovery rate `fp / (tp + fp)` """ tp, tn, fp, fn = contingency_table(y, z) return fp / (tp + fp)
[ "def", "fdr", "(", "y", ",", "z", ")", ":", "tp", ",", "tn", ",", "fp", ",", "fn", "=", "contingency_table", "(", "y", ",", "z", ")", "return", "fp", "/", "(", "tp", "+", "fp", ")" ]
False discovery rate `fp / (tp + fp)`
[ "False", "discovery", "rate", "fp", "/", "(", "tp", "+", "fp", ")" ]
python
train
F5Networks/f5-common-python
f5/bigip/mixins.py
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/mixins.py#L463-L468
def _return_object(self, container, item_name): """Helper method to retrieve the object""" coll = container.get_collection() for item in coll: if item.name == item_name: return item
[ "def", "_return_object", "(", "self", ",", "container", ",", "item_name", ")", ":", "coll", "=", "container", ".", "get_collection", "(", ")", "for", "item", "in", "coll", ":", "if", "item", ".", "name", "==", "item_name", ":", "return", "item" ]
Helper method to retrieve the object
[ "Helper", "method", "to", "retrieve", "the", "object" ]
python
train
serge-sans-paille/pythran
pythran/types/types.py
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/types.py#L564-L575
def visit_Dict(self, node): """ Define set type from all elements type (or empty_dict type). """ self.generic_visit(node) if node.keys: for key, value in zip(node.keys, node.values): value_type = self.result[value] self.combine(node, key, unary_op=partial(self.builder.DictType, of_val=value_type)) else: self.result[node] = self.builder.NamedType( "pythonic::types::empty_dict")
[ "def", "visit_Dict", "(", "self", ",", "node", ")", ":", "self", ".", "generic_visit", "(", "node", ")", "if", "node", ".", "keys", ":", "for", "key", ",", "value", "in", "zip", "(", "node", ".", "keys", ",", "node", ".", "values", ")", ":", "val...
Define set type from all elements type (or empty_dict type).
[ "Define", "set", "type", "from", "all", "elements", "type", "(", "or", "empty_dict", "type", ")", "." ]
python
train
tonybaloney/wily
wily/config.py
https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/config.py#L112-L143
def load(config_path=DEFAULT_CONFIG_PATH): """ Load config file and set values to defaults where no present. :return: The configuration ``WilyConfig`` :rtype: :class:`wily.config.WilyConfig` """ if not pathlib.Path(config_path).exists(): logger.debug(f"Could not locate {config_path}, using default config.") return DEFAULT_CONFIG config = configparser.ConfigParser(default_section=DEFAULT_CONFIG_SECTION) config.read(config_path) operators = config.get( section=DEFAULT_CONFIG_SECTION, option="operators", fallback=DEFAULT_OPERATORS ) archiver = config.get( section=DEFAULT_CONFIG_SECTION, option="archiver", fallback=DEFAULT_ARCHIVER ) path = config.get(section=DEFAULT_CONFIG_SECTION, option="path", fallback=".") max_revisions = int( config.get( section=DEFAULT_CONFIG_SECTION, option="max_revisions", fallback=DEFAULT_MAX_REVISIONS, ) ) return WilyConfig( operators=operators, archiver=archiver, path=path, max_revisions=max_revisions )
[ "def", "load", "(", "config_path", "=", "DEFAULT_CONFIG_PATH", ")", ":", "if", "not", "pathlib", ".", "Path", "(", "config_path", ")", ".", "exists", "(", ")", ":", "logger", ".", "debug", "(", "f\"Could not locate {config_path}, using default config.\"", ")", "...
Load config file and set values to defaults where no present. :return: The configuration ``WilyConfig`` :rtype: :class:`wily.config.WilyConfig`
[ "Load", "config", "file", "and", "set", "values", "to", "defaults", "where", "no", "present", "." ]
python
train
Microsoft/knack
knack/util.py
https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/util.py#L60-L83
def todict(obj, post_processor=None): # pylint: disable=too-many-return-statements """ Convert an object to a dictionary. Use 'post_processor(original_obj, dictionary)' to update the dictionary in the process """ if isinstance(obj, dict): result = {k: todict(v, post_processor) for (k, v) in obj.items()} return post_processor(obj, result) if post_processor else result if isinstance(obj, list): return [todict(a, post_processor) for a in obj] if isinstance(obj, Enum): return obj.value if isinstance(obj, (date, time, datetime)): return obj.isoformat() if isinstance(obj, timedelta): return str(obj) if hasattr(obj, '_asdict'): return todict(obj._asdict(), post_processor) if hasattr(obj, '__dict__'): result = {to_camel_case(k): todict(v, post_processor) for k, v in obj.__dict__.items() if not callable(v) and not k.startswith('_')} return post_processor(obj, result) if post_processor else result return obj
[ "def", "todict", "(", "obj", ",", "post_processor", "=", "None", ")", ":", "# pylint: disable=too-many-return-statements", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "result", "=", "{", "k", ":", "todict", "(", "v", ",", "post_processor", ")", ...
Convert an object to a dictionary. Use 'post_processor(original_obj, dictionary)' to update the dictionary in the process
[ "Convert", "an", "object", "to", "a", "dictionary", ".", "Use", "post_processor", "(", "original_obj", "dictionary", ")", "to", "update", "the", "dictionary", "in", "the", "process" ]
python
train
DistrictDataLabs/yellowbrick
yellowbrick/classifier/prcurve.py
https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/classifier/prcurve.py#L329-L366
def _get_y_scores(self, X): """ The ``precision_recall_curve`` metric requires target scores that can either be the probability estimates of the positive class, confidence values, or non-thresholded measures of decisions (as returned by a "decision function"). """ # TODO refactor shared method with ROCAUC # Resolution order of scoring functions attrs = ( 'decision_function', 'predict_proba', ) # Return the first resolved function for attr in attrs: try: method = getattr(self.estimator, attr, None) if method: # Compute the scores from the decision function y_scores = method(X) # Return only the positive class for binary predict_proba if self.target_type_ == BINARY and y_scores.ndim == 2: return y_scores[:,1] return y_scores except AttributeError: # Some Scikit-Learn estimators have both probability and # decision functions but override __getattr__ and raise an # AttributeError on access. continue # If we've gotten this far, we can't do anything raise ModelError(( "{} requires estimators with predict_proba or decision_function methods." ).format(self.__class__.__name__))
[ "def", "_get_y_scores", "(", "self", ",", "X", ")", ":", "# TODO refactor shared method with ROCAUC", "# Resolution order of scoring functions", "attrs", "=", "(", "'decision_function'", ",", "'predict_proba'", ",", ")", "# Return the first resolved function", "for", "attr", ...
The ``precision_recall_curve`` metric requires target scores that can either be the probability estimates of the positive class, confidence values, or non-thresholded measures of decisions (as returned by a "decision function").
[ "The", "precision_recall_curve", "metric", "requires", "target", "scores", "that", "can", "either", "be", "the", "probability", "estimates", "of", "the", "positive", "class", "confidence", "values", "or", "non", "-", "thresholded", "measures", "of", "decisions", "...
python
train
josiahcarlson/rom
rom/query.py
https://github.com/josiahcarlson/rom/blob/8b5607a856341df85df33422accc30ba9294dbdb/rom/query.py#L691-L705
def first(self): ''' Returns only the first result from the query, if any. ''' lim = [0, 1] if self._limit: lim[0] = self._limit[0] if not self._filters and not self._order_by: for ent in self: return ent return None ids = self.limit(*lim)._search() if ids: return self._model.get(ids[0]) return None
[ "def", "first", "(", "self", ")", ":", "lim", "=", "[", "0", ",", "1", "]", "if", "self", ".", "_limit", ":", "lim", "[", "0", "]", "=", "self", ".", "_limit", "[", "0", "]", "if", "not", "self", ".", "_filters", "and", "not", "self", ".", ...
Returns only the first result from the query, if any.
[ "Returns", "only", "the", "first", "result", "from", "the", "query", "if", "any", "." ]
python
test
Netuitive/netuitive-client-python
netuitive/element.py
https://github.com/Netuitive/netuitive-client-python/blob/16426ade6a5dc0888ce978c97b02663a9713fc16/netuitive/element.py#L43-L50
def merge_metrics(self): """ Merge metrics in the internal _metrics dict to metrics list and delete the internal _metrics """ self.metrics.extend(self._metrics.values()) del self._metrics
[ "def", "merge_metrics", "(", "self", ")", ":", "self", ".", "metrics", ".", "extend", "(", "self", ".", "_metrics", ".", "values", "(", ")", ")", "del", "self", ".", "_metrics" ]
Merge metrics in the internal _metrics dict to metrics list and delete the internal _metrics
[ "Merge", "metrics", "in", "the", "internal", "_metrics", "dict", "to", "metrics", "list", "and", "delete", "the", "internal", "_metrics" ]
python
train
lemieuxl/pyplink
pyplink/pyplink.py
https://github.com/lemieuxl/pyplink/blob/31d47c86f589064bda98206314a2d0b20e7fd2f0/pyplink/pyplink.py#L445-L471
def iter_geno_marker(self, markers, return_index=False): """Iterates over genotypes for a list of markers. Args: markers (list): The list of markers to iterate onto. return_index (bool): Wether to return the marker's index or not. Returns: tuple: The name of the marker as a string, and its genotypes as a :py:class:`numpy.ndarray` (additive format). """ if self._mode != "r": raise UnsupportedOperation("not available in 'w' mode") # If string, we change to list if isinstance(markers, str): markers = [markers] # Iterating over all markers if return_index: for marker in markers: geno, seek = self.get_geno_marker(marker, return_index=True) yield marker, geno, seek else: for marker in markers: yield marker, self.get_geno_marker(marker)
[ "def", "iter_geno_marker", "(", "self", ",", "markers", ",", "return_index", "=", "False", ")", ":", "if", "self", ".", "_mode", "!=", "\"r\"", ":", "raise", "UnsupportedOperation", "(", "\"not available in 'w' mode\"", ")", "# If string, we change to list", "if", ...
Iterates over genotypes for a list of markers. Args: markers (list): The list of markers to iterate onto. return_index (bool): Wether to return the marker's index or not. Returns: tuple: The name of the marker as a string, and its genotypes as a :py:class:`numpy.ndarray` (additive format).
[ "Iterates", "over", "genotypes", "for", "a", "list", "of", "markers", "." ]
python
train
Azure/azure-sdk-for-python
build_package.py
https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/build_package.py#L29-L67
def travis_build_package(): """Assumed called on Travis, to prepare a package to be deployed This method prints on stdout for Travis. Return is obj to pass to sys.exit() directly """ travis_tag = os.environ.get('TRAVIS_TAG') if not travis_tag: print("TRAVIS_TAG environment variable is not present") return "TRAVIS_TAG environment variable is not present" try: name, version = travis_tag.split("_") except ValueError: print("TRAVIS_TAG is not '<package_name>_<version>' (tag is: {})".format(travis_tag)) return "TRAVIS_TAG is not '<package_name>_<version>' (tag is: {})".format(travis_tag) try: version = Version(version) except InvalidVersion: print("Version must be a valid PEP440 version (version is: {})".format(version)) return "Version must be a valid PEP440 version (version is: {})".format(version) if name.lower() in OMITTED_RELEASE_PACKAGES: print("The input package {} has been disabled for release from Travis.CI.".format(name)) return abs_dist_path = Path(os.environ['TRAVIS_BUILD_DIR'], 'dist') create_package(name, str(abs_dist_path)) print("Produced:\n{}".format(list(abs_dist_path.glob('*')))) pattern = "*{}*".format(version) packages = list(abs_dist_path.glob(pattern)) if not packages: return "Package version does not match tag {}, abort".format(version) pypi_server = os.environ.get("PYPI_SERVER", "default PyPI server") print("Package created as expected and will be pushed to {}".format(pypi_server))
[ "def", "travis_build_package", "(", ")", ":", "travis_tag", "=", "os", ".", "environ", ".", "get", "(", "'TRAVIS_TAG'", ")", "if", "not", "travis_tag", ":", "print", "(", "\"TRAVIS_TAG environment variable is not present\"", ")", "return", "\"TRAVIS_TAG environment va...
Assumed called on Travis, to prepare a package to be deployed This method prints on stdout for Travis. Return is obj to pass to sys.exit() directly
[ "Assumed", "called", "on", "Travis", "to", "prepare", "a", "package", "to", "be", "deployed" ]
python
test
pycontribs/jira
jira/client.py
https://github.com/pycontribs/jira/blob/397db5d78441ed6a680a9b7db4c62030ade1fd8a/jira/client.py#L3753-L3761
def sprint_info(self, board_id, sprint_id): """Return the information about a sprint. :param board_id: the board retrieving issues from. Deprecated and ignored. :param sprint_id: the sprint retrieving issues from """ sprint = Sprint(self._options, self._session) sprint.find(sprint_id) return sprint.raw
[ "def", "sprint_info", "(", "self", ",", "board_id", ",", "sprint_id", ")", ":", "sprint", "=", "Sprint", "(", "self", ".", "_options", ",", "self", ".", "_session", ")", "sprint", ".", "find", "(", "sprint_id", ")", "return", "sprint", ".", "raw" ]
Return the information about a sprint. :param board_id: the board retrieving issues from. Deprecated and ignored. :param sprint_id: the sprint retrieving issues from
[ "Return", "the", "information", "about", "a", "sprint", "." ]
python
train
opennode/waldur-core
waldur_core/cost_tracking/views.py
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/views.py#L79-L101
def create(self, request, *args, **kwargs): """ Run **POST** request against */api/price-list-items/* to create new price list item. Customer owner and staff can create price items. Example of request: .. code-block:: http POST /api/price-list-items/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "units": "per month", "value": 100, "service": "http://example.com/api/oracle/d4060812ca5d4de390e0d7a5062d99f6/", "default_price_list_item": "http://example.com/api/default-price-list-items/349d11e28f634f48866089e41c6f71f1/" } """ return super(PriceListItemViewSet, self).create(request, *args, **kwargs)
[ "def", "create", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "PriceListItemViewSet", ",", "self", ")", ".", "create", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Run **POST** request against */api/price-list-items/* to create new price list item. Customer owner and staff can create price items. Example of request: .. code-block:: http POST /api/price-list-items/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "units": "per month", "value": 100, "service": "http://example.com/api/oracle/d4060812ca5d4de390e0d7a5062d99f6/", "default_price_list_item": "http://example.com/api/default-price-list-items/349d11e28f634f48866089e41c6f71f1/" }
[ "Run", "**", "POST", "**", "request", "against", "*", "/", "api", "/", "price", "-", "list", "-", "items", "/", "*", "to", "create", "new", "price", "list", "item", ".", "Customer", "owner", "and", "staff", "can", "create", "price", "items", "." ]
python
train
tanghaibao/jcvi
jcvi/formats/fasta.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L970-L1003
def ids(args): """ %prog ids fastafiles Generate the FASTA headers without the '>'. """ p = OptionParser(ids.__doc__) p.add_option("--until", default=None, help="Truncate the name and description at words [default: %default]") p.add_option("--description", default=False, action="store_true", help="Generate a second column with description [default: %default]") p.set_outfile() opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) until = opts.until fw = must_open(opts.outfile, "w") for row in must_open(args): if row[0] == ">": row = row[1:].rstrip() if until: row = row.split(until)[0] atoms = row.split(None, 1) if opts.description: outrow = "\t".join(atoms) else: outrow = atoms[0] print(outrow, file=fw) fw.close()
[ "def", "ids", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "ids", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--until\"", ",", "default", "=", "None", ",", "help", "=", "\"Truncate the name and description at words [default: %default]\"", ")", ...
%prog ids fastafiles Generate the FASTA headers without the '>'.
[ "%prog", "ids", "fastafiles" ]
python
train
listen-lavender/webcrawl
webcrawl/urlkit.py
https://github.com/listen-lavender/webcrawl/blob/905dcfa6e6934aac764045660c0efcef28eae1e6/webcrawl/urlkit.py#L12-L29
def urljoin(refurl, objurl): """ >>> urljoin('http://www.homeinns.com/hotel', 'http://www.homeinns.com/beijing') 'http://www.homeinns.com/beijing' >>> urljoin('http://www.homeinns.com/hotel', '/beijing') 'http://www.homeinns.com/beijing' >>> urljoin('http://www.homeinns.com/hotel', 'beijing') 'http://www.homeinns.com/beijing' """ if objurl.strip() in ('', '#'): return '' elif objurl.startswith('http'): return objurl elif objurl.startswith('/'): refurl = refurl.replace('//', '{$$}') return ''.join([refurl[:refurl.index('/')].replace('{$$}', '//'), objurl]) else: return '/'.join([refurl[:refurl.rindex('/')], objurl])
[ "def", "urljoin", "(", "refurl", ",", "objurl", ")", ":", "if", "objurl", ".", "strip", "(", ")", "in", "(", "''", ",", "'#'", ")", ":", "return", "''", "elif", "objurl", ".", "startswith", "(", "'http'", ")", ":", "return", "objurl", "elif", "obju...
>>> urljoin('http://www.homeinns.com/hotel', 'http://www.homeinns.com/beijing') 'http://www.homeinns.com/beijing' >>> urljoin('http://www.homeinns.com/hotel', '/beijing') 'http://www.homeinns.com/beijing' >>> urljoin('http://www.homeinns.com/hotel', 'beijing') 'http://www.homeinns.com/beijing'
[ ">>>", "urljoin", "(", "http", ":", "//", "www", ".", "homeinns", ".", "com", "/", "hotel", "http", ":", "//", "www", ".", "homeinns", ".", "com", "/", "beijing", ")", "http", ":", "//", "www", ".", "homeinns", ".", "com", "/", "beijing", ">>>", ...
python
train
pricingassistant/mrq
mrq/queue_raw.py
https://github.com/pricingassistant/mrq/blob/d0a5a34de9cba38afa94fb7c9e17f9b570b79a50/mrq/queue_raw.py#L97-L117
def remove_raw_jobs(self, params_list): """ Remove jobs from a raw queue with their raw params. """ if len(params_list) == 0: return # ZSET if self.is_sorted: context.connections.redis.zrem(self.redis_key, *iter(params_list)) # SET elif self.is_set: context.connections.redis.srem(self.redis_key, *params_list) else: # O(n)! Use with caution. for k in params_list: context.connections.redis.lrem(self.redis_key, 1, k) context.metric("queues.%s.removed" % self.id, len(params_list)) context.metric("queues.all.removed", len(params_list))
[ "def", "remove_raw_jobs", "(", "self", ",", "params_list", ")", ":", "if", "len", "(", "params_list", ")", "==", "0", ":", "return", "# ZSET", "if", "self", ".", "is_sorted", ":", "context", ".", "connections", ".", "redis", ".", "zrem", "(", "self", "...
Remove jobs from a raw queue with their raw params.
[ "Remove", "jobs", "from", "a", "raw", "queue", "with", "their", "raw", "params", "." ]
python
train
MisterWil/abodepy
abodepy/__init__.py
https://github.com/MisterWil/abodepy/blob/6f84bb428fd1da98855f55083cd427bebbcc57ae/abodepy/__init__.py#L107-L151
def login(self, username=None, password=None): """Explicit Abode login.""" if username is not None: self._cache[CONST.ID] = username if password is not None: self._cache[CONST.PASSWORD] = password if (self._cache[CONST.ID] is None or not isinstance(self._cache[CONST.ID], str)): raise AbodeAuthenticationException(ERROR.USERNAME) if (self._cache[CONST.PASSWORD] is None or not isinstance(self._cache[CONST.PASSWORD], str)): raise AbodeAuthenticationException(ERROR.PASSWORD) self._save_cache() self._token = None login_data = { CONST.ID: self._cache[CONST.ID], CONST.PASSWORD: self._cache[CONST.PASSWORD], CONST.UUID: self._cache[CONST.UUID] } response = self._session.post(CONST.LOGIN_URL, json=login_data) response_object = json.loads(response.text) oauth_token = self._session.get(CONST.OAUTH_TOKEN_URL) oauth_token_object = json.loads(oauth_token.text) if response.status_code != 200: raise AbodeAuthenticationException((response.status_code, response_object['message'])) _LOGGER.debug("Login Response: %s", response.text) self._token = response_object['token'] self._panel = response_object['panel'] self._user = response_object['user'] self._oauth_token = oauth_token_object['access_token'] _LOGGER.info("Login successful") return True
[ "def", "login", "(", "self", ",", "username", "=", "None", ",", "password", "=", "None", ")", ":", "if", "username", "is", "not", "None", ":", "self", ".", "_cache", "[", "CONST", ".", "ID", "]", "=", "username", "if", "password", "is", "not", "Non...
Explicit Abode login.
[ "Explicit", "Abode", "login", "." ]
python
train
wonambi-python/wonambi
wonambi/trans/peaks.py
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/peaks.py#L9-L58
def peaks(data, method='max', axis='time', limits=None): """Return the values of an index where the data is at max or min Parameters ---------- method : str, optional 'max' or 'min' axis : str, optional the axis where you want to detect the peaks limits : tuple of two values, optional the lowest and highest limits where to search for the peaks data : instance of Data one of the datatypes Returns ------- instance of Data with one dimension less that the input data. The actual values in the data can be not-numberic, for example, if you look for the max value across electrodes Notes ----- This function is useful when you want to find the frequency value at which the power is the largest, or to find the time point at which the signal is largest, or the channel at which the activity is largest. """ idx_axis = data.index_of(axis) output = data._copy() output.axis.pop(axis) for trl in range(data.number_of('trial')): values = data.axis[axis][trl] dat = data(trial=trl) if limits is not None: limits = (values < limits[0]) | (values > limits[1]) idx = [slice(None)] * len(data.list_of_axes) idx[idx_axis] = limits dat[idx] = nan if method == 'max': peak_val = nanargmax(dat, axis=idx_axis) elif method == 'min': peak_val = nanargmin(dat, axis=idx_axis) output.data[trl] = values[peak_val] return output
[ "def", "peaks", "(", "data", ",", "method", "=", "'max'", ",", "axis", "=", "'time'", ",", "limits", "=", "None", ")", ":", "idx_axis", "=", "data", ".", "index_of", "(", "axis", ")", "output", "=", "data", ".", "_copy", "(", ")", "output", ".", ...
Return the values of an index where the data is at max or min Parameters ---------- method : str, optional 'max' or 'min' axis : str, optional the axis where you want to detect the peaks limits : tuple of two values, optional the lowest and highest limits where to search for the peaks data : instance of Data one of the datatypes Returns ------- instance of Data with one dimension less that the input data. The actual values in the data can be not-numberic, for example, if you look for the max value across electrodes Notes ----- This function is useful when you want to find the frequency value at which the power is the largest, or to find the time point at which the signal is largest, or the channel at which the activity is largest.
[ "Return", "the", "values", "of", "an", "index", "where", "the", "data", "is", "at", "max", "or", "min" ]
python
train
bcbio/bcbio-nextgen
bcbio/bam/__init__.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L496-L511
def filter_primary(bam_file, data): """Filter reads to primary only BAM. Removes: - not primary alignment (0x100) 256 - supplementary alignment (0x800) 2048 """ stem, ext = os.path.splitext(bam_file) out_file = stem + ".primary" + ext if not utils.file_exists(out_file): with file_transaction(data, out_file) as tx_out_file: cores = dd.get_num_cores(data) cmd = ("samtools view -@ {cores} -F 2304 -b {bam_file} > {tx_out_file}") do.run(cmd.format(**locals()), ("Filtering primary alignments in %s." % os.path.basename(bam_file))) return out_file
[ "def", "filter_primary", "(", "bam_file", ",", "data", ")", ":", "stem", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "bam_file", ")", "out_file", "=", "stem", "+", "\".primary\"", "+", "ext", "if", "not", "utils", ".", "file_exists", "(",...
Filter reads to primary only BAM. Removes: - not primary alignment (0x100) 256 - supplementary alignment (0x800) 2048
[ "Filter", "reads", "to", "primary", "only", "BAM", "." ]
python
train
watson-developer-cloud/python-sdk
ibm_watson/discovery_v1.py
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/discovery_v1.py#L11789-L11802
def _from_dict(cls, _dict): """Initialize a TrainingQuery object from a json dictionary.""" args = {} if 'query_id' in _dict: args['query_id'] = _dict.get('query_id') if 'natural_language_query' in _dict: args['natural_language_query'] = _dict.get('natural_language_query') if 'filter' in _dict: args['filter'] = _dict.get('filter') if 'examples' in _dict: args['examples'] = [ TrainingExample._from_dict(x) for x in (_dict.get('examples')) ] return cls(**args)
[ "def", "_from_dict", "(", "cls", ",", "_dict", ")", ":", "args", "=", "{", "}", "if", "'query_id'", "in", "_dict", ":", "args", "[", "'query_id'", "]", "=", "_dict", ".", "get", "(", "'query_id'", ")", "if", "'natural_language_query'", "in", "_dict", "...
Initialize a TrainingQuery object from a json dictionary.
[ "Initialize", "a", "TrainingQuery", "object", "from", "a", "json", "dictionary", "." ]
python
train
changhiskhan/poseidon
poseidon/ssh.py
https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/ssh.py#L213-L226
def pip_r(self, requirements, raise_on_error=True): """ Install all requirements contained in the given file path Waits for command to finish. Parameters ---------- requirements: str Path to requirements.txt raise_on_error: bool, default True If True then raise ValueError if stderr is not empty """ cmd = "pip install -r %s" % requirements return self.wait(cmd, raise_on_error=raise_on_error)
[ "def", "pip_r", "(", "self", ",", "requirements", ",", "raise_on_error", "=", "True", ")", ":", "cmd", "=", "\"pip install -r %s\"", "%", "requirements", "return", "self", ".", "wait", "(", "cmd", ",", "raise_on_error", "=", "raise_on_error", ")" ]
Install all requirements contained in the given file path Waits for command to finish. Parameters ---------- requirements: str Path to requirements.txt raise_on_error: bool, default True If True then raise ValueError if stderr is not empty
[ "Install", "all", "requirements", "contained", "in", "the", "given", "file", "path", "Waits", "for", "command", "to", "finish", "." ]
python
valid
CalebBell/fluids
fluids/numerics/__init__.py
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/numerics/__init__.py#L361-L392
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None): '''Port of numpy's linspace to pure python. Does not support dtype, and returns lists of floats. ''' num = int(num) start = start * 1. stop = stop * 1. if num <= 0: return [] if endpoint: if num == 1: return [start] step = (stop-start)/float((num-1)) if num == 1: step = nan y = [start] for _ in range(num-2): y.append(y[-1] + step) y.append(stop) else: step = (stop-start)/float(num) if num == 1: step = nan y = [start] for _ in range(num-1): y.append(y[-1] + step) if retstep: return y, step else: return y
[ "def", "linspace", "(", "start", ",", "stop", ",", "num", "=", "50", ",", "endpoint", "=", "True", ",", "retstep", "=", "False", ",", "dtype", "=", "None", ")", ":", "num", "=", "int", "(", "num", ")", "start", "=", "start", "*", "1.", "stop", ...
Port of numpy's linspace to pure python. Does not support dtype, and returns lists of floats.
[ "Port", "of", "numpy", "s", "linspace", "to", "pure", "python", ".", "Does", "not", "support", "dtype", "and", "returns", "lists", "of", "floats", "." ]
python
train
iclab/centinel
centinel/primitives/dnslib.py
https://github.com/iclab/centinel/blob/9a25dcf30c6a1db3c046f7ccb8ab8873e455c1a4/centinel/primitives/dnslib.py#L264-L271
def parse_out_ips(message): """Given a message, parse out the ips in the answer""" ips = [] for entry in message.answer: for rdata in entry.items: ips.append(rdata.to_text()) return ips
[ "def", "parse_out_ips", "(", "message", ")", ":", "ips", "=", "[", "]", "for", "entry", "in", "message", ".", "answer", ":", "for", "rdata", "in", "entry", ".", "items", ":", "ips", ".", "append", "(", "rdata", ".", "to_text", "(", ")", ")", "retur...
Given a message, parse out the ips in the answer
[ "Given", "a", "message", "parse", "out", "the", "ips", "in", "the", "answer" ]
python
train
rosenbrockc/fortpy
fortpy/parsers/variable.py
https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/parsers/variable.py#L32-L78
def _process_member(self, member, parent, string): """Extracts all the member info from the regex match; returns a ValueElements.""" #The modifiers regex is very greedy so we have some cleaning up to do #to extract the mods. modifiers = member.group("modifiers") dimension = None if modifiers is not None: #Unfortunately, the dimension can also be specified as a modifier and #the dimensions can include variable names and functions. This introduces #the possibility of nested lists. modifiers = modifiers.lower() if "dimension" in modifiers: start, end = self._get_dim_modifier(modifiers) dimension = modifiers[start+1:end] dimtext = modifiers[modifiers.index("dimension"):end+1] modifiers = re.split(",\s*", modifiers.replace(dimtext, "").strip()) #modifiers.append("dimension") else: modifiers = re.split("[,\s]+", modifiers.strip()) if "" in modifiers: modifiers.remove("") dtype = member.group("type") kind = member.group("kind") names = member.group("names") #If there are multiple vars defined on this line we need to return #a list of all of them. result = [] #They might have defined multiple vars on the same line refstring = string[member.start():member.end()].strip() if parent is not None: refline = parent.module.linenum(member.start()) else: refline = "?" ready = self._separate_multiple_def(re.sub(",\s*", ", ", names.strip()), parent, refstring, refline) for name, ldimension, default, D in self._clean_multiple_def(ready): #Now construct the element and set all the values, then add it in the results list. udim = ldimension if ldimension is not None else dimension uD = D if ldimension is not None else count_dimensions([dimension]) result.append(ValueElement(name, modifiers, dtype, kind, default, udim, parent, uD)) return result
[ "def", "_process_member", "(", "self", ",", "member", ",", "parent", ",", "string", ")", ":", "#The modifiers regex is very greedy so we have some cleaning up to do", "#to extract the mods.", "modifiers", "=", "member", ".", "group", "(", "\"modifiers\"", ")", "dimension"...
Extracts all the member info from the regex match; returns a ValueElements.
[ "Extracts", "all", "the", "member", "info", "from", "the", "regex", "match", ";", "returns", "a", "ValueElements", "." ]
python
train
go-macaroon-bakery/py-macaroon-bakery
macaroonbakery/bakery/_oven.py
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_oven.py#L81-L117
def macaroon(self, version, expiry, caveats, ops): ''' Takes a macaroon with the given version from the oven, associates it with the given operations and attaches the given caveats. There must be at least one operation specified. The macaroon will expire at the given time - a time_before first party caveat will be added with that time. @return: a new Macaroon object. ''' if len(ops) == 0: raise ValueError('cannot mint a macaroon associated ' 'with no operations') ops = canonical_ops(ops) root_key, storage_id = self.root_keystore_for_ops(ops).root_key() id = self._new_macaroon_id(storage_id, expiry, ops) id_bytes = six.int2byte(LATEST_VERSION) + \ id.SerializeToString() if macaroon_version(version) < MACAROON_V2: # The old macaroon format required valid text for the macaroon id, # so base64-encode it. id_bytes = raw_urlsafe_b64encode(id_bytes) m = Macaroon( root_key, id_bytes, self.location, version, self.namespace, ) m.add_caveat(checkers.time_before_caveat(expiry), self.key, self.locator) m.add_caveats(caveats, self.key, self.locator) return m
[ "def", "macaroon", "(", "self", ",", "version", ",", "expiry", ",", "caveats", ",", "ops", ")", ":", "if", "len", "(", "ops", ")", "==", "0", ":", "raise", "ValueError", "(", "'cannot mint a macaroon associated '", "'with no operations'", ")", "ops", "=", ...
Takes a macaroon with the given version from the oven, associates it with the given operations and attaches the given caveats. There must be at least one operation specified. The macaroon will expire at the given time - a time_before first party caveat will be added with that time. @return: a new Macaroon object.
[ "Takes", "a", "macaroon", "with", "the", "given", "version", "from", "the", "oven", "associates", "it", "with", "the", "given", "operations", "and", "attaches", "the", "given", "caveats", ".", "There", "must", "be", "at", "least", "one", "operation", "specif...
python
train
numenta/nupic
src/nupic/swarming/exp_generator/experiment_generator.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/exp_generator/experiment_generator.py#L198-L229
def _handleDescriptionFromFileOption(filename, outDir, usageStr, hsVersion, claDescriptionTemplateFile): """ Parses and validates the --descriptionFromFile option and executes the request Parameters: ----------------------------------------------------------------------- filename: File from which we'll extract description JSON outDir: where to place generated experiment files usageStr: program usage string hsVersion: which version of hypersearch permutations file to generate, can be 'v1' or 'v2' claDescriptionTemplateFile: Filename containing the template description retval: nothing """ try: fileHandle = open(filename, 'r') JSONStringFromFile = fileHandle.read().splitlines() JSONStringFromFile = ''.join(JSONStringFromFile) except Exception, e: raise _InvalidCommandArgException( _makeUsageErrorStr( ("File open failed for --descriptionFromFile: %s\n" + \ "ARG=<%s>") % (str(e), filename), usageStr)) _handleDescriptionOption(JSONStringFromFile, outDir, usageStr, hsVersion=hsVersion, claDescriptionTemplateFile = claDescriptionTemplateFile) return
[ "def", "_handleDescriptionFromFileOption", "(", "filename", ",", "outDir", ",", "usageStr", ",", "hsVersion", ",", "claDescriptionTemplateFile", ")", ":", "try", ":", "fileHandle", "=", "open", "(", "filename", ",", "'r'", ")", "JSONStringFromFile", "=", "fileHand...
Parses and validates the --descriptionFromFile option and executes the request Parameters: ----------------------------------------------------------------------- filename: File from which we'll extract description JSON outDir: where to place generated experiment files usageStr: program usage string hsVersion: which version of hypersearch permutations file to generate, can be 'v1' or 'v2' claDescriptionTemplateFile: Filename containing the template description retval: nothing
[ "Parses", "and", "validates", "the", "--", "descriptionFromFile", "option", "and", "executes", "the", "request" ]
python
valid
sixty-north/asq
asq/queryables.py
https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L240-L289
def select_with_correspondence( self, selector, result_selector=KeyedElement): '''Apply a callable to each element in an input sequence, generating a new sequence of 2-tuples where the first element is the input value and the second is the transformed input value. The generated sequence is lazily evaluated. Note: This method uses deferred execution. Args: selector: A unary function mapping a value in the source sequence to the second argument of the result selector. result_selector: A binary callable mapping the of a value in the source sequence and the transformed value to the corresponding value in the generated sequence. The two positional arguments of the selector function are the original source element and the transformed value. The return value should be the corresponding value in the result sequence. The default selector produces a KeyedElement containing the index and the element giving this function similar behaviour to the built-in enumerate(). Returns: When using the default selector, a Queryable whose elements are KeyedElements where the first element is from the input sequence and the second is the result of invoking the transform function on the first value. Raises: ValueError: If this Queryable has been closed. TypeError: If transform is not callable. ''' if self.closed(): raise ValueError("Attempt to call select_with_correspondence() on a " "closed Queryable.") if not is_callable(selector): raise TypeError("select_with_correspondence() parameter selector={0} is " "not callable".format(repr(selector))) if not is_callable(result_selector): raise TypeError("select_with_correspondence() parameter result_selector={0} is " "not callable".format(repr(result_selector))) return self._create(result_selector(elem, selector(elem)) for elem in iter(self))
[ "def", "select_with_correspondence", "(", "self", ",", "selector", ",", "result_selector", "=", "KeyedElement", ")", ":", "if", "self", ".", "closed", "(", ")", ":", "raise", "ValueError", "(", "\"Attempt to call select_with_correspondence() on a \"", "\"closed Queryabl...
Apply a callable to each element in an input sequence, generating a new sequence of 2-tuples where the first element is the input value and the second is the transformed input value. The generated sequence is lazily evaluated. Note: This method uses deferred execution. Args: selector: A unary function mapping a value in the source sequence to the second argument of the result selector. result_selector: A binary callable mapping the of a value in the source sequence and the transformed value to the corresponding value in the generated sequence. The two positional arguments of the selector function are the original source element and the transformed value. The return value should be the corresponding value in the result sequence. The default selector produces a KeyedElement containing the index and the element giving this function similar behaviour to the built-in enumerate(). Returns: When using the default selector, a Queryable whose elements are KeyedElements where the first element is from the input sequence and the second is the result of invoking the transform function on the first value. Raises: ValueError: If this Queryable has been closed. TypeError: If transform is not callable.
[ "Apply", "a", "callable", "to", "each", "element", "in", "an", "input", "sequence", "generating", "a", "new", "sequence", "of", "2", "-", "tuples", "where", "the", "first", "element", "is", "the", "input", "value", "and", "the", "second", "is", "the", "t...
python
train
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavextra.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavextra.py#L708-L714
def demix1(servo1, servo2, gain=0.5): '''de-mix a mixed servo output''' s1 = servo1 - 1500 s2 = servo2 - 1500 out1 = (s1+s2)*gain out2 = (s1-s2)*gain return out1+1500
[ "def", "demix1", "(", "servo1", ",", "servo2", ",", "gain", "=", "0.5", ")", ":", "s1", "=", "servo1", "-", "1500", "s2", "=", "servo2", "-", "1500", "out1", "=", "(", "s1", "+", "s2", ")", "*", "gain", "out2", "=", "(", "s1", "-", "s2", ")",...
de-mix a mixed servo output
[ "de", "-", "mix", "a", "mixed", "servo", "output" ]
python
train
manns/pyspread
pyspread/src/gui/_chart_dialog.py
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_chart_dialog.py#L712-L721
def get_code(self): """Returns code representation of value of widget""" selection = self.GetSelection() if selection == wx.NOT_FOUND: selection = 0 # Return code string return self.styles[selection][1]
[ "def", "get_code", "(", "self", ")", ":", "selection", "=", "self", ".", "GetSelection", "(", ")", "if", "selection", "==", "wx", ".", "NOT_FOUND", ":", "selection", "=", "0", "# Return code string", "return", "self", ".", "styles", "[", "selection", "]", ...
Returns code representation of value of widget
[ "Returns", "code", "representation", "of", "value", "of", "widget" ]
python
train
yfpeng/bioc
bioc/biocxml/encoder.py
https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/biocxml/encoder.py#L111-L122
def encode_document(document): """Encode a single document.""" tree = etree.Element('document') etree.SubElement(tree, 'id').text = document.id encode_infons(tree, document.infons) for passage in document.passages: tree.append(encode_passage(passage)) for ann in document.annotations: tree.append(encode_annotation(ann)) for rel in document.relations: tree.append(encode_relation(rel)) return tree
[ "def", "encode_document", "(", "document", ")", ":", "tree", "=", "etree", ".", "Element", "(", "'document'", ")", "etree", ".", "SubElement", "(", "tree", ",", "'id'", ")", ".", "text", "=", "document", ".", "id", "encode_infons", "(", "tree", ",", "d...
Encode a single document.
[ "Encode", "a", "single", "document", "." ]
python
train