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
pyjanitor-devs/pyjanitor
2207c0bddbf7e23f56e87892de0405787b11621e
janitor/functions/remove_empty.py
python
remove_empty
(df: pd.DataFrame)
return df
Drop all rows and columns that are completely null. This method also resets the index(by default) since it doesn't make sense to preserve the index of a completely empty row. This method mutates the original DataFrame. Implementation is inspired from [StackOverflow][so]. [so]: https://stackoverf...
Drop all rows and columns that are completely null.
[ "Drop", "all", "rows", "and", "columns", "that", "are", "completely", "null", "." ]
def remove_empty(df: pd.DataFrame) -> pd.DataFrame: """Drop all rows and columns that are completely null. This method also resets the index(by default) since it doesn't make sense to preserve the index of a completely empty row. This method mutates the original DataFrame. Implementation is inspi...
[ "def", "remove_empty", "(", "df", ":", "pd", ".", "DataFrame", ")", "->", "pd", ".", "DataFrame", ":", "# noqa: E501", "nanrows", "=", "df", ".", "index", "[", "df", ".", "isna", "(", ")", ".", "all", "(", "axis", "=", "1", ")", "]", "df", "=", ...
https://github.com/pyjanitor-devs/pyjanitor/blob/2207c0bddbf7e23f56e87892de0405787b11621e/janitor/functions/remove_empty.py#L6-L41
ethereum/trinity
6383280c5044feb06695ac2f7bc1100b7bcf4fe0
p2p/auth.py
python
HandshakeInitiator.decode_auth_ack_message
(self, ciphertext: bytes)
return eph_pubkey, nonce
[]
def decode_auth_ack_message(self, ciphertext: bytes) -> Tuple[datatypes.PublicKey, bytes]: if len(ciphertext) < ENCRYPTED_AUTH_ACK_LEN: raise BadAckMessage(f"Auth ack msg too short: {len(ciphertext)}") elif len(ciphertext) == ENCRYPTED_AUTH_ACK_LEN: eph_pubkey, nonce, _ = decode_...
[ "def", "decode_auth_ack_message", "(", "self", ",", "ciphertext", ":", "bytes", ")", "->", "Tuple", "[", "datatypes", ".", "PublicKey", ",", "bytes", "]", ":", "if", "len", "(", "ciphertext", ")", "<", "ENCRYPTED_AUTH_ACK_LEN", ":", "raise", "BadAckMessage", ...
https://github.com/ethereum/trinity/blob/6383280c5044feb06695ac2f7bc1100b7bcf4fe0/p2p/auth.py#L205-L212
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v1_rbd_volume_source.py
python
V1RBDVolumeSource.__repr__
(self)
return self.to_str()
For `print` and `pprint`
For `print` and `pprint`
[ "For", "print", "and", "pprint" ]
def __repr__(self): """For `print` and `pprint`""" return self.to_str()
[ "def", "__repr__", "(", "self", ")", ":", "return", "self", ".", "to_str", "(", ")" ]
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1_rbd_volume_source.py#L302-L304
stopstalk/stopstalk-deployment
10c3ab44c4ece33ae515f6888c15033db2004bb1
modules/sites/hackerrank.py
python
Profile.get_submissions
(self, last_retrieved, is_daily_retrieval)
return submissions
Retrieve HackerRank submissions after last retrieved timestamp @param last_retrieved (DateTime): Last retrieved timestamp for the user @param is_daily_retrieval (Boolean): If this call is from daily retrieval cron @return (Dict): Dictionary of submissions containing all the ...
Retrieve HackerRank submissions after last retrieved timestamp
[ "Retrieve", "HackerRank", "submissions", "after", "last", "retrieved", "timestamp" ]
def get_submissions(self, last_retrieved, is_daily_retrieval): """ Retrieve HackerRank submissions after last retrieved timestamp @param last_retrieved (DateTime): Last retrieved timestamp for the user @param is_daily_retrieval (Boolean): If this call is from daily retrieval...
[ "def", "get_submissions", "(", "self", ",", "last_retrieved", ",", "is_daily_retrieval", ")", ":", "handle", "=", "self", ".", "handle", "url", "=", "\"https://www.hackerrank.com/rest/hackers/\"", "+", "handle", "+", "\"/recent_challenges\"", "request_params", "=", "{...
https://github.com/stopstalk/stopstalk-deployment/blob/10c3ab44c4ece33ae515f6888c15033db2004bb1/modules/sites/hackerrank.py#L185-L244
wikimedia/pywikibot
81a01ffaec7271bf5b4b170f85a80388420a4e78
docs/conf.py
python
pywikibot_skip_members
(app, what, name, obj, skip, options)
return skip or name in exclusions
Skip certain members from documentation.
Skip certain members from documentation.
[ "Skip", "certain", "members", "from", "documentation", "." ]
def pywikibot_skip_members(app, what, name, obj, skip, options): """Skip certain members from documentation.""" inclusions = () exclusions = () if name in inclusions and len(str.splitlines(obj.__doc__ or '')) >= 3: return False if name.startswith('__') and name.endswith('__'): return...
[ "def", "pywikibot_skip_members", "(", "app", ",", "what", ",", "name", ",", "obj", ",", "skip", ",", "options", ")", ":", "inclusions", "=", "(", ")", "exclusions", "=", "(", ")", "if", "name", "in", "inclusions", "and", "len", "(", "str", ".", "spli...
https://github.com/wikimedia/pywikibot/blob/81a01ffaec7271bf5b4b170f85a80388420a4e78/docs/conf.py#L470-L481
celery/kombu
853b13f1d018ebfe7ad2d064a3111cac9fcf5383
kombu/transport/azurestoragequeues.py
python
Channel._ensure_queue
(self, queue)
Ensure a queue exists.
Ensure a queue exists.
[ "Ensure", "a", "queue", "exists", "." ]
def _ensure_queue(self, queue): """Ensure a queue exists.""" queue = self.entity_name(self.queue_name_prefix + queue) try: return self._queue_name_cache[queue] except KeyError: self.queue_service.create_queue(queue, fail_on_exist=False) q = self._queue...
[ "def", "_ensure_queue", "(", "self", ",", "queue", ")", ":", "queue", "=", "self", ".", "entity_name", "(", "self", ".", "queue_name_prefix", "+", "queue", ")", "try", ":", "return", "self", ".", "_queue_name_cache", "[", "queue", "]", "except", "KeyError"...
https://github.com/celery/kombu/blob/853b13f1d018ebfe7ad2d064a3111cac9fcf5383/kombu/transport/azurestoragequeues.py#L84-L92
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/core/handlers/base.py
python
BaseHandler._legacy_get_response
(self, request)
return response
Apply process_request() middleware and call the main _get_response(), if needed. Used only for legacy MIDDLEWARE_CLASSES.
Apply process_request() middleware and call the main _get_response(), if needed. Used only for legacy MIDDLEWARE_CLASSES.
[ "Apply", "process_request", "()", "middleware", "and", "call", "the", "main", "_get_response", "()", "if", "needed", ".", "Used", "only", "for", "legacy", "MIDDLEWARE_CLASSES", "." ]
def _legacy_get_response(self, request): """ Apply process_request() middleware and call the main _get_response(), if needed. Used only for legacy MIDDLEWARE_CLASSES. """ response = None # Apply request middleware for middleware_method in self._request_middleware:...
[ "def", "_legacy_get_response", "(", "self", ",", "request", ")", ":", "response", "=", "None", "# Apply request middleware", "for", "middleware_method", "in", "self", ".", "_request_middleware", ":", "response", "=", "middleware_method", "(", "request", ")", "if", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/core/handlers/base.py#L236-L250
dinghanshen/SWEM
487f8bc1ee18e70397db79794ae4294fe114db26
intrinsic_dimension/general/stats_buddy.py
python
StatsBuddy._summary_pretty_re
(self, keys_values, style='')
Produce a short, printable summary. Strips "train_" and "test_" strings assuming they will be printed elsewhere.
Produce a short, printable summary. Strips "train_" and "test_" strings assuming they will be printed elsewhere.
[ "Produce", "a", "short", "printable", "summary", ".", "Strips", "train_", "and", "test_", "strings", "assuming", "they", "will", "be", "printed", "elsewhere", "." ]
def _summary_pretty_re(self, keys_values, style=''): '''Produce a short, printable summary. Strips "train_" and "test_" strings assuming they will be printed elsewhere.''' ret = [] losses_seen = 0 for key, value in keys_values: short = key for orig,new in self._pr...
[ "def", "_summary_pretty_re", "(", "self", ",", "keys_values", ",", "style", "=", "''", ")", ":", "ret", "=", "[", "]", "losses_seen", "=", "0", "for", "key", ",", "value", "in", "keys_values", ":", "short", "=", "key", "for", "orig", ",", "new", "in"...
https://github.com/dinghanshen/SWEM/blob/487f8bc1ee18e70397db79794ae4294fe114db26/intrinsic_dimension/general/stats_buddy.py#L209-L229
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/python-social-auth/social/apps/django_app/default/fields.py
python
JSONField.validate
(self, value, model_instance)
Check value is a valid JSON string, raise ValidationError on error.
Check value is a valid JSON string, raise ValidationError on error.
[ "Check", "value", "is", "a", "valid", "JSON", "string", "raise", "ValidationError", "on", "error", "." ]
def validate(self, value, model_instance): """Check value is a valid JSON string, raise ValidationError on error.""" if isinstance(value, six.string_types): super(JSONField, self).validate(value, model_instance) try: json.loads(value) except Ex...
[ "def", "validate", "(", "self", ",", "value", ",", "model_instance", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "super", "(", "JSONField", ",", "self", ")", ".", "validate", "(", "value", ",", "model_instance",...
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/python-social-auth/social/apps/django_app/default/fields.py#L45-L53
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/api/v2010/account/message/media.py
python
MediaList.__init__
(self, version, account_sid, message_sid)
Initialize the MediaList :param Version version: Version that contains the resource :param account_sid: The SID of the Account that created this resource :param message_sid: The unique string that identifies the resource :returns: twilio.rest.api.v2010.account.message.media.MediaList ...
Initialize the MediaList
[ "Initialize", "the", "MediaList" ]
def __init__(self, version, account_sid, message_sid): """ Initialize the MediaList :param Version version: Version that contains the resource :param account_sid: The SID of the Account that created this resource :param message_sid: The unique string that identifies the resource...
[ "def", "__init__", "(", "self", ",", "version", ",", "account_sid", ",", "message_sid", ")", ":", "super", "(", "MediaList", ",", "self", ")", ".", "__init__", "(", "version", ")", "# Path Solution", "self", ".", "_solution", "=", "{", "'account_sid'", ":"...
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/api/v2010/account/message/media.py#L20-L35
openstack/glance
502fa0ffc8970c087c5924742231812c0da6a114
glance/api/authorization.py
python
is_namespace_mutable
(context, namespace)
return namespace.owner == context.owner
Return True if the namespace is mutable in this context.
Return True if the namespace is mutable in this context.
[ "Return", "True", "if", "the", "namespace", "is", "mutable", "in", "this", "context", "." ]
def is_namespace_mutable(context, namespace): """Return True if the namespace is mutable in this context.""" if context.is_admin: return True if context.owner is None: return False return namespace.owner == context.owner
[ "def", "is_namespace_mutable", "(", "context", ",", "namespace", ")", ":", "if", "context", ".", "is_admin", ":", "return", "True", "if", "context", ".", "owner", "is", "None", ":", "return", "False", "return", "namespace", ".", "owner", "==", "context", "...
https://github.com/openstack/glance/blob/502fa0ffc8970c087c5924742231812c0da6a114/glance/api/authorization.py#L489-L497
LudovicRousseau/pyscard
c0a5e2f626be69a0fc7b530631471cf014e4b20e
smartcard/Card.py
python
Card.__hash__
(self)
return hash(str(self))
Returns a hash value for this object (str(self) is unique).
Returns a hash value for this object (str(self) is unique).
[ "Returns", "a", "hash", "value", "for", "this", "object", "(", "str", "(", "self", ")", "is", "unique", ")", "." ]
def __hash__(self): """Returns a hash value for this object (str(self) is unique).""" return hash(str(self))
[ "def", "__hash__", "(", "self", ")", ":", "return", "hash", "(", "str", "(", "self", ")", ")" ]
https://github.com/LudovicRousseau/pyscard/blob/c0a5e2f626be69a0fc7b530631471cf014e4b20e/smartcard/Card.py#L58-L60
akanimax/natural-language-summary-generation-from-structured-data
b8cc906286f97e8523acc8306945c34a4f8ef17c
TensorFlow_implementation/seq2seq/contrib/seq2seq/helper.py
python
ScheduledEmbeddingTrainingHelper.__init__
(self, inputs, sequence_length, embedding, sampling_probability, time_major=False, seed=None, scheduling_seed=None, name=None)
Initializer. Args: inputs: A (structure of) input tensors. sequence_length: An int32 vector tensor. embedding: A callable that takes a vector tensor of `ids` (argmax ids), or the `params` argument for `embedding_lookup`. sampling_probability: A 0D `float32` tensor: the probability o...
Initializer.
[ "Initializer", "." ]
def __init__(self, inputs, sequence_length, embedding, sampling_probability, time_major=False, seed=None, scheduling_seed=None, name=None): """Initializer. Args: inputs: A (structure of) input tensors. sequence_length: An int32 vector tensor. embedding: A callable that takes a ...
[ "def", "__init__", "(", "self", ",", "inputs", ",", "sequence_length", ",", "embedding", ",", "sampling_probability", ",", "time_major", "=", "False", ",", "seed", "=", "None", ",", "scheduling_seed", "=", "None", ",", "name", "=", "None", ")", ":", "with"...
https://github.com/akanimax/natural-language-summary-generation-from-structured-data/blob/b8cc906286f97e8523acc8306945c34a4f8ef17c/TensorFlow_implementation/seq2seq/contrib/seq2seq/helper.py#L215-L255
morganstanley/treadmill
f18267c665baf6def4374d21170198f63ff1cde4
lib/python/treadmill/formatter/tablefmt.py
python
InstanceFinishedStatePrettyFormatter.format
(item)
Return pretty-formatted item.
Return pretty-formatted item.
[ "Return", "pretty", "-", "formatted", "item", "." ]
def format(item): """Return pretty-formatted item.""" schema = [ ('name', None, None), ('state', None, None), ('host', None, None), ('when', None, None), ('details', None, None), ] format_item = make_dict_to_table(schema) ...
[ "def", "format", "(", "item", ")", ":", "schema", "=", "[", "(", "'name'", ",", "None", ",", "None", ")", ",", "(", "'state'", ",", "None", ",", "None", ")", ",", "(", "'host'", ",", "None", ",", "None", ")", ",", "(", "'when'", ",", "None", ...
https://github.com/morganstanley/treadmill/blob/f18267c665baf6def4374d21170198f63ff1cde4/lib/python/treadmill/formatter/tablefmt.py#L575-L591
implus/PytorchInsight
2864528f8b83f52c3df76f7c3804aa468b91e5cf
classification/utils/progress/progress/counter.py
python
Countdown.update
(self)
[]
def update(self): self.write(str(self.remaining))
[ "def", "update", "(", "self", ")", ":", "self", ".", "write", "(", "str", "(", "self", ".", "remaining", ")", ")" ]
https://github.com/implus/PytorchInsight/blob/2864528f8b83f52c3df76f7c3804aa468b91e5cf/classification/utils/progress/progress/counter.py#L33-L34
hahnyuan/nn_tools
e04903d2946a75b62128b64ada7eec8b9fbd841f
Caffe/caffe_net.py
python
_Net.layer
(self,layer_name)
return self.get_layer_by_name(layer_name)
[]
def layer(self,layer_name): return self.get_layer_by_name(layer_name)
[ "def", "layer", "(", "self", ",", "layer_name", ")", ":", "return", "self", ".", "get_layer_by_name", "(", "layer_name", ")" ]
https://github.com/hahnyuan/nn_tools/blob/e04903d2946a75b62128b64ada7eec8b9fbd841f/Caffe/caffe_net.py#L57-L58
openstack/sahara
c4f4d29847d5bcca83d49ef7e9a3378458462a79
sahara/common/config.py
python
set_config_defaults
()
This method updates all configuration default values.
This method updates all configuration default values.
[ "This", "method", "updates", "all", "configuration", "default", "values", "." ]
def set_config_defaults(): """This method updates all configuration default values.""" set_cors_middleware_defaults() # TODO(gmann): Remove setting the default value of config policy_file # once oslo_policy change the default value to 'policy.yaml'. # https://opendev.org/openstack/oslo.policy/src/c...
[ "def", "set_config_defaults", "(", ")", ":", "set_cors_middleware_defaults", "(", ")", "# TODO(gmann): Remove setting the default value of config policy_file", "# once oslo_policy change the default value to 'policy.yaml'.", "# https://opendev.org/openstack/oslo.policy/src/commit/d8534850d9238e8...
https://github.com/openstack/sahara/blob/c4f4d29847d5bcca83d49ef7e9a3378458462a79/sahara/common/config.py#L22-L29
moberweger/deep-prior-pp
11f585f73d2c7957c95db302b770a3b4962c0386
src/util/handdetector.py
python
HandDetector.estimateHandsize
(self, contours, com, cube=(250, 250, 250), tol=0.)
return cube
Estimate hand size from contours :param contours: contours of hand :param com: center of mass :param cube: default cube :param tol: tolerance to be added to all sides :return: metric cube for cropping (x, y, z)
Estimate hand size from contours :param contours: contours of hand :param com: center of mass :param cube: default cube :param tol: tolerance to be added to all sides :return: metric cube for cropping (x, y, z)
[ "Estimate", "hand", "size", "from", "contours", ":", "param", "contours", ":", "contours", "of", "hand", ":", "param", "com", ":", "center", "of", "mass", ":", "param", "cube", ":", "default", "cube", ":", "param", "tol", ":", "tolerance", "to", "be", ...
def estimateHandsize(self, contours, com, cube=(250, 250, 250), tol=0.): """ Estimate hand size from contours :param contours: contours of hand :param com: center of mass :param cube: default cube :param tol: tolerance to be added to all sides :return: metric cube...
[ "def", "estimateHandsize", "(", "self", ",", "contours", ",", "com", ",", "cube", "=", "(", "250", ",", "250", ",", "250", ")", ",", "tol", "=", "0.", ")", ":", "x", ",", "y", ",", "w", ",", "h", "=", "cv2", ".", "boundingRect", "(", "contours"...
https://github.com/moberweger/deep-prior-pp/blob/11f585f73d2c7957c95db302b770a3b4962c0386/src/util/handdetector.py#L911-L937
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Tools/demo/spreadsheet.py
python
SheetGUI.return_event
(self, event)
return "break"
Callback for the Return key.
Callback for the Return key.
[ "Callback", "for", "the", "Return", "key", "." ]
def return_event(self, event): "Callback for the Return key." self.change_cell() x, y = self.currentxy self.setcurrent(x, y+1) return "break"
[ "def", "return_event", "(", "self", ",", "event", ")", ":", "self", ".", "change_cell", "(", ")", "x", ",", "y", "=", "self", ".", "currentxy", "self", ".", "setcurrent", "(", "x", ",", "y", "+", "1", ")", "return", "\"break\"" ]
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Tools/demo/spreadsheet.py#L727-L732
ComplianceAsCode/content
6760a14e7fe3fb34205bd1a165095a9334412e95
ssg/templates.py
python
Builder.get_resolved_langs_to_generate
(self, rule)
return rule_langs.intersection(template_langs)
Given a specific Rule instance, determine which languages are generated by the combination of the rule's template_backends AND the rule's template keys.
Given a specific Rule instance, determine which languages are generated by the combination of the rule's template_backends AND the rule's template keys.
[ "Given", "a", "specific", "Rule", "instance", "determine", "which", "languages", "are", "generated", "by", "the", "combination", "of", "the", "rule", "s", "template_backends", "AND", "the", "rule", "s", "template", "keys", "." ]
def get_resolved_langs_to_generate(self, rule): """ Given a specific Rule instance, determine which languages are generated by the combination of the rule's template_backends AND the rule's template keys. """ if rule.template is None: return None rule...
[ "def", "get_resolved_langs_to_generate", "(", "self", ",", "rule", ")", ":", "if", "rule", ".", "template", "is", "None", ":", "return", "None", "rule_langs", "=", "set", "(", "self", ".", "get_langs_to_generate", "(", "rule", ")", ")", "template_name", "=",...
https://github.com/ComplianceAsCode/content/blob/6760a14e7fe3fb34205bd1a165095a9334412e95/ssg/templates.py#L256-L268
Yelp/paasta
6c08c04a577359509575c794b973ea84d72accf9
paasta_tools/cleanup_maintenance.py
python
cleanup_forgotten_down
()
Clean up hosts forgotten down
Clean up hosts forgotten down
[ "Clean", "up", "hosts", "forgotten", "down" ]
def cleanup_forgotten_down(): """Clean up hosts forgotten down""" log.debug("Cleaning up hosts forgotten down") hosts_forgotten_down = get_hosts_forgotten_down( grace=seconds_to_nanoseconds(10 * 60) ) if hosts_forgotten_down: up(hostnames=hosts_forgotten_down) else: log.d...
[ "def", "cleanup_forgotten_down", "(", ")", ":", "log", ".", "debug", "(", "\"Cleaning up hosts forgotten down\"", ")", "hosts_forgotten_down", "=", "get_hosts_forgotten_down", "(", "grace", "=", "seconds_to_nanoseconds", "(", "10", "*", "60", ")", ")", "if", "hosts_...
https://github.com/Yelp/paasta/blob/6c08c04a577359509575c794b973ea84d72accf9/paasta_tools/cleanup_maintenance.py#L68-L77
Kjuly/iPokeMon-Server
b5e67c67ae248bd092c53fe9e3eee8bf2dba9e3f
bottle.py
python
load
(target, **namespace)
return eval('%s.%s' % (module, target), namespace)
Import a module or fetch an object from a module. * ``package.module`` returns `module` as a module object. * ``pack.mod:name`` returns the module variable `name` from `pack.mod`. * ``pack.mod:func()`` calls `pack.mod.func()` and returns the result. The last form accepts not only funct...
Import a module or fetch an object from a module.
[ "Import", "a", "module", "or", "fetch", "an", "object", "from", "a", "module", "." ]
def load(target, **namespace): """ Import a module or fetch an object from a module. * ``package.module`` returns `module` as a module object. * ``pack.mod:name`` returns the module variable `name` from `pack.mod`. * ``pack.mod:func()`` calls `pack.mod.func()` and returns the result. ...
[ "def", "load", "(", "target", ",", "*", "*", "namespace", ")", ":", "module", ",", "target", "=", "target", ".", "split", "(", "\":\"", ",", "1", ")", "if", "':'", "in", "target", "else", "(", "target", ",", "None", ")", "if", "module", "not", "i...
https://github.com/Kjuly/iPokeMon-Server/blob/b5e67c67ae248bd092c53fe9e3eee8bf2dba9e3f/bottle.py#L2614-L2631
ganeti/ganeti
d340a9ddd12f501bef57da421b5f9b969a4ba905
lib/storage/base.py
python
BlockDev.Rename
(self, new_id)
Rename this device. This may or may not make sense for a given device type.
Rename this device.
[ "Rename", "this", "device", "." ]
def Rename(self, new_id): """Rename this device. This may or may not make sense for a given device type. """ raise NotImplementedError
[ "def", "Rename", "(", "self", ",", "new_id", ")", ":", "raise", "NotImplementedError" ]
https://github.com/ganeti/ganeti/blob/d340a9ddd12f501bef57da421b5f9b969a4ba905/lib/storage/base.py#L179-L185
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/core/virtual_network_client_composite_operations.py
python
VirtualNetworkClientCompositeOperations.remove_import_drg_route_distribution_and_wait_for_state
(self, drg_route_table_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={})
Calls :py:func:`~oci.core.VirtualNetworkClient.remove_import_drg_route_distribution` and waits for the :py:class:`~oci.core.models.DrgRouteTable` acted upon to enter the given state(s). :param str drg_route_table_id: (required) The `OCID`__ of the DRG route table. __ https://do...
Calls :py:func:`~oci.core.VirtualNetworkClient.remove_import_drg_route_distribution` and waits for the :py:class:`~oci.core.models.DrgRouteTable` acted upon to enter the given state(s).
[ "Calls", ":", "py", ":", "func", ":", "~oci", ".", "core", ".", "VirtualNetworkClient", ".", "remove_import_drg_route_distribution", "and", "waits", "for", "the", ":", "py", ":", "class", ":", "~oci", ".", "core", ".", "models", ".", "DrgRouteTable", "acted"...
def remove_import_drg_route_distribution_and_wait_for_state(self, drg_route_table_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}): """ Calls :py:func:`~oci.core.VirtualNetworkClient.remove_import_drg_route_distribution` and waits for the :py:class:`~oci.core.models.DrgRouteTable` acted up...
[ "def", "remove_import_drg_route_distribution_and_wait_for_state", "(", "self", ",", "drg_route_table_id", ",", "wait_for_states", "=", "[", "]", ",", "operation_kwargs", "=", "{", "}", ",", "waiter_kwargs", "=", "{", "}", ")", ":", "operation_result", "=", "self", ...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/core/virtual_network_client_composite_operations.py#L2552-L2590
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
lms/djangoapps/certificates/models.py
python
CertificateTemplateAsset.save
(self, *args, **kwargs)
save the certificate template asset
save the certificate template asset
[ "save", "the", "certificate", "template", "asset" ]
def save(self, *args, **kwargs): """save the certificate template asset """ if self.pk is None: asset_image = self.asset self.asset = None super().save(*args, **kwargs) self.asset = asset_image super().save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "pk", "is", "None", ":", "asset_image", "=", "self", ".", "asset", "self", ".", "asset", "=", "None", "super", "(", ")", ".", "save", "(", "*", ...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/lms/djangoapps/certificates/models.py#L1211-L1219
plasticityai/magnitude
7ac0baeaf181263b661c3ae00643d21e3fd90216
pymagnitude/third_party/_apsw/tools/apswtrace.py
python
fmtfloat
(n, decimals=3, total=None)
return s
Work around borken python float formatting
Work around borken python float formatting
[ "Work", "around", "borken", "python", "float", "formatting" ]
def fmtfloat(n, decimals=3, total=None): "Work around borken python float formatting" s="%0.*f" % (decimals, n) if total: s=(" "*total+s)[-total:] return s
[ "def", "fmtfloat", "(", "n", ",", "decimals", "=", "3", ",", "total", "=", "None", ")", ":", "s", "=", "\"%0.*f\"", "%", "(", "decimals", ",", "n", ")", "if", "total", ":", "s", "=", "(", "\" \"", "*", "total", "+", "s", ")", "[", "-", "total...
https://github.com/plasticityai/magnitude/blob/7ac0baeaf181263b661c3ae00643d21e3fd90216/pymagnitude/third_party/_apsw/tools/apswtrace.py#L294-L299
osmr/imgclsmob
f2993d3ce73a2f7ddba05da3891defb08547d504
tensorflow2/tf2cv/models/vgg.py
python
bn_vgg13b
(**kwargs)
return get_vgg(blocks=13, use_bias=True, use_bn=True, model_name="bn_vgg13b", **kwargs)
VGG-13 model with batch normalization and biases in convolution layers from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root :...
VGG-13 model with batch normalization and biases in convolution layers from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556.
[ "VGG", "-", "13", "model", "with", "batch", "normalization", "and", "biases", "in", "convolution", "layers", "from", "Very", "Deep", "Convolutional", "Networks", "for", "Large", "-", "Scale", "Image", "Recognition", "https", ":", "//", "arxiv", ".", "org", "...
def bn_vgg13b(**kwargs): """ VGG-13 model with batch normalization and biases in convolution layers from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556. Parameters: ---------- pretrained : bool, default False Whether to load the pre...
[ "def", "bn_vgg13b", "(", "*", "*", "kwargs", ")", ":", "return", "get_vgg", "(", "blocks", "=", "13", ",", "use_bias", "=", "True", ",", "use_bn", "=", "True", ",", "model_name", "=", "\"bn_vgg13b\"", ",", "*", "*", "kwargs", ")" ]
https://github.com/osmr/imgclsmob/blob/f2993d3ce73a2f7ddba05da3891defb08547d504/tensorflow2/tf2cv/models/vgg.py#L351-L363
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/api/search/query_parser.py
python
GetQueryNodeTextUnicode
(node)
return node.getText()
Returns the unicode text from node.
Returns the unicode text from node.
[ "Returns", "the", "unicode", "text", "from", "node", "." ]
def GetQueryNodeTextUnicode(node): """Returns the unicode text from node.""" if node.getType() == QueryParser.VALUE and len(node.children) >= 2: return u''.join(c.getText() for c in node.children[1:]) elif node.getType() == QueryParser.VALUE: return None return node.getText()
[ "def", "GetQueryNodeTextUnicode", "(", "node", ")", ":", "if", "node", ".", "getType", "(", ")", "==", "QueryParser", ".", "VALUE", "and", "len", "(", "node", ".", "children", ")", ">=", "2", ":", "return", "u''", ".", "join", "(", "c", ".", "getText...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/api/search/query_parser.py#L221-L227
DataDog/dd-trace-py
13f9c6c1a8b4820365b299ab204f2bb5189d2a49
ddtrace/vendor/dogstatsd/base.py
python
DogStatsd.timing
(self, metric, value, tags=None, sample_rate=None)
Record a timing, optionally setting tags and a sample rate. >>> statsd.timing("query.response.time", 1234)
Record a timing, optionally setting tags and a sample rate.
[ "Record", "a", "timing", "optionally", "setting", "tags", "and", "a", "sample", "rate", "." ]
def timing(self, metric, value, tags=None, sample_rate=None): """ Record a timing, optionally setting tags and a sample rate. >>> statsd.timing("query.response.time", 1234) """ self._report(metric, 'ms', value, tags, sample_rate)
[ "def", "timing", "(", "self", ",", "metric", ",", "value", ",", "tags", "=", "None", ",", "sample_rate", "=", "None", ")", ":", "self", ".", "_report", "(", "metric", ",", "'ms'", ",", "value", ",", "tags", ",", "sample_rate", ")" ]
https://github.com/DataDog/dd-trace-py/blob/13f9c6c1a8b4820365b299ab204f2bb5189d2a49/ddtrace/vendor/dogstatsd/base.py#L352-L358
GoSecure/pyrdp
abd8b8762b6d7fd0e49d4a927b529f892b412743
pyrdp/mitm/config.py
python
MITMConfig.fileDir
(self)
return self.outDir / "files"
Get the directory for intercepted files.
Get the directory for intercepted files.
[ "Get", "the", "directory", "for", "intercepted", "files", "." ]
def fileDir(self) -> Path: """ Get the directory for intercepted files. """ return self.outDir / "files"
[ "def", "fileDir", "(", "self", ")", "->", "Path", ":", "return", "self", ".", "outDir", "/", "\"files\"" ]
https://github.com/GoSecure/pyrdp/blob/abd8b8762b6d7fd0e49d4a927b529f892b412743/pyrdp/mitm/config.py#L99-L103
oanda/v20-python
f28192f4a31bce038cf6dfa302f5878bec192fe5
src/v20/user.py
python
UserInfo.__init__
(self, **kwargs)
Create a new UserInfo instance
Create a new UserInfo instance
[ "Create", "a", "new", "UserInfo", "instance" ]
def __init__(self, **kwargs): """ Create a new UserInfo instance """ super(UserInfo, self).__init__() # # The user-provided username. # self.username = kwargs.get("username") # # The user's OANDA-assigned user ID. # self...
[ "def", "__init__", "(", "self", ",", "*", "*", "kwargs", ")", ":", "super", "(", "UserInfo", ",", "self", ")", ".", "__init__", "(", ")", "#", "# The user-provided username.", "#", "self", ".", "username", "=", "kwargs", ".", "get", "(", "\"username\"", ...
https://github.com/oanda/v20-python/blob/f28192f4a31bce038cf6dfa302f5878bec192fe5/src/v20/user.py#L29-L53
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/matplotlib/image.py
python
_AxesImageBase.set_filterrad
(self, filterrad)
Set the resize filter radius only applicable to some interpolation schemes -- see help for imshow ACCEPTS: positive float
Set the resize filter radius only applicable to some interpolation schemes -- see help for imshow
[ "Set", "the", "resize", "filter", "radius", "only", "applicable", "to", "some", "interpolation", "schemes", "--", "see", "help", "for", "imshow" ]
def set_filterrad(self, filterrad): """ Set the resize filter radius only applicable to some interpolation schemes -- see help for imshow ACCEPTS: positive float """ r = float(filterrad) assert(r > 0) self._filterrad = r
[ "def", "set_filterrad", "(", "self", ",", "filterrad", ")", ":", "r", "=", "float", "(", "filterrad", ")", "assert", "(", "r", ">", "0", ")", "self", ".", "_filterrad", "=", "r" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/matplotlib/image.py#L511-L520
kamalgill/flask-appengine-template
11760f83faccbb0d0afe416fc58e67ecfb4643c2
src/lib/gae_mini_profiler/sampling_profiler.py
python
Profile.__init__
(self)
[]
def __init__(self): # All saved stack trace samples self.samples = [] # Thread id for the request thread currently being profiled self.current_request_thread_id = None # Thread that constantly waits, inspects, waits, inspect, ... self.inspecting_thread = None
[ "def", "__init__", "(", "self", ")", ":", "# All saved stack trace samples", "self", ".", "samples", "=", "[", "]", "# Thread id for the request thread currently being profiled", "self", ".", "current_request_thread_id", "=", "None", "# Thread that constantly waits, inspects, w...
https://github.com/kamalgill/flask-appengine-template/blob/11760f83faccbb0d0afe416fc58e67ecfb4643c2/src/lib/gae_mini_profiler/sampling_profiler.py#L78-L86
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/agca/ideals.py
python
Ideal.intersect
(self, J)
return self._intersect(J)
Compute the intersection of self with ideal J. >>> from sympy.abc import x, y >>> from sympy import QQ >>> R = QQ.old_poly_ring(x, y) >>> R.ideal(x).intersect(R.ideal(y)) <x*y>
Compute the intersection of self with ideal J.
[ "Compute", "the", "intersection", "of", "self", "with", "ideal", "J", "." ]
def intersect(self, J): """ Compute the intersection of self with ideal J. >>> from sympy.abc import x, y >>> from sympy import QQ >>> R = QQ.old_poly_ring(x, y) >>> R.ideal(x).intersect(R.ideal(y)) <x*y> """ self._check_ideal(J) return se...
[ "def", "intersect", "(", "self", ",", "J", ")", ":", "self", ".", "_check_ideal", "(", "J", ")", "return", "self", ".", "_intersect", "(", "J", ")" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/agca/ideals.py#L168-L179
ym2011/POC-EXP
206b22d3a6b2a172359678df33bbc5b2ad04b6c3
K8/Web-Exp/sqlmap/lib/core/target.py
python
_resumeHashDBValues
()
Resume stored data values from HashDB
Resume stored data values from HashDB
[ "Resume", "stored", "data", "values", "from", "HashDB" ]
def _resumeHashDBValues(): """ Resume stored data values from HashDB """ kb.absFilePaths = hashDBRetrieve(HASHDB_KEYS.KB_ABS_FILE_PATHS, True) or kb.absFilePaths kb.brute.tables = hashDBRetrieve(HASHDB_KEYS.KB_BRUTE_TABLES, True) or kb.brute.tables kb.brute.columns = hashDBRetrieve(HASHDB_KEYS....
[ "def", "_resumeHashDBValues", "(", ")", ":", "kb", ".", "absFilePaths", "=", "hashDBRetrieve", "(", "HASHDB_KEYS", ".", "KB_ABS_FILE_PATHS", ",", "True", ")", "or", "kb", ".", "absFilePaths", "kb", ".", "brute", ".", "tables", "=", "hashDBRetrieve", "(", "HA...
https://github.com/ym2011/POC-EXP/blob/206b22d3a6b2a172359678df33bbc5b2ad04b6c3/K8/Web-Exp/sqlmap/lib/core/target.py#L406-L438
MartinThoma/algorithms
6199cfa3446e1056c7b4d75ca6e306e9e56fd95b
ML/50-mlps/04-keras-1000-epochs/hasy_tools.py
python
_inner_class_distance
(data)
return (distances, mean_img)
Measure the eucliden distances of one class to the mean image.
Measure the eucliden distances of one class to the mean image.
[ "Measure", "the", "eucliden", "distances", "of", "one", "class", "to", "the", "mean", "image", "." ]
def _inner_class_distance(data): """Measure the eucliden distances of one class to the mean image.""" distances = [] mean_img = None for e1 in data: fname1 = os.path.join('.', e1['path']) img1 = scipy.ndimage.imread(fname1, flatten=False, mode='L') if mean_img is None: ...
[ "def", "_inner_class_distance", "(", "data", ")", ":", "distances", "=", "[", "]", "mean_img", "=", "None", "for", "e1", "in", "data", ":", "fname1", "=", "os", ".", "path", ".", "join", "(", "'.'", ",", "e1", "[", "'path'", "]", ")", "img1", "=", ...
https://github.com/MartinThoma/algorithms/blob/6199cfa3446e1056c7b4d75ca6e306e9e56fd95b/ML/50-mlps/04-keras-1000-epochs/hasy_tools.py#L812-L832
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/tencentcloud/cbs/v20170312/models.py
python
DetachDisksResponse.__init__
(self)
:param RequestId: 唯一请求ID,每次请求都会返回。定位问题时需要提供该次请求的RequestId。 :type RequestId: str
:param RequestId: 唯一请求ID,每次请求都会返回。定位问题时需要提供该次请求的RequestId。 :type RequestId: str
[ ":", "param", "RequestId", ":", "唯一请求ID,每次请求都会返回。定位问题时需要提供该次请求的RequestId。", ":", "type", "RequestId", ":", "str" ]
def __init__(self): """ :param RequestId: 唯一请求ID,每次请求都会返回。定位问题时需要提供该次请求的RequestId。 :type RequestId: str """ self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "RequestId", "=", "None" ]
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/tencentcloud/cbs/v20170312/models.py#L545-L550
Tuxemon/Tuxemon
ee80708090525391c1dfc43849a6348aca636b22
scripts/tuxepedia/extractor.py
python
TuxepediaWebExtractor.get_logger
(self)
return logging.getLogger(self.__class__.__name__)
Access a custom class logger.
Access a custom class logger.
[ "Access", "a", "custom", "class", "logger", "." ]
def get_logger(self): """Access a custom class logger.""" return logging.getLogger(self.__class__.__name__)
[ "def", "get_logger", "(", "self", ")", ":", "return", "logging", ".", "getLogger", "(", "self", ".", "__class__", ".", "__name__", ")" ]
https://github.com/Tuxemon/Tuxemon/blob/ee80708090525391c1dfc43849a6348aca636b22/scripts/tuxepedia/extractor.py#L38-L41
emmetio/livestyle-sublime-old
c42833c046e9b2f53ebce3df3aa926528f5a33b5
tornado/websocket.py
python
WebSocketProtocol.__init__
(self, handler)
[]
def __init__(self, handler): self.handler = handler self.request = handler.request self.stream = handler.stream self.client_terminated = False self.server_terminated = False
[ "def", "__init__", "(", "self", ",", "handler", ")", ":", "self", ".", "handler", "=", "handler", "self", ".", "request", "=", "handler", ".", "request", "self", ".", "stream", "=", "handler", ".", "stream", "self", ".", "client_terminated", "=", "False"...
https://github.com/emmetio/livestyle-sublime-old/blob/c42833c046e9b2f53ebce3df3aa926528f5a33b5/tornado/websocket.py#L285-L290
google/seq2seq
7f485894d412e8d81ce0e07977831865e44309ce
seq2seq/inference/inference.py
python
create_inference_graph
(model, input_pipeline, batch_size=32)
return model(features=features, labels=labels, params=None)
Creates a graph to perform inference. Args: task: An `InferenceTask` instance. input_pipeline: An instance of `InputPipeline` that defines how to read and parse data. batch_size: The batch size used for inference Returns: The return value of the model function, typically a tuple of (pred...
Creates a graph to perform inference.
[ "Creates", "a", "graph", "to", "perform", "inference", "." ]
def create_inference_graph(model, input_pipeline, batch_size=32): """Creates a graph to perform inference. Args: task: An `InferenceTask` instance. input_pipeline: An instance of `InputPipeline` that defines how to read and parse data. batch_size: The batch size used for inference Returns: ...
[ "def", "create_inference_graph", "(", "model", ",", "input_pipeline", ",", "batch_size", "=", "32", ")", ":", "# TODO: This doesn't really belong here.", "# How to get rid of this?", "if", "hasattr", "(", "model", ",", "\"use_beam_search\"", ")", ":", "if", "model", "...
https://github.com/google/seq2seq/blob/7f485894d412e8d81ce0e07977831865e44309ce/seq2seq/inference/inference.py#L26-L54
sklearn-theano/sklearn-theano
3eba566d8b624885b75759de47e52f903c015e40
sklearn_theano/externals/google/protobuf/internal/decoder.py
python
_SkipVarint
(buffer, pos, end)
return pos
Skip a varint value. Returns the new position.
Skip a varint value. Returns the new position.
[ "Skip", "a", "varint", "value", ".", "Returns", "the", "new", "position", "." ]
def _SkipVarint(buffer, pos, end): """Skip a varint value. Returns the new position.""" # Previously ord(buffer[pos]) raised IndexError when pos is out of range. # With this code, ord(b'') raises TypeError. Both are handled in # python_message.py to generate a 'Truncated message' error. while ord(buffer[pos...
[ "def", "_SkipVarint", "(", "buffer", ",", "pos", ",", "end", ")", ":", "# Previously ord(buffer[pos]) raised IndexError when pos is out of range.", "# With this code, ord(b'') raises TypeError. Both are handled in", "# python_message.py to generate a 'Truncated message' error.", "while", ...
https://github.com/sklearn-theano/sklearn-theano/blob/3eba566d8b624885b75759de47e52f903c015e40/sklearn_theano/externals/google/protobuf/internal/decoder.py#L767-L777
seantis/seantis-questionnaire
698c77b3d707635f50bcd86e7f1c94e94061b0f5
questionnaire/models.py
python
Question.get_type
(self)
return t
Get the type name, treating sameas and custom specially
Get the type name, treating sameas and custom specially
[ "Get", "the", "type", "name", "treating", "sameas", "and", "custom", "specially" ]
def get_type(self): "Get the type name, treating sameas and custom specially" t = self.sameas().type if t == 'custom': cd = self.sameas().getcheckdict() if 'type' not in cd: raise Exception( "When using custom types, you must have type=...
[ "def", "get_type", "(", "self", ")", ":", "t", "=", "self", ".", "sameas", "(", ")", ".", "type", "if", "t", "==", "'custom'", ":", "cd", "=", "self", ".", "sameas", "(", ")", ".", "getcheckdict", "(", ")", "if", "'type'", "not", "in", "cd", ":...
https://github.com/seantis/seantis-questionnaire/blob/698c77b3d707635f50bcd86e7f1c94e94061b0f5/questionnaire/models.py#L524-L535
kevoreilly/CAPEv2
6cf79c33264624b3604d4cd432cde2a6b4536de6
lib/cuckoo/common/objects.py
python
File.get_md5
(self)
return self._md5
Get MD5. @return: MD5.
Get MD5.
[ "Get", "MD5", "." ]
def get_md5(self): """Get MD5. @return: MD5. """ if not self._md5: self.calc_hashes() return self._md5
[ "def", "get_md5", "(", "self", ")", ":", "if", "not", "self", ".", "_md5", ":", "self", ".", "calc_hashes", "(", ")", "return", "self", ".", "_md5" ]
https://github.com/kevoreilly/CAPEv2/blob/6cf79c33264624b3604d4cd432cde2a6b4536de6/lib/cuckoo/common/objects.py#L341-L347
hyperledger/aries-cloudagent-python
2f36776e99f6053ae92eed8123b5b1b2e891c02a
aries_cloudagent/ledger/merkel_validation/hasher.py
python
TreeHasher.hash_leaf
(self, data)
return hasher.digest()
Return leaf node hash.
Return leaf node hash.
[ "Return", "leaf", "node", "hash", "." ]
def hash_leaf(self, data): """Return leaf node hash.""" hasher = self.hashfunc() hasher.update(b"\x00" + data) return hasher.digest()
[ "def", "hash_leaf", "(", "self", ",", "data", ")", ":", "hasher", "=", "self", ".", "hashfunc", "(", ")", "hasher", ".", "update", "(", "b\"\\x00\"", "+", "data", ")", "return", "hasher", ".", "digest", "(", ")" ]
https://github.com/hyperledger/aries-cloudagent-python/blob/2f36776e99f6053ae92eed8123b5b1b2e891c02a/aries_cloudagent/ledger/merkel_validation/hasher.py#L14-L18
apache/libcloud
90971e17bfd7b6bb97b2489986472c531cc8e140
libcloud/container/drivers/lxd.py
python
LXDContainerDriver._to_image
(self, metadata)
return ContainerImage( id=fingerprint, name=name, path=None, version=version, driver=self, extra=extra, )
Returns a container image from the given metadata :param metadata: :type metadata: ``dict`` :rtype: :class:`.ContainerImage`
Returns a container image from the given metadata
[ "Returns", "a", "container", "image", "from", "the", "given", "metadata" ]
def _to_image(self, metadata): """ Returns a container image from the given metadata :param metadata: :type metadata: ``dict`` :rtype: :class:`.ContainerImage` """ fingerprint = metadata.get("fingerprint") aliases = metadata.get("aliases", []) ...
[ "def", "_to_image", "(", "self", ",", "metadata", ")", ":", "fingerprint", "=", "metadata", ".", "get", "(", "\"fingerprint\"", ")", "aliases", "=", "metadata", ".", "get", "(", "\"aliases\"", ",", "[", "]", ")", "if", "aliases", ":", "name", "=", "met...
https://github.com/apache/libcloud/blob/90971e17bfd7b6bb97b2489986472c531cc8e140/libcloud/container/drivers/lxd.py#L1764-L1791
Esri/ArcREST
ab240fde2b0200f61d4a5f6df033516e53f2f416
src/arcrest/ags/_gpobjects.py
python
GPString.value
(self, value)
gets/sets the object as a dictionary
gets/sets the object as a dictionary
[ "gets", "/", "sets", "the", "object", "as", "a", "dictionary" ]
def value(self, value): """gets/sets the object as a dictionary""" #if isinstance(value, str): self._value = value
[ "def", "value", "(", "self", ",", "value", ")", ":", "#if isinstance(value, str):", "self", ".", "_value", "=", "value" ]
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/ags/_gpobjects.py#L601-L604
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/cls/v20201016/models.py
python
CreateExportResponse.__init__
(self)
r""" :param ExportId: 日志导出ID。 :type ExportId: str :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
r""" :param ExportId: 日志导出ID。 :type ExportId: str :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
[ "r", ":", "param", "ExportId", ":", "日志导出ID。", ":", "type", "ExportId", ":", "str", ":", "param", "RequestId", ":", "唯一请求", "ID,每次请求都会返回。定位问题时需要提供该次请求的", "RequestId。", ":", "type", "RequestId", ":", "str" ]
def __init__(self): r""" :param ExportId: 日志导出ID。 :type ExportId: str :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.ExportId = None self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "ExportId", "=", "None", "self", ".", "RequestId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cls/v20201016/models.py#L975-L983
vlachoudis/bCNC
67126b4894dabf6579baf47af8d0f9b7de35e6e3
bCNC/plugins/function_plot.py
python
Tool.execute
(self, app)
[]
def execute(self, app): name = self['name'] if not name or name == 'default': name = 'Function' # Initialize blocks that will contain our gCode blocks = [] block = Block(name) #Variable definitions formula = self['form'] res = self['res'] #...
[ "def", "execute", "(", "self", ",", "app", ")", ":", "name", "=", "self", "[", "'name'", "]", "if", "not", "name", "or", "name", "==", "'default'", ":", "name", "=", "'Function'", "# Initialize blocks that will contain our gCode", "blocks", "=", "[", "]", ...
https://github.com/vlachoudis/bCNC/blob/67126b4894dabf6579baf47af8d0f9b7de35e6e3/bCNC/plugins/function_plot.py#L52-L230
pypr/pysph
9cb9a859934939307c65a25cbf73e4ecc83fea4a
pysph/tools/pysph_to_vtk.py
python
write_vtk
(data, filename, scalars=None, vectors={'V':('u','v','w')}, tensors={}, coords=('x','y','z'), dims=None, **kwargs)
write data in to vtk file Parameters ---------- data : dict mapping of variable name to their numpy array filename : str the file to write to (can be any recognized vtk extension) if extension is missing .vts extension is appended scalars : list list of arrays to wri...
write data in to vtk file
[ "write", "data", "in", "to", "vtk", "file" ]
def write_vtk(data, filename, scalars=None, vectors={'V':('u','v','w')}, tensors={}, coords=('x','y','z'), dims=None, **kwargs): ''' write data in to vtk file Parameters ---------- data : dict mapping of variable name to their numpy array filename : str the file to wri...
[ "def", "write_vtk", "(", "data", ",", "filename", ",", "scalars", "=", "None", ",", "vectors", "=", "{", "'V'", ":", "(", "'u'", ",", "'v'", ",", "'w'", ")", "}", ",", "tensors", "=", "{", "}", ",", "coords", "=", "(", "'x'", ",", "'y'", ",", ...
https://github.com/pypr/pysph/blob/9cb9a859934939307c65a25cbf73e4ecc83fea4a/pysph/tools/pysph_to_vtk.py#L10-L68
materialsproject/pymatgen
8128f3062a334a2edd240e4062b5b9bdd1ae6f58
pymatgen/analysis/chemenv/connectivity/environment_nodes.py
python
AbstractEnvironmentNode.everything_equal
(self, other)
return self.__eq__(other) and self.central_site == other.central_site
Checks equality with respect to another AbstractEnvironmentNode using the index of the central site as well as the central site itself.
Checks equality with respect to another AbstractEnvironmentNode using the index of the central site as well as the central site itself.
[ "Checks", "equality", "with", "respect", "to", "another", "AbstractEnvironmentNode", "using", "the", "index", "of", "the", "central", "site", "as", "well", "as", "the", "central", "site", "itself", "." ]
def everything_equal(self, other): """Checks equality with respect to another AbstractEnvironmentNode using the index of the central site as well as the central site itself.""" return self.__eq__(other) and self.central_site == other.central_site
[ "def", "everything_equal", "(", "self", ",", "other", ")", ":", "return", "self", ".", "__eq__", "(", "other", ")", "and", "self", ".", "central_site", "==", "other", ".", "central_site" ]
https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/analysis/chemenv/connectivity/environment_nodes.py#L62-L65
orestis/pysmell
14382f377f7759a1b6505120990898dd51f175e6
pysmell/codefinder.py
python
ModuleDict.__len__
(self)
return len(self.keys())
[]
def __len__(self): return len(self.keys())
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "keys", "(", ")", ")" ]
https://github.com/orestis/pysmell/blob/14382f377f7759a1b6505120990898dd51f175e6/pysmell/codefinder.py#L88-L89
WGLab/InterVar
4801682d37982bb3e99b50392790878a568b42cd
Intervar.py
python
check_PP3
(line,Funcanno_flgs,Allels_flgs)
return(PP3)
Multiple lines of computational evidence support a deleterious effect on the gene or gene product (conservation, evolutionary, splicing impact, etc.) sfit for conservation, GERP++_RS for evolutionary, splicing impact from dbNSFP
Multiple lines of computational evidence support a deleterious effect on the gene or gene product (conservation, evolutionary, splicing impact, etc.) sfit for conservation, GERP++_RS for evolutionary, splicing impact from dbNSFP
[ "Multiple", "lines", "of", "computational", "evidence", "support", "a", "deleterious", "effect", "on", "the", "gene", "or", "gene", "product", "(", "conservation", "evolutionary", "splicing", "impact", "etc", ".", ")", "sfit", "for", "conservation", "GERP", "++"...
def check_PP3(line,Funcanno_flgs,Allels_flgs): ''' Multiple lines of computational evidence support a deleterious effect on the gene or gene product (conservation, evolutionary, splicing impact, etc.) sfit for conservation, GERP++_RS for evolutionary, splicing impact from dbNSFP ''' PP3=0 PP...
[ "def", "check_PP3", "(", "line", ",", "Funcanno_flgs", ",", "Allels_flgs", ")", ":", "PP3", "=", "0", "PP3_t1", "=", "0", "PP3_t2", "=", "0", "PP3_t3", "=", "0", "sift_cutoff", "=", "0.05", "#SIFT_score,SIFT_pred, The smaller the score the more likely the SNP has da...
https://github.com/WGLab/InterVar/blob/4801682d37982bb3e99b50392790878a568b42cd/Intervar.py#L1257-L1307
ValvePython/steam
7aef9d2df57c2195f35bd85013e1b5ccb04624a5
steam/guard.py
python
get_time_offset
()
return int(resp.get('response', {}).get('server_time', ts)) - ts
Get time offset from steam server time via WebAPI :return: time offset (``None`` when Steam WebAPI fails to respond) :rtype: :class:`int`, :class:`None`
Get time offset from steam server time via WebAPI
[ "Get", "time", "offset", "from", "steam", "server", "time", "via", "WebAPI" ]
def get_time_offset(): """Get time offset from steam server time via WebAPI :return: time offset (``None`` when Steam WebAPI fails to respond) :rtype: :class:`int`, :class:`None` """ try: resp = webapi.post('ITwoFactorService', 'QueryTime', 1, params={'http_timeout': 10}) except: ...
[ "def", "get_time_offset", "(", ")", ":", "try", ":", "resp", "=", "webapi", ".", "post", "(", "'ITwoFactorService'", ",", "'QueryTime'", ",", "1", ",", "params", "=", "{", "'http_timeout'", ":", "10", "}", ")", "except", ":", "return", "None", "ts", "=...
https://github.com/ValvePython/steam/blob/7aef9d2df57c2195f35bd85013e1b5ccb04624a5/steam/guard.py#L548-L560
PUNCH-Cyber/stoq
8bfc78b226ee6500eb78e1bdf361fc83bc5005b7
stoq/core.py
python
Stoq.reconstruct_all_subresponses
( self, stoq_response: StoqResponse )
Generate a new `StoqResponse` object for each `Payload` within the `Request`
[]
async def reconstruct_all_subresponses( self, stoq_response: StoqResponse ) -> AsyncGenerator[StoqResponse, None]: """ Generate a new `StoqResponse` object for each `Payload` within the `Request` """ for i, new_root_payload_result in enumerate(stoq_response.results...
[ "async", "def", "reconstruct_all_subresponses", "(", "self", ",", "stoq_response", ":", "StoqResponse", ")", "->", "AsyncGenerator", "[", "StoqResponse", ",", "None", "]", ":", "for", "i", ",", "new_root_payload_result", "in", "enumerate", "(", "stoq_response", "....
https://github.com/PUNCH-Cyber/stoq/blob/8bfc78b226ee6500eb78e1bdf361fc83bc5005b7/stoq/core.py#L667-L705
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/models/mbart/modeling_tf_mbart.py
python
TFMBartAttention.call
( self, hidden_states: tf.Tensor, key_value_states: Optional[tf.Tensor] = None, past_key_value: Optional[Tuple[Tuple[tf.Tensor]]] = None, attention_mask: Optional[tf.Tensor] = None, layer_head_mask: Optional[tf.Tensor] = None, training=False, )
return attn_output, attn_weights, past_key_value
Input shape: Batch x Time x Channel
Input shape: Batch x Time x Channel
[ "Input", "shape", ":", "Batch", "x", "Time", "x", "Channel" ]
def call( self, hidden_states: tf.Tensor, key_value_states: Optional[tf.Tensor] = None, past_key_value: Optional[Tuple[Tuple[tf.Tensor]]] = None, attention_mask: Optional[tf.Tensor] = None, layer_head_mask: Optional[tf.Tensor] = None, training=False, ) -> Tupl...
[ "def", "call", "(", "self", ",", "hidden_states", ":", "tf", ".", "Tensor", ",", "key_value_states", ":", "Optional", "[", "tf", ".", "Tensor", "]", "=", "None", ",", "past_key_value", ":", "Optional", "[", "Tuple", "[", "Tuple", "[", "tf", ".", "Tenso...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/mbart/modeling_tf_mbart.py#L164-L280
fake-name/ReadableWebProxy
ed5c7abe38706acc2684a1e6cd80242a03c5f010
WebMirror/management/rss_parser_funcs/feed_parse_extractLittlebambooHomeBlog.py
python
extractLittlebambooHomeBlog
(item)
return False
Parser for 'littlebamboo.home.blog'
Parser for 'littlebamboo.home.blog'
[ "Parser", "for", "littlebamboo", ".", "home", ".", "blog" ]
def extractLittlebambooHomeBlog(item): ''' Parser for 'littlebamboo.home.blog' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('FW', 'Fortunate Wife', 'translated'), ...
[ "def", "extractLittlebambooHomeBlog", "(", "item", ")", ":", "vol", ",", "chp", ",", "frag", ",", "postfix", "=", "extractVolChapterFragmentPostfix", "(", "item", "[", "'title'", "]", ")", "if", "not", "(", "chp", "or", "vol", ")", "or", "\"preview\"", "in...
https://github.com/fake-name/ReadableWebProxy/blob/ed5c7abe38706acc2684a1e6cd80242a03c5f010/WebMirror/management/rss_parser_funcs/feed_parse_extractLittlebambooHomeBlog.py#L1-L21
kalliope-project/kalliope
7b2bb4671c8fbfa0ea9f768c84994fe75da974eb
kalliope/core/Utils/Utils.py
python
Utils.print_yaml_nicely
(to_print)
return line.encode('utf-8')
Used for debug :param to_print: Dict to print nicely :return:
Used for debug :param to_print: Dict to print nicely :return:
[ "Used", "for", "debug", ":", "param", "to_print", ":", "Dict", "to", "print", "nicely", ":", "return", ":" ]
def print_yaml_nicely(to_print): """ Used for debug :param to_print: Dict to print nicely :return: """ import json line = json.dumps(to_print, indent=2) return line.encode('utf-8')
[ "def", "print_yaml_nicely", "(", "to_print", ")", ":", "import", "json", "line", "=", "json", ".", "dumps", "(", "to_print", ",", "indent", "=", "2", ")", "return", "line", ".", "encode", "(", "'utf-8'", ")" ]
https://github.com/kalliope-project/kalliope/blob/7b2bb4671c8fbfa0ea9f768c84994fe75da974eb/kalliope/core/Utils/Utils.py#L85-L93
Pylons/pyramid
0b24ac16cc04746b25cf460f1497c157f6d3d6f4
src/pyramid/static.py
python
ManifestCacheBuster.manifest
(self)
return self._manifest
The current manifest dictionary.
The current manifest dictionary.
[ "The", "current", "manifest", "dictionary", "." ]
def manifest(self): """ The current manifest dictionary.""" if self.reload: if not self.exists(self.manifest_path): return {} mtime = self.getmtime(self.manifest_path) if self._mtime is None or mtime > self._mtime: self._manifest = self...
[ "def", "manifest", "(", "self", ")", ":", "if", "self", ".", "reload", ":", "if", "not", "self", ".", "exists", "(", "self", ".", "manifest_path", ")", ":", "return", "{", "}", "mtime", "=", "self", ".", "getmtime", "(", "self", ".", "manifest_path",...
https://github.com/Pylons/pyramid/blob/0b24ac16cc04746b25cf460f1497c157f6d3d6f4/src/pyramid/static.py#L410-L419
deanishe/alfred-repos
7f7b3999331808cb58fc33e8793f6be692ed9fe5
src/workflow/web.py
python
Response.raise_for_status
(self)
return
Raise stored error if one occurred. error will be instance of :class:`urllib2.HTTPError`
Raise stored error if one occurred.
[ "Raise", "stored", "error", "if", "one", "occurred", "." ]
def raise_for_status(self): """Raise stored error if one occurred. error will be instance of :class:`urllib2.HTTPError` """ if self.error is not None: raise self.error return
[ "def", "raise_for_status", "(", "self", ")", ":", "if", "self", ".", "error", "is", "not", "None", ":", "raise", "self", ".", "error", "return" ]
https://github.com/deanishe/alfred-repos/blob/7f7b3999331808cb58fc33e8793f6be692ed9fe5/src/workflow/web.py#L423-L430
DamnWidget/anaconda
a9998fb362320f907d5ccbc6fcf5b62baca677c0
anaconda_lib/autopep/autopep8_lib/autopep8.py
python
extract_code_from_function
(function)
return code
Return code handled by function.
Return code handled by function.
[ "Return", "code", "handled", "by", "function", "." ]
def extract_code_from_function(function): """Return code handled by function.""" if not function.__name__.startswith('fix_'): return None code = re.sub('^fix_', '', function.__name__) if not code: return None try: int(code[1:]) except ValueError: return None ...
[ "def", "extract_code_from_function", "(", "function", ")", ":", "if", "not", "function", ".", "__name__", ".", "startswith", "(", "'fix_'", ")", ":", "return", "None", "code", "=", "re", ".", "sub", "(", "'^fix_'", ",", "''", ",", "function", ".", "__nam...
https://github.com/DamnWidget/anaconda/blob/a9998fb362320f907d5ccbc6fcf5b62baca677c0/anaconda_lib/autopep/autopep8_lib/autopep8.py#L3245-L3259
Azure/WALinuxAgent
c964d70282de17ab439be21d7ab32373c3965f59
azurelinuxagent/common/osutil/ubuntu.py
python
UbuntuOSUtil.restart_if
(self, ifname, retries=3, wait=5)
Restart an interface by bouncing the link. systemd-networkd observes this event, and forces a renew of DHCP.
Restart an interface by bouncing the link. systemd-networkd observes this event, and forces a renew of DHCP.
[ "Restart", "an", "interface", "by", "bouncing", "the", "link", ".", "systemd", "-", "networkd", "observes", "this", "event", "and", "forces", "a", "renew", "of", "DHCP", "." ]
def restart_if(self, ifname, retries=3, wait=5): """ Restart an interface by bouncing the link. systemd-networkd observes this event, and forces a renew of DHCP. """ retry_limit = retries+1 for attempt in range(1, retry_limit): return_code = shellutil.run("ip ...
[ "def", "restart_if", "(", "self", ",", "ifname", ",", "retries", "=", "3", ",", "wait", "=", "5", ")", ":", "retry_limit", "=", "retries", "+", "1", "for", "attempt", "in", "range", "(", "1", ",", "retry_limit", ")", ":", "return_code", "=", "shellut...
https://github.com/Azure/WALinuxAgent/blob/c964d70282de17ab439be21d7ab32373c3965f59/azurelinuxagent/common/osutil/ubuntu.py#L140-L155
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/concurrent/futures/process.py
python
_queue_management_worker
(executor_reference, processes, pending_work_items, work_ids_queue, call_queue, result_queue)
Manages the communication between this process and the worker processes. This function is run in a local thread. Args: executor_reference: A weakref.ref to the ProcessPoolExecutor that owns this thread. Used to determine if the ProcessPoolExecutor has been garbage collected and...
Manages the communication between this process and the worker processes.
[ "Manages", "the", "communication", "between", "this", "process", "and", "the", "worker", "processes", "." ]
def _queue_management_worker(executor_reference, processes, pending_work_items, work_ids_queue, call_queue, result_queue): """Manages the communication between this proces...
[ "def", "_queue_management_worker", "(", "executor_reference", ",", "processes", ",", "pending_work_items", ",", "work_ids_queue", ",", "call_queue", ",", "result_queue", ")", ":", "executor", "=", "None", "def", "shutting_down", "(", ")", ":", "return", "_shutdown",...
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/concurrent/futures/process.py#L199-L312
omni-us/squeezedet-keras
cb3555041cbb175221a42f83677023dbfcbdd00d
main/utils/utils.py
python
iou
(box1, box2)
return 0
Compute the Intersection-Over-Union of two given boxes. Args: box1: array of 4 elements [cx, cy, width, height]. box2: same as above Returns: iou: a float number in range [0, 1]. iou of the two boxes.
Compute the Intersection-Over-Union of two given boxes.
[ "Compute", "the", "Intersection", "-", "Over", "-", "Union", "of", "two", "given", "boxes", "." ]
def iou(box1, box2): """Compute the Intersection-Over-Union of two given boxes. Args: box1: array of 4 elements [cx, cy, width, height]. box2: same as above Returns: iou: a float number in range [0, 1]. iou of the two boxes. """ lr = min(box1[0]+0.5*box1[2], box2[0]+0.5*box2[2]) - \ max(bo...
[ "def", "iou", "(", "box1", ",", "box2", ")", ":", "lr", "=", "min", "(", "box1", "[", "0", "]", "+", "0.5", "*", "box1", "[", "2", "]", ",", "box2", "[", "0", "]", "+", "0.5", "*", "box2", "[", "2", "]", ")", "-", "max", "(", "box1", "[...
https://github.com/omni-us/squeezedet-keras/blob/cb3555041cbb175221a42f83677023dbfcbdd00d/main/utils/utils.py#L18-L39
ipython/ipyparallel
d35d4fb9501da5b3280b11e83ed633a95f17be1d
ipyparallel/client/asyncresult.py
python
AsyncResult._collect_exceptions
(self, results)
Wrap Exceptions in a CompositeError if self._return_exceptions is True, this is a no-op
Wrap Exceptions in a CompositeError
[ "Wrap", "Exceptions", "in", "a", "CompositeError" ]
def _collect_exceptions(self, results): """Wrap Exceptions in a CompositeError if self._return_exceptions is True, this is a no-op """ if self._return_exceptions: return results else: return error.collect_exceptions(results, self._fname)
[ "def", "_collect_exceptions", "(", "self", ",", "results", ")", ":", "if", "self", ".", "_return_exceptions", ":", "return", "results", "else", ":", "return", "error", ".", "collect_exceptions", "(", "results", ",", "self", ".", "_fname", ")" ]
https://github.com/ipython/ipyparallel/blob/d35d4fb9501da5b3280b11e83ed633a95f17be1d/ipyparallel/client/asyncresult.py#L548-L556
spack/spack
675210bd8bd1c5d32ad1cc83d898fb43b569ed74
lib/spack/spack/fetch_strategy.py
python
FetchStrategy.archive
(self, destination)
Create an archive of the downloaded data for a mirror. For downloaded files, this should preserve the checksum of the original file. For repositories, it should just create an expandable tarball out of the downloaded repository.
Create an archive of the downloaded data for a mirror.
[ "Create", "an", "archive", "of", "the", "downloaded", "data", "for", "a", "mirror", "." ]
def archive(self, destination): """Create an archive of the downloaded data for a mirror. For downloaded files, this should preserve the checksum of the original file. For repositories, it should just create an expandable tarball out of the downloaded repository. """
[ "def", "archive", "(", "self", ",", "destination", ")", ":" ]
https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/lib/spack/spack/fetch_strategy.py#L139-L145
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/userreports/custom/data_source.py
python
ConfigurableReportCustomDataSource.helper
(self)
[]
def helper(self): if self.config.backend_id == 'SQL': return ConfigurableReportCustomSQLDataSourceHelper(self)
[ "def", "helper", "(", "self", ")", ":", "if", "self", ".", "config", ".", "backend_id", "==", "'SQL'", ":", "return", "ConfigurableReportCustomSQLDataSourceHelper", "(", "self", ")" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/userreports/custom/data_source.py#L22-L24
robotlearn/pyrobolearn
9cd7c060723fda7d2779fa255ac998c2c82b8436
pyrobolearn/policies/policy.py
python
Policy.inner_predict
(self, state_data, deterministic=True, to_numpy=False, return_logits=True, set_output_data=False)
return self.model.predict(state_data, to_numpy=to_numpy)
Inner prediction step. Args: state_data ((list of) torch.Tensor, (list of) np.array): state data. deterministic (bool): True by default. It can only be set to False, if the policy is stochastic. to_numpy (bool): If True, it will convert the data (torch.Tensors) to numpy arra...
Inner prediction step.
[ "Inner", "prediction", "step", "." ]
def inner_predict(self, state_data, deterministic=True, to_numpy=False, return_logits=True, set_output_data=False): """Inner prediction step. Args: state_data ((list of) torch.Tensor, (list of) np.array): state data. deterministic (bool): True by default. It can only be set to F...
[ "def", "inner_predict", "(", "self", ",", "state_data", ",", "deterministic", "=", "True", ",", "to_numpy", "=", "False", ",", "return_logits", "=", "True", ",", "set_output_data", "=", "False", ")", ":", "if", "isinstance", "(", "self", ".", "model", ",",...
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/policies/policy.py#L445-L463
ronf/asyncssh
ee1714c598d8c2ea6f5484e465443f38b68714aa
asyncssh/kex_dh.py
python
_KexDHBase._parse_client_key
(self, packet: SSHPacket)
Parse a DH client key
Parse a DH client key
[ "Parse", "a", "DH", "client", "key" ]
def _parse_client_key(self, packet: SSHPacket) -> None: """Parse a DH client key""" if not self._p: raise ProtocolError('Kex DH p not specified') self._e = packet.get_mpint()
[ "def", "_parse_client_key", "(", "self", ",", "packet", ":", "SSHPacket", ")", "->", "None", ":", "if", "not", "self", ".", "_p", ":", "raise", "ProtocolError", "(", "'Kex DH p not specified'", ")", "self", ".", "_e", "=", "packet", ".", "get_mpint", "(", ...
https://github.com/ronf/asyncssh/blob/ee1714c598d8c2ea6f5484e465443f38b68714aa/asyncssh/kex_dh.py#L158-L164
EdinburghNLP/nematus
d55074a2e342a33a4d5b0288cbad6269bd47271d
nematus/metrics/beer.py
python
BeerScorer.set_reference
(self, reference_tokens)
Construct a BeerReference from a sequence of tokens and make it the reference against which the scorer evaluates hypotheses. This can be done any time.
Construct a BeerReference from a sequence of tokens and make it the reference against which the scorer evaluates hypotheses. This can be done any time.
[ "Construct", "a", "BeerReference", "from", "a", "sequence", "of", "tokens", "and", "make", "it", "the", "reference", "against", "which", "the", "scorer", "evaluates", "hypotheses", ".", "This", "can", "be", "done", "any", "time", "." ]
def set_reference(self, reference_tokens): """ Construct a BeerReference from a sequence of tokens and make it the reference against which the scorer evaluates hypotheses. This can be done any time. """ self.lock.acquire() self._reference = BeerReference(reference_tokens,...
[ "def", "set_reference", "(", "self", ",", "reference_tokens", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "self", ".", "_reference", "=", "BeerReference", "(", "reference_tokens", ",", "self", ")", "self", ".", "lock", ".", "release", "(", "...
https://github.com/EdinburghNLP/nematus/blob/d55074a2e342a33a4d5b0288cbad6269bd47271d/nematus/metrics/beer.py#L44-L51
FutunnOpen/py-futu-api
b8f9fb1f26f35f99630ca47863f5595b6e635533
futu/trade/open_trade_context.py
python
OpenTradeContextBase.on_api_socket_reconnected
(self)
return ret, msg
for API socket reconnected
for API socket reconnected
[ "for", "API", "socket", "reconnected" ]
def on_api_socket_reconnected(self): """for API socket reconnected""" self.__is_acc_sub_push = False self.__last_acc_list = [] ret, msg = RET_OK, '' # auto unlock trade if self._ctx_unlock is not None: password, password_md5 = self._ctx_unlock ret...
[ "def", "on_api_socket_reconnected", "(", "self", ")", ":", "self", ".", "__is_acc_sub_push", "=", "False", "self", ".", "__last_acc_list", "=", "[", "]", "ret", ",", "msg", "=", "RET_OK", ",", "''", "# auto unlock trade", "if", "self", ".", "_ctx_unlock", "i...
https://github.com/FutunnOpen/py-futu-api/blob/b8f9fb1f26f35f99630ca47863f5595b6e635533/futu/trade/open_trade_context.py#L34-L52
sshaoshuai/PointRCNN
1d0dee91262b970f460135252049112d80259ca0
lib/utils/loss_utils.py
python
SigmoidFocalClassificationLoss.__init__
(self, gamma=2.0, alpha=0.25)
Constructor. Args: gamma: exponent of the modulating factor (1 - p_t) ^ gamma. alpha: optional alpha weighting factor to balance positives vs negatives. all_zero_negative: bool. if True, will treat all zero as background. else, will treat first label as background...
Constructor. Args: gamma: exponent of the modulating factor (1 - p_t) ^ gamma. alpha: optional alpha weighting factor to balance positives vs negatives. all_zero_negative: bool. if True, will treat all zero as background. else, will treat first label as background...
[ "Constructor", ".", "Args", ":", "gamma", ":", "exponent", "of", "the", "modulating", "factor", "(", "1", "-", "p_t", ")", "^", "gamma", ".", "alpha", ":", "optional", "alpha", "weighting", "factor", "to", "balance", "positives", "vs", "negatives", ".", ...
def __init__(self, gamma=2.0, alpha=0.25): """Constructor. Args: gamma: exponent of the modulating factor (1 - p_t) ^ gamma. alpha: optional alpha weighting factor to balance positives vs negatives. all_zero_negative: bool. if True, will treat all zero as background. ...
[ "def", "__init__", "(", "self", ",", "gamma", "=", "2.0", ",", "alpha", "=", "0.25", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "_alpha", "=", "alpha", "self", ".", "_gamma", "=", "gamma" ]
https://github.com/sshaoshuai/PointRCNN/blob/1d0dee91262b970f460135252049112d80259ca0/lib/utils/loss_utils.py#L29-L39
slinderman/pyhawkes
0df433a40c5e6d8c1dcdb98ffc88fe3a403ac223
pyhawkes/internals/impulses.py
python
SBMDirichletImpulseResponses.expected_log_g
(self)
return E_lng
Compute the expected log impulse response vector wrt c and mf_gamma :return:
Compute the expected log impulse response vector wrt c and mf_gamma :return:
[ "Compute", "the", "expected", "log", "impulse", "response", "vector", "wrt", "c", "and", "mf_gamma", ":", "return", ":" ]
def expected_log_g(self): """ Compute the expected log impulse response vector wrt c and mf_gamma :return: """ raise NotImplementedError() E_lng = np.zeros_like(self.mf_gamma) # \psi(\sum_{b} \gamma_b) trm2 = psi(self.mf_gamma.sum(axis=2)) for b i...
[ "def", "expected_log_g", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")", "E_lng", "=", "np", ".", "zeros_like", "(", "self", ".", "mf_gamma", ")", "# \\psi(\\sum_{b} \\gamma_b)", "trm2", "=", "psi", "(", "self", ".", "mf_gamma", ".", "sum", ...
https://github.com/slinderman/pyhawkes/blob/0df433a40c5e6d8c1dcdb98ffc88fe3a403ac223/pyhawkes/internals/impulses.py#L267-L280
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
lib-python/3.5.1/http/cookiejar.py
python
CookieJar._normalized_cookie_tuples
(self, attrs_set)
return cookie_tuples
Return list of tuples containing normalised cookie information. attrs_set is the list of lists of key,value pairs extracted from the Set-Cookie or Set-Cookie2 headers. Tuples are name, value, standard, rest, where name and value are the cookie name and value, standard is a dictionary c...
Return list of tuples containing normalised cookie information.
[ "Return", "list", "of", "tuples", "containing", "normalised", "cookie", "information", "." ]
def _normalized_cookie_tuples(self, attrs_set): """Return list of tuples containing normalised cookie information. attrs_set is the list of lists of key,value pairs extracted from the Set-Cookie or Set-Cookie2 headers. Tuples are name, value, standard, rest, where name and value are th...
[ "def", "_normalized_cookie_tuples", "(", "self", ",", "attrs_set", ")", ":", "cookie_tuples", "=", "[", "]", "boolean_attrs", "=", "\"discard\"", ",", "\"secure\"", "value_attrs", "=", "(", "\"version\"", ",", "\"expires\"", ",", "\"max-age\"", ",", "\"domain\"", ...
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/http/cookiejar.py#L1364-L1459
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/converters/usm3d/usm3d_reader.py
python
read_flo
(flo_filename, n=None, node_ids=None)
return node_id, loads
reads a *.flo file
reads a *.flo file
[ "reads", "a", "*", ".", "flo", "file" ]
def read_flo(flo_filename, n=None, node_ids=None): """reads a *.flo file""" result_names = ['Mach', 'U', 'V', 'W', 'T', 'rho', 'rhoU', 'rhoV', 'rhoW', 'p', 'Cp'] is_sparse = None if n is None: assert node_ids is not None, node_ids assert len(node_ids) > 0, node_ids n = len(node_...
[ "def", "read_flo", "(", "flo_filename", ",", "n", "=", "None", ",", "node_ids", "=", "None", ")", ":", "result_names", "=", "[", "'Mach'", ",", "'U'", ",", "'V'", ",", "'W'", ",", "'T'", ",", "'rho'", ",", "'rhoU'", ",", "'rhoV'", ",", "'rhoW'", ",...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/converters/usm3d/usm3d_reader.py#L517-L748
HarshUpadhyay/TesseractTrainer
c50a3663af579ae0d847e770c382466c57d3e7d6
tesseract_trainer/__init__.py
python
TesseractTrainer._generate_boxfile
(self)
Generate a multipage tif, filled with the training text and generate a boxfile from the coordinates of the characters inside it
Generate a multipage tif, filled with the training text and generate a boxfile from the coordinates of the characters inside it
[ "Generate", "a", "multipage", "tif", "filled", "with", "the", "training", "text", "and", "generate", "a", "boxfile", "from", "the", "coordinates", "of", "the", "characters", "inside", "it" ]
def _generate_boxfile(self): """ Generate a multipage tif, filled with the training text and generate a boxfile from the coordinates of the characters inside it """ mp = MultiPageTif(self.training_text, 3600, 3600, 50,50, self.font_name, self.font_path, self.font_size, se...
[ "def", "_generate_boxfile", "(", "self", ")", ":", "mp", "=", "MultiPageTif", "(", "self", ".", "training_text", ",", "3600", ",", "3600", ",", "50", ",", "50", ",", "self", ".", "font_name", ",", "self", ".", "font_path", ",", "self", ".", "font_size"...
https://github.com/HarshUpadhyay/TesseractTrainer/blob/c50a3663af579ae0d847e770c382466c57d3e7d6/tesseract_trainer/__init__.py#L90-L97
returntocorp/bento
05b365da71b65170d41fe92a702480ab76c1d17c
bento/error.py
python
NoIgnoreFileException.__init__
(self, context: BaseContext)
[]
def __init__(self, context: BaseContext) -> None: super().__init__() self.msg = f"No ignore file found (looked in {context.ignore_file_path}). Please run `bento init`."
[ "def", "__init__", "(", "self", ",", "context", ":", "BaseContext", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "msg", "=", "f\"No ignore file found (looked in {context.ignore_file_path}). Please run `bento init`.\"" ]
https://github.com/returntocorp/bento/blob/05b365da71b65170d41fe92a702480ab76c1d17c/bento/error.py#L39-L41
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/packages/site-packages/path.py
python
Path.write_text
(self, text, encoding=None, errors='strict', linesep=os.linesep, append=False)
r""" Write the given text to this file. The default behavior is to overwrite any existing file; to append instead, use the `append=True` keyword argument. There are two differences between :meth:`write_text` and :meth:`write_bytes`: newline handling and Unicode handling. See be...
r""" Write the given text to this file.
[ "r", "Write", "the", "given", "text", "to", "this", "file", "." ]
def write_text(self, text, encoding=None, errors='strict', linesep=os.linesep, append=False): r""" Write the given text to this file. The default behavior is to overwrite any existing file; to append instead, use the `append=True` keyword argument. There are two diff...
[ "def", "write_text", "(", "self", ",", "text", ",", "encoding", "=", "None", ",", "errors", "=", "'strict'", ",", "linesep", "=", "os", ".", "linesep", ",", "append", "=", "False", ")", ":", "if", "isinstance", "(", "text", ",", "text_type", ")", ":"...
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/path.py#L792-L864
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pkg_resources/_vendor/six.py
python
Module_six_moves_urllib.__dir__
(self)
return ['parse', 'error', 'request', 'response', 'robotparser']
[]
def __dir__(self): return ['parse', 'error', 'request', 'response', 'robotparser']
[ "def", "__dir__", "(", "self", ")", ":", "return", "[", "'parse'", ",", "'error'", ",", "'request'", ",", "'response'", ",", "'robotparser'", "]" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pkg_resources/_vendor/six.py#L479-L480
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-darwin/x64/tornado/web.py
python
RequestHandler.check_etag_header
(self)
return match
Checks the ``Etag`` header against requests's ``If-None-Match``. Returns ``True`` if the request's Etag matches and a 304 should be returned. For example:: self.set_etag_header() if self.check_etag_header(): self.set_status(304) return T...
Checks the ``Etag`` header against requests's ``If-None-Match``.
[ "Checks", "the", "Etag", "header", "against", "requests", "s", "If", "-", "None", "-", "Match", "." ]
def check_etag_header(self): """Checks the ``Etag`` header against requests's ``If-None-Match``. Returns ``True`` if the request's Etag matches and a 304 should be returned. For example:: self.set_etag_header() if self.check_etag_header(): self.set_statu...
[ "def", "check_etag_header", "(", "self", ")", ":", "computed_etag", "=", "utf8", "(", "self", ".", "_headers", ".", "get", "(", "\"Etag\"", ",", "\"\"", ")", ")", "# Find all weak and strong etag values from If-None-Match header", "# because RFC 7232 allows multiple etag ...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/tornado/web.py#L1501-L1540
a312863063/seeprettyface-generator-yellow
c75b95b56c40036d00b35f3e140cc4a45598e077
dnnlib/tflib/network.py
python
Network.list_ops
(self)
return ops
[]
def list_ops(self) -> List[TfExpression]: include_prefix = self.scope + "/" exclude_prefix = include_prefix + "_" ops = tf.get_default_graph().get_operations() ops = [op for op in ops if op.name.startswith(include_prefix)] ops = [op for op in ops if not op.name.startswith(exclude...
[ "def", "list_ops", "(", "self", ")", "->", "List", "[", "TfExpression", "]", ":", "include_prefix", "=", "self", ".", "scope", "+", "\"/\"", "exclude_prefix", "=", "include_prefix", "+", "\"_\"", "ops", "=", "tf", ".", "get_default_graph", "(", ")", ".", ...
https://github.com/a312863063/seeprettyface-generator-yellow/blob/c75b95b56c40036d00b35f3e140cc4a45598e077/dnnlib/tflib/network.py#L457-L463
AkariAsai/learning_to_retrieve_reasoning_paths
a020d52cfbbb7d7fca9fa25361e549c85e81875c
graph_retriever/modeling_graph_retriever.py
python
BertForGraphRetriever.weight_norm
(self, state)
return state
[]
def weight_norm(self, state): state = state / state.norm(dim = 2).unsqueeze(2) state = self.g * state return state
[ "def", "weight_norm", "(", "self", ",", "state", ")", ":", "state", "=", "state", "/", "state", ".", "norm", "(", "dim", "=", "2", ")", ".", "unsqueeze", "(", "2", ")", "state", "=", "self", ".", "g", "*", "state", "return", "state" ]
https://github.com/AkariAsai/learning_to_retrieve_reasoning_paths/blob/a020d52cfbbb7d7fca9fa25361e549c85e81875c/graph_retriever/modeling_graph_retriever.py#L47-L50
pytroll/satpy
09e51f932048f98cce7919a4ff8bd2ec01e1ae98
satpy/readers/fci_l1c_nc.py
python
FCIL1cNCFileHandler.calibrate
(self, data, key)
return data
Calibrate data.
Calibrate data.
[ "Calibrate", "data", "." ]
def calibrate(self, data, key): """Calibrate data.""" if key['calibration'] in ['brightness_temperature', 'reflectance', 'radiance']: data = self.calibrate_counts_to_physical_quantity(data, key) elif key['calibration'] != "counts": logger.error( "Received ...
[ "def", "calibrate", "(", "self", ",", "data", ",", "key", ")", ":", "if", "key", "[", "'calibration'", "]", "in", "[", "'brightness_temperature'", ",", "'reflectance'", ",", "'radiance'", "]", ":", "data", "=", "self", ".", "calibrate_counts_to_physical_quanti...
https://github.com/pytroll/satpy/blob/09e51f932048f98cce7919a4ff8bd2ec01e1ae98/satpy/readers/fci_l1c_nc.py#L441-L451
EventGhost/EventGhost
177be516849e74970d2e13cda82244be09f277ce
lib27/site-packages/tornado/ioloop.py
python
PeriodicCallback.is_running
(self)
return self._running
Return True if this `.PeriodicCallback` has been started. .. versionadded:: 4.1
Return True if this `.PeriodicCallback` has been started.
[ "Return", "True", "if", "this", ".", "PeriodicCallback", "has", "been", "started", "." ]
def is_running(self): """Return True if this `.PeriodicCallback` has been started. .. versionadded:: 4.1 """ return self._running
[ "def", "is_running", "(", "self", ")", ":", "return", "self", ".", "_running" ]
https://github.com/EventGhost/EventGhost/blob/177be516849e74970d2e13cda82244be09f277ce/lib27/site-packages/tornado/ioloop.py#L1028-L1033
mudpi/mudpi-core
fb206b1136f529c7197f1e6b29629ed05630d377
mudpi/extensions/sun/sensor.py
python
SunSensor.restore_state
(self, state)
Retstore state to prevent calls after multiple restarts
Retstore state to prevent calls after multiple restarts
[ "Retstore", "state", "to", "prevent", "calls", "after", "multiple", "restarts" ]
def restore_state(self, state): """ Retstore state to prevent calls after multiple restarts """ self._sunrise = state.state["sunrise"] self._sunset = state.state["sunset"] self._solar_noon = state.state["solar_noon"] self._day_length = state.state["day_length"] try: ...
[ "def", "restore_state", "(", "self", ",", "state", ")", ":", "self", ".", "_sunrise", "=", "state", ".", "state", "[", "\"sunrise\"", "]", "self", ".", "_sunset", "=", "state", ".", "state", "[", "\"sunset\"", "]", "self", ".", "_solar_noon", "=", "sta...
https://github.com/mudpi/mudpi-core/blob/fb206b1136f529c7197f1e6b29629ed05630d377/mudpi/extensions/sun/sensor.py#L108-L122
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/olefile/olefile.py
python
OleFileIO.loadfat_sect
(self, sect)
return isect
Adds the indexes of the given sector to the FAT :param sect: string containing the first FAT sector, or array of long integers :returns: index of last FAT sector.
Adds the indexes of the given sector to the FAT
[ "Adds", "the", "indexes", "of", "the", "given", "sector", "to", "the", "FAT" ]
def loadfat_sect(self, sect): """ Adds the indexes of the given sector to the FAT :param sect: string containing the first FAT sector, or array of long integers :returns: index of last FAT sector. """ # a FAT sector is an array of ulong integers. if isinstance(se...
[ "def", "loadfat_sect", "(", "self", ",", "sect", ")", ":", "# a FAT sector is an array of ulong integers.", "if", "isinstance", "(", "sect", ",", "array", ".", "array", ")", ":", "# if sect is already an array it is directly used", "fat1", "=", "sect", "else", ":", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/olefile/olefile.py#L1450-L1483
linuxscout/mishkal
4f4ae0ebc2d6acbeb3de3f0303151ec7b54d2f76
interfaces/web/lib/paste/flup_session.py
python
make_session_middleware
(app, global_conf, session_type=NoDefault, cookie_name=NoDefault, **store_config)
return SessionMiddleware( app, global_conf=global_conf, session_type=session_type, cookie_name=cookie_name, **store_config)
Wraps the application in a session-managing middleware. The session service can then be found in ``environ['paste.flup_session_service']``
Wraps the application in a session-managing middleware. The session service can then be found in ``environ['paste.flup_session_service']``
[ "Wraps", "the", "application", "in", "a", "session", "-", "managing", "middleware", ".", "The", "session", "service", "can", "then", "be", "found", "in", "environ", "[", "paste", ".", "flup_session_service", "]" ]
def make_session_middleware(app, global_conf, session_type=NoDefault, cookie_name=NoDefault, **store_config): """ Wraps the application in a session-managing middleware. The session service can then be found in ``environ...
[ "def", "make_session_middleware", "(", "app", ",", "global_conf", ",", "session_type", "=", "NoDefault", ",", "cookie_name", "=", "NoDefault", ",", "*", "*", "store_config", ")", ":", "return", "SessionMiddleware", "(", "app", ",", "global_conf", "=", "global_co...
https://github.com/linuxscout/mishkal/blob/4f4ae0ebc2d6acbeb3de3f0303151ec7b54d2f76/interfaces/web/lib/paste/flup_session.py#L96-L108
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/histogram2dcontour/_colorbar.py
python
ColorBar.ticklabeloverflow
(self)
return self["ticklabeloverflow"]
Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. In other cases the default is *hide past div*. The 'ticklabeloverflow' property is an enumeration that may be spec...
Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. In other cases the default is *hide past div*. The 'ticklabeloverflow' property is an enumeration that may be spec...
[ "Determines", "how", "we", "handle", "tick", "labels", "that", "would", "overflow", "either", "the", "graph", "div", "or", "the", "domain", "of", "the", "axis", ".", "The", "default", "value", "for", "inside", "tick", "labels", "is", "*", "hide", "past", ...
def ticklabeloverflow(self): """ Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. In other cases the default is *hide past div*. The 'ticklabelover...
[ "def", "ticklabeloverflow", "(", "self", ")", ":", "return", "self", "[", "\"ticklabeloverflow\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/histogram2dcontour/_colorbar.py#L879-L894
modflowpy/flopy
eecd1ad193c5972093c9712e5c4b7a83284f0688
flopy/modflow/mfsfr2.py
python
ModflowSfr2.get_outlets
(self, level=0, verbose=True)
return txt
Traces all routing connections from each headwater to the outlet.
Traces all routing connections from each headwater to the outlet.
[ "Traces", "all", "routing", "connections", "from", "each", "headwater", "to", "the", "outlet", "." ]
def get_outlets(self, level=0, verbose=True): """ Traces all routing connections from each headwater to the outlet. """ txt = "" for per in range(self.nper): if ( per > 0 > self.dataset_5[per][0] ): # skip stress periods where seg data not...
[ "def", "get_outlets", "(", "self", ",", "level", "=", "0", ",", "verbose", "=", "True", ")", ":", "txt", "=", "\"\"", "for", "per", "in", "range", "(", "self", ".", "nper", ")", ":", "if", "(", "per", ">", "0", ">", "self", ".", "dataset_5", "[...
https://github.com/modflowpy/flopy/blob/eecd1ad193c5972093c9712e5c4b7a83284f0688/flopy/modflow/mfsfr2.py#L1198-L1288
karolzak/keras-unet
9b7aff5247fff75dc4e2a11ba9c45929b9166d1f
keras_unet/utils.py
python
get_augmented
( X_train, Y_train, X_val=None, Y_val=None, batch_size=32, seed=0, data_gen_args=dict( rotation_range=10.0, # width_shift_range=0.02, height_shift_range=0.02, shear_range=5, # zoom_range=0.3, horizontal_flip=True, vertical_flip=False, ...
[summary] Args: X_train (numpy.ndarray): [description] Y_train (numpy.ndarray): [description] X_val (numpy.ndarray, optional): [description]. Defaults to None. Y_val (numpy.ndarray, optional): [description]. Defaults to None. batch_size (int, optional): [description]. De...
[summary] Args: X_train (numpy.ndarray): [description] Y_train (numpy.ndarray): [description] X_val (numpy.ndarray, optional): [description]. Defaults to None. Y_val (numpy.ndarray, optional): [description]. Defaults to None. batch_size (int, optional): [description]. De...
[ "[", "summary", "]", "Args", ":", "X_train", "(", "numpy", ".", "ndarray", ")", ":", "[", "description", "]", "Y_train", "(", "numpy", ".", "ndarray", ")", ":", "[", "description", "]", "X_val", "(", "numpy", ".", "ndarray", "optional", ")", ":", "["...
def get_augmented( X_train, Y_train, X_val=None, Y_val=None, batch_size=32, seed=0, data_gen_args=dict( rotation_range=10.0, # width_shift_range=0.02, height_shift_range=0.02, shear_range=5, # zoom_range=0.3, horizontal_flip=True, verti...
[ "def", "get_augmented", "(", "X_train", ",", "Y_train", ",", "X_val", "=", "None", ",", "Y_val", "=", "None", ",", "batch_size", "=", "32", ",", "seed", "=", "0", ",", "data_gen_args", "=", "dict", "(", "rotation_range", "=", "10.0", ",", "# width_shift_...
https://github.com/karolzak/keras-unet/blob/9b7aff5247fff75dc4e2a11ba9c45929b9166d1f/keras_unet/utils.py#L17-L82
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/physics/quantum/cartesian.py
python
PxKet.momentum
(self)
return self.label[0]
The momentum of the state.
The momentum of the state.
[ "The", "momentum", "of", "the", "state", "." ]
def momentum(self): """The momentum of the state.""" return self.label[0]
[ "def", "momentum", "(", "self", ")", ":", "return", "self", ".", "label", "[", "0", "]" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/physics/quantum/cartesian.py#L272-L274
Pyomo/pyomo
dbd4faee151084f343b893cc2b0c04cf2b76fd92
pyomo/contrib/pyros/util.py
python
add_decision_rule_variables
(model_data, config)
return
Function to add decision rule (DR) variables to the working model. DR variables become first-stage design variables which do not get copied at each iteration. Currently support static_approx (no DR), affine DR, and quadratic DR. :param model_data: the data container for the working model :param config: ...
Function to add decision rule (DR) variables to the working model. DR variables become first-stage design variables which do not get copied at each iteration. Currently support static_approx (no DR), affine DR, and quadratic DR. :param model_data: the data container for the working model :param config: ...
[ "Function", "to", "add", "decision", "rule", "(", "DR", ")", "variables", "to", "the", "working", "model", ".", "DR", "variables", "become", "first", "-", "stage", "design", "variables", "which", "do", "not", "get", "copied", "at", "each", "iteration", "."...
def add_decision_rule_variables(model_data, config): ''' Function to add decision rule (DR) variables to the working model. DR variables become first-stage design variables which do not get copied at each iteration. Currently support static_approx (no DR), affine DR, and quadratic DR. :param model_d...
[ "def", "add_decision_rule_variables", "(", "model_data", ",", "config", ")", ":", "second_stage_variables", "=", "model_data", ".", "working_model", ".", "util", ".", "second_stage_variables", "first_stage_variables", "=", "model_data", ".", "working_model", ".", "util"...
https://github.com/Pyomo/pyomo/blob/dbd4faee151084f343b893cc2b0c04cf2b76fd92/pyomo/contrib/pyros/util.py#L694-L747
zestedesavoir/zds-site
2ba922223c859984a413cc6c108a8aa4023b113e
zds/tutorialv2/publish_container.py
python
write_chapter_file
(base_dir, container, part_path, parsed, path_to_title_dict, image_callback=None)
Takes a chapter (i.e a set of extract gathers in one html text) and write in into the right file. :param image_callback: a callback taking html code and transforming img tags :type image_callback: callable :param base_dir: the directory into wich we will write the file :param container: the container t...
Takes a chapter (i.e a set of extract gathers in one html text) and write in into the right file.
[ "Takes", "a", "chapter", "(", "i", ".", "e", "a", "set", "of", "extract", "gathers", "in", "one", "html", "text", ")", "and", "write", "in", "into", "the", "right", "file", "." ]
def write_chapter_file(base_dir, container, part_path, parsed, path_to_title_dict, image_callback=None): """ Takes a chapter (i.e a set of extract gathers in one html text) and write in into the right file. :param image_callback: a callback taking html code and transforming img tags :type image_callbac...
[ "def", "write_chapter_file", "(", "base_dir", ",", "container", ",", "part_path", ",", "parsed", ",", "path_to_title_dict", ",", "image_callback", "=", "None", ")", ":", "full_path", "=", "Path", "(", "base_dir", ",", "part_path", ")", "if", "image_callback", ...
https://github.com/zestedesavoir/zds-site/blob/2ba922223c859984a413cc6c108a8aa4023b113e/zds/tutorialv2/publish_container.py#L244-L279
yuanli2333/Teacher-free-Knowledge-Distillation
ca9f966ea13c06ba0d427d104002d7dd9442779b
model/shufflenetv2.py
python
shufflenetv2
(**kwargs)
return ShuffleNetV2(**kwargs)
[]
def shufflenetv2(**kwargs): return ShuffleNetV2(**kwargs)
[ "def", "shufflenetv2", "(", "*", "*", "kwargs", ")", ":", "return", "ShuffleNetV2", "(", "*", "*", "kwargs", ")" ]
https://github.com/yuanli2333/Teacher-free-Knowledge-Distillation/blob/ca9f966ea13c06ba0d427d104002d7dd9442779b/model/shufflenetv2.py#L152-L153
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.2/django/db/models/fields/__init__.py
python
Field.has_default
(self)
return self.default is not NOT_PROVIDED
Returns a boolean of whether this field has a default value.
Returns a boolean of whether this field has a default value.
[ "Returns", "a", "boolean", "of", "whether", "this", "field", "has", "a", "default", "value", "." ]
def has_default(self): "Returns a boolean of whether this field has a default value." return self.default is not NOT_PROVIDED
[ "def", "has_default", "(", "self", ")", ":", "return", "self", ".", "default", "is", "not", "NOT_PROVIDED" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.2/django/db/models/fields/__init__.py#L342-L344
containernet/containernet
7b2ae38d691b2ed8da2b2700b85ed03562271d01
mininet/cli.py
python
CLI.do_gterm
( self, line )
Spawn gnome-terminal(s) for the given node(s). Usage: gterm node1 node2 ...
Spawn gnome-terminal(s) for the given node(s). Usage: gterm node1 node2 ...
[ "Spawn", "gnome", "-", "terminal", "(", "s", ")", "for", "the", "given", "node", "(", "s", ")", ".", "Usage", ":", "gterm", "node1", "node2", "..." ]
def do_gterm( self, line ): """Spawn gnome-terminal(s) for the given node(s). Usage: gterm node1 node2 ...""" self.do_xterm( line, term='gterm' )
[ "def", "do_gterm", "(", "self", ",", "line", ")", ":", "self", ".", "do_xterm", "(", "line", ",", "term", "=", "'gterm'", ")" ]
https://github.com/containernet/containernet/blob/7b2ae38d691b2ed8da2b2700b85ed03562271d01/mininet/cli.py#L318-L321
aio-libs/aiohttp-session
09a93b936d94e514bd16791c37d9301715710c61
aiohttp_session/memcached_storage.py
python
MemcachedStorage.load_session
(self, request: web.Request)
[]
async def load_session(self, request: web.Request) -> Session: cookie = self.load_cookie(request) if cookie is None: return Session(None, data=None, new=True, max_age=self.max_age) else: key = str(cookie) stored_key = (self.cookie_name + "_" + key).encode("utf...
[ "async", "def", "load_session", "(", "self", ",", "request", ":", "web", ".", "Request", ")", "->", "Session", ":", "cookie", "=", "self", ".", "load_cookie", "(", "request", ")", "if", "cookie", "is", "None", ":", "return", "Session", "(", "None", ","...
https://github.com/aio-libs/aiohttp-session/blob/09a93b936d94e514bd16791c37d9301715710c61/aiohttp_session/memcached_storage.py#L44-L59
tensorflow/models
6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3
research/lstm_object_detection/trainer.py
python
train
(create_tensor_dict_fn, create_model_fn, train_config, master, task, num_clones, worker_replicas, clone_on_cpu, ps_tasks, worker_job_name, is_chief, train_dir, graph_hook_fn=None)
Training function for detection models. Args: create_tensor_dict_fn: a function to create a tensor input dictionary. create_model_fn: a function that creates a DetectionModel and generates losses. train_config: a train_pb2.TrainConfig protobuf. master: BNS name of the TensorFlow ...
Training function for detection models.
[ "Training", "function", "for", "detection", "models", "." ]
def train(create_tensor_dict_fn, create_model_fn, train_config, master, task, num_clones, worker_replicas, clone_on_cpu, ps_tasks, worker_job_name, is_chief, train_dir, graph_hook_fn=None): """Train...
[ "def", "train", "(", "create_tensor_dict_fn", ",", "create_model_fn", ",", "train_config", ",", "master", ",", "task", ",", "num_clones", ",", "worker_replicas", ",", "clone_on_cpu", ",", "ps_tasks", ",", "worker_job_name", ",", "is_chief", ",", "train_dir", ",", ...
https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/research/lstm_object_detection/trainer.py#L234-L414
OCA/l10n-spain
99050907670a70307fcd8cdfb6f3400d9e120df4
l10n_es_aeat_mod347/models/mod347.py
python
L10nEsAeatMod347Report.calculate
(self)
return True
[]
def calculate(self): for report in self: # Delete previous partner records report.partner_record_ids.unlink() with self.env.norecompute(): self._create_partner_records("A", KEY_TAX_MAPPING["A"]) self._create_partner_records("B", KEY_TAX_MAPPING...
[ "def", "calculate", "(", "self", ")", ":", "for", "report", "in", "self", ":", "# Delete previous partner records", "report", ".", "partner_record_ids", ".", "unlink", "(", ")", "with", "self", ".", "env", ".", "norecompute", "(", ")", ":", "self", ".", "_...
https://github.com/OCA/l10n-spain/blob/99050907670a70307fcd8cdfb6f3400d9e120df4/l10n_es_aeat_mod347/models/mod347.py#L312-L322
moabitcoin/ig65m-pytorch
fc749e2ee354c3e4ddbb144cf511bb868b008f61
ig65m/models.py
python
r2plus1d_34_32_kinetics
(num_classes, pretrained=False, progress=False)
return r2plus1d_34(num_classes=num_classes, arch="r2plus1d_34_32_kinetics", pretrained=pretrained, progress=progress)
R(2+1)D 34-layer IG65M-Kinetics model for clips of length 32 frames. Args: num_classes: Number of classes in last classification layer pretrained: If True, loads IG65M weights fine-tuned on Kinetics videos progress: If True, displays a progress bar of the download to stderr
R(2+1)D 34-layer IG65M-Kinetics model for clips of length 32 frames.
[ "R", "(", "2", "+", "1", ")", "D", "34", "-", "layer", "IG65M", "-", "Kinetics", "model", "for", "clips", "of", "length", "32", "frames", "." ]
def r2plus1d_34_32_kinetics(num_classes, pretrained=False, progress=False): """R(2+1)D 34-layer IG65M-Kinetics model for clips of length 32 frames. Args: num_classes: Number of classes in last classification layer pretrained: If True, loads IG65M weights fine-tuned on Kinetics videos progress...
[ "def", "r2plus1d_34_32_kinetics", "(", "num_classes", ",", "pretrained", "=", "False", ",", "progress", "=", "False", ")", ":", "assert", "not", "pretrained", "or", "num_classes", "==", "400", ",", "\"pretrained on 400 classes\"", "return", "r2plus1d_34", "(", "nu...
https://github.com/moabitcoin/ig65m-pytorch/blob/fc749e2ee354c3e4ddbb144cf511bb868b008f61/ig65m/models.py#L54-L64
pinterest/mysql_utils
7ab237699b85de8b503b09f36e0309ac807689fe
zdict_gen/zdict_gen.py
python
parse
()
return parser.parse_args()
Defines a cli and parses command line inputs Args: Returns: object(options): The returned object from an argparse.ArgumentParser().parse_args() call
Defines a cli and parses command line inputs
[ "Defines", "a", "cli", "and", "parses", "command", "line", "inputs" ]
def parse(): """ Defines a cli and parses command line inputs Args: Returns: object(options): The returned object from an argparse.ArgumentParser().parse_args() call """ parser = argparse.ArgumentParser( description="Generates a *good* p...
[ "def", "parse", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Generates a *good* predefined dictionary \"", "\"for compressing pin objects with the \"", "\"DEFLATE algorithm. Takes in a file of \"", "\"commonly occuring substrings and th...
https://github.com/pinterest/mysql_utils/blob/7ab237699b85de8b503b09f36e0309ac807689fe/zdict_gen/zdict_gen.py#L83-L114