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
errbotio/errbot
66e1de8e1d7daa62be7f9ed1b2ac8832f09fa25d
errbot/templates/initdir/example.py
python
Example.tryme
(self, msg, args)
return "It *works*!"
Execute to check if Errbot responds to command. Feel free to tweak me to experiment with Errbot. You can find me in your init directory in the subdirectory plugins.
Execute to check if Errbot responds to command. Feel free to tweak me to experiment with Errbot. You can find me in your init directory in the subdirectory plugins.
[ "Execute", "to", "check", "if", "Errbot", "responds", "to", "command", ".", "Feel", "free", "to", "tweak", "me", "to", "experiment", "with", "Errbot", ".", "You", "can", "find", "me", "in", "your", "init", "directory", "in", "the", "subdirectory", "plugins", "." ]
def tryme(self, msg, args): # a command callable with !tryme """ Execute to check if Errbot responds to command. Feel free to tweak me to experiment with Errbot. You can find me in your init directory in the subdirectory plugins. """ return "It *works*!"
[ "def", "tryme", "(", "self", ",", "msg", ",", "args", ")", ":", "# a command callable with !tryme", "return", "\"It *works*!\"" ]
https://github.com/errbotio/errbot/blob/66e1de8e1d7daa62be7f9ed1b2ac8832f09fa25d/errbot/templates/initdir/example.py#L12-L18
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/zipfile.py
python
LZMACompressor.__init__
(self)
[]
def __init__(self): self._comp = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "_comp", "=", "None" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/zipfile.py#L594-L595
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
openedx/core/djangoapps/courseware_api/views.py
python
CoursewareInformation.set_last_seen_courseware_timezone
(self, user)
The timezone in the user's account is frequently not set. This method sets a user's recent timezone that can be used as a fallback
The timezone in the user's account is frequently not set. This method sets a user's recent timezone that can be used as a fallback
[ "The", "timezone", "in", "the", "user", "s", "account", "is", "frequently", "not", "set", ".", "This", "method", "sets", "a", "user", "s", "recent", "timezone", "that", "can", "be", "used", "as", "a", "fallback" ]
def set_last_seen_courseware_timezone(self, user): """ The timezone in the user's account is frequently not set. This method sets a user's recent timezone that can be used as a fallback """ if not user.id: return cache_key = 'browser_timezone_{}'.format(str(user.id)) browser_timezone = self.request.query_params.get('browser_timezone', None) cached_value = TieredCache.get_cached_response(cache_key) if not cached_value.is_found: if browser_timezone: TieredCache.set_all_tiers(cache_key, str(browser_timezone), 86400) # Refresh the cache daily LastSeenCoursewareTimezone.objects.update_or_create( user=user, defaults={'last_seen_courseware_timezone': browser_timezone}, )
[ "def", "set_last_seen_courseware_timezone", "(", "self", ",", "user", ")", ":", "if", "not", "user", ".", "id", ":", "return", "cache_key", "=", "'browser_timezone_{}'", ".", "format", "(", "str", "(", "user", ".", "id", ")", ")", "browser_timezone", "=", "self", ".", "request", ".", "query_params", ".", "get", "(", "'browser_timezone'", ",", "None", ")", "cached_value", "=", "TieredCache", ".", "get_cached_response", "(", "cache_key", ")", "if", "not", "cached_value", ".", "is_found", ":", "if", "browser_timezone", ":", "TieredCache", ".", "set_all_tiers", "(", "cache_key", ",", "str", "(", "browser_timezone", ")", ",", "86400", ")", "# Refresh the cache daily", "LastSeenCoursewareTimezone", ".", "objects", ".", "update_or_create", "(", "user", "=", "user", ",", "defaults", "=", "{", "'last_seen_courseware_timezone'", ":", "browser_timezone", "}", ",", ")" ]
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/openedx/core/djangoapps/courseware_api/views.py#L497-L514
rushter/MLAlgorithms
3c8e16b8de3baf131395ae57edd479e59566a7c6
mla/neuralnet/layers/convnet.py
python
Convolution.shape
(self, x_shape)
return x_shape[0], self.n_filters, height, width
[]
def shape(self, x_shape): height, width = convoltuion_shape(self.height, self.width, self.filter_shape, self.stride, self.padding) return x_shape[0], self.n_filters, height, width
[ "def", "shape", "(", "self", ",", "x_shape", ")", ":", "height", ",", "width", "=", "convoltuion_shape", "(", "self", ".", "height", ",", "self", ".", "width", ",", "self", ".", "filter_shape", ",", "self", ".", "stride", ",", "self", ".", "padding", ")", "return", "x_shape", "[", "0", "]", ",", "self", ".", "n_filters", ",", "height", ",", "width" ]
https://github.com/rushter/MLAlgorithms/blob/3c8e16b8de3baf131395ae57edd479e59566a7c6/mla/neuralnet/layers/convnet.py#L62-L64
chengzhengxin/groupsoftmax-simpledet
3f63a00998c57fee25241cf43a2e8600893ea462
symbol/builder.py
python
BboxHead.get_prediction
(self, conv_feat, im_info, proposal)
return cls_score, bbox_xyxy
[]
def get_prediction(self, conv_feat, im_info, proposal): p = self.p bbox_mean = p.regress_target.mean bbox_std = p.regress_target.std batch_image = p.batch_image num_class = p.num_class class_agnostic = p.regress_target.class_agnostic num_reg_class = 2 if class_agnostic else num_class cls_logit, bbox_delta = self.get_output(conv_feat) bbox_delta = X.reshape( bbox_delta, shape=(batch_image, -1, 4 * num_reg_class), name='bbox_delta_reshape' ) bbox_xyxy = X.decode_bbox( rois=proposal, bbox_pred=bbox_delta, im_info=im_info, name='decode_bbox', bbox_mean=bbox_mean, bbox_std=bbox_std, class_agnostic=class_agnostic ) cls_score = X.softmax( cls_logit, axis=-1, name='bbox_cls_score' ) cls_score = X.reshape( cls_score, shape=(batch_image, -1, num_class), name='bbox_cls_score_reshape' ) return cls_score, bbox_xyxy
[ "def", "get_prediction", "(", "self", ",", "conv_feat", ",", "im_info", ",", "proposal", ")", ":", "p", "=", "self", ".", "p", "bbox_mean", "=", "p", ".", "regress_target", ".", "mean", "bbox_std", "=", "p", ".", "regress_target", ".", "std", "batch_image", "=", "p", ".", "batch_image", "num_class", "=", "p", ".", "num_class", "class_agnostic", "=", "p", ".", "regress_target", ".", "class_agnostic", "num_reg_class", "=", "2", "if", "class_agnostic", "else", "num_class", "cls_logit", ",", "bbox_delta", "=", "self", ".", "get_output", "(", "conv_feat", ")", "bbox_delta", "=", "X", ".", "reshape", "(", "bbox_delta", ",", "shape", "=", "(", "batch_image", ",", "-", "1", ",", "4", "*", "num_reg_class", ")", ",", "name", "=", "'bbox_delta_reshape'", ")", "bbox_xyxy", "=", "X", ".", "decode_bbox", "(", "rois", "=", "proposal", ",", "bbox_pred", "=", "bbox_delta", ",", "im_info", "=", "im_info", ",", "name", "=", "'decode_bbox'", ",", "bbox_mean", "=", "bbox_mean", ",", "bbox_std", "=", "bbox_std", ",", "class_agnostic", "=", "class_agnostic", ")", "cls_score", "=", "X", ".", "softmax", "(", "cls_logit", ",", "axis", "=", "-", "1", ",", "name", "=", "'bbox_cls_score'", ")", "cls_score", "=", "X", ".", "reshape", "(", "cls_score", ",", "shape", "=", "(", "batch_image", ",", "-", "1", ",", "num_class", ")", ",", "name", "=", "'bbox_cls_score_reshape'", ")", "return", "cls_score", ",", "bbox_xyxy" ]
https://github.com/chengzhengxin/groupsoftmax-simpledet/blob/3f63a00998c57fee25241cf43a2e8600893ea462/symbol/builder.py#L394-L430
gpodder/mygpo
7a028ad621d05d4ca0d58fd22fb92656c8835e43
mygpo/podcasts/models.py
python
Episode.get_episode_number
(self, common_title)
return int(match.group(1))
Number of the episode
Number of the episode
[ "Number", "of", "the", "episode" ]
def get_episode_number(self, common_title): """Number of the episode""" if not self.title or not common_title: return None title = self.title.replace(common_title, "").strip() match = re.search(r"^\W*(\d+)", title) if not match: return None return int(match.group(1))
[ "def", "get_episode_number", "(", "self", ",", "common_title", ")", ":", "if", "not", "self", ".", "title", "or", "not", "common_title", ":", "return", "None", "title", "=", "self", ".", "title", ".", "replace", "(", "common_title", ",", "\"\"", ")", ".", "strip", "(", ")", "match", "=", "re", ".", "search", "(", "r\"^\\W*(\\d+)\"", ",", "title", ")", "if", "not", "match", ":", "return", "None", "return", "int", "(", "match", ".", "group", "(", "1", ")", ")" ]
https://github.com/gpodder/mygpo/blob/7a028ad621d05d4ca0d58fd22fb92656c8835e43/mygpo/podcasts/models.py#L852-L862
google/macops
8442745359c0c941cd4e4e7d243e43bd16b40dec
gmacpyutil/gmacpyutil/airport.py
python
GetDefaultInterface
()
return CWInterface.interface()
Returns the default Wi-Fi interface.
Returns the default Wi-Fi interface.
[ "Returns", "the", "default", "Wi", "-", "Fi", "interface", "." ]
def GetDefaultInterface(): """Returns the default Wi-Fi interface.""" return CWInterface.interface()
[ "def", "GetDefaultInterface", "(", ")", ":", "return", "CWInterface", ".", "interface", "(", ")" ]
https://github.com/google/macops/blob/8442745359c0c941cd4e4e7d243e43bd16b40dec/gmacpyutil/gmacpyutil/airport.py#L48-L50
openai/baselines
ea25b9e8b234e6ee1bca43083f8f3cf974143998
baselines/her/ddpg.py
python
DDPG.store_episode
(self, episode_batch, update_stats=True)
episode_batch: array of batch_size x (T or T+1) x dim_key 'o' is of size T+1, others are of size T
episode_batch: array of batch_size x (T or T+1) x dim_key 'o' is of size T+1, others are of size T
[ "episode_batch", ":", "array", "of", "batch_size", "x", "(", "T", "or", "T", "+", "1", ")", "x", "dim_key", "o", "is", "of", "size", "T", "+", "1", "others", "are", "of", "size", "T" ]
def store_episode(self, episode_batch, update_stats=True): """ episode_batch: array of batch_size x (T or T+1) x dim_key 'o' is of size T+1, others are of size T """ self.buffer.store_episode(episode_batch) if update_stats: # add transitions to normalizer episode_batch['o_2'] = episode_batch['o'][:, 1:, :] episode_batch['ag_2'] = episode_batch['ag'][:, 1:, :] num_normalizing_transitions = transitions_in_episode_batch(episode_batch) transitions = self.sample_transitions(episode_batch, num_normalizing_transitions) o, g, ag = transitions['o'], transitions['g'], transitions['ag'] transitions['o'], transitions['g'] = self._preprocess_og(o, ag, g) # No need to preprocess the o_2 and g_2 since this is only used for stats self.o_stats.update(transitions['o']) self.g_stats.update(transitions['g']) self.o_stats.recompute_stats() self.g_stats.recompute_stats()
[ "def", "store_episode", "(", "self", ",", "episode_batch", ",", "update_stats", "=", "True", ")", ":", "self", ".", "buffer", ".", "store_episode", "(", "episode_batch", ")", "if", "update_stats", ":", "# add transitions to normalizer", "episode_batch", "[", "'o_2'", "]", "=", "episode_batch", "[", "'o'", "]", "[", ":", ",", "1", ":", ",", ":", "]", "episode_batch", "[", "'ag_2'", "]", "=", "episode_batch", "[", "'ag'", "]", "[", ":", ",", "1", ":", ",", ":", "]", "num_normalizing_transitions", "=", "transitions_in_episode_batch", "(", "episode_batch", ")", "transitions", "=", "self", ".", "sample_transitions", "(", "episode_batch", ",", "num_normalizing_transitions", ")", "o", ",", "g", ",", "ag", "=", "transitions", "[", "'o'", "]", ",", "transitions", "[", "'g'", "]", ",", "transitions", "[", "'ag'", "]", "transitions", "[", "'o'", "]", ",", "transitions", "[", "'g'", "]", "=", "self", ".", "_preprocess_og", "(", "o", ",", "ag", ",", "g", ")", "# No need to preprocess the o_2 and g_2 since this is only used for stats", "self", ".", "o_stats", ".", "update", "(", "transitions", "[", "'o'", "]", ")", "self", ".", "g_stats", ".", "update", "(", "transitions", "[", "'g'", "]", ")", "self", ".", "o_stats", ".", "recompute_stats", "(", ")", "self", ".", "g_stats", ".", "recompute_stats", "(", ")" ]
https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/her/ddpg.py#L217-L240
tribe29/checkmk
6260f2512e159e311f426e16b84b19d0b8e9ad0c
cmk/base/ip_lookup.py
python
IPLookupCache.__setitem__
(self, cache_id: IPLookupCacheId, ipa: HostAddress)
Updates the cache with a new / changed entry When self.persist_on_update update is disabled, this simply updates the in-memory cache without any persistence interaction. Otherwise: The cache that was previously loaded into this IPLookupCache with load_persisted() might be outdated compared to the current persisted lookup cache. Another process might have updated the cache in the meantime. The approach here is to load the currently persisted cache with a lock, then update the current IPLookupCache with it, add the given new / changed entry and then write out the resulting data structure. This could really be solved in a better way, but may be sufficient for the moment. The cache can only be cleaned up with the "Update DNS cache" option in WATO or the "cmk --update-dns-cache" call that both call update_dns_cache().
Updates the cache with a new / changed entry
[ "Updates", "the", "cache", "with", "a", "new", "/", "changed", "entry" ]
def __setitem__(self, cache_id: IPLookupCacheId, ipa: HostAddress) -> None: """Updates the cache with a new / changed entry When self.persist_on_update update is disabled, this simply updates the in-memory cache without any persistence interaction. Otherwise: The cache that was previously loaded into this IPLookupCache with load_persisted() might be outdated compared to the current persisted lookup cache. Another process might have updated the cache in the meantime. The approach here is to load the currently persisted cache with a lock, then update the current IPLookupCache with it, add the given new / changed entry and then write out the resulting data structure. This could really be solved in a better way, but may be sufficient for the moment. The cache can only be cleaned up with the "Update DNS cache" option in WATO or the "cmk --update-dns-cache" call that both call update_dns_cache(). """ if not self._persist_on_update: self._cache[cache_id] = ipa return with self._store.locked(): self._cache.update(self._store.read_obj(default={})) self._cache[cache_id] = ipa self.save_persisted()
[ "def", "__setitem__", "(", "self", ",", "cache_id", ":", "IPLookupCacheId", ",", "ipa", ":", "HostAddress", ")", "->", "None", ":", "if", "not", "self", ".", "_persist_on_update", ":", "self", ".", "_cache", "[", "cache_id", "]", "=", "ipa", "return", "with", "self", ".", "_store", ".", "locked", "(", ")", ":", "self", ".", "_cache", ".", "update", "(", "self", ".", "_store", ".", "read_obj", "(", "default", "=", "{", "}", ")", ")", "self", ".", "_cache", "[", "cache_id", "]", "=", "ipa", "self", ".", "save_persisted", "(", ")" ]
https://github.com/tribe29/checkmk/blob/6260f2512e159e311f426e16b84b19d0b8e9ad0c/cmk/base/ip_lookup.py#L287-L313
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/pkg_resources/_vendor/pyparsing.py
python
ParseResults.pop
( self, *args, **kwargs)
Removes and returns item at specified index (default=C{last}). Supports both C{list} and C{dict} semantics for C{pop()}. If passed no argument or an integer argument, it will use C{list} semantics and pop tokens from the list of parsed tokens. If passed a non-integer argument (most likely a string), it will use C{dict} semantics and pop the corresponding value from any defined results names. A second default return value argument is supported, just as in C{dict.pop()}. Example:: def remove_first(tokens): tokens.pop(0) print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321'] label = Word(alphas) patt = label("LABEL") + OneOrMore(Word(nums)) print(patt.parseString("AAB 123 321").dump()) # Use pop() in a parse action to remove named result (note that corresponding value is not # removed from list form of results) def remove_LABEL(tokens): tokens.pop("LABEL") return tokens patt.addParseAction(remove_LABEL) print(patt.parseString("AAB 123 321").dump()) prints:: ['AAB', '123', '321'] - LABEL: AAB ['AAB', '123', '321']
Removes and returns item at specified index (default=C{last}). Supports both C{list} and C{dict} semantics for C{pop()}. If passed no argument or an integer argument, it will use C{list} semantics and pop tokens from the list of parsed tokens. If passed a non-integer argument (most likely a string), it will use C{dict} semantics and pop the corresponding value from any defined results names. A second default return value argument is supported, just as in C{dict.pop()}.
[ "Removes", "and", "returns", "item", "at", "specified", "index", "(", "default", "=", "C", "{", "last", "}", ")", ".", "Supports", "both", "C", "{", "list", "}", "and", "C", "{", "dict", "}", "semantics", "for", "C", "{", "pop", "()", "}", ".", "If", "passed", "no", "argument", "or", "an", "integer", "argument", "it", "will", "use", "C", "{", "list", "}", "semantics", "and", "pop", "tokens", "from", "the", "list", "of", "parsed", "tokens", ".", "If", "passed", "a", "non", "-", "integer", "argument", "(", "most", "likely", "a", "string", ")", "it", "will", "use", "C", "{", "dict", "}", "semantics", "and", "pop", "the", "corresponding", "value", "from", "any", "defined", "results", "names", ".", "A", "second", "default", "return", "value", "argument", "is", "supported", "just", "as", "in", "C", "{", "dict", ".", "pop", "()", "}", "." ]
def pop( self, *args, **kwargs): """ Removes and returns item at specified index (default=C{last}). Supports both C{list} and C{dict} semantics for C{pop()}. If passed no argument or an integer argument, it will use C{list} semantics and pop tokens from the list of parsed tokens. If passed a non-integer argument (most likely a string), it will use C{dict} semantics and pop the corresponding value from any defined results names. A second default return value argument is supported, just as in C{dict.pop()}. Example:: def remove_first(tokens): tokens.pop(0) print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321'] label = Word(alphas) patt = label("LABEL") + OneOrMore(Word(nums)) print(patt.parseString("AAB 123 321").dump()) # Use pop() in a parse action to remove named result (note that corresponding value is not # removed from list form of results) def remove_LABEL(tokens): tokens.pop("LABEL") return tokens patt.addParseAction(remove_LABEL) print(patt.parseString("AAB 123 321").dump()) prints:: ['AAB', '123', '321'] - LABEL: AAB ['AAB', '123', '321'] """ if not args: args = [-1] for k,v in kwargs.items(): if k == 'default': args = (args[0], v) else: raise TypeError("pop() got an unexpected keyword argument '%s'" % k) if (isinstance(args[0], int) or len(args) == 1 or args[0] in self): index = args[0] ret = self[index] del self[index] return ret else: defaultvalue = args[1] return defaultvalue
[ "def", "pop", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "args", ":", "args", "=", "[", "-", "1", "]", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "if", "k", "==", "'default'", ":", "args", "=", "(", "args", "[", "0", "]", ",", "v", ")", "else", ":", "raise", "TypeError", "(", "\"pop() got an unexpected keyword argument '%s'\"", "%", "k", ")", "if", "(", "isinstance", "(", "args", "[", "0", "]", ",", "int", ")", "or", "len", "(", "args", ")", "==", "1", "or", "args", "[", "0", "]", "in", "self", ")", ":", "index", "=", "args", "[", "0", "]", "ret", "=", "self", "[", "index", "]", "del", "self", "[", "index", "]", "return", "ret", "else", ":", "defaultvalue", "=", "args", "[", "1", "]", "return", "defaultvalue" ]
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/pkg_resources/_vendor/pyparsing.py#L488-L538
francisck/DanderSpritz_docs
86bb7caca5a957147f120b18bb5c31f299914904
Python/Core/Lib/lib-tk/Tkinter.py
python
Misc.winfo_atom
(self, name, displayof=0)
return getint(self.tk.call(args))
Return integer which represents atom NAME.
Return integer which represents atom NAME.
[ "Return", "integer", "which", "represents", "atom", "NAME", "." ]
def winfo_atom(self, name, displayof=0): """Return integer which represents atom NAME.""" args = ('winfo', 'atom') + self._displayof(displayof) + (name,) return getint(self.tk.call(args))
[ "def", "winfo_atom", "(", "self", ",", "name", ",", "displayof", "=", "0", ")", ":", "args", "=", "(", "'winfo'", ",", "'atom'", ")", "+", "self", ".", "_displayof", "(", "displayof", ")", "+", "(", "name", ",", ")", "return", "getint", "(", "self", ".", "tk", ".", "call", "(", "args", ")", ")" ]
https://github.com/francisck/DanderSpritz_docs/blob/86bb7caca5a957147f120b18bb5c31f299914904/Python/Core/Lib/lib-tk/Tkinter.py#L767-L770
pyg-team/pytorch_geometric
b920e9a3a64e22c8356be55301c88444ff051cae
torch_geometric/datasets/hgb_dataset.py
python
HGBDataset.download
(self)
[]
def download(self): url = self.url.format(self.names[self.name]) path = download_url(url, self.raw_dir) extract_zip(path, self.raw_dir) os.unlink(path)
[ "def", "download", "(", "self", ")", ":", "url", "=", "self", ".", "url", ".", "format", "(", "self", ".", "names", "[", "self", ".", "name", "]", ")", "path", "=", "download_url", "(", "url", ",", "self", ".", "raw_dir", ")", "extract_zip", "(", "path", ",", "self", ".", "raw_dir", ")", "os", ".", "unlink", "(", "path", ")" ]
https://github.com/pyg-team/pytorch_geometric/blob/b920e9a3a64e22c8356be55301c88444ff051cae/torch_geometric/datasets/hgb_dataset.py#L75-L79
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_vendor/six.py
python
_SixMetaPathImporter.load_module
(self, fullname)
return mod
[]
def load_module(self, fullname): try: # in case of a reload return sys.modules[fullname] except KeyError: pass mod = self.__get_module(fullname) if isinstance(mod, MovedModule): mod = mod._resolve() else: mod.__loader__ = self sys.modules[fullname] = mod return mod
[ "def", "load_module", "(", "self", ",", "fullname", ")", ":", "try", ":", "# in case of a reload", "return", "sys", ".", "modules", "[", "fullname", "]", "except", "KeyError", ":", "pass", "mod", "=", "self", ".", "__get_module", "(", "fullname", ")", "if", "isinstance", "(", "mod", ",", "MovedModule", ")", ":", "mod", "=", "mod", ".", "_resolve", "(", ")", "else", ":", "mod", ".", "__loader__", "=", "self", "sys", ".", "modules", "[", "fullname", "]", "=", "mod", "return", "mod" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_vendor/six.py#L195-L207
aimagelab/novelty-detection
553cab1757ba18048343929515f65e7c3ca8ff90
models/blocks_3d.py
python
residual_op
(x, functions, bns, activation_fn)
return activation_fn(out)
Implements a global residual operation. :param x: the input tensor. :param functions: a list of functions (nn.Modules). :param bns: a list of optional batch-norm layers. :param activation_fn: the activation to be applied. :return: the output of the residual operation.
Implements a global residual operation.
[ "Implements", "a", "global", "residual", "operation", "." ]
def residual_op(x, functions, bns, activation_fn): # type: (torch.Tensor, List[Module, Module, Module], List[Module, Module, Module], Module) -> torch.Tensor """ Implements a global residual operation. :param x: the input tensor. :param functions: a list of functions (nn.Modules). :param bns: a list of optional batch-norm layers. :param activation_fn: the activation to be applied. :return: the output of the residual operation. """ f1, f2, f3 = functions bn1, bn2, bn3 = bns assert len(functions) == len(bns) == 3 assert f1 is not None and f2 is not None assert not (f3 is None and bn3 is not None) # A-branch ha = x ha = f1(ha) if bn1 is not None: ha = bn1(ha) ha = activation_fn(ha) ha = f2(ha) if bn2 is not None: ha = bn2(ha) # B-branch hb = x if f3 is not None: hb = f3(hb) if bn3 is not None: hb = bn3(hb) # Residual connection out = ha + hb return activation_fn(out)
[ "def", "residual_op", "(", "x", ",", "functions", ",", "bns", ",", "activation_fn", ")", ":", "# type: (torch.Tensor, List[Module, Module, Module], List[Module, Module, Module], Module) -> torch.Tensor", "f1", ",", "f2", ",", "f3", "=", "functions", "bn1", ",", "bn2", ",", "bn3", "=", "bns", "assert", "len", "(", "functions", ")", "==", "len", "(", "bns", ")", "==", "3", "assert", "f1", "is", "not", "None", "and", "f2", "is", "not", "None", "assert", "not", "(", "f3", "is", "None", "and", "bn3", "is", "not", "None", ")", "# A-branch", "ha", "=", "x", "ha", "=", "f1", "(", "ha", ")", "if", "bn1", "is", "not", "None", ":", "ha", "=", "bn1", "(", "ha", ")", "ha", "=", "activation_fn", "(", "ha", ")", "ha", "=", "f2", "(", "ha", ")", "if", "bn2", "is", "not", "None", ":", "ha", "=", "bn2", "(", "ha", ")", "# B-branch", "hb", "=", "x", "if", "f3", "is", "not", "None", ":", "hb", "=", "f3", "(", "hb", ")", "if", "bn3", "is", "not", "None", ":", "hb", "=", "bn3", "(", "hb", ")", "# Residual connection", "out", "=", "ha", "+", "hb", "return", "activation_fn", "(", "out", ")" ]
https://github.com/aimagelab/novelty-detection/blob/553cab1757ba18048343929515f65e7c3ca8ff90/models/blocks_3d.py#L13-L51
mdiazcl/fuzzbunch-debian
2b76c2249ade83a389ae3badb12a1bd09901fd2c
windows/Resources/Python/Core/Lib/bsddb/dbtables.py
python
bsdTableDB.ListTableColumns
(self, table)
Return a list of columns in the given table. [] if the table doesn't exist.
Return a list of columns in the given table. [] if the table doesn't exist.
[ "Return", "a", "list", "of", "columns", "in", "the", "given", "table", ".", "[]", "if", "the", "table", "doesn", "t", "exist", "." ]
def ListTableColumns(self, table): """Return a list of columns in the given table. [] if the table doesn't exist. """ if contains_metastrings(table): raise ValueError, 'bad table name: contains reserved metastrings' columnlist_key = _columns_key(table) if not getattr(self.db, 'has_key')(columnlist_key): return [] else: pickledcolumnlist = getattr(self.db, 'get_bytes', self.db.get)(columnlist_key) if pickledcolumnlist: return pickle.loads(pickledcolumnlist) return []
[ "def", "ListTableColumns", "(", "self", ",", "table", ")", ":", "if", "contains_metastrings", "(", "table", ")", ":", "raise", "ValueError", ",", "'bad table name: contains reserved metastrings'", "columnlist_key", "=", "_columns_key", "(", "table", ")", "if", "not", "getattr", "(", "self", ".", "db", ",", "'has_key'", ")", "(", "columnlist_key", ")", ":", "return", "[", "]", "else", ":", "pickledcolumnlist", "=", "getattr", "(", "self", ".", "db", ",", "'get_bytes'", ",", "self", ".", "db", ".", "get", ")", "(", "columnlist_key", ")", "if", "pickledcolumnlist", ":", "return", "pickle", ".", "loads", "(", "pickledcolumnlist", ")", "return", "[", "]" ]
https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/bsddb/dbtables.py#L316-L329
lixinsu/RCZoo
37fcb7962fbd4c751c561d4a0c84173881ea8339
reader/fusionnet/model.py
python
DocReader.cuda
(self)
[]
def cuda(self): self.use_cuda = True self.network = self.network.cuda()
[ "def", "cuda", "(", "self", ")", ":", "self", ".", "use_cuda", "=", "True", "self", ".", "network", "=", "self", ".", "network", ".", "cuda", "(", ")" ]
https://github.com/lixinsu/RCZoo/blob/37fcb7962fbd4c751c561d4a0c84173881ea8339/reader/fusionnet/model.py#L487-L489
drckf/paysage
85ef951be2750e13c0b42121b40e530689bdc1f4
paysage/backends/pytorch_backend/rand.py
python
rand_softmax_units
(phi: T.FloatTensor)
return on_units
Draw random unit values according to softmax probabilities. Given an effective field vector v, the softmax probabilities are p = exp(v) / sum(exp(v)) The unit values (the on-units for a 1-hot encoding) are sampled according to p. Args: phi (tensor (batch_size, num_units)): the effective field Returns: tensor (batch_size,): random unit values from the softmax distribution.
Draw random unit values according to softmax probabilities.
[ "Draw", "random", "unit", "values", "according", "to", "softmax", "probabilities", "." ]
def rand_softmax_units(phi: T.FloatTensor) -> T.FloatTensor: """ Draw random unit values according to softmax probabilities. Given an effective field vector v, the softmax probabilities are p = exp(v) / sum(exp(v)) The unit values (the on-units for a 1-hot encoding) are sampled according to p. Args: phi (tensor (batch_size, num_units)): the effective field Returns: tensor (batch_size,): random unit values from the softmax distribution. """ max_index = matrix.shape(phi)[1]-1 probs = nl.softmax(phi) cum_probs = matrix.cumsum(probs, 1) ref_probs = rand((len(phi), 1)) on_units = matrix.tsum(matrix.cast_long(cum_probs < ref_probs), axis=1, keepdims=True) matrix.clip_(on_units, a_min=0, a_max=max_index) return on_units
[ "def", "rand_softmax_units", "(", "phi", ":", "T", ".", "FloatTensor", ")", "->", "T", ".", "FloatTensor", ":", "max_index", "=", "matrix", ".", "shape", "(", "phi", ")", "[", "1", "]", "-", "1", "probs", "=", "nl", ".", "softmax", "(", "phi", ")", "cum_probs", "=", "matrix", ".", "cumsum", "(", "probs", ",", "1", ")", "ref_probs", "=", "rand", "(", "(", "len", "(", "phi", ")", ",", "1", ")", ")", "on_units", "=", "matrix", ".", "tsum", "(", "matrix", ".", "cast_long", "(", "cum_probs", "<", "ref_probs", ")", ",", "axis", "=", "1", ",", "keepdims", "=", "True", ")", "matrix", ".", "clip_", "(", "on_units", ",", "a_min", "=", "0", ",", "a_max", "=", "max_index", ")", "return", "on_units" ]
https://github.com/drckf/paysage/blob/85ef951be2750e13c0b42121b40e530689bdc1f4/paysage/backends/pytorch_backend/rand.py#L145-L169
openseg-group/OCNet.pytorch
812cc57b560fe7fb3b3d9c80da5db80d1e83fbaa
eval.py
python
predict_whole_img
(net, image, classes, method, scale)
return result
Predict the whole image w/o using multiple crops. The scale specify whether rescale the input image before predicting the results.
Predict the whole image w/o using multiple crops. The scale specify whether rescale the input image before predicting the results.
[ "Predict", "the", "whole", "image", "w", "/", "o", "using", "multiple", "crops", ".", "The", "scale", "specify", "whether", "rescale", "the", "input", "image", "before", "predicting", "the", "results", "." ]
def predict_whole_img(net, image, classes, method, scale): """ Predict the whole image w/o using multiple crops. The scale specify whether rescale the input image before predicting the results. """ N_, C_, H_, W_ = image.shape if torch_ver == '0.4': interp = nn.Upsample(size=(H_, W_), mode='bilinear', align_corners=True) else: interp = nn.Upsample(size=(H_, W_), mode='bilinear') if scale != 1: scaled_img = ndimage.zoom(image, (1.0, 1.0, scale, scale), order=1, prefilter=False) else: scaled_img = image full_prediction_ = net(Variable(torch.from_numpy(scaled_img), volatile=True).cuda(), ) if 'dsn' in method or 'center' in method or 'fuse' in method: full_prediction = full_prediction_[-1] else: full_prediction = full_prediction_ if torch_ver == '0.4': full_prediction = F.upsample(input=full_prediction, size=(H_, W_), mode='bilinear', align_corners=True) else: full_prediction = F.upsample(input=full_prediction, size=(H_, W_), mode='bilinear') result = full_prediction.cpu().data.numpy().transpose(0,2,3,1) return result
[ "def", "predict_whole_img", "(", "net", ",", "image", ",", "classes", ",", "method", ",", "scale", ")", ":", "N_", ",", "C_", ",", "H_", ",", "W_", "=", "image", ".", "shape", "if", "torch_ver", "==", "'0.4'", ":", "interp", "=", "nn", ".", "Upsample", "(", "size", "=", "(", "H_", ",", "W_", ")", ",", "mode", "=", "'bilinear'", ",", "align_corners", "=", "True", ")", "else", ":", "interp", "=", "nn", ".", "Upsample", "(", "size", "=", "(", "H_", ",", "W_", ")", ",", "mode", "=", "'bilinear'", ")", "if", "scale", "!=", "1", ":", "scaled_img", "=", "ndimage", ".", "zoom", "(", "image", ",", "(", "1.0", ",", "1.0", ",", "scale", ",", "scale", ")", ",", "order", "=", "1", ",", "prefilter", "=", "False", ")", "else", ":", "scaled_img", "=", "image", "full_prediction_", "=", "net", "(", "Variable", "(", "torch", ".", "from_numpy", "(", "scaled_img", ")", ",", "volatile", "=", "True", ")", ".", "cuda", "(", ")", ",", ")", "if", "'dsn'", "in", "method", "or", "'center'", "in", "method", "or", "'fuse'", "in", "method", ":", "full_prediction", "=", "full_prediction_", "[", "-", "1", "]", "else", ":", "full_prediction", "=", "full_prediction_", "if", "torch_ver", "==", "'0.4'", ":", "full_prediction", "=", "F", ".", "upsample", "(", "input", "=", "full_prediction", ",", "size", "=", "(", "H_", ",", "W_", ")", ",", "mode", "=", "'bilinear'", ",", "align_corners", "=", "True", ")", "else", ":", "full_prediction", "=", "F", ".", "upsample", "(", "input", "=", "full_prediction", ",", "size", "=", "(", "H_", ",", "W_", ")", ",", "mode", "=", "'bilinear'", ")", "result", "=", "full_prediction", ".", "cpu", "(", ")", ".", "data", ".", "numpy", "(", ")", ".", "transpose", "(", "0", ",", "2", ",", "3", ",", "1", ")", "return", "result" ]
https://github.com/openseg-group/OCNet.pytorch/blob/812cc57b560fe7fb3b3d9c80da5db80d1e83fbaa/eval.py#L139-L165
sammchardy/python-binance
217f1e2205877f80dbaba6ee92354ce4aca74232
binance/client.py
python
Client.get_max_margin_loan
(self, **params)
return self._request_margin_api('get', 'margin/maxBorrowable', signed=True, data=params)
Query max borrow amount for an asset https://binance-docs.github.io/apidocs/spot/en/#query-max-borrow-user_data :param asset: required :type asset: str :param isolatedSymbol: isolated symbol (if querying isolated margin) :type isolatedSymbol: str :param recvWindow: the number of milliseconds the request is valid for :type recvWindow: int :returns: API response { "amount": "1.69248805" } :raises: BinanceRequestException, BinanceAPIException
Query max borrow amount for an asset
[ "Query", "max", "borrow", "amount", "for", "an", "asset" ]
def get_max_margin_loan(self, **params): """Query max borrow amount for an asset https://binance-docs.github.io/apidocs/spot/en/#query-max-borrow-user_data :param asset: required :type asset: str :param isolatedSymbol: isolated symbol (if querying isolated margin) :type isolatedSymbol: str :param recvWindow: the number of milliseconds the request is valid for :type recvWindow: int :returns: API response { "amount": "1.69248805" } :raises: BinanceRequestException, BinanceAPIException """ return self._request_margin_api('get', 'margin/maxBorrowable', signed=True, data=params)
[ "def", "get_max_margin_loan", "(", "self", ",", "*", "*", "params", ")", ":", "return", "self", ".", "_request_margin_api", "(", "'get'", ",", "'margin/maxBorrowable'", ",", "signed", "=", "True", ",", "data", "=", "params", ")" ]
https://github.com/sammchardy/python-binance/blob/217f1e2205877f80dbaba6ee92354ce4aca74232/binance/client.py#L4058-L4079
ljean/modbus-tk
1159c71794071ae67f73f86fa14dd71c989b4859
modbus_tk/simulator.py
python
CompositeServer.start
(self)
Start the server. It will handle request
Start the server. It will handle request
[ "Start", "the", "server", ".", "It", "will", "handle", "request" ]
def start(self): """Start the server. It will handle request""" for srv in self._servers: srv.start()
[ "def", "start", "(", "self", ")", ":", "for", "srv", "in", "self", ".", "_servers", ":", "srv", ".", "start", "(", ")" ]
https://github.com/ljean/modbus-tk/blob/1159c71794071ae67f73f86fa14dd71c989b4859/modbus_tk/simulator.py#L75-L78
open-cogsci/OpenSesame
c4a3641b097a80a76937edbd8c365f036bcc9705
opensesame_extensions/undo_manager/undo_manager.py
python
undo_manager.event_new_item
(self, name, _type)
desc: Remember addition of a new item.
desc: Remember addition of a new item.
[ "desc", ":", "Remember", "addition", "of", "a", "new", "item", "." ]
def event_new_item(self, name, _type): """ desc: Remember addition of a new item. """ self.remember_new_item(name)
[ "def", "event_new_item", "(", "self", ",", "name", ",", "_type", ")", ":", "self", ".", "remember_new_item", "(", "name", ")" ]
https://github.com/open-cogsci/OpenSesame/blob/c4a3641b097a80a76937edbd8c365f036bcc9705/opensesame_extensions/undo_manager/undo_manager.py#L70-L77
fatiando/fatiando
ac2afbcb2d99b18f145cc1ed40075beb5f92dd5a
fatiando/utils.py
python
si2eotvos
(value)
return value * constants.SI2EOTVOS
Convert a value from SI units to Eotvos. Parameters: * value : number or array The value in SI Returns: * value : number or array The value in Eotvos
Convert a value from SI units to Eotvos.
[ "Convert", "a", "value", "from", "SI", "units", "to", "Eotvos", "." ]
def si2eotvos(value): """ Convert a value from SI units to Eotvos. Parameters: * value : number or array The value in SI Returns: * value : number or array The value in Eotvos """ return value * constants.SI2EOTVOS
[ "def", "si2eotvos", "(", "value", ")", ":", "return", "value", "*", "constants", ".", "SI2EOTVOS" ]
https://github.com/fatiando/fatiando/blob/ac2afbcb2d99b18f145cc1ed40075beb5f92dd5a/fatiando/utils.py#L180-L195
mkusner/grammarVAE
ffffe272a8cf1772578dfc92254c55c224cddc02
Theano-master/theano/tensor/opt.py
python
encompasses_broadcastable
(b1, b2)
return not any(v1 and not v2 for v1, v2 in zip(b1, b2))
Parameters ---------- b1 The broadcastable attribute of a tensor type. b2 The broadcastable attribute of a tensor type. Returns ------- bool True if the broadcastable patterns b1 and b2 are such that b2 is broadcasted to b1's shape and not the opposite.
[]
def encompasses_broadcastable(b1, b2): """ Parameters ---------- b1 The broadcastable attribute of a tensor type. b2 The broadcastable attribute of a tensor type. Returns ------- bool True if the broadcastable patterns b1 and b2 are such that b2 is broadcasted to b1's shape and not the opposite. """ if len(b1) < len(b2): return False b1 = b1[-len(b2):] return not any(v1 and not v2 for v1, v2 in zip(b1, b2))
[ "def", "encompasses_broadcastable", "(", "b1", ",", "b2", ")", ":", "if", "len", "(", "b1", ")", "<", "len", "(", "b2", ")", ":", "return", "False", "b1", "=", "b1", "[", "-", "len", "(", "b2", ")", ":", "]", "return", "not", "any", "(", "v1", "and", "not", "v2", "for", "v1", ",", "v2", "in", "zip", "(", "b1", ",", "b2", ")", ")" ]
https://github.com/mkusner/grammarVAE/blob/ffffe272a8cf1772578dfc92254c55c224cddc02/Theano-master/theano/tensor/opt.py#L146-L166
Qiskit/qiskit-terra
b66030e3b9192efdd3eb95cf25c6545fe0a13da4
qiskit/quantum_info/states/quantum_state.py
python
QuantumState._subsystem_probabilities
(probs, dims, qargs=None)
return new_probs
Marginalize a probability vector according to subsystems. Args: probs (np.array): a probability vector Numpy array. dims (tuple): subsystem dimensions. qargs (None or list): a list of subsystems to return marginalized probabilities for. If None return all probabilities (Default: None). Returns: np.array: the marginalized probability vector flattened for the specified qargs.
Marginalize a probability vector according to subsystems.
[ "Marginalize", "a", "probability", "vector", "according", "to", "subsystems", "." ]
def _subsystem_probabilities(probs, dims, qargs=None): """Marginalize a probability vector according to subsystems. Args: probs (np.array): a probability vector Numpy array. dims (tuple): subsystem dimensions. qargs (None or list): a list of subsystems to return marginalized probabilities for. If None return all probabilities (Default: None). Returns: np.array: the marginalized probability vector flattened for the specified qargs. """ if qargs is None: return probs # Convert qargs to tensor axes probs_tens = np.reshape(probs, dims) ndim = probs_tens.ndim qargs_axes = [ndim - 1 - i for i in reversed(qargs)] # Get sum axis for marginalized subsystems sum_axis = tuple(i for i in range(ndim) if i not in qargs_axes) if sum_axis: probs_tens = np.sum(probs_tens, axis=sum_axis) qargs_axes = np.argsort(np.argsort(qargs_axes)) # Permute probability vector for desired qargs order probs_tens = np.transpose(probs_tens, axes=qargs_axes) new_probs = np.reshape(probs_tens, (probs_tens.size,)) return new_probs
[ "def", "_subsystem_probabilities", "(", "probs", ",", "dims", ",", "qargs", "=", "None", ")", ":", "if", "qargs", "is", "None", ":", "return", "probs", "# Convert qargs to tensor axes", "probs_tens", "=", "np", ".", "reshape", "(", "probs", ",", "dims", ")", "ndim", "=", "probs_tens", ".", "ndim", "qargs_axes", "=", "[", "ndim", "-", "1", "-", "i", "for", "i", "in", "reversed", "(", "qargs", ")", "]", "# Get sum axis for marginalized subsystems", "sum_axis", "=", "tuple", "(", "i", "for", "i", "in", "range", "(", "ndim", ")", "if", "i", "not", "in", "qargs_axes", ")", "if", "sum_axis", ":", "probs_tens", "=", "np", ".", "sum", "(", "probs_tens", ",", "axis", "=", "sum_axis", ")", "qargs_axes", "=", "np", ".", "argsort", "(", "np", ".", "argsort", "(", "qargs_axes", ")", ")", "# Permute probability vector for desired qargs order", "probs_tens", "=", "np", ".", "transpose", "(", "probs_tens", ",", "axes", "=", "qargs_axes", ")", "new_probs", "=", "np", ".", "reshape", "(", "probs_tens", ",", "(", "probs_tens", ".", "size", ",", ")", ")", "return", "new_probs" ]
https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/quantum_info/states/quantum_state.py#L440-L468
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/ceilometer/ceilometer/openstack/common/rpc/impl_qpid.py
python
DirectPublisher.__init__
(self, conf, session, msg_id)
Init a 'direct' publisher.
Init a 'direct' publisher.
[ "Init", "a", "direct", "publisher", "." ]
def __init__(self, conf, session, msg_id): """Init a 'direct' publisher.""" super(DirectPublisher, self).__init__(session, msg_id, {"type": "Direct"})
[ "def", "__init__", "(", "self", ",", "conf", ",", "session", ",", "msg_id", ")", ":", "super", "(", "DirectPublisher", ",", "self", ")", ".", "__init__", "(", "session", ",", "msg_id", ",", "{", "\"type\"", ":", "\"Direct\"", "}", ")" ]
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/ceilometer/ceilometer/openstack/common/rpc/impl_qpid.py#L285-L288
Komodo/KomodoEdit
61edab75dce2bdb03943b387b0608ea36f548e8e
src/codeintel/lib/codeintel2/css_linter.py
python
_CSSParser._parse_assignment
(self)
we saw $var or @var at top-level, expect : expression ;
we saw $var or
[ "we", "saw", "$var", "or" ]
def _parse_assignment(self): """ we saw $var or @var at top-level, expect : expression ; """ self._parse_required_operator(":") self._parse_expression() self._parse_required_operator(";")
[ "def", "_parse_assignment", "(", "self", ")", ":", "self", ".", "_parse_required_operator", "(", "\":\"", ")", "self", ".", "_parse_expression", "(", ")", "self", ".", "_parse_required_operator", "(", "\";\"", ")" ]
https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/src/codeintel/lib/codeintel2/css_linter.py#L729-L735
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/min/encodings/zlib_codec.py
python
IncrementalDecoder.__init__
(self, errors='strict')
[]
def __init__(self, errors='strict'): assert errors == 'strict' self.errors = errors self.decompressobj = zlib.decompressobj()
[ "def", "__init__", "(", "self", ",", "errors", "=", "'strict'", ")", ":", "assert", "errors", "==", "'strict'", "self", ".", "errors", "=", "errors", "self", ".", "decompressobj", "=", "zlib", ".", "decompressobj", "(", ")" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/encodings/zlib_codec.py#L44-L47
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/team_log.py
python
EventDetails.member_change_status_details
(cls, val)
return cls('member_change_status_details', val)
Create an instance of this class set to the ``member_change_status_details`` tag with value ``val``. :param MemberChangeStatusDetails val: :rtype: EventDetails
Create an instance of this class set to the ``member_change_status_details`` tag with value ``val``.
[ "Create", "an", "instance", "of", "this", "class", "set", "to", "the", "member_change_status_details", "tag", "with", "value", "val", "." ]
def member_change_status_details(cls, val): """ Create an instance of this class set to the ``member_change_status_details`` tag with value ``val``. :param MemberChangeStatusDetails val: :rtype: EventDetails """ return cls('member_change_status_details', val)
[ "def", "member_change_status_details", "(", "cls", ",", "val", ")", ":", "return", "cls", "(", "'member_change_status_details'", ",", "val", ")" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team_log.py#L9620-L9628
descarteslabs/descarteslabs-python
ace8a1a89d58b75df1bcaa613a4b3544d7bdc4be
descarteslabs/vectors/featurecollection.py
python
FeatureCollection.list_exports
(self)
return results
Get all the export tasks for this product. Returns ------- list(:class:`ExportTask <descarteslabs.common.tasks.exporttask.ExportTask>`) The list of tasks for the product. Raises ------ ~descarteslabs.client.exceptions.NotFoundError Raised if the product cannot be found. ~descarteslabs.client.exceptions.RateLimitError Raised when too many requests have been made within a given time period. ~descarteslabs.client.exceptions.ServerError Raised when a unknown error occurred on the server. Example ------- >>> from descarteslabs.vectors import FeatureCollection, properties as p >>> aoi_geometry = { ... "type": "Polygon", ... "coordinates": [[ # A small area in Washington DC ... [-77.05501556396483, 38.90946877327506], ... [-77.0419692993164, 38.90946877327506], ... [-77.0419692993164, 38.91855139233948], ... [-77.05501556396483, 38.91855139233948], ... [-77.05501556396483, 38.90946877327506] ... ]] ... } >>> buildings = FeatureCollection( ... "a35126a241bd022c026e96ab9fe5e0ea23967d08:USBuildingFootprints") # doctest: +SKIP >>> filtered_buildings = buildings.filter(geometry=aoi_geometry) # doctest: +SKIP >>> task = filtered_buildings.export("my_export") # doctest: +SKIP >>> exports = filtered_buildings.list_exports() # doctest: +SKIP
Get all the export tasks for this product.
[ "Get", "all", "the", "export", "tasks", "for", "this", "product", "." ]
def list_exports(self): """ Get all the export tasks for this product. Returns ------- list(:class:`ExportTask <descarteslabs.common.tasks.exporttask.ExportTask>`) The list of tasks for the product. Raises ------ ~descarteslabs.client.exceptions.NotFoundError Raised if the product cannot be found. ~descarteslabs.client.exceptions.RateLimitError Raised when too many requests have been made within a given time period. ~descarteslabs.client.exceptions.ServerError Raised when a unknown error occurred on the server. Example ------- >>> from descarteslabs.vectors import FeatureCollection, properties as p >>> aoi_geometry = { ... "type": "Polygon", ... "coordinates": [[ # A small area in Washington DC ... [-77.05501556396483, 38.90946877327506], ... [-77.0419692993164, 38.90946877327506], ... [-77.0419692993164, 38.91855139233948], ... [-77.05501556396483, 38.91855139233948], ... [-77.05501556396483, 38.90946877327506] ... ]] ... } >>> buildings = FeatureCollection( ... "a35126a241bd022c026e96ab9fe5e0ea23967d08:USBuildingFootprints") # doctest: +SKIP >>> filtered_buildings = buildings.filter(geometry=aoi_geometry) # doctest: +SKIP >>> task = filtered_buildings.export("my_export") # doctest: +SKIP >>> exports = filtered_buildings.list_exports() # doctest: +SKIP """ results = [] for result in self.vector_client.get_export_results(self.id): results.append( ExportTask( self.id, tuid=result.id, result_attrs=result.attributes, client=self.vector_client, ) ) return results
[ "def", "list_exports", "(", "self", ")", ":", "results", "=", "[", "]", "for", "result", "in", "self", ".", "vector_client", ".", "get_export_results", "(", "self", ".", "id", ")", ":", "results", ".", "append", "(", "ExportTask", "(", "self", ".", "id", ",", "tuid", "=", "result", ".", "id", ",", "result_attrs", "=", "result", ".", "attributes", ",", "client", "=", "self", ".", "vector_client", ",", ")", ")", "return", "results" ]
https://github.com/descarteslabs/descarteslabs-python/blob/ace8a1a89d58b75df1bcaa613a4b3544d7bdc4be/descarteslabs/vectors/featurecollection.py#L956-L1006
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/core/data/url/handlers/ntlm_auth.py
python
HTTPNtlmAuthHandler.http_error_401
(self, req, fp, code, msg, headers)
return response
[]
def http_error_401(self, req, fp, code, msg, headers): url = req.get_full_url() response = self.http_error_auth_reqed('www-authenticate', url, req, headers) self.reset_retry_count() return response
[ "def", "http_error_401", "(", "self", ",", "req", ",", "fp", ",", "code", ",", "msg", ",", "headers", ")", ":", "url", "=", "req", ".", "get_full_url", "(", ")", "response", "=", "self", ".", "http_error_auth_reqed", "(", "'www-authenticate'", ",", "url", ",", "req", ",", "headers", ")", "self", ".", "reset_retry_count", "(", ")", "return", "response" ]
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/core/data/url/handlers/ntlm_auth.py#L97-L102
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
sqlserver/datadog_checks/sqlserver/config_models/defaults.py
python
shared_custom_metrics
(field, value)
return get_default_field_value(field, value)
[]
def shared_custom_metrics(field, value): return get_default_field_value(field, value)
[ "def", "shared_custom_metrics", "(", "field", ",", "value", ")", ":", "return", "get_default_field_value", "(", "field", ",", "value", ")" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/sqlserver/datadog_checks/sqlserver/config_models/defaults.py#L13-L14
XaF/TraktForVLC
7851368d7ce62a15bb245fc078f3eab201c12357
version.py
python
CIVersionReader.check_tag
(self, tag=None, abbrev=7)
[]
def check_tag(self, tag=None, abbrev=7): if not tag: tag = self.call_git_describe(abbrev, exact=True) # If we did not find any version, we can return now, there # is no tag to check if not tag: raise GitVersionException( 'No tag found for the current commit.') if not self.pep440_public_version.search(tag): raise GitVersionException( 'Version {} does not match PEP440 for public version ' 'identifiers.'.format(tag))
[ "def", "check_tag", "(", "self", ",", "tag", "=", "None", ",", "abbrev", "=", "7", ")", ":", "if", "not", "tag", ":", "tag", "=", "self", ".", "call_git_describe", "(", "abbrev", ",", "exact", "=", "True", ")", "# If we did not find any version, we can return now, there", "# is no tag to check", "if", "not", "tag", ":", "raise", "GitVersionException", "(", "'No tag found for the current commit.'", ")", "if", "not", "self", ".", "pep440_public_version", ".", "search", "(", "tag", ")", ":", "raise", "GitVersionException", "(", "'Version {} does not match PEP440 for public version '", "'identifiers.'", ".", "format", "(", "tag", ")", ")" ]
https://github.com/XaF/TraktForVLC/blob/7851368d7ce62a15bb245fc078f3eab201c12357/version.py#L202-L215
kiibohd/kll
b6d997b810006326d31fc570c89d396fd0b70569
kll/common/stage.py
python
FileImportStage.command_line_flags
(self, parser)
Group parser for command line options @param parser: argparse setup object
Group parser for command line options
[ "Group", "parser", "for", "command", "line", "options" ]
def command_line_flags(self, parser): ''' Group parser for command line options @param parser: argparse setup object ''' # Create new option group group = parser.add_argument_group('\033[1mFile Context Configuration\033[0m') # Positional Arguments group.add_argument('generic', type=str, nargs='*', default=self.generic_files, help="Auto-detect context of .kll files, defaults to a base map configuration." ) # Optional Arguments group.add_argument('--config', type=str, nargs='+', default=self.config_files, help="Specify base configuration .kll files, earliest priority" ) group.add_argument('--base', type=str, nargs='+', default=self.base_files, help="Specify base map configuration, applied after config .kll files.\n" "The base map is applied prior to all default and partial maps and is used as the basis for them." ) group.add_argument('--default', type=str, nargs='+', default=self.default_files, help="Specify .kll files to layer on top of the default map to create a combined map.\n" "Also known as layer 0." ) group.add_argument('--partial', type=str, nargs='+', action='append', default=self.partial_files, help="Specify .kll files to generate partial map, multiple files per flag.\n" "Each -p defines another partial map.\n" "Base .kll files (that define the scan code maps) must be defined for each partial map." )
[ "def", "command_line_flags", "(", "self", ",", "parser", ")", ":", "# Create new option group", "group", "=", "parser", ".", "add_argument_group", "(", "'\\033[1mFile Context Configuration\\033[0m'", ")", "# Positional Arguments", "group", ".", "add_argument", "(", "'generic'", ",", "type", "=", "str", ",", "nargs", "=", "'*'", ",", "default", "=", "self", ".", "generic_files", ",", "help", "=", "\"Auto-detect context of .kll files, defaults to a base map configuration.\"", ")", "# Optional Arguments", "group", ".", "add_argument", "(", "'--config'", ",", "type", "=", "str", ",", "nargs", "=", "'+'", ",", "default", "=", "self", ".", "config_files", ",", "help", "=", "\"Specify base configuration .kll files, earliest priority\"", ")", "group", ".", "add_argument", "(", "'--base'", ",", "type", "=", "str", ",", "nargs", "=", "'+'", ",", "default", "=", "self", ".", "base_files", ",", "help", "=", "\"Specify base map configuration, applied after config .kll files.\\n\"", "\"The base map is applied prior to all default and partial maps and is used as the basis for them.\"", ")", "group", ".", "add_argument", "(", "'--default'", ",", "type", "=", "str", ",", "nargs", "=", "'+'", ",", "default", "=", "self", ".", "default_files", ",", "help", "=", "\"Specify .kll files to layer on top of the default map to create a combined map.\\n\"", "\"Also known as layer 0.\"", ")", "group", ".", "add_argument", "(", "'--partial'", ",", "type", "=", "str", ",", "nargs", "=", "'+'", ",", "action", "=", "'append'", ",", "default", "=", "self", ".", "partial_files", ",", "help", "=", "\"Specify .kll files to generate partial map, multiple files per flag.\\n\"", "\"Each -p defines another partial map.\\n\"", "\"Base .kll files (that define the scan code maps) must be defined for each partial map.\"", ")" ]
https://github.com/kiibohd/kll/blob/b6d997b810006326d31fc570c89d396fd0b70569/kll/common/stage.py#L344-L374
matplotlib/matplotlib
8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322
lib/matplotlib/backends/backend_pdf.py
python
_create_pdf_info_dict
(backend, metadata)
return info
Create a PDF infoDict based on user-supplied metadata. A default ``Creator``, ``Producer``, and ``CreationDate`` are added, though the user metadata may override it. The date may be the current time, or a time set by the ``SOURCE_DATE_EPOCH`` environment variable. Metadata is verified to have the correct keys and their expected types. Any unknown keys/types will raise a warning. Parameters ---------- backend : str The name of the backend to use in the Producer value. metadata : dict[str, Union[str, datetime, Name]] A dictionary of metadata supplied by the user with information following the PDF specification, also defined in `~.backend_pdf.PdfPages` below. If any value is *None*, then the key will be removed. This can be used to remove any pre-defined values. Returns ------- dict[str, Union[str, datetime, Name]] A validated dictionary of metadata.
Create a PDF infoDict based on user-supplied metadata.
[ "Create", "a", "PDF", "infoDict", "based", "on", "user", "-", "supplied", "metadata", "." ]
def _create_pdf_info_dict(backend, metadata): """ Create a PDF infoDict based on user-supplied metadata. A default ``Creator``, ``Producer``, and ``CreationDate`` are added, though the user metadata may override it. The date may be the current time, or a time set by the ``SOURCE_DATE_EPOCH`` environment variable. Metadata is verified to have the correct keys and their expected types. Any unknown keys/types will raise a warning. Parameters ---------- backend : str The name of the backend to use in the Producer value. metadata : dict[str, Union[str, datetime, Name]] A dictionary of metadata supplied by the user with information following the PDF specification, also defined in `~.backend_pdf.PdfPages` below. If any value is *None*, then the key will be removed. This can be used to remove any pre-defined values. Returns ------- dict[str, Union[str, datetime, Name]] A validated dictionary of metadata. """ # get source date from SOURCE_DATE_EPOCH, if set # See https://reproducible-builds.org/specs/source-date-epoch/ source_date_epoch = os.getenv("SOURCE_DATE_EPOCH") if source_date_epoch: source_date = datetime.utcfromtimestamp(int(source_date_epoch)) source_date = source_date.replace(tzinfo=UTC) else: source_date = datetime.today() info = { 'Creator': f'Matplotlib v{mpl.__version__}, https://matplotlib.org', 'Producer': f'Matplotlib {backend} backend v{mpl.__version__}', 'CreationDate': source_date, **metadata } info = {k: v for (k, v) in info.items() if v is not None} def is_string_like(x): return isinstance(x, str) is_string_like.text_for_warning = "an instance of str" def is_date(x): return isinstance(x, datetime) is_date.text_for_warning = "an instance of datetime.datetime" def check_trapped(x): if isinstance(x, Name): return x.name in (b'True', b'False', b'Unknown') else: return x in ('True', 'False', 'Unknown') check_trapped.text_for_warning = 'one of {"True", "False", "Unknown"}' keywords = { 'Title': is_string_like, 'Author': is_string_like, 'Subject': is_string_like, 'Keywords': is_string_like, 'Creator': is_string_like, 'Producer': is_string_like, 'CreationDate': is_date, 'ModDate': is_date, 'Trapped': check_trapped, } for k in info: if k not in keywords: _api.warn_external(f'Unknown infodict keyword: {k!r}. ' f'Must be one of {set(keywords)!r}.') elif not keywords[k](info[k]): _api.warn_external(f'Bad value for infodict keyword {k}. ' f'Got {info[k]!r} which is not ' f'{keywords[k].text_for_warning}.') if 'Trapped' in info: info['Trapped'] = Name(info['Trapped']) return info
[ "def", "_create_pdf_info_dict", "(", "backend", ",", "metadata", ")", ":", "# get source date from SOURCE_DATE_EPOCH, if set", "# See https://reproducible-builds.org/specs/source-date-epoch/", "source_date_epoch", "=", "os", ".", "getenv", "(", "\"SOURCE_DATE_EPOCH\"", ")", "if", "source_date_epoch", ":", "source_date", "=", "datetime", ".", "utcfromtimestamp", "(", "int", "(", "source_date_epoch", ")", ")", "source_date", "=", "source_date", ".", "replace", "(", "tzinfo", "=", "UTC", ")", "else", ":", "source_date", "=", "datetime", ".", "today", "(", ")", "info", "=", "{", "'Creator'", ":", "f'Matplotlib v{mpl.__version__}, https://matplotlib.org'", ",", "'Producer'", ":", "f'Matplotlib {backend} backend v{mpl.__version__}'", ",", "'CreationDate'", ":", "source_date", ",", "*", "*", "metadata", "}", "info", "=", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "info", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}", "def", "is_string_like", "(", "x", ")", ":", "return", "isinstance", "(", "x", ",", "str", ")", "is_string_like", ".", "text_for_warning", "=", "\"an instance of str\"", "def", "is_date", "(", "x", ")", ":", "return", "isinstance", "(", "x", ",", "datetime", ")", "is_date", ".", "text_for_warning", "=", "\"an instance of datetime.datetime\"", "def", "check_trapped", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "Name", ")", ":", "return", "x", ".", "name", "in", "(", "b'True'", ",", "b'False'", ",", "b'Unknown'", ")", "else", ":", "return", "x", "in", "(", "'True'", ",", "'False'", ",", "'Unknown'", ")", "check_trapped", ".", "text_for_warning", "=", "'one of {\"True\", \"False\", \"Unknown\"}'", "keywords", "=", "{", "'Title'", ":", "is_string_like", ",", "'Author'", ":", "is_string_like", ",", "'Subject'", ":", "is_string_like", ",", "'Keywords'", ":", "is_string_like", ",", "'Creator'", ":", "is_string_like", ",", "'Producer'", ":", "is_string_like", ",", "'CreationDate'", ":", "is_date", ",", "'ModDate'", ":", "is_date", ",", "'Trapped'", ":", "check_trapped", ",", "}", "for", "k", "in", "info", ":", "if", "k", "not", "in", "keywords", ":", "_api", ".", "warn_external", "(", "f'Unknown infodict keyword: {k!r}. '", "f'Must be one of {set(keywords)!r}.'", ")", "elif", "not", "keywords", "[", "k", "]", "(", "info", "[", "k", "]", ")", ":", "_api", ".", "warn_external", "(", "f'Bad value for infodict keyword {k}. '", "f'Got {info[k]!r} which is not '", "f'{keywords[k].text_for_warning}.'", ")", "if", "'Trapped'", "in", "info", ":", "info", "[", "'Trapped'", "]", "=", "Name", "(", "info", "[", "'Trapped'", "]", ")", "return", "info" ]
https://github.com/matplotlib/matplotlib/blob/8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322/lib/matplotlib/backends/backend_pdf.py#L139-L223
CATIA-Systems/FMPy
fde192346c36eb69dbaca60a96e80cdc8ef37b89
fmpy/util.py
python
plot_result
(result, reference=None, names=None, filename=None, window_title=None, events=False)
Plot a collection of time series. Parameters: result: structured NumPy Array that contains the time series to plot where 'time' is the independent variable reference: optional reference signals with the same structure as `result` names: variables to plot filename: when provided the plot is saved as `filename` instead of showing the figure window_title: title for the figure window events: draw vertical lines at events
Plot a collection of time series.
[ "Plot", "a", "collection", "of", "time", "series", "." ]
def plot_result(result, reference=None, names=None, filename=None, window_title=None, events=False): """ Plot a collection of time series. Parameters: result: structured NumPy Array that contains the time series to plot where 'time' is the independent variable reference: optional reference signals with the same structure as `result` names: variables to plot filename: when provided the plot is saved as `filename` instead of showing the figure window_title: title for the figure window events: draw vertical lines at events """ from . import plot_library if plot_library == 'plotly': figure = create_plotly_figure(result, names=names, events=events) if filename is None: figure.show() else: figure.write_image(filename) return import matplotlib.pylab as pylab import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms from matplotlib.ticker import MaxNLocator from collections.abc import Iterable params = { 'legend.fontsize': 8, 'axes.labelsize': 8, 'xtick.labelsize': 8, 'ytick.labelsize': 8, 'axes.linewidth': 0.5, } pylab.rcParams.update(params) time = result['time'] if names is None: names = [] # plot at most 20 one-dimensional signals for d in result.dtype.descr[1:]: if len(d) < 3 and len(names) < 20: names.append(d[0]) if len(names) > 0: # indent label 0.015 inch / character label_x = -0.015 * np.max(list(map(len, names)) + [8]) fig, axes = plt.subplots(len(names), sharex=True) fig.set_facecolor('white') if not isinstance(axes, Iterable): axes = [axes] if events: t_event = time[np.argwhere(np.diff(time) == 0)] for ax, name in zip(axes, names): y = result[name] ax.grid(b=True, which='both', color='0.8', linestyle='-', zorder=0) ax.tick_params(direction='in') if events: for t in t_event: ax.axvline(x=t, color='y', linewidth=1) if reference is not None and name in reference.dtype.names: t_ref = reference[reference.dtype.names[0]] y_ref = reference[name] t_band, y_min, y_max, i_out = validate_signal(t=time, y=y, t_ref=t_ref, y_ref=y_ref) ax.fill_between(t_band, y_min, y_max, facecolor=(0, 0.5, 0), alpha=0.1) ax.plot(t_band, y_min, color=(0, 0.5, 0), linewidth=1, label='lower bound', zorder=101, alpha=0.5) ax.plot(t_band, y_max, color=(0, 0.5, 0), linewidth=1, label='upper bound', zorder=101, alpha=0.5) # mark the outliers # use the data coordinates for the x-axis and the axes coordinates for the y-axis trans = mtransforms.blended_transform_factory(ax.transData, ax.transAxes) ax.fill_between(time, 0, 1, where=i_out, facecolor='red', alpha=0.5, transform=trans) if y.dtype == np.float64: # find left indices of discontinuities i_disc = np.flatnonzero(np.diff(time) == 0) i_disc = np.append(i_disc + 1, len(time)) i0 = 0 for i1 in i_disc: ax.plot(time[i0:i1], y[i0:i1], color='b', linewidth=0.9, label='result', zorder=101) i0 = i1 else: ax.hlines(y[:-1], time[:-1], time[1:], colors='b', linewidth=1, label='result', zorder=101) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) if y.dtype == bool: # use fixed range and labels and fill area ax.set_ylim(-0.25, 1.25) ax.yaxis.set_ticks([0, 1]) ax.yaxis.set_ticklabels(['false', 'true']) if y.ndim == 1: ax.fill_between(time, y, 0, step='post', facecolor='b', alpha=0.1) else: ax.margins(x=0, y=0.05) if time.size < 200: ax.scatter(time, y, color='b', s=5, zorder=101) ax.set_ylabel(name, horizontalalignment='left', rotation=0) # align the y-labels ax.get_yaxis().set_label_coords(label_x, 0.5) # set the window title if window_title is not None: fig.canvas.set_window_title(window_title) def onresize(event): fig = plt.gcf() w = fig.get_figwidth() # tight_layout() crashes on very small figures if w < 3: return x = label_x * (8.0 / w) # update label coordinates for ax in fig.get_axes(): ax.get_yaxis().set_label_coords(x, 0.5) # update layout plt.tight_layout() # update layout when the plot is re-sized fig.canvas.mpl_connect('resize_event', onresize) fig.set_size_inches(w=8, h=1.5 * len(names), forward=True) plt.tight_layout() if filename is None: plt.show() else: dir, _ = os.path.split(filename) if not os.path.isdir(dir): os.makedirs(dir) fig.savefig(filename) plt.close(fig)
[ "def", "plot_result", "(", "result", ",", "reference", "=", "None", ",", "names", "=", "None", ",", "filename", "=", "None", ",", "window_title", "=", "None", ",", "events", "=", "False", ")", ":", "from", ".", "import", "plot_library", "if", "plot_library", "==", "'plotly'", ":", "figure", "=", "create_plotly_figure", "(", "result", ",", "names", "=", "names", ",", "events", "=", "events", ")", "if", "filename", "is", "None", ":", "figure", ".", "show", "(", ")", "else", ":", "figure", ".", "write_image", "(", "filename", ")", "return", "import", "matplotlib", ".", "pylab", "as", "pylab", "import", "matplotlib", ".", "pyplot", "as", "plt", "import", "matplotlib", ".", "transforms", "as", "mtransforms", "from", "matplotlib", ".", "ticker", "import", "MaxNLocator", "from", "collections", ".", "abc", "import", "Iterable", "params", "=", "{", "'legend.fontsize'", ":", "8", ",", "'axes.labelsize'", ":", "8", ",", "'xtick.labelsize'", ":", "8", ",", "'ytick.labelsize'", ":", "8", ",", "'axes.linewidth'", ":", "0.5", ",", "}", "pylab", ".", "rcParams", ".", "update", "(", "params", ")", "time", "=", "result", "[", "'time'", "]", "if", "names", "is", "None", ":", "names", "=", "[", "]", "# plot at most 20 one-dimensional signals", "for", "d", "in", "result", ".", "dtype", ".", "descr", "[", "1", ":", "]", ":", "if", "len", "(", "d", ")", "<", "3", "and", "len", "(", "names", ")", "<", "20", ":", "names", ".", "append", "(", "d", "[", "0", "]", ")", "if", "len", "(", "names", ")", ">", "0", ":", "# indent label 0.015 inch / character", "label_x", "=", "-", "0.015", "*", "np", ".", "max", "(", "list", "(", "map", "(", "len", ",", "names", ")", ")", "+", "[", "8", "]", ")", "fig", ",", "axes", "=", "plt", ".", "subplots", "(", "len", "(", "names", ")", ",", "sharex", "=", "True", ")", "fig", ".", "set_facecolor", "(", "'white'", ")", "if", "not", "isinstance", "(", "axes", ",", "Iterable", ")", ":", "axes", "=", "[", "axes", "]", "if", "events", ":", "t_event", "=", "time", "[", "np", ".", "argwhere", "(", "np", ".", "diff", "(", "time", ")", "==", "0", ")", "]", "for", "ax", ",", "name", "in", "zip", "(", "axes", ",", "names", ")", ":", "y", "=", "result", "[", "name", "]", "ax", ".", "grid", "(", "b", "=", "True", ",", "which", "=", "'both'", ",", "color", "=", "'0.8'", ",", "linestyle", "=", "'-'", ",", "zorder", "=", "0", ")", "ax", ".", "tick_params", "(", "direction", "=", "'in'", ")", "if", "events", ":", "for", "t", "in", "t_event", ":", "ax", ".", "axvline", "(", "x", "=", "t", ",", "color", "=", "'y'", ",", "linewidth", "=", "1", ")", "if", "reference", "is", "not", "None", "and", "name", "in", "reference", ".", "dtype", ".", "names", ":", "t_ref", "=", "reference", "[", "reference", ".", "dtype", ".", "names", "[", "0", "]", "]", "y_ref", "=", "reference", "[", "name", "]", "t_band", ",", "y_min", ",", "y_max", ",", "i_out", "=", "validate_signal", "(", "t", "=", "time", ",", "y", "=", "y", ",", "t_ref", "=", "t_ref", ",", "y_ref", "=", "y_ref", ")", "ax", ".", "fill_between", "(", "t_band", ",", "y_min", ",", "y_max", ",", "facecolor", "=", "(", "0", ",", "0.5", ",", "0", ")", ",", "alpha", "=", "0.1", ")", "ax", ".", "plot", "(", "t_band", ",", "y_min", ",", "color", "=", "(", "0", ",", "0.5", ",", "0", ")", ",", "linewidth", "=", "1", ",", "label", "=", "'lower bound'", ",", "zorder", "=", "101", ",", "alpha", "=", "0.5", ")", "ax", ".", "plot", "(", "t_band", ",", "y_max", ",", "color", "=", "(", "0", ",", "0.5", ",", "0", ")", ",", "linewidth", "=", "1", ",", "label", "=", "'upper bound'", ",", "zorder", "=", "101", ",", "alpha", "=", "0.5", ")", "# mark the outliers", "# use the data coordinates for the x-axis and the axes coordinates for the y-axis", "trans", "=", "mtransforms", ".", "blended_transform_factory", "(", "ax", ".", "transData", ",", "ax", ".", "transAxes", ")", "ax", ".", "fill_between", "(", "time", ",", "0", ",", "1", ",", "where", "=", "i_out", ",", "facecolor", "=", "'red'", ",", "alpha", "=", "0.5", ",", "transform", "=", "trans", ")", "if", "y", ".", "dtype", "==", "np", ".", "float64", ":", "# find left indices of discontinuities", "i_disc", "=", "np", ".", "flatnonzero", "(", "np", ".", "diff", "(", "time", ")", "==", "0", ")", "i_disc", "=", "np", ".", "append", "(", "i_disc", "+", "1", ",", "len", "(", "time", ")", ")", "i0", "=", "0", "for", "i1", "in", "i_disc", ":", "ax", ".", "plot", "(", "time", "[", "i0", ":", "i1", "]", ",", "y", "[", "i0", ":", "i1", "]", ",", "color", "=", "'b'", ",", "linewidth", "=", "0.9", ",", "label", "=", "'result'", ",", "zorder", "=", "101", ")", "i0", "=", "i1", "else", ":", "ax", ".", "hlines", "(", "y", "[", ":", "-", "1", "]", ",", "time", "[", ":", "-", "1", "]", ",", "time", "[", "1", ":", "]", ",", "colors", "=", "'b'", ",", "linewidth", "=", "1", ",", "label", "=", "'result'", ",", "zorder", "=", "101", ")", "ax", ".", "yaxis", ".", "set_major_locator", "(", "MaxNLocator", "(", "integer", "=", "True", ")", ")", "if", "y", ".", "dtype", "==", "bool", ":", "# use fixed range and labels and fill area", "ax", ".", "set_ylim", "(", "-", "0.25", ",", "1.25", ")", "ax", ".", "yaxis", ".", "set_ticks", "(", "[", "0", ",", "1", "]", ")", "ax", ".", "yaxis", ".", "set_ticklabels", "(", "[", "'false'", ",", "'true'", "]", ")", "if", "y", ".", "ndim", "==", "1", ":", "ax", ".", "fill_between", "(", "time", ",", "y", ",", "0", ",", "step", "=", "'post'", ",", "facecolor", "=", "'b'", ",", "alpha", "=", "0.1", ")", "else", ":", "ax", ".", "margins", "(", "x", "=", "0", ",", "y", "=", "0.05", ")", "if", "time", ".", "size", "<", "200", ":", "ax", ".", "scatter", "(", "time", ",", "y", ",", "color", "=", "'b'", ",", "s", "=", "5", ",", "zorder", "=", "101", ")", "ax", ".", "set_ylabel", "(", "name", ",", "horizontalalignment", "=", "'left'", ",", "rotation", "=", "0", ")", "# align the y-labels", "ax", ".", "get_yaxis", "(", ")", ".", "set_label_coords", "(", "label_x", ",", "0.5", ")", "# set the window title", "if", "window_title", "is", "not", "None", ":", "fig", ".", "canvas", ".", "set_window_title", "(", "window_title", ")", "def", "onresize", "(", "event", ")", ":", "fig", "=", "plt", ".", "gcf", "(", ")", "w", "=", "fig", ".", "get_figwidth", "(", ")", "# tight_layout() crashes on very small figures", "if", "w", "<", "3", ":", "return", "x", "=", "label_x", "*", "(", "8.0", "/", "w", ")", "# update label coordinates", "for", "ax", "in", "fig", ".", "get_axes", "(", ")", ":", "ax", ".", "get_yaxis", "(", ")", ".", "set_label_coords", "(", "x", ",", "0.5", ")", "# update layout", "plt", ".", "tight_layout", "(", ")", "# update layout when the plot is re-sized", "fig", ".", "canvas", ".", "mpl_connect", "(", "'resize_event'", ",", "onresize", ")", "fig", ".", "set_size_inches", "(", "w", "=", "8", ",", "h", "=", "1.5", "*", "len", "(", "names", ")", ",", "forward", "=", "True", ")", "plt", ".", "tight_layout", "(", ")", "if", "filename", "is", "None", ":", "plt", ".", "show", "(", ")", "else", ":", "dir", ",", "_", "=", "os", ".", "path", ".", "split", "(", "filename", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "dir", ")", ":", "os", ".", "makedirs", "(", "dir", ")", "fig", ".", "savefig", "(", "filename", ")", "plt", ".", "close", "(", "fig", ")" ]
https://github.com/CATIA-Systems/FMPy/blob/fde192346c36eb69dbaca60a96e80cdc8ef37b89/fmpy/util.py#L348-L505
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
medusa/name_parser/rules/rules.py
python
OnePreGroupAsMultiEpisode.when
(self, matches, context)
return to_remove, to_append
Evaluate the rule. :param matches: :type matches: rebulk.match.Matches :param context: :type context: dict :return:
Evaluate the rule.
[ "Evaluate", "the", "rule", "." ]
def when(self, matches, context): """Evaluate the rule. :param matches: :type matches: rebulk.match.Matches :param context: :type context: dict :return: """ titles = matches.named('title') if not titles: return episodes = matches.named('episode') if not episodes or len(episodes) != 2: return is_anime = context.get('show_type') == 'anime' or matches.tagged('anime') if is_anime or matches.named('season'): return sorted_episodes = sorted(episodes) if sorted_episodes[-1].value != 1: return episode = copy.copy(sorted_episodes[0]) episode.name = 'absolute_episode' to_remove = [sorted_episodes[-1]] to_append = [episode] episode_titles = matches.named('episode_title') if episode_titles: release_group = copy.copy(episode_titles[0]) release_group.name = 'release_group' to_remove.append(episode_titles[0]) to_append.append(release_group) return to_remove, to_append
[ "def", "when", "(", "self", ",", "matches", ",", "context", ")", ":", "titles", "=", "matches", ".", "named", "(", "'title'", ")", "if", "not", "titles", ":", "return", "episodes", "=", "matches", ".", "named", "(", "'episode'", ")", "if", "not", "episodes", "or", "len", "(", "episodes", ")", "!=", "2", ":", "return", "is_anime", "=", "context", ".", "get", "(", "'show_type'", ")", "==", "'anime'", "or", "matches", ".", "tagged", "(", "'anime'", ")", "if", "is_anime", "or", "matches", ".", "named", "(", "'season'", ")", ":", "return", "sorted_episodes", "=", "sorted", "(", "episodes", ")", "if", "sorted_episodes", "[", "-", "1", "]", ".", "value", "!=", "1", ":", "return", "episode", "=", "copy", ".", "copy", "(", "sorted_episodes", "[", "0", "]", ")", "episode", ".", "name", "=", "'absolute_episode'", "to_remove", "=", "[", "sorted_episodes", "[", "-", "1", "]", "]", "to_append", "=", "[", "episode", "]", "episode_titles", "=", "matches", ".", "named", "(", "'episode_title'", ")", "if", "episode_titles", ":", "release_group", "=", "copy", ".", "copy", "(", "episode_titles", "[", "0", "]", ")", "release_group", ".", "name", "=", "'release_group'", "to_remove", ".", "append", "(", "episode_titles", "[", "0", "]", ")", "to_append", ".", "append", "(", "release_group", ")", "return", "to_remove", ",", "to_append" ]
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/medusa/name_parser/rules/rules.py#L825-L864
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/ext/tornado/websocket.py
python
WebSocketHandler.ping
(self, data)
Send ping frame to the remote end.
Send ping frame to the remote end.
[ "Send", "ping", "frame", "to", "the", "remote", "end", "." ]
def ping(self, data): """Send ping frame to the remote end.""" if self.ws_connection is None: raise WebSocketClosedError() self.ws_connection.write_ping(data)
[ "def", "ping", "(", "self", ",", "data", ")", ":", "if", "self", ".", "ws_connection", "is", "None", ":", "raise", "WebSocketClosedError", "(", ")", "self", ".", "ws_connection", ".", "write_ping", "(", "data", ")" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/ext/tornado/websocket.py#L312-L316
mypaint/mypaint
90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33
gui/drawwindow.py
python
DrawWindow._display_filter_radioaction_changed_cb
(self, action, newaction)
Handle changes to the Display Filter radioaction set.
Handle changes to the Display Filter radioaction set.
[ "Handle", "changes", "to", "the", "Display", "Filter", "radioaction", "set", "." ]
def _display_filter_radioaction_changed_cb(self, action, newaction): """Handle changes to the Display Filter radioaction set.""" newaction_name = newaction.get_name() newfilter = { "DisplayFilterNone": None, "DisplayFilterLumaOnly": gui.displayfilter.luma_only, "DisplayFilterInvertColors": gui.displayfilter.invert_colors, "DisplayFilterSimDeuteranopia": gui.displayfilter.sim_deuteranopia, "DisplayFilterSimProtanopia": gui.displayfilter.sim_protanopia, "DisplayFilterSimTritanopia": gui.displayfilter.sim_tritanopia, }.get(newaction_name) for tdw in gui.tileddrawwidget.TiledDrawWidget.get_visible_tdws(): if tdw.renderer.display_filter is newfilter: continue logger.debug("Updating display_filter on %r to %r", tdw, newfilter) tdw.renderer.display_filter = newfilter tdw.queue_draw()
[ "def", "_display_filter_radioaction_changed_cb", "(", "self", ",", "action", ",", "newaction", ")", ":", "newaction_name", "=", "newaction", ".", "get_name", "(", ")", "newfilter", "=", "{", "\"DisplayFilterNone\"", ":", "None", ",", "\"DisplayFilterLumaOnly\"", ":", "gui", ".", "displayfilter", ".", "luma_only", ",", "\"DisplayFilterInvertColors\"", ":", "gui", ".", "displayfilter", ".", "invert_colors", ",", "\"DisplayFilterSimDeuteranopia\"", ":", "gui", ".", "displayfilter", ".", "sim_deuteranopia", ",", "\"DisplayFilterSimProtanopia\"", ":", "gui", ".", "displayfilter", ".", "sim_protanopia", ",", "\"DisplayFilterSimTritanopia\"", ":", "gui", ".", "displayfilter", ".", "sim_tritanopia", ",", "}", ".", "get", "(", "newaction_name", ")", "for", "tdw", "in", "gui", ".", "tileddrawwidget", ".", "TiledDrawWidget", ".", "get_visible_tdws", "(", ")", ":", "if", "tdw", ".", "renderer", ".", "display_filter", "is", "newfilter", ":", "continue", "logger", ".", "debug", "(", "\"Updating display_filter on %r to %r\"", ",", "tdw", ",", "newfilter", ")", "tdw", ".", "renderer", ".", "display_filter", "=", "newfilter", "tdw", ".", "queue_draw", "(", ")" ]
https://github.com/mypaint/mypaint/blob/90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33/gui/drawwindow.py#L874-L890
numenta/nupic
b9ebedaf54f49a33de22d8d44dff7c765cdb5548
src/nupic/algorithms/fdrutilities.py
python
_listOfOnTimesInVec
(vector)
return (totalOnTime, numOnTimes, durations)
Returns 3 things for a vector: * the total on time * the number of runs * a list of the durations of each run. Parameters: ----------------------------------------------- input stream: 11100000001100000000011111100000 return value: (11, 3, [3, 2, 6])
Returns 3 things for a vector: * the total on time * the number of runs * a list of the durations of each run.
[ "Returns", "3", "things", "for", "a", "vector", ":", "*", "the", "total", "on", "time", "*", "the", "number", "of", "runs", "*", "a", "list", "of", "the", "durations", "of", "each", "run", "." ]
def _listOfOnTimesInVec(vector): """ Returns 3 things for a vector: * the total on time * the number of runs * a list of the durations of each run. Parameters: ----------------------------------------------- input stream: 11100000001100000000011111100000 return value: (11, 3, [3, 2, 6]) """ # init counters durations = [] numOnTimes = 0 totalOnTime = 0 # Find where the nonzeros are nonzeros = numpy.array(vector).nonzero()[0] # Nothing to do if vector is empty if len(nonzeros) == 0: return (0, 0, []) # Special case of only 1 on bit if len(nonzeros) == 1: return (1, 1, [1]) # Count the consecutive non-zeros prev = nonzeros[0] onTime = 1 endIdx = nonzeros[-1] for idx in nonzeros[1:]: if idx != prev+1: totalOnTime += onTime numOnTimes += 1 durations.append(onTime) onTime = 1 else: onTime += 1 prev = idx # Add in the last one totalOnTime += onTime numOnTimes += 1 durations.append(onTime) return (totalOnTime, numOnTimes, durations)
[ "def", "_listOfOnTimesInVec", "(", "vector", ")", ":", "# init counters", "durations", "=", "[", "]", "numOnTimes", "=", "0", "totalOnTime", "=", "0", "# Find where the nonzeros are", "nonzeros", "=", "numpy", ".", "array", "(", "vector", ")", ".", "nonzero", "(", ")", "[", "0", "]", "# Nothing to do if vector is empty", "if", "len", "(", "nonzeros", ")", "==", "0", ":", "return", "(", "0", ",", "0", ",", "[", "]", ")", "# Special case of only 1 on bit", "if", "len", "(", "nonzeros", ")", "==", "1", ":", "return", "(", "1", ",", "1", ",", "[", "1", "]", ")", "# Count the consecutive non-zeros", "prev", "=", "nonzeros", "[", "0", "]", "onTime", "=", "1", "endIdx", "=", "nonzeros", "[", "-", "1", "]", "for", "idx", "in", "nonzeros", "[", "1", ":", "]", ":", "if", "idx", "!=", "prev", "+", "1", ":", "totalOnTime", "+=", "onTime", "numOnTimes", "+=", "1", "durations", ".", "append", "(", "onTime", ")", "onTime", "=", "1", "else", ":", "onTime", "+=", "1", "prev", "=", "idx", "# Add in the last one", "totalOnTime", "+=", "onTime", "numOnTimes", "+=", "1", "durations", ".", "append", "(", "onTime", ")", "return", "(", "totalOnTime", ",", "numOnTimes", ",", "durations", ")" ]
https://github.com/numenta/nupic/blob/b9ebedaf54f49a33de22d8d44dff7c765cdb5548/src/nupic/algorithms/fdrutilities.py#L848-L896
hamcrest/PyHamcrest
11aafabd688af2db23e8614f89da3015fd39f611
src/hamcrest/core/core/raises.py
python
DeferredCallable.with_args
(self, *args, **kwargs)
return self
[]
def with_args(self, *args, **kwargs): self.args = args self.kwargs = kwargs return self
[ "def", "with_args", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "args", "=", "args", "self", ".", "kwargs", "=", "kwargs", "return", "self" ]
https://github.com/hamcrest/PyHamcrest/blob/11aafabd688af2db23e8614f89da3015fd39f611/src/hamcrest/core/core/raises.py#L124-L127
LinOTP/LinOTP
bb3940bbaccea99550e6c063ff824f258dd6d6d7
linotp/lib/userservice.py
python
get_cookie_expiry
()
return config.get("selfservice.auth_expiry", False)
get the cookie encryption expiry from the config - if the selfservice is dropped from running locally, this configuration option might not exist anymore :return: return the cookie encryption expiry
get the cookie encryption expiry from the config - if the selfservice is dropped from running locally, this configuration option might not exist anymore
[ "get", "the", "cookie", "encryption", "expiry", "from", "the", "config", "-", "if", "the", "selfservice", "is", "dropped", "from", "running", "locally", "this", "configuration", "option", "might", "not", "exist", "anymore" ]
def get_cookie_expiry(): """ get the cookie encryption expiry from the config - if the selfservice is dropped from running locally, this configuration option might not exist anymore :return: return the cookie encryption expiry """ config = request_context["Config"] return config.get("selfservice.auth_expiry", False)
[ "def", "get_cookie_expiry", "(", ")", ":", "config", "=", "request_context", "[", "\"Config\"", "]", "return", "config", ".", "get", "(", "\"selfservice.auth_expiry\"", ",", "False", ")" ]
https://github.com/LinOTP/LinOTP/blob/bb3940bbaccea99550e6c063ff824f258dd6d6d7/linotp/lib/userservice.py#L263-L273
scipy/scipy
e0a749f01e79046642ccfdc419edbf9e7ca141ad
scipy/stats/_stats_py.py
python
relfreq
(a, numbins=10, defaultreallimits=None, weights=None)
return RelfreqResult(h, l, b, e)
Return a relative frequency histogram, using the histogram function. A relative frequency histogram is a mapping of the number of observations in each of the bins relative to the total of observations. Parameters ---------- a : array_like Input array. numbins : int, optional The number of bins to use for the histogram. Default is 10. defaultreallimits : tuple (lower, upper), optional The lower and upper values for the range of the histogram. If no value is given, a range slightly larger than the range of the values in a is used. Specifically ``(a.min() - s, a.max() + s)``, where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``. weights : array_like, optional The weights for each value in `a`. Default is None, which gives each value a weight of 1.0 Returns ------- frequency : ndarray Binned values of relative frequency. lowerlimit : float Lower real limit. binsize : float Width of each bin. extrapoints : int Extra points. Examples -------- >>> import matplotlib.pyplot as plt >>> from numpy.random import default_rng >>> from scipy import stats >>> rng = default_rng() >>> a = np.array([2, 4, 1, 2, 3, 2]) >>> res = stats.relfreq(a, numbins=4) >>> res.frequency array([ 0.16666667, 0.5 , 0.16666667, 0.16666667]) >>> np.sum(res.frequency) # relative frequencies should add up to 1 1.0 Create a normal distribution with 1000 random values >>> samples = stats.norm.rvs(size=1000, random_state=rng) Calculate relative frequencies >>> res = stats.relfreq(samples, numbins=25) Calculate space of values for x >>> x = res.lowerlimit + np.linspace(0, res.binsize*res.frequency.size, ... res.frequency.size) Plot relative frequency histogram >>> fig = plt.figure(figsize=(5, 4)) >>> ax = fig.add_subplot(1, 1, 1) >>> ax.bar(x, res.frequency, width=res.binsize) >>> ax.set_title('Relative frequency histogram') >>> ax.set_xlim([x.min(), x.max()]) >>> plt.show()
Return a relative frequency histogram, using the histogram function.
[ "Return", "a", "relative", "frequency", "histogram", "using", "the", "histogram", "function", "." ]
def relfreq(a, numbins=10, defaultreallimits=None, weights=None): """Return a relative frequency histogram, using the histogram function. A relative frequency histogram is a mapping of the number of observations in each of the bins relative to the total of observations. Parameters ---------- a : array_like Input array. numbins : int, optional The number of bins to use for the histogram. Default is 10. defaultreallimits : tuple (lower, upper), optional The lower and upper values for the range of the histogram. If no value is given, a range slightly larger than the range of the values in a is used. Specifically ``(a.min() - s, a.max() + s)``, where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``. weights : array_like, optional The weights for each value in `a`. Default is None, which gives each value a weight of 1.0 Returns ------- frequency : ndarray Binned values of relative frequency. lowerlimit : float Lower real limit. binsize : float Width of each bin. extrapoints : int Extra points. Examples -------- >>> import matplotlib.pyplot as plt >>> from numpy.random import default_rng >>> from scipy import stats >>> rng = default_rng() >>> a = np.array([2, 4, 1, 2, 3, 2]) >>> res = stats.relfreq(a, numbins=4) >>> res.frequency array([ 0.16666667, 0.5 , 0.16666667, 0.16666667]) >>> np.sum(res.frequency) # relative frequencies should add up to 1 1.0 Create a normal distribution with 1000 random values >>> samples = stats.norm.rvs(size=1000, random_state=rng) Calculate relative frequencies >>> res = stats.relfreq(samples, numbins=25) Calculate space of values for x >>> x = res.lowerlimit + np.linspace(0, res.binsize*res.frequency.size, ... res.frequency.size) Plot relative frequency histogram >>> fig = plt.figure(figsize=(5, 4)) >>> ax = fig.add_subplot(1, 1, 1) >>> ax.bar(x, res.frequency, width=res.binsize) >>> ax.set_title('Relative frequency histogram') >>> ax.set_xlim([x.min(), x.max()]) >>> plt.show() """ a = np.asanyarray(a) h, l, b, e = _histogram(a, numbins, defaultreallimits, weights=weights) h = h / a.shape[0] return RelfreqResult(h, l, b, e)
[ "def", "relfreq", "(", "a", ",", "numbins", "=", "10", ",", "defaultreallimits", "=", "None", ",", "weights", "=", "None", ")", ":", "a", "=", "np", ".", "asanyarray", "(", "a", ")", "h", ",", "l", ",", "b", ",", "e", "=", "_histogram", "(", "a", ",", "numbins", ",", "defaultreallimits", ",", "weights", "=", "weights", ")", "h", "=", "h", "/", "a", ".", "shape", "[", "0", "]", "return", "RelfreqResult", "(", "h", ",", "l", ",", "b", ",", "e", ")" ]
https://github.com/scipy/scipy/blob/e0a749f01e79046642ccfdc419edbf9e7ca141ad/scipy/stats/_stats_py.py#L2086-L2159
sdaps/sdaps
51d1072185223f5e48512661e2c1e8399d63e876
sdaps/recognize/buddies.py
python
Checkbox.get_outline_mask
(self)
return surf, xoff, yoff
[]
def get_outline_mask(self): cr, surf, line_width, width, height, xoff, yoff = self.prepare_mask() if self.obj.form == "ellipse": cr.save() cr.scale((width - line_width) / 2.0, (height - line_width) / 2.0) cr.arc(0, 0, 1.0, 0, 2*math.pi) # Restore old matrix (without removing the current path) cr.restore() else: cr.translate(-0.5 * width, -0.5 * height) cr.rectangle(line_width / 2, line_width / 2, width - line_width / 2, height - line_width / 2) cr.stroke() surf.flush() del cr return surf, xoff, yoff
[ "def", "get_outline_mask", "(", "self", ")", ":", "cr", ",", "surf", ",", "line_width", ",", "width", ",", "height", ",", "xoff", ",", "yoff", "=", "self", ".", "prepare_mask", "(", ")", "if", "self", ".", "obj", ".", "form", "==", "\"ellipse\"", ":", "cr", ".", "save", "(", ")", "cr", ".", "scale", "(", "(", "width", "-", "line_width", ")", "/", "2.0", ",", "(", "height", "-", "line_width", ")", "/", "2.0", ")", "cr", ".", "arc", "(", "0", ",", "0", ",", "1.0", ",", "0", ",", "2", "*", "math", ".", "pi", ")", "# Restore old matrix (without removing the current path)", "cr", ".", "restore", "(", ")", "else", ":", "cr", ".", "translate", "(", "-", "0.5", "*", "width", ",", "-", "0.5", "*", "height", ")", "cr", ".", "rectangle", "(", "line_width", "/", "2", ",", "line_width", "/", "2", ",", "width", "-", "line_width", "/", "2", ",", "height", "-", "line_width", "/", "2", ")", "cr", ".", "stroke", "(", ")", "surf", ".", "flush", "(", ")", "del", "cr", "return", "surf", ",", "xoff", ",", "yoff" ]
https://github.com/sdaps/sdaps/blob/51d1072185223f5e48512661e2c1e8399d63e876/sdaps/recognize/buddies.py#L613-L632
cdent/gabbi
73dd8996ef4c7a9b50eb70532f830b71d41a1225
gabbi/handlers/jsonhandler.py
python
JSONHandler.action
(self, test, path, value=None)
Test json_paths against json data.
Test json_paths against json data.
[ "Test", "json_paths", "against", "json", "data", "." ]
def action(self, test, path, value=None): """Test json_paths against json data.""" # Do template expansion in the left hand side. lhs_path = test.replace_template(path) rhs_path = rhs_match = None try: lhs_match = self.extract_json_path_value( test.response_data, lhs_path) except AttributeError: raise AssertionError('unable to extract JSON from test results') except ValueError: raise AssertionError('left hand side json path %s cannot match ' '%s' % (path, test.response_data)) # read data from disk if the value starts with '<@' if isinstance(value, six.string_types) and value.startswith('<@'): # Do template expansion in the rhs if rhs_path is provided. if ':' in value: value, rhs_path = value.split(':$', 1) rhs_path = test.replace_template('$' + rhs_path) value = self.load_data_file(test, value.replace('<@', '', 1)) if rhs_path: try: rhs_match = self.extract_json_path_value(value, rhs_path) except AttributeError: raise AssertionError('unable to extract JSON from data on ' 'disk') except ValueError: raise AssertionError('right hand side json path %s cannot ' 'match %s' % (rhs_path, value)) # If expected is a string, check to see if it is a regex. is_regex = (isinstance(value, six.string_types) and value.startswith('/') and value.endswith('/') and len(value) > 1) expected = (rhs_match or test.replace_template(value, escape_regex=is_regex)) match = lhs_match if is_regex and not rhs_match: expected = expected[1:-1] # match may be a number so stringify match = six.text_type(match) test.assertRegex( match, expected, 'Expect jsonpath %s to match /%s/, got %s' % (path, expected, match)) else: test.assertEqual(expected, match, 'Unable to match %s as %s, got %s' % (path, expected, match))
[ "def", "action", "(", "self", ",", "test", ",", "path", ",", "value", "=", "None", ")", ":", "# Do template expansion in the left hand side.", "lhs_path", "=", "test", ".", "replace_template", "(", "path", ")", "rhs_path", "=", "rhs_match", "=", "None", "try", ":", "lhs_match", "=", "self", ".", "extract_json_path_value", "(", "test", ".", "response_data", ",", "lhs_path", ")", "except", "AttributeError", ":", "raise", "AssertionError", "(", "'unable to extract JSON from test results'", ")", "except", "ValueError", ":", "raise", "AssertionError", "(", "'left hand side json path %s cannot match '", "'%s'", "%", "(", "path", ",", "test", ".", "response_data", ")", ")", "# read data from disk if the value starts with '<@'", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", "and", "value", ".", "startswith", "(", "'<@'", ")", ":", "# Do template expansion in the rhs if rhs_path is provided.", "if", "':'", "in", "value", ":", "value", ",", "rhs_path", "=", "value", ".", "split", "(", "':$'", ",", "1", ")", "rhs_path", "=", "test", ".", "replace_template", "(", "'$'", "+", "rhs_path", ")", "value", "=", "self", ".", "load_data_file", "(", "test", ",", "value", ".", "replace", "(", "'<@'", ",", "''", ",", "1", ")", ")", "if", "rhs_path", ":", "try", ":", "rhs_match", "=", "self", ".", "extract_json_path_value", "(", "value", ",", "rhs_path", ")", "except", "AttributeError", ":", "raise", "AssertionError", "(", "'unable to extract JSON from data on '", "'disk'", ")", "except", "ValueError", ":", "raise", "AssertionError", "(", "'right hand side json path %s cannot '", "'match %s'", "%", "(", "rhs_path", ",", "value", ")", ")", "# If expected is a string, check to see if it is a regex.", "is_regex", "=", "(", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", "and", "value", ".", "startswith", "(", "'/'", ")", "and", "value", ".", "endswith", "(", "'/'", ")", "and", "len", "(", "value", ")", ">", "1", ")", "expected", "=", "(", "rhs_match", "or", "test", ".", "replace_template", "(", "value", ",", "escape_regex", "=", "is_regex", ")", ")", "match", "=", "lhs_match", "if", "is_regex", "and", "not", "rhs_match", ":", "expected", "=", "expected", "[", "1", ":", "-", "1", "]", "# match may be a number so stringify", "match", "=", "six", ".", "text_type", "(", "match", ")", "test", ".", "assertRegex", "(", "match", ",", "expected", ",", "'Expect jsonpath %s to match /%s/, got %s'", "%", "(", "path", ",", "expected", ",", "match", ")", ")", "else", ":", "test", ".", "assertEqual", "(", "expected", ",", "match", ",", "'Unable to match %s as %s, got %s'", "%", "(", "path", ",", "expected", ",", "match", ")", ")" ]
https://github.com/cdent/gabbi/blob/73dd8996ef4c7a9b50eb70532f830b71d41a1225/gabbi/handlers/jsonhandler.py#L91-L141
openstack/cinder
23494a6d6c51451688191e1847a458f1d3cdcaa5
cinder/volume/drivers/nimble.py
python
NimbleBaseVolumeDriver.delete_group_snapshot
(self, context, group_snapshot, snapshots)
return model_update, snapshots_model_update
Deletes a group snapshot.
Deletes a group snapshot.
[ "Deletes", "a", "group", "snapshot", "." ]
def delete_group_snapshot(self, context, group_snapshot, snapshots): """Deletes a group snapshot.""" if not volume_utils.is_group_a_cg_snapshot_type(group_snapshot): raise NotImplementedError() snap_name = group_snapshot.id model_update = {'status': fields.ConsistencyGroupStatus.DELETED} snapshots_model_update = [] snapcoll_id = self.APIExecutor.get_snapcoll_id_by_name(snap_name) try: self.APIExecutor.snapcoll_delete(snapcoll_id) for snapshot in snapshots: snapshots_model_update.append( {'id': snapshot.id, 'status': fields.SnapshotStatus.DELETED}) except Exception as e: LOG.error("Error deleting volume group snapshot." "Error received: %(e)s", {'e': e}) model_update = { 'status': fields.GroupSnapshotStatus.ERROR_DELETING} return model_update, snapshots_model_update
[ "def", "delete_group_snapshot", "(", "self", ",", "context", ",", "group_snapshot", ",", "snapshots", ")", ":", "if", "not", "volume_utils", ".", "is_group_a_cg_snapshot_type", "(", "group_snapshot", ")", ":", "raise", "NotImplementedError", "(", ")", "snap_name", "=", "group_snapshot", ".", "id", "model_update", "=", "{", "'status'", ":", "fields", ".", "ConsistencyGroupStatus", ".", "DELETED", "}", "snapshots_model_update", "=", "[", "]", "snapcoll_id", "=", "self", ".", "APIExecutor", ".", "get_snapcoll_id_by_name", "(", "snap_name", ")", "try", ":", "self", ".", "APIExecutor", ".", "snapcoll_delete", "(", "snapcoll_id", ")", "for", "snapshot", "in", "snapshots", ":", "snapshots_model_update", ".", "append", "(", "{", "'id'", ":", "snapshot", ".", "id", ",", "'status'", ":", "fields", ".", "SnapshotStatus", ".", "DELETED", "}", ")", "except", "Exception", "as", "e", ":", "LOG", ".", "error", "(", "\"Error deleting volume group snapshot.\"", "\"Error received: %(e)s\"", ",", "{", "'e'", ":", "e", "}", ")", "model_update", "=", "{", "'status'", ":", "fields", ".", "GroupSnapshotStatus", ".", "ERROR_DELETING", "}", "return", "model_update", ",", "snapshots_model_update" ]
https://github.com/openstack/cinder/blob/23494a6d6c51451688191e1847a458f1d3cdcaa5/cinder/volume/drivers/nimble.py#L901-L920
ioflo/ioflo
177ac656d7c4ff801aebb0d8b401db365a5248ce
ioflo/aid/vectoring.py
python
insideOnly
(p, vs)
return inside(p, vs, side=False)
Returns True if p is strictly inside polygon given by vs, False otherwise. If p on edge or vertex it is considered as outside
Returns True if p is strictly inside polygon given by vs, False otherwise. If p on edge or vertex it is considered as outside
[ "Returns", "True", "if", "p", "is", "strictly", "inside", "polygon", "given", "by", "vs", "False", "otherwise", ".", "If", "p", "on", "edge", "or", "vertex", "it", "is", "considered", "as", "outside" ]
def insideOnly(p, vs): """ Returns True if p is strictly inside polygon given by vs, False otherwise. If p on edge or vertex it is considered as outside """ return inside(p, vs, side=False)
[ "def", "insideOnly", "(", "p", ",", "vs", ")", ":", "return", "inside", "(", "p", ",", "vs", ",", "side", "=", "False", ")" ]
https://github.com/ioflo/ioflo/blob/177ac656d7c4ff801aebb0d8b401db365a5248ce/ioflo/aid/vectoring.py#L344-L349
GoogleCloudPlatform/professional-services
0c707aa97437f3d154035ef8548109b7882f71da
examples/dlp/cloud_function_example/cloud_function/main.py
python
_post_scrubbed_message_to_pub_sub
(message_topic, scrubbed_message, log_json)
Posts the log json payload with redacted PII to a pub/sub topic. Args: message_topic: The pub/sub topic to post the message to. scrubbed_message: The PII scrubbed message string. log_json: The original log json.
Posts the log json payload with redacted PII to a pub/sub topic.
[ "Posts", "the", "log", "json", "payload", "with", "redacted", "PII", "to", "a", "pub", "/", "sub", "topic", "." ]
def _post_scrubbed_message_to_pub_sub(message_topic, scrubbed_message, log_json): """Posts the log json payload with redacted PII to a pub/sub topic. Args: message_topic: The pub/sub topic to post the message to. scrubbed_message: The PII scrubbed message string. log_json: The original log json. """ publisher = pubsub_v1.PublisherClient() topic_path = publisher.topic_path(_PROJECT_ID, message_topic) log_json['jsonPayload']['message'] = scrubbed_message data = json.dumps(log_json).encode('utf-8') message_future = publisher.publish(topic_path, data=data) message_future.add_done_callback(_post_scrubbed_message_callback)
[ "def", "_post_scrubbed_message_to_pub_sub", "(", "message_topic", ",", "scrubbed_message", ",", "log_json", ")", ":", "publisher", "=", "pubsub_v1", ".", "PublisherClient", "(", ")", "topic_path", "=", "publisher", ".", "topic_path", "(", "_PROJECT_ID", ",", "message_topic", ")", "log_json", "[", "'jsonPayload'", "]", "[", "'message'", "]", "=", "scrubbed_message", "data", "=", "json", ".", "dumps", "(", "log_json", ")", ".", "encode", "(", "'utf-8'", ")", "message_future", "=", "publisher", ".", "publish", "(", "topic_path", ",", "data", "=", "data", ")", "message_future", ".", "add_done_callback", "(", "_post_scrubbed_message_callback", ")" ]
https://github.com/GoogleCloudPlatform/professional-services/blob/0c707aa97437f3d154035ef8548109b7882f71da/examples/dlp/cloud_function_example/cloud_function/main.py#L125-L140
ipython/ipython
c0abea7a6dfe52c1f74c9d0387d4accadba7cc14
IPython/lib/backgroundjobs.py
python
BackgroundJobManager.remove
(self,num)
Remove a finished (completed or dead) job.
Remove a finished (completed or dead) job.
[ "Remove", "a", "finished", "(", "completed", "or", "dead", ")", "job", "." ]
def remove(self,num): """Remove a finished (completed or dead) job.""" try: job = self.all[num] except KeyError: error('Job #%s not found' % num) else: stat_code = job.stat_code if stat_code == self._s_running: error('Job #%s is still running, it can not be removed.' % num) return elif stat_code == self._s_completed: self.completed.remove(job) elif stat_code == self._s_dead: self.dead.remove(job)
[ "def", "remove", "(", "self", ",", "num", ")", ":", "try", ":", "job", "=", "self", ".", "all", "[", "num", "]", "except", "KeyError", ":", "error", "(", "'Job #%s not found'", "%", "num", ")", "else", ":", "stat_code", "=", "job", ".", "stat_code", "if", "stat_code", "==", "self", ".", "_s_running", ":", "error", "(", "'Job #%s is still running, it can not be removed.'", "%", "num", ")", "return", "elif", "stat_code", "==", "self", ".", "_s_completed", ":", "self", ".", "completed", ".", "remove", "(", "job", ")", "elif", "stat_code", "==", "self", ".", "_s_dead", ":", "self", ".", "dead", ".", "remove", "(", "job", ")" ]
https://github.com/ipython/ipython/blob/c0abea7a6dfe52c1f74c9d0387d4accadba7cc14/IPython/lib/backgroundjobs.py#L295-L310
moinwiki/moin
568f223231aadecbd3b21a701ec02271f8d8021d
src/moin/macros/MailTo.py
python
Macro.macro
(self, content, arguments, page_url, alternative)
return result
Invocation: <<MailTo(user AT example DOT org, write me)>> where 2nd parameter is optional.
Invocation: <<MailTo(user AT example DOT org, write me)>> where 2nd parameter is optional.
[ "Invocation", ":", "<<MailTo", "(", "user", "AT", "example", "DOT", "org", "write", "me", ")", ">>", "where", "2nd", "parameter", "is", "optional", "." ]
def macro(self, content, arguments, page_url, alternative): """ Invocation: <<MailTo(user AT example DOT org, write me)>> where 2nd parameter is optional. """ if arguments: arguments = arguments[0].split(',') try: assert len(arguments) > 0 and len(arguments) < 3 email = arguments[0] assert len(email) >= 5 except (AttributeError, AssertionError): raise ValueError(_("MailTo: invalid format, try: <<MailTo(user AT example DOT org, write me)>>")) try: text = arguments[1] except IndexError: text = '' if flaskg.user.valid: # decode address and generate mailto: link email = decodeSpamSafeEmail(email) result = moin_page.a(attrib={xlink.href: 'mailto:{0}'.format(email)}, children=[text or email]) else: # unknown user, maybe even a spambot, so just return text as given in macro args if text: text += " " result = moin_page.code(children=[text, "<{0}>".format(email)]) return result
[ "def", "macro", "(", "self", ",", "content", ",", "arguments", ",", "page_url", ",", "alternative", ")", ":", "if", "arguments", ":", "arguments", "=", "arguments", "[", "0", "]", ".", "split", "(", "','", ")", "try", ":", "assert", "len", "(", "arguments", ")", ">", "0", "and", "len", "(", "arguments", ")", "<", "3", "email", "=", "arguments", "[", "0", "]", "assert", "len", "(", "email", ")", ">=", "5", "except", "(", "AttributeError", ",", "AssertionError", ")", ":", "raise", "ValueError", "(", "_", "(", "\"MailTo: invalid format, try: <<MailTo(user AT example DOT org, write me)>>\"", ")", ")", "try", ":", "text", "=", "arguments", "[", "1", "]", "except", "IndexError", ":", "text", "=", "''", "if", "flaskg", ".", "user", ".", "valid", ":", "# decode address and generate mailto: link", "email", "=", "decodeSpamSafeEmail", "(", "email", ")", "result", "=", "moin_page", ".", "a", "(", "attrib", "=", "{", "xlink", ".", "href", ":", "'mailto:{0}'", ".", "format", "(", "email", ")", "}", ",", "children", "=", "[", "text", "or", "email", "]", ")", "else", ":", "# unknown user, maybe even a spambot, so just return text as given in macro args", "if", "text", ":", "text", "+=", "\" \"", "result", "=", "moin_page", ".", "code", "(", "children", "=", "[", "text", ",", "\"<{0}>\"", ".", "format", "(", "email", ")", "]", ")", "return", "result" ]
https://github.com/moinwiki/moin/blob/568f223231aadecbd3b21a701ec02271f8d8021d/src/moin/macros/MailTo.py#L20-L49
kmpm/nodemcu-uploader
6178f40fff2deadd56b5bc474f9b4475ef444b37
nodemcu_uploader/uploader.py
python
Uploader.exec_file
(self, path)
execute the lines in the local file 'path
execute the lines in the local file 'path
[ "execute", "the", "lines", "in", "the", "local", "file", "path" ]
def exec_file(self, path): """execute the lines in the local file 'path'""" filename = os.path.basename(path) log.info('Execute %s', filename) content = from_file(path).replace('\r', '').split('\n') res = '> ' for line in content: line = line.rstrip('\n') retlines = (res + self.__exchange(line)).splitlines() # Log all but the last line res = retlines.pop() for lin in retlines: log.info(lin) # last line log.info(res)
[ "def", "exec_file", "(", "self", ",", "path", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "log", ".", "info", "(", "'Execute %s'", ",", "filename", ")", "content", "=", "from_file", "(", "path", ")", ".", "replace", "(", "'\\r'", ",", "''", ")", ".", "split", "(", "'\\n'", ")", "res", "=", "'> '", "for", "line", "in", "content", ":", "line", "=", "line", ".", "rstrip", "(", "'\\n'", ")", "retlines", "=", "(", "res", "+", "self", ".", "__exchange", "(", "line", ")", ")", ".", "splitlines", "(", ")", "# Log all but the last line", "res", "=", "retlines", ".", "pop", "(", ")", "for", "lin", "in", "retlines", ":", "log", ".", "info", "(", "lin", ")", "# last line", "log", ".", "info", "(", "res", ")" ]
https://github.com/kmpm/nodemcu-uploader/blob/6178f40fff2deadd56b5bc474f9b4475ef444b37/nodemcu_uploader/uploader.py#L358-L374
RobotLocomotion/LabelFusion
e4d90bef01552a9e26e8ee37177f92294ce03217
modules/labelfusion/registration.py
python
GlobalRegistration.segmentTable
(self, scenePolyData=None, searchRadius=0.3, visualize=True, thickness=0.01, pointOnTable=None, pointAboveTable=None)
return returnData
This requires two clicks using measurement panel. One on the table, one above the table on one of the objects. Call them point0, point1. Then we will attempt to fit a plane that passes through point0 with approximate normal point1 - point0 :param scenePolyData: :param searchRadius: :return:
This requires two clicks using measurement panel. One on the table, one above the table on one of the objects. Call them point0, point1. Then we will attempt to fit a plane that passes through point0 with approximate normal point1 - point0 :param scenePolyData: :param searchRadius: :return:
[ "This", "requires", "two", "clicks", "using", "measurement", "panel", ".", "One", "on", "the", "table", "one", "above", "the", "table", "on", "one", "of", "the", "objects", ".", "Call", "them", "point0", "point1", ".", "Then", "we", "will", "attempt", "to", "fit", "a", "plane", "that", "passes", "through", "point0", "with", "approximate", "normal", "point1", "-", "point0", ":", "param", "scenePolyData", ":", ":", "param", "searchRadius", ":", ":", "return", ":" ]
def segmentTable(self, scenePolyData=None, searchRadius=0.3, visualize=True, thickness=0.01, pointOnTable=None, pointAboveTable=None): """ This requires two clicks using measurement panel. One on the table, one above the table on one of the objects. Call them point0, point1. Then we will attempt to fit a plane that passes through point0 with approximate normal point1 - point0 :param scenePolyData: :param searchRadius: :return: """ if scenePolyData is None: scenePolyData = om.findObjectByName('reconstruction').polyData if pointOnTable is None: assert (len(self.measurementPanel.pickPoints) >= 2) pointOnTable = self.measurementPanel.pickPoints[0] pointAboveTable = self.measurementPanel.pickPoints[1] expectedNormal= pointAboveTable - pointOnTable expectedNormal = expectedNormal/np.linalg.norm(expectedNormal) polyData, normal = segmentation.applyPlaneFit(scenePolyData, searchOrigin=pointOnTable, searchRadius=searchRadius, expectedNormal=expectedNormal) # get points above plane abovePolyData = filterUtils.thresholdPoints(polyData, 'dist_to_plane', [thickness / 2.0, np.inf]) belowPolyData = filterUtils.thresholdPoints(polyData, 'dist_to_plane', [-np.inf, -thickness / 2.0]) self.aboveTablePolyData = abovePolyData # some debugging visualization if visualize: vis.showPolyData(abovePolyData, 'above table segmentation', color=[0, 1, 0], parent=self.visFolder) arrowLength = 0.3 headRadius = 0.02 d = DebugData() d.addArrow(pointOnTable, pointOnTable + arrowLength*expectedNormal, headRadius=headRadius) vis.showPolyData(d.getPolyData(), 'expected normal', color=[1, 0, 0], parent=self.visFolder) d = DebugData() d.addArrow(pointOnTable, pointOnTable + arrowLength * normal, headRadius=headRadius) vis.showPolyData(d.getPolyData(), 'computed normal', color=[0, 1, 0], parent=self.visFolder) returnData = dict() returnData['abovePolyData'] = abovePolyData returnData['polyData'] = polyData returnData['normal'] = normal returnData['pointOnTable'] = pointOnTable return returnData
[ "def", "segmentTable", "(", "self", ",", "scenePolyData", "=", "None", ",", "searchRadius", "=", "0.3", ",", "visualize", "=", "True", ",", "thickness", "=", "0.01", ",", "pointOnTable", "=", "None", ",", "pointAboveTable", "=", "None", ")", ":", "if", "scenePolyData", "is", "None", ":", "scenePolyData", "=", "om", ".", "findObjectByName", "(", "'reconstruction'", ")", ".", "polyData", "if", "pointOnTable", "is", "None", ":", "assert", "(", "len", "(", "self", ".", "measurementPanel", ".", "pickPoints", ")", ">=", "2", ")", "pointOnTable", "=", "self", ".", "measurementPanel", ".", "pickPoints", "[", "0", "]", "pointAboveTable", "=", "self", ".", "measurementPanel", ".", "pickPoints", "[", "1", "]", "expectedNormal", "=", "pointAboveTable", "-", "pointOnTable", "expectedNormal", "=", "expectedNormal", "/", "np", ".", "linalg", ".", "norm", "(", "expectedNormal", ")", "polyData", ",", "normal", "=", "segmentation", ".", "applyPlaneFit", "(", "scenePolyData", ",", "searchOrigin", "=", "pointOnTable", ",", "searchRadius", "=", "searchRadius", ",", "expectedNormal", "=", "expectedNormal", ")", "# get points above plane", "abovePolyData", "=", "filterUtils", ".", "thresholdPoints", "(", "polyData", ",", "'dist_to_plane'", ",", "[", "thickness", "/", "2.0", ",", "np", ".", "inf", "]", ")", "belowPolyData", "=", "filterUtils", ".", "thresholdPoints", "(", "polyData", ",", "'dist_to_plane'", ",", "[", "-", "np", ".", "inf", ",", "-", "thickness", "/", "2.0", "]", ")", "self", ".", "aboveTablePolyData", "=", "abovePolyData", "# some debugging visualization", "if", "visualize", ":", "vis", ".", "showPolyData", "(", "abovePolyData", ",", "'above table segmentation'", ",", "color", "=", "[", "0", ",", "1", ",", "0", "]", ",", "parent", "=", "self", ".", "visFolder", ")", "arrowLength", "=", "0.3", "headRadius", "=", "0.02", "d", "=", "DebugData", "(", ")", "d", ".", "addArrow", "(", "pointOnTable", ",", "pointOnTable", "+", "arrowLength", "*", "expectedNormal", ",", "headRadius", "=", "headRadius", ")", "vis", ".", "showPolyData", "(", "d", ".", "getPolyData", "(", ")", ",", "'expected normal'", ",", "color", "=", "[", "1", ",", "0", ",", "0", "]", ",", "parent", "=", "self", ".", "visFolder", ")", "d", "=", "DebugData", "(", ")", "d", ".", "addArrow", "(", "pointOnTable", ",", "pointOnTable", "+", "arrowLength", "*", "normal", ",", "headRadius", "=", "headRadius", ")", "vis", ".", "showPolyData", "(", "d", ".", "getPolyData", "(", ")", ",", "'computed normal'", ",", "color", "=", "[", "0", ",", "1", ",", "0", "]", ",", "parent", "=", "self", ".", "visFolder", ")", "returnData", "=", "dict", "(", ")", "returnData", "[", "'abovePolyData'", "]", "=", "abovePolyData", "returnData", "[", "'polyData'", "]", "=", "polyData", "returnData", "[", "'normal'", "]", "=", "normal", "returnData", "[", "'pointOnTable'", "]", "=", "pointOnTable", "return", "returnData" ]
https://github.com/RobotLocomotion/LabelFusion/blob/e4d90bef01552a9e26e8ee37177f92294ce03217/modules/labelfusion/registration.py#L150-L206
youyuge34/PI-REC
9f8f1adff169fda301f3134ac730991484a6b128
main.py
python
load_config_costume
(mode, config)
return config
r"""loads model costume config Args: mode (int): 5: draw mode (int): 6: refinement
r"""loads model costume config
[ "r", "loads", "model", "costume", "config" ]
def load_config_costume(mode, config): r"""loads model costume config Args: mode (int): 5: draw mode (int): 6: refinement """ print('load_config_demo----->') if mode == 5: config.MODE = 5 elif mode == 6: config.MODE = 6 return config
[ "def", "load_config_costume", "(", "mode", ",", "config", ")", ":", "print", "(", "'load_config_demo----->'", ")", "if", "mode", "==", "5", ":", "config", ".", "MODE", "=", "5", "elif", "mode", "==", "6", ":", "config", ".", "MODE", "=", "6", "return", "config" ]
https://github.com/youyuge34/PI-REC/blob/9f8f1adff169fda301f3134ac730991484a6b128/main.py#L151-L163
kanzure/pyphantomjs
e878516bb10f6ce27302aabb5a5f30247ea261b8
pyphantomjs/utils.py
python
MessageHandler.process
(self, msgType, msg)
[]
def process(self, msgType, msg): now = QDateTime.currentDateTime().toString(Qt.ISODate) if msgType == QtDebugMsg: if self.verbose: print '%s [DEBUG] %s' % (now, msg) elif msgType == QtWarningMsg: print >> sys.stderr, '%s [WARNING] %s' % (now, msg) elif msgType == QtCriticalMsg: print >> sys.stderr, '%s [CRITICAL] %s' % (now, msg) elif msgType == QtFatalMsg: print >> sys.stderr, '%s [FATAL] %s' % (now, msg)
[ "def", "process", "(", "self", ",", "msgType", ",", "msg", ")", ":", "now", "=", "QDateTime", ".", "currentDateTime", "(", ")", ".", "toString", "(", "Qt", ".", "ISODate", ")", "if", "msgType", "==", "QtDebugMsg", ":", "if", "self", ".", "verbose", ":", "print", "'%s [DEBUG] %s'", "%", "(", "now", ",", "msg", ")", "elif", "msgType", "==", "QtWarningMsg", ":", "print", ">>", "sys", ".", "stderr", ",", "'%s [WARNING] %s'", "%", "(", "now", ",", "msg", ")", "elif", "msgType", "==", "QtCriticalMsg", ":", "print", ">>", "sys", ".", "stderr", ",", "'%s [CRITICAL] %s'", "%", "(", "now", ",", "msg", ")", "elif", "msgType", "==", "QtFatalMsg", ":", "print", ">>", "sys", ".", "stderr", ",", "'%s [FATAL] %s'", "%", "(", "now", ",", "msg", ")" ]
https://github.com/kanzure/pyphantomjs/blob/e878516bb10f6ce27302aabb5a5f30247ea261b8/pyphantomjs/utils.py#L95-L106
CENSUS/choronzon
d702c318e2292a061da57d7ba5f88d4c4b0f5256
choronzon.py
python
Choronzon.fuzz
(self)
Each time fuzz method is called, it is indicating that a new epoch has begun. The function picks random couples of chromosomes from the population and apply to them recombination and mutation algorithms. Finally, the new (fuzzed) chromosomes are imported to the new generation.
Each time fuzz method is called, it is indicating that a new epoch has begun. The function picks random couples of chromosomes from the population and apply to them recombination and mutation algorithms. Finally, the new (fuzzed) chromosomes are imported to the new generation.
[ "Each", "time", "fuzz", "method", "is", "called", "it", "is", "indicating", "that", "a", "new", "epoch", "has", "begun", ".", "The", "function", "picks", "random", "couples", "of", "chromosomes", "from", "the", "population", "and", "apply", "to", "them", "recombination", "and", "mutation", "algorithms", ".", "Finally", "the", "new", "(", "fuzzed", ")", "chromosomes", "are", "imported", "to", "the", "new", "generation", "." ]
def fuzz(self): ''' Each time fuzz method is called, it is indicating that a new epoch has begun. The function picks random couples of chromosomes from the population and apply to them recombination and mutation algorithms. Finally, the new (fuzzed) chromosomes are imported to the new generation. ''' self.population.new_epoch() self.campaign.log('Fuzzing of chromosomes has begun.') # This is to keep the family tree of the chromosomes for male, female in self.population.get_couple_from_previous(True): # assume that the UID is colliding with another's chromosome UID uid_collision = True maleclone = male.clone() femaleclone = female.clone() # assign new UIDs to the new chromosomes until they are unique while uid_collision: if self.population.does_exist(maleclone.uid) == False and \ self.population.does_exist(femaleclone.uid) == False: uid_collision = False else: maleclone.new_uid() femaleclone.new_uid() son, daughter = self.strategy.recombine(maleclone, femaleclone) self.population.add_chromosome(son) self.population.add_chromosome(daughter) self.campaign.log('The stage of fuzzing is finished') if 'KeepGenerations' in self.configuration and \ self.configuration['KeepGenerations']: gpath = self.campaign.create_directory( '%s' % self.population.epoch ) for chromo in self.population.get_all_from_current(): path = os.path.join( '%s' % gpath, '%s' % chromo.uid ) with open(path, 'wb') as fout: fout.write(chromo.serialize())
[ "def", "fuzz", "(", "self", ")", ":", "self", ".", "population", ".", "new_epoch", "(", ")", "self", ".", "campaign", ".", "log", "(", "'Fuzzing of chromosomes has begun.'", ")", "# This is to keep the family tree of the chromosomes", "for", "male", ",", "female", "in", "self", ".", "population", ".", "get_couple_from_previous", "(", "True", ")", ":", "# assume that the UID is colliding with another's chromosome UID", "uid_collision", "=", "True", "maleclone", "=", "male", ".", "clone", "(", ")", "femaleclone", "=", "female", ".", "clone", "(", ")", "# assign new UIDs to the new chromosomes until they are unique", "while", "uid_collision", ":", "if", "self", ".", "population", ".", "does_exist", "(", "maleclone", ".", "uid", ")", "==", "False", "and", "self", ".", "population", ".", "does_exist", "(", "femaleclone", ".", "uid", ")", "==", "False", ":", "uid_collision", "=", "False", "else", ":", "maleclone", ".", "new_uid", "(", ")", "femaleclone", ".", "new_uid", "(", ")", "son", ",", "daughter", "=", "self", ".", "strategy", ".", "recombine", "(", "maleclone", ",", "femaleclone", ")", "self", ".", "population", ".", "add_chromosome", "(", "son", ")", "self", ".", "population", ".", "add_chromosome", "(", "daughter", ")", "self", ".", "campaign", ".", "log", "(", "'The stage of fuzzing is finished'", ")", "if", "'KeepGenerations'", "in", "self", ".", "configuration", "and", "self", ".", "configuration", "[", "'KeepGenerations'", "]", ":", "gpath", "=", "self", ".", "campaign", ".", "create_directory", "(", "'%s'", "%", "self", ".", "population", ".", "epoch", ")", "for", "chromo", "in", "self", ".", "population", ".", "get_all_from_current", "(", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "'%s'", "%", "gpath", ",", "'%s'", "%", "chromo", ".", "uid", ")", "with", "open", "(", "path", ",", "'wb'", ")", "as", "fout", ":", "fout", ".", "write", "(", "chromo", ".", "serialize", "(", ")", ")" ]
https://github.com/CENSUS/choronzon/blob/d702c318e2292a061da57d7ba5f88d4c4b0f5256/choronzon.py#L78-L124
urwid/urwid
e2423b5069f51d318ea1ac0f355a0efe5448f7eb
docs/examples/real_edit.py
python
re_tab
(s)
Return a tabbed string from an expanded one.
Return a tabbed string from an expanded one.
[ "Return", "a", "tabbed", "string", "from", "an", "expanded", "one", "." ]
def re_tab(s): """Return a tabbed string from an expanded one.""" l = [] p = 0 for i in range(8, len(s), 8): if s[i-2:i] == " ": # collapse two or more spaces into a tab l.append(s[p:i].rstrip() + "\t") p = i if p == 0: return s else: l.append(s[p:]) return "".join(l)
[ "def", "re_tab", "(", "s", ")", ":", "l", "=", "[", "]", "p", "=", "0", "for", "i", "in", "range", "(", "8", ",", "len", "(", "s", ")", ",", "8", ")", ":", "if", "s", "[", "i", "-", "2", ":", "i", "]", "==", "\" \"", ":", "# collapse two or more spaces into a tab", "l", ".", "append", "(", "s", "[", "p", ":", "i", "]", ".", "rstrip", "(", ")", "+", "\"\\t\"", ")", "p", "=", "i", "if", "p", "==", "0", ":", "return", "s", "else", ":", "l", ".", "append", "(", "s", "[", "p", ":", "]", ")", "return", "\"\"", ".", "join", "(", "l", ")" ]
https://github.com/urwid/urwid/blob/e2423b5069f51d318ea1ac0f355a0efe5448f7eb/docs/examples/real_edit.py#L226-L240
DxCx/plugin.video.9anime
34358c2f701e5ddf19d3276926374a16f63f7b6a
resources/lib/ui/js2py/es6/babel.py
python
PyJs_anonymous_2830_
(require, module, exports, this, arguments, var=var)
[]
def PyJs_anonymous_2830_(require, module, exports, this, arguments, var=var): var = Scope({u'this':this, u'require':require, u'exports':exports, u'module':module, u'arguments':arguments}, var) var.registers([u'_create', u'exports', u'_interopRequireWildcard', u'_index', u'getBindingIdentifiers', u'require', u'module', u'_create2', u'getOuterBindingIdentifiers', u't', u'_interopRequireDefault']) @Js def PyJsHoisted__interopRequireDefault_(obj, this, arguments, var=var): var = Scope({u'this':this, u'obj':obj, u'arguments':arguments}, var) var.registers([u'obj']) PyJs_Object_2832_ = Js({u'default':var.get(u'obj')}) return (var.get(u'obj') if (var.get(u'obj') and var.get(u'obj').get(u'__esModule')) else PyJs_Object_2832_) PyJsHoisted__interopRequireDefault_.func_name = u'_interopRequireDefault' var.put(u'_interopRequireDefault', PyJsHoisted__interopRequireDefault_) @Js def PyJsHoisted_getBindingIdentifiers_(node, duplicates, outerOnly, this, arguments, var=var): var = Scope({u'node':node, u'duplicates':duplicates, u'this':this, u'arguments':arguments, u'outerOnly':outerOnly}, var) var.registers([u'node', u'search', u'duplicates', u'outerOnly', u'keys', u'ids', u'i', u'key', u'id', u'_ids']) var.put(u'search', Js([]).callprop(u'concat', var.get(u'node'))) var.put(u'ids', PyJsComma(Js(0.0),var.get(u'_create2').get(u'default'))(var.get(u"null"))) while var.get(u'search').get(u'length'): var.put(u'id', var.get(u'search').callprop(u'shift')) if var.get(u'id').neg(): continue var.put(u'keys', var.get(u't').get(u'getBindingIdentifiers').get(u'keys').get(var.get(u'id').get(u'type'))) if var.get(u't').callprop(u'isIdentifier', var.get(u'id')): if var.get(u'duplicates'): var.put(u'_ids', var.get(u'ids').put(var.get(u'id').get(u'name'), (var.get(u'ids').get(var.get(u'id').get(u'name')) or Js([])))) var.get(u'_ids').callprop(u'push', var.get(u'id')) else: var.get(u'ids').put(var.get(u'id').get(u'name'), var.get(u'id')) continue if var.get(u't').callprop(u'isExportDeclaration', var.get(u'id')): if var.get(u't').callprop(u'isDeclaration', var.get(u'node').get(u'declaration')): var.get(u'search').callprop(u'push', var.get(u'node').get(u'declaration')) continue if var.get(u'outerOnly'): if var.get(u't').callprop(u'isFunctionDeclaration', var.get(u'id')): var.get(u'search').callprop(u'push', var.get(u'id').get(u'id')) continue if var.get(u't').callprop(u'isFunctionExpression', var.get(u'id')): continue if var.get(u'keys'): #for JS loop var.put(u'i', Js(0.0)) while (var.get(u'i')<var.get(u'keys').get(u'length')): try: var.put(u'key', var.get(u'keys').get(var.get(u'i'))) if var.get(u'id').get(var.get(u'key')): var.put(u'search', var.get(u'search').callprop(u'concat', var.get(u'id').get(var.get(u'key')))) finally: (var.put(u'i',Js(var.get(u'i').to_number())+Js(1))-Js(1)) return var.get(u'ids') PyJsHoisted_getBindingIdentifiers_.func_name = u'getBindingIdentifiers' var.put(u'getBindingIdentifiers', PyJsHoisted_getBindingIdentifiers_) @Js def PyJsHoisted_getOuterBindingIdentifiers_(node, duplicates, this, arguments, var=var): var = Scope({u'node':node, u'duplicates':duplicates, u'this':this, u'arguments':arguments}, var) var.registers([u'node', u'duplicates']) return var.get(u'getBindingIdentifiers')(var.get(u'node'), var.get(u'duplicates'), var.get(u'true')) PyJsHoisted_getOuterBindingIdentifiers_.func_name = u'getOuterBindingIdentifiers' var.put(u'getOuterBindingIdentifiers', PyJsHoisted_getOuterBindingIdentifiers_) @Js def PyJsHoisted__interopRequireWildcard_(obj, this, arguments, var=var): var = Scope({u'this':this, u'obj':obj, u'arguments':arguments}, var) var.registers([u'obj', u'key', u'newObj']) if (var.get(u'obj') and var.get(u'obj').get(u'__esModule')): return var.get(u'obj') else: PyJs_Object_2831_ = Js({}) var.put(u'newObj', PyJs_Object_2831_) if (var.get(u'obj')!=var.get(u"null")): for PyJsTemp in var.get(u'obj'): var.put(u'key', PyJsTemp) if var.get(u'Object').get(u'prototype').get(u'hasOwnProperty').callprop(u'call', var.get(u'obj'), var.get(u'key')): var.get(u'newObj').put(var.get(u'key'), var.get(u'obj').get(var.get(u'key'))) var.get(u'newObj').put(u'default', var.get(u'obj')) return var.get(u'newObj') PyJsHoisted__interopRequireWildcard_.func_name = u'_interopRequireWildcard' var.put(u'_interopRequireWildcard', PyJsHoisted__interopRequireWildcard_) Js(u'use strict') var.get(u'exports').put(u'__esModule', var.get(u'true')) var.put(u'_create', var.get(u'require')(Js(u'babel-runtime/core-js/object/create'))) var.put(u'_create2', var.get(u'_interopRequireDefault')(var.get(u'_create'))) var.get(u'exports').put(u'getBindingIdentifiers', var.get(u'getBindingIdentifiers')) var.get(u'exports').put(u'getOuterBindingIdentifiers', var.get(u'getOuterBindingIdentifiers')) var.put(u'_index', var.get(u'require')(Js(u'./index'))) var.put(u't', var.get(u'_interopRequireWildcard')(var.get(u'_index'))) pass pass pass PyJs_Object_2833_ = Js({u'DeclareClass':Js([Js(u'id')]),u'DeclareFunction':Js([Js(u'id')]),u'DeclareModule':Js([Js(u'id')]),u'DeclareVariable':Js([Js(u'id')]),u'InterfaceDeclaration':Js([Js(u'id')]),u'TypeAlias':Js([Js(u'id')]),u'CatchClause':Js([Js(u'param')]),u'LabeledStatement':Js([Js(u'label')]),u'UnaryExpression':Js([Js(u'argument')]),u'AssignmentExpression':Js([Js(u'left')]),u'ImportSpecifier':Js([Js(u'local')]),u'ImportNamespaceSpecifier':Js([Js(u'local')]),u'ImportDefaultSpecifier':Js([Js(u'local')]),u'ImportDeclaration':Js([Js(u'specifiers')]),u'ExportSpecifier':Js([Js(u'exported')]),u'ExportNamespaceSpecifier':Js([Js(u'exported')]),u'ExportDefaultSpecifier':Js([Js(u'exported')]),u'FunctionDeclaration':Js([Js(u'id'), Js(u'params')]),u'FunctionExpression':Js([Js(u'id'), Js(u'params')]),u'ClassDeclaration':Js([Js(u'id')]),u'ClassExpression':Js([Js(u'id')]),u'RestElement':Js([Js(u'argument')]),u'UpdateExpression':Js([Js(u'argument')]),u'RestProperty':Js([Js(u'argument')]),u'ObjectProperty':Js([Js(u'value')]),u'AssignmentPattern':Js([Js(u'left')]),u'ArrayPattern':Js([Js(u'elements')]),u'ObjectPattern':Js([Js(u'properties')]),u'VariableDeclaration':Js([Js(u'declarations')]),u'VariableDeclarator':Js([Js(u'id')])}) var.get(u'getBindingIdentifiers').put(u'keys', PyJs_Object_2833_) pass
[ "def", "PyJs_anonymous_2830_", "(", "require", ",", "module", ",", "exports", ",", "this", ",", "arguments", ",", "var", "=", "var", ")", ":", "var", "=", "Scope", "(", "{", "u'this'", ":", "this", ",", "u'require'", ":", "require", ",", "u'exports'", ":", "exports", ",", "u'module'", ":", "module", ",", "u'arguments'", ":", "arguments", "}", ",", "var", ")", "var", ".", "registers", "(", "[", "u'_create'", ",", "u'exports'", ",", "u'_interopRequireWildcard'", ",", "u'_index'", ",", "u'getBindingIdentifiers'", ",", "u'require'", ",", "u'module'", ",", "u'_create2'", ",", "u'getOuterBindingIdentifiers'", ",", "u't'", ",", "u'_interopRequireDefault'", "]", ")", "@", "Js", "def", "PyJsHoisted__interopRequireDefault_", "(", "obj", ",", "this", ",", "arguments", ",", "var", "=", "var", ")", ":", "var", "=", "Scope", "(", "{", "u'this'", ":", "this", ",", "u'obj'", ":", "obj", ",", "u'arguments'", ":", "arguments", "}", ",", "var", ")", "var", ".", "registers", "(", "[", "u'obj'", "]", ")", "PyJs_Object_2832_", "=", "Js", "(", "{", "u'default'", ":", "var", ".", "get", "(", "u'obj'", ")", "}", ")", "return", "(", "var", ".", "get", "(", "u'obj'", ")", "if", "(", "var", ".", "get", "(", "u'obj'", ")", "and", "var", ".", "get", "(", "u'obj'", ")", ".", "get", "(", "u'__esModule'", ")", ")", "else", "PyJs_Object_2832_", ")", "PyJsHoisted__interopRequireDefault_", ".", "func_name", "=", "u'_interopRequireDefault'", "var", ".", "put", "(", "u'_interopRequireDefault'", ",", "PyJsHoisted__interopRequireDefault_", ")", "@", "Js", "def", "PyJsHoisted_getBindingIdentifiers_", "(", "node", ",", "duplicates", ",", "outerOnly", ",", "this", ",", "arguments", ",", "var", "=", "var", ")", ":", "var", "=", "Scope", "(", "{", "u'node'", ":", "node", ",", "u'duplicates'", ":", "duplicates", ",", "u'this'", ":", "this", ",", "u'arguments'", ":", "arguments", ",", "u'outerOnly'", ":", "outerOnly", "}", ",", "var", ")", "var", ".", "registers", "(", "[", "u'node'", ",", "u'search'", ",", "u'duplicates'", ",", "u'outerOnly'", ",", "u'keys'", ",", "u'ids'", ",", "u'i'", ",", "u'key'", ",", "u'id'", ",", "u'_ids'", "]", ")", "var", ".", "put", "(", "u'search'", ",", "Js", "(", "[", "]", ")", ".", "callprop", "(", "u'concat'", ",", "var", ".", "get", "(", "u'node'", ")", ")", ")", "var", ".", "put", "(", "u'ids'", ",", "PyJsComma", "(", "Js", "(", "0.0", ")", ",", "var", ".", "get", "(", "u'_create2'", ")", ".", "get", "(", "u'default'", ")", ")", "(", "var", ".", "get", "(", "u\"null\"", ")", ")", ")", "while", "var", ".", "get", "(", "u'search'", ")", ".", "get", "(", "u'length'", ")", ":", "var", ".", "put", "(", "u'id'", ",", "var", ".", "get", "(", "u'search'", ")", ".", "callprop", "(", "u'shift'", ")", ")", "if", "var", ".", "get", "(", "u'id'", ")", ".", "neg", "(", ")", ":", "continue", "var", ".", "put", "(", "u'keys'", ",", "var", ".", "get", "(", "u't'", ")", ".", "get", "(", "u'getBindingIdentifiers'", ")", ".", "get", "(", "u'keys'", ")", ".", "get", "(", "var", ".", "get", "(", "u'id'", ")", ".", "get", "(", "u'type'", ")", ")", ")", "if", "var", ".", "get", "(", "u't'", ")", ".", "callprop", "(", "u'isIdentifier'", ",", "var", ".", "get", "(", "u'id'", ")", ")", ":", "if", "var", ".", "get", "(", "u'duplicates'", ")", ":", "var", ".", "put", "(", "u'_ids'", ",", "var", ".", "get", "(", "u'ids'", ")", ".", "put", "(", "var", ".", "get", "(", "u'id'", ")", ".", "get", "(", "u'name'", ")", ",", "(", "var", ".", "get", "(", "u'ids'", ")", ".", "get", "(", "var", ".", "get", "(", "u'id'", ")", ".", "get", "(", "u'name'", ")", ")", "or", "Js", "(", "[", "]", ")", ")", ")", ")", "var", ".", "get", "(", "u'_ids'", ")", ".", "callprop", "(", "u'push'", ",", "var", ".", "get", "(", "u'id'", ")", ")", "else", ":", "var", ".", "get", "(", "u'ids'", ")", ".", "put", "(", "var", ".", "get", "(", "u'id'", ")", ".", "get", "(", "u'name'", ")", ",", "var", ".", "get", "(", "u'id'", ")", ")", "continue", "if", "var", ".", "get", "(", "u't'", ")", ".", "callprop", "(", "u'isExportDeclaration'", ",", "var", ".", "get", "(", "u'id'", ")", ")", ":", "if", "var", ".", "get", "(", "u't'", ")", ".", "callprop", "(", "u'isDeclaration'", ",", "var", ".", "get", "(", "u'node'", ")", ".", "get", "(", "u'declaration'", ")", ")", ":", "var", ".", "get", "(", "u'search'", ")", ".", "callprop", "(", "u'push'", ",", "var", ".", "get", "(", "u'node'", ")", ".", "get", "(", "u'declaration'", ")", ")", "continue", "if", "var", ".", "get", "(", "u'outerOnly'", ")", ":", "if", "var", ".", "get", "(", "u't'", ")", ".", "callprop", "(", "u'isFunctionDeclaration'", ",", "var", ".", "get", "(", "u'id'", ")", ")", ":", "var", ".", "get", "(", "u'search'", ")", ".", "callprop", "(", "u'push'", ",", "var", ".", "get", "(", "u'id'", ")", ".", "get", "(", "u'id'", ")", ")", "continue", "if", "var", ".", "get", "(", "u't'", ")", ".", "callprop", "(", "u'isFunctionExpression'", ",", "var", ".", "get", "(", "u'id'", ")", ")", ":", "continue", "if", "var", ".", "get", "(", "u'keys'", ")", ":", "#for JS loop", "var", ".", "put", "(", "u'i'", ",", "Js", "(", "0.0", ")", ")", "while", "(", "var", ".", "get", "(", "u'i'", ")", "<", "var", ".", "get", "(", "u'keys'", ")", ".", "get", "(", "u'length'", ")", ")", ":", "try", ":", "var", ".", "put", "(", "u'key'", ",", "var", ".", "get", "(", "u'keys'", ")", ".", "get", "(", "var", ".", "get", "(", "u'i'", ")", ")", ")", "if", "var", ".", "get", "(", "u'id'", ")", ".", "get", "(", "var", ".", "get", "(", "u'key'", ")", ")", ":", "var", ".", "put", "(", "u'search'", ",", "var", ".", "get", "(", "u'search'", ")", ".", "callprop", "(", "u'concat'", ",", "var", ".", "get", "(", "u'id'", ")", ".", "get", "(", "var", ".", "get", "(", "u'key'", ")", ")", ")", ")", "finally", ":", "(", "var", ".", "put", "(", "u'i'", ",", "Js", "(", "var", ".", "get", "(", "u'i'", ")", ".", "to_number", "(", ")", ")", "+", "Js", "(", "1", ")", ")", "-", "Js", "(", "1", ")", ")", "return", "var", ".", "get", "(", "u'ids'", ")", "PyJsHoisted_getBindingIdentifiers_", ".", "func_name", "=", "u'getBindingIdentifiers'", "var", ".", "put", "(", "u'getBindingIdentifiers'", ",", "PyJsHoisted_getBindingIdentifiers_", ")", "@", "Js", "def", "PyJsHoisted_getOuterBindingIdentifiers_", "(", "node", ",", "duplicates", ",", "this", ",", "arguments", ",", "var", "=", "var", ")", ":", "var", "=", "Scope", "(", "{", "u'node'", ":", "node", ",", "u'duplicates'", ":", "duplicates", ",", "u'this'", ":", "this", ",", "u'arguments'", ":", "arguments", "}", ",", "var", ")", "var", ".", "registers", "(", "[", "u'node'", ",", "u'duplicates'", "]", ")", "return", "var", ".", "get", "(", "u'getBindingIdentifiers'", ")", "(", "var", ".", "get", "(", "u'node'", ")", ",", "var", ".", "get", "(", "u'duplicates'", ")", ",", "var", ".", "get", "(", "u'true'", ")", ")", "PyJsHoisted_getOuterBindingIdentifiers_", ".", "func_name", "=", "u'getOuterBindingIdentifiers'", "var", ".", "put", "(", "u'getOuterBindingIdentifiers'", ",", "PyJsHoisted_getOuterBindingIdentifiers_", ")", "@", "Js", "def", "PyJsHoisted__interopRequireWildcard_", "(", "obj", ",", "this", ",", "arguments", ",", "var", "=", "var", ")", ":", "var", "=", "Scope", "(", "{", "u'this'", ":", "this", ",", "u'obj'", ":", "obj", ",", "u'arguments'", ":", "arguments", "}", ",", "var", ")", "var", ".", "registers", "(", "[", "u'obj'", ",", "u'key'", ",", "u'newObj'", "]", ")", "if", "(", "var", ".", "get", "(", "u'obj'", ")", "and", "var", ".", "get", "(", "u'obj'", ")", ".", "get", "(", "u'__esModule'", ")", ")", ":", "return", "var", ".", "get", "(", "u'obj'", ")", "else", ":", "PyJs_Object_2831_", "=", "Js", "(", "{", "}", ")", "var", ".", "put", "(", "u'newObj'", ",", "PyJs_Object_2831_", ")", "if", "(", "var", ".", "get", "(", "u'obj'", ")", "!=", "var", ".", "get", "(", "u\"null\"", ")", ")", ":", "for", "PyJsTemp", "in", "var", ".", "get", "(", "u'obj'", ")", ":", "var", ".", "put", "(", "u'key'", ",", "PyJsTemp", ")", "if", "var", ".", "get", "(", "u'Object'", ")", ".", "get", "(", "u'prototype'", ")", ".", "get", "(", "u'hasOwnProperty'", ")", ".", "callprop", "(", "u'call'", ",", "var", ".", "get", "(", "u'obj'", ")", ",", "var", ".", "get", "(", "u'key'", ")", ")", ":", "var", ".", "get", "(", "u'newObj'", ")", ".", "put", "(", "var", ".", "get", "(", "u'key'", ")", ",", "var", ".", "get", "(", "u'obj'", ")", ".", "get", "(", "var", ".", "get", "(", "u'key'", ")", ")", ")", "var", ".", "get", "(", "u'newObj'", ")", ".", "put", "(", "u'default'", ",", "var", ".", "get", "(", "u'obj'", ")", ")", "return", "var", ".", "get", "(", "u'newObj'", ")", "PyJsHoisted__interopRequireWildcard_", ".", "func_name", "=", "u'_interopRequireWildcard'", "var", ".", "put", "(", "u'_interopRequireWildcard'", ",", "PyJsHoisted__interopRequireWildcard_", ")", "Js", "(", "u'use strict'", ")", "var", ".", "get", "(", "u'exports'", ")", ".", "put", "(", "u'__esModule'", ",", "var", ".", "get", "(", "u'true'", ")", ")", "var", ".", "put", "(", "u'_create'", ",", "var", ".", "get", "(", "u'require'", ")", "(", "Js", "(", "u'babel-runtime/core-js/object/create'", ")", ")", ")", "var", ".", "put", "(", "u'_create2'", ",", "var", ".", "get", "(", "u'_interopRequireDefault'", ")", "(", "var", ".", "get", "(", "u'_create'", ")", ")", ")", "var", ".", "get", "(", "u'exports'", ")", ".", "put", "(", "u'getBindingIdentifiers'", ",", "var", ".", "get", "(", "u'getBindingIdentifiers'", ")", ")", "var", ".", "get", "(", "u'exports'", ")", ".", "put", "(", "u'getOuterBindingIdentifiers'", ",", "var", ".", "get", "(", "u'getOuterBindingIdentifiers'", ")", ")", "var", ".", "put", "(", "u'_index'", ",", "var", ".", "get", "(", "u'require'", ")", "(", "Js", "(", "u'./index'", ")", ")", ")", "var", ".", "put", "(", "u't'", ",", "var", ".", "get", "(", "u'_interopRequireWildcard'", ")", "(", "var", ".", "get", "(", "u'_index'", ")", ")", ")", "pass", "pass", "pass", "PyJs_Object_2833_", "=", "Js", "(", "{", "u'DeclareClass'", ":", "Js", "(", "[", "Js", "(", "u'id'", ")", "]", ")", ",", "u'DeclareFunction'", ":", "Js", "(", "[", "Js", "(", "u'id'", ")", "]", ")", ",", "u'DeclareModule'", ":", "Js", "(", "[", "Js", "(", "u'id'", ")", "]", ")", ",", "u'DeclareVariable'", ":", "Js", "(", "[", "Js", "(", "u'id'", ")", "]", ")", ",", "u'InterfaceDeclaration'", ":", "Js", "(", "[", "Js", "(", "u'id'", ")", "]", ")", ",", "u'TypeAlias'", ":", "Js", "(", "[", "Js", "(", "u'id'", ")", "]", ")", ",", "u'CatchClause'", ":", "Js", "(", "[", "Js", "(", "u'param'", ")", "]", ")", ",", "u'LabeledStatement'", ":", "Js", "(", "[", "Js", "(", "u'label'", ")", "]", ")", ",", "u'UnaryExpression'", ":", "Js", "(", "[", "Js", "(", "u'argument'", ")", "]", ")", ",", "u'AssignmentExpression'", ":", "Js", "(", "[", "Js", "(", "u'left'", ")", "]", ")", ",", "u'ImportSpecifier'", ":", "Js", "(", "[", "Js", "(", "u'local'", ")", "]", ")", ",", "u'ImportNamespaceSpecifier'", ":", "Js", "(", "[", "Js", "(", "u'local'", ")", "]", ")", ",", "u'ImportDefaultSpecifier'", ":", "Js", "(", "[", "Js", "(", "u'local'", ")", "]", ")", ",", "u'ImportDeclaration'", ":", "Js", "(", "[", "Js", "(", "u'specifiers'", ")", "]", ")", ",", "u'ExportSpecifier'", ":", "Js", "(", "[", "Js", "(", "u'exported'", ")", "]", ")", ",", "u'ExportNamespaceSpecifier'", ":", "Js", "(", "[", "Js", "(", "u'exported'", ")", "]", ")", ",", "u'ExportDefaultSpecifier'", ":", "Js", "(", "[", "Js", "(", "u'exported'", ")", "]", ")", ",", "u'FunctionDeclaration'", ":", "Js", "(", "[", "Js", "(", "u'id'", ")", ",", "Js", "(", "u'params'", ")", "]", ")", ",", "u'FunctionExpression'", ":", "Js", "(", "[", "Js", "(", "u'id'", ")", ",", "Js", "(", "u'params'", ")", "]", ")", ",", "u'ClassDeclaration'", ":", "Js", "(", "[", "Js", "(", "u'id'", ")", "]", ")", ",", "u'ClassExpression'", ":", "Js", "(", "[", "Js", "(", "u'id'", ")", "]", ")", ",", "u'RestElement'", ":", "Js", "(", "[", "Js", "(", "u'argument'", ")", "]", ")", ",", "u'UpdateExpression'", ":", "Js", "(", "[", "Js", "(", "u'argument'", ")", "]", ")", ",", "u'RestProperty'", ":", "Js", "(", "[", "Js", "(", "u'argument'", ")", "]", ")", ",", "u'ObjectProperty'", ":", "Js", "(", "[", "Js", "(", "u'value'", ")", "]", ")", ",", "u'AssignmentPattern'", ":", "Js", "(", "[", "Js", "(", "u'left'", ")", "]", ")", ",", "u'ArrayPattern'", ":", "Js", "(", "[", "Js", "(", "u'elements'", ")", "]", ")", ",", "u'ObjectPattern'", ":", "Js", "(", "[", "Js", "(", "u'properties'", ")", "]", ")", ",", "u'VariableDeclaration'", ":", "Js", "(", "[", "Js", "(", "u'declarations'", ")", "]", ")", ",", "u'VariableDeclarator'", ":", "Js", "(", "[", "Js", "(", "u'id'", ")", "]", ")", "}", ")", "var", ".", "get", "(", "u'getBindingIdentifiers'", ")", ".", "put", "(", "u'keys'", ",", "PyJs_Object_2833_", ")", "pass" ]
https://github.com/DxCx/plugin.video.9anime/blob/34358c2f701e5ddf19d3276926374a16f63f7b6a/resources/lib/ui/js2py/es6/babel.py#L29394-L29484
zyfra/ebonite
b01b662c43709d152940f488574d78ff25f89ecf
src/ebonite/build/builder/base.py
python
PythonBuildContext.__init__
(self, provider: PythonProvider)
[]
def __init__(self, provider: PythonProvider): self.provider = provider
[ "def", "__init__", "(", "self", ",", "provider", ":", "PythonProvider", ")", ":", "self", ".", "provider", "=", "provider" ]
https://github.com/zyfra/ebonite/blob/b01b662c43709d152940f488574d78ff25f89ecf/src/ebonite/build/builder/base.py#L81-L82
zedshaw/learn-more-python-the-hard-way-solutions
7886c860f69d69739a41d6490b8dc3fa777f227b
ex14_dllist/dllist.py
python
DoubleLinkedList.get
(self, index)
return None
Get the value at index.
Get the value at index.
[ "Get", "the", "value", "at", "index", "." ]
def get(self, index): """Get the value at index.""" # similar code to count, but stop at index and return value or None node = self.begin i = 0 while node: if i == index: return node.value else: i += 1 node = node.next return None
[ "def", "get", "(", "self", ",", "index", ")", ":", "# similar code to count, but stop at index and return value or None", "node", "=", "self", ".", "begin", "i", "=", "0", "while", "node", ":", "if", "i", "==", "index", ":", "return", "node", ".", "value", "else", ":", "i", "+=", "1", "node", "=", "node", ".", "next", "return", "None" ]
https://github.com/zedshaw/learn-more-python-the-hard-way-solutions/blob/7886c860f69d69739a41d6490b8dc3fa777f227b/ex14_dllist/dllist.py#L137-L148
google-research/tapas
a3e069b50c71f50b12a6e5bb3dad10fb51f6fe68
tapas/utils/table_pruning.py
python
ModelPruningSelector._gather_scores
(self, scores, input_mask)
return tf.gather_nd(indices=indexes, params=scores, batch_dims=1)
Gather the smaller tensor of scores.
Gather the smaller tensor of scores.
[ "Gather", "the", "smaller", "tensor", "of", "scores", "." ]
def _gather_scores(self, scores, input_mask): """Gather the smaller tensor of scores.""" # <int32>[batch_size, max_num_tokens, 1] indexes = self._get_index_gather(scores=scores, input_mask=input_mask) # <float32>[batch_size, max_num_tokens] return tf.gather_nd(indices=indexes, params=scores, batch_dims=1)
[ "def", "_gather_scores", "(", "self", ",", "scores", ",", "input_mask", ")", ":", "# <int32>[batch_size, max_num_tokens, 1]", "indexes", "=", "self", ".", "_get_index_gather", "(", "scores", "=", "scores", ",", "input_mask", "=", "input_mask", ")", "# <float32>[batch_size, max_num_tokens]", "return", "tf", ".", "gather_nd", "(", "indices", "=", "indexes", ",", "params", "=", "scores", ",", "batch_dims", "=", "1", ")" ]
https://github.com/google-research/tapas/blob/a3e069b50c71f50b12a6e5bb3dad10fb51f6fe68/tapas/utils/table_pruning.py#L170-L176
learningequality/ka-lite
571918ea668013dcf022286ea85eff1c5333fb8b
kalite/packages/bundled/django/forms/widgets.py
python
Widget.build_attrs
(self, extra_attrs=None, **kwargs)
return attrs
Helper function for building an attribute dictionary.
Helper function for building an attribute dictionary.
[ "Helper", "function", "for", "building", "an", "attribute", "dictionary", "." ]
def build_attrs(self, extra_attrs=None, **kwargs): "Helper function for building an attribute dictionary." attrs = dict(self.attrs, **kwargs) if extra_attrs: attrs.update(extra_attrs) return attrs
[ "def", "build_attrs", "(", "self", ",", "extra_attrs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "attrs", "=", "dict", "(", "self", ".", "attrs", ",", "*", "*", "kwargs", ")", "if", "extra_attrs", ":", "attrs", ".", "update", "(", "extra_attrs", ")", "return", "attrs" ]
https://github.com/learningequality/ka-lite/blob/571918ea668013dcf022286ea85eff1c5333fb8b/kalite/packages/bundled/django/forms/widgets.py#L197-L202
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/atom/__init__.py
python
Contributor.__init__
(self, name=None, email=None, uri=None, extension_elements=None, extension_attributes=None, text=None)
Constructor for Contributor Args: name: Name email: Email uri: Uri extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs text: str The text data in the this element
Constructor for Contributor
[ "Constructor", "for", "Contributor" ]
def __init__(self, name=None, email=None, uri=None, extension_elements=None, extension_attributes=None, text=None): """Constructor for Contributor Args: name: Name email: Email uri: Uri extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs text: str The text data in the this element """ self.name = name self.email = email self.uri = uri self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} self.text = text
[ "def", "__init__", "(", "self", ",", "name", "=", "None", ",", "email", "=", "None", ",", "uri", "=", "None", ",", "extension_elements", "=", "None", ",", "extension_attributes", "=", "None", ",", "text", "=", "None", ")", ":", "self", ".", "name", "=", "name", "self", ".", "email", "=", "email", "self", ".", "uri", "=", "uri", "self", ".", "extension_elements", "=", "extension_elements", "or", "[", "]", "self", ".", "extension_attributes", "=", "extension_attributes", "or", "{", "}", "self", ".", "text", "=", "text" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/atom/__init__.py#L547-L565
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/nova/nova/virt/libvirt/utils.py
python
delete_snapshot
(disk_path, snapshot_name)
Create a snapshot in a disk image :param disk_path: Path to disk image :param snapshot_name: Name of snapshot in disk image
Create a snapshot in a disk image
[ "Create", "a", "snapshot", "in", "a", "disk", "image" ]
def delete_snapshot(disk_path, snapshot_name): """Create a snapshot in a disk image :param disk_path: Path to disk image :param snapshot_name: Name of snapshot in disk image """ qemu_img_cmd = ('qemu-img', 'snapshot', '-d', snapshot_name, disk_path) # NOTE(vish): libvirt changes ownership of images execute(*qemu_img_cmd, run_as_root=True)
[ "def", "delete_snapshot", "(", "disk_path", ",", "snapshot_name", ")", ":", "qemu_img_cmd", "=", "(", "'qemu-img'", ",", "'snapshot'", ",", "'-d'", ",", "snapshot_name", ",", "disk_path", ")", "# NOTE(vish): libvirt changes ownership of images", "execute", "(", "*", "qemu_img_cmd", ",", "run_as_root", "=", "True", ")" ]
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/nova/nova/virt/libvirt/utils.py#L474-L482
pengming617/bert_classification
c155e73ee9272aa61589116aebd762204c3e4c83
run_classifier.py
python
convert_examples_to_features
(examples, label_list, max_seq_length, tokenizer)
return features
Convert a set of `InputExample`s to a list of `InputFeatures`.
Convert a set of `InputExample`s to a list of `InputFeatures`.
[ "Convert", "a", "set", "of", "InputExample", "s", "to", "a", "list", "of", "InputFeatures", "." ]
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer): """Convert a set of `InputExample`s to a list of `InputFeatures`.""" features = [] for (ex_index, example) in enumerate(examples): if ex_index % 10000 == 0: tf.logging.info("Writing example %d of %d" % (ex_index, len(examples))) feature = convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer) features.append(feature) return features
[ "def", "convert_examples_to_features", "(", "examples", ",", "label_list", ",", "max_seq_length", ",", "tokenizer", ")", ":", "features", "=", "[", "]", "for", "(", "ex_index", ",", "example", ")", "in", "enumerate", "(", "examples", ")", ":", "if", "ex_index", "%", "10000", "==", "0", ":", "tf", ".", "logging", ".", "info", "(", "\"Writing example %d of %d\"", "%", "(", "ex_index", ",", "len", "(", "examples", ")", ")", ")", "feature", "=", "convert_single_example", "(", "ex_index", ",", "example", ",", "label_list", ",", "max_seq_length", ",", "tokenizer", ")", "features", ".", "append", "(", "feature", ")", "return", "features" ]
https://github.com/pengming617/bert_classification/blob/c155e73ee9272aa61589116aebd762204c3e4c83/run_classifier.py#L905-L918
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gen/relationship.py
python
RelationshipCalculator._get_parent_unknown
(self, level, step='', inlaw='')
Internal english method to create relation string
Internal english method to create relation string
[ "Internal", "english", "method", "to", "create", "relation", "string" ]
def _get_parent_unknown(self, level, step='', inlaw=''): """ Internal english method to create relation string """ if level < len(_LEVEL_NAME): return _LEVEL_NAME[level] + ' ' + '%sancestor%s' % (step, inlaw) else: return "distant %sancestor%s (%d generations)" % (step, inlaw, level)
[ "def", "_get_parent_unknown", "(", "self", ",", "level", ",", "step", "=", "''", ",", "inlaw", "=", "''", ")", ":", "if", "level", "<", "len", "(", "_LEVEL_NAME", ")", ":", "return", "_LEVEL_NAME", "[", "level", "]", "+", "' '", "+", "'%sancestor%s'", "%", "(", "step", ",", "inlaw", ")", "else", ":", "return", "\"distant %sancestor%s (%d generations)\"", "%", "(", "step", ",", "inlaw", ",", "level", ")" ]
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gen/relationship.py#L921-L929
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_oa_openshift/library/oc_image.py
python
Utils.cleanup
(files)
Clean up on exit
Clean up on exit
[ "Clean", "up", "on", "exit" ]
def cleanup(files): '''Clean up on exit ''' for sfile in files: if os.path.exists(sfile): if os.path.isdir(sfile): shutil.rmtree(sfile) elif os.path.isfile(sfile): os.remove(sfile)
[ "def", "cleanup", "(", "files", ")", ":", "for", "sfile", "in", "files", ":", "if", "os", ".", "path", ".", "exists", "(", "sfile", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "sfile", ")", ":", "shutil", ".", "rmtree", "(", "sfile", ")", "elif", "os", ".", "path", ".", "isfile", "(", "sfile", ")", ":", "os", ".", "remove", "(", "sfile", ")" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_oa_openshift/library/oc_image.py#L1228-L1235
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_csi_volume_source.py
python
V1CSIVolumeSource.__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/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_csi_volume_source.py#L217-L219
pyjs/pyjs
6c4a3d3a67300cd5df7f95a67ca9dcdc06950523
pgen/tokenize.py
python
tokenize
(readline, tokeneater=printtoken)
The tokenize() function accepts two parameters: one representing the input stream, and one providing an output mechanism for tokenize(). The first parameter, readline, must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. The second parameter, tokeneater, must also be a callable object. It is called once for each token, with five arguments, corresponding to the tuples generated by generate_tokens().
The tokenize() function accepts two parameters: one representing the input stream, and one providing an output mechanism for tokenize().
[ "The", "tokenize", "()", "function", "accepts", "two", "parameters", ":", "one", "representing", "the", "input", "stream", "and", "one", "providing", "an", "output", "mechanism", "for", "tokenize", "()", "." ]
def tokenize(readline, tokeneater=printtoken): """ The tokenize() function accepts two parameters: one representing the input stream, and one providing an output mechanism for tokenize(). The first parameter, readline, must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. The second parameter, tokeneater, must also be a callable object. It is called once for each token, with five arguments, corresponding to the tuples generated by generate_tokens(). """ try: tokenize_loop(readline, tokeneater) except StopTokenizing: pass
[ "def", "tokenize", "(", "readline", ",", "tokeneater", "=", "printtoken", ")", ":", "try", ":", "tokenize_loop", "(", "readline", ",", "tokeneater", ")", "except", "StopTokenizing", ":", "pass" ]
https://github.com/pyjs/pyjs/blob/6c4a3d3a67300cd5df7f95a67ca9dcdc06950523/pgen/tokenize.py#L152-L168
bardiadoosti/HOPE
24f99bb6c4f1d3e185e8988179347dde5c37f42c
models/resnet.py
python
resnet18
(pretrained=False, num_classes=1000, **kwargs)
return model
Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
[ "Constructs", "a", "ResNet", "-", "18", "model", ".", "Args", ":", "pretrained", "(", "bool", ")", ":", "If", "True", "returns", "a", "model", "pre", "-", "trained", "on", "ImageNet" ]
def resnet18(pretrained=False, num_classes=1000, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [2, 2, 2, 2], num_classes=1000, **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])) num_ftrs = model.fc.in_features model.fc = nn.Linear(num_ftrs, num_classes) return model
[ "def", "resnet18", "(", "pretrained", "=", "False", ",", "num_classes", "=", "1000", ",", "*", "*", "kwargs", ")", ":", "model", "=", "ResNet", "(", "BasicBlock", ",", "[", "2", ",", "2", ",", "2", ",", "2", "]", ",", "num_classes", "=", "1000", ",", "*", "*", "kwargs", ")", "if", "pretrained", ":", "model", ".", "load_state_dict", "(", "model_zoo", ".", "load_url", "(", "model_urls", "[", "'resnet18'", "]", ")", ")", "num_ftrs", "=", "model", ".", "fc", ".", "in_features", "model", ".", "fc", "=", "nn", ".", "Linear", "(", "num_ftrs", ",", "num_classes", ")", "return", "model" ]
https://github.com/bardiadoosti/HOPE/blob/24f99bb6c4f1d3e185e8988179347dde5c37f42c/models/resnet.py#L222-L232
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/heatmap/_colorbar.py
python
ColorBar.outlinecolor
(self)
return self["outlinecolor"]
Sets the axis line color. The 'outlinecolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str
Sets the axis line color. The 'outlinecolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen
[ "Sets", "the", "axis", "line", "color", ".", "The", "outlinecolor", "property", "is", "a", "color", "and", "may", "be", "specified", "as", ":", "-", "A", "hex", "string", "(", "e", ".", "g", ".", "#ff0000", ")", "-", "An", "rgb", "/", "rgba", "string", "(", "e", ".", "g", ".", "rgb", "(", "255", "0", "0", ")", ")", "-", "An", "hsl", "/", "hsla", "string", "(", "e", ".", "g", ".", "hsl", "(", "0", "100%", "50%", ")", ")", "-", "An", "hsv", "/", "hsva", "string", "(", "e", ".", "g", ".", "hsv", "(", "0", "100%", "100%", ")", ")", "-", "A", "named", "CSS", "color", ":", "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgrey", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkslategrey", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dimgrey", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgrey", "lightgreen", "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightslategrey", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "purple", "red", "rosybrown", "royalblue", "rebeccapurple", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", "slategrey", "snow", "springgreen", "steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen" ]
def outlinecolor(self): """ Sets the axis line color. The 'outlinecolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["outlinecolor"]
[ "def", "outlinecolor", "(", "self", ")", ":", "return", "self", "[", "\"outlinecolor\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/heatmap/_colorbar.py#L376-L426
tspurway/hustle
e62bf1269b446ea6fae23bc5698f845a2f3247c7
hustle/core/pipeline.py
python
_aggregate_fast
(inp, label_fn, ffuncs, ghfuncs, deffuncs)
Fast channel for executing aggregate function, would be used if all columns in project are aggregations
Fast channel for executing aggregate function, would be used if all columns in project are aggregations
[ "Fast", "channel", "for", "executing", "aggregate", "function", "would", "be", "used", "if", "all", "columns", "in", "project", "are", "aggregations" ]
def _aggregate_fast(inp, label_fn, ffuncs, ghfuncs, deffuncs): """ Fast channel for executing aggregate function, would be used if all columns in project are aggregations """ accums = [default() for default in deffuncs] for record, _ in inp: try: accums = [f(a, v) for f, a, v in zip(ffuncs, accums, record)] except Exception as e: print e print "YEEHEQW: f=%s a=%s r=%s" % (ffuncs, accums, record) import traceback print traceback.format_exc(15) raise e key = tuple(h(a) for h, a in zip(ghfuncs, accums)) yield 0, key
[ "def", "_aggregate_fast", "(", "inp", ",", "label_fn", ",", "ffuncs", ",", "ghfuncs", ",", "deffuncs", ")", ":", "accums", "=", "[", "default", "(", ")", "for", "default", "in", "deffuncs", "]", "for", "record", ",", "_", "in", "inp", ":", "try", ":", "accums", "=", "[", "f", "(", "a", ",", "v", ")", "for", "f", ",", "a", ",", "v", "in", "zip", "(", "ffuncs", ",", "accums", ",", "record", ")", "]", "except", "Exception", "as", "e", ":", "print", "e", "print", "\"YEEHEQW: f=%s a=%s r=%s\"", "%", "(", "ffuncs", ",", "accums", ",", "record", ")", "import", "traceback", "print", "traceback", ".", "format_exc", "(", "15", ")", "raise", "e", "key", "=", "tuple", "(", "h", "(", "a", ")", "for", "h", ",", "a", "in", "zip", "(", "ghfuncs", ",", "accums", ")", ")", "yield", "0", ",", "key" ]
https://github.com/tspurway/hustle/blob/e62bf1269b446ea6fae23bc5698f845a2f3247c7/hustle/core/pipeline.py#L480-L497
pulp/pulp
a0a28d804f997b6f81c391378aff2e4c90183df9
client_admin/pulp/client/admin/tasks.py
python
AllTasksSection.retrieve_tasks
(self, **kwargs)
return tasks
:return: list of pulp.bindings.responses.Task instances :rtype: list
:return: list of pulp.bindings.responses.Task instances :rtype: list
[ ":", "return", ":", "list", "of", "pulp", ".", "bindings", ".", "responses", ".", "Task", "instances", ":", "rtype", ":", "list" ]
def retrieve_tasks(self, **kwargs): """ :return: list of pulp.bindings.responses.Task instances :rtype: list """ if kwargs.get(self.all_flag.keyword): tasks = self.context.server.tasks_search.search(fields=self.FIELDS) elif kwargs.get(self.state_option.keyword): states = kwargs[self.state_option.keyword] # This is a temorary fix(because of backward incompatible reasons) # until #1028 and #1041 are fixed. self.translate_state_discrepancy(states) tasks = self.context.server.tasks_search.search( filters={'state': {'$in': states}, 'group_id': None}, fields=self.FIELDS) else: tasks = self.context.server.tasks_search.search( filters={'state': {'$in': ['running', 'waiting']}, 'group_id': None}, fields=self.FIELDS) return tasks
[ "def", "retrieve_tasks", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "self", ".", "all_flag", ".", "keyword", ")", ":", "tasks", "=", "self", ".", "context", ".", "server", ".", "tasks_search", ".", "search", "(", "fields", "=", "self", ".", "FIELDS", ")", "elif", "kwargs", ".", "get", "(", "self", ".", "state_option", ".", "keyword", ")", ":", "states", "=", "kwargs", "[", "self", ".", "state_option", ".", "keyword", "]", "# This is a temorary fix(because of backward incompatible reasons)", "# until #1028 and #1041 are fixed.", "self", ".", "translate_state_discrepancy", "(", "states", ")", "tasks", "=", "self", ".", "context", ".", "server", ".", "tasks_search", ".", "search", "(", "filters", "=", "{", "'state'", ":", "{", "'$in'", ":", "states", "}", ",", "'group_id'", ":", "None", "}", ",", "fields", "=", "self", ".", "FIELDS", ")", "else", ":", "tasks", "=", "self", ".", "context", ".", "server", ".", "tasks_search", ".", "search", "(", "filters", "=", "{", "'state'", ":", "{", "'$in'", ":", "[", "'running'", ",", "'waiting'", "]", "}", ",", "'group_id'", ":", "None", "}", ",", "fields", "=", "self", ".", "FIELDS", ")", "return", "tasks" ]
https://github.com/pulp/pulp/blob/a0a28d804f997b6f81c391378aff2e4c90183df9/client_admin/pulp/client/admin/tasks.py#L280-L299
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/Lib/random.py
python
Random.choice
(self, seq)
return seq[int(self.random() * len(seq))]
Choose a random element from a non-empty sequence.
Choose a random element from a non-empty sequence.
[ "Choose", "a", "random", "element", "from", "a", "non", "-", "empty", "sequence", "." ]
def choice(self, seq): """Choose a random element from a non-empty sequence.""" return seq[int(self.random() * len(seq))]
[ "def", "choice", "(", "self", ",", "seq", ")", ":", "return", "seq", "[", "int", "(", "self", ".", "random", "(", ")", "*", "len", "(", "seq", ")", ")", "]" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/Lib/random.py#L272-L274
log2timeline/dfvfs
4ca7bf06b15cdc000297a7122a065f0ca71de544
dfvfs/volume/volume_system.py
python
Volume.GetAttribute
(self, identifier)
return self._attributes[identifier]
Retrieves a specific attribute. Args: identifier (str): identifier of the attribute within the volume. Returns: VolumeAttribute: volume attribute or None if not available.
Retrieves a specific attribute.
[ "Retrieves", "a", "specific", "attribute", "." ]
def GetAttribute(self, identifier): """Retrieves a specific attribute. Args: identifier (str): identifier of the attribute within the volume. Returns: VolumeAttribute: volume attribute or None if not available. """ if not self._is_parsed: self._Parse() self._is_parsed = True if identifier not in self._attributes: return None return self._attributes[identifier]
[ "def", "GetAttribute", "(", "self", ",", "identifier", ")", ":", "if", "not", "self", ".", "_is_parsed", ":", "self", ".", "_Parse", "(", ")", "self", ".", "_is_parsed", "=", "True", "if", "identifier", "not", "in", "self", ".", "_attributes", ":", "return", "None", "return", "self", ".", "_attributes", "[", "identifier", "]" ]
https://github.com/log2timeline/dfvfs/blob/4ca7bf06b15cdc000297a7122a065f0ca71de544/dfvfs/volume/volume_system.py#L117-L133
superfish9/hackcdn
eb164946aad36c3781d73566bdf170b2b1411f0d
thirdparty/IPy/IPy.py
python
_count0Bits
(num)
return ret
Find the highest bit set to 0 in an integer.
Find the highest bit set to 0 in an integer.
[ "Find", "the", "highest", "bit", "set", "to", "0", "in", "an", "integer", "." ]
def _count0Bits(num): """Find the highest bit set to 0 in an integer.""" # this could be so easy if _count1Bits(~int(num)) would work as excepted num = int(num) if num < 0: raise ValueError("Only positive Numbers please: %s" % (num)) ret = 0 while num > 0: if num & 1 == 1: break num = num >> 1 ret += 1 return ret
[ "def", "_count0Bits", "(", "num", ")", ":", "# this could be so easy if _count1Bits(~int(num)) would work as excepted", "num", "=", "int", "(", "num", ")", "if", "num", "<", "0", ":", "raise", "ValueError", "(", "\"Only positive Numbers please: %s\"", "%", "(", "num", ")", ")", "ret", "=", "0", "while", "num", ">", "0", ":", "if", "num", "&", "1", "==", "1", ":", "break", "num", "=", "num", ">>", "1", "ret", "+=", "1", "return", "ret" ]
https://github.com/superfish9/hackcdn/blob/eb164946aad36c3781d73566bdf170b2b1411f0d/thirdparty/IPy/IPy.py#L1486-L1499
OpenMDAO/OpenMDAO-Framework
f2e37b7de3edeaaeb2d251b375917adec059db9b
openmdao.main/src/openmdao/main/rbac.py
python
Credentials.encode
(self)
return (self.data, self.signature, self.client_creds)
Return object to be sent: ``(data, signature, client_creds)``.
Return object to be sent: ``(data, signature, client_creds)``.
[ "Return", "object", "to", "be", "sent", ":", "(", "data", "signature", "client_creds", ")", "." ]
def encode(self): """ Return object to be sent: ``(data, signature, client_creds)``. """ return (self.data, self.signature, self.client_creds)
[ "def", "encode", "(", "self", ")", ":", "return", "(", "self", ".", "data", ",", "self", ".", "signature", ",", "self", ".", "client_creds", ")" ]
https://github.com/OpenMDAO/OpenMDAO-Framework/blob/f2e37b7de3edeaaeb2d251b375917adec059db9b/openmdao.main/src/openmdao/main/rbac.py#L155-L157
JasperSnoek/spearmint
b37a541be1ea035f82c7c82bbd93f5b4320e7d91
spearmint/spearmint/chooser/cma.py
python
Options.set
(self, dic, val=None, warn=True)
return self
set can assign versatile options from `Options.versatileOptions()` with a new value, use `init()` for the others. Arguments --------- `dic` either a dictionary or a key. In the latter case, val must be provided `val` value for key `warn` bool, print a warning if the option cannot be changed and is therefore omitted This method will be most probably used with the ``opts`` attribute of a `CMAEvolutionStrategy` instance.
set can assign versatile options from `Options.versatileOptions()` with a new value, use `init()` for the others.
[ "set", "can", "assign", "versatile", "options", "from", "Options", ".", "versatileOptions", "()", "with", "a", "new", "value", "use", "init", "()", "for", "the", "others", "." ]
def set(self, dic, val=None, warn=True): """set can assign versatile options from `Options.versatileOptions()` with a new value, use `init()` for the others. Arguments --------- `dic` either a dictionary or a key. In the latter case, val must be provided `val` value for key `warn` bool, print a warning if the option cannot be changed and is therefore omitted This method will be most probably used with the ``opts`` attribute of a `CMAEvolutionStrategy` instance. """ if val is not None: # dic is a key in this case dic = {dic:val} # compose a dictionary for key, val in list(dic.items()): if key in Options.versatileOptions(): self[key] = val elif warn: print('Warning in cma.Options.set(): key ' + str(key) + ' ignored') return self
[ "def", "set", "(", "self", ",", "dic", ",", "val", "=", "None", ",", "warn", "=", "True", ")", ":", "if", "val", "is", "not", "None", ":", "# dic is a key in this case", "dic", "=", "{", "dic", ":", "val", "}", "# compose a dictionary", "for", "key", ",", "val", "in", "list", "(", "dic", ".", "items", "(", ")", ")", ":", "if", "key", "in", "Options", ".", "versatileOptions", "(", ")", ":", "self", "[", "key", "]", "=", "val", "elif", "warn", ":", "print", "(", "'Warning in cma.Options.set(): key '", "+", "str", "(", "key", ")", "+", "' ignored'", ")", "return", "self" ]
https://github.com/JasperSnoek/spearmint/blob/b37a541be1ea035f82c7c82bbd93f5b4320e7d91/spearmint/spearmint/chooser/cma.py#L2815-L2841
tensorflow/lingvo
ce10019243d954c3c3ebe739f7589b5eebfdf907
lingvo/core/py_utils.py
python
GetOrCreateGlobalStepVar
()
Return the global_step variable, creating it if it does not exist. Prefer GetGlobalStep if a tensor rather than a tf.Variable is sufficient. Returns: The global_step variable, or a new created one if it does not exist.
Return the global_step variable, creating it if it does not exist.
[ "Return", "the", "global_step", "variable", "creating", "it", "if", "it", "does", "not", "exist", "." ]
def GetOrCreateGlobalStepVar(): """Return the global_step variable, creating it if it does not exist. Prefer GetGlobalStep if a tensor rather than a tf.Variable is sufficient. Returns: The global_step variable, or a new created one if it does not exist. """ with tf.variable_scope(GetGlobalVariableScope(), use_resource=True): if _FromGlobal('pin_vars_to_cpu'): with tf.device('/cpu:0'): return tf.train.get_or_create_global_step() else: return tf.train.get_or_create_global_step()
[ "def", "GetOrCreateGlobalStepVar", "(", ")", ":", "with", "tf", ".", "variable_scope", "(", "GetGlobalVariableScope", "(", ")", ",", "use_resource", "=", "True", ")", ":", "if", "_FromGlobal", "(", "'pin_vars_to_cpu'", ")", ":", "with", "tf", ".", "device", "(", "'/cpu:0'", ")", ":", "return", "tf", ".", "train", ".", "get_or_create_global_step", "(", ")", "else", ":", "return", "tf", ".", "train", ".", "get_or_create_global_step", "(", ")" ]
https://github.com/tensorflow/lingvo/blob/ce10019243d954c3c3ebe739f7589b5eebfdf907/lingvo/core/py_utils.py#L2429-L2442
pandas-dev/pandas
5ba7d714014ae8feaccc0dd4a98890828cf2832d
pandas/io/pytables.py
python
IndexCol.is_indexed
(self)
return getattr(self.table.cols, self.cname).is_indexed
return whether I am an indexed column
return whether I am an indexed column
[ "return", "whether", "I", "am", "an", "indexed", "column" ]
def is_indexed(self) -> bool: """return whether I am an indexed column""" if not hasattr(self.table, "cols"): # e.g. if infer hasn't been called yet, self.table will be None. return False return getattr(self.table.cols, self.cname).is_indexed
[ "def", "is_indexed", "(", "self", ")", "->", "bool", ":", "if", "not", "hasattr", "(", "self", ".", "table", ",", "\"cols\"", ")", ":", "# e.g. if infer hasn't been called yet, self.table will be None.", "return", "False", "return", "getattr", "(", "self", ".", "table", ".", "cols", ",", "self", ".", "cname", ")", ".", "is_indexed" ]
https://github.com/pandas-dev/pandas/blob/5ba7d714014ae8feaccc0dd4a98890828cf2832d/pandas/io/pytables.py#L2050-L2055
ganglia/gmond_python_modules
2f7fcab3d27926ef4a2feb1b53c09af16a43e729
passenger/python_modules/passenger.py
python
UpdateMetricThread.update_metric
(self)
[]
def update_metric(self): status_output = timeout_command(self.status, self.timeout) status_output += timeout_command(self.memory_stats, self.timeout)[-1:] # to get last line of memory output dprint("%s", status_output) for line in status_output: for (name,regex) in self.status_regex.iteritems(): result = re.search(regex,line) if result: dprint("%s = %d", name, int(result.group(1))) self.metric[self.mp+'_'+name] = int(result.group(1))
[ "def", "update_metric", "(", "self", ")", ":", "status_output", "=", "timeout_command", "(", "self", ".", "status", ",", "self", ".", "timeout", ")", "status_output", "+=", "timeout_command", "(", "self", ".", "memory_stats", ",", "self", ".", "timeout", ")", "[", "-", "1", ":", "]", "# to get last line of memory output", "dprint", "(", "\"%s\"", ",", "status_output", ")", "for", "line", "in", "status_output", ":", "for", "(", "name", ",", "regex", ")", "in", "self", ".", "status_regex", ".", "iteritems", "(", ")", ":", "result", "=", "re", ".", "search", "(", "regex", ",", "line", ")", "if", "result", ":", "dprint", "(", "\"%s = %d\"", ",", "name", ",", "int", "(", "result", ".", "group", "(", "1", ")", ")", ")", "self", ".", "metric", "[", "self", ".", "mp", "+", "'_'", "+", "name", "]", "=", "int", "(", "result", ".", "group", "(", "1", ")", ")" ]
https://github.com/ganglia/gmond_python_modules/blob/2f7fcab3d27926ef4a2feb1b53c09af16a43e729/passenger/python_modules/passenger.py#L76-L85
crossbario/crossbar
ed350b7ba1c8421f3640b9c2e94a21ed4cfdff64
crossbar/router/service.py
python
RouterServiceAgent.subscription_get_events
(self, subscription_id, limit=10, details=None)
Return history of events for given subscription. :param subscription_id: The ID of the subscription to get events for. :type subscription_id: int :param limit: Return at most this many events. :type limit: int :returns: List of events. :rtype: list
Return history of events for given subscription.
[ "Return", "history", "of", "events", "for", "given", "subscription", "." ]
def subscription_get_events(self, subscription_id, limit=10, details=None): """ Return history of events for given subscription. :param subscription_id: The ID of the subscription to get events for. :type subscription_id: int :param limit: Return at most this many events. :type limit: int :returns: List of events. :rtype: list """ self.log.debug('subscription_get_events({subscription_id}, {limit})', subscription_id=subscription_id, limit=limit) if not self._router._broker._event_store: raise ApplicationError( 'wamp.error.history_unavailable', message='event history not available or enabled', ) subscription = self._router._broker._subscription_map.get_observation_by_id(subscription_id) if subscription: if is_protected_uri(subscription.uri, details): raise ApplicationError( ApplicationError.NOT_AUTHORIZED, message='not authorized to retrieve event history for protected URI "{}"'.format(subscription.uri), ) events = self._router._broker._event_store.get_events(subscription_id, limit) if events is None: # a return value of None in above signals that event history really # is not available/enabled (which is different from an empty history!) raise ApplicationError( 'wamp.error.history_unavailable', message='event history for the given subscription is not available or enabled', ) else: return events else: raise ApplicationError( ApplicationError.NO_SUCH_SUBSCRIPTION, 'no subscription with ID {} exists on this broker'.format(subscription_id), )
[ "def", "subscription_get_events", "(", "self", ",", "subscription_id", ",", "limit", "=", "10", ",", "details", "=", "None", ")", ":", "self", ".", "log", ".", "debug", "(", "'subscription_get_events({subscription_id}, {limit})'", ",", "subscription_id", "=", "subscription_id", ",", "limit", "=", "limit", ")", "if", "not", "self", ".", "_router", ".", "_broker", ".", "_event_store", ":", "raise", "ApplicationError", "(", "'wamp.error.history_unavailable'", ",", "message", "=", "'event history not available or enabled'", ",", ")", "subscription", "=", "self", ".", "_router", ".", "_broker", ".", "_subscription_map", ".", "get_observation_by_id", "(", "subscription_id", ")", "if", "subscription", ":", "if", "is_protected_uri", "(", "subscription", ".", "uri", ",", "details", ")", ":", "raise", "ApplicationError", "(", "ApplicationError", ".", "NOT_AUTHORIZED", ",", "message", "=", "'not authorized to retrieve event history for protected URI \"{}\"'", ".", "format", "(", "subscription", ".", "uri", ")", ",", ")", "events", "=", "self", ".", "_router", ".", "_broker", ".", "_event_store", ".", "get_events", "(", "subscription_id", ",", "limit", ")", "if", "events", "is", "None", ":", "# a return value of None in above signals that event history really", "# is not available/enabled (which is different from an empty history!)", "raise", "ApplicationError", "(", "'wamp.error.history_unavailable'", ",", "message", "=", "'event history for the given subscription is not available or enabled'", ",", ")", "else", ":", "return", "events", "else", ":", "raise", "ApplicationError", "(", "ApplicationError", ".", "NO_SUCH_SUBSCRIPTION", ",", "'no subscription with ID {} exists on this broker'", ".", "format", "(", "subscription_id", ")", ",", ")" ]
https://github.com/crossbario/crossbar/blob/ed350b7ba1c8421f3640b9c2e94a21ed4cfdff64/crossbar/router/service.py#L903-L948
fedora-infra/anitya
cc01878ac023790646a76eb4cbef45d639e2372c
anitya/db/migrations/versions/2d1aa7ff82a5_remove_code_google_backend.py
python
upgrade
()
Change backend of projects with code google backend to custom.
Change backend of projects with code google backend to custom.
[ "Change", "backend", "of", "projects", "with", "code", "google", "backend", "to", "custom", "." ]
def upgrade(): """ Change backend of projects with code google backend to custom. """ op.execute( """ UPDATE projects SET backend='custom' WHERE backend='Google code' """ )
[ "def", "upgrade", "(", ")", ":", "op", ".", "execute", "(", "\"\"\"\n UPDATE projects\n SET backend='custom'\n WHERE backend='Google code'\n \"\"\"", ")" ]
https://github.com/fedora-infra/anitya/blob/cc01878ac023790646a76eb4cbef45d639e2372c/anitya/db/migrations/versions/2d1aa7ff82a5_remove_code_google_backend.py#L16-L26
sleventyeleven/linuxprivchecker
0d701080bbf92efd464e97d71a70f97c6f2cd658
linuxprivchecker.py
python
enum_user_info
()
return userinfo
Enumerate User Information (enum_user_info) Enumerate current user information and save the results :return: Dictionary with the user information commands and results
Enumerate User Information (enum_user_info) Enumerate current user information and save the results
[ "Enumerate", "User", "Information", "(", "enum_user_info", ")", "Enumerate", "current", "user", "information", "and", "save", "the", "results" ]
def enum_user_info(): """ Enumerate User Information (enum_user_info) Enumerate current user information and save the results :return: Dictionary with the user information commands and results """ print "\n[*] ENUMERATING USER AND ENVIRONMENTAL INFO...\n" userinfo = { "WHOAMI": {"cmd": "whoami", "msg": "Current User", "results": []}, "ID": {"cmd": "id", "msg": "Current User ID", "results": []}, "ALLUSERS": {"cmd": "cat /etc/passwd", "msg": "All users", "results": []}, "SUPUSERS": {"cmd": "grep -v -E '^#' /etc/passwd | awk -F: '$3 == 0{print $1}'", "msg": "Super Users Found:", "results": []}, "ENV": {"cmd": "env 2>/dev/null | grep -v 'LS_COLORS'", "msg": "Environment", "results": []}, "SUDOERS": {"cmd": "cat /etc/sudoers 2>/dev/null | grep -v '#' 2>/dev/null", "msg": "Sudoers (privileged)", "results": []}, "SCREENS": {"cmd": "screen -ls 2>/dev/null", "msg": "List out any screens running for the current user", "results": []}, "LOGGEDIN": {"cmd": "who -a 2>/dev/null", "msg": "Logged in User Activity", "results": []} } userinfo = execute_cmd(userinfo) print_results(userinfo) if "root" in userinfo["ID"]["results"][0]: print "[!] ARE YOU SURE YOU'RE NOT ROOT ALREADY?\n" exit() return userinfo
[ "def", "enum_user_info", "(", ")", ":", "print", "\"\\n[*] ENUMERATING USER AND ENVIRONMENTAL INFO...\\n\"", "userinfo", "=", "{", "\"WHOAMI\"", ":", "{", "\"cmd\"", ":", "\"whoami\"", ",", "\"msg\"", ":", "\"Current User\"", ",", "\"results\"", ":", "[", "]", "}", ",", "\"ID\"", ":", "{", "\"cmd\"", ":", "\"id\"", ",", "\"msg\"", ":", "\"Current User ID\"", ",", "\"results\"", ":", "[", "]", "}", ",", "\"ALLUSERS\"", ":", "{", "\"cmd\"", ":", "\"cat /etc/passwd\"", ",", "\"msg\"", ":", "\"All users\"", ",", "\"results\"", ":", "[", "]", "}", ",", "\"SUPUSERS\"", ":", "{", "\"cmd\"", ":", "\"grep -v -E '^#' /etc/passwd | awk -F: '$3 == 0{print $1}'\"", ",", "\"msg\"", ":", "\"Super Users Found:\"", ",", "\"results\"", ":", "[", "]", "}", ",", "\"ENV\"", ":", "{", "\"cmd\"", ":", "\"env 2>/dev/null | grep -v 'LS_COLORS'\"", ",", "\"msg\"", ":", "\"Environment\"", ",", "\"results\"", ":", "[", "]", "}", ",", "\"SUDOERS\"", ":", "{", "\"cmd\"", ":", "\"cat /etc/sudoers 2>/dev/null | grep -v '#' 2>/dev/null\"", ",", "\"msg\"", ":", "\"Sudoers (privileged)\"", ",", "\"results\"", ":", "[", "]", "}", ",", "\"SCREENS\"", ":", "{", "\"cmd\"", ":", "\"screen -ls 2>/dev/null\"", ",", "\"msg\"", ":", "\"List out any screens running for the current user\"", ",", "\"results\"", ":", "[", "]", "}", ",", "\"LOGGEDIN\"", ":", "{", "\"cmd\"", ":", "\"who -a 2>/dev/null\"", ",", "\"msg\"", ":", "\"Logged in User Activity\"", ",", "\"results\"", ":", "[", "]", "}", "}", "userinfo", "=", "execute_cmd", "(", "userinfo", ")", "print_results", "(", "userinfo", ")", "if", "\"root\"", "in", "userinfo", "[", "\"ID\"", "]", "[", "\"results\"", "]", "[", "0", "]", ":", "print", "\"[!] ARE YOU SURE YOU'RE NOT ROOT ALREADY?\\n\"", "exit", "(", ")", "return", "userinfo" ]
https://github.com/sleventyeleven/linuxprivchecker/blob/0d701080bbf92efd464e97d71a70f97c6f2cd658/linuxprivchecker.py#L164-L191
openstack/designate
bff3d5f6e31fe595a77143ec4ac779c187bf72a8
designate/api/v2/controllers/zones/__init__.py
python
ZonesController.get_one
(self, zone_id)
return DesignateAdapter.render( 'API_v2', zone, request=request)
Get Zone
Get Zone
[ "Get", "Zone" ]
def get_one(self, zone_id): """Get Zone""" # TODO(kiall): Validate we have a sane UUID for zone_id request = pecan.request context = request.environ['context'] zone = self.central_api.get_zone(context, zone_id) LOG.info("Retrieved %(zone)s", {'zone': zone}) return DesignateAdapter.render( 'API_v2', zone, request=request)
[ "def", "get_one", "(", "self", ",", "zone_id", ")", ":", "# TODO(kiall): Validate we have a sane UUID for zone_id", "request", "=", "pecan", ".", "request", "context", "=", "request", ".", "environ", "[", "'context'", "]", "zone", "=", "self", ".", "central_api", ".", "get_zone", "(", "context", ",", "zone_id", ")", "LOG", ".", "info", "(", "\"Retrieved %(zone)s\"", ",", "{", "'zone'", ":", "zone", "}", ")", "return", "DesignateAdapter", ".", "render", "(", "'API_v2'", ",", "zone", ",", "request", "=", "request", ")" ]
https://github.com/openstack/designate/blob/bff3d5f6e31fe595a77143ec4ac779c187bf72a8/designate/api/v2/controllers/zones/__init__.py#L46-L60
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/matplotlib/afm.py
python
AFM.get_width_from_char_name
(self, name)
return self._metrics_by_name[name].width
Get the width of the character from a type1 character name.
Get the width of the character from a type1 character name.
[ "Get", "the", "width", "of", "the", "character", "from", "a", "type1", "character", "name", "." ]
def get_width_from_char_name(self, name): """Get the width of the character from a type1 character name.""" return self._metrics_by_name[name].width
[ "def", "get_width_from_char_name", "(", "self", ",", "name", ")", ":", "return", "self", ".", "_metrics_by_name", "[", "name", "]", ".", "width" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/matplotlib/afm.py#L478-L480
dpressel/mead-baseline
9987e6b37fa6525a4ddc187c305e292a718f59a9
layers/eight_mile/bleu.py
python
geometric_mean
(precision: np.ndarray)
return np.exp(np.mean(np.log(precision))).item()
Calculate the geometric mean of the precision. Geometric mean is the nth root of the product of n numbers. This can be expressed as the e^(arithmetic mean of the logs). The geometric mean only applies to positive number and any 0 is the values makes the answer trivially zero to checkout for that first to avoid log(0). :param precision: The precision for each n-gram size. :returns: The geometric_mean of the values.
Calculate the geometric mean of the precision.
[ "Calculate", "the", "geometric", "mean", "of", "the", "precision", "." ]
def geometric_mean(precision: np.ndarray) -> float: """Calculate the geometric mean of the precision. Geometric mean is the nth root of the product of n numbers. This can be expressed as the e^(arithmetic mean of the logs). The geometric mean only applies to positive number and any 0 is the values makes the answer trivially zero to checkout for that first to avoid log(0). :param precision: The precision for each n-gram size. :returns: The geometric_mean of the values. """ if np.min(precision) <= 0: return 0.0 return np.exp(np.mean(np.log(precision))).item()
[ "def", "geometric_mean", "(", "precision", ":", "np", ".", "ndarray", ")", "->", "float", ":", "if", "np", ".", "min", "(", "precision", ")", "<=", "0", ":", "return", "0.0", "return", "np", ".", "exp", "(", "np", ".", "mean", "(", "np", ".", "log", "(", "precision", ")", ")", ")", ".", "item", "(", ")" ]
https://github.com/dpressel/mead-baseline/blob/9987e6b37fa6525a4ddc187c305e292a718f59a9/layers/eight_mile/bleu.py#L205-L219
spesmilo/electrum
bdbd59300fbd35b01605e66145458e5f396108e8
electrum/plugins/safe_t/safe_t.py
python
SafeTPlugin.get_safet_input_script_type
(self, electrum_txin_type: str)
[]
def get_safet_input_script_type(self, electrum_txin_type: str): if electrum_txin_type in ('p2wpkh', 'p2wsh'): return self.types.InputScriptType.SPENDWITNESS if electrum_txin_type in ('p2wpkh-p2sh', 'p2wsh-p2sh'): return self.types.InputScriptType.SPENDP2SHWITNESS if electrum_txin_type in ('p2pkh',): return self.types.InputScriptType.SPENDADDRESS if electrum_txin_type in ('p2sh',): return self.types.InputScriptType.SPENDMULTISIG raise ValueError('unexpected txin type: {}'.format(electrum_txin_type))
[ "def", "get_safet_input_script_type", "(", "self", ",", "electrum_txin_type", ":", "str", ")", ":", "if", "electrum_txin_type", "in", "(", "'p2wpkh'", ",", "'p2wsh'", ")", ":", "return", "self", ".", "types", ".", "InputScriptType", ".", "SPENDWITNESS", "if", "electrum_txin_type", "in", "(", "'p2wpkh-p2sh'", ",", "'p2wsh-p2sh'", ")", ":", "return", "self", ".", "types", ".", "InputScriptType", ".", "SPENDP2SHWITNESS", "if", "electrum_txin_type", "in", "(", "'p2pkh'", ",", ")", ":", "return", "self", ".", "types", ".", "InputScriptType", ".", "SPENDADDRESS", "if", "electrum_txin_type", "in", "(", "'p2sh'", ",", ")", ":", "return", "self", ".", "types", ".", "InputScriptType", ".", "SPENDMULTISIG", "raise", "ValueError", "(", "'unexpected txin type: {}'", ".", "format", "(", "electrum_txin_type", ")", ")" ]
https://github.com/spesmilo/electrum/blob/bdbd59300fbd35b01605e66145458e5f396108e8/electrum/plugins/safe_t/safe_t.py#L276-L285
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v8/services/services/dynamic_search_ads_search_term_view_service/client.py
python
DynamicSearchAdsSearchTermViewServiceClient.common_folder_path
(folder: str,)
return "folders/{folder}".format(folder=folder,)
Return a fully-qualified folder string.
Return a fully-qualified folder string.
[ "Return", "a", "fully", "-", "qualified", "folder", "string", "." ]
def common_folder_path(folder: str,) -> str: """Return a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,)
[ "def", "common_folder_path", "(", "folder", ":", "str", ",", ")", "->", "str", ":", "return", "\"folders/{folder}\"", ".", "format", "(", "folder", "=", "folder", ",", ")" ]
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/dynamic_search_ads_search_term_view_service/client.py#L213-L215
jina-ai/jina
c77a492fcd5adba0fc3de5347bea83dd4e7d8087
jina/hubble/hubapi.py
python
get_lockfile
()
return str(_hub_root / 'LOCK')
Get the path of file locker :return: the path of file locker
Get the path of file locker :return: the path of file locker
[ "Get", "the", "path", "of", "file", "locker", ":", "return", ":", "the", "path", "of", "file", "locker" ]
def get_lockfile() -> str: """Get the path of file locker :return: the path of file locker """ return str(_hub_root / 'LOCK')
[ "def", "get_lockfile", "(", ")", "->", "str", ":", "return", "str", "(", "_hub_root", "/", "'LOCK'", ")" ]
https://github.com/jina-ai/jina/blob/c77a492fcd5adba0fc3de5347bea83dd4e7d8087/jina/hubble/hubapi.py#L55-L59
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/blinksticklight/light.py
python
setup_platform
( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, )
Set up Blinkstick device specified by serial number.
Set up Blinkstick device specified by serial number.
[ "Set", "up", "Blinkstick", "device", "specified", "by", "serial", "number", "." ]
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up Blinkstick device specified by serial number.""" name = config[CONF_NAME] serial = config[CONF_SERIAL] stick = blinkstick.find_by_serial(serial) add_entities([BlinkStickLight(stick, name)], True)
[ "def", "setup_platform", "(", "hass", ":", "HomeAssistant", ",", "config", ":", "ConfigType", ",", "add_entities", ":", "AddEntitiesCallback", ",", "discovery_info", ":", "DiscoveryInfoType", "|", "None", "=", "None", ",", ")", "->", "None", ":", "name", "=", "config", "[", "CONF_NAME", "]", "serial", "=", "config", "[", "CONF_SERIAL", "]", "stick", "=", "blinkstick", ".", "find_by_serial", "(", "serial", ")", "add_entities", "(", "[", "BlinkStickLight", "(", "stick", ",", "name", ")", "]", ",", "True", ")" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/blinksticklight/light.py#L36-L49
P1sec/pycrate
d12bbccf1df8c9c7891a26967a9d2635610ec5b8
pycrate_core/elt.py
python
Element.to_int
(self)
Produce a signed integer from the internal value Args: None Returns: integ (int) : signed integer
Produce a signed integer from the internal value Args: None Returns: integ (int) : signed integer
[ "Produce", "a", "signed", "integer", "from", "the", "internal", "value", "Args", ":", "None", "Returns", ":", "integ", "(", "int", ")", ":", "signed", "integer" ]
def to_int(self): """Produce a signed integer from the internal value Args: None Returns: integ (int) : signed integer """ try: return bytes_to_int(self.to_bytes(), self.get_bl()) except PycrateErr: # an invalid value has been set, _SAFE_STAT / DYN is probably disabled # for e.g. fuzzing purpose, but there is still need to not break here b = self.to_bytes() return bytes_to_int(b, len(b)<<3)
[ "def", "to_int", "(", "self", ")", ":", "try", ":", "return", "bytes_to_int", "(", "self", ".", "to_bytes", "(", ")", ",", "self", ".", "get_bl", "(", ")", ")", "except", "PycrateErr", ":", "# an invalid value has been set, _SAFE_STAT / DYN is probably disabled", "# for e.g. fuzzing purpose, but there is still need to not break here", "b", "=", "self", ".", "to_bytes", "(", ")", "return", "bytes_to_int", "(", "b", ",", "len", "(", "b", ")", "<<", "3", ")" ]
https://github.com/P1sec/pycrate/blob/d12bbccf1df8c9c7891a26967a9d2635610ec5b8/pycrate_core/elt.py#L720-L735
ansible/ansible-modules-extras
f216ba8e0616bc8ad8794c22d4b48e1ab18886cf
cloud/misc/virt.py
python
Virt.start
(self, vmid)
return self.conn.create(vmid)
Start the machine via the given id/name
Start the machine via the given id/name
[ "Start", "the", "machine", "via", "the", "given", "id", "/", "name" ]
def start(self, vmid): """ Start the machine via the given id/name """ self.__get_conn() return self.conn.create(vmid)
[ "def", "start", "(", "self", ",", "vmid", ")", ":", "self", ".", "__get_conn", "(", ")", "return", "self", ".", "conn", ".", "create", "(", "vmid", ")" ]
https://github.com/ansible/ansible-modules-extras/blob/f216ba8e0616bc8ad8794c22d4b48e1ab18886cf/cloud/misc/virt.py#L374-L378
h2oai/h2o4gpu
aaf7795d3c3be430129eacfd99d598da0cc838e7
src/interface_py/h2o4gpu/types.py
python
make_settings
(double_precision=False, **kwargs)
return settings
Creates a SettingsS objects from key-values :param double_precision: boolean, optional, default : False :param kwargs: **kwargs :return: SettingsS object
Creates a SettingsS objects from key-values
[ "Creates", "a", "SettingsS", "objects", "from", "key", "-", "values" ]
def make_settings(double_precision=False, **kwargs): """Creates a SettingsS objects from key-values :param double_precision: boolean, optional, default : False :param kwargs: **kwargs :return: SettingsS object """ settings = lazyLib().H2O4GPUSettingsD if double_precision \ else lazyLib().H2O4GPUSettingsS settings.rho = kwargs['rho'] if 'rho' in list( kwargs.keys()) else H2OSolverDefault.RHO settings.relt = kwargs['abs_tol'] if 'abs_tol' in list( kwargs.keys()) else H2OSolverDefault.ABS_TOL settings.abst = kwargs['rel_tol'] if 'rel_tol' in list( kwargs.keys()) else H2OSolverDefault.REL_TOL settings.maxit = kwargs['max_iters'] if 'max_iters' in list( kwargs.keys()) else H2OSolverDefault.MAX_ITERS settings.verb = kwargs['verbose'] if 'verbose' in list( kwargs.keys()) else H2OSolverDefault.VERBOSE settings.adap = kwargs['adaptive_rho'] if 'adaptive_rho' in list( kwargs.keys()) else H2OSolverDefault.ADAPTIVE_RHO settings.equil = kwargs['equil'] if 'equil' in list( kwargs.keys()) else H2OSolverDefault.EQUIL settings.gaps = kwargs['gap_stop'] if 'gap_stop' in list( kwargs.keys()) else H2OSolverDefault.GAP_STOP settings.warm = kwargs['warm_start'] if 'warm_start' in list( kwargs.keys()) else H2OSolverDefault.WARM_START settings.ndev = kwargs['nDev'] if 'nDev' in list( kwargs.keys()) else H2OSolverDefault.N_DEV settings.wdev = kwargs['wDev'] if 'wDev' in list( kwargs.keys()) else H2OSolverDefault.W_DEV return settings
[ "def", "make_settings", "(", "double_precision", "=", "False", ",", "*", "*", "kwargs", ")", ":", "settings", "=", "lazyLib", "(", ")", ".", "H2O4GPUSettingsD", "if", "double_precision", "else", "lazyLib", "(", ")", ".", "H2O4GPUSettingsS", "settings", ".", "rho", "=", "kwargs", "[", "'rho'", "]", "if", "'rho'", "in", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "else", "H2OSolverDefault", ".", "RHO", "settings", ".", "relt", "=", "kwargs", "[", "'abs_tol'", "]", "if", "'abs_tol'", "in", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "else", "H2OSolverDefault", ".", "ABS_TOL", "settings", ".", "abst", "=", "kwargs", "[", "'rel_tol'", "]", "if", "'rel_tol'", "in", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "else", "H2OSolverDefault", ".", "REL_TOL", "settings", ".", "maxit", "=", "kwargs", "[", "'max_iters'", "]", "if", "'max_iters'", "in", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "else", "H2OSolverDefault", ".", "MAX_ITERS", "settings", ".", "verb", "=", "kwargs", "[", "'verbose'", "]", "if", "'verbose'", "in", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "else", "H2OSolverDefault", ".", "VERBOSE", "settings", ".", "adap", "=", "kwargs", "[", "'adaptive_rho'", "]", "if", "'adaptive_rho'", "in", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "else", "H2OSolverDefault", ".", "ADAPTIVE_RHO", "settings", ".", "equil", "=", "kwargs", "[", "'equil'", "]", "if", "'equil'", "in", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "else", "H2OSolverDefault", ".", "EQUIL", "settings", ".", "gaps", "=", "kwargs", "[", "'gap_stop'", "]", "if", "'gap_stop'", "in", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "else", "H2OSolverDefault", ".", "GAP_STOP", "settings", ".", "warm", "=", "kwargs", "[", "'warm_start'", "]", "if", "'warm_start'", "in", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "else", "H2OSolverDefault", ".", "WARM_START", "settings", ".", "ndev", "=", "kwargs", "[", "'nDev'", "]", "if", "'nDev'", "in", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "else", "H2OSolverDefault", ".", "N_DEV", "settings", ".", "wdev", "=", "kwargs", "[", "'wDev'", "]", "if", "'wDev'", "in", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "else", "H2OSolverDefault", ".", "W_DEV", "return", "settings" ]
https://github.com/h2oai/h2o4gpu/blob/aaf7795d3c3be430129eacfd99d598da0cc838e7/src/interface_py/h2o4gpu/types.py#L90-L121
Anaconda-Platform/anaconda-project
df5ec33c12591e6512436d38d36c6132fa2e9618
anaconda_project/internal/cli/environment_commands.py
python
main_remove_packages
(args)
return remove_packages(args.directory, args.env_spec, args.packages, args.pip)
Start the remove-packages command and return exit status code.
Start the remove-packages command and return exit status code.
[ "Start", "the", "remove", "-", "packages", "command", "and", "return", "exit", "status", "code", "." ]
def main_remove_packages(args): """Start the remove-packages command and return exit status code.""" return remove_packages(args.directory, args.env_spec, args.packages, args.pip)
[ "def", "main_remove_packages", "(", "args", ")", ":", "return", "remove_packages", "(", "args", ".", "directory", ",", "args", ".", "env_spec", ",", "args", ".", "packages", ",", "args", ".", "pip", ")" ]
https://github.com/Anaconda-Platform/anaconda-project/blob/df5ec33c12591e6512436d38d36c6132fa2e9618/anaconda_project/internal/cli/environment_commands.py#L196-L198
BMW-InnovationLab/BMW-TensorFlow-Training-GUI
4f10d1f00f9ac312ca833e5b28fd0f8952cfee17
training_api/research/object_detection/metrics/coco_tools.py
python
ExportSingleImageDetectionMasksToCoco
(image_id, category_id_set, detection_masks, detection_scores, detection_classes)
return detections_list
Export detection masks of a single image to COCO format. This function converts detections represented as numpy arrays to dictionaries that can be ingested by the COCO evaluation API. We assume that detection_masks, detection_scores, and detection_classes are in correspondence - that is: detection_masks[i, :], detection_classes[i] and detection_scores[i] are associated with the same annotation. Args: image_id: unique image identifier either of type integer or string. category_id_set: A set of valid class ids. Detections with classes not in category_id_set are dropped. detection_masks: uint8 numpy array of shape [num_detections, image_height, image_width] containing detection_masks. detection_scores: float numpy array of shape [num_detections] containing scores for detection masks. detection_classes: integer numpy array of shape [num_detections] containing the classes for detection masks. Returns: a list of detection mask annotations for a single image in the COCO format. Raises: ValueError: if (1) detection_masks, detection_scores and detection_classes do not have the right lengths or (2) if each of the elements inside these lists do not have the correct shapes or (3) if image_ids are not integers.
Export detection masks of a single image to COCO format.
[ "Export", "detection", "masks", "of", "a", "single", "image", "to", "COCO", "format", "." ]
def ExportSingleImageDetectionMasksToCoco(image_id, category_id_set, detection_masks, detection_scores, detection_classes): """Export detection masks of a single image to COCO format. This function converts detections represented as numpy arrays to dictionaries that can be ingested by the COCO evaluation API. We assume that detection_masks, detection_scores, and detection_classes are in correspondence - that is: detection_masks[i, :], detection_classes[i] and detection_scores[i] are associated with the same annotation. Args: image_id: unique image identifier either of type integer or string. category_id_set: A set of valid class ids. Detections with classes not in category_id_set are dropped. detection_masks: uint8 numpy array of shape [num_detections, image_height, image_width] containing detection_masks. detection_scores: float numpy array of shape [num_detections] containing scores for detection masks. detection_classes: integer numpy array of shape [num_detections] containing the classes for detection masks. Returns: a list of detection mask annotations for a single image in the COCO format. Raises: ValueError: if (1) detection_masks, detection_scores and detection_classes do not have the right lengths or (2) if each of the elements inside these lists do not have the correct shapes or (3) if image_ids are not integers. """ if len(detection_classes.shape) != 1 or len(detection_scores.shape) != 1: raise ValueError('All entries in detection_classes and detection_scores' 'expected to be of rank 1.') num_boxes = detection_classes.shape[0] if not num_boxes == len(detection_masks) == detection_scores.shape[0]: raise ValueError('Corresponding entries in detection_classes, ' 'detection_scores and detection_masks should have ' 'compatible lengths and shapes ' 'Classes length: %d. Masks length: %d. ' 'Scores length: %d' % ( detection_classes.shape[0], len(detection_masks), detection_scores.shape[0] )) detections_list = [] for i in range(num_boxes): if detection_classes[i] in category_id_set: detections_list.append({ 'image_id': image_id, 'category_id': int(detection_classes[i]), 'segmentation': _RleCompress(detection_masks[i]), 'score': float(detection_scores[i]) }) return detections_list
[ "def", "ExportSingleImageDetectionMasksToCoco", "(", "image_id", ",", "category_id_set", ",", "detection_masks", ",", "detection_scores", ",", "detection_classes", ")", ":", "if", "len", "(", "detection_classes", ".", "shape", ")", "!=", "1", "or", "len", "(", "detection_scores", ".", "shape", ")", "!=", "1", ":", "raise", "ValueError", "(", "'All entries in detection_classes and detection_scores'", "'expected to be of rank 1.'", ")", "num_boxes", "=", "detection_classes", ".", "shape", "[", "0", "]", "if", "not", "num_boxes", "==", "len", "(", "detection_masks", ")", "==", "detection_scores", ".", "shape", "[", "0", "]", ":", "raise", "ValueError", "(", "'Corresponding entries in detection_classes, '", "'detection_scores and detection_masks should have '", "'compatible lengths and shapes '", "'Classes length: %d. Masks length: %d. '", "'Scores length: %d'", "%", "(", "detection_classes", ".", "shape", "[", "0", "]", ",", "len", "(", "detection_masks", ")", ",", "detection_scores", ".", "shape", "[", "0", "]", ")", ")", "detections_list", "=", "[", "]", "for", "i", "in", "range", "(", "num_boxes", ")", ":", "if", "detection_classes", "[", "i", "]", "in", "category_id_set", ":", "detections_list", ".", "append", "(", "{", "'image_id'", ":", "image_id", ",", "'category_id'", ":", "int", "(", "detection_classes", "[", "i", "]", ")", ",", "'segmentation'", ":", "_RleCompress", "(", "detection_masks", "[", "i", "]", ")", ",", "'score'", ":", "float", "(", "detection_scores", "[", "i", "]", ")", "}", ")", "return", "detections_list" ]
https://github.com/BMW-InnovationLab/BMW-TensorFlow-Training-GUI/blob/4f10d1f00f9ac312ca833e5b28fd0f8952cfee17/training_api/research/object_detection/metrics/coco_tools.py#L552-L607
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_obj.py
python
OCObject.get
(self)
return results
return a kind by name
return a kind by name
[ "return", "a", "kind", "by", "name" ]
def get(self): '''return a kind by name ''' results = self._get(self.kind, name=self.name, selector=self.selector, field_selector=self.field_selector) if (results['returncode'] != 0 and 'stderr' in results and '\"{}\" not found'.format(self.name) in results['stderr']): results['returncode'] = 0 return results
[ "def", "get", "(", "self", ")", ":", "results", "=", "self", ".", "_get", "(", "self", ".", "kind", ",", "name", "=", "self", ".", "name", ",", "selector", "=", "self", ".", "selector", ",", "field_selector", "=", "self", ".", "field_selector", ")", "if", "(", "results", "[", "'returncode'", "]", "!=", "0", "and", "'stderr'", "in", "results", "and", "'\\\"{}\\\" not found'", ".", "format", "(", "self", ".", "name", ")", "in", "results", "[", "'stderr'", "]", ")", ":", "results", "[", "'returncode'", "]", "=", "0", "return", "results" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_obj.py#L1513-L1520
Dentosal/python-sc2
e816cce83772d1aee1291b86b300b69405aa96b4
sc2/unit.py
python
PassengerUnit.armor
(self)
return self._type_data._proto.armor
Does not include upgrades
Does not include upgrades
[ "Does", "not", "include", "upgrades" ]
def armor(self) -> Union[int, float]: """ Does not include upgrades """ return self._type_data._proto.armor
[ "def", "armor", "(", "self", ")", "->", "Union", "[", "int", ",", "float", "]", ":", "return", "self", ".", "_type_data", ".", "_proto", ".", "armor" ]
https://github.com/Dentosal/python-sc2/blob/e816cce83772d1aee1291b86b300b69405aa96b4/sc2/unit.py#L180-L182
GaoPeng97/transformer-xl-chinese
ecb924f2e6e97955054ef134edc11f72279d18bb
tf/data_utils.py
python
get_bin_sizes
(data, batch_size, tgt_len, cutoffs, std_mult=[2.5, 2.5, 2.5])
return bin_sizes
Note: the `batch_size` here should be per-core batch size
Note: the `batch_size` here should be per-core batch size
[ "Note", ":", "the", "batch_size", "here", "should", "be", "per", "-", "core", "batch", "size" ]
def get_bin_sizes(data, batch_size, tgt_len, cutoffs, std_mult=[2.5, 2.5, 2.5]): """ Note: the `batch_size` here should be per-core batch size """ bin_sizes = [] def _nearest_to_eight(x): # so that it's faster on TPUs y = x - x % 8 return y + 8 if x % 8 >= 4 else max(8, y) if cutoffs: print('======={}======================={}=============================='.format(batch_size, tgt_len)) num_batch = len(data) // batch_size // tgt_len data = data[:batch_size * num_batch * tgt_len] data = data.reshape(batch_size, num_batch, tgt_len) tot = batch_size * tgt_len for b, (left, right) in enumerate(zip(cutoffs[1:-1], cutoffs[2:])): mask = (data >= left) * (data < right) percents = mask.astype(np.float64).sum(2).sum(0) / tot mean = np.mean(percents) std = np.std(percents) bin_size = int(math.ceil(tgt_len * batch_size * (mean + std_mult[b] * std))) bin_size = _nearest_to_eight(bin_size) bin_sizes.append(bin_size) return bin_sizes
[ "def", "get_bin_sizes", "(", "data", ",", "batch_size", ",", "tgt_len", ",", "cutoffs", ",", "std_mult", "=", "[", "2.5", ",", "2.5", ",", "2.5", "]", ")", ":", "bin_sizes", "=", "[", "]", "def", "_nearest_to_eight", "(", "x", ")", ":", "# so that it's faster on TPUs", "y", "=", "x", "-", "x", "%", "8", "return", "y", "+", "8", "if", "x", "%", "8", ">=", "4", "else", "max", "(", "8", ",", "y", ")", "if", "cutoffs", ":", "print", "(", "'======={}======================={}=============================='", ".", "format", "(", "batch_size", ",", "tgt_len", ")", ")", "num_batch", "=", "len", "(", "data", ")", "//", "batch_size", "//", "tgt_len", "data", "=", "data", "[", ":", "batch_size", "*", "num_batch", "*", "tgt_len", "]", "data", "=", "data", ".", "reshape", "(", "batch_size", ",", "num_batch", ",", "tgt_len", ")", "tot", "=", "batch_size", "*", "tgt_len", "for", "b", ",", "(", "left", ",", "right", ")", "in", "enumerate", "(", "zip", "(", "cutoffs", "[", "1", ":", "-", "1", "]", ",", "cutoffs", "[", "2", ":", "]", ")", ")", ":", "mask", "=", "(", "data", ">=", "left", ")", "*", "(", "data", "<", "right", ")", "percents", "=", "mask", ".", "astype", "(", "np", ".", "float64", ")", ".", "sum", "(", "2", ")", ".", "sum", "(", "0", ")", "/", "tot", "mean", "=", "np", ".", "mean", "(", "percents", ")", "std", "=", "np", ".", "std", "(", "percents", ")", "bin_size", "=", "int", "(", "math", ".", "ceil", "(", "tgt_len", "*", "batch_size", "*", "(", "mean", "+", "std_mult", "[", "b", "]", "*", "std", ")", ")", ")", "bin_size", "=", "_nearest_to_eight", "(", "bin_size", ")", "bin_sizes", ".", "append", "(", "bin_size", ")", "return", "bin_sizes" ]
https://github.com/GaoPeng97/transformer-xl-chinese/blob/ecb924f2e6e97955054ef134edc11f72279d18bb/tf/data_utils.py#L181-L209
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/partition.py
python
RegularPartitions_n.cardinality
(self)
return ZZ.sum(1 for x in self)
Return the cardinality of ``self``. EXAMPLES:: sage: P = Partitions(5, regular=3) sage: P.cardinality() 5 sage: P = Partitions(5, regular=6) sage: P.cardinality() 7 sage: P.cardinality() == Partitions(5).cardinality() True TESTS: Check the corner case:: sage: P = Partitions(0, regular=3) sage: P.cardinality() 1 Check for 1-regular partitions:: sage: P = Partitions(0, regular=1) sage: P.cardinality() 1 sage: P = Partitions(5, regular=1) sage: P.cardinality() 0
Return the cardinality of ``self``.
[ "Return", "the", "cardinality", "of", "self", "." ]
def cardinality(self): """ Return the cardinality of ``self``. EXAMPLES:: sage: P = Partitions(5, regular=3) sage: P.cardinality() 5 sage: P = Partitions(5, regular=6) sage: P.cardinality() 7 sage: P.cardinality() == Partitions(5).cardinality() True TESTS: Check the corner case:: sage: P = Partitions(0, regular=3) sage: P.cardinality() 1 Check for 1-regular partitions:: sage: P = Partitions(0, regular=1) sage: P.cardinality() 1 sage: P = Partitions(5, regular=1) sage: P.cardinality() 0 """ if self._ell > self.n: return Partitions_n.cardinality(self) return ZZ.sum(1 for x in self)
[ "def", "cardinality", "(", "self", ")", ":", "if", "self", ".", "_ell", ">", "self", ".", "n", ":", "return", "Partitions_n", ".", "cardinality", "(", "self", ")", "return", "ZZ", ".", "sum", "(", "1", "for", "x", "in", "self", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/partition.py#L8005-L8040
rizar/attention-lvcsr
1ae52cafdd8419874846f9544a299eef9c758f3b
libs/Theano/theano/compile/mode.py
python
register_optimizer
(name, opt)
Add a `Optimizer` which can be referred to by `name` in `Mode`.
Add a `Optimizer` which can be referred to by `name` in `Mode`.
[ "Add", "a", "Optimizer", "which", "can", "be", "referred", "to", "by", "name", "in", "Mode", "." ]
def register_optimizer(name, opt): """Add a `Optimizer` which can be referred to by `name` in `Mode`.""" if name in predefined_optimizers: raise ValueError('Optimizer name already taken: %s' % name) predefined_optimizers[name] = opt
[ "def", "register_optimizer", "(", "name", ",", "opt", ")", ":", "if", "name", "in", "predefined_optimizers", ":", "raise", "ValueError", "(", "'Optimizer name already taken: %s'", "%", "name", ")", "predefined_optimizers", "[", "name", "]", "=", "opt" ]
https://github.com/rizar/attention-lvcsr/blob/1ae52cafdd8419874846f9544a299eef9c758f3b/libs/Theano/theano/compile/mode.py#L109-L113
Podshot/MCEdit-Unified
90abfb170c65b877ac67193e717fa3a3ded635dd
pymclevel/infiniteworld.py
python
MCInfdevOldLevel.close
(self)
Unload all chunks and close all open filehandles. Discard any unsaved data.
Unload all chunks and close all open filehandles. Discard any unsaved data.
[ "Unload", "all", "chunks", "and", "close", "all", "open", "filehandles", ".", "Discard", "any", "unsaved", "data", "." ]
def close(self): """ Unload all chunks and close all open filehandles. Discard any unsaved data. """ self.unload() try: self.checkSessionLock() shutil.rmtree(self.unsavedWorkFolder.filename, True) shutil.rmtree(self.fileEditsFolder.filename, True) except SessionLockLost: pass
[ "def", "close", "(", "self", ")", ":", "self", ".", "unload", "(", ")", "try", ":", "self", ".", "checkSessionLock", "(", ")", "shutil", ".", "rmtree", "(", "self", ".", "unsavedWorkFolder", ".", "filename", ",", "True", ")", "shutil", ".", "rmtree", "(", "self", ".", "fileEditsFolder", ".", "filename", ",", "True", ")", "except", "SessionLockLost", ":", "pass" ]
https://github.com/Podshot/MCEdit-Unified/blob/90abfb170c65b877ac67193e717fa3a3ded635dd/pymclevel/infiniteworld.py#L1351-L1361