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
tariqdaouda/pyGeno
pyGeno/tools/BinarySequence.py
BinarySequence.decode
def decode(self, binSequence): """decodes a binary sequence to return a string""" try: binSeq = iter(binSequence[0]) except TypeError, te: binSeq = binSequence ret = '' for b in binSeq : ch = '' for c in self.charToBin : if b & self.forma[self.charToBin[c]] > 0 : ch += c +'/' if ch == '' : raise KeyError('Key %d unkowom, bad format' % b) ret += ch[:-1] return ret
python
def decode(self, binSequence): """decodes a binary sequence to return a string""" try: binSeq = iter(binSequence[0]) except TypeError, te: binSeq = binSequence ret = '' for b in binSeq : ch = '' for c in self.charToBin : if b & self.forma[self.charToBin[c]] > 0 : ch += c +'/' if ch == '' : raise KeyError('Key %d unkowom, bad format' % b) ret += ch[:-1] return ret
[ "def", "decode", "(", "self", ",", "binSequence", ")", ":", "try", ":", "binSeq", "=", "iter", "(", "binSequence", "[", "0", "]", ")", "except", "TypeError", ",", "te", ":", "binSeq", "=", "binSequence", "ret", "=", "''", "for", "b", "in", "binSeq", ...
decodes a binary sequence to return a string
[ "decodes", "a", "binary", "sequence", "to", "return", "a", "string" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/BinarySequence.py#L298-L315
train
54,300
tariqdaouda/pyGeno
pyGeno/tools/parsers/VCFTools.py
VCFFile.parse
def parse(self, filename, gziped = False, stream = False) : """opens a file""" self.stream = stream if gziped : self.f = gzip.open(filename) else : self.f = open(filename) self.filename = filename self.gziped = gziped lineId = 0 inLegend = True while inLegend : ll = self.f.readline() l = ll.replace('\r', '\n').replace('\n', '') if l[:2] == '##' : eqPos = l.find('=') key = l[2:eqPos] values = l[eqPos+1:].strip() if l[eqPos+1] != '<' : self.meta[key] = values else : if key not in self.meta : self.meta[key] = {} svalues = l[eqPos+2:-1].split(',') #remove the < and > that surounf the string idKey = svalues[0].split('=')[1] self.meta[key][idKey] = {} i = 1 for v in svalues[1:] : sv = v.split("=") field = sv[0] value = sv[1] if field.lower() == 'description' : self.meta[key][idKey][field] = ','.join(svalues[i:])[len(field)+2:-1] break self.meta[key][idKey][field] = value i += 1 elif l[:6] == '#CHROM': #we are in legend sl = l.split('\t') for i in range(len(sl)) : self.legend[sl[i]] = i self.dnegel[i] = sl[i] break lineId += 1 if not stream : self.lines = self.f.readlines() self.f.close()
python
def parse(self, filename, gziped = False, stream = False) : """opens a file""" self.stream = stream if gziped : self.f = gzip.open(filename) else : self.f = open(filename) self.filename = filename self.gziped = gziped lineId = 0 inLegend = True while inLegend : ll = self.f.readline() l = ll.replace('\r', '\n').replace('\n', '') if l[:2] == '##' : eqPos = l.find('=') key = l[2:eqPos] values = l[eqPos+1:].strip() if l[eqPos+1] != '<' : self.meta[key] = values else : if key not in self.meta : self.meta[key] = {} svalues = l[eqPos+2:-1].split(',') #remove the < and > that surounf the string idKey = svalues[0].split('=')[1] self.meta[key][idKey] = {} i = 1 for v in svalues[1:] : sv = v.split("=") field = sv[0] value = sv[1] if field.lower() == 'description' : self.meta[key][idKey][field] = ','.join(svalues[i:])[len(field)+2:-1] break self.meta[key][idKey][field] = value i += 1 elif l[:6] == '#CHROM': #we are in legend sl = l.split('\t') for i in range(len(sl)) : self.legend[sl[i]] = i self.dnegel[i] = sl[i] break lineId += 1 if not stream : self.lines = self.f.readlines() self.f.close()
[ "def", "parse", "(", "self", ",", "filename", ",", "gziped", "=", "False", ",", "stream", "=", "False", ")", ":", "self", ".", "stream", "=", "stream", "if", "gziped", ":", "self", ".", "f", "=", "gzip", ".", "open", "(", "filename", ")", "else", ...
opens a file
[ "opens", "a", "file" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/parsers/VCFTools.py#L91-L142
train
54,301
appknox/pyaxmlparser
pyaxmlparser/stringblock.py
StringBlock._decode8
def _decode8(self, offset): """ Decode an UTF-8 String at the given offset :param offset: offset of the string inside the data :return: str """ # UTF-8 Strings contain two lengths, as they might differ: # 1) the UTF-16 length str_len, skip = self._decode_length(offset, 1) offset += skip # 2) the utf-8 string length encoded_bytes, skip = self._decode_length(offset, 1) offset += skip data = self.m_charbuff[offset: offset + encoded_bytes] assert self.m_charbuff[offset + encoded_bytes] == 0, \ "UTF-8 String is not null terminated! At offset={}".format(offset) return self._decode_bytes(data, 'utf-8', str_len)
python
def _decode8(self, offset): """ Decode an UTF-8 String at the given offset :param offset: offset of the string inside the data :return: str """ # UTF-8 Strings contain two lengths, as they might differ: # 1) the UTF-16 length str_len, skip = self._decode_length(offset, 1) offset += skip # 2) the utf-8 string length encoded_bytes, skip = self._decode_length(offset, 1) offset += skip data = self.m_charbuff[offset: offset + encoded_bytes] assert self.m_charbuff[offset + encoded_bytes] == 0, \ "UTF-8 String is not null terminated! At offset={}".format(offset) return self._decode_bytes(data, 'utf-8', str_len)
[ "def", "_decode8", "(", "self", ",", "offset", ")", ":", "# UTF-8 Strings contain two lengths, as they might differ:", "# 1) the UTF-16 length", "str_len", ",", "skip", "=", "self", ".", "_decode_length", "(", "offset", ",", "1", ")", "offset", "+=", "skip", "# 2) t...
Decode an UTF-8 String at the given offset :param offset: offset of the string inside the data :return: str
[ "Decode", "an", "UTF", "-", "8", "String", "at", "the", "given", "offset" ]
8ffe43e81a534f42c3620f3c1e3c6c0181a066bd
https://github.com/appknox/pyaxmlparser/blob/8ffe43e81a534f42c3620f3c1e3c6c0181a066bd/pyaxmlparser/stringblock.py#L150-L171
train
54,302
appknox/pyaxmlparser
pyaxmlparser/stringblock.py
StringBlock._decode16
def _decode16(self, offset): """ Decode an UTF-16 String at the given offset :param offset: offset of the string inside the data :return: str """ str_len, skip = self._decode_length(offset, 2) offset += skip # The len is the string len in utf-16 units encoded_bytes = str_len * 2 data = self.m_charbuff[offset: offset + encoded_bytes] assert self.m_charbuff[offset + encoded_bytes:offset + encoded_bytes + 2] == b"\x00\x00", \ "UTF-16 String is not null terminated! At offset={}".format(offset) return self._decode_bytes(data, 'utf-16', str_len)
python
def _decode16(self, offset): """ Decode an UTF-16 String at the given offset :param offset: offset of the string inside the data :return: str """ str_len, skip = self._decode_length(offset, 2) offset += skip # The len is the string len in utf-16 units encoded_bytes = str_len * 2 data = self.m_charbuff[offset: offset + encoded_bytes] assert self.m_charbuff[offset + encoded_bytes:offset + encoded_bytes + 2] == b"\x00\x00", \ "UTF-16 String is not null terminated! At offset={}".format(offset) return self._decode_bytes(data, 'utf-16', str_len)
[ "def", "_decode16", "(", "self", ",", "offset", ")", ":", "str_len", ",", "skip", "=", "self", ".", "_decode_length", "(", "offset", ",", "2", ")", "offset", "+=", "skip", "# The len is the string len in utf-16 units", "encoded_bytes", "=", "str_len", "*", "2"...
Decode an UTF-16 String at the given offset :param offset: offset of the string inside the data :return: str
[ "Decode", "an", "UTF", "-", "16", "String", "at", "the", "given", "offset" ]
8ffe43e81a534f42c3620f3c1e3c6c0181a066bd
https://github.com/appknox/pyaxmlparser/blob/8ffe43e81a534f42c3620f3c1e3c6c0181a066bd/pyaxmlparser/stringblock.py#L173-L191
train
54,303
appknox/pyaxmlparser
pyaxmlparser/stringblock.py
StringBlock._decode_length
def _decode_length(self, offset, sizeof_char): """ Generic Length Decoding at offset of string The method works for both 8 and 16 bit Strings. Length checks are enforced: * 8 bit strings: maximum of 0x7FFF bytes (See http://androidxref.com/9.0.0_r3/xref/frameworks/base/libs/androidfw/ResourceTypes.cpp#692) * 16 bit strings: maximum of 0x7FFFFFF bytes (See http://androidxref.com/9.0.0_r3/xref/frameworks/base/libs/androidfw/ResourceTypes.cpp#670) :param offset: offset into the string data section of the beginning of the string :param sizeof_char: number of bytes per char (1 = 8bit, 2 = 16bit) :returns: tuple of (length, read bytes) """ sizeof_2chars = sizeof_char << 1 fmt = "<2{}".format('B' if sizeof_char == 1 else 'H') highbit = 0x80 << (8 * (sizeof_char - 1)) length1, length2 = unpack(fmt, self.m_charbuff[offset:(offset + sizeof_2chars)]) if (length1 & highbit) != 0: length = ((length1 & ~highbit) << (8 * sizeof_char)) | length2 size = sizeof_2chars else: length = length1 size = sizeof_char if sizeof_char == 1: assert length <= 0x7FFF, "length of UTF-8 string is too large! At offset={}".format(offset) else: assert length <= 0x7FFFFFFF, "length of UTF-16 string is too large! At offset={}".format(offset) return length, size
python
def _decode_length(self, offset, sizeof_char): """ Generic Length Decoding at offset of string The method works for both 8 and 16 bit Strings. Length checks are enforced: * 8 bit strings: maximum of 0x7FFF bytes (See http://androidxref.com/9.0.0_r3/xref/frameworks/base/libs/androidfw/ResourceTypes.cpp#692) * 16 bit strings: maximum of 0x7FFFFFF bytes (See http://androidxref.com/9.0.0_r3/xref/frameworks/base/libs/androidfw/ResourceTypes.cpp#670) :param offset: offset into the string data section of the beginning of the string :param sizeof_char: number of bytes per char (1 = 8bit, 2 = 16bit) :returns: tuple of (length, read bytes) """ sizeof_2chars = sizeof_char << 1 fmt = "<2{}".format('B' if sizeof_char == 1 else 'H') highbit = 0x80 << (8 * (sizeof_char - 1)) length1, length2 = unpack(fmt, self.m_charbuff[offset:(offset + sizeof_2chars)]) if (length1 & highbit) != 0: length = ((length1 & ~highbit) << (8 * sizeof_char)) | length2 size = sizeof_2chars else: length = length1 size = sizeof_char if sizeof_char == 1: assert length <= 0x7FFF, "length of UTF-8 string is too large! At offset={}".format(offset) else: assert length <= 0x7FFFFFFF, "length of UTF-16 string is too large! At offset={}".format(offset) return length, size
[ "def", "_decode_length", "(", "self", ",", "offset", ",", "sizeof_char", ")", ":", "sizeof_2chars", "=", "sizeof_char", "<<", "1", "fmt", "=", "\"<2{}\"", ".", "format", "(", "'B'", "if", "sizeof_char", "==", "1", "else", "'H'", ")", "highbit", "=", "0x8...
Generic Length Decoding at offset of string The method works for both 8 and 16 bit Strings. Length checks are enforced: * 8 bit strings: maximum of 0x7FFF bytes (See http://androidxref.com/9.0.0_r3/xref/frameworks/base/libs/androidfw/ResourceTypes.cpp#692) * 16 bit strings: maximum of 0x7FFFFFF bytes (See http://androidxref.com/9.0.0_r3/xref/frameworks/base/libs/androidfw/ResourceTypes.cpp#670) :param offset: offset into the string data section of the beginning of the string :param sizeof_char: number of bytes per char (1 = 8bit, 2 = 16bit) :returns: tuple of (length, read bytes)
[ "Generic", "Length", "Decoding", "at", "offset", "of", "string" ]
8ffe43e81a534f42c3620f3c1e3c6c0181a066bd
https://github.com/appknox/pyaxmlparser/blob/8ffe43e81a534f42c3620f3c1e3c6c0181a066bd/pyaxmlparser/stringblock.py#L211-L245
train
54,304
appknox/pyaxmlparser
pyaxmlparser/core.py
APK._apk_analysis
def _apk_analysis(self): """ Run analysis on the APK file. This method is usually called by __init__ except if skip_analysis is False. It will then parse the AndroidManifest.xml and set all fields in the APK class which can be extracted from the Manifest. """ i = "AndroidManifest.xml" try: manifest_data = self.zip.read(i) except KeyError: log.warning("Missing AndroidManifest.xml. Is this an APK file?") else: ap = AXMLPrinter(manifest_data) if not ap.is_valid(): log.error("Error while parsing AndroidManifest.xml - is the file valid?") return self.axml[i] = ap self.xml[i] = self.axml[i].get_xml_obj() if self.axml[i].is_packed(): log.warning("XML Seems to be packed, operations on the AndroidManifest.xml might fail.") if self.xml[i] is not None: if self.xml[i].tag != "manifest": log.error("AndroidManifest.xml does not start with a <manifest> tag! Is this a valid APK?") return self.package = self.get_attribute_value("manifest", "package") self.androidversion["Code"] = self.get_attribute_value("manifest", "versionCode") self.androidversion["Name"] = self.get_attribute_value("manifest", "versionName") permission = list(self.get_all_attribute_value("uses-permission", "name")) self.permissions = list(set(self.permissions + permission)) for uses_permission in self.find_tags("uses-permission"): self.uses_permissions.append([ self.get_value_from_tag(uses_permission, "name"), self._get_permission_maxsdk(uses_permission) ]) # getting details of the declared permissions for d_perm_item in self.find_tags('permission'): d_perm_name = self._get_res_string_value( str(self.get_value_from_tag(d_perm_item, "name"))) d_perm_label = self._get_res_string_value( str(self.get_value_from_tag(d_perm_item, "label"))) d_perm_description = self._get_res_string_value( str(self.get_value_from_tag(d_perm_item, "description"))) d_perm_permissionGroup = self._get_res_string_value( str(self.get_value_from_tag(d_perm_item, "permissionGroup"))) d_perm_protectionLevel = self._get_res_string_value( str(self.get_value_from_tag(d_perm_item, "protectionLevel"))) d_perm_details = { "label": d_perm_label, "description": d_perm_description, "permissionGroup": d_perm_permissionGroup, "protectionLevel": d_perm_protectionLevel, } self.declared_permissions[d_perm_name] = d_perm_details self.valid_apk = True
python
def _apk_analysis(self): """ Run analysis on the APK file. This method is usually called by __init__ except if skip_analysis is False. It will then parse the AndroidManifest.xml and set all fields in the APK class which can be extracted from the Manifest. """ i = "AndroidManifest.xml" try: manifest_data = self.zip.read(i) except KeyError: log.warning("Missing AndroidManifest.xml. Is this an APK file?") else: ap = AXMLPrinter(manifest_data) if not ap.is_valid(): log.error("Error while parsing AndroidManifest.xml - is the file valid?") return self.axml[i] = ap self.xml[i] = self.axml[i].get_xml_obj() if self.axml[i].is_packed(): log.warning("XML Seems to be packed, operations on the AndroidManifest.xml might fail.") if self.xml[i] is not None: if self.xml[i].tag != "manifest": log.error("AndroidManifest.xml does not start with a <manifest> tag! Is this a valid APK?") return self.package = self.get_attribute_value("manifest", "package") self.androidversion["Code"] = self.get_attribute_value("manifest", "versionCode") self.androidversion["Name"] = self.get_attribute_value("manifest", "versionName") permission = list(self.get_all_attribute_value("uses-permission", "name")) self.permissions = list(set(self.permissions + permission)) for uses_permission in self.find_tags("uses-permission"): self.uses_permissions.append([ self.get_value_from_tag(uses_permission, "name"), self._get_permission_maxsdk(uses_permission) ]) # getting details of the declared permissions for d_perm_item in self.find_tags('permission'): d_perm_name = self._get_res_string_value( str(self.get_value_from_tag(d_perm_item, "name"))) d_perm_label = self._get_res_string_value( str(self.get_value_from_tag(d_perm_item, "label"))) d_perm_description = self._get_res_string_value( str(self.get_value_from_tag(d_perm_item, "description"))) d_perm_permissionGroup = self._get_res_string_value( str(self.get_value_from_tag(d_perm_item, "permissionGroup"))) d_perm_protectionLevel = self._get_res_string_value( str(self.get_value_from_tag(d_perm_item, "protectionLevel"))) d_perm_details = { "label": d_perm_label, "description": d_perm_description, "permissionGroup": d_perm_permissionGroup, "protectionLevel": d_perm_protectionLevel, } self.declared_permissions[d_perm_name] = d_perm_details self.valid_apk = True
[ "def", "_apk_analysis", "(", "self", ")", ":", "i", "=", "\"AndroidManifest.xml\"", "try", ":", "manifest_data", "=", "self", ".", "zip", ".", "read", "(", "i", ")", "except", "KeyError", ":", "log", ".", "warning", "(", "\"Missing AndroidManifest.xml. Is this...
Run analysis on the APK file. This method is usually called by __init__ except if skip_analysis is False. It will then parse the AndroidManifest.xml and set all fields in the APK class which can be extracted from the Manifest.
[ "Run", "analysis", "on", "the", "APK", "file", "." ]
8ffe43e81a534f42c3620f3c1e3c6c0181a066bd
https://github.com/appknox/pyaxmlparser/blob/8ffe43e81a534f42c3620f3c1e3c6c0181a066bd/pyaxmlparser/core.py#L129-L193
train
54,305
appknox/pyaxmlparser
pyaxmlparser/core.py
APK.is_multidex
def is_multidex(self): """ Test if the APK has multiple DEX files :return: True if multiple dex found, otherwise False """ dexre = re.compile("^classes(\d+)?.dex$") return len([instance for instance in self.get_files() if dexre.search(instance)]) > 1
python
def is_multidex(self): """ Test if the APK has multiple DEX files :return: True if multiple dex found, otherwise False """ dexre = re.compile("^classes(\d+)?.dex$") return len([instance for instance in self.get_files() if dexre.search(instance)]) > 1
[ "def", "is_multidex", "(", "self", ")", ":", "dexre", "=", "re", ".", "compile", "(", "\"^classes(\\d+)?.dex$\"", ")", "return", "len", "(", "[", "instance", "for", "instance", "in", "self", ".", "get_files", "(", ")", "if", "dexre", ".", "search", "(", ...
Test if the APK has multiple DEX files :return: True if multiple dex found, otherwise False
[ "Test", "if", "the", "APK", "has", "multiple", "DEX", "files" ]
8ffe43e81a534f42c3620f3c1e3c6c0181a066bd
https://github.com/appknox/pyaxmlparser/blob/8ffe43e81a534f42c3620f3c1e3c6c0181a066bd/pyaxmlparser/core.py#L604-L611
train
54,306
appknox/pyaxmlparser
pyaxmlparser/core.py
APK._format_value
def _format_value(self, value): """ Format a value with packagename, if not already set :param value: :return: """ if len(value) > 0: if value[0] == ".": value = self.package + value else: v_dot = value.find(".") if v_dot == 0: value = self.package + "." + value elif v_dot == -1: value = self.package + "." + value return value
python
def _format_value(self, value): """ Format a value with packagename, if not already set :param value: :return: """ if len(value) > 0: if value[0] == ".": value = self.package + value else: v_dot = value.find(".") if v_dot == 0: value = self.package + "." + value elif v_dot == -1: value = self.package + "." + value return value
[ "def", "_format_value", "(", "self", ",", "value", ")", ":", "if", "len", "(", "value", ")", ">", "0", ":", "if", "value", "[", "0", "]", "==", "\".\"", ":", "value", "=", "self", ".", "package", "+", "value", "else", ":", "v_dot", "=", "value", ...
Format a value with packagename, if not already set :param value: :return:
[ "Format", "a", "value", "with", "packagename", "if", "not", "already", "set" ]
8ffe43e81a534f42c3620f3c1e3c6c0181a066bd
https://github.com/appknox/pyaxmlparser/blob/8ffe43e81a534f42c3620f3c1e3c6c0181a066bd/pyaxmlparser/core.py#L633-L649
train
54,307
appknox/pyaxmlparser
pyaxmlparser/axmlparser.py
AXMLParser.getAttributeName
def getAttributeName(self, index): """ Returns the String which represents the attribute name """ offset = self._get_attribute_offset(index) name = self.m_attributes[offset + const.ATTRIBUTE_IX_NAME] res = self.sb[name] # If the result is a (null) string, we need to look it up. if not res: attr = self.m_resourceIDs[name] if attr in public.SYSTEM_RESOURCES['attributes']['inverse']: res = 'android:' + public.SYSTEM_RESOURCES['attributes']['inverse'][attr] else: # Attach the HEX Number, so for multiple missing attributes we do not run # into problems. res = 'android:UNKNOWN_SYSTEM_ATTRIBUTE_{:08x}'.format(attr) return res
python
def getAttributeName(self, index): """ Returns the String which represents the attribute name """ offset = self._get_attribute_offset(index) name = self.m_attributes[offset + const.ATTRIBUTE_IX_NAME] res = self.sb[name] # If the result is a (null) string, we need to look it up. if not res: attr = self.m_resourceIDs[name] if attr in public.SYSTEM_RESOURCES['attributes']['inverse']: res = 'android:' + public.SYSTEM_RESOURCES['attributes']['inverse'][attr] else: # Attach the HEX Number, so for multiple missing attributes we do not run # into problems. res = 'android:UNKNOWN_SYSTEM_ATTRIBUTE_{:08x}'.format(attr) return res
[ "def", "getAttributeName", "(", "self", ",", "index", ")", ":", "offset", "=", "self", ".", "_get_attribute_offset", "(", "index", ")", "name", "=", "self", ".", "m_attributes", "[", "offset", "+", "const", ".", "ATTRIBUTE_IX_NAME", "]", "res", "=", "self"...
Returns the String which represents the attribute name
[ "Returns", "the", "String", "which", "represents", "the", "attribute", "name" ]
8ffe43e81a534f42c3620f3c1e3c6c0181a066bd
https://github.com/appknox/pyaxmlparser/blob/8ffe43e81a534f42c3620f3c1e3c6c0181a066bd/pyaxmlparser/axmlparser.py#L522-L540
train
54,308
appknox/pyaxmlparser
pyaxmlparser/axmlparser.py
AXMLParser.getAttributeValueType
def getAttributeValueType(self, index): """ Return the type of the attribute at the given index :param index: index of the attribute """ offset = self._get_attribute_offset(index) return self.m_attributes[offset + const.ATTRIBUTE_IX_VALUE_TYPE]
python
def getAttributeValueType(self, index): """ Return the type of the attribute at the given index :param index: index of the attribute """ offset = self._get_attribute_offset(index) return self.m_attributes[offset + const.ATTRIBUTE_IX_VALUE_TYPE]
[ "def", "getAttributeValueType", "(", "self", ",", "index", ")", ":", "offset", "=", "self", ".", "_get_attribute_offset", "(", "index", ")", "return", "self", ".", "m_attributes", "[", "offset", "+", "const", ".", "ATTRIBUTE_IX_VALUE_TYPE", "]" ]
Return the type of the attribute at the given index :param index: index of the attribute
[ "Return", "the", "type", "of", "the", "attribute", "at", "the", "given", "index" ]
8ffe43e81a534f42c3620f3c1e3c6c0181a066bd
https://github.com/appknox/pyaxmlparser/blob/8ffe43e81a534f42c3620f3c1e3c6c0181a066bd/pyaxmlparser/axmlparser.py#L542-L549
train
54,309
appknox/pyaxmlparser
pyaxmlparser/axmlparser.py
AXMLParser.getAttributeValueData
def getAttributeValueData(self, index): """ Return the data of the attribute at the given index :param index: index of the attribute """ offset = self._get_attribute_offset(index) return self.m_attributes[offset + const.ATTRIBUTE_IX_VALUE_DATA]
python
def getAttributeValueData(self, index): """ Return the data of the attribute at the given index :param index: index of the attribute """ offset = self._get_attribute_offset(index) return self.m_attributes[offset + const.ATTRIBUTE_IX_VALUE_DATA]
[ "def", "getAttributeValueData", "(", "self", ",", "index", ")", ":", "offset", "=", "self", ".", "_get_attribute_offset", "(", "index", ")", "return", "self", ".", "m_attributes", "[", "offset", "+", "const", ".", "ATTRIBUTE_IX_VALUE_DATA", "]" ]
Return the data of the attribute at the given index :param index: index of the attribute
[ "Return", "the", "data", "of", "the", "attribute", "at", "the", "given", "index" ]
8ffe43e81a534f42c3620f3c1e3c6c0181a066bd
https://github.com/appknox/pyaxmlparser/blob/8ffe43e81a534f42c3620f3c1e3c6c0181a066bd/pyaxmlparser/axmlparser.py#L551-L558
train
54,310
Kyria/EsiPy
esipy/utils.py
make_cache_key
def make_cache_key(request): """ Generate a cache key from request object data """ headers = frozenset(request._p['header'].items()) path = frozenset(request._p['path'].items()) query = frozenset(request._p['query']) return (request.url, headers, path, query)
python
def make_cache_key(request): """ Generate a cache key from request object data """ headers = frozenset(request._p['header'].items()) path = frozenset(request._p['path'].items()) query = frozenset(request._p['query']) return (request.url, headers, path, query)
[ "def", "make_cache_key", "(", "request", ")", ":", "headers", "=", "frozenset", "(", "request", ".", "_p", "[", "'header'", "]", ".", "items", "(", ")", ")", "path", "=", "frozenset", "(", "request", ".", "_p", "[", "'path'", "]", ".", "items", "(", ...
Generate a cache key from request object data
[ "Generate", "a", "cache", "key", "from", "request", "object", "data" ]
06407a0218a126678f80d8a7e8a67b9729327865
https://github.com/Kyria/EsiPy/blob/06407a0218a126678f80d8a7e8a67b9729327865/esipy/utils.py#L15-L20
train
54,311
Kyria/EsiPy
esipy/utils.py
check_cache
def check_cache(cache): """ check if a cache fits esipy needs or not """ if isinstance(cache, BaseCache): return cache elif cache is False: return DictCache() elif cache is None: return DummyCache() else: raise ValueError('Provided cache must implement BaseCache')
python
def check_cache(cache): """ check if a cache fits esipy needs or not """ if isinstance(cache, BaseCache): return cache elif cache is False: return DictCache() elif cache is None: return DummyCache() else: raise ValueError('Provided cache must implement BaseCache')
[ "def", "check_cache", "(", "cache", ")", ":", "if", "isinstance", "(", "cache", ",", "BaseCache", ")", ":", "return", "cache", "elif", "cache", "is", "False", ":", "return", "DictCache", "(", ")", "elif", "cache", "is", "None", ":", "return", "DummyCache...
check if a cache fits esipy needs or not
[ "check", "if", "a", "cache", "fits", "esipy", "needs", "or", "not" ]
06407a0218a126678f80d8a7e8a67b9729327865
https://github.com/Kyria/EsiPy/blob/06407a0218a126678f80d8a7e8a67b9729327865/esipy/utils.py#L23-L32
train
54,312
Kyria/EsiPy
esipy/utils.py
get_cache_time_left
def get_cache_time_left(expires_header): """ return the time left in second for an expires header """ epoch = datetime(1970, 1, 1) # this date is ALWAYS in UTC (RFC 7231) expire = ( datetime( *parsedate(expires_header)[:6] ) - epoch ).total_seconds() now = (datetime.utcnow() - epoch).total_seconds() return int(expire) - int(now)
python
def get_cache_time_left(expires_header): """ return the time left in second for an expires header """ epoch = datetime(1970, 1, 1) # this date is ALWAYS in UTC (RFC 7231) expire = ( datetime( *parsedate(expires_header)[:6] ) - epoch ).total_seconds() now = (datetime.utcnow() - epoch).total_seconds() return int(expire) - int(now)
[ "def", "get_cache_time_left", "(", "expires_header", ")", ":", "epoch", "=", "datetime", "(", "1970", ",", "1", ",", "1", ")", "# this date is ALWAYS in UTC (RFC 7231)", "expire", "=", "(", "datetime", "(", "*", "parsedate", "(", "expires_header", ")", "[", ":...
return the time left in second for an expires header
[ "return", "the", "time", "left", "in", "second", "for", "an", "expires", "header" ]
06407a0218a126678f80d8a7e8a67b9729327865
https://github.com/Kyria/EsiPy/blob/06407a0218a126678f80d8a7e8a67b9729327865/esipy/utils.py#L35-L45
train
54,313
Kyria/EsiPy
esipy/app.py
EsiApp.__get_or_create_app
def __get_or_create_app(self, url, cache_key): """ Get the app from cache or generate a new one if required Because app object doesn't have etag/expiry, we have to make a head() call before, to have these informations first... """ headers = {"Accept": "application/json"} app_url = '%s?datasource=%s' % (url, self.datasource) cached = self.cache.get(cache_key, (None, None, 0)) if cached is None or len(cached) != 3: self.cache.invalidate(cache_key) cached_app, cached_headers, cached_expiry = (cached, None, 0) else: cached_app, cached_headers, cached_expiry = cached if cached_app is not None and cached_headers is not None: # we didn't set custom expire, use header expiry expires = cached_headers.get('expires', None) cache_timeout = -1 if self.expire is None and expires is not None: cache_timeout = get_cache_time_left( cached_headers['expires'] ) if cache_timeout >= 0: return cached_app # we set custom expire, check this instead else: if self.expire == 0 or cached_expiry >= time.time(): return cached_app # if we have etags, add the header to use them etag = cached_headers.get('etag', None) if etag is not None: headers['If-None-Match'] = etag # if nothing makes us use the cache, invalidate it if ((expires is None or cache_timeout < 0 or cached_expiry < time.time()) and etag is None): self.cache.invalidate(cache_key) # set timeout value in case we have to cache it later timeout = 0 if self.expire is not None and self.expire > 0: timeout = time.time() + self.expire # we are here, we know we have to make a head call... res = requests.head(app_url, headers=headers) if res.status_code == 304 and cached_app is not None: self.cache.set( cache_key, (cached_app, res.headers, timeout) ) return cached_app # ok, cache is not accurate, make the full stuff app = App.create(app_url) if self.caching: self.cache.set(cache_key, (app, res.headers, timeout)) return app
python
def __get_or_create_app(self, url, cache_key): """ Get the app from cache or generate a new one if required Because app object doesn't have etag/expiry, we have to make a head() call before, to have these informations first... """ headers = {"Accept": "application/json"} app_url = '%s?datasource=%s' % (url, self.datasource) cached = self.cache.get(cache_key, (None, None, 0)) if cached is None or len(cached) != 3: self.cache.invalidate(cache_key) cached_app, cached_headers, cached_expiry = (cached, None, 0) else: cached_app, cached_headers, cached_expiry = cached if cached_app is not None and cached_headers is not None: # we didn't set custom expire, use header expiry expires = cached_headers.get('expires', None) cache_timeout = -1 if self.expire is None and expires is not None: cache_timeout = get_cache_time_left( cached_headers['expires'] ) if cache_timeout >= 0: return cached_app # we set custom expire, check this instead else: if self.expire == 0 or cached_expiry >= time.time(): return cached_app # if we have etags, add the header to use them etag = cached_headers.get('etag', None) if etag is not None: headers['If-None-Match'] = etag # if nothing makes us use the cache, invalidate it if ((expires is None or cache_timeout < 0 or cached_expiry < time.time()) and etag is None): self.cache.invalidate(cache_key) # set timeout value in case we have to cache it later timeout = 0 if self.expire is not None and self.expire > 0: timeout = time.time() + self.expire # we are here, we know we have to make a head call... res = requests.head(app_url, headers=headers) if res.status_code == 304 and cached_app is not None: self.cache.set( cache_key, (cached_app, res.headers, timeout) ) return cached_app # ok, cache is not accurate, make the full stuff app = App.create(app_url) if self.caching: self.cache.set(cache_key, (app, res.headers, timeout)) return app
[ "def", "__get_or_create_app", "(", "self", ",", "url", ",", "cache_key", ")", ":", "headers", "=", "{", "\"Accept\"", ":", "\"application/json\"", "}", "app_url", "=", "'%s?datasource=%s'", "%", "(", "url", ",", "self", ".", "datasource", ")", "cached", "=",...
Get the app from cache or generate a new one if required Because app object doesn't have etag/expiry, we have to make a head() call before, to have these informations first...
[ "Get", "the", "app", "from", "cache", "or", "generate", "a", "new", "one", "if", "required" ]
06407a0218a126678f80d8a7e8a67b9729327865
https://github.com/Kyria/EsiPy/blob/06407a0218a126678f80d8a7e8a67b9729327865/esipy/app.py#L50-L110
train
54,314
Kyria/EsiPy
esipy/app.py
EsiApp.clear_cached_endpoints
def clear_cached_endpoints(self, prefix=None): """ Invalidate all cached endpoints, meta included Loop over all meta endpoints to generate all cache key the invalidate each of them. Doing it this way will prevent the app not finding keys as the user may change its prefixes Meta endpoint will be updated upon next call. :param: prefix the prefix for the cache key (default is cache_prefix) """ prefix = prefix if prefix is not None else self.cache_prefix for endpoint in self.app.op.values(): cache_key = '%s:app:%s' % (prefix, endpoint.url) self.cache.invalidate(cache_key) self.cache.invalidate('%s:app:meta_swagger_url' % self.cache_prefix) self.app = None
python
def clear_cached_endpoints(self, prefix=None): """ Invalidate all cached endpoints, meta included Loop over all meta endpoints to generate all cache key the invalidate each of them. Doing it this way will prevent the app not finding keys as the user may change its prefixes Meta endpoint will be updated upon next call. :param: prefix the prefix for the cache key (default is cache_prefix) """ prefix = prefix if prefix is not None else self.cache_prefix for endpoint in self.app.op.values(): cache_key = '%s:app:%s' % (prefix, endpoint.url) self.cache.invalidate(cache_key) self.cache.invalidate('%s:app:meta_swagger_url' % self.cache_prefix) self.app = None
[ "def", "clear_cached_endpoints", "(", "self", ",", "prefix", "=", "None", ")", ":", "prefix", "=", "prefix", "if", "prefix", "is", "not", "None", "else", "self", ".", "cache_prefix", "for", "endpoint", "in", "self", ".", "app", ".", "op", ".", "values", ...
Invalidate all cached endpoints, meta included Loop over all meta endpoints to generate all cache key the invalidate each of them. Doing it this way will prevent the app not finding keys as the user may change its prefixes Meta endpoint will be updated upon next call. :param: prefix the prefix for the cache key (default is cache_prefix)
[ "Invalidate", "all", "cached", "endpoints", "meta", "included" ]
06407a0218a126678f80d8a7e8a67b9729327865
https://github.com/Kyria/EsiPy/blob/06407a0218a126678f80d8a7e8a67b9729327865/esipy/app.py#L147-L161
train
54,315
Kyria/EsiPy
esipy/cache.py
_hash
def _hash(data): """ generate a hash from data object to be used as cache key """ hash_algo = hashlib.new('md5') hash_algo.update(pickle.dumps(data)) # prefix allows possibility of multiple applications # sharing same keyspace return 'esi_' + hash_algo.hexdigest()
python
def _hash(data): """ generate a hash from data object to be used as cache key """ hash_algo = hashlib.new('md5') hash_algo.update(pickle.dumps(data)) # prefix allows possibility of multiple applications # sharing same keyspace return 'esi_' + hash_algo.hexdigest()
[ "def", "_hash", "(", "data", ")", ":", "hash_algo", "=", "hashlib", ".", "new", "(", "'md5'", ")", "hash_algo", ".", "update", "(", "pickle", ".", "dumps", "(", "data", ")", ")", "# prefix allows possibility of multiple applications\r", "# sharing same keyspace\r"...
generate a hash from data object to be used as cache key
[ "generate", "a", "hash", "from", "data", "object", "to", "be", "used", "as", "cache", "key" ]
06407a0218a126678f80d8a7e8a67b9729327865
https://github.com/Kyria/EsiPy/blob/06407a0218a126678f80d8a7e8a67b9729327865/esipy/cache.py#L14-L20
train
54,316
mjirik/imcut
imcut/models.py
Model3D.fit_from_image
def fit_from_image(self, data, voxelsize, seeds, unique_cls): """ This Method allows computes feature vector and train model. :cls: list of index number of requested classes in seeds """ fvs, clsselected = self.features_from_image(data, voxelsize, seeds, unique_cls) self.fit(fvs, clsselected)
python
def fit_from_image(self, data, voxelsize, seeds, unique_cls): """ This Method allows computes feature vector and train model. :cls: list of index number of requested classes in seeds """ fvs, clsselected = self.features_from_image(data, voxelsize, seeds, unique_cls) self.fit(fvs, clsselected)
[ "def", "fit_from_image", "(", "self", ",", "data", ",", "voxelsize", ",", "seeds", ",", "unique_cls", ")", ":", "fvs", ",", "clsselected", "=", "self", ".", "features_from_image", "(", "data", ",", "voxelsize", ",", "seeds", ",", "unique_cls", ")", "self",...
This Method allows computes feature vector and train model. :cls: list of index number of requested classes in seeds
[ "This", "Method", "allows", "computes", "feature", "vector", "and", "train", "model", "." ]
1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3
https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/models.py#L118-L125
train
54,317
mjirik/imcut
imcut/models.py
Model3D.save
def save(self, filename): """ Save model to pickle file. External feature function is not stored """ import dill tmpmodelparams = self.modelparams.copy() # fv_extern_src = None fv_extern_name = None # try: # fv_extern_src = dill.source.getsource(tmpmodelparams['fv_extern']) # tmpmodelparams.pop('fv_extern') # except: # pass # fv_extern_name = dill.source.getname(tmpmodelparams['fv_extern']) if "fv_extern" in tmpmodelparams: tmpmodelparams.pop("fv_extern") sv = { "modelparams": tmpmodelparams, "mdl": self.mdl, # 'fv_extern_src': fv_extern_src, # 'fv_extern_src_name': fv_extern_src_name, # 'fv_extern_name': fv_extern_src_name, # } sss = dill.dumps(self.modelparams) logger.debug("pickled " + str(sss)) dill.dump(sv, open(filename, "wb"))
python
def save(self, filename): """ Save model to pickle file. External feature function is not stored """ import dill tmpmodelparams = self.modelparams.copy() # fv_extern_src = None fv_extern_name = None # try: # fv_extern_src = dill.source.getsource(tmpmodelparams['fv_extern']) # tmpmodelparams.pop('fv_extern') # except: # pass # fv_extern_name = dill.source.getname(tmpmodelparams['fv_extern']) if "fv_extern" in tmpmodelparams: tmpmodelparams.pop("fv_extern") sv = { "modelparams": tmpmodelparams, "mdl": self.mdl, # 'fv_extern_src': fv_extern_src, # 'fv_extern_src_name': fv_extern_src_name, # 'fv_extern_name': fv_extern_src_name, # } sss = dill.dumps(self.modelparams) logger.debug("pickled " + str(sss)) dill.dump(sv, open(filename, "wb"))
[ "def", "save", "(", "self", ",", "filename", ")", ":", "import", "dill", "tmpmodelparams", "=", "self", ".", "modelparams", ".", "copy", "(", ")", "# fv_extern_src = None", "fv_extern_name", "=", "None", "# try:", "# fv_extern_src = dill.source.getsource(tmpmodelp...
Save model to pickle file. External feature function is not stored
[ "Save", "model", "to", "pickle", "file", ".", "External", "feature", "function", "is", "not", "stored" ]
1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3
https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/models.py#L133-L163
train
54,318
mjirik/imcut
imcut/models.py
Model3D.load
def load(self, mdl_file): """ load model from file. fv_type is not set with this function. It is expected to set it before. """ import dill as pickle mdl_file_e = op.expanduser(mdl_file) sv = pickle.load(open(mdl_file_e, "rb")) self.mdl = sv["mdl"] # self.mdl[2] = self.mdl[0] # try: # eval(sv['fv_extern_src']) # eval("fv_extern_temp_name = " + sv['fv_extern_src_name']) # sv['fv_extern'] = fv_extern_temp_name # except: # print "pomoc,necoje blbe" # pass self.modelparams.update(sv["modelparams"]) logger.debug("loaded model from path: " + mdl_file_e)
python
def load(self, mdl_file): """ load model from file. fv_type is not set with this function. It is expected to set it before. """ import dill as pickle mdl_file_e = op.expanduser(mdl_file) sv = pickle.load(open(mdl_file_e, "rb")) self.mdl = sv["mdl"] # self.mdl[2] = self.mdl[0] # try: # eval(sv['fv_extern_src']) # eval("fv_extern_temp_name = " + sv['fv_extern_src_name']) # sv['fv_extern'] = fv_extern_temp_name # except: # print "pomoc,necoje blbe" # pass self.modelparams.update(sv["modelparams"]) logger.debug("loaded model from path: " + mdl_file_e)
[ "def", "load", "(", "self", ",", "mdl_file", ")", ":", "import", "dill", "as", "pickle", "mdl_file_e", "=", "op", ".", "expanduser", "(", "mdl_file", ")", "sv", "=", "pickle", ".", "load", "(", "open", "(", "mdl_file_e", ",", "\"rb\"", ")", ")", "sel...
load model from file. fv_type is not set with this function. It is expected to set it before.
[ "load", "model", "from", "file", ".", "fv_type", "is", "not", "set", "with", "this", "function", ".", "It", "is", "expected", "to", "set", "it", "before", "." ]
1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3
https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/models.py#L165-L185
train
54,319
mjirik/imcut
imcut/models.py
Model.features_from_image
def features_from_image( self, data, voxelsize, seeds=None, unique_cls=None ): # , voxels=None): """ Input data is 3d image :param data: is 3d image :param seeds: ndimage with same shape as data, nonzero values means seeds. :param unique_cls: can select only fv for seeds from specific class. f.e. unique_cls = [1, 2] ignores label 0 funcion is called twice in graph cut first call is with all params, second is only with data. based on self.modelparams['fv_type'] the feature vector is computed keywords "intensity", "voxels", "fv001", "fv_extern" can be used. modelparams['fv_type'] = 'fv_extern' allows to use external fv function Example of exter feature function. For easier implementation of return values use function return_fv_by_seeds(). def fv_function(data, voxelsize, seeds=None, cl=None): data2 = scipy.ndimage.filters.gaussian_filter(data, sigma=5) arrs = [data.reshape(-1, 1), data2.reshape(-1, 1)] fv = np.concatenate(arrs, axis=1) return imcut.features.return_fv_by_seeds(fv, seeds, unique_cls) modelparams['fv_extern'] = fv_function """ fv_type = self.modelparams["fv_type"] logger.debug("fv_type " + fv_type) fv = [] if fv_type == "intensity": fv = data.reshape(-1, 1) if seeds is not None: logger.debug("seeds: %s", scipy.stats.describe(seeds, axis=None)) sd = seeds.reshape(-1, 1) selection = np.in1d(sd, unique_cls) fv = fv[selection] sd = sd[selection] # sd = sd[] return fv, sd return fv # elif fv_type in ("voxels"): # if seeds is not None: # fv = np.asarray(voxels).reshape(-1, 1) # else: # fv = data # fv = fv.reshape(-1, 1) elif fv_type in ("fv001", "FV001", "intensity_and_blur"): # intensity in pixel, gaussian blur intensity return features.fv_function_intensity_and_smoothing( data, voxelsize, seeds, unique_cls ) # from PyQt4.QtCore import pyqtRemoveInputHook # pyqtRemoveInputHook() # print fv1.shape # print fv2.shape # print fv.shape elif fv_type == "fv_extern": fv_function = self.modelparams["fv_extern"] return fv_function(data, voxelsize, seeds, unique_cls) else: logger.error("Unknown feature vector type: " + self.modelparams["fv_type"]) return fv
python
def features_from_image( self, data, voxelsize, seeds=None, unique_cls=None ): # , voxels=None): """ Input data is 3d image :param data: is 3d image :param seeds: ndimage with same shape as data, nonzero values means seeds. :param unique_cls: can select only fv for seeds from specific class. f.e. unique_cls = [1, 2] ignores label 0 funcion is called twice in graph cut first call is with all params, second is only with data. based on self.modelparams['fv_type'] the feature vector is computed keywords "intensity", "voxels", "fv001", "fv_extern" can be used. modelparams['fv_type'] = 'fv_extern' allows to use external fv function Example of exter feature function. For easier implementation of return values use function return_fv_by_seeds(). def fv_function(data, voxelsize, seeds=None, cl=None): data2 = scipy.ndimage.filters.gaussian_filter(data, sigma=5) arrs = [data.reshape(-1, 1), data2.reshape(-1, 1)] fv = np.concatenate(arrs, axis=1) return imcut.features.return_fv_by_seeds(fv, seeds, unique_cls) modelparams['fv_extern'] = fv_function """ fv_type = self.modelparams["fv_type"] logger.debug("fv_type " + fv_type) fv = [] if fv_type == "intensity": fv = data.reshape(-1, 1) if seeds is not None: logger.debug("seeds: %s", scipy.stats.describe(seeds, axis=None)) sd = seeds.reshape(-1, 1) selection = np.in1d(sd, unique_cls) fv = fv[selection] sd = sd[selection] # sd = sd[] return fv, sd return fv # elif fv_type in ("voxels"): # if seeds is not None: # fv = np.asarray(voxels).reshape(-1, 1) # else: # fv = data # fv = fv.reshape(-1, 1) elif fv_type in ("fv001", "FV001", "intensity_and_blur"): # intensity in pixel, gaussian blur intensity return features.fv_function_intensity_and_smoothing( data, voxelsize, seeds, unique_cls ) # from PyQt4.QtCore import pyqtRemoveInputHook # pyqtRemoveInputHook() # print fv1.shape # print fv2.shape # print fv.shape elif fv_type == "fv_extern": fv_function = self.modelparams["fv_extern"] return fv_function(data, voxelsize, seeds, unique_cls) else: logger.error("Unknown feature vector type: " + self.modelparams["fv_type"]) return fv
[ "def", "features_from_image", "(", "self", ",", "data", ",", "voxelsize", ",", "seeds", "=", "None", ",", "unique_cls", "=", "None", ")", ":", "# , voxels=None):", "fv_type", "=", "self", ".", "modelparams", "[", "\"fv_type\"", "]", "logger", ".", "debug", ...
Input data is 3d image :param data: is 3d image :param seeds: ndimage with same shape as data, nonzero values means seeds. :param unique_cls: can select only fv for seeds from specific class. f.e. unique_cls = [1, 2] ignores label 0 funcion is called twice in graph cut first call is with all params, second is only with data. based on self.modelparams['fv_type'] the feature vector is computed keywords "intensity", "voxels", "fv001", "fv_extern" can be used. modelparams['fv_type'] = 'fv_extern' allows to use external fv function Example of exter feature function. For easier implementation of return values use function return_fv_by_seeds(). def fv_function(data, voxelsize, seeds=None, cl=None): data2 = scipy.ndimage.filters.gaussian_filter(data, sigma=5) arrs = [data.reshape(-1, 1), data2.reshape(-1, 1)] fv = np.concatenate(arrs, axis=1) return imcut.features.return_fv_by_seeds(fv, seeds, unique_cls) modelparams['fv_extern'] = fv_function
[ "Input", "data", "is", "3d", "image" ]
1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3
https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/models.py#L203-L273
train
54,320
mjirik/imcut
imcut/models.py
Model._fit_one_class
def _fit_one_class(self, clx, cl): """ Train clas number cl with data clx. Use trainFromImageAndSeeds() function if you want to use 3D image data as an input. clx: data, 2d matrix cl: label, integer label: gmmsame, gaussian_kde, dpgmm, stored """ logger.debug("clx " + str(clx[:10, :])) logger.debug("clx type" + str(clx.dtype)) # name = 'clx' + str(cl) + '.npy' # print name # np.save(name, clx) logger.debug("_fit()") if self.modelparams["adaptation"] == "original_data": if cl in self.mdl.keys(): return # if True: # return logger.debug("training continues") if self.modelparams["type"] == "gmmsame": if len(clx.shape) == 1: logger.warning( "reshaping in train will be removed. Use \ \ntrainFromImageAndSeeds() function" ) print("Warning deprecated feature in train() function") # je to jen jednorozměrný vektor, tak je potřeba to # převést na 2d matici clx = clx.reshape(-1, 1) gmmparams = self.modelparams["params"] self.mdl[cl] = sklearn.mixture.GaussianMixture(**gmmparams) self.mdl[cl].fit(clx) elif self.modelparams["type"] == "kernel": # Not working (probably) in old versions of scikits # from sklearn.neighbors.kde import KernelDensity from sklearn.neighbors import KernelDensity # kernelmodelparams = {'kernel': 'gaussian', 'bandwidth': 0.2} kernelmodelparams = self.modelparams["params"] self.mdl[cl] = KernelDensity(**kernelmodelparams).fit(clx) elif self.modelparams["type"] == "gaussian_kde": # print clx import scipy.stats # from PyQt4.QtCore import pyqtRemoveInputHook # pyqtRemoveInputHook() # gaussian_kde works only with floating point types self.mdl[cl] = scipy.stats.gaussian_kde(clx.astype(np.float)) elif self.modelparams["type"] == "dpgmm": # print 'clx.shape ', clx.shape # print 'cl ', cl gmmparams = self.modelparams["params"] self.mdl[cl] = sklearn.mixture.DPGMM(**gmmparams) # todo here is a hack # dpgmm z nějakého důvodu nefunguje pro naše data # vždy natrénuje jednu složku v blízkosti nuly # patrně to bude mít něco společného s parametrem alpha # přenásobí-li se to malým číslem, zázračně to chodí self.mdl[cl].fit(clx * 0.001) elif self.modelparams["type"] == "stored": # Classifer is trained before segmentation and stored to pickle import pickle print("stored") logger.warning("deprecated use of stored parameters") mdl_file = self.modelparams["params"]["mdl_file"] self.mdl = pickle.load(open(mdl_file, "rb")) else: raise NameError("Unknown model type")
python
def _fit_one_class(self, clx, cl): """ Train clas number cl with data clx. Use trainFromImageAndSeeds() function if you want to use 3D image data as an input. clx: data, 2d matrix cl: label, integer label: gmmsame, gaussian_kde, dpgmm, stored """ logger.debug("clx " + str(clx[:10, :])) logger.debug("clx type" + str(clx.dtype)) # name = 'clx' + str(cl) + '.npy' # print name # np.save(name, clx) logger.debug("_fit()") if self.modelparams["adaptation"] == "original_data": if cl in self.mdl.keys(): return # if True: # return logger.debug("training continues") if self.modelparams["type"] == "gmmsame": if len(clx.shape) == 1: logger.warning( "reshaping in train will be removed. Use \ \ntrainFromImageAndSeeds() function" ) print("Warning deprecated feature in train() function") # je to jen jednorozměrný vektor, tak je potřeba to # převést na 2d matici clx = clx.reshape(-1, 1) gmmparams = self.modelparams["params"] self.mdl[cl] = sklearn.mixture.GaussianMixture(**gmmparams) self.mdl[cl].fit(clx) elif self.modelparams["type"] == "kernel": # Not working (probably) in old versions of scikits # from sklearn.neighbors.kde import KernelDensity from sklearn.neighbors import KernelDensity # kernelmodelparams = {'kernel': 'gaussian', 'bandwidth': 0.2} kernelmodelparams = self.modelparams["params"] self.mdl[cl] = KernelDensity(**kernelmodelparams).fit(clx) elif self.modelparams["type"] == "gaussian_kde": # print clx import scipy.stats # from PyQt4.QtCore import pyqtRemoveInputHook # pyqtRemoveInputHook() # gaussian_kde works only with floating point types self.mdl[cl] = scipy.stats.gaussian_kde(clx.astype(np.float)) elif self.modelparams["type"] == "dpgmm": # print 'clx.shape ', clx.shape # print 'cl ', cl gmmparams = self.modelparams["params"] self.mdl[cl] = sklearn.mixture.DPGMM(**gmmparams) # todo here is a hack # dpgmm z nějakého důvodu nefunguje pro naše data # vždy natrénuje jednu složku v blízkosti nuly # patrně to bude mít něco společného s parametrem alpha # přenásobí-li se to malým číslem, zázračně to chodí self.mdl[cl].fit(clx * 0.001) elif self.modelparams["type"] == "stored": # Classifer is trained before segmentation and stored to pickle import pickle print("stored") logger.warning("deprecated use of stored parameters") mdl_file = self.modelparams["params"]["mdl_file"] self.mdl = pickle.load(open(mdl_file, "rb")) else: raise NameError("Unknown model type")
[ "def", "_fit_one_class", "(", "self", ",", "clx", ",", "cl", ")", ":", "logger", ".", "debug", "(", "\"clx \"", "+", "str", "(", "clx", "[", ":", "10", ",", ":", "]", ")", ")", "logger", ".", "debug", "(", "\"clx type\"", "+", "str", "(", "clx", ...
Train clas number cl with data clx. Use trainFromImageAndSeeds() function if you want to use 3D image data as an input. clx: data, 2d matrix cl: label, integer label: gmmsame, gaussian_kde, dpgmm, stored
[ "Train", "clas", "number", "cl", "with", "data", "clx", "." ]
1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3
https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/models.py#L311-L391
train
54,321
mjirik/imcut
imcut/pycut.py
relabel_squeeze
def relabel_squeeze(data): """ Makes relabeling of data if there are unused values. """ palette, index = np.unique(data, return_inverse=True) data = index.reshape(data.shape) # realy slow solution # unq = np.unique(data) # actual_label = 0 # for lab in unq: # data[data == lab] = actual_label # actual_label += 1 # one another solution probably slower # arr = data # data = (np.digitize(arr.reshape(-1,),np.unique(arr))-1).reshape(arr.shape) return data
python
def relabel_squeeze(data): """ Makes relabeling of data if there are unused values. """ palette, index = np.unique(data, return_inverse=True) data = index.reshape(data.shape) # realy slow solution # unq = np.unique(data) # actual_label = 0 # for lab in unq: # data[data == lab] = actual_label # actual_label += 1 # one another solution probably slower # arr = data # data = (np.digitize(arr.reshape(-1,),np.unique(arr))-1).reshape(arr.shape) return data
[ "def", "relabel_squeeze", "(", "data", ")", ":", "palette", ",", "index", "=", "np", ".", "unique", "(", "data", ",", "return_inverse", "=", "True", ")", "data", "=", "index", ".", "reshape", "(", "data", ".", "shape", ")", "# realy slow solution", "# ...
Makes relabeling of data if there are unused values.
[ "Makes", "relabeling", "of", "data", "if", "there", "are", "unused", "values", "." ]
1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3
https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/pycut.py#L1607-L1622
train
54,322
mjirik/imcut
imcut/pycut.py
ImageGraphCut.load
def load(self, filename, fv_extern=None): """ Read model stored in the file. :param filename: Path to file with model :param fv_extern: external feature vector function is passed here :return: """ self.modelparams["mdl_stored_file"] = filename if fv_extern is not None: self.modelparams["fv_extern"] = fv_extern # segparams['modelparams'] = { # 'mdl_stored_file': mdl_stored_file, # # 'fv_extern': fv_function # } self.mdl = Model(modelparams=self.modelparams)
python
def load(self, filename, fv_extern=None): """ Read model stored in the file. :param filename: Path to file with model :param fv_extern: external feature vector function is passed here :return: """ self.modelparams["mdl_stored_file"] = filename if fv_extern is not None: self.modelparams["fv_extern"] = fv_extern # segparams['modelparams'] = { # 'mdl_stored_file': mdl_stored_file, # # 'fv_extern': fv_function # } self.mdl = Model(modelparams=self.modelparams)
[ "def", "load", "(", "self", ",", "filename", ",", "fv_extern", "=", "None", ")", ":", "self", ".", "modelparams", "[", "\"mdl_stored_file\"", "]", "=", "filename", "if", "fv_extern", "is", "not", "None", ":", "self", ".", "modelparams", "[", "\"fv_extern\"...
Read model stored in the file. :param filename: Path to file with model :param fv_extern: external feature vector function is passed here :return:
[ "Read", "model", "stored", "in", "the", "file", "." ]
1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3
https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/pycut.py#L153-L169
train
54,323
ArabellaTech/django-basic-cms
basic_cms/templatetags/pages_tags.py
show_slug_with_level
def show_slug_with_level(context, page, lang=None, fallback=True): """Display slug with level by language.""" if not lang: lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE) page = get_page_from_string_or_id(page, lang) if not page: return '' return {'content': page.slug_with_level(lang)}
python
def show_slug_with_level(context, page, lang=None, fallback=True): """Display slug with level by language.""" if not lang: lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE) page = get_page_from_string_or_id(page, lang) if not page: return '' return {'content': page.slug_with_level(lang)}
[ "def", "show_slug_with_level", "(", "context", ",", "page", ",", "lang", "=", "None", ",", "fallback", "=", "True", ")", ":", "if", "not", "lang", ":", "lang", "=", "context", ".", "get", "(", "'lang'", ",", "pages_settings", ".", "PAGE_DEFAULT_LANGUAGE", ...
Display slug with level by language.
[ "Display", "slug", "with", "level", "by", "language", "." ]
863f3c6098606f663994930cd8e7723ad0c07caf
https://github.com/ArabellaTech/django-basic-cms/blob/863f3c6098606f663994930cd8e7723ad0c07caf/basic_cms/templatetags/pages_tags.py#L174-L183
train
54,324
ArabellaTech/django-basic-cms
basic_cms/templatetags/pages_tags.py
do_get_pages_with_tag
def do_get_pages_with_tag(parser, token): """ Return Pages with given tag Syntax:: {% get_pages_with_tag <tag name> as <varname> %} Example use: {% get_pages_with_tag "footer" as pages %} """ bits = token.split_contents() if 4 != len(bits): raise TemplateSyntaxError('%r expects 2 arguments' % bits[0]) if bits[-2] != 'as': raise TemplateSyntaxError( '%r expects "as" as the second last argument' % bits[0]) varname = bits[-1] tag = parser.compile_filter(bits[1]) varname = bits[-1] return GetPagesWithTagNode(tag, varname)
python
def do_get_pages_with_tag(parser, token): """ Return Pages with given tag Syntax:: {% get_pages_with_tag <tag name> as <varname> %} Example use: {% get_pages_with_tag "footer" as pages %} """ bits = token.split_contents() if 4 != len(bits): raise TemplateSyntaxError('%r expects 2 arguments' % bits[0]) if bits[-2] != 'as': raise TemplateSyntaxError( '%r expects "as" as the second last argument' % bits[0]) varname = bits[-1] tag = parser.compile_filter(bits[1]) varname = bits[-1] return GetPagesWithTagNode(tag, varname)
[ "def", "do_get_pages_with_tag", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "4", "!=", "len", "(", "bits", ")", ":", "raise", "TemplateSyntaxError", "(", "'%r expects 2 arguments'", "%", "bits", "[", ...
Return Pages with given tag Syntax:: {% get_pages_with_tag <tag name> as <varname> %} Example use: {% get_pages_with_tag "footer" as pages %}
[ "Return", "Pages", "with", "given", "tag" ]
863f3c6098606f663994930cd8e7723ad0c07caf
https://github.com/ArabellaTech/django-basic-cms/blob/863f3c6098606f663994930cd8e7723ad0c07caf/basic_cms/templatetags/pages_tags.py#L503-L523
train
54,325
sirfoga/pyhal
hal/files/models/system.py
remove_year
def remove_year(name): """Removes year from input :param name: path to edit :return: inputs with no years """ for i in range(len( name) - 3): # last index is length - 3 - 1 = length - 4 if name[i: i + 4].isdigit(): name = name[:i] + name[i + 4:] return remove_year( name) # if there is a removal, start again return name
python
def remove_year(name): """Removes year from input :param name: path to edit :return: inputs with no years """ for i in range(len( name) - 3): # last index is length - 3 - 1 = length - 4 if name[i: i + 4].isdigit(): name = name[:i] + name[i + 4:] return remove_year( name) # if there is a removal, start again return name
[ "def", "remove_year", "(", "name", ")", ":", "for", "i", "in", "range", "(", "len", "(", "name", ")", "-", "3", ")", ":", "# last index is length - 3 - 1 = length - 4", "if", "name", "[", "i", ":", "i", "+", "4", "]", ".", "isdigit", "(", ")", ":", ...
Removes year from input :param name: path to edit :return: inputs with no years
[ "Removes", "year", "from", "input" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/files/models/system.py#L85-L97
train
54,326
sirfoga/pyhal
hal/files/models/system.py
remove_brackets
def remove_brackets(name): """Removes brackets form input :param name: path to fix :return: inputs with no brackets """ name = re.sub( r"([(\[]).*?([)\]])", r"\g<1>\g<2>", name ) # remove anything in between brackets brackets = "()[]{}" # list of brackets for bracket in brackets: name = name.replace(bracket, "") return name
python
def remove_brackets(name): """Removes brackets form input :param name: path to fix :return: inputs with no brackets """ name = re.sub( r"([(\[]).*?([)\]])", r"\g<1>\g<2>", name ) # remove anything in between brackets brackets = "()[]{}" # list of brackets for bracket in brackets: name = name.replace(bracket, "") return name
[ "def", "remove_brackets", "(", "name", ")", ":", "name", "=", "re", ".", "sub", "(", "r\"([(\\[]).*?([)\\]])\"", ",", "r\"\\g<1>\\g<2>\"", ",", "name", ")", "# remove anything in between brackets", "brackets", "=", "\"()[]{}\"", "# list of brackets", "for", "bracket",...
Removes brackets form input :param name: path to fix :return: inputs with no brackets
[ "Removes", "brackets", "form", "input" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/files/models/system.py#L100-L114
train
54,327
sirfoga/pyhal
hal/files/models/system.py
extract_name_max_chars
def extract_name_max_chars(name, max_chars=64, blank=" "): """Extracts max chars in name truncated to nearest word :param name: path to edit :param max_chars: max chars of new name :param blank: char that represents the blank between words :return: Name edited to contain at most max_chars """ new_name = name.strip() if len(new_name) > max_chars: new_name = new_name[:max_chars] # get at most 64 chars if new_name.rfind(blank) > 0: new_name = new_name[:new_name.rfind(blank)] # nearest word return new_name
python
def extract_name_max_chars(name, max_chars=64, blank=" "): """Extracts max chars in name truncated to nearest word :param name: path to edit :param max_chars: max chars of new name :param blank: char that represents the blank between words :return: Name edited to contain at most max_chars """ new_name = name.strip() if len(new_name) > max_chars: new_name = new_name[:max_chars] # get at most 64 chars if new_name.rfind(blank) > 0: new_name = new_name[:new_name.rfind(blank)] # nearest word return new_name
[ "def", "extract_name_max_chars", "(", "name", ",", "max_chars", "=", "64", ",", "blank", "=", "\" \"", ")", ":", "new_name", "=", "name", ".", "strip", "(", ")", "if", "len", "(", "new_name", ")", ">", "max_chars", ":", "new_name", "=", "new_name", "["...
Extracts max chars in name truncated to nearest word :param name: path to edit :param max_chars: max chars of new name :param blank: char that represents the blank between words :return: Name edited to contain at most max_chars
[ "Extracts", "max", "chars", "in", "name", "truncated", "to", "nearest", "word" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/files/models/system.py#L117-L130
train
54,328
sirfoga/pyhal
hal/files/models/system.py
get_parent_folder_name
def get_parent_folder_name(file_path): """Finds parent folder of file :param file_path: path :return: Name of folder container """ return os.path.split(os.path.split(os.path.abspath(file_path))[0])[-1]
python
def get_parent_folder_name(file_path): """Finds parent folder of file :param file_path: path :return: Name of folder container """ return os.path.split(os.path.split(os.path.abspath(file_path))[0])[-1]
[ "def", "get_parent_folder_name", "(", "file_path", ")", ":", "return", "os", ".", "path", ".", "split", "(", "os", ".", "path", ".", "split", "(", "os", ".", "path", ".", "abspath", "(", "file_path", ")", ")", "[", "0", "]", ")", "[", "-", "1", "...
Finds parent folder of file :param file_path: path :return: Name of folder container
[ "Finds", "parent", "folder", "of", "file" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/files/models/system.py#L183-L189
train
54,329
sirfoga/pyhal
hal/files/models/system.py
ls_dir
def ls_dir(path, include_hidden=False): """Finds content of folder :param path: directory to get list of files and folders :param include_hidden: True iff include hidden files in list :return: List of paths in given directory """ lst = [] for file in os.listdir(path): hidden_file = FileSystem(file).is_hidden() if (hidden_file and include_hidden) or (not hidden_file): lst.append(os.path.join(path, file)) return list(set(lst))
python
def ls_dir(path, include_hidden=False): """Finds content of folder :param path: directory to get list of files and folders :param include_hidden: True iff include hidden files in list :return: List of paths in given directory """ lst = [] for file in os.listdir(path): hidden_file = FileSystem(file).is_hidden() if (hidden_file and include_hidden) or (not hidden_file): lst.append(os.path.join(path, file)) return list(set(lst))
[ "def", "ls_dir", "(", "path", ",", "include_hidden", "=", "False", ")", ":", "lst", "=", "[", "]", "for", "file", "in", "os", ".", "listdir", "(", "path", ")", ":", "hidden_file", "=", "FileSystem", "(", "file", ")", ".", "is_hidden", "(", ")", "if...
Finds content of folder :param path: directory to get list of files and folders :param include_hidden: True iff include hidden files in list :return: List of paths in given directory
[ "Finds", "content", "of", "folder" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/files/models/system.py#L201-L213
train
54,330
sirfoga/pyhal
hal/files/models/system.py
ls_recurse
def ls_recurse(path, include_hidden=False): """Finds content of folder recursively :param path: directory to get list of files and folders :param include_hidden: True iff include hidden files in list :return: List of paths in given directory recursively """ lst = [] for file in os.listdir(path): hidden_file = FileSystem(file).is_hidden() if (hidden_file and include_hidden) or (not hidden_file): lst.append(os.path.join(path, file)) if is_folder(os.path.join(path, file)): lst += ls_recurse( os.path.join(path, file), include_hidden=include_hidden ) # get list of files in directory return list(set(lst))
python
def ls_recurse(path, include_hidden=False): """Finds content of folder recursively :param path: directory to get list of files and folders :param include_hidden: True iff include hidden files in list :return: List of paths in given directory recursively """ lst = [] for file in os.listdir(path): hidden_file = FileSystem(file).is_hidden() if (hidden_file and include_hidden) or (not hidden_file): lst.append(os.path.join(path, file)) if is_folder(os.path.join(path, file)): lst += ls_recurse( os.path.join(path, file), include_hidden=include_hidden ) # get list of files in directory return list(set(lst))
[ "def", "ls_recurse", "(", "path", ",", "include_hidden", "=", "False", ")", ":", "lst", "=", "[", "]", "for", "file", "in", "os", ".", "listdir", "(", "path", ")", ":", "hidden_file", "=", "FileSystem", "(", "file", ")", ".", "is_hidden", "(", ")", ...
Finds content of folder recursively :param path: directory to get list of files and folders :param include_hidden: True iff include hidden files in list :return: List of paths in given directory recursively
[ "Finds", "content", "of", "folder", "recursively" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/files/models/system.py#L216-L233
train
54,331
sirfoga/pyhal
hal/files/models/system.py
FileSystem.is_russian
def is_russian(self): """Checks if file path is russian :return: True iff document has a russian name """ russian_chars = 0 for char in RUSSIAN_CHARS: if char in self.name: russian_chars += 1 # found a russian char return russian_chars > len(RUSSIAN_CHARS) / 2.0
python
def is_russian(self): """Checks if file path is russian :return: True iff document has a russian name """ russian_chars = 0 for char in RUSSIAN_CHARS: if char in self.name: russian_chars += 1 # found a russian char return russian_chars > len(RUSSIAN_CHARS) / 2.0
[ "def", "is_russian", "(", "self", ")", ":", "russian_chars", "=", "0", "for", "char", "in", "RUSSIAN_CHARS", ":", "if", "char", "in", "self", ".", "name", ":", "russian_chars", "+=", "1", "# found a russian char", "return", "russian_chars", ">", "len", "(", ...
Checks if file path is russian :return: True iff document has a russian name
[ "Checks", "if", "file", "path", "is", "russian" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/files/models/system.py#L275-L285
train
54,332
sirfoga/pyhal
hal/files/models/system.py
FileSystem.rename
def rename(self, new_path): """Renames to new path :param new_path: new path to use """ rename_path = fix_raw_path(new_path) if is_folder(self.path): os.rename(self.path, rename_path) else: os.renames(self.path, rename_path)
python
def rename(self, new_path): """Renames to new path :param new_path: new path to use """ rename_path = fix_raw_path(new_path) if is_folder(self.path): os.rename(self.path, rename_path) else: os.renames(self.path, rename_path)
[ "def", "rename", "(", "self", ",", "new_path", ")", ":", "rename_path", "=", "fix_raw_path", "(", "new_path", ")", "if", "is_folder", "(", "self", ".", "path", ")", ":", "os", ".", "rename", "(", "self", ".", "path", ",", "rename_path", ")", "else", ...
Renames to new path :param new_path: new path to use
[ "Renames", "to", "new", "path" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/files/models/system.py#L291-L300
train
54,333
portfors-lab/sparkle
sparkle/gui/drag_label.py
DragLabel.setClass
def setClass(self, factoryclass): """Sets the constructor for the component type this label is to represent :param factoryclass: a class that, when called, results in an instance of the desired class :type factoryclass: callable """ self.factoryclass = factoryclass self.setText(str(factoryclass.name))
python
def setClass(self, factoryclass): """Sets the constructor for the component type this label is to represent :param factoryclass: a class that, when called, results in an instance of the desired class :type factoryclass: callable """ self.factoryclass = factoryclass self.setText(str(factoryclass.name))
[ "def", "setClass", "(", "self", ",", "factoryclass", ")", ":", "self", ".", "factoryclass", "=", "factoryclass", "self", ".", "setText", "(", "str", "(", "factoryclass", ".", "name", ")", ")" ]
Sets the constructor for the component type this label is to represent :param factoryclass: a class that, when called, results in an instance of the desired class :type factoryclass: callable
[ "Sets", "the", "constructor", "for", "the", "component", "type", "this", "label", "is", "to", "represent" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/drag_label.py#L19-L27
train
54,334
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
BasePlot.getLabel
def getLabel(self, key): """Gets the label assigned to an axes :param key:??? :type key: str """ axisItem = self.getPlotItem().axes[key]['item'] return axisItem.label.toPlainText()
python
def getLabel(self, key): """Gets the label assigned to an axes :param key:??? :type key: str """ axisItem = self.getPlotItem().axes[key]['item'] return axisItem.label.toPlainText()
[ "def", "getLabel", "(", "self", ",", "key", ")", ":", "axisItem", "=", "self", ".", "getPlotItem", "(", ")", ".", "axes", "[", "key", "]", "[", "'item'", "]", "return", "axisItem", ".", "label", ".", "toPlainText", "(", ")" ]
Gets the label assigned to an axes :param key:??? :type key: str
[ "Gets", "the", "label", "assigned", "to", "an", "axes" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L78-L85
train
54,335
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
TraceWidget.updateData
def updateData(self, axeskey, x, y): """Replaces the currently displayed data :param axeskey: name of data plot to update. Valid options are 'stim' or 'response' :type axeskey: str :param x: index values associated with y to plot :type x: numpy.ndarray :param y: values to plot at x :type y: numpy.ndarray """ if axeskey == 'stim': self.stimPlot.setData(x,y) # call manually to ajust placement of signal ranges = self.viewRange() self.rangeChange(self, ranges) if axeskey == 'response': self.clearTraces() if self._traceUnit == 'A': y = y * self._ampScalar if self.zeroAction.isChecked(): start_avg = np.mean(y[5:25]) y = y - start_avg self.tracePlot.setData(x,y*self._polarity)
python
def updateData(self, axeskey, x, y): """Replaces the currently displayed data :param axeskey: name of data plot to update. Valid options are 'stim' or 'response' :type axeskey: str :param x: index values associated with y to plot :type x: numpy.ndarray :param y: values to plot at x :type y: numpy.ndarray """ if axeskey == 'stim': self.stimPlot.setData(x,y) # call manually to ajust placement of signal ranges = self.viewRange() self.rangeChange(self, ranges) if axeskey == 'response': self.clearTraces() if self._traceUnit == 'A': y = y * self._ampScalar if self.zeroAction.isChecked(): start_avg = np.mean(y[5:25]) y = y - start_avg self.tracePlot.setData(x,y*self._polarity)
[ "def", "updateData", "(", "self", ",", "axeskey", ",", "x", ",", "y", ")", ":", "if", "axeskey", "==", "'stim'", ":", "self", ".", "stimPlot", ".", "setData", "(", "x", ",", "y", ")", "# call manually to ajust placement of signal", "ranges", "=", "self", ...
Replaces the currently displayed data :param axeskey: name of data plot to update. Valid options are 'stim' or 'response' :type axeskey: str :param x: index values associated with y to plot :type x: numpy.ndarray :param y: values to plot at x :type y: numpy.ndarray
[ "Replaces", "the", "currently", "displayed", "data" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L177-L199
train
54,336
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
TraceWidget.appendData
def appendData(self, axeskey, bins, ypoints): """Appends data to existing plotted data :param axeskey: name of data plot to update. Valid options are 'stim' or 'response' :type axeskey: str :param bins: bins to plot a point for :type bin: numpy.ndarray :param ypoints: iteration number of raster, *should* match bins dimension, but really takes the first value in array for iteration number and plot row at proper place for included bins :type ypoints: numpy.ndarray """ if axeskey == 'raster' and len(bins) > 0: x, y = self.rasterPlot.getData() # don't plot overlapping points bins = np.unique(bins) # adjust repetition number to response scale ypoints = np.ones_like(bins)*self.rasterYslots[ypoints[0]] x = np.append(x, bins) y = np.append(y, ypoints) self.rasterPlot.setData(x, y)
python
def appendData(self, axeskey, bins, ypoints): """Appends data to existing plotted data :param axeskey: name of data plot to update. Valid options are 'stim' or 'response' :type axeskey: str :param bins: bins to plot a point for :type bin: numpy.ndarray :param ypoints: iteration number of raster, *should* match bins dimension, but really takes the first value in array for iteration number and plot row at proper place for included bins :type ypoints: numpy.ndarray """ if axeskey == 'raster' and len(bins) > 0: x, y = self.rasterPlot.getData() # don't plot overlapping points bins = np.unique(bins) # adjust repetition number to response scale ypoints = np.ones_like(bins)*self.rasterYslots[ypoints[0]] x = np.append(x, bins) y = np.append(y, ypoints) self.rasterPlot.setData(x, y)
[ "def", "appendData", "(", "self", ",", "axeskey", ",", "bins", ",", "ypoints", ")", ":", "if", "axeskey", "==", "'raster'", "and", "len", "(", "bins", ")", ">", "0", ":", "x", ",", "y", "=", "self", ".", "rasterPlot", ".", "getData", "(", ")", "#...
Appends data to existing plotted data :param axeskey: name of data plot to update. Valid options are 'stim' or 'response' :type axeskey: str :param bins: bins to plot a point for :type bin: numpy.ndarray :param ypoints: iteration number of raster, *should* match bins dimension, but really takes the first value in array for iteration number and plot row at proper place for included bins :type ypoints: numpy.ndarray
[ "Appends", "data", "to", "existing", "plotted", "data" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L211-L229
train
54,337
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
TraceWidget.setThreshold
def setThreshold(self, threshold): """Sets the current threshold :param threshold: the y value to set the threshold line at :type threshold: float """ self.threshLine.setValue(threshold) self.threshold_field.setValue(threshold)
python
def setThreshold(self, threshold): """Sets the current threshold :param threshold: the y value to set the threshold line at :type threshold: float """ self.threshLine.setValue(threshold) self.threshold_field.setValue(threshold)
[ "def", "setThreshold", "(", "self", ",", "threshold", ")", ":", "self", ".", "threshLine", ".", "setValue", "(", "threshold", ")", "self", ".", "threshold_field", ".", "setValue", "(", "threshold", ")" ]
Sets the current threshold :param threshold: the y value to set the threshold line at :type threshold: float
[ "Sets", "the", "current", "threshold" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L243-L250
train
54,338
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
TraceWidget.setRasterBounds
def setRasterBounds(self, lims): """Sets the raster plot y-axis bounds, where in the plot the raster will appear between :param lims: the (min, max) y-values for the raster plot to be placed between :type lims: (float, float) """ self.rasterBottom = lims[0] self.rasterTop = lims[1] self.updateRasterBounds()
python
def setRasterBounds(self, lims): """Sets the raster plot y-axis bounds, where in the plot the raster will appear between :param lims: the (min, max) y-values for the raster plot to be placed between :type lims: (float, float) """ self.rasterBottom = lims[0] self.rasterTop = lims[1] self.updateRasterBounds()
[ "def", "setRasterBounds", "(", "self", ",", "lims", ")", ":", "self", ".", "rasterBottom", "=", "lims", "[", "0", "]", "self", ".", "rasterTop", "=", "lims", "[", "1", "]", "self", ".", "updateRasterBounds", "(", ")" ]
Sets the raster plot y-axis bounds, where in the plot the raster will appear between :param lims: the (min, max) y-values for the raster plot to be placed between :type lims: (float, float)
[ "Sets", "the", "raster", "plot", "y", "-", "axis", "bounds", "where", "in", "the", "plot", "the", "raster", "will", "appear", "between" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L262-L270
train
54,339
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
TraceWidget.updateRasterBounds
def updateRasterBounds(self): """Updates the y-coordinate slots where the raster points are plotted, according to the current limits of the y-axis""" yrange = self.viewRange()[1] yrange_size = yrange[1] - yrange[0] rmax = self.rasterTop*yrange_size + yrange[0] rmin = self.rasterBottom*yrange_size + yrange[0] self.rasterYslots = np.linspace(rmin, rmax, self.nreps) self.rasterBoundsUpdated.emit((self.rasterBottom, self.rasterTop), self.getTitle())
python
def updateRasterBounds(self): """Updates the y-coordinate slots where the raster points are plotted, according to the current limits of the y-axis""" yrange = self.viewRange()[1] yrange_size = yrange[1] - yrange[0] rmax = self.rasterTop*yrange_size + yrange[0] rmin = self.rasterBottom*yrange_size + yrange[0] self.rasterYslots = np.linspace(rmin, rmax, self.nreps) self.rasterBoundsUpdated.emit((self.rasterBottom, self.rasterTop), self.getTitle())
[ "def", "updateRasterBounds", "(", "self", ")", ":", "yrange", "=", "self", ".", "viewRange", "(", ")", "[", "1", "]", "yrange_size", "=", "yrange", "[", "1", "]", "-", "yrange", "[", "0", "]", "rmax", "=", "self", ".", "rasterTop", "*", "yrange_size"...
Updates the y-coordinate slots where the raster points are plotted, according to the current limits of the y-axis
[ "Updates", "the", "y", "-", "coordinate", "slots", "where", "the", "raster", "points", "are", "plotted", "according", "to", "the", "current", "limits", "of", "the", "y", "-", "axis" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L272-L280
train
54,340
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
TraceWidget.askRasterBounds
def askRasterBounds(self): """Prompts the user to provide the raster bounds with a dialog. Saves the bounds to be applied to the plot""" dlg = RasterBoundsDialog(bounds= (self.rasterBottom, self.rasterTop)) if dlg.exec_(): bounds = dlg.values() self.setRasterBounds(bounds)
python
def askRasterBounds(self): """Prompts the user to provide the raster bounds with a dialog. Saves the bounds to be applied to the plot""" dlg = RasterBoundsDialog(bounds= (self.rasterBottom, self.rasterTop)) if dlg.exec_(): bounds = dlg.values() self.setRasterBounds(bounds)
[ "def", "askRasterBounds", "(", "self", ")", ":", "dlg", "=", "RasterBoundsDialog", "(", "bounds", "=", "(", "self", ".", "rasterBottom", ",", "self", ".", "rasterTop", ")", ")", "if", "dlg", ".", "exec_", "(", ")", ":", "bounds", "=", "dlg", ".", "va...
Prompts the user to provide the raster bounds with a dialog. Saves the bounds to be applied to the plot
[ "Prompts", "the", "user", "to", "provide", "the", "raster", "bounds", "with", "a", "dialog", ".", "Saves", "the", "bounds", "to", "be", "applied", "to", "the", "plot" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L282-L288
train
54,341
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
TraceWidget.rangeChange
def rangeChange(self, pw, ranges): """Adjusts the stimulus signal to keep it at the top of a plot, after any ajustment to the axes ranges takes place. This is a slot for the undocumented pyqtgraph signal sigRangeChanged. From what I can tell the arguments are: :param pw: reference to the emitting object (plot widget in my case) :type pw: object :param ranges: I am only interested when this turns out to be a nested list of axis bounds :type ranges: object """ if hasattr(ranges, '__iter__'): # adjust the stim signal so that it falls in the correct range yrange_size = ranges[1][1] - ranges[1][0] stim_x, stim_y = self.stimPlot.getData() if stim_y is not None: stim_height = yrange_size*STIM_HEIGHT # take it to 0 stim_y = stim_y - np.amin(stim_y) # normalize if np.amax(stim_y) != 0: stim_y = stim_y/np.amax(stim_y) # scale for new size stim_y = stim_y*stim_height # raise to right place in plot stim_y = stim_y + (ranges[1][1] - (stim_height*1.1 + (stim_height*0.2))) self.stimPlot.setData(stim_x, stim_y) # rmax = self.rasterTop*yrange_size + ranges[1][0] # rmin = self.rasterBottom*yrange_size + ranges[1][0] self.updateRasterBounds()
python
def rangeChange(self, pw, ranges): """Adjusts the stimulus signal to keep it at the top of a plot, after any ajustment to the axes ranges takes place. This is a slot for the undocumented pyqtgraph signal sigRangeChanged. From what I can tell the arguments are: :param pw: reference to the emitting object (plot widget in my case) :type pw: object :param ranges: I am only interested when this turns out to be a nested list of axis bounds :type ranges: object """ if hasattr(ranges, '__iter__'): # adjust the stim signal so that it falls in the correct range yrange_size = ranges[1][1] - ranges[1][0] stim_x, stim_y = self.stimPlot.getData() if stim_y is not None: stim_height = yrange_size*STIM_HEIGHT # take it to 0 stim_y = stim_y - np.amin(stim_y) # normalize if np.amax(stim_y) != 0: stim_y = stim_y/np.amax(stim_y) # scale for new size stim_y = stim_y*stim_height # raise to right place in plot stim_y = stim_y + (ranges[1][1] - (stim_height*1.1 + (stim_height*0.2))) self.stimPlot.setData(stim_x, stim_y) # rmax = self.rasterTop*yrange_size + ranges[1][0] # rmin = self.rasterBottom*yrange_size + ranges[1][0] self.updateRasterBounds()
[ "def", "rangeChange", "(", "self", ",", "pw", ",", "ranges", ")", ":", "if", "hasattr", "(", "ranges", ",", "'__iter__'", ")", ":", "# adjust the stim signal so that it falls in the correct range", "yrange_size", "=", "ranges", "[", "1", "]", "[", "1", "]", "-...
Adjusts the stimulus signal to keep it at the top of a plot, after any ajustment to the axes ranges takes place. This is a slot for the undocumented pyqtgraph signal sigRangeChanged. From what I can tell the arguments are: :param pw: reference to the emitting object (plot widget in my case) :type pw: object :param ranges: I am only interested when this turns out to be a nested list of axis bounds :type ranges: object
[ "Adjusts", "the", "stimulus", "signal", "to", "keep", "it", "at", "the", "top", "of", "a", "plot", "after", "any", "ajustment", "to", "the", "axes", "ranges", "takes", "place", "." ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L307-L337
train
54,342
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
TraceWidget.update_thresh
def update_thresh(self): """Emits a Qt signal thresholdUpdated with the current threshold value""" thresh_val = self.threshLine.value() self.threshold_field.setValue(thresh_val) self.thresholdUpdated.emit(thresh_val, self.getTitle())
python
def update_thresh(self): """Emits a Qt signal thresholdUpdated with the current threshold value""" thresh_val = self.threshLine.value() self.threshold_field.setValue(thresh_val) self.thresholdUpdated.emit(thresh_val, self.getTitle())
[ "def", "update_thresh", "(", "self", ")", ":", "thresh_val", "=", "self", ".", "threshLine", ".", "value", "(", ")", "self", ".", "threshold_field", ".", "setValue", "(", "thresh_val", ")", "self", ".", "thresholdUpdated", ".", "emit", "(", "thresh_val", "...
Emits a Qt signal thresholdUpdated with the current threshold value
[ "Emits", "a", "Qt", "signal", "thresholdUpdated", "with", "the", "current", "threshold", "value" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L339-L343
train
54,343
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
SpecWidget.updateImage
def updateImage(self, imgdata, xaxis=None, yaxis=None): """Updates the Widget image directly. :type imgdata: numpy.ndarray, see :meth:`pyqtgraph:pyqtgraph.ImageItem.setImage` :param xaxis: x-axis values, length should match dimension 1 of imgdata :param yaxis: y-axis values, length should match dimension 0 of imgdata """ imgdata = imgdata.T self.img.setImage(imgdata) if xaxis is not None and yaxis is not None: xscale = 1.0/(imgdata.shape[0]/xaxis[-1]) yscale = 1.0/(imgdata.shape[1]/yaxis[-1]) self.resetScale() self.img.scale(xscale, yscale) self.imgScale = (xscale, yscale) self.imageArray = np.fliplr(imgdata) self.updateColormap()
python
def updateImage(self, imgdata, xaxis=None, yaxis=None): """Updates the Widget image directly. :type imgdata: numpy.ndarray, see :meth:`pyqtgraph:pyqtgraph.ImageItem.setImage` :param xaxis: x-axis values, length should match dimension 1 of imgdata :param yaxis: y-axis values, length should match dimension 0 of imgdata """ imgdata = imgdata.T self.img.setImage(imgdata) if xaxis is not None and yaxis is not None: xscale = 1.0/(imgdata.shape[0]/xaxis[-1]) yscale = 1.0/(imgdata.shape[1]/yaxis[-1]) self.resetScale() self.img.scale(xscale, yscale) self.imgScale = (xscale, yscale) self.imageArray = np.fliplr(imgdata) self.updateColormap()
[ "def", "updateImage", "(", "self", ",", "imgdata", ",", "xaxis", "=", "None", ",", "yaxis", "=", "None", ")", ":", "imgdata", "=", "imgdata", ".", "T", "self", ".", "img", ".", "setImage", "(", "imgdata", ")", "if", "xaxis", "is", "not", "None", "a...
Updates the Widget image directly. :type imgdata: numpy.ndarray, see :meth:`pyqtgraph:pyqtgraph.ImageItem.setImage` :param xaxis: x-axis values, length should match dimension 1 of imgdata :param yaxis: y-axis values, length should match dimension 0 of imgdata
[ "Updates", "the", "Widget", "image", "directly", "." ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L414-L430
train
54,344
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
SpecWidget.resetScale
def resetScale(self): """Resets the scale on this image. Correctly aligns time scale, undoes manual scaling""" self.img.scale(1./self.imgScale[0], 1./self.imgScale[1]) self.imgScale = (1.,1.)
python
def resetScale(self): """Resets the scale on this image. Correctly aligns time scale, undoes manual scaling""" self.img.scale(1./self.imgScale[0], 1./self.imgScale[1]) self.imgScale = (1.,1.)
[ "def", "resetScale", "(", "self", ")", ":", "self", ".", "img", ".", "scale", "(", "1.", "/", "self", ".", "imgScale", "[", "0", "]", ",", "1.", "/", "self", ".", "imgScale", "[", "1", "]", ")", "self", ".", "imgScale", "=", "(", "1.", ",", "...
Resets the scale on this image. Correctly aligns time scale, undoes manual scaling
[ "Resets", "the", "scale", "on", "this", "image", ".", "Correctly", "aligns", "time", "scale", "undoes", "manual", "scaling" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L432-L435
train
54,345
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
SpecWidget.updateData
def updateData(self, signal, fs): """Displays a spectrogram of the provided signal :param signal: 1-D signal of audio :type signal: numpy.ndarray :param fs: samplerate of signal :type fs: int """ # use a separate thread to calculate spectrogram so UI doesn't lag t = threading.Thread(target=_doSpectrogram, args=(self.spec_done, (fs, signal),), kwargs=self.specgramArgs) t.start()
python
def updateData(self, signal, fs): """Displays a spectrogram of the provided signal :param signal: 1-D signal of audio :type signal: numpy.ndarray :param fs: samplerate of signal :type fs: int """ # use a separate thread to calculate spectrogram so UI doesn't lag t = threading.Thread(target=_doSpectrogram, args=(self.spec_done, (fs, signal),), kwargs=self.specgramArgs) t.start()
[ "def", "updateData", "(", "self", ",", "signal", ",", "fs", ")", ":", "# use a separate thread to calculate spectrogram so UI doesn't lag", "t", "=", "threading", ".", "Thread", "(", "target", "=", "_doSpectrogram", ",", "args", "=", "(", "self", ".", "spec_done",...
Displays a spectrogram of the provided signal :param signal: 1-D signal of audio :type signal: numpy.ndarray :param fs: samplerate of signal :type fs: int
[ "Displays", "a", "spectrogram", "of", "the", "provided", "signal" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L437-L447
train
54,346
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
SpecWidget.setSpecArgs
def setSpecArgs(**kwargs): """Sets optional arguments for the spectrogram appearance. Available options: :param nfft: size of FFT window to use :type nfft: int :param overlap: percent overlap of window :type overlap: number :param window: Type of window to use, choices are hanning, hamming, blackman, bartlett or none (rectangular) :type window: string :param colormap: Gets set by colormap editor. Holds the information to generate the colormap. Items: :meth:`lut<pyqtgraph:pyqtgraph.ImageItem.setLookupTable>`, :meth:`levels<pyqtgraph:pyqtgraph.ImageItem.setLevels>`, state (info for editor) :type colormap: dict """ for key, value in kwargs.items(): if key == 'colormap': SpecWidget.imgArgs['lut'] = value['lut'] SpecWidget.imgArgs['levels'] = value['levels'] SpecWidget.imgArgs['state'] = value['state'] for w in SpecWidget.instances: w.updateColormap() else: SpecWidget.specgramArgs[key] = value
python
def setSpecArgs(**kwargs): """Sets optional arguments for the spectrogram appearance. Available options: :param nfft: size of FFT window to use :type nfft: int :param overlap: percent overlap of window :type overlap: number :param window: Type of window to use, choices are hanning, hamming, blackman, bartlett or none (rectangular) :type window: string :param colormap: Gets set by colormap editor. Holds the information to generate the colormap. Items: :meth:`lut<pyqtgraph:pyqtgraph.ImageItem.setLookupTable>`, :meth:`levels<pyqtgraph:pyqtgraph.ImageItem.setLevels>`, state (info for editor) :type colormap: dict """ for key, value in kwargs.items(): if key == 'colormap': SpecWidget.imgArgs['lut'] = value['lut'] SpecWidget.imgArgs['levels'] = value['levels'] SpecWidget.imgArgs['state'] = value['state'] for w in SpecWidget.instances: w.updateColormap() else: SpecWidget.specgramArgs[key] = value
[ "def", "setSpecArgs", "(", "*", "*", "kwargs", ")", ":", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "key", "==", "'colormap'", ":", "SpecWidget", ".", "imgArgs", "[", "'lut'", "]", "=", "value", "[", "'lut'", "]"...
Sets optional arguments for the spectrogram appearance. Available options: :param nfft: size of FFT window to use :type nfft: int :param overlap: percent overlap of window :type overlap: number :param window: Type of window to use, choices are hanning, hamming, blackman, bartlett or none (rectangular) :type window: string :param colormap: Gets set by colormap editor. Holds the information to generate the colormap. Items: :meth:`lut<pyqtgraph:pyqtgraph.ImageItem.setLookupTable>`, :meth:`levels<pyqtgraph:pyqtgraph.ImageItem.setLevels>`, state (info for editor) :type colormap: dict
[ "Sets", "optional", "arguments", "for", "the", "spectrogram", "appearance", "." ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L450-L472
train
54,347
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
SpecWidget.clearImg
def clearImg(self): """Clears the current image""" self.img.setImage(np.array([[0]])) self.img.image = None
python
def clearImg(self): """Clears the current image""" self.img.setImage(np.array([[0]])) self.img.image = None
[ "def", "clearImg", "(", "self", ")", ":", "self", ".", "img", ".", "setImage", "(", "np", ".", "array", "(", "[", "[", "0", "]", "]", ")", ")", "self", ".", "img", ".", "image", "=", "None" ]
Clears the current image
[ "Clears", "the", "current", "image" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L474-L477
train
54,348
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
SpecWidget.editColormap
def editColormap(self): """Prompts the user with a dialog to change colormap""" self.editor = pg.ImageView() # remove the ROI and Norm buttons self.editor.ui.roiBtn.setVisible(False) self.editor.ui.menuBtn.setVisible(False) self.editor.setImage(self.imageArray) if self.imgArgs['state'] is not None: self.editor.getHistogramWidget().item.gradient.restoreState(self.imgArgs['state']) self.editor.getHistogramWidget().item.setLevels(*self.imgArgs['levels']) self.editor.closeEvent = self._editor_close self.editor.setWindowModality(QtCore.Qt.ApplicationModal) self.editor.show()
python
def editColormap(self): """Prompts the user with a dialog to change colormap""" self.editor = pg.ImageView() # remove the ROI and Norm buttons self.editor.ui.roiBtn.setVisible(False) self.editor.ui.menuBtn.setVisible(False) self.editor.setImage(self.imageArray) if self.imgArgs['state'] is not None: self.editor.getHistogramWidget().item.gradient.restoreState(self.imgArgs['state']) self.editor.getHistogramWidget().item.setLevels(*self.imgArgs['levels']) self.editor.closeEvent = self._editor_close self.editor.setWindowModality(QtCore.Qt.ApplicationModal) self.editor.show()
[ "def", "editColormap", "(", "self", ")", ":", "self", ".", "editor", "=", "pg", ".", "ImageView", "(", ")", "# remove the ROI and Norm buttons", "self", ".", "editor", ".", "ui", ".", "roiBtn", ".", "setVisible", "(", "False", ")", "self", ".", "editor", ...
Prompts the user with a dialog to change colormap
[ "Prompts", "the", "user", "with", "a", "dialog", "to", "change", "colormap" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L483-L496
train
54,349
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
SpecWidget.updateColormap
def updateColormap(self): """Updates the currently colormap accoring to stored settings""" if self.imgArgs['lut'] is not None: self.img.setLookupTable(self.imgArgs['lut']) self.img.setLevels(self.imgArgs['levels'])
python
def updateColormap(self): """Updates the currently colormap accoring to stored settings""" if self.imgArgs['lut'] is not None: self.img.setLookupTable(self.imgArgs['lut']) self.img.setLevels(self.imgArgs['levels'])
[ "def", "updateColormap", "(", "self", ")", ":", "if", "self", ".", "imgArgs", "[", "'lut'", "]", "is", "not", "None", ":", "self", ".", "img", ".", "setLookupTable", "(", "self", ".", "imgArgs", "[", "'lut'", "]", ")", "self", ".", "img", ".", "set...
Updates the currently colormap accoring to stored settings
[ "Updates", "the", "currently", "colormap", "accoring", "to", "stored", "settings" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L510-L514
train
54,350
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
SimplePlotWidget.appendData
def appendData(self, xdata, ydata, color='b', legendstr=None): """Adds the data to the plot :param xdata: index values for data, plotted on x-axis :type xdata: numpy.ndarray :param ydata: value data to plot, dimension must match xdata :type ydata: numpy.ndarray """ item = self.plot(xdata, ydata, pen=color) if legendstr is not None: self.legend.addItem(item, legendstr) return item
python
def appendData(self, xdata, ydata, color='b', legendstr=None): """Adds the data to the plot :param xdata: index values for data, plotted on x-axis :type xdata: numpy.ndarray :param ydata: value data to plot, dimension must match xdata :type ydata: numpy.ndarray """ item = self.plot(xdata, ydata, pen=color) if legendstr is not None: self.legend.addItem(item, legendstr) return item
[ "def", "appendData", "(", "self", ",", "xdata", ",", "ydata", ",", "color", "=", "'b'", ",", "legendstr", "=", "None", ")", ":", "item", "=", "self", ".", "plot", "(", "xdata", ",", "ydata", ",", "pen", "=", "color", ")", "if", "legendstr", "is", ...
Adds the data to the plot :param xdata: index values for data, plotted on x-axis :type xdata: numpy.ndarray :param ydata: value data to plot, dimension must match xdata :type ydata: numpy.ndarray
[ "Adds", "the", "data", "to", "the", "plot" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L568-L579
train
54,351
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
SimplePlotWidget.setLabels
def setLabels(self, xlabel=None, ylabel=None, title=None, xunits=None, yunits=None): """Sets the plot labels :param xlabel: X-axis label (do not include units) :type xlabel: str :param ylabel: Y-axis label (do not include units) :type ylabel: str :param title: Plot title :type title: str :param xunit: SI units for the x-axis. An appropriate label will be appended according to scale :type xunit: str :param yunit: SI units for the y-axis. An appropriate label will be appended according to scale :type yunit: str """ if xlabel is not None: self.setLabel('bottom', xlabel, units=xunits) if ylabel is not None: self.setLabel('left', ylabel, units=yunits) if title is not None: self.setTitle(title)
python
def setLabels(self, xlabel=None, ylabel=None, title=None, xunits=None, yunits=None): """Sets the plot labels :param xlabel: X-axis label (do not include units) :type xlabel: str :param ylabel: Y-axis label (do not include units) :type ylabel: str :param title: Plot title :type title: str :param xunit: SI units for the x-axis. An appropriate label will be appended according to scale :type xunit: str :param yunit: SI units for the y-axis. An appropriate label will be appended according to scale :type yunit: str """ if xlabel is not None: self.setLabel('bottom', xlabel, units=xunits) if ylabel is not None: self.setLabel('left', ylabel, units=yunits) if title is not None: self.setTitle(title)
[ "def", "setLabels", "(", "self", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ",", "title", "=", "None", ",", "xunits", "=", "None", ",", "yunits", "=", "None", ")", ":", "if", "xlabel", "is", "not", "None", ":", "self", ".", "setLabel",...
Sets the plot labels :param xlabel: X-axis label (do not include units) :type xlabel: str :param ylabel: Y-axis label (do not include units) :type ylabel: str :param title: Plot title :type title: str :param xunit: SI units for the x-axis. An appropriate label will be appended according to scale :type xunit: str :param yunit: SI units for the y-axis. An appropriate label will be appended according to scale :type yunit: str
[ "Sets", "the", "plot", "labels" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L581-L600
train
54,352
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
ProgressWidget.setPoint
def setPoint(self, x, group, y): """Sets the given point, connects line to previous point in group :param x: x value of point :type x: float :param group: group which plot point for :type group: float :param y: y value of point :type y: float """ if x == -1: # silence window self.plot([0],[y], symbol='o') else: yindex = self.groups.index(group) xdata, ydata = self.lines[yindex].getData() if ydata is None: xdata = [x] ydata = [y] else: xdata = np.append(xdata, x) ydata = np.append(ydata, y) self.lines[yindex].setData(xdata, ydata)
python
def setPoint(self, x, group, y): """Sets the given point, connects line to previous point in group :param x: x value of point :type x: float :param group: group which plot point for :type group: float :param y: y value of point :type y: float """ if x == -1: # silence window self.plot([0],[y], symbol='o') else: yindex = self.groups.index(group) xdata, ydata = self.lines[yindex].getData() if ydata is None: xdata = [x] ydata = [y] else: xdata = np.append(xdata, x) ydata = np.append(ydata, y) self.lines[yindex].setData(xdata, ydata)
[ "def", "setPoint", "(", "self", ",", "x", ",", "group", ",", "y", ")", ":", "if", "x", "==", "-", "1", ":", "# silence window", "self", ".", "plot", "(", "[", "0", "]", ",", "[", "y", "]", ",", "symbol", "=", "'o'", ")", "else", ":", "yindex"...
Sets the given point, connects line to previous point in group :param x: x value of point :type x: float :param group: group which plot point for :type group: float :param y: y value of point :type y: float
[ "Sets", "the", "given", "point", "connects", "line", "to", "previous", "point", "in", "group" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L626-L648
train
54,353
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
ProgressWidget.setLabels
def setLabels(self, name): """Sets plot labels, according to predefined options :param name: The type of plot to create labels for. Options: calibration, tuning, anything else labels for spike counts :type name: str """ if name == "calibration": self.setWindowTitle("Calibration Curve") self.setTitle("Calibration Curve") self.setLabel('bottom', "Frequency", units='Hz') self.setLabel('left', 'Recorded Intensity (dB SPL)') elif name == "tuning": self.setWindowTitle("Tuning Curve") self.setTitle("Tuning Curve") self.setLabel('bottom', "Frequency", units="Hz") self.setLabel('left', "Spike Count (mean)") else: self.setWindowTitle("Spike Counts") self.setTitle("Spike Counts") self.setLabel('bottom', "Test Number", units='') self.setLabel('left', "Spike Count (mean)", units='')
python
def setLabels(self, name): """Sets plot labels, according to predefined options :param name: The type of plot to create labels for. Options: calibration, tuning, anything else labels for spike counts :type name: str """ if name == "calibration": self.setWindowTitle("Calibration Curve") self.setTitle("Calibration Curve") self.setLabel('bottom', "Frequency", units='Hz') self.setLabel('left', 'Recorded Intensity (dB SPL)') elif name == "tuning": self.setWindowTitle("Tuning Curve") self.setTitle("Tuning Curve") self.setLabel('bottom', "Frequency", units="Hz") self.setLabel('left', "Spike Count (mean)") else: self.setWindowTitle("Spike Counts") self.setTitle("Spike Counts") self.setLabel('bottom', "Test Number", units='') self.setLabel('left', "Spike Count (mean)", units='')
[ "def", "setLabels", "(", "self", ",", "name", ")", ":", "if", "name", "==", "\"calibration\"", ":", "self", ".", "setWindowTitle", "(", "\"Calibration Curve\"", ")", "self", ".", "setTitle", "(", "\"Calibration Curve\"", ")", "self", ".", "setLabel", "(", "'...
Sets plot labels, according to predefined options :param name: The type of plot to create labels for. Options: calibration, tuning, anything else labels for spike counts :type name: str
[ "Sets", "plot", "labels", "according", "to", "predefined", "options" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L650-L670
train
54,354
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
ProgressWidget.loadCurve
def loadCurve(data, groups, thresholds, absvals, fs, xlabels): """Accepts a data set from a whole test, averages reps and re-creates the progress plot as the same as it was during live plotting. Number of thresholds must match the size of the channel dimension""" xlims = (xlabels[0], xlabels[-1]) pw = ProgressWidget(groups, xlims) spike_counts = [] # skip control for itrace in range(data.shape[0]): count = 0 for ichan in range(data.shape[2]): flat_reps = data[itrace,:,ichan,:].flatten() count += len(spikestats.spike_times(flat_reps, thresholds[ichan], fs, absvals[ichan])) spike_counts.append(count/(data.shape[1]*data.shape[2])) #mean spikes per rep i = 0 for g in groups: for x in xlabels: pw.setPoint(x, g, spike_counts[i]) i +=1 return pw
python
def loadCurve(data, groups, thresholds, absvals, fs, xlabels): """Accepts a data set from a whole test, averages reps and re-creates the progress plot as the same as it was during live plotting. Number of thresholds must match the size of the channel dimension""" xlims = (xlabels[0], xlabels[-1]) pw = ProgressWidget(groups, xlims) spike_counts = [] # skip control for itrace in range(data.shape[0]): count = 0 for ichan in range(data.shape[2]): flat_reps = data[itrace,:,ichan,:].flatten() count += len(spikestats.spike_times(flat_reps, thresholds[ichan], fs, absvals[ichan])) spike_counts.append(count/(data.shape[1]*data.shape[2])) #mean spikes per rep i = 0 for g in groups: for x in xlabels: pw.setPoint(x, g, spike_counts[i]) i +=1 return pw
[ "def", "loadCurve", "(", "data", ",", "groups", ",", "thresholds", ",", "absvals", ",", "fs", ",", "xlabels", ")", ":", "xlims", "=", "(", "xlabels", "[", "0", "]", ",", "xlabels", "[", "-", "1", "]", ")", "pw", "=", "ProgressWidget", "(", "groups"...
Accepts a data set from a whole test, averages reps and re-creates the progress plot as the same as it was during live plotting. Number of thresholds must match the size of the channel dimension
[ "Accepts", "a", "data", "set", "from", "a", "whole", "test", "averages", "reps", "and", "re", "-", "creates", "the", "progress", "plot", "as", "the", "same", "as", "it", "was", "during", "live", "plotting", ".", "Number", "of", "thresholds", "must", "mat...
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L673-L694
train
54,355
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
PSTHWidget.processData
def processData(self, times, response, test_num, trace_num, rep_num): """Calulate spike times from raw response data""" # invert polarity affects spike counting response = response * self._polarity if rep_num == 0: # reset self.spike_counts = [] self.spike_latencies = [] self.spike_rates = [] fs = 1./(times[1] - times[0]) # process response; calculate spike times spike_times = spikestats.spike_times(response, self._threshold, fs) self.spike_counts.append(len(spike_times)) if len(spike_times) > 0: self.spike_latencies.append(spike_times[0]) else: self.spike_latencies.append(np.nan) self.spike_rates.append(spikestats.firing_rate(spike_times, times)) binsz = self._bins[1] - self._bins[0] response_bins = spikestats.bin_spikes(spike_times, binsz) # self.putnotify('spikes_found', (response_bins, rep_num)) self.appendData(response_bins, rep_num)
python
def processData(self, times, response, test_num, trace_num, rep_num): """Calulate spike times from raw response data""" # invert polarity affects spike counting response = response * self._polarity if rep_num == 0: # reset self.spike_counts = [] self.spike_latencies = [] self.spike_rates = [] fs = 1./(times[1] - times[0]) # process response; calculate spike times spike_times = spikestats.spike_times(response, self._threshold, fs) self.spike_counts.append(len(spike_times)) if len(spike_times) > 0: self.spike_latencies.append(spike_times[0]) else: self.spike_latencies.append(np.nan) self.spike_rates.append(spikestats.firing_rate(spike_times, times)) binsz = self._bins[1] - self._bins[0] response_bins = spikestats.bin_spikes(spike_times, binsz) # self.putnotify('spikes_found', (response_bins, rep_num)) self.appendData(response_bins, rep_num)
[ "def", "processData", "(", "self", ",", "times", ",", "response", ",", "test_num", ",", "trace_num", ",", "rep_num", ")", ":", "# invert polarity affects spike counting", "response", "=", "response", "*", "self", ".", "_polarity", "if", "rep_num", "==", "0", "...
Calulate spike times from raw response data
[ "Calulate", "spike", "times", "from", "raw", "response", "data" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L749-L774
train
54,356
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
ChartWidget.setSr
def setSr(self, fs): """Sets the samplerate of the input operation being plotted""" self.tracePlot.setSr(fs) self.stimPlot.setSr(fs)
python
def setSr(self, fs): """Sets the samplerate of the input operation being plotted""" self.tracePlot.setSr(fs) self.stimPlot.setSr(fs)
[ "def", "setSr", "(", "self", ",", "fs", ")", ":", "self", ".", "tracePlot", ".", "setSr", "(", "fs", ")", "self", ".", "stimPlot", ".", "setSr", "(", "fs", ")" ]
Sets the samplerate of the input operation being plotted
[ "Sets", "the", "samplerate", "of", "the", "input", "operation", "being", "plotted" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L806-L809
train
54,357
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
ChartWidget.setWindowSize
def setWindowSize(self, winsz): """Sets the size of scroll window""" self.tracePlot.setWindowSize(winsz) self.stimPlot.setWindowSize(winsz)
python
def setWindowSize(self, winsz): """Sets the size of scroll window""" self.tracePlot.setWindowSize(winsz) self.stimPlot.setWindowSize(winsz)
[ "def", "setWindowSize", "(", "self", ",", "winsz", ")", ":", "self", ".", "tracePlot", ".", "setWindowSize", "(", "winsz", ")", "self", ".", "stimPlot", ".", "setWindowSize", "(", "winsz", ")" ]
Sets the size of scroll window
[ "Sets", "the", "size", "of", "scroll", "window" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L811-L814
train
54,358
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
StackedPlot.addSpectrogram
def addSpectrogram(self, ydata, fs, title=None): """Adds a new spectorgram plot for the given image. Generates a SpecWidget :param ydata: 2-D array of the image to display :type ydata: numpy.ndarray :param fs: the samplerate of the signal in the image, used to set time/ frequency scale :type fs: int :param title: Plot title :type title: str """ p = SpecWidget() p.updateData(ydata, fs) if title is not None: p.setTitle(title) self.stacker.addWidget(p)
python
def addSpectrogram(self, ydata, fs, title=None): """Adds a new spectorgram plot for the given image. Generates a SpecWidget :param ydata: 2-D array of the image to display :type ydata: numpy.ndarray :param fs: the samplerate of the signal in the image, used to set time/ frequency scale :type fs: int :param title: Plot title :type title: str """ p = SpecWidget() p.updateData(ydata, fs) if title is not None: p.setTitle(title) self.stacker.addWidget(p)
[ "def", "addSpectrogram", "(", "self", ",", "ydata", ",", "fs", ",", "title", "=", "None", ")", ":", "p", "=", "SpecWidget", "(", ")", "p", ".", "updateData", "(", "ydata", ",", "fs", ")", "if", "title", "is", "not", "None", ":", "p", ".", "setTit...
Adds a new spectorgram plot for the given image. Generates a SpecWidget :param ydata: 2-D array of the image to display :type ydata: numpy.ndarray :param fs: the samplerate of the signal in the image, used to set time/ frequency scale :type fs: int :param title: Plot title :type title: str
[ "Adds", "a", "new", "spectorgram", "plot", "for", "the", "given", "image", ".", "Generates", "a", "SpecWidget" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L927-L941
train
54,359
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
StackedPlot.nextPlot
def nextPlot(self): """Moves the displayed plot to the next one""" if self.stacker.currentIndex() < self.stacker.count(): self.stacker.setCurrentIndex(self.stacker.currentIndex()+1)
python
def nextPlot(self): """Moves the displayed plot to the next one""" if self.stacker.currentIndex() < self.stacker.count(): self.stacker.setCurrentIndex(self.stacker.currentIndex()+1)
[ "def", "nextPlot", "(", "self", ")", ":", "if", "self", ".", "stacker", ".", "currentIndex", "(", ")", "<", "self", ".", "stacker", ".", "count", "(", ")", ":", "self", ".", "stacker", ".", "setCurrentIndex", "(", "self", ".", "stacker", ".", "curren...
Moves the displayed plot to the next one
[ "Moves", "the", "displayed", "plot", "to", "the", "next", "one" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L943-L946
train
54,360
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
StackedPlot.prevPlot
def prevPlot(self): """Moves the displayed plot to the previous one""" if self.stacker.currentIndex() > 0: self.stacker.setCurrentIndex(self.stacker.currentIndex()-1)
python
def prevPlot(self): """Moves the displayed plot to the previous one""" if self.stacker.currentIndex() > 0: self.stacker.setCurrentIndex(self.stacker.currentIndex()-1)
[ "def", "prevPlot", "(", "self", ")", ":", "if", "self", ".", "stacker", ".", "currentIndex", "(", ")", ">", "0", ":", "self", ".", "stacker", ".", "setCurrentIndex", "(", "self", ".", "stacker", ".", "currentIndex", "(", ")", "-", "1", ")" ]
Moves the displayed plot to the previous one
[ "Moves", "the", "displayed", "plot", "to", "the", "previous", "one" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L948-L951
train
54,361
NoviceLive/pat
pat/utils.py
most_even_chunk
def most_even_chunk(string, group): """Divide a string into a list of strings as even as possible.""" counts = [0] + most_even(len(string), group) indices = accumulate(counts) slices = window(indices, 2) return [string[slice(*one)] for one in slices]
python
def most_even_chunk(string, group): """Divide a string into a list of strings as even as possible.""" counts = [0] + most_even(len(string), group) indices = accumulate(counts) slices = window(indices, 2) return [string[slice(*one)] for one in slices]
[ "def", "most_even_chunk", "(", "string", ",", "group", ")", ":", "counts", "=", "[", "0", "]", "+", "most_even", "(", "len", "(", "string", ")", ",", "group", ")", "indices", "=", "accumulate", "(", "counts", ")", "slices", "=", "window", "(", "indic...
Divide a string into a list of strings as even as possible.
[ "Divide", "a", "string", "into", "a", "list", "of", "strings", "as", "even", "as", "possible", "." ]
bd223fc5e758213662befbebdf9538f3fbf58ad6
https://github.com/NoviceLive/pat/blob/bd223fc5e758213662befbebdf9538f3fbf58ad6/pat/utils.py#L32-L37
train
54,362
NoviceLive/pat
pat/utils.py
most_even
def most_even(number, group): """Divide a number into a list of numbers as even as possible.""" count, rest = divmod(number, group) counts = zip_longest([count] * group, [1] * rest, fillvalue=0) chunks = [sum(one) for one in counts] logging.debug('chunks: %s', chunks) return chunks
python
def most_even(number, group): """Divide a number into a list of numbers as even as possible.""" count, rest = divmod(number, group) counts = zip_longest([count] * group, [1] * rest, fillvalue=0) chunks = [sum(one) for one in counts] logging.debug('chunks: %s', chunks) return chunks
[ "def", "most_even", "(", "number", ",", "group", ")", ":", "count", ",", "rest", "=", "divmod", "(", "number", ",", "group", ")", "counts", "=", "zip_longest", "(", "[", "count", "]", "*", "group", ",", "[", "1", "]", "*", "rest", ",", "fillvalue",...
Divide a number into a list of numbers as even as possible.
[ "Divide", "a", "number", "into", "a", "list", "of", "numbers", "as", "even", "as", "possible", "." ]
bd223fc5e758213662befbebdf9538f3fbf58ad6
https://github.com/NoviceLive/pat/blob/bd223fc5e758213662befbebdf9538f3fbf58ad6/pat/utils.py#L40-L46
train
54,363
NoviceLive/pat
pat/utils.py
window
def window(seq, count=2): """Slide window.""" iseq = iter(seq) result = tuple(islice(iseq, count)) if len(result) == count: yield result for elem in iseq: result = result[1:] + (elem,) yield result
python
def window(seq, count=2): """Slide window.""" iseq = iter(seq) result = tuple(islice(iseq, count)) if len(result) == count: yield result for elem in iseq: result = result[1:] + (elem,) yield result
[ "def", "window", "(", "seq", ",", "count", "=", "2", ")", ":", "iseq", "=", "iter", "(", "seq", ")", "result", "=", "tuple", "(", "islice", "(", "iseq", ",", "count", ")", ")", "if", "len", "(", "result", ")", "==", "count", ":", "yield", "resu...
Slide window.
[ "Slide", "window", "." ]
bd223fc5e758213662befbebdf9538f3fbf58ad6
https://github.com/NoviceLive/pat/blob/bd223fc5e758213662befbebdf9538f3fbf58ad6/pat/utils.py#L49-L57
train
54,364
sirfoga/pyhal
hal/meta/attributes.py
_get_modules
def _get_modules(path): """Finds modules in folder recursively :param path: directory :return: list of modules """ lst = [] folder_contents = os.listdir(path) is_python_module = "__init__.py" in folder_contents if is_python_module: for file in folder_contents: full_path = os.path.join(path, file) if is_file(full_path): lst.append(full_path) if is_folder(full_path): lst += _get_modules(full_path) # recurse in folder return list(set(lst))
python
def _get_modules(path): """Finds modules in folder recursively :param path: directory :return: list of modules """ lst = [] folder_contents = os.listdir(path) is_python_module = "__init__.py" in folder_contents if is_python_module: for file in folder_contents: full_path = os.path.join(path, file) if is_file(full_path): lst.append(full_path) if is_folder(full_path): lst += _get_modules(full_path) # recurse in folder return list(set(lst))
[ "def", "_get_modules", "(", "path", ")", ":", "lst", "=", "[", "]", "folder_contents", "=", "os", ".", "listdir", "(", "path", ")", "is_python_module", "=", "\"__init__.py\"", "in", "folder_contents", "if", "is_python_module", ":", "for", "file", "in", "fold...
Finds modules in folder recursively :param path: directory :return: list of modules
[ "Finds", "modules", "in", "folder", "recursively" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/meta/attributes.py#L152-L172
train
54,365
sirfoga/pyhal
hal/meta/attributes.py
ModuleFile._parse
def _parse(self): """Parses file contents :return: Tree hierarchy of file """ with open(self.path, "rt") as reader: return ast.parse(reader.read(), filename=self.path)
python
def _parse(self): """Parses file contents :return: Tree hierarchy of file """ with open(self.path, "rt") as reader: return ast.parse(reader.read(), filename=self.path)
[ "def", "_parse", "(", "self", ")", ":", "with", "open", "(", "self", ".", "path", ",", "\"rt\"", ")", "as", "reader", ":", "return", "ast", ".", "parse", "(", "reader", ".", "read", "(", ")", ",", "filename", "=", "self", ".", "path", ")" ]
Parses file contents :return: Tree hierarchy of file
[ "Parses", "file", "contents" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/meta/attributes.py#L26-L32
train
54,366
sirfoga/pyhal
hal/meta/attributes.py
ModuleFile._find_package
def _find_package(self, root_package): """Finds package name of file :param root_package: root package :return: package name """ package = self.path.replace(root_package, "") if package.endswith(".py"): package = package[:-3] package = package.replace(os.path.sep, MODULE_SEP) root_package = get_folder_name(root_package) package = root_package + package # add root return package
python
def _find_package(self, root_package): """Finds package name of file :param root_package: root package :return: package name """ package = self.path.replace(root_package, "") if package.endswith(".py"): package = package[:-3] package = package.replace(os.path.sep, MODULE_SEP) root_package = get_folder_name(root_package) package = root_package + package # add root return package
[ "def", "_find_package", "(", "self", ",", "root_package", ")", ":", "package", "=", "self", ".", "path", ".", "replace", "(", "root_package", ",", "\"\"", ")", "if", "package", ".", "endswith", "(", "\".py\"", ")", ":", "package", "=", "package", "[", ...
Finds package name of file :param root_package: root package :return: package name
[ "Finds", "package", "name", "of", "file" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/meta/attributes.py#L34-L49
train
54,367
sirfoga/pyhal
hal/meta/attributes.py
ModuleTree._get_instances
def _get_instances(self, instance): """Finds all instances of instance in tree :param instance: type of object :return: list of objects in tree of same instance """ return [ x for x in self.tree.body if isinstance(x, instance) ]
python
def _get_instances(self, instance): """Finds all instances of instance in tree :param instance: type of object :return: list of objects in tree of same instance """ return [ x for x in self.tree.body if isinstance(x, instance) ]
[ "def", "_get_instances", "(", "self", ",", "instance", ")", ":", "return", "[", "x", "for", "x", "in", "self", ".", "tree", ".", "body", "if", "isinstance", "(", "x", ",", "instance", ")", "]" ]
Finds all instances of instance in tree :param instance: type of object :return: list of objects in tree of same instance
[ "Finds", "all", "instances", "of", "instance", "in", "tree" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/meta/attributes.py#L70-L81
train
54,368
sirfoga/pyhal
hal/meta/attributes.py
ModuleTree.get_classes
def get_classes(self): """Finds classes in file :return: list of top-level classes """ instances = self._get_instances(ast.ClassDef) instances = [ PyClass(instance, self.package) for instance in instances ] return instances
python
def get_classes(self): """Finds classes in file :return: list of top-level classes """ instances = self._get_instances(ast.ClassDef) instances = [ PyClass(instance, self.package) for instance in instances ] return instances
[ "def", "get_classes", "(", "self", ")", ":", "instances", "=", "self", ".", "_get_instances", "(", "ast", ".", "ClassDef", ")", "instances", "=", "[", "PyClass", "(", "instance", ",", "self", ".", "package", ")", "for", "instance", "in", "instances", "]"...
Finds classes in file :return: list of top-level classes
[ "Finds", "classes", "in", "file" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/meta/attributes.py#L83-L93
train
54,369
lowandrew/OLCTools
spadespipeline/skesa.py
Skesa.best_assemblyfile
def best_assemblyfile(self): """ Determine whether the contigs.fasta output file from the assembler is present. If not, set the .bestassembly attribute to 'NA' """ for sample in self.metadata: try: # Set the name of the filtered assembly file filtered_outputfile = os.path.join(self.path, 'raw_assemblies', '{}.fasta'.format(sample.name)) # Set the name of the unfiltered spades assembly output file if os.path.isfile(sample.general.assemblyfile): size = os.path.getsize(sample.general.assemblyfile) # Ensure that the assembly isn't just an empty file if size == 0: sample.general.bestassemblyfile = 'NA' else: sample.general.bestassemblyfile = sample.general.assemblyfile shutil.copyfile(sample.general.bestassemblyfile, filtered_outputfile) else: sample.general.bestassemblyfile = 'NA' # Add the name and path of the filtered file to the metadata sample.general.filteredfile = filtered_outputfile except AttributeError: sample.general.assemblyfile = 'NA' sample.general.bestassemblyfile = 'NA'
python
def best_assemblyfile(self): """ Determine whether the contigs.fasta output file from the assembler is present. If not, set the .bestassembly attribute to 'NA' """ for sample in self.metadata: try: # Set the name of the filtered assembly file filtered_outputfile = os.path.join(self.path, 'raw_assemblies', '{}.fasta'.format(sample.name)) # Set the name of the unfiltered spades assembly output file if os.path.isfile(sample.general.assemblyfile): size = os.path.getsize(sample.general.assemblyfile) # Ensure that the assembly isn't just an empty file if size == 0: sample.general.bestassemblyfile = 'NA' else: sample.general.bestassemblyfile = sample.general.assemblyfile shutil.copyfile(sample.general.bestassemblyfile, filtered_outputfile) else: sample.general.bestassemblyfile = 'NA' # Add the name and path of the filtered file to the metadata sample.general.filteredfile = filtered_outputfile except AttributeError: sample.general.assemblyfile = 'NA' sample.general.bestassemblyfile = 'NA'
[ "def", "best_assemblyfile", "(", "self", ")", ":", "for", "sample", "in", "self", ".", "metadata", ":", "try", ":", "# Set the name of the filtered assembly file", "filtered_outputfile", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "'raw...
Determine whether the contigs.fasta output file from the assembler is present. If not, set the .bestassembly attribute to 'NA'
[ "Determine", "whether", "the", "contigs", ".", "fasta", "output", "file", "from", "the", "assembler", "is", "present", ".", "If", "not", "set", "the", ".", "bestassembly", "attribute", "to", "NA" ]
88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/skesa.py#L179-L203
train
54,370
outini/python-pylls
pylls/cachet.py
ComponentGroups.get
def get(self, group_id=None, **kwargs): """Get component groups :param group_id: Component group ID (optional) :return: Component groups data (:class:`dict`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-componentgroups .. seealso:: https://docs.cachethq.io/docs/advanced-api-usage """ path = 'components/groups' if group_id is not None: path += '/%s' % group_id return self.paginate_get(path, data=kwargs)
python
def get(self, group_id=None, **kwargs): """Get component groups :param group_id: Component group ID (optional) :return: Component groups data (:class:`dict`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-componentgroups .. seealso:: https://docs.cachethq.io/docs/advanced-api-usage """ path = 'components/groups' if group_id is not None: path += '/%s' % group_id return self.paginate_get(path, data=kwargs)
[ "def", "get", "(", "self", ",", "group_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "path", "=", "'components/groups'", "if", "group_id", "is", "not", "None", ":", "path", "+=", "'/%s'", "%", "group_id", "return", "self", ".", "paginate_get", "...
Get component groups :param group_id: Component group ID (optional) :return: Component groups data (:class:`dict`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-componentgroups .. seealso:: https://docs.cachethq.io/docs/advanced-api-usage
[ "Get", "component", "groups" ]
f9fa220594bc1974469097d9bad690a42d0d0f0f
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L185-L200
train
54,371
outini/python-pylls
pylls/cachet.py
ComponentGroups.create
def create(self, name, order=None, collapsed=None): """Create a new Component Group :param str name: Name of the component group :param int order: Order of the component group :param int collapsed: Collapse the group? 0-2 :return: Created component group data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#post-componentgroups """ data = ApiParams() data['name'] = name data['order'] = order data['collapsed'] = collapsed return self._post('components/groups', data=data)['data']
python
def create(self, name, order=None, collapsed=None): """Create a new Component Group :param str name: Name of the component group :param int order: Order of the component group :param int collapsed: Collapse the group? 0-2 :return: Created component group data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#post-componentgroups """ data = ApiParams() data['name'] = name data['order'] = order data['collapsed'] = collapsed return self._post('components/groups', data=data)['data']
[ "def", "create", "(", "self", ",", "name", ",", "order", "=", "None", ",", "collapsed", "=", "None", ")", ":", "data", "=", "ApiParams", "(", ")", "data", "[", "'name'", "]", "=", "name", "data", "[", "'order'", "]", "=", "order", "data", "[", "'...
Create a new Component Group :param str name: Name of the component group :param int order: Order of the component group :param int collapsed: Collapse the group? 0-2 :return: Created component group data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#post-componentgroups
[ "Create", "a", "new", "Component", "Group" ]
f9fa220594bc1974469097d9bad690a42d0d0f0f
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L202-L216
train
54,372
outini/python-pylls
pylls/cachet.py
ComponentGroups.update
def update(self, group_id, name=None, order=None, collapsed=None): """Update a Component Group :param int group_id: Component Group ID :param str name: Name of the component group :param int order: Order of the group :param int collapsed: Collapse the group? :return: Updated component group data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#put-component-group """ data = ApiParams() data['group'] = group_id data['name'] = name data['order'] = order data['collapsed'] = collapsed return self._put('components/groups/%s' % group_id, data=data)['data']
python
def update(self, group_id, name=None, order=None, collapsed=None): """Update a Component Group :param int group_id: Component Group ID :param str name: Name of the component group :param int order: Order of the group :param int collapsed: Collapse the group? :return: Updated component group data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#put-component-group """ data = ApiParams() data['group'] = group_id data['name'] = name data['order'] = order data['collapsed'] = collapsed return self._put('components/groups/%s' % group_id, data=data)['data']
[ "def", "update", "(", "self", ",", "group_id", ",", "name", "=", "None", ",", "order", "=", "None", ",", "collapsed", "=", "None", ")", ":", "data", "=", "ApiParams", "(", ")", "data", "[", "'group'", "]", "=", "group_id", "data", "[", "'name'", "]...
Update a Component Group :param int group_id: Component Group ID :param str name: Name of the component group :param int order: Order of the group :param int collapsed: Collapse the group? :return: Updated component group data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#put-component-group
[ "Update", "a", "Component", "Group" ]
f9fa220594bc1974469097d9bad690a42d0d0f0f
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L218-L234
train
54,373
outini/python-pylls
pylls/cachet.py
Incidents.create
def create(self, name, message, status, visible, component_id=None, component_status=None, notify=None, created_at=None, template=None, tplvars=None): """Create a new Incident :param str name: Name of the incident :param str message: Incident explanation message :param int status: Status of the incident :param int visible: Whether the incident is publicly visible :param int component_id: Component to update :param int component_status: The status to update the given component :param bool notify: Whether to notify subscribers :param str created_at: When the incident was created :param str template: The template slug to use :param list tplvars: The variables to pass to the template :return: Created incident data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#incidents """ data = ApiParams() data['name'] = name data['message'] = message data['status'] = status data['visible'] = visible data['component_id'] = component_id data['component_status'] = component_status data['notify'] = notify data['created_at'] = created_at data['template'] = template data['vars'] = tplvars return self._post('incidents', data=data)['data']
python
def create(self, name, message, status, visible, component_id=None, component_status=None, notify=None, created_at=None, template=None, tplvars=None): """Create a new Incident :param str name: Name of the incident :param str message: Incident explanation message :param int status: Status of the incident :param int visible: Whether the incident is publicly visible :param int component_id: Component to update :param int component_status: The status to update the given component :param bool notify: Whether to notify subscribers :param str created_at: When the incident was created :param str template: The template slug to use :param list tplvars: The variables to pass to the template :return: Created incident data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#incidents """ data = ApiParams() data['name'] = name data['message'] = message data['status'] = status data['visible'] = visible data['component_id'] = component_id data['component_status'] = component_status data['notify'] = notify data['created_at'] = created_at data['template'] = template data['vars'] = tplvars return self._post('incidents', data=data)['data']
[ "def", "create", "(", "self", ",", "name", ",", "message", ",", "status", ",", "visible", ",", "component_id", "=", "None", ",", "component_status", "=", "None", ",", "notify", "=", "None", ",", "created_at", "=", "None", ",", "template", "=", "None", ...
Create a new Incident :param str name: Name of the incident :param str message: Incident explanation message :param int status: Status of the incident :param int visible: Whether the incident is publicly visible :param int component_id: Component to update :param int component_status: The status to update the given component :param bool notify: Whether to notify subscribers :param str created_at: When the incident was created :param str template: The template slug to use :param list tplvars: The variables to pass to the template :return: Created incident data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#incidents
[ "Create", "a", "new", "Incident" ]
f9fa220594bc1974469097d9bad690a42d0d0f0f
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L271-L301
train
54,374
outini/python-pylls
pylls/cachet.py
Incidents.update
def update(self, incident_id, name=None, message=None, status=None, visible=None, component_id=None, component_status=None, notify=None, created_at=None, template=None, tpl_vars=None): """Update an Incident :param int incident_id: Incident ID :param str name: Name of the incident :param str message: Incident explanation message :param int status: Status of the incident :param int visible: Whether the incident is publicly visible :param int component_id: Component to update :param int component_status: The status to update the given component :param bool notify: Whether to notify subscribers :param str created_at: When the incident was created :param str template: The template slug to use :param list tpl_vars: The variables to pass to the template :return: Created incident data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#update-an-incident """ data = ApiParams() data['name'] = name data['message'] = message data['status'] = status data['visible'] = visible data['component_id'] = component_id data['component_status'] = component_status data['notify'] = notify data['created_at'] = created_at data['template'] = template data['vars'] = tpl_vars return self._put('incidents/%s' % incident_id, data=data)['data']
python
def update(self, incident_id, name=None, message=None, status=None, visible=None, component_id=None, component_status=None, notify=None, created_at=None, template=None, tpl_vars=None): """Update an Incident :param int incident_id: Incident ID :param str name: Name of the incident :param str message: Incident explanation message :param int status: Status of the incident :param int visible: Whether the incident is publicly visible :param int component_id: Component to update :param int component_status: The status to update the given component :param bool notify: Whether to notify subscribers :param str created_at: When the incident was created :param str template: The template slug to use :param list tpl_vars: The variables to pass to the template :return: Created incident data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#update-an-incident """ data = ApiParams() data['name'] = name data['message'] = message data['status'] = status data['visible'] = visible data['component_id'] = component_id data['component_status'] = component_status data['notify'] = notify data['created_at'] = created_at data['template'] = template data['vars'] = tpl_vars return self._put('incidents/%s' % incident_id, data=data)['data']
[ "def", "update", "(", "self", ",", "incident_id", ",", "name", "=", "None", ",", "message", "=", "None", ",", "status", "=", "None", ",", "visible", "=", "None", ",", "component_id", "=", "None", ",", "component_status", "=", "None", ",", "notify", "="...
Update an Incident :param int incident_id: Incident ID :param str name: Name of the incident :param str message: Incident explanation message :param int status: Status of the incident :param int visible: Whether the incident is publicly visible :param int component_id: Component to update :param int component_status: The status to update the given component :param bool notify: Whether to notify subscribers :param str created_at: When the incident was created :param str template: The template slug to use :param list tpl_vars: The variables to pass to the template :return: Created incident data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#update-an-incident
[ "Update", "an", "Incident" ]
f9fa220594bc1974469097d9bad690a42d0d0f0f
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L303-L334
train
54,375
outini/python-pylls
pylls/cachet.py
Metrics.create
def create(self, name, suffix, description, default_value, display=None): """Create a new Metric :param str name: Name of metric :param str suffix: Metric unit :param str description: Description of what the metric is measuring :param int default_value: Default value to use when a point is added :param int display: Display the chart on the status page :return: Created metric data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#metrics """ data = ApiParams() data['name'] = name data['suffix'] = suffix data['description'] = description data['default_value'] = default_value data['display'] = display return self._post('metrics', data=data)['data']
python
def create(self, name, suffix, description, default_value, display=None): """Create a new Metric :param str name: Name of metric :param str suffix: Metric unit :param str description: Description of what the metric is measuring :param int default_value: Default value to use when a point is added :param int display: Display the chart on the status page :return: Created metric data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#metrics """ data = ApiParams() data['name'] = name data['suffix'] = suffix data['description'] = description data['default_value'] = default_value data['display'] = display return self._post('metrics', data=data)['data']
[ "def", "create", "(", "self", ",", "name", ",", "suffix", ",", "description", ",", "default_value", ",", "display", "=", "None", ")", ":", "data", "=", "ApiParams", "(", ")", "data", "[", "'name'", "]", "=", "name", "data", "[", "'suffix'", "]", "=",...
Create a new Metric :param str name: Name of metric :param str suffix: Metric unit :param str description: Description of what the metric is measuring :param int default_value: Default value to use when a point is added :param int display: Display the chart on the status page :return: Created metric data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#metrics
[ "Create", "a", "new", "Metric" ]
f9fa220594bc1974469097d9bad690a42d0d0f0f
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L383-L401
train
54,376
outini/python-pylls
pylls/cachet.py
MetricPoints.create
def create(self, metric_id, value, timestamp=None): """Add a Metric Point to a Metric :param int metric_id: Metric ID :param int value: Value to plot on the metric graph :param str timestamp: Unix timestamp of the point was measured :return: Created metric point data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#post-metric-points """ data = ApiParams() data['value'] = value data['timestamp'] = timestamp return self._post('metrics/%s/points' % metric_id, data=data)['data']
python
def create(self, metric_id, value, timestamp=None): """Add a Metric Point to a Metric :param int metric_id: Metric ID :param int value: Value to plot on the metric graph :param str timestamp: Unix timestamp of the point was measured :return: Created metric point data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#post-metric-points """ data = ApiParams() data['value'] = value data['timestamp'] = timestamp return self._post('metrics/%s/points' % metric_id, data=data)['data']
[ "def", "create", "(", "self", ",", "metric_id", ",", "value", ",", "timestamp", "=", "None", ")", ":", "data", "=", "ApiParams", "(", ")", "data", "[", "'value'", "]", "=", "value", "data", "[", "'timestamp'", "]", "=", "timestamp", "return", "self", ...
Add a Metric Point to a Metric :param int metric_id: Metric ID :param int value: Value to plot on the metric graph :param str timestamp: Unix timestamp of the point was measured :return: Created metric point data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#post-metric-points
[ "Add", "a", "Metric", "Point", "to", "a", "Metric" ]
f9fa220594bc1974469097d9bad690a42d0d0f0f
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L431-L444
train
54,377
outini/python-pylls
pylls/cachet.py
Subscribers.create
def create(self, email, verify=None, components=None): """Create a new subscriber :param str email: Email address to subscribe :param bool verify: Whether to send verification email :param list components: Components ID list, defaults to all :return: Created subscriber data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#subscribers """ data = ApiParams() data['email'] = email data['verify'] = verify data['components'] = components return self._post('subscribers', data=data)['data']
python
def create(self, email, verify=None, components=None): """Create a new subscriber :param str email: Email address to subscribe :param bool verify: Whether to send verification email :param list components: Components ID list, defaults to all :return: Created subscriber data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#subscribers """ data = ApiParams() data['email'] = email data['verify'] = verify data['components'] = components return self._post('subscribers', data=data)['data']
[ "def", "create", "(", "self", ",", "email", ",", "verify", "=", "None", ",", "components", "=", "None", ")", ":", "data", "=", "ApiParams", "(", ")", "data", "[", "'email'", "]", "=", "email", "data", "[", "'verify'", "]", "=", "verify", "data", "[...
Create a new subscriber :param str email: Email address to subscribe :param bool verify: Whether to send verification email :param list components: Components ID list, defaults to all :return: Created subscriber data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#subscribers
[ "Create", "a", "new", "subscriber" ]
f9fa220594bc1974469097d9bad690a42d0d0f0f
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L479-L493
train
54,378
lowandrew/OLCTools
coreGenome/core.py
AnnotatedCore.annotatedcore
def annotatedcore(self): """ Calculates the core genome of organisms using custom databases """ logging.info('Calculating annotated core') # Determine the total number of core genes self.total_core() # Iterate through all the samples, and process all Escherichia for sample in self.metadata: if sample.general.bestassemblyfile != 'NA': # Create a set to store the names of all the core genes in this strain sample[self.analysistype].coreset = set() if sample.general.referencegenus == 'Escherichia': # Add the Escherichia sample to the runmetadata self.runmetadata.samples.append(sample) # Parse the BLAST report try: report = sample[self.analysistype].report self.blastparser(report=report, sample=sample, fieldnames=self.fieldnames) except KeyError: sample[self.analysistype].coreset = list() # Create the report self.reporter()
python
def annotatedcore(self): """ Calculates the core genome of organisms using custom databases """ logging.info('Calculating annotated core') # Determine the total number of core genes self.total_core() # Iterate through all the samples, and process all Escherichia for sample in self.metadata: if sample.general.bestassemblyfile != 'NA': # Create a set to store the names of all the core genes in this strain sample[self.analysistype].coreset = set() if sample.general.referencegenus == 'Escherichia': # Add the Escherichia sample to the runmetadata self.runmetadata.samples.append(sample) # Parse the BLAST report try: report = sample[self.analysistype].report self.blastparser(report=report, sample=sample, fieldnames=self.fieldnames) except KeyError: sample[self.analysistype].coreset = list() # Create the report self.reporter()
[ "def", "annotatedcore", "(", "self", ")", ":", "logging", ".", "info", "(", "'Calculating annotated core'", ")", "# Determine the total number of core genes", "self", ".", "total_core", "(", ")", "# Iterate through all the samples, and process all Escherichia", "for", "sample...
Calculates the core genome of organisms using custom databases
[ "Calculates", "the", "core", "genome", "of", "organisms", "using", "custom", "databases" ]
88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/coreGenome/core.py#L169-L193
train
54,379
lowandrew/OLCTools
coreGenome/core.py
AnnotatedCore.total_core
def total_core(self): """ Determine the total number of core genes present """ corefile = os.path.join(self.reffilepath, self.analysistype, 'Escherichia', 'core_combined.fasta') for record in SeqIO.parse(corefile, 'fasta'): gene_name = record.id.split('-')[0] if gene_name not in self.coregenomes: self.coregenomes.append(gene_name)
python
def total_core(self): """ Determine the total number of core genes present """ corefile = os.path.join(self.reffilepath, self.analysistype, 'Escherichia', 'core_combined.fasta') for record in SeqIO.parse(corefile, 'fasta'): gene_name = record.id.split('-')[0] if gene_name not in self.coregenomes: self.coregenomes.append(gene_name)
[ "def", "total_core", "(", "self", ")", ":", "corefile", "=", "os", ".", "path", ".", "join", "(", "self", ".", "reffilepath", ",", "self", ".", "analysistype", ",", "'Escherichia'", ",", "'core_combined.fasta'", ")", "for", "record", "in", "SeqIO", ".", ...
Determine the total number of core genes present
[ "Determine", "the", "total", "number", "of", "core", "genes", "present" ]
88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/coreGenome/core.py#L195-L203
train
54,380
sirfoga/pyhal
hal/system/process.py
Process.get_simple_output
def get_simple_output(self, stderr=STDOUT): """Executes a simple external command and get its output The command contains no pipes. Error messages are redirected to the standard output by default :param stderr: where to put stderr :return: output of command """ args = shlex.split(self.cmd) proc = Popen(args, stdout=PIPE, stderr=stderr) return proc.communicate()[0].decode("utf8")
python
def get_simple_output(self, stderr=STDOUT): """Executes a simple external command and get its output The command contains no pipes. Error messages are redirected to the standard output by default :param stderr: where to put stderr :return: output of command """ args = shlex.split(self.cmd) proc = Popen(args, stdout=PIPE, stderr=stderr) return proc.communicate()[0].decode("utf8")
[ "def", "get_simple_output", "(", "self", ",", "stderr", "=", "STDOUT", ")", ":", "args", "=", "shlex", ".", "split", "(", "self", ".", "cmd", ")", "proc", "=", "Popen", "(", "args", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "stderr", ")", "re...
Executes a simple external command and get its output The command contains no pipes. Error messages are redirected to the standard output by default :param stderr: where to put stderr :return: output of command
[ "Executes", "a", "simple", "external", "command", "and", "get", "its", "output", "The", "command", "contains", "no", "pipes", ".", "Error", "messages", "are", "redirected", "to", "the", "standard", "output", "by", "default" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/system/process.py#L21-L31
train
54,381
sirfoga/pyhal
hal/system/process.py
Process.get_complex_output
def get_complex_output(self, stderr=STDOUT): """Executes a piped command and get the lines of the output in a list :param stderr: where to put stderr :return: output of command """ proc = Popen(self.cmd, shell=True, stdout=PIPE, stderr=stderr) return proc.stdout.readlines()
python
def get_complex_output(self, stderr=STDOUT): """Executes a piped command and get the lines of the output in a list :param stderr: where to put stderr :return: output of command """ proc = Popen(self.cmd, shell=True, stdout=PIPE, stderr=stderr) return proc.stdout.readlines()
[ "def", "get_complex_output", "(", "self", ",", "stderr", "=", "STDOUT", ")", ":", "proc", "=", "Popen", "(", "self", ".", "cmd", ",", "shell", "=", "True", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "stderr", ")", "return", "proc", ".", "stdout"...
Executes a piped command and get the lines of the output in a list :param stderr: where to put stderr :return: output of command
[ "Executes", "a", "piped", "command", "and", "get", "the", "lines", "of", "the", "output", "in", "a", "list" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/system/process.py#L33-L40
train
54,382
sirfoga/pyhal
hal/system/process.py
Process.keep_alive
def keep_alive(self): """Keeps a process alive. If the process terminates, it will restart it The terminated processes become zombies. They die when their parent terminates """ while True: pid = self.execute_in_background() p = psutil.Process(pid) while p.is_running() and str(p.status) != 'zombie': os.system('sleep 5')
python
def keep_alive(self): """Keeps a process alive. If the process terminates, it will restart it The terminated processes become zombies. They die when their parent terminates """ while True: pid = self.execute_in_background() p = psutil.Process(pid) while p.is_running() and str(p.status) != 'zombie': os.system('sleep 5')
[ "def", "keep_alive", "(", "self", ")", ":", "while", "True", ":", "pid", "=", "self", ".", "execute_in_background", "(", ")", "p", "=", "psutil", ".", "Process", "(", "pid", ")", "while", "p", ".", "is_running", "(", ")", "and", "str", "(", "p", "....
Keeps a process alive. If the process terminates, it will restart it The terminated processes become zombies. They die when their parent terminates
[ "Keeps", "a", "process", "alive", ".", "If", "the", "process", "terminates", "it", "will", "restart", "it", "The", "terminated", "processes", "become", "zombies", ".", "They", "die", "when", "their", "parent", "terminates" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/system/process.py#L92-L101
train
54,383
portfors-lab/sparkle
sparkle/tools/util.py
increment_title
def increment_title(title): """ Increments a string that ends in a number """ count = re.search('\d+$', title).group(0) new_title = title[:-(len(count))] + str(int(count)+1) return new_title
python
def increment_title(title): """ Increments a string that ends in a number """ count = re.search('\d+$', title).group(0) new_title = title[:-(len(count))] + str(int(count)+1) return new_title
[ "def", "increment_title", "(", "title", ")", ":", "count", "=", "re", ".", "search", "(", "'\\d+$'", ",", "title", ")", ".", "group", "(", "0", ")", "new_title", "=", "title", "[", ":", "-", "(", "len", "(", "count", ")", ")", "]", "+", "str", ...
Increments a string that ends in a number
[ "Increments", "a", "string", "that", "ends", "in", "a", "number" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/tools/util.py#L9-L15
train
54,384
Frzk/Ellis
ellis/rule.py
Rule.check_limit
def check_limit(self, limit): """ Checks if the given limit is valid. A limit must be > 0 to be considered valid. Raises ValueError when the *limit* is not > 0. """ if limit > 0: self.limit = limit else: raise ValueError("Rule limit must be strictly > 0 ({0} given)" .format(limit)) return self
python
def check_limit(self, limit): """ Checks if the given limit is valid. A limit must be > 0 to be considered valid. Raises ValueError when the *limit* is not > 0. """ if limit > 0: self.limit = limit else: raise ValueError("Rule limit must be strictly > 0 ({0} given)" .format(limit)) return self
[ "def", "check_limit", "(", "self", ",", "limit", ")", ":", "if", "limit", ">", "0", ":", "self", ".", "limit", "=", "limit", "else", ":", "raise", "ValueError", "(", "\"Rule limit must be strictly > 0 ({0} given)\"", ".", "format", "(", "limit", ")", ")", ...
Checks if the given limit is valid. A limit must be > 0 to be considered valid. Raises ValueError when the *limit* is not > 0.
[ "Checks", "if", "the", "given", "limit", "is", "valid", "." ]
39ce8987cbc503354cf1f45927344186a8b18363
https://github.com/Frzk/Ellis/blob/39ce8987cbc503354cf1f45927344186a8b18363/ellis/rule.py#L59-L73
train
54,385
jmbhughes/suvi-trainer
scripts/make_movie_frames.py
get_args
def get_args(): """ request the arguments for running """ ap = argparse.ArgumentParser(description="Create frames for a movie that can be compiled using ffmpeg") ap.add_argument("start", help="date string as start time") ap.add_argument("end", help="date string as end time") ap.add_argument("step", type=float, help="fraction of a day to step by") ap.add_argument("--config", help="path to a config file", default="config.json") return ap.parse_args()
python
def get_args(): """ request the arguments for running """ ap = argparse.ArgumentParser(description="Create frames for a movie that can be compiled using ffmpeg") ap.add_argument("start", help="date string as start time") ap.add_argument("end", help="date string as end time") ap.add_argument("step", type=float, help="fraction of a day to step by") ap.add_argument("--config", help="path to a config file", default="config.json") return ap.parse_args()
[ "def", "get_args", "(", ")", ":", "ap", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Create frames for a movie that can be compiled using ffmpeg\"", ")", "ap", ".", "add_argument", "(", "\"start\"", ",", "help", "=", "\"date string as start time\"...
request the arguments for running
[ "request", "the", "arguments", "for", "running" ]
3d89894a4a037286221974c7eb5634d229b4f5d4
https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/scripts/make_movie_frames.py#L11-L20
train
54,386
jmbhughes/suvi-trainer
scripts/make_movie_frames.py
main
def main(): """ process the main task """ args = get_args() args.start = date_parser.parse(args.start) args.end = date_parser.parse(args.end) args.step = timedelta(args.step) config = Config(args.config) times = [args.start + i * args.step for i in range(int((args.end - args.start) / args.step))] for i, time in enumerate(times): make_plot(time, config, args.step)
python
def main(): """ process the main task """ args = get_args() args.start = date_parser.parse(args.start) args.end = date_parser.parse(args.end) args.step = timedelta(args.step) config = Config(args.config) times = [args.start + i * args.step for i in range(int((args.end - args.start) / args.step))] for i, time in enumerate(times): make_plot(time, config, args.step)
[ "def", "main", "(", ")", ":", "args", "=", "get_args", "(", ")", "args", ".", "start", "=", "date_parser", ".", "parse", "(", "args", ".", "start", ")", "args", ".", "end", "=", "date_parser", ".", "parse", "(", "args", ".", "end", ")", "args", "...
process the main task
[ "process", "the", "main", "task" ]
3d89894a4a037286221974c7eb5634d229b4f5d4
https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/scripts/make_movie_frames.py#L61-L74
train
54,387
TorkamaniLab/metapipe
metapipe/models/grammar.py
Grammar.overall
def overall(): """ The overall grammer for pulling apart the main input files. """ return ZeroOrMore(Grammar.comment) + Dict(ZeroOrMore(Group( Grammar._section + ZeroOrMore(Group(Grammar.line))) ))
python
def overall(): """ The overall grammer for pulling apart the main input files. """ return ZeroOrMore(Grammar.comment) + Dict(ZeroOrMore(Group( Grammar._section + ZeroOrMore(Group(Grammar.line))) ))
[ "def", "overall", "(", ")", ":", "return", "ZeroOrMore", "(", "Grammar", ".", "comment", ")", "+", "Dict", "(", "ZeroOrMore", "(", "Group", "(", "Grammar", ".", "_section", "+", "ZeroOrMore", "(", "Group", "(", "Grammar", ".", "line", ")", ")", ")", ...
The overall grammer for pulling apart the main input files.
[ "The", "overall", "grammer", "for", "pulling", "apart", "the", "main", "input", "files", "." ]
15592e5b0c217afb00ac03503f8d0d7453d4baf4
https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/models/grammar.py#L51-L55
train
54,388
TorkamaniLab/metapipe
metapipe/models/grammar.py
Grammar.file
def file(): """ Grammar for files found in the overall input files. """ return ( Optional(Word(alphanums).setResultsName('alias') + Suppress(Literal('.'))) + Suppress(White()) + Word(approved_printables).setResultsName('filename') )
python
def file(): """ Grammar for files found in the overall input files. """ return ( Optional(Word(alphanums).setResultsName('alias') + Suppress(Literal('.'))) + Suppress(White()) + Word(approved_printables).setResultsName('filename') )
[ "def", "file", "(", ")", ":", "return", "(", "Optional", "(", "Word", "(", "alphanums", ")", ".", "setResultsName", "(", "'alias'", ")", "+", "Suppress", "(", "Literal", "(", "'.'", ")", ")", ")", "+", "Suppress", "(", "White", "(", ")", ")", "+", ...
Grammar for files found in the overall input files.
[ "Grammar", "for", "files", "found", "in", "the", "overall", "input", "files", "." ]
15592e5b0c217afb00ac03503f8d0d7453d4baf4
https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/models/grammar.py#L64-L70
train
54,389
yamcs/yamcs-python
yamcs-client/examples/events.py
listen_to_event_updates
def listen_to_event_updates(): """Subscribe to events.""" def callback(event): print('Event:', event) client.create_event_subscription(instance='simulator', on_data=callback) sleep(5)
python
def listen_to_event_updates(): """Subscribe to events.""" def callback(event): print('Event:', event) client.create_event_subscription(instance='simulator', on_data=callback) sleep(5)
[ "def", "listen_to_event_updates", "(", ")", ":", "def", "callback", "(", "event", ")", ":", "print", "(", "'Event:'", ",", "event", ")", "client", ".", "create_event_subscription", "(", "instance", "=", "'simulator'", ",", "on_data", "=", "callback", ")", "s...
Subscribe to events.
[ "Subscribe", "to", "events", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/examples/events.py#L8-L15
train
54,390
JukeboxPipeline/jukeboxmaya
src/jukeboxmaya/mayaplugins/jbscene.py
get_current_scene_node
def get_current_scene_node(): """Return the name of the jb_sceneNode, that describes the current scene or None if there is no scene node. :returns: the full name of the node or none, if there is no scene node :rtype: str | None :raises: None """ c = cmds.namespaceInfo(':', listOnlyDependencyNodes=True, absoluteName=True, dagPath=True) l = cmds.ls(c, type='jb_sceneNode', absoluteName=True) if not l: return else: for n in sorted(l): if not cmds.listConnections("%s.reftrack" % n, d=False): return n
python
def get_current_scene_node(): """Return the name of the jb_sceneNode, that describes the current scene or None if there is no scene node. :returns: the full name of the node or none, if there is no scene node :rtype: str | None :raises: None """ c = cmds.namespaceInfo(':', listOnlyDependencyNodes=True, absoluteName=True, dagPath=True) l = cmds.ls(c, type='jb_sceneNode', absoluteName=True) if not l: return else: for n in sorted(l): if not cmds.listConnections("%s.reftrack" % n, d=False): return n
[ "def", "get_current_scene_node", "(", ")", ":", "c", "=", "cmds", ".", "namespaceInfo", "(", "':'", ",", "listOnlyDependencyNodes", "=", "True", ",", "absoluteName", "=", "True", ",", "dagPath", "=", "True", ")", "l", "=", "cmds", ".", "ls", "(", "c", ...
Return the name of the jb_sceneNode, that describes the current scene or None if there is no scene node. :returns: the full name of the node or none, if there is no scene node :rtype: str | None :raises: None
[ "Return", "the", "name", "of", "the", "jb_sceneNode", "that", "describes", "the", "current", "scene", "or", "None", "if", "there", "is", "no", "scene", "node", "." ]
c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c
https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/mayaplugins/jbscene.py#L53-L67
train
54,391
portfors-lab/sparkle
sparkle/gui/plotting/protocoldisplay.py
ProtocolDisplay.updateSpec
def updateSpec(self, *args, **kwargs): """Updates the spectrogram. First argument can be a filename, or a data array. If no arguments are given, clears the spectrograms. For other arguments, see: :meth:`SpecWidget.updateData<sparkle.gui.plotting.pyqtgraph_widgets.SpecWidget.updateData>` """ if args[0] is None: self.specPlot.clearImg() elif isinstance(args[0], basestring): self.specPlot.fromFile(*args, **kwargs) else: self.specPlot.updateData(*args,**kwargs)
python
def updateSpec(self, *args, **kwargs): """Updates the spectrogram. First argument can be a filename, or a data array. If no arguments are given, clears the spectrograms. For other arguments, see: :meth:`SpecWidget.updateData<sparkle.gui.plotting.pyqtgraph_widgets.SpecWidget.updateData>` """ if args[0] is None: self.specPlot.clearImg() elif isinstance(args[0], basestring): self.specPlot.fromFile(*args, **kwargs) else: self.specPlot.updateData(*args,**kwargs)
[ "def", "updateSpec", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "[", "0", "]", "is", "None", ":", "self", ".", "specPlot", ".", "clearImg", "(", ")", "elif", "isinstance", "(", "args", "[", "0", "]", ",", "b...
Updates the spectrogram. First argument can be a filename, or a data array. If no arguments are given, clears the spectrograms. For other arguments, see: :meth:`SpecWidget.updateData<sparkle.gui.plotting.pyqtgraph_widgets.SpecWidget.updateData>`
[ "Updates", "the", "spectrogram", ".", "First", "argument", "can", "be", "a", "filename", "or", "a", "data", "array", ".", "If", "no", "arguments", "are", "given", "clears", "the", "spectrograms", "." ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/protocoldisplay.py#L72-L83
train
54,392
portfors-lab/sparkle
sparkle/gui/plotting/protocoldisplay.py
ProtocolDisplay.showSpec
def showSpec(self, fname): """Draws the spectrogram if it is currently None""" if not self.specPlot.hasImg() and fname is not None: self.specPlot.fromFile(fname)
python
def showSpec(self, fname): """Draws the spectrogram if it is currently None""" if not self.specPlot.hasImg() and fname is not None: self.specPlot.fromFile(fname)
[ "def", "showSpec", "(", "self", ",", "fname", ")", ":", "if", "not", "self", ".", "specPlot", ".", "hasImg", "(", ")", "and", "fname", "is", "not", "None", ":", "self", ".", "specPlot", ".", "fromFile", "(", "fname", ")" ]
Draws the spectrogram if it is currently None
[ "Draws", "the", "spectrogram", "if", "it", "is", "currently", "None" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/protocoldisplay.py#L85-L88
train
54,393
portfors-lab/sparkle
sparkle/gui/plotting/protocoldisplay.py
ProtocolDisplay.updateSpiketrace
def updateSpiketrace(self, xdata, ydata, plotname=None): """Updates the spike trace :param xdata: index values :type xdata: numpy.ndarray :param ydata: values to plot :type ydata: numpy.ndarray """ if plotname is None: plotname = self.responsePlots.keys()[0] if len(ydata.shape) == 1: self.responsePlots[plotname].updateData(axeskey='response', x=xdata, y=ydata) else: self.responsePlots[plotname].addTraces(xdata, ydata)
python
def updateSpiketrace(self, xdata, ydata, plotname=None): """Updates the spike trace :param xdata: index values :type xdata: numpy.ndarray :param ydata: values to plot :type ydata: numpy.ndarray """ if plotname is None: plotname = self.responsePlots.keys()[0] if len(ydata.shape) == 1: self.responsePlots[plotname].updateData(axeskey='response', x=xdata, y=ydata) else: self.responsePlots[plotname].addTraces(xdata, ydata)
[ "def", "updateSpiketrace", "(", "self", ",", "xdata", ",", "ydata", ",", "plotname", "=", "None", ")", ":", "if", "plotname", "is", "None", ":", "plotname", "=", "self", ".", "responsePlots", ".", "keys", "(", ")", "[", "0", "]", "if", "len", "(", ...
Updates the spike trace :param xdata: index values :type xdata: numpy.ndarray :param ydata: values to plot :type ydata: numpy.ndarray
[ "Updates", "the", "spike", "trace" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/protocoldisplay.py#L127-L141
train
54,394
portfors-lab/sparkle
sparkle/gui/plotting/protocoldisplay.py
ProtocolDisplay.updateSignal
def updateSignal(self, xdata, ydata, plotname=None): """Updates the trace of the outgoing signal :param xdata: time points of recording :param ydata: brain potential at time points """ if plotname is None: plotname = self.responsePlots.keys()[0] self.responsePlots[plotname].updateData(axeskey='stim', x=xdata, y=ydata)
python
def updateSignal(self, xdata, ydata, plotname=None): """Updates the trace of the outgoing signal :param xdata: time points of recording :param ydata: brain potential at time points """ if plotname is None: plotname = self.responsePlots.keys()[0] self.responsePlots[plotname].updateData(axeskey='stim', x=xdata, y=ydata)
[ "def", "updateSignal", "(", "self", ",", "xdata", ",", "ydata", ",", "plotname", "=", "None", ")", ":", "if", "plotname", "is", "None", ":", "plotname", "=", "self", ".", "responsePlots", ".", "keys", "(", ")", "[", "0", "]", "self", ".", "responsePl...
Updates the trace of the outgoing signal :param xdata: time points of recording :param ydata: brain potential at time points
[ "Updates", "the", "trace", "of", "the", "outgoing", "signal" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/protocoldisplay.py#L160-L168
train
54,395
portfors-lab/sparkle
sparkle/gui/plotting/protocoldisplay.py
ProtocolDisplay.setXlimits
def setXlimits(self, lims): """Sets the X axis limits of the trace plot :param lims: (min, max) of x axis, in same units as data :type lims: (float, float) """ # update all "linked", plots self.specPlot.setXlim(lims) for plot in self.responsePlots.values(): plot.setXlim(lims) # ridiculous... sizes = self.splittersw.sizes() if len(sizes) > 1: if self.badbadbad: sizes[0] +=1 sizes[1] -=1 else: sizes[0] -=1 sizes[1] +=1 self.badbadbad = not self.badbadbad self.splittersw.setSizes(sizes) self._ignore_range_signal = False
python
def setXlimits(self, lims): """Sets the X axis limits of the trace plot :param lims: (min, max) of x axis, in same units as data :type lims: (float, float) """ # update all "linked", plots self.specPlot.setXlim(lims) for plot in self.responsePlots.values(): plot.setXlim(lims) # ridiculous... sizes = self.splittersw.sizes() if len(sizes) > 1: if self.badbadbad: sizes[0] +=1 sizes[1] -=1 else: sizes[0] -=1 sizes[1] +=1 self.badbadbad = not self.badbadbad self.splittersw.setSizes(sizes) self._ignore_range_signal = False
[ "def", "setXlimits", "(", "self", ",", "lims", ")", ":", "# update all \"linked\", plots", "self", ".", "specPlot", ".", "setXlim", "(", "lims", ")", "for", "plot", "in", "self", ".", "responsePlots", ".", "values", "(", ")", ":", "plot", ".", "setXlim", ...
Sets the X axis limits of the trace plot :param lims: (min, max) of x axis, in same units as data :type lims: (float, float)
[ "Sets", "the", "X", "axis", "limits", "of", "the", "trace", "plot" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/protocoldisplay.py#L170-L192
train
54,396
portfors-lab/sparkle
sparkle/gui/plotting/protocoldisplay.py
ProtocolDisplay.setNreps
def setNreps(self, nreps): """Sets the number of reps before the raster plot resets""" for plot in self.responsePlots.values(): plot.setNreps(nreps)
python
def setNreps(self, nreps): """Sets the number of reps before the raster plot resets""" for plot in self.responsePlots.values(): plot.setNreps(nreps)
[ "def", "setNreps", "(", "self", ",", "nreps", ")", ":", "for", "plot", "in", "self", ".", "responsePlots", ".", "values", "(", ")", ":", "plot", ".", "setNreps", "(", "nreps", ")" ]
Sets the number of reps before the raster plot resets
[ "Sets", "the", "number", "of", "reps", "before", "the", "raster", "plot", "resets" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/protocoldisplay.py#L200-L203
train
54,397
portfors-lab/sparkle
sparkle/gui/plotting/protocoldisplay.py
ProtocolDisplay.specAutoRange
def specAutoRange(self): """Auto adjusts the visible range of the spectrogram""" trace_range = self.responsePlots.values()[0].viewRange()[0] vb = self.specPlot.getViewBox() vb.autoRange(padding=0) self.specPlot.setXlim(trace_range)
python
def specAutoRange(self): """Auto adjusts the visible range of the spectrogram""" trace_range = self.responsePlots.values()[0].viewRange()[0] vb = self.specPlot.getViewBox() vb.autoRange(padding=0) self.specPlot.setXlim(trace_range)
[ "def", "specAutoRange", "(", "self", ")", ":", "trace_range", "=", "self", ".", "responsePlots", ".", "values", "(", ")", "[", "0", "]", ".", "viewRange", "(", ")", "[", "0", "]", "vb", "=", "self", ".", "specPlot", ".", "getViewBox", "(", ")", "vb...
Auto adjusts the visible range of the spectrogram
[ "Auto", "adjusts", "the", "visible", "range", "of", "the", "spectrogram" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/protocoldisplay.py#L209-L214
train
54,398
jmbhughes/suvi-trainer
suvitrainer/gui.py
App.save
def save(self): """ Save as a FITS file and attempt an upload if designated in the configuration file """ out = Outgest(self.output, self.selection_array.astype('uint8'), self.headers, self.config_path) out.save() out.upload()
python
def save(self): """ Save as a FITS file and attempt an upload if designated in the configuration file """ out = Outgest(self.output, self.selection_array.astype('uint8'), self.headers, self.config_path) out.save() out.upload()
[ "def", "save", "(", "self", ")", ":", "out", "=", "Outgest", "(", "self", ".", "output", ",", "self", ".", "selection_array", ".", "astype", "(", "'uint8'", ")", ",", "self", ".", "headers", ",", "self", ".", "config_path", ")", "out", ".", "save", ...
Save as a FITS file and attempt an upload if designated in the configuration file
[ "Save", "as", "a", "FITS", "file", "and", "attempt", "an", "upload", "if", "designated", "in", "the", "configuration", "file" ]
3d89894a4a037286221974c7eb5634d229b4f5d4
https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/suvitrainer/gui.py#L198-L202
train
54,399