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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
jurismarches/chopper
chopper/html/extractor.py
HTMLExtractor._has_keep_elt_in_descendants
def _has_keep_elt_in_descendants(self, elt): """ Returns whether the element has a descendant to keep or not :param elt: The HtmlElement to check :type elt: lxml.html.HtmlElement :returns: True if the element has a keep element in its descendants :rtype: bool """ # iterdescendants is a generator, don't cast it as a list to avoid # parsing the whole descendants tree if not necessary for d in elt.iterdescendants(): if d in self.elts_to_keep: return True return False
python
def _has_keep_elt_in_descendants(self, elt): """ Returns whether the element has a descendant to keep or not :param elt: The HtmlElement to check :type elt: lxml.html.HtmlElement :returns: True if the element has a keep element in its descendants :rtype: bool """ # iterdescendants is a generator, don't cast it as a list to avoid # parsing the whole descendants tree if not necessary for d in elt.iterdescendants(): if d in self.elts_to_keep: return True return False
[ "def", "_has_keep_elt_in_descendants", "(", "self", ",", "elt", ")", ":", "# iterdescendants is a generator, don't cast it as a list to avoid", "# parsing the whole descendants tree if not necessary", "for", "d", "in", "elt", ".", "iterdescendants", "(", ")", ":", "if", "d", ...
Returns whether the element has a descendant to keep or not :param elt: The HtmlElement to check :type elt: lxml.html.HtmlElement :returns: True if the element has a keep element in its descendants :rtype: bool
[ "Returns", "whether", "the", "element", "has", "a", "descendant", "to", "keep", "or", "not" ]
53c5489a53e3a5d205a5cb207df751c09633e7ce
https://github.com/jurismarches/chopper/blob/53c5489a53e3a5d205a5cb207df751c09633e7ce/chopper/html/extractor.py#L195-L210
train
51,400
jurismarches/chopper
chopper/html/extractor.py
HTMLExtractor._remove_elements
def _remove_elements(self, elts_to_remove): """ Removes flagged elements from the ElementTree """ for e in elts_to_remove: # Get the element parent parent = e.getparent() # lxml also remove the element tail, preserve it if e.tail and e.tail.strip(): parent_text = parent.text or '' parent.text = parent_text + e.tail # Remove the element e.getparent().remove(e)
python
def _remove_elements(self, elts_to_remove): """ Removes flagged elements from the ElementTree """ for e in elts_to_remove: # Get the element parent parent = e.getparent() # lxml also remove the element tail, preserve it if e.tail and e.tail.strip(): parent_text = parent.text or '' parent.text = parent_text + e.tail # Remove the element e.getparent().remove(e)
[ "def", "_remove_elements", "(", "self", ",", "elts_to_remove", ")", ":", "for", "e", "in", "elts_to_remove", ":", "# Get the element parent", "parent", "=", "e", ".", "getparent", "(", ")", "# lxml also remove the element tail, preserve it", "if", "e", ".", "tail", ...
Removes flagged elements from the ElementTree
[ "Removes", "flagged", "elements", "from", "the", "ElementTree" ]
53c5489a53e3a5d205a5cb207df751c09633e7ce
https://github.com/jurismarches/chopper/blob/53c5489a53e3a5d205a5cb207df751c09633e7ce/chopper/html/extractor.py#L212-L227
train
51,401
bpannier/simpletr64
simpletr64/actions/system.py
System.getSystemInfo
def getSystemInfo(self, timeout=1): """Execute GetInfo action to get information's about the System on the device. :return: information's about the System on the device. :rtype: SystemInfo """ namespace = System.getServiceType("getSystemInfo") uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetInfo", timeout=timeout) return SystemInfo(results)
python
def getSystemInfo(self, timeout=1): """Execute GetInfo action to get information's about the System on the device. :return: information's about the System on the device. :rtype: SystemInfo """ namespace = System.getServiceType("getSystemInfo") uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetInfo", timeout=timeout) return SystemInfo(results)
[ "def", "getSystemInfo", "(", "self", ",", "timeout", "=", "1", ")", ":", "namespace", "=", "System", ".", "getServiceType", "(", "\"getSystemInfo\"", ")", "uri", "=", "self", ".", "getControlURL", "(", "namespace", ")", "results", "=", "self", ".", "execut...
Execute GetInfo action to get information's about the System on the device. :return: information's about the System on the device. :rtype: SystemInfo
[ "Execute", "GetInfo", "action", "to", "get", "information", "s", "about", "the", "System", "on", "the", "device", "." ]
31081139f4e6c85084a56de1617df73927135466
https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/system.py#L86-L97
train
51,402
bpannier/simpletr64
simpletr64/actions/system.py
System.reboot
def reboot(self, timeout=1): """Reboot the device""" namespace = System.getServiceType("reboot") uri = self.getControlURL(namespace) self.execute(uri, namespace, "Reboot", timeout=timeout)
python
def reboot(self, timeout=1): """Reboot the device""" namespace = System.getServiceType("reboot") uri = self.getControlURL(namespace) self.execute(uri, namespace, "Reboot", timeout=timeout)
[ "def", "reboot", "(", "self", ",", "timeout", "=", "1", ")", ":", "namespace", "=", "System", ".", "getServiceType", "(", "\"reboot\"", ")", "uri", "=", "self", ".", "getControlURL", "(", "namespace", ")", "self", ".", "execute", "(", "uri", ",", "name...
Reboot the device
[ "Reboot", "the", "device" ]
31081139f4e6c85084a56de1617df73927135466
https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/system.py#L99-L104
train
51,403
bpannier/simpletr64
simpletr64/actions/system.py
System.getTimeInfo
def getTimeInfo(self, timeout=1): """Execute GetInfo action to get information's about the time on the device. :return: information's about the time on the device. :rtype: TimeInfo """ namespace = System.getServiceType("getTimeInfo") uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetInfo", timeout=timeout) return TimeInfo(results)
python
def getTimeInfo(self, timeout=1): """Execute GetInfo action to get information's about the time on the device. :return: information's about the time on the device. :rtype: TimeInfo """ namespace = System.getServiceType("getTimeInfo") uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetInfo", timeout=timeout) return TimeInfo(results)
[ "def", "getTimeInfo", "(", "self", ",", "timeout", "=", "1", ")", ":", "namespace", "=", "System", ".", "getServiceType", "(", "\"getTimeInfo\"", ")", "uri", "=", "self", ".", "getControlURL", "(", "namespace", ")", "results", "=", "self", ".", "execute", ...
Execute GetInfo action to get information's about the time on the device. :return: information's about the time on the device. :rtype: TimeInfo
[ "Execute", "GetInfo", "action", "to", "get", "information", "s", "about", "the", "time", "on", "the", "device", "." ]
31081139f4e6c85084a56de1617df73927135466
https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/system.py#L106-L117
train
51,404
bpannier/simpletr64
simpletr64/actions/system.py
System.softwareUpdateAvailable
def softwareUpdateAvailable(self, timeout=1): """Returns if a software update is available :return: if a software update is available :rtype: bool """ namespace = System.getServiceType("softwareUpdateAvailable") uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetInfo", timeout=timeout) return bool(int(results["NewUpgradeAvailable"]))
python
def softwareUpdateAvailable(self, timeout=1): """Returns if a software update is available :return: if a software update is available :rtype: bool """ namespace = System.getServiceType("softwareUpdateAvailable") uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetInfo", timeout=timeout) return bool(int(results["NewUpgradeAvailable"]))
[ "def", "softwareUpdateAvailable", "(", "self", ",", "timeout", "=", "1", ")", ":", "namespace", "=", "System", ".", "getServiceType", "(", "\"softwareUpdateAvailable\"", ")", "uri", "=", "self", ".", "getControlURL", "(", "namespace", ")", "results", "=", "sel...
Returns if a software update is available :return: if a software update is available :rtype: bool
[ "Returns", "if", "a", "software", "update", "is", "available" ]
31081139f4e6c85084a56de1617df73927135466
https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/system.py#L119-L130
train
51,405
PlaidWeb/Pushl
pushl/caching.py
make_headers
def make_headers(headers): """ Make the cache control headers based on a previous request's response headers """ out = {} if 'etag' in headers: out['if-none-match'] = headers['etag'] if 'last-modified' in headers: out['if-modified-since'] = headers['last-modified'] return out
python
def make_headers(headers): """ Make the cache control headers based on a previous request's response headers """ out = {} if 'etag' in headers: out['if-none-match'] = headers['etag'] if 'last-modified' in headers: out['if-modified-since'] = headers['last-modified'] return out
[ "def", "make_headers", "(", "headers", ")", ":", "out", "=", "{", "}", "if", "'etag'", "in", "headers", ":", "out", "[", "'if-none-match'", "]", "=", "headers", "[", "'etag'", "]", "if", "'last-modified'", "in", "headers", ":", "out", "[", "'if-modified-...
Make the cache control headers based on a previous request's response headers
[ "Make", "the", "cache", "control", "headers", "based", "on", "a", "previous", "request", "s", "response", "headers" ]
5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c
https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/caching.py#L69-L78
train
51,406
PlaidWeb/Pushl
pushl/caching.py
Cache.get
def get(self, prefix, url, schema_version=None): """ Get the cached object """ if not self.cache_dir: return None filename = self._get_cache_file(prefix, url) try: with open(filename, 'rb') as file: item = pickle.load(file) if schema_version and schema_version != item.schema: LOGGER.debug("Cache get %s %s: Wanted schema %d, got %d", prefix, url, schema_version, item.schema) return None return item except FileNotFoundError: pass except Exception: # pylint:disable=broad-except _, msg, _ = sys.exc_info() LOGGER.warning("Cache get %s %s failed: %s", prefix, url, msg) return None
python
def get(self, prefix, url, schema_version=None): """ Get the cached object """ if not self.cache_dir: return None filename = self._get_cache_file(prefix, url) try: with open(filename, 'rb') as file: item = pickle.load(file) if schema_version and schema_version != item.schema: LOGGER.debug("Cache get %s %s: Wanted schema %d, got %d", prefix, url, schema_version, item.schema) return None return item except FileNotFoundError: pass except Exception: # pylint:disable=broad-except _, msg, _ = sys.exc_info() LOGGER.warning("Cache get %s %s failed: %s", prefix, url, msg) return None
[ "def", "get", "(", "self", ",", "prefix", ",", "url", ",", "schema_version", "=", "None", ")", ":", "if", "not", "self", ".", "cache_dir", ":", "return", "None", "filename", "=", "self", ".", "_get_cache_file", "(", "prefix", ",", "url", ")", "try", ...
Get the cached object
[ "Get", "the", "cached", "object" ]
5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c
https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/caching.py#L29-L51
train
51,407
PlaidWeb/Pushl
pushl/caching.py
Cache.set
def set(self, prefix, url, obj): """ Add an object into the cache """ if not self.cache_dir: return filename = self._get_cache_file(prefix, url) try: os.makedirs(os.path.join(self.cache_dir, prefix)) except OSError: pass with open(filename, 'wb') as file: pickle.dump(obj, file)
python
def set(self, prefix, url, obj): """ Add an object into the cache """ if not self.cache_dir: return filename = self._get_cache_file(prefix, url) try: os.makedirs(os.path.join(self.cache_dir, prefix)) except OSError: pass with open(filename, 'wb') as file: pickle.dump(obj, file)
[ "def", "set", "(", "self", ",", "prefix", ",", "url", ",", "obj", ")", ":", "if", "not", "self", ".", "cache_dir", ":", "return", "filename", "=", "self", ".", "_get_cache_file", "(", "prefix", ",", "url", ")", "try", ":", "os", ".", "makedirs", "(...
Add an object into the cache
[ "Add", "an", "object", "into", "the", "cache" ]
5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c
https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/caching.py#L53-L66
train
51,408
mjirik/io3d
io3d/datasets.py
dataset_path
def dataset_path(cache=None, cachefile="~/.io3d_cache.yaml", get_root=False): """Get dataset path. :param cache: CacheFile object :param cachefile: cachefile path, default '~/.io3d_cache.yaml' :return: path to dataset """ local_data_dir = local_dir if cachefile is not None: cache = cachef.CacheFile(cachefile) # cache.update('local_dataset_dir', head) if cache is not None: local_data_dir = cache.get_or_save_default("local_dataset_dir", local_dir) if get_root: local_data_dir else: logger.warning("Parameter") local_data_dir = op.join(local_data_dir, "medical", "orig") return op.expanduser(local_data_dir)
python
def dataset_path(cache=None, cachefile="~/.io3d_cache.yaml", get_root=False): """Get dataset path. :param cache: CacheFile object :param cachefile: cachefile path, default '~/.io3d_cache.yaml' :return: path to dataset """ local_data_dir = local_dir if cachefile is not None: cache = cachef.CacheFile(cachefile) # cache.update('local_dataset_dir', head) if cache is not None: local_data_dir = cache.get_or_save_default("local_dataset_dir", local_dir) if get_root: local_data_dir else: logger.warning("Parameter") local_data_dir = op.join(local_data_dir, "medical", "orig") return op.expanduser(local_data_dir)
[ "def", "dataset_path", "(", "cache", "=", "None", ",", "cachefile", "=", "\"~/.io3d_cache.yaml\"", ",", "get_root", "=", "False", ")", ":", "local_data_dir", "=", "local_dir", "if", "cachefile", "is", "not", "None", ":", "cache", "=", "cachef", ".", "CacheFi...
Get dataset path. :param cache: CacheFile object :param cachefile: cachefile path, default '~/.io3d_cache.yaml' :return: path to dataset
[ "Get", "dataset", "path", "." ]
ccaf3e378dcc967f2565d477fc27583fd0f61fcc
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L211-L232
train
51,409
mjirik/io3d
io3d/datasets.py
get_dataset_meta
def get_dataset_meta(label): """Gives you metadata for dataset chosen via 'label' param :param label: label = key in data_url dict (that big dict containing all possible datasets) :return: tuple (data_url, url, expected_hash, hash_path, relative_download_dir) relative_download_dir says where will be downloaded the file from url and eventually unzipped """ data_url = data_urls[label] if type(data_url) == str: # back compatibility data_url = [data_url] if type(data_url) == list: data_url.extend([None, None, None, None]) data_url = data_url[:4] url, expected_hash, hash_path, relative_donwload_dir = data_url if hash_path is None: hash_path = label # elif type(data_url) == dict: return data_url, url, expected_hash, hash_path, relative_donwload_dir
python
def get_dataset_meta(label): """Gives you metadata for dataset chosen via 'label' param :param label: label = key in data_url dict (that big dict containing all possible datasets) :return: tuple (data_url, url, expected_hash, hash_path, relative_download_dir) relative_download_dir says where will be downloaded the file from url and eventually unzipped """ data_url = data_urls[label] if type(data_url) == str: # back compatibility data_url = [data_url] if type(data_url) == list: data_url.extend([None, None, None, None]) data_url = data_url[:4] url, expected_hash, hash_path, relative_donwload_dir = data_url if hash_path is None: hash_path = label # elif type(data_url) == dict: return data_url, url, expected_hash, hash_path, relative_donwload_dir
[ "def", "get_dataset_meta", "(", "label", ")", ":", "data_url", "=", "data_urls", "[", "label", "]", "if", "type", "(", "data_url", ")", "==", "str", ":", "# back compatibility", "data_url", "=", "[", "data_url", "]", "if", "type", "(", "data_url", ")", "...
Gives you metadata for dataset chosen via 'label' param :param label: label = key in data_url dict (that big dict containing all possible datasets) :return: tuple (data_url, url, expected_hash, hash_path, relative_download_dir) relative_download_dir says where will be downloaded the file from url and eventually unzipped
[ "Gives", "you", "metadata", "for", "dataset", "chosen", "via", "label", "param" ]
ccaf3e378dcc967f2565d477fc27583fd0f61fcc
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L241-L260
train
51,410
mjirik/io3d
io3d/datasets.py
_expand_dataset_packages
def _expand_dataset_packages(dataset_label_dict): """Returns list of possible packages contained in dataset, in case the dataset is multi dataset, eg. 'lisa'. In case the param is not pointing to multidataset returns only that label in a list. :param str dataset_label_dict: label of multi dataset :return: list of labels """ new_dataset_label_dict = [] for label in dataset_label_dict: dataset_metadata = data_urls[label] if type(dataset_metadata) == dict and "package" in dataset_metadata: new_dataset_label_dict.extend(dataset_metadata["package"]) else: new_dataset_label_dict.append(label) return new_dataset_label_dict
python
def _expand_dataset_packages(dataset_label_dict): """Returns list of possible packages contained in dataset, in case the dataset is multi dataset, eg. 'lisa'. In case the param is not pointing to multidataset returns only that label in a list. :param str dataset_label_dict: label of multi dataset :return: list of labels """ new_dataset_label_dict = [] for label in dataset_label_dict: dataset_metadata = data_urls[label] if type(dataset_metadata) == dict and "package" in dataset_metadata: new_dataset_label_dict.extend(dataset_metadata["package"]) else: new_dataset_label_dict.append(label) return new_dataset_label_dict
[ "def", "_expand_dataset_packages", "(", "dataset_label_dict", ")", ":", "new_dataset_label_dict", "=", "[", "]", "for", "label", "in", "dataset_label_dict", ":", "dataset_metadata", "=", "data_urls", "[", "label", "]", "if", "type", "(", "dataset_metadata", ")", "...
Returns list of possible packages contained in dataset, in case the dataset is multi dataset, eg. 'lisa'. In case the param is not pointing to multidataset returns only that label in a list. :param str dataset_label_dict: label of multi dataset :return: list of labels
[ "Returns", "list", "of", "possible", "packages", "contained", "in", "dataset", "in", "case", "the", "dataset", "is", "multi", "dataset", "eg", ".", "lisa", "." ]
ccaf3e378dcc967f2565d477fc27583fd0f61fcc
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L264-L279
train
51,411
mjirik/io3d
io3d/datasets.py
get_old
def get_old(dataset_label, data_id, destination_dir=None): """Get the 3D data from specified dataset with specified id. Download data if necessary. :param dataset_label: :param data_id: integer or wildcards file pattern :param destination_dir: :return: """ # TODO implement if destination_dir is None: destination_dir = op.join(dataset_path(get_root=True), "medical", "orig") destination_dir = op.expanduser(destination_dir) data_url, url, expected_hash, hash_path, relative_output_path = get_dataset_meta( dataset_label ) paths = glob.glob(os.path.join(destination_dir, hash_path)) paths.sort() import fnmatch print(paths) print(data_id) pathsf = fnmatch.filter(paths, data_id) print(pathsf) datap = io3d.read(pathsf[0], dataplus_format=True) return datap
python
def get_old(dataset_label, data_id, destination_dir=None): """Get the 3D data from specified dataset with specified id. Download data if necessary. :param dataset_label: :param data_id: integer or wildcards file pattern :param destination_dir: :return: """ # TODO implement if destination_dir is None: destination_dir = op.join(dataset_path(get_root=True), "medical", "orig") destination_dir = op.expanduser(destination_dir) data_url, url, expected_hash, hash_path, relative_output_path = get_dataset_meta( dataset_label ) paths = glob.glob(os.path.join(destination_dir, hash_path)) paths.sort() import fnmatch print(paths) print(data_id) pathsf = fnmatch.filter(paths, data_id) print(pathsf) datap = io3d.read(pathsf[0], dataplus_format=True) return datap
[ "def", "get_old", "(", "dataset_label", ",", "data_id", ",", "destination_dir", "=", "None", ")", ":", "# TODO implement", "if", "destination_dir", "is", "None", ":", "destination_dir", "=", "op", ".", "join", "(", "dataset_path", "(", "get_root", "=", "True",...
Get the 3D data from specified dataset with specified id. Download data if necessary. :param dataset_label: :param data_id: integer or wildcards file pattern :param destination_dir: :return:
[ "Get", "the", "3D", "data", "from", "specified", "dataset", "with", "specified", "id", "." ]
ccaf3e378dcc967f2565d477fc27583fd0f61fcc
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L360-L387
train
51,412
mjirik/io3d
io3d/datasets.py
checksum
def checksum(path, hashfunc="md5"): """Return checksum of files given by path. Wildcards can be used in check sum. Function is strongly dependent on checksumdir package by 'cakepietoast'. :param path: path of files to get hash from :param hashfunc: function used to get hash, default 'md5' :return: (str) hash of the file/files given by path """ import checksumdir hash_func = checksumdir.HASH_FUNCS.get(hashfunc) if not hash_func: raise NotImplementedError("{} not implemented.".format(hashfunc)) if os.path.isdir(path): return checksumdir.dirhash(path, hashfunc=hashfunc) hashvalues = [] path_list = list(sorted(glob.glob(path))) logger.debug("path_list: len: %i", len(path_list)) if len(path_list) > 0: logger.debug("first ... last: %s ... %s", str(path_list[0]), str(path_list[-1])) for path in path_list: if os.path.isfile(path): hashvalues.append(checksumdir._filehash(path, hashfunc=hash_func)) logger.debug("one hash per file: len: %i", len(hashvalues)) if len(path_list) > 0: logger.debug("first ... last: %s ... %s", str(hashvalues[0]), str(hashvalues[-1])) checksum_hash = checksumdir._reduce_hash(hashvalues, hashfunc=hash_func) logger.debug("total hash: {}".format(str(checksum_hash))) return checksum_hash
python
def checksum(path, hashfunc="md5"): """Return checksum of files given by path. Wildcards can be used in check sum. Function is strongly dependent on checksumdir package by 'cakepietoast'. :param path: path of files to get hash from :param hashfunc: function used to get hash, default 'md5' :return: (str) hash of the file/files given by path """ import checksumdir hash_func = checksumdir.HASH_FUNCS.get(hashfunc) if not hash_func: raise NotImplementedError("{} not implemented.".format(hashfunc)) if os.path.isdir(path): return checksumdir.dirhash(path, hashfunc=hashfunc) hashvalues = [] path_list = list(sorted(glob.glob(path))) logger.debug("path_list: len: %i", len(path_list)) if len(path_list) > 0: logger.debug("first ... last: %s ... %s", str(path_list[0]), str(path_list[-1])) for path in path_list: if os.path.isfile(path): hashvalues.append(checksumdir._filehash(path, hashfunc=hash_func)) logger.debug("one hash per file: len: %i", len(hashvalues)) if len(path_list) > 0: logger.debug("first ... last: %s ... %s", str(hashvalues[0]), str(hashvalues[-1])) checksum_hash = checksumdir._reduce_hash(hashvalues, hashfunc=hash_func) logger.debug("total hash: {}".format(str(checksum_hash))) return checksum_hash
[ "def", "checksum", "(", "path", ",", "hashfunc", "=", "\"md5\"", ")", ":", "import", "checksumdir", "hash_func", "=", "checksumdir", ".", "HASH_FUNCS", ".", "get", "(", "hashfunc", ")", "if", "not", "hash_func", ":", "raise", "NotImplementedError", "(", "\"{...
Return checksum of files given by path. Wildcards can be used in check sum. Function is strongly dependent on checksumdir package by 'cakepietoast'. :param path: path of files to get hash from :param hashfunc: function used to get hash, default 'md5' :return: (str) hash of the file/files given by path
[ "Return", "checksum", "of", "files", "given", "by", "path", "." ]
ccaf3e378dcc967f2565d477fc27583fd0f61fcc
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L415-L447
train
51,413
mjirik/io3d
io3d/datasets.py
generate_face
def generate_face(shape=None, face_r=1.0, smile_r1=0.5, smile_r2=0.7, eye_r=0.2): """ Create 2D or 3D binar data with smile face. :param shape: 2D or 3D shape of data :param face_r: :param smile_r1: :param smile_r2: :param eye_r: :return: binar ndarray """ # TODO add axis (ax=0) if shape is None: shape = [32, 32] nd = len(shape) if nd == 2: sh2 = shape else: sh2 = shape[1:] fc2 = _get_face2( sh2, face_r=face_r, smile_r1=smile_r1, smile_r2=smile_r2, eye_r=eye_r ) if nd == 2: return fc2 else: fc3 = np.zeros(shape) for i in range(fc3.shape[0]): fc3[i, :, :] = fc2 return fc3
python
def generate_face(shape=None, face_r=1.0, smile_r1=0.5, smile_r2=0.7, eye_r=0.2): """ Create 2D or 3D binar data with smile face. :param shape: 2D or 3D shape of data :param face_r: :param smile_r1: :param smile_r2: :param eye_r: :return: binar ndarray """ # TODO add axis (ax=0) if shape is None: shape = [32, 32] nd = len(shape) if nd == 2: sh2 = shape else: sh2 = shape[1:] fc2 = _get_face2( sh2, face_r=face_r, smile_r1=smile_r1, smile_r2=smile_r2, eye_r=eye_r ) if nd == 2: return fc2 else: fc3 = np.zeros(shape) for i in range(fc3.shape[0]): fc3[i, :, :] = fc2 return fc3
[ "def", "generate_face", "(", "shape", "=", "None", ",", "face_r", "=", "1.0", ",", "smile_r1", "=", "0.5", ",", "smile_r2", "=", "0.7", ",", "eye_r", "=", "0.2", ")", ":", "# TODO add axis (ax=0)", "if", "shape", "is", "None", ":", "shape", "=", "[", ...
Create 2D or 3D binar data with smile face. :param shape: 2D or 3D shape of data :param face_r: :param smile_r1: :param smile_r2: :param eye_r: :return: binar ndarray
[ "Create", "2D", "or", "3D", "binar", "data", "with", "smile", "face", "." ]
ccaf3e378dcc967f2565d477fc27583fd0f61fcc
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L669-L698
train
51,414
mjirik/io3d
io3d/datasets.py
remove
def remove(local_file_name): """Function attempts to remove file, if failure occures -> print exception :param local_file_name: name of file to remove """ try: os.remove(local_file_name) except Exception as e: print( "Cannot remove file '" + local_file_name + "'. Please remove it manually." ) print(e)
python
def remove(local_file_name): """Function attempts to remove file, if failure occures -> print exception :param local_file_name: name of file to remove """ try: os.remove(local_file_name) except Exception as e: print( "Cannot remove file '" + local_file_name + "'. Please remove it manually." ) print(e)
[ "def", "remove", "(", "local_file_name", ")", ":", "try", ":", "os", ".", "remove", "(", "local_file_name", ")", "except", "Exception", "as", "e", ":", "print", "(", "\"Cannot remove file '\"", "+", "local_file_name", "+", "\"'. Please remove it manually.\"", ")",...
Function attempts to remove file, if failure occures -> print exception :param local_file_name: name of file to remove
[ "Function", "attempts", "to", "remove", "file", "if", "failure", "occures", "-", ">", "print", "exception" ]
ccaf3e378dcc967f2565d477fc27583fd0f61fcc
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L741-L752
train
51,415
mjirik/io3d
io3d/datasets.py
unzip_recursive
def unzip_recursive(zip_file_name): """Unzip file with all recursive zip files inside and delete zip files after that. :param zip_file_name: file name of zip file :return: list of archive members by name. """ logger.debug("unzipping " + zip_file_name) fnlist = unzip_one(zip_file_name) for fn in fnlist: if zipfile.is_zipfile(fn): local_fnlist = unzip_recursive(fn) fnlist.extend(local_fnlist) return fnlist
python
def unzip_recursive(zip_file_name): """Unzip file with all recursive zip files inside and delete zip files after that. :param zip_file_name: file name of zip file :return: list of archive members by name. """ logger.debug("unzipping " + zip_file_name) fnlist = unzip_one(zip_file_name) for fn in fnlist: if zipfile.is_zipfile(fn): local_fnlist = unzip_recursive(fn) fnlist.extend(local_fnlist) return fnlist
[ "def", "unzip_recursive", "(", "zip_file_name", ")", ":", "logger", ".", "debug", "(", "\"unzipping \"", "+", "zip_file_name", ")", "fnlist", "=", "unzip_one", "(", "zip_file_name", ")", "for", "fn", "in", "fnlist", ":", "if", "zipfile", ".", "is_zipfile", "...
Unzip file with all recursive zip files inside and delete zip files after that. :param zip_file_name: file name of zip file :return: list of archive members by name.
[ "Unzip", "file", "with", "all", "recursive", "zip", "files", "inside", "and", "delete", "zip", "files", "after", "that", "." ]
ccaf3e378dcc967f2565d477fc27583fd0f61fcc
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L821-L833
train
51,416
vsoch/helpme
helpme/action/submit.py
upload_asciinema
def upload_asciinema(filename): '''a wrapper around generation of an asciinema.api.Api to call the upload command given an already existing asciinema file. Parameters ========== filename: the asciinema file to upload, can be generated with function record_asciinema in record.py ''' if os.path.exists(filename): import asciinema.config as aconfig from asciinema.api import Api # Load the API class cfg = aconfig.load() api = Api(cfg.api_url, os.environ.get("USER"), cfg.install_id) # Perform the upload, return the url uploader = UploadCommand(api, filename) try: url, warn = uploader.api.upload_asciicast(filename) if warn: uploader.print_warning(warn) # Extract just the url, if provided (always is https) if url: match = re.search('https://.+', url) if match: url = match.group() return url except: bot.error('Problem with upload, skipping') else: bot.warning('Cannot find %s, skipping submission.' %filename)
python
def upload_asciinema(filename): '''a wrapper around generation of an asciinema.api.Api to call the upload command given an already existing asciinema file. Parameters ========== filename: the asciinema file to upload, can be generated with function record_asciinema in record.py ''' if os.path.exists(filename): import asciinema.config as aconfig from asciinema.api import Api # Load the API class cfg = aconfig.load() api = Api(cfg.api_url, os.environ.get("USER"), cfg.install_id) # Perform the upload, return the url uploader = UploadCommand(api, filename) try: url, warn = uploader.api.upload_asciicast(filename) if warn: uploader.print_warning(warn) # Extract just the url, if provided (always is https) if url: match = re.search('https://.+', url) if match: url = match.group() return url except: bot.error('Problem with upload, skipping') else: bot.warning('Cannot find %s, skipping submission.' %filename)
[ "def", "upload_asciinema", "(", "filename", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "import", "asciinema", ".", "config", "as", "aconfig", "from", "asciinema", ".", "api", "import", "Api", "# Load the API class", "cfg", ...
a wrapper around generation of an asciinema.api.Api to call the upload command given an already existing asciinema file. Parameters ========== filename: the asciinema file to upload, can be generated with function record_asciinema in record.py
[ "a", "wrapper", "around", "generation", "of", "an", "asciinema", ".", "api", ".", "Api", "to", "call", "the", "upload", "command", "given", "an", "already", "existing", "asciinema", "file", "." ]
e609172260b10cddadb2d2023ab26da8082a9feb
https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/action/submit.py#L24-L64
train
51,417
tonyseek/flask-docker
flask_docker.py
make_tls_config
def make_tls_config(app_config): """Creates TLS configuration object.""" if not app_config['DOCKER_TLS']: return False cert_path = app_config['DOCKER_TLS_CERT_PATH'] if cert_path: client_cert = '{0}:{1}'.format( os.path.join(cert_path, 'cert.pem'), os.path.join(cert_path, 'key.pem')) ca_cert = os.path.join(cert_path, 'ca.pem') else: client_cert = app_config['DOCKER_TLS_CLIENT_CERT'] ca_cert = app_config['DOCKER_TLS_CA_CERT'] client_cert = parse_client_cert_pair(client_cert) return TLSConfig( client_cert=client_cert, ca_cert=ca_cert, verify=app_config['DOCKER_TLS_VERIFY'], ssl_version=app_config['DOCKER_TLS_SSL_VERSION'], assert_hostname=app_config['DOCKER_TLS_ASSERT_HOSTNAME'])
python
def make_tls_config(app_config): """Creates TLS configuration object.""" if not app_config['DOCKER_TLS']: return False cert_path = app_config['DOCKER_TLS_CERT_PATH'] if cert_path: client_cert = '{0}:{1}'.format( os.path.join(cert_path, 'cert.pem'), os.path.join(cert_path, 'key.pem')) ca_cert = os.path.join(cert_path, 'ca.pem') else: client_cert = app_config['DOCKER_TLS_CLIENT_CERT'] ca_cert = app_config['DOCKER_TLS_CA_CERT'] client_cert = parse_client_cert_pair(client_cert) return TLSConfig( client_cert=client_cert, ca_cert=ca_cert, verify=app_config['DOCKER_TLS_VERIFY'], ssl_version=app_config['DOCKER_TLS_SSL_VERSION'], assert_hostname=app_config['DOCKER_TLS_ASSERT_HOSTNAME'])
[ "def", "make_tls_config", "(", "app_config", ")", ":", "if", "not", "app_config", "[", "'DOCKER_TLS'", "]", ":", "return", "False", "cert_path", "=", "app_config", "[", "'DOCKER_TLS_CERT_PATH'", "]", "if", "cert_path", ":", "client_cert", "=", "'{0}:{1}'", ".", ...
Creates TLS configuration object.
[ "Creates", "TLS", "configuration", "object", "." ]
bbc7faa72d0bb08fcd17f336abc210bb71f1e34e
https://github.com/tonyseek/flask-docker/blob/bbc7faa72d0bb08fcd17f336abc210bb71f1e34e/flask_docker.py#L71-L93
train
51,418
tonyseek/flask-docker
flask_docker.py
parse_client_cert_pair
def parse_client_cert_pair(config_value): """Parses the client cert pair from config item. :param config_value: the string value of config item. :returns: tuple or none. """ if not config_value: return client_cert = config_value.split(':') if len(client_cert) != 2: tips = ('client_cert should be formatted like ' '"/path/to/cert.pem:/path/to/key.pem"') raise ValueError('{0!r} is invalid.\n{1}'.format(config_value, tips)) return tuple(client_cert)
python
def parse_client_cert_pair(config_value): """Parses the client cert pair from config item. :param config_value: the string value of config item. :returns: tuple or none. """ if not config_value: return client_cert = config_value.split(':') if len(client_cert) != 2: tips = ('client_cert should be formatted like ' '"/path/to/cert.pem:/path/to/key.pem"') raise ValueError('{0!r} is invalid.\n{1}'.format(config_value, tips)) return tuple(client_cert)
[ "def", "parse_client_cert_pair", "(", "config_value", ")", ":", "if", "not", "config_value", ":", "return", "client_cert", "=", "config_value", ".", "split", "(", "':'", ")", "if", "len", "(", "client_cert", ")", "!=", "2", ":", "tips", "=", "(", "'client_...
Parses the client cert pair from config item. :param config_value: the string value of config item. :returns: tuple or none.
[ "Parses", "the", "client", "cert", "pair", "from", "config", "item", "." ]
bbc7faa72d0bb08fcd17f336abc210bb71f1e34e
https://github.com/tonyseek/flask-docker/blob/bbc7faa72d0bb08fcd17f336abc210bb71f1e34e/flask_docker.py#L96-L109
train
51,419
PlaidWeb/Pushl
pushl/__init__.py
Pushl.process_feed
async def process_feed(self, url, send_mentions=True): """ process a feed """ self._feed_domains.add(utils.get_domain(url)) if url in self._processed_feeds: LOGGER.debug("Skipping already processed feed %s", url) return self._processed_feeds.add(url) LOGGER.debug("++WAIT: %s: get feed", url) feed, previous, updated = await feeds.get_feed(self, url) LOGGER.debug("++DONE: %s: get feed", url) if updated: LOGGER.info("Feed %s has been updated", url) if not feed: return LOGGER.debug("--- starting process_feed %s %s", url, send_mentions) pending = [] try: for link in feed.links: href = link['href'] if not href: continue # RFC5005 archive links if self.args.archive and link.get('rel') in ('prev-archive', 'next-archive', 'prev-page', 'next-page'): LOGGER.debug("Found archive link %s", link) pending.append( ("process feed " + href, self.process_feed(href, send_mentions))) # WebSub notification if updated and link.get('rel') == 'hub' and not feed.is_archive: LOGGER.debug("Found WebSub hub %s", link) pending.append( ("update websub " + href, feed.update_websub(self, href))) except (AttributeError, KeyError): LOGGER.debug("Feed %s has no links", url) # Schedule the entries items = set(feed.entry_links) if previous: items |= set(previous.entry_links) for entry in items: pending.append(("process entry " + entry, self.process_entry(entry, send_mentions=send_mentions))) LOGGER.debug("--- finish process_feed %s %s", url, send_mentions) if pending: LOGGER.debug("+++WAIT: process_feed(%s): %d subtasks", url, len(pending)) LOGGER.debug("%s", [name for (name, _) in pending]) await asyncio.wait([task for (_, task) in pending]) LOGGER.debug("+++DONE: process_feed(%s): %d subtasks", url, len(pending))
python
async def process_feed(self, url, send_mentions=True): """ process a feed """ self._feed_domains.add(utils.get_domain(url)) if url in self._processed_feeds: LOGGER.debug("Skipping already processed feed %s", url) return self._processed_feeds.add(url) LOGGER.debug("++WAIT: %s: get feed", url) feed, previous, updated = await feeds.get_feed(self, url) LOGGER.debug("++DONE: %s: get feed", url) if updated: LOGGER.info("Feed %s has been updated", url) if not feed: return LOGGER.debug("--- starting process_feed %s %s", url, send_mentions) pending = [] try: for link in feed.links: href = link['href'] if not href: continue # RFC5005 archive links if self.args.archive and link.get('rel') in ('prev-archive', 'next-archive', 'prev-page', 'next-page'): LOGGER.debug("Found archive link %s", link) pending.append( ("process feed " + href, self.process_feed(href, send_mentions))) # WebSub notification if updated and link.get('rel') == 'hub' and not feed.is_archive: LOGGER.debug("Found WebSub hub %s", link) pending.append( ("update websub " + href, feed.update_websub(self, href))) except (AttributeError, KeyError): LOGGER.debug("Feed %s has no links", url) # Schedule the entries items = set(feed.entry_links) if previous: items |= set(previous.entry_links) for entry in items: pending.append(("process entry " + entry, self.process_entry(entry, send_mentions=send_mentions))) LOGGER.debug("--- finish process_feed %s %s", url, send_mentions) if pending: LOGGER.debug("+++WAIT: process_feed(%s): %d subtasks", url, len(pending)) LOGGER.debug("%s", [name for (name, _) in pending]) await asyncio.wait([task for (_, task) in pending]) LOGGER.debug("+++DONE: process_feed(%s): %d subtasks", url, len(pending))
[ "async", "def", "process_feed", "(", "self", ",", "url", ",", "send_mentions", "=", "True", ")", ":", "self", ".", "_feed_domains", ".", "add", "(", "utils", ".", "get_domain", "(", "url", ")", ")", "if", "url", "in", "self", ".", "_processed_feeds", "...
process a feed
[ "process", "a", "feed" ]
5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c
https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/__init__.py#L31-L94
train
51,420
PlaidWeb/Pushl
pushl/__init__.py
Pushl.process_entry
async def process_entry(self, url, add_domain=False, send_mentions=True): """ process an entry """ if add_domain: self._feed_domains.add(utils.get_domain(url)) if url in self._processed_entries: LOGGER.debug("Skipping already processed entry %s", url) return self._processed_entries.add(url) LOGGER.debug("++WAIT: get entry %s", url) entry, previous, updated = await entries.get_entry(self, url) LOGGER.debug("++DONE: get entry %s", url) LOGGER.debug("--- starting process_entry %s", url) pending = [] if updated: LOGGER.info("Processing entry: %s", url) if send_mentions: # get the webmention targets links = entry.get_targets(self) if previous: # Only bother with links that changed from the last time links = links ^ previous.get_targets(self) for link in links: pending.append(("send webmention {} -> {}".format(url, link), self.send_webmention(entry, link))) if self.args.recurse: for feed in entry.feeds: if utils.get_domain(feed) in self._feed_domains: pending.append(("process feed " + feed, self.process_feed(feed, send_mentions=send_mentions))) else: LOGGER.info("Ignoring non-local feed %s", feed) LOGGER.debug("--- finish process_entry %s", url) if pending: LOGGER.debug("+++WAIT: process_entry(%s): %d subtasks", url, len(pending)) LOGGER.debug("%s", [name for (name, _) in pending]) await asyncio.wait([task for (_, task) in pending]) LOGGER.debug("+++DONE: process_entry(%s): %d subtasks", url, len(pending))
python
async def process_entry(self, url, add_domain=False, send_mentions=True): """ process an entry """ if add_domain: self._feed_domains.add(utils.get_domain(url)) if url in self._processed_entries: LOGGER.debug("Skipping already processed entry %s", url) return self._processed_entries.add(url) LOGGER.debug("++WAIT: get entry %s", url) entry, previous, updated = await entries.get_entry(self, url) LOGGER.debug("++DONE: get entry %s", url) LOGGER.debug("--- starting process_entry %s", url) pending = [] if updated: LOGGER.info("Processing entry: %s", url) if send_mentions: # get the webmention targets links = entry.get_targets(self) if previous: # Only bother with links that changed from the last time links = links ^ previous.get_targets(self) for link in links: pending.append(("send webmention {} -> {}".format(url, link), self.send_webmention(entry, link))) if self.args.recurse: for feed in entry.feeds: if utils.get_domain(feed) in self._feed_domains: pending.append(("process feed " + feed, self.process_feed(feed, send_mentions=send_mentions))) else: LOGGER.info("Ignoring non-local feed %s", feed) LOGGER.debug("--- finish process_entry %s", url) if pending: LOGGER.debug("+++WAIT: process_entry(%s): %d subtasks", url, len(pending)) LOGGER.debug("%s", [name for (name, _) in pending]) await asyncio.wait([task for (_, task) in pending]) LOGGER.debug("+++DONE: process_entry(%s): %d subtasks", url, len(pending))
[ "async", "def", "process_entry", "(", "self", ",", "url", ",", "add_domain", "=", "False", ",", "send_mentions", "=", "True", ")", ":", "if", "add_domain", ":", "self", ".", "_feed_domains", ".", "add", "(", "utils", ".", "get_domain", "(", "url", ")", ...
process an entry
[ "process", "an", "entry" ]
5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c
https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/__init__.py#L96-L144
train
51,421
PlaidWeb/Pushl
pushl/__init__.py
Pushl.send_webmention
async def send_webmention(self, entry, url): """ send a webmention from an entry to a URL """ if (entry.url, url) in self._processed_mentions: LOGGER.debug( "Skipping already processed mention %s -> %s", entry.url, url) self._processed_mentions.add((entry.url, url)) LOGGER.debug("++WAIT: webmentions.get_target %s", url) target = await webmentions.get_target(self, url) LOGGER.debug("++DONE: webmentions.get_target %s", url) if target: LOGGER.debug("++WAIT: Sending webmention %s -> %s", entry.url, url) await target.send(self, entry) LOGGER.debug("++DONE: Sending webmention %s -> %s", entry.url, url)
python
async def send_webmention(self, entry, url): """ send a webmention from an entry to a URL """ if (entry.url, url) in self._processed_mentions: LOGGER.debug( "Skipping already processed mention %s -> %s", entry.url, url) self._processed_mentions.add((entry.url, url)) LOGGER.debug("++WAIT: webmentions.get_target %s", url) target = await webmentions.get_target(self, url) LOGGER.debug("++DONE: webmentions.get_target %s", url) if target: LOGGER.debug("++WAIT: Sending webmention %s -> %s", entry.url, url) await target.send(self, entry) LOGGER.debug("++DONE: Sending webmention %s -> %s", entry.url, url)
[ "async", "def", "send_webmention", "(", "self", ",", "entry", ",", "url", ")", ":", "if", "(", "entry", ".", "url", ",", "url", ")", "in", "self", ".", "_processed_mentions", ":", "LOGGER", ".", "debug", "(", "\"Skipping already processed mention %s -> %s\"", ...
send a webmention from an entry to a URL
[ "send", "a", "webmention", "from", "an", "entry", "to", "a", "URL" ]
5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c
https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/__init__.py#L146-L161
train
51,422
nephila/djangocms-helper
djangocms_helper/main.py
compilemessages
def compilemessages(application): """ Compiles locale messages """ from django.core.management import call_command with work_in(application): if DJANGO_1_11: call_command('compilemessages', all=True) else: call_command('compilemessages')
python
def compilemessages(application): """ Compiles locale messages """ from django.core.management import call_command with work_in(application): if DJANGO_1_11: call_command('compilemessages', all=True) else: call_command('compilemessages')
[ "def", "compilemessages", "(", "application", ")", ":", "from", "django", ".", "core", ".", "management", "import", "call_command", "with", "work_in", "(", "application", ")", ":", "if", "DJANGO_1_11", ":", "call_command", "(", "'compilemessages'", ",", "all", ...
Compiles locale messages
[ "Compiles", "locale", "messages" ]
3fe53aee7b06922112c5e4445b74afeb86f6d836
https://github.com/nephila/djangocms-helper/blob/3fe53aee7b06922112c5e4445b74afeb86f6d836/djangocms_helper/main.py#L99-L109
train
51,423
nephila/djangocms-helper
djangocms_helper/main.py
makemessages
def makemessages(application, locale): """ Updates the locale message files """ from django.core.management import call_command if not locale: locale = 'en' with work_in(application): call_command('makemessages', locale=(locale,))
python
def makemessages(application, locale): """ Updates the locale message files """ from django.core.management import call_command if not locale: locale = 'en' with work_in(application): call_command('makemessages', locale=(locale,))
[ "def", "makemessages", "(", "application", ",", "locale", ")", ":", "from", "django", ".", "core", ".", "management", "import", "call_command", "if", "not", "locale", ":", "locale", "=", "'en'", "with", "work_in", "(", "application", ")", ":", "call_command"...
Updates the locale message files
[ "Updates", "the", "locale", "message", "files" ]
3fe53aee7b06922112c5e4445b74afeb86f6d836
https://github.com/nephila/djangocms-helper/blob/3fe53aee7b06922112c5e4445b74afeb86f6d836/djangocms_helper/main.py#L112-L121
train
51,424
nephila/djangocms-helper
djangocms_helper/main.py
cms_check
def cms_check(migrate_cmd=False): """ Runs the django CMS ``cms check`` command """ from django.core.management import call_command try: import cms # NOQA # nopyflakes _create_db(migrate_cmd) call_command('cms', 'check') except ImportError: print('cms_check available only if django CMS is installed')
python
def cms_check(migrate_cmd=False): """ Runs the django CMS ``cms check`` command """ from django.core.management import call_command try: import cms # NOQA # nopyflakes _create_db(migrate_cmd) call_command('cms', 'check') except ImportError: print('cms_check available only if django CMS is installed')
[ "def", "cms_check", "(", "migrate_cmd", "=", "False", ")", ":", "from", "django", ".", "core", ".", "management", "import", "call_command", "try", ":", "import", "cms", "# NOQA # nopyflakes", "_create_db", "(", "migrate_cmd", ")", "call_command", "(", "'cms'", ...
Runs the django CMS ``cms check`` command
[ "Runs", "the", "django", "CMS", "cms", "check", "command" ]
3fe53aee7b06922112c5e4445b74afeb86f6d836
https://github.com/nephila/djangocms-helper/blob/3fe53aee7b06922112c5e4445b74afeb86f6d836/djangocms_helper/main.py#L124-L134
train
51,425
nephila/djangocms-helper
djangocms_helper/main.py
generate_authors
def generate_authors(): """ Updates the authors list """ print('Generating AUTHORS') # Get our list of authors print('Collecting author names') r = subprocess.Popen(['git', 'log', '--use-mailmap', '--format=%aN'], stdout=subprocess.PIPE) seen_authors = [] authors = [] for authfile in ('AUTHORS', 'AUTHORS.rst'): if os.path.exists(authfile): break with open(authfile, 'r') as f: for line in f.readlines(): if line.startswith("*"): author = force_text(line).strip("* \n") if author.lower() not in seen_authors: seen_authors.append(author.lower()) authors.append(author) for author in r.stdout.readlines(): author = force_text(author).strip() if author.lower() not in seen_authors: seen_authors.append(author.lower()) authors.append(author) # Sort our list of Authors by their case insensitive name authors = sorted(authors, key=lambda x: x.lower()) # Write our authors to the AUTHORS file print('Authors (%s):\n\n\n* %s' % (len(authors), '\n* '.join(authors)))
python
def generate_authors(): """ Updates the authors list """ print('Generating AUTHORS') # Get our list of authors print('Collecting author names') r = subprocess.Popen(['git', 'log', '--use-mailmap', '--format=%aN'], stdout=subprocess.PIPE) seen_authors = [] authors = [] for authfile in ('AUTHORS', 'AUTHORS.rst'): if os.path.exists(authfile): break with open(authfile, 'r') as f: for line in f.readlines(): if line.startswith("*"): author = force_text(line).strip("* \n") if author.lower() not in seen_authors: seen_authors.append(author.lower()) authors.append(author) for author in r.stdout.readlines(): author = force_text(author).strip() if author.lower() not in seen_authors: seen_authors.append(author.lower()) authors.append(author) # Sort our list of Authors by their case insensitive name authors = sorted(authors, key=lambda x: x.lower()) # Write our authors to the AUTHORS file print('Authors (%s):\n\n\n* %s' % (len(authors), '\n* '.join(authors)))
[ "def", "generate_authors", "(", ")", ":", "print", "(", "'Generating AUTHORS'", ")", "# Get our list of authors", "print", "(", "'Collecting author names'", ")", "r", "=", "subprocess", ".", "Popen", "(", "[", "'git'", ",", "'log'", ",", "'--use-mailmap'", ",", ...
Updates the authors list
[ "Updates", "the", "authors", "list" ]
3fe53aee7b06922112c5e4445b74afeb86f6d836
https://github.com/nephila/djangocms-helper/blob/3fe53aee7b06922112c5e4445b74afeb86f6d836/djangocms_helper/main.py#L154-L186
train
51,426
nephila/djangocms-helper
djangocms_helper/main.py
static_analisys
def static_analisys(application): """ Performs a pyflakes static analysis with the same configuration as django CMS testsuite """ try: from cms.test_utils.util.static_analysis import pyflakes application_module = __import__(application) report = pyflakes((application_module,)) if type(report) == tuple: assert report[0] == 0 else: assert report == 0 except ImportError: print('Static analysis available only if django CMS is installed')
python
def static_analisys(application): """ Performs a pyflakes static analysis with the same configuration as django CMS testsuite """ try: from cms.test_utils.util.static_analysis import pyflakes application_module = __import__(application) report = pyflakes((application_module,)) if type(report) == tuple: assert report[0] == 0 else: assert report == 0 except ImportError: print('Static analysis available only if django CMS is installed')
[ "def", "static_analisys", "(", "application", ")", ":", "try", ":", "from", "cms", ".", "test_utils", ".", "util", ".", "static_analysis", "import", "pyflakes", "application_module", "=", "__import__", "(", "application", ")", "report", "=", "pyflakes", "(", "...
Performs a pyflakes static analysis with the same configuration as django CMS testsuite
[ "Performs", "a", "pyflakes", "static", "analysis", "with", "the", "same", "configuration", "as", "django", "CMS", "testsuite" ]
3fe53aee7b06922112c5e4445b74afeb86f6d836
https://github.com/nephila/djangocms-helper/blob/3fe53aee7b06922112c5e4445b74afeb86f6d836/djangocms_helper/main.py#L189-L203
train
51,427
iotile/baBLE
tools/release.py
build_wheel
def build_wheel(platform): """Create a wheel""" if platform in ['x86_64', 'i686']: system = 'manylinux1' else: system = 'linux' setuptools.sandbox.run_setup( 'setup.py', ['-q', 'clean', '--all', 'bdist_wheel', '--plat-name', '{}_{}'.format(system, platform)] )
python
def build_wheel(platform): """Create a wheel""" if platform in ['x86_64', 'i686']: system = 'manylinux1' else: system = 'linux' setuptools.sandbox.run_setup( 'setup.py', ['-q', 'clean', '--all', 'bdist_wheel', '--plat-name', '{}_{}'.format(system, platform)] )
[ "def", "build_wheel", "(", "platform", ")", ":", "if", "platform", "in", "[", "'x86_64'", ",", "'i686'", "]", ":", "system", "=", "'manylinux1'", "else", ":", "system", "=", "'linux'", "setuptools", ".", "sandbox", ".", "run_setup", "(", "'setup.py'", ",",...
Create a wheel
[ "Create", "a", "wheel" ]
faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db
https://github.com/iotile/baBLE/blob/faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db/tools/release.py#L23-L34
train
51,428
ClericPy/torequests
torequests/utils.py
print_mem
def print_mem(unit="MB"): """Show the proc-mem-cost with psutil, use this only for lazinesssss. :param unit: B, KB, MB, GB. """ try: import psutil B = float(psutil.Process(os.getpid()).memory_info().vms) KB = B / 1024 MB = KB / 1024 GB = MB / 1024 result = vars()[unit] print_info("memory usage: %.2f(%s)" % (result, unit)) return result except ImportError: print_info("pip install psutil first.")
python
def print_mem(unit="MB"): """Show the proc-mem-cost with psutil, use this only for lazinesssss. :param unit: B, KB, MB, GB. """ try: import psutil B = float(psutil.Process(os.getpid()).memory_info().vms) KB = B / 1024 MB = KB / 1024 GB = MB / 1024 result = vars()[unit] print_info("memory usage: %.2f(%s)" % (result, unit)) return result except ImportError: print_info("pip install psutil first.")
[ "def", "print_mem", "(", "unit", "=", "\"MB\"", ")", ":", "try", ":", "import", "psutil", "B", "=", "float", "(", "psutil", ".", "Process", "(", "os", ".", "getpid", "(", ")", ")", ".", "memory_info", "(", ")", ".", "vms", ")", "KB", "=", "B", ...
Show the proc-mem-cost with psutil, use this only for lazinesssss. :param unit: B, KB, MB, GB.
[ "Show", "the", "proc", "-", "mem", "-", "cost", "with", "psutil", "use", "this", "only", "for", "lazinesssss", "." ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L110-L126
train
51,429
ClericPy/torequests
torequests/utils.py
slice_into_pieces
def slice_into_pieces(seq, n): """Slice a sequence into `n` pieces, return a generation of n pieces""" length = len(seq) if length % n == 0: size = length // n else: size = length // n + 1 for it in slice_by_size(seq, size): yield it
python
def slice_into_pieces(seq, n): """Slice a sequence into `n` pieces, return a generation of n pieces""" length = len(seq) if length % n == 0: size = length // n else: size = length // n + 1 for it in slice_by_size(seq, size): yield it
[ "def", "slice_into_pieces", "(", "seq", ",", "n", ")", ":", "length", "=", "len", "(", "seq", ")", "if", "length", "%", "n", "==", "0", ":", "size", "=", "length", "//", "n", "else", ":", "size", "=", "length", "//", "n", "+", "1", "for", "it",...
Slice a sequence into `n` pieces, return a generation of n pieces
[ "Slice", "a", "sequence", "into", "n", "pieces", "return", "a", "generation", "of", "n", "pieces" ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L250-L258
train
51,430
ClericPy/torequests
torequests/utils.py
slice_by_size
def slice_by_size(seq, size): """Slice a sequence into chunks, return as a generation of chunks with `size`.""" filling = null for it in zip(*(itertools_chain(seq, [filling] * size),) * size): if filling in it: it = tuple(i for i in it if i is not filling) if it: yield it
python
def slice_by_size(seq, size): """Slice a sequence into chunks, return as a generation of chunks with `size`.""" filling = null for it in zip(*(itertools_chain(seq, [filling] * size),) * size): if filling in it: it = tuple(i for i in it if i is not filling) if it: yield it
[ "def", "slice_by_size", "(", "seq", ",", "size", ")", ":", "filling", "=", "null", "for", "it", "in", "zip", "(", "*", "(", "itertools_chain", "(", "seq", ",", "[", "filling", "]", "*", "size", ")", ",", ")", "*", "size", ")", ":", "if", "filling...
Slice a sequence into chunks, return as a generation of chunks with `size`.
[ "Slice", "a", "sequence", "into", "chunks", "return", "as", "a", "generation", "of", "chunks", "with", "size", "." ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L261-L268
train
51,431
ClericPy/torequests
torequests/utils.py
unique
def unique(seq, key=None, return_as=None): """Unique the seq and keep the order. Instead of the slow way: `lambda seq: (x for index, x in enumerate(seq) if seq.index(x)==index)` :param seq: raw sequence. :param return_as: generator for default, or list / set / str... >>> from torequests.utils import unique >>> a = [1,2,3,4,2,3,4] >>> unique(a) <generator object unique.<locals>.<genexpr> at 0x05720EA0> >>> unique(a, str) '1234' >>> unique(a, list) [1, 2, 3, 4] """ seen = set() add = seen.add if key: generator = (x for x in seq if key(x) not in seen and not add(key(x))) else: generator = (x for x in seq if x not in seen and not add(x)) if return_as: if return_as == str: return "".join(map(str, generator)) else: return return_as(generator) else: # python2 not support yield from return generator
python
def unique(seq, key=None, return_as=None): """Unique the seq and keep the order. Instead of the slow way: `lambda seq: (x for index, x in enumerate(seq) if seq.index(x)==index)` :param seq: raw sequence. :param return_as: generator for default, or list / set / str... >>> from torequests.utils import unique >>> a = [1,2,3,4,2,3,4] >>> unique(a) <generator object unique.<locals>.<genexpr> at 0x05720EA0> >>> unique(a, str) '1234' >>> unique(a, list) [1, 2, 3, 4] """ seen = set() add = seen.add if key: generator = (x for x in seq if key(x) not in seen and not add(key(x))) else: generator = (x for x in seq if x not in seen and not add(x)) if return_as: if return_as == str: return "".join(map(str, generator)) else: return return_as(generator) else: # python2 not support yield from return generator
[ "def", "unique", "(", "seq", ",", "key", "=", "None", ",", "return_as", "=", "None", ")", ":", "seen", "=", "set", "(", ")", "add", "=", "seen", ".", "add", "if", "key", ":", "generator", "=", "(", "x", "for", "x", "in", "seq", "if", "key", "...
Unique the seq and keep the order. Instead of the slow way: `lambda seq: (x for index, x in enumerate(seq) if seq.index(x)==index)` :param seq: raw sequence. :param return_as: generator for default, or list / set / str... >>> from torequests.utils import unique >>> a = [1,2,3,4,2,3,4] >>> unique(a) <generator object unique.<locals>.<genexpr> at 0x05720EA0> >>> unique(a, str) '1234' >>> unique(a, list) [1, 2, 3, 4]
[ "Unique", "the", "seq", "and", "keep", "the", "order", "." ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L482-L513
train
51,432
ClericPy/torequests
torequests/utils.py
unparse_qs
def unparse_qs(qs, sort=False, reverse=False): """Reverse conversion for parse_qs""" result = [] items = qs.items() if sort: items = sorted(items, key=lambda x: x[0], reverse=reverse) for keys, values in items: query_name = quote(keys) for value in values: result.append(query_name + "=" + quote(value)) return "&".join(result)
python
def unparse_qs(qs, sort=False, reverse=False): """Reverse conversion for parse_qs""" result = [] items = qs.items() if sort: items = sorted(items, key=lambda x: x[0], reverse=reverse) for keys, values in items: query_name = quote(keys) for value in values: result.append(query_name + "=" + quote(value)) return "&".join(result)
[ "def", "unparse_qs", "(", "qs", ",", "sort", "=", "False", ",", "reverse", "=", "False", ")", ":", "result", "=", "[", "]", "items", "=", "qs", ".", "items", "(", ")", "if", "sort", ":", "items", "=", "sorted", "(", "items", ",", "key", "=", "l...
Reverse conversion for parse_qs
[ "Reverse", "conversion", "for", "parse_qs" ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L516-L526
train
51,433
ClericPy/torequests
torequests/utils.py
unparse_qsl
def unparse_qsl(qsl, sort=False, reverse=False): """Reverse conversion for parse_qsl""" result = [] items = qsl if sort: items = sorted(items, key=lambda x: x[0], reverse=reverse) for keys, values in items: query_name = quote(keys) result.append(query_name + "=" + quote(values)) return "&".join(result)
python
def unparse_qsl(qsl, sort=False, reverse=False): """Reverse conversion for parse_qsl""" result = [] items = qsl if sort: items = sorted(items, key=lambda x: x[0], reverse=reverse) for keys, values in items: query_name = quote(keys) result.append(query_name + "=" + quote(values)) return "&".join(result)
[ "def", "unparse_qsl", "(", "qsl", ",", "sort", "=", "False", ",", "reverse", "=", "False", ")", ":", "result", "=", "[", "]", "items", "=", "qsl", "if", "sort", ":", "items", "=", "sorted", "(", "items", ",", "key", "=", "lambda", "x", ":", "x", ...
Reverse conversion for parse_qsl
[ "Reverse", "conversion", "for", "parse_qsl" ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L529-L538
train
51,434
ClericPy/torequests
torequests/utils.py
kill_after
def kill_after(seconds, timeout=2): """Kill self after seconds""" pid = os.getpid() kill = os.kill run_after_async(seconds, kill, pid, signal.SIGTERM) run_after_async(seconds + timeout, kill, pid, 9)
python
def kill_after(seconds, timeout=2): """Kill self after seconds""" pid = os.getpid() kill = os.kill run_after_async(seconds, kill, pid, signal.SIGTERM) run_after_async(seconds + timeout, kill, pid, 9)
[ "def", "kill_after", "(", "seconds", ",", "timeout", "=", "2", ")", ":", "pid", "=", "os", ".", "getpid", "(", ")", "kill", "=", "os", ".", "kill", "run_after_async", "(", "seconds", ",", "kill", ",", "pid", ",", "signal", ".", "SIGTERM", ")", "run...
Kill self after seconds
[ "Kill", "self", "after", "seconds" ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L682-L687
train
51,435
ClericPy/torequests
torequests/utils.py
try_import
def try_import(module_name, names=None, default=ImportErrorModule, warn=True): """Try import module_name, except ImportError and return default, sometimes to be used for catch ImportError and lazy-import. """ try: module = importlib.import_module(module_name) except ImportError: if warn: if warn is True: Config.utils_logger.warning( "Module `%s` not found. Install it to remove this warning" % module_name ) else: warn(module_name, names, default) module = ( ImportErrorModule(module_name) if default is ImportErrorModule else default ) if not names: return module if not isinstance(names, (tuple, set, list)): names = [names] result = [] for name in names: if hasattr(module, name): result.append(module.__getattribute__(name)) else: result.append( ImportErrorModule("%s.%s" % (module_name, name)) if default is ImportErrorModule else default ) return result[0] if len(result) == 1 else result
python
def try_import(module_name, names=None, default=ImportErrorModule, warn=True): """Try import module_name, except ImportError and return default, sometimes to be used for catch ImportError and lazy-import. """ try: module = importlib.import_module(module_name) except ImportError: if warn: if warn is True: Config.utils_logger.warning( "Module `%s` not found. Install it to remove this warning" % module_name ) else: warn(module_name, names, default) module = ( ImportErrorModule(module_name) if default is ImportErrorModule else default ) if not names: return module if not isinstance(names, (tuple, set, list)): names = [names] result = [] for name in names: if hasattr(module, name): result.append(module.__getattribute__(name)) else: result.append( ImportErrorModule("%s.%s" % (module_name, name)) if default is ImportErrorModule else default ) return result[0] if len(result) == 1 else result
[ "def", "try_import", "(", "module_name", ",", "names", "=", "None", ",", "default", "=", "ImportErrorModule", ",", "warn", "=", "True", ")", ":", "try", ":", "module", "=", "importlib", ".", "import_module", "(", "module_name", ")", "except", "ImportError", ...
Try import module_name, except ImportError and return default, sometimes to be used for catch ImportError and lazy-import.
[ "Try", "import", "module_name", "except", "ImportError", "and", "return", "default", "sometimes", "to", "be", "used", "for", "catch", "ImportError", "and", "lazy", "-", "import", "." ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L709-L741
train
51,436
ClericPy/torequests
torequests/utils.py
guess_interval
def guess_interval(nums, accuracy=0): """Given a seq of number, return the median, only calculate interval >= accuracy. :: from torequests.utils import guess_interval import random seq = [random.randint(1, 100) for i in range(20)] print(guess_interval(seq, 5)) # sorted_seq: [2, 10, 12, 19, 19, 29, 30, 32, 38, 40, 41, 54, 62, 69, 75, 79, 82, 88, 97, 99] # diffs: [8, 7, 10, 6, 13, 8, 7, 6, 6, 9] # median: 8 """ if not nums: return 0 nums = sorted([int(i) for i in nums]) if len(nums) == 1: return nums[0] diffs = [nums[i + 1] - nums[i] for i in range(len(nums) - 1)] diffs = [item for item in diffs if item >= accuracy] sorted_diff = sorted(diffs) result = sorted_diff[len(diffs) // 2] return result
python
def guess_interval(nums, accuracy=0): """Given a seq of number, return the median, only calculate interval >= accuracy. :: from torequests.utils import guess_interval import random seq = [random.randint(1, 100) for i in range(20)] print(guess_interval(seq, 5)) # sorted_seq: [2, 10, 12, 19, 19, 29, 30, 32, 38, 40, 41, 54, 62, 69, 75, 79, 82, 88, 97, 99] # diffs: [8, 7, 10, 6, 13, 8, 7, 6, 6, 9] # median: 8 """ if not nums: return 0 nums = sorted([int(i) for i in nums]) if len(nums) == 1: return nums[0] diffs = [nums[i + 1] - nums[i] for i in range(len(nums) - 1)] diffs = [item for item in diffs if item >= accuracy] sorted_diff = sorted(diffs) result = sorted_diff[len(diffs) // 2] return result
[ "def", "guess_interval", "(", "nums", ",", "accuracy", "=", "0", ")", ":", "if", "not", "nums", ":", "return", "0", "nums", "=", "sorted", "(", "[", "int", "(", "i", ")", "for", "i", "in", "nums", "]", ")", "if", "len", "(", "nums", ")", "==", ...
Given a seq of number, return the median, only calculate interval >= accuracy. :: from torequests.utils import guess_interval import random seq = [random.randint(1, 100) for i in range(20)] print(guess_interval(seq, 5)) # sorted_seq: [2, 10, 12, 19, 19, 29, 30, 32, 38, 40, 41, 54, 62, 69, 75, 79, 82, 88, 97, 99] # diffs: [8, 7, 10, 6, 13, 8, 7, 6, 6, 9] # median: 8
[ "Given", "a", "seq", "of", "number", "return", "the", "median", "only", "calculate", "interval", ">", "=", "accuracy", "." ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L1211-L1234
train
51,437
ClericPy/torequests
torequests/utils.py
split_n
def split_n(string, seps, reg=False): r"""Split strings into n-dimensional list. :: from torequests.utils import split_n ss = '''a b c d e f 1 2 3 4 5 6 a b c d e f 1 2 3 4 5 6 a b c d e f 1 2 3 4 5 6''' print(split_n(ss, ('\n', ' ', ' '))) # [[['a', 'b', 'c'], ['d', 'e', 'f'], ['1', '2', '3'], ['4', '5', '6']], [['a', 'b', 'c'], ['d', 'e', 'f'], ['1', '2', '3'], ['4', '5', '6']], [['a', 'b', 'c'], ['d', 'e', 'f'], ['1', '2', '3'], ['4', '5', '6']]] print(split_n(ss, ['\s+'], reg=1)) # ['a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6', 'a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6', 'a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6'] """ deep = len(seps) if not deep: return string return [split_n(i, seps[1:]) for i in _re_split_mixin(string, seps[0], reg=reg)]
python
def split_n(string, seps, reg=False): r"""Split strings into n-dimensional list. :: from torequests.utils import split_n ss = '''a b c d e f 1 2 3 4 5 6 a b c d e f 1 2 3 4 5 6 a b c d e f 1 2 3 4 5 6''' print(split_n(ss, ('\n', ' ', ' '))) # [[['a', 'b', 'c'], ['d', 'e', 'f'], ['1', '2', '3'], ['4', '5', '6']], [['a', 'b', 'c'], ['d', 'e', 'f'], ['1', '2', '3'], ['4', '5', '6']], [['a', 'b', 'c'], ['d', 'e', 'f'], ['1', '2', '3'], ['4', '5', '6']]] print(split_n(ss, ['\s+'], reg=1)) # ['a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6', 'a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6', 'a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6'] """ deep = len(seps) if not deep: return string return [split_n(i, seps[1:]) for i in _re_split_mixin(string, seps[0], reg=reg)]
[ "def", "split_n", "(", "string", ",", "seps", ",", "reg", "=", "False", ")", ":", "deep", "=", "len", "(", "seps", ")", "if", "not", "deep", ":", "return", "string", "return", "[", "split_n", "(", "i", ",", "seps", "[", "1", ":", "]", ")", "for...
r"""Split strings into n-dimensional list. :: from torequests.utils import split_n ss = '''a b c d e f 1 2 3 4 5 6 a b c d e f 1 2 3 4 5 6 a b c d e f 1 2 3 4 5 6''' print(split_n(ss, ('\n', ' ', ' '))) # [[['a', 'b', 'c'], ['d', 'e', 'f'], ['1', '2', '3'], ['4', '5', '6']], [['a', 'b', 'c'], ['d', 'e', 'f'], ['1', '2', '3'], ['4', '5', '6']], [['a', 'b', 'c'], ['d', 'e', 'f'], ['1', '2', '3'], ['4', '5', '6']]] print(split_n(ss, ['\s+'], reg=1)) # ['a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6', 'a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6', 'a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6']
[ "r", "Split", "strings", "into", "n", "-", "dimensional", "list", "." ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L1244-L1263
train
51,438
ClericPy/torequests
torequests/utils.py
curlrequests
def curlrequests(curl_string, **kwargs): """Use tPool to request for curl string. If kwargs contains the req which hasattr request method, like req=requests. :param curl_string: standard curl string. :type curl_string: str :param kwargs: valid kwargs for tPool. :type curl_string: dict Basic Usage:: from torequests.utils import curlrequests r = curlrequests('''curl 'http://p.3.cn/' -H 'Connection: keep-alive' -H 'Cache-Control: max-age=0' -H 'Upgrade-Insecure-Requests: 1' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36' -H 'DNT: 1' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' -H 'If-None-Match: "55dd9090-264"' -H 'If-Modified-Since: Wed, 26 Aug 2015 10:10:24 GMT' --compressed''', retry=1) print(r.text) """ req = kwargs.pop('req', tPool()) kwargs.update(curlparse(curl_string)) return req.request(**kwargs)
python
def curlrequests(curl_string, **kwargs): """Use tPool to request for curl string. If kwargs contains the req which hasattr request method, like req=requests. :param curl_string: standard curl string. :type curl_string: str :param kwargs: valid kwargs for tPool. :type curl_string: dict Basic Usage:: from torequests.utils import curlrequests r = curlrequests('''curl 'http://p.3.cn/' -H 'Connection: keep-alive' -H 'Cache-Control: max-age=0' -H 'Upgrade-Insecure-Requests: 1' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36' -H 'DNT: 1' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' -H 'If-None-Match: "55dd9090-264"' -H 'If-Modified-Since: Wed, 26 Aug 2015 10:10:24 GMT' --compressed''', retry=1) print(r.text) """ req = kwargs.pop('req', tPool()) kwargs.update(curlparse(curl_string)) return req.request(**kwargs)
[ "def", "curlrequests", "(", "curl_string", ",", "*", "*", "kwargs", ")", ":", "req", "=", "kwargs", ".", "pop", "(", "'req'", ",", "tPool", "(", ")", ")", "kwargs", ".", "update", "(", "curlparse", "(", "curl_string", ")", ")", "return", "req", ".", ...
Use tPool to request for curl string. If kwargs contains the req which hasattr request method, like req=requests. :param curl_string: standard curl string. :type curl_string: str :param kwargs: valid kwargs for tPool. :type curl_string: dict Basic Usage:: from torequests.utils import curlrequests r = curlrequests('''curl 'http://p.3.cn/' -H 'Connection: keep-alive' -H 'Cache-Control: max-age=0' -H 'Upgrade-Insecure-Requests: 1' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36' -H 'DNT: 1' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' -H 'If-None-Match: "55dd9090-264"' -H 'If-Modified-Since: Wed, 26 Aug 2015 10:10:24 GMT' --compressed''', retry=1) print(r.text)
[ "Use", "tPool", "to", "request", "for", "curl", "string", ".", "If", "kwargs", "contains", "the", "req", "which", "hasattr", "request", "method", "like", "req", "=", "requests", "." ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L1621-L1640
train
51,439
ClericPy/torequests
torequests/utils.py
Regex.register_function
def register_function(self, patterns, instances=None, **reg_kwargs): """Decorator for register.""" def wrapper(function): self.register(patterns, function, instances=instances, **reg_kwargs) return function return wrapper
python
def register_function(self, patterns, instances=None, **reg_kwargs): """Decorator for register.""" def wrapper(function): self.register(patterns, function, instances=instances, **reg_kwargs) return function return wrapper
[ "def", "register_function", "(", "self", ",", "patterns", ",", "instances", "=", "None", ",", "*", "*", "reg_kwargs", ")", ":", "def", "wrapper", "(", "function", ")", ":", "self", ".", "register", "(", "patterns", ",", "function", ",", "instances", "=",...
Decorator for register.
[ "Decorator", "for", "register", "." ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L607-L614
train
51,440
ClericPy/torequests
torequests/utils.py
Regex.find
def find(self, string, default=None): """Return match or search result. :rtype: list""" return self.match(string) or self.search(string) or default
python
def find(self, string, default=None): """Return match or search result. :rtype: list""" return self.match(string) or self.search(string) or default
[ "def", "find", "(", "self", ",", "string", ",", "default", "=", "None", ")", ":", "return", "self", ".", "match", "(", "string", ")", "or", "self", ".", "search", "(", "string", ")", "or", "default" ]
Return match or search result. :rtype: list
[ "Return", "match", "or", "search", "result", "." ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L616-L620
train
51,441
ClericPy/torequests
torequests/utils.py
Regex.search
def search(self, string, default=None): """Use re.search to find the result :rtype: list""" default = default if default else [] result = [item[1] for item in self.container if item[0].search(string)] if self.ensure_mapping: assert len(result) < 2, "%s matches more than one pattern: %s" % ( string, result, ) return result if result else default
python
def search(self, string, default=None): """Use re.search to find the result :rtype: list""" default = default if default else [] result = [item[1] for item in self.container if item[0].search(string)] if self.ensure_mapping: assert len(result) < 2, "%s matches more than one pattern: %s" % ( string, result, ) return result if result else default
[ "def", "search", "(", "self", ",", "string", ",", "default", "=", "None", ")", ":", "default", "=", "default", "if", "default", "else", "[", "]", "result", "=", "[", "item", "[", "1", "]", "for", "item", "in", "self", ".", "container", "if", "item"...
Use re.search to find the result :rtype: list
[ "Use", "re", ".", "search", "to", "find", "the", "result" ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L622-L633
train
51,442
ClericPy/torequests
torequests/utils.py
Regex.fuzzy
def fuzzy(self, key, limit=5): """Give suggestion from all instances.""" instances = [i[2] for i in self.container if i[2]] if not instances: return instances = sum(instances, []) from fuzzywuzzy import process maybe = process.extract(key, instances, limit=limit) return maybe
python
def fuzzy(self, key, limit=5): """Give suggestion from all instances.""" instances = [i[2] for i in self.container if i[2]] if not instances: return instances = sum(instances, []) from fuzzywuzzy import process maybe = process.extract(key, instances, limit=limit) return maybe
[ "def", "fuzzy", "(", "self", ",", "key", ",", "limit", "=", "5", ")", ":", "instances", "=", "[", "i", "[", "2", "]", "for", "i", "in", "self", ".", "container", "if", "i", "[", "2", "]", "]", "if", "not", "instances", ":", "return", "instances...
Give suggestion from all instances.
[ "Give", "suggestion", "from", "all", "instances", "." ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L648-L657
train
51,443
ClericPy/torequests
torequests/utils.py
Regex.show_all
def show_all(self, as_string=True): """, python2 will not show flags""" result = [] for item in self.container: pattern = str(item[0])[10:] if PY3 else item[0].pattern instances = item[2] or [] value = ( '%s "%s"' % (item[1].__name__, (item[1].__doc__ or "")) if callable(item[1]) else str(item[1]) ) value = "%s %s" % (type(item[1]), value) result.append(" => ".join((pattern, ",".join(instances), value))) return "\n".join(result) if as_string else result
python
def show_all(self, as_string=True): """, python2 will not show flags""" result = [] for item in self.container: pattern = str(item[0])[10:] if PY3 else item[0].pattern instances = item[2] or [] value = ( '%s "%s"' % (item[1].__name__, (item[1].__doc__ or "")) if callable(item[1]) else str(item[1]) ) value = "%s %s" % (type(item[1]), value) result.append(" => ".join((pattern, ",".join(instances), value))) return "\n".join(result) if as_string else result
[ "def", "show_all", "(", "self", ",", "as_string", "=", "True", ")", ":", "result", "=", "[", "]", "for", "item", "in", "self", ".", "container", ":", "pattern", "=", "str", "(", "item", "[", "0", "]", ")", "[", "10", ":", "]", "if", "PY3", "els...
, python2 will not show flags
[ "python2", "will", "not", "show", "flags" ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L666-L679
train
51,444
ClericPy/torequests
torequests/utils.py
Timer.tick
def tick(self): """Return the time cost string as expect.""" string = self.passed if self.rounding: string = round(string) if self.readable: string = self.readable(string) return string
python
def tick(self): """Return the time cost string as expect.""" string = self.passed if self.rounding: string = round(string) if self.readable: string = self.readable(string) return string
[ "def", "tick", "(", "self", ")", ":", "string", "=", "self", ".", "passed", "if", "self", ".", "rounding", ":", "string", "=", "round", "(", "string", ")", "if", "self", ".", "readable", ":", "string", "=", "self", ".", "readable", "(", "string", "...
Return the time cost string as expect.
[ "Return", "the", "time", "cost", "string", "as", "expect", "." ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L887-L894
train
51,445
ClericPy/torequests
torequests/utils.py
Timer.watch
def watch(*timer_args, **timer_kwargs): """Decorator for Timer.""" def wrapper(function): @wraps(function) def inner(*args, **kwargs): args1 = ", ".join(map(repr, args)) if args else "" kwargs1 = ", ".join( ["%s=%s" % (i, repr(kwargs[i])) for i in sorted(kwargs.keys())] ) arg = ", ".join(filter(None, [args1, kwargs1])) name = "%s(%s)" % (function.__name__, arg) _ = Timer(name=name, *timer_args, **timer_kwargs) result = function(*args, **kwargs) return result return inner return wrapper
python
def watch(*timer_args, **timer_kwargs): """Decorator for Timer.""" def wrapper(function): @wraps(function) def inner(*args, **kwargs): args1 = ", ".join(map(repr, args)) if args else "" kwargs1 = ", ".join( ["%s=%s" % (i, repr(kwargs[i])) for i in sorted(kwargs.keys())] ) arg = ", ".join(filter(None, [args1, kwargs1])) name = "%s(%s)" % (function.__name__, arg) _ = Timer(name=name, *timer_args, **timer_kwargs) result = function(*args, **kwargs) return result return inner return wrapper
[ "def", "watch", "(", "*", "timer_args", ",", "*", "*", "timer_kwargs", ")", ":", "def", "wrapper", "(", "function", ")", ":", "@", "wraps", "(", "function", ")", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args1", "=", "...
Decorator for Timer.
[ "Decorator", "for", "Timer", "." ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L897-L915
train
51,446
ClericPy/torequests
torequests/utils.py
ClipboardWatcher.default_callback
def default_callback(self, text): """Default clean the \\n in text.""" text = text.replace("\r\n", "\n") text = "%s\n" % text flush_print(text, sep="", end="") return text
python
def default_callback(self, text): """Default clean the \\n in text.""" text = text.replace("\r\n", "\n") text = "%s\n" % text flush_print(text, sep="", end="") return text
[ "def", "default_callback", "(", "self", ",", "text", ")", ":", "text", "=", "text", ".", "replace", "(", "\"\\r\\n\"", ",", "\"\\n\"", ")", "text", "=", "\"%s\\n\"", "%", "text", "flush_print", "(", "text", ",", "sep", "=", "\"\"", ",", "end", "=", "...
Default clean the \\n in text.
[ "Default", "clean", "the", "\\\\", "n", "in", "text", "." ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L964-L969
train
51,447
ClericPy/torequests
torequests/utils.py
ClipboardWatcher.watch
def watch(self, limit=None, timeout=None): """Block method to watch the clipboard changing.""" start_time = time.time() count = 0 while not timeout or time.time() - start_time < timeout: new = self.read() if new != self.temp: count += 1 self.callback(new) if count == limit: break self.temp = new time.sleep(self.interval)
python
def watch(self, limit=None, timeout=None): """Block method to watch the clipboard changing.""" start_time = time.time() count = 0 while not timeout or time.time() - start_time < timeout: new = self.read() if new != self.temp: count += 1 self.callback(new) if count == limit: break self.temp = new time.sleep(self.interval)
[ "def", "watch", "(", "self", ",", "limit", "=", "None", ",", "timeout", "=", "None", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "count", "=", "0", "while", "not", "timeout", "or", "time", ".", "time", "(", ")", "-", "start_time", ...
Block method to watch the clipboard changing.
[ "Block", "method", "to", "watch", "the", "clipboard", "changing", "." ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L971-L983
train
51,448
ClericPy/torequests
torequests/utils.py
ClipboardWatcher.watch_async
def watch_async(self, limit=None, timeout=None): """Non-block method to watch the clipboard changing.""" return self.watch(limit=limit, timeout=timeout)
python
def watch_async(self, limit=None, timeout=None): """Non-block method to watch the clipboard changing.""" return self.watch(limit=limit, timeout=timeout)
[ "def", "watch_async", "(", "self", ",", "limit", "=", "None", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "watch", "(", "limit", "=", "limit", ",", "timeout", "=", "timeout", ")" ]
Non-block method to watch the clipboard changing.
[ "Non", "-", "block", "method", "to", "watch", "the", "clipboard", "changing", "." ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L991-L993
train
51,449
ClericPy/torequests
torequests/utils.py
RegMatch.find_one
def find_one(cls, pattern, string, flags=0): """JS-like match object. Use index number to get groups, if not match or no group, will return ''. Basic Usage:: >>> from torequests.utils import find_one >>> string = "abcd" >>> find_one("a.*", string) <torequests.utils.RegMatch object at 0x0705F1D0> >>> find_one("a.*", string)[0] 'abcd' >>> find_one("a.*", string)[1] '' >>> find_one("a(.)", string)[0] 'ab' >>> find_one("a(.)", string)[1] 'b' >>> find_one("a(.)", string)[2] or "default" 'default' >>> import re >>> item = find_one("a(B)(C)", string, flags=re.I | re.S) >>> item <torequests.utils.RegMatch object at 0x0705F1D0> >>> item[0] 'abc' >>> item[1] 'b' >>> item[2] 'c' >>> item[3] '' >>> # import re >>> # re.findone = find_one >>> register_re_findone() >>> re.findone('a(b)', 'abcd')[1] or 'default' 'b' """ item = re.search(pattern, string, flags=flags) return cls(item)
python
def find_one(cls, pattern, string, flags=0): """JS-like match object. Use index number to get groups, if not match or no group, will return ''. Basic Usage:: >>> from torequests.utils import find_one >>> string = "abcd" >>> find_one("a.*", string) <torequests.utils.RegMatch object at 0x0705F1D0> >>> find_one("a.*", string)[0] 'abcd' >>> find_one("a.*", string)[1] '' >>> find_one("a(.)", string)[0] 'ab' >>> find_one("a(.)", string)[1] 'b' >>> find_one("a(.)", string)[2] or "default" 'default' >>> import re >>> item = find_one("a(B)(C)", string, flags=re.I | re.S) >>> item <torequests.utils.RegMatch object at 0x0705F1D0> >>> item[0] 'abc' >>> item[1] 'b' >>> item[2] 'c' >>> item[3] '' >>> # import re >>> # re.findone = find_one >>> register_re_findone() >>> re.findone('a(b)', 'abcd')[1] or 'default' 'b' """ item = re.search(pattern, string, flags=flags) return cls(item)
[ "def", "find_one", "(", "cls", ",", "pattern", ",", "string", ",", "flags", "=", "0", ")", ":", "item", "=", "re", ".", "search", "(", "pattern", ",", "string", ",", "flags", "=", "flags", ")", "return", "cls", "(", "item", ")" ]
JS-like match object. Use index number to get groups, if not match or no group, will return ''. Basic Usage:: >>> from torequests.utils import find_one >>> string = "abcd" >>> find_one("a.*", string) <torequests.utils.RegMatch object at 0x0705F1D0> >>> find_one("a.*", string)[0] 'abcd' >>> find_one("a.*", string)[1] '' >>> find_one("a(.)", string)[0] 'ab' >>> find_one("a(.)", string)[1] 'b' >>> find_one("a(.)", string)[2] or "default" 'default' >>> import re >>> item = find_one("a(B)(C)", string, flags=re.I | re.S) >>> item <torequests.utils.RegMatch object at 0x0705F1D0> >>> item[0] 'abc' >>> item[1] 'b' >>> item[2] 'c' >>> item[3] '' >>> # import re >>> # re.findone = find_one >>> register_re_findone() >>> re.findone('a(b)', 'abcd')[1] or 'default' 'b'
[ "JS", "-", "like", "match", "object", ".", "Use", "index", "number", "to", "get", "groups", "if", "not", "match", "or", "no", "group", "will", "return", "." ]
1793261688d7a47e1c3a0830d83f8552f5e3e5d9
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L1460-L1499
train
51,450
vsoch/helpme
helpme/main/github/utils.py
create_issue
def create_issue(title, body, repo, token): '''create a Github issue, given a title, body, repo, and token. Parameters ========== title: the issue title body: the issue body repo: the full name of the repo token: the user's personal Github token ''' owner, name = repo.split('/') url = 'https://api.github.com/repos/%s/%s/issues' % (owner, name) data = {'title': title, 'body': body } headers = { "Authorization": "token %s" % token, "Accept": "application/vnd.github.symmetra-preview+json" } response = requests.post(url, data=json.dumps(data), headers=headers) if response.status_code in [201, 202]: url = response.json()['html_url'] bot.info(url) return url elif response.status_code == 404: bot.error('Cannot create issue. Does your token have scope repo?') sys.exit(1) else: bot.error('Cannot create issue %s' %title) bot.error(response.content) sys.exit(1)
python
def create_issue(title, body, repo, token): '''create a Github issue, given a title, body, repo, and token. Parameters ========== title: the issue title body: the issue body repo: the full name of the repo token: the user's personal Github token ''' owner, name = repo.split('/') url = 'https://api.github.com/repos/%s/%s/issues' % (owner, name) data = {'title': title, 'body': body } headers = { "Authorization": "token %s" % token, "Accept": "application/vnd.github.symmetra-preview+json" } response = requests.post(url, data=json.dumps(data), headers=headers) if response.status_code in [201, 202]: url = response.json()['html_url'] bot.info(url) return url elif response.status_code == 404: bot.error('Cannot create issue. Does your token have scope repo?') sys.exit(1) else: bot.error('Cannot create issue %s' %title) bot.error(response.content) sys.exit(1)
[ "def", "create_issue", "(", "title", ",", "body", ",", "repo", ",", "token", ")", ":", "owner", ",", "name", "=", "repo", ".", "split", "(", "'/'", ")", "url", "=", "'https://api.github.com/repos/%s/%s/issues'", "%", "(", "owner", ",", "name", ")", "data...
create a Github issue, given a title, body, repo, and token. Parameters ========== title: the issue title body: the issue body repo: the full name of the repo token: the user's personal Github token
[ "create", "a", "Github", "issue", "given", "a", "title", "body", "repo", "and", "token", "." ]
e609172260b10cddadb2d2023ab26da8082a9feb
https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/github/utils.py#L26-L59
train
51,451
PlaidWeb/Pushl
pushl/webmentions.py
get_target
async def get_target(config, url): """ Given a URL, get the webmention endpoint """ previous = config.cache.get( 'target', url, schema_version=SCHEMA_VERSION) if config.cache else None headers = previous.caching if previous else None request = await utils.retry_get(config, url, headers=headers) if not request or not request.success: return previous if request.cached: return previous current = Target(request) if config.cache: config.cache.set('target', url, current) return current
python
async def get_target(config, url): """ Given a URL, get the webmention endpoint """ previous = config.cache.get( 'target', url, schema_version=SCHEMA_VERSION) if config.cache else None headers = previous.caching if previous else None request = await utils.retry_get(config, url, headers=headers) if not request or not request.success: return previous if request.cached: return previous current = Target(request) if config.cache: config.cache.set('target', url, current) return current
[ "async", "def", "get_target", "(", "config", ",", "url", ")", ":", "previous", "=", "config", ".", "cache", ".", "get", "(", "'target'", ",", "url", ",", "schema_version", "=", "SCHEMA_VERSION", ")", "if", "config", ".", "cache", "else", "None", "headers...
Given a URL, get the webmention endpoint
[ "Given", "a", "URL", "get", "the", "webmention", "endpoint" ]
5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c
https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/webmentions.py#L160-L180
train
51,452
PlaidWeb/Pushl
pushl/webmentions.py
Target.send
async def send(self, config, entry): """ Send a webmention to this target from the specified entry """ if self.endpoint: LOGGER.debug("%s -> %s", entry.url, self.url) try: await self.endpoint.send(config, entry.url, self.url) except Exception as err: # pylint:disable=broad-except LOGGER.warning("Ping %s: got %s: %s", self.url, err.__class__.__name__, err)
python
async def send(self, config, entry): """ Send a webmention to this target from the specified entry """ if self.endpoint: LOGGER.debug("%s -> %s", entry.url, self.url) try: await self.endpoint.send(config, entry.url, self.url) except Exception as err: # pylint:disable=broad-except LOGGER.warning("Ping %s: got %s: %s", self.url, err.__class__.__name__, err)
[ "async", "def", "send", "(", "self", ",", "config", ",", "entry", ")", ":", "if", "self", ".", "endpoint", ":", "LOGGER", ".", "debug", "(", "\"%s -> %s\"", ",", "entry", ".", "url", ",", "self", ".", "url", ")", "try", ":", "await", "self", ".", ...
Send a webmention to this target from the specified entry
[ "Send", "a", "webmention", "to", "this", "target", "from", "the", "specified", "entry" ]
5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c
https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/webmentions.py#L148-L156
train
51,453
vsoch/helpme
helpme/main/__init__.py
get_helper
def get_helper(name=None, quiet=True, **kwargs): ''' get the correct helper depending on the environment variable HELPME_CLIENT quiet: if True, suppress most output about the client (e.g. speak) ''' # Second priority, from environment from helpme.defaults import HELPME_CLIENT # First priority, from command line if name is not None: HELPME_CLIENT = name # If no obvious credential provided, we can use HELPME_CLIENT if HELPME_CLIENT == 'github': from .github import Helper; elif HELPME_CLIENT == 'uservoice': from .uservoice import Helper elif HELPME_CLIENT == 'discourse': from .discourse import Helper else: from .github import Helper Helper.name = HELPME_CLIENT Helper.quiet = quiet # Initialize the database return Helper()
python
def get_helper(name=None, quiet=True, **kwargs): ''' get the correct helper depending on the environment variable HELPME_CLIENT quiet: if True, suppress most output about the client (e.g. speak) ''' # Second priority, from environment from helpme.defaults import HELPME_CLIENT # First priority, from command line if name is not None: HELPME_CLIENT = name # If no obvious credential provided, we can use HELPME_CLIENT if HELPME_CLIENT == 'github': from .github import Helper; elif HELPME_CLIENT == 'uservoice': from .uservoice import Helper elif HELPME_CLIENT == 'discourse': from .discourse import Helper else: from .github import Helper Helper.name = HELPME_CLIENT Helper.quiet = quiet # Initialize the database return Helper()
[ "def", "get_helper", "(", "name", "=", "None", ",", "quiet", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# Second priority, from environment", "from", "helpme", ".", "defaults", "import", "HELPME_CLIENT", "# First priority, from command line", "if", "name", "...
get the correct helper depending on the environment variable HELPME_CLIENT quiet: if True, suppress most output about the client (e.g. speak)
[ "get", "the", "correct", "helper", "depending", "on", "the", "environment", "variable", "HELPME_CLIENT" ]
e609172260b10cddadb2d2023ab26da8082a9feb
https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/__init__.py#L23-L48
train
51,454
iotile/baBLE
interfaces/python/bable_interface/scripts/mock_bable_interface.py
mock_bable
def mock_bable(monkeypatch): """ Mock the BaBLEInterface class with some controllers inside. """ mocked_bable = MockBaBLE() mocked_bable.set_controllers([ Controller(0, '11:22:33:44:55:66', '#0'), Controller(1, '22:33:44:55:66:11', '#1', settings={'powered': True, 'low_energy': True}), Controller(2, '33:44:55:66:11:22', '#2', settings={'powered': True}) ]) monkeypatch.setattr(bable_interface, 'BaBLEInterface', lambda: mocked_bable) return mocked_bable
python
def mock_bable(monkeypatch): """ Mock the BaBLEInterface class with some controllers inside. """ mocked_bable = MockBaBLE() mocked_bable.set_controllers([ Controller(0, '11:22:33:44:55:66', '#0'), Controller(1, '22:33:44:55:66:11', '#1', settings={'powered': True, 'low_energy': True}), Controller(2, '33:44:55:66:11:22', '#2', settings={'powered': True}) ]) monkeypatch.setattr(bable_interface, 'BaBLEInterface', lambda: mocked_bable) return mocked_bable
[ "def", "mock_bable", "(", "monkeypatch", ")", ":", "mocked_bable", "=", "MockBaBLE", "(", ")", "mocked_bable", ".", "set_controllers", "(", "[", "Controller", "(", "0", ",", "'11:22:33:44:55:66'", ",", "'#0'", ")", ",", "Controller", "(", "1", ",", "'22:33:4...
Mock the BaBLEInterface class with some controllers inside.
[ "Mock", "the", "BaBLEInterface", "class", "with", "some", "controllers", "inside", "." ]
faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db
https://github.com/iotile/baBLE/blob/faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db/interfaces/python/bable_interface/scripts/mock_bable_interface.py#L542-L553
train
51,455
SetBased/py-stratum
pystratum/command/PyStratumCommand.py
PyStratumCommand.handle
def handle(self): """ Executes the actual Stratum program. """ self.output = PyStratumStyle(self.input, self.output) command = self.get_application().find('constants') ret = command.execute(self.input, self.output) if ret: return ret command = self.get_application().find('loader') ret = command.execute(self.input, self.output) if ret: return ret command = self.get_application().find('wrapper') ret = command.execute(self.input, self.output) self.output.writeln('') return ret
python
def handle(self): """ Executes the actual Stratum program. """ self.output = PyStratumStyle(self.input, self.output) command = self.get_application().find('constants') ret = command.execute(self.input, self.output) if ret: return ret command = self.get_application().find('loader') ret = command.execute(self.input, self.output) if ret: return ret command = self.get_application().find('wrapper') ret = command.execute(self.input, self.output) self.output.writeln('') return ret
[ "def", "handle", "(", "self", ")", ":", "self", ".", "output", "=", "PyStratumStyle", "(", "self", ".", "input", ",", "self", ".", "output", ")", "command", "=", "self", ".", "get_application", "(", ")", ".", "find", "(", "'constants'", ")", "ret", "...
Executes the actual Stratum program.
[ "Executes", "the", "actual", "Stratum", "program", "." ]
7c5ffaa2fdd03f865832a5190b5897ff2c0e3155
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/command/PyStratumCommand.py#L26-L47
train
51,456
nephila/djangocms-helper
djangocms_helper/utils.py
load_from_file
def load_from_file(module_path): """ Load a python module from its absolute filesystem path Borrowed from django-cms """ from imp import load_module, PY_SOURCE imported = None if module_path: with open(module_path, 'r') as openfile: imported = load_module('mod', openfile, module_path, ('imported', 'r', PY_SOURCE)) return imported
python
def load_from_file(module_path): """ Load a python module from its absolute filesystem path Borrowed from django-cms """ from imp import load_module, PY_SOURCE imported = None if module_path: with open(module_path, 'r') as openfile: imported = load_module('mod', openfile, module_path, ('imported', 'r', PY_SOURCE)) return imported
[ "def", "load_from_file", "(", "module_path", ")", ":", "from", "imp", "import", "load_module", ",", "PY_SOURCE", "imported", "=", "None", "if", "module_path", ":", "with", "open", "(", "module_path", ",", "'r'", ")", "as", "openfile", ":", "imported", "=", ...
Load a python module from its absolute filesystem path Borrowed from django-cms
[ "Load", "a", "python", "module", "from", "its", "absolute", "filesystem", "path" ]
3fe53aee7b06922112c5e4445b74afeb86f6d836
https://github.com/nephila/djangocms-helper/blob/3fe53aee7b06922112c5e4445b74afeb86f6d836/djangocms_helper/utils.py#L58-L70
train
51,457
nephila/djangocms-helper
djangocms_helper/utils.py
ensure_unicoded_and_unique
def ensure_unicoded_and_unique(args_list, application): """ Iterate over args_list, make it unicode if needed and ensure that there are no duplicates. Returns list of unicoded arguments in the same order. """ unicoded_args = [] for argument in args_list: argument = (six.u(argument) if not isinstance(argument, six.text_type) else argument) if argument not in unicoded_args or argument == application: unicoded_args.append(argument) return unicoded_args
python
def ensure_unicoded_and_unique(args_list, application): """ Iterate over args_list, make it unicode if needed and ensure that there are no duplicates. Returns list of unicoded arguments in the same order. """ unicoded_args = [] for argument in args_list: argument = (six.u(argument) if not isinstance(argument, six.text_type) else argument) if argument not in unicoded_args or argument == application: unicoded_args.append(argument) return unicoded_args
[ "def", "ensure_unicoded_and_unique", "(", "args_list", ",", "application", ")", ":", "unicoded_args", "=", "[", "]", "for", "argument", "in", "args_list", ":", "argument", "=", "(", "six", ".", "u", "(", "argument", ")", "if", "not", "isinstance", "(", "ar...
Iterate over args_list, make it unicode if needed and ensure that there are no duplicates. Returns list of unicoded arguments in the same order.
[ "Iterate", "over", "args_list", "make", "it", "unicode", "if", "needed", "and", "ensure", "that", "there", "are", "no", "duplicates", ".", "Returns", "list", "of", "unicoded", "arguments", "in", "the", "same", "order", "." ]
3fe53aee7b06922112c5e4445b74afeb86f6d836
https://github.com/nephila/djangocms-helper/blob/3fe53aee7b06922112c5e4445b74afeb86f6d836/djangocms_helper/utils.py#L407-L419
train
51,458
SetBased/py-stratum
pystratum/Util.py
Util.write_two_phases
def write_two_phases(filename, data, io): """ Writes a file in two phase to the filesystem. First write the data to a temporary file (in the same directory) and than renames the temporary file. If the file already exists and its content is equal to the data that must be written no action is taken. This has the following advantages: * In case of some write error (e.g. disk full) the original file is kep in tact and no file with partially data is written. * Renaming a file is atomic. So, running processes will never read a partially written data. :param str filename: The name of the file were the data must be stored. :param str data: The data that must be written. :param pystratum.style.PyStratumStyle.PyStratumStyle io: The output decorator. """ write_flag = True if os.path.exists(filename): with open(filename, 'r') as file: old_data = file.read() if data == old_data: write_flag = False if write_flag: tmp_filename = filename + '.tmp' with open(tmp_filename, 'w+') as file: file.write(data) os.replace(tmp_filename, filename) io.text('Wrote: <fso>{0}</fso>'.format(filename)) else: io.text('File <fso>{0}</fso> is up to date'.format(filename))
python
def write_two_phases(filename, data, io): """ Writes a file in two phase to the filesystem. First write the data to a temporary file (in the same directory) and than renames the temporary file. If the file already exists and its content is equal to the data that must be written no action is taken. This has the following advantages: * In case of some write error (e.g. disk full) the original file is kep in tact and no file with partially data is written. * Renaming a file is atomic. So, running processes will never read a partially written data. :param str filename: The name of the file were the data must be stored. :param str data: The data that must be written. :param pystratum.style.PyStratumStyle.PyStratumStyle io: The output decorator. """ write_flag = True if os.path.exists(filename): with open(filename, 'r') as file: old_data = file.read() if data == old_data: write_flag = False if write_flag: tmp_filename = filename + '.tmp' with open(tmp_filename, 'w+') as file: file.write(data) os.replace(tmp_filename, filename) io.text('Wrote: <fso>{0}</fso>'.format(filename)) else: io.text('File <fso>{0}</fso> is up to date'.format(filename))
[ "def", "write_two_phases", "(", "filename", ",", "data", ",", "io", ")", ":", "write_flag", "=", "True", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "file", ":", "old_data...
Writes a file in two phase to the filesystem. First write the data to a temporary file (in the same directory) and than renames the temporary file. If the file already exists and its content is equal to the data that must be written no action is taken. This has the following advantages: * In case of some write error (e.g. disk full) the original file is kep in tact and no file with partially data is written. * Renaming a file is atomic. So, running processes will never read a partially written data. :param str filename: The name of the file were the data must be stored. :param str data: The data that must be written. :param pystratum.style.PyStratumStyle.PyStratumStyle io: The output decorator.
[ "Writes", "a", "file", "in", "two", "phase", "to", "the", "filesystem", "." ]
7c5ffaa2fdd03f865832a5190b5897ff2c0e3155
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/Util.py#L14-L43
train
51,459
PlaidWeb/Pushl
pushl/entries.py
get_entry
async def get_entry(config, url): """ Given an entry URL, return the entry Arguments: config -- the configuration url -- the URL of the entry Returns: 3-tuple of (current, previous, updated) """ previous = config.cache.get( 'entry', url, schema_version=SCHEMA_VERSION) if config.cache else None headers = previous.caching if previous else None request = await utils.retry_get(config, url, headers=headers) if not request or not request.success: LOGGER.error("Could not get entry %s: %d", url, request.status if request else -1) return None, previous, False # cache hit if request.cached: return previous, previous, False current = Entry(request) # Content updated if config.cache: config.cache.set('entry', url, current) return current, previous, (not previous or previous.digest != current.digest or previous.status != current.status)
python
async def get_entry(config, url): """ Given an entry URL, return the entry Arguments: config -- the configuration url -- the URL of the entry Returns: 3-tuple of (current, previous, updated) """ previous = config.cache.get( 'entry', url, schema_version=SCHEMA_VERSION) if config.cache else None headers = previous.caching if previous else None request = await utils.retry_get(config, url, headers=headers) if not request or not request.success: LOGGER.error("Could not get entry %s: %d", url, request.status if request else -1) return None, previous, False # cache hit if request.cached: return previous, previous, False current = Entry(request) # Content updated if config.cache: config.cache.set('entry', url, current) return current, previous, (not previous or previous.digest != current.digest or previous.status != current.status)
[ "async", "def", "get_entry", "(", "config", ",", "url", ")", ":", "previous", "=", "config", ".", "cache", ".", "get", "(", "'entry'", ",", "url", ",", "schema_version", "=", "SCHEMA_VERSION", ")", "if", "config", ".", "cache", "else", "None", "headers",...
Given an entry URL, return the entry Arguments: config -- the configuration url -- the URL of the entry Returns: 3-tuple of (current, previous, updated)
[ "Given", "an", "entry", "URL", "return", "the", "entry" ]
5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c
https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/entries.py#L108-L142
train
51,460
PlaidWeb/Pushl
pushl/entries.py
Entry._check_rel
def _check_rel(attrs, rel_whitelist, rel_blacklist): """ Check a link's relations against the whitelist or blacklist. First, this will reject based on blacklist. Next, if there is a whitelist, there must be at least one rel that matches. To explicitly allow links without a rel you can add None to the whitelist (e.g. ['in-reply-to',None]) """ rels = attrs.get('rel', [None]) if rel_blacklist: # Never return True for a link whose rel appears in the blacklist for rel in rels: if rel in rel_blacklist: return False if rel_whitelist: # If there is a whitelist for rels, only return true for a rel that # appears in it for rel in rels: if rel in rel_whitelist: return True # If there is a whitelist and we don't match, then reject return False return True
python
def _check_rel(attrs, rel_whitelist, rel_blacklist): """ Check a link's relations against the whitelist or blacklist. First, this will reject based on blacklist. Next, if there is a whitelist, there must be at least one rel that matches. To explicitly allow links without a rel you can add None to the whitelist (e.g. ['in-reply-to',None]) """ rels = attrs.get('rel', [None]) if rel_blacklist: # Never return True for a link whose rel appears in the blacklist for rel in rels: if rel in rel_blacklist: return False if rel_whitelist: # If there is a whitelist for rels, only return true for a rel that # appears in it for rel in rels: if rel in rel_whitelist: return True # If there is a whitelist and we don't match, then reject return False return True
[ "def", "_check_rel", "(", "attrs", ",", "rel_whitelist", ",", "rel_blacklist", ")", ":", "rels", "=", "attrs", ".", "get", "(", "'rel'", ",", "[", "None", "]", ")", "if", "rel_blacklist", ":", "# Never return True for a link whose rel appears in the blacklist", "f...
Check a link's relations against the whitelist or blacklist. First, this will reject based on blacklist. Next, if there is a whitelist, there must be at least one rel that matches. To explicitly allow links without a rel you can add None to the whitelist (e.g. ['in-reply-to',None])
[ "Check", "a", "link", "s", "relations", "against", "the", "whitelist", "or", "blacklist", "." ]
5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c
https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/entries.py#L61-L88
train
51,461
PlaidWeb/Pushl
pushl/entries.py
Entry._domain_differs
def _domain_differs(self, href): """ Check that a link is not on the same domain as the source URL """ target = utils.get_domain(href) if not target: return False origin = utils.get_domain(self.url) return target != origin
python
def _domain_differs(self, href): """ Check that a link is not on the same domain as the source URL """ target = utils.get_domain(href) if not target: return False origin = utils.get_domain(self.url) return target != origin
[ "def", "_domain_differs", "(", "self", ",", "href", ")", ":", "target", "=", "utils", ".", "get_domain", "(", "href", ")", "if", "not", "target", ":", "return", "False", "origin", "=", "utils", ".", "get_domain", "(", "self", ".", "url", ")", "return",...
Check that a link is not on the same domain as the source URL
[ "Check", "that", "a", "link", "is", "not", "on", "the", "same", "domain", "as", "the", "source", "URL" ]
5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c
https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/entries.py#L90-L97
train
51,462
PlaidWeb/Pushl
pushl/entries.py
Entry.get_targets
def get_targets(self, config): """ Given an Entry object, return all of the outgoing links. """ return {urllib.parse.urljoin(self.url, attrs['href']) for attrs in self._targets if self._check_rel(attrs, config.rel_whitelist, config.rel_blacklist) and self._domain_differs(attrs['href'])}
python
def get_targets(self, config): """ Given an Entry object, return all of the outgoing links. """ return {urllib.parse.urljoin(self.url, attrs['href']) for attrs in self._targets if self._check_rel(attrs, config.rel_whitelist, config.rel_blacklist) and self._domain_differs(attrs['href'])}
[ "def", "get_targets", "(", "self", ",", "config", ")", ":", "return", "{", "urllib", ".", "parse", ".", "urljoin", "(", "self", ".", "url", ",", "attrs", "[", "'href'", "]", ")", "for", "attrs", "in", "self", ".", "_targets", "if", "self", ".", "_c...
Given an Entry object, return all of the outgoing links.
[ "Given", "an", "Entry", "object", "return", "all", "of", "the", "outgoing", "links", "." ]
5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c
https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/entries.py#L99-L105
train
51,463
SetBased/py-stratum
pystratum/command/LoaderCommand.py
LoaderCommand.handle
def handle(self): """ Executes loader command. """ self.output = PyStratumStyle(self.input, self.output) config_file = self.argument('config_file') sources = self.argument('file_names') status = self.run_command(config_file, sources) return status
python
def handle(self): """ Executes loader command. """ self.output = PyStratumStyle(self.input, self.output) config_file = self.argument('config_file') sources = self.argument('file_names') status = self.run_command(config_file, sources) return status
[ "def", "handle", "(", "self", ")", ":", "self", ".", "output", "=", "PyStratumStyle", "(", "self", ".", "input", ",", "self", ".", "output", ")", "config_file", "=", "self", ".", "argument", "(", "'config_file'", ")", "sources", "=", "self", ".", "argu...
Executes loader command.
[ "Executes", "loader", "command", "." ]
7c5ffaa2fdd03f865832a5190b5897ff2c0e3155
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/command/LoaderCommand.py#L29-L40
train
51,464
DreamLab/VmShepherd
src/vmshepherd/iaas/dummy_driver.py
DummyIaasDriver.create_vm
async def create_vm(self, *, preset_name, image, flavor, security_groups=None, userdata=None, key_name=None, availability_zone=None, subnet=None): """ Dummy create_vm func. """ info = { 'id': next(self._id_it), 'name': preset_name, 'ip': ['127.0.0.1'], 'created': 0, 'state': VmState.RUNNING, 'flavor': flavor, 'image': image, 'metadata': {'test-meta': 'abctest'}, 'timed_shutdown_at': 1522753481, 'tags': ['a-tag', 'b-tag', 'c-tag'] } logging.debug('Prepare vm: %s', info) vm = Vm(self, **info) self._vms[vm.id] = vm logging.debug('Create: %s', vm) return None
python
async def create_vm(self, *, preset_name, image, flavor, security_groups=None, userdata=None, key_name=None, availability_zone=None, subnet=None): """ Dummy create_vm func. """ info = { 'id': next(self._id_it), 'name': preset_name, 'ip': ['127.0.0.1'], 'created': 0, 'state': VmState.RUNNING, 'flavor': flavor, 'image': image, 'metadata': {'test-meta': 'abctest'}, 'timed_shutdown_at': 1522753481, 'tags': ['a-tag', 'b-tag', 'c-tag'] } logging.debug('Prepare vm: %s', info) vm = Vm(self, **info) self._vms[vm.id] = vm logging.debug('Create: %s', vm) return None
[ "async", "def", "create_vm", "(", "self", ",", "*", ",", "preset_name", ",", "image", ",", "flavor", ",", "security_groups", "=", "None", ",", "userdata", "=", "None", ",", "key_name", "=", "None", ",", "availability_zone", "=", "None", ",", "subnet", "=...
Dummy create_vm func.
[ "Dummy", "create_vm", "func", "." ]
709a412c372b897d53808039c5c64a8b69c12c8d
https://github.com/DreamLab/VmShepherd/blob/709a412c372b897d53808039c5c64a8b69c12c8d/src/vmshepherd/iaas/dummy_driver.py#L34-L56
train
51,465
DreamLab/VmShepherd
src/vmshepherd/iaas/dummy_driver.py
DummyIaasDriver.list_vms
async def list_vms(self, preset_name): """Dummy list_vms func""" return list(vm for vm in self._vms.values() if vm.name == preset_name)
python
async def list_vms(self, preset_name): """Dummy list_vms func""" return list(vm for vm in self._vms.values() if vm.name == preset_name)
[ "async", "def", "list_vms", "(", "self", ",", "preset_name", ")", ":", "return", "list", "(", "vm", "for", "vm", "in", "self", ".", "_vms", ".", "values", "(", ")", "if", "vm", ".", "name", "==", "preset_name", ")" ]
Dummy list_vms func
[ "Dummy", "list_vms", "func" ]
709a412c372b897d53808039c5c64a8b69c12c8d
https://github.com/DreamLab/VmShepherd/blob/709a412c372b897d53808039c5c64a8b69c12c8d/src/vmshepherd/iaas/dummy_driver.py#L59-L61
train
51,466
DreamLab/VmShepherd
src/vmshepherd/iaas/dummy_driver.py
DummyIaasDriver.terminate_vm
async def terminate_vm(self, vm_id): """ Dummy terminate_vm func """ if vm_id not in self._vms: raise DummyIaasVmNotFound() del self._vms[vm_id] return None
python
async def terminate_vm(self, vm_id): """ Dummy terminate_vm func """ if vm_id not in self._vms: raise DummyIaasVmNotFound() del self._vms[vm_id] return None
[ "async", "def", "terminate_vm", "(", "self", ",", "vm_id", ")", ":", "if", "vm_id", "not", "in", "self", ".", "_vms", ":", "raise", "DummyIaasVmNotFound", "(", ")", "del", "self", ".", "_vms", "[", "vm_id", "]", "return", "None" ]
Dummy terminate_vm func
[ "Dummy", "terminate_vm", "func" ]
709a412c372b897d53808039c5c64a8b69c12c8d
https://github.com/DreamLab/VmShepherd/blob/709a412c372b897d53808039c5c64a8b69c12c8d/src/vmshepherd/iaas/dummy_driver.py#L64-L69
train
51,467
DreamLab/VmShepherd
src/vmshepherd/iaas/dummy_driver.py
DummyIaasDriver.get_vm
async def get_vm(self, vm_id): """ Dummy get_vm func """ if vm_id not in self._vms: raise DummyIaasVmNotFound() return self._vms[vm_id]
python
async def get_vm(self, vm_id): """ Dummy get_vm func """ if vm_id not in self._vms: raise DummyIaasVmNotFound() return self._vms[vm_id]
[ "async", "def", "get_vm", "(", "self", ",", "vm_id", ")", ":", "if", "vm_id", "not", "in", "self", ".", "_vms", ":", "raise", "DummyIaasVmNotFound", "(", ")", "return", "self", ".", "_vms", "[", "vm_id", "]" ]
Dummy get_vm func
[ "Dummy", "get_vm", "func" ]
709a412c372b897d53808039c5c64a8b69c12c8d
https://github.com/DreamLab/VmShepherd/blob/709a412c372b897d53808039c5c64a8b69c12c8d/src/vmshepherd/iaas/dummy_driver.py#L72-L76
train
51,468
mjirik/io3d
io3d/misc.py
suggest_filename
def suggest_filename(file_path, exists=None): """ Try if exist path and append number to its end. For debug you can set as input if file exists or not. """ import os.path import re if not isinstance(exists, bool): exists = os.path.exists(file_path) if exists: file_path, file_extension = os.path.splitext(file_path) # print(file_path) m = re.search(r"_\d+$", file_path) if m is None: # cislo = 2 new_cislo_str = "_2" else: cislostr = (m.group()) cislo = int(cislostr[1:]) + 1 # it is normal number file_path = file_path[:-len(cislostr)] new_cislo_str = "_" + str(cislo) file_path = file_path + new_cislo_str + file_extension # .zfill(2) # trorcha rekurze file_path = suggest_filename(file_path) return file_path
python
def suggest_filename(file_path, exists=None): """ Try if exist path and append number to its end. For debug you can set as input if file exists or not. """ import os.path import re if not isinstance(exists, bool): exists = os.path.exists(file_path) if exists: file_path, file_extension = os.path.splitext(file_path) # print(file_path) m = re.search(r"_\d+$", file_path) if m is None: # cislo = 2 new_cislo_str = "_2" else: cislostr = (m.group()) cislo = int(cislostr[1:]) + 1 # it is normal number file_path = file_path[:-len(cislostr)] new_cislo_str = "_" + str(cislo) file_path = file_path + new_cislo_str + file_extension # .zfill(2) # trorcha rekurze file_path = suggest_filename(file_path) return file_path
[ "def", "suggest_filename", "(", "file_path", ",", "exists", "=", "None", ")", ":", "import", "os", ".", "path", "import", "re", "if", "not", "isinstance", "(", "exists", ",", "bool", ")", ":", "exists", "=", "os", ".", "path", ".", "exists", "(", "fi...
Try if exist path and append number to its end. For debug you can set as input if file exists or not.
[ "Try", "if", "exist", "path", "and", "append", "number", "to", "its", "end", ".", "For", "debug", "you", "can", "set", "as", "input", "if", "file", "exists", "or", "not", "." ]
ccaf3e378dcc967f2565d477fc27583fd0f61fcc
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/misc.py#L30-L58
train
51,469
mjirik/io3d
io3d/misc.py
obj_from_file
def obj_from_file(filename='annotation.yaml', filetype='auto'): ''' Read object from file ''' if filetype == 'auto': _, ext = os.path.splitext(filename) filetype = ext[1:] if filetype in ('yaml', 'yml'): from ruamel.yaml import YAML yaml = YAML(typ="unsafe") with open(filename, encoding="utf-8") as f: obj = yaml.load(f) if obj is None: obj = {} # import yaml # with open(filename, encoding="utf-8") as f: # intext = f.read() # obj = yaml.load(intext) elif filetype in ('pickle', 'pkl', 'pklz', 'picklezip'): fcontent = read_pkl_and_pklz(filename) # import pickle if sys.version_info[0] < 3: import cPickle as pickle else: import _pickle as pickle # import sPickle as pickle if sys.version_info.major == 2: obj = pickle.loads(fcontent) else: obj = pickle.loads(fcontent, encoding="latin1") else: logger.error('Unknown filetype ' + filetype) return obj
python
def obj_from_file(filename='annotation.yaml', filetype='auto'): ''' Read object from file ''' if filetype == 'auto': _, ext = os.path.splitext(filename) filetype = ext[1:] if filetype in ('yaml', 'yml'): from ruamel.yaml import YAML yaml = YAML(typ="unsafe") with open(filename, encoding="utf-8") as f: obj = yaml.load(f) if obj is None: obj = {} # import yaml # with open(filename, encoding="utf-8") as f: # intext = f.read() # obj = yaml.load(intext) elif filetype in ('pickle', 'pkl', 'pklz', 'picklezip'): fcontent = read_pkl_and_pklz(filename) # import pickle if sys.version_info[0] < 3: import cPickle as pickle else: import _pickle as pickle # import sPickle as pickle if sys.version_info.major == 2: obj = pickle.loads(fcontent) else: obj = pickle.loads(fcontent, encoding="latin1") else: logger.error('Unknown filetype ' + filetype) return obj
[ "def", "obj_from_file", "(", "filename", "=", "'annotation.yaml'", ",", "filetype", "=", "'auto'", ")", ":", "if", "filetype", "==", "'auto'", ":", "_", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "filetype", "=", "ext", ...
Read object from file
[ "Read", "object", "from", "file" ]
ccaf3e378dcc967f2565d477fc27583fd0f61fcc
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/misc.py#L61-L93
train
51,470
mjirik/io3d
io3d/misc.py
read_pkl_and_pklz
def read_pkl_and_pklz(filename): """ Try read zipped or not zipped pickle file """ fcontent = None try: import gzip f = gzip.open(filename, 'rb') fcontent = f.read() f.close() except IOError as e: # if the problem is in not gzip file logger.info("Input gzip exception: " + str(e)) f = open(filename, 'rb') fcontent = f.read() f.close() except Exception as e: # other problem import traceback logger.error("Input gzip exception: " + str(e)) logger.error(traceback.format_exc()) return fcontent
python
def read_pkl_and_pklz(filename): """ Try read zipped or not zipped pickle file """ fcontent = None try: import gzip f = gzip.open(filename, 'rb') fcontent = f.read() f.close() except IOError as e: # if the problem is in not gzip file logger.info("Input gzip exception: " + str(e)) f = open(filename, 'rb') fcontent = f.read() f.close() except Exception as e: # other problem import traceback logger.error("Input gzip exception: " + str(e)) logger.error(traceback.format_exc()) return fcontent
[ "def", "read_pkl_and_pklz", "(", "filename", ")", ":", "fcontent", "=", "None", "try", ":", "import", "gzip", "f", "=", "gzip", ".", "open", "(", "filename", ",", "'rb'", ")", "fcontent", "=", "f", ".", "read", "(", ")", "f", ".", "close", "(", ")"...
Try read zipped or not zipped pickle file
[ "Try", "read", "zipped", "or", "not", "zipped", "pickle", "file" ]
ccaf3e378dcc967f2565d477fc27583fd0f61fcc
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/misc.py#L96-L118
train
51,471
mjirik/io3d
io3d/misc.py
obj_to_file
def obj_to_file(obj, filename, filetype='auto', ndarray_to_list=False, squeeze=True): '''Writes annotation in file. :param filetype: auto yaml pkl, pickle pklz, picklezip :param ndarray_to_list: convert ndarrays in obj to lists :param squeeze: squeeze ndarray ''' # import json # with open(filename, mode='w') as f: # json.dump(annotation,f) if ndarray_to_list: obj = ndarray_to_list_in_structure(obj, squeeze=squeeze) # write to yaml d = os.path.dirname(os.path.abspath(filename)) if not os.path.exists(d): os.makedirs(d) if filetype == 'auto': _, ext = os.path.splitext(filename) filetype = ext[1:] if filetype in ('yaml', 'yml'): # import yaml from ruamel.yaml import YAML yaml = YAML(typ="unsafe") with open(filename, 'wt', encoding="utf-8") as f: yaml.dump(obj, f) # if sys.version_info.major == 2: # with open(filename, 'wb') as f: # yaml.dump(obj, f, encoding="utf-8") # else: # with open(filename, "w", encoding="utf-8") as f: # yaml.dump(obj, f) elif filetype in ('pickle', 'pkl'): f = open(filename, 'wb') logger.info("filename " + filename) # if sys.version_info[0] < 3: import cPickle as pickle # else: import _pickle as pickle import pickle pickle.dump(obj, f, -1) f.close elif filetype in ('streamingpicklezip', 'spklz'): # this is not working :-( import gzip import sPickle as pickle f = gzip.open(filename, 'wb', compresslevel=1) # f = open(filename, 'wb') pickle.s_dump(obj, f) f.close elif filetype in ('picklezip', 'pklz'): import gzip if sys.version_info[0] < 3: import cPickle as pickle else: import _pickle as pickle f = gzip.open(filename, 'wb', compresslevel=1) # f = open(filename, 'wb') pickle.dump(obj, f) f.close elif filetype in('mat'): import scipy.io as sio sio.savemat(filename, obj) else: logger.error('Unknown filetype ' + filetype)
python
def obj_to_file(obj, filename, filetype='auto', ndarray_to_list=False, squeeze=True): '''Writes annotation in file. :param filetype: auto yaml pkl, pickle pklz, picklezip :param ndarray_to_list: convert ndarrays in obj to lists :param squeeze: squeeze ndarray ''' # import json # with open(filename, mode='w') as f: # json.dump(annotation,f) if ndarray_to_list: obj = ndarray_to_list_in_structure(obj, squeeze=squeeze) # write to yaml d = os.path.dirname(os.path.abspath(filename)) if not os.path.exists(d): os.makedirs(d) if filetype == 'auto': _, ext = os.path.splitext(filename) filetype = ext[1:] if filetype in ('yaml', 'yml'): # import yaml from ruamel.yaml import YAML yaml = YAML(typ="unsafe") with open(filename, 'wt', encoding="utf-8") as f: yaml.dump(obj, f) # if sys.version_info.major == 2: # with open(filename, 'wb') as f: # yaml.dump(obj, f, encoding="utf-8") # else: # with open(filename, "w", encoding="utf-8") as f: # yaml.dump(obj, f) elif filetype in ('pickle', 'pkl'): f = open(filename, 'wb') logger.info("filename " + filename) # if sys.version_info[0] < 3: import cPickle as pickle # else: import _pickle as pickle import pickle pickle.dump(obj, f, -1) f.close elif filetype in ('streamingpicklezip', 'spklz'): # this is not working :-( import gzip import sPickle as pickle f = gzip.open(filename, 'wb', compresslevel=1) # f = open(filename, 'wb') pickle.s_dump(obj, f) f.close elif filetype in ('picklezip', 'pklz'): import gzip if sys.version_info[0] < 3: import cPickle as pickle else: import _pickle as pickle f = gzip.open(filename, 'wb', compresslevel=1) # f = open(filename, 'wb') pickle.dump(obj, f) f.close elif filetype in('mat'): import scipy.io as sio sio.savemat(filename, obj) else: logger.error('Unknown filetype ' + filetype)
[ "def", "obj_to_file", "(", "obj", ",", "filename", ",", "filetype", "=", "'auto'", ",", "ndarray_to_list", "=", "False", ",", "squeeze", "=", "True", ")", ":", "# import json", "# with open(filename, mode='w') as f:", "# json.dump(annotation,f)", "if", "ndarray_to_...
Writes annotation in file. :param filetype: auto yaml pkl, pickle pklz, picklezip :param ndarray_to_list: convert ndarrays in obj to lists :param squeeze: squeeze ndarray
[ "Writes", "annotation", "in", "file", "." ]
ccaf3e378dcc967f2565d477fc27583fd0f61fcc
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/misc.py#L121-L189
train
51,472
mjirik/io3d
io3d/misc.py
resize_to_shape
def resize_to_shape(data, shape, zoom=None, mode='nearest', order=0): """ Function resize input data to specific shape. :param data: input 3d array-like data :param shape: shape of output data :param zoom: zoom is used for back compatibility :mode: default is 'nearest' """ # @TODO remove old code in except part try: # rint 'pred vyjimkou' # aise Exception ('test without skimage') # rint 'za vyjimkou' import skimage import skimage.transform # Now we need reshape seeds and segmentation to original size segm_orig_scale = skimage.transform.resize( data, shape, order=0, preserve_range=True, mode="constant", ) segmentation = segm_orig_scale logger.debug('resize to orig with skimage') except: import scipy import scipy.ndimage dtype = data.dtype if zoom is None: zoom = shape / np.asarray(data.shape).astype(np.double) segm_orig_scale = scipy.ndimage.zoom( data, 1.0 / zoom, mode=mode, order=order ).astype(dtype) logger.debug('resize to orig with scipy.ndimage') # @TODO odstranit hack pro oříznutí na stejnou velikost # v podstatě je to vyřešeno, ale nechalo by se to dělat elegantněji v zoom # tam je bohužel patrně bug # rint 'd3d ', self.data3d.shape # rint 's orig scale shape ', segm_orig_scale.shape shp = [ np.min([segm_orig_scale.shape[0], shape[0]]), np.min([segm_orig_scale.shape[1], shape[1]]), np.min([segm_orig_scale.shape[2], shape[2]]), ] # elf.data3d = self.data3d[0:shp[0], 0:shp[1], 0:shp[2]] # mport ipdb; ipdb.set_trace() # BREAKPOINT segmentation = np.zeros(shape, dtype=dtype) segmentation[ 0:shp[0], 0:shp[1], 0:shp[2]] = segm_orig_scale[0:shp[0], 0:shp[1], 0:shp[2]] del segm_orig_scale return segmentation
python
def resize_to_shape(data, shape, zoom=None, mode='nearest', order=0): """ Function resize input data to specific shape. :param data: input 3d array-like data :param shape: shape of output data :param zoom: zoom is used for back compatibility :mode: default is 'nearest' """ # @TODO remove old code in except part try: # rint 'pred vyjimkou' # aise Exception ('test without skimage') # rint 'za vyjimkou' import skimage import skimage.transform # Now we need reshape seeds and segmentation to original size segm_orig_scale = skimage.transform.resize( data, shape, order=0, preserve_range=True, mode="constant", ) segmentation = segm_orig_scale logger.debug('resize to orig with skimage') except: import scipy import scipy.ndimage dtype = data.dtype if zoom is None: zoom = shape / np.asarray(data.shape).astype(np.double) segm_orig_scale = scipy.ndimage.zoom( data, 1.0 / zoom, mode=mode, order=order ).astype(dtype) logger.debug('resize to orig with scipy.ndimage') # @TODO odstranit hack pro oříznutí na stejnou velikost # v podstatě je to vyřešeno, ale nechalo by se to dělat elegantněji v zoom # tam je bohužel patrně bug # rint 'd3d ', self.data3d.shape # rint 's orig scale shape ', segm_orig_scale.shape shp = [ np.min([segm_orig_scale.shape[0], shape[0]]), np.min([segm_orig_scale.shape[1], shape[1]]), np.min([segm_orig_scale.shape[2], shape[2]]), ] # elf.data3d = self.data3d[0:shp[0], 0:shp[1], 0:shp[2]] # mport ipdb; ipdb.set_trace() # BREAKPOINT segmentation = np.zeros(shape, dtype=dtype) segmentation[ 0:shp[0], 0:shp[1], 0:shp[2]] = segm_orig_scale[0:shp[0], 0:shp[1], 0:shp[2]] del segm_orig_scale return segmentation
[ "def", "resize_to_shape", "(", "data", ",", "shape", ",", "zoom", "=", "None", ",", "mode", "=", "'nearest'", ",", "order", "=", "0", ")", ":", "# @TODO remove old code in except part", "try", ":", "# rint 'pred vyjimkou'", "# aise Exception ('test without skimage')",...
Function resize input data to specific shape. :param data: input 3d array-like data :param shape: shape of output data :param zoom: zoom is used for back compatibility :mode: default is 'nearest'
[ "Function", "resize", "input", "data", "to", "specific", "shape", "." ]
ccaf3e378dcc967f2565d477fc27583fd0f61fcc
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/misc.py#L191-L253
train
51,473
mjirik/io3d
io3d/misc.py
use_economic_dtype
def use_economic_dtype(data3d, slope=1, inter=0, dtype=None): """ Use more economic integer-like dtype if it is possible. :param data3d: :param dtype: if dtype is not used, the automatic is used :return: """ if dtype is None: dtype = data3d.dtype if issubclass(dtype.type, np.integer): mn = data3d.min() * slope + inter mx = data3d.max() * slope + inter if suits_with_dtype(mn, mx, dtype=np.uint8): dtype = np.uint8 elif suits_with_dtype(mn, mx, dtype=np.int8): dtype = np.int8 elif suits_with_dtype(mn, mx, dtype=np.uint16): dtype = np.uint16 elif suits_with_dtype(mn, mx, dtype=np.int16): dtype = np.int16 elif suits_with_dtype(mn, mx, dtype=np.uint32): dtype = np.uint32 elif suits_with_dtype(mn, mx, dtype=np.int32): dtype = np.int32 # new_data3d = ((np.float(slope) * data3d) + np.float(inter)).astype(dtype) if slope == 1 and inter == 0: # this can prevent out of memmory new_data3d = data3d.astype(dtype) else: new_data3d = ((slope * data3d) + inter).astype(dtype) return new_data3d
python
def use_economic_dtype(data3d, slope=1, inter=0, dtype=None): """ Use more economic integer-like dtype if it is possible. :param data3d: :param dtype: if dtype is not used, the automatic is used :return: """ if dtype is None: dtype = data3d.dtype if issubclass(dtype.type, np.integer): mn = data3d.min() * slope + inter mx = data3d.max() * slope + inter if suits_with_dtype(mn, mx, dtype=np.uint8): dtype = np.uint8 elif suits_with_dtype(mn, mx, dtype=np.int8): dtype = np.int8 elif suits_with_dtype(mn, mx, dtype=np.uint16): dtype = np.uint16 elif suits_with_dtype(mn, mx, dtype=np.int16): dtype = np.int16 elif suits_with_dtype(mn, mx, dtype=np.uint32): dtype = np.uint32 elif suits_with_dtype(mn, mx, dtype=np.int32): dtype = np.int32 # new_data3d = ((np.float(slope) * data3d) + np.float(inter)).astype(dtype) if slope == 1 and inter == 0: # this can prevent out of memmory new_data3d = data3d.astype(dtype) else: new_data3d = ((slope * data3d) + inter).astype(dtype) return new_data3d
[ "def", "use_economic_dtype", "(", "data3d", ",", "slope", "=", "1", ",", "inter", "=", "0", ",", "dtype", "=", "None", ")", ":", "if", "dtype", "is", "None", ":", "dtype", "=", "data3d", ".", "dtype", "if", "issubclass", "(", "dtype", ".", "type", ...
Use more economic integer-like dtype if it is possible. :param data3d: :param dtype: if dtype is not used, the automatic is used :return:
[ "Use", "more", "economic", "integer", "-", "like", "dtype", "if", "it", "is", "possible", "." ]
ccaf3e378dcc967f2565d477fc27583fd0f61fcc
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/misc.py#L299-L331
train
51,474
mjirik/io3d
io3d/dcmtools.py
get_sitk_image_from_ndarray
def get_sitk_image_from_ndarray(data3d): """ Prepare SimpleItk Image object and rescale data to unsigned types. Simple ITK with version higher than 1.0.0 can not write signed int16. This function check the SimpleITK version and use work around with Rescale Intercept and Rescale Slope :param data3d: :return: """ import SimpleITK as sitk rescale_intercept = None if sitk.Version.MajorVersion() > 0: if data3d.dtype == np.int8: rescale_intercept = -2**7 data3d = (data3d - rescale_intercept).astype(np.uint8) elif data3d.dtype == np.int16: # simpleitk is not able to store this. It uses only 11 bites # rescale_intercept = -2**15 rescale_intercept = -2**10 data3d = (data3d - rescale_intercept).astype(np.uint16) elif data3d.dtype == np.int32: rescale_intercept = -2**31 data3d = (data3d - rescale_intercept).astype(np.uint16) dim = sitk.GetImageFromArray(data3d) if sitk.Version.MajorVersion() > 0: if rescale_intercept is not None: # rescale slope (0028|1053), rescale intercept (0028|1052) dim.SetMetaData("0028|1052", str(rescale_intercept)) dim.SetMetaData("0028|1053", "1") return dim
python
def get_sitk_image_from_ndarray(data3d): """ Prepare SimpleItk Image object and rescale data to unsigned types. Simple ITK with version higher than 1.0.0 can not write signed int16. This function check the SimpleITK version and use work around with Rescale Intercept and Rescale Slope :param data3d: :return: """ import SimpleITK as sitk rescale_intercept = None if sitk.Version.MajorVersion() > 0: if data3d.dtype == np.int8: rescale_intercept = -2**7 data3d = (data3d - rescale_intercept).astype(np.uint8) elif data3d.dtype == np.int16: # simpleitk is not able to store this. It uses only 11 bites # rescale_intercept = -2**15 rescale_intercept = -2**10 data3d = (data3d - rescale_intercept).astype(np.uint16) elif data3d.dtype == np.int32: rescale_intercept = -2**31 data3d = (data3d - rescale_intercept).astype(np.uint16) dim = sitk.GetImageFromArray(data3d) if sitk.Version.MajorVersion() > 0: if rescale_intercept is not None: # rescale slope (0028|1053), rescale intercept (0028|1052) dim.SetMetaData("0028|1052", str(rescale_intercept)) dim.SetMetaData("0028|1053", "1") return dim
[ "def", "get_sitk_image_from_ndarray", "(", "data3d", ")", ":", "import", "SimpleITK", "as", "sitk", "rescale_intercept", "=", "None", "if", "sitk", ".", "Version", ".", "MajorVersion", "(", ")", ">", "0", ":", "if", "data3d", ".", "dtype", "==", "np", ".",...
Prepare SimpleItk Image object and rescale data to unsigned types. Simple ITK with version higher than 1.0.0 can not write signed int16. This function check the SimpleITK version and use work around with Rescale Intercept and Rescale Slope :param data3d: :return:
[ "Prepare", "SimpleItk", "Image", "object", "and", "rescale", "data", "to", "unsigned", "types", "." ]
ccaf3e378dcc967f2565d477fc27583fd0f61fcc
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dcmtools.py#L27-L59
train
51,475
bhearsum/chunkify
chunkify/__init__.py
split_evenly
def split_evenly(n, chunks): """Split an integer into evenly distributed list >>> split_evenly(7, 3) [3, 2, 2] >>> split_evenly(12, 3) [4, 4, 4] >>> split_evenly(35, 10) [4, 4, 4, 4, 4, 3, 3, 3, 3, 3] >>> split_evenly(1, 2) Traceback (most recent call last): ... ChunkingError: Number of chunks is greater than number """ if n < chunks: raise ChunkingError("Number of chunks is greater than number") if n % chunks == 0: # Either we can evenly split or only 1 chunk left return [n / chunks] * chunks # otherwise the current chunk should be a bit larger max_size = n / chunks + 1 return [max_size] + split_evenly(n - max_size, chunks - 1)
python
def split_evenly(n, chunks): """Split an integer into evenly distributed list >>> split_evenly(7, 3) [3, 2, 2] >>> split_evenly(12, 3) [4, 4, 4] >>> split_evenly(35, 10) [4, 4, 4, 4, 4, 3, 3, 3, 3, 3] >>> split_evenly(1, 2) Traceback (most recent call last): ... ChunkingError: Number of chunks is greater than number """ if n < chunks: raise ChunkingError("Number of chunks is greater than number") if n % chunks == 0: # Either we can evenly split or only 1 chunk left return [n / chunks] * chunks # otherwise the current chunk should be a bit larger max_size = n / chunks + 1 return [max_size] + split_evenly(n - max_size, chunks - 1)
[ "def", "split_evenly", "(", "n", ",", "chunks", ")", ":", "if", "n", "<", "chunks", ":", "raise", "ChunkingError", "(", "\"Number of chunks is greater than number\"", ")", "if", "n", "%", "chunks", "==", "0", ":", "# Either we can evenly split or only 1 chunk left",...
Split an integer into evenly distributed list >>> split_evenly(7, 3) [3, 2, 2] >>> split_evenly(12, 3) [4, 4, 4] >>> split_evenly(35, 10) [4, 4, 4, 4, 4, 3, 3, 3, 3, 3] >>> split_evenly(1, 2) Traceback (most recent call last): ... ChunkingError: Number of chunks is greater than number
[ "Split", "an", "integer", "into", "evenly", "distributed", "list" ]
f3a693b17c80626852523955bf3c01b4fd93439b
https://github.com/bhearsum/chunkify/blob/f3a693b17c80626852523955bf3c01b4fd93439b/chunkify/__init__.py#L8-L33
train
51,476
vsoch/helpme
helpme/main/discourse/__init__.py
Helper._generate_keys
def _generate_keys(self): '''the discourse API requires the interactions to be signed, so we generate a keypair on behalf of the user ''' from helpme.defaults import HELPME_CLIENT_SECRETS keypair_dir = os.path.join(os.path.dirname(HELPME_CLIENT_SECRETS), 'discourse') # Have we generated a keypair file before? self.keypair_file = os.path.join(keypair_dir, 'private.pem') # We likely won't have generated it on first use! if not hasattr(self, 'key'): self.key = generate_keypair(self.keypair_file) # If we generated the keypair file, we will have already loaded the key if not hasattr(self, 'public_key'): self.public_key = load_keypair(self.keypair_file)
python
def _generate_keys(self): '''the discourse API requires the interactions to be signed, so we generate a keypair on behalf of the user ''' from helpme.defaults import HELPME_CLIENT_SECRETS keypair_dir = os.path.join(os.path.dirname(HELPME_CLIENT_SECRETS), 'discourse') # Have we generated a keypair file before? self.keypair_file = os.path.join(keypair_dir, 'private.pem') # We likely won't have generated it on first use! if not hasattr(self, 'key'): self.key = generate_keypair(self.keypair_file) # If we generated the keypair file, we will have already loaded the key if not hasattr(self, 'public_key'): self.public_key = load_keypair(self.keypair_file)
[ "def", "_generate_keys", "(", "self", ")", ":", "from", "helpme", ".", "defaults", "import", "HELPME_CLIENT_SECRETS", "keypair_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "HELPME_CLIENT_SECRETS", ")", ",", "'discou...
the discourse API requires the interactions to be signed, so we generate a keypair on behalf of the user
[ "the", "discourse", "API", "requires", "the", "interactions", "to", "be", "signed", "so", "we", "generate", "a", "keypair", "on", "behalf", "of", "the", "user" ]
e609172260b10cddadb2d2023ab26da8082a9feb
https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/discourse/__init__.py#L80-L97
train
51,477
closeio/cachecow
cachecow/__init__.py
CacheCow.invalidate
def invalidate(self, cls, id_field, id_val): """ Invalidate the cache for a given Mongo object by deleting the cached data and the cache flag. """ cache_key, flag_key = self.get_keys(cls, id_field, id_val) pipeline = self.redis.pipeline() pipeline.delete(cache_key) pipeline.delete(flag_key) pipeline.execute()
python
def invalidate(self, cls, id_field, id_val): """ Invalidate the cache for a given Mongo object by deleting the cached data and the cache flag. """ cache_key, flag_key = self.get_keys(cls, id_field, id_val) pipeline = self.redis.pipeline() pipeline.delete(cache_key) pipeline.delete(flag_key) pipeline.execute()
[ "def", "invalidate", "(", "self", ",", "cls", ",", "id_field", ",", "id_val", ")", ":", "cache_key", ",", "flag_key", "=", "self", ".", "get_keys", "(", "cls", ",", "id_field", ",", "id_val", ")", "pipeline", "=", "self", ".", "redis", ".", "pipeline",...
Invalidate the cache for a given Mongo object by deleting the cached data and the cache flag.
[ "Invalidate", "the", "cache", "for", "a", "given", "Mongo", "object", "by", "deleting", "the", "cached", "data", "and", "the", "cache", "flag", "." ]
a0531686db40baa81b3cfa0076a23a53d2762cc6
https://github.com/closeio/cachecow/blob/a0531686db40baa81b3cfa0076a23a53d2762cc6/cachecow/__init__.py#L120-L130
train
51,478
DreamLab/VmShepherd
src/vmshepherd/presets/preset.py
Preset.manage
async def manage(self): """ Manage function docstring""" self._vms = await self.iaas.list_vms(self.name) vms_stat = Counter([vm.get_state() for vm in self._vms]) missing = self.count - len(self._vms) if len(self._vms) < self.count else 0 logging.info( 'VMs Status: %s expected, %s in iaas, %s running, %s nearby shutdown, %s pending, %s after time shutdown, ' '%s terminated, %s error, %s unknown, %s missing', self.count, len(self._vms), vms_stat[VmState.RUNNING.value], vms_stat[VmState.NEARBY_SHUTDOWN.value], vms_stat[VmState.PENDING.value], vms_stat[VmState.AFTER_TIME_SHUTDOWN.value], vms_stat[VmState.TERMINATED.value], vms_stat[VmState.ERROR.value], vms_stat[VmState.UNKNOWN.value], missing, extra=self._extra ) for vm in self._vms: if vm.is_dead(): logging.info("Terminate %s", vm, extra=self._extra) await vm.terminate() self.terminated += 1 to_create = self.count - (len(self._vms) - self.terminated - vms_stat[VmState.NEARBY_SHUTDOWN.value]) to_create = to_create if to_create > 0 else 0 logging.debug("Create %s Vm", to_create, extra=self._extra) await self._create_vms(to_create) await self._healthcheck(self._vms) logging.info( 'VMs Status update: %s terminated, %s terminated by healthcheck, %s created, %s failed healthcheck', self.terminated, self.healthcheck_terminated, to_create, len(self.runtime.failed_checks), extra=self._extra )
python
async def manage(self): """ Manage function docstring""" self._vms = await self.iaas.list_vms(self.name) vms_stat = Counter([vm.get_state() for vm in self._vms]) missing = self.count - len(self._vms) if len(self._vms) < self.count else 0 logging.info( 'VMs Status: %s expected, %s in iaas, %s running, %s nearby shutdown, %s pending, %s after time shutdown, ' '%s terminated, %s error, %s unknown, %s missing', self.count, len(self._vms), vms_stat[VmState.RUNNING.value], vms_stat[VmState.NEARBY_SHUTDOWN.value], vms_stat[VmState.PENDING.value], vms_stat[VmState.AFTER_TIME_SHUTDOWN.value], vms_stat[VmState.TERMINATED.value], vms_stat[VmState.ERROR.value], vms_stat[VmState.UNKNOWN.value], missing, extra=self._extra ) for vm in self._vms: if vm.is_dead(): logging.info("Terminate %s", vm, extra=self._extra) await vm.terminate() self.terminated += 1 to_create = self.count - (len(self._vms) - self.terminated - vms_stat[VmState.NEARBY_SHUTDOWN.value]) to_create = to_create if to_create > 0 else 0 logging.debug("Create %s Vm", to_create, extra=self._extra) await self._create_vms(to_create) await self._healthcheck(self._vms) logging.info( 'VMs Status update: %s terminated, %s terminated by healthcheck, %s created, %s failed healthcheck', self.terminated, self.healthcheck_terminated, to_create, len(self.runtime.failed_checks), extra=self._extra )
[ "async", "def", "manage", "(", "self", ")", ":", "self", ".", "_vms", "=", "await", "self", ".", "iaas", ".", "list_vms", "(", "self", ".", "name", ")", "vms_stat", "=", "Counter", "(", "[", "vm", ".", "get_state", "(", ")", "for", "vm", "in", "s...
Manage function docstring
[ "Manage", "function", "docstring" ]
709a412c372b897d53808039c5c64a8b69c12c8d
https://github.com/DreamLab/VmShepherd/blob/709a412c372b897d53808039c5c64a8b69c12c8d/src/vmshepherd/presets/preset.py#L76-L103
train
51,479
CentOS/python-cicoclient
cicoclient/utils.py
log_method
def log_method(log, level=logging.DEBUG): """Logs a method and its arguments when entered.""" def decorator(func): func_name = func.__name__ @six.wraps(func) def wrapper(self, *args, **kwargs): if log.isEnabledFor(level): pretty_args = [] if args: pretty_args.extend(str(a) for a in args) if kwargs: pretty_args.extend( "%s=%s" % (k, v) for k, v in six.iteritems(kwargs)) log.log(level, "%s(%s)", func_name, ", ".join(pretty_args)) return func(self, *args, **kwargs) return wrapper return decorator
python
def log_method(log, level=logging.DEBUG): """Logs a method and its arguments when entered.""" def decorator(func): func_name = func.__name__ @six.wraps(func) def wrapper(self, *args, **kwargs): if log.isEnabledFor(level): pretty_args = [] if args: pretty_args.extend(str(a) for a in args) if kwargs: pretty_args.extend( "%s=%s" % (k, v) for k, v in six.iteritems(kwargs)) log.log(level, "%s(%s)", func_name, ", ".join(pretty_args)) return func(self, *args, **kwargs) return wrapper return decorator
[ "def", "log_method", "(", "log", ",", "level", "=", "logging", ".", "DEBUG", ")", ":", "def", "decorator", "(", "func", ")", ":", "func_name", "=", "func", ".", "__name__", "@", "six", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ...
Logs a method and its arguments when entered.
[ "Logs", "a", "method", "and", "its", "arguments", "when", "entered", "." ]
ffee34f446ceb25348b13a500d5c545df202c182
https://github.com/CentOS/python-cicoclient/blob/ffee34f446ceb25348b13a500d5c545df202c182/cicoclient/utils.py#L44-L64
train
51,480
launchdarkly/relayCommander
relay_commander/replay_builder.py
check_local
def check_local() -> None: """ Verify required directories exist. This functions checks the current working directory to ensure that the required directories exist. If they do not exist, it will create them. """ to_check = ['./replay', './replay/toDo', './replay/archive'] for i in to_check: if not os.path.exists(i): os.makedirs(i)
python
def check_local() -> None: """ Verify required directories exist. This functions checks the current working directory to ensure that the required directories exist. If they do not exist, it will create them. """ to_check = ['./replay', './replay/toDo', './replay/archive'] for i in to_check: if not os.path.exists(i): os.makedirs(i)
[ "def", "check_local", "(", ")", "->", "None", ":", "to_check", "=", "[", "'./replay'", ",", "'./replay/toDo'", ",", "'./replay/archive'", "]", "for", "i", "in", "to_check", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "i", ")", ":", "os", ...
Verify required directories exist. This functions checks the current working directory to ensure that the required directories exist. If they do not exist, it will create them.
[ "Verify", "required", "directories", "exist", "." ]
eee7fa22f04edc3854dd53c3ec2db8c599ad1e89
https://github.com/launchdarkly/relayCommander/blob/eee7fa22f04edc3854dd53c3ec2db8c599ad1e89/relay_commander/replay_builder.py#L33-L44
train
51,481
launchdarkly/relayCommander
relay_commander/replay_builder.py
create_file
def create_file(project: str, environment: str, feature: str, state: str) -> None: """ Create file to replay. Create file with ``rc`` command that will be called against the LaunchDarkly API when ``rc playback`` is called from the main CLI. :param project: LaunchDarkly Project :param environment: LaunchDarkly Environment :param feature: LaunchDarkly Feature :param state: State to update feature flag """ check_local() save_path = './replay/toDo/' filename = '{0}.txt'.format(str(uuid.uuid1())) complete_name = os.path.join(save_path, filename) with open(complete_name, 'w') as filename: filename.write('rc update-ld-api -p {0} -e {1} -f {2} -s {3}'.format( project, environment, feature, state ))
python
def create_file(project: str, environment: str, feature: str, state: str) -> None: """ Create file to replay. Create file with ``rc`` command that will be called against the LaunchDarkly API when ``rc playback`` is called from the main CLI. :param project: LaunchDarkly Project :param environment: LaunchDarkly Environment :param feature: LaunchDarkly Feature :param state: State to update feature flag """ check_local() save_path = './replay/toDo/' filename = '{0}.txt'.format(str(uuid.uuid1())) complete_name = os.path.join(save_path, filename) with open(complete_name, 'w') as filename: filename.write('rc update-ld-api -p {0} -e {1} -f {2} -s {3}'.format( project, environment, feature, state ))
[ "def", "create_file", "(", "project", ":", "str", ",", "environment", ":", "str", ",", "feature", ":", "str", ",", "state", ":", "str", ")", "->", "None", ":", "check_local", "(", ")", "save_path", "=", "'./replay/toDo/'", "filename", "=", "'{0}.txt'", "...
Create file to replay. Create file with ``rc`` command that will be called against the LaunchDarkly API when ``rc playback`` is called from the main CLI. :param project: LaunchDarkly Project :param environment: LaunchDarkly Environment :param feature: LaunchDarkly Feature :param state: State to update feature flag
[ "Create", "file", "to", "replay", "." ]
eee7fa22f04edc3854dd53c3ec2db8c599ad1e89
https://github.com/launchdarkly/relayCommander/blob/eee7fa22f04edc3854dd53c3ec2db8c599ad1e89/relay_commander/replay_builder.py#L47-L70
train
51,482
launchdarkly/relayCommander
relay_commander/replay_builder.py
execute_replay
def execute_replay() -> None: """ Execute all commands. For every command that is found in replay/toDo, execute each of them and move the file to the replay/archive directory. """ files = glob.glob('./replay/toDo/*') sorted_files = sorted(files, key=os.path.getctime) if not sorted_files: # list is not empty LOG.debug('Found %s, beginning execution.', sorted_files) for command_file in sorted_files: with open(command_file, 'r') as command: cmd = command.read() LOG.debug('executing command: %s', cmd) resp = run([cmd, '-v', 'DEBUG'], shell=True, check=True) LOG.debug(resp) LOG.debug('moving %s to archive', command.name) move_command = 'mv {0} ./replay/archive/'.format(command.name) run(move_command, shell=True, check=True) LOG.info('LaunchDarkly is now up to date.') else: LOG.warning('No files found, nothing to replay.')
python
def execute_replay() -> None: """ Execute all commands. For every command that is found in replay/toDo, execute each of them and move the file to the replay/archive directory. """ files = glob.glob('./replay/toDo/*') sorted_files = sorted(files, key=os.path.getctime) if not sorted_files: # list is not empty LOG.debug('Found %s, beginning execution.', sorted_files) for command_file in sorted_files: with open(command_file, 'r') as command: cmd = command.read() LOG.debug('executing command: %s', cmd) resp = run([cmd, '-v', 'DEBUG'], shell=True, check=True) LOG.debug(resp) LOG.debug('moving %s to archive', command.name) move_command = 'mv {0} ./replay/archive/'.format(command.name) run(move_command, shell=True, check=True) LOG.info('LaunchDarkly is now up to date.') else: LOG.warning('No files found, nothing to replay.')
[ "def", "execute_replay", "(", ")", "->", "None", ":", "files", "=", "glob", ".", "glob", "(", "'./replay/toDo/*'", ")", "sorted_files", "=", "sorted", "(", "files", ",", "key", "=", "os", ".", "path", ".", "getctime", ")", "if", "not", "sorted_files", ...
Execute all commands. For every command that is found in replay/toDo, execute each of them and move the file to the replay/archive directory.
[ "Execute", "all", "commands", "." ]
eee7fa22f04edc3854dd53c3ec2db8c599ad1e89
https://github.com/launchdarkly/relayCommander/blob/eee7fa22f04edc3854dd53c3ec2db8c599ad1e89/relay_commander/replay_builder.py#L73-L96
train
51,483
vsoch/helpme
helpme/utils/terminal.py
choice_prompt
def choice_prompt(prompt, choices=None, choice=None): '''Ask the user for a prompt, and only return when one of the requested options is provided. Parameters ========== prompt: the prompt to ask the user choices: a list of choices that are valid, defaults to [Y/N/y/n] ''' if not choices: choices = ["y", "n", "Y", "N"] print(prompt) get_input = getattr(__builtins__, 'raw_input', input) pretty_choices = '/'.join(choices) message = 'Please enter your choice [%s] : ' %(pretty_choices) while choice not in choices: choice = get_input(message).strip() # If the option isn't valid, this is shown next message = "Please enter a valid option in [%s]" %(pretty_choices) return choice
python
def choice_prompt(prompt, choices=None, choice=None): '''Ask the user for a prompt, and only return when one of the requested options is provided. Parameters ========== prompt: the prompt to ask the user choices: a list of choices that are valid, defaults to [Y/N/y/n] ''' if not choices: choices = ["y", "n", "Y", "N"] print(prompt) get_input = getattr(__builtins__, 'raw_input', input) pretty_choices = '/'.join(choices) message = 'Please enter your choice [%s] : ' %(pretty_choices) while choice not in choices: choice = get_input(message).strip() # If the option isn't valid, this is shown next message = "Please enter a valid option in [%s]" %(pretty_choices) return choice
[ "def", "choice_prompt", "(", "prompt", ",", "choices", "=", "None", ",", "choice", "=", "None", ")", ":", "if", "not", "choices", ":", "choices", "=", "[", "\"y\"", ",", "\"n\"", ",", "\"Y\"", ",", "\"N\"", "]", "print", "(", "prompt", ")", "get_inpu...
Ask the user for a prompt, and only return when one of the requested options is provided. Parameters ========== prompt: the prompt to ask the user choices: a list of choices that are valid, defaults to [Y/N/y/n]
[ "Ask", "the", "user", "for", "a", "prompt", "and", "only", "return", "when", "one", "of", "the", "requested", "options", "is", "provided", "." ]
e609172260b10cddadb2d2023ab26da8082a9feb
https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/utils/terminal.py#L46-L68
train
51,484
vsoch/helpme
helpme/utils/terminal.py
regexp_prompt
def regexp_prompt(prompt, regexp='.', answer=''): '''Ask the user for a text entry that matches a regular expression Parameters ========== prompt: the prompt to ask the user regexp: the regular expression to match. defaults to anything. ''' get_input = getattr(__builtins__, 'raw_input', input) while not re.search(regexp, answer): answer = get_input(prompt + ': ').strip() # If the option isn't valid, this is shown next message = "Your entry must match the regular expression %s" %regexp return answer
python
def regexp_prompt(prompt, regexp='.', answer=''): '''Ask the user for a text entry that matches a regular expression Parameters ========== prompt: the prompt to ask the user regexp: the regular expression to match. defaults to anything. ''' get_input = getattr(__builtins__, 'raw_input', input) while not re.search(regexp, answer): answer = get_input(prompt + ': ').strip() # If the option isn't valid, this is shown next message = "Your entry must match the regular expression %s" %regexp return answer
[ "def", "regexp_prompt", "(", "prompt", ",", "regexp", "=", "'.'", ",", "answer", "=", "''", ")", ":", "get_input", "=", "getattr", "(", "__builtins__", ",", "'raw_input'", ",", "input", ")", "while", "not", "re", ".", "search", "(", "regexp", ",", "ans...
Ask the user for a text entry that matches a regular expression Parameters ========== prompt: the prompt to ask the user regexp: the regular expression to match. defaults to anything.
[ "Ask", "the", "user", "for", "a", "text", "entry", "that", "matches", "a", "regular", "expression" ]
e609172260b10cddadb2d2023ab26da8082a9feb
https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/utils/terminal.py#L71-L86
train
51,485
vsoch/helpme
helpme/utils/terminal.py
which
def which(software, strip_newline=True): '''get_install will return the path to where an executable is installed. ''' if software is None: software = "singularity" cmd = ['which', software ] try: result = run_command(cmd) if strip_newline is True: result['message'] = result['message'].strip('\n') return result except: # FileNotFoundError return None
python
def which(software, strip_newline=True): '''get_install will return the path to where an executable is installed. ''' if software is None: software = "singularity" cmd = ['which', software ] try: result = run_command(cmd) if strip_newline is True: result['message'] = result['message'].strip('\n') return result except: # FileNotFoundError return None
[ "def", "which", "(", "software", ",", "strip_newline", "=", "True", ")", ":", "if", "software", "is", "None", ":", "software", "=", "\"singularity\"", "cmd", "=", "[", "'which'", ",", "software", "]", "try", ":", "result", "=", "run_command", "(", "cmd",...
get_install will return the path to where an executable is installed.
[ "get_install", "will", "return", "the", "path", "to", "where", "an", "executable", "is", "installed", "." ]
e609172260b10cddadb2d2023ab26da8082a9feb
https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/utils/terminal.py#L91-L104
train
51,486
PlaidWeb/Pushl
pushl/utils.py
guess_encoding
def guess_encoding(request): """ Try to guess the encoding of a request without going through the slow chardet process""" ctype = request.headers.get('content-type') if not ctype: # we don't have a content-type, somehow, so... LOGGER.warning("%s: no content-type; headers are %s", request.url, request.headers) return 'utf-8' # explicit declaration match = re.search(r'charset=([^ ;]*)(;| |$)', ctype) if match: return match[1] # html default if ctype.startswith('text/html'): return 'iso-8859-1' # everything else's default return 'utf-8'
python
def guess_encoding(request): """ Try to guess the encoding of a request without going through the slow chardet process""" ctype = request.headers.get('content-type') if not ctype: # we don't have a content-type, somehow, so... LOGGER.warning("%s: no content-type; headers are %s", request.url, request.headers) return 'utf-8' # explicit declaration match = re.search(r'charset=([^ ;]*)(;| |$)', ctype) if match: return match[1] # html default if ctype.startswith('text/html'): return 'iso-8859-1' # everything else's default return 'utf-8'
[ "def", "guess_encoding", "(", "request", ")", ":", "ctype", "=", "request", ".", "headers", ".", "get", "(", "'content-type'", ")", "if", "not", "ctype", ":", "# we don't have a content-type, somehow, so...", "LOGGER", ".", "warning", "(", "\"%s: no content-type; he...
Try to guess the encoding of a request without going through the slow chardet process
[ "Try", "to", "guess", "the", "encoding", "of", "a", "request", "without", "going", "through", "the", "slow", "chardet", "process" ]
5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c
https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/utils.py#L15-L34
train
51,487
PlaidWeb/Pushl
pushl/utils.py
_make_headers
def _make_headers(config, kwargs): """ Replace the kwargs with one where the headers include our user-agent """ headers = kwargs.get('headers') headers = headers.copy() if headers is not None else {} headers['User-Agent'] = config.args.user_agent kwargs = kwargs.copy() kwargs['headers'] = headers return kwargs
python
def _make_headers(config, kwargs): """ Replace the kwargs with one where the headers include our user-agent """ headers = kwargs.get('headers') headers = headers.copy() if headers is not None else {} headers['User-Agent'] = config.args.user_agent kwargs = kwargs.copy() kwargs['headers'] = headers return kwargs
[ "def", "_make_headers", "(", "config", ",", "kwargs", ")", ":", "headers", "=", "kwargs", ".", "get", "(", "'headers'", ")", "headers", "=", "headers", ".", "copy", "(", ")", "if", "headers", "is", "not", "None", "else", "{", "}", "headers", "[", "'U...
Replace the kwargs with one where the headers include our user-agent
[ "Replace", "the", "kwargs", "with", "one", "where", "the", "headers", "include", "our", "user", "-", "agent" ]
5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c
https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/utils.py#L97-L106
train
51,488
PlaidWeb/Pushl
pushl/utils.py
retry_get
async def retry_get(config, url, *args, **kwargs): """ aiohttp wrapper for GET """ return await _retry_do(config.session.get, url, *args, **_make_headers(config, kwargs))
python
async def retry_get(config, url, *args, **kwargs): """ aiohttp wrapper for GET """ return await _retry_do(config.session.get, url, *args, **_make_headers(config, kwargs))
[ "async", "def", "retry_get", "(", "config", ",", "url", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "await", "_retry_do", "(", "config", ".", "session", ".", "get", ",", "url", ",", "*", "args", ",", "*", "*", "_make_headers", "(...
aiohttp wrapper for GET
[ "aiohttp", "wrapper", "for", "GET" ]
5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c
https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/utils.py#L109-L112
train
51,489
PlaidWeb/Pushl
pushl/utils.py
retry_post
async def retry_post(config, url, *args, **kwargs): """ aiohttp wrapper for POST """ return await _retry_do(config.session.post, url, *args, **_make_headers(config, kwargs))
python
async def retry_post(config, url, *args, **kwargs): """ aiohttp wrapper for POST """ return await _retry_do(config.session.post, url, *args, **_make_headers(config, kwargs))
[ "async", "def", "retry_post", "(", "config", ",", "url", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "await", "_retry_do", "(", "config", ".", "session", ".", "post", ",", "url", ",", "*", "args", ",", "*", "*", "_make_headers", ...
aiohttp wrapper for POST
[ "aiohttp", "wrapper", "for", "POST" ]
5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c
https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/utils.py#L115-L118
train
51,490
vsoch/helpme
helpme/main/base/__init__.py
HelperBase.collect_argument
def collect_argument(self, step, message): '''given a key in the configuration, collect the runtime argument if provided. Otherwise, prompt the user for the value. Parameters ========== step: the name of the step, should be 'runtime_arg_<name>' message: the content of the step, the message to show the user if the argument <name> is not found under args. ''' if step not in self.data: self.data[step] = regexp_prompt(message)
python
def collect_argument(self, step, message): '''given a key in the configuration, collect the runtime argument if provided. Otherwise, prompt the user for the value. Parameters ========== step: the name of the step, should be 'runtime_arg_<name>' message: the content of the step, the message to show the user if the argument <name> is not found under args. ''' if step not in self.data: self.data[step] = regexp_prompt(message)
[ "def", "collect_argument", "(", "self", ",", "step", ",", "message", ")", ":", "if", "step", "not", "in", "self", ".", "data", ":", "self", ".", "data", "[", "step", "]", "=", "regexp_prompt", "(", "message", ")" ]
given a key in the configuration, collect the runtime argument if provided. Otherwise, prompt the user for the value. Parameters ========== step: the name of the step, should be 'runtime_arg_<name>' message: the content of the step, the message to show the user if the argument <name> is not found under args.
[ "given", "a", "key", "in", "the", "configuration", "collect", "the", "runtime", "argument", "if", "provided", ".", "Otherwise", "prompt", "the", "user", "for", "the", "value", "." ]
e609172260b10cddadb2d2023ab26da8082a9feb
https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/base/__init__.py#L172-L184
train
51,491
vsoch/helpme
helpme/main/base/__init__.py
HelperBase.record_environment
def record_environment(self): '''collect a limited set of environment variables based on the list under record_envirionment in the configuration file. ''' # whitelist is a newline separated list under record_environment envars = self._get_setting(name='whitelist', section='record_environment', user=False) if envars is not None: # User uppercase envars = [x.upper() for x in envars.split('\n')] # Make transparent for the user bot.custom(prefix="Environment ", message='|'.join(envars), color="CYAN") # Iterate through and collect based on name keep = [(k,v) for k,v in os.environ.items() if k.upper() in envars] # Ask the user for permission if confirm_prompt('Is this list ok to share?'): self.data['record_environment'] = keep
python
def record_environment(self): '''collect a limited set of environment variables based on the list under record_envirionment in the configuration file. ''' # whitelist is a newline separated list under record_environment envars = self._get_setting(name='whitelist', section='record_environment', user=False) if envars is not None: # User uppercase envars = [x.upper() for x in envars.split('\n')] # Make transparent for the user bot.custom(prefix="Environment ", message='|'.join(envars), color="CYAN") # Iterate through and collect based on name keep = [(k,v) for k,v in os.environ.items() if k.upper() in envars] # Ask the user for permission if confirm_prompt('Is this list ok to share?'): self.data['record_environment'] = keep
[ "def", "record_environment", "(", "self", ")", ":", "# whitelist is a newline separated list under record_environment", "envars", "=", "self", ".", "_get_setting", "(", "name", "=", "'whitelist'", ",", "section", "=", "'record_environment'", ",", "user", "=", "False", ...
collect a limited set of environment variables based on the list under record_envirionment in the configuration file.
[ "collect", "a", "limited", "set", "of", "environment", "variables", "based", "on", "the", "list", "under", "record_envirionment", "in", "the", "configuration", "file", "." ]
e609172260b10cddadb2d2023ab26da8082a9feb
https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/base/__init__.py#L189-L219
train
51,492
vsoch/helpme
helpme/main/base/__init__.py
HelperBase.speak
def speak(self): ''' a function for the helper to announce him or herself, depending on the level specified. If you want your client to have additional announced things here, then implement the class `_speak` for your client. ''' if self.quiet is False: bot.info('[helper|%s]' %(self.name)) self._speak()
python
def speak(self): ''' a function for the helper to announce him or herself, depending on the level specified. If you want your client to have additional announced things here, then implement the class `_speak` for your client. ''' if self.quiet is False: bot.info('[helper|%s]' %(self.name)) self._speak()
[ "def", "speak", "(", "self", ")", ":", "if", "self", ".", "quiet", "is", "False", ":", "bot", ".", "info", "(", "'[helper|%s]'", "%", "(", "self", ".", "name", ")", ")", "self", ".", "_speak", "(", ")" ]
a function for the helper to announce him or herself, depending on the level specified. If you want your client to have additional announced things here, then implement the class `_speak` for your client.
[ "a", "function", "for", "the", "helper", "to", "announce", "him", "or", "herself", "depending", "on", "the", "level", "specified", ".", "If", "you", "want", "your", "client", "to", "have", "additional", "announced", "things", "here", "then", "implement", "th...
e609172260b10cddadb2d2023ab26da8082a9feb
https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/base/__init__.py#L257-L267
train
51,493
SetBased/py-stratum
pystratum/Constants.py
Constants.__log_number_of_constants
def __log_number_of_constants(self): """ Logs the number of constants generated. """ n_id = len(self._labels) n_widths = len(self._constants) - n_id self._io.writeln('') self._io.text('Number of constants based on column widths: {0}'.format(n_widths)) self._io.text('Number of constants based on database IDs : {0}'.format(n_id))
python
def __log_number_of_constants(self): """ Logs the number of constants generated. """ n_id = len(self._labels) n_widths = len(self._constants) - n_id self._io.writeln('') self._io.text('Number of constants based on column widths: {0}'.format(n_widths)) self._io.text('Number of constants based on database IDs : {0}'.format(n_id))
[ "def", "__log_number_of_constants", "(", "self", ")", ":", "n_id", "=", "len", "(", "self", ".", "_labels", ")", "n_widths", "=", "len", "(", "self", ".", "_constants", ")", "-", "n_id", "self", ".", "_io", ".", "writeln", "(", "''", ")", "self", "."...
Logs the number of constants generated.
[ "Logs", "the", "number", "of", "constants", "generated", "." ]
7c5ffaa2fdd03f865832a5190b5897ff2c0e3155
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/Constants.py#L119-L128
train
51,494
launchdarkly/relayCommander
relay_commander/validator.py
_check_env_var
def _check_env_var(envvar: str) -> bool: """Check Environment Variable to verify that it is set and not empty. :param envvar: Environment Variable to Check. :returns: True if Environment Variable is set and not empty. :raises: KeyError if Environment Variable is not set or is empty. .. versionadded:: 0.0.12 """ if os.getenv(envvar) is None: raise KeyError( "Required ENVVAR: {0} is not set".format(envvar)) if not os.getenv(envvar): # test if env var is empty raise KeyError( "Required ENVVAR: {0} is empty".format(envvar)) return True
python
def _check_env_var(envvar: str) -> bool: """Check Environment Variable to verify that it is set and not empty. :param envvar: Environment Variable to Check. :returns: True if Environment Variable is set and not empty. :raises: KeyError if Environment Variable is not set or is empty. .. versionadded:: 0.0.12 """ if os.getenv(envvar) is None: raise KeyError( "Required ENVVAR: {0} is not set".format(envvar)) if not os.getenv(envvar): # test if env var is empty raise KeyError( "Required ENVVAR: {0} is empty".format(envvar)) return True
[ "def", "_check_env_var", "(", "envvar", ":", "str", ")", "->", "bool", ":", "if", "os", ".", "getenv", "(", "envvar", ")", "is", "None", ":", "raise", "KeyError", "(", "\"Required ENVVAR: {0} is not set\"", ".", "format", "(", "envvar", ")", ")", "if", "...
Check Environment Variable to verify that it is set and not empty. :param envvar: Environment Variable to Check. :returns: True if Environment Variable is set and not empty. :raises: KeyError if Environment Variable is not set or is empty. .. versionadded:: 0.0.12
[ "Check", "Environment", "Variable", "to", "verify", "that", "it", "is", "set", "and", "not", "empty", "." ]
eee7fa22f04edc3854dd53c3ec2db8c599ad1e89
https://github.com/launchdarkly/relayCommander/blob/eee7fa22f04edc3854dd53c3ec2db8c599ad1e89/relay_commander/validator.py#L19-L36
train
51,495
launchdarkly/relayCommander
relay_commander/validator.py
valid_state
def valid_state(state: str) -> bool: """Validate State Argument Checks that either 'on' or 'off' was entered as an argument to the CLI and make it lower case. :param state: state to validate. :returns: True if state is valid. .. versionchanged:: 0.0.12 This moethod was renamed from validateState to valid_state to conform to PEP-8. Also removed "magic" text for state and instead reference the _VALID_STATES constant. """ lower_case_state = state.lower() if lower_case_state in _VALID_STATES: return True return False
python
def valid_state(state: str) -> bool: """Validate State Argument Checks that either 'on' or 'off' was entered as an argument to the CLI and make it lower case. :param state: state to validate. :returns: True if state is valid. .. versionchanged:: 0.0.12 This moethod was renamed from validateState to valid_state to conform to PEP-8. Also removed "magic" text for state and instead reference the _VALID_STATES constant. """ lower_case_state = state.lower() if lower_case_state in _VALID_STATES: return True return False
[ "def", "valid_state", "(", "state", ":", "str", ")", "->", "bool", ":", "lower_case_state", "=", "state", ".", "lower", "(", ")", "if", "lower_case_state", "in", "_VALID_STATES", ":", "return", "True", "return", "False" ]
Validate State Argument Checks that either 'on' or 'off' was entered as an argument to the CLI and make it lower case. :param state: state to validate. :returns: True if state is valid. .. versionchanged:: 0.0.12 This moethod was renamed from validateState to valid_state to conform to PEP-8. Also removed "magic" text for state and instead reference the _VALID_STATES constant.
[ "Validate", "State", "Argument" ]
eee7fa22f04edc3854dd53c3ec2db8c599ad1e89
https://github.com/launchdarkly/relayCommander/blob/eee7fa22f04edc3854dd53c3ec2db8c599ad1e89/relay_commander/validator.py#L39-L58
train
51,496
launchdarkly/relayCommander
relay_commander/validator.py
valid_env_vars
def valid_env_vars() -> bool: """Validate that required env vars exist. :returns: True if required env vars exist. .. versionadded:: 0.0.12 """ for envvar in _REQUIRED_ENV_VARS: try: _check_env_var(envvar) except KeyError as ex: LOG.error(ex) sys.exit(1) return True
python
def valid_env_vars() -> bool: """Validate that required env vars exist. :returns: True if required env vars exist. .. versionadded:: 0.0.12 """ for envvar in _REQUIRED_ENV_VARS: try: _check_env_var(envvar) except KeyError as ex: LOG.error(ex) sys.exit(1) return True
[ "def", "valid_env_vars", "(", ")", "->", "bool", ":", "for", "envvar", "in", "_REQUIRED_ENV_VARS", ":", "try", ":", "_check_env_var", "(", "envvar", ")", "except", "KeyError", "as", "ex", ":", "LOG", ".", "error", "(", "ex", ")", "sys", ".", "exit", "(...
Validate that required env vars exist. :returns: True if required env vars exist. .. versionadded:: 0.0.12
[ "Validate", "that", "required", "env", "vars", "exist", "." ]
eee7fa22f04edc3854dd53c3ec2db8c599ad1e89
https://github.com/launchdarkly/relayCommander/blob/eee7fa22f04edc3854dd53c3ec2db8c599ad1e89/relay_commander/validator.py#L61-L74
train
51,497
DreamLab/VmShepherd
src/vmshepherd/http/__init__.py
WebServer.configure_panel
def configure_panel(self): """ Configure templates and routing """ webroot = os.path.dirname(__file__) self.template_path = os.path.join(webroot, 'templates') aiohttp_jinja2.setup( self, loader=jinja2.FileSystemLoader(self.template_path), filters={'sorted': sorted, 'int': int} ) self['static_root_url'] = '/static' self.router.add_view('/', Panel) self.router.add_static( '/static/', path=os.path.join(webroot, 'static'), name='static' )
python
def configure_panel(self): """ Configure templates and routing """ webroot = os.path.dirname(__file__) self.template_path = os.path.join(webroot, 'templates') aiohttp_jinja2.setup( self, loader=jinja2.FileSystemLoader(self.template_path), filters={'sorted': sorted, 'int': int} ) self['static_root_url'] = '/static' self.router.add_view('/', Panel) self.router.add_static( '/static/', path=os.path.join(webroot, 'static'), name='static' )
[ "def", "configure_panel", "(", "self", ")", ":", "webroot", "=", "os", ".", "path", ".", "dirname", "(", "__file__", ")", "self", ".", "template_path", "=", "os", ".", "path", ".", "join", "(", "webroot", ",", "'templates'", ")", "aiohttp_jinja2", ".", ...
Configure templates and routing
[ "Configure", "templates", "and", "routing" ]
709a412c372b897d53808039c5c64a8b69c12c8d
https://github.com/DreamLab/VmShepherd/blob/709a412c372b897d53808039c5c64a8b69c12c8d/src/vmshepherd/http/__init__.py#L20-L36
train
51,498
DreamLab/VmShepherd
src/vmshepherd/http/__init__.py
WebServer.start
async def start(self): """ Initialize and start WebServer """ logging.info('Starting server, listening on %s.', self.port) runner = web.AppRunner(self) await runner.setup() site = web.TCPSite(runner, '', self.port) await site.start()
python
async def start(self): """ Initialize and start WebServer """ logging.info('Starting server, listening on %s.', self.port) runner = web.AppRunner(self) await runner.setup() site = web.TCPSite(runner, '', self.port) await site.start()
[ "async", "def", "start", "(", "self", ")", ":", "logging", ".", "info", "(", "'Starting server, listening on %s.'", ",", "self", ".", "port", ")", "runner", "=", "web", ".", "AppRunner", "(", "self", ")", "await", "runner", ".", "setup", "(", ")", "site"...
Initialize and start WebServer
[ "Initialize", "and", "start", "WebServer" ]
709a412c372b897d53808039c5c64a8b69c12c8d
https://github.com/DreamLab/VmShepherd/blob/709a412c372b897d53808039c5c64a8b69c12c8d/src/vmshepherd/http/__init__.py#L45-L53
train
51,499