code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# load the proxy from path try: proxy = M2Crypto.X509.load_cert(path) except Exception, e: msg = "Unable to load proxy from path %s : %s" % (path, e) print >>sys.stderr, msg sys.exit(1) # make sure the proxy is RFC 3820 compliant # or is an end-entity X.509 cer...
def validateProxy(path)
Test that the proxy certificate is RFC 3820 compliant and that it is valid for at least the next 15 minutes.
4.457603
4.225738
1.05487
data = kwargs.pop('data', {}) sync = kwargs.pop('sync', True) if not self.id and sync: self.push_to_server(data) super(CustomerProfile, self).save(*args, **kwargs)
def save(self, *args, **kwargs)
If creating new instance, create profile on Authorize.NET also
4.229342
3.470828
1.21854
response = delete_profile(self.profile_id) response.raise_if_error() super(CustomerProfile, self).delete()
def delete(self)
Delete the customer profile remotely and locally
7.978395
5.671758
1.406688
output = add_profile(self.customer.pk, data, data) output['response'].raise_if_error() self.profile_id = output['profile_id'] self.payment_profile_ids = output['payment_profile_ids']
def push_to_server(self, data)
Create customer profile for given ``customer`` on Authorize.NET
7.71584
6.092377
1.266474
output = get_profile(self.profile_id) output['response'].raise_if_error() for payment_profile in output['payment_profiles']: instance, created = CustomerPaymentProfile.objects.get_or_create( customer_profile=self, payment_profile_id=payment_pr...
def sync(self)
Overwrite local customer profile data with remote data
4.304083
3.586682
1.200018
if kwargs.pop('sync', True): self.push_to_server() self.card_code = None self.card_number = "XXXX%s" % self.card_number[-4:] super(CustomerPaymentProfile, self).save(*args, **kwargs)
def save(self, *args, **kwargs)
Sync payment profile on Authorize.NET if sync kwarg is not False
5.90227
4.394967
1.342961
if not self.customer_profile_id: try: self.customer_profile = CustomerProfile.objects.get( customer=self.customer) except CustomerProfile.DoesNotExist: pass if self.payment_profile_id: response = update_paym...
def push_to_server(self)
Use appropriate CIM API call to save payment profile to Authorize.NET 1. If customer has no profile yet, create one with this payment profile 2. If payment profile is not on Authorize.NET yet, create it there 3. If payment profile exists on Authorize.NET update it there
2.083956
1.931818
1.078754
for k, v in data.get('billing', {}).items(): setattr(self, k, v) self.card_number = data.get('credit_card', {}).get('card_number', self.card_number) self.save(sync=False)
def sync(self, data)
Overwrite local customer payment profile data with remote data
4.189622
3.629502
1.154324
response = delete_payment_profile(self.customer_profile.profile_id, self.payment_profile_id) response.raise_if_error() return super(CustomerPaymentProfile, self).delete()
def delete(self)
Delete the customer payment profile remotely and locally
6.136751
4.32584
1.418627
from django.conf import settings try: return settings.LIQUIMIGRATE_CHANGELOG_FILES[database] except AttributeError: if database == DEFAULT_DB_ALIAS: try: return settings.LIQUIMIGRATE_CHANGELOG_FILE except AttributeError: raise Im...
def get_changelog_file_for_database(database=DEFAULT_DB_ALIAS)
get changelog filename for given `database` DB alias
2.751452
2.653267
1.037005
if not database: database = DEFAULT_DB_ALIAS if not changelog_file: changelog_file = get_changelog_file_for_database(database) try: doc = minidom.parse(changelog_file) except ExpatError as ex: raise InvalidChangelogFile( 'Could not parse XML file %...
def find_target_migration_file(database=DEFAULT_DB_ALIAS, changelog_file=None)
Finds best matching target migration file
2.711394
2.702899
1.003143
if self._connection: return self._connection self.log.debug('Initializing connection to %s' % (self.bosh_service. netloc)) if self.bosh_service.scheme == 'http': Connection = httplib.HTTPConnection ...
def connection(self)
Returns an stablished connection
3.797057
3.682642
1.031069
if self._sid: return self._sid self.log.debug('Prepare to request BOSH session') data = self.send_request(self.get_body(sid_request=True)) if not data: return None # This is XML. response_body contains the <body/> element of the # respo...
def request_sid(self)
Request a BOSH session according to http://xmpp.org/extensions/xep-0124.html#session-request Returns the new SID (str).
3.672319
3.582809
1.024983
# Get a basic stanza body body = self.get_body() # Create a response tag and add the response content on it # using base64 encoding response_node = ET.SubElement(body, 'response') response_node.set('xmlns', XMPP_SASL_NS) response_node.text = base64.b6...
def send_challenge_response(self, response_plain)
Send a challenge response to server
4.316424
4.12792
1.045666
self.request_sid() self.log.debug('Prepare the XMPP authentication') # Instantiate a sasl object sasl = SASLClient( host=self.to, service='xmpp', username=self.jid, password=self.password ) # Choose an auth mech...
def authenticate_xmpp(self)
Authenticate the user to the XMPP server via the BOSH connection.
4.440542
4.22647
1.05065
name = StripParamName(name) return elem.getElements(lambda e: (e.tagName == ligolw.Param.tagName) and (e.Name == name))
def getParamsByName(elem, name)
Return a list of params with name name under elem.
16.241993
13.074935
1.242224
elem = Param() elem.Name = name elem.Type = type elem.pcdata = value # FIXME: I have no idea how most of the attributes should be # encoded, I don't even know what they're supposed to be. if dataunit is not None: elem.DataUnit = dataunit if scale is not None: elem.Scale = scale if start is not None: e...
def new_param(name, type, value, start = None, scale = None, unit = None, dataunit = None, comment = None)
Construct a LIGO Light Weight XML Param document subtree. FIXME: document keyword arguments.
3.480908
3.13922
1.108845
params = getParamsByName(xmldoc, name) if len(params) != 1: raise ValueError("document must contain exactly one %s param" % StripParamName(name)) return params[0]
def get_param(xmldoc, name)
Scan xmldoc for a param named name. Raises ValueError if not exactly 1 such param is found.
5.11082
4.294849
1.189988
return new_param(name, ligolwtypes.FromPyType[type(value)], value, **kwargs)
def from_pyvalue(name, value, **kwargs)
Convenience wrapper for new_param() that constructs a Param element from an instance of a Python builtin type. See new_param() for a description of the valid keyword arguments.
16.393021
11.235588
1.459026
return from_pyvalue(u"pickle:%s" % name, unicode(pickle.dumps(obj)))
def pickle_to_param(obj, name)
Return the top-level element of a document sub-tree containing the pickled serialization of a Python object.
14.275605
14.439922
0.988621
return pickle.loads(str(get_pyvalue(elem, u"pickle:%s" % name)))
def pickle_from_param(elem, name)
Retrieve a pickled Python object from the document tree rooted at elem.
12.662354
13.69904
0.924324
return from_pyvalue(u"yaml:%s" % name, unicode(yaml.dump(obj)))
def yaml_to_param(obj, name)
Return the top-level element of a document sub-tree containing the YAML serialization of a Python object.
14.42417
16.108564
0.895435
def startParam(self, parent, attrs): return Param(attrs) ContentHandler.startParam = startParam return ContentHandler
def use_in(ContentHandler)
Modify ContentHandler, a sub-class of pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Param class defined in this module when parsing XML documents. Example: >>> from pycbc_glue.ligolw import ligolw >>> def MyContentHandler(ligolw.LIGOLWContentHandler): ... pass ... >>> use_in(MyContentHandler)
8.373481
11.807152
0.709187
for i in _xrange(self.num_patterns): for c in self._available_connections[i]: yield c for c in self._in_use_connections[i]: yield c
def all_connections(self)
Returns a generator over all current connection objects
6.036404
5.66112
1.066292
self._checkpid() try: connection = self._available_connections[self._pattern_idx].pop() except IndexError: connection = self.make_connection() self._in_use_connections[self._pattern_idx].add(connection) self._next_pattern() return connecti...
def get_connection(self, command_name, *keys, **options)
Get a connection from the pool
5.276186
4.63661
1.137941
if self._created_connections[self._pattern_idx] >= self.max_connections_per_pattern: raise ConnectionError("Too many connections") self._created_connections[self._pattern_idx] += 1 conn = self.connection_class(**self.patterns[self._pattern_idx]) conn._pattern_idx = s...
def make_connection(self)
Create a new connection
3.369089
3.277678
1.027889
self._checkpid() if connection.pid == self.pid: idx = connection._pattern_idx self._in_use_connections[idx].remove(connection) self._available_connections[idx].append(connection)
def release(self, connection)
Releases the connection back to the pool
7.017701
6.319287
1.110521
self._checkpid() if connection.pid == self.pid: idx = connection._pattern_idx if connection in self._in_use_connections[idx]: self._in_use_connections[idx].remove(connection) else: self._available_connections[idx].remove(connec...
def purge(self, connection)
Remove the connection from rotation
5.136378
4.73138
1.085598
pool = self.connection_pool command_name = args[0] for i in _xrange(self.execution_attempts): connection = pool.get_connection(command_name, **options) try: connection.send_command(*args) res = self.parse_response(connection, comma...
def execute_command(self, *args, **options)
Execute a command and return a parsed response
3.395839
3.27118
1.038108
if verbose: if reverse: print >>sys.stderr, "sorting files from largest to smallest ..." else: print >>sys.stderr, "sorting files from smallest to largest ..." return sorted(filenames, key = (lambda filename: os.stat(filename)[stat.ST_SIZE] if filename is not None else 0), reverse = reverse)
def sort_files_by_size(filenames, verbose = False, reverse = False)
Return a list of the filenames sorted in order from smallest file to largest file (or largest to smallest if reverse is set to True). If a filename in the list is None (used by many pycbc_glue.ligolw based codes to indicate stdin), its size is treated as 0. The filenames may be any sequence, including generator ex...
2.353484
2.175986
1.081571
if url is None: return None scheme, host, path = urlparse.urlparse(url)[:3] if scheme.lower() not in ("", "file") or host.lower() not in ("", "localhost"): raise ValueError("%s is not a local file" % repr(url)) return path
def local_path_from_url(url)
For URLs that point to locations in the local filesystem, extract and return the filesystem path of the object to which they point. As a special case pass-through, if the URL is None, the return value is None. Raises ValueError if the URL is not None and does not point to a local file. Example: >>> print local...
2.820271
2.816781
1.001239
fileobj = MD5File(fileobj) md5obj = fileobj.md5obj if gz or gz is None: fileobj = RewindableInputFile(fileobj) magic = fileobj.read(2) fileobj.seek(0, os.SEEK_SET) if gz or magic == '\037\213': fileobj = gzip.GzipFile(mode = "rb", fileobj = fileobj) if xmldoc is None: xmldoc = ligolw.Document() ligo...
def load_fileobj(fileobj, gz = None, xmldoc = None, contenthandler = None)
Parse the contents of the file object fileobj, and return the contents as a LIGO Light Weight document tree. The file object does not need to be seekable. If the gz parameter is None (the default) then gzip compressed data will be automatically detected and decompressed, otherwise decompression can be forced on ...
3.561469
3.260685
1.092246
if verbose: print >>sys.stderr, "reading %s ..." % (("'%s'" % filename) if filename is not None else "stdin") if filename is not None: fileobj = open(filename, "rb") else: fileobj = sys.stdin xmldoc, hexdigest = load_fileobj(fileobj, **kwargs) if verbose: print >>sys.stderr, "md5sum: %s %s" % (hexdigest...
def load_filename(filename, verbose = False, **kwargs)
Parse the contents of the file identified by filename, and return the contents as a LIGO Light Weight document tree. stdin is parsed if filename is None. Helpful verbosity messages are printed to stderr if verbose is True. All other keyword arguments are passed to load_fileobj(), see that function for more infor...
2.840392
2.945669
0.96426
if verbose: print >>sys.stderr, "reading %s ..." % (("'%s'" % url) if url is not None else "stdin") if url is not None: scheme, host, path = urlparse.urlparse(url)[:3] if scheme.lower() in ("", "file") and host.lower() in ("", "localhost"): fileobj = open(path) else: fileobj = urllib2.urlopen(url) el...
def load_url(url, verbose = False, **kwargs)
Parse the contents of file at the given URL and return the contents as a LIGO Light Weight document tree. Any source from which Python's urllib2 library can read data is acceptable. stdin is parsed if url is None. Helpful verbosity messages are printed to stderr if verbose is True. All other keyword arguments a...
2.786925
2.645158
1.053595
# initialize SIGTERM and SIGTSTP trap deferred_signals = [] def newsigterm(signum, frame): deferred_signals.append(signum) oldhandlers = {} if trap_signals is not None: for sig in trap_signals: oldhandlers[sig] = signal.getsignal(sig) signal.signal(sig, newsigterm) # write the document with MD5File(...
def write_fileobj(xmldoc, fileobj, gz = False, trap_signals = (signal.SIGTERM, signal.SIGTSTP), **kwargs)
Writes the LIGO Light Weight document tree rooted at xmldoc to the given file object. Internally, the .write() method of the xmldoc object is invoked and any additional keyword arguments are passed to that method. The file object need not be seekable. The output data is gzip compressed on the fly if gz is True. ...
3.19884
3.146043
1.016782
if verbose: print >>sys.stderr, "writing %s ..." % (("'%s'" % filename) if filename is not None else "stdout") if filename is not None: if not gz and filename.endswith(".gz"): warnings.warn("filename '%s' ends in '.gz' but file is not being gzip-compressed" % filename, UserWarning) fileobj = open(filename,...
def write_filename(xmldoc, filename, verbose = False, gz = False, **kwargs)
Writes the LIGO Light Weight document tree rooted at xmldoc to the file name filename. Friendly verbosity messages are printed while doing so if verbose is True. The output data is gzip compressed on the fly if gz is True. Internally, write_fileobj() is used to perform the write. All additional keyword argumen...
2.801658
2.763452
1.013826
userStr = m.group(3) # print(userStr) imgURL = processString(userStr) # print(imgURL) el = etree.Element('img') # Sets imgURL to 'src' attribute of <img> tag element el.set('src', imgURL) el.set('alt', userStr) el.set('title', userS...
def handleMatch(self, m)
Handles user input into [magic] tag, processes it, and inserts the returned URL into an <img> tag through a Python ElementTree <img> Element.
5.000089
3.721742
1.343481
polls = [] for row in curDB.execute('SELECT id, title FROM Poll ORDER BY title'): polls.append({'id': row[0], 'name': row[1]}) return {'polls': polls}
def home(request)
Show the home page. Send the list of polls
5.146795
4.526292
1.137089
# Get the poll curDB.execute('SELECT id, title, description FROM Poll WHERE id = ? ORDER BY title', (pollId,)) poll = curDB.fetchone() if poll is None: return {} responses = [] totalVotes = 0 votedFor = 0 # Compute the list of responses curDB.execute('SELECT id, titl...
def show(request, pollId)
Show a poll. We send informations about votes only if the user is an administrator
3.070232
2.924504
1.04983
username = request.args.get('ebuio_u_username') # Remove old votes from the same user on the same poll curDB.execute('DELETE FROM Vote WHERE username = ? AND responseId IN (SELECT id FROM Response WHERE pollId = ?) ', (username, pollId)) # Save the vote curDB.execute('INSERT INTO Vote (user...
def vote(request, pollId, responseId)
Vote for a poll
7.515442
7.353105
1.022077
errors = [] success = False listOfResponses = ['', '', ''] # 3 Blank lines by default title = '' description = '' id = '' if request.method == 'POST': # User saved the form # Retrieve parameters title = request.form.get('title') description = request.form.get...
def create(request)
Create a new poll
3.537627
3.366307
1.050892
new = Type(sax.xmlreader.AttributesImpl({u"Name": Type.tableName}), **kwargs) colnamefmt = u":".join(Type.tableName.split(":")[:-1]) + u":%s" if columns is not None: for key in columns: if key not in new.validcolumns: raise ligolw.ElementError("invalid Column '%s' for Table '%s'" % (key, new.tableName)) ...
def New(Type, columns = None, **kwargs)
Construct a pre-defined LSC table. The optional columns argument is a sequence of the names of the columns the table should be constructed with. If columns = None, then the table is constructed with all valid columns (use columns = [] to create a table with no columns). Example: >>> import sys >>> tbl = New(...
3.601636
3.430914
1.04976
import warnings warnings.warn("lsctables.IsTableProperties() is deprecated. use pycbc_glue.ligolw.table.Table.CheckProperties() instead", DeprecationWarning) return Type.CheckProperties(tagname, attrs)
def IsTableProperties(Type, tagname, attrs)
obsolete. see .CheckProperties() method of pycbc_glue.ligolw.table.Table class.
8.216969
2.77674
2.959214
return any(t.Name not in TableByName for t in elem.getElementsByTagName(ligolw.Table.tagName))
def HasNonLSCTables(elem)
Return True if the document tree below elem contains non-LSC tables, otherwise return False.
24.049101
27.556801
0.87271
if ifos is None: return None if u"," in ifos: result = set(ifo.strip() for ifo in ifos.split(u",")) result.discard(u"") return result if u"+" in ifos: result = set(ifo.strip() for ifo in ifos.split(u"+")) result.discard(u"") return result ifos = ifos.strip() if len(ifos) > 2 and not len(ifos) % 2: ...
def instrument_set_from_ifos(ifos)
Parse the values stored in the "ifos" and "instruments" columns found in many tables. This function is mostly for internal use by the .instruments properties of the corresponding row classes. The mapping from input to output is as follows (rules are applied in order): input is None --> output is None input co...
3.271709
2.687441
1.217407
if instruments is None: return None _instruments = sorted(set(instrument.strip() for instrument in instruments)) # safety check: refuse to accept blank names, or names with commas # or pluses in them as they cannot survive the encode/decode # process if not all(_instruments) or any(u"," in instrument or u"+"...
def ifos_from_instrument_set(instruments)
Convert an iterable of instrument names into a value suitable for storage in the "ifos" column found in many tables. This function is mostly for internal use by the .instruments properties of the corresponding row classes. The input can be None or an iterable of zero or more instrument names, none of which may be...
5.094111
4.026098
1.265273
ContentHandler = table.use_in(ContentHandler) def startTable(self, parent, attrs, __orig_startTable = ContentHandler.startTable): name = table.StripTableName(attrs[u"Name"]) if name in TableByName: return TableByName[name](attrs) return __orig_startTable(self, parent, attrs) ContentHandler.startTable = ...
def use_in(ContentHandler)
Modify ContentHandler, a sub-class of pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Table classes defined in this module when parsing XML documents. Example: >>> from pycbc_glue.ligolw import ligolw >>> class MyContentHandler(ligolw.LIGOLWContentHandler): ... pass ... >>> use_in(MyContentHand...
5.127828
6.880834
0.745234
return set(row.process_id for row in self if row.program == program)
def get_ids_by_program(self, program)
Return a set containing the process IDs from rows whose program string equals the given program.
7.239309
3.718748
1.946706
seglists = segments.segmentlistdict() for row in self: ifos = row.instruments or (None,) if process_ids is None or row.process_id in process_ids: seglists.extend(dict((ifo, segments.segmentlist([row.in_segment])) for ifo in ifos)) return seglists
def get_in_segmentlistdict(self, process_ids = None)
Return a segmentlistdict mapping instrument to in segment list. If process_ids is a sequence of process IDs, then only rows with matching IDs are included otherwise all rows are included. Note: the result is not coalesced, each segmentlist contains the segments listed for that instrument as they appeared...
5.461194
5.417941
1.007983
seglists = segments.segmentlistdict() for row in self: ifos = row.instruments or (None,) if process_ids is None or row.process_id in process_ids: seglists.extend(dict((ifo, segments.segmentlist([row.out_segment])) for ifo in ifos)) return seglists
def get_out_segmentlistdict(self, process_ids = None)
Return a segmentlistdict mapping instrument to out segment list. If process_ids is a sequence of process IDs, then only rows with matching IDs are included otherwise all rows are included. Note: the result is not coalesced, each segmentlist contains the segments listed for that instrument as they appeare...
5.488761
5.293601
1.036867
# create string from instrument set instruments = ifos_from_instrument_set(instruments) # look for the ID for row in self: if (row.search_group, row.search, row.lars_id, row.instruments, row.gps_start_time, row.gps_end_time, row.comments) == (search_group, search, lars_id, instruments, gps_start_time, gp...
def get_expr_id(self, search_group, search, lars_id, instruments, gps_start_time, gps_end_time, comments = None)
Return the expr_def_id for the row in the table whose values match the givens. If a matching row is not found, returns None. @search_group: string representing the search group (e.g., cbc) @serach: string representing search (e.g., inspiral) @lars_id: string representing lars_id @instruments: the instrumen...
2.910483
2.835985
1.026269
# check if id already exists check_id = self.get_expr_id( search_group, search, lars_id, instruments, gps_start_time, gps_end_time, comments = comments ) if check_id: return check_id # experiment not found in table row = self.RowType() row.experiment_id = self.get_next_id() row.search_group = se...
def write_new_expr_id(self, search_group, search, lars_id, instruments, gps_start_time, gps_end_time, comments = None)
Creates a new def_id for the given arguments and returns it. If an entry already exists with these, will just return that id. @search_group: string representing the search group (e.g., cbc) @serach: string representing search (e.g., inspiral) @lars_id: string representing lars_id @instruments: the instrumen...
2.341116
2.370687
0.987526
row = [row for row in self if row.experiment_id == experiment_id] if len(row) > 1: raise ValueError("duplicate ids in experiment table") if len(row) == 0: raise ValueError("id '%s' not found in table" % experiment_id) return row[0]
def get_row_from_id(self, experiment_id)
Returns row in matching the given experiment_id.
2.733418
2.604542
1.049481
d = {} for row in self: if row.experiment_id not in d: d[row.experiment_id] = {} if (row.time_slide_id, row.veto_def_name, row.datatype, row.sim_proc_id) in d[row.experiment_id]: # entry already exists, raise error raise KeyError("duplicate entries in experiment_summary table") d[row.experim...
def as_id_dict(self)
Return table as a dictionary mapping experiment_id, time_slide_id, veto_def_name, and sim_proc_id (if it exists) to the expr_summ_id.
3.600955
2.042855
1.762708
# look for the ID for row in self: if (row.experiment_id, row.time_slide_id, row.veto_def_name, row.datatype, row.sim_proc_id) == (experiment_id, time_slide_id, veto_def_name, datatype, sim_proc_id): # found it return row.experiment_summ_id # if get to here, experiment not found in table return ...
def get_expr_summ_id(self, experiment_id, time_slide_id, veto_def_name, datatype, sim_proc_id = None)
Return the expr_summ_id for the row in the table whose experiment_id, time_slide_id, veto_def_name, and datatype match the given. If sim_proc_id, will retrieve the injection run matching that sim_proc_id. If a matching row is not found, returns None.
2.406189
2.326782
1.034127
# check if entry alredy exists; if so, return value check_id = self.get_expr_summ_id(experiment_id, time_slide_id, veto_def_name, datatype, sim_proc_id = sim_proc_id) if check_id: return check_id row = self.RowType() row.experiment_summ_id = self.get_next_id() row.experiment_id = experiment_id row....
def write_experiment_summ(self, experiment_id, time_slide_id, veto_def_name, datatype, sim_proc_id = None )
Writes a single entry to the experiment_summ table. This can be used for either injections or non-injection experiments. However, it is recommended that this only be used for injection experiments; for non-injection experiments write_experiment_summ_set should be used to ensure that an entry gets written for ev...
2.199566
2.168246
1.014445
for slide_id in time_slide_dict: # check if it's zero_lag or not if not any( time_slide_dict[slide_id].values() ): if write_all_data: self.write_experiment_summ( experiment_id, slide_id, veto_def_name, 'all_data', sim_proc_id = None ) if write_playground: self.write_experiment_summ( experim...
def write_non_injection_summary(self, experiment_id, time_slide_dict, veto_def_name, write_all_data = True, write_playground = True, write_exclude_play = True, return_dict = False)
Method for writing a new set of non-injection experiments to the experiment summary table. This ensures that for every entry in the experiment table, an entry for every slide is added to the experiment_summ table, rather than just an entry for slides that have events in them. Default is to write a 3 rows for z...
2.156185
1.889679
1.141033
for row in self: if row.experiment_summ_id != experiment_summ_id: continue if row.nevents is None: row.nevents = 0 if add_to_current: row.nevents += num_events return row.nevents else: row.nevents = num_events return row.nevents # if get to here, couldn't find experiment_...
def add_nevents(self, experiment_summ_id, num_events, add_to_current = True)
Add num_events to the nevents column in a specific entry in the table. If add_to_current is set to False, will overwrite the current nevents entry in the row with num_events. Otherwise, default is to add num_events to the current value. Note: Can subtract events by passing a negative number to num_events.
2.361353
2.288774
1.031711
experiment_summ_ids = [] for row in self: if row.coinc_event_id == coinc_event_id: experiment_summ_ids.append(row.experiment_summ_id) if len(experiment_summ_ids) == 0: raise ValueError("'%s' could not be found in the experiment_map table" % coinc_event_id) return experiment_summ_ids
def get_experiment_summ_ids( self, coinc_event_id )
Gets all the experiment_summ_ids that map to a given coinc_event_id.
2.109893
1.910985
1.104087
if column.lower() == 'q': return self.get_q else: return self.getColumnByName(column).asarray()
def get_column(self, column)
@returns: an array of column values for each row in the table @param column: name of column to return @returntype: numpy.ndarray
7.36267
7.681795
0.958457
if inplace: iterutils.inplace_filter(lambda row: row.ifo == ifo, self) return self else: ifoTrigs = self.copy() ifoTrigs.extend([row for row in self if row.ifo == ifo]) return ifoTrigs
def ifocut(self, ifo, inplace=False)
Return a SnglInspiralTable with rows from self having IFO equal to the given ifo. If inplace, modify self directly, else create a new table and fill it.
4.884891
4.973351
0.982213
slideTrigs = self.copy() slideTrigs.extend(row for row in self if row.get_slide_number() == slide_num) return slideTrigs
def getslide(self,slide_num)
Return the triggers with a specific slide number. @param slide_num: the slide number to recover (contained in the event_id)
6.19355
6.256979
0.989863
int_event_id = int(self.event_id) a = int_event_id // 1000000000 slidenum = (int_event_id % 1000000000) // 100000 b = int_event_id % 100000 return int(a), int(slidenum), int(b)
def get_id_parts(self)
Return the three pieces of the int_8s-style sngl_inspiral event_id.
2.644449
2.387264
1.107732
a, slide_number, b = self.get_id_parts() if slide_number > 5000: slide_number = 5000 - slide_number return slide_number
def get_slide_number(self)
Return the slide-number for this trigger
4.633401
4.309993
1.075037
null_snr_sq = self.get_coinc_snr()**2 - self.get_column('snr')**2 null_snr_sq[null_snr_sq < 0] = 0. return null_snr_sq**(1./2.)
def get_null_snr(self)
Get the coherent Null SNR for each row in the table.
3.877131
3.667233
1.057236
if len(self): if not instruments: instruments = map(str, \ instrument_set_from_ifos(self[0].ifos)) return dict((ifo, self.get_sigmasq(ifo))\ for ifo in instruments) else: return dict()
def get_sigmasqs(self, instruments=None)
Return dictionary of single-detector sigmas for each row in the table.
5.071263
5.338385
0.949962
if len(self) and instruments is None: instruments = map(str, \ instrument_set_from_ifos(self[0].ifos)) elif instruments is None: instruments = [] return dict((ifo, self.get_sngl_snr(ifo))\ for ifo in instruments)
def get_sngl_snrs(self, instruments=None)
Get the single-detector SNRs for each row in the table.
4.906269
4.752633
1.032326
if len(self) and instruments is None: instruments = map(str, \ instrument_set_from_ifos(self[0].ifos)) elif instruments is None: instruments = [] return dict((ifo, self.get_sngl_chisq(ifo))\ for ifo in instruments)
def get_sngl_chisqs(self, instruments=None)
Get the single-detector \chi^2 for each row in the table.
4.806878
4.752566
1.011428
if len(self) and instruments is None: instruments = map(str, \ instrument_set_from_ifos(self[0].ifos)) elif instruments is None: instruments = [] return dict((ifo, self.get_sngl_bank_chisq(ifo))\ for ifo in instruments)
def get_sngl_bank_chisqs(self, instruments=None)
Get the single-detector \chi^2 for each row in the table.
4.659118
4.533125
1.027794
if len(self) and instruments is None: instruments = map(str, \ instrument_set_from_ifos(self[0].ifos)) elif instruments is None: instruments = [] return dict((ifo, self.get_sngl_cont_chisq(ifo))\ for ifo in instruments)
def get_sngl_cont_chisqs(self, instruments=None)
Get the single-detector \chi^2 for each row in the table.
4.598063
4.582644
1.003365
return [row.get_bestnr(index=index, nhigh=nhigh, null_snr_threshold=null_snr_threshold, null_grad_thresh=null_grad_thresh, null_grad_val=null_grad_val) for row in self]
def get_bestnr(self, index=4.0, nhigh=3.0, null_snr_threshold=4.25,\ null_grad_thresh=20., null_grad_val = 1./5.)
Get the BestNR statistic for each row in the table
1.990518
1.853199
1.074099
null_snr_sq = (numpy.asarray(self.get_sngl_snrs().values())**2)\ .sum() - self.snr**2 if null_snr_sq < 0: return 0 else: return null_snr_sq**(1./2.)
def get_null_snr(self)
Get the coherent Null SNR for this row.
4.500538
4.269782
1.054044
return dict((ifo, self.get_sngl_snr(ifo)) for ifo in\ instrument_set_from_ifos(self.ifos))
def get_sngl_snrs(self)
Return a dictionary of single-detector SNRs for this row.
9.019319
8.014303
1.125403
# weight SNR by chisq bestnr = self.get_new_snr(index=index, nhigh=nhigh, column="chisq") if len(self.get_ifos()) < 3: return bestnr # recontour null SNR threshold for higher SNRs if self.snr > null_grad_thresh: null_snr_threshold += (self.snr - null_grad_thresh) * null_gr...
def get_bestnr(self, index=4.0, nhigh=3.0, null_snr_threshold=4.25,\ null_grad_thresh=20., null_grad_val = 1./5.)
Return the BestNR statistic for this row.
3.60675
3.727757
0.967539
if segment_def_id is None: return segments.segmentlist(row.segment for row in self) return segments.segmentlist(row.segment for row in self if row.segment_def_id == segment_def_id)
def get(self, segment_def_id = None)
Return a segmentlist object describing the times spanned by the segments carrying the given segment_def_id. If segment_def_id is None then all segments are returned. Note: the result is not coalesced, the segmentlist contains the segments as they appear in the table.
3.459734
3.002835
1.152156
d = {} for row in self: if row.time_slide_id not in d: d[row.time_slide_id] = offsetvector.offsetvector() if row.instrument in d[row.time_slide_id]: raise KeyError("'%s': duplicate instrument '%s'" % (row.time_slide_id, row.instrument)) d[row.time_slide_id][row.instrument] = row.offset return ...
def as_dict(self)
Return a ditionary mapping time slide IDs to offset dictionaries.
3.368999
2.430494
1.386138
time_slide_id = self.get_next_id() for instrument, offset in offsetvect.items(): row = self.RowType() row.process_id = process.process_id row.time_slide_id = time_slide_id row.instrument = instrument row.offset = offset self.append(row) return time_slide_id
def append_offsetvector(self, offsetvect, process)
Append rows describing an instrument --> offset mapping to this table. offsetvect is a dictionary mapping instrument to offset. process should be the row in the process table on which the new time_slide table rows will be blamed (or any object with a process_id attribute). The return value is the time_slid...
3.212303
1.956063
1.642229
# look for matching offset vectors if superset_ok: ids = [id for id, slide in self.as_dict().items() if offsetdict == dict((instrument, offset) for instrument, offset in slide.items() if instrument in offsetdict)] else: ids = [id for id, slide in self.as_dict().items() if offsetdict == slide] if len(id...
def get_time_slide_id(self, offsetdict, create_new = None, superset_ok = False, nonunique_ok = False)
Return the time_slide_id corresponding to the offset vector described by offsetdict, a dictionary of instrument/offset pairs. If the optional create_new argument is None (the default), then the table must contain a matching offset vector. The return value is the ID of that vector. If the table does not c...
2.833968
2.570298
1.102583
# look for the ID rows = [row for row in self if (row.search, row.search_coinc_type) == (search, search_coinc_type)] if len(rows) > 1: raise ValueError("(search, search coincidence type) = ('%s', %d) is not unique" % (search, search_coinc_type)) if len(rows) > 0: return rows[0].coinc_def_id # coinc ...
def get_coinc_def_id(self, search, search_coinc_type, create_new = True, description = None)
Return the coinc_def_id for the row in the table whose search string and search_coinc_type integer have the values given. If a matching row is not found, the default behaviour is to create a new row and return the ID assigned to the new row. If, instead, create_new is False then KeyError is raised when a ma...
2.328696
2.19329
1.061736
for i, seg in enumerate(seglist): seglist[i] = seg.__class__(seg[0] - self.low_window, seg[1] + self.high_window)
def apply_to_segmentlist(self, seglist)
Apply our low and high windows to the segments in a segmentlist.
3.711482
2.796361
1.327254
primary.configure_bound(surface_size) secondary.configure_bound(surface_size) # Check for key size. if (primary.key_size < secondary.key_size): logging.warning('Normalizing key size from secondary to primary') secondary.key_size = primary.key_size elif (primary.key_size > second...
def synchronizeLayout(primary, secondary, surface_size)
Synchronizes given layouts by normalizing height by using max height of given layouts to avoid transistion dirty effects. :param primary: Primary layout used. :param secondary: Secondary layout used. :param surface_size: Target surface size on which layout will be displayed.
2.193215
2.325987
0.942918
if isinstance(key, VSpaceKey): self.draw_space_key(surface, key) elif isinstance(key, VBackKey): self.draw_back_key(surface, key) elif isinstance(key, VUppercaseKey): self.draw_uppercase_key(surface, key) elif isinstance(key, VSpecialCharKey):...
def draw_key(self, surface, key)
Default drawing method for key. Draw the key accordingly to it type. :param surface: Surface background should be drawn in. :param key: Target key to be drawn.
2.107979
2.242154
0.940158
background_color = self.key_background_color if special and self.special_key_background_color is not None: background_color = self.special_key_background_color pygame.draw.rect(surface, background_color[key.state], key.position + key.size) size = self.font.size(key.v...
def draw_character_key(self, surface, key, special=False)
Default drawing method for key. Key is drawn as a simple rectangle filled using this cell style background color attribute. Key value is printed into drawn cell using internal font. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. ...
1.971418
2.004431
0.98353
key.value = u'\u21e7' if key.is_activated(): key.value = u'\u21ea' self.draw_character_key(surface, key, True)
def draw_uppercase_key(self, surface, key)
Default drawing method for uppercase key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn.
6.320904
6.723629
0.940103
key.value = u'#' if key.is_activated(): key.value = u'Ab' self.draw_character_key(surface, key, True)
def draw_special_char_key(self, surface, key)
Default drawing method for special char key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn.
10.032525
11.050099
0.907913
return position[0] >= self.position[0] and position[0] <= self.position[0]+ self.size[0]
def is_touched(self, position)
Hit detection method. Indicates if this key has been hit by a touch / click event at the given position. :param position: Event position. :returns: True is the given position collide this key, False otherwise.
3.382499
4.572761
0.739706
if first: self.keys = [key] + self.keys else: self.keys.append(key) if isinstance(key, VSpaceKey): self.space = key
def add_key(self, key, first=False)
Adds the given key to this row. :param key: Key to be added to this row. :param first: BOolean flag that indicates if key is added at the beginning or at the end.
3.770093
5.041366
0.747832
self.height = size self.position = position x = position[0] for key in self.keys: key.set_size(size) key.position = (x, position[1]) x += padding + key.size[0]
def set_size(self, position, size, padding)
Row size setter. The size correspond to the row height, since the row width is constraint to the surface width the associated keyboard belongs. Once size is settled, the size for each child keys is associated. :param position: Position of this row. :param size: Size of ...
3.462719
3.257188
1.063101
special_row = VKeyRow() max_length = self.max_length i = len(self.rows) - 1 current_row = self.rows[i] special_keys = [VBackKey()] if self.allow_uppercase: special_keys.append(VUppercaseKey(keyboard)) if self.allow_special_chars: special_keys.append(VSpec...
def configure_specials_key(self, keyboard)
Configures specials key if needed. :param keyboard: Keyboard instance this layout belong.
2.635853
2.755975
0.956414
r = len(self.rows) max_length = self.max_length if self.key_size is None: self.key_size = (surface_size[0] - (self.padding * (max_length + 1))) / max_length height = self.key_size * r + self.padding * (r + 1) if height >= surface_size[1] / 2: logg...
def configure_bound(self, surface_size)
Compute keyboard bound regarding of this layout. If key_size is None, then it will compute it regarding of the given surface_size. :param surface_size: Size of the surface this layout will be rendered on. :raise ValueError: If the layout model is empty.
3.331622
3.166334
1.052202
self.size = size self.position = (0, surface_size[1] - self.size[1]) y = self.position[1] + self.padding max_length = self.max_length for row in self.rows: r = len(row) width = (r * self.key_size) + ((r + 1) * self.padding) x = (surfac...
def set_size(self, size, surface_size)
Sets the size of this layout, and updates position, and rows accordingly. :param size: Size of this layout. :param surface_size: Target surface size on which layout will be displayed.
2.901448
2.888222
1.004579
for row in self.rows: for key in row.keys: key.state = 0
def invalidate(self)
Rests all keys states.
8.558398
4.66045
1.836389
for row in self.rows: for key in row.keys: if type(key) == VKey: if uppercase: key.value = key.value.upper() else: key.value = key.value.lower()
def set_uppercase(self, uppercase)
Sets layout uppercase state. :param uppercase: True if uppercase, False otherwise.
3.15875
3.404165
0.927907
for row in self.rows: if position in row: for key in row.keys: if key.is_touched(position): return key return None
def get_key_at(self, position)
Retrieves if any key is located at the given position :param position: Position to check key at. :returns: The located key if any at the given position, None otherwise.
4.770286
5.316402
0.897277
if self.state > 0: self.renderer.draw_background(self.surface, self.layout.position, self.layout.size) for row in self.layout.rows: for key in row.keys: self.renderer.draw_key(self.surface, key)
def draw(self)
Draw the virtual keyboard into the delegate surface object if enabled.
4.112011
3.068565
1.340044
self.uppercase = not self.uppercase self.original_layout.set_uppercase(self.uppercase) self.special_char_layout.set_uppercase(self.uppercase) self.invalidate()
def on_uppercase(self)
Uppercase key press handler.
4.650254
4.051533
1.147776
self.special_char = not self.special_char if self.special_char: self.set_layout(self.special_char_layout) else: self.set_layout(self.original_layout) self.invalidate()
def on_special_char(self)
Special char key press handler.
2.772095
2.528632
1.096283
if self.state > 0: if event.type == MOUSEBUTTONDOWN: key = self.layout.get_key_at(pygame.mouse.get_pos()) if key is not None: self.on_key_down(key) elif event.type == MOUSEBUTTONUP: self.on_key_up() ...
def on_event(self, event)
Pygame event processing callback method. :param event: Event to process.
3.46828
3.689405
0.940065
key.state = state self.renderer.draw_key(self.surface, key)
def set_key_state(self, key, state)
Sets the key state and redraws it. :param key: Key to update state for. :param state: New key state.
9.190198
11.623043
0.790688
if (self.last_pressed is not None): self.set_key_state(self.last_pressed, 0) self.buffer = self.last_pressed.update_buffer(self.buffer) self.text_consumer(self.buffer) self.last_pressed = None
def on_key_up(self)
Process key up event by updating buffer and release key.
4.425284
3.838511
1.152865