code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
builder.start(tag, {}) builder.data(content) # Must be UTF-8 encoded builder.end(tag)
def make_element(builder, tag, content)
Make an element with this tag and text content
4.121951
4.200968
0.981191
if isinstance(other, trigger_klass): # Check property exists if not hasattr(self, property_name): raise AttributeError("%s has no property %s" % (self.__class__.__name__, property_name)) if getattr(self, property_name) is None: seta...
def set_single_attribute(self, other, trigger_klass, property_name)
Used to set guard the setting of an attribute which is singular and can't be set twice
2.712018
2.660204
1.019477
# Check property exists if isinstance(other, trigger_klass): if not hasattr(self, property_name): raise AttributeError("%s has no property %s" % (self.__class__.__name__, property_name)) val = getattr(self, property_name, []) if other in val...
def set_list_attribute(self, other, trigger_klass, property_name)
Used to set guard the setting of a list attribute, ensuring the same element is not added twice.
2.367312
2.322558
1.019269
if value is not None: if value not in self.ALLOWED_TRANSACTION_TYPES: raise AttributeError('%s transaction_type element must be one of %s not %s' % ( self.__class__.__name__, ','.join(self.ALLOWED_TRANSACTION_TYPES), value,)) self._transaction_typ...
def transaction_type(self, value)
Set the TransactionType (with Input Validation)
2.964011
2.986758
0.992384
params = {} if self.study_oid: params.update(dict(StudyOID=self.study_oid)) builder.start("AdminData", params) for user in self.users: user.build(builder) for location in self.locations: location.build(builder) builder.end("Ad...
def build(self, builder)
Build XML by appending to builder
4.331917
3.706474
1.168743
params = dict(StudyOID=self.study_oid, MetaDataVersionOID=self.metadata_version_oid, EffectiveDate=dt_to_iso8601(self.effective_date)) builder.start("MetaDataVersionRef", params) builder.end("MetaDataVersionRef")
def build(self, builder)
Build XML by appending to builder
4.996196
4.601518
1.085771
params = dict(OID=self.oid, Name=self.name) if self.location_type: params.update(dict(LocationType=self.location_type.value)) # mixins self.mixin() self.mixin_params(params) builder.start("Location", params) for mdv in se...
def build(self, builder)
Build XML by appending to builder
4.981524
4.824369
1.032575
params = dict() builder.start(self.__class__.__name__, params) for street in self.street_names: street.build(builder) # build the children for child in ('city', 'country', 'state_prov', 'postal_code', 'other_text'): if getattr(self, child) is not ...
def build(self, builder)
Build XML by appending to builder
4.022997
3.598768
1.117882
params = dict(OID=self.oid) if self.user_type: params.update(dict(UserType=self.user_type.value)) builder.start(self.__class__.__name__, params) # build the children for child in ('login_name', 'display_name', 'full_name', 'first_name', 'last_name', ...
def build(self, builder)
Build XML by appending to builder
2.580266
2.498869
1.032574
builder.start(self.__class__.__name__) builder.data(self.country_code) builder.end(self.__class__.__name__)
def build(self, builder)
Build this element :param builder: :return:
4.489869
4.486892
1.000663
link = self.rws_connection.last_result.links.get("next", None) if link: link = link['url'] p = urlparse(link) start_id = int(parse_qs(p.query)['startid'][0]) return start_id return None
def get_next_start_id(self)
If link for next result set has been passed, extract it and get the next set start id
4.755086
3.687882
1.289381
odm = ODM("test system")( ClinicalData("Mediflex", "DEV")( SubjectData("MDSOL", "IJS TEST4", transaction_type="Insert")( StudyEventData("SUBJECT")( FormData("EN", transaction_type="Update")( # Although Signature is ODM1.3.1 RWS does not support ...
def example_clinical_data(study_name, environment)
Test demonstrating building clinical data
16.850641
16.925661
0.995568
f = StringIO(data[:-4]) # Remove \nEOF return reader_type(f)
def getCSVReader(data, reader_type=csv.DictReader)
Take a Rave CSV output ending with a line with just EOF on it and return a DictReader
13.79978
8.970673
1.538322
# Pull the lot into a list cols = list(self.getCSVReader(metadata)) # sort the cols by view name and ordinal (they come sorted, but lets be sure) cols.sort(key=lambda x: [x['viewname'], int(x['ordinal'])]) # Now group them by their viewname for key, grp in grou...
def _setDatasets(self, metadata)
Extract dataset definitions from CSV metadata
7.698493
7.098915
1.084461
# Get the cols for this dataset cols = self.datasets[dataset_name] reader = self.getCSVReader(data, reader_type=csv.reader) # Get fieldnames from first line of reader, what is left is set of rows fieldnames = next(reader) # Check columns for col in col...
def processFormData(self, data, dataset_name)
Take a string of form data as CSV and convert to insert statements, return template and data values
6.523349
6.853505
0.951827
sql_statements = self._generateDDL() logging.info('Generating sqllite tables') for stmt in sql_statements: c = self.conn.cursor() c.execute(stmt) self.conn.commit()
def _processDDL(self)
Generate and process table SQL, SQLLite version
4.403897
3.980414
1.106392
sql = [] # Next convert each set of columns into a table structure for dataset_name in sorted(self.datasets.keys()): # SQL to drop the table if it already exists sql.append('''drop table if exists %s;''' % dataset_name) # Generate the SQL for the co...
def _generateDDL(self)
Generate DDL statements for SQLLite
3.831887
3.730486
1.027182
sql_template = self._generateInsertStatement(dataset_name, cols) # Now insert in batch, reader is a list of rows to insert at this point c = self.conn.cursor() c.executemany(sql_template, reader) self.conn.commit()
def _processDML(self, dataset_name, cols, reader)
Overridden version of create DML for SQLLite
5.559908
5.108251
1.088417
col_names = [col["varname"] for col in cols] # Generate question mark placeholders qms = ','.join(['?' for x in col_names]) return 'INSERT INTO %s (%s) values (%s)' % (dataset_name, ','.join(col_names), qms)
def _generateInsertStatement(self, dataset_name, cols)
Generates a sql INSERT template
4.252611
3.984256
1.067354
matched = VIEW_REX.match(viewname) return matched.group('view'), matched.group('type') or 'REGULAR'
def name_type_from_viewname(viewname)
Have format V_<studyname>_<view>[_RAW], return name and view type REGULAR or RAW
7.423831
5.019636
1.478958
logging.info('Requesting view metadata for project %s' % self.project_name) project_csv_meta = self.rws_connection.send_request(ProjectMetaDataRequest(self.project_name)) # Process it into a set of tables self.db_adapter.processMetaData(project_csv_meta) # Get the dat...
def execute(self)
Generate local DB, pulling metadata and data from RWSConnection
4.810661
4.189889
1.148159
# Test if value is a date for format in ['%d %b %Y', '%b %Y', '%Y', '%d %m %Y', '%m %Y', '%d/%b/%Y', '%b/%Y', '%d/%m/%Y', '%m/%Y']: try: datetime.datetime.strptime(value, format) if len(value) == 4 and (int(value) < 1900 or int(value) > 2030): break ...
def typeof_rave_data(value)
Function to duck-type values, not relying on standard Python functions because, for example, a string of '1' should be typed as an integer and not as a string or float since we're trying to replace like with like when scrambling.
2.167428
2.174061
0.996949
if sd == 0: return str(fake.random_number(length)) else: return str(fake.pyfloat(length - sd, sd, positive=True))
def scramble_float(self, length, sd=0)
Return random float in specified format
4.574002
4.446121
1.028762
# faker method signature changed if value == '': # handle the empty string by defaulting to 'now' and 1 year ago end_date = 'now' start_date = '-1y' else: # specified end date, and one year prior end_date = datetime.datetime.st...
def scramble_date(self, value, format='%d %b %Y')
Return random date
4.332359
4.206019
1.030038
return fake.text(length) if length > 5 else ''.join([fake.random_letter() for n in range(0, length)])
def scramble_string(self, length)
Return random string
7.587171
7.247737
1.046833
try: type, format = typeof_rave_data(value) if type == 'float': i, f = value.split('.') return self.scramble_float(len(value) - 1, len(f)) elif type == 'int': return self.scramble_int(len(value)) elif type =...
def scramble_value(self, value)
Duck-type value and scramble appropriately
3.220855
3.115422
1.033842
# TODO: External code lists path = ".//{0}[@{1}='{2}']".format(E_ODM.CODELIST.value, A_ODM.OID.value, codelist) elem = self.metadata.find(path) codes = [] for c in elem.iter(E_ODM.CODELIST_ITEM.value): codes.append(c.get(A_ODM.CODED_VALUE.value)) for...
def scramble_codelist(self, codelist)
Return random element from code list
3.874967
3.53817
1.095189
if self.metadata is not None: path = ".//{0}[@{1}='{2}']".format(E_ODM.ITEM_DEF.value, A_ODM.OID.value, oid) elem = self.metadata.find(path) # for elem in self.metadata.iter(E_ODM.ITEM_DEF.value): datatype = elem.get(A_ODM.DATATYPE.value) cod...
def scramble_itemdata(self, oid, value)
If metadata provided, use it to scramble the value based on data type
2.287541
2.233566
1.024165
odm_elements = etree.fromstring(input) for v in odm_elements.iter(E_ODM.ITEM_DATA.value): if v.get(A_ODM.VALUE.value) == "": oid = v.get(A_ODM.ITEM_OID.value) if fixed_values is not None and oid in fixed_values: d = fixed_values[...
def fill_empty(self, fixed_values, input)
Fill in random values for all empty-valued ItemData elements in an ODM document
2.164843
1.984638
1.0908
if isinstance(value, six.string_types): if not value.strip(): return missing elif value is None: return missing return int(value)
def make_int(value, missing=-1)
Convert string value to long, '' to missing
2.655234
2.835823
0.936319
parser = etree.XMLParser(target=ODMTargetParser(eventer)) return etree.XML(data, parser)
def parse(data, eventer)
Parse the XML data, firing events from the eventer
7.44473
6.996494
1.064066
self.count += 1 # event_name = 'on_{0}'.format(self.context.subcategory.lower()) event_name = self.context.subcategory if hasattr(self.handler, event_name): getattr(self.handler, event_name)(self.context) elif hasattr(self.handler, 'default'): s...
def emit(self)
We are finished processing one element. Emit it
3.811208
3.608309
1.056231
return {AUDIT_REF_STATE: self.context.audit_record, SIGNATURE_REF_STATE: self.context.signature}[self.ref_state]
def get_parent_element(self)
Signatures and Audit elements share sub-elements, we need to know which to set attributes on
14.649889
8.854317
1.654548
if self.state == STATE_SOURCE_ID: self.context.audit_record.source_id = int(data) # Audit ids can be 64 bits elif self.state == STATE_DATETIME: dt = datetime.datetime.strptime(data, "%Y-%m-%dT%H:%M:%S") self.get_parent_element().datetimestamp = dt el...
def data(self, data)
Called for text between tags
5.535948
5.23245
1.058003
def empty_validator(field, data): if isinstance(field.value, str) and not field.value.strip(): raise ValidationError('empty') return empty_validator
def validate_not_empty()
Validate that a field is not empty (blank string). :raises: ``ValidationError('empty')``
4.701606
4.394783
1.069815
def length_validator(field, data): if field.value is None: return if equal is not None and len(field.value) != equal: raise ValidationError('length_equal', equal=equal) if low is not None and len(field.value) < low: key = 'length_low' if high is None ...
def validate_length(low=None, high=None, equal=None)
Validate the length of a field with either low, high, or equal. Should work with anything that supports len(). :param low: Smallest length required. :param high: Longest length required. :param equal: Exact length required. :raises: ``ValidationError('length_low')`` :raises: ``ValidationError('...
1.938989
1.794601
1.080457
def one_of_validator(field, data): if field.value is None: return options = values if callable(options): options = options() if field.value not in options: raise ValidationError('one_of', choices=', '.join(map(str, options))) return one_of...
def validate_one_of(values)
Validate that a field is in one of the given values. :param values: Iterable of valid values. :raises: ``ValidationError('one_of')``
3.966399
3.625738
1.093956
def none_of_validator(field, data): options = values if callable(options): options = options() if field.value in options: raise ValidationError('none_of', choices=str.join(', ', options)) return none_of_validator
def validate_none_of(values)
Validate that a field is not in one of the given values. :param values: Iterable of invalid values. :raises: ``ValidationError('none_of')``
5.551199
5.206367
1.066233
def range_validator(field, data): if field.value is None: return if low is not None and field.value < low: key = 'range_low' if high is None else 'range_between' raise ValidationError(key, low=low, high=high) if high is not None and field.value > high...
def validate_range(low=None, high=None)
Validate the range of a field with either low, high, or equal. Should work with anything that supports '>' and '<' operators. :param low: Smallest value required. :param high: Longest value required. :raises: ``ValidationError('range_low')`` :raises: ``ValidationError('range_high')`` :raises: `...
2.237762
2.038628
1.097681
def equal_validator(field, data): if field.value is None: return if not (field.value == value): raise ValidationError('equal', other=value) return equal_validator
def validate_equal(value)
Validate the field value is equal to the given value. Should work with anything that supports '==' operator. :param value: Value to compare. :raises: ``ValidationError('equal')``
5.69032
4.956896
1.14796
def matches_validator(field, data): if field.value is None: return if not (field.value == data.get(other)): raise ValidationError('matches', other=other) return matches_validator
def validate_matches(other)
Validate the field value is equal to another field in the data. Should work with anything that supports '==' operator. :param value: Field key to compare. :raises: ``ValidationError('matches')``
6.308249
4.137673
1.524588
regex = re.compile(pattern, flags) if isinstance(pattern, str) else pattern def regexp_validator(field, data): if field.value is None: return if regex.match(str(field.value)) is None: raise ValidationError('regexp', pattern=pattern) return regexp_validator
def validate_regexp(pattern, flags=0)
Validate the field matches the given regular expression. Should work with anything that supports '==' operator. :param pattern: Regular expresion to match. String or regular expression instance. :param pattern: Flags for the regular expression. :raises: ``ValidationError('equal')``
3.172353
3.940719
0.805019
def function_validator(field, data): if field.value is None: return if not method(field.value, **kwargs): raise ValidationError('function', function=method.__name__) return function_validator
def validate_function(method, **kwargs)
Validate the field matches the result of calling the given method. Example:: def myfunc(value, name): return value == name validator = validate_function(myfunc, name='tim') Essentially creates a validator that only accepts the name 'tim'. :param method: Method to call. :param...
5.651637
4.670118
1.21017
user_regex = re.compile( r"(^[-!#$%&'*+/=?^`{}|~\w]+(\.[-!#$%&'*+/=?^`{}|~\w]+)*$" r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]' r'|\\[\001-\011\013\014\016-\177])*"$)', re.IGNORECASE | re.UNICODE) domain_regex = re.compile( r'(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+' ...
def validate_email()
Validate the field is a valid email address. :raises: ``ValidationError('email')``
1.540689
1.556507
0.989837
def unique_validator(field, data): # If we have a PK, ignore it because it represents the current record. query = queryset.where(lookup_field == field.value) if pk_field and pk_value: query = query.where(~(pk_field == pk_value)) if query.count(): raise Va...
def validate_model_unique(lookup_field, queryset, pk_field=None, pk_value=None)
Validate the field is a unique, given a queryset and lookup_field. Example:: validator = validate_model_unique(User.email, User.select()) Creates a validator that can validate the uniqueness of an email address. :param lookup_field: Peewee model field that should be used for checking existing values....
4.931944
4.162824
1.184759
if isinstance(value, dict): return value.get(lookup_field.name) if isinstance(value, peewee.Model): return getattr(value, lookup_field.name) return value
def coerce_single_instance(lookup_field, value)
Convert from whatever value is given to a scalar value for lookup_field. If value is a dict, then lookup_field.name is used to get the value from the dict. Example: lookup_field.name = 'id' value = {'id': 123, 'name': 'tim'} returns = 123 If value is a model, then lookup_field.name is ex...
2.940575
2.293866
1.281929
if isinstance(value, str): return False return isinstance(value, Iterable) or isgeneratorfunction(value) or isgenerator(value)
def isiterable_notstring(value)
Returns True if the value is iterable but not a string. Otherwise returns False. :param value: Value to check.
3.473378
4.912781
0.707009
if name in data: return data.get(name) if self.default: if callable(self.default): return self.default() return self.default return None
def get_value(self, name, data)
Get the value of this field from the data. If there is a problem with the data, raise ValidationError. :param name: Name of this field (to retrieve from data). :param data: Dictionary of data for all fields. :raises: ValidationError :return: The value of this field. :rty...
2.747582
3.219484
0.853423
self.value = self.get_value(name, data) if self.value is not None: self.value = self.coerce(self.value) for method in self.validators: method(self, data)
def validate(self, name, data)
Check to make sure ths data for this field is valid. Usually runs all validators in self.validators list. If there is a problem with the data, raise ValidationError. :param name: The name of this field. :param data: Dictionary of data for all fields. :raises: ValidationError
3.422751
3.49615
0.979006
super().validate(name, data) if self.value is not None: try: self.value = self.query.get(self.lookup_field == self.value) except (AttributeError, ValueError, peewee.DoesNotExist): raise ValidationError('related', field=self.lookup_field.na...
def validate(self, name, data)
If there is a problem with the data, raise ValidationError. :param name: The name of this field. :param data: Dictionary of data for all fields. :raises: ValidationError
5.388364
5.998758
0.898247
if isinstance(value, dict): value = [value] if not isiterable_notstring(value): value = [value] return [coerce_single_instance(self.lookup_field, v) for v in value]
def coerce(self, value)
Convert from whatever is given to a list of scalars for the lookup_field.
4.649722
3.462939
1.34271
for field in dir(self): obj = getattr(self, field) if isinstance(obj, Field): self._meta.fields[field] = obj
def initialize_fields(self)
The dict self.base_fields is a model instance at this point. Turn it into an instance attribute on this meta class. Also intitialize any other special fields if needed in sub-classes. :return: None
3.261265
3.932013
0.829413
only = only or [] exclude = exclude or [] data = data or {} self.errors = {} self.data = {} # Validate individual fields. for name, field in self._meta.fields.items(): if name in exclude or (only and name not in only): continu...
def validate(self, data=None, only=None, exclude=None)
Validate the data for all fields and return whether the validation was successful. This method also retains the validated data in ``self.data`` so that it can be accessed later. This is usually the method you want to call after creating the validator instance. :param data: Dictionary of data t...
2.672743
2.863264
0.93346
for name, value in data.items(): try: method = getattr(self, 'clean_{}'.format(name), None) if method: self.data[name] = method(value) except ValidationError as err: self.add_error(name, err) con...
def clean_fields(self, data)
For each field, check to see if there is a clean_<name> method. If so, run that method and set the returned value on the self.data dict. This happens after all validations so that each field can act on the cleaned data of other fields if needed. :param data: Dictionary of data to clean....
2.67945
2.498293
1.072512
# # Pull all the "normal" fields off the model instance meta. for name, field in self.instance._meta.fields.items(): if getattr(field, 'primary_key', False): continue self._meta.fields[name] = self.convert_field(name, field) # Many-to-many fields...
def initialize_fields(self)
Convert all model fields to validator fields. Then call the parent so that overwrites can happen if necessary for manually defined fields. :return: None
3.602762
3.50481
1.027948
if PEEWEE3: field_type = field.field_type.lower() else: field_type = field.db_field pwv_field = ModelValidator.FIELD_MAP.get(field_type, StringField) print('pwv_field', field_type, pwv_field) validators = [] required = not bool(getattr(...
def convert_field(self, name, field)
Convert a single field from a Peewee model field to a validator field. :param name: Name of the field as defined on this validator. :param name: Peewee field instance. :return: Validator field.
2.95445
2.806451
1.052736
data = data or {} only = only or self._meta.only exclude = exclude or self._meta.exclude for name, field in self.instance._meta.fields.items(): if name in exclude or (only and name not in only): continue try: data.setdefau...
def validate(self, data=None, only=None, exclude=None)
Validate the data for all fields and return whether the validation was successful. This method also retains the validated data in ``self.data`` so that it can be accessed later. If data for a field is not provided in ``data`` then this validator will check against the provided model instance. ...
3.499199
3.545214
0.987021
# Build a list of dict containing query values for each unique index. index_data = [] for columns, unique in self.instance._meta.indexes: if not unique: continue index_data.append({col: data.get(col, None) for col in columns}) # Then quer...
def perform_index_validation(self, data)
Validate any unique indexes specified on the model. This should happen after all the normal fields have been validated. This can add error messages to multiple fields. :return: None
4.498407
4.150665
1.08378
delayed = {} for field, value in self.data.items(): model_field = getattr(type(self.instance), field, None) # If this is a many-to-many field, we cannot save it to the instance until the instance # is saved to the database. Collect these fields and delay the...
def save(self, force_insert=False)
Save the model and any related many-to-many fields. :param force_insert: Should the save force an insert? :return: Number of rows impacted, or False.
3.184656
3.158248
1.008362
bytestring = hex(N) bytestring = bytestring[2:] if bytestring.startswith('0x') else bytestring bytestring = bytestring[:-1] if bytestring.endswith('L') else bytestring bytestring = '0' + bytestring if (len(bytestring) % 2) != 0 else bytestring bytestring = binascii.unhexlify(bytestring) i...
def long_to_bytes(N, blocksize=1)
Given an input integer ``N``, ``long_to_bytes`` returns the representation of ``N`` in bytes. If ``blocksize`` is greater than ``1`` then the output string will be right justified and then padded with zero-bytes, such that the return values length is a multiple of ``blocksize``.
1.955777
1.944398
1.005852
if not isinstance(plaintext, str): raise PlaintextTypeError("Input plaintext is not of type string") if iv_bytes is None: iv_bytes = fte.bit_ops.random_bytes(Encrypter._IV_LENGTH) iv1_bytes = '\x01' + iv_bytes iv2_bytes = '\x02' + iv_bytes W1 ...
def encrypt(self, plaintext, iv_bytes=None)
Given ``plaintext``, returns a ``ciphertext`` encrypted with an authenticated-encryption scheme, using the keys specified in ``__init__``. Ciphertext expansion is deterministic, the output ciphertext is always 42 bytes longer than the input ``plaintext``. The input ``plaintext`` can be ``''``. ...
3.404487
3.220407
1.057161
if not isinstance(ciphertext, str): raise CiphertextTypeError("Input ciphertext is not of type string") plaintext_length = self.getPlaintextLen(ciphertext) ciphertext_length = self.getCiphertextLen(ciphertext) ciphertext_complete = (len(ciphertext) >= ciphertext_le...
def decrypt(self, ciphertext)
Given ``ciphertext`` returns a ``plaintext`` decrypted using the keys specified in ``__init__``. Raises ``CiphertextTypeError`` if the input ``ciphertext`` is not a string. Raises ``RecoverableDecryptionError`` if the input ``ciphertext`` has a non-negative message length greater than the ciphertext le...
3.127393
2.891383
1.081625
plaintext_length = self.getPlaintextLen(ciphertext) ciphertext_length = plaintext_length + Encrypter._CTXT_EXPANSION return ciphertext_length
def getCiphertextLen(self, ciphertext)
Given a ``ciphertext`` with a valid header, returns the length of the ciphertext inclusive of ciphertext expansion.
9.258505
6.377293
1.451792
completeCiphertextHeader = (len(ciphertext) >= 16) if completeCiphertextHeader is False: raise RecoverableDecryptionError('Incomplete ciphertext header.') ciphertext_header = ciphertext[:16] L = self._ecb_enc_K1.decrypt(ciphertext_header) padding_expected ...
def getPlaintextLen(self, ciphertext)
Given a ``ciphertext`` with a valid header, returns the length of the plaintext payload.
4.36216
4.157804
1.04915
result = list() result_dict = _make_digest_dict(k, **kwargs) if result_dict is None: return 'default' else: for (key, h) in sorted(result_dict.items()): result.append('{}_{}'.format(key, h)) return '.'.join(result)
def _make_digest(k, **kwargs)
Creates a digest suitable for use within an :class:`phyles.FSCache` object from the key object `k`. >>> adict = {'a' : {'b':1}, 'f': []} >>> make_digest(adict) 'a2VKynHgDrUIm17r6BQ5QcA5XVmqpNBmiKbZ9kTu0A'
3.898538
4.864971
0.801349
''' Given model name & stan model code/file, compute path to cached stan fit if include_prefix, returns (model_prefix, model_cachefile) ''' cache_dir = _get_cache_dir(cache_dir) model_name = _sanitize_model_name(model_name) ## compute model prefix if file: model_code = _...
def cached_model_file(model_name='anon_model', file=None, model_code=None, cache_dir=None, fit_cachefile=None, include_prefix=False)
Given model name & stan model code/file, compute path to cached stan fit if include_prefix, returns (model_prefix, model_cachefile)
4.054666
3.40378
1.191224
''' Given inputs to cached_stan_fit, compute pickle file containing cached fit ''' model_prefix, model_cachefile = cached_model_file(model_name=model_name, file=file, model_code=model_code, cache_dir=cache_dir, fit_cachefile=fit_cachefile, include_prefix...
def cached_stan_file(model_name='anon_model', file=None, model_code=None, cache_dir=None, fit_cachefile=None, cache_only=None, force=False, include_modelfile=False, prefix_only=False, **kwargs )
Given inputs to cached_stan_fit, compute pickle file containing cached fit
3.935328
3.119838
1.261388
''' Cache fit stan model, by storing pickled objects in filesystem per following warning: 07: UserWarning: Pickling fit objects is an experimental feature! The relevant StanModel instance must be pickled along with this fit object. When unpickling the StanModel must be unpickled first...
def _cached_stan_fit(model_name='anon_model', file=None, model_code=None, force=False, cache_dir=None, cache_only=None, fit_cachefile=None, **kwargs)
Cache fit stan model, by storing pickled objects in filesystem per following warning: 07: UserWarning: Pickling fit objects is an experimental feature! The relevant StanModel instance must be pickled along with this fit object. When unpickling the StanModel must be unpickled first. ...
4.07745
2.392578
1.704208
def fit_lorentizan(curve,p0=None,N_points=1000): '''Fits a lorentzian curve using p0=[x0,A,gamma] as an initial guess. It returns a curve with N_points.''' def lorentzian(x,x0,A,gamma): return A*gamma**2/((x-x0)**2+gamma**2) N=len(curve) x=[curve[i][0] for i in range(N)] y=[curve[i][1] for i in range(N)] ...
Fits a lorentzian curve using p0=[x0,A,gamma] as an initial guess. It returns a curve with N_points.
null
null
null
def electric_field_amplitude_gaussian(P, sigmax, sigmay=None, Omega=1.0e6, units="ad-hoc"): e0 = hbar*Omega/(e*a0) # This is the electric field scale. if sigmay is None: sigmay = sigmax E0 = sqrt((c*mu0*P)/(2*Pi))/sqrt(sigmax*sigmay) if units == "ad-ho...
Return the amplitude of the electric field for a Gaussian beam. This the amplitude at the center of a laser beam of power P (in Watts) and\ a Gaussian intensity distribution of standard deviations sigmax, sigmay\ (in meters). The value of E0 is given in rescaled units according to the\ frequency scale Ome...
null
null
null
def electric_field_amplitude_top(P, a, Omega=1e6, units="ad-hoc"): e0 = hbar*Omega/(e*a0) # This is the electric field scale. E0 = sqrt((c*mu0*P)/(Pi*a**2)) if units == "ad-hoc": E0 = E0/e0 return E0
Return the amplitude of the electric field for a top hat beam. This is the amplitude of a laser beam of power P (in Watts) and a top-hat\ intensity distribution of radius a (in meters). The value of E0 is given in\ rescaled units according to the frequency scale Omega (in Hertz)\ understood as absolute fr...
null
null
null
def electric_field_amplitude_intensity(s0, Isat=16.6889462814, Omega=1e6, units="ad-hoc"): E0_sat = sqrt(2*mu0*c*Isat)/Omega if units == "ad-hoc": e0 = hbar/(e*a0) # This is the electric field scale. E0_sat = E0_sat/e0 return E0_sat*sqr...
Return the amplitude of the electric field for saturation parameter. This is at a given saturation parameter s0=I/Isat, where I0 is by default \ Isat=16.6889462814 m/m^2 is the saturation intensity of the D2 line of \ rubidium for circularly polarized light. Optionally, a frequency scale \ `Omega` can be prov...
null
null
null
def plot(self, **kwds): r plo = self.lx.plot(dist_to_center=3, **kwds) plo += self.ly.plot(dist_to_center=3, **kwds) plo += self.lz.plot(dist_to_center=3, **kwds) plo += self.lx_r.plot(dist_to_center=3, **kwds) plo += self.ly_r.plot(dist_to_center=3, **kwds) ...
r"""The plotting function for MOT fields.
null
null
null
r if print_ascii: pprint(expr, use_unicode=False, num_columns=120) else: return expr
def fprint(expr, print_ascii=False)
r"""This function chooses whether to use ascii characters to represent a symbolic expression in the notebook or to use sympy's pprint. >>> from sympy import cos >>> omega=Symbol("omega") >>> fprint(cos(omega),print_ascii=True) cos(omega)
10.510301
11.040668
0.951962
if i == j: if s == -1: if i == 1: return 0 else: mes = 'There is no population rhoii with i='+str(i)+'.' raise ValueError(mes) mu = i-1 elif i > j and s == 1: mu = i - j + sum([N-k for k in range(1, j)])+N-1 ...
def Mu(i, j, s, N, excluded_mu=[])
This function calculates the global index mu for the element i, j. It returns the index for the real part if s=0 and the one for the imaginary part if s=1.
3.769913
3.782994
0.996542
if mu == 0: return 1, 1, 1 if mu not in range(0, N**2): raise ValueError('mu has an invalid value mu='+str(mu)+'.') if 1 <= mu <= N-1: return mu+1, mu+1, 1 else: m = N-1 M = N*(N-1)/2 for jj in range(1, N): for ii in range(jj+1, N+1): ...
def IJ(mu, N)
Return i, j, s for any given mu.
3.655381
3.447508
1.060297
r if clone is not None: clone = '_'+str(clone) else: clone = '' if use_netcdf: ncfile = Dataset(path+name+clone+'.nc', 'r') matrix = ncfile.variables['matrix'][:] vector = ncfile.variables['vector'][:] Nrho, n_points = len(matrix), len(matrix[0]) ...
def read_result(path, name, i=None, j=None, s=0, N=None, excluded_mu=[], use_netcdf=True, clone=None)
r"""This function reads the results stored in path under file name.dat returning them as a list of N^2 lists of the form [frequency, rho22, rho33, ... rho_N,N-1]. Alternatively it can return only two lists [frequency, rho_i,j,s] where s must be 1 for the real part and -1 for the imaginary part.
3.140261
3.049219
1.029858
# We first define the needed variables _omega_laser = [Symbol('omega_laser'+str(l+1)) for l in range(Nl)] _theta = [Symbol('theta'+str(i+1)) for i in range(Ne)] # We find all the equations that the specified problem has to fulfil. eqs = [] for i in range(Ne): for j in range(i+1, Ne...
def find_phase_transformation(Ne, Nl, r, Lij, verbose=0, return_equations=False, **kwds)
This function returns a phase transformation specified as a list of lenght Ne whose elements correspond to each theta_i. Each element is a list of length Nl which specifies the coefficients multiplying each optical frequency omega^l. So for instance [[1,1],[1,0],[0,0]] means theta_1=omega^1+omega^2 ...
2.305813
2.305607
1.000089
r Ne = len(omega[0]) om = omega[0][0] correspondence = [] I = 0 for i in range(Ne): if omega[i][0] != om: om = omega[i][0] I += 1 correspondence += [(i+1, I+1)] Nnd = I+1 def I_nd(i): return correspondence[i-1][1] def i_d(I): ...
def calculate_iI_correspondence(omega)
r"""Get the correspondance between degenerate and nondegenerate schemes.
3.615539
3.647957
0.991113
r if sage_included: if s == 1: return np.real(z) elif s == -1: return np.imag(z) elif s == 0: return z else: if s == 1: return z.real elif s == -1: return z.imag elif s == 0: return z
def part(z, s)
r"""Get the real or imaginary part of a complex number.
3.431902
3.732564
0.919449
r if s == 1: return symre(z) elif s == -1: return symim(z) elif s == 0: return z
def symbolic_part(z, s)
r"""Get the real or imaginary part of a complex symbol.
5.096767
5.033759
1.012517
r Nl = len(lists) comb = [[i] for i in range(lists[0])] for l in range(1, Nl): combn = [] for c0 in comb: for cl in range(lists[l]): combn += [c0[:]+[cl]] comb = combn[:] return comb
def detuning_combinations(lists)
r"""This function recieves a list of length Nl with the number of transitions each laser induces. It returns the cartesian product of all these posibilities as a list of all possible combinations.
4.412853
3.500711
1.260559
r Ne = len(Lij) detunings = [[] for i in range(Nl)] detuningsij = [[] for i in range(Nl)] detuning = [0 for i in range(Nnd)] for i in range(1, Ne): for j in range(i): for l in Lij[i][j]: det = detuning[:] det[I_nd(i+1)-1] += 1; det[I_nd(j+1)-1]...
def laser_detunings(Lij, Nl, i_d, I_nd, Nnd)
r"""This function returns the list of transitions i,j that each laser produces as lists of length Ne, whose elements are all zero except for the ith element =1 and the jth element = -1. Also, it returns detuningsij, which contains the same information but as pairs if ij. The indices in it start from 0.
2.97268
2.711033
1.096512
r omega_min = [] omega_min_indices = [] for l in range(Nl): omegas = sorted([(omega[i_d(p[0]+1)-1][i_d(p[1]+1)-1], p) for p in detuningsij[l]]) omega_min += [omegas[0][0]] omega_min_indices += [omegas[0][1]] return omega_min, omega_min_indices
def find_omega_min(omega, Nl, detuningsij, i_d, I_nd)
r"""This function returns a list of length Nl containing the mininmal frequency that each laser excites.
2.902064
2.930289
0.990368
ur if type is None: type = np.float64 sizes = [Ai.shape[0] for Ai in matrices] size = sum(sizes) symbolic = hasattr(matrices[0][0], "subs") if symbolic: A = symzeros(size, size) else: A = np.zeros((size, size), type) ini = 0; fin = 0 for i, sizei in enumerate(...
def block_diagonal_matrix(matrices, type=None)
ur"""Build a block-diagonal matrix out of a given list of matrices. The type of matrix is chosen according to the input matrices. >>> import numpy as np >>> import sympy as sy >>> lis = [sy.ones(2), 2*sy.ones(3), 3*sy.ones(4)] >>> sy.pprint(block_diagonal_matrix(lis)) ⎡1 1 0 0 0 0 0 0 ...
3.621702
4.093196
0.88481
super(MergingDict, self).__setitem__(key, value)
def replace(self, key, value)
Convenience method provided as a way to replace a value mapped by a key.This is required since a MergingDict always merges via assignment of item/attribute. :param key: Attribute name or item key to replace rvalue for. :type key: object :param value: The new value to assign. ...
7.553407
6.706805
1.12623
if other is not None: if isinstance(other, dict): for key in other: self[key] = other[key] else: # noinspection PyTypeChecker super(MergingDict, self).update(other) for key in kwargs: self._...
def update(self, other=None, **kwargs)
A special update method to handle merging of dict objects. For all other iterable objects, we use the parent class update method. For other objects, we simply make use of the internal merging logic. :param other: An iterable object. :type other: dict or object :param kwargs: key...
2.910706
2.708253
1.074754
if key in self: for method in ["update", "append"]: if hasattr(self[key], method): return method return None
def _merge_method(self, key)
Identify a merge compatible method available in self[key]. Currently we support 'update' and 'append'. :param key: Attribute name or item key :return: Method name usable to merge a value into the instance mapped by key :rtype: str
5.706846
3.786934
1.506983
method = self._merge_method(key) if method is not None: # strings are special, update methods like set.update looks for # iterables if method == "update" and is_str(value): value = [value] if ( method == "append" ...
def _merge(self, key, value)
Internal merge logic implementation to allow merging of values when setting attributes/items. :param key: Attribute name or item key :type key: str :param value: Value to set attribute/item as. :type value: object :rtype: None
5.1283
5.493833
0.933465
tweet = Tweet() tweet.published_at = status.created_at tweet.content = status.text return tweet
def _tweepy_status_to_tweet(self, status)
Fields documentation: https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline
4.384208
3.658203
1.198459
#We create Lij as a matrix of lists of laser indices global Lij Lij=[] for i in range(Ne): fila=[] for j in range(Ne): band=False for tri in Lij0: if [i+1,j+1] == tri[:2]: band=True break elif [j+1,i+1] == tri[:2]: band=True break if band: fila+=[tri[2]] else: f...
def formatLij(Lij0,Ne)
This function transforms a list of laser conections of the form [i,j,[l1,l2,...]] between states i and j by lasers l1,l2,... into a Ne x Ne matrix whose elements are the lasers connecting the corresponding indices.
3.039475
2.678531
1.134755
"This function calculates the dot product epsilon^(l(+-)) . vec(r_ij)." if sign==1: dp=sum([laserl.Yp[1-p]*r[p+1][i-1][j-1]*(-1)**p for p in range(-1,2)]) elif sign==-1: dp=sum([laserl.Ym[1-p]*r[p+1][i-1][j-1]*(-1)**p for p in range(-1,2)]) #~ if i==2 and j==9 and sign==-1: #~ print 222 #~ print dp #~ pr...
def dot_product(laserl,sign,r,i,j)
This function calculates the dot product epsilon^(l(+-)) . vec(r_ij).
4.274152
3.112149
1.373376
''' Cell wrappers for customizing the GUI data table TODO : must coincide with hierarchy! TODO : simplify this! ''' html_class = '' # for GUI javascript out = '' #if 'cell_wrapper' in entity: # TODO : this bound type was defined by apps only # out = entity['cell_wrapper'](js...
def wrap_cell(entity, json_obj, mapping, table_view=False)
Cell wrappers for customizing the GUI data table TODO : must coincide with hierarchy! TODO : simplify this!
5.157427
4.177116
1.234686
f = open("/proc/meminfo") hwinfo = {} for line in f.readlines(): meml = line.split() if (meml[0] == "MemTotal:"): mem = int(meml[1]) hwinfo["Mem_MiB"] = mem/1024 elif (meml[0] == "SwapTotal:"): swap = int(meml[1]) hwinfo["Swap_MiB"...
def meminfo()
Get the amount of memory and swap, Mebibytes
2.287555
2.213994
1.033226
f = open("/proc/cpuinfo") hwinfo = {} for line in f.readlines(): cpul = line.split(":") name = cpul[0].strip() if (len(cpul) > 1): val = cpul[1].strip() if (name == "model name"): hwinfo["CPU"] = val elif (name == "cpu MHz"): h...
def cpuinfo()
Get the cpu info
2.540537
2.579698
0.98482
if os.path.isfile('/sbin/lspci'): lspci = '/sbin/lspci' else: lspci = '/usr/bin/lspci' f = os.popen (lspci + ' -m') pdata = {} for line in f.readlines(): p = line.split("\"") name = p[1].strip() if (name == "VGA compatible controller"): pdata[...
def vgadata()
Get data about the graphics card.
3.697167
3.548881
1.041784
sdata = {} if os.getuid() == 0: try: sdata['Serial'] = open('/sys/class/dmi/id/product_serial') \ .read().strip() except: for line in os.popen('/usr/sbin/dmidecode -s system-serial-number'): sdata['Serial'] = line.strip() return sd...
def serial_number()
Get the serial number. Requires root access
3.158686
2.87115
1.100147
mdata = {} man = None pn = None try: # This might be # sys_vendor, bios_vendor, board_vendor, or chassis_vendor man = open('/sys/class/dmi/id/sys_vendor').read().strip() except: if os.getuid() == 0: for line in os.popen('/usr/sbin/dmidecode -s system-...
def system_model()
Get manufacturer and model number. On older Linux kernel versions without /sys/class/dmi/id this requires root access.
2.687164
2.441613
1.100569
p = os.popen("/bin/df -l -P") ddata = {} tsize = 0 for line in p.readlines(): d = line.split() if ("/dev/sd" in d[0] or "/dev/hd" in d[0] or "/dev/mapper" in d[0]): tsize = tsize + int(d[1]) ddata["Disk_GB"] = int(tsize)/1000000 p.close() return ddata
def diskdata()
Get total disk size in GB.
3.125162
2.966082
1.053633
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 8.8.8.8 is the google public DNS s.connect(("8.8.8.8", 53)) ip = s.getsockname()[0] s.close() return ip
def ip_address()
Get the IP address used for public connections.
2.050331
2.129618
0.96277