code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
file_dest: IO = file_dest_maybe or sys.stderr def _print_progress(progress_min: float, rt_remaining: float, _mc: MeasureComparison) -> None: nonlocal file_dest percent_progress = progress_min * 100.0 time_remaining, unit = _display_time(rt_remaining) print( f"Pr...
def capture_print(file_dest_maybe: Optional[IO] = None)
Progress capture that writes updated metrics to an interactive terminal.
4.652574
4.293502
1.083631
def measure_to_target() -> MeasureComparison: return list(zip(measure(), target)) def is_finished(progress: MeasureComparison) -> bool: return all(p >= t for p, t in progress) capture = capture_maybe or capture_print() rt_started = now_real() while True: advance(inter...
def track_progress( measure: MeasureProgress, target: MetricProgress, interval_check: float, capture_maybe: Optional[CaptureProgress] = None ) -> None
Tracks progress against a certain end condition of the simulation (for instance, a certain duration on the simulated clock), reporting this progress as the simulation chugs along. Stops the simulation once the target has been reached. By default, the progress is reported as printout on standard output, in a man...
4.268807
4.120729
1.035935
''' Return the tm of `seq` as a float. ''' tm_meth = _tm_methods.get(tm_method) if tm_meth is None: raise ValueError('{} is not a valid tm calculation method'.format( tm_method)) salt_meth = _salt_corrections_methods.get(salt_corrections_method) if salt_meth is N...
def calcTm(seq, mv_conc=50, dv_conc=0, dntp_conc=0.8, dna_conc=50, max_nn_length=60, tm_method='santalucia', salt_corrections_method='santalucia')
Return the tm of `seq` as a float.
3.147918
2.981231
1.055912
''' Helper method that uses regex to parse ntthal output. ''' parsed_vals = re.search(_ntthal_re, ntthal_output) return THERMORESULT( True, # Structure found float(parsed_vals.group(1)), # dS float(parsed_vals.group(2)), # dH float(parsed_vals....
def _parse_ntthal(ntthal_output)
Helper method that uses regex to parse ntthal output.
4.842437
4.308908
1.12382
args = [pjoin(PRIMER3_HOME, 'ntthal'), '-a', str(calc_type), '-mv', str(mv_conc), '-dv', str(dv_conc), '-n', str(dntp_conc), '-d', str(dna_conc), '-t', str(temp_c), '-maxloop', str(max_loop), ...
def calcThermo(seq1, seq2, calc_type='ANY', mv_conc=50, dv_conc=0, dntp_conc=0.8, dna_conc=50, temp_c=37, max_loop=30, temp_only=False)
Main subprocess wrapper for calls to the ntthal executable. Returns a named tuple with tm, ds, dh, and dg values or None if no structure / complex could be computed.
3.021669
2.611908
1.156882
''' Return a namedtuple of the dS, dH, dG, and Tm of any hairpin struct present. ''' return calcThermo(seq, seq, 'HAIRPIN', mv_conc, dv_conc, dntp_conc, dna_conc, temp_c, max_loop, temp_only)
def calcHairpin(seq, mv_conc=50, dv_conc=0, dntp_conc=0.8, dna_conc=50, temp_c=37, max_loop=30, temp_only=False)
Return a namedtuple of the dS, dH, dG, and Tm of any hairpin struct present.
7.038536
2.457143
2.86452
''' Return a tuple of the dS, dH, dG, and Tm of any predicted heterodimer. ''' return calcThermo(seq1, seq2, 'ANY', mv_conc, dv_conc, dntp_conc, dna_conc, temp_c, max_loop, temp_only)
def calcHeterodimer(seq1, seq2, mv_conc=50, dv_conc=0, dntp_conc=0.8, dna_conc=50, temp_c=37, max_loop=30, temp_only=False)
Return a tuple of the dS, dH, dG, and Tm of any predicted heterodimer.
5.118137
2.371193
2.158465
''' Return the thermodynamic characteristics of hairpin/homodimer structures. Returns a tuple of namedtuples (hairpin data, homodimer data) in which each individual tuple is structured (dS, dH, dG, Tm). ''' hairpin_out = calcHairpin(seq) homodimer_out = calcHomodimer(seq) return (hairp...
def assessOligo(seq)
Return the thermodynamic characteristics of hairpin/homodimer structures. Returns a tuple of namedtuples (hairpin data, homodimer data) in which each individual tuple is structured (dS, dH, dG, Tm).
7.55983
1.822778
4.147422
''' Return the raw primer3_core output for the provided primer3 args. Returns an ordered dict of the boulderIO-format primer3 output file ''' sp = subprocess.Popen([pjoin(PRIMER3_HOME, 'primer3_core')], stdout=subprocess.PIPE, stdin=subprocess.PIPE, s...
def designPrimers(p3_args, input_log=None, output_log=None, err_log=None)
Return the raw primer3_core output for the provided primer3 args. Returns an ordered dict of the boulderIO-format primer3 output file
3.335076
2.253005
1.480279
''' Adds the executable bit to the file at filepath `fp` ''' mode = ((os.stat(fp).st_mode) | 0o555) & 0o7777 setup_log.info("Adding executable bit to %s (mode is now %o)", fp, mode) os.chmod(fp, mode)
def makeExecutable(fp)
Adds the executable bit to the file at filepath `fp`
4.205443
3.744103
1.123218
''' Calculate the hairpin formation thermodynamics of a DNA sequence. **Note that the maximum length of `seq` is 60 bp.** This is a cap suggested by the Primer3 team as the longest reasonable sequence length for which a two-state NN model produces reliable results (see primer3/src/libnano/thal.h:50). ...
def calcHairpin(seq, mv_conc=50.0, dv_conc=0.0, dntp_conc=0.8, dna_conc=50.0, temp_c=37, max_loop=30)
Calculate the hairpin formation thermodynamics of a DNA sequence. **Note that the maximum length of `seq` is 60 bp.** This is a cap suggested by the Primer3 team as the longest reasonable sequence length for which a two-state NN model produces reliable results (see primer3/src/libnano/thal.h:50). Args...
6.813582
1.508293
4.517413
''' Calculate the 3' end stability of DNA sequence `seq1` against DNA sequence `seq2`. **Note that at least one of the two sequences must by <60 bp in length.** This is a cap imposed by Primer3 as the longest reasonable sequence length for which a two-state NN model produces reliable results (see ...
def calcEndStability(seq1, seq2, mv_conc=50, dv_conc=0, dntp_conc=0.8, dna_conc=50, temp_c=37, max_loop=30)
Calculate the 3' end stability of DNA sequence `seq1` against DNA sequence `seq2`. **Note that at least one of the two sequences must by <60 bp in length.** This is a cap imposed by Primer3 as the longest reasonable sequence length for which a two-state NN model produces reliable results (see prime...
6.598808
1.384302
4.766885
''' Calculate the melting temperature (Tm) of a DNA sequence. Note that NN thermodynamics will be used to calculate the Tm of sequences up to 60 bp in length, after which point the following formula will be used:: Tm = 81.5 + 16.6(log10([mv_conc])) + 0.41(%GC) - 600/length Args: s...
def calcTm(seq, mv_conc=50, dv_conc=0, dntp_conc=0.8, dna_conc=50, max_nn_length=60, tm_method='santalucia', salt_corrections_method='santalucia')
Calculate the melting temperature (Tm) of a DNA sequence. Note that NN thermodynamics will be used to calculate the Tm of sequences up to 60 bp in length, after which point the following formula will be used:: Tm = 81.5 + 16.6(log10([mv_conc])) + 0.41(%GC) - 600/length Args: seq (str)...
4.800038
1.351732
3.551028
''' Run the Primer3 design process. If the global args have been previously set (either by a pervious `designPrimers` call or by a `setGlobals` call), `designPrimers` may be called with seqArgs alone (as a means of optimization). Args: seq_args (dict) : Primer3 sequence/desig...
def designPrimers(seq_args, global_args=None, misprime_lib=None, mishyb_lib=None, debug=False)
Run the Primer3 design process. If the global args have been previously set (either by a pervious `designPrimers` call or by a `setGlobals` call), `designPrimers` may be called with seqArgs alone (as a means of optimization). Args: seq_args (dict) : Primer3 sequence/design args a...
5.892588
1.406423
4.189769
sections = [] for type, subsection_list in section_data.items(): for section in subsection_list: section['sectionType'] = type sections.append(section) return sections
def unravel_sections(section_data)
Unravels section type dictionary into flat list of sections with section type set as an attribute. Args: section_data(dict): Data return from py:method::get_sections Returns: list: Flat list of sections with ``sectionType`` set to type (i.e. recitation, ...
3.498739
3.532932
0.990322
staff_list = [] for role, staff_members in staff_data['data'].items(): for member in staff_members: member['role'] = role staff_list.append(member) return staff_list
def unravel_staff(staff_data)
Unravels staff role dictionary into flat list of staff members with ``role`` set as an attribute. Args: staff_data(dict): Data return from py:method::get_staff Returns: list: Flat list of staff members with ``role`` set to role type (i.e. course_admin, ...
3.066784
3.074008
0.99765
gradebook = self.get('gradebook', params={'uuid': gbuuid}) if 'data' not in gradebook: failure_messsage = ('Error in get_gradebook_id ' 'for {0} - no data'.format( gradebook )) ...
def get_gradebook_id(self, gbuuid)
Return gradebookid for a given gradebook uuid. Args: gbuuid (str): gradebook uuid, i.e. ``STELLAR:/project/gbngtest`` Raises: PyLmodUnexpectedData: No gradebook id returned requests.RequestException: Exception connection error ValueError: Unable to decod...
5.023655
4.194726
1.197612
end_point = 'gradebook/options/{gradebookId}'.format( gradebookId=gradebook_id or self.gradebook_id) options = self.get(end_point) return options['data']
def get_options(self, gradebook_id)
Get options for gradebook. Get options dictionary for a gradebook. Options include gradebook attributes. Args: gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` Returns: An example return value is: .. code-block:: python ...
3.639354
3.646085
0.998154
# These are parameters required for the remote API call, so # there aren't too many arguments # pylint: disable=too-many-arguments params = dict( includeMaxPoints=json.dumps(max_points), includeAvgStats=json.dumps(avg_stats), includeGradingSta...
def get_assignments( self, gradebook_id='', simple=False, max_points=True, avg_stats=False, grading_stats=False )
Get assignments for a gradebook. Return list of assignments for a given gradebook, specified by a py:attribute::gradebook_id. You can control if additional parameters are returned, but the response time with py:attribute::avg_stats and py:attribute::grading_stats enabled is sig...
3.207326
3.434667
0.93381
if assignments is None: assignments = self.get_assignments() for assignment in assignments: if assignment['name'] == assignment_name: return assignment['assignmentId'], assignment return None, None
def get_assignment_by_name(self, assignment_name, assignments=None)
Get assignment by name. Get an assignment by name. It works by retrieving all assignments and returning the first assignment with a matching name. If the optional parameter ``assignments`` is provided, it uses this collection rather than retrieving all assignments from the service. ...
2.481967
2.325132
1.067452
data = { 'name': name, 'shortName': short_name, 'weight': weight, 'graderVisible': False, 'gradingSchemeType': 'NUMERIC', 'gradebookId': gradebook_id or self.gradebook_id, 'maxPointsTotal': max_points, 'dueD...
def create_assignment( # pylint: disable=too-many-arguments self, name, short_name, weight, max_points, due_date_str, gradebook_id='', **kwargs )
Create a new assignment. Create a new assignment. By default, assignments are created under the `Uncategorized` category. Args: name (str): descriptive assignment name, i.e. ``new NUMERIC SIMPLE ASSIGNMENT`` short_name (str): short name of assignment, on...
2.996242
2.415334
1.240508
# pylint: disable=too-many-arguments # numericGradeValue stringified because 'x' is a possible # value for excused grades. grade_info = { 'studentId': student_id, 'assignmentId': assignment_id, 'mode': 2, 'comment': 'from MITx {0}...
def set_grade( self, assignment_id, student_id, grade_value, gradebook_id='', **kwargs )
Set numerical grade for student and assignment. Set a numerical grade for for a student and assignment. Additional options for grade ``mode`` are: OVERALL_GRADE = ``1``, REGULAR_GRADE = ``2`` To set 'excused' as the grade, enter ``None`` for letter and numeric grade values, ...
4.42379
3.933598
1.124617
log.info('Sending grades: %r', grade_array) return self.post( 'multiGrades/{gradebookId}'.format( gradebookId=gradebook_id or self.gradebook_id ), data=grade_array, )
def multi_grade(self, grade_array, gradebook_id='')
Set multiple grades for students. Set multiple student grades for a gradebook. The grades are passed as a list of dictionaries. Each grade dictionary in ``grade_array`` must contain a ``studentId`` and a ``assignmentId``. Options for grade mode are: OVERALL_GRADE = ``1``, ...
3.368426
3.831032
0.879248
params = dict(includeMembers='false') section_data = self.get( 'sections/{gradebookId}'.format( gradebookId=gradebook_id or self.gradebook_id ), params=params ) if simple: sections = self.unravel_sections(section_...
def get_sections(self, gradebook_id='', simple=False)
Get the sections for a gradebook. Return a dictionary of types of sections containing a list of that type for a given gradebook. Specified by a gradebookid. If simple=True, a list of dictionaries is provided for each section regardless of type. The dictionary only contains one ...
3.692487
3.653926
1.010553
sections = self.unravel_sections(self.get_sections()) for section in sections: if section['name'] == section_name: return section['groupId'], section return None, None
def get_section_by_name(self, section_name)
Get a section by its name. Get a list of sections for a given gradebook, specified by a gradebookid. Args: section_name (str): The section's name. Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response co...
4.499897
4.280586
1.051234
# These are parameters required for the remote API call, so # there aren't too many arguments, or too many variables # pylint: disable=too-many-arguments,too-many-locals # Set params by arguments params = dict( includePhoto=json.dumps(include_photo), ...
def get_students( self, gradebook_id='', simple=False, section_name='', include_photo=False, include_grade_info=False, include_grade_history=False, include_makeup_grades=False )
Get students for a gradebook. Get a list of students for a given gradebook, specified by a gradebook id. Does not include grade data. Args: gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` simple (bool): if ``True``, just return diction...
3.607172
3.694577
0.976342
if students is None: students = self.get_students() email = email.lower() for student in students: if student['accountEmail'].lower() == email: return student['studentId'], student return None, None
def get_student_by_email(self, email, students=None)
Get a student based on an email address. Calls ``self.get_students()`` to get list of all students, if not passed as the ``students`` parameter. Args: email (str): student email students (list): dictionary of students to search, default: None When ``stud...
2.980893
2.97547
1.001823
non_assignment_fields = [ 'ID', 'Username', 'Full Name', 'edX email', 'External email' ] if max_points_column is not None: non_assignment_fields.append(max_points_column) if normalize_column is not None: non_assignment_fields.append(normalize_...
def spreadsheet2gradebook( self, csv_file, email_field=None, approve_grades=False, use_max_points_column=False, max_points_column=None, normalize_column=None )
Upload grade spreadsheet to gradebook. Upload grades from CSV format spreadsheet file into the Learning Modules gradebook. The spreadsheet must have a column named ``External email`` which is used as the student's email address (for looking up and matching studentId). These co...
2.093146
1.829984
1.143805
staff_data = self.get( 'staff/{gradebookId}'.format( gradebookId=gradebook_id or self.gradebook_id ), params=None, ) if simple: simple_list = [] unraveled_list = self.unravel_staff(staff_data) for me...
def get_staff(self, gradebook_id, simple=False)
Get staff list for gradebook. Get staff list for the gradebook specified. Optionally, return a less detailed list by specifying ``simple = True``. If simple=True, return a list of dictionaries, one dictionary for each member. The dictionary contains a member's ``email``, ``disp...
3.180224
2.836851
1.12104
if uuid is None: uuid = self.uuid group_data = self.get('group', params={'uuid': uuid}) return group_data
def get_group(self, uuid=None)
Get group data based on uuid. Args: uuid (str): optional uuid. defaults to self.cuuid Raises: PyLmodUnexpectedData: No data was returned. requests.RequestException: Exception connection error Returns: dict: group json
3.682507
5.244381
0.702181
group_data = self.get_group(uuid) try: return group_data['response']['docs'][0]['id'] except (KeyError, IndexError): failure_message = ('Error in get_group response data - ' 'got {0}'.format(group_data)) log.exception(fa...
def get_group_id(self, uuid=None)
Get group id based on uuid. Args: uuid (str): optional uuid. defaults to self.cuuid Raises: PyLmodUnexpectedData: No group data was returned. requests.RequestException: Exception connection error Returns: int: numeric group id
5.206519
4.29834
1.211286
group_id = self.get_group_id(uuid=uuid) uri = 'group/{group_id}/member' mbr_data = self.get(uri.format(group_id=group_id), params=None) return mbr_data
def get_membership(self, uuid=None)
Get membership data based on uuid. Args: uuid (str): optional uuid. defaults to self.cuuid Raises: PyLmodUnexpectedData: No data was returned. requests.RequestException: Exception connection error Returns: dict: membership json
3.55092
4.296917
0.826388
mbr_data = self.get_membership(uuid=uuid) docs = [] try: docs = mbr_data['response']['docs'] except KeyError: failure_message = ('KeyError in membership data - ' 'got {0}'.format(mbr_data)) log.exception(failure_...
def email_has_role(self, email, role_name, uuid=None)
Determine if an email is associated with a role. Args: email (str): user email role_name (str): user role uuid (str): optional uuid. defaults to self.cuuid Raises: PyLmodUnexpectedData: Unexpected data was returned. requests.RequestException:...
3.88572
3.252995
1.194505
course_data = self.get( 'courseguide/course?uuid={uuid}'.format( uuid=course_uuid or self.course_id ), params=None ) try: return course_data['response']['docs'][0]['id'] except KeyError: failure_message ...
def get_course_id(self, course_uuid)
Get course id based on uuid. Args: uuid (str): course uuid, i.e. /project/mitxdemosite Raises: PyLmodUnexpectedData: No course data was returned. requests.RequestException: Exception connection error Returns: int: numeric course id
3.158559
2.863312
1.103114
staff_data = self.get( 'courseguide/course/{courseId}/staff'.format( courseId=course_id or self.course_id ), params=None ) return staff_data['response']['docs']
def get_course_guide_staff(self, course_id='')
Get the staff roster for a course. Get a list of staff members for a given course, specified by a course id. Args: course_id (int): unique identifier for course, i.e. ``2314`` Raises: requests.RequestException: Exception connection error ValueError:...
4.255169
5.231843
0.813321
if type(data) not in [str, unicode]: data = json.dumps(data) return data
def _data_to_json(data)
Convert to json if it isn't already a string. Args: data (str): data to convert to json
4.412534
4.560666
0.96752
base_service_url = '{base}{service}'.format( base=self.urlbase, service=service ) return base_service_url
def _url_format(self, service)
Generate URL from urlbase and service. Args: service (str): The endpoint service to use, i.e. gradebook Returns: str: URL to where the request should be made
4.613537
5.314881
0.868041
try: response = func(url, timeout=self.TIMEOUT, **kwargs) except requests.RequestException, err: log.exception( "[PyLmod] Error - connection error in " "rest_action, err=%s", err ) raise err try: ...
def rest_action(self, func, url, **kwargs)
Routine to do low-level REST operation, with retry. Args: func (callable): API function to call url (str): service URL endpoint kwargs (dict): addition parameters Raises: requests.RequestException: Exception connection error ValueError: Unabl...
5.021168
4.911558
1.022317
url = self._url_format(service) if params is None: params = {} return self.rest_action(self._session.get, url, params=params)
def get(self, service, params=None)
Generic GET operation for retrieving data from Learning Modules API. .. code-block:: python gbk.get('students/{gradebookId}', params=params, gradebookId=gbid) Args: service (str): The endpoint service to use, i.e. gradebook params (dict): additional parameters to a...
4.150091
5.886729
0.704991
url = self._url_format(service) data = Base._data_to_json(data) # Add content-type for body in POST. headers = {'content-type': 'application/json'} return self.rest_action(self._session.post, url, data=data, headers=headers)
def post(self, service, data)
Generic POST operation for sending data to Learning Modules API. Data should be a JSON string or a dict. If it is not a string, it is turned into a JSON string for the POST body. Args: service (str): The endpoint service to use, i.e. gradebook data (json or dict): the ...
5.194209
5.784269
0.897989
url = self._url_format(service) return self.rest_action( self._session.delete, url )
def delete(self, service)
Generic DELETE operation for Learning Modules API. Args: service (str): The endpoint service to use, i.e. gradebook Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: list: the js...
9.96811
11.819184
0.843384
if not isinstance(secret, basestring): raise ValueError("firebase_token_generator.create_token: secret must be a string.") if not options and not data: raise ValueError("firebase_token_generator.create_token: data is empty and no options are set. This token will have no effect on Firebase....
def create_token(secret, data, options=None)
Generates a secure authentication token. Our token format follows the JSON Web Token (JWT) standard: header.claims.signature Where: 1) "header" is a stringified, base64-encoded JSON object containing version and algorithm information. 2) "claims" is a stringified, base64-encoded JSON object con...
3.395159
3.182153
1.066938
parser = HTMLParser(encoding=encoding, remove_blank_text=True) return parse(fileobj, parser)
def parse_html(fileobj, encoding)
Given a file object *fileobj*, get an ElementTree instance. The *encoding* is assumed to be utf8.
3.925623
3.739974
1.049639
rec = self._db.execute(, [seq_id]).fetchone() if rec is None: raise KeyError(seq_id) if self._writing and self._writing["relpath"] == rec["relpath"]: logger.warning(.format(rec["relpath"])) self.commit() path = os.path.join(self._root_dir, ...
def fetch(self, seq_id, start=None, end=None)
fetch sequence by seq_id, optionally with start, end bounds
5.551437
5.500643
1.009234
if not self._writeable: raise RuntimeError("Cannot write -- opened read-only") # open a file for writing if necessary # path: <root_dir>/<reldir>/<basename> # <---- relpath ----> # <------ dir_ -----> # <----------- path...
def store(self, seq_id, seq)
store a sequence with key seq_id. The sequence itself is stored in a fasta file and a reference to it in the sqlite3 database.
4.428299
4.380791
1.010845
dialect = postgresql.dialect() statement = getattr(source, 'statement', source) compiled = statement.compile(dialect=dialect) conn, autoclose = raw_connection_from(engine_or_conn) cursor = conn.cursor() query = cursor.mogrify(compiled.string, compiled.params).decode() formatted_flags = ...
def copy_to(source, dest, engine_or_conn, **flags)
Export a query or select to a file. For flags, see the PostgreSQL documentation at http://www.postgresql.org/docs/9.5/static/sql-copy.html. Examples: :: select = MyTable.select() with open('/path/to/file.tsv', 'w') as fp: copy_to(select, fp, conn) query = session.query(MyMo...
3.639928
3.656322
0.995516
tbl = dest.__table__ if is_model(dest) else dest conn, autoclose = raw_connection_from(engine_or_conn) cursor = conn.cursor() relation = '.'.join('"{}"'.format(part) for part in (tbl.schema, tbl.name) if part) formatted_columns = '({})'.format(','.join(columns)) if columns else '' formatted...
def copy_from(source, dest, engine_or_conn, columns=(), **flags)
Import a table from a file. For flags, see the PostgreSQL documentation at http://www.postgresql.org/docs/9.5/static/sql-copy.html. Examples: :: with open('/path/to/file.tsv') as fp: copy_from(fp, MyTable, conn) with open('/path/to/file.csv') as fp: copy_from(fp, MyMode...
3.565821
3.70046
0.963616
if hasattr(engine_or_conn, 'cursor'): return engine_or_conn, False if hasattr(engine_or_conn, 'connection'): return engine_or_conn.connection, False return engine_or_conn.raw_connection(), True
def raw_connection_from(engine_or_conn)
Extract a raw_connection and determine if it should be automatically closed. Only connections opened by this package will be closed automatically.
2.400659
2.445205
0.981782
if os.path.exists(name): if not exist_ok: raise FileExistsError("File exists: " + name) else: os.makedirs(name, mode)
def makedirs(name, mode=0o777, exist_ok=False)
cheapo replacement for py3 makedirs with support for exist_ok
2.316233
2.178837
1.063059
def fetch_seq(q, nsa): pid, ppid = os.getpid(), os.getppid() q.put((pid, ppid, sr[nsa])) q = Queue() p = Process(target=fetch_seq, args=(q, nsa)) p.start() pid, ppid, seq = q.get() p.join() assert pid != ppid, "sequence was not fetched from thread" return pid,...
def fetch_in_thread(sr, nsa)
fetch a sequence in a thread
3.325603
3.136495
1.060293
try: self.linux.verify_system_status() except InstallSkipError: Log.info('Install skipped.') return work_dir = tempfile.mkdtemp(suffix='-rpm-py-installer') Log.info("Created working directory '{0}'".format(work_dir)) with Cmd.pushd(w...
def run(self)
Run install process.
5.212046
4.898743
1.063956
if self.is_installed_from_bin: try: self.installer.install_from_rpm_py_package() return except RpmPyPackageNotFoundError as e: Log.warn('RPM Py Package not found. reason: {0}'.format(e)) # Pass to try to install fr...
def download_and_install(self)
Download and install RPM Python binding.
4.768725
4.393528
1.085398
info = self.info return 'rpm-{major}.{minor}.x'.format( major=info[0], minor=info[1])
def git_branch(self)
Git branch name.
8.753235
8.093161
1.08156
additional_patches = [ { 'src': r"pkgconfig\('--libs-only-L'\)", 'dest': "['{0}']".format(lib_dir), }, # Considering -libs-only-l and -libs-only-L # https://github.com/rpm-software-management/rpm/pull/327 { ...
def add_patchs_to_build_without_pkg_config(self, lib_dir, include_dir)
Add patches to remove pkg-config command and rpm.pc part. Replace with given library_path: lib_dir and include_path: include_dir without rpm.pc file.
4.398304
4.310285
1.020421
patches = self.patches content = None with open(self.IN_PATH) as f_in: # As setup.py.in file size is 2.4 KByte. # it's fine to read entire content. content = f_in.read() # Replace words. for key in self.replaced_word_dict: ...
def apply_and_save(self)
Apply replaced words and patches, and save setup.py file.
4.466107
4.116834
1.08484
top_dir_name = None if self.git_branch: # Download a source by git clone. top_dir_name = self._download_and_expand_by_git() else: # Download a source from the arcihve URL. # Downloading the compressed archive is better than "git clone", ...
def download_and_expand(self)
Download and expand RPM Python binding.
5.171849
5.015609
1.031151
self._make_lib_file_symbolic_links() self._copy_each_include_files_to_include_dir() self._make_dep_lib_file_sym_links_and_copy_include_files() self.setup_py.add_patchs_to_build_without_pkg_config( self.rpm.lib_dir, self.rpm.include_dir ) self.setup_py...
def run(self)
Run install main logic.
7.128586
6.728305
1.059492
so_file_dict = { 'rpmio': { 'sym_src_dir': self.rpm.lib_dir, 'sym_dst_dir': 'rpmio/.libs', 'require': True, }, 'rpm': { 'sym_src_dir': self.rpm.lib_dir, 'sym_dst_dir': 'lib/.libs', ...
def _make_lib_file_symbolic_links(self)
Make symbolic links for lib files. Make symbolic links from system library files or downloaded lib files to downloaded source library files. For example, case: Fedora x86_64 Make symbolic links from a. /usr/lib64/librpmio.so* (one of them) b. /usr/lib64/...
2.721995
2.501853
1.087991
src_header_dirs = [ 'rpmio', 'lib', 'build', 'sign', ] with Cmd.pushd('..'): src_include_dir = os.path.abspath('./include') for header_dir in src_header_dirs: if not os.path.isdir(header_dir): ...
def _copy_each_include_files_to_include_dir(self)
Copy include header files for each directory to include directory. Copy include header files from rpm/ rpmio/*.h lib/*.h build/*.h sign/*.h to rpm/ include/ rpm/*.h ...
3.043634
2.59051
1.174917
if not self._rpm_py_has_popt_devel_dep(): message = ( 'The RPM Python binding does not have popt-devel dependency' ) Log.debug(message) return if self._is_popt_devel_installed(): message = '{0} package is installed.'.fo...
def _make_dep_lib_file_sym_links_and_copy_include_files(self)
Make symbolick links for lib files and copy include files. Do below steps for a dependency packages. Dependency packages - popt-devel Steps 1. Make symbolic links from system library files or downloaded lib files to downloaded source library files. 2. Copy i...
3.818412
3.744539
1.019728
found = False with open('../include/rpm/rpmlib.h') as f_in: for line in f_in: if re.match(r'^#include .*popt.h.*$', line): found = True break return found
def _rpm_py_has_popt_devel_dep(self)
Check if the RPM Python binding has a depndency to popt-devel. Search include header files in the source code to check it.
4.117386
3.601273
1.143314
try: if not self._is_rpm_all_lib_include_files_installed(): self._make_lib_file_symbolic_links() self._copy_each_include_files_to_include_dir() self._make_dep_lib_file_sym_links_and_copy_include_files() self.setup_py.add_patchs...
def run(self)
Run install main logic.
6.365664
6.065749
1.049444
self._download_and_extract_rpm_py_package() # Find ./usr/lib64/pythonN.N/site-packages/rpm directory. # A binary built by same version Python with used Python is target # for the safe installation. if self.rpm.has_set_up_py_in(): # If RPM has setup.py.in, t...
def install_from_rpm_py_package(self)
Run install from RPM Python binding RPM package.
3.082473
3.052965
1.009665
linux = None if Cmd.which('apt-get'): linux = DebianLinux(python, rpm_path, **kwargs) else: linux = FedoraLinux(python, rpm_path, **kwargs) return linux
def get_instance(cls, python, rpm_path, **kwargs)
Get OS object.
3.879314
3.458202
1.121772
if not sys.platform.startswith('linux'): raise InstallError('Supported platform is Linux only.') if self.python.is_system_python(): if self.python.is_python_binding_installed(): message = ''' RPM Python binding already installed on system Python. Nothing...
def verify_system_status(self)
Verify system status.
7.251663
7.150516
1.014146
# rpm-libs is required for /usr/lib64/librpm*.so self.rpm.verify_packages_installed(['rpm-libs']) # Check RPM so files to build the Python binding. message_format = ''' RPM: {0} or RPM download tool (dnf-plugins-core (dnf) or yum-utils (yum)) required. Install any of those. '''...
def verify_package_status(self)
Verify dependency RPM package status.
10.541012
10.086446
1.045067
return FedoraInstaller(rpm_py_version, self.python, self.rpm, **kwargs)
def create_installer(self, rpm_py_version, **kwargs)
Create Installer object.
6.939909
6.408188
1.082975
return DebianInstaller(rpm_py_version, self.python, self.rpm, **kwargs)
def create_installer(self, rpm_py_version, **kwargs)
Create Installer object.
7.734736
7.013157
1.102889
libs = [self.python_lib_arch_dir, self.python_lib_non_arch_dir] def append_rpm(path): return os.path.join(path, 'rpm') return map(append_rpm, libs)
def python_lib_rpm_dirs(self)
Both arch and non-arch site-packages directories.
4.315709
3.476493
1.241397
is_installed = False is_install_error = False try: is_installed = self.is_python_binding_installed_on_pip() except InstallError: # Consider a case of pip is not installed in old Python (<= 2.6). is_install_error = True if not is_insta...
def is_python_binding_installed(self)
Check if the Python binding has already installed. Consider below cases. - pip command is not installed. - The installed RPM Python binding does not have information showed as a result of pip list.
3.787623
3.482317
1.087673
pip_version = self._get_pip_version() Log.debug('Pip version: {0}'.format(pip_version)) pip_major_version = int(pip_version.split('.')[0]) installed = False # --format is from pip v9.0.0 # https://pip.pypa.io/en/stable/news/ if pip_major_version >= 9: ...
def is_python_binding_installed_on_pip(self)
Check if the Python binding has already installed.
3.664224
3.595061
1.019238
stdout = Cmd.sh_e_out('{0} --version'.format(self.rpm_path)) rpm_version = stdout.split()[2] return rpm_version
def version(self)
RPM vesion string.
9.956802
6.282162
1.584933
sys_rpm_paths = [ '/usr/bin/rpm', # On CentOS6, system RPM is installed in this directory. '/bin/rpm', ] matched = False for sys_rpm_path in sys_rpm_paths: if self.rpm_path.startswith(sys_rpm_path): matched = True ...
def is_system_rpm(self)
Check if the RPM is system RPM.
3.698923
3.416813
1.082565
if not package_name: raise ValueError('package_name required.') installed = True try: Cmd.sh_e('{0} --query {1} --quiet'.format(self.rpm_path, package_name)) except InstallError: installed...
def is_package_installed(self, package_name)
Check if the RPM package is installed.
6.572613
5.274612
1.246085
if not package_names: raise ValueError('package_names required.') missing_packages = [] for package_name in package_names: if not self.is_package_installed(package_name): missing_packages.append(package_name) if missing_packages: ...
def verify_packages_installed(self, package_names)
Check if the RPM packages are installed. Raise InstallError if any of the packages is not installed.
3.352736
2.977933
1.12586
if not self._lib_dir: rpm_lib_dir = None cmd = '{0} -ql rpm-libs'.format(self.rpm_path) out = Cmd.sh_e_out(cmd) lines = out.split('\n') for line in lines: if 'librpm.so' in line: rpm_lib_dir = os.path.dirnam...
def lib_dir(self)
Return standard library directory path used by RPM libs. TODO: Support non-system RPM.
3.184533
2.905339
1.096097
is_plugin_avaiable = False if self.is_dnf: is_plugin_avaiable = self.is_package_installed( 'dnf-plugins-core') else: is_plugin_avaiable = self.is_package_installed( 'yum-utils') ...
def is_downloadable(self)
Return if rpm is downloadable by the package command. Check if dnf or yum plugin package exists.
4.708537
3.536761
1.331313
if not package_name: ValueError('package_name required.') if self.is_dnf: cmd = 'dnf download {0}.{1}'.format(package_name, self.arch) else: cmd = 'yumdownloader {0}.{1}'.format(package_name, self.arch) try: Cmd.sh_e(cmd, stdout=su...
def download(self, package_name)
Download given package.
3.959386
3.848583
1.028791
for cmd in ['rpm2cpio', 'cpio']: if not Cmd.which(cmd): message = '{0} command not found. Install {0}.'.format(cmd) raise InstallError(message) pattern = '{0}*{1}.rpm'.format(package_name, self.arch) rpm_files = Cmd.find('.', pattern) ...
def extract(self, package_name)
Extract given package.
3.983257
3.841526
1.036894
if not self._lib_dir: lib_files = glob.glob("/usr/lib/*/librpm.so*") if not lib_files: raise InstallError("Can not find lib directory.") self._lib_dir = os.path.dirname(lib_files[0]) return self._lib_dir
def lib_dir(self)
Return standard library directory path used by RPM libs.
3.29697
2.60252
1.266838
Log.debug('CMD: {0}'.format(cmd)) cmd_kwargs = { 'shell': True, } cmd_kwargs.update(kwargs) env = os.environ.copy() # Better to parse English output env['LC_ALL'] = 'en_US.utf-8' if 'env' in kwargs: env.update(kwargs['env'...
def sh_e(cls, cmd, **kwargs)
Run the command. It behaves like "sh -e". It raises InstallError if the command failed.
2.529401
2.522158
1.002872
cmd_kwargs = { 'stdout': subprocess.PIPE, } cmd_kwargs.update(kwargs) return cls.sh_e(cmd, **cmd_kwargs)[0]
def sh_e_out(cls, cmd, **kwargs)
Run the command. and returns the stdout.
3.333672
2.96373
1.124823
Log.debug('CMD: cd {0}'.format(directory)) os.chdir(directory)
def cd(cls, directory)
Change directory. It behaves like "cd directory".
6.670444
5.810431
1.148012
previous_dir = os.getcwd() try: new_ab_dir = None if os.path.isabs(new_dir): new_ab_dir = new_dir else: new_ab_dir = os.path.join(previous_dir, new_dir) # Use absolute path to show it on FileNotFoundError message. ...
def pushd(cls, new_dir)
Change directory, and back to previous directory. It behaves like "pushd directory; something; popd".
3.454486
3.527734
0.979236
abs_path_cmd = None if sys.version_info >= (3, 3): abs_path_cmd = shutil.which(cmd) else: abs_path_cmd = find_executable(cmd) return abs_path_cmd
def which(cls, cmd)
Return an absolute path of the command. It behaves like "which command".
2.749858
2.744659
1.001894
tar_gz_file_name = file_url.split('/')[-1] if sys.version_info >= (3, 2): from urllib.request import urlopen from urllib.error import HTTPError else: from urllib2 import urlopen from urllib2 import HTTPError response = None ...
def curl_remote_name(cls, file_url)
Download file_url, and save as a file name of the URL. It behaves like "curl -O or --remote-name". It raises HTTPError if the file_url not found.
2.213211
2.22318
0.995516
try: with contextlib.closing(tarfile.open(tar_comp_file_path)) as tar: tar.extractall() except tarfile.ReadError as e: message_format = ( 'Extract failed: ' 'tar_comp_file_path: {0}, reason: {1}' ) r...
def tar_extract(cls, tar_comp_file_path)
Extract tar.gz or tar bz2 file. It behaves like - tar xzf tar_gz_file_path - tar xjf tar_bz2_file_path It raises tarfile.ReadError if the file is broken.
2.741483
2.687602
1.020048
Log.debug('find {0} with pattern: {1}'.format(searched_dir, pattern)) matched_files = [] for root_dir, dir_names, file_names in os.walk(searched_dir, followlinks=False): for file_name in file_names: if fn...
def find(cls, searched_dir, pattern)
Find matched files. It does not include symbolic file in the result.
1.949984
1.866197
1.044897
if not isinstance(version_str, str): ValueError('version_str invalid instance.') version_info_list = re.findall(r'[0-9a-zA-Z]+', version_str) def convert_to_int(string): value = None if re.match(r'^\d+$', string): value = int(string) ...
def version_str2tuple(cls, version_str)
Version info. tuple object. ex. ('4', '14', '0', 'rc1')
2.681875
2.568462
1.044156
header = None for line in handle: if line.startswith(">"): if header is not None: # not the first record yield header, "".join(seq_lines) seq_lines = list() header = line[1:].rstrip() else: if header is not None: # not the f...
def FastaIter(handle)
generator that returns (header, sequence) tuples from an open FASTA file handle Lines before the start of the first record are ignored.
2.424237
2.284493
1.06117
for path in os.environ["PATH"].split(os.pathsep): if os.path.exists(os.path.join(path, file)): return os.path.join(path, file) return None
def which(file)
>>> which("sh") is not None True >>> which("bogus-executable-that-doesn't-exist") is None True
1.683786
2.080878
0.809171
python_path = sys.executable cmd = '{0} install.py'.format(python_path) exit_status = os.system(cmd) if exit_status != 0: raise Exception('Command failed: {0}'.format(cmd))
def install_rpm_py()
Install RPM Python binding.
3.103341
3.041469
1.020343
p = subprocess.Popen([exe, "-h"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) output = p.communicate() version_line = output[0].splitlines()[1] version = re.match(r"(?:Version:|bgzip \(htslib\))\s+(\d+\.\d+(\.\d+)?)", version_line).group(1) return version
def _get_bgzip_version(exe)
return bgzip version as string
2.586228
2.505376
1.032271
missing_file_exception = OSError if six.PY2 else FileNotFoundError min_bgzip_version = ".".join(map(str, min_bgzip_version_info)) exe = os.environ.get("SEQREPO_BGZIP_PATH", which("bgzip") or "/usr/bin/bgzip") try: bgzip_version = _get_bgzip_version(exe) except AttributeError: r...
def _find_bgzip()
return path to bgzip if found and meets version requirements, else exception
3.069873
3.038451
1.010341
namespace, alias = uri_re.match(uri).groups() return self.fetch(alias=alias, namespace=namespace, start=start, end=end)
def fetch_uri(self, uri, start=None, end=None)
fetch sequence for URI/CURIE of the form namespace:alias, such as NCBI:NM_000059.3.
5.262537
4.087036
1.287617
if not self._writeable: raise RuntimeError("Cannot write -- opened read-only") if self._upcase: seq = seq.upper() try: seqhash = bioutils.digests.seq_seqhash(seq) except Exception as e: import pprint _logger.critical(...
def store(self, seq, nsaliases)
nsaliases is a list of dicts, like: [{"namespace": "en", "alias": "rose"}, {"namespace": "fr", "alias": "rose"}, {"namespace": "es", "alias": "rosa"}]
3.641512
3.567336
1.020793
if translate_ncbi_namespace is None: translate_ncbi_namespace = self.translate_ncbi_namespace seq_id = self._get_unique_seqid(alias=alias, namespace=namespace) aliases = self.aliases.fetch_aliases(seq_id=seq_id, translate_ncbi_na...
def translate_alias(self, alias, namespace=None, target_namespaces=None, translate_ncbi_namespace=None)
given an alias and optional namespace, return a list of all other aliases for same sequence
2.81918
2.448267
1.1515
namespace, alias = identifier.split(nsa_sep) if nsa_sep in identifier else (None, identifier) aliases = self.translate_alias(alias=alias, namespace=namespace, target_namespaces=target_namespaces, ...
def translate_identifier(self, identifier, target_namespaces=None, translate_ncbi_namespace=None)
Given a string identifier, return a list of aliases (as identifiers) that refer to the same sequence.
3.256133
3.050558
1.067389
recs = self.aliases.find_aliases(alias=alias, namespace=namespace) seq_ids = set(r["seq_id"] for r in recs) if len(seq_ids) == 0: raise KeyError("Alias {} (namespace: {})".format(alias, namespace)) if len(seq_ids) > 1: # This should only happen when name...
def _get_unique_seqid(self, alias, namespace)
given alias and namespace, return seq_id if exactly one distinct sequence id is found, raise KeyError if there's no match, or raise ValueError if there's more than one match.
2.990371
2.731774
1.094663
ir = bioutils.digests.seq_vmc_identifier(seq) seq_aliases = [ { "namespace": ir["namespace"], "alias": ir["accession"], }, { "namespace": "SHA1", "alias": bioutils.digests.seq_sha1(seq) ...
def _update_digest_aliases(self, seq_id, seq)
compute digest aliases for seq and update; returns number of digest aliases (some of which may have already existed) For the moment, sha512 is computed for seq_id separately from the sha512 here. We should fix that.
3.332374
3.246712
1.026384