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
Tanganelli/CoAPthon3
coapthon/client/coap.py
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/client/coap.py#L69-L79
def close(self): """ Stop the client. """ self.stopped.set() for event in self.to_be_stopped: event.set() if self._receiver_thread is not None: self._receiver_thread.join() self._socket.close()
[ "def", "close", "(", "self", ")", ":", "self", ".", "stopped", ".", "set", "(", ")", "for", "event", "in", "self", ".", "to_be_stopped", ":", "event", ".", "set", "(", ")", "if", "self", ".", "_receiver_thread", "is", "not", "None", ":", "self", "....
Stop the client.
[ "Stop", "the", "client", "." ]
python
train
bcicen/haproxy-stats
haproxystats/__init__.py
https://github.com/bcicen/haproxy-stats/blob/f9268244b84eb52095d07b577646fdea4135fe3b/haproxystats/__init__.py#L115-L124
def _decode(value): """ decode byte strings and convert to int where needed """ if value.isdigit(): return int(value) if isinstance(value, bytes): return value.decode('utf-8') else: return value
[ "def", "_decode", "(", "value", ")", ":", "if", "value", ".", "isdigit", "(", ")", ":", "return", "int", "(", "value", ")", "if", "isinstance", "(", "value", ",", "bytes", ")", ":", "return", "value", ".", "decode", "(", "'utf-8'", ")", "else", ":"...
decode byte strings and convert to int where needed
[ "decode", "byte", "strings", "and", "convert", "to", "int", "where", "needed" ]
python
train
mitsei/dlkit
dlkit/json_/grading/searches.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/grading/searches.py#L97-L108
def get_grade_systems(self): """Gets the grade system list resulting from the search. return: (osid.grading.GradeSystemList) - the grade system list raise: IllegalState - list already retrieved *compliance: mandatory -- This method must be implemented.* """ if self.retrieved: raise errors.IllegalState('List has already been retrieved.') self.retrieved = True return objects.GradeSystemList(self._results, runtime=self._runtime)
[ "def", "get_grade_systems", "(", "self", ")", ":", "if", "self", ".", "retrieved", ":", "raise", "errors", ".", "IllegalState", "(", "'List has already been retrieved.'", ")", "self", ".", "retrieved", "=", "True", "return", "objects", ".", "GradeSystemList", "(...
Gets the grade system list resulting from the search. return: (osid.grading.GradeSystemList) - the grade system list raise: IllegalState - list already retrieved *compliance: mandatory -- This method must be implemented.*
[ "Gets", "the", "grade", "system", "list", "resulting", "from", "the", "search", "." ]
python
train
intel-analytics/BigDL
pyspark/bigdl/util/common.py
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/util/common.py#L478-L490
def to_sample_rdd(x, y, numSlices=None): """ Conver x and y into RDD[Sample] :param x: ndarray and the first dimension should be batch :param y: ndarray and the first dimension should be batch :param numSlices: :return: """ sc = get_spark_context() from bigdl.util.common import Sample x_rdd = sc.parallelize(x, numSlices) y_rdd = sc.parallelize(y, numSlices) return x_rdd.zip(y_rdd).map(lambda item: Sample.from_ndarray(item[0], item[1]))
[ "def", "to_sample_rdd", "(", "x", ",", "y", ",", "numSlices", "=", "None", ")", ":", "sc", "=", "get_spark_context", "(", ")", "from", "bigdl", ".", "util", ".", "common", "import", "Sample", "x_rdd", "=", "sc", ".", "parallelize", "(", "x", ",", "nu...
Conver x and y into RDD[Sample] :param x: ndarray and the first dimension should be batch :param y: ndarray and the first dimension should be batch :param numSlices: :return:
[ "Conver", "x", "and", "y", "into", "RDD", "[", "Sample", "]", ":", "param", "x", ":", "ndarray", "and", "the", "first", "dimension", "should", "be", "batch", ":", "param", "y", ":", "ndarray", "and", "the", "first", "dimension", "should", "be", "batch"...
python
test
sofiatolaosebikan/hopcroftkarp
hopcroftkarp/__init__.py
https://github.com/sofiatolaosebikan/hopcroftkarp/blob/5e6cf4f95702304847307a07d369f8041edff8c9/hopcroftkarp/__init__.py#L84-L109
def __dfs(self, v, index, layers): """ we recursively run dfs on each vertices in free_vertex, :param v: vertices in free_vertex :return: True if P is not empty (i.e., the maximal set of vertex-disjoint alternating path of length k) and false otherwise. """ if index == 0: path = [v] while self._dfs_parent[v] != v: path.append(self._dfs_parent[v]) v = self._dfs_parent[v] self._dfs_paths.append(path) return True for neighbour in self._graph[v]: # check the neighbours of vertex if neighbour in layers[index - 1]: # if neighbour is in left, we are traversing unmatched edges.. if neighbour in self._dfs_parent: continue if (neighbour in self._left and (v not in self._matching or neighbour != self._matching[v])) or \ (neighbour in self._right and (v in self._matching and neighbour == self._matching[v])): self._dfs_parent[neighbour] = v if self.__dfs(neighbour, index-1, layers): return True return False
[ "def", "__dfs", "(", "self", ",", "v", ",", "index", ",", "layers", ")", ":", "if", "index", "==", "0", ":", "path", "=", "[", "v", "]", "while", "self", ".", "_dfs_parent", "[", "v", "]", "!=", "v", ":", "path", ".", "append", "(", "self", "...
we recursively run dfs on each vertices in free_vertex, :param v: vertices in free_vertex :return: True if P is not empty (i.e., the maximal set of vertex-disjoint alternating path of length k) and false otherwise.
[ "we", "recursively", "run", "dfs", "on", "each", "vertices", "in", "free_vertex" ]
python
train
kislyuk/aegea
aegea/packages/github3/repos/repo.py
https://github.com/kislyuk/aegea/blob/94957e9dba036eae3052e2662c208b259c08399a/aegea/packages/github3/repos/repo.py#L1009-L1018
def is_assignee(self, login): """Check if the user is a possible assignee for an issue on this repository. :returns: :class:`bool` """ if not login: return False url = self._build_url('assignees', login, base_url=self._api) return self._boolean(self._get(url), 204, 404)
[ "def", "is_assignee", "(", "self", ",", "login", ")", ":", "if", "not", "login", ":", "return", "False", "url", "=", "self", ".", "_build_url", "(", "'assignees'", ",", "login", ",", "base_url", "=", "self", ".", "_api", ")", "return", "self", ".", "...
Check if the user is a possible assignee for an issue on this repository. :returns: :class:`bool`
[ "Check", "if", "the", "user", "is", "a", "possible", "assignee", "for", "an", "issue", "on", "this", "repository", "." ]
python
train
jenisys/parse_type
parse_type/builder.py
https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/builder.py#L128-L154
def make_choice(cls, choices, transform=None, strict=None): """ Creates a type-converter function to select one from a list of strings. The type-converter function returns the selected choice_text. The :param:`transform()` function is applied in the type converter. It can be used to enforce the case (because parser uses re.IGNORECASE). :param choices: List of strings as choice. :param transform: Optional, initial transform function for parsed text. :return: Type converter function object for this choices. """ # -- NOTE: Parser uses re.IGNORECASE flag # => transform may enforce case. choices = cls._normalize_choices(choices, transform) if strict is None: strict = cls.default_strict def convert_choice(text): if transform: text = transform(text) if strict and not (text in convert_choice.choices): values = ", ".join(convert_choice.choices) raise ValueError("%s not in: %s" % (text, values)) return text convert_choice.pattern = r"|".join(choices) convert_choice.choices = choices return convert_choice
[ "def", "make_choice", "(", "cls", ",", "choices", ",", "transform", "=", "None", ",", "strict", "=", "None", ")", ":", "# -- NOTE: Parser uses re.IGNORECASE flag", "# => transform may enforce case.", "choices", "=", "cls", ".", "_normalize_choices", "(", "choices",...
Creates a type-converter function to select one from a list of strings. The type-converter function returns the selected choice_text. The :param:`transform()` function is applied in the type converter. It can be used to enforce the case (because parser uses re.IGNORECASE). :param choices: List of strings as choice. :param transform: Optional, initial transform function for parsed text. :return: Type converter function object for this choices.
[ "Creates", "a", "type", "-", "converter", "function", "to", "select", "one", "from", "a", "list", "of", "strings", ".", "The", "type", "-", "converter", "function", "returns", "the", "selected", "choice_text", ".", "The", ":", "param", ":", "transform", "(...
python
train
standage/tag
tag/index.py
https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/index.py#L55-L58
def consume_file(self, infile): """Load the specified GFF3 file into memory.""" reader = tag.reader.GFF3Reader(infilename=infile) self.consume(reader)
[ "def", "consume_file", "(", "self", ",", "infile", ")", ":", "reader", "=", "tag", ".", "reader", ".", "GFF3Reader", "(", "infilename", "=", "infile", ")", "self", ".", "consume", "(", "reader", ")" ]
Load the specified GFF3 file into memory.
[ "Load", "the", "specified", "GFF3", "file", "into", "memory", "." ]
python
train
aljungberg/pyle
pyle.py
https://github.com/aljungberg/pyle/blob/e0f25f42f5f35f0cefd0f7f9afafb6c9f37cc499/pyle.py#L43-L47
def truncate_ellipsis(line, length=30): """Truncate a line to the specified length followed by ``...`` unless its shorter than length already.""" l = len(line) return line if l < length else line[:length - 3] + "..."
[ "def", "truncate_ellipsis", "(", "line", ",", "length", "=", "30", ")", ":", "l", "=", "len", "(", "line", ")", "return", "line", "if", "l", "<", "length", "else", "line", "[", ":", "length", "-", "3", "]", "+", "\"...\"" ]
Truncate a line to the specified length followed by ``...`` unless its shorter than length already.
[ "Truncate", "a", "line", "to", "the", "specified", "length", "followed", "by", "...", "unless", "its", "shorter", "than", "length", "already", "." ]
python
train
bovee/Aston
aston/tracefile/agilent_extra_cs.py
https://github.com/bovee/Aston/blob/007630fdf074690373d03398fe818260d3d3cf5a/aston/tracefile/agilent_extra_cs.py#L133-L156
def read_multireg_file(f, title=None): """ Some REG files have multiple "sections" with different data. This parses each chunk out of such a file (e.g. LCDIAG.REG) """ f.seek(0x26) nparts = struct.unpack('<H', f.read(2))[0] foff = 0x2D if title is None: data = [] for _ in range(nparts): d = read_reg_file(f, foff) data.append(d) foff = f.tell() + 1 else: for _ in range(nparts): d = read_reg_file(f, foff) if d.get('Title') == title: data = d break foff = f.tell() + 1 else: data = {} return data
[ "def", "read_multireg_file", "(", "f", ",", "title", "=", "None", ")", ":", "f", ".", "seek", "(", "0x26", ")", "nparts", "=", "struct", ".", "unpack", "(", "'<H'", ",", "f", ".", "read", "(", "2", ")", ")", "[", "0", "]", "foff", "=", "0x2D", ...
Some REG files have multiple "sections" with different data. This parses each chunk out of such a file (e.g. LCDIAG.REG)
[ "Some", "REG", "files", "have", "multiple", "sections", "with", "different", "data", ".", "This", "parses", "each", "chunk", "out", "of", "such", "a", "file", "(", "e", ".", "g", ".", "LCDIAG", ".", "REG", ")" ]
python
train
pantsbuild/pants
contrib/buildgen/src/python/pants/contrib/buildgen/build_file_manipulator.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/buildgen/src/python/pants/contrib/buildgen/build_file_manipulator.py#L375-L387
def dependency_lines(self): """The formatted dependencies=[...] lines for this target. If there are no dependencies, this returns an empty list. """ deps = sorted(self._dependencies_by_address.values(), key=lambda d: d.spec) def dep_lines(): yield ' dependencies = [' for dep in deps: for line in dep.lines(): yield line yield ' ],' return list(dep_lines()) if deps else []
[ "def", "dependency_lines", "(", "self", ")", ":", "deps", "=", "sorted", "(", "self", ".", "_dependencies_by_address", ".", "values", "(", ")", ",", "key", "=", "lambda", "d", ":", "d", ".", "spec", ")", "def", "dep_lines", "(", ")", ":", "yield", "'...
The formatted dependencies=[...] lines for this target. If there are no dependencies, this returns an empty list.
[ "The", "formatted", "dependencies", "=", "[", "...", "]", "lines", "for", "this", "target", "." ]
python
train
virtuald/pyhcl
src/hcl/parser.py
https://github.com/virtuald/pyhcl/blob/e6e27742215692974f0ef503a91a81ec4adc171c/src/hcl/parser.py#L104-L108
def p_top(self, p): "top : objectlist" if DEBUG: self.print_p(p) p[0] = self.objectlist_flat(p[1], True)
[ "def", "p_top", "(", "self", ",", "p", ")", ":", "if", "DEBUG", ":", "self", ".", "print_p", "(", "p", ")", "p", "[", "0", "]", "=", "self", ".", "objectlist_flat", "(", "p", "[", "1", "]", ",", "True", ")" ]
top : objectlist
[ "top", ":", "objectlist" ]
python
valid
yyuu/botornado
boto/fps/connection.py
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/fps/connection.py#L76-L100
def install_caller_instruction(self, token_type="Unrestricted", transaction_id=None): """ Set us up as a caller This will install a new caller_token into the FPS section. This should really only be called to regenerate the caller token. """ response = self.install_payment_instruction("MyRole=='Caller';", token_type=token_type, transaction_id=transaction_id) body = response.read() if(response.status == 200): rs = ResultSet() h = handler.XmlHandler(rs, self) xml.sax.parseString(body, h) caller_token = rs.TokenId try: boto.config.save_system_option("FPS", "caller_token", caller_token) except(IOError): boto.config.save_user_option("FPS", "caller_token", caller_token) return caller_token else: raise FPSResponseError(response.status, response.reason, body)
[ "def", "install_caller_instruction", "(", "self", ",", "token_type", "=", "\"Unrestricted\"", ",", "transaction_id", "=", "None", ")", ":", "response", "=", "self", ".", "install_payment_instruction", "(", "\"MyRole=='Caller';\"", ",", "token_type", "=", "token_type",...
Set us up as a caller This will install a new caller_token into the FPS section. This should really only be called to regenerate the caller token.
[ "Set", "us", "up", "as", "a", "caller", "This", "will", "install", "a", "new", "caller_token", "into", "the", "FPS", "section", ".", "This", "should", "really", "only", "be", "called", "to", "regenerate", "the", "caller", "token", "." ]
python
train
azraq27/neural
neural/wrappers/common.py
https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/wrappers/common.py#L69-L74
def blur(dset,fwhm,prefix=None): '''blurs ``dset`` with given ``fwhm`` runs 3dmerge to blur dataset to given ``fwhm`` default ``prefix`` is to suffix ``dset`` with ``_blur%.1fmm``''' if prefix==None: prefix = nl.suffix(dset,'_blur%.1fmm'%fwhm) return available_method('blur')(dset,fwhm,prefix)
[ "def", "blur", "(", "dset", ",", "fwhm", ",", "prefix", "=", "None", ")", ":", "if", "prefix", "==", "None", ":", "prefix", "=", "nl", ".", "suffix", "(", "dset", ",", "'_blur%.1fmm'", "%", "fwhm", ")", "return", "available_method", "(", "'blur'", ")...
blurs ``dset`` with given ``fwhm`` runs 3dmerge to blur dataset to given ``fwhm`` default ``prefix`` is to suffix ``dset`` with ``_blur%.1fmm``
[ "blurs", "dset", "with", "given", "fwhm", "runs", "3dmerge", "to", "blur", "dataset", "to", "given", "fwhm", "default", "prefix", "is", "to", "suffix", "dset", "with", "_blur%", ".", "1fmm" ]
python
train
dariosky/wfcli
wfcli/wfapi.py
https://github.com/dariosky/wfcli/blob/87a9ed30dbd456f801135a55099f0541b0614ccb/wfcli/wfapi.py#L67-L71
def list_domains(self): """ Return all domains. Domain is a key, so group by them """ self.connect() results = self.server.list_domains(self.session_id) return {i['domain']: i['subdomains'] for i in results}
[ "def", "list_domains", "(", "self", ")", ":", "self", ".", "connect", "(", ")", "results", "=", "self", ".", "server", ".", "list_domains", "(", "self", ".", "session_id", ")", "return", "{", "i", "[", "'domain'", "]", ":", "i", "[", "'subdomains'", ...
Return all domains. Domain is a key, so group by them
[ "Return", "all", "domains", ".", "Domain", "is", "a", "key", "so", "group", "by", "them" ]
python
train
kodethon/KoDrive
kodrive/cli.py
https://github.com/kodethon/KoDrive/blob/325fe5e5870b7d4eb121dcc7e93be64aa16e7988/kodrive/cli.py#L178-L200
def mv(source, target): ''' Move synchronized directory. ''' if os.path.isfile(target) and len(source) == 1: if click.confirm("Are you sure you want to overwrite %s?" % target): err_msg = cli_syncthing_adapter.mv_edge_case(source, target) # Edge case: to match Bash 'mv' behavior and overwrite file if err_msg: click.echo(err_msg) return if len(source) > 1 and not os.path.isdir(target): click.echo(click.get_current_context().get_help()) return else: err_msg, err = cli_syncthing_adapter.mv(source, target) if err_msg: click.echo(err_msg, err)
[ "def", "mv", "(", "source", ",", "target", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "target", ")", "and", "len", "(", "source", ")", "==", "1", ":", "if", "click", ".", "confirm", "(", "\"Are you sure you want to overwrite %s?\"", "%", "t...
Move synchronized directory.
[ "Move", "synchronized", "directory", "." ]
python
train
pycontribs/pyrax
pyrax/autoscale.py
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/autoscale.py#L921-L925
def get_webhook(self, webhook): """ Gets the detail for the specified webhook. """ return self.manager.get_webhook(self.scaling_group, self, webhook)
[ "def", "get_webhook", "(", "self", ",", "webhook", ")", ":", "return", "self", ".", "manager", ".", "get_webhook", "(", "self", ".", "scaling_group", ",", "self", ",", "webhook", ")" ]
Gets the detail for the specified webhook.
[ "Gets", "the", "detail", "for", "the", "specified", "webhook", "." ]
python
train
timothydmorton/VESPA
vespa/stars/populations.py
https://github.com/timothydmorton/VESPA/blob/0446b54d48009f3655cfd1a3957ceea21d3adcaa/vespa/stars/populations.py#L376-L436
def prophist2d(self,propx,propy, mask=None, logx=False,logy=False, fig=None,selected=False,**kwargs): """Makes a 2d density histogram of two given properties :param propx,propy: Names of properties to histogram. Must be names of columns in ``self.stars`` table. :param mask: (optional) Boolean mask (``True`` is good) to say which indices to plot. Must be same length as ``self.stars``. :param logx,logy: (optional) Whether to plot the log10 of x and/or y properties. :param fig: (optional) Argument passed to :func:`plotutils.setfig`. :param selected: (optional) If ``True``, then only the "selected" stars (that is, stars obeying all distribution constraints attached to this object) will be plotted. In this case, ``mask`` will be ignored. :param kwargs: Additional keyword arguments passed to :func:`plotutils.plot2dhist`. """ if mask is not None: inds = np.where(mask)[0] else: if selected: inds = self.selected.index else: inds = self.stars.index if selected: xvals = self.selected[propx].iloc[inds].values yvals = self.selected[propy].iloc[inds].values else: if mask is None: mask = np.ones_like(self.stars.index) xvals = self.stars[mask][propx].values yvals = self.stars[mask][propy].values #forward-hack for EclipsePopulations... #TODO: reorganize. if propx=='depth' and hasattr(self,'depth'): xvals = self.depth.iloc[inds].values if propy=='depth' and hasattr(self,'depth'): yvals = self.depth.iloc[inds].values if logx: xvals = np.log10(xvals) if logy: yvals = np.log10(yvals) plot2dhist(xvals,yvals,fig=fig,**kwargs) plt.xlabel(propx) plt.ylabel(propy)
[ "def", "prophist2d", "(", "self", ",", "propx", ",", "propy", ",", "mask", "=", "None", ",", "logx", "=", "False", ",", "logy", "=", "False", ",", "fig", "=", "None", ",", "selected", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "mask",...
Makes a 2d density histogram of two given properties :param propx,propy: Names of properties to histogram. Must be names of columns in ``self.stars`` table. :param mask: (optional) Boolean mask (``True`` is good) to say which indices to plot. Must be same length as ``self.stars``. :param logx,logy: (optional) Whether to plot the log10 of x and/or y properties. :param fig: (optional) Argument passed to :func:`plotutils.setfig`. :param selected: (optional) If ``True``, then only the "selected" stars (that is, stars obeying all distribution constraints attached to this object) will be plotted. In this case, ``mask`` will be ignored. :param kwargs: Additional keyword arguments passed to :func:`plotutils.plot2dhist`.
[ "Makes", "a", "2d", "density", "histogram", "of", "two", "given", "properties" ]
python
train
PSPC-SPAC-buyandsell/von_agent
von_agent/agent/issuer.py
https://github.com/PSPC-SPAC-buyandsell/von_agent/blob/0b1c17cca3bd178b6e6974af84dbac1dfce5cf45/von_agent/agent/issuer.py#L309-L407
async def create_cred( self, cred_offer_json, cred_req_json: str, cred_attrs: dict, rr_size: int = None) -> (str, str, int): """ Create credential as Issuer out of credential request and dict of key:value (raw, unencoded) entries for attributes. Return credential json, and if cred def supports revocation, credential revocation identifier and revocation registry delta ledger timestamp (epoch seconds). If the credential definition supports revocation, and the current revocation registry is full, the processing creates a new revocation registry en passant. Depending on the revocation registry size (by default starting at 256 and doubling iteratively through 4096), this operation may delay credential creation by several seconds. :param cred_offer_json: credential offer json as created by Issuer :param cred_req_json: credential request json as created by HolderProver :param cred_attrs: dict mapping each attribute to its raw value (the operation encodes it); e.g., :: { 'favourite_drink': 'martini', 'height': 180, 'last_visit_date': '2017-12-31', 'weaknesses': None } :param rr_size: size of new revocation registry (default as per _create_rev_reg()) if necessary :return: newly issued credential json; credential revocation identifier (if cred def supports revocation, None otherwise), and ledger timestamp (if cred def supports revocation, None otherwise) """ LOGGER.debug( 'Issuer.create_cred >>> cred_offer_json: %s, cred_req_json: %s, cred_attrs: %s, rr_size: %s', cred_offer_json, cred_req_json, cred_attrs, rr_size) cd_id = json.loads(cred_offer_json)['cred_def_id'] cred_def = json.loads(await self.get_cred_def(cd_id)) # ensure cred def is in cache if 'revocation' in cred_def['value']: with REVO_CACHE.lock: rr_id = Tails.current_rev_reg_id(self._dir_tails, cd_id) tails = REVO_CACHE[rr_id].tails assert tails # at (re)start, at cred def, Issuer sync_revoc() sets this index in revocation cache try: (cred_json, cred_revoc_id, rr_delta_json) = await anoncreds.issuer_create_credential( self.wallet.handle, cred_offer_json, cred_req_json, json.dumps({k: cred_attr_value(cred_attrs[k]) for k in cred_attrs}), tails.rr_id, tails.reader_handle) # do not create rr delta frame and append to cached delta frames list: timestamp could lag or skew rre_req_json = await ledger.build_revoc_reg_entry_request( self.did, tails.rr_id, 'CL_ACCUM', rr_delta_json) await self._sign_submit(rre_req_json) resp_json = await self._sign_submit(rre_req_json) resp = json.loads(resp_json) rv = (cred_json, cred_revoc_id, resp['result']['txnMetadata']['txnTime']) except IndyError as x_indy: if x_indy.error_code == ErrorCode.AnoncredsRevocationRegistryFullError: (tag, rr_size_suggested) = Tails.next_tag(self._dir_tails, cd_id) rr_id = rev_reg_id(cd_id, tag) await self._create_rev_reg(rr_id, rr_size or rr_size_suggested) REVO_CACHE[rr_id].tails = await Tails(self._dir_tails, cd_id).open() return await self.create_cred(cred_offer_json, cred_req_json, cred_attrs) # should be ok now else: LOGGER.debug( 'Issuer.create_cred: <!< cannot create cred, indy error code %s', x_indy.error_code) raise else: try: (cred_json, _, _) = await anoncreds.issuer_create_credential( self.wallet.handle, cred_offer_json, cred_req_json, json.dumps({k: cred_attr_value(cred_attrs[k]) for k in cred_attrs}), None, None) rv = (cred_json, _, _) except IndyError as x_indy: LOGGER.debug('Issuer.create_cred: <!< cannot create cred, indy error code %s', x_indy.error_code) raise LOGGER.debug('Issuer.create_cred <<< %s', rv) return rv
[ "async", "def", "create_cred", "(", "self", ",", "cred_offer_json", ",", "cred_req_json", ":", "str", ",", "cred_attrs", ":", "dict", ",", "rr_size", ":", "int", "=", "None", ")", "->", "(", "str", ",", "str", ",", "int", ")", ":", "LOGGER", ".", "de...
Create credential as Issuer out of credential request and dict of key:value (raw, unencoded) entries for attributes. Return credential json, and if cred def supports revocation, credential revocation identifier and revocation registry delta ledger timestamp (epoch seconds). If the credential definition supports revocation, and the current revocation registry is full, the processing creates a new revocation registry en passant. Depending on the revocation registry size (by default starting at 256 and doubling iteratively through 4096), this operation may delay credential creation by several seconds. :param cred_offer_json: credential offer json as created by Issuer :param cred_req_json: credential request json as created by HolderProver :param cred_attrs: dict mapping each attribute to its raw value (the operation encodes it); e.g., :: { 'favourite_drink': 'martini', 'height': 180, 'last_visit_date': '2017-12-31', 'weaknesses': None } :param rr_size: size of new revocation registry (default as per _create_rev_reg()) if necessary :return: newly issued credential json; credential revocation identifier (if cred def supports revocation, None otherwise), and ledger timestamp (if cred def supports revocation, None otherwise)
[ "Create", "credential", "as", "Issuer", "out", "of", "credential", "request", "and", "dict", "of", "key", ":", "value", "(", "raw", "unencoded", ")", "entries", "for", "attributes", "." ]
python
train
wonambi-python/wonambi
wonambi/widgets/notes.py
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L282-L500
def create_action(self): """Create actions associated with Annotations.""" actions = {} act = QAction('New Annotations', self) act.triggered.connect(self.new_annot) actions['new_annot'] = act act = QAction('Load Annotations', self) act.triggered.connect(self.load_annot) actions['load_annot'] = act act = QAction('Clear Annotations...', self) act.triggered.connect(self.clear_annot) actions['clear_annot'] = act act = QAction('New...', self) act.triggered.connect(self.new_rater) actions['new_rater'] = act act = QAction('Rename...', self) act.triggered.connect(self.rename_rater) actions['rename_rater'] = act act = QAction('Delete...', self) act.triggered.connect(self.delete_rater) actions['del_rater'] = act act = QAction(QIcon(ICON['bookmark']), 'New Bookmark', self) act.setCheckable(True) actions['new_bookmark'] = act act = QAction(QIcon(ICON['new_eventtype']), 'New Event Type', self) act.triggered.connect(self.new_eventtype) actions['new_eventtype'] = act act = QAction(QIcon(ICON['del_eventtype']), 'Delete Event Type', self) act.triggered.connect(self.delete_eventtype) actions['del_eventtype'] = act act = QAction('Rename Event Type', self) act.triggered.connect(self.rename_eventtype) actions['rename_eventtype'] = act act = QAction('New Name', self) act.triggered.connect(self.markers_to_events) actions['m2e_newname'] = act act = QAction('Keep Marker Names', self) act.triggered.connect(partial(self.markers_to_events, True)) actions['m2e_keepname'] = act act = QAction('Merge Events...', self) act.triggered.connect(self.parent.show_merge_dialog) actions['merge_events'] = act act = QAction(QIcon(ICON['event']), 'Event Mode', self) act.setCheckable(True) actions['new_event'] = act uncheck_new_event = lambda: actions['new_event'].setChecked(False) uncheck_new_bookmark = lambda: actions['new_bookmark'].setChecked(False) actions['new_event'].triggered.connect(uncheck_new_bookmark) actions['new_bookmark'].triggered.connect(uncheck_new_event) act = {} for one_stage, one_shortcut in zip(STAGE_NAME, STAGE_SHORTCUT): act[one_stage] = QAction('Score as ' + one_stage, self.parent) act[one_stage].setShortcut(one_shortcut) stage_idx = STAGE_NAME.index(one_stage) act[one_stage].triggered.connect(partial(self.get_sleepstage, stage_idx)) self.addAction(act[one_stage]) actions['stages'] = act act = {} for one_qual, one_shortcut in zip(QUALIFIERS, QUALITY_SHORTCUT): act[one_qual] = QAction('Score as ' + one_qual, self.parent) act[one_qual].setShortcut(one_shortcut) qual_idx = QUALIFIERS.index(one_qual) act[one_qual].triggered.connect(partial(self.get_quality, qual_idx)) self.addAction(act[one_qual]) actions['quality'] = act act = QAction('Set Cycle Start', self) act.setShortcut('Ctrl+[') act.triggered.connect(self.get_cycle_mrkr) actions['cyc_start'] = act act = QAction('Set Cycle End', self) act.setShortcut('Ctrl+]') act.triggered.connect(partial(self.get_cycle_mrkr, end=True)) actions['cyc_end'] = act act = QAction('Remove Cycle Marker', self) act.triggered.connect(self.remove_cycle_mrkr) actions['remove_cyc'] = act act = QAction('Clear Cycle Markers', self) act.triggered.connect(self.clear_cycle_mrkrs) actions['clear_cyc'] = act act = QAction('Domino', self) act.triggered.connect(partial(self.import_staging, 'domino')) actions['import_domino'] = act act = QAction('Alice', self) act.triggered.connect(partial(self.import_staging, 'alice')) actions['import_alice'] = act act = QAction('Sandman', self) act.triggered.connect(partial(self.import_staging, 'sandman')) actions['import_sandman'] = act act = QAction('RemLogic', self) act.triggered.connect(partial(self.import_staging, 'remlogic')) actions['import_remlogic'] = act act = QAction('Compumedics', self) act.triggered.connect(partial(self.import_staging, 'compumedics')) actions['import_compumedics'] = act act = QAction('PRANA', self) act.triggered.connect(partial(self.import_staging, 'prana')) actions['import_prana'] = act act = QAction('DeltaMed', self) act.triggered.connect(partial(self.import_staging, 'deltamed')) actions['import_deltamed'] = act act = QAction('FASST', self) act.triggered.connect(self.import_fasst) actions['import_fasst'] = act act = QAction('Domino', self) act.triggered.connect(partial(self.import_staging, 'domino', as_qual=True)) actions['import_domino_qual'] = act act = QAction('Alice', self) act.triggered.connect(partial(self.import_staging, 'alice', as_qual=True)) actions['import_alice_qual'] = act act = QAction('Sandman', self) act.triggered.connect(partial(self.import_staging, 'sandman', as_qual=True)) actions['import_sandman_qual'] = act act = QAction('RemLogic', self) act.triggered.connect(partial(self.import_staging, 'remlogic', as_qual=True)) actions['import_remlogic_qual'] = act act = QAction('Compumedics', self) act.triggered.connect(partial(self.import_staging, 'compumedics', as_qual=True)) actions['import_compumedics_qual'] = act act = QAction('PRANA', self) act.triggered.connect(partial(self.import_staging, 'prana', as_qual=True)) actions['import_prana_qual'] = act act = QAction('DeltaMed', self) act.triggered.connect(partial(self.import_staging, 'deltamed', as_qual=True)) actions['import_deltamed_qual'] = act act = QAction('Wonambi', self) act.triggered.connect(partial(self.import_events, 'wonambi')) actions['import_events_wonambi'] = act act = QAction('RemLogic', self) act.triggered.connect(partial(self.import_events, 'remlogic')) actions['import_events_remlogic'] = act act = QAction('CSV', self) act.triggered.connect(partial(self.export, xformat='csv')) actions['export_to_csv'] = act act = QAction('RemLogic', self) act.triggered.connect(partial(self.export, xformat='remlogic')) actions['export_to_remlogic'] = act act = QAction('RemLogic FR', self) act.triggered.connect(partial(self.export, xformat='remlogic_fr')) actions['export_to_remlogic_fr'] = act act = QAction('Export Events...', self) act.triggered.connect(self.parent.show_export_events_dialog) actions['export_events'] = act act = QAction('Spindle...', self) act.triggered.connect(self.parent.show_spindle_dialog) act.setShortcut('Ctrl+Shift+s') act.setEnabled(False) actions['spindle'] = act act = QAction('Slow Wave...', self) act.triggered.connect(self.parent.show_slow_wave_dialog) act.setShortcut('Ctrl+Shift+w') act.setEnabled(False) actions['slow_wave'] = act act = QAction('Analysis Console', self) act.triggered.connect(self.parent.show_analysis_dialog) act.setShortcut('Ctrl+Shift+a') act.setEnabled(False) actions['analyze'] = act act = QAction('Sleep Statistics', self) act.triggered.connect(self.export_sleeps_stats) actions['export_sleepstats'] = act self.action = actions
[ "def", "create_action", "(", "self", ")", ":", "actions", "=", "{", "}", "act", "=", "QAction", "(", "'New Annotations'", ",", "self", ")", "act", ".", "triggered", ".", "connect", "(", "self", ".", "new_annot", ")", "actions", "[", "'new_annot'", "]", ...
Create actions associated with Annotations.
[ "Create", "actions", "associated", "with", "Annotations", "." ]
python
train
spotify/luigi
luigi/tools/range.py
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L117-L124
def of_cls(self): """ DONT USE. Will be deleted soon. Use ``self.of``! """ if isinstance(self.of, six.string_types): warnings.warn('When using Range programatically, dont pass "of" param as string!') return Register.get_task_cls(self.of) return self.of
[ "def", "of_cls", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "of", ",", "six", ".", "string_types", ")", ":", "warnings", ".", "warn", "(", "'When using Range programatically, dont pass \"of\" param as string!'", ")", "return", "Register", ".", ...
DONT USE. Will be deleted soon. Use ``self.of``!
[ "DONT", "USE", ".", "Will", "be", "deleted", "soon", ".", "Use", "self", ".", "of", "!" ]
python
train
chibisov/cli-bdd
tasks.py
https://github.com/chibisov/cli-bdd/blob/579e2d9a07f9985b268aa9aaba42dee33021e163/tasks.py#L8-L27
def deploy_docs(): """ Based on https://gist.github.com/domenic/ec8b0fc8ab45f39403dd """ run('rm -rf ./site/') build_docs() with util.cd('./site/'): run('git init') run('echo ".*pyc" > .gitignore') run('git config user.name "Travis CI"') run('git config user.email "%s"' % os.environ['EMAIL']) run('git add .') run('git commit -m "Deploy to GitHub Pages"') run( 'git push --force --quiet "https://{GH_TOKEN}@{GH_REF}" ' 'master:gh-pages > /dev/null 2>&1'.format( GH_TOKEN=os.environ['GH_TOKEN'], GH_REF=os.environ['GH_REF'], ) )
[ "def", "deploy_docs", "(", ")", ":", "run", "(", "'rm -rf ./site/'", ")", "build_docs", "(", ")", "with", "util", ".", "cd", "(", "'./site/'", ")", ":", "run", "(", "'git init'", ")", "run", "(", "'echo \".*pyc\" > .gitignore'", ")", "run", "(", "'git conf...
Based on https://gist.github.com/domenic/ec8b0fc8ab45f39403dd
[ "Based", "on", "https", ":", "//", "gist", ".", "github", ".", "com", "/", "domenic", "/", "ec8b0fc8ab45f39403dd" ]
python
train
cuihantao/andes
andes/variables/dae.py
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/dae.py#L437-L481
def hard_limit_remote(self, yidx, ridx, rtype='y', rmin=None, rmax=None, min_yset=0, max_yset=0): """Limit the output of yidx if the remote y is not within the limits This function needs to be modernized. """ ny = len(yidx) assert ny == len( ridx), "Length of output vars and remote vars does not match" assert rtype in ('x', 'y'), "ridx must be either y (algeb) or x (state)" if isinstance(min_yset, (int, float)): min_yset = matrix(min_yset, (ny, 1), 'd') if isinstance(max_yset, (int, float)): max_yset = matrix(max_yset, (ny, 1), 'd') above_idx, below_idx = list(), list() yidx = matrix(yidx) if rmax: # find the over-limit remote idx above = ageb(self.__dict__[rtype][ridx], rmax) above_idx = index(above, 1.0) # reset the y values based on the remote limit violations self.y[yidx[above_idx]] = max_yset[above_idx] self.zymax[yidx[above_idx]] = 0 if rmin: below = aleb(self.__dict__[rtype][ridx], rmin) below_idx = index(below, 1.0) self.y[yidx[below_idx]] = min_yset[below_idx] self.zymin[yidx[below_idx]] = 0 idx = above_idx + below_idx self.g[yidx[idx]] = 0 if len(idx) > 0: self.factorize = True
[ "def", "hard_limit_remote", "(", "self", ",", "yidx", ",", "ridx", ",", "rtype", "=", "'y'", ",", "rmin", "=", "None", ",", "rmax", "=", "None", ",", "min_yset", "=", "0", ",", "max_yset", "=", "0", ")", ":", "ny", "=", "len", "(", "yidx", ")", ...
Limit the output of yidx if the remote y is not within the limits This function needs to be modernized.
[ "Limit", "the", "output", "of", "yidx", "if", "the", "remote", "y", "is", "not", "within", "the", "limits" ]
python
train
weso/CWR-DataApi
cwr/grammar/field/basic.py
https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/grammar/field/basic.py#L340-L359
def flag(name=None): """ Creates the grammar for a Flag (F) field, accepting only 'Y', 'N' or 'U'. :param name: name for the field :return: grammar for the flag field """ if name is None: name = 'Flag Field' # Basic field field = pp.Regex('[YNU]') # Name field.setName(name) field.leaveWhitespace() return field
[ "def", "flag", "(", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'Flag Field'", "# Basic field", "field", "=", "pp", ".", "Regex", "(", "'[YNU]'", ")", "# Name", "field", ".", "setName", "(", "name", ")", "field", "."...
Creates the grammar for a Flag (F) field, accepting only 'Y', 'N' or 'U'. :param name: name for the field :return: grammar for the flag field
[ "Creates", "the", "grammar", "for", "a", "Flag", "(", "F", ")", "field", "accepting", "only", "Y", "N", "or", "U", "." ]
python
train
dereneaton/ipyrad
ipyrad/analysis/twiist.py
https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/twiist.py#L95-L125
def sample_loci(self): """ finds loci with sufficient sampling for this test""" ## store idx of passing loci idxs = np.random.choice(self.idxs, self.ntests) ## open handle, make a proper generator to reduce mem with open(self.data) as indata: liter = (indata.read().strip().split("|\n")) ## store data as dict seqdata = {i:"" for i in self.samples} ## put chunks into a list for idx, loc in enumerate(liter): if idx in idxs: ## parse chunk lines = loc.split("\n")[:-1] names = [i.split()[0] for i in lines] seqs = [i.split()[1] for i in lines] dd = {i:j for i,j in zip(names, seqs)} ## add data to concatenated seqdict for name in seqdata: if name in names: seqdata[name] += dd[name] else: seqdata[name] += "N"*len(seqs[0]) ## concatenate into a phylip file return seqdata
[ "def", "sample_loci", "(", "self", ")", ":", "## store idx of passing loci", "idxs", "=", "np", ".", "random", ".", "choice", "(", "self", ".", "idxs", ",", "self", ".", "ntests", ")", "## open handle, make a proper generator to reduce mem", "with", "open", "(", ...
finds loci with sufficient sampling for this test
[ "finds", "loci", "with", "sufficient", "sampling", "for", "this", "test" ]
python
valid
dusktreader/flask-praetorian
example/refresh.py
https://github.com/dusktreader/flask-praetorian/blob/d530cf3ffeffd61bfff1b8c79e8b45e9bfa0db0c/example/refresh.py#L141-L154
def disable_user(): """ Disables a user in the data store .. example:: $ curl http://localhost:5000/disable_user -X POST \ -H "Authorization: Bearer <your_token>" \ -d '{"username":"Walter"}' """ req = flask.request.get_json(force=True) usr = User.query.filter_by(username=req.get('username', None)).one() usr.is_active = False db.session.commit() return flask.jsonify(message='disabled user {}'.format(usr.username))
[ "def", "disable_user", "(", ")", ":", "req", "=", "flask", ".", "request", ".", "get_json", "(", "force", "=", "True", ")", "usr", "=", "User", ".", "query", ".", "filter_by", "(", "username", "=", "req", ".", "get", "(", "'username'", ",", "None", ...
Disables a user in the data store .. example:: $ curl http://localhost:5000/disable_user -X POST \ -H "Authorization: Bearer <your_token>" \ -d '{"username":"Walter"}'
[ "Disables", "a", "user", "in", "the", "data", "store" ]
python
train
python-wink/python-wink
src/pywink/devices/cloud_clock.py
https://github.com/python-wink/python-wink/blob/cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da/src/pywink/devices/cloud_clock.py#L22-L40
def set_dial(self, json_value, index, timezone=None): """ :param json_value: The value to set :param index: The dials index :param timezone: The time zone to use for a time dial :return: """ values = self.json_state values["nonce"] = str(random.randint(0, 1000000000)) if timezone is None: json_value["channel_configuration"] = {"channel_id": "10"} values["dials"][index] = json_value response = self.api_interface.set_device_state(self, values) else: json_value["channel_configuration"] = {"channel_id": "1", "timezone": timezone} values["dials"][index] = json_value response = self.api_interface.set_device_state(self, values) return response
[ "def", "set_dial", "(", "self", ",", "json_value", ",", "index", ",", "timezone", "=", "None", ")", ":", "values", "=", "self", ".", "json_state", "values", "[", "\"nonce\"", "]", "=", "str", "(", "random", ".", "randint", "(", "0", ",", "1000000000", ...
:param json_value: The value to set :param index: The dials index :param timezone: The time zone to use for a time dial :return:
[ ":", "param", "json_value", ":", "The", "value", "to", "set", ":", "param", "index", ":", "The", "dials", "index", ":", "param", "timezone", ":", "The", "time", "zone", "to", "use", "for", "a", "time", "dial", ":", "return", ":" ]
python
train
rosenbrockc/fortpy
fortpy/interop/converter.py
https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/interop/converter.py#L193-L201
def _load(self, element, commentchar): """Loads all the child line elements from the XML group element.""" for child in element: if "id" in child.attrib: tline = TemplateLine(child, self, commentchar) self.order.append(tline.identifier) self.lines[tline.identifier] = tline else: msg.warn("no id element in {}. Ignored. (group._load)".format(child))
[ "def", "_load", "(", "self", ",", "element", ",", "commentchar", ")", ":", "for", "child", "in", "element", ":", "if", "\"id\"", "in", "child", ".", "attrib", ":", "tline", "=", "TemplateLine", "(", "child", ",", "self", ",", "commentchar", ")", "self"...
Loads all the child line elements from the XML group element.
[ "Loads", "all", "the", "child", "line", "elements", "from", "the", "XML", "group", "element", "." ]
python
train
squaresLab/BugZoo
bugzoo/client/container.py
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/container.py#L110-L138
def provision(self, bug: Bug, *, plugins: Optional[List[Tool]] = None ) -> Container: """ Provisions a container for a given bug. """ if plugins is None: plugins = [] logger.info("provisioning container for bug: %s", bug.name) endpoint = 'bugs/{}/provision'.format(bug.name) payload = { 'plugins': [p.to_dict() for p in plugins] } # type: Dict[str, Any] r = self.__api.post(endpoint, json=payload) if r.status_code == 200: container = Container.from_dict(r.json()) logger.info("provisioned container (id: %s) for bug: %s", container.uid, bug.name) return container if r.status_code == 404: raise KeyError("no bug registered with given name: {}".format(bug.name)) self.__api.handle_erroneous_response(r)
[ "def", "provision", "(", "self", ",", "bug", ":", "Bug", ",", "*", ",", "plugins", ":", "Optional", "[", "List", "[", "Tool", "]", "]", "=", "None", ")", "->", "Container", ":", "if", "plugins", "is", "None", ":", "plugins", "=", "[", "]", "logge...
Provisions a container for a given bug.
[ "Provisions", "a", "container", "for", "a", "given", "bug", "." ]
python
train
tanghaibao/goatools
goatools/grouper/wr_sections.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/wr_sections.py#L36-L40
def prt_ntgos(self, prt, ntgos): """Print the Grouper namedtuples.""" for ntgo in ntgos: key2val = ntgo._asdict() prt.write("{GO_LINE}\n".format(GO_LINE=self.prtfmt.format(**key2val)))
[ "def", "prt_ntgos", "(", "self", ",", "prt", ",", "ntgos", ")", ":", "for", "ntgo", "in", "ntgos", ":", "key2val", "=", "ntgo", ".", "_asdict", "(", ")", "prt", ".", "write", "(", "\"{GO_LINE}\\n\"", ".", "format", "(", "GO_LINE", "=", "self", ".", ...
Print the Grouper namedtuples.
[ "Print", "the", "Grouper", "namedtuples", "." ]
python
train
rogerhil/thegamesdb
thegamesdb/resources.py
https://github.com/rogerhil/thegamesdb/blob/795314215f9ee73697c7520dea4ddecfb23ca8e6/thegamesdb/resources.py#L81-L88
def games(self, platform): """ It returns a list of games given the platform *alias* (usually is the game name separated by "-" instead of white spaces). """ platform = platform.lower() data_list = self.db.get_data(self.games_path, platform=platform) data_list = data_list.get('Data') or {} return [Game(self.db.game, **i) for i in data_list.get('Game') or {}]
[ "def", "games", "(", "self", ",", "platform", ")", ":", "platform", "=", "platform", ".", "lower", "(", ")", "data_list", "=", "self", ".", "db", ".", "get_data", "(", "self", ".", "games_path", ",", "platform", "=", "platform", ")", "data_list", "=", ...
It returns a list of games given the platform *alias* (usually is the game name separated by "-" instead of white spaces).
[ "It", "returns", "a", "list", "of", "games", "given", "the", "platform", "*", "alias", "*", "(", "usually", "is", "the", "game", "name", "separated", "by", "-", "instead", "of", "white", "spaces", ")", "." ]
python
train
ANTsX/ANTsPy
ants/viz/surface.py
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/viz/surface.py#L331-L485
def _surf_smooth_single(image,outfile,dilation,smooth,threshold,inflation,alpha, cut_idx,cut_side,overlay,overlay_mask,overlay_cmap,overlay_scale, overlay_alpha,rotation,grayscale,bg_grayscale,verbose): """ Generate a surface of the smooth white matter of a brain image. This is great for displaying functional activations as are typically seen in the neuroimaging literature. Arguments --------- image : ANTsImage A binary segmentation of the white matter surface. If you don't have a white matter segmentation, you can use `kmeans_segmentation` or `atropos` on a full-brain image. inflation : integer how much to inflate the final surface rotation : 3-tuple | string | list of 3-tuples | list of string if tuple, this is rotation of X, Y, Z if string, this is a canonical view.. Options: 'left', 'right', 'inner_left', 'inner_right', 'anterior', 'posterior', 'inferior', 'superior' if list of tuples or strings, the surface images will be arranged in a grid according to the shape of the list. e.g. rotation=[['left', 'inner_left' ], ['right','inner_right']] will result in a 2x2 grid of the above 4 canonical views grayscale : float value between 0 and 1 representing how light to make the base image. grayscale = 1 will make the base image completely white and grayscale = 0 will make the base image completely black background : float value between 0 and 1 representing how light to make the base image. see `grayscale` arg. outfile : string filepath to which the surface plot will be saved Example ------- >>> import ants >>> mni = ants.image_read(ants.get_data('mni')) >>> seg = mni.otsu_segmentation(k=3) >>> wm_img = seg.threshold_image(3,3) >>> #ants.surf_smooth(wm_img, outfile='~/desktop/surf_smooth.png') >>> ants.surf_smooth(wm_img, rotation='inner_right', outfile='~/desktop/surf_smooth_innerright.png') >>> # with overlay >>> overlay = ants.weingarten_image_curvature( mni, 1.5 ).smooth_image( 1 ).iMath_GD(3) >>> ants.surf_smooth(image=wm_img, overlay=overlay, outfile='~/desktop/surf_smooth2.png') """ # handle rotation argument if rotation is None: rotation = (270,0,270) if not isinstance(rotation, (str, tuple)): raise ValueError('rotation must be a 3-tuple or string') if isinstance(rotation, str): if 'inner' in rotation: cut_idx = int(image.shape[2]/2) cut_side = rotation.replace('inner_','') rotation = _view_map[rotation.lower()] # handle filename argument if outfile is None: outfile = mktemp(suffix='.png') else: outfile = os.path.expanduser(outfile) # handle overlay argument if overlay is not None: if overlay_mask is None: overlay_mask = image.iMath_MD(3) # PROCESSING IMAGE image = image.reorient_image2('RPI') image = image.iMath_fill_holes().iMath_get_largest_component() if dilation > 0: image = image.iMath_MD(dilation) if smooth > 0: image = image.smooth_image(smooth) if threshold > 0: image = image.threshold_image(threshold) if cut_idx is not None: if cut_side == 'left': image = image.crop_indices((0,0,0),(cut_idx,image.shape[1],image.shape[2])) elif cut_side == 'right': image = image.crop_indices((cut_idx,0,0),image.shape) else: raise ValueError('not valid cut_side argument') # surface arg # save base image to temp file image_tmp_file = mktemp(suffix='.nii.gz') image.to_file(image_tmp_file) # build image color grayscale = int(grayscale*255) alpha = 1. image_color = '%sx%.1f' % ('x'.join([str(grayscale)]*3), alpha) cmd = '-s [%s,%s] ' % (image_tmp_file, image_color) # anti-alias arg tolerance = 0.01 cmd += '-a %.3f ' % tolerance # inflation arg cmd += '-i %i ' % inflation # display arg bg_grayscale = int(bg_grayscale*255) cmd += '-d %s[%s,%s]' % (outfile, 'x'.join([str(s) for s in rotation]), 'x'.join([str(bg_grayscale)]*3)) # overlay arg if overlay is not None: overlay = overlay.reorient_image2('RPI') if overlay_scale == True: min_overlay, max_overlay = overlay.quantile((0.05,0.95)) overlay[overlay<min_overlay] = min_overlay overlay[overlay>max_overlay] = max_overlay elif isinstance(overlay_scale, tuple): min_overlay, max_overlay = overlay.quantile((overlay_scale[0], overlay_scale[1])) overlay[overlay<min_overlay] = min_overlay overlay[overlay>max_overlay] = max_overlay # make tempfile for overlay overlay_tmp_file = mktemp(suffix='.nii.gz') # convert overlay image to RGB overlay.scalar_to_rgb(mask=overlay_mask, cmap=overlay_cmap, filename=overlay_tmp_file) # make tempfile for overlay mask overlay_mask_tmp_file = mktemp(suffix='.nii.gz') overlay_mask.to_file(overlay_mask_tmp_file) cmd += ' -f [%s,%s,%.2f]' % (overlay_tmp_file, overlay_mask_tmp_file, overlay_alpha) if verbose: print(cmd) time.sleep(1) cmd = cmd.split(' ') libfn = utils.get_lib_fn('antsSurf') retval = libfn(cmd) if retval != 0: print('ERROR: Non-Zero Return Value!') # cleanup temp file os.remove(image_tmp_file)
[ "def", "_surf_smooth_single", "(", "image", ",", "outfile", ",", "dilation", ",", "smooth", ",", "threshold", ",", "inflation", ",", "alpha", ",", "cut_idx", ",", "cut_side", ",", "overlay", ",", "overlay_mask", ",", "overlay_cmap", ",", "overlay_scale", ",", ...
Generate a surface of the smooth white matter of a brain image. This is great for displaying functional activations as are typically seen in the neuroimaging literature. Arguments --------- image : ANTsImage A binary segmentation of the white matter surface. If you don't have a white matter segmentation, you can use `kmeans_segmentation` or `atropos` on a full-brain image. inflation : integer how much to inflate the final surface rotation : 3-tuple | string | list of 3-tuples | list of string if tuple, this is rotation of X, Y, Z if string, this is a canonical view.. Options: 'left', 'right', 'inner_left', 'inner_right', 'anterior', 'posterior', 'inferior', 'superior' if list of tuples or strings, the surface images will be arranged in a grid according to the shape of the list. e.g. rotation=[['left', 'inner_left' ], ['right','inner_right']] will result in a 2x2 grid of the above 4 canonical views grayscale : float value between 0 and 1 representing how light to make the base image. grayscale = 1 will make the base image completely white and grayscale = 0 will make the base image completely black background : float value between 0 and 1 representing how light to make the base image. see `grayscale` arg. outfile : string filepath to which the surface plot will be saved Example ------- >>> import ants >>> mni = ants.image_read(ants.get_data('mni')) >>> seg = mni.otsu_segmentation(k=3) >>> wm_img = seg.threshold_image(3,3) >>> #ants.surf_smooth(wm_img, outfile='~/desktop/surf_smooth.png') >>> ants.surf_smooth(wm_img, rotation='inner_right', outfile='~/desktop/surf_smooth_innerright.png') >>> # with overlay >>> overlay = ants.weingarten_image_curvature( mni, 1.5 ).smooth_image( 1 ).iMath_GD(3) >>> ants.surf_smooth(image=wm_img, overlay=overlay, outfile='~/desktop/surf_smooth2.png')
[ "Generate", "a", "surface", "of", "the", "smooth", "white", "matter", "of", "a", "brain", "image", "." ]
python
train
OpenGov/python_data_wrap
datawrap/external/xmlparse.py
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L521-L526
def startElement (self, name, attrs): '''if there's a start method for this element, call it ''' func = getattr(self, 'start_' + name, None) if func: func(attrs)
[ "def", "startElement", "(", "self", ",", "name", ",", "attrs", ")", ":", "func", "=", "getattr", "(", "self", ",", "'start_'", "+", "name", ",", "None", ")", "if", "func", ":", "func", "(", "attrs", ")" ]
if there's a start method for this element, call it
[ "if", "there", "s", "a", "start", "method", "for", "this", "element", "call", "it" ]
python
train
apple/turicreate
deps/src/libxml2-2.9.1/python/libxml2.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L7312-L7315
def xpathRegisterVariable(self, name, ns_uri, value): """Register a variable with the XPath context """ ret = libxml2mod.xmlXPathRegisterVariable(self._o, name, ns_uri, value) return ret
[ "def", "xpathRegisterVariable", "(", "self", ",", "name", ",", "ns_uri", ",", "value", ")", ":", "ret", "=", "libxml2mod", ".", "xmlXPathRegisterVariable", "(", "self", ".", "_o", ",", "name", ",", "ns_uri", ",", "value", ")", "return", "ret" ]
Register a variable with the XPath context
[ "Register", "a", "variable", "with", "the", "XPath", "context" ]
python
train
Microsoft/azure-devops-python-api
azure-devops/azure/devops/v5_1/gallery/gallery_client.py
https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_1/gallery/gallery_client.py#L98-L122
def get_acquisition_options(self, item_id, installation_target, test_commerce=None, is_free_or_trial_install=None): """GetAcquisitionOptions. [Preview API] :param str item_id: :param str installation_target: :param bool test_commerce: :param bool is_free_or_trial_install: :rtype: :class:`<AcquisitionOptions> <azure.devops.v5_1.gallery.models.AcquisitionOptions>` """ route_values = {} if item_id is not None: route_values['itemId'] = self._serialize.url('item_id', item_id, 'str') query_parameters = {} if installation_target is not None: query_parameters['installationTarget'] = self._serialize.query('installation_target', installation_target, 'str') if test_commerce is not None: query_parameters['testCommerce'] = self._serialize.query('test_commerce', test_commerce, 'bool') if is_free_or_trial_install is not None: query_parameters['isFreeOrTrialInstall'] = self._serialize.query('is_free_or_trial_install', is_free_or_trial_install, 'bool') response = self._send(http_method='GET', location_id='9d0a0105-075e-4760-aa15-8bcf54d1bd7d', version='5.1-preview.1', route_values=route_values, query_parameters=query_parameters) return self._deserialize('AcquisitionOptions', response)
[ "def", "get_acquisition_options", "(", "self", ",", "item_id", ",", "installation_target", ",", "test_commerce", "=", "None", ",", "is_free_or_trial_install", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "item_id", "is", "not", "None", ":", "rou...
GetAcquisitionOptions. [Preview API] :param str item_id: :param str installation_target: :param bool test_commerce: :param bool is_free_or_trial_install: :rtype: :class:`<AcquisitionOptions> <azure.devops.v5_1.gallery.models.AcquisitionOptions>`
[ "GetAcquisitionOptions", ".", "[", "Preview", "API", "]", ":", "param", "str", "item_id", ":", ":", "param", "str", "installation_target", ":", ":", "param", "bool", "test_commerce", ":", ":", "param", "bool", "is_free_or_trial_install", ":", ":", "rtype", ":"...
python
train
calve/prof
prof/session.py
https://github.com/calve/prof/blob/c6e034f45ab60908dea661e8271bc44758aeedcf/prof/session.py#L54-L95
def get_session(session, baseurl, config): """ Try to get a valid session for this baseurl, using login found in config. This function invoques Firefox if necessary """ # Read proxy for firefox if environ.get("HTTP_PROXY"): myProxy = environ.get("HTTP_PROXY") proxy = Proxy({ 'proxyType': ProxyType.MANUAL, 'httpProxy': myProxy, 'ftpProxy': myProxy, 'sslProxy': myProxy, 'noProxy': '' # set this value as desired }) else: proxy = None if 'login' in config['DEFAULT']: login, password = credentials(config['DEFAULT']['login']) else: login, password = credentials() browser = webdriver.Firefox(proxy=proxy) browser.get(baseurl) browser.find_element_by_name('login').send_keys(login) browser.find_element_by_name('passwd').send_keys(password) cookie = {'PHPSESSID': browser.get_cookie('PHPSESSID')['value']} prof_session.cookies = requests.utils.cookiejar_from_dict(cookie) print("Please log using firefox") while True: try: browser.find_element_by_css_selector("select") break except: sleep(0.5) browser.close() set_sessid(cookie['PHPSESSID']) if not verify_session(session, baseurl): print("Cannot get a valid session, retry") get_session(session, baseurl, {'DEFAULT': {}})
[ "def", "get_session", "(", "session", ",", "baseurl", ",", "config", ")", ":", "# Read proxy for firefox", "if", "environ", ".", "get", "(", "\"HTTP_PROXY\"", ")", ":", "myProxy", "=", "environ", ".", "get", "(", "\"HTTP_PROXY\"", ")", "proxy", "=", "Proxy",...
Try to get a valid session for this baseurl, using login found in config. This function invoques Firefox if necessary
[ "Try", "to", "get", "a", "valid", "session", "for", "this", "baseurl", "using", "login", "found", "in", "config", ".", "This", "function", "invoques", "Firefox", "if", "necessary" ]
python
train
robotools/fontParts
Lib/fontParts/base/normalizers.py
https://github.com/robotools/fontParts/blob/d2ff106fe95f9d566161d936a645157626568712/Lib/fontParts/base/normalizers.py#L1083-L1098
def normalizeRounding(value): """ Normalizes rounding. Python 2 and Python 3 handing the rounding of halves (0.5, 1.5, etc) differently. This normalizes rounding to be the same (Python 3 style) in both environments. * **value** must be an :ref:`type-int-float` * Returned value is a ``int`` """ if not isinstance(value, (int, float)): raise TypeError("Value to round must be an int or float, not %s." % type(value).__name__) return round3(value)
[ "def", "normalizeRounding", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "(", "int", ",", "float", ")", ")", ":", "raise", "TypeError", "(", "\"Value to round must be an int or float, not %s.\"", "%", "type", "(", "value", ")", ".", ...
Normalizes rounding. Python 2 and Python 3 handing the rounding of halves (0.5, 1.5, etc) differently. This normalizes rounding to be the same (Python 3 style) in both environments. * **value** must be an :ref:`type-int-float` * Returned value is a ``int``
[ "Normalizes", "rounding", "." ]
python
train
kensho-technologies/grift
grift/config.py
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/config.py#L70-L74
def _iter_config_props(cls): """Iterate over all ConfigProperty attributes, yielding (attr_name, config_property) """ props = inspect.getmembers(cls, lambda a: isinstance(a, ConfigProperty)) for attr_name, config_prop in props: yield attr_name, config_prop
[ "def", "_iter_config_props", "(", "cls", ")", ":", "props", "=", "inspect", ".", "getmembers", "(", "cls", ",", "lambda", "a", ":", "isinstance", "(", "a", ",", "ConfigProperty", ")", ")", "for", "attr_name", ",", "config_prop", "in", "props", ":", "yiel...
Iterate over all ConfigProperty attributes, yielding (attr_name, config_property)
[ "Iterate", "over", "all", "ConfigProperty", "attributes", "yielding", "(", "attr_name", "config_property", ")" ]
python
train
rocky/python3-trepan
trepan/processor/parse/scanner.py
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/parse/scanner.py#L101-L105
def t_comma(self, s): r',' # Used in "list" to separate first from last self.add_token('COMMA', s) self.pos += len(s)
[ "def", "t_comma", "(", "self", ",", "s", ")", ":", "# Used in \"list\" to separate first from last", "self", ".", "add_token", "(", "'COMMA'", ",", "s", ")", "self", ".", "pos", "+=", "len", "(", "s", ")" ]
r',
[ "r" ]
python
test
gsi-upm/soil
examples/custom_generator/mymodule.py
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/examples/custom_generator/mymodule.py#L5-L21
def mygenerator(n=5, n_edges=5): ''' Just a simple generator that creates a network with n nodes and n_edges edges. Edges are assigned randomly, only avoiding self loops. ''' G = nx.Graph() for i in range(n): G.add_node(i) for i in range(n_edges): nodes = list(G.nodes) n_in = choice(nodes) nodes.remove(n_in) # Avoid loops n_out = choice(nodes) G.add_edge(n_in, n_out) return G
[ "def", "mygenerator", "(", "n", "=", "5", ",", "n_edges", "=", "5", ")", ":", "G", "=", "nx", ".", "Graph", "(", ")", "for", "i", "in", "range", "(", "n", ")", ":", "G", ".", "add_node", "(", "i", ")", "for", "i", "in", "range", "(", "n_edg...
Just a simple generator that creates a network with n nodes and n_edges edges. Edges are assigned randomly, only avoiding self loops.
[ "Just", "a", "simple", "generator", "that", "creates", "a", "network", "with", "n", "nodes", "and", "n_edges", "edges", ".", "Edges", "are", "assigned", "randomly", "only", "avoiding", "self", "loops", "." ]
python
train
quantumlib/Cirq
cirq/google/sim/xmon_simulator.py
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/sim/xmon_simulator.py#L211-L290
def _base_iterator( self, circuit: circuits.Circuit, qubit_order: ops.QubitOrderOrList, initial_state: Union[int, np.ndarray], perform_measurements: bool=True, ) -> Iterator['XmonStepResult']: """See definition in `cirq.SimulatesIntermediateState`. If the initial state is an int, the state is set to the computational basis state corresponding to this state. Otherwise if the initial state is a np.ndarray it is the full initial state. In this case it must be the correct size, be normalized (an L2 norm of 1), and be safely castable to an appropriate dtype for the simulator. """ qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for( circuit.all_qubits()) qubit_map = {q: i for i, q in enumerate(reversed(qubits))} if isinstance(initial_state, np.ndarray): initial_state = initial_state.astype(dtype=np.complex64, casting='safe') with xmon_stepper.Stepper( num_qubits=len(qubits), num_prefix_qubits=self.options.num_prefix_qubits, initial_state=initial_state, min_qubits_before_shard=self.options.min_qubits_before_shard, use_processes=self.options.use_processes ) as stepper: if len(circuit) == 0: yield XmonStepResult(stepper, qubit_map, {}) for moment in circuit: measurements = collections.defaultdict( list) # type: Dict[str, List[bool]] phase_map = {} # type: Dict[Tuple[int, ...], float] for op in moment.operations: gate = cast(ops.GateOperation, op).gate if isinstance(gate, ops.ZPowGate): index = qubit_map[op.qubits[0]] phase_map[(index,)] = cast(float, gate.exponent) elif isinstance(gate, ops.CZPowGate): index0 = qubit_map[op.qubits[0]] index1 = qubit_map[op.qubits[1]] phase_map[(index0, index1)] = cast(float, gate.exponent) elif isinstance(gate, ops.XPowGate): index = qubit_map[op.qubits[0]] stepper.simulate_w( index=index, half_turns=gate.exponent, axis_half_turns=0) elif isinstance(gate, ops.YPowGate): index = qubit_map[op.qubits[0]] stepper.simulate_w( index=index, half_turns=gate.exponent, axis_half_turns=0.5) elif isinstance(gate, ops.PhasedXPowGate): index = qubit_map[op.qubits[0]] stepper.simulate_w( index=index, half_turns=gate.exponent, axis_half_turns=gate.phase_exponent) elif isinstance(gate, ops.MeasurementGate): if perform_measurements: invert_mask = ( gate.invert_mask or len(op.qubits) * (False,)) for qubit, invert in zip(op.qubits, invert_mask): index = qubit_map[qubit] result = stepper.simulate_measurement(index) if invert: result = not result key = protocols.measurement_key(gate) measurements[key].append(result) else: # coverage: ignore raise TypeError('{!r} is not supported by the ' 'xmon simulator.'.format(gate)) stepper.simulate_phases(phase_map) yield XmonStepResult(stepper, qubit_map, measurements)
[ "def", "_base_iterator", "(", "self", ",", "circuit", ":", "circuits", ".", "Circuit", ",", "qubit_order", ":", "ops", ".", "QubitOrderOrList", ",", "initial_state", ":", "Union", "[", "int", ",", "np", ".", "ndarray", "]", ",", "perform_measurements", ":", ...
See definition in `cirq.SimulatesIntermediateState`. If the initial state is an int, the state is set to the computational basis state corresponding to this state. Otherwise if the initial state is a np.ndarray it is the full initial state. In this case it must be the correct size, be normalized (an L2 norm of 1), and be safely castable to an appropriate dtype for the simulator.
[ "See", "definition", "in", "cirq", ".", "SimulatesIntermediateState", "." ]
python
train
fedora-infra/fmn.lib
fmn/lib/models.py
https://github.com/fedora-infra/fmn.lib/blob/3120725556153d07c1809530f0fadcf250439110/fmn/lib/models.py#L724-L726
def hash_producer(*args, **kwargs): """ Returns a random hash for a confirmation secret. """ return hashlib.md5(six.text_type(uuid.uuid4()).encode('utf-8')).hexdigest()
[ "def", "hash_producer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "hashlib", ".", "md5", "(", "six", ".", "text_type", "(", "uuid", ".", "uuid4", "(", ")", ")", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ...
Returns a random hash for a confirmation secret.
[ "Returns", "a", "random", "hash", "for", "a", "confirmation", "secret", "." ]
python
train
aws/aws-xray-sdk-python
aws_xray_sdk/core/models/entity.py
https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/models/entity.py#L192-L208
def apply_status_code(self, status_code): """ When a trace entity is generated under the http context, the status code will affect this entity's fault/error/throttle flags. Flip these flags based on status code. """ self._check_ended() if not status_code: return if status_code >= 500: self.add_fault_flag() elif status_code == 429: self.add_throttle_flag() self.add_error_flag() elif status_code >= 400: self.add_error_flag()
[ "def", "apply_status_code", "(", "self", ",", "status_code", ")", ":", "self", ".", "_check_ended", "(", ")", "if", "not", "status_code", ":", "return", "if", "status_code", ">=", "500", ":", "self", ".", "add_fault_flag", "(", ")", "elif", "status_code", ...
When a trace entity is generated under the http context, the status code will affect this entity's fault/error/throttle flags. Flip these flags based on status code.
[ "When", "a", "trace", "entity", "is", "generated", "under", "the", "http", "context", "the", "status", "code", "will", "affect", "this", "entity", "s", "fault", "/", "error", "/", "throttle", "flags", ".", "Flip", "these", "flags", "based", "on", "status",...
python
train
honzamach/pydgets
pydgets/widgets.py
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L1060-L1083
def _render_line(self, line, settings): """ Render single box line. """ s = self._es(settings, self.SETTING_WIDTH, self.SETTING_FLAG_BORDER, self.SETTING_MARGIN, self.SETTING_MARGIN_LEFT, self.SETTING_MARGIN_RIGHT) width_content = self.calculate_width_widget_int(**s) s = self._es_content(settings) s[self.SETTING_WIDTH] = width_content line = self.fmt_content(line, **s) s = self._es_text(settings, settings[self.SETTING_TEXT_FORMATING]) line = self.fmt_text(line, **s) s = self._es(settings, self.SETTING_BORDER_STYLE) bchar = self.bchar('v', 'm', **s) s = self._es_text(settings, settings[self.SETTING_BORDER_FORMATING]) bchar = self.fmt_text(bchar, **s) line = '{}{}{}'.format(bchar, line, bchar) s = self._es_margin(settings) line = self.fmt_margin(line, **s) return line
[ "def", "_render_line", "(", "self", ",", "line", ",", "settings", ")", ":", "s", "=", "self", ".", "_es", "(", "settings", ",", "self", ".", "SETTING_WIDTH", ",", "self", ".", "SETTING_FLAG_BORDER", ",", "self", ".", "SETTING_MARGIN", ",", "self", ".", ...
Render single box line.
[ "Render", "single", "box", "line", "." ]
python
train
mezz64/pyEmby
pyemby/server.py
https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L148-L154
def _do_update_callback(self, msg): """Call registered callback functions.""" for callback, device in self._update_callbacks: if device == msg: _LOGGER.debug('Update callback %s for device %s by %s', callback, device, msg) self._event_loop.call_soon(callback, msg)
[ "def", "_do_update_callback", "(", "self", ",", "msg", ")", ":", "for", "callback", ",", "device", "in", "self", ".", "_update_callbacks", ":", "if", "device", "==", "msg", ":", "_LOGGER", ".", "debug", "(", "'Update callback %s for device %s by %s'", ",", "ca...
Call registered callback functions.
[ "Call", "registered", "callback", "functions", "." ]
python
train
peeringdb/peeringdb-py
peeringdb/backend.py
https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/backend.py#L8-L27
def reftag_to_cls(fn): """ decorator that checks function arguments for `concrete` and `resource` and will properly set them to class references if a string (reftag) is passed as the value """ names, _, _, values = inspect.getargspec(fn) @wraps(fn) def wrapped(*args, **kwargs): i = 0 backend = args[0] for name in names[1:]: value = args[i] if name == "concrete" and isinstance(value, six.string_types): args[i] = backend.REFTAG_CONCRETE[value] elif name == "resource" and isinstance(value, six.string_types): args[i] = backend.REFTAG_RESOURCE[value] i += 1 return fn(*args, **kwargs) return wrapped
[ "def", "reftag_to_cls", "(", "fn", ")", ":", "names", ",", "_", ",", "_", ",", "values", "=", "inspect", ".", "getargspec", "(", "fn", ")", "@", "wraps", "(", "fn", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "i"...
decorator that checks function arguments for `concrete` and `resource` and will properly set them to class references if a string (reftag) is passed as the value
[ "decorator", "that", "checks", "function", "arguments", "for", "concrete", "and", "resource", "and", "will", "properly", "set", "them", "to", "class", "references", "if", "a", "string", "(", "reftag", ")", "is", "passed", "as", "the", "value" ]
python
train
niklasf/python-chess
chess/pgn.py
https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L834-L840
def handle_error(self, error: Exception) -> None: """ Populates :data:`chess.pgn.Game.errors` with encountered errors and logs them. """ LOGGER.exception("error during pgn parsing") self.game.errors.append(error)
[ "def", "handle_error", "(", "self", ",", "error", ":", "Exception", ")", "->", "None", ":", "LOGGER", ".", "exception", "(", "\"error during pgn parsing\"", ")", "self", ".", "game", ".", "errors", ".", "append", "(", "error", ")" ]
Populates :data:`chess.pgn.Game.errors` with encountered errors and logs them.
[ "Populates", ":", "data", ":", "chess", ".", "pgn", ".", "Game", ".", "errors", "with", "encountered", "errors", "and", "logs", "them", "." ]
python
train
JohnVinyard/featureflow
featureflow/extractor.py
https://github.com/JohnVinyard/featureflow/blob/7731487b00e38fa4f58c88b7881870fda2d69fdb/featureflow/extractor.py#L118-L126
def _finalized(self): """ Return true if all dependencies have informed this node that they'll be sending no more data (by calling _finalize()), and that they have sent at least one batch of data (by calling enqueue()) """ return \ len(self._finalized_dependencies) >= self.dependency_count \ and len(self._enqueued_dependencies) >= self.dependency_count
[ "def", "_finalized", "(", "self", ")", ":", "return", "len", "(", "self", ".", "_finalized_dependencies", ")", ">=", "self", ".", "dependency_count", "and", "len", "(", "self", ".", "_enqueued_dependencies", ")", ">=", "self", ".", "dependency_count" ]
Return true if all dependencies have informed this node that they'll be sending no more data (by calling _finalize()), and that they have sent at least one batch of data (by calling enqueue())
[ "Return", "true", "if", "all", "dependencies", "have", "informed", "this", "node", "that", "they", "ll", "be", "sending", "no", "more", "data", "(", "by", "calling", "_finalize", "()", ")", "and", "that", "they", "have", "sent", "at", "least", "one", "ba...
python
train
QuantEcon/QuantEcon.py
quantecon/game_theory/repeated_game.py
https://github.com/QuantEcon/QuantEcon.py/blob/26a66c552f2a73967d7efb6e1f4b4c4985a12643/quantecon/game_theory/repeated_game.py#L370-L431
def _intersect(C, n, weights, IC, pt0, pt1, tol): """ Find the intersection points of a half-closed simplex (pt0, pt1] and IC constraints. Parameters ---------- C : ndarray(float, ndim=2) The 4 by 2 array for storing the generated points of one action profile. One action profile can only generate at most 4 points. n : scalar(int) The number of intersection points that have been found. weights : ndarray(float, ndim=1) The size 2 array for storing the weights when calculate the intersection point of simplex and IC constraints. IC : ndarray(float, ndim=1) The minimum IC continuation values. pt0 : ndarray(float, ndim=1) Coordinates of the starting point of the simplex. pt1 : ndarray(float, ndim=1) Coordinates of the ending point of the simplex. tol : scalar(float) The tolerance for checking if two values are equal. Returns ------- n : scalar(int) The updated number of found intersection points. """ for i in range(2): if (abs(pt0[i] - pt1[i]) < tol): if (abs(pt1[i] - IC[i]) < tol): x = pt1[1-i] else: continue else: weights[i] = (pt0[i] - IC[i]) / (pt0[i] - pt1[i]) # pt0 is not included to avoid duplication # weights in (0, 1] if (0 < weights[i] <= 1): x = (1 - weights[i]) * pt0[1-i] + weights[i] * pt1[1-i] else: continue # x has to be strictly higher than IC[1-j] # if it is equal, then it means IC is one of the vertex # it will be added to C in below if x - IC[1-i] > tol: C[n, i] = IC[i] C[n, 1-i] = x n += 1 elif x - IC[1-i] > -tol: # to avoid duplication when IC is a vertex break return n
[ "def", "_intersect", "(", "C", ",", "n", ",", "weights", ",", "IC", ",", "pt0", ",", "pt1", ",", "tol", ")", ":", "for", "i", "in", "range", "(", "2", ")", ":", "if", "(", "abs", "(", "pt0", "[", "i", "]", "-", "pt1", "[", "i", "]", ")", ...
Find the intersection points of a half-closed simplex (pt0, pt1] and IC constraints. Parameters ---------- C : ndarray(float, ndim=2) The 4 by 2 array for storing the generated points of one action profile. One action profile can only generate at most 4 points. n : scalar(int) The number of intersection points that have been found. weights : ndarray(float, ndim=1) The size 2 array for storing the weights when calculate the intersection point of simplex and IC constraints. IC : ndarray(float, ndim=1) The minimum IC continuation values. pt0 : ndarray(float, ndim=1) Coordinates of the starting point of the simplex. pt1 : ndarray(float, ndim=1) Coordinates of the ending point of the simplex. tol : scalar(float) The tolerance for checking if two values are equal. Returns ------- n : scalar(int) The updated number of found intersection points.
[ "Find", "the", "intersection", "points", "of", "a", "half", "-", "closed", "simplex", "(", "pt0", "pt1", "]", "and", "IC", "constraints", "." ]
python
train
pyupio/pyup
pyup/bot.py
https://github.com/pyupio/pyup/blob/b20fa88e03cfdf5dc409a9f00d27629188171c31/pyup/bot.py#L115-L128
def update(self, **kwargs): """ Main entrypoint to kick off an update run. :param kwargs: :return: RequirementsBundle """ self.configure(**kwargs) self.get_all_requirements() self.apply_updates( initial=kwargs.get("initial", False), scheduled=kwargs.get("scheduled", False) ) return self.req_bundle
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "configure", "(", "*", "*", "kwargs", ")", "self", ".", "get_all_requirements", "(", ")", "self", ".", "apply_updates", "(", "initial", "=", "kwargs", ".", "get", "(", "\"i...
Main entrypoint to kick off an update run. :param kwargs: :return: RequirementsBundle
[ "Main", "entrypoint", "to", "kick", "off", "an", "update", "run", ".", ":", "param", "kwargs", ":", ":", "return", ":", "RequirementsBundle" ]
python
train
IRC-SPHERE/HyperStream
hyperstream/stream/stream.py
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/stream/stream.py#L308-L317
def calculated_intervals(self, intervals): """ Updates the calculated intervals in the database. Performs an upsert :param intervals: The calculated intervals :return: None """ if len(intervals) > 1: raise ValueError("Only single calculated interval valid for AssetStream") super(AssetStream, self.__class__).calculated_intervals.fset(self, intervals)
[ "def", "calculated_intervals", "(", "self", ",", "intervals", ")", ":", "if", "len", "(", "intervals", ")", ">", "1", ":", "raise", "ValueError", "(", "\"Only single calculated interval valid for AssetStream\"", ")", "super", "(", "AssetStream", ",", "self", ".", ...
Updates the calculated intervals in the database. Performs an upsert :param intervals: The calculated intervals :return: None
[ "Updates", "the", "calculated", "intervals", "in", "the", "database", ".", "Performs", "an", "upsert" ]
python
train
ppo/django-guitar
guitar/utils/__init__.py
https://github.com/ppo/django-guitar/blob/857282219c0c4ff5907c3ad04ef012281d245348/guitar/utils/__init__.py#L9-L19
def get_perm_name(cls, action, full=True): """ Return the name of the permission for a given model and action. By default it returns the full permission name `app_label.perm_codename`. If `full=False`, it returns only the `perm_codename`. """ codename = "{}_{}".format(action, cls.__name__.lower()) if full: return "{}.{}".format(cls._meta.app_label, codename) return codename
[ "def", "get_perm_name", "(", "cls", ",", "action", ",", "full", "=", "True", ")", ":", "codename", "=", "\"{}_{}\"", ".", "format", "(", "action", ",", "cls", ".", "__name__", ".", "lower", "(", ")", ")", "if", "full", ":", "return", "\"{}.{}\"", "."...
Return the name of the permission for a given model and action. By default it returns the full permission name `app_label.perm_codename`. If `full=False`, it returns only the `perm_codename`.
[ "Return", "the", "name", "of", "the", "permission", "for", "a", "given", "model", "and", "action", "." ]
python
train
sensu-plugins/sensu-plugin-python
sensu_plugin/plugin.py
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/plugin.py#L51-L55
def output(self, args): ''' Print the output message. ''' print("SensuPlugin: {}".format(' '.join(str(a) for a in args)))
[ "def", "output", "(", "self", ",", "args", ")", ":", "print", "(", "\"SensuPlugin: {}\"", ".", "format", "(", "' '", ".", "join", "(", "str", "(", "a", ")", "for", "a", "in", "args", ")", ")", ")" ]
Print the output message.
[ "Print", "the", "output", "message", "." ]
python
train
timothyb0912/pylogit
pylogit/bootstrap_sampler.py
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_sampler.py#L245-L273
def check_column_existence(col_name, df, presence=True): """ Checks whether or not `col_name` is in `df` and raises a helpful error msg if the desired condition is not met. Parameters ---------- col_name : str. Should represent a column whose presence in `df` is to be checked. df : pandas DataFrame. The dataframe that will be checked for the presence of `col_name`. presence : bool, optional. If True, then this function checks for the PRESENCE of `col_name` from `df`. If False, then this function checks for the ABSENCE of `col_name` in `df`. Default == True. Returns ------- None. """ if presence: if col_name not in df.columns: msg = "Ensure that `{}` is in `df.columns`." raise ValueError(msg.format(col_name)) else: if col_name in df.columns: msg = "Ensure that `{}` is not in `df.columns`." raise ValueError(msg.format(col_name)) return None
[ "def", "check_column_existence", "(", "col_name", ",", "df", ",", "presence", "=", "True", ")", ":", "if", "presence", ":", "if", "col_name", "not", "in", "df", ".", "columns", ":", "msg", "=", "\"Ensure that `{}` is in `df.columns`.\"", "raise", "ValueError", ...
Checks whether or not `col_name` is in `df` and raises a helpful error msg if the desired condition is not met. Parameters ---------- col_name : str. Should represent a column whose presence in `df` is to be checked. df : pandas DataFrame. The dataframe that will be checked for the presence of `col_name`. presence : bool, optional. If True, then this function checks for the PRESENCE of `col_name` from `df`. If False, then this function checks for the ABSENCE of `col_name` in `df`. Default == True. Returns ------- None.
[ "Checks", "whether", "or", "not", "col_name", "is", "in", "df", "and", "raises", "a", "helpful", "error", "msg", "if", "the", "desired", "condition", "is", "not", "met", "." ]
python
train
benmontet/f3
f3/photometry.py
https://github.com/benmontet/f3/blob/b2e1dc250e4e3e884a54c501cd35cf02d5b8719e/f3/photometry.py#L540-L583
def define_spotsignal(self): """ Identify the "expected" flux value at the time of each observation based on the Kepler long-cadence data, to ensure variations observed are not the effects of a single large starspot. Only works if the target star was targeted for long or short cadence observations during the primary mission. """ client = kplr.API() star = client.star(self.kic) lcs = star.get_light_curves(short_cadence=False) time, flux, ferr, qual = [], [], [], [] for lc in lcs: with lc.open() as f: hdu_data = f[1].data time.append(hdu_data["time"]) flux.append(hdu_data["pdcsap_flux"]) ferr.append(hdu_data["pdcsap_flux_err"]) qual.append(hdu_data["sap_quality"]) tout = np.array([]) fout = np.array([]) eout = np.array([]) for i in range(len(flux)): t = time[i][qual[i] == 0] f = flux[i][qual[i] == 0] e = ferr[i][qual[i] == 0] t = t[np.isfinite(f)] e = e[np.isfinite(f)] f = f[np.isfinite(f)] e /= np.median(f) f /= np.median(f) tout = np.append(tout, t[50:]+54833) fout = np.append(fout, f[50:]) eout = np.append(eout, e[50:]) self.spot_signal = np.zeros(52) for i in range(len(self.times)): if self.times[i] < 55000: self.spot_signal[i] = 1.0 else: self.spot_signal[i] = fout[np.abs(self.times[i] - tout) == np.min(np.abs(self.times[i] - tout))]
[ "def", "define_spotsignal", "(", "self", ")", ":", "client", "=", "kplr", ".", "API", "(", ")", "star", "=", "client", ".", "star", "(", "self", ".", "kic", ")", "lcs", "=", "star", ".", "get_light_curves", "(", "short_cadence", "=", "False", ")", "t...
Identify the "expected" flux value at the time of each observation based on the Kepler long-cadence data, to ensure variations observed are not the effects of a single large starspot. Only works if the target star was targeted for long or short cadence observations during the primary mission.
[ "Identify", "the", "expected", "flux", "value", "at", "the", "time", "of", "each", "observation", "based", "on", "the", "Kepler", "long", "-", "cadence", "data", "to", "ensure", "variations", "observed", "are", "not", "the", "effects", "of", "a", "single", ...
python
valid
metagriffin/fso
fso/filesystemoverlay.py
https://github.com/metagriffin/fso/blob/c37701fbfdfde359a2044eb9420abe569a7b35e4/fso/filesystemoverlay.py#L445-L462
def fso_makedirs(self, path, mode=None): 'overlays os.makedirs()' path = self.abs(path) cur = '/' segments = path.split('/') for idx, seg in enumerate(segments): cur = os.path.join(cur, seg) try: st = self.fso_stat(cur) except OSError: st = None if st is None: self.fso_mkdir(cur) continue if idx + 1 == len(segments): raise OSError(17, 'File exists', path) if not stat.S_ISDIR(st.st_mode): raise OSError(20, 'Not a directory', path)
[ "def", "fso_makedirs", "(", "self", ",", "path", ",", "mode", "=", "None", ")", ":", "path", "=", "self", ".", "abs", "(", "path", ")", "cur", "=", "'/'", "segments", "=", "path", ".", "split", "(", "'/'", ")", "for", "idx", ",", "seg", "in", "...
overlays os.makedirs()
[ "overlays", "os", ".", "makedirs", "()" ]
python
valid
lingfeiwang/findr-python
findr/pij.py
https://github.com/lingfeiwang/findr-python/blob/417f163e658fee6ef311571f7048f96069a0cf1f/findr/pij.py#L456-L493
def cassists(self,dc,dt,dt2,nodiag=False,memlimit=-1): """Calculates probability of gene i regulating gene j with continuous data assisted method, with multiple tests, by converting log likelihoods into probabilities per A for all B. Probabilities are converted from likelihood ratios separately for each A. This gives better predictions when the number of secondary targets (dt2) is large. (Check program warnings.) dc: numpy.ndarray(nt,ns,dtype=ftype(='f4' by default)) Continuous anchor data. Entry dc[i,j] is anchor i's value for sample j. Anchor i is used to infer the probability of gene i -> any other gene. dt: numpy.ndarray(nt,ns,dtype=ftype(='=f4' by default)) Gene expression data for A Entry dt[i,j] is gene i's expression level for sample j. dt2:numpy.ndarray(nt2,ns,dtype=ftype(='=f4' by default)) Gene expression data for B. dt2 has the same format as dt, and can be identical with, different from, or a superset of dt. When dt2 is a superset of (or identical with) dt, dt2 must be arranged to be identical with dt at its upper submatrix, i.e. dt2[:nt,:]=dt, and set parameter nodiag = 1. nodiag: skip diagonal regulations, i.e. regulation A->B for A=B. This should be set to True when A is a subset of B and aligned correspondingly. memlimit: The approximate memory usage limit in bytes for the library. For datasets require a larger memory, calculation will be split into smaller chunks. If the memory limit is smaller than minimum required, calculation can fail with an error message. memlimit=0 defaults to unlimited memory usage. Return: dictionary with following keys: ret:0 iff execution succeeded. p1: numpy.ndarray(nt,dtype=ftype(='=f4' by default)). Probability for test 1. Test 1 calculates E(A)->A v.s. E(A) A. The earlier one is preferred. For nodiag=False, because the function expects significant anchors, p1 always return 1. For nodiag=True, uses diagonal elements of p2. p2: numpy.ndarray((nt,nt2),dtype=ftype(='=f4' by default)). Probability for test 2. Test 2 calculates E(A)->A--B with E(A)->B v.s. E(A)->A<-B. The earlier one is preferred. p3: numpy.ndarray((nt,nt2),dtype=ftype(='=f4' by default)). Probability for test 3. Test 3 calculates E(A)->A--B with E(A)->B v.s. E(A)->A->B. The latter one is preferred. p4: numpy.ndarray((nt,nt2),dtype=ftype(='=f4' by default)). Probability for test 4. Test 4 calculates E(A)->A--B with E(A)->B v.s. E(A)->A B. The earlier one is preferred. p5: numpy.ndarray((nt,nt2),dtype=ftype(='=f4' by default)). Probability for test 5. Test 5 calculates E(A)->A--B with E(A)->B v.s. B<-E(A)->A. The earlier one is preferred. For more information on tests, see paper. ftype can be found in auto.py. Example: see findr.examples.geuvadis4 (similar format) """ return _cassists_any(self,dc,dt,dt2,"pijs_cassist",nodiag=nodiag,memlimit=memlimit)
[ "def", "cassists", "(", "self", ",", "dc", ",", "dt", ",", "dt2", ",", "nodiag", "=", "False", ",", "memlimit", "=", "-", "1", ")", ":", "return", "_cassists_any", "(", "self", ",", "dc", ",", "dt", ",", "dt2", ",", "\"pijs_cassist\"", ",", "nodiag...
Calculates probability of gene i regulating gene j with continuous data assisted method, with multiple tests, by converting log likelihoods into probabilities per A for all B. Probabilities are converted from likelihood ratios separately for each A. This gives better predictions when the number of secondary targets (dt2) is large. (Check program warnings.) dc: numpy.ndarray(nt,ns,dtype=ftype(='f4' by default)) Continuous anchor data. Entry dc[i,j] is anchor i's value for sample j. Anchor i is used to infer the probability of gene i -> any other gene. dt: numpy.ndarray(nt,ns,dtype=ftype(='=f4' by default)) Gene expression data for A Entry dt[i,j] is gene i's expression level for sample j. dt2:numpy.ndarray(nt2,ns,dtype=ftype(='=f4' by default)) Gene expression data for B. dt2 has the same format as dt, and can be identical with, different from, or a superset of dt. When dt2 is a superset of (or identical with) dt, dt2 must be arranged to be identical with dt at its upper submatrix, i.e. dt2[:nt,:]=dt, and set parameter nodiag = 1. nodiag: skip diagonal regulations, i.e. regulation A->B for A=B. This should be set to True when A is a subset of B and aligned correspondingly. memlimit: The approximate memory usage limit in bytes for the library. For datasets require a larger memory, calculation will be split into smaller chunks. If the memory limit is smaller than minimum required, calculation can fail with an error message. memlimit=0 defaults to unlimited memory usage. Return: dictionary with following keys: ret:0 iff execution succeeded. p1: numpy.ndarray(nt,dtype=ftype(='=f4' by default)). Probability for test 1. Test 1 calculates E(A)->A v.s. E(A) A. The earlier one is preferred. For nodiag=False, because the function expects significant anchors, p1 always return 1. For nodiag=True, uses diagonal elements of p2. p2: numpy.ndarray((nt,nt2),dtype=ftype(='=f4' by default)). Probability for test 2. Test 2 calculates E(A)->A--B with E(A)->B v.s. E(A)->A<-B. The earlier one is preferred. p3: numpy.ndarray((nt,nt2),dtype=ftype(='=f4' by default)). Probability for test 3. Test 3 calculates E(A)->A--B with E(A)->B v.s. E(A)->A->B. The latter one is preferred. p4: numpy.ndarray((nt,nt2),dtype=ftype(='=f4' by default)). Probability for test 4. Test 4 calculates E(A)->A--B with E(A)->B v.s. E(A)->A B. The earlier one is preferred. p5: numpy.ndarray((nt,nt2),dtype=ftype(='=f4' by default)). Probability for test 5. Test 5 calculates E(A)->A--B with E(A)->B v.s. B<-E(A)->A. The earlier one is preferred. For more information on tests, see paper. ftype can be found in auto.py. Example: see findr.examples.geuvadis4 (similar format)
[ "Calculates", "probability", "of", "gene", "i", "regulating", "gene", "j", "with", "continuous", "data", "assisted", "method", "with", "multiple", "tests", "by", "converting", "log", "likelihoods", "into", "probabilities", "per", "A", "for", "all", "B", ".", "...
python
train
firecat53/urlscan
urlscan/urlscan.py
https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlscan.py#L446-L460
def decode_bytes(byt, enc='utf-8'): """Given a string or bytes input, return a string. Args: bytes - bytes or string enc - encoding to use for decoding the byte string. """ try: strg = byt.decode(enc) except UnicodeDecodeError as err: strg = "Unable to decode message:\n{}\n{}".format(str(byt), err) except (AttributeError, UnicodeEncodeError): # If byt is already a string, just return it return byt return strg
[ "def", "decode_bytes", "(", "byt", ",", "enc", "=", "'utf-8'", ")", ":", "try", ":", "strg", "=", "byt", ".", "decode", "(", "enc", ")", "except", "UnicodeDecodeError", "as", "err", ":", "strg", "=", "\"Unable to decode message:\\n{}\\n{}\"", ".", "format", ...
Given a string or bytes input, return a string. Args: bytes - bytes or string enc - encoding to use for decoding the byte string.
[ "Given", "a", "string", "or", "bytes", "input", "return", "a", "string", "." ]
python
train
fermiPy/fermipy
fermipy/jobs/job_archive.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L123-L140
def get_status(self): """Return an overall status based on the number of jobs in various states. """ if self.n_total == 0: return JobStatus.no_job elif self.n_done == self.n_total: return JobStatus.done elif self.n_failed > 0: # If more that a quater of the jobs fail, fail the whole thing if self.n_failed > self.n_total / 4.: return JobStatus.failed return JobStatus.partial_failed elif self.n_running > 0: return JobStatus.running elif self.n_pending > 0: return JobStatus.pending return JobStatus.ready
[ "def", "get_status", "(", "self", ")", ":", "if", "self", ".", "n_total", "==", "0", ":", "return", "JobStatus", ".", "no_job", "elif", "self", ".", "n_done", "==", "self", ".", "n_total", ":", "return", "JobStatus", ".", "done", "elif", "self", ".", ...
Return an overall status based on the number of jobs in various states.
[ "Return", "an", "overall", "status", "based", "on", "the", "number", "of", "jobs", "in", "various", "states", "." ]
python
train
saltstack/salt
salt/key.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L228-L284
def run(self): ''' Run the logic for saltkey ''' self._update_opts() cmd = self.opts['fun'] veri = None ret = None try: if cmd in ('accept', 'reject', 'delete'): ret = self._run_cmd('name_match') if not isinstance(ret, dict): salt.output.display_output(ret, 'key', opts=self.opts) return ret ret = self._filter_ret(cmd, ret) if not ret: self._print_no_match(cmd, self.opts['match']) return print('The following keys are going to be {0}ed:'.format(cmd.rstrip('e'))) salt.output.display_output(ret, 'key', opts=self.opts) if not self.opts.get('yes', False): try: if cmd.startswith('delete'): veri = input('Proceed? [N/y] ') if not veri: veri = 'n' else: veri = input('Proceed? [n/Y] ') if not veri: veri = 'y' except KeyboardInterrupt: raise SystemExit("\nExiting on CTRL-c") # accept/reject/delete the same keys we're printed to the user self.opts['match_dict'] = ret self.opts.pop('match', None) list_ret = ret if veri is None or veri.lower().startswith('y'): ret = self._run_cmd(cmd) if cmd in ('accept', 'reject', 'delete'): if cmd == 'delete': ret = list_ret for minions in ret.values(): for minion in minions: print('Key for minion {0} {1}ed.'.format(minion, cmd.rstrip('e'))) elif isinstance(ret, dict): salt.output.display_output(ret, 'key', opts=self.opts) else: salt.output.display_output({'return': ret}, 'key', opts=self.opts) except salt.exceptions.SaltException as exc: ret = '{0}'.format(exc) if not self.opts.get('quiet', False): salt.output.display_output(ret, 'nested', self.opts) return ret
[ "def", "run", "(", "self", ")", ":", "self", ".", "_update_opts", "(", ")", "cmd", "=", "self", ".", "opts", "[", "'fun'", "]", "veri", "=", "None", "ret", "=", "None", "try", ":", "if", "cmd", "in", "(", "'accept'", ",", "'reject'", ",", "'delet...
Run the logic for saltkey
[ "Run", "the", "logic", "for", "saltkey" ]
python
train
acutesoftware/AIKIF
aikif/web_app/page_data.py
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/web_app/page_data.py#L28-L39
def show_data_file(fname): """ shows a data file in CSV format - all files live in CORE folder """ txt = '<H2>' + fname + '</H2>' print (fname) #try: txt += web.read_csv_to_html_table(fname, 'Y') # it is ok to use a table for actual table data #except: # txt += '<H2>ERROR - cant read file</H2>' #txt += web.read_csv_to_html_list(fname) # only use this for single column lists txt += '</div>\n' return txt
[ "def", "show_data_file", "(", "fname", ")", ":", "txt", "=", "'<H2>'", "+", "fname", "+", "'</H2>'", "print", "(", "fname", ")", "#try:", "txt", "+=", "web", ".", "read_csv_to_html_table", "(", "fname", ",", "'Y'", ")", "# it is ok to use a table for actual ta...
shows a data file in CSV format - all files live in CORE folder
[ "shows", "a", "data", "file", "in", "CSV", "format", "-", "all", "files", "live", "in", "CORE", "folder" ]
python
train
benhoff/pluginmanager
pluginmanager/plugin_interface.py
https://github.com/benhoff/pluginmanager/blob/a8a184f9ebfbb521703492cb88c1dbda4cd04c06/pluginmanager/plugin_interface.py#L153-L165
def add_plugin_directories(self, paths, except_blacklisted=True): """ Adds `directories` to the set of plugin directories. `directories` may be either a single object or a iterable. `directories` can be relative paths, but will be converted into absolute paths based on the current working directory. if `except_blacklisted` is `True` all `directories` in that are blacklisted will be removed """ self.directory_manager.add_directories(paths, except_blacklisted)
[ "def", "add_plugin_directories", "(", "self", ",", "paths", ",", "except_blacklisted", "=", "True", ")", ":", "self", ".", "directory_manager", ".", "add_directories", "(", "paths", ",", "except_blacklisted", ")" ]
Adds `directories` to the set of plugin directories. `directories` may be either a single object or a iterable. `directories` can be relative paths, but will be converted into absolute paths based on the current working directory. if `except_blacklisted` is `True` all `directories` in that are blacklisted will be removed
[ "Adds", "directories", "to", "the", "set", "of", "plugin", "directories", "." ]
python
train
markperdue/pyvesync
src/pyvesync/helpers.py
https://github.com/markperdue/pyvesync/blob/7552dd1a6dd5ebc452acf78e33fd8f6e721e8cfc/src/pyvesync/helpers.py#L222-L256
def resolve_updates(orig_list, updated_list): """Merges changes from one list of devices against another""" if updated_list is not None and updated_list: if orig_list is None: orig_list = updated_list else: # Add new devices not in list but found in the update for new_device in updated_list: was_found = False for device in orig_list: if new_device.cid == device.cid: was_found = True break if not was_found: orig_list.append(new_device) # Remove old devices in the list not found in the update for device in orig_list: should_remove = True for new_device in updated_list: if device.cid == new_device.cid: should_remove = False break if should_remove: orig_list.remove(device) # Call update on each device in the list [device.update() for device in orig_list] return orig_list
[ "def", "resolve_updates", "(", "orig_list", ",", "updated_list", ")", ":", "if", "updated_list", "is", "not", "None", "and", "updated_list", ":", "if", "orig_list", "is", "None", ":", "orig_list", "=", "updated_list", "else", ":", "# Add new devices not in list bu...
Merges changes from one list of devices against another
[ "Merges", "changes", "from", "one", "list", "of", "devices", "against", "another" ]
python
train
OpenHumans/open-humans-api
ohapi/projects.py
https://github.com/OpenHumans/open-humans-api/blob/ca2a28cf5d55cfdae13dd222ba58c25565bdb86e/ohapi/projects.py#L139-L180
def download_all(self, target_dir, source=None, project_data=False, memberlist=None, excludelist=None, max_size=MAX_SIZE_DEFAULT, id_filename=False): """ Download data for all users including shared data files. :param target_dir: This field is the target directory to download data. :param source: This field is the data source. It's default value is None. :param project_data: This field is data related to particular project. It's default value is False. :param memberlist: This field is list of members whose data will be downloaded. It's default value is None. :param excludelist: This field is list of members whose data will be skipped. It's default value is None. :param max_size: This field is the maximum file size. It's default value is 128m. """ members = self.project_data.keys() for member in members: if not (memberlist is None) and member not in memberlist: logging.debug('Skipping {}, not in memberlist'.format(member)) continue if excludelist and member in excludelist: logging.debug('Skipping {}, in excludelist'.format(member)) continue member_dir = os.path.join(target_dir, member) if not os.path.exists(member_dir): os.mkdir(member_dir) if project_data: self.download_member_project_data( member_data=self.project_data[member], target_member_dir=member_dir, max_size=max_size, id_filename=id_filename) else: self.download_member_shared( member_data=self.project_data[member], target_member_dir=member_dir, source=source, max_size=max_size, id_filename=id_filename)
[ "def", "download_all", "(", "self", ",", "target_dir", ",", "source", "=", "None", ",", "project_data", "=", "False", ",", "memberlist", "=", "None", ",", "excludelist", "=", "None", ",", "max_size", "=", "MAX_SIZE_DEFAULT", ",", "id_filename", "=", "False",...
Download data for all users including shared data files. :param target_dir: This field is the target directory to download data. :param source: This field is the data source. It's default value is None. :param project_data: This field is data related to particular project. It's default value is False. :param memberlist: This field is list of members whose data will be downloaded. It's default value is None. :param excludelist: This field is list of members whose data will be skipped. It's default value is None. :param max_size: This field is the maximum file size. It's default value is 128m.
[ "Download", "data", "for", "all", "users", "including", "shared", "data", "files", "." ]
python
train
fulfilio/python-magento
magento/sales.py
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/sales.py#L78-L92
def addcomment(self, order_increment_id, status, comment=None, notify=False): """ Add comment to order or change its state :param order_increment_id: Order ID TODO: Identify possible values for status """ if comment is None: comment = "" return bool(self.call( 'sales_order.addComment', [order_increment_id, status, comment, notify] ) )
[ "def", "addcomment", "(", "self", ",", "order_increment_id", ",", "status", ",", "comment", "=", "None", ",", "notify", "=", "False", ")", ":", "if", "comment", "is", "None", ":", "comment", "=", "\"\"", "return", "bool", "(", "self", ".", "call", "(",...
Add comment to order or change its state :param order_increment_id: Order ID TODO: Identify possible values for status
[ "Add", "comment", "to", "order", "or", "change", "its", "state" ]
python
train
AlecAivazis/graphql-over-kafka
nautilus/network/events/actionHandlers/createHandler.py
https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/network/events/actionHandlers/createHandler.py#L12-L83
def create_handler(Model, name=None, **kwds): """ This factory returns an action handler that creates a new instance of the specified model when a create action is recieved, assuming the action follows nautilus convetions. Args: Model (nautilus.BaseModel): The model to create when the action received. Returns: function(action_type, payload): The action handler for this model """ async def action_handler(service, action_type, payload, props, notify=True, **kwds): # if the payload represents a new instance of `Model` if action_type == get_crud_action('create', name or Model): # print('handling create for ' + name or Model) try: # the props of the message message_props = {} # if there was a correlation id in the request if 'correlation_id' in props: # make sure it ends up in the reply message_props['correlation_id'] = props['correlation_id'] # for each required field for requirement in Model.required_fields(): # save the name of the field field_name = requirement.name # ensure the value is in the payload # TODO: check all required fields rather than failing on the first if not field_name in payload and field_name != 'id': # yell loudly raise ValueError( "Required field not found in payload: %s" %field_name ) # create a new model new_model = Model(**payload) # save the new model instance new_model.save() # if we need to tell someone about what happened if notify: # publish the scucess event await service.event_broker.send( payload=ModelSerializer().serialize(new_model), action_type=change_action_status(action_type, success_status()), **message_props ) # if something goes wrong except Exception as err: # if we need to tell someone about what happened if notify: # publish the error as an event await service.event_broker.send( payload=str(err), action_type=change_action_status(action_type, error_status()), **message_props ) # otherwise we aren't supposed to notify else: # raise the exception normally raise err # return the handler return action_handler
[ "def", "create_handler", "(", "Model", ",", "name", "=", "None", ",", "*", "*", "kwds", ")", ":", "async", "def", "action_handler", "(", "service", ",", "action_type", ",", "payload", ",", "props", ",", "notify", "=", "True", ",", "*", "*", "kwds", "...
This factory returns an action handler that creates a new instance of the specified model when a create action is recieved, assuming the action follows nautilus convetions. Args: Model (nautilus.BaseModel): The model to create when the action received. Returns: function(action_type, payload): The action handler for this model
[ "This", "factory", "returns", "an", "action", "handler", "that", "creates", "a", "new", "instance", "of", "the", "specified", "model", "when", "a", "create", "action", "is", "recieved", "assuming", "the", "action", "follows", "nautilus", "convetions", "." ]
python
train
econ-ark/HARK
HARK/ConsumptionSaving/TractableBufferStockModel.py
https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/TractableBufferStockModel.py#L420-L433
def getStates(self): ''' Calculate market resources for all agents this period. Parameters ---------- None Returns ------- None ''' self.bLvlNow = self.Rfree*self.aLvlNow self.mLvlNow = self.bLvlNow + self.eStateNow
[ "def", "getStates", "(", "self", ")", ":", "self", ".", "bLvlNow", "=", "self", ".", "Rfree", "*", "self", ".", "aLvlNow", "self", ".", "mLvlNow", "=", "self", ".", "bLvlNow", "+", "self", ".", "eStateNow" ]
Calculate market resources for all agents this period. Parameters ---------- None Returns ------- None
[ "Calculate", "market", "resources", "for", "all", "agents", "this", "period", "." ]
python
train
sosy-lab/benchexec
benchexec/tablegenerator/__init__.py
https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/tablegenerator/__init__.py#L629-L718
def create_from_xml(sourcefileTag, get_value_from_logfile, listOfColumns, correct_only, log_zip_cache, columns_relevant_for_diff, result_file_or_url): ''' This function collects the values from one run. Only columns that should be part of the table are collected. ''' def read_logfile_lines(log_file): if not log_file: return [] log_file_url = Util.make_url(log_file) url_parts = urllib.parse.urlparse(log_file_url, allow_fragments=False) log_zip_path = os.path.dirname(url_parts.path) + ".zip" log_zip_url = urllib.parse.urlunparse((url_parts.scheme, url_parts.netloc, log_zip_path, url_parts.params, url_parts.query, url_parts.fragment)) path_in_zip = urllib.parse.unquote( os.path.relpath(url_parts.path, os.path.dirname(log_zip_path))) if log_zip_url.startswith("file:///") and not log_zip_path.startswith("/"): # Replace file:/// with file: for relative paths, # otherwise opening fails. log_zip_url = "file:" + log_zip_url[8:] try: with Util.open_url_seekable(log_file_url, 'rt') as logfile: return logfile.readlines() except IOError as unused_e1: try: if log_zip_url not in log_zip_cache: log_zip_cache[log_zip_url] = zipfile.ZipFile( Util.open_url_seekable(log_zip_url, 'rb')) log_zip = log_zip_cache[log_zip_url] try: with io.TextIOWrapper(log_zip.open(path_in_zip)) as logfile: return logfile.readlines() except KeyError: logging.warning("Could not find logfile '%s' in archive '%s'.", log_file, log_zip_url) return [] except IOError as unused_e2: logging.warning("Could not find logfile '%s' nor log archive '%s'.", log_file, log_zip_url) return [] status = Util.get_column_value(sourcefileTag, 'status', '') category = Util.get_column_value(sourcefileTag, 'category', result.CATEGORY_MISSING) score = result.score_for_task( sourcefileTag.get('properties', '').split(), category, status) logfileLines = None values = [] for column in listOfColumns: # for all columns that should be shown value = None # default value if column.title.lower() == 'status': value = status elif not correct_only or category == result.CATEGORY_CORRECT: if not column.pattern or column.href: # collect values from XML value = Util.get_column_value(sourcefileTag, column.title) else: # collect values from logfile if logfileLines is None: # cache content logfileLines = read_logfile_lines(sourcefileTag.get('logfile')) value = get_value_from_logfile(logfileLines, column.pattern) if column.title.lower() == 'score' and value is None and score is not None: # If no score column exists in the xml, take the internally computed score, # if available value = str(score) values.append(value) sourcefiles = sourcefileTag.get('files') if sourcefiles: if sourcefiles.startswith('['): sourcefileList = [s.strip() for s in sourcefiles[1:-1].split(',') if s.strip()] sourcefiles_exist = True if sourcefileList else False else: raise AssertionError('Unknown format for files tag:') else: sourcefiles_exist = False return RunResult(get_task_id(sourcefileTag, result_file_or_url if sourcefiles_exist else None), status, category, score, sourcefileTag.get('logfile'), listOfColumns, values, columns_relevant_for_diff, sourcefiles_exist=sourcefiles_exist)
[ "def", "create_from_xml", "(", "sourcefileTag", ",", "get_value_from_logfile", ",", "listOfColumns", ",", "correct_only", ",", "log_zip_cache", ",", "columns_relevant_for_diff", ",", "result_file_or_url", ")", ":", "def", "read_logfile_lines", "(", "log_file", ")", ":",...
This function collects the values from one run. Only columns that should be part of the table are collected.
[ "This", "function", "collects", "the", "values", "from", "one", "run", ".", "Only", "columns", "that", "should", "be", "part", "of", "the", "table", "are", "collected", "." ]
python
train
spacetelescope/stsci.tools
lib/stsci/tools/validate.py
https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/validate.py#L1110-L1131
def is_int_list(value, min=None, max=None): """ Check that the value is a list of integers. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is an integer. >>> vtor = Validator() >>> vtor.check('int_list', ()) [] >>> vtor.check('int_list', []) [] >>> vtor.check('int_list', (1, 2)) [1, 2] >>> vtor.check('int_list', [1, 2]) [1, 2] >>> vtor.check('int_list', [1, 'a']) # doctest: +SKIP Traceback (most recent call last): VdtTypeError: the value "a" is of the wrong type. """ return [is_integer(mem) for mem in is_list(value, min, max)]
[ "def", "is_int_list", "(", "value", ",", "min", "=", "None", ",", "max", "=", "None", ")", ":", "return", "[", "is_integer", "(", "mem", ")", "for", "mem", "in", "is_list", "(", "value", ",", "min", ",", "max", ")", "]" ]
Check that the value is a list of integers. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is an integer. >>> vtor = Validator() >>> vtor.check('int_list', ()) [] >>> vtor.check('int_list', []) [] >>> vtor.check('int_list', (1, 2)) [1, 2] >>> vtor.check('int_list', [1, 2]) [1, 2] >>> vtor.check('int_list', [1, 'a']) # doctest: +SKIP Traceback (most recent call last): VdtTypeError: the value "a" is of the wrong type.
[ "Check", "that", "the", "value", "is", "a", "list", "of", "integers", "." ]
python
train
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L180-L183
def unregister_transformer(self, transformer): """Unregister a transformer instance.""" if transformer in self._transformers: self._transformers.remove(transformer)
[ "def", "unregister_transformer", "(", "self", ",", "transformer", ")", ":", "if", "transformer", "in", "self", ".", "_transformers", ":", "self", ".", "_transformers", ".", "remove", "(", "transformer", ")" ]
Unregister a transformer instance.
[ "Unregister", "a", "transformer", "instance", "." ]
python
test
proycon/pynlpl
pynlpl/textprocessors.py
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/textprocessors.py#L403-L411
def split_sentences(tokens): """Split sentences (based on tokenised data), returns sentences as a list of lists of tokens, each sentence is a list of tokens""" begin = 0 for i, token in enumerate(tokens): if is_end_of_sentence(tokens, i): yield tokens[begin:i+1] begin = i+1 if begin <= len(tokens)-1: yield tokens[begin:]
[ "def", "split_sentences", "(", "tokens", ")", ":", "begin", "=", "0", "for", "i", ",", "token", "in", "enumerate", "(", "tokens", ")", ":", "if", "is_end_of_sentence", "(", "tokens", ",", "i", ")", ":", "yield", "tokens", "[", "begin", ":", "i", "+",...
Split sentences (based on tokenised data), returns sentences as a list of lists of tokens, each sentence is a list of tokens
[ "Split", "sentences", "(", "based", "on", "tokenised", "data", ")", "returns", "sentences", "as", "a", "list", "of", "lists", "of", "tokens", "each", "sentence", "is", "a", "list", "of", "tokens" ]
python
train
ToFuProject/tofu
tofu/data/_core.py
https://github.com/ToFuProject/tofu/blob/39d6b2e7ced9e13666572dfd37e19403f1d6ff8d/tofu/data/_core.py#L1582-L1605
def plot(self, key=None, cmap=None, ms=4, vmin=None, vmax=None, vmin_map=None, vmax_map=None, cmap_map=None, normt_map=False, ntMax=None, nchMax=None, nlbdMax=3, lls=None, lct=None, lcch=None, lclbd=None, cbck=None, inct=[1,10], incX=[1,5], inclbd=[1,10], fmt_t='06.3f', fmt_X='01.0f', invert=True, Lplot='In', dmarker=None, Bck=True, fs=None, dmargin=None, wintit=None, tit=None, fontsize=None, labelpad=None, draw=True, connect=True): """ Plot the data content in a generic interactive figure """ kh = _plot.Data_plot(self, key=key, indref=0, cmap=cmap, ms=ms, vmin=vmin, vmax=vmax, vmin_map=vmin_map, vmax_map=vmax_map, cmap_map=cmap_map, normt_map=normt_map, ntMax=ntMax, nchMax=nchMax, nlbdMax=nlbdMax, lls=lls, lct=lct, lcch=lcch, lclbd=lclbd, cbck=cbck, inct=inct, incX=incX, inclbd=inclbd, fmt_t=fmt_t, fmt_X=fmt_X, Lplot=Lplot, invert=invert, dmarker=dmarker, Bck=Bck, fs=fs, dmargin=dmargin, wintit=wintit, tit=tit, fontsize=fontsize, labelpad=labelpad, draw=draw, connect=connect) return kh
[ "def", "plot", "(", "self", ",", "key", "=", "None", ",", "cmap", "=", "None", ",", "ms", "=", "4", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ",", "vmin_map", "=", "None", ",", "vmax_map", "=", "None", ",", "cmap_map", "=", "None", ",...
Plot the data content in a generic interactive figure
[ "Plot", "the", "data", "content", "in", "a", "generic", "interactive", "figure" ]
python
train
oisinmulvihill/stomper
lib/stomper/utils.py
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/utils.py#L11-L22
def log_init(level): """Set up a logger that catches all channels and logs it to stdout. This is used to set up logging when testing. """ log = logging.getLogger() hdlr = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) log.addHandler(hdlr) log.setLevel(level)
[ "def", "log_init", "(", "level", ")", ":", "log", "=", "logging", ".", "getLogger", "(", ")", "hdlr", "=", "logging", ".", "StreamHandler", "(", ")", "formatter", "=", "logging", ".", "Formatter", "(", "'%(asctime)s %(name)s %(levelname)s %(message)s'", ")", "...
Set up a logger that catches all channels and logs it to stdout. This is used to set up logging when testing.
[ "Set", "up", "a", "logger", "that", "catches", "all", "channels", "and", "logs", "it", "to", "stdout", ".", "This", "is", "used", "to", "set", "up", "logging", "when", "testing", "." ]
python
train
inveniosoftware/invenio-pidstore
invenio_pidstore/providers/datacite.py
https://github.com/inveniosoftware/invenio-pidstore/blob/8bf35f4e62d5dcaf1a2cfe5803245ba5220a9b78/invenio_pidstore/providers/datacite.py#L35-L49
def create(cls, pid_value, **kwargs): """Create a new record identifier. For more information about parameters, see :meth:`invenio_pidstore.providers.BaseProvider.create`. :param pid_value: Persistent identifier value. :params **kwargs: See :meth:`invenio_pidstore.providers.base.BaseProvider.create` extra parameters. :returns: A :class:`invenio_pidstore.providers.DataCiteProvider` instance. """ return super(DataCiteProvider, cls).create( pid_value=pid_value, **kwargs)
[ "def", "create", "(", "cls", ",", "pid_value", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "DataCiteProvider", ",", "cls", ")", ".", "create", "(", "pid_value", "=", "pid_value", ",", "*", "*", "kwargs", ")" ]
Create a new record identifier. For more information about parameters, see :meth:`invenio_pidstore.providers.BaseProvider.create`. :param pid_value: Persistent identifier value. :params **kwargs: See :meth:`invenio_pidstore.providers.base.BaseProvider.create` extra parameters. :returns: A :class:`invenio_pidstore.providers.DataCiteProvider` instance.
[ "Create", "a", "new", "record", "identifier", "." ]
python
train
teaearlgraycold/puni
puni/base.py
https://github.com/teaearlgraycold/puni/blob/f6d0bfde99942b29a6f91273e48abcd2d7a94c93/puni/base.py#L87-L96
def full_url(self): """Return the full reddit URL associated with the usernote. Arguments: subreddit: the subreddit name for the note (PRAW Subreddit object) """ if self.link == '': return None else: return Note._expand_url(self.link, self.subreddit)
[ "def", "full_url", "(", "self", ")", ":", "if", "self", ".", "link", "==", "''", ":", "return", "None", "else", ":", "return", "Note", ".", "_expand_url", "(", "self", ".", "link", ",", "self", ".", "subreddit", ")" ]
Return the full reddit URL associated with the usernote. Arguments: subreddit: the subreddit name for the note (PRAW Subreddit object)
[ "Return", "the", "full", "reddit", "URL", "associated", "with", "the", "usernote", "." ]
python
train
ymoch/apyori
apyori.py
https://github.com/ymoch/apyori/blob/8cc20a19d01b18b83e18e54aabb416c8dedabfde/apyori.py#L376-L397
def dump_as_json(record, output_file): """ Dump an relation record as a json value. Arguments: record -- A RelationRecord instance to dump. output_file -- A file to output. """ def default_func(value): """ Default conversion for JSON value. """ if isinstance(value, frozenset): return sorted(value) raise TypeError(repr(value) + " is not JSON serializable") converted_record = record._replace( ordered_statistics=[x._asdict() for x in record.ordered_statistics]) json.dump( converted_record._asdict(), output_file, default=default_func, ensure_ascii=False) output_file.write(os.linesep)
[ "def", "dump_as_json", "(", "record", ",", "output_file", ")", ":", "def", "default_func", "(", "value", ")", ":", "\"\"\"\n Default conversion for JSON value.\n \"\"\"", "if", "isinstance", "(", "value", ",", "frozenset", ")", ":", "return", "sorted", ...
Dump an relation record as a json value. Arguments: record -- A RelationRecord instance to dump. output_file -- A file to output.
[ "Dump", "an", "relation", "record", "as", "a", "json", "value", "." ]
python
train
AndrewAnnex/SpiceyPy
spiceypy/spiceypy.py
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1649-L1669
def cylrec(r, lon, z): """ Convert from cylindrical to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cylrec_c.html :param r: Distance of a point from z axis. :type r: float :param lon: Angle (radians) of a point from xZ plane. :type lon: float :param z: Height of a point above xY plane. :type z: float :return: Rectangular coordinates of the point. :rtype: 3-Element Array of floats """ r = ctypes.c_double(r) lon = ctypes.c_double(lon) z = ctypes.c_double(z) rectan = stypes.emptyDoubleVector(3) libspice.cylrec_c(r, lon, z, rectan) return stypes.cVectorToPython(rectan)
[ "def", "cylrec", "(", "r", ",", "lon", ",", "z", ")", ":", "r", "=", "ctypes", ".", "c_double", "(", "r", ")", "lon", "=", "ctypes", ".", "c_double", "(", "lon", ")", "z", "=", "ctypes", ".", "c_double", "(", "z", ")", "rectan", "=", "stypes", ...
Convert from cylindrical to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cylrec_c.html :param r: Distance of a point from z axis. :type r: float :param lon: Angle (radians) of a point from xZ plane. :type lon: float :param z: Height of a point above xY plane. :type z: float :return: Rectangular coordinates of the point. :rtype: 3-Element Array of floats
[ "Convert", "from", "cylindrical", "to", "rectangular", "coordinates", "." ]
python
train
poppy-project/pypot
pypot/vrep/remoteApiBindings/vrep.py
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/remoteApiBindings/vrep.py#L208-L213
def simxJointGetForce(clientID, jointHandle, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' force = ct.c_float() return c_GetJointForce(clientID, jointHandle, ct.byref(force), operationMode), force.value
[ "def", "simxJointGetForce", "(", "clientID", ",", "jointHandle", ",", "operationMode", ")", ":", "force", "=", "ct", ".", "c_float", "(", ")", "return", "c_GetJointForce", "(", "clientID", ",", "jointHandle", ",", "ct", ".", "byref", "(", "force", ")", ","...
Please have a look at the function description/documentation in the V-REP user manual
[ "Please", "have", "a", "look", "at", "the", "function", "description", "/", "documentation", "in", "the", "V", "-", "REP", "user", "manual" ]
python
train
mental32/spotify.py
spotify/utils.py
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/utils.py#L49-L64
def assert_hasattr(attr: str, msg: str, tp: BaseException = SpotifyException) -> Callable: """decorator to assert an object has an attribute when run.""" def decorator(func: Callable) -> Callable: @functools.wraps(func) def decorated(self, *args, **kwargs): if not hasattr(self, attr): raise tp(msg) return func(self, *args, **kwargs) if inspect.iscoroutinefunction(func): @functools.wraps(func) async def decorated(*args, **kwargs): return await decorated(*args, **kwargs) return decorated return decorator
[ "def", "assert_hasattr", "(", "attr", ":", "str", ",", "msg", ":", "str", ",", "tp", ":", "BaseException", "=", "SpotifyException", ")", "->", "Callable", ":", "def", "decorator", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "@", "functools"...
decorator to assert an object has an attribute when run.
[ "decorator", "to", "assert", "an", "object", "has", "an", "attribute", "when", "run", "." ]
python
test
calocan/rescape-python-helpers
rescape_python_helpers/functional/ramda.py
https://github.com/calocan/rescape-python-helpers/blob/91a1724f062ee40a25aa60fc96b2d7acadd99618/rescape_python_helpers/functional/ramda.py#L564-L574
def merge_all(dcts): """ Shallow merge all the dcts :param dcts: :return: """ return reduce( lambda accum, dct: merge(accum, dct), dict(), dcts )
[ "def", "merge_all", "(", "dcts", ")", ":", "return", "reduce", "(", "lambda", "accum", ",", "dct", ":", "merge", "(", "accum", ",", "dct", ")", ",", "dict", "(", ")", ",", "dcts", ")" ]
Shallow merge all the dcts :param dcts: :return:
[ "Shallow", "merge", "all", "the", "dcts", ":", "param", "dcts", ":", ":", "return", ":" ]
python
train
doctorzeb8/django-era
era/utils/functools.py
https://github.com/doctorzeb8/django-era/blob/6fd433ef6081c5be295df22bcea70dc2642baaa4/era/utils/functools.py#L23-L43
def unidec(fnx): ''' @unidec def render(view, request, flag=True): pass @render def first_view(request): pass @render(flag=False) def second_view(request): pass ''' return lambda *ax, **kx: ( wraps(ax[0])(lambda *ay, **ky: fnx(ax[0], *ay, **ky)) \ if len(ax) == 1 and not kx and callable(ax[0]) else \ lambda fny: wraps(fny)(lambda *ay, **ky: \ fnx(fny, *ay, **dict(kx, **ky)) if not ax else throw( TypeError('wrapper get *args'))))
[ "def", "unidec", "(", "fnx", ")", ":", "return", "lambda", "*", "ax", ",", "*", "*", "kx", ":", "(", "wraps", "(", "ax", "[", "0", "]", ")", "(", "lambda", "*", "ay", ",", "*", "*", "ky", ":", "fnx", "(", "ax", "[", "0", "]", ",", "*", ...
@unidec def render(view, request, flag=True): pass @render def first_view(request): pass @render(flag=False) def second_view(request): pass
[ "@unidec", "def", "render", "(", "view", "request", "flag", "=", "True", ")", ":", "pass" ]
python
train
openstax/cnx-archive
cnxarchive/views/robots.py
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/robots.py#L14-L24
def robots(request): """Return a simple "don't index me" robots.txt file.""" resp = request.response resp.status = '200 OK' resp.content_type = 'text/plain' resp.body = """ User-Agent: * Disallow: / """ return resp
[ "def", "robots", "(", "request", ")", ":", "resp", "=", "request", ".", "response", "resp", ".", "status", "=", "'200 OK'", "resp", ".", "content_type", "=", "'text/plain'", "resp", ".", "body", "=", "\"\"\"\nUser-Agent: *\nDisallow: /\n\"\"\"", "return", "resp"...
Return a simple "don't index me" robots.txt file.
[ "Return", "a", "simple", "don", "t", "index", "me", "robots", ".", "txt", "file", "." ]
python
train
iotile/typedargs
typedargs/metadata.py
https://github.com/iotile/typedargs/blob/0a5091a664b9b4d836e091e9ba583e944f438fd8/typedargs/metadata.py#L131-L139
def typed_returnvalue(self, type_name, formatter=None): """Add type information to the return value of this function. Args: type_name (str): The name of the type of the return value. formatter (str): An optional name of a formatting function specified for the type given in type_name. """ self.return_info = ReturnInfo(type_name, formatter, True, None)
[ "def", "typed_returnvalue", "(", "self", ",", "type_name", ",", "formatter", "=", "None", ")", ":", "self", ".", "return_info", "=", "ReturnInfo", "(", "type_name", ",", "formatter", ",", "True", ",", "None", ")" ]
Add type information to the return value of this function. Args: type_name (str): The name of the type of the return value. formatter (str): An optional name of a formatting function specified for the type given in type_name.
[ "Add", "type", "information", "to", "the", "return", "value", "of", "this", "function", "." ]
python
test
sethmlarson/virtualbox-python
virtualbox/library.py
https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L13243-L13287
def set_auto_discard_for_device(self, name, controller_port, device, discard): """Sets a flag in the device information which indicates that the medium supports discarding unused blocks (called trimming for SATA or unmap for SCSI devices) .This may or may not be supported by a particular drive, and is silently ignored in the latter case. At the moment only hard disks (which is a misnomer in this context) accept this setting. Changing the setting while the VM is running is forbidden. The device must already exist; see :py:func:`IMachine.attach_device` for how to attach a new device. The @a controllerPort and @a device parameters specify the device slot and have have the same meaning as with :py:func:`IMachine.attach_device` . in name of type str Name of the storage controller. in controller_port of type int Storage controller port. in device of type int Device slot in the given port. in discard of type bool New value for the discard device flag. raises :class:`OleErrorInvalidarg` SATA device, SATA port, SCSI port out of range. raises :class:`VBoxErrorInvalidObjectState` Attempt to modify an unregistered virtual machine. raises :class:`VBoxErrorInvalidVmState` Invalid machine state. """ if not isinstance(name, basestring): raise TypeError("name can only be an instance of type basestring") if not isinstance(controller_port, baseinteger): raise TypeError("controller_port can only be an instance of type baseinteger") if not isinstance(device, baseinteger): raise TypeError("device can only be an instance of type baseinteger") if not isinstance(discard, bool): raise TypeError("discard can only be an instance of type bool") self._call("setAutoDiscardForDevice", in_p=[name, controller_port, device, discard])
[ "def", "set_auto_discard_for_device", "(", "self", ",", "name", ",", "controller_port", ",", "device", ",", "discard", ")", ":", "if", "not", "isinstance", "(", "name", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"name can only be an instance of type...
Sets a flag in the device information which indicates that the medium supports discarding unused blocks (called trimming for SATA or unmap for SCSI devices) .This may or may not be supported by a particular drive, and is silently ignored in the latter case. At the moment only hard disks (which is a misnomer in this context) accept this setting. Changing the setting while the VM is running is forbidden. The device must already exist; see :py:func:`IMachine.attach_device` for how to attach a new device. The @a controllerPort and @a device parameters specify the device slot and have have the same meaning as with :py:func:`IMachine.attach_device` . in name of type str Name of the storage controller. in controller_port of type int Storage controller port. in device of type int Device slot in the given port. in discard of type bool New value for the discard device flag. raises :class:`OleErrorInvalidarg` SATA device, SATA port, SCSI port out of range. raises :class:`VBoxErrorInvalidObjectState` Attempt to modify an unregistered virtual machine. raises :class:`VBoxErrorInvalidVmState` Invalid machine state.
[ "Sets", "a", "flag", "in", "the", "device", "information", "which", "indicates", "that", "the", "medium", "supports", "discarding", "unused", "blocks", "(", "called", "trimming", "for", "SATA", "or", "unmap", "for", "SCSI", "devices", ")", ".", "This", "may"...
python
train
palantir/typedjsonrpc
typedjsonrpc/server.py
https://github.com/palantir/typedjsonrpc/blob/274218fcd236ff9643506caa629029c9ba25a0fb/typedjsonrpc/server.py#L129-L139
def _try_trigger_before_first_request_funcs(self): # pylint: disable=C0103 """Runs each function from ``self.before_first_request_funcs`` once and only once.""" if self._after_first_request_handled: return else: with self._before_first_request_lock: if self._after_first_request_handled: return for func in self._before_first_request_funcs: func() self._after_first_request_handled = True
[ "def", "_try_trigger_before_first_request_funcs", "(", "self", ")", ":", "# pylint: disable=C0103", "if", "self", ".", "_after_first_request_handled", ":", "return", "else", ":", "with", "self", ".", "_before_first_request_lock", ":", "if", "self", ".", "_after_first_re...
Runs each function from ``self.before_first_request_funcs`` once and only once.
[ "Runs", "each", "function", "from", "self", ".", "before_first_request_funcs", "once", "and", "only", "once", "." ]
python
train
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/extensions/storemagic.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/extensions/storemagic.py#L228-L234
def load_ipython_extension(ip): """Load the extension in IPython.""" global _loaded if not _loaded: plugin = StoreMagic(shell=ip, config=ip.config) ip.plugin_manager.register_plugin('storemagic', plugin) _loaded = True
[ "def", "load_ipython_extension", "(", "ip", ")", ":", "global", "_loaded", "if", "not", "_loaded", ":", "plugin", "=", "StoreMagic", "(", "shell", "=", "ip", ",", "config", "=", "ip", ".", "config", ")", "ip", ".", "plugin_manager", ".", "register_plugin",...
Load the extension in IPython.
[ "Load", "the", "extension", "in", "IPython", "." ]
python
test
rameshg87/pyremotevbox
pyremotevbox/ZSI/generate/wsdl2dispatch.py
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/wsdl2dispatch.py#L330-L344
def createMethodBody(msgInName, msgOutName, **kw): '''return a tuple of strings containing the body of a method. msgInName -- None or a str msgOutName -- None or a str ''' body = [] if msgInName is not None: body.append('request = ps.Parse(%s.typecode)' %msgInName) if msgOutName is not None: body.append('return request,%s()' %msgOutName) else: body.append('return request,None') return tuple(body)
[ "def", "createMethodBody", "(", "msgInName", ",", "msgOutName", ",", "*", "*", "kw", ")", ":", "body", "=", "[", "]", "if", "msgInName", "is", "not", "None", ":", "body", ".", "append", "(", "'request = ps.Parse(%s.typecode)'", "%", "msgInName", ")", "if",...
return a tuple of strings containing the body of a method. msgInName -- None or a str msgOutName -- None or a str
[ "return", "a", "tuple", "of", "strings", "containing", "the", "body", "of", "a", "method", ".", "msgInName", "--", "None", "or", "a", "str", "msgOutName", "--", "None", "or", "a", "str" ]
python
train
Parsl/parsl
parsl/providers/googlecloud/googlecloud.py
https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/googlecloud/googlecloud.py#L112-L137
def submit(self, command, blocksize, tasks_per_node, job_name="parsl.auto"): ''' The submit method takes the command string to be executed upon instantiation of a resource most often to start a pilot. Args : - command (str) : The bash command string to be executed. - blocksize (int) : Blocksize to be requested - tasks_per_node (int) : command invocations to be launched per node KWargs: - job_name (str) : Human friendly name to be assigned to the job request Returns: - A job identifier, this could be an integer, string etc Raises: - ExecutionProviderException or its subclasses ''' wrapped_cmd = self.launcher(command, tasks_per_node, 1) instance, name = self.create_instance(command=wrapped_cmd) self.provisioned_blocks += 1 self.resources[name] = {"job_id": name, "status": translate_table[instance['status']]} return name
[ "def", "submit", "(", "self", ",", "command", ",", "blocksize", ",", "tasks_per_node", ",", "job_name", "=", "\"parsl.auto\"", ")", ":", "wrapped_cmd", "=", "self", ".", "launcher", "(", "command", ",", "tasks_per_node", ",", "1", ")", "instance", ",", "na...
The submit method takes the command string to be executed upon instantiation of a resource most often to start a pilot. Args : - command (str) : The bash command string to be executed. - blocksize (int) : Blocksize to be requested - tasks_per_node (int) : command invocations to be launched per node KWargs: - job_name (str) : Human friendly name to be assigned to the job request Returns: - A job identifier, this could be an integer, string etc Raises: - ExecutionProviderException or its subclasses
[ "The", "submit", "method", "takes", "the", "command", "string", "to", "be", "executed", "upon", "instantiation", "of", "a", "resource", "most", "often", "to", "start", "a", "pilot", "." ]
python
valid
softlayer/softlayer-python
SoftLayer/CLI/hardware/create_options.py
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/create_options.py#L13-L56
def cli(env): """Server order options for a given chassis.""" hardware_manager = hardware.HardwareManager(env.client) options = hardware_manager.get_create_options() tables = [] # Datacenters dc_table = formatting.Table(['datacenter', 'value']) dc_table.sortby = 'value' for location in options['locations']: dc_table.add_row([location['name'], location['key']]) tables.append(dc_table) # Presets preset_table = formatting.Table(['size', 'value']) preset_table.sortby = 'value' for size in options['sizes']: preset_table.add_row([size['name'], size['key']]) tables.append(preset_table) # Operating systems os_table = formatting.Table(['operating_system', 'value']) os_table.sortby = 'value' for operating_system in options['operating_systems']: os_table.add_row([operating_system['name'], operating_system['key']]) tables.append(os_table) # Port speed port_speed_table = formatting.Table(['port_speed', 'value']) port_speed_table.sortby = 'value' for speed in options['port_speeds']: port_speed_table.add_row([speed['name'], speed['key']]) tables.append(port_speed_table) # Extras extras_table = formatting.Table(['extras', 'value']) extras_table.sortby = 'value' for extra in options['extras']: extras_table.add_row([extra['name'], extra['key']]) tables.append(extras_table) env.fout(formatting.listing(tables, separator='\n'))
[ "def", "cli", "(", "env", ")", ":", "hardware_manager", "=", "hardware", ".", "HardwareManager", "(", "env", ".", "client", ")", "options", "=", "hardware_manager", ".", "get_create_options", "(", ")", "tables", "=", "[", "]", "# Datacenters", "dc_table", "=...
Server order options for a given chassis.
[ "Server", "order", "options", "for", "a", "given", "chassis", "." ]
python
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/image_utils.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_utils.py#L282-L311
def image_generator(images, labels): """Generator for images that takes image and labels lists and creates pngs. Args: images: list of images given as [width x height x channels] numpy arrays. labels: list of ints, same length as images. Yields: A dictionary representing the images with the following fields: * image/encoded: the string encoding the image as PNG, * image/format: the string "png" representing image format, * image/class/label: an integer representing the label, * image/height: an integer representing the height, * image/width: an integer representing the width. Every field is actually a singleton list of the corresponding type. Raises: ValueError: if images is an empty list. """ if not images: raise ValueError("Must provide some images for the generator.") width, height, _ = images[0].shape for (enc_image, label) in zip(encode_images_as_png(images), labels): yield { "image/encoded": [enc_image], "image/format": ["png"], "image/class/label": [int(label)], "image/height": [height], "image/width": [width] }
[ "def", "image_generator", "(", "images", ",", "labels", ")", ":", "if", "not", "images", ":", "raise", "ValueError", "(", "\"Must provide some images for the generator.\"", ")", "width", ",", "height", ",", "_", "=", "images", "[", "0", "]", ".", "shape", "f...
Generator for images that takes image and labels lists and creates pngs. Args: images: list of images given as [width x height x channels] numpy arrays. labels: list of ints, same length as images. Yields: A dictionary representing the images with the following fields: * image/encoded: the string encoding the image as PNG, * image/format: the string "png" representing image format, * image/class/label: an integer representing the label, * image/height: an integer representing the height, * image/width: an integer representing the width. Every field is actually a singleton list of the corresponding type. Raises: ValueError: if images is an empty list.
[ "Generator", "for", "images", "that", "takes", "image", "and", "labels", "lists", "and", "creates", "pngs", "." ]
python
train
Parsl/parsl
parsl/executors/ipp_controller.py
https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/ipp_controller.py#L136-L166
def close(self): """Terminate the controller process and its child processes. Args: - None """ if self.reuse: logger.debug("Ipcontroller not shutting down: reuse enabled") return if self.mode == "manual": logger.debug("Ipcontroller not shutting down: Manual mode") return try: pgid = os.getpgid(self.proc.pid) os.killpg(pgid, signal.SIGTERM) time.sleep(0.2) os.killpg(pgid, signal.SIGKILL) try: self.proc.wait(timeout=1) x = self.proc.returncode if x == 0: logger.debug("Controller exited with {0}".format(x)) else: logger.error("Controller exited with {0}. May require manual cleanup".format(x)) except subprocess.TimeoutExpired: logger.warn("Ipcontroller process:{0} cleanup failed. May require manual cleanup".format(self.proc.pid)) except Exception as e: logger.warn("Failed to kill the ipcontroller process[{0}]: {1}".format(self.proc.pid, e))
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "reuse", ":", "logger", ".", "debug", "(", "\"Ipcontroller not shutting down: reuse enabled\"", ")", "return", "if", "self", ".", "mode", "==", "\"manual\"", ":", "logger", ".", "debug", "(", "\"Ipcon...
Terminate the controller process and its child processes. Args: - None
[ "Terminate", "the", "controller", "process", "and", "its", "child", "processes", "." ]
python
valid
saltstack/salt
salt/returners/postgres_local_cache.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/postgres_local_cache.py#L200-L221
def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid). So do what you have to do to make sure that stays the case ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() if passed_jid is None: jid = _gen_jid(cur) else: jid = passed_jid while not jid: log.info("jid clash, generating a new one") jid = _gen_jid(cur) cur.close() conn.close() return jid
[ "def", "prep_jid", "(", "nocache", "=", "False", ",", "passed_jid", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", ")", "if", "conn", "is", "None", ":", "return", "None", "cur", "=", "conn", ".", "cursor", "(", ")", "if", "passed_jid", "is", ...
Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid). So do what you have to do to make sure that stays the case
[ "Return", "a", "job", "id", "and", "prepare", "the", "job", "id", "directory", "This", "is", "the", "function", "responsible", "for", "making", "sure", "jids", "don", "t", "collide", "(", "unless", "its", "passed", "a", "jid", ")", ".", "So", "do", "wh...
python
train
zerotk/easyfs
zerotk/easyfs/_easyfs.py
https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L70-L90
def Cwd(directory): ''' Context manager for current directory (uses with_statement) e.g.: # working on some directory with Cwd('/home/new_dir'): # working on new_dir # working on some directory again :param unicode directory: Target directory to enter ''' old_directory = six.moves.getcwd() if directory is not None: os.chdir(directory) try: yield directory finally: os.chdir(old_directory)
[ "def", "Cwd", "(", "directory", ")", ":", "old_directory", "=", "six", ".", "moves", ".", "getcwd", "(", ")", "if", "directory", "is", "not", "None", ":", "os", ".", "chdir", "(", "directory", ")", "try", ":", "yield", "directory", "finally", ":", "o...
Context manager for current directory (uses with_statement) e.g.: # working on some directory with Cwd('/home/new_dir'): # working on new_dir # working on some directory again :param unicode directory: Target directory to enter
[ "Context", "manager", "for", "current", "directory", "(", "uses", "with_statement", ")" ]
python
valid
quantopian/zipline
zipline/pipeline/filters/filter.py
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/filters/filter.py#L237-L245
def create(cls, expr, binds): """ Helper for creating new NumExprFactors. This is just a wrapper around NumericalExpression.__new__ that always forwards `bool` as the dtype, since Filters can only be of boolean dtype. """ return cls(expr=expr, binds=binds, dtype=bool_dtype)
[ "def", "create", "(", "cls", ",", "expr", ",", "binds", ")", ":", "return", "cls", "(", "expr", "=", "expr", ",", "binds", "=", "binds", ",", "dtype", "=", "bool_dtype", ")" ]
Helper for creating new NumExprFactors. This is just a wrapper around NumericalExpression.__new__ that always forwards `bool` as the dtype, since Filters can only be of boolean dtype.
[ "Helper", "for", "creating", "new", "NumExprFactors", "." ]
python
train
ivknv/s3m
s3m.py
https://github.com/ivknv/s3m/blob/71663c12613d41cf7d3dd99c819d50a7c1b7ff9d/s3m.py#L133-L140
def close(self): """Close the cursor""" if self.closed or self.connection.closed: return self._cursor.close() self.closed = True
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "closed", "or", "self", ".", "connection", ".", "closed", ":", "return", "self", ".", "_cursor", ".", "close", "(", ")", "self", ".", "closed", "=", "True" ]
Close the cursor
[ "Close", "the", "cursor" ]
python
train
rossengeorgiev/aprs-python
aprslib/inet.py
https://github.com/rossengeorgiev/aprs-python/blob/94b89a6da47a322129484efcaf1e82f6a9932891/aprslib/inet.py#L265-L310
def _send_login(self): """ Sends login string to server """ login_str = "user {0} pass {1} vers aprslib {3}{2}\r\n" login_str = login_str.format( self.callsign, self.passwd, (" filter " + self.filter) if self.filter != "" else "", __version__ ) self.logger.info("Sending login information") try: self._sendall(login_str) self.sock.settimeout(5) test = self.sock.recv(len(login_str) + 100) if is_py3: test = test.decode('latin-1') test = test.rstrip() self.logger.debug("Server: %s", test) _, _, callsign, status, _ = test.split(' ', 4) if callsign == "": raise LoginError("Server responded with empty callsign???") if callsign != self.callsign: raise LoginError("Server: %s" % test) if status != "verified," and self.passwd != "-1": raise LoginError("Password is incorrect") if self.passwd == "-1": self.logger.info("Login successful (receive only)") else: self.logger.info("Login successful") except LoginError as e: self.logger.error(str(e)) self.close() raise except: self.close() self.logger.error("Failed to login") raise LoginError("Failed to login")
[ "def", "_send_login", "(", "self", ")", ":", "login_str", "=", "\"user {0} pass {1} vers aprslib {3}{2}\\r\\n\"", "login_str", "=", "login_str", ".", "format", "(", "self", ".", "callsign", ",", "self", ".", "passwd", ",", "(", "\" filter \"", "+", "self", ".", ...
Sends login string to server
[ "Sends", "login", "string", "to", "server" ]
python
valid
hvac/hvac
hvac/utils.py
https://github.com/hvac/hvac/blob/cce5b86889193f622c2a72a4a1b7e1c9c8aff1ce/hvac/utils.py#L76-L102
def generate_property_deprecation_message(to_be_removed_in_version, old_name, new_name, new_attribute, module_name='Client'): """Generate a message to be used when warning about the use of deprecated properties. :param to_be_removed_in_version: Version of this module the deprecated property will be removed in. :type to_be_removed_in_version: str :param old_name: Deprecated property name. :type old_name: str :param new_name: Name of the new property name to use. :type new_name: str :param new_attribute: The new attribute where the new property can be found. :type new_attribute: str :param module_name: Name of the module containing the new method to use. :type module_name: str :return: Full deprecation warning message for the indicated property. :rtype: str """ message = "Call to deprecated property '{name}'. This property will be removed in version '{version}'".format( name=old_name, version=to_be_removed_in_version, ) message += " Please use the '{new_name}' property on the '{module_name}.{new_attribute}' attribute moving forward.".format( new_name=new_name, module_name=module_name, new_attribute=new_attribute, ) return message
[ "def", "generate_property_deprecation_message", "(", "to_be_removed_in_version", ",", "old_name", ",", "new_name", ",", "new_attribute", ",", "module_name", "=", "'Client'", ")", ":", "message", "=", "\"Call to deprecated property '{name}'. This property will be removed in versio...
Generate a message to be used when warning about the use of deprecated properties. :param to_be_removed_in_version: Version of this module the deprecated property will be removed in. :type to_be_removed_in_version: str :param old_name: Deprecated property name. :type old_name: str :param new_name: Name of the new property name to use. :type new_name: str :param new_attribute: The new attribute where the new property can be found. :type new_attribute: str :param module_name: Name of the module containing the new method to use. :type module_name: str :return: Full deprecation warning message for the indicated property. :rtype: str
[ "Generate", "a", "message", "to", "be", "used", "when", "warning", "about", "the", "use", "of", "deprecated", "properties", "." ]
python
train
gwastro/pycbc
pycbc/population/rates_functions.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/population/rates_functions.py#L13-L55
def process_full_data(fname, rhomin, mass1, mass2, lo_mchirp, hi_mchirp): """Read the zero-lag and time-lag triggers identified by templates in a specified range of chirp mass. Parameters ---------- hdfile: File that stores all the triggers rhomin: float Minimum value of SNR threhold (will need including ifar) mass1: array First mass of the waveform in the template bank mass2: array Second mass of the waveform in the template bank lo_mchirp: float Minimum chirp mass for the template hi_mchirp: float Maximum chirp mass for the template Returns ------- dictionary containing foreground triggers and background information """ with h5py.File(fname, 'r') as bulk: id_bkg = bulk['background_exc/template_id'][:] id_fg = bulk['foreground/template_id'][:] mchirp_bkg = mchirp_from_mass1_mass2(mass1[id_bkg], mass2[id_bkg]) bound = np.sign((mchirp_bkg - lo_mchirp) * (hi_mchirp - mchirp_bkg)) idx_bkg = np.where(bound == 1) mchirp_fg = mchirp_from_mass1_mass2(mass1[id_fg], mass2[id_fg]) bound = np.sign((mchirp_fg - lo_mchirp) * (hi_mchirp - mchirp_fg)) idx_fg = np.where(bound == 1) zerolagstat = bulk['foreground/stat'][:][idx_fg] cstat_back_exc = bulk['background_exc/stat'][:][idx_bkg] dec_factors = bulk['background_exc/decimation_factor'][:][idx_bkg] return {'zerolagstat': zerolagstat[zerolagstat > rhomin], 'dec_factors': dec_factors[cstat_back_exc > rhomin], 'cstat_back_exc': cstat_back_exc[cstat_back_exc > rhomin]}
[ "def", "process_full_data", "(", "fname", ",", "rhomin", ",", "mass1", ",", "mass2", ",", "lo_mchirp", ",", "hi_mchirp", ")", ":", "with", "h5py", ".", "File", "(", "fname", ",", "'r'", ")", "as", "bulk", ":", "id_bkg", "=", "bulk", "[", "'background_e...
Read the zero-lag and time-lag triggers identified by templates in a specified range of chirp mass. Parameters ---------- hdfile: File that stores all the triggers rhomin: float Minimum value of SNR threhold (will need including ifar) mass1: array First mass of the waveform in the template bank mass2: array Second mass of the waveform in the template bank lo_mchirp: float Minimum chirp mass for the template hi_mchirp: float Maximum chirp mass for the template Returns ------- dictionary containing foreground triggers and background information
[ "Read", "the", "zero", "-", "lag", "and", "time", "-", "lag", "triggers", "identified", "by", "templates", "in", "a", "specified", "range", "of", "chirp", "mass", "." ]
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#L1010-L1019
def _getPropertyValue(schema, propertyName, options): """Checks to see if property is specified in 'options'. If not, reads the default value from the schema""" if propertyName not in options: paramsSchema = schema['properties'][propertyName] if 'default' in paramsSchema: options[propertyName] = paramsSchema['default'] else: options[propertyName] = None
[ "def", "_getPropertyValue", "(", "schema", ",", "propertyName", ",", "options", ")", ":", "if", "propertyName", "not", "in", "options", ":", "paramsSchema", "=", "schema", "[", "'properties'", "]", "[", "propertyName", "]", "if", "'default'", "in", "paramsSche...
Checks to see if property is specified in 'options'. If not, reads the default value from the schema
[ "Checks", "to", "see", "if", "property", "is", "specified", "in", "options", ".", "If", "not", "reads", "the", "default", "value", "from", "the", "schema" ]
python
valid
genialis/resolwe
resolwe/elastic/builder.py
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L424-L428
def register_signals(self): """Register signals for all indexes.""" for index in self.indexes: if index.object_type: self._connect_signal(index)
[ "def", "register_signals", "(", "self", ")", ":", "for", "index", "in", "self", ".", "indexes", ":", "if", "index", ".", "object_type", ":", "self", ".", "_connect_signal", "(", "index", ")" ]
Register signals for all indexes.
[ "Register", "signals", "for", "all", "indexes", "." ]
python
train