rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
rv = self.parse_definition(parser) parser.assert_end() | try: rv = self.parse_definition(parser) parser.assert_end() except DefinitionError, e: self.env.warn(self.env.docname, e.description, self.lineno) raise ValueError | def handle_signature(self, sig, signode): parser = DefinitionParser(sig) rv = self.parse_definition(parser) parser.assert_end() self.describe_signature(signode, rv) |
'class': CPPClassObject, 'function': CPPFunctionObject, 'member': CPPMemberObject, 'type': CPPTypeObject | 'class': CPPClassObject, 'function': CPPFunctionObject, 'member': CPPMemberObject, 'type': CPPTypeObject, 'namespace': CPPCurrentNamespace | def describe_signature(self, signode, func): # return value is None for things with a reverse return value # such as casting operator definitions or constructors # and destructors. if func.rv is not None: self.attach_type(signode, func.rv) signode += nodes.Text(u' ') self.attach_function(signode, func) |
expr = parser.parse_type() parser.skip_ws() if not parser.eof: | try: expr = parser.parse_type() parser.skip_ws() if not parser.eof: return None except DefinitionError: | def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode): parser = DefinitionParser(target) expr = parser.parse_type() parser.skip_ws() if not parser.eof: return None target = unicode(expr) if target not in self.data['objects']: return None obj = self.data['objects'][target] return make_refnode(bu... |
next | next = next | def b(s): return s.encode('utf-8') |
print objects | def add_target_and_index(self, name, sig, signode): if name not in self.state.document.ids: signode['names'].append(name) signode['ids'].append(name) signode['first'] = (not self.names) self.state.document.note_explicit_target(signode) objects = self.env.domaindata['rst']['objects'] print objects if name in objects: s... | |
if isinstance(doctree, nodes.reference) and hasattr(doctree, 'refuri'): | if isinstance(doctree, nodes.reference) and doctree.has_key('refuri'): | def get_refnodes(self, doctree, result): """Collect section titles, their depth in the toc and the refuri.""" # XXX: is there a better way than checking the attribute # toctree-l[1-8] on the parent node? if isinstance(doctree, nodes.reference) and hasattr(doctree, 'refuri'): refuri = doctree['refuri'] if refuri.startsw... |
R= str(round(self.red, 3))+',' G= str(round(self.green, 3))+',' B= str(round(self.blue, 3)) return '("'+self.model+'",'+R+G+B+')' | R= str(round(self.red, 5))+',' G= str(round(self.green, 5))+',' B= str(round(self.blue, 5)) result='"'+self.model+'",'+R+G+B if self.alpha<1: result += ','+ str(round(self.alpha, 5)) return '('+result+')' | def toSave(self): R= str(round(self.red, 3))+',' G= str(round(self.green, 3))+',' B= str(round(self.blue, 3)) return '("'+self.model+'",'+R+G+B+')' |
C= str(round(self.c, 3))+',' M= str(round(self.m, 3))+',' Y= str(round(self.y, 3))+',' K= str(round(self.k, 3)) return '("'+self.model+'",'+C+M+Y+K+')' | C= str(round(self.c, 5))+',' M= str(round(self.m, 5))+',' Y= str(round(self.y, 5))+',' K= str(round(self.k, 5)) result='"'+self.model+'",'+C+M+Y+K if self.alpha<1: result += ','+ str(round(self.alpha, 5)) return '('+result+')' | def toSave(self): C= str(round(self.c, 3))+',' M= str(round(self.m, 3))+',' Y= str(round(self.y, 3))+',' K= str(round(self.k, 3)) return '("'+self.model+'",'+C+M+Y+K+')' |
R= str(round(self.r, 3))+',' G= str(round(self.g, 3))+',' B= str(round(self.b, 3))+',' C= str(round(self.c, 3))+',' M= str(round(self.m, 3))+',' Y= str(round(self.y, 3))+',' K= str(round(self.k, 3)) return '("'+self.model+'","'+self.palette+'","'+self.name+'",'+R+G+B+C+M+Y+K+')' | R= str(round(self.r, 5))+',' G= str(round(self.g, 5))+',' B= str(round(self.b, 5))+',' C= str(round(self.c, 5))+',' M= str(round(self.m, 5))+',' Y= str(round(self.y, 5))+',' K= str(round(self.k, 5)) result='"'+self.model+'",'+self.palette+'","'+self.name+'",'+R+G+B+C+M+Y+K if self.alpha<1: result += ','+ str(round(sel... | def toSave(self): R= str(round(self.r, 3))+',' G= str(round(self.g, 3))+',' B= str(round(self.b, 3))+',' C= str(round(self.c, 3))+',' M= str(round(self.m, 3))+',' Y= str(round(self.y, 3))+',' K= str(round(self.k, 3)) return '("'+self.model+'","'+self.palette+'","'+self.name+'",'+R+G+B+C+M+Y+K+')' |
print_internal_warnings = 1 | print_internal_warnings = 0 | def save(self, filename=None): if len(self.__dict__) == 0 or filename == None: return from xml.sax.saxutils import XMLGenerator |
def updateInfo(inf1=None,inf2=None,inf3=None): pass | def updateInfo(inf1='',inf2='',inf3=0): if not receiver is None: receiver(inf1,inf2,inf3) | def updateInfo(inf1=None,inf2=None,inf3=None): pass |
elif isinstance(value, PIL.Image.Image): | elif hasattr(value, 'tostring') and hasattr(value, 'size'): | def _SetNodeProps(element, name, value): "Set the properties of the node based on the type of object" # if it is a ctypes structure if isinstance(value, ctypes.Structure): # create an element for the structure struct_elem = SubElement(element, name) #clsModule = value.__class__.__module__ cls_name = value.__class__._... |
waited = time.time() - start | time_left = timeout - ( time.time() - start) | def WaitUntil( timeout, retry_interval, func, value = True, op = operator.eq, *args): """Wait until ``op(function(*args), value)`` is True or until timeout expires * **timeout** how long the function will try the function * **retry_interval** how long to wait between retries * **func** the function that will be exe... |
if waited < timeout: | if time_left > 0: | def WaitUntil( timeout, retry_interval, func, value = True, op = operator.eq, *args): """Wait until ``op(function(*args), value)`` is True or until timeout expires * **timeout** how long the function will try the function * **retry_interval** how long to wait between retries * **func** the function that will be exe... |
time.sleep(min(retry_interval, timeout - waited)) | time.sleep(min(retry_interval, time_left)) | def WaitUntil( timeout, retry_interval, func, value = True, op = operator.eq, *args): """Wait until ``op(function(*args), value)`` is True or until timeout expires * **timeout** how long the function will try the function * **retry_interval** how long to wait between retries * **func** the function that will be exe... |
while waited <= timeout: | while True: | def WaitUntilPasses( timeout, retry_interval, func, exceptions = (Exception), *args): """Wait until ``func(*args)`` does not raise one of the exceptions in exceptions * **timeout** how long the function will try the function * **retry_interval** how long to wait between retries * **func** the function that will be ... |
waited = time.time() - start if waited < timeout: time.sleep(min(retry_interval, timeout - waited)) | time_left = timeout - ( time.time() - start) if time_left > 0: time.sleep(min(retry_interval, time_left)) | def WaitUntilPasses( timeout, retry_interval, func, exceptions = (Exception), *args): """Wait until ``func(*args)`` does not raise one of the exceptions in exceptions * **timeout** how long the function will try the function * **retry_interval** how long to wait between retries * **func** the function that will be ... |
self.assertRaises(Exception, test_view('party')) | test_view('party') | def test0005views(self): ''' Test views. ''' self.assertRaises(Exception, test_view('party')) |
new_chunks.append(ch) | if ch in ('tag', 'tags'): new_chunks.append('branches') else: new_chunks.append(ch) | >>> def dummyinfo(path): |
if nicologin: | if isinstance(nicologin, NicoLogin): | def __init__(self, group_id, nicologin=None): """Initailize Mylist instance. group_id is last number of http://www.nicovideo.jp/mylist/0000000 Using existing login session if nicologin is NicoLogin instance. """ super().__init__() if nicologin: self.opener = nicologin.opener self.islogin = True |
self.islogin = True | self.islogin = nicologin.islogin | def __init__(self, group_id, nicologin=None): """Initailize Mylist instance. group_id is last number of http://www.nicovideo.jp/mylist/0000000 Using existing login session if nicologin is NicoLogin instance. """ super().__init__() if nicologin: self.opener = nicologin.opener self.islogin = True |
def _(cls, *args, **kwds): | def _(fn, cls, *args, **kwds): | def _(cls, *args, **kwds): if not cls.islogin: raise NotLoginError |
('E-mail 9 Address', gdata.data.OTHER_REL, None, 2), ('E-mail 10 Address', gdata.data.HOME_REL, None, 3), ('E-mail 11 Address', gdata.data.OTHER_REL, None, 3), ('E-mail 12 Address', gdata.data.WORK_REL, None, 3), ('E-mail 13 Address', gdata.data.HOME_REL, None, 4), ('E-mail 14 Address', gdata.data.OTHER_REL, None, 4), ... | ('E-mail 9 Address', gdata.data.OTHER_REL, None, 2), ('E-mail 10 Address', gdata.data.WORK_REL, None, 3), ('E-mail 11 Address', gdata.data.HOME_REL, None, 3), ('E-mail 12 Address', gdata.data.OTHER_REL, None, 3), ('E-mail 13 Address', gdata.data.WORK_REL, None, 4), ('E-mail 14 Address', gdata.data.HOME_REL, None, 4), (... | def __init__(self): """Builds a new Outlook to GData converter.""" self.display_name_fields = ( 'First Name', 'Middle Name', 'Last Name', 'Suffix') |
('E-mail 19 Address', gdata.data.OTHER_REL, None, 6), ('E-mail 20 Address', gdata.data.OTHER_REL, None, 6), | ('E-mail 19 Address', gdata.data.WORK_REL, None, 6), ('E-mail 20 Address', gdata.data.HOME_REL, None, 6), | def __init__(self): """Builds a new Outlook to GData converter.""" self.display_name_fields = ( 'First Name', 'Middle Name', 'Last Name', 'Suffix') |
('E-mail 22 Address', gdata.data.OTHER_REL, None, 7), ('E-mail 23 Address', gdata.data.OTHER_REL, None, 7), | ('E-mail 22 Address', gdata.data.WORK_REL, None, 7), ('E-mail 23 Address', gdata.data.HOME_REL, None, 7), | def __init__(self): """Builds a new Outlook to GData converter.""" self.display_name_fields = ( 'First Name', 'Middle Name', 'Last Name', 'Suffix') |
all_encoding = ["utf-8", "iso-8859-1", "iso-8859-2", "us-ascii", 'windows-1250', 'windows-1252'] | all_encoding = ["utf-8", "iso-8859-1", "iso-8859-2", 'iso-8859-15', 'iso-8859-3', "us-ascii", 'windows-1250', 'windows-1252', 'windows-1254', 'ibm861'] | def CsvLineToOperation((index, fields)): """Maps a CSV line to an operation on a contact/profile. |
Log('Error: ' % self.status.text) | Log('Error: %s' % self.status.text) | def PrintResult(self, action, contact_id, new_entry, more=None): outcome = self.is_success and 'OK' or 'Error' if(self.status != None): message = ' [%s] %s %i: %s' % ( action, outcome, self.code, self.status.reason) if self.status.text: Log('Error: ' % self.status.text) existing_id = GetContactShortId(existing_entry) m... |
def ImportMsOutlookCsv(self, input_csv_file, output_csv_file, dry_run=False): | def ImportMsOutlookCsv(self, import_csv_file_name, output_csv_file, dry_run=False): | def ImportMsOutlookCsv(self, input_csv_file, output_csv_file, dry_run=False): """Imports an MS Outlook contacts/profiles CSV file into the contact list. |
input_csv_file: The MS Outlook CSV file to import, as a readable stream. | import_csv_file_name: The MS Outlook CSV file name to import, as a readable stream. | def ImportMsOutlookCsv(self, input_csv_file, output_csv_file, dry_run=False): """Imports an MS Outlook contacts/profiles CSV file into the contact list. |
csv_reader = csv.DictReader(input_csv_file, delimiter=',') | def ImportMsOutlookCsv(self, input_csv_file, output_csv_file, dry_run=False): """Imports an MS Outlook contacts/profiles CSV file into the contact list. | |
csv_reader = None all_encoding = ["utf-8", "iso-8859-1", "iso-8859-2", "us-ascii", 'windows-1250', 'windows-1252'] encoding_index = 0 print "Detecting encoding of the CSV file..." while csv_reader == None: next_encoding = all_encoding[encoding_index] print "Trying %s" % (next_encoding) input_csv_file = open(import_csv_... | def CsvLineToOperation((index, fields)): """Maps a CSV line to an operation on a contact/profile. | |
self.batch_index = int(result_entry.batch_id.text) | if(result_entry.batch_id == None): self.batch_index = 99 self.code = 500 self.status = None else: self.batch_index = int(result_entry.batch_id.text) self.status = result_entry.batch_status self.code = int(self.status.code) | def __init__(self, result_entry): self.batch_index = int(result_entry.batch_id.text) self.entry = result_entry self.status = result_entry.batch_status self.code = int(self.status.code) self.is_success = (self.code < 400) |
self.status = result_entry.batch_status self.code = int(self.status.code) | def __init__(self, result_entry): self.batch_index = int(result_entry.batch_id.text) self.entry = result_entry self.status = result_entry.batch_status self.code = int(self.status.code) self.is_success = (self.code < 400) | |
outcome = self.is_success and 'OK' or 'Error' message = ' [%s] %s %s: %s' % ( action, outcome, self.status.code, self.status.reason) if self.status.text: Log('Error: ' % self.status.text) existing_id = GetContactShortId(existing_entry) message = '%s - existing ID: %s' % (message, existing_id) if more: message = '%s %s'... | outcome = self.is_success and 'OK' or 'Error' if(self.status != None): message = ' [%s] %s %i: %s' % ( action, outcome, self.code, self.status.reason) if self.status.text: Log('Error: ' % self.status.text) existing_id = GetContactShortId(existing_entry) message = '%s - existing ID: %s' % (message, existing_id) if more:... | def PrintResult(self, action, contact_id, new_entry, more=None): outcome = self.is_success and 'OK' or 'Error' message = ' [%s] %s %s: %s' % ( action, outcome, self.status.code, self.status.reason) if self.status.text: Log('Error: ' % self.status.text) existing_id = GetContactShortId(existing_entry) message = '%s - exi... |
csv_writer = csv.DictWriter(csv_file, delimiter=',', | csv_writer = UnicodeDictWriter(csv_file, delimiter=',', | def CreateCsvWriter(self, csv_file): """Creates a CSV writer the given file. |
import_csv_file = open(import_csv_file_name, 'rt') | def main(): usage = """\ | |
contacts_manager.ImportMsOutlookCsv(import_csv_file, output_csv_file, | contacts_manager.ImportMsOutlookCsv(import_csv_file_name, output_csv_file, | def OpenOutputCsv(file_name, option_name, description): if file_name: try: csv_file = open(file_name, 'wb') Log('%s as CSV to: %s' % (description, file_name)) return csv_file except IOError, e: parser.error('Unable to open %s\n%s\nPlease set the --%s command-line' ' option to a writable file.' % (file_name, option_name... |
import_csv_file.close() | def OpenOutputCsv(file_name, option_name, description): if file_name: try: csv_file = open(file_name, 'wb') Log('%s as CSV to: %s' % (description, file_name)) return csv_file except IOError, e: parser.error('Unable to open %s\n%s\nPlease set the --%s command-line' ' option to a writable file.' % (file_name, option_name... | |
return Nonelaaklal | return None | def CsvLineToOperation((index, fields)): """Maps a CSV line to an operation on a contact/profile. |
('E-mail 24 Address', gdata.data.OTHER_REL, None, 7), | ('E-mail 24 Address', gdata.data.OTHER_REL, None, 7), ('E-mail 25 Address', gdata.data.WORK_REL, None, 8), ('E-mail 26 Address', gdata.data.HOME_REL, None, 8), ('E-mail 27 Address', gdata.data.OTHER_REL, None, 8), ('E-mail 28 Address', gdata.data.WORK_REL, None, 9), ('E-mail 29 Address', gdata.data.HOME_REL, None, 9), ... | def __init__(self): """Builds a new Outlook to GData converter.""" self.display_name_fields = ( 'First Name', 'Middle Name', 'Last Name', 'Suffix') |
email_addresses = [{},{},{},{},{},{},{},{}] | email_addresses = [{},{},{},{},{},{},{},{},{},{},{}] | def AddField(field_name, obj, attribute_name): """Populates a CSV field from an attribute of the given object. |
while email.rel in email_addresses[i]: | while i <= 10 and email.rel in email_addresses[i]: | def AddField(field_name, obj, attribute_name): """Populates a CSV field from an attribute of the given object. |
('Company Main Phone', gdata.data.GENERAL_ADDRESS, 0), | ('Company Main Phone', gdata.data.WORK_REL, 0), | def __init__(self): """Builds a new Outlook to GData converter.""" self.display_name_fields = ( 'First Name', 'Middle Name', 'Last Name', 'Suffix') |
' int tobe_allocated = msg->%(name)s_num_allocated;', ' %(ctype)s* new_data = NULL;', ' tobe_allocated = !tobe_allocated ? 1 : tobe_allocated << 1;', ' new_data = (%(ctype)s*) realloc(msg->%(name)s_data,', ' tobe_allocated * sizeof(%(ctype)s));', ' if (new_data == NULL)', | ' if (%(parent_name)s_%(name)s_expand_to_hold_more(msg)<0)', | def CodeAdd(self): codearrayadd = self._entry.CodeArrayAdd( 'msg->%(name)s_data[msg->%(name)s_length - 1]' % self.GetTranslation(), 'value') code = [ '%(ctype)s %(optpointer)s', '%(parent_name)s_%(name)s_add(' 'struct %(parent_name)s *msg%(optaddarg)s)', '{', ' if (++msg->%(name)s_length >= msg->%(name)s_num_allocated... |
' msg->%(name)s_data = new_data;', ' msg->%(name)s_num_allocated = tobe_allocated;', | def CodeAdd(self): codearrayadd = self._entry.CodeArrayAdd( 'msg->%(name)s_data[msg->%(name)s_length - 1]' % self.GetTranslation(), 'value') code = [ '%(ctype)s %(optpointer)s', '%(parent_name)s_%(name)s_add(' 'struct %(parent_name)s *msg%(optaddarg)s)', '{', ' if (++msg->%(name)s_length >= msg->%(name)s_num_allocated... | |
if self._optaddarg: code = [ 'if (%(parent_name)s_%(name)s_add(%(var)s, %(init)s) == NULL)', ' return (-1);' ] else: code = [ 'if (%(parent_name)s_%(name)s_add(%(var)s) == NULL)', ' return (-1);' ] | code = [ 'if (%(var)s->%(name)s_length >= %(var)s->%(name)s_num_allocated &&', ' %(parent_name)s_%(name)s_expand_to_hold_more(%(var)s) < 0) {', ' puts("HEY NOW");', ' return (-1);', '}'] | def CodeUnmarshal(self, buf, tag_name, var_name, var_len): translate = self.GetTranslation({ 'var' : var_name, 'buf' : buf, 'tag' : tag_name, 'init' : self._entry.GetInitializer()}) if self._optaddarg: code = [ 'if (%(parent_name)s_%(name)s_add(%(var)s, %(init)s) == NULL)', ' return (-1);' ] else: code = [ 'if (%(pare... |
code += [ '--%(var)s->%(name)s_length;' % translate ] | def CodeUnmarshal(self, buf, tag_name, var_name, var_len): translate = self.GetTranslation({ 'var' : var_name, 'buf' : buf, 'tag' : tag_name, 'init' : self._entry.GetInitializer()}) if self._optaddarg: code = [ 'if (%(parent_name)s_%(name)s_add(%(var)s, %(init)s) == NULL)', ' return (-1);' ] else: code = [ 'if (%(pare... | |
tpl = resource_string('collective.recipe.funkload', tpl_name) | tpl = resource_string('collective.funkload', tpl_name) | def writeScript(self, script): """Write the FunkLoad test script.""" from pkg_resources import resource_string tpl_name = 'data/ScriptTestCase.tpl' trace('Creating script: %s.\n' % self.script_path) tpl = resource_string('collective.recipe.funkload', tpl_name) content = tpl % {'script': script, 'test_name': self.test_... |
if not getTracker().waitForBlockStart(100,1,1): | try: if not getTracker().waitForBlockStart(1000,1,1): raise Exception("waitForBlockStart failed") except Exception: | def startRecording(): """Commence eyetracker recording and verify that it's working. """ getTracker().resetData() getTracker().startRecording(1,1,1,1) getExperiment().recording = True pylink.beginRealTimeMode(100) if not getTracker().waitForBlockStart(100,1,1): getTracker().drawText("LINK DATA NOT RECEIVED!",pos=(1,20)... |
self.checkEyeLink() | return self.checkEyeLink() | def handleEvent(self,event): if not getExperiment().recording: self.stop() return False if getTracker(): action = getTracker().isRecording() if action != pylink.TRIAL_OK: raise TrialAbort(action) self.checkEyeLink() else: # So that the experiment can be tested without the eyetracker, # just fake a response after 2000 m... |
event = getTracker().getFloatData() if event.getType() == pylink.STARTFIX and event.getEye() == self.eyeUsed: for area in self.params['possible_resp']: if area.contains(event.getStartGaze()): self.fixtime=event.getStartTime() self.fixatedArea = area break if (event.getType() == pylink.FIXUPDATE or event.getType() == ... | eventType = getTracker().getNextData() if eventType == pylink.STARTFIX or eventType == pylink.FIXUPDATE or eventType == pylink.ENDFIX: event = getTracker().getFloatData() if event.getType() == pylink.STARTFIX and event.getEye() == self.eyeUsed: for area in self.params['possible_resp']: if area.contains(event.getStart... | def checkEyeLink(self): """Check if the eyes have fixated in one of the areas listed in possible_resp, and have stayed there for the specified minimum time. If so, record rt, rt_time, and resp, and return True; otherwise return False. """ if self.fixatedArea: #We've already started fixating on one of the areas in poss... |
username = parser.get('beerbug', 'username') | username = parser.get('google', 'username') | def serve_forever(): username = None password = None # Read the username and password from a config file. # If not present, prompt the user for their credentials. parser = ConfigParser.SafeConfigParser() path = os.path.expanduser('~/.beerbug/beerbug.ini') parser.read(path) if parser is not None: try: try: username = pa... |
password = parser.get('beerbug', 'password') | password = parser.get('google', 'password') | def serve_forever(): username = None password = None # Read the username and password from a config file. # If not present, prompt the user for their credentials. parser = ConfigParser.SafeConfigParser() path = os.path.expanduser('~/.beerbug/beerbug.ini') parser.read(path) if parser is not None: try: try: username = pa... |
define_macros = [('_CRT_[SECURE_NO_WARNINGS', '1')] | macros = [('_CRT_SECURE_NO_WARNINGS', '1')] | def __init__(self, *args, **kwargs): Extension.__init__(self, *args, **kwargs) self.export_symbols = finallist(self.export_symbols) |
define_macros = [] | macros = [] | def __init__(self, *args, **kwargs): Extension.__init__(self, *args, **kwargs) self.export_symbols = finallist(self.export_symbols) |
f = open(tmpfile) | f = open(tmpfile, 'wb') | def test_raiseOnEmptyFile(self): """ Test case ensures that empty files do raise warnings. """ tmpfile = NamedTemporaryFile().name # generate empty file f = open(tmpfile) f.write("") f.close() formats_ep = _getPlugins('obspy.plugin.waveform', 'readFormat') for ep in formats_ep.values(): isFormat = load_entry_point(ep.d... |
if hasattr(warnings, 'catch_warnings'): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") blockette.parseSEED(b010) self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[-1].category, UserWarning)) self.assertTrue('date' and 'required' in \ w[-1].message.message.lower()) else: blocket... | warnings.simplefilter("always") blockette.parseSEED(b010) warnings.resetwarnings() | def test_missingRequiredDateTimes(self): """ A warning should be raised if a blockette misses a required date. """ # blockette 10 - missing start time b010 = "0100034 2.408~2038,001~2009,001~~~" # strict raises an exception blockette = Blockette010(strict=True) self.assertRaises(SEEDParserException, blockette.parseSEED... |
header['sh'][key] = value | if key in SH_KEYS_INT: header['sh'][key] = int(value) elif key in SH_KEYS_FLOAT: header['sh'][key] = float(value) else: header['sh'][key] = value | def readASC(filename, headonly=False): """ Reads a ASC file and returns an ObsPy Stream object. This function should NOT be called directly, it registers via the obspy :func:`~obspy.core.stream.read` function, call this instead. Parameters ---------- filename : string ASC file to be read. headonly : bool, optional If... |
header['sh'][key] = value | if key in SH_KEYS_INT: header['sh'][key] = int(value) elif key in SH_KEYS_FLOAT: header['sh'][key] = float(value) else: header['sh'][key] = value | def readQ(filename, headonly=False, data_directory=None, byteorder='='): """ Reads a Q file and returns an ObsPy Stream object. Q files consists of two files per data set: * a ASCII header file with file extension `QHD` and the * binary data file with file extension `QBN`. The read method only accepts header files f... |
lib.read_header(fp, C.pointer(head)) | errcode = lib.read_header(fp, C.pointer(head)) if errcode != 0: raise GSEUtiError("Error in lib.read_header") | def read(f, verify_chksum=True): """ Read GSE2 file and return header and data. Currently supports only CM6 compressed GSE2 files, this should be sufficient for most cases. Data are in circular frequency counts, for correction of calper multiply by 2PI and calper: data * 2 * pi * header['calper']. :type f: File Point... |
assert n == head.n_samps, "Missmatching length in lib.decomp_6b" | if n != head.n_samps: raise GSEUtiError("Missmatching length in lib.decomp_6b") | def read(f, verify_chksum=True): """ Read GSE2 file and return header and data. Currently supports only CM6 compressed GSE2 files, this should be sufficient for most cases. Data are in circular frequency counts, for correction of calper multiply by 2PI and calper: data * 2 * pi * header['calper']. :type f: File Point... |
def copy(self, init={}): return self.__class__(init) | def copy(self): return self.__class__(self.__dict__.copy()) | def copy(self, init={}): return self.__class__(init) |
geometry = np.concatenate([geometry, np.zeros((1,3))]) | geometry[nstat][0] = 0.0 geometry[nstat][1] = 0.0 geometry[nstat][2] = 0.0 | def get_geometry(stream, coordsys='lonlat', verbose=False): """ Method to calculate the array geometry and the center coordinates in km :param stream: Stream object, the trace.stats dict like class must contain a obspy.core.util.attribdict with 'latitude', 'longitude' (in degrees) and 'elevation' (in km), or 'x', 'y',... |
from numpydoc.docscrape import Reader | from numpydoc.docscrape import Reader, NumpyDocString | #def skip_underscore(app, what, name, obj, skip, options): |
if (self.use_plots and 'import matplotlib' in examples_str | if not self['Basic Usage']: return [''] elif (self.use_plots and 'import matplotlib' in examples_str | def obspy_str_usage(self): examples_str = "\n".join(self['Basic Usage']) if (self.use_plots and 'import matplotlib' in examples_str and 'plot::' not in examples_str): out = [] out += self._str_header('Basic Usage') out += ['.. plot::', ''] out += self._str_indent(self['Basic Usage']) out += [''] return out else: retur... |
out = [] | out = [''] | def obspy_str_usage(self): examples_str = "\n".join(self['Basic Usage']) if (self.use_plots and 'import matplotlib' in examples_str and 'plot::' not in examples_str): out = [] out += self._str_header('Basic Usage') out += ['.. plot::', ''] out += self._str_indent(self['Basic Usage']) out += [''] return out else: retur... |
return self._str_section('Examples') | return [''] + self._str_section('Basic Usage') + [''] | def obspy_str_usage(self): examples_str = "\n".join(self['Basic Usage']) if (self.use_plots and 'import matplotlib' in examples_str and 'plot::' not in examples_str): out = [] out += self._str_header('Basic Usage') out += ['.. plot::', ''] out += self._str_indent(self['Basic Usage']) out += [''] return out else: retur... |
out += self._str_usage() | def obspy__str__(self, indent=0, func_role="obj"): out = [] out += self._str_signature() out += self._str_index() + [''] out += self._str_summary() out += self._str_extended_summary() #out += self._str_usage() for param_list in ('Parameters', 'Returns', 'Raises'): out += self._str_param_list(param_list) out += self._st... | |
out += self._str_member_list('Methods') | def obspy__str__(self, indent=0, func_role="obj"): out = [] out += self._str_signature() out += self._str_index() + [''] out += self._str_summary() out += self._str_extended_summary() #out += self._str_usage() for param_list in ('Parameters', 'Returns', 'Raises'): out += self._str_param_list(param_list) out += self._st... | |
SphinxDocString._str_usage = obspy_str_usage | def obspy__str__(self, indent=0, func_role="obj"): out = [] out += self._str_signature() out += self._str_index() + [''] out += self._str_summary() out += self._str_extended_summary() #out += self._str_usage() for param_list in ('Parameters', 'Returns', 'Raises'): out += self._str_param_list(param_list) out += self._st... | |
return [node.__dict__ for node in root.getchildren()] | return [dict(((k, v.pyval) for k, v in node.__dict__.iteritems())) \ for node in root.getchildren()] | def getLatency(self, network_id=None, station_id=None, location_id=None, channel_id=None, **kwargs): """ Gets a list of network latency values. |
return [node.__dict__ for node in root.getchildren()] | return [dict(((k, v.pyval) for k, v in node.__dict__.iteritems())) \ for node in root.getchildren()] | def getList(self, network_id=None, station_id=None, **kwargs): """ Gets a list of station information. |
id_length = max(len(tr.id) for tr in self) | id_length = self and max(len(tr.id) for tr in self) or 0 | def __str__(self): """ __str__ method of obspy.Stream objects. |
root = SubElement(doc, utils.toTag('Volume Index Control Header')) | sub = SubElement(doc, utils.toTag('Volume Index Control Header')) | def getXSEED(self, version=DEFAULT_XSEED_VERSION, split_stations=False): """ Returns a XML representation of all headers of a SEED volume. |
root.append(blockette.getXML(xseed_version=version)) | sub.append(blockette.getXML(xseed_version=version)) | def getXSEED(self, version=DEFAULT_XSEED_VERSION, split_stations=False): """ Returns a XML representation of all headers of a SEED volume. |
root = SubElement(doc, | sub = SubElement(doc, | def getXSEED(self, version=DEFAULT_XSEED_VERSION, split_stations=False): """ Returns a XML representation of all headers of a SEED volume. |
root.append(blockette.getXML(xseed_version=version)) if version == '1.0': root = SubElement(doc, utils.toTag('Timespan Control Header')) root = SubElement(doc, utils.toTag('Data Records')) | sub.append(blockette.getXML(xseed_version=version)) | def getXSEED(self, version=DEFAULT_XSEED_VERSION, split_stations=False): """ Returns a XML representation of all headers of a SEED volume. |
root = SubElement(doc, utils.toTag('Station Control Header')) | sub = SubElement(doc, utils.toTag('Station Control Header')) | def getXSEED(self, version=DEFAULT_XSEED_VERSION, split_stations=False): """ Returns a XML representation of all headers of a SEED volume. |
root.append(blockette.getXML(xseed_version=version)) | sub.append(blockette.getXML(xseed_version=version)) if version == '1.0': SubElement(doc, utils.toTag('Timespan Control Header')) SubElement(doc, utils.toTag('Data Records')) | def getXSEED(self, version=DEFAULT_XSEED_VERSION, split_stations=False): """ Returns a XML representation of all headers of a SEED volume. |
root = SubElement(cdoc, utils.toTag('Station Control Header')) | sub = SubElement(cdoc, utils.toTag('Station Control Header')) | def getXSEED(self, version=DEFAULT_XSEED_VERSION, split_stations=False): """ Returns a XML representation of all headers of a SEED volume. |
amp_val = paz2AmpValueOfFreqResp(woodander) / paz2AmpValueOfFreqResp(paz) | amp_val = paz2AmpValueOfFreqResp(woodander, freq) / paz2AmpValueOfFreqResp(paz, freq) | def estimateMagnitude(paz, amplitude, timespan, h_dist): """ Estimates local magnitude from poles and zeros of given instrument, the peak to peak amplitude and the period in which it is measured :param paz: PAZ of the instrument :param amplitude: Peak to peak amplitude :param timespan: Timespan of peak to peak amplitu... |
class deprecated_keywords: def __init__(self, keywords): self.keywords = keywords def __call__(self, func): | def deprecated_keywords(keywords): def fdec(func): | def new_func(*args, **kwargs): if 'deprecated' in str(func.__doc__).lower(): msg = func.__doc__ else: msg = "Call to deprecated function %s." % func.__name__ warnings.warn(msg, category=DeprecationWarning) return func(*args, **kwargs) |
if kw in self.keywords: nkw = self.keywords[kw] | if kw in keywords: nkw = keywords[kw] | def echo_func(*args, **kwargs): for kw in kwargs.keys(): if kw in self.keywords: nkw = self.keywords[kw] warnings.warn(msg % (kw, fname, nkw), category=DeprecationWarning) kwargs[nkw] = kwargs[kw] del(kwargs[kw]) return func(*args, **kwargs) |
name_service="dmc.iris.washington.edu:6371/NameService"): | name_service="dmc.iris.washington.edu:6371/NameService", debug=False): | def __init__(self, network_dc=("/edu/iris/dmc", "IRIS_NetworkDC"), seismogram_dc=("/edu/iris/dmc", "IRIS_DataCenter"), name_service="dmc.iris.washington.edu:6371/NameService"): """ Initialize Fissures/DHI client. :param network_dc: Tuple containing dns and NetworkDC name :param seismogram_dc: Tuple containing dns and ... |
:param network_dc: Tuple containing dns and NetworkDC name :param seismogram_dc: Tuple containing dns and DataCenter name :param name_service: String containing the name service | :param network_dc: Tuple containing dns and NetworkDC name. :param seismogram_dc: Tuple containing dns and DataCenter name. :param name_service: String containing the name service. :param debug: Enables verbose output of the connection handling (default is False). | def __init__(self, network_dc=("/edu/iris/dmc", "IRIS_NetworkDC"), seismogram_dc=("/edu/iris/dmc", "IRIS_DataCenter"), name_service="dmc.iris.washington.edu:6371/NameService"): """ Initialize Fissures/DHI client. :param network_dc: Tuple containing dns and NetworkDC name :param seismogram_dc: Tuple containing dns and ... |
orb = CORBA.ORB_init([ "-ORBgiopMaxMsgSize", "2097152", "-ORBInitRef", "NameService=corbaloc:iiop:" + name_service, ], CORBA.ORB_ID) | args = ["-ORBgiopMaxMsgSize", "2097152", "-ORBInitRef", "NameService=corbaloc:iiop:" + name_service, ] if debug: args = ["-ORBtraceLevel", "40"] + args orb = CORBA.ORB_init(args, CORBA.ORB_ID) | def __init__(self, network_dc=("/edu/iris/dmc", "IRIS_NetworkDC"), seismogram_dc=("/edu/iris/dmc", "IRIS_DataCenter"), name_service="dmc.iris.washington.edu:6371/NameService"): """ Initialize Fissures/DHI client. :param network_dc: Tuple containing dns and NetworkDC name :param seismogram_dc: Tuple containing dns and ... |
if format == 'MSEED': | if format in ('MSEED', 'GSE2'): | def test_readAndWriteAllInstalledWaveformPlugins(self): """ Tests read and write methods for all installed waveform plug-ins. """ data = np.arange(0, 2000) start = UTCDateTime(2009, 1, 13, 12, 1, 2, 999000) formats = _getPlugins('obspy.plugin.waveform', 'writeFormat') for format in formats: for native_byteorder in ['<'... |
if format == 'MSEED': | if format in ('MSEED', 'GSE2'): | def test_read_thread_safe(self): """ Tests for race conditions. Reading n_threads (currently 30) times the same waveform file in parallel and compare the results which must be all the same. """ data = np.arange(0, 20000) start = UTCDateTime(2009, 1, 13, 12, 1, 2, 999000) formats = _getPlugins('obspy.plugin.waveform', '... |
tr.trim(starttime, endttime) | tr.trim(starttime, endtime) | def readMSEED(filename, headonly=False, starttime=None, endtime=None, reclen= -1, quality=False, nearest_sample=False, **kwargs): """ Reads a given Mini-SEED file and returns an Stream object. This function should NOT be called directly, it registers via the obspy :func:`~obspy.core.stream.read` function, call this in... |
def test_toPythonDateTimeObjects(self): | def test_subAddFloat(self): | def test_toPythonDateTimeObjects(self): """ Tests subtraction of floats from UTCDateTime """ time = UTCDateTime(2010, 05, 31, 19, 54, 24.490) res = -0.045149 |
result1 = time + (-res) result2 = time - res self.assertAlmostEquals(result1 - result2, 0.0) | result1 = UTCDateTime("2010-05-31T19:54:24.535148Z") result2 = time + (-res) result3 = time - res self.assertAlmostEquals(result2 - result3, 0.0) self.assertAlmostEquals(result1.timestamp, result2.timestamp) | def test_toPythonDateTimeObjects(self): """ Tests subtraction of floats from UTCDateTime """ time = UTCDateTime(2010, 05, 31, 19, 54, 24.490) res = -0.045149 |
sacconstant = pazdict['digitizer_gain']*pazdict['seismometer_gain']*pazdict['gain'] np.testing.assert_almost_equal(tr.stats.paz['gain']/1e17,sacconstant/1e17,decimal=6) | sacconstant = pazdict['digitizer_gain'] * \ pazdict['seismometer_gain'] * pazdict['gain'] np.testing.assert_almost_equal(tr.stats.paz['gain'] / 1e17, sacconstant / 1e17, decimal=6) | def test_sacpaz_from_dataless(self): ### The following dictionary is extracted from a datalessSEED ### file pazdict = {'sensitivity': 2516580000.0, 'digitizer_gain': 1677720.0, 'seismometer_gain': 1500.0, 'zeros': [0j, 0j], 'gain': 59198800.0, 'poles': [(-0.037010000000000001+0.037010000000000001j), (-0.037010000000000... |
self.assertEqual(len(tr.stats.paz['zeros']),3) | self.assertEqual(len(tr.stats.paz['zeros']), 3) def test_issue171(self): """ Test for issue """ tr = read()[0] tempfile = NamedTemporaryFile().name tr.write(tempfile, format="SAC") trace = SacIO(tempfile) trace.SetHvalue('stel', 91.0) trace.WriteSacHeader(tempfile) trace = SacIO(tempfile) os.remove(tempfile) | def test_sacpaz_from_dataless(self): ### The following dictionary is extracted from a datalessSEED ### file pazdict = {'sensitivity': 2516580000.0, 'digitizer_gain': 1677720.0, 'seismometer_gain': 1500.0, 'zeros': [0j, 0j], 'gain': 59198800.0, 'poles': [(-0.037010000000000001+0.037010000000000001j), (-0.037010000000000... |
def IsValidXYSacFile(self, thePath): | def IsValidXYSacFile(self, filename): | def IsValidXYSacFile(self, thePath): """ Quick test for a valid SAC ascii file. |
self.ReadSacXY(thePath) except SacError: return False except SacIOError: return False except MemoryError: | self.ReadSacXY(filename) except: | def IsValidXYSacFile(self, thePath): """ Quick test for a valid SAC ascii file. |
if azi[0][0] - azi[0][1] > pi: azi[0][0] -= pi * 2.; elif azi[0][1] - azi[0][0] > pi: azi[0][0] += pi * 2. | def plotMT(T, N, P, size=200, outline=True, plot_zerotrace=True, x0=0, y0=0, xy=(0, 0), width=200): """ Uses a principal axis T, N and P to draw a beach ball plot. :param ax: axis object of a matplotlib figure :param T: L{PrincipalAxis} :param N: L{PrincipalAxis} :param P: L{PrincipalAxis} Adapted from ps_tensor / ut... | |
yp1[i] = y0 + radius_size * co | def plotMT(T, N, P, size=200, outline=True, plot_zerotrace=True, x0=0, y0=0, xy=(0, 0), width=200): """ Uses a principal axis T, N and P to draw a beach ball plot. :param ax: axis object of a matplotlib figure :param T: L{PrincipalAxis} :param N: L{PrincipalAxis} :param P: L{PrincipalAxis} Adapted from ps_tensor / ut... | |
if azi[1][0] - azi[1][1] > pi: azi[1][0] -= pi * 2. elif azi[1][1] - azi[1][0] > pi: azi[1][0] += pi * 2. | def plotMT(T, N, P, size=200, outline=True, plot_zerotrace=True, x0=0, y0=0, xy=(0, 0), width=200): """ Uses a principal axis T, N and P to draw a beach ball plot. :param ax: axis object of a matplotlib figure :param T: L{PrincipalAxis} :param N: L{PrincipalAxis} :param P: L{PrincipalAxis} Adapted from ps_tensor / ut... | |
if azi[2][0] - azi[0][1] > pi: azi[2][0] -= pi * 2. elif azi[0][1] - azi[2][0] > pi: azi[2][0] += pi * 2. | def plotMT(T, N, P, size=200, outline=True, plot_zerotrace=True, x0=0, y0=0, xy=(0, 0), width=200): """ Uses a principal axis T, N and P to draw a beach ball plot. :param ax: axis object of a matplotlib figure :param T: L{PrincipalAxis} :param N: L{PrincipalAxis} :param P: L{PrincipalAxis} Adapted from ps_tensor / ut... | |
start_datetime, end_datetime): | start_datetime, end_datetime, getPAZ=False, getCoordinates=False): | def getWaveform(self, network_id, station_id, location_id, channel_id, start_datetime, end_datetime): """ Get Waveform in an ObsPy stream object from Fissures / DHI. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.