repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L283-L287
def on_new_line(self): """On new input line""" self.set_cursor_position('eof') self.current_prompt_pos = self.get_position('cursor') self.new_input_line = False
[ "def", "on_new_line", "(", "self", ")", ":", "self", ".", "set_cursor_position", "(", "'eof'", ")", "self", ".", "current_prompt_pos", "=", "self", ".", "get_position", "(", "'cursor'", ")", "self", ".", "new_input_line", "=", "False" ]
On new input line
[ "On", "new", "input", "line" ]
python
train
38.4
HDI-Project/BTB
btb/selection/pure.py
https://github.com/HDI-Project/BTB/blob/7f489ebc5591bd0886652ef743098c022d7f7460/btb/selection/pure.py#L23-L36
def compute_rewards(self, scores): """ Compute the "velocity" of (average distance between) the k+1 best scores. Return a list with those k velocities padded out with zeros so that the count remains the same. """ # get the k + 1 best scores in descending order best_scores = sorted(scores, reverse=True)[:self.k + 1] velocities = [best_scores[i] - best_scores[i + 1] for i in range(len(best_scores) - 1)] # pad the list out with zeros to maintain the length of the list zeros = (len(scores) - self.k) * [0] return velocities + zeros
[ "def", "compute_rewards", "(", "self", ",", "scores", ")", ":", "# get the k + 1 best scores in descending order", "best_scores", "=", "sorted", "(", "scores", ",", "reverse", "=", "True", ")", "[", ":", "self", ".", "k", "+", "1", "]", "velocities", "=", "[...
Compute the "velocity" of (average distance between) the k+1 best scores. Return a list with those k velocities padded out with zeros so that the count remains the same.
[ "Compute", "the", "velocity", "of", "(", "average", "distance", "between", ")", "the", "k", "+", "1", "best", "scores", ".", "Return", "a", "list", "with", "those", "k", "velocities", "padded", "out", "with", "zeros", "so", "that", "the", "count", "remai...
python
train
45
wonambi-python/wonambi
wonambi/ioeeg/bci2000.py
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/bci2000.py#L38-L99
def return_hdr(self): """Return the header for further use. Returns ------- subj_id : str subject identification code start_time : datetime start time of the dataset s_freq : float sampling frequency chan_name : list of str list of all the channels n_samples : int number of samples in the dataset orig : dict additional information taken directly from the header Notes ----- As far as I can, BCI2000 doesn't have channel labels, so we use dummies starting at chan001 (more consistent with Matlab 1-base indexing...) """ orig = {} orig = _read_header(self.filename) nchan = int(orig['SourceCh']) chan_name = ['ch{:03d}'.format(i + 1) for i in range(nchan)] chan_dtype = dtype(orig['DataFormat']) self.statevector_len = int(orig['StatevectorLen']) s_freq = orig['Parameter']['SamplingRate'] if s_freq.endswith('Hz'): s_freq = s_freq.replace('Hz', '') s_freq = int(s_freq.strip()) self.s_freq = s_freq storagetime = orig['Parameter']['StorageTime'].replace('%20', ' ') try: # newer version start_time = datetime.strptime(storagetime, '%a %b %d %H:%M:%S %Y') except: start_time = datetime.strptime(storagetime, '%Y-%m-%dT%H:%M:%S') subj_id = orig['Parameter']['SubjectName'] self.dtype = dtype([(chan, chan_dtype) for chan in chan_name] + [('statevector', 'S', self.statevector_len)]) # compute n_samples based on file size - header with open(self.filename, 'rb') as f: f.seek(0, SEEK_END) EOData = f.tell() n_samples = int((EOData - int(orig['HeaderLen'])) / self.dtype.itemsize) self.s_freq = s_freq self.header_len = int(orig['HeaderLen']) self.n_samples = n_samples self.statevectors = _prepare_statevectors(orig['StateVector']) # TODO: a better way to parse header self.gain = array([float(x) for x in orig['Parameter']['SourceChGain'].split(' ')[1:]]) return subj_id, start_time, s_freq, chan_name, n_samples, orig
[ "def", "return_hdr", "(", "self", ")", ":", "orig", "=", "{", "}", "orig", "=", "_read_header", "(", "self", ".", "filename", ")", "nchan", "=", "int", "(", "orig", "[", "'SourceCh'", "]", ")", "chan_name", "=", "[", "'ch{:03d}'", ".", "format", "(",...
Return the header for further use. Returns ------- subj_id : str subject identification code start_time : datetime start time of the dataset s_freq : float sampling frequency chan_name : list of str list of all the channels n_samples : int number of samples in the dataset orig : dict additional information taken directly from the header Notes ----- As far as I can, BCI2000 doesn't have channel labels, so we use dummies starting at chan001 (more consistent with Matlab 1-base indexing...)
[ "Return", "the", "header", "for", "further", "use", "." ]
python
train
36.096774
SITools2/pySitools2_1.0
sitools2/core/query.py
https://github.com/SITools2/pySitools2_1.0/blob/acd13198162456ba401a0b923af989bb29feb3b6/sitools2/core/query.py#L264-L274
def _getParameters(self): """Returns the result of this decorator.""" param = self.query._getParameters() index = self._getFilterIndex() param.update({ 'filter['+str(index)+'][columnAlias]' : self.__column, 'filter['+str(index)+'][data][type]' : self.__type, 'filter['+str(index)+'][data][value]' : self.__value, 'filter['+str(index)+'][data][comparison]' : self.__comparison}) #self.__column.getColumnAlias() return param
[ "def", "_getParameters", "(", "self", ")", ":", "param", "=", "self", ".", "query", ".", "_getParameters", "(", ")", "index", "=", "self", ".", "_getFilterIndex", "(", ")", "param", ".", "update", "(", "{", "'filter['", "+", "str", "(", "index", ")", ...
Returns the result of this decorator.
[ "Returns", "the", "result", "of", "this", "decorator", "." ]
python
train
45.545455
mitsei/dlkit
dlkit/json_/__init__.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/__init__.py#L74-L84
def _notify_receiver(self, receiver, params, doc): """Send notification to the receiver""" verb = VMAP[doc['op']] ns = doc['ns'] notification_id = Id(ns + 'Notification:' + str(ObjectId()) + '@' + params['authority']) object_id = Id(ns + ':' + str(doc['o']['_id']) + '@' + params['authority']) try: getattr(receiver, '_'.join([verb, params['obj_name_plural']]))(notification_id, [object_id]) except AttributeError: pass return notification_id
[ "def", "_notify_receiver", "(", "self", ",", "receiver", ",", "params", ",", "doc", ")", ":", "verb", "=", "VMAP", "[", "doc", "[", "'op'", "]", "]", "ns", "=", "doc", "[", "'ns'", "]", "notification_id", "=", "Id", "(", "ns", "+", "'Notification:'",...
Send notification to the receiver
[ "Send", "notification", "to", "the", "receiver" ]
python
train
47.272727
codenerix/django-codenerix-invoicing
codenerix_invoicing/models_sales.py
https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/models_sales.py#L2372-L2407
def create_ticket_from_albaran(pk, list_lines): MODEL_SOURCE = SalesAlbaran MODEL_FINAL = SalesTicket url_reverse = 'CDNX_invoicing_ticketsaless_list' # type_doc msg_error_relation = _("Hay lineas asignadas a ticket") msg_error_not_found = _('Sales albaran not found') msg_error_line_not_found = _('Todas las lineas ya se han pasado a ticket') return SalesLines.create_document_from_another(pk, list_lines, MODEL_SOURCE, MODEL_FINAL, url_reverse, msg_error_relation, msg_error_not_found, msg_error_line_not_found, False) """ context = {} if list_lines: new_list_lines = SalesLines.objects.filter( pk__in=[int(x) for x in list_lines] ).exclude( invoice__isnull=True ).values_list('pk') if new_list_lines: new_pk = SalesLines.objects.values_list('order__pk').filter(pk__in=new_list_lines).first() if new_pk: context = SalesLines.create_ticket_from_order(new_pk, new_list_lines) return context else: error = _('Pedido no encontrado') else: error = _('Lineas no relacionadas con pedido') else: error = _('Lineas no seleccionadas') context['error'] = error return context """
[ "def", "create_ticket_from_albaran", "(", "pk", ",", "list_lines", ")", ":", "MODEL_SOURCE", "=", "SalesAlbaran", "MODEL_FINAL", "=", "SalesTicket", "url_reverse", "=", "'CDNX_invoicing_ticketsaless_list'", "# type_doc", "msg_error_relation", "=", "_", "(", "\"Hay lineas ...
context = {} if list_lines: new_list_lines = SalesLines.objects.filter( pk__in=[int(x) for x in list_lines] ).exclude( invoice__isnull=True ).values_list('pk') if new_list_lines: new_pk = SalesLines.objects.values_list('order__pk').filter(pk__in=new_list_lines).first() if new_pk: context = SalesLines.create_ticket_from_order(new_pk, new_list_lines) return context else: error = _('Pedido no encontrado') else: error = _('Lineas no relacionadas con pedido') else: error = _('Lineas no seleccionadas') context['error'] = error return context
[ "context", "=", "{}", "if", "list_lines", ":", "new_list_lines", "=", "SalesLines", ".", "objects", ".", "filter", "(", "pk__in", "=", "[", "int", "(", "x", ")", "for", "x", "in", "list_lines", "]", ")", ".", "exclude", "(", "invoice__isnull", "=", "Tr...
python
train
43.055556
Microsoft/nni
examples/trials/kaggle-tgs-salt/models.py
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/models.py#L210-L214
def freeze_bn(self): '''Freeze BatchNorm layers.''' for layer in self.modules(): if isinstance(layer, nn.BatchNorm2d): layer.eval()
[ "def", "freeze_bn", "(", "self", ")", ":", "for", "layer", "in", "self", ".", "modules", "(", ")", ":", "if", "isinstance", "(", "layer", ",", "nn", ".", "BatchNorm2d", ")", ":", "layer", ".", "eval", "(", ")" ]
Freeze BatchNorm layers.
[ "Freeze", "BatchNorm", "layers", "." ]
python
train
34.2
deepmind/sonnet
sonnet/python/modules/batch_norm.py
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm.py#L400-L442
def _batch_norm_op(self, input_batch, mean, variance, use_batch_stats, stat_dtype): """Creates a batch normalization op. It uses the tf.nn.batch_normalization op by default and the tf.nn.fused_batch_norm op to support fused batch normalization. Args: input_batch: A input Tensor of arbitrary dimension. mean: A mean tensor, of the same dtype as `input_batch`. variance: A variance tensor, of the same dtype as `input_batch`. use_batch_stats: A bool value that indicates whether the operation should use the batch statistics. stat_dtype: TensorFlow datatype used for the moving mean and variance. Returns: A batch normalization operation. The current mean tensor, of datatype `stat_dtype`. The current variance tensor, of datatype `stat_dtype`. """ if self._fused: # For the non-training case where not using batch stats, # pass in the moving statistic variables directly. # These will already be in the correct dtype, even for float16 input. batch_norm_op, mean, variance = self._fused_batch_norm_op( input_batch, self._moving_mean, self._moving_variance, use_batch_stats) else: batch_norm_op = tf.nn.batch_normalization( input_batch, mean, variance, self._beta, self._gamma, self._eps, name="batch_norm") # We'll echo the supplied mean and variance so that they can also be used # to update the moving statistics. Cast to matching type if necessary. if input_batch.dtype.base_dtype != stat_dtype: mean = tf.cast(mean, stat_dtype) variance = tf.cast(variance, stat_dtype) return batch_norm_op, mean, variance
[ "def", "_batch_norm_op", "(", "self", ",", "input_batch", ",", "mean", ",", "variance", ",", "use_batch_stats", ",", "stat_dtype", ")", ":", "if", "self", ".", "_fused", ":", "# For the non-training case where not using batch stats,", "# pass in the moving statistic varia...
Creates a batch normalization op. It uses the tf.nn.batch_normalization op by default and the tf.nn.fused_batch_norm op to support fused batch normalization. Args: input_batch: A input Tensor of arbitrary dimension. mean: A mean tensor, of the same dtype as `input_batch`. variance: A variance tensor, of the same dtype as `input_batch`. use_batch_stats: A bool value that indicates whether the operation should use the batch statistics. stat_dtype: TensorFlow datatype used for the moving mean and variance. Returns: A batch normalization operation. The current mean tensor, of datatype `stat_dtype`. The current variance tensor, of datatype `stat_dtype`.
[ "Creates", "a", "batch", "normalization", "op", "." ]
python
train
40.418605
theno/fabsetup
fabsetup/addons.py
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/addons.py#L126-L145
def load_repo_addons(_globals): '''Load all fabsetup addons which are stored under ~/.fabsetup-addon-repos as git repositories. Args: _globals(dict): the globals() namespace of the fabric script. Return: None ''' repos_dir = os.path.expanduser('~/.fabsetup-addon-repos') if os.path.isdir(repos_dir): basedir, repos, _ = next(os.walk(repos_dir)) for repo_dir in [os.path.join(basedir, repo) for repo in repos # omit dot dirs like '.rope' # or 'fabsetup-theno-termdown.disabled' if '.' not in repo]: sys.path.append(repo_dir) package_name, username = package_username(repo_dir.split('/')[-1]) load_addon(username, package_name, _globals)
[ "def", "load_repo_addons", "(", "_globals", ")", ":", "repos_dir", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.fabsetup-addon-repos'", ")", "if", "os", ".", "path", ".", "isdir", "(", "repos_dir", ")", ":", "basedir", ",", "repos", ",", "_", "="...
Load all fabsetup addons which are stored under ~/.fabsetup-addon-repos as git repositories. Args: _globals(dict): the globals() namespace of the fabric script. Return: None
[ "Load", "all", "fabsetup", "addons", "which", "are", "stored", "under", "~", "/", ".", "fabsetup", "-", "addon", "-", "repos", "as", "git", "repositories", "." ]
python
train
40.3
fermiPy/fermipy
fermipy/tsmap.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/tsmap.py#L507-L523
def f_cash(x, counts, bkg, model): """ Wrapper for cash statistics, that defines the model function. Parameters ---------- x : float Model amplitude. counts : `~numpy.ndarray` Count map slice, where model is defined. bkg : `~numpy.ndarray` Background map slice, where model is defined. model : `~numpy.ndarray` Source template (multiplied with exposure). """ return 2.0 * poisson_log_like(counts, bkg + x * model)
[ "def", "f_cash", "(", "x", ",", "counts", ",", "bkg", ",", "model", ")", ":", "return", "2.0", "*", "poisson_log_like", "(", "counts", ",", "bkg", "+", "x", "*", "model", ")" ]
Wrapper for cash statistics, that defines the model function. Parameters ---------- x : float Model amplitude. counts : `~numpy.ndarray` Count map slice, where model is defined. bkg : `~numpy.ndarray` Background map slice, where model is defined. model : `~numpy.ndarray` Source template (multiplied with exposure).
[ "Wrapper", "for", "cash", "statistics", "that", "defines", "the", "model", "function", "." ]
python
train
27.705882
watson-developer-cloud/python-sdk
ibm_watson/compare_comply_v1.py
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/compare_comply_v1.py#L4573-L4586
def _from_dict(cls, _dict): """Initialize a TableReturn object from a json dictionary.""" args = {} if 'document' in _dict: args['document'] = DocInfo._from_dict(_dict.get('document')) if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') if 'model_version' in _dict: args['model_version'] = _dict.get('model_version') if 'tables' in _dict: args['tables'] = [ Tables._from_dict(x) for x in (_dict.get('tables')) ] return cls(**args)
[ "def", "_from_dict", "(", "cls", ",", "_dict", ")", ":", "args", "=", "{", "}", "if", "'document'", "in", "_dict", ":", "args", "[", "'document'", "]", "=", "DocInfo", ".", "_from_dict", "(", "_dict", ".", "get", "(", "'document'", ")", ")", "if", ...
Initialize a TableReturn object from a json dictionary.
[ "Initialize", "a", "TableReturn", "object", "from", "a", "json", "dictionary", "." ]
python
train
40.142857
stephenmcd/gnotty
gnotty/bots/rss.py
https://github.com/stephenmcd/gnotty/blob/bea3762dc9cbc3cb21a5ae7224091cf027273c40/gnotty/bots/rss.py#L30-L45
def parse_feeds(self, message_channel=True): """ Iterates through each of the feed URLs, parses their items, and sends any items to the channel that have not been previously been parsed. """ if parse: for feed_url in self.feeds: feed = parse(feed_url) for item in feed.entries: if item["id"] not in self.feed_items: self.feed_items.add(item["id"]) if message_channel: message = self.format_item_message(feed, item) self.message_channel(message) return
[ "def", "parse_feeds", "(", "self", ",", "message_channel", "=", "True", ")", ":", "if", "parse", ":", "for", "feed_url", "in", "self", ".", "feeds", ":", "feed", "=", "parse", "(", "feed_url", ")", "for", "item", "in", "feed", ".", "entries", ":", "i...
Iterates through each of the feed URLs, parses their items, and sends any items to the channel that have not been previously been parsed.
[ "Iterates", "through", "each", "of", "the", "feed", "URLs", "parses", "their", "items", "and", "sends", "any", "items", "to", "the", "channel", "that", "have", "not", "been", "previously", "been", "parsed", "." ]
python
train
42.5
iotaledger/iota.lib.py
iota/api.py
https://github.com/iotaledger/iota.lib.py/blob/97cdd1e241498446b46157b79b2a1ea2ec6d387a/iota/api.py#L520-L581
def get_account_data(self, start=0, stop=None, inclusion_states=False, security_level=None): # type: (int, Optional[int], bool, Optional[int]) -> dict """ More comprehensive version of :py:meth:`get_transfers` that returns addresses and account balance in addition to bundles. This function is useful in getting all the relevant information of your account. :param start: Starting key index. :param stop: Stop before this index. Note that this parameter behaves like the ``stop`` attribute in a :py:class:`slice` object; the stop index is *not* included in the result. If ``None`` (default), then this method will check every address until it finds one without any transfers. :param inclusion_states: Whether to also fetch the inclusion states of the transfers. This requires an additional API call to the node, so it is disabled by default. :param security_level: Number of iterations to use when generating new addresses (see :py:meth:`get_new_addresses`). This value must be between 1 and 3, inclusive. If not set, defaults to :py:attr:`AddressGenerator.DEFAULT_SECURITY_LEVEL`. :return: Dict with the following structure:: { 'addresses': List[Address], List of generated addresses. Note that this list may include unused addresses. 'balance': int, Total account balance. Might be 0. 'bundles': List[Bundle], List of bundles with transactions to/from this account. } """ return extended.GetAccountDataCommand(self.adapter)( seed=self.seed, start=start, stop=stop, inclusionStates=inclusion_states, security_level=security_level )
[ "def", "get_account_data", "(", "self", ",", "start", "=", "0", ",", "stop", "=", "None", ",", "inclusion_states", "=", "False", ",", "security_level", "=", "None", ")", ":", "# type: (int, Optional[int], bool, Optional[int]) -> dict", "return", "extended", ".", "...
More comprehensive version of :py:meth:`get_transfers` that returns addresses and account balance in addition to bundles. This function is useful in getting all the relevant information of your account. :param start: Starting key index. :param stop: Stop before this index. Note that this parameter behaves like the ``stop`` attribute in a :py:class:`slice` object; the stop index is *not* included in the result. If ``None`` (default), then this method will check every address until it finds one without any transfers. :param inclusion_states: Whether to also fetch the inclusion states of the transfers. This requires an additional API call to the node, so it is disabled by default. :param security_level: Number of iterations to use when generating new addresses (see :py:meth:`get_new_addresses`). This value must be between 1 and 3, inclusive. If not set, defaults to :py:attr:`AddressGenerator.DEFAULT_SECURITY_LEVEL`. :return: Dict with the following structure:: { 'addresses': List[Address], List of generated addresses. Note that this list may include unused addresses. 'balance': int, Total account balance. Might be 0. 'bundles': List[Bundle], List of bundles with transactions to/from this account. }
[ "More", "comprehensive", "version", "of", ":", "py", ":", "meth", ":", "get_transfers", "that", "returns", "addresses", "and", "account", "balance", "in", "addition", "to", "bundles", "." ]
python
test
33.66129
jamesturk/scrapelib
scrapelib/cache.py
https://github.com/jamesturk/scrapelib/blob/dcae9fa86f1fdcc4b4e90dbca12c8063bcb36525/scrapelib/cache.py#L117-L161
def get(self, orig_key): """Get cache entry for key, or return None.""" resp = requests.Response() key = self._clean_key(orig_key) path = os.path.join(self.cache_dir, key) try: with open(path, 'rb') as f: # read lines one at a time while True: line = f.readline().decode('utf8').strip('\r\n') # set headers if self.check_last_modified and re.search("last-modified", line, flags=re.I): # line contains last modified header head_resp = requests.head(orig_key) try: new_lm = head_resp.headers['last-modified'] old_lm = line[string.find(line, ':') + 1:].strip() if old_lm != new_lm: # last modified timestamps don't match, need to download again return None except KeyError: # no last modified header present, so redownload return None header = self._header_re.match(line) if header: resp.headers[header.group(1)] = header.group(2) else: break # everything left is the real content resp._content = f.read() # status & encoding will be in headers, but are faked # need to split spaces out of status to get code (e.g. '200 OK') resp.status_code = int(resp.headers.pop('status').split(' ')[0]) resp.encoding = resp.headers.pop('encoding') resp.url = resp.headers.get('content-location', orig_key) # TODO: resp.request = request return resp except IOError: return None
[ "def", "get", "(", "self", ",", "orig_key", ")", ":", "resp", "=", "requests", ".", "Response", "(", ")", "key", "=", "self", ".", "_clean_key", "(", "orig_key", ")", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "cache_dir", ",", ...
Get cache entry for key, or return None.
[ "Get", "cache", "entry", "for", "key", "or", "return", "None", "." ]
python
train
42.444444
thiagopbueno/pyrddl
pyrddl/parser.py
https://github.com/thiagopbueno/pyrddl/blob/3bcfa850b1a7532c7744358f3c6b9e0f8ab978c9/pyrddl/parser.py#L278-L286
def p_req_section(self, p): '''req_section : REQUIREMENTS ASSIGN_EQUAL LCURLY string_list RCURLY SEMI | REQUIREMENTS LCURLY string_list RCURLY SEMI | empty''' if len(p) == 7: p[0] = p[4] elif len(p) == 6: p[0] = p[3] self._print_verbose('requirements')
[ "def", "p_req_section", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", "==", "7", ":", "p", "[", "0", "]", "=", "p", "[", "4", "]", "elif", "len", "(", "p", ")", "==", "6", ":", "p", "[", "0", "]", "=", "p", "[", "3", "]...
req_section : REQUIREMENTS ASSIGN_EQUAL LCURLY string_list RCURLY SEMI | REQUIREMENTS LCURLY string_list RCURLY SEMI | empty
[ "req_section", ":", "REQUIREMENTS", "ASSIGN_EQUAL", "LCURLY", "string_list", "RCURLY", "SEMI", "|", "REQUIREMENTS", "LCURLY", "string_list", "RCURLY", "SEMI", "|", "empty" ]
python
train
38.444444
Rapptz/discord.py
discord/ext/commands/core.py
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1430-L1453
def bot_has_any_role(*items): """Similar to :func:`.has_any_role` except checks if the bot itself has any of the roles listed. This check raises one of two special exceptions, :exc:`.BotMissingAnyRole` if the bot is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1.0 Raise :exc:`.BotMissingAnyRole` or :exc:`.NoPrivateMessage` instead of generic checkfailure """ def predicate(ctx): ch = ctx.channel if not isinstance(ch, discord.abc.GuildChannel): raise NoPrivateMessage() me = ch.guild.me getter = functools.partial(discord.utils.get, me.roles) if any(getter(id=item) is not None if isinstance(item, int) else getter(name=item) is not None for item in items): return True raise BotMissingAnyRole(items) return check(predicate)
[ "def", "bot_has_any_role", "(", "*", "items", ")", ":", "def", "predicate", "(", "ctx", ")", ":", "ch", "=", "ctx", ".", "channel", "if", "not", "isinstance", "(", "ch", ",", "discord", ".", "abc", ".", "GuildChannel", ")", ":", "raise", "NoPrivateMess...
Similar to :func:`.has_any_role` except checks if the bot itself has any of the roles listed. This check raises one of two special exceptions, :exc:`.BotMissingAnyRole` if the bot is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1.0 Raise :exc:`.BotMissingAnyRole` or :exc:`.NoPrivateMessage` instead of generic checkfailure
[ "Similar", "to", ":", "func", ":", ".", "has_any_role", "except", "checks", "if", "the", "bot", "itself", "has", "any", "of", "the", "roles", "listed", "." ]
python
train
38.791667
aestrivex/bctpy
bct/algorithms/degree.py
https://github.com/aestrivex/bctpy/blob/4cb0e759eb4a038750b07e23bd29958c400684b8/bct/algorithms/degree.py#L6-L35
def degrees_dir(CIJ): ''' Node degree is the number of links connected to the node. The indegree is the number of inward links and the outdegree is the number of outward links. Parameters ---------- CIJ : NxN np.ndarray directed binary/weighted connection matrix Returns ------- id : Nx1 np.ndarray node in-degree od : Nx1 np.ndarray node out-degree deg : Nx1 np.ndarray node degree (in-degree + out-degree) Notes ----- Inputs are assumed to be on the columns of the CIJ matrix. Weight information is discarded. ''' CIJ = binarize(CIJ, copy=True) # ensure CIJ is binary id = np.sum(CIJ, axis=0) # indegree = column sum of CIJ od = np.sum(CIJ, axis=1) # outdegree = row sum of CIJ deg = id + od # degree = indegree+outdegree return id, od, deg
[ "def", "degrees_dir", "(", "CIJ", ")", ":", "CIJ", "=", "binarize", "(", "CIJ", ",", "copy", "=", "True", ")", "# ensure CIJ is binary", "id", "=", "np", ".", "sum", "(", "CIJ", ",", "axis", "=", "0", ")", "# indegree = column sum of CIJ", "od", "=", "...
Node degree is the number of links connected to the node. The indegree is the number of inward links and the outdegree is the number of outward links. Parameters ---------- CIJ : NxN np.ndarray directed binary/weighted connection matrix Returns ------- id : Nx1 np.ndarray node in-degree od : Nx1 np.ndarray node out-degree deg : Nx1 np.ndarray node degree (in-degree + out-degree) Notes ----- Inputs are assumed to be on the columns of the CIJ matrix. Weight information is discarded.
[ "Node", "degree", "is", "the", "number", "of", "links", "connected", "to", "the", "node", ".", "The", "indegree", "is", "the", "number", "of", "inward", "links", "and", "the", "outdegree", "is", "the", "number", "of", "outward", "links", "." ]
python
train
28.233333
cackharot/suds-py3
suds/servicedefinition.py
https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/servicedefinition.py#L172-L186
def getprefix(self, u): """ Get the prefix for the specified namespace (uri) @param u: A namespace uri. @type u: str @return: The namspace. @rtype: (prefix, uri). """ for ns in Namespace.all: if u == ns[1]: return ns[0] for ns in self.prefixes: if u == ns[1]: return ns[0] raise Exception('ns (%s) not mapped' % u)
[ "def", "getprefix", "(", "self", ",", "u", ")", ":", "for", "ns", "in", "Namespace", ".", "all", ":", "if", "u", "==", "ns", "[", "1", "]", ":", "return", "ns", "[", "0", "]", "for", "ns", "in", "self", ".", "prefixes", ":", "if", "u", "==", ...
Get the prefix for the specified namespace (uri) @param u: A namespace uri. @type u: str @return: The namspace. @rtype: (prefix, uri).
[ "Get", "the", "prefix", "for", "the", "specified", "namespace", "(", "uri", ")" ]
python
train
29.066667
twilio/twilio-python
twilio/rest/api/v2010/account/usage/trigger.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/usage/trigger.py#L71-L101
def stream(self, recurring=values.unset, trigger_by=values.unset, usage_category=values.unset, limit=None, page_size=None): """ Streams TriggerInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. :param TriggerInstance.Recurring recurring: The frequency of recurring UsageTriggers to read :param TriggerInstance.TriggerField trigger_by: The trigger field of the UsageTriggers to read :param TriggerInstance.UsageCategory usage_category: The usage category of the UsageTriggers to read :param int limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param int page_size: Number of records to fetch per request, when not set will use the default value of 50 records. If no page_size is defined but a limit is defined, stream() will attempt to read the limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results :rtype: list[twilio.rest.api.v2010.account.usage.trigger.TriggerInstance] """ limits = self._version.read_limits(limit, page_size) page = self.page( recurring=recurring, trigger_by=trigger_by, usage_category=usage_category, page_size=limits['page_size'], ) return self._version.stream(page, limits['limit'], limits['page_limit'])
[ "def", "stream", "(", "self", ",", "recurring", "=", "values", ".", "unset", ",", "trigger_by", "=", "values", ".", "unset", ",", "usage_category", "=", "values", ".", "unset", ",", "limit", "=", "None", ",", "page_size", "=", "None", ")", ":", "limits...
Streams TriggerInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. :param TriggerInstance.Recurring recurring: The frequency of recurring UsageTriggers to read :param TriggerInstance.TriggerField trigger_by: The trigger field of the UsageTriggers to read :param TriggerInstance.UsageCategory usage_category: The usage category of the UsageTriggers to read :param int limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param int page_size: Number of records to fetch per request, when not set will use the default value of 50 records. If no page_size is defined but a limit is defined, stream() will attempt to read the limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results :rtype: list[twilio.rest.api.v2010.account.usage.trigger.TriggerInstance]
[ "Streams", "TriggerInstance", "records", "from", "the", "API", "as", "a", "generator", "stream", ".", "This", "operation", "lazily", "loads", "records", "as", "efficiently", "as", "possible", "until", "the", "limit", "is", "reached", ".", "The", "results", "ar...
python
train
56.032258
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1830-L1853
def example_number_for_non_geo_entity(country_calling_code): """Gets a valid number for the specified country calling code for a non-geographical entity. Arguments: country_calling_code -- The country calling code for a non-geographical entity. Returns a valid number for the non-geographical entity. Returns None when the metadata does not contain such information, or the country calling code passed in does not belong to a non-geographical entity. """ metadata = PhoneMetadata.metadata_for_nongeo_region(country_calling_code, None) if metadata is not None: # For geographical entities, fixed-line data is always present. However, for non-geographical # entities, this is not the case, so we have to go through different types to find the # example number. We don't check fixed-line or personal number since they aren't used by # non-geographical entities (if this changes, a unit-test will catch this.) for desc in (metadata.mobile, metadata.toll_free, metadata.shared_cost, metadata.voip, metadata.voicemail, metadata.uan, metadata.premium_rate): try: if (desc is not None and desc.example_number is not None): return parse(_PLUS_SIGN + unicod(country_calling_code) + desc.example_number, UNKNOWN_REGION) except NumberParseException: pass return None
[ "def", "example_number_for_non_geo_entity", "(", "country_calling_code", ")", ":", "metadata", "=", "PhoneMetadata", ".", "metadata_for_nongeo_region", "(", "country_calling_code", ",", "None", ")", "if", "metadata", "is", "not", "None", ":", "# For geographical entities,...
Gets a valid number for the specified country calling code for a non-geographical entity. Arguments: country_calling_code -- The country calling code for a non-geographical entity. Returns a valid number for the non-geographical entity. Returns None when the metadata does not contain such information, or the country calling code passed in does not belong to a non-geographical entity.
[ "Gets", "a", "valid", "number", "for", "the", "specified", "country", "calling", "code", "for", "a", "non", "-", "geographical", "entity", "." ]
python
train
58.75
hydraplatform/hydra-base
hydra_base/lib/users.py
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L278-L292
def delete_role_perm(role_id, perm_id,**kwargs): """ Remove a permission from a role """ #check_perm(kwargs.get('user_id'), 'edit_perm') _get_perm(perm_id) _get_role(role_id) try: roleperm_i = db.DBSession.query(RolePerm).filter(RolePerm.role_id==role_id, RolePerm.perm_id==perm_id).one() db.DBSession.delete(roleperm_i) except NoResultFound: raise ResourceNotFoundError("Role Perm does not exist") return 'OK'
[ "def", "delete_role_perm", "(", "role_id", ",", "perm_id", ",", "*", "*", "kwargs", ")", ":", "#check_perm(kwargs.get('user_id'), 'edit_perm')", "_get_perm", "(", "perm_id", ")", "_get_role", "(", "role_id", ")", "try", ":", "roleperm_i", "=", "db", ".", "DBSess...
Remove a permission from a role
[ "Remove", "a", "permission", "from", "a", "role" ]
python
train
30.8
inspirehep/harvesting-kit
harvestingkit/utils.py
https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L476-L482
def return_letters_from_string(text): """Get letters from string only.""" out = "" for letter in text: if letter.isalpha(): out += letter return out
[ "def", "return_letters_from_string", "(", "text", ")", ":", "out", "=", "\"\"", "for", "letter", "in", "text", ":", "if", "letter", ".", "isalpha", "(", ")", ":", "out", "+=", "letter", "return", "out" ]
Get letters from string only.
[ "Get", "letters", "from", "string", "only", "." ]
python
valid
25.428571
osfclient/osfclient
osfclient/api.py
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/api.py#L22-L28
def project(self, project_id): """Fetch project `project_id`.""" type_ = self.guid(project_id) url = self._build_url(type_, project_id) if type_ in Project._types: return Project(self._json(self._get(url), 200), self.session) raise OSFException('{} is unrecognized type {}. Clone supports projects and registrations'.format(project_id, type_))
[ "def", "project", "(", "self", ",", "project_id", ")", ":", "type_", "=", "self", ".", "guid", "(", "project_id", ")", "url", "=", "self", ".", "_build_url", "(", "type_", ",", "project_id", ")", "if", "type_", "in", "Project", ".", "_types", ":", "r...
Fetch project `project_id`.
[ "Fetch", "project", "project_id", "." ]
python
valid
55.571429
asphalt-framework/asphalt
asphalt/core/context.py
https://github.com/asphalt-framework/asphalt/blob/4114b3ac9743cbd9facb374a3f53e19d3afef22d/asphalt/core/context.py#L176-L184
def context_chain(self) -> List['Context']: """Return a list of contexts starting from this one, its parent and so on.""" contexts = [] ctx = self # type: Optional[Context] while ctx is not None: contexts.append(ctx) ctx = ctx.parent return contexts
[ "def", "context_chain", "(", "self", ")", "->", "List", "[", "'Context'", "]", ":", "contexts", "=", "[", "]", "ctx", "=", "self", "# type: Optional[Context]", "while", "ctx", "is", "not", "None", ":", "contexts", ".", "append", "(", "ctx", ")", "ctx", ...
Return a list of contexts starting from this one, its parent and so on.
[ "Return", "a", "list", "of", "contexts", "starting", "from", "this", "one", "its", "parent", "and", "so", "on", "." ]
python
train
34.111111
ml4ai/delphi
delphi/utils/fp.py
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/fp.py#L56-L80
def append(x: T, xs: Iterable[T]) -> Iterator[T]: """ Append a value to an iterable. Parameters ---------- x An element of type T. xs An iterable of elements of type T. Returns ------- Iterator An iterator that yields elements of *xs*, then yields *x*. Examples -------- >>> from delphi.utils.fp import append >>> list(append(1, [2, 3])) [2, 3, 1] """ return chain(xs, [x])
[ "def", "append", "(", "x", ":", "T", ",", "xs", ":", "Iterable", "[", "T", "]", ")", "->", "Iterator", "[", "T", "]", ":", "return", "chain", "(", "xs", ",", "[", "x", "]", ")" ]
Append a value to an iterable. Parameters ---------- x An element of type T. xs An iterable of elements of type T. Returns ------- Iterator An iterator that yields elements of *xs*, then yields *x*. Examples -------- >>> from delphi.utils.fp import append >>> list(append(1, [2, 3])) [2, 3, 1]
[ "Append", "a", "value", "to", "an", "iterable", "." ]
python
train
17.56
davidfokkema/artist
artist/plot.py
https://github.com/davidfokkema/artist/blob/26ae7987522622710f2910980770c50012fda47d/artist/plot.py#L952-L993
def _calc_position_for_pin(self, x, y, relative_position): """Determine position at fraction of x, y path. :param x,y: two equal length lists of values describing a path. :param relative_position: value between 0 and 1 :returns: the x, y position of the fraction (relative_position) of the path length. """ try: max_idx_x = len(x) - 1 max_idx_y = len(y) - 1 except TypeError: return x, y else: assert max_idx_x == max_idx_y, \ 'If x and y are iterables, they must be the same length' if relative_position == 0: xs, ys = x[0], y[0] elif relative_position == 1: xs, ys = x[max_idx_x], y[max_idx_y] else: if self.xmode == 'log': x = np.log10(np.array(x)) if self.ymode == 'log': y = np.log10(np.array(y)) rel_length = [0] rel_length.extend(self._calc_relative_path_lengths(x, y)) idx = np.interp(relative_position, rel_length, range(len(rel_length))) frac, idx = modf(idx) idx = int(idx) if self.xmode == 'log': xs = 10 ** (x[idx] + (x[idx + 1] - x[idx]) * frac) else: xs = x[idx] + (x[idx + 1] - x[idx]) * frac if self.ymode == 'log': ys = 10 ** (y[idx] + (y[idx + 1] - y[idx]) * frac) else: ys = y[idx] + (y[idx + 1] - y[idx]) * frac return xs, ys
[ "def", "_calc_position_for_pin", "(", "self", ",", "x", ",", "y", ",", "relative_position", ")", ":", "try", ":", "max_idx_x", "=", "len", "(", "x", ")", "-", "1", "max_idx_y", "=", "len", "(", "y", ")", "-", "1", "except", "TypeError", ":", "return"...
Determine position at fraction of x, y path. :param x,y: two equal length lists of values describing a path. :param relative_position: value between 0 and 1 :returns: the x, y position of the fraction (relative_position) of the path length.
[ "Determine", "position", "at", "fraction", "of", "x", "y", "path", "." ]
python
train
37.285714
slarse/pdfebc-core
pdfebc_core/compress.py
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/compress.py#L54-L85
def compress_pdf(filepath, output_path, ghostscript_binary): """Compress a single PDF file. Args: filepath (str): Path to the PDF file. output_path (str): Output path. ghostscript_binary (str): Name/alias of the Ghostscript binary. Raises: ValueError FileNotFoundError """ if not filepath.endswith(PDF_EXTENSION): raise ValueError("Filename must end with .pdf!\n%s does not." % filepath) try: file_size = os.stat(filepath).st_size if file_size < FILE_SIZE_LOWER_LIMIT: LOGGER.info(NOT_COMPRESSING.format(filepath, file_size, FILE_SIZE_LOWER_LIMIT)) process = subprocess.Popen(['cp', filepath, output_path]) else: LOGGER.info(COMPRESSING.format(filepath)) process = subprocess.Popen( [ghostscript_binary, "-sDEVICE=pdfwrite", "-dCompatabilityLevel=1.4", "-dPDFSETTINGS=/ebook", "-dNOPAUSE", "-dQUIET", "-dBATCH", "-sOutputFile=%s" % output_path, filepath] ) except FileNotFoundError: msg = GS_NOT_INSTALLED.format(ghostscript_binary) raise FileNotFoundError(msg) process.communicate() LOGGER.info(FILE_DONE.format(output_path))
[ "def", "compress_pdf", "(", "filepath", ",", "output_path", ",", "ghostscript_binary", ")", ":", "if", "not", "filepath", ".", "endswith", "(", "PDF_EXTENSION", ")", ":", "raise", "ValueError", "(", "\"Filename must end with .pdf!\\n%s does not.\"", "%", "filepath", ...
Compress a single PDF file. Args: filepath (str): Path to the PDF file. output_path (str): Output path. ghostscript_binary (str): Name/alias of the Ghostscript binary. Raises: ValueError FileNotFoundError
[ "Compress", "a", "single", "PDF", "file", "." ]
python
train
39.125
bloomreach/s4cmd
s4cmd.py
https://github.com/bloomreach/s4cmd/blob/bb51075bf43703e7cd95aa39288cf7732ec13a6d/s4cmd.py#L410-L420
def get_legal_params(self, method): '''Given a API name, list all legal parameters using boto3 service model.''' if method not in self.client.meta.method_to_api_mapping: # Injected methods. Ignore. return [] api = self.client.meta.method_to_api_mapping[method] shape = self.client.meta.service_model.operation_model(api).input_shape if shape is None: # No params needed for this API. return [] return shape.members.keys()
[ "def", "get_legal_params", "(", "self", ",", "method", ")", ":", "if", "method", "not", "in", "self", ".", "client", ".", "meta", ".", "method_to_api_mapping", ":", "# Injected methods. Ignore.", "return", "[", "]", "api", "=", "self", ".", "client", ".", ...
Given a API name, list all legal parameters using boto3 service model.
[ "Given", "a", "API", "name", "list", "all", "legal", "parameters", "using", "boto3", "service", "model", "." ]
python
test
41.727273
Spinmob/spinmob
egg/_gui.py
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/egg/_gui.py#L1206-L1210
def get_all_items(self): """ Returns all items in the combobox dictionary. """ return [self._widget.itemText(k) for k in range(self._widget.count())]
[ "def", "get_all_items", "(", "self", ")", ":", "return", "[", "self", ".", "_widget", ".", "itemText", "(", "k", ")", "for", "k", "in", "range", "(", "self", ".", "_widget", ".", "count", "(", ")", ")", "]" ]
Returns all items in the combobox dictionary.
[ "Returns", "all", "items", "in", "the", "combobox", "dictionary", "." ]
python
train
35.4
honzamach/pynspect
pynspect/traversers.py
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/traversers.py#L467-L477
def binary_operation_comparison(self, rule, left, right, **kwargs): """ Callback method for rule tree traversing. Will be called at proper time from :py:class:`pynspect.rules.ComparisonBinOpRule.traverse` method. :param pynspect.rules.Rule rule: Reference to rule. :param left: Left operand for operation. :param right: right operand for operation. :param dict kwargs: Optional callback arguments. """ return '<div class="pynspect-rule-operation pynspect-rule-operation-comparison"><h3 class="pynspect-rule-operation-name">{}</h3><ul class="pynspect-rule-operation-arguments"><li class="pynspect-rule-operation-argument-left">{}</li><li class="pynspect-rule-operation-argument-right">{}</li></ul></div>'.format(rule.operation, left, right)
[ "def", "binary_operation_comparison", "(", "self", ",", "rule", ",", "left", ",", "right", ",", "*", "*", "kwargs", ")", ":", "return", "'<div class=\"pynspect-rule-operation pynspect-rule-operation-comparison\"><h3 class=\"pynspect-rule-operation-name\">{}</h3><ul class=\"pynspect...
Callback method for rule tree traversing. Will be called at proper time from :py:class:`pynspect.rules.ComparisonBinOpRule.traverse` method. :param pynspect.rules.Rule rule: Reference to rule. :param left: Left operand for operation. :param right: right operand for operation. :param dict kwargs: Optional callback arguments.
[ "Callback", "method", "for", "rule", "tree", "traversing", ".", "Will", "be", "called", "at", "proper", "time", "from", ":", "py", ":", "class", ":", "pynspect", ".", "rules", ".", "ComparisonBinOpRule", ".", "traverse", "method", "." ]
python
train
72.909091
facelessuser/soupsieve
soupsieve/css_match.py
https://github.com/facelessuser/soupsieve/blob/24859cc3e756ebf46b75547d49c6b4a7bf35ee82/soupsieve/css_match.py#L1422-L1426
def iselect(self, tag, limit=0): """Iterate the specified tags.""" for el in CSSMatch(self.selectors, tag, self.namespaces, self.flags).select(limit): yield el
[ "def", "iselect", "(", "self", ",", "tag", ",", "limit", "=", "0", ")", ":", "for", "el", "in", "CSSMatch", "(", "self", ".", "selectors", ",", "tag", ",", "self", ".", "namespaces", ",", "self", ".", "flags", ")", ".", "select", "(", "limit", ")...
Iterate the specified tags.
[ "Iterate", "the", "specified", "tags", "." ]
python
train
36.8
ManiacalLabs/BiblioPixel
bibliopixel/layout/matrix_drawing.py
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix_drawing.py#L244-L249
def draw_rect(setter, x, y, w, h, color=None, aa=False): """Draw rectangle with top-left corner at x,y, width w and height h""" _draw_fast_hline(setter, x, y, w, color, aa) _draw_fast_hline(setter, x, y + h - 1, w, color, aa) _draw_fast_vline(setter, x, y, h, color, aa) _draw_fast_vline(setter, x + w - 1, y, h, color, aa)
[ "def", "draw_rect", "(", "setter", ",", "x", ",", "y", ",", "w", ",", "h", ",", "color", "=", "None", ",", "aa", "=", "False", ")", ":", "_draw_fast_hline", "(", "setter", ",", "x", ",", "y", ",", "w", ",", "color", ",", "aa", ")", "_draw_fast_...
Draw rectangle with top-left corner at x,y, width w and height h
[ "Draw", "rectangle", "with", "top", "-", "left", "corner", "at", "x", "y", "width", "w", "and", "height", "h" ]
python
valid
56.333333
vijayvarma392/surfinBH
surfinBH/surfinBH.py
https://github.com/vijayvarma392/surfinBH/blob/9f2d25d00f894ee2ce9ffbb02f4e4a41fa7989eb/surfinBH/surfinBH.py#L103-L121
def _load_scalar_fit(self, fit_key=None, h5file=None, fit_data=None): """ Loads a single fit """ if (fit_key is None) ^ (h5file is None): raise ValueError("Either specify both fit_key and h5file, or" " neither") if not ((fit_key is None) ^ (fit_data is None)): raise ValueError("Specify exactly one of fit_key and fit_data.") if fit_data is None: fit_data = self._read_dict(h5file[fit_key]) if 'fitType' in fit_data.keys() and fit_data['fitType'] == 'GPR': fit = _eval_pysur.evaluate_fit.getGPRFitAndErrorEvaluator(fit_data) else: fit = _eval_pysur.evaluate_fit.getFitEvaluator(fit_data) return fit
[ "def", "_load_scalar_fit", "(", "self", ",", "fit_key", "=", "None", ",", "h5file", "=", "None", ",", "fit_data", "=", "None", ")", ":", "if", "(", "fit_key", "is", "None", ")", "^", "(", "h5file", "is", "None", ")", ":", "raise", "ValueError", "(", ...
Loads a single fit
[ "Loads", "a", "single", "fit" ]
python
train
38.105263
disqus/django-mailviews
mailviews/previews.py
https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/previews.py#L167-L213
def detail_view(self, request): """ Renders the message view to a response. """ context = { 'preview': self, } kwargs = {} if self.form_class: if request.GET: form = self.form_class(data=request.GET) else: form = self.form_class() context['form'] = form if not form.is_bound or not form.is_valid(): return render(request, 'mailviews/previews/detail.html', context) kwargs.update(form.get_message_view_kwargs()) message_view = self.get_message_view(request, **kwargs) message = message_view.render_to_message() raw = message.message() headers = OrderedDict((header, maybe_decode_header(raw[header])) for header in self.headers) context.update({ 'message': message, 'subject': message.subject, 'body': message.body, 'headers': headers, 'raw': raw.as_string(), }) alternatives = getattr(message, 'alternatives', []) try: html = next(alternative[0] for alternative in alternatives if alternative[1] == 'text/html') context.update({ 'html': html, 'escaped_html': b64encode(html.encode('utf-8')), }) except StopIteration: pass return render(request, self.template_name, context)
[ "def", "detail_view", "(", "self", ",", "request", ")", ":", "context", "=", "{", "'preview'", ":", "self", ",", "}", "kwargs", "=", "{", "}", "if", "self", ".", "form_class", ":", "if", "request", ".", "GET", ":", "form", "=", "self", ".", "form_c...
Renders the message view to a response.
[ "Renders", "the", "message", "view", "to", "a", "response", "." ]
python
valid
30.765957
kakwa/ldapcherry
ldapcherry/__init__.py
https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L891-L931
def login(self, login, password, url=None): """login page """ auth = self._auth(login, password) cherrypy.session['isadmin'] = auth['isadmin'] cherrypy.session['connected'] = auth['connected'] if auth['connected']: if auth['isadmin']: message = \ "login success for user '%(user)s' as administrator" % { 'user': login } else: message = \ "login success for user '%(user)s' as normal user" % { 'user': login } cherrypy.log.error( msg=message, severity=logging.INFO ) cherrypy.session[SESSION_KEY] = cherrypy.request.login = login if url is None: redirect = "/" else: redirect = url raise cherrypy.HTTPRedirect(redirect) else: message = "login failed for user '%(user)s'" % { 'user': login } cherrypy.log.error( msg=message, severity=logging.WARNING ) if url is None: qs = '' else: qs = '?url=' + quote_plus(url) raise cherrypy.HTTPRedirect("/signin" + qs)
[ "def", "login", "(", "self", ",", "login", ",", "password", ",", "url", "=", "None", ")", ":", "auth", "=", "self", ".", "_auth", "(", "login", ",", "password", ")", "cherrypy", ".", "session", "[", "'isadmin'", "]", "=", "auth", "[", "'isadmin'", ...
login page
[ "login", "page" ]
python
train
33.04878
deepmipt/DeepPavlov
deeppavlov/core/models/keras_model.py
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/keras_model.py#L156-L165
def train_on_batch(self, *args) -> None: """Trains the model on a single batch. Args: *args: the list of network inputs. Last element of `args` is the batch of targets, all previous elements are training data batches """ *data, labels = args self._net.train_on_batch(data, labels)
[ "def", "train_on_batch", "(", "self", ",", "*", "args", ")", "->", "None", ":", "*", "data", ",", "labels", "=", "args", "self", ".", "_net", ".", "train_on_batch", "(", "data", ",", "labels", ")" ]
Trains the model on a single batch. Args: *args: the list of network inputs. Last element of `args` is the batch of targets, all previous elements are training data batches
[ "Trains", "the", "model", "on", "a", "single", "batch", "." ]
python
test
34.8
tanghaibao/jcvi
jcvi/annotation/reformat.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/annotation/reformat.py#L934-L1101
def reindex(args): """ %prog reindex gffile pep.fasta ref.pep.fasta Reindex the splice isoforms (mRNA) in input GFF file, preferably generated after PASA annotation update In the input GFF file, there can be several types of mRNA within a locus: * CDS matches reference, UTR extended, inherits reference mRNA ID * CDS (slightly) different from reference, inherits reference mRNA ID * Novel isoform added by PASA, have IDs like "LOCUS.1.1", "LOCUS.1.2" * Multiple mRNA collapsed due to shared structure, have IDs like "LOCUS.1-LOCUS.1.1" In the case of multiple mRNA which have inherited the same reference mRNA ID, break ties by comparing the new protein with the reference protein using EMBOSS `needle` to decide which mRNA retains ID and which is assigned a new ID. All mRNA identifiers should follow the AGI naming conventions. When reindexing the isoform identifiers, order mRNA based on: * decreasing transcript length * decreasing support from multiple input datasets used to run pasa.consolidate() """ from jcvi.formats.gff import make_index from jcvi.formats.fasta import Fasta from jcvi.apps.emboss import needle from jcvi.formats.base import FileShredder from tempfile import mkstemp p = OptionParser(reindex.__doc__) p.add_option("--scores", type="str", \ help="read from existing EMBOSS `needle` scores file") p.set_outfile() opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) gffile, pep, refpep, = args gffdb = make_index(gffile) reffasta = Fasta(refpep) if not opts.scores: fh, pairsfile = mkstemp(prefix='pairs', suffix=".txt", dir=".") fw = must_open(pairsfile, "w") conflict, novel = AutoVivification(), {} for gene in gffdb.features_of_type('gene', order_by=('seqid', 'start')): geneid = atg_name(gene.id, retval='locus') novel[geneid] = [] updated_mrna, hybrid_mrna = [], [] for mrna in gffdb.children(gene, featuretype='mRNA', order_by=('seqid', 'start')): if re.match(atg_name_pat, mrna.id) is not None and "_" not in mrna.id: pf, mrnaid = parse_prefix(mrna.id) mlen = gffdb.children_bp(mrna, child_featuretype='exon') if "-" in mrna.id: hybrid_mrna.append((mrna.id, mrna.start, mlen, len(pf))) else: updated_mrna.append((mrna.id, mrna.start, mlen, len(pf))) for mrna in sorted(updated_mrna, key=lambda k:(k[1], -k[2], -k[3])): pf, mrnaid = parse_prefix(mrna[0]) mstart, mlen = mrna[1], mrna[2] iso = atg_name(mrnaid, retval='iso') newiso = "{0}{1}".format(iso, re.sub(atg_name_pat, "", mrnaid)) if iso == newiso: if iso not in conflict[geneid]: conflict[geneid][iso] = [] conflict[geneid][iso].append((mrna[0], iso, newiso, \ mstart, mlen, len(pf))) else: novel[geneid].append((mrna[0], None, newiso, \ mstart, mlen, len(pf))) for mrna in sorted(hybrid_mrna, key=lambda k:(k[1], -k[2], -k[3])): pf, mrnaid = parse_prefix(mrna[0]) mstart, mlen = mrna[1], mrna[2] _iso, _newiso = [], [] for id in sorted(mrnaid.split("-")): a = atg_name(id, retval='iso') b = "{0}{1}".format(a, re.sub(atg_name_pat, "", id)) _iso.append(a) _newiso.append(b) _novel = None newiso = "-".join(str(x) for x in set(_newiso)) for iso, niso in zip(_iso, _newiso): if iso == niso: if iso not in conflict[geneid]: conflict[geneid][iso] = \ [(mrna[0], iso, newiso, mstart, mlen, len(pf))] _novel = None break _novel = True if _novel is not None: novel[geneid].append((mrna[0], None, newiso, \ mstart, mlen, len(pf))) if not opts.scores: for isoform in sorted(conflict[geneid]): mrnaid = "{0}.{1}".format(geneid, isoform) if mrnaid in reffasta.keys(): for mrna in conflict[geneid][isoform]: print("\t".join(str(x) for x in (mrnaid, mrna[0])), file=fw) scoresfile = None if not opts.scores: fw.close() needle([pairsfile, refpep, pep]) FileShredder([pairsfile], verbose=False) scoresfile = "{0}.scores".format(pairsfile.rsplit(".")[0]) else: scoresfile = opts.scores scores = read_scores(scoresfile, sort=True, trimsuffix=False) primary = {} for geneid in conflict: primary[geneid] = [] for iso in sorted(conflict[geneid]): conflict[geneid][iso].sort(key=lambda k:(k[3], -k[4], -k[5])) _iso = "{0}.{1}".format(geneid, iso) if _iso not in scores: novel[geneid].extend(conflict[geneid][iso]) continue top_score = scores[_iso][0][1] result = next((i for i, v in enumerate(conflict[geneid][iso]) if v[0] == top_score), None) if result is not None: primary[geneid].append(conflict[geneid][iso][result]) del conflict[geneid][iso][result] if geneid not in novel: novel[geneid] = [] novel[geneid].extend(conflict[geneid][iso]) novel[geneid].sort(key=lambda k:(k[3], -k[4], -k[5])) fw = must_open(opts.outfile, 'w') for gene in gffdb.features_of_type('gene', order_by=('seqid', 'start')): geneid = gene.id print(gene, file=fw) seen = [] if geneid in primary: all_mrna = primary[geneid] all_mrna.extend(novel[geneid]) for iso, mrna in enumerate(all_mrna): _mrna = gffdb[mrna[0]] _iso = mrna[1] if mrna not in novel[geneid]: seen.append(int(mrna[1])) else: mseen = 0 if len(seen) == 0 else max(seen) _iso = (mseen + iso + 1) - len(seen) _mrnaid = "{0}.{1}".format(geneid, _iso) _mrna['ID'], _mrna['_old_ID'] = [_mrnaid], [_mrna.id] print(_mrna, file=fw) for c in gffdb.children(_mrna, order_by=('start')): c['Parent'] = [_mrnaid] print(c, file=fw) else: for feat in gffdb.children(gene, order_by=('seqid', 'start')): print(feat, file=fw) fw.close()
[ "def", "reindex", "(", "args", ")", ":", "from", "jcvi", ".", "formats", ".", "gff", "import", "make_index", "from", "jcvi", ".", "formats", ".", "fasta", "import", "Fasta", "from", "jcvi", ".", "apps", ".", "emboss", "import", "needle", "from", "jcvi", ...
%prog reindex gffile pep.fasta ref.pep.fasta Reindex the splice isoforms (mRNA) in input GFF file, preferably generated after PASA annotation update In the input GFF file, there can be several types of mRNA within a locus: * CDS matches reference, UTR extended, inherits reference mRNA ID * CDS (slightly) different from reference, inherits reference mRNA ID * Novel isoform added by PASA, have IDs like "LOCUS.1.1", "LOCUS.1.2" * Multiple mRNA collapsed due to shared structure, have IDs like "LOCUS.1-LOCUS.1.1" In the case of multiple mRNA which have inherited the same reference mRNA ID, break ties by comparing the new protein with the reference protein using EMBOSS `needle` to decide which mRNA retains ID and which is assigned a new ID. All mRNA identifiers should follow the AGI naming conventions. When reindexing the isoform identifiers, order mRNA based on: * decreasing transcript length * decreasing support from multiple input datasets used to run pasa.consolidate()
[ "%prog", "reindex", "gffile", "pep", ".", "fasta", "ref", ".", "pep", ".", "fasta" ]
python
train
39.803571
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L2448-L2478
def connect_array(self, address, connection_key, connection_type, **kwargs): """Connect this array with another one. :param address: IP address or DNS name of other array. :type address: str :param connection_key: Connection key of other array. :type connection_key: str :param connection_type: Type(s) of connection desired. :type connection_type: list :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST array/connection** :type \*\*kwargs: optional :returns: A dictionary describing the connection to the other array. :rtype: ResponseDict .. note:: Currently, the only type of connection is "replication". .. note:: Requires use of REST API 1.2 or later. """ data = {"management_address": address, "connection_key": connection_key, "type": connection_type} data.update(kwargs) return self._request("POST", "array/connection", data)
[ "def", "connect_array", "(", "self", ",", "address", ",", "connection_key", ",", "connection_type", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "\"management_address\"", ":", "address", ",", "\"connection_key\"", ":", "connection_key", ",", "\"type\"", ...
Connect this array with another one. :param address: IP address or DNS name of other array. :type address: str :param connection_key: Connection key of other array. :type connection_key: str :param connection_type: Type(s) of connection desired. :type connection_type: list :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST array/connection** :type \*\*kwargs: optional :returns: A dictionary describing the connection to the other array. :rtype: ResponseDict .. note:: Currently, the only type of connection is "replication". .. note:: Requires use of REST API 1.2 or later.
[ "Connect", "this", "array", "with", "another", "one", "." ]
python
train
35.677419
ByteInternet/amqpconsumer
amqpconsumer/events.py
https://github.com/ByteInternet/amqpconsumer/blob/144ab16b3fbba8ad30f8688ae1c58e3a6423b88b/amqpconsumer/events.py#L278-L304
def on_message(self, _, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties and the body is the message that was sent. We'll json-decode the message body, and if that succeeds, call the handler that was given to us. Messages that contain invalid json will be discarded. :type _: pika.channel.Channel :type basic_deliver: pika.Spec.Basic.Deliver :type properties: pika.Spec.BasicProperties :type body: str|unicode """ logger.debug('Received message # %s from %s: %s', basic_deliver.delivery_tag, properties.app_id, body) try: decoded = json.loads(body.decode('-utf-8')) except ValueError: logger.warning('Discarding message containing invalid json: %s', body) else: self._handler(decoded) self.acknowledge_message(basic_deliver.delivery_tag)
[ "def", "on_message", "(", "self", ",", "_", ",", "basic_deliver", ",", "properties", ",", "body", ")", ":", "logger", ".", "debug", "(", "'Received message # %s from %s: %s'", ",", "basic_deliver", ".", "delivery_tag", ",", "properties", ".", "app_id", ",", "b...
Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties and the body is the message that was sent. We'll json-decode the message body, and if that succeeds, call the handler that was given to us. Messages that contain invalid json will be discarded. :type _: pika.channel.Channel :type basic_deliver: pika.Spec.Basic.Deliver :type properties: pika.Spec.BasicProperties :type body: str|unicode
[ "Invoked", "by", "pika", "when", "a", "message", "is", "delivered", "from", "RabbitMQ", "." ]
python
train
44.888889
floydhub/floyd-cli
floyd/cli/experiment.py
https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L82-L97
def status(id): """ View status of all jobs in a project. The command also accepts a specific job name. """ if id: try: experiment = ExperimentClient().get(normalize_job_name(id)) except FloydException: experiment = ExperimentClient().get(id) print_experiments([experiment]) else: experiments = ExperimentClient().get_all() print_experiments(experiments)
[ "def", "status", "(", "id", ")", ":", "if", "id", ":", "try", ":", "experiment", "=", "ExperimentClient", "(", ")", ".", "get", "(", "normalize_job_name", "(", "id", ")", ")", "except", "FloydException", ":", "experiment", "=", "ExperimentClient", "(", "...
View status of all jobs in a project. The command also accepts a specific job name.
[ "View", "status", "of", "all", "jobs", "in", "a", "project", "." ]
python
train
26.8125
shmir/PyIxExplorer
ixexplorer/ixe_port.py
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_port.py#L344-L352
def set_phy_mode(self, mode=IxePhyMode.ignore): """ Set phy mode to copper or fiber. :param mode: requested PHY mode. """ if isinstance(mode, IxePhyMode): if mode.value: self.api.call_rc('port setPhyMode {} {}'.format(mode.value, self.uri)) else: self.api.call_rc('port setPhyMode {} {}'.format(mode, self.uri))
[ "def", "set_phy_mode", "(", "self", ",", "mode", "=", "IxePhyMode", ".", "ignore", ")", ":", "if", "isinstance", "(", "mode", ",", "IxePhyMode", ")", ":", "if", "mode", ".", "value", ":", "self", ".", "api", ".", "call_rc", "(", "'port setPhyMode {} {}'"...
Set phy mode to copper or fiber. :param mode: requested PHY mode.
[ "Set", "phy", "mode", "to", "copper", "or", "fiber", ".", ":", "param", "mode", ":", "requested", "PHY", "mode", "." ]
python
train
42.555556
JNRowe/upoints
upoints/utils.py
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/utils.py#L1002-L1026
def sun_events(latitude, longitude, date, timezone=0, zenith=None): """Convenience function for calculating sunrise and sunset. Civil twilight starts/ends when the Sun's centre is 6 degrees below the horizon. Nautical twilight starts/ends when the Sun's centre is 12 degrees below the horizon. Astronomical twilight starts/ends when the Sun's centre is 18 degrees below the horizon. Args: latitude (float): Location's latitude longitude (float): Location's longitude date (datetime.date): Calculate rise or set for given date timezone (int): Offset from UTC in minutes zenith (str): Calculate rise/set events, or twilight times Returns: tuple of datetime.time: The time for the given events in the specified timezone """ return (sun_rise_set(latitude, longitude, date, 'rise', timezone, zenith), sun_rise_set(latitude, longitude, date, 'set', timezone, zenith))
[ "def", "sun_events", "(", "latitude", ",", "longitude", ",", "date", ",", "timezone", "=", "0", ",", "zenith", "=", "None", ")", ":", "return", "(", "sun_rise_set", "(", "latitude", ",", "longitude", ",", "date", ",", "'rise'", ",", "timezone", ",", "z...
Convenience function for calculating sunrise and sunset. Civil twilight starts/ends when the Sun's centre is 6 degrees below the horizon. Nautical twilight starts/ends when the Sun's centre is 12 degrees below the horizon. Astronomical twilight starts/ends when the Sun's centre is 18 degrees below the horizon. Args: latitude (float): Location's latitude longitude (float): Location's longitude date (datetime.date): Calculate rise or set for given date timezone (int): Offset from UTC in minutes zenith (str): Calculate rise/set events, or twilight times Returns: tuple of datetime.time: The time for the given events in the specified timezone
[ "Convenience", "function", "for", "calculating", "sunrise", "and", "sunset", "." ]
python
train
38.32
ranaroussi/qtpylib
qtpylib/tools.py
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L375-L414
def backdate(res, date=None, as_datetime=False, fmt='%Y-%m-%d'): """ get past date based on currect date """ if res is None: return None if date is None: date = datetime.datetime.now() else: try: date = parse_date(date) except Exception as e: pass new_date = date periods = int("".join([s for s in res if s.isdigit()])) if periods > 0: if "K" in res: new_date = date - datetime.timedelta(microseconds=periods) elif "S" in res: new_date = date - datetime.timedelta(seconds=periods) elif "T" in res: new_date = date - datetime.timedelta(minutes=periods) elif "H" in res or "V" in res: new_date = date - datetime.timedelta(hours=periods) elif "W" in res: new_date = date - datetime.timedelta(weeks=periods) else: # days new_date = date - datetime.timedelta(days=periods) # not a week day: while new_date.weekday() > 4: # Mon-Fri are 0-4 new_date = backdate(res="1D", date=new_date, as_datetime=True) if as_datetime: return new_date return new_date.strftime(fmt)
[ "def", "backdate", "(", "res", ",", "date", "=", "None", ",", "as_datetime", "=", "False", ",", "fmt", "=", "'%Y-%m-%d'", ")", ":", "if", "res", "is", "None", ":", "return", "None", "if", "date", "is", "None", ":", "date", "=", "datetime", ".", "da...
get past date based on currect date
[ "get", "past", "date", "based", "on", "currect", "date" ]
python
train
29.425
jbeluch/xbmcswift2
xbmcswift2/listitem.py
https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/listitem.py#L186-L221
def from_dict(cls, label=None, label2=None, icon=None, thumbnail=None, path=None, selected=None, info=None, properties=None, context_menu=None, replace_context_menu=False, is_playable=None, info_type='video', stream_info=None): '''A ListItem constructor for setting a lot of properties not available in the regular __init__ method. Useful to collect all the properties in a dict and then use the **dct to call this method. ''' listitem = cls(label, label2, icon, thumbnail, path) if selected is not None: listitem.select(selected) if info: listitem.set_info(info_type, info) if is_playable: listitem.set_is_playable(True) if properties: # Need to support existing tuples, but prefer to have a dict for # properties. if hasattr(properties, 'items'): properties = properties.items() for key, val in properties: listitem.set_property(key, val) if stream_info: for stream_type, stream_values in stream_info.items(): listitem.add_stream_info(stream_type, stream_values) if context_menu: listitem.add_context_menu_items(context_menu, replace_context_menu) return listitem
[ "def", "from_dict", "(", "cls", ",", "label", "=", "None", ",", "label2", "=", "None", ",", "icon", "=", "None", ",", "thumbnail", "=", "None", ",", "path", "=", "None", ",", "selected", "=", "None", ",", "info", "=", "None", ",", "properties", "="...
A ListItem constructor for setting a lot of properties not available in the regular __init__ method. Useful to collect all the properties in a dict and then use the **dct to call this method.
[ "A", "ListItem", "constructor", "for", "setting", "a", "lot", "of", "properties", "not", "available", "in", "the", "regular", "__init__", "method", ".", "Useful", "to", "collect", "all", "the", "properties", "in", "a", "dict", "and", "then", "use", "the", ...
python
train
37.527778
ninuxorg/nodeshot
nodeshot/community/notifications/registrars/nodes.py
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/registrars/nodes.py#L42-L62
def node_status_changed_handler(**kwargs): """ send notification when the status of a node changes according to users's settings """ obj = kwargs['instance'] obj.old_status = kwargs['old_status'].name obj.new_status = kwargs['new_status'].name queryset = exclude_owner_of_node(obj) create_notifications.delay(**{ "users": queryset, "notification_model": Notification, "notification_type": "node_status_changed", "related_object": obj }) # if node has owner send a different notification to him if obj.user is not None: create_notifications.delay(**{ "users": [obj.user], "notification_model": Notification, "notification_type": "node_own_status_changed", "related_object": obj })
[ "def", "node_status_changed_handler", "(", "*", "*", "kwargs", ")", ":", "obj", "=", "kwargs", "[", "'instance'", "]", "obj", ".", "old_status", "=", "kwargs", "[", "'old_status'", "]", ".", "name", "obj", ".", "new_status", "=", "kwargs", "[", "'new_statu...
send notification when the status of a node changes according to users's settings
[ "send", "notification", "when", "the", "status", "of", "a", "node", "changes", "according", "to", "users", "s", "settings" ]
python
train
37.714286
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3544-L3558
def extract_code_from_function(function): """Return code handled by function.""" if not function.__name__.startswith('fix_'): return None code = re.sub('^fix_', '', function.__name__) if not code: return None try: int(code[1:]) except ValueError: return None return code
[ "def", "extract_code_from_function", "(", "function", ")", ":", "if", "not", "function", ".", "__name__", ".", "startswith", "(", "'fix_'", ")", ":", "return", "None", "code", "=", "re", ".", "sub", "(", "'^fix_'", ",", "''", ",", "function", ".", "__nam...
Return code handled by function.
[ "Return", "code", "handled", "by", "function", "." ]
python
train
21.266667
maxfischer2781/chainlet
chainlet/genlink.py
https://github.com/maxfischer2781/chainlet/blob/4e17f9992b4780bd0d9309202e2847df640bffe8/chainlet/genlink.py#L203-L239
def genlet(generator_function=None, prime=True): """ Decorator to convert a generator function to a :py:class:`~chainlink.ChainLink` :param generator_function: the generator function to convert :type generator_function: generator :param prime: advance the generator to the next/first yield :type prime: bool When used as a decorator, this function can also be called with and without keywords. .. code:: python @genlet def pingpong(): "Chainlet that passes on its value" last = yield while True: last = yield last @genlet(prime=True) def produce(): "Chainlet that produces a value" while True: yield time.time() @genlet(True) def read(iterable): "Chainlet that reads from an iterable" for item in iterable: yield item """ if generator_function is None: return GeneratorLink.wraplet(prime=prime) elif not callable(generator_function): return GeneratorLink.wraplet(prime=generator_function) return GeneratorLink.wraplet(prime=prime)(generator_function)
[ "def", "genlet", "(", "generator_function", "=", "None", ",", "prime", "=", "True", ")", ":", "if", "generator_function", "is", "None", ":", "return", "GeneratorLink", ".", "wraplet", "(", "prime", "=", "prime", ")", "elif", "not", "callable", "(", "genera...
Decorator to convert a generator function to a :py:class:`~chainlink.ChainLink` :param generator_function: the generator function to convert :type generator_function: generator :param prime: advance the generator to the next/first yield :type prime: bool When used as a decorator, this function can also be called with and without keywords. .. code:: python @genlet def pingpong(): "Chainlet that passes on its value" last = yield while True: last = yield last @genlet(prime=True) def produce(): "Chainlet that produces a value" while True: yield time.time() @genlet(True) def read(iterable): "Chainlet that reads from an iterable" for item in iterable: yield item
[ "Decorator", "to", "convert", "a", "generator", "function", "to", "a", ":", "py", ":", "class", ":", "~chainlink", ".", "ChainLink" ]
python
train
31.459459
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/utils.py
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/utils.py#L187-L203
def parse_bucket_info(domain): """Parse a domain name to gather the bucket name and region for an S3 bucket. Returns a tuple (bucket_name, bucket_region) if a valid domain name, else `None` >>> parse_bucket_info('www.riotgames.com.br.s3-website-us-west-2.amazonaws.com') ('www.riotgames.com.br', 'us-west-2') Args: domain (`str`): Domain name to parse Returns: :obj:`list` of `str`: `str`,`None` """ match = RGX_BUCKET.match(domain) if match: data = match.groupdict() return data['bucket'], data['region'] or 'us-east-1'
[ "def", "parse_bucket_info", "(", "domain", ")", ":", "match", "=", "RGX_BUCKET", ".", "match", "(", "domain", ")", "if", "match", ":", "data", "=", "match", ".", "groupdict", "(", ")", "return", "data", "[", "'bucket'", "]", ",", "data", "[", "'region'...
Parse a domain name to gather the bucket name and region for an S3 bucket. Returns a tuple (bucket_name, bucket_region) if a valid domain name, else `None` >>> parse_bucket_info('www.riotgames.com.br.s3-website-us-west-2.amazonaws.com') ('www.riotgames.com.br', 'us-west-2') Args: domain (`str`): Domain name to parse Returns: :obj:`list` of `str`: `str`,`None`
[ "Parse", "a", "domain", "name", "to", "gather", "the", "bucket", "name", "and", "region", "for", "an", "S3", "bucket", ".", "Returns", "a", "tuple", "(", "bucket_name", "bucket_region", ")", "if", "a", "valid", "domain", "name", "else", "None" ]
python
train
33.941176
standage/tag
tag/transcript.py
https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/transcript.py#L46-L74
def primary_mrna(entrystream, parenttype='gene'): """ Select a single mRNA as a representative for each protein-coding gene. The primary mRNA is the one with the longest translation product. In cases where multiple isoforms have the same translated length, the feature ID is used for sorting. This function **does not** return only mRNA features, it returns all GFF3 entry types (pragmas, features, sequences, etc). The function **does** modify the gene features that pass through to ensure that they have at most a single mRNA feature. >>> reader = tag.GFF3Reader(tag.pkgdata('pdom-withseq.gff3')) >>> filter = tag.transcript.primary_mrna(reader) >>> for gene in tag.select.features(filter, type='gene'): ... assert gene.num_children == 1 """ for entry in entrystream: if not isinstance(entry, tag.Feature): yield entry continue for parent in tag.select.features(entry, parenttype, traverse=True): mrnas = [f for f in parent.children if f.type == 'mRNA'] if len(mrnas) == 0: continue _emplace_pmrna(mrnas, parent) yield entry
[ "def", "primary_mrna", "(", "entrystream", ",", "parenttype", "=", "'gene'", ")", ":", "for", "entry", "in", "entrystream", ":", "if", "not", "isinstance", "(", "entry", ",", "tag", ".", "Feature", ")", ":", "yield", "entry", "continue", "for", "parent", ...
Select a single mRNA as a representative for each protein-coding gene. The primary mRNA is the one with the longest translation product. In cases where multiple isoforms have the same translated length, the feature ID is used for sorting. This function **does not** return only mRNA features, it returns all GFF3 entry types (pragmas, features, sequences, etc). The function **does** modify the gene features that pass through to ensure that they have at most a single mRNA feature. >>> reader = tag.GFF3Reader(tag.pkgdata('pdom-withseq.gff3')) >>> filter = tag.transcript.primary_mrna(reader) >>> for gene in tag.select.features(filter, type='gene'): ... assert gene.num_children == 1
[ "Select", "a", "single", "mRNA", "as", "a", "representative", "for", "each", "protein", "-", "coding", "gene", "." ]
python
train
40.172414
saltstack/salt
salt/modules/zfs.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L1158-L1264
def get(*dataset, **kwargs): ''' Displays properties for the given datasets. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string comma-separated list of properties to list, defaults to all recursive : boolean recursively list children depth : int recursively list children to depth fields : string comma-separated list of fields to include, the name and property field will always be added type : string comma-separated list of types to display, where type is one of filesystem, snapshot, volume, bookmark, or all. source : string comma-separated list of sources to display. Must be one of the following: local, default, inherited, temporary, and none. The default value is all sources. parsable : boolean display numbers in parsable (exact) values (default = True) .. versionadded:: 2018.3.0 .. note:: If no datasets are specified, then the command displays properties for all datasets on the system. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.get salt '*' zfs.get myzpool/mydataset [recursive=True|False] salt '*' zfs.get myzpool/mydataset properties="sharenfs,mountpoint" [recursive=True|False] salt '*' zfs.get myzpool/mydataset myzpool/myotherdataset properties=available fields=value depth=1 ''' ## Configure command # NOTE: initialize the defaults flags = ['-H'] opts = {} # NOTE: set extra config from kwargs if kwargs.get('depth', False): opts['-d'] = kwargs.get('depth') elif kwargs.get('recursive', False): flags.append('-r') fields = kwargs.get('fields', 'value,source').split(',') if 'name' in fields: # ensure name is first fields.remove('name') if 'property' in fields: # ensure property is second fields.remove('property') fields.insert(0, 'name') fields.insert(1, 'property') opts['-o'] = ",".join(fields) if kwargs.get('type', False): opts['-t'] = kwargs.get('type') if kwargs.get('source', False): opts['-s'] = kwargs.get('source') # NOTE: set property_name property_name = kwargs.get('properties', 'all') ## Get properties res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='get', flags=flags, opts=opts, property_name=property_name, target=list(dataset), ), python_shell=False, ) ret = __utils__['zfs.parse_command_result'](res) if res['retcode'] == 0: for ds in res['stdout'].splitlines(): ds_data = OrderedDict(list(zip( fields, ds.split("\t") ))) if 'value' in ds_data: if kwargs.get('parsable', True): ds_data['value'] = __utils__['zfs.from_auto']( ds_data['property'], ds_data['value'], ) else: ds_data['value'] = __utils__['zfs.to_auto']( ds_data['property'], ds_data['value'], convert_to_human=True, ) if ds_data['name'] not in ret: ret[ds_data['name']] = OrderedDict() ret[ds_data['name']][ds_data['property']] = ds_data del ds_data['name'] del ds_data['property'] return ret
[ "def", "get", "(", "*", "dataset", ",", "*", "*", "kwargs", ")", ":", "## Configure command", "# NOTE: initialize the defaults", "flags", "=", "[", "'-H'", "]", "opts", "=", "{", "}", "# NOTE: set extra config from kwargs", "if", "kwargs", ".", "get", "(", "'d...
Displays properties for the given datasets. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string comma-separated list of properties to list, defaults to all recursive : boolean recursively list children depth : int recursively list children to depth fields : string comma-separated list of fields to include, the name and property field will always be added type : string comma-separated list of types to display, where type is one of filesystem, snapshot, volume, bookmark, or all. source : string comma-separated list of sources to display. Must be one of the following: local, default, inherited, temporary, and none. The default value is all sources. parsable : boolean display numbers in parsable (exact) values (default = True) .. versionadded:: 2018.3.0 .. note:: If no datasets are specified, then the command displays properties for all datasets on the system. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.get salt '*' zfs.get myzpool/mydataset [recursive=True|False] salt '*' zfs.get myzpool/mydataset properties="sharenfs,mountpoint" [recursive=True|False] salt '*' zfs.get myzpool/mydataset myzpool/myotherdataset properties=available fields=value depth=1
[ "Displays", "properties", "for", "the", "given", "datasets", "." ]
python
train
32.654206
sdss/sdss_access
python/sdss_access/path/path.py
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/path/path.py#L69-L78
def _input_templates(self): """Read the path template file. """ foo = self._config.read([self._pathfile]) if len(foo) == 1: for k, v in self._config.items('paths'): self.templates[k] = v else: raise ValueError("Could not read {0}!".format(self._pathfile)) return
[ "def", "_input_templates", "(", "self", ")", ":", "foo", "=", "self", ".", "_config", ".", "read", "(", "[", "self", ".", "_pathfile", "]", ")", "if", "len", "(", "foo", ")", "==", "1", ":", "for", "k", ",", "v", "in", "self", ".", "_config", "...
Read the path template file.
[ "Read", "the", "path", "template", "file", "." ]
python
train
34.1
BDNYC/astrodbkit
astrodbkit/astrodb.py
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L274-L478
def add_data(self, data, table, delimiter='|', bands='', clean_up=True, rename_columns={}, column_fill={}, verbose=False): """ Adds data to the specified database table. Column names must match table fields to insert, however order and completeness don't matter. Parameters ---------- data: str, array-like, astropy.table.Table The path to an ascii file, array-like object, or table. The first row or element must be the list of column names table: str The name of the table into which the data should be inserted delimiter: str The string to use as the delimiter when parsing the ascii file bands: sequence Sequence of band to look for in the data header when digesting columns of multiple photometric measurements (e.g. ['MKO_J','MKO_H','MKO_K']) into individual rows of data for database insertion clean_up: bool Run self.clean_up() rename_columns: dict A dictionary of the {input_col_name:desired_col_name} for table columns, e.g. {'e_Jmag':'J_unc', 'RAJ2000':'ra'} column_fill: dict A dictionary of the column name and value to fill, e.g. {'instrument_id':2, 'band':'2MASS.J'} verbose: bool Print diagnostic messages """ # Store raw entry entry, del_records = data, [] # Digest the ascii file into table if isinstance(data, str) and os.path.isfile(data): data = ii.read(data, delimiter=delimiter) # Or read the sequence of data elements into a table elif isinstance(data, (list, tuple, np.ndarray)): data = ii.read(['|'.join(map(str, row)) for row in data], data_start=1, delimiter='|') # Or convert pandas dataframe to astropy table elif isinstance(data, pd.core.frame.DataFrame): data = at.Table.from_pandas(data) # Or if it's already an astropy table elif isinstance(data, at.Table): pass else: data = None if data: # Rename columns if isinstance(rename_columns,str): rename_columns = astrocat.default_rename_columns(rename_columns) for input_name,new_name in rename_columns.items(): data.rename_column(input_name,new_name) # Add column fills if isinstance(column_fill,str): column_fill = astrocat.default_column_fill(column_fill) for colname,fill_value in column_fill.items(): data[colname] = [fill_value]*len(data) # Get list of all columns and make an empty table for new records metadata = self.query("PRAGMA table_info({})".format(table), fmt='table') columns, types, required = [np.array(metadata[n]) for n in ['name', 'type', 'notnull']] new_records = at.Table(names=columns, dtype=[type_dict[t] for t in types]) # Fix column dtypes and blanks for col in data.colnames: # Convert data dtypes to those of the existing table try: temp = data[col].astype(new_records[col].dtype) data.replace_column(col, temp) except KeyError: continue # If a row contains photometry for multiple bands, use the *multiband argument and execute this if bands and table.lower() == 'photometry': # Pull out columns that are band names for b in list(set(bands) & set(data.colnames)): try: # Get the repeated data plus the band data and rename the columns band = data[list(set(columns) & set(data.colnames)) + [b, b + '_unc']] for suf in ['', '_unc']: band.rename_column(b+suf, 'magnitude'+suf) temp = band['magnitude'+suf].astype(new_records['magnitude'+suf].dtype) band.replace_column('magnitude'+suf, temp) band.add_column(at.Column([b] * len(band), name='band', dtype='O')) # Add the band data to the list of new_records new_records = at.vstack([new_records, band]) except IOError: pass else: # Inject data into full database table format new_records = at.vstack([new_records, data])[new_records.colnames] # Reject rows that fail column requirements, e.g. NOT NULL fields like 'source_id' for r in columns[np.where(np.logical_and(required, columns != 'id'))]: # Null values... new_records = new_records[np.where(new_records[r])] # Masked values... try: new_records = new_records[~new_records[r].mask] except: pass # NaN values... if new_records.dtype[r] in (int, float): new_records = new_records[~np.isnan(new_records[r])] # For spectra, try to populate the table by reading the FITS header if table.lower() == 'spectra': for n, new_rec in enumerate(new_records): # Convert relative path to absolute path relpath = new_rec['spectrum'] if relpath.startswith('$'): abspath = os.popen('echo {}'.format(relpath.split('/')[0])).read()[:-1] if abspath: new_rec['spectrum'] = relpath.replace(relpath.split('/')[0], abspath) # Test if the file exists and try to pull metadata from the FITS header if os.path.isfile(new_rec['spectrum']): new_records[n]['spectrum'] = relpath new_records[n] = _autofill_spec_record(new_rec) else: print('Error adding the spectrum at {}'.format(new_rec['spectrum'])) del_records.append(n) # Remove bad records from the table new_records.remove_rows(del_records) # For images, try to populate the table by reading the FITS header if table.lower() == 'images': for n, new_rec in enumerate(new_records): # Convert relative path to absolute path relpath = new_rec['image'] if relpath.startswith('$'): abspath = os.popen('echo {}'.format(relpath.split('/')[0])).read()[:-1] if abspath: new_rec['image'] = relpath.replace(relpath.split('/')[0], abspath) # Test if the file exists and try to pull metadata from the FITS header if os.path.isfile(new_rec['image']): new_records[n]['image'] = relpath new_records[n] = _autofill_spec_record(new_rec) else: print('Error adding the image at {}'.format(new_rec['image'])) del_records.append(n) # Remove bad records from the table new_records.remove_rows(del_records) # Get some new row ids for the good records rowids = self._lowest_rowids(table, len(new_records)) # Add the new records keepers, rejects = [], [] for N, new_rec in enumerate(new_records): new_rec = list(new_rec) new_rec[0] = rowids[N] for n, col in enumerate(new_rec): if type(col) == np.int64 and sys.version_info[0] >= 3: # Fix for Py3 and sqlite3 issue with numpy types new_rec[n] = col.item() if type(col) == np.ma.core.MaskedConstant: new_rec[n] = None try: self.modify("INSERT INTO {} VALUES({})".format(table, ','.join('?'*len(columns))), new_rec, verbose=verbose) keepers.append(N) except IOError: rejects.append(N) new_records[N]['id'] = rowids[N] # Make tables of keepers and rejects rejected = new_records[rejects] new_records = new_records[keepers] # Print a table of the new records or bad news if new_records: print("\033[1;32m{} new records added to the {} table.\033[1;m".format(len(new_records), table.upper())) new_records.pprint() if rejected: print("\033[1;31m{} records rejected from the {} table.\033[1;m".format(len(rejected), table.upper())) rejected.pprint() # Run table clean up if clean_up: self.clean_up(table, verbose) else: print('Please check your input: {}'.format(entry))
[ "def", "add_data", "(", "self", ",", "data", ",", "table", ",", "delimiter", "=", "'|'", ",", "bands", "=", "''", ",", "clean_up", "=", "True", ",", "rename_columns", "=", "{", "}", ",", "column_fill", "=", "{", "}", ",", "verbose", "=", "False", "...
Adds data to the specified database table. Column names must match table fields to insert, however order and completeness don't matter. Parameters ---------- data: str, array-like, astropy.table.Table The path to an ascii file, array-like object, or table. The first row or element must be the list of column names table: str The name of the table into which the data should be inserted delimiter: str The string to use as the delimiter when parsing the ascii file bands: sequence Sequence of band to look for in the data header when digesting columns of multiple photometric measurements (e.g. ['MKO_J','MKO_H','MKO_K']) into individual rows of data for database insertion clean_up: bool Run self.clean_up() rename_columns: dict A dictionary of the {input_col_name:desired_col_name} for table columns, e.g. {'e_Jmag':'J_unc', 'RAJ2000':'ra'} column_fill: dict A dictionary of the column name and value to fill, e.g. {'instrument_id':2, 'band':'2MASS.J'} verbose: bool Print diagnostic messages
[ "Adds", "data", "to", "the", "specified", "database", "table", ".", "Column", "names", "must", "match", "table", "fields", "to", "insert", "however", "order", "and", "completeness", "don", "t", "matter", ".", "Parameters", "----------", "data", ":", "str", "...
python
train
46.887805
FujiMakoto/IPS-Vagrant
ips_vagrant/commands/setup/__init__.py
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/commands/setup/__init__.py#L20-L201
def cli(ctx): """ Run setup after a fresh Vagrant installation. """ log = logging.getLogger('ipsv.setup') assert isinstance(ctx, Context) lock_path = os.path.join(ctx.config.get('Paths', 'Data'), 'setup.lck') if os.path.exists(lock_path): raise Exception('Setup is locked, please remove the setup lock file to continue') # Create our package directories p = Echo('Creating IPS Vagrant system directories...') dirs = ['/etc/ipsv', ctx.config.get('Paths', 'Data'), ctx.config.get('Paths', 'Log'), ctx.config.get('Paths', 'NginxSitesAvailable'), ctx.config.get('Paths', 'NginxSitesEnabled'), ctx.config.get('Paths', 'NginxSSL')] for d in dirs: if not os.path.exists(d): os.makedirs(d, 0o755) p.done() p = Echo('Copying IPS Vagrant configuration files...') with open('/etc/ipsv/ipsv.conf', 'w+') as f: ctx.config.write(f) p.done() # Set up alembic alembic_cfg = Config(os.path.join(ctx.basedir, 'alembic.ini')) alembic_cfg.set_main_option("script_location", os.path.join(ctx.basedir, 'migrations')) alembic_cfg.set_main_option("sqlalchemy.url", "sqlite:////{path}" .format(path=os.path.join(ctx.config.get('Paths', 'Data'), 'sites.db'))) command.current(alembic_cfg) command.downgrade(alembic_cfg, 'base') command.upgrade(alembic_cfg, 'head') # Update the system p = Echo('Updating package cache...') cache = apt.Cache() cache.update() cache.open(None) p.done() p = Echo('Upgrading system packages...') cache.upgrade() cache.commit() p.done() # Install our required packages requirements = ['nginx', 'php5-fpm', 'php5-curl', 'php5-gd', 'php5-imagick', 'php5-json', 'php5-mysql', 'php5-readline', 'php5-apcu', 'php5-xdebug'] for requirement in requirements: # Make sure the package is available p = Echo('Marking package {pkg} for installation'.format(pkg=requirement)) if requirement not in cache: log.warn('Required package {pkg} not available'.format(pkg=requirement)) p.done(p.FAIL) continue # Mark the package for installation cache[requirement].mark_install() p.done() log.info('Committing package cache') p = Echo('Downloading and installing packages...') cache.commit() p.done() # Disable the default server block p = Echo('Configuring Nginx...') default_available = os.path.join(ctx.config.get('Paths', 'NginxSitesAvailable'), 'default') default_enabled = os.path.join(ctx.config.get('Paths', 'NginxSitesEnabled'), 'default') if os.path.isfile(default_available): os.remove(default_available) if os.path.islink(default_enabled): os.unlink(default_enabled) p.done() # Restart Nginx FNULL = open(os.devnull, 'w') p = Echo('Restarting Nginx...') subprocess.check_call(['service', 'nginx', 'restart'], stdout=FNULL, stderr=subprocess.STDOUT) p.done() # php.ini configuration p = Echo('Configuring php...') with open('/etc/php5/fpm/php.ini', 'a') as f: f.write('\n[XDebug]') f.write('\nxdebug.cli_color=1') temp_fh, temp_path = mkstemp() with open(temp_path, 'w') as nf: with open('/etc/php5/fpm/php.ini') as of: # Configuration options we are replacing upload_max_filesize = re.compile( '^upload_max_filesize\s+=\s+(\d+[a-zA-Z])\s*$' ) post_max_size = re.compile( '^post_max_size\s+=\s+(\d+[a-zA-Z])\s*$' ) for line in of: match = upload_max_filesize.match( line ) if upload_max_filesize is not True else False if match: nf.write( 'upload_max_filesize = 1000M\n' ) upload_max_filesize = True continue match = post_max_size.match( line ) if post_max_size is not True else False if match: nf.write( 'post_max_size = 1000M\n' ) post_max_size = True continue nf.write(line) os.close(temp_fh) os.remove('/etc/php5/fpm/php.ini') shutil.move(temp_path, '/etc/php5/fpm/php.ini') os.chmod('/etc/php5/fpm/php.ini', 0o644) p.done() # php5-fpm configuration p = Echo('Configuring php5-fpm...') if os.path.isfile('/etc/php5/fpm/pool.d/www.conf'): os.remove('/etc/php5/fpm/pool.d/www.conf') fpm_config = FpmPoolConfig().template with open('/etc/php5/fpm/pool.d/ips.conf', 'w') as f: f.write(fpm_config) p.done() # Restart php5-fpm p = Echo('Restarting php5-fpm...') subprocess.check_call(['service', 'php5-fpm', 'restart'], stdout=FNULL, stderr=subprocess.STDOUT) p.done() # Copy the man pages and rebuild the manual database p = Echo('Writing manual pages...') man_path = os.path.join(ctx.basedir, 'man', 'ipsv.1') sys_man_path = '/usr/local/share/man/man1' if not os.path.exists(sys_man_path): os.makedirs(sys_man_path) shutil.copyfile(man_path, os.path.join(sys_man_path, 'ipsv.1')) subprocess.check_call(['mandb'], stdout=FNULL, stderr=subprocess.STDOUT) # Enable the welcome message log.debug('Writing welcome message') wm_header = '## DO NOT REMOVE :: AUTOMATICALLY GENERATED BY IPSV ##' wm_remove = False # Remove old profile data for line in fileinput.input('/etc/profile', inplace=True): # Header / footer match? if line == wm_header: # Footer match (Stop removing) if wm_remove: wm_remove = False continue # Header match (Start removing) wm_remove = True continue # Removing lines? if wm_remove: continue # Print line and continue as normal sys.stdout.write(line) # Write new profile data with open('/etc/profile', 'a') as f: f.write("\n" + wm_header + "\n") fl_lock_path = os.path.join(ctx.config.get('Paths', 'Data'), 'first_login.lck') f.write('if [ ! -f "{lp}" ]; then'.format(lp=fl_lock_path) + "\n") f.write(' less "{wp}"'.format(wp=os.path.join(ctx.basedir, 'WELCOME.rst')) + "\n") f.write(' sudo touch "{lp}"'.format(lp=fl_lock_path) + "\n") f.write('fi' + "\n") f.write(wm_header + "\n") p.done() log.debug('Writing setup lock file') with open(os.path.join(ctx.config.get('Paths', 'Data'), 'setup.lck'), 'w') as f: f.write('1')
[ "def", "cli", "(", "ctx", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "'ipsv.setup'", ")", "assert", "isinstance", "(", "ctx", ",", "Context", ")", "lock_path", "=", "os", ".", "path", ".", "join", "(", "ctx", ".", "config", ".", "get", ...
Run setup after a fresh Vagrant installation.
[ "Run", "setup", "after", "a", "fresh", "Vagrant", "installation", "." ]
python
train
35.510989
scottrice/pysteam
pysteam/winutils.py
https://github.com/scottrice/pysteam/blob/1eb2254b5235a053a953e596fa7602d0b110245d/pysteam/winutils.py#L10-L20
def find_steam_location(): """ Finds the location of the current Steam installation on Windows machines. Returns None for any non-Windows machines, or for Windows machines where Steam is not installed. """ if registry is None: return None key = registry.CreateKey(registry.HKEY_CURRENT_USER,"Software\Valve\Steam") return registry.QueryValueEx(key,"SteamPath")[0]
[ "def", "find_steam_location", "(", ")", ":", "if", "registry", "is", "None", ":", "return", "None", "key", "=", "registry", ".", "CreateKey", "(", "registry", ".", "HKEY_CURRENT_USER", ",", "\"Software\\Valve\\Steam\"", ")", "return", "registry", ".", "QueryValu...
Finds the location of the current Steam installation on Windows machines. Returns None for any non-Windows machines, or for Windows machines where Steam is not installed.
[ "Finds", "the", "location", "of", "the", "current", "Steam", "installation", "on", "Windows", "machines", ".", "Returns", "None", "for", "any", "non", "-", "Windows", "machines", "or", "for", "Windows", "machines", "where", "Steam", "is", "not", "installed", ...
python
train
34
SiLab-Bonn/pyBAR
pybar/utils/utils.py
https://github.com/SiLab-Bonn/pyBAR/blob/5ad95bbcd41cd358825823fb78f396cfce23593e/pybar/utils/utils.py#L285-L291
def get_float_time(): '''returns time as double precision floats - Time64 in pytables - mapping to and from python datetime's ''' t1 = time.time() t2 = datetime.datetime.fromtimestamp(t1) return time.mktime(t2.timetuple()) + 1e-6 * t2.microsecond
[ "def", "get_float_time", "(", ")", ":", "t1", "=", "time", ".", "time", "(", ")", "t2", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "t1", ")", "return", "time", ".", "mktime", "(", "t2", ".", "timetuple", "(", ")", ")", "+", "1e-6"...
returns time as double precision floats - Time64 in pytables - mapping to and from python datetime's
[ "returns", "time", "as", "double", "precision", "floats", "-", "Time64", "in", "pytables", "-", "mapping", "to", "and", "from", "python", "datetime", "s" ]
python
train
38.142857
TrafficSenseMSD/SumoTools
traci/_vehicle.py
https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/traci/_vehicle.py#L936-L957
def rerouteTraveltime(self, vehID, currentTravelTimes=True): """rerouteTraveltime(string, bool) -> None Reroutes a vehicle. If currentTravelTimes is True (default) then the current traveltime of the edges is loaded and used for rerouting. If currentTravelTimes is False custom travel times are used. The various functions and options for customizing travel times are described at http://sumo.dlr.de/wiki/Simulation/Routing When rerouteTraveltime has been called once with option currentTravelTimes=True, all edge weights are set to the current travel times at the time of that call (even for subsequent simulation steps). """ if currentTravelTimes: time = self._connection.simulation.getCurrentTime() if time != self.LAST_TRAVEL_TIME_UPDATE: self.LAST_TRAVEL_TIME_UPDATE = time for edge in self._connection.edge.getIDList(): self._connection.edge.adaptTraveltime( edge, self._connection.edge.getTraveltime(edge)) self._connection._beginMessage( tc.CMD_SET_VEHICLE_VARIABLE, tc.CMD_REROUTE_TRAVELTIME, vehID, 1 + 4) self._connection._string += struct.pack("!Bi", tc.TYPE_COMPOUND, 0) self._connection._sendExact()
[ "def", "rerouteTraveltime", "(", "self", ",", "vehID", ",", "currentTravelTimes", "=", "True", ")", ":", "if", "currentTravelTimes", ":", "time", "=", "self", ".", "_connection", ".", "simulation", ".", "getCurrentTime", "(", ")", "if", "time", "!=", "self",...
rerouteTraveltime(string, bool) -> None Reroutes a vehicle. If currentTravelTimes is True (default) then the current traveltime of the edges is loaded and used for rerouting. If currentTravelTimes is False custom travel times are used. The various functions and options for customizing travel times are described at http://sumo.dlr.de/wiki/Simulation/Routing When rerouteTraveltime has been called once with option currentTravelTimes=True, all edge weights are set to the current travel times at the time of that call (even for subsequent simulation steps).
[ "rerouteTraveltime", "(", "string", "bool", ")", "-", ">", "None", "Reroutes", "a", "vehicle", ".", "If", "currentTravelTimes", "is", "True", "(", "default", ")", "then", "the", "current", "traveltime", "of", "the", "edges", "is", "loaded", "and", "used", ...
python
train
59.454545
googleapis/google-cloud-python
datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py#L119-L127
def example_path(cls, project, dataset, annotated_dataset, example): """Return a fully-qualified example string.""" return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}/examples/{example}", project=project, dataset=dataset, annotated_dataset=annotated_dataset, example=example, )
[ "def", "example_path", "(", "cls", ",", "project", ",", "dataset", ",", "annotated_dataset", ",", "example", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_da...
Return a fully-qualified example string.
[ "Return", "a", "fully", "-", "qualified", "example", "string", "." ]
python
train
47.111111
tariqdaouda/pyGeno
pyGeno/bootstrap.py
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/bootstrap.py#L19-L47
def printRemoteDatawraps(location = conf.pyGeno_REMOTE_LOCATION) : """ print all available datawraps from a remote location the location must have a datawraps.json in the following format:: { "Ordered": { "Reference genomes": { "Human" : ["GRCh37.75", "GRCh38.78"], "Mouse" : ["GRCm38.78"], }, "SNPs":{ } }, "Flat":{ "Reference genomes": { "GRCh37.75": "Human.GRCh37.75.tar.gz", "GRCh38.78": "Human.GRCh37.75.tar.gz", "GRCm38.78": "Mouse.GRCm38.78.tar.gz" }, "SNPs":{ } } } """ l = listRemoteDatawraps(location) printf("Available datawraps for bootstraping\n") print json.dumps(l["Ordered"], sort_keys=True, indent=4, separators=(',', ': '))
[ "def", "printRemoteDatawraps", "(", "location", "=", "conf", ".", "pyGeno_REMOTE_LOCATION", ")", ":", "l", "=", "listRemoteDatawraps", "(", "location", ")", "printf", "(", "\"Available datawraps for bootstraping\\n\"", ")", "print", "json", ".", "dumps", "(", "l", ...
print all available datawraps from a remote location the location must have a datawraps.json in the following format:: { "Ordered": { "Reference genomes": { "Human" : ["GRCh37.75", "GRCh38.78"], "Mouse" : ["GRCm38.78"], }, "SNPs":{ } }, "Flat":{ "Reference genomes": { "GRCh37.75": "Human.GRCh37.75.tar.gz", "GRCh38.78": "Human.GRCh37.75.tar.gz", "GRCm38.78": "Mouse.GRCm38.78.tar.gz" }, "SNPs":{ } } }
[ "print", "all", "available", "datawraps", "from", "a", "remote", "location", "the", "location", "must", "have", "a", "datawraps", ".", "json", "in", "the", "following", "format", "::" ]
python
train
24.172414
dmlc/gluon-nlp
scripts/bert/fp16_utils.py
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/fp16_utils.py#L236-L253
def update_scale(self, overflow): """dynamically update loss scale""" iter_since_rescale = self._num_steps - self._last_rescale_iter if overflow: self._last_overflow_iter = self._num_steps self._overflows_since_rescale += 1 percentage = self._overflows_since_rescale / float(iter_since_rescale) # we tolerate a certrain amount of NaNs before actually scaling it down if percentage >= self.tolerance: self.loss_scale /= self.scale_factor self._last_rescale_iter = self._num_steps self._overflows_since_rescale = 0 logging.info('DynamicLossScaler: overflow detected. set loss_scale = %s', self.loss_scale) elif (self._num_steps - self._last_overflow_iter) % self.scale_window == 0: self.loss_scale *= self.scale_factor self._last_rescale_iter = self._num_steps self._num_steps += 1
[ "def", "update_scale", "(", "self", ",", "overflow", ")", ":", "iter_since_rescale", "=", "self", ".", "_num_steps", "-", "self", ".", "_last_rescale_iter", "if", "overflow", ":", "self", ".", "_last_overflow_iter", "=", "self", ".", "_num_steps", "self", ".",...
dynamically update loss scale
[ "dynamically", "update", "loss", "scale" ]
python
train
54.388889
pysal/spglm
spglm/family.py
https://github.com/pysal/spglm/blob/1339898adcb7e1638f1da83d57aa37392525f018/spglm/family.py#L800-L831
def deviance(self, endog, mu, freq_weights=1, scale=1., axis=None): r''' Deviance function for either Bernoulli or Binomial data. Parameters ---------- endog : array-like Endogenous response variable (already transformed to a probability if appropriate). mu : array Fitted mean response variable freq_weights : array-like 1d array of frequency weights. The default is 1. scale : float, optional An optional scale argument. The default is 1. Returns -------- deviance : float The deviance function as defined below ''' if np.shape(self.n) == () and self.n == 1: one = np.equal(endog, 1) return -2 * np.sum((one * np.log(mu + 1e-200) + (1-one) * np.log(1 - mu + 1e-200)) * freq_weights, axis=axis) else: return 2 * np.sum(self.n * freq_weights * (endog * np.log(endog/mu + 1e-200) + (1 - endog) * np.log((1 - endog) / (1 - mu) + 1e-200)), axis=axis)
[ "def", "deviance", "(", "self", ",", "endog", ",", "mu", ",", "freq_weights", "=", "1", ",", "scale", "=", "1.", ",", "axis", "=", "None", ")", ":", "if", "np", ".", "shape", "(", "self", ".", "n", ")", "==", "(", ")", "and", "self", ".", "n"...
r''' Deviance function for either Bernoulli or Binomial data. Parameters ---------- endog : array-like Endogenous response variable (already transformed to a probability if appropriate). mu : array Fitted mean response variable freq_weights : array-like 1d array of frequency weights. The default is 1. scale : float, optional An optional scale argument. The default is 1. Returns -------- deviance : float The deviance function as defined below
[ "r", "Deviance", "function", "for", "either", "Bernoulli", "or", "Binomial", "data", "." ]
python
train
36.34375
CalebBell/fluids
fluids/jet_pump.py
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/jet_pump.py#L33-L163
def liquid_jet_pump_ancillary(rhop, rhos, Kp, Ks, d_nozzle=None, d_mixing=None, Qp=None, Qs=None, P1=None, P2=None): r'''Calculates the remaining variable in a liquid jet pump when solving for one if the inlet variables only and the rest of them are known. The equation comes from conservation of energy and momentum in the mixing chamber. The variable to be solved for must be one of `d_nozzle`, `d_mixing`, `Qp`, `Qs`, `P1`, or `P2`. .. math:: P_1 - P_2 = \frac{1}{2}\rho_pV_n^2(1+K_p) - \frac{1}{2}\rho_s V_3^2(1+K_s) Rearrange to express V3 in terms of Vn, and using the density ratio `C`, the expression becomes: .. math:: P_1 - P_2 = \frac{1}{2}\rho_p V_n^2\left[(1+K_p) - C(1+K_s) \left(\frac{MR}{1-R}\right)^2\right] Using the primary nozzle area and flow rate: .. math:: P_1 - P_2 = \frac{1}{2}\rho_p \left(\frac{Q_p}{A_n}\right)^2 \left[(1+K_p) - C(1+K_s) \left(\frac{MR}{1-R}\right)^2\right] For `P`, `P2`, `Qs`, and `Qp`, the equation can be rearranged explicitly for them. For `d_mixing` and `d_nozzle`, a bounded solver is used searching between 1E-9 m and 20 times the other diameter which was specified. Parameters ---------- rhop : float The density of the primary (motive) fluid, [kg/m^3] rhos : float The density of the secondary fluid (drawn from the vacuum chamber), [kg/m^3] Kp : float The primary nozzle loss coefficient, [-] Ks : float The secondary inlet loss coefficient, [-] d_nozzle : float, optional The inside diameter of the primary fluid's nozle, [m] d_mixing : float, optional The diameter of the mixing chamber, [m] Qp : float, optional The volumetric flow rate of the primary fluid, [m^3/s] Qs : float, optional The volumetric flow rate of the secondary fluid, [m^3/s] P1 : float, optional The pressure of the primary fluid entering its nozzle, [Pa] P2 : float, optional The pressure of the secondary fluid at the entry of the ejector, [Pa] Returns ------- solution : float The parameter not specified (one of `d_nozzle`, `d_mixing`, `Qp`, `Qs`, `P1`, or `P2`), (units of `m`, `m`, `m^3/s`, `m^3/s`, `Pa`, or `Pa` respectively) Notes ----- The following SymPy code was used to obtain the analytical formulas ( they are not shown here due to their length): >>> from sympy import * >>> A_nozzle, A_mixing, Qs, Qp, P1, P2, rhos, rhop, Ks, Kp = symbols('A_nozzle, A_mixing, Qs, Qp, P1, P2, rhos, rhop, Ks, Kp') >>> R = A_nozzle/A_mixing >>> M = Qs/Qp >>> C = rhos/rhop >>> rhs = rhop/2*(Qp/A_nozzle)**2*((1+Kp) - C*(1 + Ks)*((M*R)/(1-R))**2 ) >>> new = Eq(P1 - P2, rhs) >>> #solve(new, Qp) >>> #solve(new, Qs) >>> #solve(new, P1) >>> #solve(new, P2) Examples -------- Calculating primary fluid nozzle inlet pressure P1: >>> liquid_jet_pump_ancillary(rhop=998., rhos=1098., Ks=0.11, Kp=.04, ... P2=133600, Qp=0.01, Qs=0.01, d_mixing=0.045, d_nozzle=0.02238) 426434.60314398084 References ---------- .. [1] Ejectors and Jet Pumps. Design and Performance for Incompressible Liquid Flow. 85032. ESDU International PLC, 1985. ''' unknowns = sum(i is None for i in (d_nozzle, d_mixing, Qs, Qp, P1, P2)) if unknowns > 1: raise Exception('Too many unknowns') elif unknowns < 1: raise Exception('Overspecified') C = rhos/rhop if Qp is not None and Qs is not None: M = Qs/Qp if d_nozzle is not None: A_nozzle = pi/4*d_nozzle*d_nozzle if d_mixing is not None: A_mixing = pi/4*d_mixing*d_mixing R = A_nozzle/A_mixing if P1 is None: return rhop/2*(Qp/A_nozzle)**2*((1+Kp) - C*(1 + Ks)*((M*R)/(1-R))**2 ) + P2 elif P2 is None: return -rhop/2*(Qp/A_nozzle)**2*((1+Kp) - C*(1 + Ks)*((M*R)/(1-R))**2 ) + P1 elif Qs is None: try: return ((-2*A_nozzle**2*P1 + 2*A_nozzle**2*P2 + Kp*Qp**2*rhop + Qp**2*rhop)/(C*rhop*(Ks + 1)))**0.5*(A_mixing - A_nozzle)/A_nozzle except ValueError: return -1j elif Qp is None: return A_nozzle*((2*A_mixing**2*P1 - 2*A_mixing**2*P2 - 4*A_mixing*A_nozzle*P1 + 4*A_mixing*A_nozzle*P2 + 2*A_nozzle**2*P1 - 2*A_nozzle**2*P2 + C*Ks*Qs**2*rhop + C*Qs**2*rhop)/(rhop*(Kp + 1)))**0.5/(A_mixing - A_nozzle) elif d_nozzle is None: def err(d_nozzle): return P1 - liquid_jet_pump_ancillary(rhop=rhop, rhos=rhos, Kp=Kp, Ks=Ks, d_nozzle=d_nozzle, d_mixing=d_mixing, Qp=Qp, Qs=Qs, P1=None, P2=P2) return brenth(err, 1E-9, d_mixing*20) elif d_mixing is None: def err(d_mixing): return P1 - liquid_jet_pump_ancillary(rhop=rhop, rhos=rhos, Kp=Kp, Ks=Ks, d_nozzle=d_nozzle, d_mixing=d_mixing, Qp=Qp, Qs=Qs, P1=None, P2=P2) try: return brenth(err, 1E-9, d_nozzle*20) except: return newton(err, d_nozzle*2)
[ "def", "liquid_jet_pump_ancillary", "(", "rhop", ",", "rhos", ",", "Kp", ",", "Ks", ",", "d_nozzle", "=", "None", ",", "d_mixing", "=", "None", ",", "Qp", "=", "None", ",", "Qs", "=", "None", ",", "P1", "=", "None", ",", "P2", "=", "None", ")", "...
r'''Calculates the remaining variable in a liquid jet pump when solving for one if the inlet variables only and the rest of them are known. The equation comes from conservation of energy and momentum in the mixing chamber. The variable to be solved for must be one of `d_nozzle`, `d_mixing`, `Qp`, `Qs`, `P1`, or `P2`. .. math:: P_1 - P_2 = \frac{1}{2}\rho_pV_n^2(1+K_p) - \frac{1}{2}\rho_s V_3^2(1+K_s) Rearrange to express V3 in terms of Vn, and using the density ratio `C`, the expression becomes: .. math:: P_1 - P_2 = \frac{1}{2}\rho_p V_n^2\left[(1+K_p) - C(1+K_s) \left(\frac{MR}{1-R}\right)^2\right] Using the primary nozzle area and flow rate: .. math:: P_1 - P_2 = \frac{1}{2}\rho_p \left(\frac{Q_p}{A_n}\right)^2 \left[(1+K_p) - C(1+K_s) \left(\frac{MR}{1-R}\right)^2\right] For `P`, `P2`, `Qs`, and `Qp`, the equation can be rearranged explicitly for them. For `d_mixing` and `d_nozzle`, a bounded solver is used searching between 1E-9 m and 20 times the other diameter which was specified. Parameters ---------- rhop : float The density of the primary (motive) fluid, [kg/m^3] rhos : float The density of the secondary fluid (drawn from the vacuum chamber), [kg/m^3] Kp : float The primary nozzle loss coefficient, [-] Ks : float The secondary inlet loss coefficient, [-] d_nozzle : float, optional The inside diameter of the primary fluid's nozle, [m] d_mixing : float, optional The diameter of the mixing chamber, [m] Qp : float, optional The volumetric flow rate of the primary fluid, [m^3/s] Qs : float, optional The volumetric flow rate of the secondary fluid, [m^3/s] P1 : float, optional The pressure of the primary fluid entering its nozzle, [Pa] P2 : float, optional The pressure of the secondary fluid at the entry of the ejector, [Pa] Returns ------- solution : float The parameter not specified (one of `d_nozzle`, `d_mixing`, `Qp`, `Qs`, `P1`, or `P2`), (units of `m`, `m`, `m^3/s`, `m^3/s`, `Pa`, or `Pa` respectively) Notes ----- The following SymPy code was used to obtain the analytical formulas ( they are not shown here due to their length): >>> from sympy import * >>> A_nozzle, A_mixing, Qs, Qp, P1, P2, rhos, rhop, Ks, Kp = symbols('A_nozzle, A_mixing, Qs, Qp, P1, P2, rhos, rhop, Ks, Kp') >>> R = A_nozzle/A_mixing >>> M = Qs/Qp >>> C = rhos/rhop >>> rhs = rhop/2*(Qp/A_nozzle)**2*((1+Kp) - C*(1 + Ks)*((M*R)/(1-R))**2 ) >>> new = Eq(P1 - P2, rhs) >>> #solve(new, Qp) >>> #solve(new, Qs) >>> #solve(new, P1) >>> #solve(new, P2) Examples -------- Calculating primary fluid nozzle inlet pressure P1: >>> liquid_jet_pump_ancillary(rhop=998., rhos=1098., Ks=0.11, Kp=.04, ... P2=133600, Qp=0.01, Qs=0.01, d_mixing=0.045, d_nozzle=0.02238) 426434.60314398084 References ---------- .. [1] Ejectors and Jet Pumps. Design and Performance for Incompressible Liquid Flow. 85032. ESDU International PLC, 1985.
[ "r", "Calculates", "the", "remaining", "variable", "in", "a", "liquid", "jet", "pump", "when", "solving", "for", "one", "if", "the", "inlet", "variables", "only", "and", "the", "rest", "of", "them", "are", "known", ".", "The", "equation", "comes", "from", ...
python
train
39.21374
thefactory/marathon-python
marathon/models/constraint.py
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/constraint.py#L45-L57
def from_json(cls, obj): """Construct a MarathonConstraint from a parsed response. :param dict attributes: object attributes from parsed response :rtype: :class:`MarathonConstraint` """ if len(obj) == 2: (field, operator) = obj return cls(field, operator) if len(obj) > 2: (field, operator, value) = obj return cls(field, operator, value)
[ "def", "from_json", "(", "cls", ",", "obj", ")", ":", "if", "len", "(", "obj", ")", "==", "2", ":", "(", "field", ",", "operator", ")", "=", "obj", "return", "cls", "(", "field", ",", "operator", ")", "if", "len", "(", "obj", ")", ">", "2", "...
Construct a MarathonConstraint from a parsed response. :param dict attributes: object attributes from parsed response :rtype: :class:`MarathonConstraint`
[ "Construct", "a", "MarathonConstraint", "from", "a", "parsed", "response", "." ]
python
train
32.615385
davidfokkema/artist
artist/plot.py
https://github.com/davidfokkema/artist/blob/26ae7987522622710f2910980770c50012fda47d/artist/plot.py#L460-L481
def scatter_table(self, x, y, c, s, mark='*'): """Add a data series to the plot. :param x: array containing x-values. :param y: array containing y-values. :param c: array containing values for the color of the mark. :param s: array containing values for the size of the mark. :param mark: the symbol used to mark the data point. May be None, or any plot mark accepted by TikZ (e.g. ``*, x, +, o, square, triangle``). The dimensions of x, y, c and s should be equal. The c values will be mapped to a colormap. """ # clear the background of the marks # self._clear_plot_mark_background(x, y, mark, markstyle) # draw the plot series over the background options = self._parse_plot_options(mark) s = [sqrt(si) for si in s] plot_series = self._create_plot_tables_object(x, y, c, s, options) self.plot_table_list.append(plot_series)
[ "def", "scatter_table", "(", "self", ",", "x", ",", "y", ",", "c", ",", "s", ",", "mark", "=", "'*'", ")", ":", "# clear the background of the marks", "# self._clear_plot_mark_background(x, y, mark, markstyle)", "# draw the plot series over the background", "options", "="...
Add a data series to the plot. :param x: array containing x-values. :param y: array containing y-values. :param c: array containing values for the color of the mark. :param s: array containing values for the size of the mark. :param mark: the symbol used to mark the data point. May be None, or any plot mark accepted by TikZ (e.g. ``*, x, +, o, square, triangle``). The dimensions of x, y, c and s should be equal. The c values will be mapped to a colormap.
[ "Add", "a", "data", "series", "to", "the", "plot", "." ]
python
train
43.636364
ellmetha/django-machina
machina/core/loading.py
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/core/loading.py#L62-L79
def _import_module(module_path, classnames): """ Tries to import the given Python module path. """ try: imported_module = __import__(module_path, fromlist=classnames) return imported_module except ImportError: # In case of an ImportError, the module being loaded generally does not exist. But an # ImportError can occur if the module being loaded exists and another import located inside # it failed. # # In order to provide a meaningfull traceback, the execution information can be inspected in # order to determine which case to consider. If the execution information provides more than # a certain amount of frames, this means that an ImportError occured while loading the # initial Python module. __, __, exc_traceback = sys.exc_info() frames = traceback.extract_tb(exc_traceback) if len(frames) > 1: raise
[ "def", "_import_module", "(", "module_path", ",", "classnames", ")", ":", "try", ":", "imported_module", "=", "__import__", "(", "module_path", ",", "fromlist", "=", "classnames", ")", "return", "imported_module", "except", "ImportError", ":", "# In case of an Impor...
Tries to import the given Python module path.
[ "Tries", "to", "import", "the", "given", "Python", "module", "path", "." ]
python
train
51.166667
msoulier/tftpy
tftpy/TftpStates.py
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpStates.py#L82-L111
def sendDAT(self): """This method sends the next DAT packet based on the data in the context. It returns a boolean indicating whether the transfer is finished.""" finished = False blocknumber = self.context.next_block # Test hook if DELAY_BLOCK and DELAY_BLOCK == blocknumber: import time log.debug("Deliberately delaying 10 seconds...") time.sleep(10) dat = None blksize = self.context.getBlocksize() buffer = self.context.fileobj.read(blksize) log.debug("Read %d bytes into buffer", len(buffer)) if len(buffer) < blksize: log.info("Reached EOF on file %s" % self.context.file_to_transfer) finished = True dat = TftpPacketDAT() dat.data = buffer dat.blocknumber = blocknumber self.context.metrics.bytes += len(dat.data) log.debug("Sending DAT packet %d", dat.blocknumber) self.context.sock.sendto(dat.encode().buffer, (self.context.host, self.context.tidport)) if self.context.packethook: self.context.packethook(dat) self.context.last_pkt = dat return finished
[ "def", "sendDAT", "(", "self", ")", ":", "finished", "=", "False", "blocknumber", "=", "self", ".", "context", ".", "next_block", "# Test hook", "if", "DELAY_BLOCK", "and", "DELAY_BLOCK", "==", "blocknumber", ":", "import", "time", "log", ".", "debug", "(", ...
This method sends the next DAT packet based on the data in the context. It returns a boolean indicating whether the transfer is finished.
[ "This", "method", "sends", "the", "next", "DAT", "packet", "based", "on", "the", "data", "in", "the", "context", ".", "It", "returns", "a", "boolean", "indicating", "whether", "the", "transfer", "is", "finished", "." ]
python
train
40.733333
knipknap/SpiffWorkflow
SpiffWorkflow/bpmn/parser/BpmnParser.py
https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/parser/BpmnParser.py#L119-L128
def add_bpmn_files(self, filenames): """ Add all filenames in the given list to the parser's set. """ for filename in filenames: f = open(filename, 'r') try: self.add_bpmn_xml(ET.parse(f), filename=filename) finally: f.close()
[ "def", "add_bpmn_files", "(", "self", ",", "filenames", ")", ":", "for", "filename", "in", "filenames", ":", "f", "=", "open", "(", "filename", ",", "'r'", ")", "try", ":", "self", ".", "add_bpmn_xml", "(", "ET", ".", "parse", "(", "f", ")", ",", "...
Add all filenames in the given list to the parser's set.
[ "Add", "all", "filenames", "in", "the", "given", "list", "to", "the", "parser", "s", "set", "." ]
python
valid
31.7
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_system.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_system.py#L103-L114
def get_system_uptime_output_cmd_error(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_system_uptime = ET.Element("get_system_uptime") config = get_system_uptime output = ET.SubElement(get_system_uptime, "output") cmd_error = ET.SubElement(output, "cmd-error") cmd_error.text = kwargs.pop('cmd_error') callback = kwargs.pop('callback', self._callback) return callback(config)
[ "def", "get_system_uptime_output_cmd_error", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_system_uptime", "=", "ET", ".", "Element", "(", "\"get_system_uptime\"", ")", "config", "=", "get_sys...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
39.583333
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/shuffler.py
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/shuffler.py#L429-L444
def validate(cls, mapper_spec): """Validates mapper specification. Args: mapper_spec: an instance of model.MapperSpec to validate. Raises: BadWriterParamsError: when Output writer class mismatch. """ if mapper_spec.output_writer_class() != cls: raise errors.BadWriterParamsError("Output writer class mismatch") params = output_writers._get_params(mapper_spec) # Bucket Name is required if cls.BUCKET_NAME_PARAM not in params: raise errors.BadWriterParamsError( "%s is required for the _HashingGCSOutputWriter" % cls.BUCKET_NAME_PARAM)
[ "def", "validate", "(", "cls", ",", "mapper_spec", ")", ":", "if", "mapper_spec", ".", "output_writer_class", "(", ")", "!=", "cls", ":", "raise", "errors", ".", "BadWriterParamsError", "(", "\"Output writer class mismatch\"", ")", "params", "=", "output_writers",...
Validates mapper specification. Args: mapper_spec: an instance of model.MapperSpec to validate. Raises: BadWriterParamsError: when Output writer class mismatch.
[ "Validates", "mapper", "specification", "." ]
python
train
37.25
kxgames/kxg
kxg/multiplayer.py
https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/multiplayer.py#L274-L283
def _relay_message(self, message): """ Relay messages from the forum on the server to the client represented by this actor. """ info("relaying message: {message}") if not message.was_sent_by(self._id_factory): self.pipe.send(message) self.pipe.deliver()
[ "def", "_relay_message", "(", "self", ",", "message", ")", ":", "info", "(", "\"relaying message: {message}\"", ")", "if", "not", "message", ".", "was_sent_by", "(", "self", ".", "_id_factory", ")", ":", "self", ".", "pipe", ".", "send", "(", "message", ")...
Relay messages from the forum on the server to the client represented by this actor.
[ "Relay", "messages", "from", "the", "forum", "on", "the", "server", "to", "the", "client", "represented", "by", "this", "actor", "." ]
python
valid
31.8
SUNCAT-Center/CatHub
cathub/reaction_networks.py
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L276-L293
def get_ZPE(viblist): """Returns the zero point energy from a list of frequencies. Parameters ---------- viblist : List of numbers or string of list of numbers. Returns ------- ZPE : Zero point energy in eV. """ if type(viblist) is str: l = ast.literal_eval(viblist) else: l = viblist l = [float(w) for w in l] ZPE = 0.5*sum(l)*cm2ev return(ZPE)
[ "def", "get_ZPE", "(", "viblist", ")", ":", "if", "type", "(", "viblist", ")", "is", "str", ":", "l", "=", "ast", ".", "literal_eval", "(", "viblist", ")", "else", ":", "l", "=", "viblist", "l", "=", "[", "float", "(", "w", ")", "for", "w", "in...
Returns the zero point energy from a list of frequencies. Parameters ---------- viblist : List of numbers or string of list of numbers. Returns ------- ZPE : Zero point energy in eV.
[ "Returns", "the", "zero", "point", "energy", "from", "a", "list", "of", "frequencies", "." ]
python
train
22.111111
SFDO-Tooling/CumulusCI
cumulusci/core/config/BaseTaskFlowConfig.py
https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/core/config/BaseTaskFlowConfig.py#L32-L37
def get_task(self, name): """ Returns a TaskConfig """ config = getattr(self, "tasks__{}".format(name)) if not config: raise TaskNotFoundError("Task not found: {}".format(name)) return TaskConfig(config)
[ "def", "get_task", "(", "self", ",", "name", ")", ":", "config", "=", "getattr", "(", "self", ",", "\"tasks__{}\"", ".", "format", "(", "name", ")", ")", "if", "not", "config", ":", "raise", "TaskNotFoundError", "(", "\"Task not found: {}\"", ".", "format"...
Returns a TaskConfig
[ "Returns", "a", "TaskConfig" ]
python
train
40.333333
JensRantil/rewind
rewind/server/eventstores.py
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L785-L797
def rotate(self): """Rotate the files to disk. This is done by calling `store.close()` on each store, bumping the batchno and reopening the stores using their factories. """ self._logger.info('Rotating data files. New batch number will be: %s', self.batchno + 1) self.estore.close() self.estore = None self.batchno += 1 self.estore = self._open_event_store()
[ "def", "rotate", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Rotating data files. New batch number will be: %s'", ",", "self", ".", "batchno", "+", "1", ")", "self", ".", "estore", ".", "close", "(", ")", "self", ".", "estore", "=", ...
Rotate the files to disk. This is done by calling `store.close()` on each store, bumping the batchno and reopening the stores using their factories.
[ "Rotate", "the", "files", "to", "disk", "." ]
python
train
34.307692
hootnot/postcode-api-wrapper
postcodepy/postcodepy.py
https://github.com/hootnot/postcode-api-wrapper/blob/42359cb9402f84a06f7d58f889f1156d653f5ea9/postcodepy/postcodepy.py#L14-L51
def get_postcodedata(self, postcode, nr, addition="", **params): """get_postcodedata - fetch information for 'postcode'. Parameters ---------- postcode : string The full (dutch) postcode nr : int The housenumber addition : string (optional) the extension to a housenumber params : dict (optional) a list of parameters to send with the request. returns : a response dictionary """ endpoint = 'rest/addresses/%s/%s' % (postcode, nr) if addition: endpoint += '/' + addition retValue = self._API__request(endpoint, params=params) # then it should match the houseNumberAdditions if addition and addition.upper() not in \ [a.upper() for a in retValue['houseNumberAdditions']]: raise PostcodeError( "ERRHouseNumberAdditionInvalid", {"exceptionId": "ERRHouseNumberAdditionInvalid", "exception": "Invalid housenumber addition: '%s'" % retValue['houseNumberAddition'], "validHouseNumberAdditions": retValue['houseNumberAdditions']}) return retValue
[ "def", "get_postcodedata", "(", "self", ",", "postcode", ",", "nr", ",", "addition", "=", "\"\"", ",", "*", "*", "params", ")", ":", "endpoint", "=", "'rest/addresses/%s/%s'", "%", "(", "postcode", ",", "nr", ")", "if", "addition", ":", "endpoint", "+=",...
get_postcodedata - fetch information for 'postcode'. Parameters ---------- postcode : string The full (dutch) postcode nr : int The housenumber addition : string (optional) the extension to a housenumber params : dict (optional) a list of parameters to send with the request. returns : a response dictionary
[ "get_postcodedata", "-", "fetch", "information", "for", "postcode", "." ]
python
train
32.842105
jessamynsmith/pipreq
pipreq/command.py
https://github.com/jessamynsmith/pipreq/blob/4081c1238722166445f58ae57e939207f8a6fb83/pipreq/command.py#L129-L144
def _parse_requirements(self, input): """ Parse a list of requirements specifications. Lines that look like "foobar==1.0" are parsed; all other lines are silently ignored. Returns a tuple of tuples, where each inner tuple is: (package, version) """ results = [] for line in input: (package, version) = self._parse_line(line) if package: results.append((package, version)) return tuple(results)
[ "def", "_parse_requirements", "(", "self", ",", "input", ")", ":", "results", "=", "[", "]", "for", "line", "in", "input", ":", "(", "package", ",", "version", ")", "=", "self", ".", "_parse_line", "(", "line", ")", "if", "package", ":", "results", "...
Parse a list of requirements specifications. Lines that look like "foobar==1.0" are parsed; all other lines are silently ignored. Returns a tuple of tuples, where each inner tuple is: (package, version)
[ "Parse", "a", "list", "of", "requirements", "specifications", ".", "Lines", "that", "look", "like", "foobar", "==", "1", ".", "0", "are", "parsed", ";", "all", "other", "lines", "are", "silently", "ignored", "." ]
python
train
31.625
prompt-toolkit/pyvim
pyvim/window_arrangement.py
https://github.com/prompt-toolkit/pyvim/blob/5928b53b9d700863c1a06d2181a034a955f94594/pyvim/window_arrangement.py#L303-L308
def keep_only_current_window(self): """ Close all other windows, except the current one. """ self.tab_pages = [TabPage(self.active_tab.active_window)] self.active_tab_index = 0
[ "def", "keep_only_current_window", "(", "self", ")", ":", "self", ".", "tab_pages", "=", "[", "TabPage", "(", "self", ".", "active_tab", ".", "active_window", ")", "]", "self", ".", "active_tab_index", "=", "0" ]
Close all other windows, except the current one.
[ "Close", "all", "other", "windows", "except", "the", "current", "one", "." ]
python
train
35.166667
jaredLunde/vital-tools
vital/security/__init__.py
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L31-L52
def aes_b64_encrypt(value, secret, block_size=AES.block_size): """ AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt aes_encrypt("Hello, world", "aLWEFlwgwlreWELFNWEFWLEgwklgbweLKWEBGW") # -> 'zYgVYMbeOuiHR50aMFinY9JsfyMQCvpzI+LNqNcmZhw=' aes_decrypt( "zYgVYMbeOuiHR50aMFinY9JsfyMQCvpzI+LNqNcmZhw=", "aLWEFlwgwlreWELFNWEFWLEgwklgbweLKWEBGW") # -> 'Hello, world' .. """ # iv = randstr(block_size * 2, rng=random) iv = randstr(block_size * 2) cipher = AES.new(secret[:32], AES.MODE_CFB, iv[:block_size].encode()) return iv + b64encode(cipher.encrypt( uniorbytes(value, bytes))).decode('utf-8')
[ "def", "aes_b64_encrypt", "(", "value", ",", "secret", ",", "block_size", "=", "AES", ".", "block_size", ")", ":", "# iv = randstr(block_size * 2, rng=random)", "iv", "=", "randstr", "(", "block_size", "*", "2", ")", "cipher", "=", "AES", ".", "new", "(", "s...
AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt aes_encrypt("Hello, world", "aLWEFlwgwlreWELFNWEFWLEgwklgbweLKWEBGW") # -> 'zYgVYMbeOuiHR50aMFinY9JsfyMQCvpzI+LNqNcmZhw=' aes_decrypt( "zYgVYMbeOuiHR50aMFinY9JsfyMQCvpzI+LNqNcmZhw=", "aLWEFlwgwlreWELFNWEFWLEgwklgbweLKWEBGW") # -> 'Hello, world' ..
[ "AES", "encrypt", "@value", "with", "@secret", "using", "the", "|CFB|", "mode", "of", "AES", "with", "a", "cryptographically", "secure", "initialization", "vector", "." ]
python
train
41.045455
troeger/opensubmit
web/opensubmit/cmdline.py
https://github.com/troeger/opensubmit/blob/384a95b7c6fa41e3f949a129d25dafd9a1c54859/web/opensubmit/cmdline.py#L229-L244
def check_web_config(config_fname): ''' Try to load the Django settings. If this does not work, than settings file does not exist. Returns: Loaded configuration, or None. ''' print("Looking for config file at {0} ...".format(config_fname)) config = RawConfigParser() try: config.readfp(open(config_fname)) return config except IOError: print("ERROR: Seems like the config file does not exist. Please call 'opensubmit-web configcreate' first, or specify a location with the '-c' option.") return None
[ "def", "check_web_config", "(", "config_fname", ")", ":", "print", "(", "\"Looking for config file at {0} ...\"", ".", "format", "(", "config_fname", ")", ")", "config", "=", "RawConfigParser", "(", ")", "try", ":", "config", ".", "readfp", "(", "open", "(", "...
Try to load the Django settings. If this does not work, than settings file does not exist. Returns: Loaded configuration, or None.
[ "Try", "to", "load", "the", "Django", "settings", ".", "If", "this", "does", "not", "work", "than", "settings", "file", "does", "not", "exist", "." ]
python
train
36.0625
saltstack/salt
salt/beacons/__init__.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/__init__.py#L381-L393
def disable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = False # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_disabled_complete') return True
[ "def", "disable_beacons", "(", "self", ")", ":", "self", ".", "opts", "[", "'beacons'", "]", "[", "'enabled'", "]", "=", "False", "# Fire the complete event back along with updated list of beacons", "evt", "=", "salt", ".", "utils", ".", "event", ".", "get_event",...
Enable beacons
[ "Enable", "beacons" ]
python
train
32.692308
ihgazni2/edict
edict/edict.py
https://github.com/ihgazni2/edict/blob/44a08ccc10b196aa3854619b4c51ddb246778a34/edict/edict.py#L921-L940
def _diff_internal(d1,d2): ''' d1 = {'a':'x','b':'y','c':'z'} d2 = {'a':'x','b':'u','d':'v'} _diff_internal(d1,d2) _diff_internald2,d1) ''' same =[] kdiff =[] vdiff = [] for key in d1: value = d1[key] if(key in d2): if(value == d2[key]): same.append(key) else: vdiff.append(key) else: kdiff.append(key) return({'same':same,'kdiff':kdiff,'vdiff':vdiff})
[ "def", "_diff_internal", "(", "d1", ",", "d2", ")", ":", "same", "=", "[", "]", "kdiff", "=", "[", "]", "vdiff", "=", "[", "]", "for", "key", "in", "d1", ":", "value", "=", "d1", "[", "key", "]", "if", "(", "key", "in", "d2", ")", ":", "if"...
d1 = {'a':'x','b':'y','c':'z'} d2 = {'a':'x','b':'u','d':'v'} _diff_internal(d1,d2) _diff_internald2,d1)
[ "d1", "=", "{", "a", ":", "x", "b", ":", "y", "c", ":", "z", "}", "d2", "=", "{", "a", ":", "x", "b", ":", "u", "d", ":", "v", "}", "_diff_internal", "(", "d1", "d2", ")", "_diff_internald2", "d1", ")" ]
python
train
24.25
RJT1990/pyflux
pyflux/families/exponential.py
https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/exponential.py#L251-L275
def neg_loglikelihood(y, mean, scale, shape, skewness): """ Negative loglikelihood function Parameters ---------- y : np.ndarray univariate time series mean : np.ndarray array of location parameters for the Exponential distribution scale : float scale parameter for the Exponential distribution shape : float tail thickness parameter for the Exponential distribution skewness : float skewness parameter for the Exponential distribution Returns ---------- - Negative loglikelihood of the Exponential family """ return -np.sum(ss.expon.logpdf(x=y, scale=1/mean))
[ "def", "neg_loglikelihood", "(", "y", ",", "mean", ",", "scale", ",", "shape", ",", "skewness", ")", ":", "return", "-", "np", ".", "sum", "(", "ss", ".", "expon", ".", "logpdf", "(", "x", "=", "y", ",", "scale", "=", "1", "/", "mean", ")", ")"...
Negative loglikelihood function Parameters ---------- y : np.ndarray univariate time series mean : np.ndarray array of location parameters for the Exponential distribution scale : float scale parameter for the Exponential distribution shape : float tail thickness parameter for the Exponential distribution skewness : float skewness parameter for the Exponential distribution Returns ---------- - Negative loglikelihood of the Exponential family
[ "Negative", "loglikelihood", "function" ]
python
train
28.24
google/grumpy
third_party/stdlib/csv.py
https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/csv.py#L189-L215
def sniff(self, sample, delimiters=None): """ Returns a dialect (or None) corresponding to the sample """ quotechar, doublequote, delimiter, skipinitialspace = \ self._guess_quote_and_delimiter(sample, delimiters) if not delimiter: delimiter, skipinitialspace = self._guess_delimiter(sample, delimiters) if not delimiter: raise Error, "Could not determine delimiter" class dialect(Dialect): _name = "sniffed" lineterminator = '\r\n' quoting = QUOTE_MINIMAL # escapechar = '' dialect.doublequote = doublequote dialect.delimiter = delimiter # _csv.reader won't accept a quotechar of '' dialect.quotechar = quotechar or '"' dialect.skipinitialspace = skipinitialspace return dialect
[ "def", "sniff", "(", "self", ",", "sample", ",", "delimiters", "=", "None", ")", ":", "quotechar", ",", "doublequote", ",", "delimiter", ",", "skipinitialspace", "=", "self", ".", "_guess_quote_and_delimiter", "(", "sample", ",", "delimiters", ")", "if", "no...
Returns a dialect (or None) corresponding to the sample
[ "Returns", "a", "dialect", "(", "or", "None", ")", "corresponding", "to", "the", "sample" ]
python
valid
33.962963
mromanello/hucitlib
knowledge_base/__init__.py
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/__init__.py#L114-L127
def author_names(self): """ Returns a dictionary like this: { "urn:cts:greekLit:tlg0012$$n1" : "Homer" , "urn:cts:greekLit:tlg0012$$n2" : "Omero" , ... } """ return {"%s$$n%i" % (author.get_urn(), i): name[1] for author in self.get_authors() for i, name in enumerate(author.get_names()) if author.get_urn() is not None}
[ "def", "author_names", "(", "self", ")", ":", "return", "{", "\"%s$$n%i\"", "%", "(", "author", ".", "get_urn", "(", ")", ",", "i", ")", ":", "name", "[", "1", "]", "for", "author", "in", "self", ".", "get_authors", "(", ")", "for", "i", ",", "na...
Returns a dictionary like this: { "urn:cts:greekLit:tlg0012$$n1" : "Homer" , "urn:cts:greekLit:tlg0012$$n2" : "Omero" , ... }
[ "Returns", "a", "dictionary", "like", "this", ":" ]
python
train
31.357143
novopl/peltak
src/peltak/extra/pypi/logic.py
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/pypi/logic.py#L31-L44
def upload(target): # type: (str) -> None """ Upload the release to a pypi server. TODO: Make sure the git directory is clean before allowing a release. Args: target (str): pypi target as defined in ~/.pypirc """ log.info("Uploading to pypi server <33>{}".format(target)) with conf.within_proj_dir(): shell.run('python setup.py sdist register -r "{}"'.format(target)) shell.run('python setup.py sdist upload -r "{}"'.format(target))
[ "def", "upload", "(", "target", ")", ":", "# type: (str) -> None", "log", ".", "info", "(", "\"Uploading to pypi server <33>{}\"", ".", "format", "(", "target", ")", ")", "with", "conf", ".", "within_proj_dir", "(", ")", ":", "shell", ".", "run", "(", "'pyth...
Upload the release to a pypi server. TODO: Make sure the git directory is clean before allowing a release. Args: target (str): pypi target as defined in ~/.pypirc
[ "Upload", "the", "release", "to", "a", "pypi", "server", "." ]
python
train
34.642857
Hypex/hyppy
hyppy/hapi.py
https://github.com/Hypex/hyppy/blob/a425619c2a102b0e598fd6cac8aa0f6b766f542d/hyppy/hapi.py#L204-L234
def parse(response): """Parse a postdata-style response format from the API into usable data""" """Split a a=1b=2c=3 string into a dictionary of pairs""" tokens = {r[0]: r[1] for r in [r.split('=') for r in response.split("&")]} # The odd dummy parameter is of no use to us if 'dummy' in tokens: del tokens['dummy'] """ If we have key names that end in digits, these indicate the result set contains multiple sets For example, planet0=Hoth&x=1&y=-10&planet1=Naboo&x=9&y=13 is actually data for two planets Elements that end in digits (like tag0, tag1 for planets) are formatted like (tag0_1, tag1_1), so we rstrip underscores afterwards. """ if re.match('\D\d+$', tokens.keys()[0]): # Produce a list of dictionaries set_tokens = [] for key, value in tokens: key = re.match('^(.+\D)(\d+)$', key) # If the key isn't in the format (i.e. a failsafe), skip it if key is not None: if key.group(1) not in set_tokens: set_tokens[key.group(1)] = {} set_tokens[key.group(1)][key.group(0).rstrip('_')] = value tokens = set_tokens return tokens
[ "def", "parse", "(", "response", ")", ":", "\"\"\"Split a a=1b=2c=3 string into a dictionary of pairs\"\"\"", "tokens", "=", "{", "r", "[", "0", "]", ":", "r", "[", "1", "]", "for", "r", "in", "[", "r", ".", "split", "(", "'='", ")", "for", "r", "in", ...
Parse a postdata-style response format from the API into usable data
[ "Parse", "a", "postdata", "-", "style", "response", "format", "from", "the", "API", "into", "usable", "data" ]
python
train
41.419355
QUANTAXIS/QUANTAXIS
QUANTAXIS/QAIndicator/base.py
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/base.py#L160-L172
def LAST(COND, N1, N2): """表达持续性 从前N1日到前N2日一直满足COND条件 Arguments: COND {[type]} -- [description] N1 {[type]} -- [description] N2 {[type]} -- [description] """ N2 = 1 if N2 == 0 else N2 assert N2 > 0 assert N1 > N2 return COND.iloc[-N1:-N2].all()
[ "def", "LAST", "(", "COND", ",", "N1", ",", "N2", ")", ":", "N2", "=", "1", "if", "N2", "==", "0", "else", "N2", "assert", "N2", ">", "0", "assert", "N1", ">", "N2", "return", "COND", ".", "iloc", "[", "-", "N1", ":", "-", "N2", "]", ".", ...
表达持续性 从前N1日到前N2日一直满足COND条件 Arguments: COND {[type]} -- [description] N1 {[type]} -- [description] N2 {[type]} -- [description]
[ "表达持续性", "从前N1日到前N2日一直满足COND条件" ]
python
train
22.230769
openeemeter/eemeter
eemeter/transform.py
https://github.com/openeemeter/eemeter/blob/e03b1cc5f4906e8f4f7fd16183bc037107d1dfa0/eemeter/transform.py#L62-L138
def as_freq(data_series, freq, atomic_freq="1 Min", series_type="cumulative"): """Resample data to a different frequency. This method can be used to upsample or downsample meter data. The assumption it makes to do so is that meter data is constant and averaged over the given periods. For instance, to convert billing-period data to daily data, this method first upsamples to the atomic frequency (1 minute freqency, by default), "spreading" usage evenly across all minutes in each period. Then it downsamples to hourly frequency and returns that result. With instantaneous series, the data is copied to all contiguous time intervals and the mean over `freq` is returned. **Caveats**: - This method gives a fair amount of flexibility in resampling as long as you are OK with the assumption that usage is constant over the period (this assumption is generally broken in observed data at large enough frequencies, so this caveat should not be taken lightly). Parameters ---------- data_series : :any:`pandas.Series` Data to resample. Should have a :any:`pandas.DatetimeIndex`. freq : :any:`str` The frequency to resample to. This should be given in a form recognized by the :any:`pandas.Series.resample` method. atomic_freq : :any:`str`, optional The "atomic" frequency of the intermediate data form. This can be adjusted to a higher atomic frequency to increase speed or memory performance. series_type : :any:`str`, {'cumulative', ‘instantaneous’}, default 'cumulative' Type of data sampling. 'cumulative' data can be spread over smaller time intervals and is aggregated using addition (e.g. meter data). 'instantaneous' data is copied (not spread) over smaller time intervals and is aggregated by averaging (e.g. weather data). Returns ------- resampled_data : :any:`pandas.Series` Data resampled to the given frequency. """ # TODO(philngo): make sure this complies with CalTRACK 2.2.2.1 if not isinstance(data_series, pd.Series): raise ValueError( "expected series, got object with class {}".format(data_series.__class__) ) if data_series.empty: return data_series series = remove_duplicates(data_series) target_freq = pd.Timedelta(atomic_freq) timedeltas = (series.index[1:] - series.index[:-1]).append( pd.TimedeltaIndex([pd.NaT]) ) if series_type == "cumulative": spread_factor = target_freq.total_seconds() / timedeltas.total_seconds() series_spread = series * spread_factor atomic_series = series_spread.asfreq(atomic_freq, method="ffill") resampled = atomic_series.resample(freq).sum() resampled_with_nans = atomic_series.resample(freq).mean() resampled = resampled[resampled_with_nans.notnull()].reindex(resampled.index) elif series_type == "instantaneous": atomic_series = series.asfreq(atomic_freq, method="ffill") resampled = atomic_series.resample(freq).mean() if resampled.index[-1] < series.index[-1]: # this adds a null at the end using the target frequency last_index = pd.date_range(resampled.index[-1], freq=freq, periods=2)[1:] resampled = ( pd.concat([resampled, pd.Series(np.nan, index=last_index)]) .resample(freq) .mean() ) return resampled
[ "def", "as_freq", "(", "data_series", ",", "freq", ",", "atomic_freq", "=", "\"1 Min\"", ",", "series_type", "=", "\"cumulative\"", ")", ":", "# TODO(philngo): make sure this complies with CalTRACK 2.2.2.1", "if", "not", "isinstance", "(", "data_series", ",", "pd", "....
Resample data to a different frequency. This method can be used to upsample or downsample meter data. The assumption it makes to do so is that meter data is constant and averaged over the given periods. For instance, to convert billing-period data to daily data, this method first upsamples to the atomic frequency (1 minute freqency, by default), "spreading" usage evenly across all minutes in each period. Then it downsamples to hourly frequency and returns that result. With instantaneous series, the data is copied to all contiguous time intervals and the mean over `freq` is returned. **Caveats**: - This method gives a fair amount of flexibility in resampling as long as you are OK with the assumption that usage is constant over the period (this assumption is generally broken in observed data at large enough frequencies, so this caveat should not be taken lightly). Parameters ---------- data_series : :any:`pandas.Series` Data to resample. Should have a :any:`pandas.DatetimeIndex`. freq : :any:`str` The frequency to resample to. This should be given in a form recognized by the :any:`pandas.Series.resample` method. atomic_freq : :any:`str`, optional The "atomic" frequency of the intermediate data form. This can be adjusted to a higher atomic frequency to increase speed or memory performance. series_type : :any:`str`, {'cumulative', ‘instantaneous’}, default 'cumulative' Type of data sampling. 'cumulative' data can be spread over smaller time intervals and is aggregated using addition (e.g. meter data). 'instantaneous' data is copied (not spread) over smaller time intervals and is aggregated by averaging (e.g. weather data). Returns ------- resampled_data : :any:`pandas.Series` Data resampled to the given frequency.
[ "Resample", "data", "to", "a", "different", "frequency", "." ]
python
train
44.480519
MacHu-GWU/constant2-project
constant2/_constant2.py
https://github.com/MacHu-GWU/constant2-project/blob/ccf7e14b0e23f9f4bfd13a3e2ce4a1142e570d4f/constant2/_constant2.py#L373-L432
def BackAssign(cls, other_entity_klass, this_entity_backpopulate_field, other_entity_backpopulate_field, is_many_to_one=False): """ Assign defined one side mapping relationship to other side. For example, each employee belongs to one department, then one department includes many employees. If you defined each employee's department, this method will assign employees to ``Department.employees`` field. This is an one to many (department to employee) example. Another example would be, each employee has multiple tags. If you defined tags for each employee, this method will assign employees to ``Tag.employees`` field. This is and many to many (employee to tag) example. Support: - many to many mapping - one to many mapping :param other_entity_klass: a :class:`Constant` class. :param this_entity_backpopulate_field: str :param other_entity_backpopulate_field: str :param is_many_to_one: bool :return: """ data = dict() for _, other_klass in other_entity_klass.Subclasses(): other_field_value = getattr( other_klass, this_entity_backpopulate_field) if isinstance(other_field_value, (tuple, list)): for self_klass in other_field_value: self_key = self_klass.__name__ try: data[self_key].append(other_klass) except KeyError: data[self_key] = [other_klass, ] else: if other_field_value is not None: self_klass = other_field_value self_key = self_klass.__name__ try: data[self_key].append(other_klass) except KeyError: data[self_key] = [other_klass, ] if is_many_to_one: new_data = dict() for key, value in data.items(): try: new_data[key] = value[0] except: # pragma: no cover pass data = new_data for self_key, other_klass_list in data.items(): setattr(getattr(cls, self_key), other_entity_backpopulate_field, other_klass_list)
[ "def", "BackAssign", "(", "cls", ",", "other_entity_klass", ",", "this_entity_backpopulate_field", ",", "other_entity_backpopulate_field", ",", "is_many_to_one", "=", "False", ")", ":", "data", "=", "dict", "(", ")", "for", "_", ",", "other_klass", "in", "other_en...
Assign defined one side mapping relationship to other side. For example, each employee belongs to one department, then one department includes many employees. If you defined each employee's department, this method will assign employees to ``Department.employees`` field. This is an one to many (department to employee) example. Another example would be, each employee has multiple tags. If you defined tags for each employee, this method will assign employees to ``Tag.employees`` field. This is and many to many (employee to tag) example. Support: - many to many mapping - one to many mapping :param other_entity_klass: a :class:`Constant` class. :param this_entity_backpopulate_field: str :param other_entity_backpopulate_field: str :param is_many_to_one: bool :return:
[ "Assign", "defined", "one", "side", "mapping", "relationship", "to", "other", "side", "." ]
python
train
39.8
quantumlib/Cirq
cirq/contrib/acquaintance/executor.py
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/contrib/acquaintance/executor.py#L61-L65
def get_operations(self, indices: Sequence[LogicalIndex], qubits: Sequence[ops.Qid] ) -> ops.OP_TREE: """Gets the logical operations to apply to qubits."""
[ "def", "get_operations", "(", "self", ",", "indices", ":", "Sequence", "[", "LogicalIndex", "]", ",", "qubits", ":", "Sequence", "[", "ops", ".", "Qid", "]", ")", "->", "ops", ".", "OP_TREE", ":" ]
Gets the logical operations to apply to qubits.
[ "Gets", "the", "logical", "operations", "to", "apply", "to", "qubits", "." ]
python
train
45.6
Erotemic/utool
utool/util_dbg.py
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dbg.py#L112-L203
def execstr_dict(dict_, local_name=None, exclude_list=None, explicit=False): """ returns execable python code that declares variables using keys and values execstr_dict Args: dict_ (dict): local_name (str): optional: local name of dictionary. Specifying this is much safer exclude_list (list): Returns: str: execstr --- the executable string that will put keys from dict into local vars CommandLine: python -m utool.util_dbg --test-execstr_dict Example: >>> # DISABLE_DOCTEST >>> # UNSTABLE_DOCTEST >>> from utool.util_dbg import * # NOQA >>> my_dictionary = {'a': True, 'b': False} >>> execstr = execstr_dict(my_dictionary) >>> exec(execstr) >>> assert 'a' in vars() and 'b' in vars(), 'execstr failed' >>> assert b is False and a is True, 'execstr failed' >>> result = execstr >>> print(result) a = my_dictionary['a'] b = my_dictionary['b'] Example: >>> # ENABLE_DOCTEST >>> from utool.util_dbg import * # NOQA >>> import utool as ut >>> my_dictionary = {'a': True, 'b': False} >>> execstr = execstr_dict(my_dictionary) >>> locals_ = locals() >>> exec(execstr, locals_) >>> a, b = ut.dict_take(locals_, ['a', 'b']) >>> assert 'a' in locals_ and 'b' in locals_, 'execstr failed' >>> assert b is False and a is True, 'execstr failed' >>> result = execstr >>> print(result) a = my_dictionary['a'] b = my_dictionary['b'] Example: >>> # ENABLE_DOCTEST >>> from utool.util_dbg import * # NOQA >>> import utool as ut >>> my_dictionary = {'a': True, 'b': False} >>> execstr = execstr_dict(my_dictionary, explicit=True) >>> result = execstr >>> print(result) a = True b = False """ import utool as ut if explicit: expr_list = [] for (key, val) in sorted(dict_.items()): assert isinstance(key, six.string_types), 'keys must be strings' expr_list.append('%s = %s' % (key, ut.repr2(val),)) execstr = '\n'.join(expr_list) return execstr else: if local_name is None: # Magic way of getting the local name of dict_ local_name = get_varname_from_locals(dict_, get_parent_frame().f_locals) try: if exclude_list is None: exclude_list = [] assert isinstance(exclude_list, list) exclude_list.append(local_name) expr_list = [] assert isinstance(dict_, dict), 'incorrect type type(dict_)=%r, dict_=%r' % (type(dict), dict_) for (key, val) in sorted(dict_.items()): assert isinstance(key, six.string_types), 'keys must be strings' if not is_valid_varname(key): continue if not any((fnmatch.fnmatch(key, pat) for pat in exclude_list)): expr = '%s = %s[%s]' % (key, local_name, ut.repr2(key)) expr_list.append(expr) execstr = '\n'.join(expr_list) return execstr except Exception as ex: locals_ = locals() ut.printex(ex, key_list=['locals_']) raise
[ "def", "execstr_dict", "(", "dict_", ",", "local_name", "=", "None", ",", "exclude_list", "=", "None", ",", "explicit", "=", "False", ")", ":", "import", "utool", "as", "ut", "if", "explicit", ":", "expr_list", "=", "[", "]", "for", "(", "key", ",", ...
returns execable python code that declares variables using keys and values execstr_dict Args: dict_ (dict): local_name (str): optional: local name of dictionary. Specifying this is much safer exclude_list (list): Returns: str: execstr --- the executable string that will put keys from dict into local vars CommandLine: python -m utool.util_dbg --test-execstr_dict Example: >>> # DISABLE_DOCTEST >>> # UNSTABLE_DOCTEST >>> from utool.util_dbg import * # NOQA >>> my_dictionary = {'a': True, 'b': False} >>> execstr = execstr_dict(my_dictionary) >>> exec(execstr) >>> assert 'a' in vars() and 'b' in vars(), 'execstr failed' >>> assert b is False and a is True, 'execstr failed' >>> result = execstr >>> print(result) a = my_dictionary['a'] b = my_dictionary['b'] Example: >>> # ENABLE_DOCTEST >>> from utool.util_dbg import * # NOQA >>> import utool as ut >>> my_dictionary = {'a': True, 'b': False} >>> execstr = execstr_dict(my_dictionary) >>> locals_ = locals() >>> exec(execstr, locals_) >>> a, b = ut.dict_take(locals_, ['a', 'b']) >>> assert 'a' in locals_ and 'b' in locals_, 'execstr failed' >>> assert b is False and a is True, 'execstr failed' >>> result = execstr >>> print(result) a = my_dictionary['a'] b = my_dictionary['b'] Example: >>> # ENABLE_DOCTEST >>> from utool.util_dbg import * # NOQA >>> import utool as ut >>> my_dictionary = {'a': True, 'b': False} >>> execstr = execstr_dict(my_dictionary, explicit=True) >>> result = execstr >>> print(result) a = True b = False
[ "returns", "execable", "python", "code", "that", "declares", "variables", "using", "keys", "and", "values" ]
python
train
35.858696
python-astrodynamics/spacetrack
spacetrack/base.py
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L415-L441
def _ratelimited_get(self, *args, **kwargs): """Perform get request, handling rate limiting.""" with self._ratelimiter: resp = self.session.get(*args, **kwargs) # It's possible that Space-Track will return HTTP status 500 with a # query rate limit violation. This can happen if a script is cancelled # before it has finished sleeping to satisfy the rate limit and it is # started again. # # Let's catch this specific instance and retry once if it happens. if resp.status_code == 500: # Let's only retry if the error page tells us it's a rate limit # violation. if 'violated your query rate limit' in resp.text: # Mimic the RateLimiter callback behaviour. until = time.time() + self._ratelimiter.period t = threading.Thread(target=self._ratelimit_callback, args=(until,)) t.daemon = True t.start() time.sleep(self._ratelimiter.period) # Now retry with self._ratelimiter: resp = self.session.get(*args, **kwargs) return resp
[ "def", "_ratelimited_get", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "_ratelimiter", ":", "resp", "=", "self", ".", "session", ".", "get", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# It's possible t...
Perform get request, handling rate limiting.
[ "Perform", "get", "request", "handling", "rate", "limiting", "." ]
python
train
43.518519
log2timeline/plaso
plaso/multi_processing/task_manager.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/multi_processing/task_manager.py#L197-L212
def _AbandonQueuedTasks(self): """Marks queued tasks abandoned. This method does not lock the manager and should be called by a method holding the manager lock. """ # Abandon all tasks after they're identified so as not to modify the # dict while iterating over it. tasks_to_abandon = [] for task_identifier, task in iter(self._tasks_queued.items()): logger.debug('Abandoned queued task: {0:s}.'.format(task_identifier)) tasks_to_abandon.append((task_identifier, task)) for task_identifier, task in tasks_to_abandon: self._tasks_abandoned[task_identifier] = task del self._tasks_queued[task_identifier]
[ "def", "_AbandonQueuedTasks", "(", "self", ")", ":", "# Abandon all tasks after they're identified so as not to modify the", "# dict while iterating over it.", "tasks_to_abandon", "=", "[", "]", "for", "task_identifier", ",", "task", "in", "iter", "(", "self", ".", "_tasks_...
Marks queued tasks abandoned. This method does not lock the manager and should be called by a method holding the manager lock.
[ "Marks", "queued", "tasks", "abandoned", "." ]
python
train
40.5625
ekalinin/marktime.py
marktime.py
https://github.com/ekalinin/marktime.py/blob/111897cfa30f570155bb009ea653ce402457b17d/marktime.py#L103-L120
def stop(label, at=None, remove_from_labels=False, stop_once=True): """Stops the countdown""" t = at if at is not None else time.time() if label not in labels: return None timer = Marker().loads(labels[label]) if timer.is_running() or (timer.is_stopped() and not stop_once): timer.stop(t) if remove_from_labels: del labels[label] else: labels[label] = timer.dumps() return timer.duration()
[ "def", "stop", "(", "label", ",", "at", "=", "None", ",", "remove_from_labels", "=", "False", ",", "stop_once", "=", "True", ")", ":", "t", "=", "at", "if", "at", "is", "not", "None", "else", "time", ".", "time", "(", ")", "if", "label", "not", "...
Stops the countdown
[ "Stops", "the", "countdown" ]
python
train
24.5
moonlitesolutions/SolrClient
SolrClient/zk.py
https://github.com/moonlitesolutions/SolrClient/blob/19c5280c9f8e97ee104d22ae883c4ccfd7c4f43b/SolrClient/zk.py#L114-L124
def download_collection_configs(self, collection, fs_path): ''' Downloads ZK Directory to the FileSystem. :param collection str: Name of the collection (zk config name) :param fs_path str: Destination filesystem path. ''' if not self.kz.exists('/configs/{}'.format(collection)): raise ZookeeperError("Collection doesn't exist in Zookeeper. Current Collections are: {} ".format(self.kz.get_children('/configs'))) self._download_dir('/configs/{}'.format(collection), fs_path + os.sep + collection)
[ "def", "download_collection_configs", "(", "self", ",", "collection", ",", "fs_path", ")", ":", "if", "not", "self", ".", "kz", ".", "exists", "(", "'/configs/{}'", ".", "format", "(", "collection", ")", ")", ":", "raise", "ZookeeperError", "(", "\"Collectio...
Downloads ZK Directory to the FileSystem. :param collection str: Name of the collection (zk config name) :param fs_path str: Destination filesystem path.
[ "Downloads", "ZK", "Directory", "to", "the", "FileSystem", "." ]
python
train
51.272727
tetframework/Tonnikala
tonnikala/languages/javascript/jslex.py
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/languages/javascript/jslex.py#L52-L75
def lex(self, text, start=0): """Lexically analyze `text`. Yields pairs (`name`, `tokentext`). """ max = len(text) eaten = start s = self.state r = self.regexes toks = self.toks while eaten < max: for match in r[s].finditer(text, eaten): name = match.lastgroup tok = toks[name] toktext = match.group(name) eaten += len(toktext) yield (tok.name, toktext) if tok.next: s = tok.next break self.state = s
[ "def", "lex", "(", "self", ",", "text", ",", "start", "=", "0", ")", ":", "max", "=", "len", "(", "text", ")", "eaten", "=", "start", "s", "=", "self", ".", "state", "r", "=", "self", ".", "regexes", "toks", "=", "self", ".", "toks", "while", ...
Lexically analyze `text`. Yields pairs (`name`, `tokentext`).
[ "Lexically", "analyze", "text", "." ]
python
train
25.375
dhermes/bezier
src/bezier/_geometric_intersection.py
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L906-L970
def tangent_bbox_intersection(first, second, intersections): r"""Check if two curves with tangent bounding boxes intersect. .. note:: This is a helper for :func:`intersect_one_round`. These functions are used (directly or indirectly) by :func:`_all_intersections` exclusively, and that function has a Fortran equivalent. If the bounding boxes are tangent, intersection can only occur along that tangency. If the curve is **not** a line, the **only** way the curve can touch the bounding box is at the endpoints. To see this, consider the component .. math:: x(s) = \sum_j W_j x_j. Since :math:`W_j > 0` for :math:`s \in \left(0, 1\right)`, if there is some :math:`k` with :math:`x_k < M = \max x_j`, then for any interior :math:`s` .. math:: x(s) < \sum_j W_j M = M. If all :math:`x_j = M`, then :math:`B(s)` falls on the line :math:`x = M`. (A similar argument holds for the other three component-extrema types.) .. note:: This function assumes callers will not pass curves that can be linearized / are linear. In :func:`_all_intersections`, curves are pre-processed to do any linearization before the subdivision / intersection process begins. Args: first (SubdividedCurve): First curve being intersected (assumed in :math:\mathbf{R}^2`). second (SubdividedCurve): Second curve being intersected (assumed in :math:\mathbf{R}^2`). intersections (list): A list of already encountered intersections. If these curves intersect at their tangency, then those intersections will be added to this list. """ node_first1 = first.nodes[:, 0] node_first2 = first.nodes[:, -1] node_second1 = second.nodes[:, 0] node_second2 = second.nodes[:, -1] endpoint_check( first, node_first1, 0.0, second, node_second1, 0.0, intersections ) endpoint_check( first, node_first1, 0.0, second, node_second2, 1.0, intersections ) endpoint_check( first, node_first2, 1.0, second, node_second1, 0.0, intersections ) endpoint_check( first, node_first2, 1.0, second, node_second2, 1.0, intersections )
[ "def", "tangent_bbox_intersection", "(", "first", ",", "second", ",", "intersections", ")", ":", "node_first1", "=", "first", ".", "nodes", "[", ":", ",", "0", "]", "node_first2", "=", "first", ".", "nodes", "[", ":", ",", "-", "1", "]", "node_second1", ...
r"""Check if two curves with tangent bounding boxes intersect. .. note:: This is a helper for :func:`intersect_one_round`. These functions are used (directly or indirectly) by :func:`_all_intersections` exclusively, and that function has a Fortran equivalent. If the bounding boxes are tangent, intersection can only occur along that tangency. If the curve is **not** a line, the **only** way the curve can touch the bounding box is at the endpoints. To see this, consider the component .. math:: x(s) = \sum_j W_j x_j. Since :math:`W_j > 0` for :math:`s \in \left(0, 1\right)`, if there is some :math:`k` with :math:`x_k < M = \max x_j`, then for any interior :math:`s` .. math:: x(s) < \sum_j W_j M = M. If all :math:`x_j = M`, then :math:`B(s)` falls on the line :math:`x = M`. (A similar argument holds for the other three component-extrema types.) .. note:: This function assumes callers will not pass curves that can be linearized / are linear. In :func:`_all_intersections`, curves are pre-processed to do any linearization before the subdivision / intersection process begins. Args: first (SubdividedCurve): First curve being intersected (assumed in :math:\mathbf{R}^2`). second (SubdividedCurve): Second curve being intersected (assumed in :math:\mathbf{R}^2`). intersections (list): A list of already encountered intersections. If these curves intersect at their tangency, then those intersections will be added to this list.
[ "r", "Check", "if", "two", "curves", "with", "tangent", "bounding", "boxes", "intersect", "." ]
python
train
34.046154
J535D165/recordlinkage
recordlinkage/api.py
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/api.py#L211-L225
def date(self, *args, **kwargs): """Compare attributes of pairs with date algorithm. Shortcut of :class:`recordlinkage.compare.Date`:: from recordlinkage.compare import Date indexer = recordlinkage.Compare() indexer.add(Date()) """ compare = Date(*args, **kwargs) self.add(compare) return self
[ "def", "date", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "compare", "=", "Date", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "add", "(", "compare", ")", "return", "self" ]
Compare attributes of pairs with date algorithm. Shortcut of :class:`recordlinkage.compare.Date`:: from recordlinkage.compare import Date indexer = recordlinkage.Compare() indexer.add(Date())
[ "Compare", "attributes", "of", "pairs", "with", "date", "algorithm", "." ]
python
train
24.533333
jimzhan/pyx
rex/debug/function.py
https://github.com/jimzhan/pyx/blob/819e8251323a7923e196c0c438aa8524f5aaee6e/rex/debug/function.py#L20-L33
def attr(**context): """ Decorator that add attributes into func. Added attributes can be access outside via function's `func_dict` property. """ #TODO(Jim Zhan) FIXME def decorator(func): def wrapped_func(*args, **kwargs): for key, value in context.items(): print key, value return func(*args, **kwargs) return wraps(func)(decorator) return decorator
[ "def", "attr", "(", "*", "*", "context", ")", ":", "#TODO(Jim Zhan) FIXME", "def", "decorator", "(", "func", ")", ":", "def", "wrapped_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "key", ",", "value", "in", "context", ".", "item...
Decorator that add attributes into func. Added attributes can be access outside via function's `func_dict` property.
[ "Decorator", "that", "add", "attributes", "into", "func", "." ]
python
train
30.214286
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/win32/kernel32.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/win32/kernel32.py#L4659-L4670
def Wow64EnableWow64FsRedirection(Wow64FsEnableRedirection): """ This function may not work reliably when there are nested calls. Therefore, this function has been replaced by the L{Wow64DisableWow64FsRedirection} and L{Wow64RevertWow64FsRedirection} functions. @see: U{http://msdn.microsoft.com/en-us/library/windows/desktop/aa365744(v=vs.85).aspx} """ _Wow64EnableWow64FsRedirection = windll.kernel32.Wow64EnableWow64FsRedirection _Wow64EnableWow64FsRedirection.argtypes = [BOOLEAN] _Wow64EnableWow64FsRedirection.restype = BOOLEAN _Wow64EnableWow64FsRedirection.errcheck = RaiseIfZero
[ "def", "Wow64EnableWow64FsRedirection", "(", "Wow64FsEnableRedirection", ")", ":", "_Wow64EnableWow64FsRedirection", "=", "windll", ".", "kernel32", ".", "Wow64EnableWow64FsRedirection", "_Wow64EnableWow64FsRedirection", ".", "argtypes", "=", "[", "BOOLEAN", "]", "_Wow64Enabl...
This function may not work reliably when there are nested calls. Therefore, this function has been replaced by the L{Wow64DisableWow64FsRedirection} and L{Wow64RevertWow64FsRedirection} functions. @see: U{http://msdn.microsoft.com/en-us/library/windows/desktop/aa365744(v=vs.85).aspx}
[ "This", "function", "may", "not", "work", "reliably", "when", "there", "are", "nested", "calls", ".", "Therefore", "this", "function", "has", "been", "replaced", "by", "the", "L", "{", "Wow64DisableWow64FsRedirection", "}", "and", "L", "{", "Wow64RevertWow64FsRe...
python
train
51.5
noxdafox/pebble
pebble/pool/process.py
https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/pool/process.py#L410-L419
def task_transaction(channel): """Ensures a task is fetched and acknowledged atomically.""" with channel.lock: if channel.poll(0): task = channel.recv() channel.send(Acknowledgement(os.getpid(), task.id)) else: raise RuntimeError("Race condition between workers") return task
[ "def", "task_transaction", "(", "channel", ")", ":", "with", "channel", ".", "lock", ":", "if", "channel", ".", "poll", "(", "0", ")", ":", "task", "=", "channel", ".", "recv", "(", ")", "channel", ".", "send", "(", "Acknowledgement", "(", "os", ".",...
Ensures a task is fetched and acknowledged atomically.
[ "Ensures", "a", "task", "is", "fetched", "and", "acknowledged", "atomically", "." ]
python
train
33.1
spyder-ide/conda-manager
conda_manager/api/conda_api.py
https://github.com/spyder-ide/conda-manager/blob/89a2126cbecefc92185cf979347ccac1c5ee5d9d/conda_manager/api/conda_api.py#L655-L661
def remove_environment(self, name=None, path=None, **kwargs): """ Remove an environment entirely. See ``remove``. """ return self.remove(name=name, path=path, all=True, **kwargs)
[ "def", "remove_environment", "(", "self", ",", "name", "=", "None", ",", "path", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "remove", "(", "name", "=", "name", ",", "path", "=", "path", ",", "all", "=", "True", ",", "*...
Remove an environment entirely. See ``remove``.
[ "Remove", "an", "environment", "entirely", "." ]
python
train
30.428571