id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
239,300
flipagram/smarterling
smarterling/__init__.py
sha1
def sha1(s): """ Returns a sha1 of the given string """ h = hashlib.new('sha1') h.update(s) return h.hexdigest()
python
def sha1(s): """ Returns a sha1 of the given string """ h = hashlib.new('sha1') h.update(s) return h.hexdigest()
[ "def", "sha1", "(", "s", ")", ":", "h", "=", "hashlib", ".", "new", "(", "'sha1'", ")", "h", ".", "update", "(", "s", ")", "return", "h", ".", "hexdigest", "(", ")" ]
Returns a sha1 of the given string
[ "Returns", "a", "sha1", "of", "the", "given", "string" ]
2ea0957edad0657ba4c54280796869ffc1031b11
https://github.com/flipagram/smarterling/blob/2ea0957edad0657ba4c54280796869ffc1031b11/smarterling/__init__.py#L35-L40
239,301
flipagram/smarterling
smarterling/__init__.py
get_translated_items
def get_translated_items(fapi, file_uri, use_cache, cache_dir=None): """ Returns the last modified from smarterling """ items = None cache_file = os.path.join(cache_dir, sha1(file_uri)) if use_cache else None if use_cache and os.path.exists(cache_file): print("Using cache file %s for translated items for: %s" % (cache_file, file_uri)) items = json.loads(read_from_file(cache_file)) if not items: print("Downloading %s from smartling" % file_uri) (response, code) = fapi.last_modified(file_uri) items = response.data.items if cache_file: print("Caching %s to %s" % (file_uri, cache_file)) write_to_file(cache_file, json.dumps(items)) return items
python
def get_translated_items(fapi, file_uri, use_cache, cache_dir=None): """ Returns the last modified from smarterling """ items = None cache_file = os.path.join(cache_dir, sha1(file_uri)) if use_cache else None if use_cache and os.path.exists(cache_file): print("Using cache file %s for translated items for: %s" % (cache_file, file_uri)) items = json.loads(read_from_file(cache_file)) if not items: print("Downloading %s from smartling" % file_uri) (response, code) = fapi.last_modified(file_uri) items = response.data.items if cache_file: print("Caching %s to %s" % (file_uri, cache_file)) write_to_file(cache_file, json.dumps(items)) return items
[ "def", "get_translated_items", "(", "fapi", ",", "file_uri", ",", "use_cache", ",", "cache_dir", "=", "None", ")", ":", "items", "=", "None", "cache_file", "=", "os", ".", "path", ".", "join", "(", "cache_dir", ",", "sha1", "(", "file_uri", ")", ")", "if", "use_cache", "else", "None", "if", "use_cache", "and", "os", ".", "path", ".", "exists", "(", "cache_file", ")", ":", "print", "(", "\"Using cache file %s for translated items for: %s\"", "%", "(", "cache_file", ",", "file_uri", ")", ")", "items", "=", "json", ".", "loads", "(", "read_from_file", "(", "cache_file", ")", ")", "if", "not", "items", ":", "print", "(", "\"Downloading %s from smartling\"", "%", "file_uri", ")", "(", "response", ",", "code", ")", "=", "fapi", ".", "last_modified", "(", "file_uri", ")", "items", "=", "response", ".", "data", ".", "items", "if", "cache_file", ":", "print", "(", "\"Caching %s to %s\"", "%", "(", "file_uri", ",", "cache_file", ")", ")", "write_to_file", "(", "cache_file", ",", "json", ".", "dumps", "(", "items", ")", ")", "return", "items" ]
Returns the last modified from smarterling
[ "Returns", "the", "last", "modified", "from", "smarterling" ]
2ea0957edad0657ba4c54280796869ffc1031b11
https://github.com/flipagram/smarterling/blob/2ea0957edad0657ba4c54280796869ffc1031b11/smarterling/__init__.py#L59-L74
239,302
flipagram/smarterling
smarterling/__init__.py
get_translated_file
def get_translated_file(fapi, file_uri, locale, retrieval_type, include_original_strings, use_cache, cache_dir=None): """ Returns a translated file from smartling """ file_data = None cache_name = str(file_uri)+"."+str(locale)+"."+str(retrieval_type)+"."+str(include_original_strings) cache_file = os.path.join(cache_dir, sha1(cache_name)) if cache_dir else None if use_cache and os.path.exists(cache_file): print("Using cache file %s for %s translation file: %s" % (cache_file, locale, file_uri)) file_data = read_from_file(cache_file) elif not use_cache: (file_data, code) = fapi.get(file_uri, locale, retrievalType=retrieval_type, includeOriginalStrings=include_original_strings) file_data = str(file_data).strip() if cache_file and code == 200 and len(file_data)>0: print("Chaching to %s for %s translation file: %s" % (cache_file, locale, file_uri)) write_to_file(cache_file, file_data) if not file_data or len(file_data)==0: print("%s translation not found for %s" % (locale, file_uri)) return None return file_data
python
def get_translated_file(fapi, file_uri, locale, retrieval_type, include_original_strings, use_cache, cache_dir=None): """ Returns a translated file from smartling """ file_data = None cache_name = str(file_uri)+"."+str(locale)+"."+str(retrieval_type)+"."+str(include_original_strings) cache_file = os.path.join(cache_dir, sha1(cache_name)) if cache_dir else None if use_cache and os.path.exists(cache_file): print("Using cache file %s for %s translation file: %s" % (cache_file, locale, file_uri)) file_data = read_from_file(cache_file) elif not use_cache: (file_data, code) = fapi.get(file_uri, locale, retrievalType=retrieval_type, includeOriginalStrings=include_original_strings) file_data = str(file_data).strip() if cache_file and code == 200 and len(file_data)>0: print("Chaching to %s for %s translation file: %s" % (cache_file, locale, file_uri)) write_to_file(cache_file, file_data) if not file_data or len(file_data)==0: print("%s translation not found for %s" % (locale, file_uri)) return None return file_data
[ "def", "get_translated_file", "(", "fapi", ",", "file_uri", ",", "locale", ",", "retrieval_type", ",", "include_original_strings", ",", "use_cache", ",", "cache_dir", "=", "None", ")", ":", "file_data", "=", "None", "cache_name", "=", "str", "(", "file_uri", ")", "+", "\".\"", "+", "str", "(", "locale", ")", "+", "\".\"", "+", "str", "(", "retrieval_type", ")", "+", "\".\"", "+", "str", "(", "include_original_strings", ")", "cache_file", "=", "os", ".", "path", ".", "join", "(", "cache_dir", ",", "sha1", "(", "cache_name", ")", ")", "if", "cache_dir", "else", "None", "if", "use_cache", "and", "os", ".", "path", ".", "exists", "(", "cache_file", ")", ":", "print", "(", "\"Using cache file %s for %s translation file: %s\"", "%", "(", "cache_file", ",", "locale", ",", "file_uri", ")", ")", "file_data", "=", "read_from_file", "(", "cache_file", ")", "elif", "not", "use_cache", ":", "(", "file_data", ",", "code", ")", "=", "fapi", ".", "get", "(", "file_uri", ",", "locale", ",", "retrievalType", "=", "retrieval_type", ",", "includeOriginalStrings", "=", "include_original_strings", ")", "file_data", "=", "str", "(", "file_data", ")", ".", "strip", "(", ")", "if", "cache_file", "and", "code", "==", "200", "and", "len", "(", "file_data", ")", ">", "0", ":", "print", "(", "\"Chaching to %s for %s translation file: %s\"", "%", "(", "cache_file", ",", "locale", ",", "file_uri", ")", ")", "write_to_file", "(", "cache_file", ",", "file_data", ")", "if", "not", "file_data", "or", "len", "(", "file_data", ")", "==", "0", ":", "print", "(", "\"%s translation not found for %s\"", "%", "(", "locale", ",", "file_uri", ")", ")", "return", "None", "return", "file_data" ]
Returns a translated file from smartling
[ "Returns", "a", "translated", "file", "from", "smartling" ]
2ea0957edad0657ba4c54280796869ffc1031b11
https://github.com/flipagram/smarterling/blob/2ea0957edad0657ba4c54280796869ffc1031b11/smarterling/__init__.py#L76-L97
239,303
flipagram/smarterling
smarterling/__init__.py
upload_file
def upload_file(fapi, file_name, conf): """ Uploads a file to smartling """ if not conf.has_key('file-type'): raise SmarterlingError("%s doesn't have a file-type" % file_name) print("Uploading %s to smartling" % file_name) data = UploadData( os.path.dirname(file_name)+os.sep, os.path.basename(file_name), conf.get('file-type')) data.setUri(file_uri(file_name, conf)) if conf.has_key('approve-content'): data.setApproveContent("true" if conf.get('approve-content', True) else "false") if conf.has_key('callback-url'): data.setCallbackUrl(conf.get('callback-url')) for name, value in conf.get('directives', {}).items(): data.addDirective(SmartlingDirective(name, value)) (response, code) = fapi.upload(data) if code!=200: print(repr(response)) raise SmarterlingError("Error uploading file: %s" % file_name) else: print("Uploaded %s, wordCount: %s, stringCount: %s" % (file_name, response.data.wordCount, response.data.stringCount))
python
def upload_file(fapi, file_name, conf): """ Uploads a file to smartling """ if not conf.has_key('file-type'): raise SmarterlingError("%s doesn't have a file-type" % file_name) print("Uploading %s to smartling" % file_name) data = UploadData( os.path.dirname(file_name)+os.sep, os.path.basename(file_name), conf.get('file-type')) data.setUri(file_uri(file_name, conf)) if conf.has_key('approve-content'): data.setApproveContent("true" if conf.get('approve-content', True) else "false") if conf.has_key('callback-url'): data.setCallbackUrl(conf.get('callback-url')) for name, value in conf.get('directives', {}).items(): data.addDirective(SmartlingDirective(name, value)) (response, code) = fapi.upload(data) if code!=200: print(repr(response)) raise SmarterlingError("Error uploading file: %s" % file_name) else: print("Uploaded %s, wordCount: %s, stringCount: %s" % (file_name, response.data.wordCount, response.data.stringCount))
[ "def", "upload_file", "(", "fapi", ",", "file_name", ",", "conf", ")", ":", "if", "not", "conf", ".", "has_key", "(", "'file-type'", ")", ":", "raise", "SmarterlingError", "(", "\"%s doesn't have a file-type\"", "%", "file_name", ")", "print", "(", "\"Uploading %s to smartling\"", "%", "file_name", ")", "data", "=", "UploadData", "(", "os", ".", "path", ".", "dirname", "(", "file_name", ")", "+", "os", ".", "sep", ",", "os", ".", "path", ".", "basename", "(", "file_name", ")", ",", "conf", ".", "get", "(", "'file-type'", ")", ")", "data", ".", "setUri", "(", "file_uri", "(", "file_name", ",", "conf", ")", ")", "if", "conf", ".", "has_key", "(", "'approve-content'", ")", ":", "data", ".", "setApproveContent", "(", "\"true\"", "if", "conf", ".", "get", "(", "'approve-content'", ",", "True", ")", "else", "\"false\"", ")", "if", "conf", ".", "has_key", "(", "'callback-url'", ")", ":", "data", ".", "setCallbackUrl", "(", "conf", ".", "get", "(", "'callback-url'", ")", ")", "for", "name", ",", "value", "in", "conf", ".", "get", "(", "'directives'", ",", "{", "}", ")", ".", "items", "(", ")", ":", "data", ".", "addDirective", "(", "SmartlingDirective", "(", "name", ",", "value", ")", ")", "(", "response", ",", "code", ")", "=", "fapi", ".", "upload", "(", "data", ")", "if", "code", "!=", "200", ":", "print", "(", "repr", "(", "response", ")", ")", "raise", "SmarterlingError", "(", "\"Error uploading file: %s\"", "%", "file_name", ")", "else", ":", "print", "(", "\"Uploaded %s, wordCount: %s, stringCount: %s\"", "%", "(", "file_name", ",", "response", ".", "data", ".", "wordCount", ",", "response", ".", "data", ".", "stringCount", ")", ")" ]
Uploads a file to smartling
[ "Uploads", "a", "file", "to", "smartling" ]
2ea0957edad0657ba4c54280796869ffc1031b11
https://github.com/flipagram/smarterling/blob/2ea0957edad0657ba4c54280796869ffc1031b11/smarterling/__init__.py#L189-L211
239,304
flipagram/smarterling
smarterling/__init__.py
create_file_api
def create_file_api(conf): """ Creates a SmartlingFileApi from the given config """ api_key = conf.config.get('api-key', os.environ.get('SMARTLING_API_KEY')) project_id = conf.config.get('project-id', os.environ.get('SMARTLING_PROJECT_ID')) if not project_id or not api_key: raise SmarterlingError('config.api-key and config.project-id are required configuration items') proxy_settings=None if conf.config.has_key('proxy-settings'): proxy_settings = ProxySettings( conf.config.get('proxy-settings').get('username', ''), conf.config.get('proxy-settings').get('password', ''), conf.config.get('proxy-settings').get('host', ''), int(conf.config.get('proxy-settings').get('port', '80'))) return SmartlingFileApiFactory().getSmartlingTranslationApi( not conf.config.get('sandbox', False), api_key, project_id, proxySettings=proxy_settings)
python
def create_file_api(conf): """ Creates a SmartlingFileApi from the given config """ api_key = conf.config.get('api-key', os.environ.get('SMARTLING_API_KEY')) project_id = conf.config.get('project-id', os.environ.get('SMARTLING_PROJECT_ID')) if not project_id or not api_key: raise SmarterlingError('config.api-key and config.project-id are required configuration items') proxy_settings=None if conf.config.has_key('proxy-settings'): proxy_settings = ProxySettings( conf.config.get('proxy-settings').get('username', ''), conf.config.get('proxy-settings').get('password', ''), conf.config.get('proxy-settings').get('host', ''), int(conf.config.get('proxy-settings').get('port', '80'))) return SmartlingFileApiFactory().getSmartlingTranslationApi( not conf.config.get('sandbox', False), api_key, project_id, proxySettings=proxy_settings)
[ "def", "create_file_api", "(", "conf", ")", ":", "api_key", "=", "conf", ".", "config", ".", "get", "(", "'api-key'", ",", "os", ".", "environ", ".", "get", "(", "'SMARTLING_API_KEY'", ")", ")", "project_id", "=", "conf", ".", "config", ".", "get", "(", "'project-id'", ",", "os", ".", "environ", ".", "get", "(", "'SMARTLING_PROJECT_ID'", ")", ")", "if", "not", "project_id", "or", "not", "api_key", ":", "raise", "SmarterlingError", "(", "'config.api-key and config.project-id are required configuration items'", ")", "proxy_settings", "=", "None", "if", "conf", ".", "config", ".", "has_key", "(", "'proxy-settings'", ")", ":", "proxy_settings", "=", "ProxySettings", "(", "conf", ".", "config", ".", "get", "(", "'proxy-settings'", ")", ".", "get", "(", "'username'", ",", "''", ")", ",", "conf", ".", "config", ".", "get", "(", "'proxy-settings'", ")", ".", "get", "(", "'password'", ",", "''", ")", ",", "conf", ".", "config", ".", "get", "(", "'proxy-settings'", ")", ".", "get", "(", "'host'", ",", "''", ")", ",", "int", "(", "conf", ".", "config", ".", "get", "(", "'proxy-settings'", ")", ".", "get", "(", "'port'", ",", "'80'", ")", ")", ")", "return", "SmartlingFileApiFactory", "(", ")", ".", "getSmartlingTranslationApi", "(", "not", "conf", ".", "config", ".", "get", "(", "'sandbox'", ",", "False", ")", ",", "api_key", ",", "project_id", ",", "proxySettings", "=", "proxy_settings", ")" ]
Creates a SmartlingFileApi from the given config
[ "Creates", "a", "SmartlingFileApi", "from", "the", "given", "config" ]
2ea0957edad0657ba4c54280796869ffc1031b11
https://github.com/flipagram/smarterling/blob/2ea0957edad0657ba4c54280796869ffc1031b11/smarterling/__init__.py#L213-L232
239,305
flipagram/smarterling
smarterling/__init__.py
parse_config
def parse_config(file_name='smarterling.config'): """ Parses a smarterling configuration file """ if not os.path.exists(file_name) or not os.path.isfile(file_name): raise SmarterlingError('Config file not found: %s' % file_name) try: contents = read_from_file(file_name) contents_with_environment_variables_expanded = os.path.expandvars(contents) return AttributeDict(yaml.load(contents_with_environment_variables_expanded)) except Exception as e: raise SmarterlingError("Error paring config file: %s" % str(e))
python
def parse_config(file_name='smarterling.config'): """ Parses a smarterling configuration file """ if not os.path.exists(file_name) or not os.path.isfile(file_name): raise SmarterlingError('Config file not found: %s' % file_name) try: contents = read_from_file(file_name) contents_with_environment_variables_expanded = os.path.expandvars(contents) return AttributeDict(yaml.load(contents_with_environment_variables_expanded)) except Exception as e: raise SmarterlingError("Error paring config file: %s" % str(e))
[ "def", "parse_config", "(", "file_name", "=", "'smarterling.config'", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "file_name", ")", "or", "not", "os", ".", "path", ".", "isfile", "(", "file_name", ")", ":", "raise", "SmarterlingError", "(", "'Config file not found: %s'", "%", "file_name", ")", "try", ":", "contents", "=", "read_from_file", "(", "file_name", ")", "contents_with_environment_variables_expanded", "=", "os", ".", "path", ".", "expandvars", "(", "contents", ")", "return", "AttributeDict", "(", "yaml", ".", "load", "(", "contents_with_environment_variables_expanded", ")", ")", "except", "Exception", "as", "e", ":", "raise", "SmarterlingError", "(", "\"Error paring config file: %s\"", "%", "str", "(", "e", ")", ")" ]
Parses a smarterling configuration file
[ "Parses", "a", "smarterling", "configuration", "file" ]
2ea0957edad0657ba4c54280796869ffc1031b11
https://github.com/flipagram/smarterling/blob/2ea0957edad0657ba4c54280796869ffc1031b11/smarterling/__init__.py#L234-L244
239,306
flipagram/smarterling
smarterling/__init__.py
AttributeDict.get
def get(self, key, default_val=None, require_value=False): """ Returns a dictionary value """ val = dict.get(self, key, default_val) if val is None and require_value: raise KeyError('key "%s" not found' % key) if isinstance(val, dict): return AttributeDict(val) return val
python
def get(self, key, default_val=None, require_value=False): """ Returns a dictionary value """ val = dict.get(self, key, default_val) if val is None and require_value: raise KeyError('key "%s" not found' % key) if isinstance(val, dict): return AttributeDict(val) return val
[ "def", "get", "(", "self", ",", "key", ",", "default_val", "=", "None", ",", "require_value", "=", "False", ")", ":", "val", "=", "dict", ".", "get", "(", "self", ",", "key", ",", "default_val", ")", "if", "val", "is", "None", "and", "require_value", ":", "raise", "KeyError", "(", "'key \"%s\" not found'", "%", "key", ")", "if", "isinstance", "(", "val", ",", "dict", ")", ":", "return", "AttributeDict", "(", "val", ")", "return", "val" ]
Returns a dictionary value
[ "Returns", "a", "dictionary", "value" ]
2ea0957edad0657ba4c54280796869ffc1031b11
https://github.com/flipagram/smarterling/blob/2ea0957edad0657ba4c54280796869ffc1031b11/smarterling/__init__.py#L25-L33
239,307
roboogle/gtkmvc3
gtkmvco/gtkmvc3/adapters/basic.py
Adapter.connect_widget
def connect_widget(self, wid, getter=None, setter=None, signal=None, arg=None, update=True, flavour=None): """ Finish set-up by connecting the widget. The model was already specified in the constructor. *wid* is a widget instance. *getter* is a callable. It is passed *wid* and must return its current value. *setter* is a callable. It is passed *wid* and the current value of the model property and must update the widget. *signal* is a string naming the signal to connect to on *wid*. When it is emitted we update the model. *getter*, *setter* and *signal* are optional. Missing values are guessed from *wid* using :meth:`gtkmvc3.adapters.default.search_adapter_info`. If nothing is found this raises :exc:`TypeError`. *arg* is an optional value passed to the handler for *signal*. This doesn't do anything unless a subclass overrides the handler. *update* denotes whether to update the widget from the model immediately. Otherwise the widget stays unchanged until the first notification. *flavour* can be used to select special behaviours about the adaptation when twice or more possibilities are possibly handled for the same widget type. See adapters.default for further information. """ if wid in self._wid_info: raise ValueError("Widget " + str(wid) + " was already connected") wid_type = None if None in (getter, setter, signal): w = search_adapter_info(wid, flavour) if getter is None: getter = w[GETTER] if setter is None: setter = w[SETTER] wid_type = w[WIDTYPE] if signal is None: signal = w[SIGNAL] # saves information about the widget self._wid_info[wid] = (getter, setter, wid_type) # connects the widget if signal: if arg: wid.connect(signal, self._on_wid_changed, arg) else: wid.connect(signal, self._on_wid_changed) self._wid = wid # updates the widget: if update: self.update_widget()
python
def connect_widget(self, wid, getter=None, setter=None, signal=None, arg=None, update=True, flavour=None): """ Finish set-up by connecting the widget. The model was already specified in the constructor. *wid* is a widget instance. *getter* is a callable. It is passed *wid* and must return its current value. *setter* is a callable. It is passed *wid* and the current value of the model property and must update the widget. *signal* is a string naming the signal to connect to on *wid*. When it is emitted we update the model. *getter*, *setter* and *signal* are optional. Missing values are guessed from *wid* using :meth:`gtkmvc3.adapters.default.search_adapter_info`. If nothing is found this raises :exc:`TypeError`. *arg* is an optional value passed to the handler for *signal*. This doesn't do anything unless a subclass overrides the handler. *update* denotes whether to update the widget from the model immediately. Otherwise the widget stays unchanged until the first notification. *flavour* can be used to select special behaviours about the adaptation when twice or more possibilities are possibly handled for the same widget type. See adapters.default for further information. """ if wid in self._wid_info: raise ValueError("Widget " + str(wid) + " was already connected") wid_type = None if None in (getter, setter, signal): w = search_adapter_info(wid, flavour) if getter is None: getter = w[GETTER] if setter is None: setter = w[SETTER] wid_type = w[WIDTYPE] if signal is None: signal = w[SIGNAL] # saves information about the widget self._wid_info[wid] = (getter, setter, wid_type) # connects the widget if signal: if arg: wid.connect(signal, self._on_wid_changed, arg) else: wid.connect(signal, self._on_wid_changed) self._wid = wid # updates the widget: if update: self.update_widget()
[ "def", "connect_widget", "(", "self", ",", "wid", ",", "getter", "=", "None", ",", "setter", "=", "None", ",", "signal", "=", "None", ",", "arg", "=", "None", ",", "update", "=", "True", ",", "flavour", "=", "None", ")", ":", "if", "wid", "in", "self", ".", "_wid_info", ":", "raise", "ValueError", "(", "\"Widget \"", "+", "str", "(", "wid", ")", "+", "\" was already connected\"", ")", "wid_type", "=", "None", "if", "None", "in", "(", "getter", ",", "setter", ",", "signal", ")", ":", "w", "=", "search_adapter_info", "(", "wid", ",", "flavour", ")", "if", "getter", "is", "None", ":", "getter", "=", "w", "[", "GETTER", "]", "if", "setter", "is", "None", ":", "setter", "=", "w", "[", "SETTER", "]", "wid_type", "=", "w", "[", "WIDTYPE", "]", "if", "signal", "is", "None", ":", "signal", "=", "w", "[", "SIGNAL", "]", "# saves information about the widget", "self", ".", "_wid_info", "[", "wid", "]", "=", "(", "getter", ",", "setter", ",", "wid_type", ")", "# connects the widget", "if", "signal", ":", "if", "arg", ":", "wid", ".", "connect", "(", "signal", ",", "self", ".", "_on_wid_changed", ",", "arg", ")", "else", ":", "wid", ".", "connect", "(", "signal", ",", "self", ".", "_on_wid_changed", ")", "self", ".", "_wid", "=", "wid", "# updates the widget:", "if", "update", ":", "self", ".", "update_widget", "(", ")" ]
Finish set-up by connecting the widget. The model was already specified in the constructor. *wid* is a widget instance. *getter* is a callable. It is passed *wid* and must return its current value. *setter* is a callable. It is passed *wid* and the current value of the model property and must update the widget. *signal* is a string naming the signal to connect to on *wid*. When it is emitted we update the model. *getter*, *setter* and *signal* are optional. Missing values are guessed from *wid* using :meth:`gtkmvc3.adapters.default.search_adapter_info`. If nothing is found this raises :exc:`TypeError`. *arg* is an optional value passed to the handler for *signal*. This doesn't do anything unless a subclass overrides the handler. *update* denotes whether to update the widget from the model immediately. Otherwise the widget stays unchanged until the first notification. *flavour* can be used to select special behaviours about the adaptation when twice or more possibilities are possibly handled for the same widget type. See adapters.default for further information.
[ "Finish", "set", "-", "up", "by", "connecting", "the", "widget", ".", "The", "model", "was", "already", "specified", "in", "the", "constructor", "." ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/adapters/basic.py#L160-L229
239,308
roboogle/gtkmvc3
gtkmvco/gtkmvc3/adapters/basic.py
Adapter._connect_model
def _connect_model(self, model): """ Used internally to connect the property into the model, and register self as a value observer for that property""" parts = self._prop_name.split(".") if len(parts) > 1: # identifies the model models = parts[:-1] Intermediate(model, models, self) for name in models: model = getattr(model, name) if not isinstance(model, Model): raise TypeError("Attribute '" + name + "' was expected to be a Model, but found: " + str(model)) prop = parts[-1] else: prop = parts[0] # prop is inside model? if not hasattr(model, prop): raise ValueError("Attribute '" + prop + "' not found in model " + str(model)) # is it observable? if model.has_property(prop): # we need to create an observing method before registering meth = types.MethodType(self._get_observer_fun(prop), self) setattr(self, meth.__name__, meth) self._prop = getattr(model, prop) self._prop_name = prop # registration of model: self._model = model self.observe_model(model)
python
def _connect_model(self, model): """ Used internally to connect the property into the model, and register self as a value observer for that property""" parts = self._prop_name.split(".") if len(parts) > 1: # identifies the model models = parts[:-1] Intermediate(model, models, self) for name in models: model = getattr(model, name) if not isinstance(model, Model): raise TypeError("Attribute '" + name + "' was expected to be a Model, but found: " + str(model)) prop = parts[-1] else: prop = parts[0] # prop is inside model? if not hasattr(model, prop): raise ValueError("Attribute '" + prop + "' not found in model " + str(model)) # is it observable? if model.has_property(prop): # we need to create an observing method before registering meth = types.MethodType(self._get_observer_fun(prop), self) setattr(self, meth.__name__, meth) self._prop = getattr(model, prop) self._prop_name = prop # registration of model: self._model = model self.observe_model(model)
[ "def", "_connect_model", "(", "self", ",", "model", ")", ":", "parts", "=", "self", ".", "_prop_name", ".", "split", "(", "\".\"", ")", "if", "len", "(", "parts", ")", ">", "1", ":", "# identifies the model", "models", "=", "parts", "[", ":", "-", "1", "]", "Intermediate", "(", "model", ",", "models", ",", "self", ")", "for", "name", "in", "models", ":", "model", "=", "getattr", "(", "model", ",", "name", ")", "if", "not", "isinstance", "(", "model", ",", "Model", ")", ":", "raise", "TypeError", "(", "\"Attribute '\"", "+", "name", "+", "\"' was expected to be a Model, but found: \"", "+", "str", "(", "model", ")", ")", "prop", "=", "parts", "[", "-", "1", "]", "else", ":", "prop", "=", "parts", "[", "0", "]", "# prop is inside model?", "if", "not", "hasattr", "(", "model", ",", "prop", ")", ":", "raise", "ValueError", "(", "\"Attribute '\"", "+", "prop", "+", "\"' not found in model \"", "+", "str", "(", "model", ")", ")", "# is it observable?", "if", "model", ".", "has_property", "(", "prop", ")", ":", "# we need to create an observing method before registering", "meth", "=", "types", ".", "MethodType", "(", "self", ".", "_get_observer_fun", "(", "prop", ")", ",", "self", ")", "setattr", "(", "self", ",", "meth", ".", "__name__", ",", "meth", ")", "self", ".", "_prop", "=", "getattr", "(", "model", ",", "prop", ")", "self", ".", "_prop_name", "=", "prop", "# registration of model:", "self", ".", "_model", "=", "model", "self", ".", "observe_model", "(", "model", ")" ]
Used internally to connect the property into the model, and register self as a value observer for that property
[ "Used", "internally", "to", "connect", "the", "property", "into", "the", "model", "and", "register", "self", "as", "a", "value", "observer", "for", "that", "property" ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/adapters/basic.py#L257-L292
239,309
roboogle/gtkmvc3
gtkmvco/gtkmvc3/adapters/basic.py
Adapter._get_observer_fun
def _get_observer_fun(self, prop_name): """This is the code for an value change observer""" def _observer_fun(self, model, old, new): if self._itsme: return self._on_prop_changed() # doesn't affect stack traces _observer_fun.__name__ = "property_%s_value_change" % prop_name return _observer_fun
python
def _get_observer_fun(self, prop_name): """This is the code for an value change observer""" def _observer_fun(self, model, old, new): if self._itsme: return self._on_prop_changed() # doesn't affect stack traces _observer_fun.__name__ = "property_%s_value_change" % prop_name return _observer_fun
[ "def", "_get_observer_fun", "(", "self", ",", "prop_name", ")", ":", "def", "_observer_fun", "(", "self", ",", "model", ",", "old", ",", "new", ")", ":", "if", "self", ".", "_itsme", ":", "return", "self", ".", "_on_prop_changed", "(", ")", "# doesn't affect stack traces", "_observer_fun", ".", "__name__", "=", "\"property_%s_value_change\"", "%", "prop_name", "return", "_observer_fun" ]
This is the code for an value change observer
[ "This", "is", "the", "code", "for", "an", "value", "change", "observer" ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/adapters/basic.py#L294-L303
239,310
roboogle/gtkmvc3
gtkmvco/gtkmvc3/adapters/basic.py
Adapter._write_property
def _write_property(self, val, *args): """Sets the value of property. Given val is transformed accodingly to prop_write function when specified at construction-time. A try to cast the value to the property type is given.""" val_wid = val # 'finally' would be better here, but not supported in 2.4 :( try: totype = type(self._get_property(*args)) if (totype is not type(None) and (self._prop_cast or not self._prop_write)): val = self._cast_value(val, totype) if self._prop_write: val = self._prop_write(val) self._itsme = True self._set_property(val, *args) except ValueError: self._itsme = False if self._value_error: self._value_error(self, self._prop_name, val_wid) else: raise except: self._itsme = False raise self._itsme = False
python
def _write_property(self, val, *args): """Sets the value of property. Given val is transformed accodingly to prop_write function when specified at construction-time. A try to cast the value to the property type is given.""" val_wid = val # 'finally' would be better here, but not supported in 2.4 :( try: totype = type(self._get_property(*args)) if (totype is not type(None) and (self._prop_cast or not self._prop_write)): val = self._cast_value(val, totype) if self._prop_write: val = self._prop_write(val) self._itsme = True self._set_property(val, *args) except ValueError: self._itsme = False if self._value_error: self._value_error(self, self._prop_name, val_wid) else: raise except: self._itsme = False raise self._itsme = False
[ "def", "_write_property", "(", "self", ",", "val", ",", "*", "args", ")", ":", "val_wid", "=", "val", "# 'finally' would be better here, but not supported in 2.4 :(", "try", ":", "totype", "=", "type", "(", "self", ".", "_get_property", "(", "*", "args", ")", ")", "if", "(", "totype", "is", "not", "type", "(", "None", ")", "and", "(", "self", ".", "_prop_cast", "or", "not", "self", ".", "_prop_write", ")", ")", ":", "val", "=", "self", ".", "_cast_value", "(", "val", ",", "totype", ")", "if", "self", ".", "_prop_write", ":", "val", "=", "self", ".", "_prop_write", "(", "val", ")", "self", ".", "_itsme", "=", "True", "self", ".", "_set_property", "(", "val", ",", "*", "args", ")", "except", "ValueError", ":", "self", ".", "_itsme", "=", "False", "if", "self", ".", "_value_error", ":", "self", ".", "_value_error", "(", "self", ",", "self", ".", "_prop_name", ",", "val_wid", ")", "else", ":", "raise", "except", ":", "self", ".", "_itsme", "=", "False", "raise", "self", ".", "_itsme", "=", "False" ]
Sets the value of property. Given val is transformed accodingly to prop_write function when specified at construction-time. A try to cast the value to the property type is given.
[ "Sets", "the", "value", "of", "property", ".", "Given", "val", "is", "transformed", "accodingly", "to", "prop_write", "function", "when", "specified", "at", "construction", "-", "time", ".", "A", "try", "to", "cast", "the", "value", "to", "the", "property", "type", "is", "given", "." ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/adapters/basic.py#L326-L356
239,311
roboogle/gtkmvc3
gtkmvco/gtkmvc3/adapters/basic.py
Adapter._read_widget
def _read_widget(self): """Returns the value currently stored into the widget, after transforming it accordingly to possibly specified function. This is implemented by calling the getter provided by the user. This method can raise InvalidValue (raised by the getter) when the value in the widget must not be considered as valid.""" getter = self._wid_info[self._wid][0] return getter(self._wid)
python
def _read_widget(self): """Returns the value currently stored into the widget, after transforming it accordingly to possibly specified function. This is implemented by calling the getter provided by the user. This method can raise InvalidValue (raised by the getter) when the value in the widget must not be considered as valid.""" getter = self._wid_info[self._wid][0] return getter(self._wid)
[ "def", "_read_widget", "(", "self", ")", ":", "getter", "=", "self", ".", "_wid_info", "[", "self", ".", "_wid", "]", "[", "0", "]", "return", "getter", "(", "self", ".", "_wid", ")" ]
Returns the value currently stored into the widget, after transforming it accordingly to possibly specified function. This is implemented by calling the getter provided by the user. This method can raise InvalidValue (raised by the getter) when the value in the widget must not be considered as valid.
[ "Returns", "the", "value", "currently", "stored", "into", "the", "widget", "after", "transforming", "it", "accordingly", "to", "possibly", "specified", "function", "." ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/adapters/basic.py#L358-L367
239,312
roboogle/gtkmvc3
gtkmvco/gtkmvc3/adapters/basic.py
Adapter._write_widget
def _write_widget(self, val): """Writes value into the widget. If specified, user setter is invoked.""" self._itsme = True try: setter = self._wid_info[self._wid][1] wtype = self._wid_info[self._wid][2] if setter: if wtype is not None: setter(self._wid, self._cast_value(val, wtype)) else: setter(self._wid, val) finally: self._itsme = False
python
def _write_widget(self, val): """Writes value into the widget. If specified, user setter is invoked.""" self._itsme = True try: setter = self._wid_info[self._wid][1] wtype = self._wid_info[self._wid][2] if setter: if wtype is not None: setter(self._wid, self._cast_value(val, wtype)) else: setter(self._wid, val) finally: self._itsme = False
[ "def", "_write_widget", "(", "self", ",", "val", ")", ":", "self", ".", "_itsme", "=", "True", "try", ":", "setter", "=", "self", ".", "_wid_info", "[", "self", ".", "_wid", "]", "[", "1", "]", "wtype", "=", "self", ".", "_wid_info", "[", "self", ".", "_wid", "]", "[", "2", "]", "if", "setter", ":", "if", "wtype", "is", "not", "None", ":", "setter", "(", "self", ".", "_wid", ",", "self", ".", "_cast_value", "(", "val", ",", "wtype", ")", ")", "else", ":", "setter", "(", "self", ".", "_wid", ",", "val", ")", "finally", ":", "self", ".", "_itsme", "=", "False" ]
Writes value into the widget. If specified, user setter is invoked.
[ "Writes", "value", "into", "the", "widget", ".", "If", "specified", "user", "setter", "is", "invoked", "." ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/adapters/basic.py#L369-L382
239,313
roboogle/gtkmvc3
gtkmvco/gtkmvc3/adapters/basic.py
UserClassAdapter._on_prop_changed
def _on_prop_changed(self, instance, meth_name, res, args, kwargs): """Called by the observation code, when a modifying method is called""" Adapter._on_prop_changed(self)
python
def _on_prop_changed(self, instance, meth_name, res, args, kwargs): """Called by the observation code, when a modifying method is called""" Adapter._on_prop_changed(self)
[ "def", "_on_prop_changed", "(", "self", ",", "instance", ",", "meth_name", ",", "res", ",", "args", ",", "kwargs", ")", ":", "Adapter", ".", "_on_prop_changed", "(", "self", ")" ]
Called by the observation code, when a modifying method is called
[ "Called", "by", "the", "observation", "code", "when", "a", "modifying", "method", "is", "called" ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/adapters/basic.py#L459-L462
239,314
roboogle/gtkmvc3
gtkmvco/gtkmvc3/adapters/basic.py
UserClassAdapter._get_property
def _get_property(self, *args): """Private method that returns the value currently stored into the property""" val = self._getter(Adapter._get_property(self), *args) if self._prop_read: return self._prop_read(val, *args) return val
python
def _get_property(self, *args): """Private method that returns the value currently stored into the property""" val = self._getter(Adapter._get_property(self), *args) if self._prop_read: return self._prop_read(val, *args) return val
[ "def", "_get_property", "(", "self", ",", "*", "args", ")", ":", "val", "=", "self", ".", "_getter", "(", "Adapter", ".", "_get_property", "(", "self", ")", ",", "*", "args", ")", "if", "self", ".", "_prop_read", ":", "return", "self", ".", "_prop_read", "(", "val", ",", "*", "args", ")", "return", "val" ]
Private method that returns the value currently stored into the property
[ "Private", "method", "that", "returns", "the", "value", "currently", "stored", "into", "the", "property" ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/adapters/basic.py#L464-L470
239,315
pip-services3-python/pip-services3-commons-python
pip_services3_commons/random/RandomString.py
RandomString.distort
def distort(value): """ Distorts a string by randomly replacing characters in it. :param value: a string to distort. :return: a distored string. """ value = value.lower() if (RandomBoolean.chance(1, 5)): value = value[0:1].upper() + value[1:] if (RandomBoolean.chance(1, 3)): value = value + random.choice(_symbols) return value
python
def distort(value): """ Distorts a string by randomly replacing characters in it. :param value: a string to distort. :return: a distored string. """ value = value.lower() if (RandomBoolean.chance(1, 5)): value = value[0:1].upper() + value[1:] if (RandomBoolean.chance(1, 3)): value = value + random.choice(_symbols) return value
[ "def", "distort", "(", "value", ")", ":", "value", "=", "value", ".", "lower", "(", ")", "if", "(", "RandomBoolean", ".", "chance", "(", "1", ",", "5", ")", ")", ":", "value", "=", "value", "[", "0", ":", "1", "]", ".", "upper", "(", ")", "+", "value", "[", "1", ":", "]", "if", "(", "RandomBoolean", ".", "chance", "(", "1", ",", "3", ")", ")", ":", "value", "=", "value", "+", "random", ".", "choice", "(", "_symbols", ")", "return", "value" ]
Distorts a string by randomly replacing characters in it. :param value: a string to distort. :return: a distored string.
[ "Distorts", "a", "string", "by", "randomly", "replacing", "characters", "in", "it", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/random/RandomString.py#L47-L63
239,316
kervi/kervi-devices
kervi/devices/pwm/PCA9685.py
PCA9685DeviceDriver.pwm_start
def pwm_start(self, channel, duty_cycle=None, frequency=None): """ Starts the pwm signal on a channel. The channel should be defined as pwm prior to this call. If no duty_cycle or frequency is passed in this call previous values from call to define_as_pwm or pwm_start is used. :param channel: The channel to start the pwm signal on. :type channel: ``int`` :param duty_cycle: The duty cycle use on the channel. :type duty_cycle: ``int`` :param frequency: The frequency to be used on the pwm channel. :type frequency: ``int`` """ if frequency: self.set_pwm_freq(frequency) self.set_pwm(channel, 0, int(4096 * (duty_cycle/100)))
python
def pwm_start(self, channel, duty_cycle=None, frequency=None): """ Starts the pwm signal on a channel. The channel should be defined as pwm prior to this call. If no duty_cycle or frequency is passed in this call previous values from call to define_as_pwm or pwm_start is used. :param channel: The channel to start the pwm signal on. :type channel: ``int`` :param duty_cycle: The duty cycle use on the channel. :type duty_cycle: ``int`` :param frequency: The frequency to be used on the pwm channel. :type frequency: ``int`` """ if frequency: self.set_pwm_freq(frequency) self.set_pwm(channel, 0, int(4096 * (duty_cycle/100)))
[ "def", "pwm_start", "(", "self", ",", "channel", ",", "duty_cycle", "=", "None", ",", "frequency", "=", "None", ")", ":", "if", "frequency", ":", "self", ".", "set_pwm_freq", "(", "frequency", ")", "self", ".", "set_pwm", "(", "channel", ",", "0", ",", "int", "(", "4096", "*", "(", "duty_cycle", "/", "100", ")", ")", ")" ]
Starts the pwm signal on a channel. The channel should be defined as pwm prior to this call. If no duty_cycle or frequency is passed in this call previous values from call to define_as_pwm or pwm_start is used. :param channel: The channel to start the pwm signal on. :type channel: ``int`` :param duty_cycle: The duty cycle use on the channel. :type duty_cycle: ``int`` :param frequency: The frequency to be used on the pwm channel. :type frequency: ``int``
[ "Starts", "the", "pwm", "signal", "on", "a", "channel", ".", "The", "channel", "should", "be", "defined", "as", "pwm", "prior", "to", "this", "call", ".", "If", "no", "duty_cycle", "or", "frequency", "is", "passed", "in", "this", "call", "previous", "values", "from", "call", "to", "define_as_pwm", "or", "pwm_start", "is", "used", "." ]
c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56
https://github.com/kervi/kervi-devices/blob/c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56/kervi/devices/pwm/PCA9685.py#L119-L143
239,317
kervi/kervi-devices
kervi/devices/pwm/PCA9685.py
PCA9685DeviceDriver.set_pwm_freq
def set_pwm_freq(self, freq_hz): """Set the PWM frequency to the provided value in hertz.""" prescaleval = 25000000.0 # 25MHz prescaleval /= 4096.0 # 12-bit prescaleval /= float(freq_hz) prescaleval -= 1.0 logger.debug('Setting PWM frequency to {0} Hz'.format(freq_hz)) logger.debug('Estimated pre-scale: {0}'.format(prescaleval)) prescale = int(math.floor(prescaleval + 0.5)) logger.debug('Final pre-scale: {0}'.format(prescale)) oldmode = self.i2c.read_U8(MODE1) newmode = (oldmode & 0x7F) | 0x10 # sleep self.i2c.write8(MODE1, newmode) # go to sleep self.i2c.write8(PRESCALE, prescale) self.i2c.write8(MODE1, oldmode) time.sleep(0.005) self.i2c.write8(MODE1, oldmode | 0x80)
python
def set_pwm_freq(self, freq_hz): """Set the PWM frequency to the provided value in hertz.""" prescaleval = 25000000.0 # 25MHz prescaleval /= 4096.0 # 12-bit prescaleval /= float(freq_hz) prescaleval -= 1.0 logger.debug('Setting PWM frequency to {0} Hz'.format(freq_hz)) logger.debug('Estimated pre-scale: {0}'.format(prescaleval)) prescale = int(math.floor(prescaleval + 0.5)) logger.debug('Final pre-scale: {0}'.format(prescale)) oldmode = self.i2c.read_U8(MODE1) newmode = (oldmode & 0x7F) | 0x10 # sleep self.i2c.write8(MODE1, newmode) # go to sleep self.i2c.write8(PRESCALE, prescale) self.i2c.write8(MODE1, oldmode) time.sleep(0.005) self.i2c.write8(MODE1, oldmode | 0x80)
[ "def", "set_pwm_freq", "(", "self", ",", "freq_hz", ")", ":", "prescaleval", "=", "25000000.0", "# 25MHz", "prescaleval", "/=", "4096.0", "# 12-bit", "prescaleval", "/=", "float", "(", "freq_hz", ")", "prescaleval", "-=", "1.0", "logger", ".", "debug", "(", "'Setting PWM frequency to {0} Hz'", ".", "format", "(", "freq_hz", ")", ")", "logger", ".", "debug", "(", "'Estimated pre-scale: {0}'", ".", "format", "(", "prescaleval", ")", ")", "prescale", "=", "int", "(", "math", ".", "floor", "(", "prescaleval", "+", "0.5", ")", ")", "logger", ".", "debug", "(", "'Final pre-scale: {0}'", ".", "format", "(", "prescale", ")", ")", "oldmode", "=", "self", ".", "i2c", ".", "read_U8", "(", "MODE1", ")", "newmode", "=", "(", "oldmode", "&", "0x7F", ")", "|", "0x10", "# sleep", "self", ".", "i2c", ".", "write8", "(", "MODE1", ",", "newmode", ")", "# go to sleep", "self", ".", "i2c", ".", "write8", "(", "PRESCALE", ",", "prescale", ")", "self", ".", "i2c", ".", "write8", "(", "MODE1", ",", "oldmode", ")", "time", ".", "sleep", "(", "0.005", ")", "self", ".", "i2c", ".", "write8", "(", "MODE1", ",", "oldmode", "|", "0x80", ")" ]
Set the PWM frequency to the provided value in hertz.
[ "Set", "the", "PWM", "frequency", "to", "the", "provided", "value", "in", "hertz", "." ]
c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56
https://github.com/kervi/kervi-devices/blob/c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56/kervi/devices/pwm/PCA9685.py#L151-L167
239,318
kervi/kervi-devices
kervi/devices/pwm/PCA9685.py
PCA9685DeviceDriver.set_pwm
def set_pwm(self, channel, on, off): """Sets a single PWM channel.""" self.i2c.write8(LED0_ON_L+4*channel, on & 0xFF) self.i2c.write8(LED0_ON_H+4*channel, on >> 8) self.i2c.write8(LED0_OFF_L+4*channel, off & 0xFF) self.i2c.write8(LED0_OFF_H+4*channel, off >> 8)
python
def set_pwm(self, channel, on, off): """Sets a single PWM channel.""" self.i2c.write8(LED0_ON_L+4*channel, on & 0xFF) self.i2c.write8(LED0_ON_H+4*channel, on >> 8) self.i2c.write8(LED0_OFF_L+4*channel, off & 0xFF) self.i2c.write8(LED0_OFF_H+4*channel, off >> 8)
[ "def", "set_pwm", "(", "self", ",", "channel", ",", "on", ",", "off", ")", ":", "self", ".", "i2c", ".", "write8", "(", "LED0_ON_L", "+", "4", "*", "channel", ",", "on", "&", "0xFF", ")", "self", ".", "i2c", ".", "write8", "(", "LED0_ON_H", "+", "4", "*", "channel", ",", "on", ">>", "8", ")", "self", ".", "i2c", ".", "write8", "(", "LED0_OFF_L", "+", "4", "*", "channel", ",", "off", "&", "0xFF", ")", "self", ".", "i2c", ".", "write8", "(", "LED0_OFF_H", "+", "4", "*", "channel", ",", "off", ">>", "8", ")" ]
Sets a single PWM channel.
[ "Sets", "a", "single", "PWM", "channel", "." ]
c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56
https://github.com/kervi/kervi-devices/blob/c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56/kervi/devices/pwm/PCA9685.py#L169-L174
239,319
kervi/kervi-devices
kervi/devices/pwm/PCA9685.py
PCA9685DeviceDriver.set_all_pwm
def set_all_pwm(self, on, off): """Sets all PWM channels.""" self.i2c.write8(ALL_LED_ON_L, on & 0xFF) self.i2c.write8(ALL_LED_ON_H, on >> 8) self.i2c.write8(ALL_LED_OFF_L, off & 0xFF) self.i2c.write8(ALL_LED_OFF_H, off >> 8)
python
def set_all_pwm(self, on, off): """Sets all PWM channels.""" self.i2c.write8(ALL_LED_ON_L, on & 0xFF) self.i2c.write8(ALL_LED_ON_H, on >> 8) self.i2c.write8(ALL_LED_OFF_L, off & 0xFF) self.i2c.write8(ALL_LED_OFF_H, off >> 8)
[ "def", "set_all_pwm", "(", "self", ",", "on", ",", "off", ")", ":", "self", ".", "i2c", ".", "write8", "(", "ALL_LED_ON_L", ",", "on", "&", "0xFF", ")", "self", ".", "i2c", ".", "write8", "(", "ALL_LED_ON_H", ",", "on", ">>", "8", ")", "self", ".", "i2c", ".", "write8", "(", "ALL_LED_OFF_L", ",", "off", "&", "0xFF", ")", "self", ".", "i2c", ".", "write8", "(", "ALL_LED_OFF_H", ",", "off", ">>", "8", ")" ]
Sets all PWM channels.
[ "Sets", "all", "PWM", "channels", "." ]
c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56
https://github.com/kervi/kervi-devices/blob/c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56/kervi/devices/pwm/PCA9685.py#L176-L181
239,320
host-anshu/simpleInterceptor
example/call_graph/generate.py
collect_ansible_classes
def collect_ansible_classes(): """Run playbook and collect classes of ansible that are run.""" def trace_calls(frame, event, arg): # pylint: disable=W0613 """Trace function calls to collect ansible classes. Trace functions and check if they have self as an arg. If so, get their class if the class belongs to ansible. """ if event != 'call': return try: _locals = inspect.getargvalues(frame).locals if 'self' not in _locals: return _class = _locals['self'].__class__ _class_repr = repr(_class) if 'ansible' not in _class_repr: return ANSIBLE_CLASSES[_class] = True except (AttributeError, TypeError): pass print "Gathering classes" sys.settrace(trace_calls) main()
python
def collect_ansible_classes(): """Run playbook and collect classes of ansible that are run.""" def trace_calls(frame, event, arg): # pylint: disable=W0613 """Trace function calls to collect ansible classes. Trace functions and check if they have self as an arg. If so, get their class if the class belongs to ansible. """ if event != 'call': return try: _locals = inspect.getargvalues(frame).locals if 'self' not in _locals: return _class = _locals['self'].__class__ _class_repr = repr(_class) if 'ansible' not in _class_repr: return ANSIBLE_CLASSES[_class] = True except (AttributeError, TypeError): pass print "Gathering classes" sys.settrace(trace_calls) main()
[ "def", "collect_ansible_classes", "(", ")", ":", "def", "trace_calls", "(", "frame", ",", "event", ",", "arg", ")", ":", "# pylint: disable=W0613", "\"\"\"Trace function calls to collect ansible classes.\n\n Trace functions and check if they have self as an arg. If so, get their class if the\n class belongs to ansible.\n \"\"\"", "if", "event", "!=", "'call'", ":", "return", "try", ":", "_locals", "=", "inspect", ".", "getargvalues", "(", "frame", ")", ".", "locals", "if", "'self'", "not", "in", "_locals", ":", "return", "_class", "=", "_locals", "[", "'self'", "]", ".", "__class__", "_class_repr", "=", "repr", "(", "_class", ")", "if", "'ansible'", "not", "in", "_class_repr", ":", "return", "ANSIBLE_CLASSES", "[", "_class", "]", "=", "True", "except", "(", "AttributeError", ",", "TypeError", ")", ":", "pass", "print", "\"Gathering classes\"", "sys", ".", "settrace", "(", "trace_calls", ")", "main", "(", ")" ]
Run playbook and collect classes of ansible that are run.
[ "Run", "playbook", "and", "collect", "classes", "of", "ansible", "that", "are", "run", "." ]
71238fed57c62b5f77ce32d0c9b98acad73ab6a8
https://github.com/host-anshu/simpleInterceptor/blob/71238fed57c62b5f77ce32d0c9b98acad73ab6a8/example/call_graph/generate.py#L30-L54
239,321
host-anshu/simpleInterceptor
example/call_graph/generate.py
_parse_args
def _parse_args(): """Parse args and separate generator and playbook args.""" class HelpOnErrorArgParser(argparse.ArgumentParser): """Print help message as well when an error is raised.""" def error(self, message): sys.stderr.write("Error: %s\n" % message) self.print_help() sys.exit(2) def validate(_file): """Validate if the given target argument is a valid file or a valid directory""" _file = abspath(_file) if not exists(_file): if not exists(dirname(_file)): # Argparse uses the ArgumentTypeError to give a rejection message like: # error: argument input: x does not exist raise argparse.ArgumentTypeError("{0} does not exist".format(_file)) return _file def expand_cg_args(cg_args): """Separate clubbed flags in command line args for the generator.py Allows flags to be clubbed like, -ilt example.txt. """ expanded = list() for item in cg_args: if len(item) < 3: # If at all a flag, must be single flag expanded.append(item) continue if item.startswith("-"): if not item.startswith("--"): for flag in item[1:]: expanded.append('-' + flag) continue expanded.append(item) return expanded class AssignDefaultIgnore(argparse.Action): """If argument is specified but nothing provided, use pre-defined. nargs="*" doesn't allow const and default kwarg can't be used as we might not want to ignore as well. """ def __call__(self, parser, args, values, option_string=None): if values is not None and not len(values): values = IGNORE_METHODS setattr(args, self.dest, values) try: indx = sys.argv.index('--') cg_args, sys.argv = sys.argv[1:indx], sys.argv[:1] + sys.argv[indx + 1:] except ValueError: cg_args = [] cg_args = expand_cg_args(cg_args) # allow -il type of usage parser = HelpOnErrorArgParser(description=DESCRIPTION) parser.add_argument( "-l", "--long", action='store_true', default=False, help="File reference of method in call graph is absolute, i.e. starts with ansible, " "otherwise just the basename if not __init__.py") parser.add_argument( "-t", "--target", nargs="?", type=validate, const=TARGET_FILE, default=TARGET_FILE, help="Filepath to write call graph, defaults to %(default)s") parser.add_argument( "-i", "--ignore", nargs='*', action=AssignDefaultIgnore, help="Methods to ignore while generating call graph") # TODO: Aloow classes that can be intercepted parser.usage = \ parser.format_usage()[len("usage: "):].rstrip() + " -- <ansible-playbook options>\n" cg_args = parser.parse_args(cg_args) if not len(sys.argv[1:]): parser.print_help() sys.exit(2) return cg_args
python
def _parse_args(): """Parse args and separate generator and playbook args.""" class HelpOnErrorArgParser(argparse.ArgumentParser): """Print help message as well when an error is raised.""" def error(self, message): sys.stderr.write("Error: %s\n" % message) self.print_help() sys.exit(2) def validate(_file): """Validate if the given target argument is a valid file or a valid directory""" _file = abspath(_file) if not exists(_file): if not exists(dirname(_file)): # Argparse uses the ArgumentTypeError to give a rejection message like: # error: argument input: x does not exist raise argparse.ArgumentTypeError("{0} does not exist".format(_file)) return _file def expand_cg_args(cg_args): """Separate clubbed flags in command line args for the generator.py Allows flags to be clubbed like, -ilt example.txt. """ expanded = list() for item in cg_args: if len(item) < 3: # If at all a flag, must be single flag expanded.append(item) continue if item.startswith("-"): if not item.startswith("--"): for flag in item[1:]: expanded.append('-' + flag) continue expanded.append(item) return expanded class AssignDefaultIgnore(argparse.Action): """If argument is specified but nothing provided, use pre-defined. nargs="*" doesn't allow const and default kwarg can't be used as we might not want to ignore as well. """ def __call__(self, parser, args, values, option_string=None): if values is not None and not len(values): values = IGNORE_METHODS setattr(args, self.dest, values) try: indx = sys.argv.index('--') cg_args, sys.argv = sys.argv[1:indx], sys.argv[:1] + sys.argv[indx + 1:] except ValueError: cg_args = [] cg_args = expand_cg_args(cg_args) # allow -il type of usage parser = HelpOnErrorArgParser(description=DESCRIPTION) parser.add_argument( "-l", "--long", action='store_true', default=False, help="File reference of method in call graph is absolute, i.e. starts with ansible, " "otherwise just the basename if not __init__.py") parser.add_argument( "-t", "--target", nargs="?", type=validate, const=TARGET_FILE, default=TARGET_FILE, help="Filepath to write call graph, defaults to %(default)s") parser.add_argument( "-i", "--ignore", nargs='*', action=AssignDefaultIgnore, help="Methods to ignore while generating call graph") # TODO: Aloow classes that can be intercepted parser.usage = \ parser.format_usage()[len("usage: "):].rstrip() + " -- <ansible-playbook options>\n" cg_args = parser.parse_args(cg_args) if not len(sys.argv[1:]): parser.print_help() sys.exit(2) return cg_args
[ "def", "_parse_args", "(", ")", ":", "class", "HelpOnErrorArgParser", "(", "argparse", ".", "ArgumentParser", ")", ":", "\"\"\"Print help message as well when an error is raised.\"\"\"", "def", "error", "(", "self", ",", "message", ")", ":", "sys", ".", "stderr", ".", "write", "(", "\"Error: %s\\n\"", "%", "message", ")", "self", ".", "print_help", "(", ")", "sys", ".", "exit", "(", "2", ")", "def", "validate", "(", "_file", ")", ":", "\"\"\"Validate if the given target argument is a valid file or a valid directory\"\"\"", "_file", "=", "abspath", "(", "_file", ")", "if", "not", "exists", "(", "_file", ")", ":", "if", "not", "exists", "(", "dirname", "(", "_file", ")", ")", ":", "# Argparse uses the ArgumentTypeError to give a rejection message like:", "# error: argument input: x does not exist", "raise", "argparse", ".", "ArgumentTypeError", "(", "\"{0} does not exist\"", ".", "format", "(", "_file", ")", ")", "return", "_file", "def", "expand_cg_args", "(", "cg_args", ")", ":", "\"\"\"Separate clubbed flags in command line args for the generator.py\n\n Allows flags to be clubbed like, -ilt example.txt.\n \"\"\"", "expanded", "=", "list", "(", ")", "for", "item", "in", "cg_args", ":", "if", "len", "(", "item", ")", "<", "3", ":", "# If at all a flag, must be single flag", "expanded", ".", "append", "(", "item", ")", "continue", "if", "item", ".", "startswith", "(", "\"-\"", ")", ":", "if", "not", "item", ".", "startswith", "(", "\"--\"", ")", ":", "for", "flag", "in", "item", "[", "1", ":", "]", ":", "expanded", ".", "append", "(", "'-'", "+", "flag", ")", "continue", "expanded", ".", "append", "(", "item", ")", "return", "expanded", "class", "AssignDefaultIgnore", "(", "argparse", ".", "Action", ")", ":", "\"\"\"If argument is specified but nothing provided, use pre-defined.\n\n nargs=\"*\" doesn't allow const and default kwarg can't be used as we might not want to\n ignore as well.\n \"\"\"", "def", "__call__", "(", "self", ",", "parser", ",", "args", ",", "values", ",", "option_string", "=", "None", ")", ":", "if", "values", "is", "not", "None", "and", "not", "len", "(", "values", ")", ":", "values", "=", "IGNORE_METHODS", "setattr", "(", "args", ",", "self", ".", "dest", ",", "values", ")", "try", ":", "indx", "=", "sys", ".", "argv", ".", "index", "(", "'--'", ")", "cg_args", ",", "sys", ".", "argv", "=", "sys", ".", "argv", "[", "1", ":", "indx", "]", ",", "sys", ".", "argv", "[", ":", "1", "]", "+", "sys", ".", "argv", "[", "indx", "+", "1", ":", "]", "except", "ValueError", ":", "cg_args", "=", "[", "]", "cg_args", "=", "expand_cg_args", "(", "cg_args", ")", "# allow -il type of usage", "parser", "=", "HelpOnErrorArgParser", "(", "description", "=", "DESCRIPTION", ")", "parser", ".", "add_argument", "(", "\"-l\"", ",", "\"--long\"", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "\"File reference of method in call graph is absolute, i.e. starts with ansible, \"", "\"otherwise just the basename if not __init__.py\"", ")", "parser", ".", "add_argument", "(", "\"-t\"", ",", "\"--target\"", ",", "nargs", "=", "\"?\"", ",", "type", "=", "validate", ",", "const", "=", "TARGET_FILE", ",", "default", "=", "TARGET_FILE", ",", "help", "=", "\"Filepath to write call graph, defaults to %(default)s\"", ")", "parser", ".", "add_argument", "(", "\"-i\"", ",", "\"--ignore\"", ",", "nargs", "=", "'*'", ",", "action", "=", "AssignDefaultIgnore", ",", "help", "=", "\"Methods to ignore while generating call graph\"", ")", "# TODO: Aloow classes that can be intercepted", "parser", ".", "usage", "=", "parser", ".", "format_usage", "(", ")", "[", "len", "(", "\"usage: \"", ")", ":", "]", ".", "rstrip", "(", ")", "+", "\" -- <ansible-playbook options>\\n\"", "cg_args", "=", "parser", ".", "parse_args", "(", "cg_args", ")", "if", "not", "len", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", ":", "parser", ".", "print_help", "(", ")", "sys", ".", "exit", "(", "2", ")", "return", "cg_args" ]
Parse args and separate generator and playbook args.
[ "Parse", "args", "and", "separate", "generator", "and", "playbook", "args", "." ]
71238fed57c62b5f77ce32d0c9b98acad73ab6a8
https://github.com/host-anshu/simpleInterceptor/blob/71238fed57c62b5f77ce32d0c9b98acad73ab6a8/example/call_graph/generate.py#L68-L144
239,322
wickman/compactor
compactor/httpd.py
WireProtocolMessageHandler.detect_process
def detect_process(cls, headers): """Returns tuple of process, legacy or None, None if not process originating.""" try: if 'Libprocess-From' in headers: return PID.from_string(headers['Libprocess-From']), False elif 'User-Agent' in headers and headers['User-Agent'].startswith('libprocess/'): return PID.from_string(headers['User-Agent'][len('libprocess/'):]), True except ValueError as e: log.error('Failed to detect process: %r' % e) pass return None, None
python
def detect_process(cls, headers): """Returns tuple of process, legacy or None, None if not process originating.""" try: if 'Libprocess-From' in headers: return PID.from_string(headers['Libprocess-From']), False elif 'User-Agent' in headers and headers['User-Agent'].startswith('libprocess/'): return PID.from_string(headers['User-Agent'][len('libprocess/'):]), True except ValueError as e: log.error('Failed to detect process: %r' % e) pass return None, None
[ "def", "detect_process", "(", "cls", ",", "headers", ")", ":", "try", ":", "if", "'Libprocess-From'", "in", "headers", ":", "return", "PID", ".", "from_string", "(", "headers", "[", "'Libprocess-From'", "]", ")", ",", "False", "elif", "'User-Agent'", "in", "headers", "and", "headers", "[", "'User-Agent'", "]", ".", "startswith", "(", "'libprocess/'", ")", ":", "return", "PID", ".", "from_string", "(", "headers", "[", "'User-Agent'", "]", "[", "len", "(", "'libprocess/'", ")", ":", "]", ")", ",", "True", "except", "ValueError", "as", "e", ":", "log", ".", "error", "(", "'Failed to detect process: %r'", "%", "e", ")", "pass", "return", "None", ",", "None" ]
Returns tuple of process, legacy or None, None if not process originating.
[ "Returns", "tuple", "of", "process", "legacy", "or", "None", "None", "if", "not", "process", "originating", "." ]
52714be3d84aa595a212feccb4d92ec250cede2a
https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/httpd.py#L27-L39
239,323
wickman/compactor
compactor/httpd.py
HTTPD.mount_process
def mount_process(self, process): """ Mount a Process onto the http server to receive message callbacks. """ for route_path in process.route_paths: route = '/%s%s' % (process.pid.id, route_path) log.info('Mounting route %s' % route) self.app.add_handlers('.*$', [( re.escape(route), RoutedRequestHandler, dict(process=process, path=route_path) )]) for message_name in process.message_names: route = '/%s/%s' % (process.pid.id, message_name) log.info('Mounting message handler %s' % route) self.app.add_handlers('.*$', [( re.escape(route), WireProtocolMessageHandler, dict(process=process, name=message_name) )])
python
def mount_process(self, process): """ Mount a Process onto the http server to receive message callbacks. """ for route_path in process.route_paths: route = '/%s%s' % (process.pid.id, route_path) log.info('Mounting route %s' % route) self.app.add_handlers('.*$', [( re.escape(route), RoutedRequestHandler, dict(process=process, path=route_path) )]) for message_name in process.message_names: route = '/%s/%s' % (process.pid.id, message_name) log.info('Mounting message handler %s' % route) self.app.add_handlers('.*$', [( re.escape(route), WireProtocolMessageHandler, dict(process=process, name=message_name) )])
[ "def", "mount_process", "(", "self", ",", "process", ")", ":", "for", "route_path", "in", "process", ".", "route_paths", ":", "route", "=", "'/%s%s'", "%", "(", "process", ".", "pid", ".", "id", ",", "route_path", ")", "log", ".", "info", "(", "'Mounting route %s'", "%", "route", ")", "self", ".", "app", ".", "add_handlers", "(", "'.*$'", ",", "[", "(", "re", ".", "escape", "(", "route", ")", ",", "RoutedRequestHandler", ",", "dict", "(", "process", "=", "process", ",", "path", "=", "route_path", ")", ")", "]", ")", "for", "message_name", "in", "process", ".", "message_names", ":", "route", "=", "'/%s/%s'", "%", "(", "process", ".", "pid", ".", "id", ",", "message_name", ")", "log", ".", "info", "(", "'Mounting message handler %s'", "%", "route", ")", "self", ".", "app", ".", "add_handlers", "(", "'.*$'", ",", "[", "(", "re", ".", "escape", "(", "route", ")", ",", "WireProtocolMessageHandler", ",", "dict", "(", "process", "=", "process", ",", "name", "=", "message_name", ")", ")", "]", ")" ]
Mount a Process onto the http server to receive message callbacks.
[ "Mount", "a", "Process", "onto", "the", "http", "server", "to", "receive", "message", "callbacks", "." ]
52714be3d84aa595a212feccb4d92ec250cede2a
https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/httpd.py#L118-L139
239,324
wickman/compactor
compactor/httpd.py
HTTPD.unmount_process
def unmount_process(self, process): """ Unmount a process from the http server to stop receiving message callbacks. """ # There is no remove_handlers, but .handlers is public so why not. server.handlers is a list of # 2-tuples of the form (host_pattern, [list of RequestHandler]) objects. We filter out all # handlers matching our process from the RequestHandler list for each host pattern. def nonmatching(handler): return 'process' not in handler.kwargs or handler.kwargs['process'] != process def filter_handlers(handlers): host_pattern, handlers = handlers return (host_pattern, list(filter(nonmatching, handlers))) self.app.handlers = [filter_handlers(handlers) for handlers in self.app.handlers]
python
def unmount_process(self, process): """ Unmount a process from the http server to stop receiving message callbacks. """ # There is no remove_handlers, but .handlers is public so why not. server.handlers is a list of # 2-tuples of the form (host_pattern, [list of RequestHandler]) objects. We filter out all # handlers matching our process from the RequestHandler list for each host pattern. def nonmatching(handler): return 'process' not in handler.kwargs or handler.kwargs['process'] != process def filter_handlers(handlers): host_pattern, handlers = handlers return (host_pattern, list(filter(nonmatching, handlers))) self.app.handlers = [filter_handlers(handlers) for handlers in self.app.handlers]
[ "def", "unmount_process", "(", "self", ",", "process", ")", ":", "# There is no remove_handlers, but .handlers is public so why not. server.handlers is a list of", "# 2-tuples of the form (host_pattern, [list of RequestHandler]) objects. We filter out all", "# handlers matching our process from the RequestHandler list for each host pattern.", "def", "nonmatching", "(", "handler", ")", ":", "return", "'process'", "not", "in", "handler", ".", "kwargs", "or", "handler", ".", "kwargs", "[", "'process'", "]", "!=", "process", "def", "filter_handlers", "(", "handlers", ")", ":", "host_pattern", ",", "handlers", "=", "handlers", "return", "(", "host_pattern", ",", "list", "(", "filter", "(", "nonmatching", ",", "handlers", ")", ")", ")", "self", ".", "app", ".", "handlers", "=", "[", "filter_handlers", "(", "handlers", ")", "for", "handlers", "in", "self", ".", "app", ".", "handlers", "]" ]
Unmount a process from the http server to stop receiving message callbacks.
[ "Unmount", "a", "process", "from", "the", "http", "server", "to", "stop", "receiving", "message", "callbacks", "." ]
52714be3d84aa595a212feccb4d92ec250cede2a
https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/httpd.py#L141-L157
239,325
staffanm/layeredconfig
layeredconfig/configsource.py
ConfigSource.typevalue
def typevalue(self, key, value): """Given a parameter identified by ``key`` and an untyped string, convert that string to the type that our version of key has. """ def listconvert(value): # this function might be called with both string # represenations of entire lists and simple (unquoted) # strings. String representations come in two flavours, # the (legacy/deprecated) python literal (eg "['foo', # 'bar']") and the simple (eg "foo, bar") The # ast.literal_eval handles the first case, and if the # value can't be parsed as a python expression, the second # way is attempted. If both fail, it is returned verbatim # (not wrapped in a list, for reasons) try: return ast.literal_eval(value) except (SyntaxError, ValueError): if "," in value: return [x.strip() for x in value.split(",")] else: return value # self.get(key) should never fail default = self.get(key) # if type(default) == type: if inspect.isclass(default): # print("Using class for %s" % key) t = default else: # print("Using instance for %s" % key) t = type(default) if t == bool: t = LayeredConfig.boolconvert elif t == list: t = listconvert elif t == date: t = LayeredConfig.dateconvert elif t == datetime: t = LayeredConfig.datetimeconvert # print("Converting %r to %r" % (value,t(value))) return t(value)
python
def typevalue(self, key, value): """Given a parameter identified by ``key`` and an untyped string, convert that string to the type that our version of key has. """ def listconvert(value): # this function might be called with both string # represenations of entire lists and simple (unquoted) # strings. String representations come in two flavours, # the (legacy/deprecated) python literal (eg "['foo', # 'bar']") and the simple (eg "foo, bar") The # ast.literal_eval handles the first case, and if the # value can't be parsed as a python expression, the second # way is attempted. If both fail, it is returned verbatim # (not wrapped in a list, for reasons) try: return ast.literal_eval(value) except (SyntaxError, ValueError): if "," in value: return [x.strip() for x in value.split(",")] else: return value # self.get(key) should never fail default = self.get(key) # if type(default) == type: if inspect.isclass(default): # print("Using class for %s" % key) t = default else: # print("Using instance for %s" % key) t = type(default) if t == bool: t = LayeredConfig.boolconvert elif t == list: t = listconvert elif t == date: t = LayeredConfig.dateconvert elif t == datetime: t = LayeredConfig.datetimeconvert # print("Converting %r to %r" % (value,t(value))) return t(value)
[ "def", "typevalue", "(", "self", ",", "key", ",", "value", ")", ":", "def", "listconvert", "(", "value", ")", ":", "# this function might be called with both string", "# represenations of entire lists and simple (unquoted)", "# strings. String representations come in two flavours,", "# the (legacy/deprecated) python literal (eg \"['foo',", "# 'bar']\") and the simple (eg \"foo, bar\") The", "# ast.literal_eval handles the first case, and if the", "# value can't be parsed as a python expression, the second", "# way is attempted. If both fail, it is returned verbatim", "# (not wrapped in a list, for reasons)", "try", ":", "return", "ast", ".", "literal_eval", "(", "value", ")", "except", "(", "SyntaxError", ",", "ValueError", ")", ":", "if", "\",\"", "in", "value", ":", "return", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "value", ".", "split", "(", "\",\"", ")", "]", "else", ":", "return", "value", "# self.get(key) should never fail", "default", "=", "self", ".", "get", "(", "key", ")", "# if type(default) == type:", "if", "inspect", ".", "isclass", "(", "default", ")", ":", "# print(\"Using class for %s\" % key)", "t", "=", "default", "else", ":", "# print(\"Using instance for %s\" % key)", "t", "=", "type", "(", "default", ")", "if", "t", "==", "bool", ":", "t", "=", "LayeredConfig", ".", "boolconvert", "elif", "t", "==", "list", ":", "t", "=", "listconvert", "elif", "t", "==", "date", ":", "t", "=", "LayeredConfig", ".", "dateconvert", "elif", "t", "==", "datetime", ":", "t", "=", "LayeredConfig", ".", "datetimeconvert", "# print(\"Converting %r to %r\" % (value,t(value)))", "return", "t", "(", "value", ")" ]
Given a parameter identified by ``key`` and an untyped string, convert that string to the type that our version of key has.
[ "Given", "a", "parameter", "identified", "by", "key", "and", "an", "untyped", "string", "convert", "that", "string", "to", "the", "type", "that", "our", "version", "of", "key", "has", "." ]
f3dad66729854f5c34910c7533f88d39b223a977
https://github.com/staffanm/layeredconfig/blob/f3dad66729854f5c34910c7533f88d39b223a977/layeredconfig/configsource.py#L175-L218
239,326
toumorokoshi/jenks
jenks/utils.py
generate_valid_keys
def generate_valid_keys(): """ create a list of valid keys """ valid_keys = [] for minimum, maximum in RANGES: for i in range(ord(minimum), ord(maximum) + 1): valid_keys.append(chr(i)) return valid_keys
python
def generate_valid_keys(): """ create a list of valid keys """ valid_keys = [] for minimum, maximum in RANGES: for i in range(ord(minimum), ord(maximum) + 1): valid_keys.append(chr(i)) return valid_keys
[ "def", "generate_valid_keys", "(", ")", ":", "valid_keys", "=", "[", "]", "for", "minimum", ",", "maximum", "in", "RANGES", ":", "for", "i", "in", "range", "(", "ord", "(", "minimum", ")", ",", "ord", "(", "maximum", ")", "+", "1", ")", ":", "valid_keys", ".", "append", "(", "chr", "(", "i", ")", ")", "return", "valid_keys" ]
create a list of valid keys
[ "create", "a", "list", "of", "valid", "keys" ]
d3333a7b86ba290b7185aa5b8da75e76a28124f5
https://github.com/toumorokoshi/jenks/blob/d3333a7b86ba290b7185aa5b8da75e76a28124f5/jenks/utils.py#L27-L33
239,327
toumorokoshi/jenks
jenks/utils.py
get_configuration_file
def get_configuration_file(): """ return jenks configuration file """ path = os.path.abspath(os.curdir) while path != os.sep: config_path = os.path.join(path, CONFIG_FILE_NAME) if os.path.exists(config_path): return config_path path = os.path.dirname(path) return None
python
def get_configuration_file(): """ return jenks configuration file """ path = os.path.abspath(os.curdir) while path != os.sep: config_path = os.path.join(path, CONFIG_FILE_NAME) if os.path.exists(config_path): return config_path path = os.path.dirname(path) return None
[ "def", "get_configuration_file", "(", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "curdir", ")", "while", "path", "!=", "os", ".", "sep", ":", "config_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "CONFIG_FILE_NAME", ")", "if", "os", ".", "path", ".", "exists", "(", "config_path", ")", ":", "return", "config_path", "path", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "return", "None" ]
return jenks configuration file
[ "return", "jenks", "configuration", "file" ]
d3333a7b86ba290b7185aa5b8da75e76a28124f5
https://github.com/toumorokoshi/jenks/blob/d3333a7b86ba290b7185aa5b8da75e76a28124f5/jenks/utils.py#L36-L44
239,328
toumorokoshi/jenks
jenks/utils.py
generate_write_yaml_to_file
def generate_write_yaml_to_file(file_name): """ generate a method to write the configuration in yaml to the method desired """ def write_yaml(config): with open(file_name, 'w+') as fh: fh.write(yaml.dump(config)) return write_yaml
python
def generate_write_yaml_to_file(file_name): """ generate a method to write the configuration in yaml to the method desired """ def write_yaml(config): with open(file_name, 'w+') as fh: fh.write(yaml.dump(config)) return write_yaml
[ "def", "generate_write_yaml_to_file", "(", "file_name", ")", ":", "def", "write_yaml", "(", "config", ")", ":", "with", "open", "(", "file_name", ",", "'w+'", ")", "as", "fh", ":", "fh", ".", "write", "(", "yaml", ".", "dump", "(", "config", ")", ")", "return", "write_yaml" ]
generate a method to write the configuration in yaml to the method desired
[ "generate", "a", "method", "to", "write", "the", "configuration", "in", "yaml", "to", "the", "method", "desired" ]
d3333a7b86ba290b7185aa5b8da75e76a28124f5
https://github.com/toumorokoshi/jenks/blob/d3333a7b86ba290b7185aa5b8da75e76a28124f5/jenks/utils.py#L47-L52
239,329
emilydolson/avida-spatial-tools
avidaspatial/parse_files.py
load_grid_data
def load_grid_data(file_list, data_type="binary", sort=True, delim=" "): """ Loads data from one or multiple grid_task files. Arguments: file_list - either a string or a list of strings indicating files to load data from. Files are assumed to be in grid_task.dat format (space delimited values, one per cell). data_type - a string representing what type of data is in the file. Either "binary", "int", "float", or "string". sort - If you're making a movie, you want the files to be in chronological order. By default, they will be sorted. If for some reason you don't want them in chronological order, set sort to False. Returns: A three-dimensional array. The first dimension is columns, the second is rows. At each row,column index in the array is another list which holds the values that each of the requested files has at that location in the grid. If you want this list collapsed to a single representative number, you should use agg_niche_grid. """ # If there's only one file, we pretend it's a list if not type(file_list) is list: file_list = [file_list] elif sort: # put file_list in chronological order file_list.sort(key=lambda f: int(re.sub("[^0-9]", "", f))) world_size = get_world_dimensions(file_list[0], delim) # Initialize empty data array data = initialize_grid(world_size, []) # Loop through file list, reading in data for f in file_list: infile = open(f) lines = infile.readlines() for i in range(world_size[1]): lines[i] = lines[i].strip().split(delim) for j in range(world_size[0]): if data_type == "binary": val = bin(int(lines[i][j])) elif data_type == "float": val = float(lines[i][j]) elif data_type == "int": val = int(lines[i][j]) elif data_type == "string": val = str(lines[i][j]) else: print("Unsupported data_type passed to load_grid") return data[i][j].append(val) infile.close() return data
python
def load_grid_data(file_list, data_type="binary", sort=True, delim=" "): """ Loads data from one or multiple grid_task files. Arguments: file_list - either a string or a list of strings indicating files to load data from. Files are assumed to be in grid_task.dat format (space delimited values, one per cell). data_type - a string representing what type of data is in the file. Either "binary", "int", "float", or "string". sort - If you're making a movie, you want the files to be in chronological order. By default, they will be sorted. If for some reason you don't want them in chronological order, set sort to False. Returns: A three-dimensional array. The first dimension is columns, the second is rows. At each row,column index in the array is another list which holds the values that each of the requested files has at that location in the grid. If you want this list collapsed to a single representative number, you should use agg_niche_grid. """ # If there's only one file, we pretend it's a list if not type(file_list) is list: file_list = [file_list] elif sort: # put file_list in chronological order file_list.sort(key=lambda f: int(re.sub("[^0-9]", "", f))) world_size = get_world_dimensions(file_list[0], delim) # Initialize empty data array data = initialize_grid(world_size, []) # Loop through file list, reading in data for f in file_list: infile = open(f) lines = infile.readlines() for i in range(world_size[1]): lines[i] = lines[i].strip().split(delim) for j in range(world_size[0]): if data_type == "binary": val = bin(int(lines[i][j])) elif data_type == "float": val = float(lines[i][j]) elif data_type == "int": val = int(lines[i][j]) elif data_type == "string": val = str(lines[i][j]) else: print("Unsupported data_type passed to load_grid") return data[i][j].append(val) infile.close() return data
[ "def", "load_grid_data", "(", "file_list", ",", "data_type", "=", "\"binary\"", ",", "sort", "=", "True", ",", "delim", "=", "\" \"", ")", ":", "# If there's only one file, we pretend it's a list", "if", "not", "type", "(", "file_list", ")", "is", "list", ":", "file_list", "=", "[", "file_list", "]", "elif", "sort", ":", "# put file_list in chronological order", "file_list", ".", "sort", "(", "key", "=", "lambda", "f", ":", "int", "(", "re", ".", "sub", "(", "\"[^0-9]\"", ",", "\"\"", ",", "f", ")", ")", ")", "world_size", "=", "get_world_dimensions", "(", "file_list", "[", "0", "]", ",", "delim", ")", "# Initialize empty data array", "data", "=", "initialize_grid", "(", "world_size", ",", "[", "]", ")", "# Loop through file list, reading in data", "for", "f", "in", "file_list", ":", "infile", "=", "open", "(", "f", ")", "lines", "=", "infile", ".", "readlines", "(", ")", "for", "i", "in", "range", "(", "world_size", "[", "1", "]", ")", ":", "lines", "[", "i", "]", "=", "lines", "[", "i", "]", ".", "strip", "(", ")", ".", "split", "(", "delim", ")", "for", "j", "in", "range", "(", "world_size", "[", "0", "]", ")", ":", "if", "data_type", "==", "\"binary\"", ":", "val", "=", "bin", "(", "int", "(", "lines", "[", "i", "]", "[", "j", "]", ")", ")", "elif", "data_type", "==", "\"float\"", ":", "val", "=", "float", "(", "lines", "[", "i", "]", "[", "j", "]", ")", "elif", "data_type", "==", "\"int\"", ":", "val", "=", "int", "(", "lines", "[", "i", "]", "[", "j", "]", ")", "elif", "data_type", "==", "\"string\"", ":", "val", "=", "str", "(", "lines", "[", "i", "]", "[", "j", "]", ")", "else", ":", "print", "(", "\"Unsupported data_type passed to load_grid\"", ")", "return", "data", "[", "i", "]", "[", "j", "]", ".", "append", "(", "val", ")", "infile", ".", "close", "(", ")", "return", "data" ]
Loads data from one or multiple grid_task files. Arguments: file_list - either a string or a list of strings indicating files to load data from. Files are assumed to be in grid_task.dat format (space delimited values, one per cell). data_type - a string representing what type of data is in the file. Either "binary", "int", "float", or "string". sort - If you're making a movie, you want the files to be in chronological order. By default, they will be sorted. If for some reason you don't want them in chronological order, set sort to False. Returns: A three-dimensional array. The first dimension is columns, the second is rows. At each row,column index in the array is another list which holds the values that each of the requested files has at that location in the grid. If you want this list collapsed to a single representative number, you should use agg_niche_grid.
[ "Loads", "data", "from", "one", "or", "multiple", "grid_task", "files", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/parse_files.py#L11-L70
239,330
emilydolson/avida-spatial-tools
avidaspatial/parse_files.py
make_niche_grid
def make_niche_grid(res_dict, world_size=(60, 60)): """ Converts dictionary specifying where resources are to nested lists specifying what sets of resources are where. res_dict - a dictionary in which keys are resources in the environment and values are list of tuples representing the cells they're in. world_size - a tuple indicating the dimensions of the world. Default = 60x60, because that's the default Avida world size Returns a list of lists of sets indicating the set of resources available at each x,y location in the Avida grid. """ # Initialize array to represent world world = initialize_grid(world_size, set()) # Fill in data on niches present in each cell of the world for res in res_dict: for cell in res_dict[res]: world[cell[1]][cell[0]].add(res) return world
python
def make_niche_grid(res_dict, world_size=(60, 60)): """ Converts dictionary specifying where resources are to nested lists specifying what sets of resources are where. res_dict - a dictionary in which keys are resources in the environment and values are list of tuples representing the cells they're in. world_size - a tuple indicating the dimensions of the world. Default = 60x60, because that's the default Avida world size Returns a list of lists of sets indicating the set of resources available at each x,y location in the Avida grid. """ # Initialize array to represent world world = initialize_grid(world_size, set()) # Fill in data on niches present in each cell of the world for res in res_dict: for cell in res_dict[res]: world[cell[1]][cell[0]].add(res) return world
[ "def", "make_niche_grid", "(", "res_dict", ",", "world_size", "=", "(", "60", ",", "60", ")", ")", ":", "# Initialize array to represent world", "world", "=", "initialize_grid", "(", "world_size", ",", "set", "(", ")", ")", "# Fill in data on niches present in each cell of the world", "for", "res", "in", "res_dict", ":", "for", "cell", "in", "res_dict", "[", "res", "]", ":", "world", "[", "cell", "[", "1", "]", "]", "[", "cell", "[", "0", "]", "]", ".", "add", "(", "res", ")", "return", "world" ]
Converts dictionary specifying where resources are to nested lists specifying what sets of resources are where. res_dict - a dictionary in which keys are resources in the environment and values are list of tuples representing the cells they're in. world_size - a tuple indicating the dimensions of the world. Default = 60x60, because that's the default Avida world size Returns a list of lists of sets indicating the set of resources available at each x,y location in the Avida grid.
[ "Converts", "dictionary", "specifying", "where", "resources", "are", "to", "nested", "lists", "specifying", "what", "sets", "of", "resources", "are", "where", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/parse_files.py#L73-L96
239,331
emilydolson/avida-spatial-tools
avidaspatial/parse_files.py
parse_environment_file_list
def parse_environment_file_list(names, world_size=(60, 60)): """ Extract information about spatial resources from all environment files in a list. Arguments: names - a list of strings representing the paths to the environment files. world_size - a tuple representing the x and y coordinates of the world. (default: 60x60) Returns a dictionary in which the keys are filenames and the values are list of lists of sets indicating the set of resources available at each x,y location in the Avida grid for that environment. """ # Convert single file to list if necessary try: names[0] = names[0] except: names = [names] envs = [] for name in names: envs.append(parse_environment_file(name, world_size)) return envs
python
def parse_environment_file_list(names, world_size=(60, 60)): """ Extract information about spatial resources from all environment files in a list. Arguments: names - a list of strings representing the paths to the environment files. world_size - a tuple representing the x and y coordinates of the world. (default: 60x60) Returns a dictionary in which the keys are filenames and the values are list of lists of sets indicating the set of resources available at each x,y location in the Avida grid for that environment. """ # Convert single file to list if necessary try: names[0] = names[0] except: names = [names] envs = [] for name in names: envs.append(parse_environment_file(name, world_size)) return envs
[ "def", "parse_environment_file_list", "(", "names", ",", "world_size", "=", "(", "60", ",", "60", ")", ")", ":", "# Convert single file to list if necessary", "try", ":", "names", "[", "0", "]", "=", "names", "[", "0", "]", "except", ":", "names", "=", "[", "names", "]", "envs", "=", "[", "]", "for", "name", "in", "names", ":", "envs", ".", "append", "(", "parse_environment_file", "(", "name", ",", "world_size", ")", ")", "return", "envs" ]
Extract information about spatial resources from all environment files in a list. Arguments: names - a list of strings representing the paths to the environment files. world_size - a tuple representing the x and y coordinates of the world. (default: 60x60) Returns a dictionary in which the keys are filenames and the values are list of lists of sets indicating the set of resources available at each x,y location in the Avida grid for that environment.
[ "Extract", "information", "about", "spatial", "resources", "from", "all", "environment", "files", "in", "a", "list", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/parse_files.py#L99-L124
239,332
emilydolson/avida-spatial-tools
avidaspatial/parse_files.py
parse_environment_file
def parse_environment_file(filename, world_size=(60, 60)): """ Extract information about spatial resources from an environment file. Arguments: filename - a string representing the path to the environment file. world_size - a tuple representing the x and y coordinates of the world. (default: 60x60) Returns a list of lists of sets indicating the set of resources available at each x,y location in the Avida grid. """ infile = open(filename) lines = infile.readlines() infile.close() tasks = [] # Find all spatial resources and record which cells they're in res_order = [] res_dict = {} for line in lines: if line.startswith("GRADIENT_RESOURCE"): name, cells = parse_gradient(line, world_size) elif line.startswith("CELL"): name, cells = parse_cell(line, world_size) elif line.startswith("REACTION"): task = parse_reaction(line) if task not in tasks: tasks.append(task) else: continue dict_increment(res_dict, name, cells) if name not in res_order: res_order.append(name) # Create a map of niches across the environment and return it grid = make_niche_grid(res_dict, world_size) return EnvironmentFile(grid, res_order, world_size, filename, tasks)
python
def parse_environment_file(filename, world_size=(60, 60)): """ Extract information about spatial resources from an environment file. Arguments: filename - a string representing the path to the environment file. world_size - a tuple representing the x and y coordinates of the world. (default: 60x60) Returns a list of lists of sets indicating the set of resources available at each x,y location in the Avida grid. """ infile = open(filename) lines = infile.readlines() infile.close() tasks = [] # Find all spatial resources and record which cells they're in res_order = [] res_dict = {} for line in lines: if line.startswith("GRADIENT_RESOURCE"): name, cells = parse_gradient(line, world_size) elif line.startswith("CELL"): name, cells = parse_cell(line, world_size) elif line.startswith("REACTION"): task = parse_reaction(line) if task not in tasks: tasks.append(task) else: continue dict_increment(res_dict, name, cells) if name not in res_order: res_order.append(name) # Create a map of niches across the environment and return it grid = make_niche_grid(res_dict, world_size) return EnvironmentFile(grid, res_order, world_size, filename, tasks)
[ "def", "parse_environment_file", "(", "filename", ",", "world_size", "=", "(", "60", ",", "60", ")", ")", ":", "infile", "=", "open", "(", "filename", ")", "lines", "=", "infile", ".", "readlines", "(", ")", "infile", ".", "close", "(", ")", "tasks", "=", "[", "]", "# Find all spatial resources and record which cells they're in", "res_order", "=", "[", "]", "res_dict", "=", "{", "}", "for", "line", "in", "lines", ":", "if", "line", ".", "startswith", "(", "\"GRADIENT_RESOURCE\"", ")", ":", "name", ",", "cells", "=", "parse_gradient", "(", "line", ",", "world_size", ")", "elif", "line", ".", "startswith", "(", "\"CELL\"", ")", ":", "name", ",", "cells", "=", "parse_cell", "(", "line", ",", "world_size", ")", "elif", "line", ".", "startswith", "(", "\"REACTION\"", ")", ":", "task", "=", "parse_reaction", "(", "line", ")", "if", "task", "not", "in", "tasks", ":", "tasks", ".", "append", "(", "task", ")", "else", ":", "continue", "dict_increment", "(", "res_dict", ",", "name", ",", "cells", ")", "if", "name", "not", "in", "res_order", ":", "res_order", ".", "append", "(", "name", ")", "# Create a map of niches across the environment and return it", "grid", "=", "make_niche_grid", "(", "res_dict", ",", "world_size", ")", "return", "EnvironmentFile", "(", "grid", ",", "res_order", ",", "world_size", ",", "filename", ",", "tasks", ")" ]
Extract information about spatial resources from an environment file. Arguments: filename - a string representing the path to the environment file. world_size - a tuple representing the x and y coordinates of the world. (default: 60x60) Returns a list of lists of sets indicating the set of resources available at each x,y location in the Avida grid.
[ "Extract", "information", "about", "spatial", "resources", "from", "an", "environment", "file", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/parse_files.py#L143-L184
239,333
CenterForOpenScience/sharepa
sharepa/experimental_analysis_functions.py
add_category_labels
def add_category_labels(level_name, cat_name, dataframe_needing_cat): '''A function that adds a category name column to a pandas dataframe :param level_name: an aggregation from elasticsearch results with nesting :type level_name: elasticsearch response.aggregation object :param cat_name: an aggregation from elasticsearch results with nesting :type cat_name: elasticsearch response.aggregation object :param dataframe_needing_cat: a pandas dataframe to append category name too :type dataframe_needing_cat: elasticsearch response.aggregation object :returns: pandas data frame like example above, with nested data ''' cat_name_dataframe = pd.DataFrame( [level_name for i in range(0, dataframe_needing_cat.shape[0])]) # create a cat name column cat_name_dataframe.columns = [cat_name] # name the column something meaningful return pd.concat([cat_name_dataframe, dataframe_needing_cat], axis=1)
python
def add_category_labels(level_name, cat_name, dataframe_needing_cat): '''A function that adds a category name column to a pandas dataframe :param level_name: an aggregation from elasticsearch results with nesting :type level_name: elasticsearch response.aggregation object :param cat_name: an aggregation from elasticsearch results with nesting :type cat_name: elasticsearch response.aggregation object :param dataframe_needing_cat: a pandas dataframe to append category name too :type dataframe_needing_cat: elasticsearch response.aggregation object :returns: pandas data frame like example above, with nested data ''' cat_name_dataframe = pd.DataFrame( [level_name for i in range(0, dataframe_needing_cat.shape[0])]) # create a cat name column cat_name_dataframe.columns = [cat_name] # name the column something meaningful return pd.concat([cat_name_dataframe, dataframe_needing_cat], axis=1)
[ "def", "add_category_labels", "(", "level_name", ",", "cat_name", ",", "dataframe_needing_cat", ")", ":", "cat_name_dataframe", "=", "pd", ".", "DataFrame", "(", "[", "level_name", "for", "i", "in", "range", "(", "0", ",", "dataframe_needing_cat", ".", "shape", "[", "0", "]", ")", "]", ")", "# create a cat name column", "cat_name_dataframe", ".", "columns", "=", "[", "cat_name", "]", "# name the column something meaningful", "return", "pd", ".", "concat", "(", "[", "cat_name_dataframe", ",", "dataframe_needing_cat", "]", ",", "axis", "=", "1", ")" ]
A function that adds a category name column to a pandas dataframe :param level_name: an aggregation from elasticsearch results with nesting :type level_name: elasticsearch response.aggregation object :param cat_name: an aggregation from elasticsearch results with nesting :type cat_name: elasticsearch response.aggregation object :param dataframe_needing_cat: a pandas dataframe to append category name too :type dataframe_needing_cat: elasticsearch response.aggregation object :returns: pandas data frame like example above, with nested data
[ "A", "function", "that", "adds", "a", "category", "name", "column", "to", "a", "pandas", "dataframe" ]
5ea69b160080f0b9c655012f17fabaa1bcc02ae0
https://github.com/CenterForOpenScience/sharepa/blob/5ea69b160080f0b9c655012f17fabaa1bcc02ae0/sharepa/experimental_analysis_functions.py#L81-L95
239,334
siemens/django-dingos
dingos/core/datastructures.py
ExtendedSortedDict.chained_set
def chained_set(self, value, command='set', *keys): """ chained_set takes the value to enter into the dictionary, a command of what to do with the value, and a sequence of keys. Examples: d = {} d.chained_set(1,'append','level 1','level 2') -> d['level 1']['level 2'] = [1] d.chained_set(2,'append','level 1','level 2') -> d['level 1']['level 2'] = [1,2] """ new_object = self.__class__() existing = self for i in range(0, len(keys) - 1): if keys[i] in existing: existing = existing[keys[i]] else: existing[keys[i]] = new_object existing = existing[keys[i]] if command == 'set': existing[keys[len(keys) - 1]] = value elif command == 'append': if keys[len(keys) - 1] in existing: existing[keys[len(keys) - 1]].append(value) else: existing[keys[len(keys) - 1]] = [value] elif command == 'set_or_append': if keys[len(keys) - 1] in existing: if type(keys[len(keys) - 1]) == type([]): existing[keys[len(keys) - 1]].append(value) else: existing[keys[len(keys) - 1]] = [existing[keys[len(keys) - 1]], value] else: existing[keys[len(keys) - 1]] = value elif command == 'insert': if keys[len(keys) - 1] in existing: if not value in existing[keys[len(keys) - 1]]: existing[keys[len(keys) - 1]].append(value) else: existing[keys[len(keys) - 1]] = [value]
python
def chained_set(self, value, command='set', *keys): """ chained_set takes the value to enter into the dictionary, a command of what to do with the value, and a sequence of keys. Examples: d = {} d.chained_set(1,'append','level 1','level 2') -> d['level 1']['level 2'] = [1] d.chained_set(2,'append','level 1','level 2') -> d['level 1']['level 2'] = [1,2] """ new_object = self.__class__() existing = self for i in range(0, len(keys) - 1): if keys[i] in existing: existing = existing[keys[i]] else: existing[keys[i]] = new_object existing = existing[keys[i]] if command == 'set': existing[keys[len(keys) - 1]] = value elif command == 'append': if keys[len(keys) - 1] in existing: existing[keys[len(keys) - 1]].append(value) else: existing[keys[len(keys) - 1]] = [value] elif command == 'set_or_append': if keys[len(keys) - 1] in existing: if type(keys[len(keys) - 1]) == type([]): existing[keys[len(keys) - 1]].append(value) else: existing[keys[len(keys) - 1]] = [existing[keys[len(keys) - 1]], value] else: existing[keys[len(keys) - 1]] = value elif command == 'insert': if keys[len(keys) - 1] in existing: if not value in existing[keys[len(keys) - 1]]: existing[keys[len(keys) - 1]].append(value) else: existing[keys[len(keys) - 1]] = [value]
[ "def", "chained_set", "(", "self", ",", "value", ",", "command", "=", "'set'", ",", "*", "keys", ")", ":", "new_object", "=", "self", ".", "__class__", "(", ")", "existing", "=", "self", "for", "i", "in", "range", "(", "0", ",", "len", "(", "keys", ")", "-", "1", ")", ":", "if", "keys", "[", "i", "]", "in", "existing", ":", "existing", "=", "existing", "[", "keys", "[", "i", "]", "]", "else", ":", "existing", "[", "keys", "[", "i", "]", "]", "=", "new_object", "existing", "=", "existing", "[", "keys", "[", "i", "]", "]", "if", "command", "==", "'set'", ":", "existing", "[", "keys", "[", "len", "(", "keys", ")", "-", "1", "]", "]", "=", "value", "elif", "command", "==", "'append'", ":", "if", "keys", "[", "len", "(", "keys", ")", "-", "1", "]", "in", "existing", ":", "existing", "[", "keys", "[", "len", "(", "keys", ")", "-", "1", "]", "]", ".", "append", "(", "value", ")", "else", ":", "existing", "[", "keys", "[", "len", "(", "keys", ")", "-", "1", "]", "]", "=", "[", "value", "]", "elif", "command", "==", "'set_or_append'", ":", "if", "keys", "[", "len", "(", "keys", ")", "-", "1", "]", "in", "existing", ":", "if", "type", "(", "keys", "[", "len", "(", "keys", ")", "-", "1", "]", ")", "==", "type", "(", "[", "]", ")", ":", "existing", "[", "keys", "[", "len", "(", "keys", ")", "-", "1", "]", "]", ".", "append", "(", "value", ")", "else", ":", "existing", "[", "keys", "[", "len", "(", "keys", ")", "-", "1", "]", "]", "=", "[", "existing", "[", "keys", "[", "len", "(", "keys", ")", "-", "1", "]", "]", ",", "value", "]", "else", ":", "existing", "[", "keys", "[", "len", "(", "keys", ")", "-", "1", "]", "]", "=", "value", "elif", "command", "==", "'insert'", ":", "if", "keys", "[", "len", "(", "keys", ")", "-", "1", "]", "in", "existing", ":", "if", "not", "value", "in", "existing", "[", "keys", "[", "len", "(", "keys", ")", "-", "1", "]", "]", ":", "existing", "[", "keys", "[", "len", "(", "keys", ")", "-", "1", "]", "]", ".", "append", "(", "value", ")", "else", ":", "existing", "[", "keys", "[", "len", "(", "keys", ")", "-", "1", "]", "]", "=", "[", "value", "]" ]
chained_set takes the value to enter into the dictionary, a command of what to do with the value, and a sequence of keys. Examples: d = {} d.chained_set(1,'append','level 1','level 2') -> d['level 1']['level 2'] = [1] d.chained_set(2,'append','level 1','level 2') -> d['level 1']['level 2'] = [1,2]
[ "chained_set", "takes", "the", "value", "to", "enter", "into", "the", "dictionary", "a", "command", "of", "what", "to", "do", "with", "the", "value", "and", "a", "sequence", "of", "keys", "." ]
7154f75b06d2538568e2f2455a76f3d0db0b7d70
https://github.com/siemens/django-dingos/blob/7154f75b06d2538568e2f2455a76f3d0db0b7d70/dingos/core/datastructures.py#L129-L177
239,335
usc-isi-i2/dig-extractor
digExtractor/extractor.py
Extractor.set_renamed_input_fields
def set_renamed_input_fields(self, renamed_input_fields): """This method expects a scalar string or a list of input_fields to """ if not (isinstance(renamed_input_fields, basestring) or isinstance(renamed_input_fields, ListType)): raise ValueError("renamed_input_fields must be a string or a list") self.renamed_input_fields = renamed_input_fields return self
python
def set_renamed_input_fields(self, renamed_input_fields): """This method expects a scalar string or a list of input_fields to """ if not (isinstance(renamed_input_fields, basestring) or isinstance(renamed_input_fields, ListType)): raise ValueError("renamed_input_fields must be a string or a list") self.renamed_input_fields = renamed_input_fields return self
[ "def", "set_renamed_input_fields", "(", "self", ",", "renamed_input_fields", ")", ":", "if", "not", "(", "isinstance", "(", "renamed_input_fields", ",", "basestring", ")", "or", "isinstance", "(", "renamed_input_fields", ",", "ListType", ")", ")", ":", "raise", "ValueError", "(", "\"renamed_input_fields must be a string or a list\"", ")", "self", ".", "renamed_input_fields", "=", "renamed_input_fields", "return", "self" ]
This method expects a scalar string or a list of input_fields to
[ "This", "method", "expects", "a", "scalar", "string", "or", "a", "list", "of", "input_fields", "to" ]
87c138e0300d77e35ebeb5f5e9488c3d71e60eb3
https://github.com/usc-isi-i2/dig-extractor/blob/87c138e0300d77e35ebeb5f5e9488c3d71e60eb3/digExtractor/extractor.py#L36-L43
239,336
wooga/play-deliver
playdeliver/file_util.py
list_dir_abspath
def list_dir_abspath(path): """ Return a list absolute file paths. see mkdir_p os.listdir. """ return map(lambda f: os.path.join(path, f), os.listdir(path))
python
def list_dir_abspath(path): """ Return a list absolute file paths. see mkdir_p os.listdir. """ return map(lambda f: os.path.join(path, f), os.listdir(path))
[ "def", "list_dir_abspath", "(", "path", ")", ":", "return", "map", "(", "lambda", "f", ":", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", ",", "os", ".", "listdir", "(", "path", ")", ")" ]
Return a list absolute file paths. see mkdir_p os.listdir.
[ "Return", "a", "list", "absolute", "file", "paths", "." ]
9de0f35376f5342720b3a90bd3ca296b1f3a3f4c
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/file_util.py#L7-L13
239,337
tarvitz/django-unity-asset-server-http-client
duashttp/models.py
AssetVersion.get_digest
def get_digest(self): """ return int uuid number for digest :rtype: int :return: digest """ a, b = struct.unpack('>QQ', self.digest) return (a << 64) | b
python
def get_digest(self): """ return int uuid number for digest :rtype: int :return: digest """ a, b = struct.unpack('>QQ', self.digest) return (a << 64) | b
[ "def", "get_digest", "(", "self", ")", ":", "a", ",", "b", "=", "struct", ".", "unpack", "(", "'>QQ'", ",", "self", ".", "digest", ")", "return", "(", "a", "<<", "64", ")", "|", "b" ]
return int uuid number for digest :rtype: int :return: digest
[ "return", "int", "uuid", "number", "for", "digest" ]
2b7e3b1116b5e98b31c2e267bdd66a77e0579ad1
https://github.com/tarvitz/django-unity-asset-server-http-client/blob/2b7e3b1116b5e98b31c2e267bdd66a77e0579ad1/duashttp/models.py#L102-L109
239,338
tarvitz/django-unity-asset-server-http-client
duashttp/models.py
AssetVersion.get_blob_hash
def get_blob_hash(self, h=hashlib.md5): """ get hash instance of blob content :param h: callable hash generator :type h: builtin_function_or_method :rtype: _hashlib.HASH :return: hash instance """ assert callable(h) return h(self.get_blob_data())
python
def get_blob_hash(self, h=hashlib.md5): """ get hash instance of blob content :param h: callable hash generator :type h: builtin_function_or_method :rtype: _hashlib.HASH :return: hash instance """ assert callable(h) return h(self.get_blob_data())
[ "def", "get_blob_hash", "(", "self", ",", "h", "=", "hashlib", ".", "md5", ")", ":", "assert", "callable", "(", "h", ")", "return", "h", "(", "self", ".", "get_blob_data", "(", ")", ")" ]
get hash instance of blob content :param h: callable hash generator :type h: builtin_function_or_method :rtype: _hashlib.HASH :return: hash instance
[ "get", "hash", "instance", "of", "blob", "content" ]
2b7e3b1116b5e98b31c2e267bdd66a77e0579ad1
https://github.com/tarvitz/django-unity-asset-server-http-client/blob/2b7e3b1116b5e98b31c2e267bdd66a77e0579ad1/duashttp/models.py#L111-L121
239,339
tarvitz/django-unity-asset-server-http-client
duashttp/models.py
AssetVersion.get_blob_data
def get_blob_data(self, tag_target='asset', force=False): """ get asset version content using pg large object streams :param bool force: False by default, forces get content from database instead of using cached value :rtype: str :return: content in raw format """ if hasattr(self, '_blob_data') and not force: return self._blob_data if six.PY2: self._blob_data = six.binary_type('') elif six.PY3: self._blob_data = six.binary_type('', encoding='ascii') asset_contents = self.contents.filter(tag=tag_target) for asset_content in asset_contents: blobs = asset_content.stream.get_blobs() for blob in blobs: self._blob_data += six.binary_type(blob.data) return self._blob_data
python
def get_blob_data(self, tag_target='asset', force=False): """ get asset version content using pg large object streams :param bool force: False by default, forces get content from database instead of using cached value :rtype: str :return: content in raw format """ if hasattr(self, '_blob_data') and not force: return self._blob_data if six.PY2: self._blob_data = six.binary_type('') elif six.PY3: self._blob_data = six.binary_type('', encoding='ascii') asset_contents = self.contents.filter(tag=tag_target) for asset_content in asset_contents: blobs = asset_content.stream.get_blobs() for blob in blobs: self._blob_data += six.binary_type(blob.data) return self._blob_data
[ "def", "get_blob_data", "(", "self", ",", "tag_target", "=", "'asset'", ",", "force", "=", "False", ")", ":", "if", "hasattr", "(", "self", ",", "'_blob_data'", ")", "and", "not", "force", ":", "return", "self", ".", "_blob_data", "if", "six", ".", "PY2", ":", "self", ".", "_blob_data", "=", "six", ".", "binary_type", "(", "''", ")", "elif", "six", ".", "PY3", ":", "self", ".", "_blob_data", "=", "six", ".", "binary_type", "(", "''", ",", "encoding", "=", "'ascii'", ")", "asset_contents", "=", "self", ".", "contents", ".", "filter", "(", "tag", "=", "tag_target", ")", "for", "asset_content", "in", "asset_contents", ":", "blobs", "=", "asset_content", ".", "stream", ".", "get_blobs", "(", ")", "for", "blob", "in", "blobs", ":", "self", ".", "_blob_data", "+=", "six", ".", "binary_type", "(", "blob", ".", "data", ")", "return", "self", ".", "_blob_data" ]
get asset version content using pg large object streams :param bool force: False by default, forces get content from database instead of using cached value :rtype: str :return: content in raw format
[ "get", "asset", "version", "content", "using", "pg", "large", "object", "streams" ]
2b7e3b1116b5e98b31c2e267bdd66a77e0579ad1
https://github.com/tarvitz/django-unity-asset-server-http-client/blob/2b7e3b1116b5e98b31c2e267bdd66a77e0579ad1/duashttp/models.py#L123-L144
239,340
JukeboxPipeline/jukebox-core
src/jukeboxcore/action.py
ActionUnit.run
def run(self, obj): """Execute the actions on the given object. :param obj: The object that the action should process :type obj: :class:`object` :returns: None :rtype: None :raises: None """ for d in self.depsuccess: if d.status.value != ActionStatus.SUCCESS: self.status = ActionStatus(ActionStatus.SKIPPED, "Skipped because action \"%s\" did not succeed." % d.name) return for d in self.depfail: if d.status.value == ActionStatus.SUCCESS: self.status = ActionStatus(ActionStatus.SKIPPED, "Skipped because action \"%s\" did not fail." % d.name) return try: self.status = self.actionfunc(obj) if not isinstance(self.status, ActionStatus): raise TypeError("Expected action function %s to return a ActionStatus" % self.actionfunc) except: self.status = ActionStatus(ActionStatus.ERROR, "Unexpected Error.", traceback.format_exc())
python
def run(self, obj): """Execute the actions on the given object. :param obj: The object that the action should process :type obj: :class:`object` :returns: None :rtype: None :raises: None """ for d in self.depsuccess: if d.status.value != ActionStatus.SUCCESS: self.status = ActionStatus(ActionStatus.SKIPPED, "Skipped because action \"%s\" did not succeed." % d.name) return for d in self.depfail: if d.status.value == ActionStatus.SUCCESS: self.status = ActionStatus(ActionStatus.SKIPPED, "Skipped because action \"%s\" did not fail." % d.name) return try: self.status = self.actionfunc(obj) if not isinstance(self.status, ActionStatus): raise TypeError("Expected action function %s to return a ActionStatus" % self.actionfunc) except: self.status = ActionStatus(ActionStatus.ERROR, "Unexpected Error.", traceback.format_exc())
[ "def", "run", "(", "self", ",", "obj", ")", ":", "for", "d", "in", "self", ".", "depsuccess", ":", "if", "d", ".", "status", ".", "value", "!=", "ActionStatus", ".", "SUCCESS", ":", "self", ".", "status", "=", "ActionStatus", "(", "ActionStatus", ".", "SKIPPED", ",", "\"Skipped because action \\\"%s\\\" did not succeed.\"", "%", "d", ".", "name", ")", "return", "for", "d", "in", "self", ".", "depfail", ":", "if", "d", ".", "status", ".", "value", "==", "ActionStatus", ".", "SUCCESS", ":", "self", ".", "status", "=", "ActionStatus", "(", "ActionStatus", ".", "SKIPPED", ",", "\"Skipped because action \\\"%s\\\" did not fail.\"", "%", "d", ".", "name", ")", "return", "try", ":", "self", ".", "status", "=", "self", ".", "actionfunc", "(", "obj", ")", "if", "not", "isinstance", "(", "self", ".", "status", ",", "ActionStatus", ")", ":", "raise", "TypeError", "(", "\"Expected action function %s to return a ActionStatus\"", "%", "self", ".", "actionfunc", ")", "except", ":", "self", ".", "status", "=", "ActionStatus", "(", "ActionStatus", ".", "ERROR", ",", "\"Unexpected Error.\"", ",", "traceback", ".", "format_exc", "(", ")", ")" ]
Execute the actions on the given object. :param obj: The object that the action should process :type obj: :class:`object` :returns: None :rtype: None :raises: None
[ "Execute", "the", "actions", "on", "the", "given", "object", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/action.py#L109-L131
239,341
JukeboxPipeline/jukebox-core
src/jukeboxcore/action.py
ActionCollection.status
def status(self, ): """The global status that summerizes all actions The status will be calculated in the following order: If any error occured, the status will be :data:`ActionStatus.ERROR`. If any failure occured, the status will be :data:`ActionStatus.FAILURE`. If all actions were successful or skipped, the status will be :data:`ActonStatus.SUCCESS` :returns: a status object that represents a summary of all actions :rtype: :class:`ActionStatus` :raises: None """ status = ActionStatus(ActionStatus.SUCCESS, "All actions succeeded.") for a in self.actions: if a.status.value == ActionStatus.ERROR: status = ActionStatus(ActionStatus.ERROR, "Error: action \"%s\" raised an error!" % a.name, a.status.traceback) break if a.status.value == ActionStatus.FAILURE: status = ActionStatus(ActionStatus.FAILURE, "Action(s) failed!") return status
python
def status(self, ): """The global status that summerizes all actions The status will be calculated in the following order: If any error occured, the status will be :data:`ActionStatus.ERROR`. If any failure occured, the status will be :data:`ActionStatus.FAILURE`. If all actions were successful or skipped, the status will be :data:`ActonStatus.SUCCESS` :returns: a status object that represents a summary of all actions :rtype: :class:`ActionStatus` :raises: None """ status = ActionStatus(ActionStatus.SUCCESS, "All actions succeeded.") for a in self.actions: if a.status.value == ActionStatus.ERROR: status = ActionStatus(ActionStatus.ERROR, "Error: action \"%s\" raised an error!" % a.name, a.status.traceback) break if a.status.value == ActionStatus.FAILURE: status = ActionStatus(ActionStatus.FAILURE, "Action(s) failed!") return status
[ "def", "status", "(", "self", ",", ")", ":", "status", "=", "ActionStatus", "(", "ActionStatus", ".", "SUCCESS", ",", "\"All actions succeeded.\"", ")", "for", "a", "in", "self", ".", "actions", ":", "if", "a", ".", "status", ".", "value", "==", "ActionStatus", ".", "ERROR", ":", "status", "=", "ActionStatus", "(", "ActionStatus", ".", "ERROR", ",", "\"Error: action \\\"%s\\\" raised an error!\"", "%", "a", ".", "name", ",", "a", ".", "status", ".", "traceback", ")", "break", "if", "a", ".", "status", ".", "value", "==", "ActionStatus", ".", "FAILURE", ":", "status", "=", "ActionStatus", "(", "ActionStatus", ".", "FAILURE", ",", "\"Action(s) failed!\"", ")", "return", "status" ]
The global status that summerizes all actions The status will be calculated in the following order: If any error occured, the status will be :data:`ActionStatus.ERROR`. If any failure occured, the status will be :data:`ActionStatus.FAILURE`. If all actions were successful or skipped, the status will be :data:`ActonStatus.SUCCESS` :returns: a status object that represents a summary of all actions :rtype: :class:`ActionStatus` :raises: None
[ "The", "global", "status", "that", "summerizes", "all", "actions" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/action.py#L169-L189
239,342
vmalloc/dessert
dessert/util.py
format_explanation
def format_explanation(explanation, original_msg=None): """This formats an explanation Normally all embedded newlines are escaped, however there are three exceptions: \n{, \n} and \n~. The first two are intended cover nested explanations, see function and attribute explanations for examples (.visit_Call(), visit_Attribute()). The last one is for when one explanation needs to span multiple lines, e.g. when displaying diffs. """ if not conf.is_message_introspection_enabled() and original_msg: return original_msg explanation = ecu(explanation) lines = _split_explanation(explanation) result = _format_lines(lines) return u('\n').join(result)
python
def format_explanation(explanation, original_msg=None): """This formats an explanation Normally all embedded newlines are escaped, however there are three exceptions: \n{, \n} and \n~. The first two are intended cover nested explanations, see function and attribute explanations for examples (.visit_Call(), visit_Attribute()). The last one is for when one explanation needs to span multiple lines, e.g. when displaying diffs. """ if not conf.is_message_introspection_enabled() and original_msg: return original_msg explanation = ecu(explanation) lines = _split_explanation(explanation) result = _format_lines(lines) return u('\n').join(result)
[ "def", "format_explanation", "(", "explanation", ",", "original_msg", "=", "None", ")", ":", "if", "not", "conf", ".", "is_message_introspection_enabled", "(", ")", "and", "original_msg", ":", "return", "original_msg", "explanation", "=", "ecu", "(", "explanation", ")", "lines", "=", "_split_explanation", "(", "explanation", ")", "result", "=", "_format_lines", "(", "lines", ")", "return", "u", "(", "'\\n'", ")", ".", "join", "(", "result", ")" ]
This formats an explanation Normally all embedded newlines are escaped, however there are three exceptions: \n{, \n} and \n~. The first two are intended cover nested explanations, see function and attribute explanations for examples (.visit_Call(), visit_Attribute()). The last one is for when one explanation needs to span multiple lines, e.g. when displaying diffs.
[ "This", "formats", "an", "explanation" ]
fa86b39da4853f2c35f0686942db777c7cc57728
https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/util.py#L33-L48
239,343
vmalloc/dessert
dessert/util.py
_split_explanation
def _split_explanation(explanation): """Return a list of individual lines in the explanation This will return a list of lines split on '\n{', '\n}' and '\n~'. Any other newlines will be escaped and appear in the line as the literal '\n' characters. """ raw_lines = (explanation or u('')).split('\n') lines = [raw_lines[0]] for l in raw_lines[1:]: if l and l[0] in ['{', '}', '~', '>']: lines.append(l) else: lines[-1] += '\\n' + l return lines
python
def _split_explanation(explanation): """Return a list of individual lines in the explanation This will return a list of lines split on '\n{', '\n}' and '\n~'. Any other newlines will be escaped and appear in the line as the literal '\n' characters. """ raw_lines = (explanation or u('')).split('\n') lines = [raw_lines[0]] for l in raw_lines[1:]: if l and l[0] in ['{', '}', '~', '>']: lines.append(l) else: lines[-1] += '\\n' + l return lines
[ "def", "_split_explanation", "(", "explanation", ")", ":", "raw_lines", "=", "(", "explanation", "or", "u", "(", "''", ")", ")", ".", "split", "(", "'\\n'", ")", "lines", "=", "[", "raw_lines", "[", "0", "]", "]", "for", "l", "in", "raw_lines", "[", "1", ":", "]", ":", "if", "l", "and", "l", "[", "0", "]", "in", "[", "'{'", ",", "'}'", ",", "'~'", ",", "'>'", "]", ":", "lines", ".", "append", "(", "l", ")", "else", ":", "lines", "[", "-", "1", "]", "+=", "'\\\\n'", "+", "l", "return", "lines" ]
Return a list of individual lines in the explanation This will return a list of lines split on '\n{', '\n}' and '\n~'. Any other newlines will be escaped and appear in the line as the literal '\n' characters.
[ "Return", "a", "list", "of", "individual", "lines", "in", "the", "explanation" ]
fa86b39da4853f2c35f0686942db777c7cc57728
https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/util.py#L51-L65
239,344
vmalloc/dessert
dessert/util.py
_format_lines
def _format_lines(lines): """Format the individual lines This will replace the '{', '}' and '~' characters of our mini formatting language with the proper 'where ...', 'and ...' and ' + ...' text, taking care of indentation along the way. Return a list of formatted lines. """ result = lines[:1] stack = [0] stackcnt = [0] for line in lines[1:]: if line.startswith('{'): if stackcnt[-1]: s = u('and ') else: s = u('where ') stack.append(len(result)) stackcnt[-1] += 1 stackcnt.append(0) result.append(u(' +') + u(' ')*(len(stack)-1) + s + line[1:]) elif line.startswith('}'): stack.pop() stackcnt.pop() result[stack[-1]] += line[1:] else: assert line[0] in ['~', '>'] stack[-1] += 1 indent = len(stack) if line.startswith('~') else len(stack) - 1 result.append(u(' ')*indent + line[1:]) assert len(stack) == 1 return result
python
def _format_lines(lines): """Format the individual lines This will replace the '{', '}' and '~' characters of our mini formatting language with the proper 'where ...', 'and ...' and ' + ...' text, taking care of indentation along the way. Return a list of formatted lines. """ result = lines[:1] stack = [0] stackcnt = [0] for line in lines[1:]: if line.startswith('{'): if stackcnt[-1]: s = u('and ') else: s = u('where ') stack.append(len(result)) stackcnt[-1] += 1 stackcnt.append(0) result.append(u(' +') + u(' ')*(len(stack)-1) + s + line[1:]) elif line.startswith('}'): stack.pop() stackcnt.pop() result[stack[-1]] += line[1:] else: assert line[0] in ['~', '>'] stack[-1] += 1 indent = len(stack) if line.startswith('~') else len(stack) - 1 result.append(u(' ')*indent + line[1:]) assert len(stack) == 1 return result
[ "def", "_format_lines", "(", "lines", ")", ":", "result", "=", "lines", "[", ":", "1", "]", "stack", "=", "[", "0", "]", "stackcnt", "=", "[", "0", "]", "for", "line", "in", "lines", "[", "1", ":", "]", ":", "if", "line", ".", "startswith", "(", "'{'", ")", ":", "if", "stackcnt", "[", "-", "1", "]", ":", "s", "=", "u", "(", "'and '", ")", "else", ":", "s", "=", "u", "(", "'where '", ")", "stack", ".", "append", "(", "len", "(", "result", ")", ")", "stackcnt", "[", "-", "1", "]", "+=", "1", "stackcnt", ".", "append", "(", "0", ")", "result", ".", "append", "(", "u", "(", "' +'", ")", "+", "u", "(", "' '", ")", "*", "(", "len", "(", "stack", ")", "-", "1", ")", "+", "s", "+", "line", "[", "1", ":", "]", ")", "elif", "line", ".", "startswith", "(", "'}'", ")", ":", "stack", ".", "pop", "(", ")", "stackcnt", ".", "pop", "(", ")", "result", "[", "stack", "[", "-", "1", "]", "]", "+=", "line", "[", "1", ":", "]", "else", ":", "assert", "line", "[", "0", "]", "in", "[", "'~'", ",", "'>'", "]", "stack", "[", "-", "1", "]", "+=", "1", "indent", "=", "len", "(", "stack", ")", "if", "line", ".", "startswith", "(", "'~'", ")", "else", "len", "(", "stack", ")", "-", "1", "result", ".", "append", "(", "u", "(", "' '", ")", "*", "indent", "+", "line", "[", "1", ":", "]", ")", "assert", "len", "(", "stack", ")", "==", "1", "return", "result" ]
Format the individual lines This will replace the '{', '}' and '~' characters of our mini formatting language with the proper 'where ...', 'and ...' and ' + ...' text, taking care of indentation along the way. Return a list of formatted lines.
[ "Format", "the", "individual", "lines" ]
fa86b39da4853f2c35f0686942db777c7cc57728
https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/util.py#L68-L100
239,345
vmalloc/dessert
dessert/util.py
_diff_text
def _diff_text(left, right, verbose=False): """Return the explanation for the diff between text or bytes Unless --verbose is used this will skip leading and trailing characters which are identical to keep the diff minimal. If the input are bytes they will be safely converted to text. """ from difflib import ndiff explanation = [] if isinstance(left, py.builtin.bytes): left = u(repr(left)[1:-1]).replace(r'\n', '\n') if isinstance(right, py.builtin.bytes): right = u(repr(right)[1:-1]).replace(r'\n', '\n') if not verbose: i = 0 # just in case left or right has zero length for i in range(min(len(left), len(right))): if left[i] != right[i]: break if i > 42: i -= 10 # Provide some context explanation = [u('Skipping %s identical leading ' 'characters in diff, use -v to show') % i] left = left[i:] right = right[i:] if len(left) == len(right): for i in range(len(left)): if left[-i] != right[-i]: break if i > 42: i -= 10 # Provide some context explanation += [u('Skipping %s identical trailing ' 'characters in diff, use -v to show') % i] left = left[:-i] right = right[:-i] keepends = True explanation += [line.strip('\n') for line in ndiff(left.splitlines(keepends), right.splitlines(keepends))] return explanation
python
def _diff_text(left, right, verbose=False): """Return the explanation for the diff between text or bytes Unless --verbose is used this will skip leading and trailing characters which are identical to keep the diff minimal. If the input are bytes they will be safely converted to text. """ from difflib import ndiff explanation = [] if isinstance(left, py.builtin.bytes): left = u(repr(left)[1:-1]).replace(r'\n', '\n') if isinstance(right, py.builtin.bytes): right = u(repr(right)[1:-1]).replace(r'\n', '\n') if not verbose: i = 0 # just in case left or right has zero length for i in range(min(len(left), len(right))): if left[i] != right[i]: break if i > 42: i -= 10 # Provide some context explanation = [u('Skipping %s identical leading ' 'characters in diff, use -v to show') % i] left = left[i:] right = right[i:] if len(left) == len(right): for i in range(len(left)): if left[-i] != right[-i]: break if i > 42: i -= 10 # Provide some context explanation += [u('Skipping %s identical trailing ' 'characters in diff, use -v to show') % i] left = left[:-i] right = right[:-i] keepends = True explanation += [line.strip('\n') for line in ndiff(left.splitlines(keepends), right.splitlines(keepends))] return explanation
[ "def", "_diff_text", "(", "left", ",", "right", ",", "verbose", "=", "False", ")", ":", "from", "difflib", "import", "ndiff", "explanation", "=", "[", "]", "if", "isinstance", "(", "left", ",", "py", ".", "builtin", ".", "bytes", ")", ":", "left", "=", "u", "(", "repr", "(", "left", ")", "[", "1", ":", "-", "1", "]", ")", ".", "replace", "(", "r'\\n'", ",", "'\\n'", ")", "if", "isinstance", "(", "right", ",", "py", ".", "builtin", ".", "bytes", ")", ":", "right", "=", "u", "(", "repr", "(", "right", ")", "[", "1", ":", "-", "1", "]", ")", ".", "replace", "(", "r'\\n'", ",", "'\\n'", ")", "if", "not", "verbose", ":", "i", "=", "0", "# just in case left or right has zero length", "for", "i", "in", "range", "(", "min", "(", "len", "(", "left", ")", ",", "len", "(", "right", ")", ")", ")", ":", "if", "left", "[", "i", "]", "!=", "right", "[", "i", "]", ":", "break", "if", "i", ">", "42", ":", "i", "-=", "10", "# Provide some context", "explanation", "=", "[", "u", "(", "'Skipping %s identical leading '", "'characters in diff, use -v to show'", ")", "%", "i", "]", "left", "=", "left", "[", "i", ":", "]", "right", "=", "right", "[", "i", ":", "]", "if", "len", "(", "left", ")", "==", "len", "(", "right", ")", ":", "for", "i", "in", "range", "(", "len", "(", "left", ")", ")", ":", "if", "left", "[", "-", "i", "]", "!=", "right", "[", "-", "i", "]", ":", "break", "if", "i", ">", "42", ":", "i", "-=", "10", "# Provide some context", "explanation", "+=", "[", "u", "(", "'Skipping %s identical trailing '", "'characters in diff, use -v to show'", ")", "%", "i", "]", "left", "=", "left", "[", ":", "-", "i", "]", "right", "=", "right", "[", ":", "-", "i", "]", "keepends", "=", "True", "explanation", "+=", "[", "line", ".", "strip", "(", "'\\n'", ")", "for", "line", "in", "ndiff", "(", "left", ".", "splitlines", "(", "keepends", ")", ",", "right", ".", "splitlines", "(", "keepends", ")", ")", "]", "return", "explanation" ]
Return the explanation for the diff between text or bytes Unless --verbose is used this will skip leading and trailing characters which are identical to keep the diff minimal. If the input are bytes they will be safely converted to text.
[ "Return", "the", "explanation", "for", "the", "diff", "between", "text", "or", "bytes" ]
fa86b39da4853f2c35f0686942db777c7cc57728
https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/util.py#L163-L202
239,346
pip-services3-python/pip-services3-commons-python
pip_services3_commons/validate/Schema.py
Schema.with_rule
def with_rule(self, rule): """ Adds validation rule to this schema. This method returns reference to this exception to implement Builder pattern to chain additional calls. :param rule: a validation rule to be added. :return: this validation schema. """ self.rules = self.rules if self.rules != None else [] self.rules.append(rule) return self
python
def with_rule(self, rule): """ Adds validation rule to this schema. This method returns reference to this exception to implement Builder pattern to chain additional calls. :param rule: a validation rule to be added. :return: this validation schema. """ self.rules = self.rules if self.rules != None else [] self.rules.append(rule) return self
[ "def", "with_rule", "(", "self", ",", "rule", ")", ":", "self", ".", "rules", "=", "self", ".", "rules", "if", "self", ".", "rules", "!=", "None", "else", "[", "]", "self", ".", "rules", ".", "append", "(", "rule", ")", "return", "self" ]
Adds validation rule to this schema. This method returns reference to this exception to implement Builder pattern to chain additional calls. :param rule: a validation rule to be added. :return: this validation schema.
[ "Adds", "validation", "rule", "to", "this", "schema", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/validate/Schema.py#L66-L79
239,347
wickman/compactor
compactor/context.py
Context._make_socket
def _make_socket(cls, ip, port): """Bind to a new socket. If LIBPROCESS_PORT or LIBPROCESS_IP are configured in the environment, these will be used for socket connectivity. """ bound_socket = bind_sockets(port, address=ip)[0] ip, port = bound_socket.getsockname() if not ip or ip == '0.0.0.0': ip = socket.gethostbyname(socket.gethostname()) return bound_socket, ip, port
python
def _make_socket(cls, ip, port): """Bind to a new socket. If LIBPROCESS_PORT or LIBPROCESS_IP are configured in the environment, these will be used for socket connectivity. """ bound_socket = bind_sockets(port, address=ip)[0] ip, port = bound_socket.getsockname() if not ip or ip == '0.0.0.0': ip = socket.gethostbyname(socket.gethostname()) return bound_socket, ip, port
[ "def", "_make_socket", "(", "cls", ",", "ip", ",", "port", ")", ":", "bound_socket", "=", "bind_sockets", "(", "port", ",", "address", "=", "ip", ")", "[", "0", "]", "ip", ",", "port", "=", "bound_socket", ".", "getsockname", "(", ")", "if", "not", "ip", "or", "ip", "==", "'0.0.0.0'", ":", "ip", "=", "socket", ".", "gethostbyname", "(", "socket", ".", "gethostname", "(", ")", ")", "return", "bound_socket", ",", "ip", ",", "port" ]
Bind to a new socket. If LIBPROCESS_PORT or LIBPROCESS_IP are configured in the environment, these will be used for socket connectivity.
[ "Bind", "to", "a", "new", "socket", "." ]
52714be3d84aa595a212feccb4d92ec250cede2a
https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/context.py#L45-L57
239,348
wickman/compactor
compactor/context.py
Context.stop
def stop(self): """Stops the context. This terminates all PIDs and closes all connections.""" log.info('Stopping %s' % self) pids = list(self._processes) # Clean up the context for pid in pids: self.terminate(pid) while self._connections: pid = next(iter(self._connections)) conn = self._connections.pop(pid, None) if conn: conn.close() self.__loop.stop()
python
def stop(self): """Stops the context. This terminates all PIDs and closes all connections.""" log.info('Stopping %s' % self) pids = list(self._processes) # Clean up the context for pid in pids: self.terminate(pid) while self._connections: pid = next(iter(self._connections)) conn = self._connections.pop(pid, None) if conn: conn.close() self.__loop.stop()
[ "def", "stop", "(", "self", ")", ":", "log", ".", "info", "(", "'Stopping %s'", "%", "self", ")", "pids", "=", "list", "(", "self", ".", "_processes", ")", "# Clean up the context", "for", "pid", "in", "pids", ":", "self", ".", "terminate", "(", "pid", ")", "while", "self", ".", "_connections", ":", "pid", "=", "next", "(", "iter", "(", "self", ".", "_connections", ")", ")", "conn", "=", "self", ".", "_connections", ".", "pop", "(", "pid", ",", "None", ")", "if", "conn", ":", "conn", ".", "close", "(", ")", "self", ".", "__loop", ".", "stop", "(", ")" ]
Stops the context. This terminates all PIDs and closes all connections.
[ "Stops", "the", "context", ".", "This", "terminates", "all", "PIDs", "and", "closes", "all", "connections", "." ]
52714be3d84aa595a212feccb4d92ec250cede2a
https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/context.py#L151-L168
239,349
wickman/compactor
compactor/context.py
Context.spawn
def spawn(self, process): """Spawn a process. Spawning a process binds it to this context and assigns the process a pid which is returned. The process' ``initialize`` method is called. Note: A process cannot send messages until it is bound to a context. :param process: The process to bind to this context. :type process: :class:`Process` :return: The pid of the process. :rtype: :class:`PID` """ self._assert_started() process.bind(self) self.http.mount_process(process) self._processes[process.pid] = process process.initialize() return process.pid
python
def spawn(self, process): """Spawn a process. Spawning a process binds it to this context and assigns the process a pid which is returned. The process' ``initialize`` method is called. Note: A process cannot send messages until it is bound to a context. :param process: The process to bind to this context. :type process: :class:`Process` :return: The pid of the process. :rtype: :class:`PID` """ self._assert_started() process.bind(self) self.http.mount_process(process) self._processes[process.pid] = process process.initialize() return process.pid
[ "def", "spawn", "(", "self", ",", "process", ")", ":", "self", ".", "_assert_started", "(", ")", "process", ".", "bind", "(", "self", ")", "self", ".", "http", ".", "mount_process", "(", "process", ")", "self", ".", "_processes", "[", "process", ".", "pid", "]", "=", "process", "process", ".", "initialize", "(", ")", "return", "process", ".", "pid" ]
Spawn a process. Spawning a process binds it to this context and assigns the process a pid which is returned. The process' ``initialize`` method is called. Note: A process cannot send messages until it is bound to a context. :param process: The process to bind to this context. :type process: :class:`Process` :return: The pid of the process. :rtype: :class:`PID`
[ "Spawn", "a", "process", "." ]
52714be3d84aa595a212feccb4d92ec250cede2a
https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/context.py#L170-L188
239,350
wickman/compactor
compactor/context.py
Context.dispatch
def dispatch(self, pid, method, *args): """Call a method on another process by its pid. The method on the other process does not need to be installed with ``Process.install``. The call is serialized with all other calls on the context's event loop. The pid must be bound to this context. This function returns immediately. :param pid: The pid of the process to be called. :type pid: :class:`PID` :param method: The name of the method to be called. :type method: ``str`` :return: Nothing """ self._assert_started() self._assert_local_pid(pid) function = self._get_dispatch_method(pid, method) self.__loop.add_callback(function, *args)
python
def dispatch(self, pid, method, *args): """Call a method on another process by its pid. The method on the other process does not need to be installed with ``Process.install``. The call is serialized with all other calls on the context's event loop. The pid must be bound to this context. This function returns immediately. :param pid: The pid of the process to be called. :type pid: :class:`PID` :param method: The name of the method to be called. :type method: ``str`` :return: Nothing """ self._assert_started() self._assert_local_pid(pid) function = self._get_dispatch_method(pid, method) self.__loop.add_callback(function, *args)
[ "def", "dispatch", "(", "self", ",", "pid", ",", "method", ",", "*", "args", ")", ":", "self", ".", "_assert_started", "(", ")", "self", ".", "_assert_local_pid", "(", "pid", ")", "function", "=", "self", ".", "_get_dispatch_method", "(", "pid", ",", "method", ")", "self", ".", "__loop", ".", "add_callback", "(", "function", ",", "*", "args", ")" ]
Call a method on another process by its pid. The method on the other process does not need to be installed with ``Process.install``. The call is serialized with all other calls on the context's event loop. The pid must be bound to this context. This function returns immediately. :param pid: The pid of the process to be called. :type pid: :class:`PID` :param method: The name of the method to be called. :type method: ``str`` :return: Nothing
[ "Call", "a", "method", "on", "another", "process", "by", "its", "pid", "." ]
52714be3d84aa595a212feccb4d92ec250cede2a
https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/context.py#L198-L216
239,351
wickman/compactor
compactor/context.py
Context.delay
def delay(self, amount, pid, method, *args): """Call a method on another process after a specified delay. This is equivalent to ``dispatch`` except with an additional amount of time to wait prior to invoking the call. This function returns immediately. :param amount: The amount of time to wait in seconds before making the call. :type amount: ``float`` or ``int`` :param pid: The pid of the process to be called. :type pid: :class:`PID` :param method: The name of the method to be called. :type method: ``str`` :return: Nothing """ self._assert_started() self._assert_local_pid(pid) function = self._get_dispatch_method(pid, method) self.__loop.add_timeout(self.__loop.time() + amount, function, *args)
python
def delay(self, amount, pid, method, *args): """Call a method on another process after a specified delay. This is equivalent to ``dispatch`` except with an additional amount of time to wait prior to invoking the call. This function returns immediately. :param amount: The amount of time to wait in seconds before making the call. :type amount: ``float`` or ``int`` :param pid: The pid of the process to be called. :type pid: :class:`PID` :param method: The name of the method to be called. :type method: ``str`` :return: Nothing """ self._assert_started() self._assert_local_pid(pid) function = self._get_dispatch_method(pid, method) self.__loop.add_timeout(self.__loop.time() + amount, function, *args)
[ "def", "delay", "(", "self", ",", "amount", ",", "pid", ",", "method", ",", "*", "args", ")", ":", "self", ".", "_assert_started", "(", ")", "self", ".", "_assert_local_pid", "(", "pid", ")", "function", "=", "self", ".", "_get_dispatch_method", "(", "pid", ",", "method", ")", "self", ".", "__loop", ".", "add_timeout", "(", "self", ".", "__loop", ".", "time", "(", ")", "+", "amount", ",", "function", ",", "*", "args", ")" ]
Call a method on another process after a specified delay. This is equivalent to ``dispatch`` except with an additional amount of time to wait prior to invoking the call. This function returns immediately. :param amount: The amount of time to wait in seconds before making the call. :type amount: ``float`` or ``int`` :param pid: The pid of the process to be called. :type pid: :class:`PID` :param method: The name of the method to be called. :type method: ``str`` :return: Nothing
[ "Call", "a", "method", "on", "another", "process", "after", "a", "specified", "delay", "." ]
52714be3d84aa595a212feccb4d92ec250cede2a
https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/context.py#L218-L237
239,352
wickman/compactor
compactor/context.py
Context._maybe_connect
def _maybe_connect(self, to_pid, callback=None): """Asynchronously establish a connection to the remote pid.""" callback = stack_context.wrap(callback or (lambda stream: None)) def streaming_callback(data): # we are not guaranteed to get an acknowledgment, but log and discard bytes if we do. log.info('Received %d bytes from %s, discarding.' % (len(data), to_pid)) log.debug(' data: %r' % (data,)) def on_connect(exit_cb, stream): log.info('Connection to %s established' % to_pid) with self._connection_callbacks_lock: self._connections[to_pid] = stream self.__dispatch_on_connect_callbacks(to_pid, stream) self.__loop.add_callback( stream.read_until_close, exit_cb, streaming_callback=streaming_callback) create = False with self._connection_callbacks_lock: stream = self._connections.get(to_pid) callbacks = self._connection_callbacks.get(to_pid) if not stream: self._connection_callbacks[to_pid].append(callback) if not callbacks: create = True if stream: self.__loop.add_callback(callback, stream) return if not create: return sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) if not sock: raise self.SocketError('Failed opening socket') stream = IOStream(sock, io_loop=self.__loop) stream.set_nodelay(True) stream.set_close_callback(partial(self.__on_exit, to_pid, b'reached end of stream')) connect_callback = partial(on_connect, partial(self.__on_exit, to_pid), stream) log.info('Establishing connection to %s' % to_pid) stream.connect((to_pid.ip, to_pid.port), callback=connect_callback) if stream.closed(): raise self.SocketError('Failed to initiate stream connection') log.info('Maybe connected to %s' % to_pid)
python
def _maybe_connect(self, to_pid, callback=None): """Asynchronously establish a connection to the remote pid.""" callback = stack_context.wrap(callback or (lambda stream: None)) def streaming_callback(data): # we are not guaranteed to get an acknowledgment, but log and discard bytes if we do. log.info('Received %d bytes from %s, discarding.' % (len(data), to_pid)) log.debug(' data: %r' % (data,)) def on_connect(exit_cb, stream): log.info('Connection to %s established' % to_pid) with self._connection_callbacks_lock: self._connections[to_pid] = stream self.__dispatch_on_connect_callbacks(to_pid, stream) self.__loop.add_callback( stream.read_until_close, exit_cb, streaming_callback=streaming_callback) create = False with self._connection_callbacks_lock: stream = self._connections.get(to_pid) callbacks = self._connection_callbacks.get(to_pid) if not stream: self._connection_callbacks[to_pid].append(callback) if not callbacks: create = True if stream: self.__loop.add_callback(callback, stream) return if not create: return sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) if not sock: raise self.SocketError('Failed opening socket') stream = IOStream(sock, io_loop=self.__loop) stream.set_nodelay(True) stream.set_close_callback(partial(self.__on_exit, to_pid, b'reached end of stream')) connect_callback = partial(on_connect, partial(self.__on_exit, to_pid), stream) log.info('Establishing connection to %s' % to_pid) stream.connect((to_pid.ip, to_pid.port), callback=connect_callback) if stream.closed(): raise self.SocketError('Failed to initiate stream connection') log.info('Maybe connected to %s' % to_pid)
[ "def", "_maybe_connect", "(", "self", ",", "to_pid", ",", "callback", "=", "None", ")", ":", "callback", "=", "stack_context", ".", "wrap", "(", "callback", "or", "(", "lambda", "stream", ":", "None", ")", ")", "def", "streaming_callback", "(", "data", ")", ":", "# we are not guaranteed to get an acknowledgment, but log and discard bytes if we do.", "log", ".", "info", "(", "'Received %d bytes from %s, discarding.'", "%", "(", "len", "(", "data", ")", ",", "to_pid", ")", ")", "log", ".", "debug", "(", "' data: %r'", "%", "(", "data", ",", ")", ")", "def", "on_connect", "(", "exit_cb", ",", "stream", ")", ":", "log", ".", "info", "(", "'Connection to %s established'", "%", "to_pid", ")", "with", "self", ".", "_connection_callbacks_lock", ":", "self", ".", "_connections", "[", "to_pid", "]", "=", "stream", "self", ".", "__dispatch_on_connect_callbacks", "(", "to_pid", ",", "stream", ")", "self", ".", "__loop", ".", "add_callback", "(", "stream", ".", "read_until_close", ",", "exit_cb", ",", "streaming_callback", "=", "streaming_callback", ")", "create", "=", "False", "with", "self", ".", "_connection_callbacks_lock", ":", "stream", "=", "self", ".", "_connections", ".", "get", "(", "to_pid", ")", "callbacks", "=", "self", ".", "_connection_callbacks", ".", "get", "(", "to_pid", ")", "if", "not", "stream", ":", "self", ".", "_connection_callbacks", "[", "to_pid", "]", ".", "append", "(", "callback", ")", "if", "not", "callbacks", ":", "create", "=", "True", "if", "stream", ":", "self", ".", "__loop", ".", "add_callback", "(", "callback", ",", "stream", ")", "return", "if", "not", "create", ":", "return", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ",", "0", ")", "if", "not", "sock", ":", "raise", "self", ".", "SocketError", "(", "'Failed opening socket'", ")", "stream", "=", "IOStream", "(", "sock", ",", "io_loop", "=", "self", ".", "__loop", ")", "stream", ".", "set_nodelay", "(", "True", ")", "stream", ".", "set_close_callback", "(", "partial", "(", "self", ".", "__on_exit", ",", "to_pid", ",", "b'reached end of stream'", ")", ")", "connect_callback", "=", "partial", "(", "on_connect", ",", "partial", "(", "self", ".", "__on_exit", ",", "to_pid", ")", ",", "stream", ")", "log", ".", "info", "(", "'Establishing connection to %s'", "%", "to_pid", ")", "stream", ".", "connect", "(", "(", "to_pid", ".", "ip", ",", "to_pid", ".", "port", ")", ",", "callback", "=", "connect_callback", ")", "if", "stream", ".", "closed", "(", ")", ":", "raise", "self", ".", "SocketError", "(", "'Failed to initiate stream connection'", ")", "log", ".", "info", "(", "'Maybe connected to %s'", "%", "to_pid", ")" ]
Asynchronously establish a connection to the remote pid.
[ "Asynchronously", "establish", "a", "connection", "to", "the", "remote", "pid", "." ]
52714be3d84aa595a212feccb4d92ec250cede2a
https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/context.py#L247-L302
239,353
wickman/compactor
compactor/context.py
Context.send
def send(self, from_pid, to_pid, method, body=None): """Send a message method from one pid to another with an optional body. Note: It is more idiomatic to send directly from a bound process rather than calling send on the context. If the destination pid is on the same context, the Context may skip the wire and route directly to process itself. ``from_pid`` must be bound to this context. This method returns immediately. :param from_pid: The pid of the sending process. :type from_pid: :class:`PID` :param to_pid: The pid of the destination process. :type to_pid: :class:`PID` :param method: The method name of the destination process. :type method: ``str`` :keyword body: Optional content to send along with the message. :type body: ``bytes`` or None :return: Nothing """ self._assert_started() self._assert_local_pid(from_pid) if self._is_local(to_pid): local_method = self._get_local_mailbox(to_pid, method) if local_method: log.info('Doing local dispatch of %s => %s (method: %s)' % (from_pid, to_pid, local_method)) self.__loop.add_callback(local_method, from_pid, body or b'') return else: # TODO(wickman) Consider failing hard if no local method is detected, otherwise we're # just going to do a POST and have it dropped on the floor. pass request_data = encode_request(from_pid, to_pid, method, body=body) log.info('Sending POST %s => %s (payload: %d bytes)' % ( from_pid, to_pid.as_url(method), len(request_data))) def on_connect(stream): log.info('Writing %s from %s to %s' % (len(request_data), from_pid, to_pid)) stream.write(request_data) log.info('Wrote %s from %s to %s' % (len(request_data), from_pid, to_pid)) self.__loop.add_callback(self._maybe_connect, to_pid, on_connect)
python
def send(self, from_pid, to_pid, method, body=None): """Send a message method from one pid to another with an optional body. Note: It is more idiomatic to send directly from a bound process rather than calling send on the context. If the destination pid is on the same context, the Context may skip the wire and route directly to process itself. ``from_pid`` must be bound to this context. This method returns immediately. :param from_pid: The pid of the sending process. :type from_pid: :class:`PID` :param to_pid: The pid of the destination process. :type to_pid: :class:`PID` :param method: The method name of the destination process. :type method: ``str`` :keyword body: Optional content to send along with the message. :type body: ``bytes`` or None :return: Nothing """ self._assert_started() self._assert_local_pid(from_pid) if self._is_local(to_pid): local_method = self._get_local_mailbox(to_pid, method) if local_method: log.info('Doing local dispatch of %s => %s (method: %s)' % (from_pid, to_pid, local_method)) self.__loop.add_callback(local_method, from_pid, body or b'') return else: # TODO(wickman) Consider failing hard if no local method is detected, otherwise we're # just going to do a POST and have it dropped on the floor. pass request_data = encode_request(from_pid, to_pid, method, body=body) log.info('Sending POST %s => %s (payload: %d bytes)' % ( from_pid, to_pid.as_url(method), len(request_data))) def on_connect(stream): log.info('Writing %s from %s to %s' % (len(request_data), from_pid, to_pid)) stream.write(request_data) log.info('Wrote %s from %s to %s' % (len(request_data), from_pid, to_pid)) self.__loop.add_callback(self._maybe_connect, to_pid, on_connect)
[ "def", "send", "(", "self", ",", "from_pid", ",", "to_pid", ",", "method", ",", "body", "=", "None", ")", ":", "self", ".", "_assert_started", "(", ")", "self", ".", "_assert_local_pid", "(", "from_pid", ")", "if", "self", ".", "_is_local", "(", "to_pid", ")", ":", "local_method", "=", "self", ".", "_get_local_mailbox", "(", "to_pid", ",", "method", ")", "if", "local_method", ":", "log", ".", "info", "(", "'Doing local dispatch of %s => %s (method: %s)'", "%", "(", "from_pid", ",", "to_pid", ",", "local_method", ")", ")", "self", ".", "__loop", ".", "add_callback", "(", "local_method", ",", "from_pid", ",", "body", "or", "b''", ")", "return", "else", ":", "# TODO(wickman) Consider failing hard if no local method is detected, otherwise we're", "# just going to do a POST and have it dropped on the floor.", "pass", "request_data", "=", "encode_request", "(", "from_pid", ",", "to_pid", ",", "method", ",", "body", "=", "body", ")", "log", ".", "info", "(", "'Sending POST %s => %s (payload: %d bytes)'", "%", "(", "from_pid", ",", "to_pid", ".", "as_url", "(", "method", ")", ",", "len", "(", "request_data", ")", ")", ")", "def", "on_connect", "(", "stream", ")", ":", "log", ".", "info", "(", "'Writing %s from %s to %s'", "%", "(", "len", "(", "request_data", ")", ",", "from_pid", ",", "to_pid", ")", ")", "stream", ".", "write", "(", "request_data", ")", "log", ".", "info", "(", "'Wrote %s from %s to %s'", "%", "(", "len", "(", "request_data", ")", ",", "from_pid", ",", "to_pid", ")", ")", "self", ".", "__loop", ".", "add_callback", "(", "self", ".", "_maybe_connect", ",", "to_pid", ",", "on_connect", ")" ]
Send a message method from one pid to another with an optional body. Note: It is more idiomatic to send directly from a bound process rather than calling send on the context. If the destination pid is on the same context, the Context may skip the wire and route directly to process itself. ``from_pid`` must be bound to this context. This method returns immediately. :param from_pid: The pid of the sending process. :type from_pid: :class:`PID` :param to_pid: The pid of the destination process. :type to_pid: :class:`PID` :param method: The method name of the destination process. :type method: ``str`` :keyword body: Optional content to send along with the message. :type body: ``bytes`` or None :return: Nothing
[ "Send", "a", "message", "method", "from", "one", "pid", "to", "another", "with", "an", "optional", "body", "." ]
52714be3d84aa595a212feccb4d92ec250cede2a
https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/context.py#L309-L356
239,354
wickman/compactor
compactor/context.py
Context.link
def link(self, pid, to): """Link a local process to a possibly remote process. Note: It is more idiomatic to call ``link`` directly on the bound Process object instead. When ``pid`` is linked to ``to``, the termination of the ``to`` process (or the severing of its connection from the Process ``pid``) will result in the local process' ``exited`` method to be called with ``to``. This method returns immediately. :param pid: The pid of the linking process. :type pid: :class:`PID` :param to: The pid of the linked process. :type to: :class:`PID` :returns: Nothing """ self._assert_started() def really_link(): self._links[pid].add(to) log.info('Added link from %s to %s' % (pid, to)) def on_connect(stream): really_link() if self._is_local(pid): really_link() else: self.__loop.add_callback(self._maybe_connect, to, on_connect)
python
def link(self, pid, to): """Link a local process to a possibly remote process. Note: It is more idiomatic to call ``link`` directly on the bound Process object instead. When ``pid`` is linked to ``to``, the termination of the ``to`` process (or the severing of its connection from the Process ``pid``) will result in the local process' ``exited`` method to be called with ``to``. This method returns immediately. :param pid: The pid of the linking process. :type pid: :class:`PID` :param to: The pid of the linked process. :type to: :class:`PID` :returns: Nothing """ self._assert_started() def really_link(): self._links[pid].add(to) log.info('Added link from %s to %s' % (pid, to)) def on_connect(stream): really_link() if self._is_local(pid): really_link() else: self.__loop.add_callback(self._maybe_connect, to, on_connect)
[ "def", "link", "(", "self", ",", "pid", ",", "to", ")", ":", "self", ".", "_assert_started", "(", ")", "def", "really_link", "(", ")", ":", "self", ".", "_links", "[", "pid", "]", ".", "add", "(", "to", ")", "log", ".", "info", "(", "'Added link from %s to %s'", "%", "(", "pid", ",", "to", ")", ")", "def", "on_connect", "(", "stream", ")", ":", "really_link", "(", ")", "if", "self", ".", "_is_local", "(", "pid", ")", ":", "really_link", "(", ")", "else", ":", "self", ".", "__loop", ".", "add_callback", "(", "self", ".", "_maybe_connect", ",", "to", ",", "on_connect", ")" ]
Link a local process to a possibly remote process. Note: It is more idiomatic to call ``link`` directly on the bound Process object instead. When ``pid`` is linked to ``to``, the termination of the ``to`` process (or the severing of its connection from the Process ``pid``) will result in the local process' ``exited`` method to be called with ``to``. This method returns immediately. :param pid: The pid of the linking process. :type pid: :class:`PID` :param to: The pid of the linked process. :type to: :class:`PID` :returns: Nothing
[ "Link", "a", "local", "process", "to", "a", "possibly", "remote", "process", "." ]
52714be3d84aa595a212feccb4d92ec250cede2a
https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/context.py#L374-L405
239,355
wickman/compactor
compactor/context.py
Context.terminate
def terminate(self, pid): """Terminate a process bound to this context. When a process is terminated, all the processes to which it is linked will be have their ``exited`` methods called. Messages to this process will no longer be delivered. This method returns immediately. :param pid: The pid of the process to terminate. :type pid: :class:`PID` :returns: Nothing """ self._assert_started() log.info('Terminating %s' % pid) process = self._processes.pop(pid, None) if process: log.info('Unmounting %s' % process) self.http.unmount_process(process) self.__erase_link(pid)
python
def terminate(self, pid): """Terminate a process bound to this context. When a process is terminated, all the processes to which it is linked will be have their ``exited`` methods called. Messages to this process will no longer be delivered. This method returns immediately. :param pid: The pid of the process to terminate. :type pid: :class:`PID` :returns: Nothing """ self._assert_started() log.info('Terminating %s' % pid) process = self._processes.pop(pid, None) if process: log.info('Unmounting %s' % process) self.http.unmount_process(process) self.__erase_link(pid)
[ "def", "terminate", "(", "self", ",", "pid", ")", ":", "self", ".", "_assert_started", "(", ")", "log", ".", "info", "(", "'Terminating %s'", "%", "pid", ")", "process", "=", "self", ".", "_processes", ".", "pop", "(", "pid", ",", "None", ")", "if", "process", ":", "log", ".", "info", "(", "'Unmounting %s'", "%", "process", ")", "self", ".", "http", ".", "unmount_process", "(", "process", ")", "self", ".", "__erase_link", "(", "pid", ")" ]
Terminate a process bound to this context. When a process is terminated, all the processes to which it is linked will be have their ``exited`` methods called. Messages to this process will no longer be delivered. This method returns immediately. :param pid: The pid of the process to terminate. :type pid: :class:`PID` :returns: Nothing
[ "Terminate", "a", "process", "bound", "to", "this", "context", "." ]
52714be3d84aa595a212feccb4d92ec250cede2a
https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/context.py#L407-L427
239,356
DolphDev/ezurl
ezurl/__init__.py
Url._page_gen
def _page_gen(self): """ Generates The String for pages """ track = "" for page in self.__pages__: track += "/{page}".format(page=page) return track
python
def _page_gen(self): """ Generates The String for pages """ track = "" for page in self.__pages__: track += "/{page}".format(page=page) return track
[ "def", "_page_gen", "(", "self", ")", ":", "track", "=", "\"\"", "for", "page", "in", "self", ".", "__pages__", ":", "track", "+=", "\"/{page}\"", ".", "format", "(", "page", "=", "page", ")", "return", "track" ]
Generates The String for pages
[ "Generates", "The", "String", "for", "pages" ]
deaa755db2c0532c237f9eb4192aa51c7e928a07
https://github.com/DolphDev/ezurl/blob/deaa755db2c0532c237f9eb4192aa51c7e928a07/ezurl/__init__.py#L102-L109
239,357
DolphDev/ezurl
ezurl/__init__.py
Url._query_gen
def _query_gen(self): """Generates The String for queries""" return urlencode(self.__query__, safe=self.safe, querydelimiter=self.__querydelimiter__)
python
def _query_gen(self): """Generates The String for queries""" return urlencode(self.__query__, safe=self.safe, querydelimiter=self.__querydelimiter__)
[ "def", "_query_gen", "(", "self", ")", ":", "return", "urlencode", "(", "self", ".", "__query__", ",", "safe", "=", "self", ".", "safe", ",", "querydelimiter", "=", "self", ".", "__querydelimiter__", ")" ]
Generates The String for queries
[ "Generates", "The", "String", "for", "queries" ]
deaa755db2c0532c237f9eb4192aa51c7e928a07
https://github.com/DolphDev/ezurl/blob/deaa755db2c0532c237f9eb4192aa51c7e928a07/ezurl/__init__.py#L111-L113
239,358
pip-services3-python/pip-services3-commons-python
pip_services3_commons/convert/StringConverter.py
StringConverter.to_nullable_string
def to_nullable_string(value): """ Converts value into string or returns None when value is None. :param value: the value to convert. :return: string value or None when value is None. """ if value == None: return None if type(value) == datetime.date: return value.isoformat() if type(value) == datetime.datetime: if value.tzinfo == None: return value.isoformat() + "Z" else: return value.isoformat() if type(value) == list: builder = '' for element in value: if len(builder) > 0: builder = builder + "," builder = builder + element return builder.__str__() return str(value)
python
def to_nullable_string(value): """ Converts value into string or returns None when value is None. :param value: the value to convert. :return: string value or None when value is None. """ if value == None: return None if type(value) == datetime.date: return value.isoformat() if type(value) == datetime.datetime: if value.tzinfo == None: return value.isoformat() + "Z" else: return value.isoformat() if type(value) == list: builder = '' for element in value: if len(builder) > 0: builder = builder + "," builder = builder + element return builder.__str__() return str(value)
[ "def", "to_nullable_string", "(", "value", ")", ":", "if", "value", "==", "None", ":", "return", "None", "if", "type", "(", "value", ")", "==", "datetime", ".", "date", ":", "return", "value", ".", "isoformat", "(", ")", "if", "type", "(", "value", ")", "==", "datetime", ".", "datetime", ":", "if", "value", ".", "tzinfo", "==", "None", ":", "return", "value", ".", "isoformat", "(", ")", "+", "\"Z\"", "else", ":", "return", "value", ".", "isoformat", "(", ")", "if", "type", "(", "value", ")", "==", "list", ":", "builder", "=", "''", "for", "element", "in", "value", ":", "if", "len", "(", "builder", ")", ">", "0", ":", "builder", "=", "builder", "+", "\",\"", "builder", "=", "builder", "+", "element", "return", "builder", ".", "__str__", "(", ")", "return", "str", "(", "value", ")" ]
Converts value into string or returns None when value is None. :param value: the value to convert. :return: string value or None when value is None.
[ "Converts", "value", "into", "string", "or", "returns", "None", "when", "value", "is", "None", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/convert/StringConverter.py#L30-L55
239,359
pip-services3-python/pip-services3-commons-python
pip_services3_commons/convert/StringConverter.py
StringConverter.to_string_with_default
def to_string_with_default(value, default_value): """ Converts value into string or returns default when value is None. :param value: the value to convert. :param default_value: the default value. :return: string value or default when value is null. """ result = StringConverter.to_nullable_string(value) return result if result != None else default_value
python
def to_string_with_default(value, default_value): """ Converts value into string or returns default when value is None. :param value: the value to convert. :param default_value: the default value. :return: string value or default when value is null. """ result = StringConverter.to_nullable_string(value) return result if result != None else default_value
[ "def", "to_string_with_default", "(", "value", ",", "default_value", ")", ":", "result", "=", "StringConverter", ".", "to_nullable_string", "(", "value", ")", "return", "result", "if", "result", "!=", "None", "else", "default_value" ]
Converts value into string or returns default when value is None. :param value: the value to convert. :param default_value: the default value. :return: string value or default when value is null.
[ "Converts", "value", "into", "string", "or", "returns", "default", "when", "value", "is", "None", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/convert/StringConverter.py#L69-L80
239,360
rvswift/EB
EB/builder/postanalysis/postanalysis.py
run
def run(itf): """ Run postanalyze functions. """ if not itf: return 1 # access user input options = SplitInput(itf) # check input args error_check(options) # read input files try: molecules, ensemble_lookup = ReadFiles(options) except: return 1 if options.compare: compare(molecules, ensemble_lookup, options) else: evaluate_list(molecules, ensemble_lookup, options)
python
def run(itf): """ Run postanalyze functions. """ if not itf: return 1 # access user input options = SplitInput(itf) # check input args error_check(options) # read input files try: molecules, ensemble_lookup = ReadFiles(options) except: return 1 if options.compare: compare(molecules, ensemble_lookup, options) else: evaluate_list(molecules, ensemble_lookup, options)
[ "def", "run", "(", "itf", ")", ":", "if", "not", "itf", ":", "return", "1", "# access user input", "options", "=", "SplitInput", "(", "itf", ")", "# check input args", "error_check", "(", "options", ")", "# read input files", "try", ":", "molecules", ",", "ensemble_lookup", "=", "ReadFiles", "(", "options", ")", "except", ":", "return", "1", "if", "options", ".", "compare", ":", "compare", "(", "molecules", ",", "ensemble_lookup", ",", "options", ")", "else", ":", "evaluate_list", "(", "molecules", ",", "ensemble_lookup", ",", "options", ")" ]
Run postanalyze functions.
[ "Run", "postanalyze", "functions", "." ]
341880b79faf8147dc9fa6e90438531cd09fabcc
https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/postanalysis/postanalysis.py#L11-L34
239,361
rvswift/EB
EB/builder/postanalysis/postanalysis.py
evaluate_list
def evaluate_list(molecules, ensemble_lookup, options): """ Evaluate a list of ensembles and return statistics and ROC plots if appropriate """ # create stats dictionaries to store results from each ensemble stats = {} # {file name : metric_List} # print progress messages if options.write_roc: print(" Determining virtual screening performance and writing ROC data ... ") print('') else: print(" Determining virtual screening performance ...") print('') for filename in sorted(ensemble_lookup.keys()): metric_List = calculate_metrics(molecules, ensemble_lookup, filename, options) stats[filename] = metric_List # write results summary output.write_summary(stats, options, fw_type = None) # plot if options.plot: print(" Making plots ... ") print plotter(molecules, ensemble_lookup, options)
python
def evaluate_list(molecules, ensemble_lookup, options): """ Evaluate a list of ensembles and return statistics and ROC plots if appropriate """ # create stats dictionaries to store results from each ensemble stats = {} # {file name : metric_List} # print progress messages if options.write_roc: print(" Determining virtual screening performance and writing ROC data ... ") print('') else: print(" Determining virtual screening performance ...") print('') for filename in sorted(ensemble_lookup.keys()): metric_List = calculate_metrics(molecules, ensemble_lookup, filename, options) stats[filename] = metric_List # write results summary output.write_summary(stats, options, fw_type = None) # plot if options.plot: print(" Making plots ... ") print plotter(molecules, ensemble_lookup, options)
[ "def", "evaluate_list", "(", "molecules", ",", "ensemble_lookup", ",", "options", ")", ":", "# create stats dictionaries to store results from each ensemble", "stats", "=", "{", "}", "# {file name : metric_List}", "# print progress messages", "if", "options", ".", "write_roc", ":", "print", "(", "\" Determining virtual screening performance and writing ROC data ... \"", ")", "print", "(", "''", ")", "else", ":", "print", "(", "\" Determining virtual screening performance ...\"", ")", "print", "(", "''", ")", "for", "filename", "in", "sorted", "(", "ensemble_lookup", ".", "keys", "(", ")", ")", ":", "metric_List", "=", "calculate_metrics", "(", "molecules", ",", "ensemble_lookup", ",", "filename", ",", "options", ")", "stats", "[", "filename", "]", "=", "metric_List", "# write results summary", "output", ".", "write_summary", "(", "stats", ",", "options", ",", "fw_type", "=", "None", ")", "# plot", "if", "options", ".", "plot", ":", "print", "(", "\" Making plots ... \"", ")", "print", "plotter", "(", "molecules", ",", "ensemble_lookup", ",", "options", ")" ]
Evaluate a list of ensembles and return statistics and ROC plots if appropriate
[ "Evaluate", "a", "list", "of", "ensembles", "and", "return", "statistics", "and", "ROC", "plots", "if", "appropriate" ]
341880b79faf8147dc9fa6e90438531cd09fabcc
https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/postanalysis/postanalysis.py#L106-L133
239,362
humilis/humilis-lambdautils
lambdautils/monitor.py
_sentry_context_dict
def _sentry_context_dict(context): """Create a dict with context information for Sentry.""" d = { "function_name": context.function_name, "function_version": context.function_version, "invoked_function_arn": context.invoked_function_arn, "memory_limit_in_mb": context.memory_limit_in_mb, "aws_request_id": context.aws_request_id, "log_group_name": context.log_group_name, "cognito_identity_id": context.identity.cognito_identity_id, "cognito_identity_pool_id": context.identity.cognito_identity_pool_id} for k, v in os.environ.items(): if k not in {"AWS_SECURITY_TOKEN", "AWS_SESSION_TOKEN", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"}: # Do not log credentials d[k] = v return d
python
def _sentry_context_dict(context): """Create a dict with context information for Sentry.""" d = { "function_name": context.function_name, "function_version": context.function_version, "invoked_function_arn": context.invoked_function_arn, "memory_limit_in_mb": context.memory_limit_in_mb, "aws_request_id": context.aws_request_id, "log_group_name": context.log_group_name, "cognito_identity_id": context.identity.cognito_identity_id, "cognito_identity_pool_id": context.identity.cognito_identity_pool_id} for k, v in os.environ.items(): if k not in {"AWS_SECURITY_TOKEN", "AWS_SESSION_TOKEN", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"}: # Do not log credentials d[k] = v return d
[ "def", "_sentry_context_dict", "(", "context", ")", ":", "d", "=", "{", "\"function_name\"", ":", "context", ".", "function_name", ",", "\"function_version\"", ":", "context", ".", "function_version", ",", "\"invoked_function_arn\"", ":", "context", ".", "invoked_function_arn", ",", "\"memory_limit_in_mb\"", ":", "context", ".", "memory_limit_in_mb", ",", "\"aws_request_id\"", ":", "context", ".", "aws_request_id", ",", "\"log_group_name\"", ":", "context", ".", "log_group_name", ",", "\"cognito_identity_id\"", ":", "context", ".", "identity", ".", "cognito_identity_id", ",", "\"cognito_identity_pool_id\"", ":", "context", ".", "identity", ".", "cognito_identity_pool_id", "}", "for", "k", ",", "v", "in", "os", ".", "environ", ".", "items", "(", ")", ":", "if", "k", "not", "in", "{", "\"AWS_SECURITY_TOKEN\"", ",", "\"AWS_SESSION_TOKEN\"", ",", "\"AWS_ACCESS_KEY_ID\"", ",", "\"AWS_SECRET_ACCESS_KEY\"", "}", ":", "# Do not log credentials", "d", "[", "k", "]", "=", "v", "return", "d" ]
Create a dict with context information for Sentry.
[ "Create", "a", "dict", "with", "context", "information", "for", "Sentry", "." ]
58f75eb5ace23523c283708d56a9193181ea7e8e
https://github.com/humilis/humilis-lambdautils/blob/58f75eb5ace23523c283708d56a9193181ea7e8e/lambdautils/monitor.py#L27-L44
239,363
humilis/humilis-lambdautils
lambdautils/monitor.py
sentry_monitor
def sentry_monitor(error_stream=None, **kwargs): """Sentry monitoring for AWS Lambda handler.""" def decorator(func): """A decorator that adds Sentry monitoring to a Lambda handler.""" def wrapper(event, context): """Wrap the target function.""" client = _setup_sentry_client(context) try: return func(event, context) except (ProcessingError, OutOfOrderError) as err: # A controlled exception from the Kinesis processor _handle_processing_error(err, error_stream, client) except Exception as err: # Raise the exception and block the stream processor if client: client.captureException() raise return wrapper return decorator
python
def sentry_monitor(error_stream=None, **kwargs): """Sentry monitoring for AWS Lambda handler.""" def decorator(func): """A decorator that adds Sentry monitoring to a Lambda handler.""" def wrapper(event, context): """Wrap the target function.""" client = _setup_sentry_client(context) try: return func(event, context) except (ProcessingError, OutOfOrderError) as err: # A controlled exception from the Kinesis processor _handle_processing_error(err, error_stream, client) except Exception as err: # Raise the exception and block the stream processor if client: client.captureException() raise return wrapper return decorator
[ "def", "sentry_monitor", "(", "error_stream", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "func", ")", ":", "\"\"\"A decorator that adds Sentry monitoring to a Lambda handler.\"\"\"", "def", "wrapper", "(", "event", ",", "context", ")", ":", "\"\"\"Wrap the target function.\"\"\"", "client", "=", "_setup_sentry_client", "(", "context", ")", "try", ":", "return", "func", "(", "event", ",", "context", ")", "except", "(", "ProcessingError", ",", "OutOfOrderError", ")", "as", "err", ":", "# A controlled exception from the Kinesis processor", "_handle_processing_error", "(", "err", ",", "error_stream", ",", "client", ")", "except", "Exception", "as", "err", ":", "# Raise the exception and block the stream processor", "if", "client", ":", "client", ".", "captureException", "(", ")", "raise", "return", "wrapper", "return", "decorator" ]
Sentry monitoring for AWS Lambda handler.
[ "Sentry", "monitoring", "for", "AWS", "Lambda", "handler", "." ]
58f75eb5ace23523c283708d56a9193181ea7e8e
https://github.com/humilis/humilis-lambdautils/blob/58f75eb5ace23523c283708d56a9193181ea7e8e/lambdautils/monitor.py#L47-L66
239,364
humilis/humilis-lambdautils
lambdautils/monitor.py
_setup_sentry_client
def _setup_sentry_client(context): """Produce and configure the sentry client.""" # get_secret will be deprecated soon dsn = os.environ.get("SENTRY_DSN") try: client = raven.Client(dsn, sample_rate=SENTRY_SAMPLE_RATE) client.user_context(_sentry_context_dict(context)) return client except: rlogger.error("Raven client error", exc_info=True) return None
python
def _setup_sentry_client(context): """Produce and configure the sentry client.""" # get_secret will be deprecated soon dsn = os.environ.get("SENTRY_DSN") try: client = raven.Client(dsn, sample_rate=SENTRY_SAMPLE_RATE) client.user_context(_sentry_context_dict(context)) return client except: rlogger.error("Raven client error", exc_info=True) return None
[ "def", "_setup_sentry_client", "(", "context", ")", ":", "# get_secret will be deprecated soon", "dsn", "=", "os", ".", "environ", ".", "get", "(", "\"SENTRY_DSN\"", ")", "try", ":", "client", "=", "raven", ".", "Client", "(", "dsn", ",", "sample_rate", "=", "SENTRY_SAMPLE_RATE", ")", "client", ".", "user_context", "(", "_sentry_context_dict", "(", "context", ")", ")", "return", "client", "except", ":", "rlogger", ".", "error", "(", "\"Raven client error\"", ",", "exc_info", "=", "True", ")", "return", "None" ]
Produce and configure the sentry client.
[ "Produce", "and", "configure", "the", "sentry", "client", "." ]
58f75eb5ace23523c283708d56a9193181ea7e8e
https://github.com/humilis/humilis-lambdautils/blob/58f75eb5ace23523c283708d56a9193181ea7e8e/lambdautils/monitor.py#L69-L80
239,365
humilis/humilis-lambdautils
lambdautils/monitor.py
_handle_processing_error
def _handle_processing_error(err, errstream, client): """Handle ProcessingError exceptions.""" errors = sorted(err.events, key=operator.attrgetter("index")) failed = [e.event for e in errors] silent = all(isinstance(e.error, OutOfOrderError) for e in errors) if errstream: _deliver_errored_events(errstream, failed) must_raise = False else: must_raise = True for _, event, error, tb in errors: if isinstance(error, OutOfOrderError): # Not really an error: do not log this to Sentry continue try: raise six.reraise(*tb) except Exception as err: if client: client.captureException() msg = "{}{}: {}".format(type(err).__name__, err.args, json.dumps(event, indent=4)) rlogger.error(msg, exc_info=tb) if must_raise: raise
python
def _handle_processing_error(err, errstream, client): """Handle ProcessingError exceptions.""" errors = sorted(err.events, key=operator.attrgetter("index")) failed = [e.event for e in errors] silent = all(isinstance(e.error, OutOfOrderError) for e in errors) if errstream: _deliver_errored_events(errstream, failed) must_raise = False else: must_raise = True for _, event, error, tb in errors: if isinstance(error, OutOfOrderError): # Not really an error: do not log this to Sentry continue try: raise six.reraise(*tb) except Exception as err: if client: client.captureException() msg = "{}{}: {}".format(type(err).__name__, err.args, json.dumps(event, indent=4)) rlogger.error(msg, exc_info=tb) if must_raise: raise
[ "def", "_handle_processing_error", "(", "err", ",", "errstream", ",", "client", ")", ":", "errors", "=", "sorted", "(", "err", ".", "events", ",", "key", "=", "operator", ".", "attrgetter", "(", "\"index\"", ")", ")", "failed", "=", "[", "e", ".", "event", "for", "e", "in", "errors", "]", "silent", "=", "all", "(", "isinstance", "(", "e", ".", "error", ",", "OutOfOrderError", ")", "for", "e", "in", "errors", ")", "if", "errstream", ":", "_deliver_errored_events", "(", "errstream", ",", "failed", ")", "must_raise", "=", "False", "else", ":", "must_raise", "=", "True", "for", "_", ",", "event", ",", "error", ",", "tb", "in", "errors", ":", "if", "isinstance", "(", "error", ",", "OutOfOrderError", ")", ":", "# Not really an error: do not log this to Sentry", "continue", "try", ":", "raise", "six", ".", "reraise", "(", "*", "tb", ")", "except", "Exception", "as", "err", ":", "if", "client", ":", "client", ".", "captureException", "(", ")", "msg", "=", "\"{}{}: {}\"", ".", "format", "(", "type", "(", "err", ")", ".", "__name__", ",", "err", ".", "args", ",", "json", ".", "dumps", "(", "event", ",", "indent", "=", "4", ")", ")", "rlogger", ".", "error", "(", "msg", ",", "exc_info", "=", "tb", ")", "if", "must_raise", ":", "raise" ]
Handle ProcessingError exceptions.
[ "Handle", "ProcessingError", "exceptions", "." ]
58f75eb5ace23523c283708d56a9193181ea7e8e
https://github.com/humilis/humilis-lambdautils/blob/58f75eb5ace23523c283708d56a9193181ea7e8e/lambdautils/monitor.py#L83-L107
239,366
humilis/humilis-lambdautils
lambdautils/monitor.py
_deliver_errored_events
def _deliver_errored_events(errstream, recs): """Deliver errors to error stream.""" rlogger.info("Going to handle %s failed events", len(recs)) rlogger.info( "First failed event: %s", json.dumps(recs[0], indent=4)) kinesis_stream = errstream.get("kinesis_stream") randomkey = str(uuid.uuid4()) if kinesis_stream: send_to_kinesis_stream( recs, kinesis_stream, partition_key=errstream.get("partition_key", randomkey)) rlogger.info("Sent errors to Kinesis stream '%s'", errstream) delivery_stream = errstream.get("firehose_delivery_stream") if delivery_stream: send_to_delivery_stream(errevents, delivery_stream) rlogger.info("Sent error payload to Firehose delivery stream '%s'", delivery_stream)
python
def _deliver_errored_events(errstream, recs): """Deliver errors to error stream.""" rlogger.info("Going to handle %s failed events", len(recs)) rlogger.info( "First failed event: %s", json.dumps(recs[0], indent=4)) kinesis_stream = errstream.get("kinesis_stream") randomkey = str(uuid.uuid4()) if kinesis_stream: send_to_kinesis_stream( recs, kinesis_stream, partition_key=errstream.get("partition_key", randomkey)) rlogger.info("Sent errors to Kinesis stream '%s'", errstream) delivery_stream = errstream.get("firehose_delivery_stream") if delivery_stream: send_to_delivery_stream(errevents, delivery_stream) rlogger.info("Sent error payload to Firehose delivery stream '%s'", delivery_stream)
[ "def", "_deliver_errored_events", "(", "errstream", ",", "recs", ")", ":", "rlogger", ".", "info", "(", "\"Going to handle %s failed events\"", ",", "len", "(", "recs", ")", ")", "rlogger", ".", "info", "(", "\"First failed event: %s\"", ",", "json", ".", "dumps", "(", "recs", "[", "0", "]", ",", "indent", "=", "4", ")", ")", "kinesis_stream", "=", "errstream", ".", "get", "(", "\"kinesis_stream\"", ")", "randomkey", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "if", "kinesis_stream", ":", "send_to_kinesis_stream", "(", "recs", ",", "kinesis_stream", ",", "partition_key", "=", "errstream", ".", "get", "(", "\"partition_key\"", ",", "randomkey", ")", ")", "rlogger", ".", "info", "(", "\"Sent errors to Kinesis stream '%s'\"", ",", "errstream", ")", "delivery_stream", "=", "errstream", ".", "get", "(", "\"firehose_delivery_stream\"", ")", "if", "delivery_stream", ":", "send_to_delivery_stream", "(", "errevents", ",", "delivery_stream", ")", "rlogger", ".", "info", "(", "\"Sent error payload to Firehose delivery stream '%s'\"", ",", "delivery_stream", ")" ]
Deliver errors to error stream.
[ "Deliver", "errors", "to", "error", "stream", "." ]
58f75eb5ace23523c283708d56a9193181ea7e8e
https://github.com/humilis/humilis-lambdautils/blob/58f75eb5ace23523c283708d56a9193181ea7e8e/lambdautils/monitor.py#L110-L129
239,367
humilis/humilis-lambdautils
lambdautils/monitor.py
_get_records
def _get_records(event): """Get records from an AWS Lambda trigger event.""" try: recs, _ = unpack_kinesis_event(event, deserializer=None) except KeyError: # If not a Kinesis event, just unpack the records recs = event["Records"] return recs
python
def _get_records(event): """Get records from an AWS Lambda trigger event.""" try: recs, _ = unpack_kinesis_event(event, deserializer=None) except KeyError: # If not a Kinesis event, just unpack the records recs = event["Records"] return recs
[ "def", "_get_records", "(", "event", ")", ":", "try", ":", "recs", ",", "_", "=", "unpack_kinesis_event", "(", "event", ",", "deserializer", "=", "None", ")", "except", "KeyError", ":", "# If not a Kinesis event, just unpack the records", "recs", "=", "event", "[", "\"Records\"", "]", "return", "recs" ]
Get records from an AWS Lambda trigger event.
[ "Get", "records", "from", "an", "AWS", "Lambda", "trigger", "event", "." ]
58f75eb5ace23523c283708d56a9193181ea7e8e
https://github.com/humilis/humilis-lambdautils/blob/58f75eb5ace23523c283708d56a9193181ea7e8e/lambdautils/monitor.py#L132-L139
239,368
macbre/elasticsearch-query
elasticsearch_query.py
ElasticsearchQuery._search
def _search(self, query, fields=None, limit=50000, sampling=None): """ Perform the search and return raw rows :type query object :type fields list[str] or None :type limit int :type sampling int or None :arg sampling: Percentage of results to be returned (0,100) :rtype: list """ body = { "query": { "bool": { "must": [ query ] } } } # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-source-filtering.html if fields: body['_source'] = { "includes": fields } # add @timestamp range # @see http://stackoverflow.com/questions/40996266/elasticsearch-5-1-unknown-key-for-a-start-object-in-filters # @see https://discuss.elastic.co/t/elasticsearch-watcher-error-for-range-query/70347/2 body['query']['bool']['must'].append(self._get_timestamp_filer()) # sample the results if needed if sampling is not None: body['query']['bool']['must'].append({ 'script': { 'script': { 'lang': 'painless', 'source': "Math.abs(doc['_id'].value.hashCode()) % 100 < params.sampling", 'params': { 'sampling': sampling } } } }) self._logger.debug("Running {} query (limit set to {:d})".format(json.dumps(body), body.get('size', 0))) # use Scroll API to be able to fetch more than 10k results and prevent "search_phase_execution_exception": # "Result window is too large, from + size must be less than or equal to: [10000] but was [500000]. # See the scroll api for a more efficient way to request large data sets." # # @see http://elasticsearch-py.readthedocs.io/en/master/helpers.html#scan rows = scan( client=self._es, clear_scroll=False, # True causes "403 Forbidden: You don't have access to this resource" index=self._index, query=body, sort=["_doc"], # return the next batch of results from every shard that still has results to return. size=self._batch_size, # batch size ) # get only requested amount of entries and cast them to a list rows = islice(rows, 0, limit) rows = [entry['_source'] for entry in rows] # get data self._logger.info("{:d} rows returned".format(len(rows))) return rows
python
def _search(self, query, fields=None, limit=50000, sampling=None): """ Perform the search and return raw rows :type query object :type fields list[str] or None :type limit int :type sampling int or None :arg sampling: Percentage of results to be returned (0,100) :rtype: list """ body = { "query": { "bool": { "must": [ query ] } } } # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-source-filtering.html if fields: body['_source'] = { "includes": fields } # add @timestamp range # @see http://stackoverflow.com/questions/40996266/elasticsearch-5-1-unknown-key-for-a-start-object-in-filters # @see https://discuss.elastic.co/t/elasticsearch-watcher-error-for-range-query/70347/2 body['query']['bool']['must'].append(self._get_timestamp_filer()) # sample the results if needed if sampling is not None: body['query']['bool']['must'].append({ 'script': { 'script': { 'lang': 'painless', 'source': "Math.abs(doc['_id'].value.hashCode()) % 100 < params.sampling", 'params': { 'sampling': sampling } } } }) self._logger.debug("Running {} query (limit set to {:d})".format(json.dumps(body), body.get('size', 0))) # use Scroll API to be able to fetch more than 10k results and prevent "search_phase_execution_exception": # "Result window is too large, from + size must be less than or equal to: [10000] but was [500000]. # See the scroll api for a more efficient way to request large data sets." # # @see http://elasticsearch-py.readthedocs.io/en/master/helpers.html#scan rows = scan( client=self._es, clear_scroll=False, # True causes "403 Forbidden: You don't have access to this resource" index=self._index, query=body, sort=["_doc"], # return the next batch of results from every shard that still has results to return. size=self._batch_size, # batch size ) # get only requested amount of entries and cast them to a list rows = islice(rows, 0, limit) rows = [entry['_source'] for entry in rows] # get data self._logger.info("{:d} rows returned".format(len(rows))) return rows
[ "def", "_search", "(", "self", ",", "query", ",", "fields", "=", "None", ",", "limit", "=", "50000", ",", "sampling", "=", "None", ")", ":", "body", "=", "{", "\"query\"", ":", "{", "\"bool\"", ":", "{", "\"must\"", ":", "[", "query", "]", "}", "}", "}", "# @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-source-filtering.html", "if", "fields", ":", "body", "[", "'_source'", "]", "=", "{", "\"includes\"", ":", "fields", "}", "# add @timestamp range", "# @see http://stackoverflow.com/questions/40996266/elasticsearch-5-1-unknown-key-for-a-start-object-in-filters", "# @see https://discuss.elastic.co/t/elasticsearch-watcher-error-for-range-query/70347/2", "body", "[", "'query'", "]", "[", "'bool'", "]", "[", "'must'", "]", ".", "append", "(", "self", ".", "_get_timestamp_filer", "(", ")", ")", "# sample the results if needed", "if", "sampling", "is", "not", "None", ":", "body", "[", "'query'", "]", "[", "'bool'", "]", "[", "'must'", "]", ".", "append", "(", "{", "'script'", ":", "{", "'script'", ":", "{", "'lang'", ":", "'painless'", ",", "'source'", ":", "\"Math.abs(doc['_id'].value.hashCode()) % 100 < params.sampling\"", ",", "'params'", ":", "{", "'sampling'", ":", "sampling", "}", "}", "}", "}", ")", "self", ".", "_logger", ".", "debug", "(", "\"Running {} query (limit set to {:d})\"", ".", "format", "(", "json", ".", "dumps", "(", "body", ")", ",", "body", ".", "get", "(", "'size'", ",", "0", ")", ")", ")", "# use Scroll API to be able to fetch more than 10k results and prevent \"search_phase_execution_exception\":", "# \"Result window is too large, from + size must be less than or equal to: [10000] but was [500000].", "# See the scroll api for a more efficient way to request large data sets.\"", "#", "# @see http://elasticsearch-py.readthedocs.io/en/master/helpers.html#scan", "rows", "=", "scan", "(", "client", "=", "self", ".", "_es", ",", "clear_scroll", "=", "False", ",", "# True causes \"403 Forbidden: You don't have access to this resource\"", "index", "=", "self", ".", "_index", ",", "query", "=", "body", ",", "sort", "=", "[", "\"_doc\"", "]", ",", "# return the next batch of results from every shard that still has results to return.", "size", "=", "self", ".", "_batch_size", ",", "# batch size", ")", "# get only requested amount of entries and cast them to a list", "rows", "=", "islice", "(", "rows", ",", "0", ",", "limit", ")", "rows", "=", "[", "entry", "[", "'_source'", "]", "for", "entry", "in", "rows", "]", "# get data", "self", ".", "_logger", ".", "info", "(", "\"{:d} rows returned\"", ".", "format", "(", "len", "(", "rows", ")", ")", ")", "return", "rows" ]
Perform the search and return raw rows :type query object :type fields list[str] or None :type limit int :type sampling int or None :arg sampling: Percentage of results to be returned (0,100) :rtype: list
[ "Perform", "the", "search", "and", "return", "raw", "rows" ]
d5e0fa43fde20b7f38f9d99c3fc24f681d6e5baf
https://github.com/macbre/elasticsearch-query/blob/d5e0fa43fde20b7f38f9d99c3fc24f681d6e5baf/elasticsearch_query.py#L121-L190
239,369
macbre/elasticsearch-query
elasticsearch_query.py
ElasticsearchQuery.get_rows
def get_rows(self, match, fields=None, limit=10, sampling=None): """ Returns raw rows that matches given query :arg match: query to be run against Kibana log messages (ex. {"@message": "Foo Bar DB queries"}) :type fields list[str] or None :arg limit: the number of results (defaults to 10) :type sampling int or None :arg sampling: Percentage of results to be returned (0,100) """ query = { "match": match, } return self._search(query, fields, limit, sampling)
python
def get_rows(self, match, fields=None, limit=10, sampling=None): """ Returns raw rows that matches given query :arg match: query to be run against Kibana log messages (ex. {"@message": "Foo Bar DB queries"}) :type fields list[str] or None :arg limit: the number of results (defaults to 10) :type sampling int or None :arg sampling: Percentage of results to be returned (0,100) """ query = { "match": match, } return self._search(query, fields, limit, sampling)
[ "def", "get_rows", "(", "self", ",", "match", ",", "fields", "=", "None", ",", "limit", "=", "10", ",", "sampling", "=", "None", ")", ":", "query", "=", "{", "\"match\"", ":", "match", ",", "}", "return", "self", ".", "_search", "(", "query", ",", "fields", ",", "limit", ",", "sampling", ")" ]
Returns raw rows that matches given query :arg match: query to be run against Kibana log messages (ex. {"@message": "Foo Bar DB queries"}) :type fields list[str] or None :arg limit: the number of results (defaults to 10) :type sampling int or None :arg sampling: Percentage of results to be returned (0,100)
[ "Returns", "raw", "rows", "that", "matches", "given", "query" ]
d5e0fa43fde20b7f38f9d99c3fc24f681d6e5baf
https://github.com/macbre/elasticsearch-query/blob/d5e0fa43fde20b7f38f9d99c3fc24f681d6e5baf/elasticsearch_query.py#L192-L206
239,370
macbre/elasticsearch-query
elasticsearch_query.py
ElasticsearchQuery.query_by_string
def query_by_string(self, query, fields=None, limit=10, sampling=None): """ Returns raw rows that matches the given query string :arg query: query string to be run against Kibana log messages (ex. @message:"^PHP Fatal"). :type fields list[str] or None :arg limit: the number of results (defaults to 10) :type sampling int or None :arg sampling: Percentage of results to be returned (0,100) """ query = { "query_string": { "query": query, } } return self._search(query, fields, limit, sampling)
python
def query_by_string(self, query, fields=None, limit=10, sampling=None): """ Returns raw rows that matches the given query string :arg query: query string to be run against Kibana log messages (ex. @message:"^PHP Fatal"). :type fields list[str] or None :arg limit: the number of results (defaults to 10) :type sampling int or None :arg sampling: Percentage of results to be returned (0,100) """ query = { "query_string": { "query": query, } } return self._search(query, fields, limit, sampling)
[ "def", "query_by_string", "(", "self", ",", "query", ",", "fields", "=", "None", ",", "limit", "=", "10", ",", "sampling", "=", "None", ")", ":", "query", "=", "{", "\"query_string\"", ":", "{", "\"query\"", ":", "query", ",", "}", "}", "return", "self", ".", "_search", "(", "query", ",", "fields", ",", "limit", ",", "sampling", ")" ]
Returns raw rows that matches the given query string :arg query: query string to be run against Kibana log messages (ex. @message:"^PHP Fatal"). :type fields list[str] or None :arg limit: the number of results (defaults to 10) :type sampling int or None :arg sampling: Percentage of results to be returned (0,100)
[ "Returns", "raw", "rows", "that", "matches", "the", "given", "query", "string" ]
d5e0fa43fde20b7f38f9d99c3fc24f681d6e5baf
https://github.com/macbre/elasticsearch-query/blob/d5e0fa43fde20b7f38f9d99c3fc24f681d6e5baf/elasticsearch_query.py#L208-L224
239,371
macbre/elasticsearch-query
elasticsearch_query.py
ElasticsearchQuery.count
def count(self, query): """ Returns number of matching entries :type query str :rtype: int """ body = { "query": { "bool": { "must": [{ "query_string": { "query": query, } }] } } } body['query']['bool']['must'].append(self._get_timestamp_filer()) return self._es.count(index=self._index, body=body).get('count')
python
def count(self, query): """ Returns number of matching entries :type query str :rtype: int """ body = { "query": { "bool": { "must": [{ "query_string": { "query": query, } }] } } } body['query']['bool']['must'].append(self._get_timestamp_filer()) return self._es.count(index=self._index, body=body).get('count')
[ "def", "count", "(", "self", ",", "query", ")", ":", "body", "=", "{", "\"query\"", ":", "{", "\"bool\"", ":", "{", "\"must\"", ":", "[", "{", "\"query_string\"", ":", "{", "\"query\"", ":", "query", ",", "}", "}", "]", "}", "}", "}", "body", "[", "'query'", "]", "[", "'bool'", "]", "[", "'must'", "]", ".", "append", "(", "self", ".", "_get_timestamp_filer", "(", ")", ")", "return", "self", ".", "_es", ".", "count", "(", "index", "=", "self", ".", "_index", ",", "body", "=", "body", ")", ".", "get", "(", "'count'", ")" ]
Returns number of matching entries :type query str :rtype: int
[ "Returns", "number", "of", "matching", "entries" ]
d5e0fa43fde20b7f38f9d99c3fc24f681d6e5baf
https://github.com/macbre/elasticsearch-query/blob/d5e0fa43fde20b7f38f9d99c3fc24f681d6e5baf/elasticsearch_query.py#L226-L247
239,372
macbre/elasticsearch-query
elasticsearch_query.py
ElasticsearchQuery.query_by_sql
def query_by_sql(self, sql): """ Returns entries matching given SQL query :type sql str :rtype: list[dict] """ # https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-rest.html # https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-syntax-select.html body = {'query': sql} resp = self._es.transport.perform_request('POST', '/_xpack/sql', params={'format': 'json'}, body=body) # build key-value dictionary for each row to match results returned by query_by_string columns = [column['name'] for column in resp.get('columns')] return [dict(zip(columns, row)) for row in resp.get('rows')]
python
def query_by_sql(self, sql): """ Returns entries matching given SQL query :type sql str :rtype: list[dict] """ # https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-rest.html # https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-syntax-select.html body = {'query': sql} resp = self._es.transport.perform_request('POST', '/_xpack/sql', params={'format': 'json'}, body=body) # build key-value dictionary for each row to match results returned by query_by_string columns = [column['name'] for column in resp.get('columns')] return [dict(zip(columns, row)) for row in resp.get('rows')]
[ "def", "query_by_sql", "(", "self", ",", "sql", ")", ":", "# https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-rest.html", "# https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-syntax-select.html", "body", "=", "{", "'query'", ":", "sql", "}", "resp", "=", "self", ".", "_es", ".", "transport", ".", "perform_request", "(", "'POST'", ",", "'/_xpack/sql'", ",", "params", "=", "{", "'format'", ":", "'json'", "}", ",", "body", "=", "body", ")", "# build key-value dictionary for each row to match results returned by query_by_string", "columns", "=", "[", "column", "[", "'name'", "]", "for", "column", "in", "resp", ".", "get", "(", "'columns'", ")", "]", "return", "[", "dict", "(", "zip", "(", "columns", ",", "row", ")", ")", "for", "row", "in", "resp", ".", "get", "(", "'rows'", ")", "]" ]
Returns entries matching given SQL query :type sql str :rtype: list[dict]
[ "Returns", "entries", "matching", "given", "SQL", "query" ]
d5e0fa43fde20b7f38f9d99c3fc24f681d6e5baf
https://github.com/macbre/elasticsearch-query/blob/d5e0fa43fde20b7f38f9d99c3fc24f681d6e5baf/elasticsearch_query.py#L249-L265
239,373
koriakin/binflakes
binflakes/types/int.py
BinInt.extract
def extract(self, pos, width): """Extracts a subword with a given width, starting from a given bit position. """ pos = operator.index(pos) width = operator.index(width) if width < 0: raise ValueError('width must not be negative') if pos < 0: raise ValueError('extracting out of range') return BinWord(width, self >> pos, trunc=True)
python
def extract(self, pos, width): """Extracts a subword with a given width, starting from a given bit position. """ pos = operator.index(pos) width = operator.index(width) if width < 0: raise ValueError('width must not be negative') if pos < 0: raise ValueError('extracting out of range') return BinWord(width, self >> pos, trunc=True)
[ "def", "extract", "(", "self", ",", "pos", ",", "width", ")", ":", "pos", "=", "operator", ".", "index", "(", "pos", ")", "width", "=", "operator", ".", "index", "(", "width", ")", "if", "width", "<", "0", ":", "raise", "ValueError", "(", "'width must not be negative'", ")", "if", "pos", "<", "0", ":", "raise", "ValueError", "(", "'extracting out of range'", ")", "return", "BinWord", "(", "width", ",", "self", ">>", "pos", ",", "trunc", "=", "True", ")" ]
Extracts a subword with a given width, starting from a given bit position.
[ "Extracts", "a", "subword", "with", "a", "given", "width", "starting", "from", "a", "given", "bit", "position", "." ]
f059cecadf1c605802a713c62375b5bd5606d53f
https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/int.py#L72-L82
239,374
Brazelton-Lab/bio_utils
bio_utils/blast_tools/blast_to_cigar.py
blast_to_cigar
def blast_to_cigar(query_seq, match_seq, subject_seq, cigar_age='new'): """converts BLAST alignment into a old or new CIGAR line Args: query_seq (str): Aligned portion of query sequence match_seq (str): Alignment sequence subject_seq (str): Aligned portion of subject/reference sequence cigar_age (str): ['old', 'new'] CIGAR format to use, new is highly detailed while old is fairly minimalistic Returns: str: CIGAR string Raises: ValueError: If query_seq, match_seq, and match_seq not same length Examples: >>> query = 'AAGGG--CCTTGTA' >>> subject = 'AAGCCTTCCAGGTA' >>> alignment_old = '||||| |||||||' >>> alignment_new = 'AAG++ CC++GTA' >>> blast_to_cigar(query, alignment_new, subject) 3=2X2D2=2X3= >>> blast_to_cigar(query, alignment_old, subject, cigar_age='old') 5M2D7M """ if not len(query_seq) == len(match_seq) \ or not len(query_seq) == len(subject_seq) \ or not len(subject_seq) == len(match_seq): raise ValueError('query_seq, match_seq, and subject_seq not same ' 'lengths.') # Translate XML alignment to CIGAR characters cigar_line_raw = [] for query, match, subject in zip(query_seq, match_seq, subject_seq): if query == '-': # Deletion cigar_line_raw.append('D') continue elif subject == '-': # Insertion cigar_line_raw.append('I') continue elif match == '+' or match == '|' or match.isalpha(): # Match if match != '+' and cigar_age == 'new': # Positive match cigar_line_raw.append('=') continue elif match == '+' and cigar_age == 'new': # Mismatch cigar_line_raw.append('X') continue else: cigar_line_raw.append('M') continue elif cigar_age == 'new': cigar_line_raw.append('X') continue else: cigar_line_raw.append('M') # Replace repeat characters with numbers cigar_line = [] last_position = '' repeats = 1 cigar_len = len(cigar_line_raw) for letter in enumerate(cigar_line_raw): if letter[1] == last_position: repeats += 1 else: if repeats != 1: cigar_line.append(str(repeats)) repeats = 1 cigar_line.append(last_position) if letter[0] == cigar_len - 1: if repeats != 1: cigar_line.append(str(repeats)) repeats = 1 cigar_line.append(letter[1]) last_position = letter[1] return ''.join(cigar_line)
python
def blast_to_cigar(query_seq, match_seq, subject_seq, cigar_age='new'): """converts BLAST alignment into a old or new CIGAR line Args: query_seq (str): Aligned portion of query sequence match_seq (str): Alignment sequence subject_seq (str): Aligned portion of subject/reference sequence cigar_age (str): ['old', 'new'] CIGAR format to use, new is highly detailed while old is fairly minimalistic Returns: str: CIGAR string Raises: ValueError: If query_seq, match_seq, and match_seq not same length Examples: >>> query = 'AAGGG--CCTTGTA' >>> subject = 'AAGCCTTCCAGGTA' >>> alignment_old = '||||| |||||||' >>> alignment_new = 'AAG++ CC++GTA' >>> blast_to_cigar(query, alignment_new, subject) 3=2X2D2=2X3= >>> blast_to_cigar(query, alignment_old, subject, cigar_age='old') 5M2D7M """ if not len(query_seq) == len(match_seq) \ or not len(query_seq) == len(subject_seq) \ or not len(subject_seq) == len(match_seq): raise ValueError('query_seq, match_seq, and subject_seq not same ' 'lengths.') # Translate XML alignment to CIGAR characters cigar_line_raw = [] for query, match, subject in zip(query_seq, match_seq, subject_seq): if query == '-': # Deletion cigar_line_raw.append('D') continue elif subject == '-': # Insertion cigar_line_raw.append('I') continue elif match == '+' or match == '|' or match.isalpha(): # Match if match != '+' and cigar_age == 'new': # Positive match cigar_line_raw.append('=') continue elif match == '+' and cigar_age == 'new': # Mismatch cigar_line_raw.append('X') continue else: cigar_line_raw.append('M') continue elif cigar_age == 'new': cigar_line_raw.append('X') continue else: cigar_line_raw.append('M') # Replace repeat characters with numbers cigar_line = [] last_position = '' repeats = 1 cigar_len = len(cigar_line_raw) for letter in enumerate(cigar_line_raw): if letter[1] == last_position: repeats += 1 else: if repeats != 1: cigar_line.append(str(repeats)) repeats = 1 cigar_line.append(last_position) if letter[0] == cigar_len - 1: if repeats != 1: cigar_line.append(str(repeats)) repeats = 1 cigar_line.append(letter[1]) last_position = letter[1] return ''.join(cigar_line)
[ "def", "blast_to_cigar", "(", "query_seq", ",", "match_seq", ",", "subject_seq", ",", "cigar_age", "=", "'new'", ")", ":", "if", "not", "len", "(", "query_seq", ")", "==", "len", "(", "match_seq", ")", "or", "not", "len", "(", "query_seq", ")", "==", "len", "(", "subject_seq", ")", "or", "not", "len", "(", "subject_seq", ")", "==", "len", "(", "match_seq", ")", ":", "raise", "ValueError", "(", "'query_seq, match_seq, and subject_seq not same '", "'lengths.'", ")", "# Translate XML alignment to CIGAR characters", "cigar_line_raw", "=", "[", "]", "for", "query", ",", "match", ",", "subject", "in", "zip", "(", "query_seq", ",", "match_seq", ",", "subject_seq", ")", ":", "if", "query", "==", "'-'", ":", "# Deletion", "cigar_line_raw", ".", "append", "(", "'D'", ")", "continue", "elif", "subject", "==", "'-'", ":", "# Insertion", "cigar_line_raw", ".", "append", "(", "'I'", ")", "continue", "elif", "match", "==", "'+'", "or", "match", "==", "'|'", "or", "match", ".", "isalpha", "(", ")", ":", "# Match", "if", "match", "!=", "'+'", "and", "cigar_age", "==", "'new'", ":", "# Positive match", "cigar_line_raw", ".", "append", "(", "'='", ")", "continue", "elif", "match", "==", "'+'", "and", "cigar_age", "==", "'new'", ":", "# Mismatch", "cigar_line_raw", ".", "append", "(", "'X'", ")", "continue", "else", ":", "cigar_line_raw", ".", "append", "(", "'M'", ")", "continue", "elif", "cigar_age", "==", "'new'", ":", "cigar_line_raw", ".", "append", "(", "'X'", ")", "continue", "else", ":", "cigar_line_raw", ".", "append", "(", "'M'", ")", "# Replace repeat characters with numbers", "cigar_line", "=", "[", "]", "last_position", "=", "''", "repeats", "=", "1", "cigar_len", "=", "len", "(", "cigar_line_raw", ")", "for", "letter", "in", "enumerate", "(", "cigar_line_raw", ")", ":", "if", "letter", "[", "1", "]", "==", "last_position", ":", "repeats", "+=", "1", "else", ":", "if", "repeats", "!=", "1", ":", "cigar_line", ".", "append", "(", "str", "(", "repeats", ")", ")", "repeats", "=", "1", "cigar_line", ".", "append", "(", "last_position", ")", "if", "letter", "[", "0", "]", "==", "cigar_len", "-", "1", ":", "if", "repeats", "!=", "1", ":", "cigar_line", ".", "append", "(", "str", "(", "repeats", ")", ")", "repeats", "=", "1", "cigar_line", ".", "append", "(", "letter", "[", "1", "]", ")", "last_position", "=", "letter", "[", "1", "]", "return", "''", ".", "join", "(", "cigar_line", ")" ]
converts BLAST alignment into a old or new CIGAR line Args: query_seq (str): Aligned portion of query sequence match_seq (str): Alignment sequence subject_seq (str): Aligned portion of subject/reference sequence cigar_age (str): ['old', 'new'] CIGAR format to use, new is highly detailed while old is fairly minimalistic Returns: str: CIGAR string Raises: ValueError: If query_seq, match_seq, and match_seq not same length Examples: >>> query = 'AAGGG--CCTTGTA' >>> subject = 'AAGCCTTCCAGGTA' >>> alignment_old = '||||| |||||||' >>> alignment_new = 'AAG++ CC++GTA' >>> blast_to_cigar(query, alignment_new, subject) 3=2X2D2=2X3= >>> blast_to_cigar(query, alignment_old, subject, cigar_age='old') 5M2D7M
[ "converts", "BLAST", "alignment", "into", "a", "old", "or", "new", "CIGAR", "line" ]
5a7ddf13ee0bf4baaaeb6b2b99e01bf74aa132b7
https://github.com/Brazelton-Lab/bio_utils/blob/5a7ddf13ee0bf4baaaeb6b2b99e01bf74aa132b7/bio_utils/blast_tools/blast_to_cigar.py#L32-L113
239,375
edeposit/isbn_validator
src/isbn_validator/isbn_validator.py
_clean_isbn
def _clean_isbn(isbn): """ Remove all non-digit and non "x" characters from given string. Args: isbn (str): isbn string, which will be cleaned. Returns: list: array of numbers (if "x" is found, it is converted to 10). """ if isinstance(isbn, basestring): isbn = list(isbn.lower()) # filter digits and "x" isbn = filter(lambda x: x.isdigit() or x == "x", isbn) # convert ISBN to numbers return map(lambda x: 10 if x == "x" else int(x), isbn)
python
def _clean_isbn(isbn): """ Remove all non-digit and non "x" characters from given string. Args: isbn (str): isbn string, which will be cleaned. Returns: list: array of numbers (if "x" is found, it is converted to 10). """ if isinstance(isbn, basestring): isbn = list(isbn.lower()) # filter digits and "x" isbn = filter(lambda x: x.isdigit() or x == "x", isbn) # convert ISBN to numbers return map(lambda x: 10 if x == "x" else int(x), isbn)
[ "def", "_clean_isbn", "(", "isbn", ")", ":", "if", "isinstance", "(", "isbn", ",", "basestring", ")", ":", "isbn", "=", "list", "(", "isbn", ".", "lower", "(", ")", ")", "# filter digits and \"x\"", "isbn", "=", "filter", "(", "lambda", "x", ":", "x", ".", "isdigit", "(", ")", "or", "x", "==", "\"x\"", ",", "isbn", ")", "# convert ISBN to numbers", "return", "map", "(", "lambda", "x", ":", "10", "if", "x", "==", "\"x\"", "else", "int", "(", "x", ")", ",", "isbn", ")" ]
Remove all non-digit and non "x" characters from given string. Args: isbn (str): isbn string, which will be cleaned. Returns: list: array of numbers (if "x" is found, it is converted to 10).
[ "Remove", "all", "non", "-", "digit", "and", "non", "x", "characters", "from", "given", "string", "." ]
d285846940a8f71bac5a4694f640c026510d9063
https://github.com/edeposit/isbn_validator/blob/d285846940a8f71bac5a4694f640c026510d9063/src/isbn_validator/isbn_validator.py#L18-L35
239,376
edeposit/isbn_validator
src/isbn_validator/isbn_validator.py
_isbn_cleaner
def _isbn_cleaner(fn): """ Decorator for calling other functions from this module. Purpose of this decorator is to clean the ISBN string from garbage and return list of digits. Args: fn (function): function in which will be :func:`_clean_isbn(isbn)` call wrapped. """ @wraps(fn) def wrapper(isbn): return fn(_clean_isbn(isbn)) return wrapper
python
def _isbn_cleaner(fn): """ Decorator for calling other functions from this module. Purpose of this decorator is to clean the ISBN string from garbage and return list of digits. Args: fn (function): function in which will be :func:`_clean_isbn(isbn)` call wrapped. """ @wraps(fn) def wrapper(isbn): return fn(_clean_isbn(isbn)) return wrapper
[ "def", "_isbn_cleaner", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "wrapper", "(", "isbn", ")", ":", "return", "fn", "(", "_clean_isbn", "(", "isbn", ")", ")", "return", "wrapper" ]
Decorator for calling other functions from this module. Purpose of this decorator is to clean the ISBN string from garbage and return list of digits. Args: fn (function): function in which will be :func:`_clean_isbn(isbn)` call wrapped.
[ "Decorator", "for", "calling", "other", "functions", "from", "this", "module", "." ]
d285846940a8f71bac5a4694f640c026510d9063
https://github.com/edeposit/isbn_validator/blob/d285846940a8f71bac5a4694f640c026510d9063/src/isbn_validator/isbn_validator.py#L38-L53
239,377
jespino/anillo
anillo/app.py
application
def application(handler, adapter_cls=WerkzeugAdapter): """Converts an anillo function based handler in a wsgi compiliant application function. :param adapter_cls: the wsgi adapter implementation (default: wekrzeug) :returns: wsgi function :rtype: callable """ adapter = adapter_cls() def wrapper(environ, start_response): request = adapter.to_request(environ) response = handler(request) response_func = adapter.from_response(response) return response_func(environ, start_response) return wrapper
python
def application(handler, adapter_cls=WerkzeugAdapter): """Converts an anillo function based handler in a wsgi compiliant application function. :param adapter_cls: the wsgi adapter implementation (default: wekrzeug) :returns: wsgi function :rtype: callable """ adapter = adapter_cls() def wrapper(environ, start_response): request = adapter.to_request(environ) response = handler(request) response_func = adapter.from_response(response) return response_func(environ, start_response) return wrapper
[ "def", "application", "(", "handler", ",", "adapter_cls", "=", "WerkzeugAdapter", ")", ":", "adapter", "=", "adapter_cls", "(", ")", "def", "wrapper", "(", "environ", ",", "start_response", ")", ":", "request", "=", "adapter", ".", "to_request", "(", "environ", ")", "response", "=", "handler", "(", "request", ")", "response_func", "=", "adapter", ".", "from_response", "(", "response", ")", "return", "response_func", "(", "environ", ",", "start_response", ")", "return", "wrapper" ]
Converts an anillo function based handler in a wsgi compiliant application function. :param adapter_cls: the wsgi adapter implementation (default: wekrzeug) :returns: wsgi function :rtype: callable
[ "Converts", "an", "anillo", "function", "based", "handler", "in", "a", "wsgi", "compiliant", "application", "function", "." ]
901a84fd2b4fa909bc06e8bd76090457990576a7
https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/app.py#L4-L20
239,378
iceb0y/aiowrap
aiowrap/wrap.py
wrap_async
def wrap_async(func): """Wraps an asynchronous function into a synchronous function.""" @functools.wraps(func) def wrapped(*args, **kwargs): fut = asyncio.ensure_future(func(*args, **kwargs)) cur = greenlet.getcurrent() def callback(fut): try: cur.switch(fut.result()) except BaseException as e: cur.throw(e) fut.add_done_callback(callback) return cur.parent.switch() return wrapped
python
def wrap_async(func): """Wraps an asynchronous function into a synchronous function.""" @functools.wraps(func) def wrapped(*args, **kwargs): fut = asyncio.ensure_future(func(*args, **kwargs)) cur = greenlet.getcurrent() def callback(fut): try: cur.switch(fut.result()) except BaseException as e: cur.throw(e) fut.add_done_callback(callback) return cur.parent.switch() return wrapped
[ "def", "wrap_async", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "fut", "=", "asyncio", ".", "ensure_future", "(", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "cur", "=", "greenlet", ".", "getcurrent", "(", ")", "def", "callback", "(", "fut", ")", ":", "try", ":", "cur", ".", "switch", "(", "fut", ".", "result", "(", ")", ")", "except", "BaseException", "as", "e", ":", "cur", ".", "throw", "(", "e", ")", "fut", ".", "add_done_callback", "(", "callback", ")", "return", "cur", ".", "parent", ".", "switch", "(", ")", "return", "wrapped" ]
Wraps an asynchronous function into a synchronous function.
[ "Wraps", "an", "asynchronous", "function", "into", "a", "synchronous", "function", "." ]
7a155e68c0faee0eea7a3f43c1e96a36ccc2fd84
https://github.com/iceb0y/aiowrap/blob/7a155e68c0faee0eea7a3f43c1e96a36ccc2fd84/aiowrap/wrap.py#L5-L18
239,379
iceb0y/aiowrap
aiowrap/wrap.py
wrap_sync
def wrap_sync(func): """Wraps a synchronous function into an asynchronous function.""" @functools.wraps(func) def wrapped(*args, **kwargs): fut = asyncio.Future() def green(): try: fut.set_result(func(*args, **kwargs)) except BaseException as e: fut.set_exception(e) greenlet.greenlet(green).switch() return fut return wrapped
python
def wrap_sync(func): """Wraps a synchronous function into an asynchronous function.""" @functools.wraps(func) def wrapped(*args, **kwargs): fut = asyncio.Future() def green(): try: fut.set_result(func(*args, **kwargs)) except BaseException as e: fut.set_exception(e) greenlet.greenlet(green).switch() return fut return wrapped
[ "def", "wrap_sync", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "fut", "=", "asyncio", ".", "Future", "(", ")", "def", "green", "(", ")", ":", "try", ":", "fut", ".", "set_result", "(", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "except", "BaseException", "as", "e", ":", "fut", ".", "set_exception", "(", "e", ")", "greenlet", ".", "greenlet", "(", "green", ")", ".", "switch", "(", ")", "return", "fut", "return", "wrapped" ]
Wraps a synchronous function into an asynchronous function.
[ "Wraps", "a", "synchronous", "function", "into", "an", "asynchronous", "function", "." ]
7a155e68c0faee0eea7a3f43c1e96a36ccc2fd84
https://github.com/iceb0y/aiowrap/blob/7a155e68c0faee0eea7a3f43c1e96a36ccc2fd84/aiowrap/wrap.py#L20-L32
239,380
dwwkelly/note
note/server.py
Note_Server.Run
def Run(self): """ Wait for clients to connect and service them :returns: None """ while True: try: events = self.poller.poll() except KeyboardInterrupt: self.context.destroy() sys.exit() self.Handle_Events(events)
python
def Run(self): """ Wait for clients to connect and service them :returns: None """ while True: try: events = self.poller.poll() except KeyboardInterrupt: self.context.destroy() sys.exit() self.Handle_Events(events)
[ "def", "Run", "(", "self", ")", ":", "while", "True", ":", "try", ":", "events", "=", "self", ".", "poller", ".", "poll", "(", ")", "except", "KeyboardInterrupt", ":", "self", ".", "context", ".", "destroy", "(", ")", "sys", ".", "exit", "(", ")", "self", ".", "Handle_Events", "(", "events", ")" ]
Wait for clients to connect and service them :returns: None
[ "Wait", "for", "clients", "to", "connect", "and", "service", "them" ]
b41d5fe1e4a3b67b50285168dd58f903bf219e6c
https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/server.py#L31-L46
239,381
dwwkelly/note
note/server.py
Note_Server.Handle_Receive
def Handle_Receive(self, msg): """ Handle a received message. :param msg: the received message :type msg: str :returns: The message to reply with :rtype: str """ msg = self.Check_Message(msg) msg_type = msg['type'] f_name = "Handle_{0}".format(msg_type) try: f = getattr(self, f_name) except AttributeError: f = self.Handle_ERROR(msg) reply = f(msg) return reply
python
def Handle_Receive(self, msg): """ Handle a received message. :param msg: the received message :type msg: str :returns: The message to reply with :rtype: str """ msg = self.Check_Message(msg) msg_type = msg['type'] f_name = "Handle_{0}".format(msg_type) try: f = getattr(self, f_name) except AttributeError: f = self.Handle_ERROR(msg) reply = f(msg) return reply
[ "def", "Handle_Receive", "(", "self", ",", "msg", ")", ":", "msg", "=", "self", ".", "Check_Message", "(", "msg", ")", "msg_type", "=", "msg", "[", "'type'", "]", "f_name", "=", "\"Handle_{0}\"", ".", "format", "(", "msg_type", ")", "try", ":", "f", "=", "getattr", "(", "self", ",", "f_name", ")", "except", "AttributeError", ":", "f", "=", "self", ".", "Handle_ERROR", "(", "msg", ")", "reply", "=", "f", "(", "msg", ")", "return", "reply" ]
Handle a received message. :param msg: the received message :type msg: str :returns: The message to reply with :rtype: str
[ "Handle", "a", "received", "message", "." ]
b41d5fe1e4a3b67b50285168dd58f903bf219e6c
https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/server.py#L73-L93
239,382
dwwkelly/note
note/server.py
Note_Server.Handle_Search
def Handle_Search(self, msg): """ Handle a search. :param msg: the received search :type msg: dict :returns: The message to reply with :rtype: str """ search_term = msg['object']['searchTerm'] results = self.db.searchForItem(search_term) reply = {"status": "OK", "type": "search", "object": { "received search": msg['object']['searchTerm'], "results": results} } return json.dumps(reply)
python
def Handle_Search(self, msg): """ Handle a search. :param msg: the received search :type msg: dict :returns: The message to reply with :rtype: str """ search_term = msg['object']['searchTerm'] results = self.db.searchForItem(search_term) reply = {"status": "OK", "type": "search", "object": { "received search": msg['object']['searchTerm'], "results": results} } return json.dumps(reply)
[ "def", "Handle_Search", "(", "self", ",", "msg", ")", ":", "search_term", "=", "msg", "[", "'object'", "]", "[", "'searchTerm'", "]", "results", "=", "self", ".", "db", ".", "searchForItem", "(", "search_term", ")", "reply", "=", "{", "\"status\"", ":", "\"OK\"", ",", "\"type\"", ":", "\"search\"", ",", "\"object\"", ":", "{", "\"received search\"", ":", "msg", "[", "'object'", "]", "[", "'searchTerm'", "]", ",", "\"results\"", ":", "results", "}", "}", "return", "json", ".", "dumps", "(", "reply", ")" ]
Handle a search. :param msg: the received search :type msg: dict :returns: The message to reply with :rtype: str
[ "Handle", "a", "search", "." ]
b41d5fe1e4a3b67b50285168dd58f903bf219e6c
https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/server.py#L103-L123
239,383
dwwkelly/note
note/server.py
Note_Server.Handle_Note
def Handle_Note(self, msg): """ Handle a new note. :param msg: the received note :type msg: dict :returns: The message to reply with :rtype: str """ note_text = msg['object']['note'] note_tags = msg['object']['tags'] if 'ID' in msg['object']: note_id = msg['object']['ID'] self.db.addItem("note", {"note": note_text, "tags": note_tags}, note_id) else: note_id = self.db.addItem("note", {"note": note_text, "tags": note_tags}) reply = {"status": "OK", "type": "Note", "object": { "received note": msg['object']['note'], "received tags": msg['object']['tags'], "ID": note_id} } return json.dumps(reply)
python
def Handle_Note(self, msg): """ Handle a new note. :param msg: the received note :type msg: dict :returns: The message to reply with :rtype: str """ note_text = msg['object']['note'] note_tags = msg['object']['tags'] if 'ID' in msg['object']: note_id = msg['object']['ID'] self.db.addItem("note", {"note": note_text, "tags": note_tags}, note_id) else: note_id = self.db.addItem("note", {"note": note_text, "tags": note_tags}) reply = {"status": "OK", "type": "Note", "object": { "received note": msg['object']['note'], "received tags": msg['object']['tags'], "ID": note_id} } return json.dumps(reply)
[ "def", "Handle_Note", "(", "self", ",", "msg", ")", ":", "note_text", "=", "msg", "[", "'object'", "]", "[", "'note'", "]", "note_tags", "=", "msg", "[", "'object'", "]", "[", "'tags'", "]", "if", "'ID'", "in", "msg", "[", "'object'", "]", ":", "note_id", "=", "msg", "[", "'object'", "]", "[", "'ID'", "]", "self", ".", "db", ".", "addItem", "(", "\"note\"", ",", "{", "\"note\"", ":", "note_text", ",", "\"tags\"", ":", "note_tags", "}", ",", "note_id", ")", "else", ":", "note_id", "=", "self", ".", "db", ".", "addItem", "(", "\"note\"", ",", "{", "\"note\"", ":", "note_text", ",", "\"tags\"", ":", "note_tags", "}", ")", "reply", "=", "{", "\"status\"", ":", "\"OK\"", ",", "\"type\"", ":", "\"Note\"", ",", "\"object\"", ":", "{", "\"received note\"", ":", "msg", "[", "'object'", "]", "[", "'note'", "]", ",", "\"received tags\"", ":", "msg", "[", "'object'", "]", "[", "'tags'", "]", ",", "\"ID\"", ":", "note_id", "}", "}", "return", "json", ".", "dumps", "(", "reply", ")" ]
Handle a new note. :param msg: the received note :type msg: dict :returns: The message to reply with :rtype: str
[ "Handle", "a", "new", "note", "." ]
b41d5fe1e4a3b67b50285168dd58f903bf219e6c
https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/server.py#L125-L154
239,384
ericflo/hurricane
hurricane/utils.py
RingBuffer.after_match
def after_match(self, func, full_fallback=False): """Returns an iterator for all the elements after the first match. If `full_fallback` is `True`, it will return all the messages if the function never matched. """ iterator = iter(self) for item in iterator: if func(item): return iterator if full_fallback: iterator = iter(self) return iterator
python
def after_match(self, func, full_fallback=False): """Returns an iterator for all the elements after the first match. If `full_fallback` is `True`, it will return all the messages if the function never matched. """ iterator = iter(self) for item in iterator: if func(item): return iterator if full_fallback: iterator = iter(self) return iterator
[ "def", "after_match", "(", "self", ",", "func", ",", "full_fallback", "=", "False", ")", ":", "iterator", "=", "iter", "(", "self", ")", "for", "item", "in", "iterator", ":", "if", "func", "(", "item", ")", ":", "return", "iterator", "if", "full_fallback", ":", "iterator", "=", "iter", "(", "self", ")", "return", "iterator" ]
Returns an iterator for all the elements after the first match. If `full_fallback` is `True`, it will return all the messages if the function never matched.
[ "Returns", "an", "iterator", "for", "all", "the", "elements", "after", "the", "first", "match", ".", "If", "full_fallback", "is", "True", "it", "will", "return", "all", "the", "messages", "if", "the", "function", "never", "matched", "." ]
c192b711b2b1c06a386d1a1a47f538b13a659cde
https://github.com/ericflo/hurricane/blob/c192b711b2b1c06a386d1a1a47f538b13a659cde/hurricane/utils.py#L112-L123
239,385
pip-services3-python/pip-services3-commons-python
pip_services3_commons/run/Cleaner.py
Cleaner.clear
def clear(correlation_id, components): """ Clears state of multiple components. To be cleaned state components must implement [[ICleanable]] interface. If they don't the call to this method has no effect. :param correlation_id: (optional) transaction id to trace execution through call chain. :param components: the list of components that are to be cleaned. """ if components == None: return for component in components: Cleaner.clear_one(correlation_id, component)
python
def clear(correlation_id, components): """ Clears state of multiple components. To be cleaned state components must implement [[ICleanable]] interface. If they don't the call to this method has no effect. :param correlation_id: (optional) transaction id to trace execution through call chain. :param components: the list of components that are to be cleaned. """ if components == None: return for component in components: Cleaner.clear_one(correlation_id, component)
[ "def", "clear", "(", "correlation_id", ",", "components", ")", ":", "if", "components", "==", "None", ":", "return", "for", "component", "in", "components", ":", "Cleaner", ".", "clear_one", "(", "correlation_id", ",", "component", ")" ]
Clears state of multiple components. To be cleaned state components must implement [[ICleanable]] interface. If they don't the call to this method has no effect. :param correlation_id: (optional) transaction id to trace execution through call chain. :param components: the list of components that are to be cleaned.
[ "Clears", "state", "of", "multiple", "components", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/run/Cleaner.py#L36-L51
239,386
lcgong/redbean
redbean/iso8601.py
parse_datetime
def parse_datetime(value): """Parses a string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raises ValueError if the input is well formatted but not a valid datetime. Returns None if the input isn't well formatted. """ match = datetime_re.match(value) if match: kw = match.groupdict() if kw['microsecond']: kw['microsecond'] = kw['microsecond'].ljust(6, '0') tzinfo = kw.pop('tzinfo') if tzinfo == 'Z': tzinfo = utc elif tzinfo is not None: offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0 offset = 60 * int(tzinfo[1:3]) + offset_mins if tzinfo[0] == '-': offset = -offset tzinfo = get_fixed_timezone(offset) kw = {k: int(v) for k, v in kw.items() if v is not None} kw['tzinfo'] = tzinfo return datetime.datetime(**kw)
python
def parse_datetime(value): """Parses a string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raises ValueError if the input is well formatted but not a valid datetime. Returns None if the input isn't well formatted. """ match = datetime_re.match(value) if match: kw = match.groupdict() if kw['microsecond']: kw['microsecond'] = kw['microsecond'].ljust(6, '0') tzinfo = kw.pop('tzinfo') if tzinfo == 'Z': tzinfo = utc elif tzinfo is not None: offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0 offset = 60 * int(tzinfo[1:3]) + offset_mins if tzinfo[0] == '-': offset = -offset tzinfo = get_fixed_timezone(offset) kw = {k: int(v) for k, v in kw.items() if v is not None} kw['tzinfo'] = tzinfo return datetime.datetime(**kw)
[ "def", "parse_datetime", "(", "value", ")", ":", "match", "=", "datetime_re", ".", "match", "(", "value", ")", "if", "match", ":", "kw", "=", "match", ".", "groupdict", "(", ")", "if", "kw", "[", "'microsecond'", "]", ":", "kw", "[", "'microsecond'", "]", "=", "kw", "[", "'microsecond'", "]", ".", "ljust", "(", "6", ",", "'0'", ")", "tzinfo", "=", "kw", ".", "pop", "(", "'tzinfo'", ")", "if", "tzinfo", "==", "'Z'", ":", "tzinfo", "=", "utc", "elif", "tzinfo", "is", "not", "None", ":", "offset_mins", "=", "int", "(", "tzinfo", "[", "-", "2", ":", "]", ")", "if", "len", "(", "tzinfo", ")", ">", "3", "else", "0", "offset", "=", "60", "*", "int", "(", "tzinfo", "[", "1", ":", "3", "]", ")", "+", "offset_mins", "if", "tzinfo", "[", "0", "]", "==", "'-'", ":", "offset", "=", "-", "offset", "tzinfo", "=", "get_fixed_timezone", "(", "offset", ")", "kw", "=", "{", "k", ":", "int", "(", "v", ")", "for", "k", ",", "v", "in", "kw", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}", "kw", "[", "'tzinfo'", "]", "=", "tzinfo", "return", "datetime", ".", "datetime", "(", "*", "*", "kw", ")" ]
Parses a string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raises ValueError if the input is well formatted but not a valid datetime. Returns None if the input isn't well formatted.
[ "Parses", "a", "string", "and", "return", "a", "datetime", ".", "datetime", "." ]
45df9ff1e807e742771c752808d7fdac4007c919
https://github.com/lcgong/redbean/blob/45df9ff1e807e742771c752808d7fdac4007c919/redbean/iso8601.py#L73-L98
239,387
sysr-q/mattdaemon
mattdaemon/daemon.py
daemon.status
def status(self): """ Check if the daemon is currently running. Requires procfs, so it will only work on POSIX compliant OS'. """ # Get the pid from the pidfile try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if not pid: return False try: return os.path.exists("/proc/{0}".format(pid)) except OSError: return False
python
def status(self): """ Check if the daemon is currently running. Requires procfs, so it will only work on POSIX compliant OS'. """ # Get the pid from the pidfile try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if not pid: return False try: return os.path.exists("/proc/{0}".format(pid)) except OSError: return False
[ "def", "status", "(", "self", ")", ":", "# Get the pid from the pidfile", "try", ":", "pf", "=", "file", "(", "self", ".", "pidfile", ",", "'r'", ")", "pid", "=", "int", "(", "pf", ".", "read", "(", ")", ".", "strip", "(", ")", ")", "pf", ".", "close", "(", ")", "except", "IOError", ":", "pid", "=", "None", "if", "not", "pid", ":", "return", "False", "try", ":", "return", "os", ".", "path", ".", "exists", "(", "\"/proc/{0}\"", ".", "format", "(", "pid", ")", ")", "except", "OSError", ":", "return", "False" ]
Check if the daemon is currently running. Requires procfs, so it will only work on POSIX compliant OS'.
[ "Check", "if", "the", "daemon", "is", "currently", "running", ".", "Requires", "procfs", "so", "it", "will", "only", "work", "on", "POSIX", "compliant", "OS", "." ]
bc32a372f46650e0ca69b84da320fa7fee3d192d
https://github.com/sysr-q/mattdaemon/blob/bc32a372f46650e0ca69b84da320fa7fee3d192d/mattdaemon/daemon.py#L174-L193
239,388
LionelAuroux/cnorm
cnorm/nodes.py
BlockStmt.func
def func(self, name: str): """return the first func defined named name""" for f in self.body: if (hasattr(f, '_ctype') and isinstance(f._ctype, FuncType) and f._name == name): return f
python
def func(self, name: str): """return the first func defined named name""" for f in self.body: if (hasattr(f, '_ctype') and isinstance(f._ctype, FuncType) and f._name == name): return f
[ "def", "func", "(", "self", ",", "name", ":", "str", ")", ":", "for", "f", "in", "self", ".", "body", ":", "if", "(", "hasattr", "(", "f", ",", "'_ctype'", ")", "and", "isinstance", "(", "f", ".", "_ctype", ",", "FuncType", ")", "and", "f", ".", "_name", "==", "name", ")", ":", "return", "f" ]
return the first func defined named name
[ "return", "the", "first", "func", "defined", "named", "name" ]
b7bb09a70c62fb02c1e41e6280a2a5c0cf2c0f15
https://github.com/LionelAuroux/cnorm/blob/b7bb09a70c62fb02c1e41e6280a2a5c0cf2c0f15/cnorm/nodes.py#L369-L375
239,389
LionelAuroux/cnorm
cnorm/nodes.py
BlockStmt.type
def type(self, name: str): """return the first complete definition of type 'name'""" for f in self.body: if (hasattr(f, '_ctype') and f._ctype._storage == Storages.TYPEDEF and f._name == name): return f
python
def type(self, name: str): """return the first complete definition of type 'name'""" for f in self.body: if (hasattr(f, '_ctype') and f._ctype._storage == Storages.TYPEDEF and f._name == name): return f
[ "def", "type", "(", "self", ",", "name", ":", "str", ")", ":", "for", "f", "in", "self", ".", "body", ":", "if", "(", "hasattr", "(", "f", ",", "'_ctype'", ")", "and", "f", ".", "_ctype", ".", "_storage", "==", "Storages", ".", "TYPEDEF", "and", "f", ".", "_name", "==", "name", ")", ":", "return", "f" ]
return the first complete definition of type 'name
[ "return", "the", "first", "complete", "definition", "of", "type", "name" ]
b7bb09a70c62fb02c1e41e6280a2a5c0cf2c0f15
https://github.com/LionelAuroux/cnorm/blob/b7bb09a70c62fb02c1e41e6280a2a5c0cf2c0f15/cnorm/nodes.py#L385-L391
239,390
LionelAuroux/cnorm
cnorm/nodes.py
BlockStmt.declallfuncs
def declallfuncs(self): """generator on all declaration of function""" for f in self.body: if (hasattr(f, '_ctype') and isinstance(f._ctype, FuncType)): yield f
python
def declallfuncs(self): """generator on all declaration of function""" for f in self.body: if (hasattr(f, '_ctype') and isinstance(f._ctype, FuncType)): yield f
[ "def", "declallfuncs", "(", "self", ")", ":", "for", "f", "in", "self", ".", "body", ":", "if", "(", "hasattr", "(", "f", ",", "'_ctype'", ")", "and", "isinstance", "(", "f", ".", "_ctype", ",", "FuncType", ")", ")", ":", "yield", "f" ]
generator on all declaration of function
[ "generator", "on", "all", "declaration", "of", "function" ]
b7bb09a70c62fb02c1e41e6280a2a5c0cf2c0f15
https://github.com/LionelAuroux/cnorm/blob/b7bb09a70c62fb02c1e41e6280a2a5c0cf2c0f15/cnorm/nodes.py#L417-L422
239,391
LionelAuroux/cnorm
cnorm/nodes.py
BlockStmt.declallvars
def declallvars(self): """generator on all declaration of variable""" for f in self.body: if (hasattr(f, '_ctype') and not isinstance(f._ctype, FuncType)): yield f
python
def declallvars(self): """generator on all declaration of variable""" for f in self.body: if (hasattr(f, '_ctype') and not isinstance(f._ctype, FuncType)): yield f
[ "def", "declallvars", "(", "self", ")", ":", "for", "f", "in", "self", ".", "body", ":", "if", "(", "hasattr", "(", "f", ",", "'_ctype'", ")", "and", "not", "isinstance", "(", "f", ".", "_ctype", ",", "FuncType", ")", ")", ":", "yield", "f" ]
generator on all declaration of variable
[ "generator", "on", "all", "declaration", "of", "variable" ]
b7bb09a70c62fb02c1e41e6280a2a5c0cf2c0f15
https://github.com/LionelAuroux/cnorm/blob/b7bb09a70c62fb02c1e41e6280a2a5c0cf2c0f15/cnorm/nodes.py#L424-L429
239,392
LionelAuroux/cnorm
cnorm/nodes.py
BlockStmt.declalltypes
def declalltypes(self): """generator on all declaration of type""" for f in self.body: if (hasattr(f, '_ctype') and f._ctype._storage == Storages.TYPEDEF): yield f
python
def declalltypes(self): """generator on all declaration of type""" for f in self.body: if (hasattr(f, '_ctype') and f._ctype._storage == Storages.TYPEDEF): yield f
[ "def", "declalltypes", "(", "self", ")", ":", "for", "f", "in", "self", ".", "body", ":", "if", "(", "hasattr", "(", "f", ",", "'_ctype'", ")", "and", "f", ".", "_ctype", ".", "_storage", "==", "Storages", ".", "TYPEDEF", ")", ":", "yield", "f" ]
generator on all declaration of type
[ "generator", "on", "all", "declaration", "of", "type" ]
b7bb09a70c62fb02c1e41e6280a2a5c0cf2c0f15
https://github.com/LionelAuroux/cnorm/blob/b7bb09a70c62fb02c1e41e6280a2a5c0cf2c0f15/cnorm/nodes.py#L431-L436
239,393
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/actionreportdialog.py
TextPopupButton.show_popup
def show_popup(self, *args, **kwargs): """Show a popup with a textedit :returns: None :rtype: None :raises: None """ self.mw = JB_MainWindow(parent=self, flags=QtCore.Qt.Dialog) self.mw.setWindowTitle(self.popuptitle) self.mw.setWindowModality(QtCore.Qt.ApplicationModal) w = QtGui.QWidget() self.mw.setCentralWidget(w) vbox = QtGui.QVBoxLayout(w) pte = QtGui.QPlainTextEdit() pte.setPlainText(self.get_popup_text()) vbox.addWidget(pte) # move window to cursor position d = self.cursor().pos() - self.mw.mapToGlobal(self.mw.pos()) self.mw.move(d) self.mw.show()
python
def show_popup(self, *args, **kwargs): """Show a popup with a textedit :returns: None :rtype: None :raises: None """ self.mw = JB_MainWindow(parent=self, flags=QtCore.Qt.Dialog) self.mw.setWindowTitle(self.popuptitle) self.mw.setWindowModality(QtCore.Qt.ApplicationModal) w = QtGui.QWidget() self.mw.setCentralWidget(w) vbox = QtGui.QVBoxLayout(w) pte = QtGui.QPlainTextEdit() pte.setPlainText(self.get_popup_text()) vbox.addWidget(pte) # move window to cursor position d = self.cursor().pos() - self.mw.mapToGlobal(self.mw.pos()) self.mw.move(d) self.mw.show()
[ "def", "show_popup", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "mw", "=", "JB_MainWindow", "(", "parent", "=", "self", ",", "flags", "=", "QtCore", ".", "Qt", ".", "Dialog", ")", "self", ".", "mw", ".", "setWindowTitle", "(", "self", ".", "popuptitle", ")", "self", ".", "mw", ".", "setWindowModality", "(", "QtCore", ".", "Qt", ".", "ApplicationModal", ")", "w", "=", "QtGui", ".", "QWidget", "(", ")", "self", ".", "mw", ".", "setCentralWidget", "(", "w", ")", "vbox", "=", "QtGui", ".", "QVBoxLayout", "(", "w", ")", "pte", "=", "QtGui", ".", "QPlainTextEdit", "(", ")", "pte", ".", "setPlainText", "(", "self", ".", "get_popup_text", "(", ")", ")", "vbox", ".", "addWidget", "(", "pte", ")", "# move window to cursor position", "d", "=", "self", ".", "cursor", "(", ")", ".", "pos", "(", ")", "-", "self", ".", "mw", ".", "mapToGlobal", "(", "self", ".", "mw", ".", "pos", "(", ")", ")", "self", ".", "mw", ".", "move", "(", "d", ")", "self", ".", "mw", ".", "show", "(", ")" ]
Show a popup with a textedit :returns: None :rtype: None :raises: None
[ "Show", "a", "popup", "with", "a", "textedit" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/actionreportdialog.py#L36-L55
239,394
ravenac95/overlay4u
overlay4u/__init__.py
mount
def mount(directory, lower_dir, upper_dir, mount_table=None): """Creates a mount""" return OverlayFS.mount(directory, lower_dir, upper_dir, mount_table=mount_table)
python
def mount(directory, lower_dir, upper_dir, mount_table=None): """Creates a mount""" return OverlayFS.mount(directory, lower_dir, upper_dir, mount_table=mount_table)
[ "def", "mount", "(", "directory", ",", "lower_dir", ",", "upper_dir", ",", "mount_table", "=", "None", ")", ":", "return", "OverlayFS", ".", "mount", "(", "directory", ",", "lower_dir", ",", "upper_dir", ",", "mount_table", "=", "mount_table", ")" ]
Creates a mount
[ "Creates", "a", "mount" ]
621eecc0d4d40951aa8afcb533b5eec5d91c73cc
https://github.com/ravenac95/overlay4u/blob/621eecc0d4d40951aa8afcb533b5eec5d91c73cc/overlay4u/__init__.py#L4-L7
239,395
TrainerDex/TrainerDex.py
trainerdex/leaderboard.py
DiscordLeaderboard.filter_teams
def filter_teams(self, teams): """Expects an iterable of team IDs""" return [LeaderboardInstance(x) for x in self._leaderboard if x['faction']['id'] in teams]
python
def filter_teams(self, teams): """Expects an iterable of team IDs""" return [LeaderboardInstance(x) for x in self._leaderboard if x['faction']['id'] in teams]
[ "def", "filter_teams", "(", "self", ",", "teams", ")", ":", "return", "[", "LeaderboardInstance", "(", "x", ")", "for", "x", "in", "self", ".", "_leaderboard", "if", "x", "[", "'faction'", "]", "[", "'id'", "]", "in", "teams", "]" ]
Expects an iterable of team IDs
[ "Expects", "an", "iterable", "of", "team", "IDs" ]
a693e1321abf2825f74bcbf29f0800f0c6835b62
https://github.com/TrainerDex/TrainerDex.py/blob/a693e1321abf2825f74bcbf29f0800f0c6835b62/trainerdex/leaderboard.py#L123-L125
239,396
TrainerDex/TrainerDex.py
trainerdex/leaderboard.py
DiscordLeaderboard.filter_users
def filter_users(self, users): """Expects an interable of User IDs ints""" return [LeaderboardInstance(x) for x in self._leaderboard if x['user_id'] in users]
python
def filter_users(self, users): """Expects an interable of User IDs ints""" return [LeaderboardInstance(x) for x in self._leaderboard if x['user_id'] in users]
[ "def", "filter_users", "(", "self", ",", "users", ")", ":", "return", "[", "LeaderboardInstance", "(", "x", ")", "for", "x", "in", "self", ".", "_leaderboard", "if", "x", "[", "'user_id'", "]", "in", "users", "]" ]
Expects an interable of User IDs ints
[ "Expects", "an", "interable", "of", "User", "IDs", "ints" ]
a693e1321abf2825f74bcbf29f0800f0c6835b62
https://github.com/TrainerDex/TrainerDex.py/blob/a693e1321abf2825f74bcbf29f0800f0c6835b62/trainerdex/leaderboard.py#L127-L129
239,397
TrainerDex/TrainerDex.py
trainerdex/leaderboard.py
DiscordLeaderboard.filter_trainers
def filter_trainers(self, trainers): """Expects an interable of Trainer IDs ints""" return [LeaderboardInstance(x) for x in self._leaderboard if x['id'] in trainers]
python
def filter_trainers(self, trainers): """Expects an interable of Trainer IDs ints""" return [LeaderboardInstance(x) for x in self._leaderboard if x['id'] in trainers]
[ "def", "filter_trainers", "(", "self", ",", "trainers", ")", ":", "return", "[", "LeaderboardInstance", "(", "x", ")", "for", "x", "in", "self", ".", "_leaderboard", "if", "x", "[", "'id'", "]", "in", "trainers", "]" ]
Expects an interable of Trainer IDs ints
[ "Expects", "an", "interable", "of", "Trainer", "IDs", "ints" ]
a693e1321abf2825f74bcbf29f0800f0c6835b62
https://github.com/TrainerDex/TrainerDex.py/blob/a693e1321abf2825f74bcbf29f0800f0c6835b62/trainerdex/leaderboard.py#L131-L133
239,398
willkg/phil
phil/util.py
normalize_path
def normalize_path(path, filetype=FILE): """Takes a path and a filetype, verifies existence and type, and returns absolute path. """ if not path: raise ValueError('"{0}" is not a valid path.'.format(path)) if not os.path.exists(path): raise ValueError('"{0}" does not exist.'.format(path)) if filetype == FILE and not os.path.isfile(path): raise ValueError('"{0}" is not a file.'.format(path)) elif filetype == DIR and not os.path.isdir(path): raise ValueError('"{0}" is not a dir.'.format(path)) return os.path.abspath(path)
python
def normalize_path(path, filetype=FILE): """Takes a path and a filetype, verifies existence and type, and returns absolute path. """ if not path: raise ValueError('"{0}" is not a valid path.'.format(path)) if not os.path.exists(path): raise ValueError('"{0}" does not exist.'.format(path)) if filetype == FILE and not os.path.isfile(path): raise ValueError('"{0}" is not a file.'.format(path)) elif filetype == DIR and not os.path.isdir(path): raise ValueError('"{0}" is not a dir.'.format(path)) return os.path.abspath(path)
[ "def", "normalize_path", "(", "path", ",", "filetype", "=", "FILE", ")", ":", "if", "not", "path", ":", "raise", "ValueError", "(", "'\"{0}\" is not a valid path.'", ".", "format", "(", "path", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "ValueError", "(", "'\"{0}\" does not exist.'", ".", "format", "(", "path", ")", ")", "if", "filetype", "==", "FILE", "and", "not", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "raise", "ValueError", "(", "'\"{0}\" is not a file.'", ".", "format", "(", "path", ")", ")", "elif", "filetype", "==", "DIR", "and", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "raise", "ValueError", "(", "'\"{0}\" is not a dir.'", ".", "format", "(", "path", ")", ")", "return", "os", ".", "path", ".", "abspath", "(", "path", ")" ]
Takes a path and a filetype, verifies existence and type, and returns absolute path.
[ "Takes", "a", "path", "and", "a", "filetype", "verifies", "existence", "and", "type", "and", "returns", "absolute", "path", "." ]
cb7ed0199cca2c405af9d6d209ddbf739a437e9c
https://github.com/willkg/phil/blob/cb7ed0199cca2c405af9d6d209ddbf739a437e9c/phil/util.py#L49-L63
239,399
willkg/phil
phil/util.py
err
def err(*output, **kwargs): """Writes output to stderr. :arg wrap: If you set ``wrap=False``, then ``err`` won't textwrap the output. """ output = 'Error: ' + ' '.join([str(o) for o in output]) if kwargs.get('wrap') is not False: output = '\n'.join(wrap(output, kwargs.get('indent', ''))) elif kwargs.get('indent'): indent = kwargs['indent'] output = indent + ('\n' + indent).join(output.splitlines()) sys.stderr.write(output + '\n')
python
def err(*output, **kwargs): """Writes output to stderr. :arg wrap: If you set ``wrap=False``, then ``err`` won't textwrap the output. """ output = 'Error: ' + ' '.join([str(o) for o in output]) if kwargs.get('wrap') is not False: output = '\n'.join(wrap(output, kwargs.get('indent', ''))) elif kwargs.get('indent'): indent = kwargs['indent'] output = indent + ('\n' + indent).join(output.splitlines()) sys.stderr.write(output + '\n')
[ "def", "err", "(", "*", "output", ",", "*", "*", "kwargs", ")", ":", "output", "=", "'Error: '", "+", "' '", ".", "join", "(", "[", "str", "(", "o", ")", "for", "o", "in", "output", "]", ")", "if", "kwargs", ".", "get", "(", "'wrap'", ")", "is", "not", "False", ":", "output", "=", "'\\n'", ".", "join", "(", "wrap", "(", "output", ",", "kwargs", ".", "get", "(", "'indent'", ",", "''", ")", ")", ")", "elif", "kwargs", ".", "get", "(", "'indent'", ")", ":", "indent", "=", "kwargs", "[", "'indent'", "]", "output", "=", "indent", "+", "(", "'\\n'", "+", "indent", ")", ".", "join", "(", "output", ".", "splitlines", "(", ")", ")", "sys", ".", "stderr", ".", "write", "(", "output", "+", "'\\n'", ")" ]
Writes output to stderr. :arg wrap: If you set ``wrap=False``, then ``err`` won't textwrap the output.
[ "Writes", "output", "to", "stderr", "." ]
cb7ed0199cca2c405af9d6d209ddbf739a437e9c
https://github.com/willkg/phil/blob/cb7ed0199cca2c405af9d6d209ddbf739a437e9c/phil/util.py#L77-L90