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://stackoverflow.com/questions/38884538/python-pandas-find-all-rows-where-all-values-are-nan Functional usage syntax: ```python df = remove_empty(df) ``` Method chaining syntax: ```python import pandas as pd import janitor df = pd.DataFrame(...).remove_empty() ``` :param df: The pandas DataFrame object. :returns: A pandas DataFrame.
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 inspired from [StackOverflow][so]. [so]: https://stackoverflow.com/questions/38884538/python-pandas-find-all-rows-where-all-values-are-nan Functional usage syntax: ```python df = remove_empty(df) ``` Method chaining syntax: ```python import pandas as pd import janitor df = pd.DataFrame(...).remove_empty() ``` :param df: The pandas DataFrame object. :returns: A pandas DataFrame. """ # noqa: E501 nanrows = df.index[df.isna().all(axis=1)] df = df.drop(index=nanrows).reset_index(drop=True) nancols = df.columns[df.isna().all(axis=0)] df = df.drop(columns=nancols) return df
[ "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_ack_plain(ciphertext, self.privkey) else: eph_pubkey, nonce, _ = decode_ack_eip8(ciphertext, self.privkey) 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", ...
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 information about the submissions
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 cron @return (Dict): Dictionary of submissions containing all the information about the submissions """ handle = self.handle url = "https://www.hackerrank.com/rest/hackers/" + \ handle + \ "/recent_challenges" request_params = {"limit": "5", "response_version": "v2"} submissions = [] next_cursor = "null" for i in xrange(1000): request_params["cursor"] = next_cursor response = get_request(url, params=request_params, is_daily_retrieval=is_daily_retrieval) if response in REQUEST_FAILURES: return response next_cursor = response.json()["cursor"] for row in response.json()["models"]: # Time of submission # @Todo: This is ugly time_stamp = row["created_at"][:-10].split("T") time_stamp = time.strptime(time_stamp[0] + " " + time_stamp[1], "%Y-%m-%d %H:%M:%S") time_stamp = datetime.datetime(time_stamp.tm_year, time_stamp.tm_mon, time_stamp.tm_mday, time_stamp.tm_hour, time_stamp.tm_min, time_stamp.tm_sec) + \ datetime.timedelta(minutes=330) curr = time.strptime(str(time_stamp), "%Y-%m-%d %H:%M:%S") if curr <= last_retrieved: return submissions submissions.append((str(time_stamp), "https://www.hackerrank.com" + row["url"], row["name"], "AC", "100", "-", "")) if response.json()["last_page"] == True: break return submissions
[ "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 True if obj.__doc__ is not None \ and ('DEPRECATED' in obj.__doc__ or 'Deprecated' in obj.__doc__): return True return skip or name in exclusions
[ "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_name_cache[queue] = queue return q
[ "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: response = middleware_method(request) if response: break if response is None: response = self._get_response(request) return response
[ "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._pretty_replaces: short = short.replace(orig, new) tup = (short, value) if key in ('loss', 'train_loss', 'val_loss', 'test_loss'): ret.insert(0, tup) losses_seen += 1 elif 'loss' in key: ret.insert(losses_seen, tup) losses_seen += 1 else: ret.append(tup) if style: return ', '.join(['%s: %s%7s%s' % (tt[0], style, '%.4f' % tt[1], Style.RESET_ALL) for tt in ret]) else: return ', '.join(['%s: %.4f' % (tt[0], tt[1]) for tt in ret])
[ "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 Exception as err: raise ValidationError(str(err))
[ "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 :rtype: 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 :returns: twilio.rest.api.v2010.account.message.media.MediaList :rtype: twilio.rest.api.v2010.account.message.media.MediaList """ super(MediaList, self).__init__(version) # Path Solution self._solution = {'account_sid': account_sid, 'message_sid': message_sid, } self._uri = '/Accounts/{account_sid}/Messages/{message_sid}/Media.json'.format(**self._solution)
[ "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 of sampling categorically from the output ids instead of reading directly from the inputs. time_major: Python bool. Whether the tensors in `inputs` are time major. If `False` (default), they are assumed to be batch major. seed: The sampling seed. scheduling_seed: The schedule decision rule sampling seed. name: Name scope for any created operations. Raises: ValueError: if `sampling_probability` is not a scalar or vector.
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 vector tensor of `ids` (argmax ids), or the `params` argument for `embedding_lookup`. sampling_probability: A 0D `float32` tensor: the probability of sampling categorically from the output ids instead of reading directly from the inputs. time_major: Python bool. Whether the tensors in `inputs` are time major. If `False` (default), they are assumed to be batch major. seed: The sampling seed. scheduling_seed: The schedule decision rule sampling seed. name: Name scope for any created operations. Raises: ValueError: if `sampling_probability` is not a scalar or vector. """ with ops.name_scope(name, "ScheduledEmbeddingSamplingWrapper", [embedding, sampling_probability]): if callable(embedding): self._embedding_fn = embedding else: self._embedding_fn = ( lambda ids: embedding_ops.embedding_lookup(embedding, ids)) self._sampling_probability = ops.convert_to_tensor( sampling_probability, name="sampling_probability") if self._sampling_probability.get_shape().ndims not in (0, 1): raise ValueError( "sampling_probability must be either a scalar or a vector. " "saw shape: %s" % (self._sampling_probability.get_shape())) self._seed = seed self._scheduling_seed = scheduling_seed super(ScheduledEmbeddingTrainingHelper, self).__init__( inputs=inputs, sequence_length=sequence_length, time_major=time_major, name=name)
[ "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) format_list = make_list_to_table(schema, header=False) if isinstance(item, list): return format_list(item) else: return format_item(item)
[ "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/commit/d8534850d9238e85ae0ea55bf2ac8583681fdb2b/oslo_policy/opts.py#L49 opts.set_defaults(config.CONF, 'policy.yaml')
[ "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 for cropping (x, y, z) """ x, y, w, h = cv2.boundingRect(contours) # drawing = numpy.zeros((480, 640), dtype=float) # cv2.drawContours(drawing, [contours], 0, (255, 0, 244), 1, 8) # cv2.rectangle(drawing, (x, y), (x+w, y+h), (244, 0, 233), 2, 8, 0) # cv2.imshow("contour", drawing) # convert to cube xstart = (com[0] - w / 2.) * com[2] / self.fx xend = (com[0] + w / 2.) * com[2] / self.fx ystart = (com[1] - h / 2.) * com[2] / self.fy yend = (com[1] + h / 2.) * com[2] / self.fy szx = xend - xstart szy = yend - ystart sz = (szx + szy) / 2. cube = (sz + tol, sz + tol, sz + tol) return 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_langs = set(self.get_langs_to_generate(rule)) template_name = self.get_template_name(rule.template) template_langs = set(templates[template_name].langs) return rule_langs.intersection(template_langs)
[ "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.debug("No hosts forgotten down")
[ "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 function calls, but any type of expression. Keyword arguments passed to this function are available as local variables. Example: ``import_string('re:compile(x)', x='[a-z]')``
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. The last form accepts not only function calls, but any type of expression. Keyword arguments passed to this function are available as local variables. Example: ``import_string('re:compile(x)', x='[a-z]')`` """ module, target = target.split(":", 1) if ':' in target else (target, None) if module not in sys.modules: __import__(module) if not target: return sys.modules[module] if target.isalnum(): return getattr(sys.modules[module], target) package_name = module.split('.')[0] namespace[package_name] = sys.modules[package_name] return eval('%s.%s' % (module, target), namespace)
[ "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://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.core.models.DrgRouteTable.lifecycle_state` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.core.VirtualNetworkClient.remove_import_drg_route_distribution` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
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 upon to enter the given state(s). :param str drg_route_table_id: (required) The `OCID`__ of the DRG route table. __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.core.models.DrgRouteTable.lifecycle_state` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.core.VirtualNetworkClient.remove_import_drg_route_distribution` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait """ operation_result = self.client.remove_import_drg_route_distribution(drg_route_table_id, **operation_kwargs) if not wait_for_states: return operation_result lowered_wait_for_states = [w.lower() for w in wait_for_states] wait_for_resource_id = operation_result.data.id try: waiter_result = oci.wait_until( self.client, self.client.get_drg_route_table(wait_for_resource_id), evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states, **waiter_kwargs ) result_to_return = waiter_result return result_to_return except Exception as e: raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
[ "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 : str, default '~/.tensorflow/models' Location for keeping the model parameters.
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 pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_vgg(blocks=13, use_bias=True, use_bn=True, model_name="bn_vgg13b", **kwargs)
[ "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.userID = kwargs.get("userID") # # The country that the user is based in. # self.country = kwargs.get("country") # # The user's email address. # self.emailAddress = kwargs.get("emailAddress")
[ "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 self._intersect(J)
[ "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.KB_BRUTE_COLUMNS, True) or kb.brute.columns kb.chars = hashDBRetrieve(HASHDB_KEYS.KB_CHARS, True) or kb.chars kb.dynamicMarkings = hashDBRetrieve(HASHDB_KEYS.KB_DYNAMIC_MARKINGS, True) or kb.dynamicMarkings kb.xpCmdshellAvailable = hashDBRetrieve(HASHDB_KEYS.KB_XP_CMDSHELL_AVAILABLE) or kb.xpCmdshellAvailable kb.errorChunkLength = hashDBRetrieve(HASHDB_KEYS.KB_ERROR_CHUNK_LENGTH) if kb.errorChunkLength and kb.errorChunkLength.isdigit(): kb.errorChunkLength = int(kb.errorChunkLength) else: kb.errorChunkLength = None conf.tmpPath = conf.tmpPath or hashDBRetrieve(HASHDB_KEYS.CONF_TMP_PATH) for injection in hashDBRetrieve(HASHDB_KEYS.KB_INJECTIONS, True) or []: if isinstance(injection, InjectionDict) and injection.place in conf.paramDict and \ injection.parameter in conf.paramDict[injection.place]: if not conf.tech or intersect(conf.tech, injection.data.keys()): if intersect(conf.tech, injection.data.keys()): injection.data = dict(filter(lambda (key, item): key in conf.tech, injection.data.items())) if injection not in kb.injections: kb.injections.append(injection) _resumeDBMS() _resumeOS()
[ "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: mean_img = img1.tolist() else: mean_img += img1 mean_img = mean_img / float(len(data)) # mean_img = thresholdize(mean_img, 'auto') scipy.misc.imshow(mean_img) for e1 in data: fname1 = os.path.join('.', e1['path']) img1 = scipy.ndimage.imread(fname1, flatten=False, mode='L') dist = _get_euclidean_dist(img1, mean_img) distances.append(dist) return (distances, mean_img)
[ "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 (predictions, loss, train_op).
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: The return value of the model function, typically a tuple of (predictions, loss, train_op). """ # TODO: This doesn't really belong here. # How to get rid of this? if hasattr(model, "use_beam_search"): if model.use_beam_search: tf.logging.info("Setting batch size to 1 for beam search.") batch_size = 1 input_fn = training_utils.create_input_fn( pipeline=input_pipeline, batch_size=batch_size, allow_smaller_final_batch=True) # Build the graph features, labels = input_fn() return model(features=features, labels=labels, params=None)
[ "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:pos+1]) & 0x80: pos += 1 pos += 1 if pos > end: raise _DecodeError('Truncated message.') return 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=<name> in " "the additional checks field" ) return cd.get('type') return t
[ "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", []) if aliases: name = metadata.get("aliases")[0].get("name") else: name = metadata.get("properties", {}).get("description") or fingerprint version = metadata.get("update_source", {}).get("alias") extra = metadata return ContainerImage( id=fingerprint, name=name, path=None, version=version, driver=self, extra=extra, )
[ "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'] # X resolution ran = [self['ranX'], self['ranY']] # Range of X,Y, from -10, to 10 range is 20 cent = [self['centX'], self['centY']] # Coordinates X,Y of the center from bottom left of the coordinate system dim = [self['dimX'], self['dimY']] # Real dimensions in gcode units spacX = self['spacX'] # Spacing of X axis lines spacY = self['spacY'] # Spacing of Y axis lines lin = self['lin'] # Small value - length of a line in gcode units draw = self['draw'] # Draw the coordinate system block.append("(Generated with a script by kswiorek)\n") block.append("(Equation: " + formula +")\n") block.append("(Resolution: " + str(res) +")\n") block.append("(Range: " + str(ran) +")\n") block.append("(Center: " + str(cent) +")\n") block.append("(Dimensions: " + str(dim) +")\n") block.append("(SpacingXY: " + str(spacX) +", " + str(spacY) +")\n") def mapc(var, axis): #Map coordinate systems return (var * (dim[axis]/ran[axis])) #Define coordinate system mins and maxes minX = -cent[0] maxX = ran[0]-cent[0] minY = -cent[1] maxY = ran[1]-cent[1] #Define domain and codomain X = [] Y = [] e_old = "" #Store old exception to comapre #Calculate values for arguments with a resolution for i in range(0, int(ran[0]/res+1)): #Complaints about values beeing floats x = i*res + minX #Iterate x X.append(x) try: Y.append(eval(formula)) except Exception as exc: #Append None, not to loose sync with X Y.append(None) e = str(exc) if e != e_old: #If there is a different exception - display it print("Warning: " + str(e)) app.setStatus(_("Warning: " + str(e))) e_old = e raised = True # Z axis is raised at start #Clip values out of bounds, replace with None, not to loose sync with X for i, item in enumerate(Y): y = Y[i] if not y is None and (y < minY or y > maxY): Y[i] = None #Y without "None", min() and max() can't compare them Ynn = [] #Y no Nones for i, item in enumerate(Y): if not Y[i] is None: Ynn.append(Y[i]) block.append(CNC.gcode(1, [("f",CNC.vars["cutfeed"])])) #Set feedrate if draw: #If the user selected to draw the coordinate system #X axis block.append(CNC.grapid(z=3)) block.append(CNC.grapid(0, mapc(cent[1], 1))) #1st point of X axis line block.append(CNC.grapid(z=0)) block.append(CNC.gline(dim[0] + lin*1.2, mapc(cent[1], 1))) #End of X axis line + a bit more for the arrow block.append(CNC.gline(dim[0] - lin/2, mapc(cent[1], 1) - lin / 2)) #bottom part of the arrow block.append(CNC.grapid(z=3)) block.append(CNC.grapid(dim[0] + lin*1.2, mapc(cent[1], 1), 0)) #End of X axis line block.append(CNC.grapid(z=0)) block.append(CNC.gline(dim[0] - lin/2, mapc(cent[1], 1) + lin / 2)) #top part of the arrow block.append(CNC.grapid(z=3)) #Y axis, just inverted x with y block.append(CNC.grapid(z=3)) block.append(CNC.grapid(mapc(cent[0], 0), 0)) #1st point of Y axis line block.append(CNC.grapid(z=0)) block.append(CNC.gline(mapc(cent[0], 0), dim[1] + lin*1.2)) #End of Y axis line + a bit more for the arrow block.append(CNC.gline(mapc(cent[0], 0) - lin / 2, dim[1] - lin/2)) #left part of the arrow block.append(CNC.grapid(z=3)) block.append(CNC.grapid(mapc(cent[0], 0), dim[1] + lin*1.2)) #End of Y axis line block.append(CNC.grapid(z=0)) block.append(CNC.gline(mapc(cent[0], 0) + lin / 2, dim[1] - lin/2)) #right part of the arrow block.append(CNC.grapid(z=3)) #X axis number lines i = 0 while i < ran[0] - cent[0]: #While i is on the left of the arrow i +=spacX #Add line spacing #Draw lines right of the center block.append(CNC.grapid(mapc(i+cent[0],0), mapc(cent[1], 1) + lin/2)) block.append(CNC.grapid(z=0)) block.append(CNC.gline(mapc(i+cent[0],0), mapc(cent[1], 1) - lin/2)) block.append(CNC.grapid(z=3)) i = 0 while i > -cent[0]: #While i is lower than center coordinate, inverted for easier math i -=spacX #Add line spacing #Draw lines left of the center block.append(CNC.grapid(mapc(i+cent[0],0), mapc(cent[1], 1) + lin/2)) block.append(CNC.grapid(z=0)) block.append(CNC.gline(mapc(i+cent[0],0), mapc(cent[1], 1) - lin/2)) block.append(CNC.grapid(z=3)) #Y axis number lines i = 0 while i < ran[1] - cent[1]: #While i is between the center and the arrow i +=spacX #Add line spacing #Draw lines top of the center (everything just inverted) block.append(CNC.grapid(mapc(cent[0], 0) + lin/2, mapc(i+cent[1],1))) block.append(CNC.grapid(z=0)) block.append(CNC.gline(mapc(cent[0], 0) - lin/2, mapc(i+cent[1],1))) block.append(CNC.grapid(z=3)) i = 0 while i > -1*cent[1]: i -=spacX #Add line spacing #Draw lines bottom of the center block.append(CNC.grapid(mapc(cent[0], 0) + lin/2, mapc(i+cent[1],1))) block.append(CNC.grapid(z=0)) block.append(CNC.gline(mapc(cent[0], 0) - lin/2, mapc(i+cent[1],1))) block.append(CNC.grapid(z=3)) raised = True #Z was raised #Draw graph for i, item in enumerate(Y): if not Y[i] is None: x = mapc(X[i]+cent[0], 0) #Take an argument y = mapc(Y[i]+cent[1], 1) #Take a value else: y = Y[i] #only for tne None checks next if y is None and not raised: #If a None "period" just started raise Z raised = True block.append(CNC.grapid(z=3)) elif not y is None and raised: #If Z was raised and the None "period" ended move to new coordinates block.append(CNC.grapid(round(x, 2),round(y, 2))) block.append(CNC.grapid(z=0)) #Lower Z raised = False elif not y is None and not raised: #Nothing to do with Nones? Just draw block.append(CNC.gline(round(x, 2),round(y, 2))) block.append(CNC.grapid(z=3)) #Raise on the end blocks.append(block) active = app.activeBlock() app.gcode.insBlocks(active, blocks, 'Function inserted') #insert blocks over active block in the editor app.refresh() #refresh editor app.setStatus(_('Generated function graph')) #feed back result print()
[ "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 write as scalars (defaults to data.keys()) vectors : dict mapping of vector name to vector component names to take from data tensors : dict mapping of tensor name to tensor component names to take from data coords : list the name of coordinate data arrays (default=('x','y','z')) dims : 3 tuple the size along the dimensions for (None means x.shape) **kwargs : extra arguments for the file writer example file_type=binary/ascii
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 write to (can be any recognized vtk extension) if extension is missing .vts extension is appended scalars : list list of arrays to write as scalars (defaults to data.keys()) vectors : dict mapping of vector name to vector component names to take from data tensors : dict mapping of tensor name to tensor component names to take from data coords : list the name of coordinate data arrays (default=('x','y','z')) dims : 3 tuple the size along the dimensions for (None means x.shape) **kwargs : extra arguments for the file writer example file_type=binary/ascii ''' x = data[coords[0]] y = data.get(coords[1], zeros_like(x)) z = data.get(coords[2], zeros_like(x)) if dims is None: dims = array([1,1,1]) dims[:x.ndim] = x.shape else: dims = array(dims) sg = tvtk.StructuredGrid(points=c_[x.flat,y.flat,z.flat],dimensions=array(dims)) pd = tvtk.PointData() if scalars is None: scalars = [i for i in data.keys() if i not in coords] for v in scalars: pd.scalars = ravel(data[v]) pd.scalars.name = v sg.point_data.add_array(pd.scalars) for vec,vec_vars in vectors.items(): u,v,w = [data[i] for i in vec_vars] pd.vectors = c_[ravel(u),ravel(v),ravel(w)] pd.vectors.name = vec sg.point_data.add_array(pd.vectors) for ten,ten_vars in tensors.items(): vars = [data[i] for i in ten_vars] tensors = c_[[ravel(i) for i in vars]].T pd.tensors = tensors pd.tensors.name = ten sg.point_data.add_array(pd.tensors) write_data(sg, filename, **kwargs)
[ "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 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 damaging effect metasvm_cutoff=0.0 # greater scores indicating more likely deleterious effects PhyloP_cutoff=1.6 # phyloP46way_placental > , The larger the score, the more conserved the site cutoff_conserv=2 # for GERP++_RS dbscSNV_cutoff=0.6 #either score(ada and rf) >0.6 as splicealtering cls=line.split('\t') try: #if float(cls[Funcanno_flgs['SIFT_score']]) < sift_cutoff: if float(cls[Funcanno_flgs['MetaSVM_score']]) > metasvm_cutoff: PP3_t1=1 except ValueError: # the sift absent means many: synonymous indel stop, but synonymous also is no impact funcs_tmp=["synon","coding-synon"] line_tmp=cls[Funcanno_flgs['Func.refGene']]+" "+cls[Funcanno_flgs['ExonicFunc.refGene']] for fc in funcs_tmp: if line_tmp.find(fc)<0 : PP3_t1=1 else: pass try: #if float(cls[Funcanno_flgs['phyloP46way_placental']])> PhyloP_cutoff: if float(cls[Funcanno_flgs['GERP++_RS']])> cutoff_conserv: PP3_t2=1 except ValueError: # absent means there are gaps in the multiple alignment,so cannot have the score,not conserved pass else: pass try: if float(cls[Funcanno_flgs['dbscSNV_RF_SCORE']])>dbscSNV_cutoff or float(cls[Funcanno_flgs['dbscSNV_ADA_SCORE']])>dbscSNV_cutoff: PP3_t3=1 except ValueError: pass else: pass if (PP3_t1+PP3_t2+PP3_t3)>=2: PP3=1 return(PP3)
[ "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: return None ts = int(time()) return int(resp.get('response', {}).get('server_time', ts)) - ts
[ "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): parent_payload_ids = {stoq_response.results[i].payload_id} # Contruct a new root Payload object since StoqResponse only has the # PayloadResults object new_root_payload = Payload(b'') new_root_payload.results = new_root_payload_result relevant_payloads: List[Payload] = [new_root_payload] for payload_result in stoq_response.results[i:]: for extracted_from in payload_result.extracted_from: if extracted_from in parent_payload_ids: parent_payload_ids.add(payload_result.payload_id) new_payload = Payload(b'') new_payload.results = payload_result relevant_payloads.append(new_payload) new_request = Request( payloads=relevant_payloads, request_meta=stoq_response.request_meta ) new_response = StoqResponse( request=new_request, time=stoq_response.time, scan_id=stoq_response.scan_id, ) decorator_tasks = [] for plugin_name, decorator in self._loaded_decorator_plugins.items(): decorator_tasks.append(self._apply_decorator(decorator, new_response)) await asyncio.gather(*decorator_tasks) yield new_response
[ "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, ) -> Tuple[tf.Tensor, Optional[tf.Tensor]]: """Input shape: Batch x Time x Channel""" # if key_value_states are provided this layer is used as a cross-attention layer # for the decoder is_cross_attention = key_value_states is not None bsz, tgt_len, embed_dim = shape_list(hidden_states) # get query proj query_states = self.q_proj(hidden_states) * self.scaling # get key, value proj if is_cross_attention and past_key_value is not None: # reuse k,v, cross_attentions key_states = past_key_value[0] value_states = past_key_value[1] elif is_cross_attention: # cross_attentions key_states = self._shape(self.k_proj(key_value_states), -1, bsz) value_states = self._shape(self.v_proj(key_value_states), -1, bsz) elif past_key_value is not None: # reuse k, v, self_attention key_states = self._shape(self.k_proj(hidden_states), -1, bsz) value_states = self._shape(self.v_proj(hidden_states), -1, bsz) key_states = tf.concat([past_key_value[0], key_states], axis=2) value_states = tf.concat([past_key_value[1], value_states], axis=2) else: # self_attention key_states = self._shape(self.k_proj(hidden_states), -1, bsz) value_states = self._shape(self.v_proj(hidden_states), -1, bsz) if self.is_decoder: # if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states. # Further calls to cross_attention layer can then reuse all cross-attention # key/value_states (first "if" case) # if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of # all previous decoder key/value_states. Further calls to uni-directional self-attention # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case) # if encoder bi-directional self-attention `past_key_value` is always `None` past_key_value = (key_states, value_states) proj_shape = (bsz * self.num_heads, -1, self.head_dim) query_states = tf.reshape(self._shape(query_states, tgt_len, bsz), proj_shape) key_states = tf.reshape(key_states, proj_shape) value_states = tf.reshape(value_states, proj_shape) src_len = shape_list(key_states)[1] attn_weights = tf.matmul(query_states, key_states, transpose_b=True) # The tf.debugging asserts are not compliant with XLA then they # have to be disabled in other modes than eager. if tf.executing_eagerly(): tf.debugging.assert_equal( shape_list(attn_weights), [bsz * self.num_heads, tgt_len, src_len], message=f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is {shape_list(attn_weights)}", ) if attention_mask is not None: # The tf.debugging asserts are not compliant with XLA then they # have to be disabled in other modes than eager. if tf.executing_eagerly(): tf.debugging.assert_equal( shape_list(attention_mask), [bsz, 1, tgt_len, src_len], message=f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {shape_list(attention_mask)}", ) attention_mask = tf.cast(attention_mask, dtype=attn_weights.dtype) attn_weights = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len)) + attention_mask attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len)) attn_weights = tf.nn.softmax(attn_weights, axis=-1) if layer_head_mask is not None: # The tf.debugging asserts are not compliant with XLA then they # have to be disabled in other modes than eager. if tf.executing_eagerly(): tf.debugging.assert_equal( shape_list(layer_head_mask), [self.num_heads], message=f"Head mask for a single layer should be of size {(self.num_heads)}, but is {shape_list(layer_head_mask)}", ) attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape( attn_weights, (bsz, self.num_heads, tgt_len, src_len) ) attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len)) attn_probs = self.dropout(attn_weights, training=training) attn_output = tf.matmul(attn_probs, value_states) # The tf.debugging asserts are not compliant with XLA then they # have to be disabled in other modes than eager. if tf.executing_eagerly(): tf.debugging.assert_equal( shape_list(attn_output), [bsz * self.num_heads, tgt_len, self.head_dim], message=f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is {shape_list(attn_output)}", ) attn_output = tf.transpose( tf.reshape(attn_output, (bsz, self.num_heads, tgt_len, self.head_dim)), (0, 2, 1, 3) ) attn_output = tf.reshape(attn_output, (bsz, tgt_len, embed_dim)) attn_output = self.out_proj(attn_output) attn_weights: tf.Tensor = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len)) return attn_output, attn_weights, past_key_value
[ "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'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
[ "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.get_manifest() self._mtime = mtime return self._manifest
[ "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 return code
[ "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 link set {0} down && ip link set {0} up".format(ifname)) if return_code == 0: return logger.warn("failed to restart {0}: return code {1}".format(ifname, return_code)) if attempt < retry_limit: logger.info("retrying in {0} seconds".format(wait)) time.sleep(wait) else: logger.warn("exceeded restart retries")
[ "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 that this function can exit. process: A list of the multiprocessing.Process instances used as workers. pending_work_items: A dict mapping work ids to _WorkItems e.g. {5: <_WorkItem...>, 6: <_WorkItem...>, ...} work_ids_queue: A queue.Queue of work ids e.g. Queue([5, 6, ...]). call_queue: A multiprocessing.Queue that will be filled with _CallItems derived from _WorkItems for processing by the process workers. result_queue: A multiprocessing.Queue of _ResultItems generated by the process workers.
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 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 that this function can exit. process: A list of the multiprocessing.Process instances used as workers. pending_work_items: A dict mapping work ids to _WorkItems e.g. {5: <_WorkItem...>, 6: <_WorkItem...>, ...} work_ids_queue: A queue.Queue of work ids e.g. Queue([5, 6, ...]). call_queue: A multiprocessing.Queue that will be filled with _CallItems derived from _WorkItems for processing by the process workers. result_queue: A multiprocessing.Queue of _ResultItems generated by the process workers. """ executor = None def shutting_down(): return _shutdown or executor is None or executor._shutdown_thread def shutdown_worker(): # This is an upper bound nb_children_alive = sum(p.is_alive() for p in processes.values()) for i in range(0, nb_children_alive): call_queue.put_nowait(None) # Release the queue's resources as soon as possible. call_queue.close() # If .join() is not called on the created processes then # some multiprocessing.Queue methods may deadlock on Mac OS X. for p in processes.values(): p.join() reader = result_queue._reader while True: _add_call_item_to_queue(pending_work_items, work_ids_queue, call_queue) sentinels = [p.sentinel for p in processes.values()] assert sentinels ready = wait([reader] + sentinels) if reader in ready: result_item = reader.recv() else: # Mark the process pool broken so that submits fail right now. executor = executor_reference() if executor is not None: executor._broken = True executor._shutdown_thread = True executor = None # All futures in flight must be marked failed for work_id, work_item in pending_work_items.items(): work_item.future.set_exception( BrokenProcessPool( "A process in the process pool was " "terminated abruptly while the future was " "running or pending." )) # Delete references to object. See issue16284 del work_item pending_work_items.clear() # Terminate remaining workers forcibly: the queues or their # locks may be in a dirty state and block forever. for p in processes.values(): p.terminate() shutdown_worker() return if isinstance(result_item, int): # Clean shutdown of a worker using its PID # (avoids marking the executor broken) assert shutting_down() p = processes.pop(result_item) p.join() if not processes: shutdown_worker() return elif result_item is not None: work_item = pending_work_items.pop(result_item.work_id, None) # work_item can be None if another process terminated (see above) if work_item is not None: if result_item.exception: work_item.future.set_exception(result_item.exception) else: work_item.future.set_result(result_item.result) # Delete references to object. See issue16284 del work_item # Check whether we should start shutting down. executor = executor_reference() # No more work items can be added if: # - The interpreter is shutting down OR # - The executor that owns this worker has been collected OR # - The executor that owns this worker has been shutdown. if shutting_down(): try: # Since no new work items can be added, it is safe to shutdown # this thread if there are no pending work items. if not pending_work_items: shutdown_worker() return except Full: # This is not a problem: we will eventually be woken up (in # result_queue.get()) and be able to send a sentinel again. pass executor = None
[ "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(box1[0]-0.5*box1[2], box2[0]-0.5*box2[2]) if lr > 0: tb = min(box1[1]+0.5*box1[3], box2[1]+0.5*box2[3]) - \ max(box1[1]-0.5*box1[3], box2[1]-0.5*box2[3]) if tb > 0: intersection = tb*lr union = box1[2]*box1[3]+box2[2]*box2[3]-intersection return intersection/union return 0
[ "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 arrays. return_logits (bool): If True, in the case of discrete outputs, it will return the logits. set_output_data (bool): If True, it will set the predicted output data to the outputs given to the approximator. Returns: (list of) torch.Tensor, (list of) np.array: predicted action data.
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 False, if the policy is stochastic. to_numpy (bool): If True, it will convert the data (torch.Tensors) to numpy arrays. return_logits (bool): If True, in the case of discrete outputs, it will return the logits. set_output_data (bool): If True, it will set the predicted output data to the outputs given to the approximator. Returns: (list of) torch.Tensor, (list of) np.array: predicted action data. """ if isinstance(self.model, Approximator): # inner model is an approximator return self.model.predict(state_data, to_numpy=to_numpy, return_logits=return_logits, set_output_data=set_output_data) # inner model is a learning model return self.model.predict(state_data, to_numpy=to_numpy)
[ "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, self) self.lock.release()
[ "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, data = self.unlock_trade(password, password_md5) logger.debug('auto unlock trade ret={},data={}'.format(ret, data)) if ret != RET_OK: msg = data # 定阅交易帐号推送 if ret == RET_OK: self.__check_acc_sub_push() return ret, msg
[ "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. only affect alpha.
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. only affect alpha.
[ "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. else, will treat first label as background. only affect alpha. """ super().__init__() self._alpha = alpha self._gamma = gamma
[ "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 in range(self.B): E_lng[:,:,b] = psi(self.mf_gamma[:,:,b]) - trm2 return E_lng
[ "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 containing the standard cookie-attributes (discard, secure, version, expires or max-age, domain, path and port) and rest is a dictionary containing the rest of the cookie-attributes.
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 the cookie name and value, standard is a dictionary containing the standard cookie-attributes (discard, secure, version, expires or max-age, domain, path and port) and rest is a dictionary containing the rest of the cookie-attributes. """ cookie_tuples = [] boolean_attrs = "discard", "secure" value_attrs = ("version", "expires", "max-age", "domain", "path", "port", "comment", "commenturl") for cookie_attrs in attrs_set: name, value = cookie_attrs[0] # Build dictionary of standard cookie-attributes (standard) and # dictionary of other cookie-attributes (rest). # Note: expiry time is normalised to seconds since epoch. V0 # cookies should have the Expires cookie-attribute, and V1 cookies # should have Max-Age, but since V1 includes RFC 2109 cookies (and # since V0 cookies may be a mish-mash of Netscape and RFC 2109), we # accept either (but prefer Max-Age). max_age_set = False bad_cookie = False standard = {} rest = {} for k, v in cookie_attrs[1:]: lc = k.lower() # don't lose case distinction for unknown fields if lc in value_attrs or lc in boolean_attrs: k = lc if k in boolean_attrs and v is None: # boolean cookie-attribute is present, but has no value # (like "discard", rather than "port=80") v = True if k in standard: # only first value is significant continue if k == "domain": if v is None: _debug(" missing value for domain attribute") bad_cookie = True break # RFC 2965 section 3.3.3 v = v.lower() if k == "expires": if max_age_set: # Prefer max-age to expires (like Mozilla) continue if v is None: _debug(" missing or invalid value for expires " "attribute: treating as session cookie") continue if k == "max-age": max_age_set = True try: v = int(v) except ValueError: _debug(" missing or invalid (non-numeric) value for " "max-age attribute") bad_cookie = True break # convert RFC 2965 Max-Age to seconds since epoch # XXX Strictly you're supposed to follow RFC 2616 # age-calculation rules. Remember that zero Max-Age # is a request to discard (old and new) cookie, though. k = "expires" v = self._now + v if (k in value_attrs) or (k in boolean_attrs): if (v is None and k not in ("port", "comment", "commenturl")): _debug(" missing value for %s attribute" % k) bad_cookie = True break standard[k] = v else: rest[k] = v if bad_cookie: continue cookie_tuples.append((name, value, standard, rest)) return cookie_tuples
[ "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_ids) is_sparse = True else: assert node_ids is None, node_ids is_sparse = False #formatCode = 2 node_id = np.zeros(n, 'int32') rho = np.zeros(n, 'float32') rhoU = np.zeros(n, 'float32') rhoV = np.zeros(n, 'float32') rhoW = np.zeros(n, 'float32') e = np.zeros(n, 'float32') with open(flo_filename, 'r') as flo_file: line = flo_file.readline().strip() try: #file is messsed up mach = float(line) except Exception: raise #loads['Cp'] = e # it's 0 anyways... #return node_id, loads # determine the number of variables on each line sline1 = flo_file.readline().strip().split() nvars = None if len(sline1) == 6: nvars = 6 rhoi = parse_float(sline1[1]) rhoui = parse_float(sline1[2]) rhovi = parse_float(sline1[3]) rhowi = parse_float(sline1[4]) ei = parse_float(sline1[5]) else: nvars = 5 rhoi = parse_float(sline1[1]) rhoui = parse_float(sline1[2]) rhovi = parse_float(sline1[3]) rhowi = parse_float(sline1[4]) sline2 = flo_file.readline().strip().split() ei = parse_float(sline2) # set the i=0 values if not is_sparse: nmax = n i = 0 node_id[i] = sline1[0] rho[i] = rhoi rhoU[i] = rhoui rhoV[i] = rhovi rhoW[i] = rhowi e[i] = ei else: ni = 0 node_ids_minus_1 = np.array(node_ids) - 1 nmax = node_ids_minus_1.max() + 1 if 0 in node_ids_minus_1: i = 0 node_id[i] = sline1[0] rho[i] = rhoi rhoU[i] = rhoui rhoV[i] = rhovi rhoW[i] = rhowi e[i] = ei ni += 1 # loop over the rest of the data in the flo file if node_ids is None: ni = n # extract nodes 1, 2, ... 10, but not 11+ if nvars == 6: # sequential nvars=6 for i in range(1, n): sline1 = flo_file.readline().strip().split() rhoi = parse_float(sline1[1]) rhoui = parse_float(sline1[2]) rhovi = parse_float(sline1[3]) rhowi = parse_float(sline1[4]) ei = parse_float(sline1[5]) node_id[i] = sline1[0] rho[i] = rhoi rhoU[i] = rhoui rhoV[i] = rhovi rhoW[i] = rhowi e[i] = ei assert len(sline1) == 6, 'len(sline1)=%s' % len(sline1) else: # sequential nvars=5 for i in range(1, n): sline1 = flo_file.readline().strip().split() rhoi = parse_float(sline1[1]) rhoui = parse_float(sline1[2]) rhovi = parse_float(sline1[3]) rhowi = parse_float(sline1[4]) assert len(sline1) == 5, 'len(sline1)=%s' % len(sline1) sline2 = flo_file.readline().strip().split() ei = parse_float(sline2) node_id[i] = sline1[0] rho[i] = rhoi rhoU[i] = rhoui rhoV[i] = rhovi rhoW[i] = rhowi e[i] = ei assert len(sline2) == 1, 'len(sline2)=%s' % len(sline2) else: # extract node 1, 2, and 10 if nvars == 6: # dynamic nvars=6 for i in range(1, nmax): if i in node_ids_minus_1: sline1 = flo_file.readline().strip().split() rhoi = parse_float(sline1[1]) rhoui = parse_float(sline1[2]) rhovi = parse_float(sline1[3]) rhowi = parse_float(sline1[4]) ei = parse_float(sline1[5]) node_id[ni] = sline1[0] rho[ni] = rhoi rhoU[ni] = rhoui rhoV[ni] = rhovi rhoW[ni] = rhowi e[ni] = ei assert len(sline1) == 6, 'len(sline1)=%s' % len(sline1) ni += 1 else: unused_line1 = flo_file.readline() else: # dynamic nvars=5 for i in range(1, nmax): if i in node_ids_minus_1: sline1 = flo_file.readline().strip().split() rhoi = parse_float(sline1[1]) rhoui = parse_float(sline1[2]) rhovi = parse_float(sline1[3]) rhowi = parse_float(sline1[4]) assert len(sline1) == 5, 'len(sline1)=%s' % len(sline1) sline2 = flo_file.readline().strip().split() ei = parse_float(sline2[1]) node_id[ni] = sline1[0] rho[ni] = rhoi rhoU[ni] = rhoui rhoV[ni] = rhovi rhoW[ni] = rhowi e[ni] = ei assert len(sline2) == 1, 'len(sline2)=%s' % len(sline2) ni += 1 else: unused_line1 = flo_file.readline() unused_line2 = flo_file.readline() assert len(rho) == ni # limit the minimum density (to prevent division errors) rho_min = 0.001 irho_zero = np.where(rho < rho_min)[0] rho[irho_zero] = rho_min loads = OrderedDict() if '.aux.' in flo_filename: # the names (rho, e, rhoU, etc.) aren't correct, but that's OK # the load names are correct loads['inst vor'] = rho loads['timeavg vor'] = rhoU loads['inst visc'] = rhoV loads['timeavg visc'] = rhoW loads['local CFL'] = e return node_id, loads # standard outputs gamma = 1.4 two_over_mach2 = 2.0 / mach ** 2 one_over_gamma = 1.0 / gamma gm1 = gamma - 1 # node_id, rhoi, rhoui, rhovi, rhowi, ei rhoVV = (rhoU ** 2 + rhoV ** 2 + rhoW ** 2) / rho if 'p' in result_names or 'Mach' in result_names or 'Cp' in result_names: pND = gm1 * (e - rhoVV / 2.) if 'p' in result_names: loads['p'] = pND if 'Mach' in result_names: pabs = np.abs(pND) Mach = np.full(n, np.nan, dtype='float32') ipwhere = np.where(pabs > 0.0)[0] if len(ipwhere): inner = rhoVV[ipwhere] / (gamma * pabs[ipwhere]) inwhere = ipwhere[np.where(inner >= 0.0)[0]] if len(inwhere): Mach[inwhere] = np.sqrt(rhoVV[inwhere] / (gamma * pabs[inwhere])) loads['Mach'] = Mach if 'Cp' in result_names: Cp = two_over_mach2 * (pND - one_over_gamma) loads['Cp'] = Cp T = gamma * pND / rho # =a^2 as well #a = T.sqrt() if 'T' in result_names: loads['T'] = T if 'rho' in result_names: loads['rho'] = rho if 'rhoU' in result_names: loads['rhoU'] = rhoU if 'rhoV' in result_names: loads['rhoV'] = rhoV if 'rhoW' in result_names: loads['rhoW'] = rhoW if 'U' in result_names: loads['U'] = rhoU / rho if 'V' in result_names: loads['V'] = rhoV / rho if 'W' in result_names: loads['W'] = rhoW / rho return node_id, loads
[ "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, self.exp_number, self.dictionary_name, self.verbose) mp.generate_tif() # generate a multi-page tif, filled with self.training_text mp.generate_boxfile()
[ "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 below. Parameters: `text` - str/unicode - The text to be written. `encoding` - str - The Unicode encoding that will be used. This is ignored if `text` isn't a Unicode string. `errors` - str - How to handle Unicode encoding errors. Default is ``'strict'``. See ``help(unicode.encode)`` for the options. This is ignored if `text` isn't a Unicode string. `linesep` - keyword argument - str/unicode - The sequence of characters to be used to mark end-of-line. The default is :data:`os.linesep`. You can also specify ``None`` to leave all newlines as they are in `text`. `append` - keyword argument - bool - Specifies what to do if the file already exists (``True``: append to the end of it; ``False``: overwrite it.) The default is ``False``. --- Newline handling. ``write_text()`` converts all standard end-of-line sequences (``'\n'``, ``'\r'``, and ``'\r\n'``) to your platform's default end-of-line sequence (see :data:`os.linesep`; on Windows, for example, the end-of-line marker is ``'\r\n'``). If you don't like your platform's default, you can override it using the `linesep=` keyword argument. If you specifically want ``write_text()`` to preserve the newlines as-is, use ``linesep=None``. This applies to Unicode text the same as to 8-bit text, except there are three additional standard Unicode end-of-line sequences: ``u'\x85'``, ``u'\r\x85'``, and ``u'\u2028'``. (This is slightly different from when you open a file for writing with ``fopen(filename, "w")`` in C or ``open(filename, 'w')`` in Python.) --- Unicode If `text` isn't Unicode, then apart from newline handling, the bytes are written verbatim to the file. The `encoding` and `errors` arguments are not used and must be omitted. If `text` is Unicode, it is first converted to :func:`bytes` using the specified `encoding` (or the default encoding if `encoding` isn't specified). The `errors` argument applies only to this conversion.
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 differences between :meth:`write_text` and :meth:`write_bytes`: newline handling and Unicode handling. See below. Parameters: `text` - str/unicode - The text to be written. `encoding` - str - The Unicode encoding that will be used. This is ignored if `text` isn't a Unicode string. `errors` - str - How to handle Unicode encoding errors. Default is ``'strict'``. See ``help(unicode.encode)`` for the options. This is ignored if `text` isn't a Unicode string. `linesep` - keyword argument - str/unicode - The sequence of characters to be used to mark end-of-line. The default is :data:`os.linesep`. You can also specify ``None`` to leave all newlines as they are in `text`. `append` - keyword argument - bool - Specifies what to do if the file already exists (``True``: append to the end of it; ``False``: overwrite it.) The default is ``False``. --- Newline handling. ``write_text()`` converts all standard end-of-line sequences (``'\n'``, ``'\r'``, and ``'\r\n'``) to your platform's default end-of-line sequence (see :data:`os.linesep`; on Windows, for example, the end-of-line marker is ``'\r\n'``). If you don't like your platform's default, you can override it using the `linesep=` keyword argument. If you specifically want ``write_text()`` to preserve the newlines as-is, use ``linesep=None``. This applies to Unicode text the same as to 8-bit text, except there are three additional standard Unicode end-of-line sequences: ``u'\x85'``, ``u'\r\x85'``, and ``u'\u2028'``. (This is slightly different from when you open a file for writing with ``fopen(filename, "w")`` in C or ``open(filename, 'w')`` in Python.) --- Unicode If `text` isn't Unicode, then apart from newline handling, the bytes are written verbatim to the file. The `encoding` and `errors` arguments are not used and must be omitted. If `text` is Unicode, it is first converted to :func:`bytes` using the specified `encoding` (or the default encoding if `encoding` isn't specified). The `errors` argument applies only to this conversion. """ if isinstance(text, text_type): if linesep is not None: text = U_NEWLINE.sub(linesep, text) text = text.encode(encoding or sys.getdefaultencoding(), errors) else: assert encoding is None text = NEWLINE.sub(linesep, text) self.write_bytes(text, append=append)
[ "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 This method is called automatically when the request is finished, but may be called earlier for applications that override `compute_etag` and want to do an early check for ``If-None-Match`` before completing the request. The ``Etag`` header should be set (perhaps with `set_etag_header`) before calling this method.
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_status(304) return This method is called automatically when the request is finished, but may be called earlier for applications that override `compute_etag` and want to do an early check for ``If-None-Match`` before completing the request. The ``Etag`` header should be set (perhaps with `set_etag_header`) before calling this method. """ 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 values in a single header. etags = re.findall( br'\*|(?:W/)?"[^"]*"', utf8(self.request.headers.get("If-None-Match", "")) ) if not computed_etag or not etags: return False match = False if etags[0] == b'*': match = True else: # Use a weak comparison when comparing entity-tags. def val(x): return x[2:] if x.startswith(b'W/') else x for etag in etags: if val(etag) == val(computed_etag): match = True break return match
[ "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_prefix)] return ops
[ "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 unknown calibration key. Expected " "'brightness_temperature', 'reflectance', 'radiance' or 'counts', got " + key['calibration'] + ".") return data
[ "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: _last_update = datetime.datetime.strptime(state.state.get("last_update"), '%Y-%m-%d %H:%M:%S') _time = datetime.datetime.now() - _last_update _hours_past = _time.total_seconds() / (60 * 60) if _hours_past < 4: self._data_expired = False self._last_update = _last_update.strftime('%Y-%m-%d %H:%M:%S') except Exception as error: pass
[ "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(sect, array.array): # if sect is already an array it is directly used fat1 = sect else: # if it's a raw sector, it is parsed in an array fat1 = self.sect2array(sect) # Display the sector contents only if the logging level is debug: if log.isEnabledFor(logging.DEBUG): self.dumpsect(sect) # The FAT is a sector chain starting at the first index of itself. # initialize isect, just in case: isect = None for isect in fat1: isect = isect & 0xFFFFFFFF # JYTHON-WORKAROUND log.debug("isect = %X" % isect) if isect == ENDOFCHAIN or isect == FREESECT: # the end of the sector chain has been reached log.debug("found end of sector chain") break # read the FAT sector s = self.getsect(isect) # parse it as an array of 32 bits integers, and add it to the # global FAT array nextfat = self.sect2array(s) self.fat = self.fat + nextfat return isect
[ "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['paste.flup_session_service']`` """ return SessionMiddleware( app, global_conf=global_conf, session_type=session_type, cookie_name=cookie_name, **store_config)
[ "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 specified as: - One of the following enumeration values: ['allow', 'hide past div', 'hide past domain'] Returns ------- Any
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 specified as: - One of the following enumeration values: ['allow', 'hide past div', 'hide past domain']
[ "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 'ticklabeloverflow' property is an enumeration that may be specified as: - One of the following enumeration values: ['allow', 'hide past div', 'hide past domain'] Returns ------- Any """ return self["ticklabeloverflow"]
[ "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 defined continue # segments = self.segment_data[per].nseg # outsegs = self.segment_data[per].outseg # # all_outsegs = np.vstack([segments, outsegs]) # max_outseg = all_outsegs[-1].max() # knt = 1 # while max_outseg > 0: # # nextlevel = np.array([outsegs[s - 1] if s > 0 and s < 999999 else 0 # for s in all_outsegs[-1]]) # # all_outsegs = np.vstack([all_outsegs, nextlevel]) # max_outseg = nextlevel.max() # if max_outseg == 0: # break # knt += 1 # if knt > self.nss: # # subset outsegs map to only include rows with outseg number > 0 in last column # circular_segs = all_outsegs.T[all_outsegs[-1] > 0] # # # only retain one instance of each outseg number at iteration=nss # vals = [] # append outseg values to vals after they've appeared once # mask = [(True, vals.append(v))[0] # if v not in vals # else False for v in circular_segs[-1]] # circular_segs = circular_segs[:, np.array(mask)] # # # cull the circular segments array to remove duplicate instances of routing circles # circles = [] # duplicates = [] # for i in range(np.shape(circular_segs)[0]): # # find where values in the row equal the last value; # # record the index of the second to last instance of last value # repeat_start_ind = np.where(circular_segs[i] == circular_segs[i, -1])[0][-2:][0] # # use that index to slice out the repeated segment sequence # circular_seq = circular_segs[i, repeat_start_ind:].tolist() # # keep track of unique sequences of repeated segments # if set(circular_seq) not in circles: # circles.append(set(circular_seq)) # duplicates.append(False) # else: # duplicates.append(True) # circular_segs = circular_segs[~np.array(duplicates), :] # # txt += '{0} instances where an outlet was not found after {1} consecutive segments!\n' \ # .format(len(circular_segs), self.nss) # if level == 1: # txt += '\n'.join([' '.join(map(str, row)) for row in circular_segs]) + '\n' # else: # f = 'circular_routing.csv' # np.savetxt(f, circular_segs, fmt='%d', delimiter=',', header=txt) # txt += 'See {} for details.'.format(f) # if verbose: # print(txt) # break # # the array of segment sequence is useful for other other operations, # # such as plotting elevation profiles # self.outsegs[per] = all_outsegs # # use graph instead of above loop nrow = len(self.segment_data[per].nseg) ncol = np.max( [len(v) if v is not None else 0 for v in self.paths.values()] ) all_outsegs = np.zeros((nrow, ncol), dtype=int) for i, (k, v) in enumerate(self.paths.items()): if k > 0: all_outsegs[i, : len(v)] = v all_outsegs.sort(axis=0) self.outsegs[per] = all_outsegs # create a dictionary listing outlets associated with each segment # outlet is the last value in each row of outseg array that is != 0 or 999999 # self.outlets[per] = {i + 1: r[(r != 0) & (r != 999999)][-1] # if len(r[(r != 0) & (r != 999999)]) > 0 # else i + 1 # for i, r in enumerate(all_outsegs.T)} self.outlets[per] = { k: self.paths[k][-1] if k in self.paths else k for k in self.segment_data[per].nseg } return txt
[ "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, fill_mode="constant", ), )
[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]. Defaults to 32. seed (int, optional): [description]. Defaults to 0. data_gen_args ([type], optional): [description]. Defaults to 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,fill_mode="constant",). Returns: [type]: [description]
[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]. Defaults to 32. seed (int, optional): [description]. Defaults to 0. data_gen_args ([type], optional): [description]. Defaults to 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,fill_mode="constant",). Returns: [type]: [description]
[ "[", "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, vertical_flip=False, fill_mode="constant", ), ): """[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]. Defaults to 32. seed (int, optional): [description]. Defaults to 0. data_gen_args ([type], optional): [description]. Defaults to 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,fill_mode="constant",). Returns: [type]: [description] """ # Train data, provide the same seed and keyword arguments to the fit and flow methods X_datagen = ImageDataGenerator(**data_gen_args) Y_datagen = ImageDataGenerator(**data_gen_args) X_datagen.fit(X_train, augment=True, seed=seed) Y_datagen.fit(Y_train, augment=True, seed=seed) X_train_augmented = X_datagen.flow( X_train, batch_size=batch_size, shuffle=True, seed=seed ) Y_train_augmented = Y_datagen.flow( Y_train, batch_size=batch_size, shuffle=True, seed=seed ) train_generator = zip(X_train_augmented, Y_train_augmented) if not (X_val is None) and not (Y_val is None): # Validation data, no data augmentation, but we create a generator anyway X_datagen_val = ImageDataGenerator(**data_gen_args) Y_datagen_val = ImageDataGenerator(**data_gen_args) X_datagen_val.fit(X_val, augment=False, seed=seed) Y_datagen_val.fit(Y_val, augment=False, seed=seed) X_val_augmented = X_datagen_val.flow( X_val, batch_size=batch_size, shuffle=False, seed=seed ) Y_val_augmented = Y_datagen_val.flow( Y_val, batch_size=batch_size, shuffle=False, seed=seed ) # combine generators into one which yields image and masks val_generator = zip(X_val_augmented, Y_val_augmented) return train_generator, val_generator else: return train_generator
[ "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: the config block :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: the config block :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", "."...
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_data: the data container for the working model :param config: the config block :return: ''' second_stage_variables = model_data.working_model.util.second_stage_variables first_stage_variables = model_data.working_model.util.first_stage_variables uncertain_params = model_data.working_model.util.uncertain_params decision_rule_vars = [] degree = config.decision_rule_order bounds = (None, None) if degree == 0: for i in range(len(second_stage_variables)): model_data.working_model.add_component("decision_rule_var_" + str(i), Var(initialize=value(second_stage_variables[i]),bounds=bounds,domain=Reals))#bounds=(second_stage_variables[i].lb, second_stage_variables[i].ub))) first_stage_variables.extend(getattr(model_data.working_model, "decision_rule_var_" + str(i)).values()) decision_rule_vars.append(getattr(model_data.working_model, "decision_rule_var_" + str(i))) elif degree == 1: for i in range(len(second_stage_variables)): index_set = list(range(len(uncertain_params) + 1)) model_data.working_model.add_component("decision_rule_var_" + str(i), Var(index_set, initialize=0, bounds=bounds, domain=Reals))#bounds=(second_stage_variables[i].lb, second_stage_variables[i].ub))) # === For affine drs, the [0]th constant term is initialized to the control variable values, all other terms are initialized to 0 getattr(model_data.working_model, "decision_rule_var_" + str(i))[0].set_value(value(second_stage_variables[i]), skip_validation=True) first_stage_variables.extend(list(getattr(model_data.working_model, "decision_rule_var_" + str(i)).values())) decision_rule_vars.append(getattr(model_data.working_model, "decision_rule_var_" + str(i))) elif degree == 2 or degree == 3 or degree == 4: for i in range(len(second_stage_variables)): num_vars = int(sp.special.comb(N=len(uncertain_params) + degree, k=degree)) dict_init = {} for r in range(num_vars): if r == 0: dict_init.update({r: value(second_stage_variables[i])}) else: dict_init.update({r: 0}) model_data.working_model.add_component("decision_rule_var_" + str(i), Var(list(range(num_vars)), initialize=dict_init, bounds=bounds, domain=Reals)) first_stage_variables.extend( list(getattr(model_data.working_model, "decision_rule_var_" + str(i)).values())) decision_rule_vars.append(getattr(model_data.working_model, "decision_rule_var_" + str(i))) else: raise ValueError( "Decision rule order " + str(config.decision_rule_order) + " is not yet supported. PyROS supports polynomials of degree 0 (static approximation), 1, 2.") model_data.working_model.util.decision_rule_vars = decision_rule_vars return
[ "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 to publish :type container: zds.tutorialv2.models.versioned.Container :param part_path: the relative path of the part to publish as html file :type part_path: pathlib.Path :param parsed: the html code :param path_to_title_dict: dictionary to write the data, usefull when dealing with epub.
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_callback: callable :param base_dir: the directory into wich we will write the file :param container: the container to publish :type container: zds.tutorialv2.models.versioned.Container :param part_path: the relative path of the part to publish as html file :type part_path: pathlib.Path :param parsed: the html code :param path_to_title_dict: dictionary to write the data, usefull when dealing with epub. """ full_path = Path(base_dir, part_path) if image_callback: parsed = image_callback(parsed) if not full_path.parent.exists(): with contextlib.suppress(OSError): full_path.parent.mkdir(parents=True) with full_path.open("w", encoding="utf-8") as chapter_file: try: chapter_file.write(parsed) except (UnicodeError, UnicodeEncodeError): from zds.tutorialv2.publication_utils import FailureDuringPublication raise FailureDuringPublication( _("Une erreur est survenue durant la publication de « {} », vérifiez le code markdown").format( container.title ) ) # fix duplicate of introduction and conclusion in ebook ids if part_path.name.startswith("conclusion.") or part_path.name.startswith("introduction."): path_to_title_dict[str(part_path)] = part_path.name.split(".")[0] + "_" + container.title else: path_to_title_dict[str(part_path)] = container.title
[ "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-8") data = await self.conn.get(stored_key) if data is None: return Session(None, data=None, new=True, max_age=self.max_age) data = data.decode("utf-8") try: data = self._decoder(data) except ValueError: data = None return Session(key, data=data, new=False, max_age=self.max_age)
[ "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 master to use. task: The task id of this training instance. num_clones: The number of clones to run per machine. worker_replicas: The number of work replicas to train with. clone_on_cpu: True if clones should be forced to run on CPU. ps_tasks: Number of parameter server tasks. worker_job_name: Name of the worker job. is_chief: Whether this replica is the chief replica. train_dir: Directory to write checkpoints and training summaries to. graph_hook_fn: Optional function that is called after the training graph is completely built. This is helpful to perform additional changes to the training graph such as optimizing batchnorm. The function should modify the default graph.
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): """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 master to use. task: The task id of this training instance. num_clones: The number of clones to run per machine. worker_replicas: The number of work replicas to train with. clone_on_cpu: True if clones should be forced to run on CPU. ps_tasks: Number of parameter server tasks. worker_job_name: Name of the worker job. is_chief: Whether this replica is the chief replica. train_dir: Directory to write checkpoints and training summaries to. graph_hook_fn: Optional function that is called after the training graph is completely built. This is helpful to perform additional changes to the training graph such as optimizing batchnorm. The function should modify the default graph. """ detection_model = create_model_fn() with tf.Graph().as_default(): # Build a configuration specifying multi-GPU and multi-replicas. deploy_config = model_deploy.DeploymentConfig( num_clones=num_clones, clone_on_cpu=clone_on_cpu, replica_id=task, num_replicas=worker_replicas, num_ps_tasks=ps_tasks, worker_job_name=worker_job_name) # Place the global step on the device storing the variables. with tf.device(deploy_config.variables_device()): global_step = slim.create_global_step() with tf.device(deploy_config.inputs_device()): input_queue = create_input_queue(create_tensor_dict_fn) # Gather initial summaries. # TODO(rathodv): See if summaries can be added/extracted from global tf # collections so that they don't have to be passed around. summaries = set(tf.get_collection(tf.GraphKeys.SUMMARIES)) global_summaries = set([]) model_fn = functools.partial( _create_losses, create_model_fn=create_model_fn, train_config=train_config) clones = model_deploy.create_clones(deploy_config, model_fn, [input_queue]) first_clone_scope = clones[0].scope # Gather update_ops from the first clone. These contain, for example, # the updates for the batch_norm variables created by model_fn. update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, first_clone_scope) with tf.device(deploy_config.optimizer_device()): training_optimizer, optimizer_summary_vars = optimizer_builder.build( train_config.optimizer) for var in optimizer_summary_vars: tf.summary.scalar(var.op.name, var) sync_optimizer = None if train_config.sync_replicas: training_optimizer = tf.train.SyncReplicasOptimizer( training_optimizer, replicas_to_aggregate=train_config.replicas_to_aggregate, total_num_replicas=train_config.worker_replicas) sync_optimizer = training_optimizer # Create ops required to initialize the model from a given checkpoint. init_fn = None if train_config.fine_tune_checkpoint: restore_checkpoints = [ path.strip() for path in train_config.fine_tune_checkpoint.split(',') ] restorers = get_restore_checkpoint_ops(restore_checkpoints, detection_model, train_config) def initializer_fn(sess): for i, restorer in enumerate(restorers): restorer.restore(sess, restore_checkpoints[i]) init_fn = initializer_fn with tf.device(deploy_config.optimizer_device()): regularization_losses = ( None if train_config.add_regularization_loss else []) total_loss, grads_and_vars = model_deploy.optimize_clones( clones, training_optimizer, regularization_losses=regularization_losses) total_loss = tf.check_numerics(total_loss, 'LossTensor is inf or nan.') # Optionally multiply bias gradients by train_config.bias_grad_multiplier. if train_config.bias_grad_multiplier: biases_regex_list = ['.*/biases'] grads_and_vars = variables_helper.multiply_gradients_matching_regex( grads_and_vars, biases_regex_list, multiplier=train_config.bias_grad_multiplier) # Optionally clip gradients if train_config.gradient_clipping_by_norm > 0: with tf.name_scope('clip_grads'): grads_and_vars = slim.learning.clip_gradient_norms( grads_and_vars, train_config.gradient_clipping_by_norm) moving_average_variables = slim.get_model_variables() variable_averages = tf.train.ExponentialMovingAverage(0.9999, global_step) update_ops.append(variable_averages.apply(moving_average_variables)) # Create gradient updates. grad_updates = training_optimizer.apply_gradients( grads_and_vars, global_step=global_step) update_ops.append(grad_updates) update_op = tf.group(*update_ops, name='update_barrier') with tf.control_dependencies([update_op]): train_tensor = tf.identity(total_loss, name='train_op') if graph_hook_fn: with tf.device(deploy_config.variables_device()): graph_hook_fn() # Add summaries. for model_var in slim.get_model_variables(): global_summaries.add(tf.summary.histogram(model_var.op.name, model_var)) for loss_tensor in tf.losses.get_losses(): global_summaries.add(tf.summary.scalar(loss_tensor.op.name, loss_tensor)) global_summaries.add( tf.summary.scalar('TotalLoss', tf.losses.get_total_loss())) # Add the summaries from the first clone. These contain the summaries # created by model_fn and either optimize_clones() or _gather_clone_loss(). summaries |= set( tf.get_collection(tf.GraphKeys.SUMMARIES, first_clone_scope)) summaries |= set(tf.get_collection(tf.GraphKeys.SUMMARIES, 'critic_loss')) summaries |= global_summaries # Merge all summaries together. summary_op = tf.summary.merge(list(summaries), name='summary_op') # Soft placement allows placing on CPU ops without GPU implementation. session_config = tf.ConfigProto( allow_soft_placement=True, log_device_placement=False) # Save checkpoints regularly. keep_checkpoint_every_n_hours = train_config.keep_checkpoint_every_n_hours saver = tf.train.Saver( keep_checkpoint_every_n_hours=keep_checkpoint_every_n_hours) slim.learning.train( train_tensor, logdir=train_dir, master=master, is_chief=is_chief, session_config=session_config, startup_delay_steps=train_config.startup_delay_steps, init_fn=init_fn, summary_op=summary_op, number_of_steps=(train_config.num_steps if train_config.num_steps else None), save_summaries_secs=120, sync_optimizer=sync_optimizer, saver=saver)
[ "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["B"]) self._create_cash_moves() self.recompute() report.partner_record_ids.calculate_quarter_totals() return True
[ "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: If True, displays a progress bar of the download to stderr """ assert not pretrained or num_classes == 400, "pretrained on 400 classes" return r2plus1d_34(num_classes=num_classes, arch="r2plus1d_34_32_kinetics", pretrained=pretrained, progress=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* predefined dictionary " "for compressing pin objects with the " "DEFLATE algorithm. Takes in a file of " "commonly occuring substrings and their " "frequencies. " "Common substring occurances are scored " "from the product of length of substring " "and the frequency with which it occurs. " "Fully contained substrings are swallowed " "and the top scoring strings are " "concatenated up to SIZE bytes.") parser.add_argument('freqs_file', action='store', help="File of commonly occuring substrings. Reads in " "json with substring keys and frequency values") parser.add_argument('--size', action='store', type=int, default=DEFAULT_ZDICT_SIZE, help='Size of predefined dictionary to generate') return parser.parse_args()
[ "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