nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
frePPLe/frepple
57aa612030b4fcd03cb9c613f83a7dac4f0e8d6d
freppledb/common/api/views.py
python
frePPleRetrieveUpdateDestroyAPIView.get_queryset
(self)
[]
def get_queryset(self): if self.request.database == "default": return super().get_queryset() else: return super().get_queryset().using(self.request.database)
[ "def", "get_queryset", "(", "self", ")", ":", "if", "self", ".", "request", ".", "database", "==", "\"default\"", ":", "return", "super", "(", ")", ".", "get_queryset", "(", ")", "else", ":", "return", "super", "(", ")", ".", "get_queryset", "(", ")", ...
https://github.com/frePPLe/frepple/blob/57aa612030b4fcd03cb9c613f83a7dac4f0e8d6d/freppledb/common/api/views.py#L117-L121
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/tools/inject/thirdparty/clientform/clientform.py
python
HTMLForm._pairs_and_controls
(self)
return pairs
Return sequence of (index, key, value, control_index) of totally ordered pairs suitable for urlencoding. control_index is the index of the control in self.controls
Return sequence of (index, key, value, control_index) of totally ordered pairs suitable for urlencoding.
[ "Return", "sequence", "of", "(", "index", "key", "value", "control_index", ")", "of", "totally", "ordered", "pairs", "suitable", "for", "urlencoding", "." ]
def _pairs_and_controls(self): """Return sequence of (index, key, value, control_index) of totally ordered pairs suitable for urlencoding. control_index is the index of the control in self.controls """ pairs = [] for control_index in xrange(len(self.controls)): control = self.controls[control_index] for ii, key, val in control._totally_ordered_pairs(): pairs.append((ii, key, val, control_index)) # stable sort by ONLY first item in tuple pairs.sort() return pairs
[ "def", "_pairs_and_controls", "(", "self", ")", ":", "pairs", "=", "[", "]", "for", "control_index", "in", "xrange", "(", "len", "(", "self", ".", "controls", ")", ")", ":", "control", "=", "self", ".", "controls", "[", "control_index", "]", "for", "ii...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/inject/thirdparty/clientform/clientform.py#L3332-L3347
python-twitter-tools/twitter
6a868f43dbc3a05527c339f45d21ea435fa8d1d3
twitter/ansi.py
python
ColourMap.colourFor
(self, string)
return self._cmap[string]
Returns an ansi colour value given a `string`. The same ansi colour value is always returned for the same string
Returns an ansi colour value given a `string`. The same ansi colour value is always returned for the same string
[ "Returns", "an", "ansi", "colour", "value", "given", "a", "string", ".", "The", "same", "ansi", "colour", "value", "is", "always", "returned", "for", "the", "same", "string" ]
def colourFor(self, string): ''' Returns an ansi colour value given a `string`. The same ansi colour value is always returned for the same string ''' if string not in self._cmap: self._cmap[string] = next(self._colourIter) return self._cmap[string]
[ "def", "colourFor", "(", "self", ",", "string", ")", ":", "if", "string", "not", "in", "self", ".", "_cmap", ":", "self", ".", "_cmap", "[", "string", "]", "=", "next", "(", "self", ".", "_colourIter", ")", "return", "self", ".", "_cmap", "[", "str...
https://github.com/python-twitter-tools/twitter/blob/6a868f43dbc3a05527c339f45d21ea435fa8d1d3/twitter/ansi.py#L45-L52
robinhood/thorn
486a53ebcf6373ff306a8d17dc016d78e880fcd6
thorn/dispatch/base.py
python
Dispatcher._maybe_subscriber
(self, d, **kwargs)
return (self.app.Subscriber.from_dict(d, **kwargs) if not isinstance(d, AbstractSubscriber) else d)
[]
def _maybe_subscriber(self, d, **kwargs): return (self.app.Subscriber.from_dict(d, **kwargs) if not isinstance(d, AbstractSubscriber) else d)
[ "def", "_maybe_subscriber", "(", "self", ",", "d", ",", "*", "*", "kwargs", ")", ":", "return", "(", "self", ".", "app", ".", "Subscriber", ".", "from_dict", "(", "d", ",", "*", "*", "kwargs", ")", "if", "not", "isinstance", "(", "d", ",", "Abstrac...
https://github.com/robinhood/thorn/blob/486a53ebcf6373ff306a8d17dc016d78e880fcd6/thorn/dispatch/base.py#L132-L134
happinesslz/TANet
2d4b2ab99b8e57c03671b0f1531eab7dca8f3c1f
second.pytorch_with_TANet/second/core/target_assigner.py
python
TargetAssigner.generate_anchors
(self, feature_map_size)
return { "anchors": anchors, "matched_thresholds": matched_thresholds, "unmatched_thresholds": unmatched_thresholds }
[]
def generate_anchors(self, feature_map_size): anchors_list = [] ndim = len(feature_map_size) matched_thresholds = [ a.match_threshold for a in self._anchor_generators ] unmatched_thresholds = [ a.unmatch_threshold for a in self._anchor_generators ] match_list, unmatch_list = [], [] if self._feature_map_sizes is not None: feature_map_sizes = self._feature_map_sizes else: feature_map_sizes = [feature_map_size] * len(self._anchor_generators) idx = 0 for anchor_generator, match_thresh, unmatch_thresh, fsize in zip( self._anchor_generators, matched_thresholds, unmatched_thresholds, feature_map_sizes): if len(fsize) == 0: fsize = feature_map_size self._feature_map_sizes[idx] = feature_map_size anchors = anchor_generator.generate(fsize) anchors = anchors.reshape([*fsize, -1, self.box_ndim]) anchors = anchors.transpose(ndim, *range(0, ndim), ndim + 1) anchors_list.append(anchors.reshape(-1, self.box_ndim)) num_anchors = np.prod(anchors.shape[:-1]) match_list.append( np.full([num_anchors], match_thresh, anchors.dtype)) unmatch_list.append( np.full([num_anchors], unmatch_thresh, anchors.dtype)) idx += 1 anchors = np.concatenate(anchors_list, axis=0) matched_thresholds = np.concatenate(match_list, axis=0) unmatched_thresholds = np.concatenate(unmatch_list, axis=0) return { "anchors": anchors, "matched_thresholds": matched_thresholds, "unmatched_thresholds": unmatched_thresholds }
[ "def", "generate_anchors", "(", "self", ",", "feature_map_size", ")", ":", "anchors_list", "=", "[", "]", "ndim", "=", "len", "(", "feature_map_size", ")", "matched_thresholds", "=", "[", "a", ".", "match_threshold", "for", "a", "in", "self", ".", "_anchor_g...
https://github.com/happinesslz/TANet/blob/2d4b2ab99b8e57c03671b0f1531eab7dca8f3c1f/second.pytorch_with_TANet/second/core/target_assigner.py#L169-L207
recruit-tech/summpy
b246bd111aa10a8ea11a0aff8c9fce891f52cc58
summpy/lexrank.py
python
summarize
(text, sent_limit=None, char_limit=None, imp_require=None, debug=False, **lexrank_params)
return summary_sents, debug_info
Args: text: text to be summarized (unicode string) sent_limit: summary length (the number of sentences) char_limit: summary length (the number of characters) imp_require: cumulative LexRank score [0.0-1.0] Returns: list of extracted sentences
Args: text: text to be summarized (unicode string) sent_limit: summary length (the number of sentences) char_limit: summary length (the number of characters) imp_require: cumulative LexRank score [0.0-1.0]
[ "Args", ":", "text", ":", "text", "to", "be", "summarized", "(", "unicode", "string", ")", "sent_limit", ":", "summary", "length", "(", "the", "number", "of", "sentences", ")", "char_limit", ":", "summary", "length", "(", "the", "number", "of", "characters...
def summarize(text, sent_limit=None, char_limit=None, imp_require=None, debug=False, **lexrank_params): ''' Args: text: text to be summarized (unicode string) sent_limit: summary length (the number of sentences) char_limit: summary length (the number of characters) imp_require: cumulative LexRank score [0.0-1.0] Returns: list of extracted sentences ''' debug_info = {} sentences = list(tools.sent_splitter_ja(text)) scores, sim_mat = lexrank(sentences, **lexrank_params) sum_scores = sum(scores.itervalues()) acc_scores = 0.0 indexes = set() num_sent, num_char = 0, 0 for i in sorted(scores, key=lambda i: scores[i], reverse=True): num_sent += 1 num_char += len(sentences[i]) if sent_limit is not None and num_sent > sent_limit: break if char_limit is not None and num_char > char_limit: break if imp_require is not None and acc_scores / sum_scores >= imp_require: break indexes.add(i) acc_scores += scores[i] if len(indexes) > 0: summary_sents = [sentences[i] for i in sorted(indexes)] else: summary_sents = sentences if debug: debug_info.update({ 'sentences': sentences, 'scores': scores }) return summary_sents, debug_info
[ "def", "summarize", "(", "text", ",", "sent_limit", "=", "None", ",", "char_limit", "=", "None", ",", "imp_require", "=", "None", ",", "debug", "=", "False", ",", "*", "*", "lexrank_params", ")", ":", "debug_info", "=", "{", "}", "sentences", "=", "lis...
https://github.com/recruit-tech/summpy/blob/b246bd111aa10a8ea11a0aff8c9fce891f52cc58/summpy/lexrank.py#L91-L132
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/taskrouter/v1/workspace/workflow/__init__.py
python
WorkflowInstance.update
(self, friendly_name=values.unset, assignment_callback_url=values.unset, fallback_assignment_callback_url=values.unset, configuration=values.unset, task_reservation_timeout=values.unset, re_evaluate_tasks=values.unset)
return self._proxy.update( friendly_name=friendly_name, assignment_callback_url=assignment_callback_url, fallback_assignment_callback_url=fallback_assignment_callback_url, configuration=configuration, task_reservation_timeout=task_reservation_timeout, re_evaluate_tasks=re_evaluate_tasks, )
Update the WorkflowInstance :param unicode friendly_name: descriptive string that you create to describe the Workflow resource :param unicode assignment_callback_url: The URL from your application that will process task assignment events :param unicode fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails :param unicode configuration: A JSON string that contains the rules to apply to the Workflow :param unicode task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker :param unicode re_evaluate_tasks: Whether or not to re-evaluate Tasks :returns: The updated WorkflowInstance :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance
Update the WorkflowInstance
[ "Update", "the", "WorkflowInstance" ]
def update(self, friendly_name=values.unset, assignment_callback_url=values.unset, fallback_assignment_callback_url=values.unset, configuration=values.unset, task_reservation_timeout=values.unset, re_evaluate_tasks=values.unset): """ Update the WorkflowInstance :param unicode friendly_name: descriptive string that you create to describe the Workflow resource :param unicode assignment_callback_url: The URL from your application that will process task assignment events :param unicode fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails :param unicode configuration: A JSON string that contains the rules to apply to the Workflow :param unicode task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker :param unicode re_evaluate_tasks: Whether or not to re-evaluate Tasks :returns: The updated WorkflowInstance :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance """ return self._proxy.update( friendly_name=friendly_name, assignment_callback_url=assignment_callback_url, fallback_assignment_callback_url=fallback_assignment_callback_url, configuration=configuration, task_reservation_timeout=task_reservation_timeout, re_evaluate_tasks=re_evaluate_tasks, )
[ "def", "update", "(", "self", ",", "friendly_name", "=", "values", ".", "unset", ",", "assignment_callback_url", "=", "values", ".", "unset", ",", "fallback_assignment_callback_url", "=", "values", ".", "unset", ",", "configuration", "=", "values", ".", "unset",...
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py#L528-L553
steeve/plugin.video.pulsar
4b316e35e6427d31f2de7ba7c4cee46059db1100
resources/site-packages/simplejson/encoder.py
python
JSONEncoder.__init__
(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None)
Constructor for JSONEncoder, with sensible defaults. If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, long, float or None. If skipkeys is True, such items are simply skipped. If ensure_ascii is true, the output is guaranteed to be str objects with all incoming unicode characters escaped. If ensure_ascii is false, the output will be unicode object. If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place. If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats. If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis. If indent is a string, then JSON array elements and object members will be pretty-printed with a newline followed by that string repeated for each level of nesting. ``None`` (the default) selects the most compact representation without any newlines. For backwards compatibility with versions of simplejson earlier than 2.1.0, an integer is also accepted and is converted to a string with that many spaces. If specified, separators should be an (item_separator, key_separator) tuple. The default is (', ', ': ') if *indent* is ``None`` and (',', ': ') otherwise. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace. If specified, default is a function that gets called for objects that can't otherwise be serialized. It should return a JSON encodable version of the object or raise a ``TypeError``. If encoding is not None, then all input strings will be transformed into unicode using that encoding prior to JSON-encoding. The default is UTF-8. If use_decimal is true (not the default), ``decimal.Decimal`` will be supported directly by the encoder. For the inverse, decode JSON with ``parse_float=decimal.Decimal``. If namedtuple_as_object is true (the default), objects with ``_asdict()`` methods will be encoded as JSON objects. If tuple_as_array is true (the default), tuple (and subclasses) will be encoded as JSON arrays. If bigint_as_string is true (not the default), ints 2**53 and higher or lower than -2**53 will be encoded as strings. This is to avoid the rounding that happens in Javascript otherwise. If int_as_string_bitcount is a positive number (n), then int of size greater than or equal to 2**n or lower than or equal to -2**n will be encoded as strings. If specified, item_sort_key is a callable used to sort the items in each dictionary. This is useful if you want to sort items other than in alphabetical order by key. If for_json is true (not the default), objects with a ``for_json()`` method will use the return value of that method for encoding as JSON instead of the object. If *ignore_nan* is true (default: ``False``), then out of range :class:`float` values (``nan``, ``inf``, ``-inf``) will be serialized as ``null`` in compliance with the ECMA-262 specification. If true, this will override *allow_nan*.
Constructor for JSONEncoder, with sensible defaults.
[ "Constructor", "for", "JSONEncoder", "with", "sensible", "defaults", "." ]
def __init__(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None): """Constructor for JSONEncoder, with sensible defaults. If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, long, float or None. If skipkeys is True, such items are simply skipped. If ensure_ascii is true, the output is guaranteed to be str objects with all incoming unicode characters escaped. If ensure_ascii is false, the output will be unicode object. If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place. If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats. If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis. If indent is a string, then JSON array elements and object members will be pretty-printed with a newline followed by that string repeated for each level of nesting. ``None`` (the default) selects the most compact representation without any newlines. For backwards compatibility with versions of simplejson earlier than 2.1.0, an integer is also accepted and is converted to a string with that many spaces. If specified, separators should be an (item_separator, key_separator) tuple. The default is (', ', ': ') if *indent* is ``None`` and (',', ': ') otherwise. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace. If specified, default is a function that gets called for objects that can't otherwise be serialized. It should return a JSON encodable version of the object or raise a ``TypeError``. If encoding is not None, then all input strings will be transformed into unicode using that encoding prior to JSON-encoding. The default is UTF-8. If use_decimal is true (not the default), ``decimal.Decimal`` will be supported directly by the encoder. For the inverse, decode JSON with ``parse_float=decimal.Decimal``. If namedtuple_as_object is true (the default), objects with ``_asdict()`` methods will be encoded as JSON objects. If tuple_as_array is true (the default), tuple (and subclasses) will be encoded as JSON arrays. If bigint_as_string is true (not the default), ints 2**53 and higher or lower than -2**53 will be encoded as strings. This is to avoid the rounding that happens in Javascript otherwise. If int_as_string_bitcount is a positive number (n), then int of size greater than or equal to 2**n or lower than or equal to -2**n will be encoded as strings. If specified, item_sort_key is a callable used to sort the items in each dictionary. This is useful if you want to sort items other than in alphabetical order by key. If for_json is true (not the default), objects with a ``for_json()`` method will use the return value of that method for encoding as JSON instead of the object. If *ignore_nan* is true (default: ``False``), then out of range :class:`float` values (``nan``, ``inf``, ``-inf``) will be serialized as ``null`` in compliance with the ECMA-262 specification. If true, this will override *allow_nan*. """ self.skipkeys = skipkeys self.ensure_ascii = ensure_ascii self.check_circular = check_circular self.allow_nan = allow_nan self.sort_keys = sort_keys self.use_decimal = use_decimal self.namedtuple_as_object = namedtuple_as_object self.tuple_as_array = tuple_as_array self.bigint_as_string = bigint_as_string self.item_sort_key = item_sort_key self.for_json = for_json self.ignore_nan = ignore_nan self.int_as_string_bitcount = int_as_string_bitcount if indent is not None and not isinstance(indent, string_types): indent = indent * ' ' self.indent = indent if separators is not None: self.item_separator, self.key_separator = separators elif indent is not None: self.item_separator = ',' if default is not None: self.default = default self.encoding = encoding
[ "def", "__init__", "(", "self", ",", "skipkeys", "=", "False", ",", "ensure_ascii", "=", "True", ",", "check_circular", "=", "True", ",", "allow_nan", "=", "True", ",", "sort_keys", "=", "False", ",", "indent", "=", "None", ",", "separators", "=", "None"...
https://github.com/steeve/plugin.video.pulsar/blob/4b316e35e6427d31f2de7ba7c4cee46059db1100/resources/site-packages/simplejson/encoder.py#L120-L226
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
php_fpm/datadog_checks/php_fpm/vendor/fcgi_app.py
python
Record.__init__
(self, type=FCGI_UNKNOWN_TYPE, requestId=FCGI_NULL_REQUEST_ID)
[]
def __init__(self, type=FCGI_UNKNOWN_TYPE, requestId=FCGI_NULL_REQUEST_ID): self.version = FCGI_VERSION_1 self.type = type self.requestId = requestId self.contentLength = 0 self.paddingLength = 0 self.contentData = b''
[ "def", "__init__", "(", "self", ",", "type", "=", "FCGI_UNKNOWN_TYPE", ",", "requestId", "=", "FCGI_NULL_REQUEST_ID", ")", ":", "self", ".", "version", "=", "FCGI_VERSION_1", "self", ".", "type", "=", "type", "self", ".", "requestId", "=", "requestId", "self...
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/php_fpm/datadog_checks/php_fpm/vendor/fcgi_app.py#L156-L162
rucio/rucio
6d0d358e04f5431f0b9a98ae40f31af0ddff4833
lib/rucio/client/ruleclient.py
python
RuleClient.delete_replication_rule
(self, rule_id, purge_replicas=None)
Deletes a replication rule and all associated locks. :param rule_id: The id of the rule to be deleted :param purge_replicas: Immediately delete the replicas. :raises: RuleNotFound, AccessDenied
Deletes a replication rule and all associated locks.
[ "Deletes", "a", "replication", "rule", "and", "all", "associated", "locks", "." ]
def delete_replication_rule(self, rule_id, purge_replicas=None): """ Deletes a replication rule and all associated locks. :param rule_id: The id of the rule to be deleted :param purge_replicas: Immediately delete the replicas. :raises: RuleNotFound, AccessDenied """ path = self.RULE_BASEURL + '/' + rule_id url = build_url(choice(self.list_hosts), path=path) data = dumps({'purge_replicas': purge_replicas}) r = self._send_request(url, type_='DEL', data=data) if r.status_code == codes.ok: return True exc_cls, exc_msg = self._get_exception(headers=r.headers, status_code=r.status_code, data=r.content) raise exc_cls(exc_msg)
[ "def", "delete_replication_rule", "(", "self", ",", "rule_id", ",", "purge_replicas", "=", "None", ")", ":", "path", "=", "self", ".", "RULE_BASEURL", "+", "'/'", "+", "rule_id", "url", "=", "build_url", "(", "choice", "(", "self", ".", "list_hosts", ")", ...
https://github.com/rucio/rucio/blob/6d0d358e04f5431f0b9a98ae40f31af0ddff4833/lib/rucio/client/ruleclient.py#L89-L108
barseghyanartur/django-fobi
a998feae007d7fe3637429a80e42952ec7cda79f
src/fobi/integration/processors.py
python
IntegrationProcessor.get_form_template_name
(self, request, instance)
return instance.form_template_name or None
Get form template name.
Get form template name.
[ "Get", "form", "template", "name", "." ]
def get_form_template_name(self, request, instance): """Get form template name.""" return instance.form_template_name or None
[ "def", "get_form_template_name", "(", "self", ",", "request", ",", "instance", ")", ":", "return", "instance", ".", "form_template_name", "or", "None" ]
https://github.com/barseghyanartur/django-fobi/blob/a998feae007d7fe3637429a80e42952ec7cda79f/src/fobi/integration/processors.py#L84-L86
w3h/isf
6faf0a3df185465ec17369c90ccc16e2a03a1870
lib/thirdparty/DateTime/interfaces.py
python
IDateTime.aCommon
()
Return a string representing the object's value in the format: Mar 1, 1997 1:45 pm
Return a string representing the object's value in the format: Mar 1, 1997 1:45 pm
[ "Return", "a", "string", "representing", "the", "object", "s", "value", "in", "the", "format", ":", "Mar", "1", "1997", "1", ":", "45", "pm" ]
def aCommon(): """Return a string representing the object's value in the format: Mar 1, 1997 1:45 pm"""
[ "def", "aCommon", "(", ")", ":" ]
https://github.com/w3h/isf/blob/6faf0a3df185465ec17369c90ccc16e2a03a1870/lib/thirdparty/DateTime/interfaces.py#L288-L290
tribe29/checkmk
6260f2512e159e311f426e16b84b19d0b8e9ad0c
cmk/gui/plugins/wato/utils/base_modes.py
python
WatoMode.mode_url
(cls, **kwargs: str)
return makeuri_contextless(request, get_vars, filename="wato.py")
Create a URL pointing to this mode (with all needed vars)
Create a URL pointing to this mode (with all needed vars)
[ "Create", "a", "URL", "pointing", "to", "this", "mode", "(", "with", "all", "needed", "vars", ")" ]
def mode_url(cls, **kwargs: str) -> str: """Create a URL pointing to this mode (with all needed vars)""" get_vars: HTTPVariables = [("mode", cls.name())] get_vars += list(kwargs.items()) return makeuri_contextless(request, get_vars, filename="wato.py")
[ "def", "mode_url", "(", "cls", ",", "*", "*", "kwargs", ":", "str", ")", "->", "str", ":", "get_vars", ":", "HTTPVariables", "=", "[", "(", "\"mode\"", ",", "cls", ".", "name", "(", ")", ")", "]", "get_vars", "+=", "list", "(", "kwargs", ".", "it...
https://github.com/tribe29/checkmk/blob/6260f2512e159e311f426e16b84b19d0b8e9ad0c/cmk/gui/plugins/wato/utils/base_modes.py#L45-L49
CuriousAI/mean-teacher
546348ff863c998c26be4339021425df973b4a36
pytorch/main.py
python
parse_dict_args
(**kwargs)
[]
def parse_dict_args(**kwargs): global args def to_cmdline_kwarg(key, value): if len(key) == 1: key = "-{}".format(key) else: key = "--{}".format(re.sub(r"_", "-", key)) value = str(value) return key, value kwargs_pairs = (to_cmdline_kwarg(key, value) for key, value in kwargs.items()) cmdline_args = list(sum(kwargs_pairs, ())) args = parser.parse_args(cmdline_args)
[ "def", "parse_dict_args", "(", "*", "*", "kwargs", ")", ":", "global", "args", "def", "to_cmdline_kwarg", "(", "key", ",", "value", ")", ":", "if", "len", "(", "key", ")", "==", "1", ":", "key", "=", "\"-{}\"", ".", "format", "(", "key", ")", "else...
https://github.com/CuriousAI/mean-teacher/blob/546348ff863c998c26be4339021425df973b4a36/pytorch/main.py#L131-L145
baidu-security/openrasp-iast
d4a5643420853a95614d371cf38d5c65ccf9cfd4
openrasp_iast/core/model/base_model.py
python
BaseModel._create_model
(self, db, table_prefix)
子类实现此方法,构建对应数据表的peewee.Model类
子类实现此方法,构建对应数据表的peewee.Model类
[ "子类实现此方法,构建对应数据表的peewee", ".", "Model类" ]
def _create_model(self, db, table_prefix): """ 子类实现此方法,构建对应数据表的peewee.Model类 """ raise NotImplementedError
[ "def", "_create_model", "(", "self", ",", "db", ",", "table_prefix", ")", ":", "raise", "NotImplementedError" ]
https://github.com/baidu-security/openrasp-iast/blob/d4a5643420853a95614d371cf38d5c65ccf9cfd4/openrasp_iast/core/model/base_model.py#L160-L164
Nikolay-Kha/PyCNC
f5ae14b72b0dee7e24f1c323771936f1daa1da97
cnc/gcode.py
python
GCode.command
(self)
return None
Get value from gcode line. :return: String with command or None if no command specified.
Get value from gcode line. :return: String with command or None if no command specified.
[ "Get", "value", "from", "gcode", "line", ".", ":", "return", ":", "String", "with", "command", "or", "None", "if", "no", "command", "specified", "." ]
def command(self): """ Get value from gcode line. :return: String with command or None if no command specified. """ if 'G' in self.params: return 'G' + self.params['G'] if 'M' in self.params: return 'M' + self.params['M'] return None
[ "def", "command", "(", "self", ")", ":", "if", "'G'", "in", "self", ".", "params", ":", "return", "'G'", "+", "self", ".", "params", "[", "'G'", "]", "if", "'M'", "in", "self", ".", "params", ":", "return", "'M'", "+", "self", ".", "params", "[",...
https://github.com/Nikolay-Kha/PyCNC/blob/f5ae14b72b0dee7e24f1c323771936f1daa1da97/cnc/gcode.py#L76-L84
neulab/xnmt
d93f8f3710f986f36eb54e9ff3976a6b683da2a4
xnmt/modelparts/scorers.py
python
Scorer.calc_loss
(self, x: tt.Tensor, y: Union[int, List[int]])
Calculate the loss incurred by making a particular decision. Args: x: The vector used to make the prediction y: The correct label(s)
Calculate the loss incurred by making a particular decision.
[ "Calculate", "the", "loss", "incurred", "by", "making", "a", "particular", "decision", "." ]
def calc_loss(self, x: tt.Tensor, y: Union[int, List[int]]) -> tt.Tensor: """ Calculate the loss incurred by making a particular decision. Args: x: The vector used to make the prediction y: The correct label(s) """ raise NotImplementedError('calc_loss must be implemented by subclasses of Scorer')
[ "def", "calc_loss", "(", "self", ",", "x", ":", "tt", ".", "Tensor", ",", "y", ":", "Union", "[", "int", ",", "List", "[", "int", "]", "]", ")", "->", "tt", ".", "Tensor", ":", "raise", "NotImplementedError", "(", "'calc_loss must be implemented by subcl...
https://github.com/neulab/xnmt/blob/d93f8f3710f986f36eb54e9ff3976a6b683da2a4/xnmt/modelparts/scorers.py#L101-L109
SCons/scons
309f0234d1d9cc76955818be47c5c722f577dac6
SCons/SConf.py
python
SConfBase.TryCompile
( self, text, extension)
return self.TryBuild(self.env.Object, text, extension)
Compiles the program given in text to an env.Object, using extension as file extension (e.g. '.c'). Returns 1, if compilation was successful, 0 otherwise. The target is saved in self.lastTarget (for further processing).
Compiles the program given in text to an env.Object, using extension as file extension (e.g. '.c'). Returns 1, if compilation was successful, 0 otherwise. The target is saved in self.lastTarget (for further processing).
[ "Compiles", "the", "program", "given", "in", "text", "to", "an", "env", ".", "Object", "using", "extension", "as", "file", "extension", "(", "e", ".", "g", ".", ".", "c", ")", ".", "Returns", "1", "if", "compilation", "was", "successful", "0", "otherwi...
def TryCompile( self, text, extension): """Compiles the program given in text to an env.Object, using extension as file extension (e.g. '.c'). Returns 1, if compilation was successful, 0 otherwise. The target is saved in self.lastTarget (for further processing). """ return self.TryBuild(self.env.Object, text, extension)
[ "def", "TryCompile", "(", "self", ",", "text", ",", "extension", ")", ":", "return", "self", ".", "TryBuild", "(", "self", ".", "env", ".", "Object", ",", "text", ",", "extension", ")" ]
https://github.com/SCons/scons/blob/309f0234d1d9cc76955818be47c5c722f577dac6/SCons/SConf.py#L669-L675
vmware/vsphere-automation-sdk-python
ba7d4e0742f58a641dfed9538ecbbb1db4f3891e
samples/vsphere/vcenter/vm/create/create_basic_vm.py
python
main
()
[]
def main(): create_basic_vm = CreateBasicVM() create_basic_vm.cleanup() create_basic_vm.run() if create_basic_vm.cleardata: create_basic_vm.cleanup()
[ "def", "main", "(", ")", ":", "create_basic_vm", "=", "CreateBasicVM", "(", ")", "create_basic_vm", ".", "cleanup", "(", ")", "create_basic_vm", ".", "run", "(", ")", "if", "create_basic_vm", ".", "cleardata", ":", "create_basic_vm", ".", "cleanup", "(", ")"...
https://github.com/vmware/vsphere-automation-sdk-python/blob/ba7d4e0742f58a641dfed9538ecbbb1db4f3891e/samples/vsphere/vcenter/vm/create/create_basic_vm.py#L155-L160
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/ipython-4.0.0-py3.3.egg/IPython/core/inputtransformer.py
python
assign_from_system
(line)
return assign_system_template % m.group('lhs', 'cmd')
Transform assignment from system commands (e.g. files = !ls)
Transform assignment from system commands (e.g. files = !ls)
[ "Transform", "assignment", "from", "system", "commands", "(", "e", ".", "g", ".", "files", "=", "!ls", ")" ]
def assign_from_system(line): """Transform assignment from system commands (e.g. files = !ls)""" m = assign_system_re.match(line) if m is None: return line return assign_system_template % m.group('lhs', 'cmd')
[ "def", "assign_from_system", "(", "line", ")", ":", "m", "=", "assign_system_re", ".", "match", "(", "line", ")", "if", "m", "is", "None", ":", "return", "line", "return", "assign_system_template", "%", "m", ".", "group", "(", "'lhs'", ",", "'cmd'", ")" ...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/ipython-4.0.0-py3.3.egg/IPython/core/inputtransformer.py#L532-L538
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/tkinter/tix.py
python
ListNoteBook.pages
(self)
return ret
[]
def pages(self): # Can't call subwidgets_all directly because we don't want .nbframe names = self.tk.split(self.tk.call(self._w, 'pages')) ret = [] for x in names: ret.append(self.subwidget(x)) return ret
[ "def", "pages", "(", "self", ")", ":", "# Can't call subwidgets_all directly because we don't want .nbframe", "names", "=", "self", ".", "tk", ".", "split", "(", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'pages'", ")", ")", "ret", "=", ...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/tkinter/tix.py#L1131-L1137
tsroten/pynlpir
384fbd8c34312645ddeb11ca848686030d693f1f
pynlpir/__init__.py
python
get_key_words
(s, max_words=50, weighted=False)
return fresult
Determines key words in Chinese text *s*. The key words are returned in a list. If *weighted* is ``True``, then each list item is a tuple: ``(word, weight)``, where *weight* is a float. If it's *False*, then each list item is a string. This uses the function :func:`~pynlpir.nlpir.GetKeyWords` to determine the key words in *s*. :param s: The Chinese text to analyze. *s* should be Unicode or a UTF-8 encoded string. :param int max_words: The maximum number of key words to find (defaults to ``50``). :param bool weighted: Whether or not to return the key words' weights (defaults to ``True``).
Determines key words in Chinese text *s*.
[ "Determines", "key", "words", "in", "Chinese", "text", "*", "s", "*", "." ]
def get_key_words(s, max_words=50, weighted=False): """Determines key words in Chinese text *s*. The key words are returned in a list. If *weighted* is ``True``, then each list item is a tuple: ``(word, weight)``, where *weight* is a float. If it's *False*, then each list item is a string. This uses the function :func:`~pynlpir.nlpir.GetKeyWords` to determine the key words in *s*. :param s: The Chinese text to analyze. *s* should be Unicode or a UTF-8 encoded string. :param int max_words: The maximum number of key words to find (defaults to ``50``). :param bool weighted: Whether or not to return the key words' weights (defaults to ``True``). """ s = _decode(s) logger.debug("Searching for up to {}{} key words in: {}.".format( max_words, ' weighted' if weighted else '', s)) result = nlpir.GetKeyWords(_encode(s), max_words, weighted) result = _decode(result) logger.debug("Finished key word search: {}.".format(result)) logger.debug("Formatting key word search results.") fresult = result.strip('#').split('#') if result else [] if weighted: weights, words = [], [] for w in fresult: result = w.split('/') word, weight = result[0], result[2] weight = _to_float(weight) weights.append(weight or 0.0) words.append(word) fresult = zip(words, weights) if is_python3: # Return a list instead of a zip object in Python 3. fresult = list(fresult) logger.debug("Key words formatted: {}.".format(fresult)) return fresult
[ "def", "get_key_words", "(", "s", ",", "max_words", "=", "50", ",", "weighted", "=", "False", ")", ":", "s", "=", "_decode", "(", "s", ")", "logger", ".", "debug", "(", "\"Searching for up to {}{} key words in: {}.\"", ".", "format", "(", "max_words", ",", ...
https://github.com/tsroten/pynlpir/blob/384fbd8c34312645ddeb11ca848686030d693f1f/pynlpir/__init__.py#L260-L299
pykaldi/pykaldi
b4e7a15a31286e57c01259edfda54d113b5ceb0e
kaldi/lat/functions.py
python
top_sort_lattice_if_needed
(lat)
Topologically sorts the lattice if it is not already sorted. Args: lat (LatticeVectorFst or CompactLatticeVectorFst): The input lattice. Raises: RuntimeError: If lattice cannot be topologically sorted.
Topologically sorts the lattice if it is not already sorted.
[ "Topologically", "sorts", "the", "lattice", "if", "it", "is", "not", "already", "sorted", "." ]
def top_sort_lattice_if_needed(lat): """Topologically sorts the lattice if it is not already sorted. Args: lat (LatticeVectorFst or CompactLatticeVectorFst): The input lattice. Raises: RuntimeError: If lattice cannot be topologically sorted. """ if isinstance(lat, _fst.LatticeVectorFst): _lat_fun._top_sort_lattice_if_needed(lat) else: _lat_fun._top_sort_compact_lattice_if_needed(lat)
[ "def", "top_sort_lattice_if_needed", "(", "lat", ")", ":", "if", "isinstance", "(", "lat", ",", "_fst", ".", "LatticeVectorFst", ")", ":", "_lat_fun", ".", "_top_sort_lattice_if_needed", "(", "lat", ")", "else", ":", "_lat_fun", ".", "_top_sort_compact_lattice_if_...
https://github.com/pykaldi/pykaldi/blob/b4e7a15a31286e57c01259edfda54d113b5ceb0e/kaldi/lat/functions.py#L204-L216
Kismuz/btgym
7fb3316e67f1d7a17c620630fb62fb29428b2cec
btgym/algorithms/policy/base.py
python
BaseAacPolicy.get_sample_config
(*args, **kwargs)
return EnvResetConfig
Dummy implementation. Returns: default data sample configuration dictionary `btgym.datafeed.base.EnvResetConfig`
Dummy implementation.
[ "Dummy", "implementation", "." ]
def get_sample_config(*args, **kwargs): """ Dummy implementation. Returns: default data sample configuration dictionary `btgym.datafeed.base.EnvResetConfig` """ return EnvResetConfig
[ "def", "get_sample_config", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "EnvResetConfig" ]
https://github.com/Kismuz/btgym/blob/7fb3316e67f1d7a17c620630fb62fb29428b2cec/btgym/algorithms/policy/base.py#L389-L396
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/ma/core.py
python
masked_outside
(x, v1, v2, copy=True)
return masked_where(condition, x, copy=copy)
Mask an array outside a given interval. Shortcut to ``masked_where``, where `condition` is True for `x` outside the interval [v1,v2] (x < v1)|(x > v2). The boundaries `v1` and `v2` can be given in either order. See Also -------- masked_where : Mask where a condition is met. Notes ----- The array `x` is prefilled with its filling value. Examples -------- >>> import numpy.ma as ma >>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1] >>> ma.masked_outside(x, -0.3, 0.3) masked_array(data = [-- -- 0.01 0.2 -- --], mask = [ True True False False True True], fill_value=1e+20) The order of `v1` and `v2` doesn't matter. >>> ma.masked_outside(x, 0.3, -0.3) masked_array(data = [-- -- 0.01 0.2 -- --], mask = [ True True False False True True], fill_value=1e+20)
Mask an array outside a given interval.
[ "Mask", "an", "array", "outside", "a", "given", "interval", "." ]
def masked_outside(x, v1, v2, copy=True): """ Mask an array outside a given interval. Shortcut to ``masked_where``, where `condition` is True for `x` outside the interval [v1,v2] (x < v1)|(x > v2). The boundaries `v1` and `v2` can be given in either order. See Also -------- masked_where : Mask where a condition is met. Notes ----- The array `x` is prefilled with its filling value. Examples -------- >>> import numpy.ma as ma >>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1] >>> ma.masked_outside(x, -0.3, 0.3) masked_array(data = [-- -- 0.01 0.2 -- --], mask = [ True True False False True True], fill_value=1e+20) The order of `v1` and `v2` doesn't matter. >>> ma.masked_outside(x, 0.3, -0.3) masked_array(data = [-- -- 0.01 0.2 -- --], mask = [ True True False False True True], fill_value=1e+20) """ if v2 < v1: (v1, v2) = (v2, v1) xf = filled(x) condition = (xf < v1) | (xf > v2) return masked_where(condition, x, copy=copy)
[ "def", "masked_outside", "(", "x", ",", "v1", ",", "v2", ",", "copy", "=", "True", ")", ":", "if", "v2", "<", "v1", ":", "(", "v1", ",", "v2", ")", "=", "(", "v2", ",", "v1", ")", "xf", "=", "filled", "(", "x", ")", "condition", "=", "(", ...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/ma/core.py#L2031-L2068
privacyidea/privacyidea
9490c12ddbf77a34ac935b082d09eb583dfafa2c
privacyidea/lib/tokenclass.py
python
TokenClass.get_setting_type
(key)
return ""
This function returns the type of the token specific config/setting. This way a tokenclass can define settings, that can be "public" or a "password". If this setting is written to the database, the type of the setting is set automatically in set_privacyidea_config The key name needs to start with the token type. :param key: The token specific setting key :return: A string like "public"
This function returns the type of the token specific config/setting. This way a tokenclass can define settings, that can be "public" or a "password". If this setting is written to the database, the type of the setting is set automatically in set_privacyidea_config
[ "This", "function", "returns", "the", "type", "of", "the", "token", "specific", "config", "/", "setting", ".", "This", "way", "a", "tokenclass", "can", "define", "settings", "that", "can", "be", "public", "or", "a", "password", ".", "If", "this", "setting"...
def get_setting_type(key): """ This function returns the type of the token specific config/setting. This way a tokenclass can define settings, that can be "public" or a "password". If this setting is written to the database, the type of the setting is set automatically in set_privacyidea_config The key name needs to start with the token type. :param key: The token specific setting key :return: A string like "public" """ return ""
[ "def", "get_setting_type", "(", "key", ")", ":", "return", "\"\"" ]
https://github.com/privacyidea/privacyidea/blob/9490c12ddbf77a34ac935b082d09eb583dfafa2c/privacyidea/lib/tokenclass.py#L1661-L1673
python-telegram-bot/python-telegram-bot
ade1529986f5b6d394a65372d6a27045a70725b2
telegram/bot.py
python
Bot.answer_inline_query
( self, inline_query_id: str, results: Union[ Sequence['InlineQueryResult'], Callable[[int], Optional[Sequence['InlineQueryResult']]] ], cache_time: int = 300, is_personal: bool = None, next_offset: str = None, switch_pm_text: str = None, switch_pm_parameter: str = None, timeout: ODVInput[float] = DEFAULT_NONE, current_offset: str = None, api_kwargs: JSONDict = None, )
return self._post( # type: ignore[return-value] 'answerInlineQuery', data, timeout=timeout, api_kwargs=api_kwargs, )
Use this method to send answers to an inline query. No more than 50 results per query are allowed. Warning: In most use cases :attr:`current_offset` should not be passed manually. Instead of calling this method directly, use the shortcut :meth:`telegram.InlineQuery.answer` with ``auto_pagination=True``, which will take care of passing the correct value. Args: inline_query_id (:obj:`str`): Unique identifier for the answered query. results (List[:class:`telegram.InlineQueryResult`] | Callable): A list of results for the inline query. In case :attr:`current_offset` is passed, ``results`` may also be a callable that accepts the current page index starting from 0. It must return either a list of :class:`telegram.InlineQueryResult` instances or :obj:`None` if there are no more results. cache_time (:obj:`int`, optional): The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to ``300``. is_personal (:obj:`bool`, optional): Pass :obj:`True`, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query. next_offset (:obj:`str`, optional): Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don't support pagination. Offset length can't exceed 64 bytes. switch_pm_text (:obj:`str`, optional): If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter ``switch_pm_parameter``. switch_pm_parameter (:obj:`str`, optional): Deep-linking parameter for the /start message sent to the bot when user presses the switch button. 1-64 characters, only A-Z, a-z, 0-9, _ and - are allowed. current_offset (:obj:`str`, optional): The :attr:`telegram.InlineQuery.offset` of the inline query to answer. If passed, PTB will automatically take care of the pagination for you, i.e. pass the correct ``next_offset`` and truncate the results list/get the results from the callable you passed. timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). api_kwargs (:obj:`dict`, optional): Arbitrary keyword arguments to be passed to the Telegram API. Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a 'Connect your YouTube account' button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an oauth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities. Returns: :obj:`bool`: On success, :obj:`True` is returned. Raises: :class:`telegram.error.TelegramError`
Use this method to send answers to an inline query. No more than 50 results per query are allowed.
[ "Use", "this", "method", "to", "send", "answers", "to", "an", "inline", "query", ".", "No", "more", "than", "50", "results", "per", "query", "are", "allowed", "." ]
def answer_inline_query( self, inline_query_id: str, results: Union[ Sequence['InlineQueryResult'], Callable[[int], Optional[Sequence['InlineQueryResult']]] ], cache_time: int = 300, is_personal: bool = None, next_offset: str = None, switch_pm_text: str = None, switch_pm_parameter: str = None, timeout: ODVInput[float] = DEFAULT_NONE, current_offset: str = None, api_kwargs: JSONDict = None, ) -> bool: """ Use this method to send answers to an inline query. No more than 50 results per query are allowed. Warning: In most use cases :attr:`current_offset` should not be passed manually. Instead of calling this method directly, use the shortcut :meth:`telegram.InlineQuery.answer` with ``auto_pagination=True``, which will take care of passing the correct value. Args: inline_query_id (:obj:`str`): Unique identifier for the answered query. results (List[:class:`telegram.InlineQueryResult`] | Callable): A list of results for the inline query. In case :attr:`current_offset` is passed, ``results`` may also be a callable that accepts the current page index starting from 0. It must return either a list of :class:`telegram.InlineQueryResult` instances or :obj:`None` if there are no more results. cache_time (:obj:`int`, optional): The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to ``300``. is_personal (:obj:`bool`, optional): Pass :obj:`True`, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query. next_offset (:obj:`str`, optional): Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don't support pagination. Offset length can't exceed 64 bytes. switch_pm_text (:obj:`str`, optional): If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter ``switch_pm_parameter``. switch_pm_parameter (:obj:`str`, optional): Deep-linking parameter for the /start message sent to the bot when user presses the switch button. 1-64 characters, only A-Z, a-z, 0-9, _ and - are allowed. current_offset (:obj:`str`, optional): The :attr:`telegram.InlineQuery.offset` of the inline query to answer. If passed, PTB will automatically take care of the pagination for you, i.e. pass the correct ``next_offset`` and truncate the results list/get the results from the callable you passed. timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). api_kwargs (:obj:`dict`, optional): Arbitrary keyword arguments to be passed to the Telegram API. Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a 'Connect your YouTube account' button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an oauth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities. Returns: :obj:`bool`: On success, :obj:`True` is returned. Raises: :class:`telegram.error.TelegramError` """ @no_type_check def _set_defaults(res): # pylint: disable=W0212 if hasattr(res, 'parse_mode') and res.parse_mode == DEFAULT_NONE: if self.defaults: res.parse_mode = self.defaults.parse_mode else: res.parse_mode = None if hasattr(res, 'input_message_content') and res.input_message_content: if ( hasattr(res.input_message_content, 'parse_mode') and res.input_message_content.parse_mode == DEFAULT_NONE ): if self.defaults: res.input_message_content.parse_mode = DefaultValue.get_value( self.defaults.parse_mode ) else: res.input_message_content.parse_mode = None if ( hasattr(res.input_message_content, 'disable_web_page_preview') and res.input_message_content.disable_web_page_preview == DEFAULT_NONE ): if self.defaults: res.input_message_content.disable_web_page_preview = ( DefaultValue.get_value(self.defaults.disable_web_page_preview) ) else: res.input_message_content.disable_web_page_preview = None effective_results, next_offset = self._effective_inline_results( results=results, next_offset=next_offset, current_offset=current_offset ) # Apply defaults for result in effective_results: _set_defaults(result) results_dicts = [res.to_dict() for res in effective_results] data: JSONDict = {'inline_query_id': inline_query_id, 'results': results_dicts} if cache_time or cache_time == 0: data['cache_time'] = cache_time if is_personal: data['is_personal'] = is_personal if next_offset is not None: data['next_offset'] = next_offset if switch_pm_text: data['switch_pm_text'] = switch_pm_text if switch_pm_parameter: data['switch_pm_parameter'] = switch_pm_parameter return self._post( # type: ignore[return-value] 'answerInlineQuery', data, timeout=timeout, api_kwargs=api_kwargs, )
[ "def", "answer_inline_query", "(", "self", ",", "inline_query_id", ":", "str", ",", "results", ":", "Union", "[", "Sequence", "[", "'InlineQueryResult'", "]", ",", "Callable", "[", "[", "int", "]", ",", "Optional", "[", "Sequence", "[", "'InlineQueryResult'", ...
https://github.com/python-telegram-bot/python-telegram-bot/blob/ade1529986f5b6d394a65372d6a27045a70725b2/telegram/bot.py#L2201-L2332
CenterForOpenScience/osf.io
cc02691be017e61e2cd64f19b848b2f4c18dcc84
tasks/utils.py
python
pip_install
(req_file, constraints_file=None)
return cmd
Return the proper 'pip install' command for installing the dependencies defined in ``req_file``. Optionally obey a file of constraints in case of version conflicts
Return the proper 'pip install' command for installing the dependencies defined in ``req_file``. Optionally obey a file of constraints in case of version conflicts
[ "Return", "the", "proper", "pip", "install", "command", "for", "installing", "the", "dependencies", "defined", "in", "req_file", ".", "Optionally", "obey", "a", "file", "of", "constraints", "in", "case", "of", "version", "conflicts" ]
def pip_install(req_file, constraints_file=None): """ Return the proper 'pip install' command for installing the dependencies defined in ``req_file``. Optionally obey a file of constraints in case of version conflicts """ cmd = bin_prefix('pip3 install --exists-action w --upgrade -r {} '.format(req_file)) if constraints_file: # Support added in pip 7.1 cmd += ' -c {}'.format(constraints_file) if WHEELHOUSE_PATH: cmd += ' --no-index --find-links={}'.format(WHEELHOUSE_PATH) return cmd
[ "def", "pip_install", "(", "req_file", ",", "constraints_file", "=", "None", ")", ":", "cmd", "=", "bin_prefix", "(", "'pip3 install --exists-action w --upgrade -r {} '", ".", "format", "(", "req_file", ")", ")", "if", "constraints_file", ":", "# Support added in pip ...
https://github.com/CenterForOpenScience/osf.io/blob/cc02691be017e61e2cd64f19b848b2f4c18dcc84/tasks/utils.py#L18-L29
huawei-noah/vega
d9f13deede7f2b584e4b1d32ffdb833856129989
examples/fully_train/fmd/networks/resnet_cifar.py
python
conv3x3
(in_planes, out_planes, stride=1)
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
3x3 convolution with padding. :param in_plane: size of input plane :type in_plane: int :param out_plane: size of output plane :type out_plane: int :param stride: stride of convolutional layers, default 1 :type stride: int :return: Conv2d value. :rtype: Tensor
3x3 convolution with padding.
[ "3x3", "convolution", "with", "padding", "." ]
def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding. :param in_plane: size of input plane :type in_plane: int :param out_plane: size of output plane :type out_plane: int :param stride: stride of convolutional layers, default 1 :type stride: int :return: Conv2d value. :rtype: Tensor """ return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
[ "def", "conv3x3", "(", "in_planes", ",", "out_planes", ",", "stride", "=", "1", ")", ":", "return", "nn", ".", "Conv2d", "(", "in_planes", ",", "out_planes", ",", "kernel_size", "=", "3", ",", "stride", "=", "stride", ",", "padding", "=", "1", ",", "...
https://github.com/huawei-noah/vega/blob/d9f13deede7f2b584e4b1d32ffdb833856129989/examples/fully_train/fmd/networks/resnet_cifar.py#L25-L38
nfcpy/nfcpy
acc6d3287d419c614f2b9a28ef9ce8326683b9c3
src/nfc/clf/pn532.py
python
Device.listen_ttf
(self, target, timeout)
return super(Device, self).listen_ttf(target, timeout)
Listen *timeout* seconds for a Type F card activation. The target ``brty`` must be set to either 212F or 424F and ``sensf_res`` provide 19 byte response data (response code + 8 byte IDm + 8 byte PMm + 2 byte system code). Note that the maximum command an response frame length is 64 bytes only (including the frame length byte), because the driver must directly program the contactless interface unit within the PN533.
Listen *timeout* seconds for a Type F card activation. The target ``brty`` must be set to either 212F or 424F and ``sensf_res`` provide 19 byte response data (response code + 8 byte IDm + 8 byte PMm + 2 byte system code). Note that the maximum command an response frame length is 64 bytes only (including the frame length byte), because the driver must directly program the contactless interface unit within the PN533.
[ "Listen", "*", "timeout", "*", "seconds", "for", "a", "Type", "F", "card", "activation", ".", "The", "target", "brty", "must", "be", "set", "to", "either", "212F", "or", "424F", "and", "sensf_res", "provide", "19", "byte", "response", "data", "(", "respo...
def listen_ttf(self, target, timeout): """Listen *timeout* seconds for a Type F card activation. The target ``brty`` must be set to either 212F or 424F and ``sensf_res`` provide 19 byte response data (response code + 8 byte IDm + 8 byte PMm + 2 byte system code). Note that the maximum command an response frame length is 64 bytes only (including the frame length byte), because the driver must directly program the contactless interface unit within the PN533. """ return super(Device, self).listen_ttf(target, timeout)
[ "def", "listen_ttf", "(", "self", ",", "target", ",", "timeout", ")", ":", "return", "super", "(", "Device", ",", "self", ")", ".", "listen_ttf", "(", "target", ",", "timeout", ")" ]
https://github.com/nfcpy/nfcpy/blob/acc6d3287d419c614f2b9a28ef9ce8326683b9c3/src/nfc/clf/pn532.py#L345-L355
nansencenter/nansat
5700ec673fbf522c19b8dedcb01cc15f7cd29a6a
nansat/mappers/scatterometers.py
python
Mapper.shift_longitudes
(lon)
return np.mod(lon+180., 360.) - 180.
Apply correction of longitudes (they are defined on 0:360 degrees but also contain egative values) TODO: consider making this core to nansat - different ways of defining longitudes (-180:180 og 0:360 degrees) often cause problems...
Apply correction of longitudes (they are defined on 0:360 degrees but also contain egative values)
[ "Apply", "correction", "of", "longitudes", "(", "they", "are", "defined", "on", "0", ":", "360", "degrees", "but", "also", "contain", "egative", "values", ")" ]
def shift_longitudes(lon): """ Apply correction of longitudes (they are defined on 0:360 degrees but also contain egative values) TODO: consider making this core to nansat - different ways of defining longitudes (-180:180 og 0:360 degrees) often cause problems... """ return np.mod(lon+180., 360.) - 180.
[ "def", "shift_longitudes", "(", "lon", ")", ":", "return", "np", ".", "mod", "(", "lon", "+", "180.", ",", "360.", ")", "-", "180." ]
https://github.com/nansencenter/nansat/blob/5700ec673fbf522c19b8dedcb01cc15f7cd29a6a/nansat/mappers/scatterometers.py#L94-L101
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gui/editors/displaytabs/repoembedlist.py
python
RepoEmbedList._connect_db_signals
(self)
Implement base class DbGUIElement method
Implement base class DbGUIElement method
[ "Implement", "base", "class", "DbGUIElement", "method" ]
def _connect_db_signals(self): """ Implement base class DbGUIElement method """ #note: repository-rebuild closes the editors, so no need to connect self.callman.register_callbacks( {'repository-delete': self.repo_delete, # delete a repo we track 'repository-update': self.repo_update, # change a repo we track }) self.callman.connect_all(keys=['repository'])
[ "def", "_connect_db_signals", "(", "self", ")", ":", "#note: repository-rebuild closes the editors, so no need to connect", "self", ".", "callman", ".", "register_callbacks", "(", "{", "'repository-delete'", ":", "self", ".", "repo_delete", ",", "# delete a repo we track", ...
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gui/editors/displaytabs/repoembedlist.py#L82-L91
web2py/web2py
095905c4e010a1426c729483d912e270a51b7ba8
gluon/contrib/pysimplesoap/client.py
python
SoapClient.wsdl_validate_params
(self, struct, value)
return (valid, errors, warnings)
Validate the arguments (actual values) for the parameters structure. Fail for any invalid arguments or type mismatches.
Validate the arguments (actual values) for the parameters structure. Fail for any invalid arguments or type mismatches.
[ "Validate", "the", "arguments", "(", "actual", "values", ")", "for", "the", "parameters", "structure", ".", "Fail", "for", "any", "invalid", "arguments", "or", "type", "mismatches", "." ]
def wsdl_validate_params(self, struct, value): """Validate the arguments (actual values) for the parameters structure. Fail for any invalid arguments or type mismatches.""" errors = [] warnings = [] valid = True # Determine parameter type if type(struct) == type(value): typematch = True if not isinstance(struct, dict) and isinstance(value, dict): typematch = True # struct can be a dict or derived (Struct) else: typematch = False if struct == str: struct = unicode # fix for py2 vs py3 string handling if not isinstance(struct, (list, dict, tuple)) and struct in TYPE_MAP.keys(): if not type(value) == struct and value is not None: try: struct(value) # attempt to cast input to parameter type except: valid = False errors.append('Type mismatch for argument value. parameter(%s): %s, value(%s): %s' % (type(struct), struct, type(value), value)) elif isinstance(struct, list) and len(struct) == 1 and not isinstance(value, list): # parameter can have a dict in a list: [{}] indicating a list is allowed, but not needed if only one argument. next_valid, next_errors, next_warnings = self.wsdl_validate_params(struct[0], value) if not next_valid: valid = False errors.extend(next_errors) warnings.extend(next_warnings) # traverse tree elif isinstance(struct, dict): if struct and value: for key in value: if key not in struct: valid = False errors.append('Argument key %s not in parameter. parameter: %s, args: %s' % (key, struct, value)) else: next_valid, next_errors, next_warnings = self.wsdl_validate_params(struct[key], value[key]) if not next_valid: valid = False errors.extend(next_errors) warnings.extend(next_warnings) for key in struct: if key not in value: warnings.append('Parameter key %s not in args. parameter: %s, value: %s' % (key, struct, value)) elif struct and not value: warnings.append('parameter keys not in args. parameter: %s, args: %s' % (struct, value)) elif not struct and value: valid = False errors.append('Args keys not in parameter. parameter: %s, args: %s' % (struct, value)) else: pass elif isinstance(struct, list): struct_list_value = struct[0] for item in value: next_valid, next_errors, next_warnings = self.wsdl_validate_params(struct_list_value, item) if not next_valid: valid = False errors.extend(next_errors) warnings.extend(next_warnings) elif not typematch: valid = False errors.append('Type mismatch. parameter(%s): %s, value(%s): %s' % (type(struct), struct, type(value), value)) return (valid, errors, warnings)
[ "def", "wsdl_validate_params", "(", "self", ",", "struct", ",", "value", ")", ":", "errors", "=", "[", "]", "warnings", "=", "[", "]", "valid", "=", "True", "# Determine parameter type", "if", "type", "(", "struct", ")", "==", "type", "(", "value", ")", ...
https://github.com/web2py/web2py/blob/095905c4e010a1426c729483d912e270a51b7ba8/gluon/contrib/pysimplesoap/client.py#L432-L501
fabioz/PyDev.Debugger
0f8c02a010fe5690405da1dd30ed72326191ce63
pydevd_attach_to_process/winappdbg/module.py
python
Module.unload_symbols
(self)
Unloads the debugging symbols for a module.
Unloads the debugging symbols for a module.
[ "Unloads", "the", "debugging", "symbols", "for", "a", "module", "." ]
def unload_symbols(self): """ Unloads the debugging symbols for a module. """ self.__symbols = list()
[ "def", "unload_symbols", "(", "self", ")", ":", "self", ".", "__symbols", "=", "list", "(", ")" ]
https://github.com/fabioz/PyDev.Debugger/blob/0f8c02a010fe5690405da1dd30ed72326191ce63/pydevd_attach_to_process/winappdbg/module.py#L513-L517
tav/pylibs
3c16b843681f54130ee6a022275289cadb2f2a69
mako/lookup.py
python
TemplateCollection.adjust_uri
(self, uri, filename)
return uri
Adjust the given uri based on the calling filename. When this method is called from the runtime, the 'filename' parameter is taken directly to the 'filename' attribute of the calling template. Therefore a custom TemplateCollection subclass can place any string identifier desired in the "filename" parameter of the Template objects it constructs and have them come back here.
Adjust the given uri based on the calling filename. When this method is called from the runtime, the 'filename' parameter is taken directly to the 'filename' attribute of the calling template. Therefore a custom TemplateCollection subclass can place any string identifier desired in the "filename" parameter of the Template objects it constructs and have them come back here.
[ "Adjust", "the", "given", "uri", "based", "on", "the", "calling", "filename", ".", "When", "this", "method", "is", "called", "from", "the", "runtime", "the", "filename", "parameter", "is", "taken", "directly", "to", "the", "filename", "attribute", "of", "the...
def adjust_uri(self, uri, filename): """Adjust the given uri based on the calling filename. When this method is called from the runtime, the 'filename' parameter is taken directly to the 'filename' attribute of the calling template. Therefore a custom TemplateCollection subclass can place any string identifier desired in the "filename" parameter of the Template objects it constructs and have them come back here. """ return uri
[ "def", "adjust_uri", "(", "self", ",", "uri", ",", "filename", ")", ":", "return", "uri" ]
https://github.com/tav/pylibs/blob/3c16b843681f54130ee6a022275289cadb2f2a69/mako/lookup.py#L34-L44
kpreid/shinysdr
25022d36903ff67e036e82a22b6555a12a4d8e8a
shinysdr/i/config.py
python
Config.wait_for
(self, deferred)
Wait for the provided Deferred before assuming the configuration to be finished.
Wait for the provided Deferred before assuming the configuration to be finished.
[ "Wait", "for", "the", "provided", "Deferred", "before", "assuming", "the", "configuration", "to", "be", "finished", "." ]
def wait_for(self, deferred): """Wait for the provided Deferred before assuming the configuration to be finished.""" self._not_finished() self.__waiting.append(defer.maybeDeferred(lambda: deferred))
[ "def", "wait_for", "(", "self", ",", "deferred", ")", ":", "self", ".", "_not_finished", "(", ")", "self", ".", "__waiting", ".", "append", "(", "defer", ".", "maybeDeferred", "(", "lambda", ":", "deferred", ")", ")" ]
https://github.com/kpreid/shinysdr/blob/25022d36903ff67e036e82a22b6555a12a4d8e8a/shinysdr/i/config.py#L109-L112
allenai/deep_qa
48b4340650ec70b801ec93adfdf651bde9c0546e
deep_qa/data/instances/instance.py
python
TextInstance.read_from_line
(cls, line: str)
Reads an instance of this type from a line. Parameters ---------- line : str A line from a data file. Returns ------- indexed_instance : IndexedInstance A ``TextInstance`` that has had all of its strings converted into indices. Notes ----- We throw a ``RuntimeError`` here instead of a ``NotImplementedError``, because it's not expected that all subclasses will implement this.
Reads an instance of this type from a line.
[ "Reads", "an", "instance", "of", "this", "type", "from", "a", "line", "." ]
def read_from_line(cls, line: str): """ Reads an instance of this type from a line. Parameters ---------- line : str A line from a data file. Returns ------- indexed_instance : IndexedInstance A ``TextInstance`` that has had all of its strings converted into indices. Notes ----- We throw a ``RuntimeError`` here instead of a ``NotImplementedError``, because it's not expected that all subclasses will implement this. """ # pylint: disable=unused-argument raise RuntimeError("%s instances can't be read from a line!" % str(cls))
[ "def", "read_from_line", "(", "cls", ",", "line", ":", "str", ")", ":", "# pylint: disable=unused-argument", "raise", "RuntimeError", "(", "\"%s instances can't be read from a line!\"", "%", "str", "(", "cls", ")", ")" ]
https://github.com/allenai/deep_qa/blob/48b4340650ec70b801ec93adfdf651bde9c0546e/deep_qa/data/instances/instance.py#L120-L142
skyhehe123/SA-SSD
2d75c973af65453186bd9242d7fa5e62dc44ec03
mmdet/datasets/utils.py
python
random_scale
(img_scales, mode='range')
return img_scale
Randomly select a scale from a list of scales or scale ranges. Args: img_scales (list[tuple]): Image scale or scale range. mode (str): "range" or "value". Returns: tuple: Sampled image scale.
Randomly select a scale from a list of scales or scale ranges.
[ "Randomly", "select", "a", "scale", "from", "a", "list", "of", "scales", "or", "scale", "ranges", "." ]
def random_scale(img_scales, mode='range'): """Randomly select a scale from a list of scales or scale ranges. Args: img_scales (list[tuple]): Image scale or scale range. mode (str): "range" or "value". Returns: tuple: Sampled image scale. """ num_scales = len(img_scales) if num_scales == 1: # fixed scale is specified img_scale = img_scales[0] elif num_scales == 2: # randomly sample a scale if mode == 'range': img_scale_long = [max(s) for s in img_scales] img_scale_short = [min(s) for s in img_scales] long_edge = np.random.randint( min(img_scale_long), max(img_scale_long) + 1) short_edge = np.random.randint( min(img_scale_short), max(img_scale_short) + 1) img_scale = (long_edge, short_edge) elif mode == 'value': img_scale = img_scales[np.random.randint(num_scales)] else: if mode != 'value': raise ValueError( 'Only "value" mode supports more than 2 image scales') img_scale = img_scales[np.random.randint(num_scales)] return img_scale
[ "def", "random_scale", "(", "img_scales", ",", "mode", "=", "'range'", ")", ":", "num_scales", "=", "len", "(", "img_scales", ")", "if", "num_scales", "==", "1", ":", "# fixed scale is specified", "img_scale", "=", "img_scales", "[", "0", "]", "elif", "num_s...
https://github.com/skyhehe123/SA-SSD/blob/2d75c973af65453186bd9242d7fa5e62dc44ec03/mmdet/datasets/utils.py#L39-L70
CouchPotato/CouchPotatoV1
135b3331d1b88ef645e29b76f2d4cc4a732c9232
library/imdb/Movie.py
python
Movie.isSameTitle
(self, other)
return 0
Return true if this and the compared object have the same long imdb title and/or movieID.
Return true if this and the compared object have the same long imdb title and/or movieID.
[ "Return", "true", "if", "this", "and", "the", "compared", "object", "have", "the", "same", "long", "imdb", "title", "and", "/", "or", "movieID", "." ]
def isSameTitle(self, other): """Return true if this and the compared object have the same long imdb title and/or movieID. """ # XXX: obsolete? if not isinstance(other, self.__class__): return 0 if self.data.has_key('title') and \ other.data.has_key('title') and \ build_title(self.data, canonical=0) == \ build_title(other.data, canonical=0): return 1 if self.accessSystem == other.accessSystem and \ self.movieID is not None and self.movieID == other.movieID: return 1 return 0
[ "def", "isSameTitle", "(", "self", ",", "other", ")", ":", "# XXX: obsolete?", "if", "not", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", ":", "return", "0", "if", "self", ".", "data", ".", "has_key", "(", "'title'", ")", "and", "othe...
https://github.com/CouchPotato/CouchPotatoV1/blob/135b3331d1b88ef645e29b76f2d4cc4a732c9232/library/imdb/Movie.py#L270-L284
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
appveyor/windows_templates/build_windows_templates.py
python
WindowsTemplateBuilder.SetupVars
(self)
Set up some vars for the directories we use.
Set up some vars for the directories we use.
[ "Set", "up", "some", "vars", "for", "the", "directories", "we", "use", "." ]
def SetupVars(self): """Set up some vars for the directories we use.""" # Python paths chosen to match appveyor: # http://www.appveyor.com/docs/installed-software#python self.virtualenv64 = os.path.join(args.build_dir, "python_64") self.grr_client_build64 = "grr_client_build" self.virtualenv_python64 = os.path.join(self.virtualenv64, r"Scripts\python.exe") self.git = r"git" self.install_path = r"C:\Windows\System32\GRR" self.service_name = "GRR Monitor" self.expect_service_running = args.expect_service_running
[ "def", "SetupVars", "(", "self", ")", ":", "# Python paths chosen to match appveyor:", "# http://www.appveyor.com/docs/installed-software#python", "self", ".", "virtualenv64", "=", "os", ".", "path", ".", "join", "(", "args", ".", "build_dir", ",", "\"python_64\"", ")",...
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/appveyor/windows_templates/build_windows_templates.py#L141-L156
python-control/python-control
df6b35212f8f657469627c227c893a175a6902cc
control/matlab/timeresp.py
python
lsim
(sys, U=0., T=None, X0=0.)
return out[1], out[0], out[2]
Simulate the output of a linear system. As a convenience for parameters `U`, `X0`: Numbers (scalars) are converted to constant arrays with the correct shape. The correct shape is inferred from arguments `sys` and `T`. Parameters ---------- sys: LTI (StateSpace, or TransferFunction) LTI system to simulate U: array-like or number, optional Input array giving input at each time `T` (default = 0). If `U` is ``None`` or ``0``, a special algorithm is used. This special algorithm is faster than the general algorithm, which is used otherwise. T: array-like, optional for discrete LTI `sys` Time steps at which the input is defined; values must be evenly spaced. X0: array-like or number, optional Initial condition (default = 0). Returns ------- yout: array Response of the system. T: array Time values of the output. xout: array Time evolution of the state vector. See Also -------- step, initial, impulse Examples -------- >>> yout, T, xout = lsim(sys, U, T, X0)
Simulate the output of a linear system.
[ "Simulate", "the", "output", "of", "a", "linear", "system", "." ]
def lsim(sys, U=0., T=None, X0=0.): ''' Simulate the output of a linear system. As a convenience for parameters `U`, `X0`: Numbers (scalars) are converted to constant arrays with the correct shape. The correct shape is inferred from arguments `sys` and `T`. Parameters ---------- sys: LTI (StateSpace, or TransferFunction) LTI system to simulate U: array-like or number, optional Input array giving input at each time `T` (default = 0). If `U` is ``None`` or ``0``, a special algorithm is used. This special algorithm is faster than the general algorithm, which is used otherwise. T: array-like, optional for discrete LTI `sys` Time steps at which the input is defined; values must be evenly spaced. X0: array-like or number, optional Initial condition (default = 0). Returns ------- yout: array Response of the system. T: array Time values of the output. xout: array Time evolution of the state vector. See Also -------- step, initial, impulse Examples -------- >>> yout, T, xout = lsim(sys, U, T, X0) ''' from ..timeresp import forced_response # Switch output argument order and transpose outputs (and always return x) out = forced_response(sys, T, U, X0, return_x=True, transpose=True) return out[1], out[0], out[2]
[ "def", "lsim", "(", "sys", ",", "U", "=", "0.", ",", "T", "=", "None", ",", "X0", "=", "0.", ")", ":", "from", ".", ".", "timeresp", "import", "forced_response", "# Switch output argument order and transpose outputs (and always return x)", "out", "=", "forced_re...
https://github.com/python-control/python-control/blob/df6b35212f8f657469627c227c893a175a6902cc/control/matlab/timeresp.py#L252-L298
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
pypy/module/cpyext/typeobject.py
python
PyType_IsSubtype
(space, a, b)
return int(abstract_issubclass_w(space, w_type1, w_type2))
Return true if a is a subtype of b.
Return true if a is a subtype of b.
[ "Return", "true", "if", "a", "is", "a", "subtype", "of", "b", "." ]
def PyType_IsSubtype(space, a, b): """Return true if a is a subtype of b. """ w_type1 = from_ref(space, rffi.cast(PyObject, a)) w_type2 = from_ref(space, rffi.cast(PyObject, b)) return int(abstract_issubclass_w(space, w_type1, w_type2))
[ "def", "PyType_IsSubtype", "(", "space", ",", "a", ",", "b", ")", ":", "w_type1", "=", "from_ref", "(", "space", ",", "rffi", ".", "cast", "(", "PyObject", ",", "a", ")", ")", "w_type2", "=", "from_ref", "(", "space", ",", "rffi", ".", "cast", "(",...
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/pypy/module/cpyext/typeobject.py#L994-L999
nithinmurali/pygsheets
09e985ccfe0585e8aa0633af8d0c0f038e3b3e1a
pygsheets/sheet.py
python
SheetAPIWrapper.create
(self, title, template=None, **kwargs)
return self._execute_requests(self.service.spreadsheets().create(body=body, **kwargs))
Create a spreadsheet. Can be created with just a title. All other values will be set to default. A template can be either a JSON representation of a Spreadsheet Resource as defined by the Google Sheets API or an instance of the Spreadsheet class. Missing fields will be set to default. :param title: Title of the new spreadsheet. :param template: Template used to create the new spreadsheet. :param kwargs: Standard parameters (see reference for details). :return: A Spreadsheet Resource.
Create a spreadsheet.
[ "Create", "a", "spreadsheet", "." ]
def create(self, title, template=None, **kwargs): """Create a spreadsheet. Can be created with just a title. All other values will be set to default. A template can be either a JSON representation of a Spreadsheet Resource as defined by the Google Sheets API or an instance of the Spreadsheet class. Missing fields will be set to default. :param title: Title of the new spreadsheet. :param template: Template used to create the new spreadsheet. :param kwargs: Standard parameters (see reference for details). :return: A Spreadsheet Resource. """ if template is None: body = {'properties': {'title': title}} else: if isinstance(template, dict): if 'properties' in template: template['properties']['title'] = title else: template['properties'] = {'title': title} body = template elif isinstance(template, Spreadsheet): body = template.to_json() body['properties']['title'] = title else: raise InvalidArgumentValue('Need a dictionary or spreadsheet for a template.') body.pop('spreadsheetId', None) return self._execute_requests(self.service.spreadsheets().create(body=body, **kwargs))
[ "def", "create", "(", "self", ",", "title", ",", "template", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "template", "is", "None", ":", "body", "=", "{", "'properties'", ":", "{", "'title'", ":", "title", "}", "}", "else", ":", "if", "i...
https://github.com/nithinmurali/pygsheets/blob/09e985ccfe0585e8aa0633af8d0c0f038e3b3e1a/pygsheets/sheet.py#L122-L150
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/python_clients/venv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/url.py
python
get_host
(url)
return p.scheme or 'http', p.hostname, p.port
Deprecated. Use :func:`.parse_url` instead.
Deprecated. Use :func:`.parse_url` instead.
[ "Deprecated", ".", "Use", ":", "func", ":", ".", "parse_url", "instead", "." ]
def get_host(url): """ Deprecated. Use :func:`.parse_url` instead. """ p = parse_url(url) return p.scheme or 'http', p.hostname, p.port
[ "def", "get_host", "(", "url", ")", ":", "p", "=", "parse_url", "(", "url", ")", "return", "p", ".", "scheme", "or", "'http'", ",", "p", ".", "hostname", ",", "p", ".", "port" ]
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/venv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/url.py#L209-L214
kennethreitz-archive/requests3
69eb662703b40db58fdc6c095d0fe130c56649bb
requests3/toolbelt/downloadutils/tee.py
python
tee_to_bytearray
( response, bytearr, chunksize=_DEFAULT_CHUNKSIZE, decode_content=None )
return _tee(response, bytearr.extend, chunksize, decode_content)
Stream the response both to the generator and a bytearray. This will stream the response provided to the function, add them to the provided :class:`bytearray` and yield them to the user. .. note:: This uses the :meth:`bytearray.extend` by default instead of passing the bytearray into the ``readinto`` method. Example usage: .. code-block:: python b = bytearray() resp = requests.get(url, stream=True) for chunk in tee_to_bytearray(resp, b): # do stuff with chunk :param response: Response from requests. :type response: requests.Response :param bytearray bytearr: Array to add the streamed bytes to. :param int chunksize: (optional), Size of chunk to attempt to stream. :param bool decode_content: (optional), If True, this will decode the compressed content of the response.
Stream the response both to the generator and a bytearray.
[ "Stream", "the", "response", "both", "to", "the", "generator", "and", "a", "bytearray", "." ]
def tee_to_bytearray( response, bytearr, chunksize=_DEFAULT_CHUNKSIZE, decode_content=None ): """Stream the response both to the generator and a bytearray. This will stream the response provided to the function, add them to the provided :class:`bytearray` and yield them to the user. .. note:: This uses the :meth:`bytearray.extend` by default instead of passing the bytearray into the ``readinto`` method. Example usage: .. code-block:: python b = bytearray() resp = requests.get(url, stream=True) for chunk in tee_to_bytearray(resp, b): # do stuff with chunk :param response: Response from requests. :type response: requests.Response :param bytearray bytearr: Array to add the streamed bytes to. :param int chunksize: (optional), Size of chunk to attempt to stream. :param bool decode_content: (optional), If True, this will decode the compressed content of the response. """ if not isinstance(bytearr, bytearray): raise TypeError("tee_to_bytearray() expects bytearr to be a " "bytearray") return _tee(response, bytearr.extend, chunksize, decode_content)
[ "def", "tee_to_bytearray", "(", "response", ",", "bytearr", ",", "chunksize", "=", "_DEFAULT_CHUNKSIZE", ",", "decode_content", "=", "None", ")", ":", "if", "not", "isinstance", "(", "bytearr", ",", "bytearray", ")", ":", "raise", "TypeError", "(", "\"tee_to_b...
https://github.com/kennethreitz-archive/requests3/blob/69eb662703b40db58fdc6c095d0fe130c56649bb/requests3/toolbelt/downloadutils/tee.py#L92-L123
MurtyShikhar/Question-Answering
86bc5952b5d8df683e10285d7607ed12d2a3462e
qa_model.py
python
QASystem.test
(self, session, valid)
return outputs[0][0], outputs[0][1]
valid: a list containing q, c and a. :return: loss on the valid dataset and the logit values
valid: a list containing q, c and a. :return: loss on the valid dataset and the logit values
[ "valid", ":", "a", "list", "containing", "q", "c", "and", "a", ".", ":", "return", ":", "loss", "on", "the", "valid", "dataset", "and", "the", "logit", "values" ]
def test(self, session, valid): """ valid: a list containing q, c and a. :return: loss on the valid dataset and the logit values """ q, c, a = valid # at test time we do not perform dropout. input_feed = self.get_feed_dict(q, c, a, 1.0) output_feed = [self.logits] outputs = session.run(output_feed, input_feed) return outputs[0][0], outputs[0][1]
[ "def", "test", "(", "self", ",", "session", ",", "valid", ")", ":", "q", ",", "c", ",", "a", "=", "valid", "# at test time we do not perform dropout.", "input_feed", "=", "self", ".", "get_feed_dict", "(", "q", ",", "c", ",", "a", ",", "1.0", ")", "out...
https://github.com/MurtyShikhar/Question-Answering/blob/86bc5952b5d8df683e10285d7607ed12d2a3462e/qa_model.py#L382-L397
LINKIWI/modern-paste
ecc4168bda2a9e5981d495f9e0538258d9f727a2
app/views/misc.py
python
version
()
return flask.Response(version_string, mimetype='text/plain')
Show the currently-deployed version of the app.
Show the currently-deployed version of the app.
[ "Show", "the", "currently", "-", "deployed", "version", "of", "the", "app", "." ]
def version(): """ Show the currently-deployed version of the app. """ branch_name = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).replace('\n', '') commit_sha = subprocess.check_output(['git', 'rev-parse', 'HEAD']).replace('\n', '') commit_date = subprocess.check_output(['git', 'log', '-1', '--format=%cd']).replace('\n', '') remote_url = subprocess.check_output(['git', 'config', '--get', 'remote.origin.url']).replace('\n', '') version_string = '{branch}\n{sha}\n{date}\n{url}'.format( branch=branch_name, sha=commit_sha, date=commit_date, url=remote_url, ) return flask.Response(version_string, mimetype='text/plain')
[ "def", "version", "(", ")", ":", "branch_name", "=", "subprocess", ".", "check_output", "(", "[", "'git'", ",", "'rev-parse'", ",", "'--abbrev-ref'", ",", "'HEAD'", "]", ")", ".", "replace", "(", "'\\n'", ",", "''", ")", "commit_sha", "=", "subprocess", ...
https://github.com/LINKIWI/modern-paste/blob/ecc4168bda2a9e5981d495f9e0538258d9f727a2/app/views/misc.py#L29-L45
OpenMined/SyferText
1e9a6c1fbbe31d1b20e852242bf2f9ab9bcc1ce6
src/syfertext/tokenizers/spacy_tokenizer.py
python
SpacyTokenizer._split_affixes
(self, substring: str)
return substring, affixes, exception_tokens
Process substring for tokenizing prefixes, infixes, suffixes and exceptions. Args: substring: The substring to tokenize. Returns: substring: The substring to tokenize. affixes: Dict holding TokenMeta lists of each affix types as a result of splitting affixes exception_tokens: The list of exception tokens TokenMeta objects.
Process substring for tokenizing prefixes, infixes, suffixes and exceptions.
[ "Process", "substring", "for", "tokenizing", "prefixes", "infixes", "suffixes", "and", "exceptions", "." ]
def _split_affixes(self, substring: str) -> Tuple[str, DefaultDict, List[TokenMeta]]: """Process substring for tokenizing prefixes, infixes, suffixes and exceptions. Args: substring: The substring to tokenize. Returns: substring: The substring to tokenize. affixes: Dict holding TokenMeta lists of each affix types as a result of splitting affixes exception_tokens: The list of exception tokens TokenMeta objects. """ infixes = [] exception_tokens = [] next_affix = ["prefix", "suffix"] # Dict holding TokenMeta lists of each affix types(prefix, suffix, infix) affixes = defaultdict(list) # The first element in the `next_affix` list is 'prefix'. # since we should start by finding prefixes, we fix the # index i = 0. # Start by finding prefixes. i = 0 # Holds the last value of `i` at the moment when either a prefix or a suffix is matched. # If the difference between `i` and l`ast_i` is greater than 2, it means that neither a # prefix nor a suffix is found. last_i = 0 # In each iteration, `substring` is searched for a prefix first, then for a suffix, and thus # alternatively. The loop terminates when an exception substring is encountered, # or when the substring is not updated for 2 continuous iterations, i.e, when # neither a prefix nor a suffix is matched in the substring. while i - last_i <= 2: if substring in self.exceptions: # Get a list of exception `TokenMeta` objects to be added to the TextDoc. exception_tokens, substring = self._get_exception_token_metas(substring) break # Get affix type (prefix or suffix) affix_type = next_affix[i % 2] affix_finder = getattr(self, f"find_{affix_type}") if affix_finder(substring): # Get the `TokenMeta` object of the affix along with updated # substring after removing the affix token_meta, substring = getattr(self, f"_get_{affix_type}_token_meta")(substring) affixes[f"{affix_type}"].append(token_meta) last_i = i # Change the affix type. i += 1 # Get infix TokenMeta objects if any. if self.infix_matches(substring): infixes, substring = self._get_infix_token_metas(substring) affixes["infix"].extend(infixes) return substring, affixes, exception_tokens
[ "def", "_split_affixes", "(", "self", ",", "substring", ":", "str", ")", "->", "Tuple", "[", "str", ",", "DefaultDict", ",", "List", "[", "TokenMeta", "]", "]", ":", "infixes", "=", "[", "]", "exception_tokens", "=", "[", "]", "next_affix", "=", "[", ...
https://github.com/OpenMined/SyferText/blob/1e9a6c1fbbe31d1b20e852242bf2f9ab9bcc1ce6/src/syfertext/tokenizers/spacy_tokenizer.py#L279-L345
fortharris/Pcode
147962d160a834c219e12cb456abc130826468e4
rope/refactor/patchedast.py
python
_Source.from_offset
(self, offset)
return self[offset:self.offset]
[]
def from_offset(self, offset): return self[offset:self.offset]
[ "def", "from_offset", "(", "self", ",", "offset", ")", ":", "return", "self", "[", "offset", ":", "self", ".", "offset", "]" ]
https://github.com/fortharris/Pcode/blob/147962d160a834c219e12cb456abc130826468e4/rope/refactor/patchedast.py#L715-L716
nipy/nibabel
4703f4d8e32be4cec30e829c2d93ebe54759bb62
nibabel/nifti1.py
python
Nifti1Image.update_header
(self)
Harmonize header with image data and affine
Harmonize header with image data and affine
[ "Harmonize", "header", "with", "image", "data", "and", "affine" ]
def update_header(self): """ Harmonize header with image data and affine """ super(Nifti1Image, self).update_header() hdr = self._header hdr['magic'] = hdr.single_magic
[ "def", "update_header", "(", "self", ")", ":", "super", "(", "Nifti1Image", ",", "self", ")", ".", "update_header", "(", ")", "hdr", "=", "self", ".", "_header", "hdr", "[", "'magic'", "]", "=", "hdr", ".", "single_magic" ]
https://github.com/nipy/nibabel/blob/4703f4d8e32be4cec30e829c2d93ebe54759bb62/nibabel/nifti1.py#L2030-L2034
VIDA-NYU/reprozip
67bbe8d2e22e0493ba0ccc78521729b49dd70a1d
reprounzip/reprounzip/common.py
python
RPZPack.copy_data_tar
(self, target)
Copies the file in which the data lies to the specified destination.
Copies the file in which the data lies to the specified destination.
[ "Copies", "the", "file", "in", "which", "the", "data", "lies", "to", "the", "specified", "destination", "." ]
def copy_data_tar(self, target): """Copies the file in which the data lies to the specified destination. """ if self.version == 1: self.pack.copyfile(target) elif self.version == 2: with target.open('wb') as fp: data = self.tar.extractfile('DATA.tar.gz') copyfile(data, fp) data.close()
[ "def", "copy_data_tar", "(", "self", ",", "target", ")", ":", "if", "self", ".", "version", "==", "1", ":", "self", ".", "pack", ".", "copyfile", "(", "target", ")", "elif", "self", ".", "version", "==", "2", ":", "with", "target", ".", "open", "("...
https://github.com/VIDA-NYU/reprozip/blob/67bbe8d2e22e0493ba0ccc78521729b49dd70a1d/reprounzip/reprounzip/common.py#L282-L291
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/sets/sets.py
python
Union.as_relational
(self, symbol)
Rewrite a Union in terms of equalities and logic operators.
Rewrite a Union in terms of equalities and logic operators.
[ "Rewrite", "a", "Union", "in", "terms", "of", "equalities", "and", "logic", "operators", "." ]
def as_relational(self, symbol): """Rewrite a Union in terms of equalities and logic operators. """ if all(isinstance(i, (FiniteSet, Interval)) for i in self.args): if len(self.args) == 2: a, b = self.args if (a.sup == b.inf and a.inf is S.NegativeInfinity and b.sup is S.Infinity): return And(Ne(symbol, a.sup), symbol < b.sup, symbol > a.inf) return Or(*[set.as_relational(symbol) for set in self.args]) raise NotImplementedError('relational of Union with non-Intervals')
[ "def", "as_relational", "(", "self", ",", "symbol", ")", ":", "if", "all", "(", "isinstance", "(", "i", ",", "(", "FiniteSet", ",", "Interval", ")", ")", "for", "i", "in", "self", ".", "args", ")", ":", "if", "len", "(", "self", ".", "args", ")",...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/sets/sets.py#L1239-L1248
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/physics/control/control_plots.py
python
ramp_response_plot
(system, slope=1, color='b', prec=8, lower_limit=0, upper_limit=10, show_axes=False, grid=True, show=True, **kwargs)
return plt
r""" Returns the ramp response of a continuous-time system. Ramp function is defined as the straight line passing through origin ($f(x) = mx$). The slope of the ramp function can be varied by the user and the default value is 1. Parameters ========== system : SISOLinearTimeInvariant type The LTI SISO system for which the Ramp Response is to be computed. slope : Number, optional The slope of the input ramp function. Defaults to 1. color : str, tuple, optional The color of the line. Default is Blue. show : boolean, optional If ``True``, the plot will be displayed otherwise the equivalent matplotlib ``plot`` object will be returned. Defaults to True. lower_limit : Number, optional The lower limit of the plot range. Defaults to 0. upper_limit : Number, optional The upper limit of the plot range. Defaults to 10. prec : int, optional The decimal point precision for the point coordinate values. Defaults to 8. show_axes : boolean, optional If ``True``, the coordinate axes will be shown. Defaults to False. grid : boolean, optional If ``True``, the plot will have a grid. Defaults to True. Examples ======== .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import ramp_response_plot >>> tf1 = TransferFunction(s, (s+4)*(s+8), s) >>> ramp_response_plot(tf1, upper_limit=2) # doctest: +SKIP See Also ======== step_response_plot, ramp_response_plot References ========== .. [1] https://en.wikipedia.org/wiki/Ramp_function
r""" Returns the ramp response of a continuous-time system.
[ "r", "Returns", "the", "ramp", "response", "of", "a", "continuous", "-", "time", "system", "." ]
def ramp_response_plot(system, slope=1, color='b', prec=8, lower_limit=0, upper_limit=10, show_axes=False, grid=True, show=True, **kwargs): r""" Returns the ramp response of a continuous-time system. Ramp function is defined as the straight line passing through origin ($f(x) = mx$). The slope of the ramp function can be varied by the user and the default value is 1. Parameters ========== system : SISOLinearTimeInvariant type The LTI SISO system for which the Ramp Response is to be computed. slope : Number, optional The slope of the input ramp function. Defaults to 1. color : str, tuple, optional The color of the line. Default is Blue. show : boolean, optional If ``True``, the plot will be displayed otherwise the equivalent matplotlib ``plot`` object will be returned. Defaults to True. lower_limit : Number, optional The lower limit of the plot range. Defaults to 0. upper_limit : Number, optional The upper limit of the plot range. Defaults to 10. prec : int, optional The decimal point precision for the point coordinate values. Defaults to 8. show_axes : boolean, optional If ``True``, the coordinate axes will be shown. Defaults to False. grid : boolean, optional If ``True``, the plot will have a grid. Defaults to True. Examples ======== .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import ramp_response_plot >>> tf1 = TransferFunction(s, (s+4)*(s+8), s) >>> ramp_response_plot(tf1, upper_limit=2) # doctest: +SKIP See Also ======== step_response_plot, ramp_response_plot References ========== .. [1] https://en.wikipedia.org/wiki/Ramp_function """ x, y = ramp_response_numerical_data(system, slope=slope, prec=prec, lower_limit=lower_limit, upper_limit=upper_limit, **kwargs) plt.plot(x, y, color=color) plt.xlabel('Time (s)') plt.ylabel('Amplitude') plt.title(f'Ramp Response of ${latex(system)}$ [Slope = {slope}]', pad=20) if grid: plt.grid() if show_axes: plt.axhline(0, color='black') plt.axvline(0, color='black') if show: plt.show() return return plt
[ "def", "ramp_response_plot", "(", "system", ",", "slope", "=", "1", ",", "color", "=", "'b'", ",", "prec", "=", "8", ",", "lower_limit", "=", "0", ",", "upper_limit", "=", "10", ",", "show_axes", "=", "False", ",", "grid", "=", "True", ",", "show", ...
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/physics/control/control_plots.py#L593-L669
ipython/ipykernel
0ab288fe42f3155c7c7d9257c9be8cf093d175e0
ipykernel/_eventloop_macos.py
python
_utf8
(s)
return s
ensure utf8 bytes
ensure utf8 bytes
[ "ensure", "utf8", "bytes" ]
def _utf8(s): """ensure utf8 bytes""" if not isinstance(s, bytes): s = s.encode('utf8') return s
[ "def", "_utf8", "(", "s", ")", ":", "if", "not", "isinstance", "(", "s", ",", "bytes", ")", ":", "s", "=", "s", ".", "encode", "(", "'utf8'", ")", "return", "s" ]
https://github.com/ipython/ipykernel/blob/0ab288fe42f3155c7c7d9257c9be8cf093d175e0/ipykernel/_eventloop_macos.py#L25-L29
safe-graph/DGFraud
4d017a5ae9c44287215f52470e1aef5ee99a5d9d
algorithms/GraphSage/minibatch.py
python
EdgeMinibatchIterator.__init__
(self, G, id2idx, placeholders, context_pairs=None, batch_size=100, max_degree=25, n2v_retrain=False, fixed_n2v=False, **kwargs)
[]
def __init__(self, G, id2idx, placeholders, context_pairs=None, batch_size=100, max_degree=25, n2v_retrain=False, fixed_n2v=False, **kwargs): self.G = G self.nodes = G.nodes() self.id2idx = id2idx self.placeholders = placeholders self.batch_size = batch_size self.max_degree = max_degree self.batch_num = 0 self.nodes = np.random.permutation(G.nodes()) self.adj, self.deg = self.construct_adj() self.test_adj = self.construct_test_adj() if context_pairs is None: edges = G.edges() else: edges = context_pairs self.train_edges = self.edges = np.random.permutation(edges) if not n2v_retrain: self.train_edges = self._remove_isolated(self.train_edges) self.val_edges = [e for e in G.edges() if G[e[0]][e[1]]['train_removed']] else: if fixed_n2v: self.train_edges = self.val_edges = self._n2v_prune(self.edges) else: self.train_edges = self.val_edges = self.edges print(len([n for n in G.nodes() if not G.node[n]['test'] and not G.node[n]['val']]), 'train nodes') print(len([n for n in G.nodes() if G.node[n]['test'] or G.node[n]['val']]), 'test nodes') self.val_set_size = len(self.val_edges)
[ "def", "__init__", "(", "self", ",", "G", ",", "id2idx", ",", "placeholders", ",", "context_pairs", "=", "None", ",", "batch_size", "=", "100", ",", "max_degree", "=", "25", ",", "n2v_retrain", "=", "False", ",", "fixed_n2v", "=", "False", ",", "*", "*...
https://github.com/safe-graph/DGFraud/blob/4d017a5ae9c44287215f52470e1aef5ee99a5d9d/algorithms/GraphSage/minibatch.py#L22-L54
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/emails/views.py
python
amazon_ses_index
(request, template_name="emails/amazon_ses/index.html")
return render_to_resp(request=request, template_name=template_name)
[]
def amazon_ses_index(request, template_name="emails/amazon_ses/index.html"): # admin only if not request.user.profile.is_superuser:raise Http403 return render_to_resp(request=request, template_name=template_name)
[ "def", "amazon_ses_index", "(", "request", ",", "template_name", "=", "\"emails/amazon_ses/index.html\"", ")", ":", "# admin only", "if", "not", "request", ".", "user", ".", "profile", ".", "is_superuser", ":", "raise", "Http403", "return", "render_to_resp", "(", ...
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/emails/views.py#L93-L97
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/fimap/language.py
python
baseLanguage.generateQuiz
(self)
return(ret)
[]
def generateQuiz(self): ret = None try: exec(self.quiz_function) except: boxarr = [] boxheader = "[!!!] BAAAAAAAAAAAAAAAANG - Welcome back to reality [!!!]" boxarr.append("The quiz function defined in one of the XML-Language-Definition files") boxarr.append("just failed! If you are coding your own XML then fix that!") boxarr.append("If not please report this bug at http://fimap.googlecode.com (!) Thanks!") self.drawBox(boxheader, boxarr) raise return(ret)
[ "def", "generateQuiz", "(", "self", ")", ":", "ret", "=", "None", "try", ":", "exec", "(", "self", ".", "quiz_function", ")", "except", ":", "boxarr", "=", "[", "]", "boxheader", "=", "\"[!!!] BAAAAAAAAAAAAAAAANG - Welcome back to reality [!!!]\"", "boxarr", "."...
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/fimap/language.py#L425-L437
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/antiddos/v20200309/antiddos_client.py
python
AntiddosClient.ModifyNewDomainRules
(self, request)
修改7层转发规则 :param request: Request instance for ModifyNewDomainRules. :type request: :class:`tencentcloud.antiddos.v20200309.models.ModifyNewDomainRulesRequest` :rtype: :class:`tencentcloud.antiddos.v20200309.models.ModifyNewDomainRulesResponse`
修改7层转发规则
[ "修改7层转发规则" ]
def ModifyNewDomainRules(self, request): """修改7层转发规则 :param request: Request instance for ModifyNewDomainRules. :type request: :class:`tencentcloud.antiddos.v20200309.models.ModifyNewDomainRulesRequest` :rtype: :class:`tencentcloud.antiddos.v20200309.models.ModifyNewDomainRulesResponse` """ try: params = request._serialize() body = self.call("ModifyNewDomainRules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyNewDomainRulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "ModifyNewDomainRules", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"ModifyNewDomainRules\"", ",", "params", ")", "response", "=", "json", ".", ...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/antiddos/v20200309/antiddos_client.py#L1401-L1426
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.5/django/core/management/__init__.py
python
ManagementUtility.fetch_command
(self, subcommand)
return klass
Tries to fetch the given subcommand, printing a message with the appropriate command called from the command line (usually "django-admin.py" or "manage.py") if it can't be found.
Tries to fetch the given subcommand, printing a message with the appropriate command called from the command line (usually "django-admin.py" or "manage.py") if it can't be found.
[ "Tries", "to", "fetch", "the", "given", "subcommand", "printing", "a", "message", "with", "the", "appropriate", "command", "called", "from", "the", "command", "line", "(", "usually", "django", "-", "admin", ".", "py", "or", "manage", ".", "py", ")", "if", ...
def fetch_command(self, subcommand): """ Tries to fetch the given subcommand, printing a message with the appropriate command called from the command line (usually "django-admin.py" or "manage.py") if it can't be found. """ try: app_name = get_commands()[subcommand] except KeyError: sys.stderr.write("Unknown command: %r\nType '%s help' for usage.\n" % \ (subcommand, self.prog_name)) sys.exit(1) if isinstance(app_name, BaseCommand): # If the command is already loaded, use it directly. klass = app_name else: klass = load_command_class(app_name, subcommand) return klass
[ "def", "fetch_command", "(", "self", ",", "subcommand", ")", ":", "try", ":", "app_name", "=", "get_commands", "(", ")", "[", "subcommand", "]", "except", "KeyError", ":", "sys", ".", "stderr", ".", "write", "(", "\"Unknown command: %r\\nType '%s help' for usage...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.5/django/core/management/__init__.py#L256-L273
playframework/play1
0ecac3bc2421ae2dbec27a368bf671eda1c9cba5
python/Lib/logging/__init__.py
python
Logger.exception
(self, msg, *args, **kwargs)
Convenience method for logging an ERROR with exception information.
Convenience method for logging an ERROR with exception information.
[ "Convenience", "method", "for", "logging", "an", "ERROR", "with", "exception", "information", "." ]
def exception(self, msg, *args, **kwargs): """ Convenience method for logging an ERROR with exception information. """ kwargs['exc_info'] = 1 self.error(msg, *args, **kwargs)
[ "def", "exception", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'exc_info'", "]", "=", "1", "self", ".", "error", "(", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/playframework/play1/blob/0ecac3bc2421ae2dbec27a368bf671eda1c9cba5/python/Lib/logging/__init__.py#L1195-L1200
albertz/music-player
d23586f5bf657cbaea8147223be7814d117ae73d
src/modules/mod_socketcontrol.py
python
socketcontrolMain
()
[]
def socketcontrolMain(): import tempfile tmpdir = tempfile.gettempdir() or "/tmp" sockfilename = "%s/%s-%i-socketcontrol" % (tmpdir, appinfo.appid, os.getpid()) globals()["socketfile"] = sockfilename # copy import socket s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.bind(sockfilename) os.chmod(sockfilename, 0700) s.listen(1) def listenThread(): print "socketcontrol: listening on", sockfilename while True: conn, address = s.accept() handleConnection(conn, address) conn, address = None, None # remove refs here utils.daemonThreadCall(listenThread, name="socketcontrol.listen") from State import state for ev,args,kwargs in state.updates.read(): pass try: s.shutdown(socket.SHUT_RDWR) except Exception: pass try: s.close() except Exception: pass try: os.unlink(sockfilename) except Exception: pass
[ "def", "socketcontrolMain", "(", ")", ":", "import", "tempfile", "tmpdir", "=", "tempfile", ".", "gettempdir", "(", ")", "or", "\"/tmp\"", "sockfilename", "=", "\"%s/%s-%i-socketcontrol\"", "%", "(", "tmpdir", ",", "appinfo", ".", "appid", ",", "os", ".", "g...
https://github.com/albertz/music-player/blob/d23586f5bf657cbaea8147223be7814d117ae73d/src/modules/mod_socketcontrol.py#L69-L101
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-build/python-libs/gdata/src/gdata/youtube/service.py
python
YouTubeService.AddVideoEntryToFavorites
(self, video_entry, username='default')
return self.Post(video_entry, post_uri, converter=gdata.youtube.YouTubeVideoEntryFromString)
Add a video entry to a users favorite feed. Needs authentication. Args: video_entry: The YouTubeVideoEntry to add. username: An optional string representing the username to whose favorite feed you wish to add the entry. Defaults to the currently authenticated user. Returns: The posted YouTubeVideoEntry if successfully posted.
Add a video entry to a users favorite feed.
[ "Add", "a", "video", "entry", "to", "a", "users", "favorite", "feed", "." ]
def AddVideoEntryToFavorites(self, video_entry, username='default'): """Add a video entry to a users favorite feed. Needs authentication. Args: video_entry: The YouTubeVideoEntry to add. username: An optional string representing the username to whose favorite feed you wish to add the entry. Defaults to the currently authenticated user. Returns: The posted YouTubeVideoEntry if successfully posted. """ post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites') return self.Post(video_entry, post_uri, converter=gdata.youtube.YouTubeVideoEntryFromString)
[ "def", "AddVideoEntryToFavorites", "(", "self", ",", "video_entry", ",", "username", "=", "'default'", ")", ":", "post_uri", "=", "'%s/%s/%s'", "%", "(", "YOUTUBE_USER_FEED_URI", ",", "username", ",", "'favorites'", ")", "return", "self", ".", "Post", "(", "vi...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-build/python-libs/gdata/src/gdata/youtube/service.py#L874-L890
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/cls/v20201016/models.py
python
CreateShipperRequest.__init__
(self)
r""" :param TopicId: 创建的投递规则所属的日志主题ID :type TopicId: str :param Bucket: 创建的投递规则投递的bucket :type Bucket: str :param Prefix: 创建的投递规则投递目录的前缀 :type Prefix: str :param ShipperName: 投递规则的名字 :type ShipperName: str :param Interval: 投递的时间间隔,单位 秒,默认300,范围 300-900 :type Interval: int :param MaxSize: 投递的文件的最大值,单位 MB,默认256,范围 100-256 :type MaxSize: int :param FilterRules: 投递日志的过滤规则,匹配的日志进行投递,各rule之间是and关系,最多5个,数组为空则表示不过滤而全部投递 :type FilterRules: list of FilterRuleInfo :param Partition: 投递日志的分区规则,支持strftime的时间格式表示 :type Partition: str :param Compress: 投递日志的压缩配置 :type Compress: :class:`tencentcloud.cls.v20201016.models.CompressInfo` :param Content: 投递日志的内容格式配置 :type Content: :class:`tencentcloud.cls.v20201016.models.ContentInfo`
r""" :param TopicId: 创建的投递规则所属的日志主题ID :type TopicId: str :param Bucket: 创建的投递规则投递的bucket :type Bucket: str :param Prefix: 创建的投递规则投递目录的前缀 :type Prefix: str :param ShipperName: 投递规则的名字 :type ShipperName: str :param Interval: 投递的时间间隔,单位 秒,默认300,范围 300-900 :type Interval: int :param MaxSize: 投递的文件的最大值,单位 MB,默认256,范围 100-256 :type MaxSize: int :param FilterRules: 投递日志的过滤规则,匹配的日志进行投递,各rule之间是and关系,最多5个,数组为空则表示不过滤而全部投递 :type FilterRules: list of FilterRuleInfo :param Partition: 投递日志的分区规则,支持strftime的时间格式表示 :type Partition: str :param Compress: 投递日志的压缩配置 :type Compress: :class:`tencentcloud.cls.v20201016.models.CompressInfo` :param Content: 投递日志的内容格式配置 :type Content: :class:`tencentcloud.cls.v20201016.models.ContentInfo`
[ "r", ":", "param", "TopicId", ":", "创建的投递规则所属的日志主题ID", ":", "type", "TopicId", ":", "str", ":", "param", "Bucket", ":", "创建的投递规则投递的bucket", ":", "type", "Bucket", ":", "str", ":", "param", "Prefix", ":", "创建的投递规则投递目录的前缀", ":", "type", "Prefix", ":", "str",...
def __init__(self): r""" :param TopicId: 创建的投递规则所属的日志主题ID :type TopicId: str :param Bucket: 创建的投递规则投递的bucket :type Bucket: str :param Prefix: 创建的投递规则投递目录的前缀 :type Prefix: str :param ShipperName: 投递规则的名字 :type ShipperName: str :param Interval: 投递的时间间隔,单位 秒,默认300,范围 300-900 :type Interval: int :param MaxSize: 投递的文件的最大值,单位 MB,默认256,范围 100-256 :type MaxSize: int :param FilterRules: 投递日志的过滤规则,匹配的日志进行投递,各rule之间是and关系,最多5个,数组为空则表示不过滤而全部投递 :type FilterRules: list of FilterRuleInfo :param Partition: 投递日志的分区规则,支持strftime的时间格式表示 :type Partition: str :param Compress: 投递日志的压缩配置 :type Compress: :class:`tencentcloud.cls.v20201016.models.CompressInfo` :param Content: 投递日志的内容格式配置 :type Content: :class:`tencentcloud.cls.v20201016.models.ContentInfo` """ self.TopicId = None self.Bucket = None self.Prefix = None self.ShipperName = None self.Interval = None self.MaxSize = None self.FilterRules = None self.Partition = None self.Compress = None self.Content = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "TopicId", "=", "None", "self", ".", "Bucket", "=", "None", "self", ".", "Prefix", "=", "None", "self", ".", "ShipperName", "=", "None", "self", ".", "Interval", "=", "None", "self", ".", "MaxSiz...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cls/v20201016/models.py#L1177-L1209
quark-engine/quark-engine
0d53b225b0c57bed6d1e2a5ec22efc842d45ed60
quark/utils/regex.py
python
validate_url
(url)
return re.match(regex, url) is not None
[]
def validate_url(url): regex = re.compile(VALIDATE_URL, re.IGNORECASE) return re.match(regex, url) is not None
[ "def", "validate_url", "(", "url", ")", ":", "regex", "=", "re", ".", "compile", "(", "VALIDATE_URL", ",", "re", ".", "IGNORECASE", ")", "return", "re", ".", "match", "(", "regex", ",", "url", ")", "is", "not", "None" ]
https://github.com/quark-engine/quark-engine/blob/0d53b225b0c57bed6d1e2a5ec22efc842d45ed60/quark/utils/regex.py#L26-L29
msracver/Deformable-ConvNets
6aeda878a95bcb55eadffbe125804e730574de8d
lib/bbox/bbox_transform.py
python
bbox_overlaps_py
(boxes, query_boxes)
return overlaps
determine overlaps between boxes and query_boxes :param boxes: n * 4 bounding boxes :param query_boxes: k * 4 bounding boxes :return: overlaps: n * k overlaps
determine overlaps between boxes and query_boxes :param boxes: n * 4 bounding boxes :param query_boxes: k * 4 bounding boxes :return: overlaps: n * k overlaps
[ "determine", "overlaps", "between", "boxes", "and", "query_boxes", ":", "param", "boxes", ":", "n", "*", "4", "bounding", "boxes", ":", "param", "query_boxes", ":", "k", "*", "4", "bounding", "boxes", ":", "return", ":", "overlaps", ":", "n", "*", "k", ...
def bbox_overlaps_py(boxes, query_boxes): """ determine overlaps between boxes and query_boxes :param boxes: n * 4 bounding boxes :param query_boxes: k * 4 bounding boxes :return: overlaps: n * k overlaps """ n_ = boxes.shape[0] k_ = query_boxes.shape[0] overlaps = np.zeros((n_, k_), dtype=np.float) for k in range(k_): query_box_area = (query_boxes[k, 2] - query_boxes[k, 0] + 1) * (query_boxes[k, 3] - query_boxes[k, 1] + 1) for n in range(n_): iw = min(boxes[n, 2], query_boxes[k, 2]) - max(boxes[n, 0], query_boxes[k, 0]) + 1 if iw > 0: ih = min(boxes[n, 3], query_boxes[k, 3]) - max(boxes[n, 1], query_boxes[k, 1]) + 1 if ih > 0: box_area = (boxes[n, 2] - boxes[n, 0] + 1) * (boxes[n, 3] - boxes[n, 1] + 1) all_area = float(box_area + query_box_area - iw * ih) overlaps[n, k] = iw * ih / all_area return overlaps
[ "def", "bbox_overlaps_py", "(", "boxes", ",", "query_boxes", ")", ":", "n_", "=", "boxes", ".", "shape", "[", "0", "]", "k_", "=", "query_boxes", ".", "shape", "[", "0", "]", "overlaps", "=", "np", ".", "zeros", "(", "(", "n_", ",", "k_", ")", ",...
https://github.com/msracver/Deformable-ConvNets/blob/6aeda878a95bcb55eadffbe125804e730574de8d/lib/bbox/bbox_transform.py#L22-L42
sphinx-doc/sphinx
e79681c76843c1339863b365747079b2d662d0c1
sphinx/transforms/post_transforms/__init__.py
python
SphinxPostTransform.is_supported
(self)
return True
Check this transform working for current builder.
Check this transform working for current builder.
[ "Check", "this", "transform", "working", "for", "current", "builder", "." ]
def is_supported(self) -> bool: """Check this transform working for current builder.""" if self.builders and self.app.builder.name not in self.builders: return False if self.formats and self.app.builder.format not in self.formats: return False return True
[ "def", "is_supported", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "builders", "and", "self", ".", "app", ".", "builder", ".", "name", "not", "in", "self", ".", "builders", ":", "return", "False", "if", "self", ".", "formats", "and", "sel...
https://github.com/sphinx-doc/sphinx/blob/e79681c76843c1339863b365747079b2d662d0c1/sphinx/transforms/post_transforms/__init__.py#L45-L52
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/distutils/core.py
python
run_setup
(script_name, script_args=None, stop_after="run")
return _setup_distribution
Run a setup script in a somewhat controlled environment, and return the Distribution instance that drives things. This is useful if you need to find out the distribution meta-data (passed as keyword args from 'script' to 'setup()', or the contents of the config files or command-line. 'script_name' is a file that will be read and run with 'exec()'; 'sys.argv[0]' will be replaced with 'script' for the duration of the call. 'script_args' is a list of strings; if supplied, 'sys.argv[1:]' will be replaced by 'script_args' for the duration of the call. 'stop_after' tells 'setup()' when to stop processing; possible values: init stop after the Distribution instance has been created and populated with the keyword arguments to 'setup()' config stop after config files have been parsed (and their data stored in the Distribution instance) commandline stop after the command-line ('sys.argv[1:]' or 'script_args') have been parsed (and the data stored in the Distribution) run [default] stop after all commands have been run (the same as if 'setup()' had been called in the usual way Returns the Distribution instance, which provides all information used to drive the Distutils.
Run a setup script in a somewhat controlled environment, and return the Distribution instance that drives things. This is useful if you need to find out the distribution meta-data (passed as keyword args from 'script' to 'setup()', or the contents of the config files or command-line.
[ "Run", "a", "setup", "script", "in", "a", "somewhat", "controlled", "environment", "and", "return", "the", "Distribution", "instance", "that", "drives", "things", ".", "This", "is", "useful", "if", "you", "need", "to", "find", "out", "the", "distribution", "...
def run_setup (script_name, script_args=None, stop_after="run"): """Run a setup script in a somewhat controlled environment, and return the Distribution instance that drives things. This is useful if you need to find out the distribution meta-data (passed as keyword args from 'script' to 'setup()', or the contents of the config files or command-line. 'script_name' is a file that will be read and run with 'exec()'; 'sys.argv[0]' will be replaced with 'script' for the duration of the call. 'script_args' is a list of strings; if supplied, 'sys.argv[1:]' will be replaced by 'script_args' for the duration of the call. 'stop_after' tells 'setup()' when to stop processing; possible values: init stop after the Distribution instance has been created and populated with the keyword arguments to 'setup()' config stop after config files have been parsed (and their data stored in the Distribution instance) commandline stop after the command-line ('sys.argv[1:]' or 'script_args') have been parsed (and the data stored in the Distribution) run [default] stop after all commands have been run (the same as if 'setup()' had been called in the usual way Returns the Distribution instance, which provides all information used to drive the Distutils. """ if stop_after not in ('init', 'config', 'commandline', 'run'): raise ValueError("invalid value for 'stop_after': %r" % (stop_after,)) global _setup_stop_after, _setup_distribution _setup_stop_after = stop_after save_argv = sys.argv.copy() g = {'__file__': script_name} try: try: sys.argv[0] = script_name if script_args is not None: sys.argv[1:] = script_args with open(script_name, 'rb') as f: exec(f.read(), g) finally: sys.argv = save_argv _setup_stop_after = None except SystemExit: # Hmm, should we do something if exiting with a non-zero code # (ie. error)? pass if _setup_distribution is None: raise RuntimeError(("'distutils.core.setup()' was never called -- " "perhaps '%s' is not a Distutils setup script?") % \ script_name) # I wonder if the setup script's namespace -- g and l -- would be of # any interest to callers? #print "_setup_distribution:", _setup_distribution return _setup_distribution
[ "def", "run_setup", "(", "script_name", ",", "script_args", "=", "None", ",", "stop_after", "=", "\"run\"", ")", ":", "if", "stop_after", "not", "in", "(", "'init'", ",", "'config'", ",", "'commandline'", ",", "'run'", ")", ":", "raise", "ValueError", "(",...
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/distutils/core.py#L170-L232
bcbio/bcbio-nextgen
c80f9b6b1be3267d1f981b7035e3b72441d258f2
bcbio/variation/vcfutils.py
python
merge_variant_files
(orig_files, out_file, ref_file, config, region=None)
Combine multiple VCF files with different samples into a single output file. Uses bcftools merge on bgzipped input files, handling both tricky merge and concatenation of files. Does not correctly handle files with the same sample (use combine_variant_files instead).
Combine multiple VCF files with different samples into a single output file.
[ "Combine", "multiple", "VCF", "files", "with", "different", "samples", "into", "a", "single", "output", "file", "." ]
def merge_variant_files(orig_files, out_file, ref_file, config, region=None): """Combine multiple VCF files with different samples into a single output file. Uses bcftools merge on bgzipped input files, handling both tricky merge and concatenation of files. Does not correctly handle files with the same sample (use combine_variant_files instead). """ in_pipeline = False if isinstance(orig_files, dict): file_key = config["file_key"] in_pipeline = True orig_files = orig_files[file_key] if tz.get_in(["algorithm", "purecn_pon_build"], config): out_vcf, ext = os.path.splitext(out_file) out_file = _do_combine_variants(orig_files, out_vcf, ref_file, config, region) else: out_file = _do_merge(orig_files, out_file, config, region) if in_pipeline: return [{file_key: out_file, "region": region, "sam_ref": ref_file, "config": config}] else: return out_file
[ "def", "merge_variant_files", "(", "orig_files", ",", "out_file", ",", "ref_file", ",", "config", ",", "region", "=", "None", ")", ":", "in_pipeline", "=", "False", "if", "isinstance", "(", "orig_files", ",", "dict", ")", ":", "file_key", "=", "config", "[...
https://github.com/bcbio/bcbio-nextgen/blob/c80f9b6b1be3267d1f981b7035e3b72441d258f2/bcbio/variation/vcfutils.py#L294-L314
googlefonts/nototools
903a218f62256a286cde48c76b3051703f8a1de5
nototools/compare_fonts.py
python
FontCompare._config
(self, msg)
Write a message that should go to config.
Write a message that should go to config.
[ "Write", "a", "message", "that", "should", "go", "to", "config", "." ]
def _config(self, msg): """Write a message that should go to config.""" if self.emit_config: print(msg)
[ "def", "_config", "(", "self", ",", "msg", ")", ":", "if", "self", ".", "emit_config", ":", "print", "(", "msg", ")" ]
https://github.com/googlefonts/nototools/blob/903a218f62256a286cde48c76b3051703f8a1de5/nototools/compare_fonts.py#L164-L167
ironport/shrapnel
9496a64c46271b0c5cef0feb8f2cdf33cb752bb6
coro/http/protocol.py
python
header_set.crack
(self, h)
Crack one header line.
Crack one header line.
[ "Crack", "one", "header", "line", "." ]
def crack (self, h): "Crack one header line." # deliberately ignoring 822 crap like continuation lines. try: i = h.index (': ') name, value = h[:i], h[i + 2:] self[name] = value except ValueError: coro.write_stderr ('dropping bogus header %r\n' % (h,)) pass
[ "def", "crack", "(", "self", ",", "h", ")", ":", "# deliberately ignoring 822 crap like continuation lines.", "try", ":", "i", "=", "h", ".", "index", "(", "': '", ")", "name", ",", "value", "=", "h", "[", ":", "i", "]", ",", "h", "[", "i", "+", "2",...
https://github.com/ironport/shrapnel/blob/9496a64c46271b0c5cef0feb8f2cdf33cb752bb6/coro/http/protocol.py#L138-L147
gaasedelen/lighthouse
7245a2d2c4e84351cd259ed81dafa4263167909a
plugins/lighthouse/reader/parsers/drcov.py
python
DrcovModule.start
(self)
return self.base
Compatability alias for the module base. DrCov table version 2 --> 3 changed this paramter name base --> start.
Compatability alias for the module base.
[ "Compatability", "alias", "for", "the", "module", "base", "." ]
def start(self): """ Compatability alias for the module base. DrCov table version 2 --> 3 changed this paramter name base --> start. """ return self.base
[ "def", "start", "(", "self", ")", ":", "return", "self", ".", "base" ]
https://github.com/gaasedelen/lighthouse/blob/7245a2d2c4e84351cd259ed81dafa4263167909a/plugins/lighthouse/reader/parsers/drcov.py#L364-L370
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/base/utils.py
python
UnicodeWriter.__init__
(self, f, dialect=csv.excel, encoding="utf-8", **kwds)
[]
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.queue = StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.stream = f self.encoder = codecs.getincrementalencoder(encoding)()
[ "def", "__init__", "(", "self", ",", "f", ",", "dialect", "=", "csv", ".", "excel", ",", "encoding", "=", "\"utf-8\"", ",", "*", "*", "kwds", ")", ":", "# Redirect output to a queue", "self", ".", "queue", "=", "StringIO", "(", ")", "self", ".", "write...
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/base/utils.py#L860-L865
PengJenas/MineWechat
ebb7d994079a66d7c04b3b2de677a55a90209bfc
MineWechat.py
python
MyThread.shutdown_pc
(self)
本机关机
本机关机
[ "本机关机" ]
def shutdown_pc(self): '''本机关机''' os.system('shutdown -s -t 60') # 执行计算机系统指令,这里是60秒后关机 send_msg = '[远控信息] 60秒后电脑关机\n取消关机命令:\n#取消关机' # 发送警告消息,提醒取消指令 self.bot.file_helper.send(send_msg) self._signal_3.emit('[远控信息] 警告:60秒后关机')
[ "def", "shutdown_pc", "(", "self", ")", ":", "os", ".", "system", "(", "'shutdown -s -t 60'", ")", "# 执行计算机系统指令,这里是60秒后关机", "send_msg", "=", "'[远控信息] 60秒后电脑关机\\n取消关机命令:\\n#取消关机' # 发送警告消息,提醒取消指令", "", "self", ".", "bot", ".", "file_helper", ".", "send", "(", "send_m...
https://github.com/PengJenas/MineWechat/blob/ebb7d994079a66d7c04b3b2de677a55a90209bfc/MineWechat.py#L683-L688
thatbrguy/Pedestrian-Detection
b11c7d6bed0ff320811726fe1c429be26a87da9e
object_detection/utils/ops.py
python
expanded_shape
(orig_shape, start_dim, num_dims)
Inserts multiple ones into a shape vector. Inserts an all-1 vector of length num_dims at position start_dim into a shape. Can be combined with tf.reshape to generalize tf.expand_dims. Args: orig_shape: the shape into which the all-1 vector is added (int32 vector) start_dim: insertion position (int scalar) num_dims: length of the inserted all-1 vector (int scalar) Returns: An int32 vector of length tf.size(orig_shape) + num_dims.
Inserts multiple ones into a shape vector.
[ "Inserts", "multiple", "ones", "into", "a", "shape", "vector", "." ]
def expanded_shape(orig_shape, start_dim, num_dims): """Inserts multiple ones into a shape vector. Inserts an all-1 vector of length num_dims at position start_dim into a shape. Can be combined with tf.reshape to generalize tf.expand_dims. Args: orig_shape: the shape into which the all-1 vector is added (int32 vector) start_dim: insertion position (int scalar) num_dims: length of the inserted all-1 vector (int scalar) Returns: An int32 vector of length tf.size(orig_shape) + num_dims. """ with tf.name_scope('ExpandedShape'): start_dim = tf.expand_dims(start_dim, 0) # scalar to rank-1 before = tf.slice(orig_shape, [0], start_dim) add_shape = tf.ones(tf.reshape(num_dims, [1]), dtype=tf.int32) after = tf.slice(orig_shape, start_dim, [-1]) new_shape = tf.concat([before, add_shape, after], 0) return new_shape
[ "def", "expanded_shape", "(", "orig_shape", ",", "start_dim", ",", "num_dims", ")", ":", "with", "tf", ".", "name_scope", "(", "'ExpandedShape'", ")", ":", "start_dim", "=", "tf", ".", "expand_dims", "(", "start_dim", ",", "0", ")", "# scalar to rank-1", "be...
https://github.com/thatbrguy/Pedestrian-Detection/blob/b11c7d6bed0ff320811726fe1c429be26a87da9e/object_detection/utils/ops.py#L29-L48
orakaro/rainbowstream
96141fac10675e0775d703f65a59c4477a48c57e
rainbowstream/config.py
python
fixup
(adict, k, v)
Fix up a key in json format
Fix up a key in json format
[ "Fix", "up", "a", "key", "in", "json", "format" ]
def fixup(adict, k, v): """ Fix up a key in json format """ for key in adict.keys(): if key == k: adict[key] = v elif isinstance(adict[key], dict): fixup(adict[key], k, v)
[ "def", "fixup", "(", "adict", ",", "k", ",", "v", ")", ":", "for", "key", "in", "adict", ".", "keys", "(", ")", ":", "if", "key", "==", "k", ":", "adict", "[", "key", "]", "=", "v", "elif", "isinstance", "(", "adict", "[", "key", "]", ",", ...
https://github.com/orakaro/rainbowstream/blob/96141fac10675e0775d703f65a59c4477a48c57e/rainbowstream/config.py#L25-L33
century-arcade/xd
44ead0590764cd4aac99e9db1cd058014eaa368b
xdfile/html.py
python
mktag
(tagname, tagclass='', inner=None, tag_params=None)
return ret
generates tag: <tagname * > or if tag_params dict passed <tagname * >inner</tagname> * tagclass or if tag_params dict passed will be overloaded by tag_params['class'] <tagname param1="value1" param2="value2" ...>
generates tag: <tagname * > or if tag_params dict passed <tagname * >inner</tagname> * tagclass or if tag_params dict passed will be overloaded by tag_params['class'] <tagname param1="value1" param2="value2" ...>
[ "generates", "tag", ":", "<tagname", "*", ">", "or", "if", "tag_params", "dict", "passed", "<tagname", "*", ">", "inner<", "/", "tagname", ">", "*", "tagclass", "or", "if", "tag_params", "dict", "passed", "will", "be", "overloaded", "by", "tag_params", "["...
def mktag(tagname, tagclass='', inner=None, tag_params=None): """ generates tag: <tagname * > or if tag_params dict passed <tagname * >inner</tagname> * tagclass or if tag_params dict passed will be overloaded by tag_params['class'] <tagname param1="value1" param2="value2" ...> """ ret = '' if tag_params: _params = [] for p, v in tag_params.items(): _params.append('%s="%s"' % (p, v)) else: _params = [ 'class="%s"' % tagclass ] ret += '<%s %s>' % (tagname, " ".join(_params)) if inner is not None: ret += inner ret += mktag('/' + tagname) return ret
[ "def", "mktag", "(", "tagname", ",", "tagclass", "=", "''", ",", "inner", "=", "None", ",", "tag_params", "=", "None", ")", ":", "ret", "=", "''", "if", "tag_params", ":", "_params", "=", "[", "]", "for", "p", ",", "v", "in", "tag_params", ".", "...
https://github.com/century-arcade/xd/blob/44ead0590764cd4aac99e9db1cd058014eaa368b/xdfile/html.py#L182-L202
j2labs/brubeck
0e42200126155973b1403a2c073768a3345329a6
brubeck/autoapi.py
python
AutoAPIBase._crud_to_http
(self, crud_status)
Translates the crud status returned by a `QuerySet` into the status used for HTTP.
Translates the crud status returned by a `QuerySet` into the status used for HTTP.
[ "Translates", "the", "crud", "status", "returned", "by", "a", "QuerySet", "into", "the", "status", "used", "for", "HTTP", "." ]
def _crud_to_http(self, crud_status): """Translates the crud status returned by a `QuerySet` into the status used for HTTP. """ if self.queries.MSG_FAILED == crud_status: return self._FAILED_CODE elif self.queries.MSG_CREATED == crud_status: return self._CREATED_CODE elif self.queries.MSG_UPDATED == crud_status: return self._UPDATED_CODE elif self.queries.MSG_OK == crud_status: return self._SUCCESS_CODE elif len(crud_status) == 0: return self._SUCCESS_CODE else: return self._SERVER_ERROR
[ "def", "_crud_to_http", "(", "self", ",", "crud_status", ")", ":", "if", "self", ".", "queries", ".", "MSG_FAILED", "==", "crud_status", ":", "return", "self", ".", "_FAILED_CODE", "elif", "self", ".", "queries", ".", "MSG_CREATED", "==", "crud_status", ":",...
https://github.com/j2labs/brubeck/blob/0e42200126155973b1403a2c073768a3345329a6/brubeck/autoapi.py#L94-L114
edgewall/trac
beb3e4eaf1e0a456d801a50a8614ecab06de29fc
trac/web/api.py
python
Request.get_header
(self, name)
return None
Return the value of the specified HTTP header, or `None` if there's no such header in the request.
Return the value of the specified HTTP header, or `None` if there's no such header in the request.
[ "Return", "the", "value", "of", "the", "specified", "HTTP", "header", "or", "None", "if", "there", "s", "no", "such", "header", "in", "the", "request", "." ]
def get_header(self, name): """Return the value of the specified HTTP header, or `None` if there's no such header in the request. """ name = name.lower() for key, value in self._inheaders: if key == name: return value return None
[ "def", "get_header", "(", "self", ",", "name", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "for", "key", ",", "value", "in", "self", ".", "_inheaders", ":", "if", "key", "==", "name", ":", "return", "value", "return", "None" ]
https://github.com/edgewall/trac/blob/beb3e4eaf1e0a456d801a50a8614ecab06de29fc/trac/web/api.py#L674-L682
blawar/nut
2cf351400418399a70164987e28670309f6c9cb5
nut/Users.py
python
User.getSwitchPort
(self)
return self.switchPort
[]
def getSwitchPort(self): return self.switchPort
[ "def", "getSwitchPort", "(", "self", ")", ":", "return", "self", ".", "switchPort" ]
https://github.com/blawar/nut/blob/2cf351400418399a70164987e28670309f6c9cb5/nut/Users.py#L81-L82
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idaapi.py
python
simplecustviewer_t.PatchLine
(self, lineno, offs, value)
return _idaapi.pyscv_patch_line(self.__this, lineno, offs, value)
Patches an existing line character at the given offset. This is a low level function. You must know what you're doing
Patches an existing line character at the given offset. This is a low level function. You must know what you're doing
[ "Patches", "an", "existing", "line", "character", "at", "the", "given", "offset", ".", "This", "is", "a", "low", "level", "function", ".", "You", "must", "know", "what", "you", "re", "doing" ]
def PatchLine(self, lineno, offs, value): """ Patches an existing line character at the given offset. This is a low level function. You must know what you're doing """ return _idaapi.pyscv_patch_line(self.__this, lineno, offs, value)
[ "def", "PatchLine", "(", "self", ",", "lineno", ",", "offs", ",", "value", ")", ":", "return", "_idaapi", ".", "pyscv_patch_line", "(", "self", ".", "__this", ",", "lineno", ",", "offs", ",", "value", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L46042-L46046
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/op2/tables/oug/oug.py
python
OUG._read_oug_no
(self, data: bytes, ndata: int)
return n
table_code = 901 # /610/611
table_code = 901 # /610/611
[ "table_code", "=", "901", "#", "/", "610", "/", "611" ]
def _read_oug_no(self, data: bytes, ndata: int): """ table_code = 901 # /610/611 """ op2 = self.op2 if op2.thermal == 0: if op2.table_code == 1: # displacement assert op2.table_name in [b'OUGNO1', b'OUGNO2'], 'op2.table_name=%r' % op2.table_name result_name = 'no.displacements' obj = RealDisplacementArray elif op2.table_code == 10: # velocity assert op2.table_name in [b'OVGNO1', b'OVGNO2'], 'op2.table_name=%r' % op2.table_name result_name = 'no.velocities' obj = RealVelocityArray elif op2.table_code == 11: # acceleration assert op2.table_name in [b'OAGNO1', b'OAGNO2'], 'op2.table_name=%r' % op2.table_name result_name = 'no.accelerations' obj = RealAccelerationArray elif op2.table_code == 901: assert op2.table_name in [b'OUGNO1', b'OUGNO2'], 'op2.table_name=%r' % op2.table_name result_name = 'no.displacements' obj = RealDisplacementArray elif op2.table_code == 910: assert op2.table_name in [b'OUGNO1', b'OUGNO2'], 'op2.table_name=%r' % op2.table_name result_name = 'no.velocities' obj = RealVelocityArray elif op2.table_code == 911: assert op2.table_name in [b'OUGNO1', b'OUGNO2', b'OAGNO1', b'OAGNO2'], 'op2.table_name=%r' % op2.table_name result_name = 'no.accelerations' obj = RealAccelerationArray else: n = op2._not_implemented_or_skip(data, ndata, op2.code_information()) return n if op2._results.is_not_saved(result_name): return ndata op2._results._found_result(result_name) storage_obj = op2.get_result(result_name) n = op2._read_random_table(data, ndata, result_name, storage_obj, obj, 'node', random_code=op2.random_code) #elif op2.thermal == 1: #result_name = 'accelerations' #storage_obj = op2.accelerations #if op2._results.is_not_saved(result_name): #return ndata #op2._results._found_result(result_name) #n = self._read_table(data, ndata, result_name, storage_obj, #None, None, #None, None, 'node', random_code=op2.random_code) #elif op2.thermal == 2: #result_name = 'acceleration_scaled_response_spectra_abs' #storage_obj = op2.acceleration_scaled_response_spectra_abs #if op2._results.is_not_saved(result_name): #return ndata #op2._results._found_result(result_name) #n = self._read_table(data, ndata, result_name, storage_obj, #RealAcceleration, ComplexAcceleration, #RealAccelerationArray, ComplexAccelerationArray, #'node', random_code=op2.random_code) ##n = op2._not_implemented_or_skip(data, ndata, msg='thermal=2') #elif op2.thermal == 4: #result_name = 'acceleration_scaled_response_spectra_nrl' #storage_obj = op2.acceleration_scaled_response_spectra_nrl #if op2._results.is_not_saved(result_name): #return ndata #op2._results._found_result(result_name) #n = self._read_table(data, ndata, result_name, storage_obj, #RealAcceleration, ComplexAcceleration, #RealAccelerationArray, ComplexAccelerationArray, #'node', random_code=op2.random_code) ##n = op2._not_implemented_or_skip(data, ndata, msg='thermal=4') else: raise NotImplementedError(op2.thermal) return n
[ "def", "_read_oug_no", "(", "self", ",", "data", ":", "bytes", ",", "ndata", ":", "int", ")", ":", "op2", "=", "self", ".", "op2", "if", "op2", ".", "thermal", "==", "0", ":", "if", "op2", ".", "table_code", "==", "1", ":", "# displacement", "asser...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/op2/tables/oug/oug.py#L1345-L1424
hujinsen/StarGAN-Voice-Conversion
eba9f39903bf93ae214a72496a927152d507ef51
utility.py
python
get_speakers
(trainset: str = './data/fourspeakers')
return all_speaker
return current selected speakers for training eg. ['SF2', 'TM1', 'SF1', 'TM2']
return current selected speakers for training eg. ['SF2', 'TM1', 'SF1', 'TM2']
[ "return", "current", "selected", "speakers", "for", "training", "eg", ".", "[", "SF2", "TM1", "SF1", "TM2", "]" ]
def get_speakers(trainset: str = './data/fourspeakers'): '''return current selected speakers for training eg. ['SF2', 'TM1', 'SF1', 'TM2'] ''' p = os.path.join(trainset, "*") all_sub_folder = glob.glob(p) all_speaker = [os.path.normpath(s).rsplit(os.sep, maxsplit=1)[1] for s in all_sub_folder] return all_speaker
[ "def", "get_speakers", "(", "trainset", ":", "str", "=", "'./data/fourspeakers'", ")", ":", "p", "=", "os", ".", "path", ".", "join", "(", "trainset", ",", "\"*\"", ")", "all_sub_folder", "=", "glob", ".", "glob", "(", "p", ")", "all_speaker", "=", "["...
https://github.com/hujinsen/StarGAN-Voice-Conversion/blob/eba9f39903bf93ae214a72496a927152d507ef51/utility.py#L9-L18
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/core/byteflow.py
python
TraceRunner.op_GET_ITER
(self, state, inst)
[]
def op_GET_ITER(self, state, inst): value = state.pop() res = state.make_temp() state.append(inst, value=value, res=res) state.push(res)
[ "def", "op_GET_ITER", "(", "self", ",", "state", ",", "inst", ")", ":", "value", "=", "state", ".", "pop", "(", ")", "res", "=", "state", ".", "make_temp", "(", ")", "state", ".", "append", "(", "inst", ",", "value", "=", "value", ",", "res", "="...
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/core/byteflow.py#L1007-L1011
fsspec/gcsfs
fd67c7d1b6ca9db83a0deadd1557470c37b0836a
gcsfs/core.py
python
GCSFileSystem.split_path
(cls, path)
Normalise GCS path string into bucket and key. Parameters ---------- path : string Input path, like `gcs://mybucket/path/to/file`. Path is of the form: '[gs|gcs://]bucket[/key]' Returns ------- (bucket, key) tuple
Normalise GCS path string into bucket and key.
[ "Normalise", "GCS", "path", "string", "into", "bucket", "and", "key", "." ]
def split_path(cls, path): """ Normalise GCS path string into bucket and key. Parameters ---------- path : string Input path, like `gcs://mybucket/path/to/file`. Path is of the form: '[gs|gcs://]bucket[/key]' Returns ------- (bucket, key) tuple """ path = cls._strip_protocol(path).lstrip("/") if "/" not in path: return path, "" else: return path.split("/", 1)
[ "def", "split_path", "(", "cls", ",", "path", ")", ":", "path", "=", "cls", ".", "_strip_protocol", "(", "path", ")", ".", "lstrip", "(", "\"/\"", ")", "if", "\"/\"", "not", "in", "path", ":", "return", "path", ",", "\"\"", "else", ":", "return", "...
https://github.com/fsspec/gcsfs/blob/fd67c7d1b6ca9db83a0deadd1557470c37b0836a/gcsfs/core.py#L1163-L1181
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/visualize/owtreeviewer2d.py
python
OWTreeViewer2D.toggle_tree_depth
(self)
[]
def toggle_tree_depth(self): self.walkupdate(self.root_node) self.scene.fix_pos(self.root_node, 10, 10) self.scene.update()
[ "def", "toggle_tree_depth", "(", "self", ")", ":", "self", ".", "walkupdate", "(", "self", ".", "root_node", ")", "self", ".", "scene", ".", "fix_pos", "(", "self", ".", "root_node", ",", "10", ",", "10", ")", "self", ".", "scene", ".", "update", "("...
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/visualize/owtreeviewer2d.py#L448-L451
google/upvote_py2
51606947641763489db31bffcb934e8112eb5a08
upvote/gae/lib/bit9/context.py
python
Context.ExecuteRequest
(self, method, api_route=None, query_args=None, data=None)
Execute an API request using the current API context.
Execute an API request using the current API context.
[ "Execute", "an", "API", "request", "using", "the", "current", "API", "context", "." ]
def ExecuteRequest(self, method, api_route=None, query_args=None, data=None): """Execute an API request using the current API context.""" if method not in constants.METHOD.SET_ALL: raise ValueError('Invalid method: {}'.format(method)) url = self._GetApiUrl(api_route, query_args) if data is None: logging.info('API %s: %s', method, url) else: logging.info('API %s: %s (data: %s)', method, url, data) try: response = requests.request( method, url, headers=self._GetApiHeaders(), json=data, verify=True, timeout=self.timeout) except requests.RequestException as e: raise excs.RequestError( 'Error performing {} {}: {}'.format(method, url, e)) else: return self._UnwrapResponse(response)
[ "def", "ExecuteRequest", "(", "self", ",", "method", ",", "api_route", "=", "None", ",", "query_args", "=", "None", ",", "data", "=", "None", ")", ":", "if", "method", "not", "in", "constants", ".", "METHOD", ".", "SET_ALL", ":", "raise", "ValueError", ...
https://github.com/google/upvote_py2/blob/51606947641763489db31bffcb934e8112eb5a08/upvote/gae/lib/bit9/context.py#L161-L181
openembedded/openembedded-core
9154f71c7267e9731156c1dfd57397103e9e6a2b
scripts/lib/argparse_oe.py
python
ArgumentParser.parse_args
(self, args=None, namespace=None)
return args
Parse arguments, using the correct subparser to show the error.
Parse arguments, using the correct subparser to show the error.
[ "Parse", "arguments", "using", "the", "correct", "subparser", "to", "show", "the", "error", "." ]
def parse_args(self, args=None, namespace=None): """Parse arguments, using the correct subparser to show the error.""" args, argv = self.parse_known_args(args, namespace) if argv: message = 'unrecognized arguments: %s' % ' '.join(argv) if self._subparsers: subparser = self._get_subparser(args) subparser.error(message) else: self.error(message) sys.exit(2) return args
[ "def", "parse_args", "(", "self", ",", "args", "=", "None", ",", "namespace", "=", "None", ")", ":", "args", ",", "argv", "=", "self", ".", "parse_known_args", "(", "args", ",", "namespace", ")", "if", "argv", ":", "message", "=", "'unrecognized argument...
https://github.com/openembedded/openembedded-core/blob/9154f71c7267e9731156c1dfd57397103e9e6a2b/scripts/lib/argparse_oe.py#L62-L73
atomistic-machine-learning/schnetpack
dacf6076d43509dfd8b6694a846ac8453ae39b5e
src/schnetpack/data/merging.py
python
save_dataset
(dbpath, dataset, overwrite=False)
Write dataset instance to ase-db file. Args: dbpath (str): path to the new database dataset (spk.data.ConcatAtomsData or spk.data.AtomsDataSubset): dataset instance to be stored overwrite (bool): overwrite existing database
Write dataset instance to ase-db file.
[ "Write", "dataset", "instance", "to", "ase", "-", "db", "file", "." ]
def save_dataset(dbpath, dataset, overwrite=False): """ Write dataset instance to ase-db file. Args: dbpath (str): path to the new database dataset (spk.data.ConcatAtomsData or spk.data.AtomsDataSubset): dataset instance to be stored overwrite (bool): overwrite existing database """ # check if path exists if os.path.exists(dbpath): if overwrite: os.remove(dbpath) raise AtomsDataError( "The selected dbpath does already exist. Set overwrite=True or change " "dbpath." ) # build metadata metadata = dict() metadata["atomref"] = dataset.atomref metadata["available_properties"] = dataset.available_properties # write dataset with connect(dbpath) as conn: # write metadata conn.metadata = metadata # write datapoints for idx in range(len(dataset)): atms, data = dataset.get_properties(idx) # filter available properties data_clean = dict() for pname, prop in data.items(): if pname.startswith("_"): continue if pname in dataset.available_properties: data_clean[pname] = prop conn.write(atms, data=data_clean)
[ "def", "save_dataset", "(", "dbpath", ",", "dataset", ",", "overwrite", "=", "False", ")", ":", "# check if path exists", "if", "os", ".", "path", ".", "exists", "(", "dbpath", ")", ":", "if", "overwrite", ":", "os", ".", "remove", "(", "dbpath", ")", ...
https://github.com/atomistic-machine-learning/schnetpack/blob/dacf6076d43509dfd8b6694a846ac8453ae39b5e/src/schnetpack/data/merging.py#L48-L88
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/domain/calculations.py
python
not_implemented
(domain, *args)
return '<p class="text-danger">not implemented</p>'
[]
def not_implemented(domain, *args): return '<p class="text-danger">not implemented</p>'
[ "def", "not_implemented", "(", "domain", ",", "*", "args", ")", ":", "return", "'<p class=\"text-danger\">not implemented</p>'" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/domain/calculations.py#L253-L254
openbmc/openbmc
5f4109adae05f4d6925bfe960007d52f98c61086
poky/meta/lib/oe/maketype.py
python
factory
(var_type)
Return the factory for a specified type.
Return the factory for a specified type.
[ "Return", "the", "factory", "for", "a", "specified", "type", "." ]
def factory(var_type): """Return the factory for a specified type.""" if var_type is None: raise TypeError("No type specified. Valid types: %s" % ', '.join(available_types)) try: return available_types[var_type] except KeyError: raise TypeError("Invalid type '%s':\n Valid types: %s" % (var_type, ', '.join(available_types)))
[ "def", "factory", "(", "var_type", ")", ":", "if", "var_type", "is", "None", ":", "raise", "TypeError", "(", "\"No type specified. Valid types: %s\"", "%", "', '", ".", "join", "(", "available_types", ")", ")", "try", ":", "return", "available_types", "[", "va...
https://github.com/openbmc/openbmc/blob/5f4109adae05f4d6925bfe960007d52f98c61086/poky/meta/lib/oe/maketype.py#L28-L37
pilotmoon/PopClip-Extensions
29fc472befc09ee350092ac70283bd9fdb456cb6
source/Trello/requests/packages/urllib3/util/retry.py
python
Retry._is_connection_error
(self, err)
return isinstance(err, ConnectTimeoutError)
Errors when we're fairly sure that the server did not receive the request, so it should be safe to retry.
Errors when we're fairly sure that the server did not receive the request, so it should be safe to retry.
[ "Errors", "when", "we", "re", "fairly", "sure", "that", "the", "server", "did", "not", "receive", "the", "request", "so", "it", "should", "be", "safe", "to", "retry", "." ]
def _is_connection_error(self, err): """ Errors when we're fairly sure that the server did not receive the request, so it should be safe to retry. """ return isinstance(err, ConnectTimeoutError)
[ "def", "_is_connection_error", "(", "self", ",", "err", ")", ":", "return", "isinstance", "(", "err", ",", "ConnectTimeoutError", ")" ]
https://github.com/pilotmoon/PopClip-Extensions/blob/29fc472befc09ee350092ac70283bd9fdb456cb6/source/Trello/requests/packages/urllib3/util/retry.py#L180-L184
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/ssh_service.py
python
start
(name, sig=None)
return __proxy__[proxy_fn](name)
Start the specified service on the ssh_sample CLI Example: .. code-block:: bash salt '*' service.start <service name>
Start the specified service on the ssh_sample
[ "Start", "the", "specified", "service", "on", "the", "ssh_sample" ]
def start(name, sig=None): """ Start the specified service on the ssh_sample CLI Example: .. code-block:: bash salt '*' service.start <service name> """ proxy_fn = "ssh_sample.service_start" return __proxy__[proxy_fn](name)
[ "def", "start", "(", "name", ",", "sig", "=", "None", ")", ":", "proxy_fn", "=", "\"ssh_sample.service_start\"", "return", "__proxy__", "[", "proxy_fn", "]", "(", "name", ")" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/ssh_service.py#L71-L83
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
cpython/Lib/decimal.py
python
Context.add
(self, a, b)
Return the sum of the two operands. >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) Decimal('19.00') >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) Decimal('1.02E+4') >>> ExtendedContext.add(1, Decimal(2)) Decimal('3') >>> ExtendedContext.add(Decimal(8), 5) Decimal('13') >>> ExtendedContext.add(5, 5) Decimal('10')
Return the sum of the two operands.
[ "Return", "the", "sum", "of", "the", "two", "operands", "." ]
def add(self, a, b): """Return the sum of the two operands. >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) Decimal('19.00') >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) Decimal('1.02E+4') >>> ExtendedContext.add(1, Decimal(2)) Decimal('3') >>> ExtendedContext.add(Decimal(8), 5) Decimal('13') >>> ExtendedContext.add(5, 5) Decimal('10') """ a = _convert_other(a, raiseit=True) r = a.__add__(b, context=self) if r is NotImplemented: raise TypeError("Unable to convert %s to Decimal" % b) else: return r
[ "def", "add", "(", "self", ",", "a", ",", "b", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "r", "=", "a", ".", "__add__", "(", "b", ",", "context", "=", "self", ")", "if", "r", "is", "NotImplemented", ":", ...
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/decimal.py#L3950-L3969
carlosgprado/JARVIS
29ffc6e92d2e251d1a29ded71f52d634482a2a57
IDAPlugin/jarvis/jarvis/core/helpers/Function.py
python
backtrace_args_x86
(ea, nr_args)
return arg_list
Find the dangerous function arguments Ex. "call strncpy" find the third push, which should correspond to the size argument @returns: list of tuples (op, ea) (may be empty)
Find the dangerous function arguments Ex. "call strncpy" find the third push, which should correspond to the size argument
[ "Find", "the", "dangerous", "function", "arguments", "Ex", ".", "call", "strncpy", "find", "the", "third", "push", "which", "should", "correspond", "to", "the", "size", "argument" ]
def backtrace_args_x86(ea, nr_args): """ Find the dangerous function arguments Ex. "call strncpy" find the third push, which should correspond to the size argument @returns: list of tuples (op, ea) (may be empty) """ if idc.__EA64__: raise "Use 64 bit version!" # # x86 is a bit trickier. # We will track the pushes # prev_addr = ea arg_list = [] while nr_args > 0: pi = DecodePreviousInstruction(prev_addr) # DecodePreviousInstruction returns None if we try # to decode past the beginning of the function if not pi: return [] if pi.get_canon_mnem() == 'push': nr_args -= 1 push_op = GetOpnd(pi.ea, 0) arg_list.append((push_op, pi.ea)) prev_addr = pi.ea return arg_list
[ "def", "backtrace_args_x86", "(", "ea", ",", "nr_args", ")", ":", "if", "idc", ".", "__EA64__", ":", "raise", "\"Use 64 bit version!\"", "#", "# x86 is a bit trickier.", "# We will track the pushes", "#", "prev_addr", "=", "ea", "arg_list", "=", "[", "]", "while",...
https://github.com/carlosgprado/JARVIS/blob/29ffc6e92d2e251d1a29ded71f52d634482a2a57/IDAPlugin/jarvis/jarvis/core/helpers/Function.py#L27-L59
openembedded/bitbake
98407efc8c670abd71d3fa88ec3776ee9b5c38f3
lib/bb/providers.py
python
sortPriorities
(pn, dataCache, pkg_pn = None)
return tmp_pn
Reorder pkg_pn by file priority and default preference
Reorder pkg_pn by file priority and default preference
[ "Reorder", "pkg_pn", "by", "file", "priority", "and", "default", "preference" ]
def sortPriorities(pn, dataCache, pkg_pn = None): """ Reorder pkg_pn by file priority and default preference """ if not pkg_pn: pkg_pn = dataCache.pkg_pn files = pkg_pn[pn] priorities = {} for f in files: priority = dataCache.bbfile_priority[f] preference = dataCache.pkg_dp[f] if priority not in priorities: priorities[priority] = {} if preference not in priorities[priority]: priorities[priority][preference] = [] priorities[priority][preference].append(f) tmp_pn = [] for pri in sorted(priorities): tmp_pref = [] for pref in sorted(priorities[pri]): tmp_pref.extend(priorities[pri][pref]) tmp_pn = [tmp_pref] + tmp_pn return tmp_pn
[ "def", "sortPriorities", "(", "pn", ",", "dataCache", ",", "pkg_pn", "=", "None", ")", ":", "if", "not", "pkg_pn", ":", "pkg_pn", "=", "dataCache", ".", "pkg_pn", "files", "=", "pkg_pn", "[", "pn", "]", "priorities", "=", "{", "}", "for", "f", "in", ...
https://github.com/openembedded/bitbake/blob/98407efc8c670abd71d3fa88ec3776ee9b5c38f3/lib/bb/providers.py#L63-L88
benedekrozemberczki/karateclub
8588463906dc792785f951d287c66c2f070bda46
karateclub/node_embedding/attributed/tene.py
python
TENE._init_weights
(self)
Setup basis and feature matrices.
Setup basis and feature matrices.
[ "Setup", "basis", "and", "feature", "matrices", "." ]
def _init_weights(self): """ Setup basis and feature matrices. """ self._M = np.random.uniform(0, 1, (self._X.shape[0], self.dimensions)) self._U = np.random.uniform(0, 1, (self._X.shape[0], self.dimensions)) self._Q = np.random.uniform(0, 1, (self._X.shape[0], self.dimensions)) self._V = np.random.uniform(0, 1, (self._T.shape[1], self.dimensions)) self._C = np.random.uniform(0, 1, (self.dimensions, self.dimensions))
[ "def", "_init_weights", "(", "self", ")", ":", "self", ".", "_M", "=", "np", ".", "random", ".", "uniform", "(", "0", ",", "1", ",", "(", "self", ".", "_X", ".", "shape", "[", "0", "]", ",", "self", ".", "dimensions", ")", ")", "self", ".", "...
https://github.com/benedekrozemberczki/karateclub/blob/8588463906dc792785f951d287c66c2f070bda46/karateclub/node_embedding/attributed/tene.py#L40-L48
Flask-Middleware/flask-security
9ebc0342c47c0eed19246e143e580d06cb680580
flask_security/recoverable.py
python
generate_reset_password_token
(user)
return _security.reset_serializer.dumps(data)
Generates a unique reset password token for the specified user. :param user: The user to work with
Generates a unique reset password token for the specified user.
[ "Generates", "a", "unique", "reset", "password", "token", "for", "the", "specified", "user", "." ]
def generate_reset_password_token(user): """Generates a unique reset password token for the specified user. :param user: The user to work with """ password_hash = hash_data(user.password) if user.password else None data = [str(user.fs_uniquifier), password_hash] return _security.reset_serializer.dumps(data)
[ "def", "generate_reset_password_token", "(", "user", ")", ":", "password_hash", "=", "hash_data", "(", "user", ".", "password", ")", "if", "user", ".", "password", "else", "None", "data", "=", "[", "str", "(", "user", ".", "fs_uniquifier", ")", ",", "passw...
https://github.com/Flask-Middleware/flask-security/blob/9ebc0342c47c0eed19246e143e580d06cb680580/flask_security/recoverable.py#L67-L74
translate/translate
72816df696b5263abfe80ab59129b299b85ae749
translate/storage/pypo.py
python
pounit.hasplural
(self)
return len(self.msgid_plural) > 0
returns whether this pounit contains plural strings...
returns whether this pounit contains plural strings...
[ "returns", "whether", "this", "pounit", "contains", "plural", "strings", "..." ]
def hasplural(self): """returns whether this pounit contains plural strings...""" return len(self.msgid_plural) > 0
[ "def", "hasplural", "(", "self", ")", ":", "return", "len", "(", "self", ".", "msgid_plural", ")", ">", "0" ]
https://github.com/translate/translate/blob/72816df696b5263abfe80ab59129b299b85ae749/translate/storage/pypo.py#L653-L655
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/sysconfig.py
python
_main
()
Display all information sysconfig detains.
Display all information sysconfig detains.
[ "Display", "all", "information", "sysconfig", "detains", "." ]
def _main(): """Display all information sysconfig detains.""" if '--generate-posix-vars' in sys.argv: _generate_posix_vars() return print('Platform: "%s"' % get_platform()) print('Python version: "%s"' % get_python_version()) print('Current installation scheme: "%s"' % _get_default_scheme()) print() _print_dict('Paths', get_paths()) print() _print_dict('Variables', get_config_vars())
[ "def", "_main", "(", ")", ":", "if", "'--generate-posix-vars'", "in", "sys", ".", "argv", ":", "_generate_posix_vars", "(", ")", "return", "print", "(", "'Platform: \"%s\"'", "%", "get_platform", "(", ")", ")", "print", "(", "'Python version: \"%s\"'", "%", "g...
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/sysconfig.py#L692-L703
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/opkg.py
python
hold
(name=None, pkgs=None, sources=None, **kwargs)
return ret
Set package in 'hold' state, meaning it will not be upgraded. name The name of the package, e.g., 'tmux' CLI Example: .. code-block:: bash salt '*' pkg.hold <package name> pkgs A list of packages to hold. Must be passed as a python list. CLI Example: .. code-block:: bash salt '*' pkg.hold pkgs='["foo", "bar"]'
Set package in 'hold' state, meaning it will not be upgraded.
[ "Set", "package", "in", "hold", "state", "meaning", "it", "will", "not", "be", "upgraded", "." ]
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613 """ Set package in 'hold' state, meaning it will not be upgraded. name The name of the package, e.g., 'tmux' CLI Example: .. code-block:: bash salt '*' pkg.hold <package name> pkgs A list of packages to hold. Must be passed as a python list. CLI Example: .. code-block:: bash salt '*' pkg.hold pkgs='["foo", "bar"]' """ if not name and not pkgs and not sources: raise SaltInvocationError("One of name, pkgs, or sources must be specified.") if pkgs and sources: raise SaltInvocationError("Only one of pkgs or sources can be specified.") targets = [] if pkgs: targets.extend(pkgs) elif sources: for source in sources: targets.append(next(iter(source))) else: targets.append(name) ret = {} for target in targets: if isinstance(target, dict): target = next(iter(target)) ret[target] = {"name": target, "changes": {}, "result": False, "comment": ""} state = _get_state(target) if not state: ret[target]["comment"] = "Package {} not currently held.".format(target) elif state != "hold": if "test" in __opts__ and __opts__["test"]: ret[target].update(result=None) ret[target]["comment"] = "Package {} is set to be held.".format(target) else: result = _set_state(target, "hold") ret[target].update(changes=result[target], result=True) ret[target]["comment"] = "Package {} is now being held.".format(target) else: ret[target].update(result=True) ret[target]["comment"] = "Package {} is already set to be held.".format( target ) return ret
[ "def", "hold", "(", "name", "=", "None", ",", "pkgs", "=", "None", ",", "sources", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=W0613", "if", "not", "name", "and", "not", "pkgs", "and", "not", "sources", ":", "raise", "SaltInvocat...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/opkg.py#L796-L855