_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q47700
ObjectiveRequisiteSession.is_objective_required
train
def is_objective_required(self, objective_id=None, required_objective_id=None): """Tests if an objective is required before proceeding with an objective. arg: objective_id (osid.id.Id): Id of the dependent Objective arg: required_objective_id (osid.id.Id): Id of the required ...
python
{ "resource": "" }
q47701
ObjectiveRequisiteAssignmentSession.can_assign_requisites
train
def can_assign_requisites(self): """Tests if this user can manage objective requisites. A return of true does not guarantee successful authorization. A return of false indicates that it is known mapping methods in this session will result in a PermissionDenied. This is intended ...
python
{ "resource": "" }
q47702
ObjectiveRequisiteAssignmentSession.assign_objective_requisites
train
def assign_objective_requisites(self, objective_id=None, requisite_objective_ids=None): """Creates a requirement dependency between Objective + a list of objectives. NON-standard method impl by cjshaw arg: objective_id (osid.id.Id): the Id of the dependent Objective a...
python
{ "resource": "" }
q47703
ObjectiveBankAdminSession.create_objective_bank
train
def create_objective_bank(self, objective_bank_form=None): """Creates a new ObjectiveBank. arg: objectiveBankForm (osid.learning.ObjectiveBankForm): the form for this ObjectiveBank return: (osid.learning.ObjectiveBankForm) - the new ObjectiveBank raise...
python
{ "resource": "" }
q47704
ObjectiveBankAdminSession.delete_objective_bank
train
def delete_objective_bank(self, objective_bank_id=None): """Deletes an ObjectiveBank. arg: objectiveBankId (osid.id.Id): the Id of the ObjectiveBank to remove raise: NotFound - objectiveBankId not found raise: NullArgument - objectiveBankId is null raise: O...
python
{ "resource": "" }
q47705
ObjectiveBankHierarchySession.get_root_objective_bank_ids
train
def get_root_objective_bank_ids(self, alias): """Gets the root objective bank Ids in this hierarchy. return: (osid.id.IdList) - the root objective bank Ids raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure compliance: mandatory...
python
{ "resource": "" }
q47706
_jsTypeof
train
def _jsTypeof(o): '''Return a string similar to JS's typeof.''' if o == None: return 'object' elif o == Undefined: return 'undefined' elif isinstance(o, bool): return 'boolean' if isinstance(o, int) or isinstance(o, float): return 'number' elif isinstance(o, list)...
python
{ "resource": "" }
q47707
match
train
def match(sel, obj, arr=None, bailout_fn=None): '''Match a selector to an object, yielding the matched values. Args: sel: The JSONSelect selector to apply (a string) obj: The object against which to apply the selector arr: If sel contains ? characters, then the values in this array will...
python
{ "resource": "" }
q47708
AgentSearchSession.get_agents_by_search
train
def get_agents_by_search(self, agent_query, agent_search): """Pass through to provider AgentSearchSession.get_agents_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can('search'): raise ...
python
{ "resource": "" }
q47709
ffmpeg
train
def ffmpeg(*args, **kwargs): """Universal ffmpeg wrapper with progress and error handling""" ff = FFMPEG(*args, **kwargs) ff.start( stdin=kwargs.get("stdin", None), stdout=kwargs.get("stdout", None), stderr=kwargs.get("stderr", subprocess.PIPE) ) ff.wait(kwa...
python
{ "resource": "" }
q47710
Response._get_xml
train
def _get_xml(self, metric): """Returns the channel element of the RSS feed""" self._opener = urllib2.build_opener() self._opener.addheaders = [('User-agent', self.user_agent)] if metric: url = self.base_url + '?w={0}&u=c'.format(self.woeid) else: url = se...
python
{ "resource": "" }
q47711
Response._parse_text
train
def _parse_text(self, element_name, namespace=''): """ Returns the text, as a string, of the specified element in the specified namespace of the RSS feed. Takes element_name and namespace as strings. """ try: text = self._channel.find('.//' + namespace + elem...
python
{ "resource": "" }
q47712
Response._parse_attributes
train
def _parse_attributes(self, element_name, package_class, namespace=''): """ Returns an instance of the package_class instantiated with a dictionary of the attributes from element_name in the specified namespace of the RSS feed. """ return package_class( self._...
python
{ "resource": "" }
q47713
Response._parse_forecasts
train
def _parse_forecasts(self): """ Returns a list of instances of the forecast.Forecast class. Each instance of the class is instantiated with the attributes of the forecast elements in the RSS feed. """ forecasts = self._channel.findall( './/{0}{1}'.format(self....
python
{ "resource": "" }
q47714
Response._parse_image
train
def _parse_image(self): """ Returns an instance of the image.Image class for the RSS feed. """ image = { 'title': self._channel.find('./image/title').text, 'width': int(self._channel.find('./image/width').text), 'height': int(self._channel.find('./imag...
python
{ "resource": "" }
q47715
Response._parse_last_build_date
train
def _parse_last_build_date(self): """ Returns the last build date of the RSS feed as datetime.datetime object. Returned datetime is not time-zone aware """ date = self._channel.find('lastBuildDate').text date = parser.parse(date, ignoretz=True) return date
python
{ "resource": "" }
q47716
Client._get_proxy_info
train
def _get_proxy_info(self, _=None): """Generate a ProxyInfo class from a connected SSH transport Args: _ (None): Ignored. This is just here as the ProxyInfo spec requires it. Returns: SSHTunnelProxyInfo: A ProxyInfo with an active socket tunneled through SSH "...
python
{ "resource": "" }
q47717
Client._single_request
train
def _single_request(self, method, *args, **kwargs): """Make a single request to the fleet API endpoint Args: method (str): A dot delimited string indicating the method to call. Example: 'Machines.List' *args: Passed directly to the method being called. **kwargs: Pas...
python
{ "resource": "" }
q47718
Client._request
train
def _request(self, method, *args, **kwargs): """Make a request with automatic pagination handling Args: method (str): A dot delimited string indicating the method to call. Example: 'Machines.List' *args: Passed directly to the method being called. **kwargs: Passed d...
python
{ "resource": "" }
q47719
Client.create_unit
train
def create_unit(self, name, unit): """Create a new Unit in the cluster Create and modify Unit entities to communicate to fleet the desired state of the cluster. This simply declares what should be happening; the backend system still has to react to the changes in this desired state. The...
python
{ "resource": "" }
q47720
Client.set_unit_desired_state
train
def set_unit_desired_state(self, unit, desired_state): """Update the desired state of a unit running in the cluster Args: unit (str, Unit): The Unit, or name of the unit to update desired_state: State the user wishes the Unit to be in ("inactive", "loa...
python
{ "resource": "" }
q47721
Client.destroy_unit
train
def destroy_unit(self, unit): """Delete a unit from the cluster Args: unit (str, Unit): The Unit, or name of the unit to delete Returns: True: The unit was deleted Raises: fleet.v1.errors.APIError: Fleet returned a response code >= 400 """ ...
python
{ "resource": "" }
q47722
Client.list_units
train
def list_units(self): """Return the current list of the Units in the fleet cluster Yields: Unit: The next Unit in the cluster Raises: fleet.v1.errors.APIError: Fleet returned a response code >= 400 """ for page in self._request('Units.List'): ...
python
{ "resource": "" }
q47723
Client.get_unit
train
def get_unit(self, name): """Retreive a specifi unit from the fleet cluster by name Args: name (str): If specified, only this unit name is returned Returns: Unit: The unit identified by ``name`` in the fleet cluster Raises: fleet.v1.errors.APIError:...
python
{ "resource": "" }
q47724
Client.list_unit_states
train
def list_unit_states(self, machine_id=None, unit_name=None): """Return the current UnitState for the fleet cluster Args: machine_id (str): filter all UnitState objects to those originating from a specific machine unit_name (str): filter all UnitSt...
python
{ "resource": "" }
q47725
Client.list_machines
train
def list_machines(self): """Retrieve a list of machines in the fleet cluster Yields: Machine: The next machine in the cluster Raises: fleet.v1.errors.APIError: Fleet returned a response code >= 400 """ # loop through each page of results for pag...
python
{ "resource": "" }
q47726
Nats.convert
train
def convert(cls, value, from_base, to_base): """ Convert value from a base to a base. :param value: the value to convert :type value: sequence of int :param int from_base: base of value :param int to_base: base of result :returns: the conversion result :r...
python
{ "resource": "" }
q47727
Nats.convert_to_int
train
def convert_to_int(value, from_base): """ Convert value to an int. :param value: the value to convert :type value: sequence of int :param int from_base: base of value :returns: the conversion result :rtype: int :raises ConvertError: if from_base is less t...
python
{ "resource": "" }
q47728
Nats.convert_from_int
train
def convert_from_int(value, to_base): """ Convert int value to a base. :param int value: the value to convert, must be at least 0 :param int to_base: base of result, must be at least 2 :returns: the conversion result :rtype: list of int :raises BasesValueError: i...
python
{ "resource": "" }
q47729
Nats.carry_in
train
def carry_in(value, carry, base): """ Add a carry digit to a number represented by ``value``. :param value: the value :type value: list of int :param int carry: the carry digit (>= 0) :param int base: the base (>= 2) :returns: carry-out and result :rtype...
python
{ "resource": "" }
q47730
BitMEX.create_key
train
def create_key(self): """Create an API key.""" print("Creating key. Please input the following options:") name = input("Key name (optional): ") print("To make this key more secure, you should restrict the IP addresses that can use it. ") print("To use with all IPs, leave blank or...
python
{ "resource": "" }
q47731
BitMEX.list_keys
train
def list_keys(self): """List your API Keys.""" keys = self._curl_bitmex("/apiKey/") print(json.dumps(keys, sort_keys=True, indent=4))
python
{ "resource": "" }
q47732
BitMEX.enable_key
train
def enable_key(self): """Enable an existing API Key.""" print("This command will enable a disabled key.") apiKeyID = input("API Key ID: ") try: key = self._curl_bitmex("/apiKey/enable", postdict={"apiKeyID": apiKeyID}) print("Ke...
python
{ "resource": "" }
q47733
BitMEX.disable_key
train
def disable_key(self): """Disable an existing API Key.""" print("This command will disable a enabled key.") apiKeyID = input("API Key ID: ") try: key = self._curl_bitmex("/apiKey/disable", postdict={"apiKeyID": apiKeyID}) print(...
python
{ "resource": "" }
q47734
BitMEX.delete_key
train
def delete_key(self): """Delete an existing API Key.""" print("This command will delete an API key.") apiKeyID = input("API Key ID: ") try: self._curl_bitmex("/apiKey/", postdict={"apiKeyID": apiKeyID}, verb='DELETE') print("Key with ...
python
{ "resource": "" }
q47735
ColorSystem.load
train
def load(self, filename=None, refresh=False): """ Try to load the data from a pre existing data file if it exists. If the data file does not exist, refresh the data and save it in the data file for future use. The data file is a json file. :param filename: The filename t...
python
{ "resource": "" }
q47736
ColorSystem.request
train
def request(self, *args, **kwargs): """ Gets the request using the `_url` and converts it into a beautiful soup object. :param args: The args to pass on to `requests`. :param kwargs: The kwargs to pass on to `requests`. """ response = requests...
python
{ "resource": "" }
q47737
ColorSystem.find_closest
train
def find_closest(self, color): """ Find the closest color in the system to the given rgb values. :param color: Tuple of r, g, b values (scaled to 255). :returns: Tuple of name and rgb closest to the given color. """ # Find distance between colors and find name based ...
python
{ "resource": "" }
q47738
Objective.get_assessment_id
train
def get_assessment_id(self): """Gets the assessment ``Id`` associated with this learning objective. return: (osid.id.Id) - the assessment ``Id`` raise: IllegalState - ``has_assessment()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # Im...
python
{ "resource": "" }
q47739
Objective.get_knowledge_category_id
train
def get_knowledge_category_id(self): """Gets the grade ``Id`` associated with the knowledge dimension. return: (osid.id.Id) - the grade ``Id`` raise: IllegalState - ``has_knowledge_category()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ ...
python
{ "resource": "" }
q47740
Objective.get_cognitive_process_id
train
def get_cognitive_process_id(self): """Gets the grade ``Id`` associated with the cognitive process. return: (osid.id.Id) - the grade ``Id`` raise: IllegalState - ``has_cognitive_process()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # ...
python
{ "resource": "" }
q47741
ObjectiveForm.get_assessment_metadata
train
def get_assessment_metadata(self): """Gets the metadata for an assessment. return: (osid.Metadata) - metadata for the assessment *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_templat...
python
{ "resource": "" }
q47742
ObjectiveForm.clear_assessment
train
def clear_assessment(self): """Clears the assessment. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm...
python
{ "resource": "" }
q47743
ObjectiveForm.get_knowledge_category_metadata
train
def get_knowledge_category_metadata(self): """Gets the metadata for a knowledge category. return: (osid.Metadata) - metadata for the knowledge category *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get...
python
{ "resource": "" }
q47744
ObjectiveForm.set_knowledge_category
train
def set_knowledge_category(self, grade_id): """Sets the knowledge category. arg: grade_id (osid.id.Id): the new knowledge category raise: InvalidArgument - ``grade_id`` is invalid raise: NoAccess - ``grade_id`` cannot be modified raise: NullArgument - ``grade_id`` is ``nul...
python
{ "resource": "" }
q47745
ObjectiveForm.clear_knowledge_category
train
def clear_knowledge_category(self): """Clears the knowledge category. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resou...
python
{ "resource": "" }
q47746
ObjectiveForm.get_cognitive_process_metadata
train
def get_cognitive_process_metadata(self): """Gets the metadata for a cognitive process. return: (osid.Metadata) - metadata for the cognitive process *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_gr...
python
{ "resource": "" }
q47747
ObjectiveForm.clear_cognitive_process
train
def clear_cognitive_process(self): """Clears the cognitive process. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resourc...
python
{ "resource": "" }
q47748
Activity.get_objective_id
train
def get_objective_id(self): """Gets the ``Id`` of the related objective. return: (osid.id.Id) - the objective ``Id`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.Activity.get_objective_id if not bool(self....
python
{ "resource": "" }
q47749
Activity.get_courses
train
def get_courses(self): """Gets any courses associated with this activity. return: (osid.course.CourseList) - list of courses raise: IllegalState - ``is_course_based_activity()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: manda...
python
{ "resource": "" }
q47750
Activity.get_assessments
train
def get_assessments(self): """Gets any assessments associated with this activity. return: (osid.assessment.AssessmentList) - list of assessments raise: IllegalState - ``is_assessment_based_activity()`` is ``false`` raise: OperationFailed - unable to complete request ...
python
{ "resource": "" }
q47751
ActivityForm.get_assets_metadata
train
def get_assets_metadata(self): """Gets the metadata for the assets. return: (osid.Metadata) - metadata for the assets *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.ActivityForm.get_assets_metadata_template ...
python
{ "resource": "" }
q47752
ActivityForm.clear_assets
train
def clear_assets(self): """Clears the assets. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.ActivityForm.clear_a...
python
{ "resource": "" }
q47753
ActivityForm.get_courses_metadata
train
def get_courses_metadata(self): """Gets the metadata for the courses. return: (osid.Metadata) - metadata for the courses *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.ActivityForm.get_assets_metadata_template ...
python
{ "resource": "" }
q47754
ActivityForm.clear_courses
train
def clear_courses(self): """Clears the courses. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.ActivityForm.clear...
python
{ "resource": "" }
q47755
ActivityForm.get_assessments_metadata
train
def get_assessments_metadata(self): """Gets the metadata for the assessments. return: (osid.Metadata) - metadata for the assessments *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.ActivityForm.get_assets_metadata_te...
python
{ "resource": "" }
q47756
ActivityForm.clear_assessments
train
def clear_assessments(self): """Clears the assessments. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.ActivityFo...
python
{ "resource": "" }
q47757
ProficiencyForm.get_completion_metadata
train
def get_completion_metadata(self): """Gets the metadata for completion percentage. return: (osid.Metadata) - metadata for the completion percentage *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_gro...
python
{ "resource": "" }
q47758
ProficiencyForm.set_completion
train
def set_completion(self, completion): """Sets the completion percentage. arg: completion (decimal): the completion percentage raise: InvalidArgument - ``completion`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method mus...
python
{ "resource": "" }
q47759
ProficiencyForm.clear_completion
train
def clear_completion(self): """Clears the completion. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.grading.GradeSystemFo...
python
{ "resource": "" }
q47760
ProficiencyForm.clear_level
train
def clear_level(self): """Clears the level. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ if (self.get_level_metadata().is_read_only() or self...
python
{ "resource": "" }
q47761
ObjectiveBankNode.get_objective_bank
train
def get_objective_bank(self): """Gets the ``ObjectiveBank`` at this node. return: (osid.learning.ObjectiveBank) - the objective bank represented by this node *compliance: mandatory -- This method must be implemented.* """ if self._lookup_session is None: ...
python
{ "resource": "" }
q47762
ObjectiveBankNode.get_parent_objective_bank_nodes
train
def get_parent_objective_bank_nodes(self): """Gets the parents of this objective bank. return: (osid.learning.ObjectiveBankNodeList) - the parents of the ``id`` *compliance: mandatory -- This method must be implemented.* """ parent_objective_bank_nodes = [] ...
python
{ "resource": "" }
q47763
ObjectiveSearchSession.get_objectives_by_search
train
def get_objectives_by_search(self, objective_query, objective_search): """Pass through to provider ObjectiveSearchSession.get_objectives_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can('search')...
python
{ "resource": "" }
q47764
ActivitySearchSession.get_activities_by_search
train
def get_activities_by_search(self, activity_query, activitiesearch): """Pass through to provider ActivitySearchSession.get_activities_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can('search'): ...
python
{ "resource": "" }
q47765
ProficiencyLookupSession.get_proficiencies_for_resource_on_date
train
def get_proficiencies_for_resource_on_date(self, resource_id, from_, to): """Pass through to provider ProficiencyLookupSession.get_proficiencies_for_resource_on_date""" # Implemented from azosid template for - # osid.relationship.RelationshipLookupSession.get_relationships_for_source_on_date_tem...
python
{ "resource": "" }
q47766
ProficiencySearchSession.get_proficiencies_by_search
train
def get_proficiencies_by_search(self, proficiency_query, proficiency_search): """Pass through to provider ProficiencySearchSession.get_proficiencies_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._c...
python
{ "resource": "" }
q47767
compute_bin_edges
train
def compute_bin_edges(features, num_bins, edge_range, trim_outliers, trim_percentile, use_orig_distr=False): "Compute the edges for the histogram bins to keep it the same for all nodes." if use_orig_distr: print('Using original distribution (without histogram) to compute edge weights!') edges=N...
python
{ "resource": "" }
q47768
extract
train
def extract(features, groups, weight_method=default_weight_method, num_bins=default_num_bins, edge_range=default_edge_range, trim_outliers=default_trim_behaviour, trim_percentile=default_trim_percentile, use_original_distribution=False, ...
python
{ "resource": "" }
q47769
pairwise_extract
train
def pairwise_extract(features, groups, edges, weight_func, use_orig_distr, group_ids, num_groups, num_links, non_symmetric, return_networkx_graph, out_weights_path): """ Core function to compute the pair-wise histogram distance between all ROIs. Parameters ----...
python
{ "resource": "" }
q47770
identify_groups
train
def identify_groups(groups): """ To compute number of unique elements in a given membership specification. Parameters ---------- groups : numpy 1d array of length p, each value specifying which group that particular node belongs to. For examlpe, if you have a cortical thickness values for 1...
python
{ "resource": "" }
q47771
check_param_ranges
train
def check_param_ranges(num_bins, num_groups, num_values, trim_outliers, trim_percentile): """Ensuring the parameters are in valid ranges.""" if num_bins < minimum_num_bins: raise ValueError('Too few bins! The number of bins must be >= 5') if num_values < num_groups: raise ValueError('Insuf...
python
{ "resource": "" }
q47772
type_cast_params
train
def type_cast_params(num_bins, edge_range_spec, features, groups): """Casting inputs to required types.""" if isinstance(num_bins, str): # possible when called from CLI num_bins = np.float(num_bins) # rounding it to ensure it is int num_bins = np.rint(num_bins) if np.isnan(num_bin...
python
{ "resource": "" }
q47773
check_weight_method
train
def check_weight_method(weight_method_spec, use_orig_distr=False, allow_non_symmetric=False): "Check if weight_method is recognized and implemented, or ensure it is callable." if not isinstance(use_orig_distr, bool): raise TypeError('use_original_distribu...
python
{ "resource": "" }
q47774
check_params
train
def check_params(features_spec, groups_spec, num_bins, edge_range_spec, trim_outliers, trim_percentile): """Necessary check on values, ranges, and types.""" if isinstance(features_spec, str) and isinstance(groups_spec, str): features, groups = read_features_and_groups(features_spec, groups_spec) el...
python
{ "resource": "" }
q47775
run_cli
train
def run_cli(): "Command line interface to hiwenet." features_path, groups_path, weight_method, num_bins, edge_range, \ trim_outliers, trim_percentile, return_networkx_graph, out_weights_path = parse_args() # TODO add the possibility to process multiple combinations of parameters: diff subjects, diff m...
python
{ "resource": "" }
q47776
read_features_and_groups
train
def read_features_and_groups(features_path, groups_path): "Reader for data and groups" try: if not pexists(features_path): raise ValueError('non-existent features file') if not pexists(groups_path): raise ValueError('non-existent groups file') if isinstance(fea...
python
{ "resource": "" }
q47777
get_parser
train
def get_parser(): "Specifies the arguments and defaults, and returns the parser." parser = argparse.ArgumentParser(prog="hiwenet") parser.add_argument("-f", "--in_features_path", action="store", dest="in_features_path", required=True, help="Abs. path to file...
python
{ "resource": "" }
q47778
_init
train
def _init(board, project_dir): """ Initialize an OpenAg-based project. Internal function we use for both init and flash commands. """ project_dir = os.path.abspath(project_dir) # Initialize the platformio project pio_config_path = os.path.join(project_dir, "platformio.ini") if not os.pa...
python
{ "resource": "" }
q47779
run
train
def run( categories, param_file, project_dir, plugin, target, status_update_interval ): """ Generate code for this project and run it """ return _run( categories, param_file, project_dir, plugin, target, status_update_interval )
python
{ "resource": "" }
q47780
prune_unspecified_categories
train
def prune_unspecified_categories(modules, categories): """ Removes unspecified module categories. Mutates dictionary and returns it. """ res = {} for mod_name, mod_info in modules.items(): mod_categories = mod_info.get("categories", all_categories) for category in categories: ...
python
{ "resource": "" }
q47781
load_plugin
train
def load_plugin(plugin_name): """ Given a plugin name, load plugin cls from plugin directory. Will throw an exception if no plugin can be found. """ plugin_cls = plugin_map.get(plugin_name, None) if not plugin_cls: try: plugin_module_name, plugin_cls_name = plugin_name.split(...
python
{ "resource": "" }
q47782
lengths_offsets
train
def lengths_offsets(value): """Split the given comma separated value to multiple integer values. """ values = [] for item in value.split(','): item = int(item) values.append(item) return values
python
{ "resource": "" }
q47783
is_bam_valid
train
def is_bam_valid(bam_file): """Check if bam file is valid. Raises a ValueError if pysam cannot read the file. #TODO: pysam does not differentiate between BAM and SAM """ try: f = pysam.AlignmentFile(bam_file) except ValueError: raise except: raise else: f.cl...
python
{ "resource": "" }
q47784
is_fasta_valid
train
def is_fasta_valid(fasta_file): """Check if fasta file is valid. Raises a ValueError if pysam cannot read the file. #TODO: pysam does not differentiate between BAM and SAM """ try: f = pysam.FastaFile(fasta_file) except IOError: raise else: f.close() return True
python
{ "resource": "" }
q47785
get_first_transcript_name
train
def get_first_transcript_name(fasta_file): """Return the first FASTA sequence from the given FASTA file. Keyword arguments: fasta_file -- FASTA format file of the transcriptome """ with open_pysam_file(fname=fasta_file, ftype='fasta') as f: transcript_name = f.references[0] return tran...
python
{ "resource": "" }
q47786
get_fasta_record
train
def get_fasta_record(fasta_file, transcript_name): """Return a single transcript from a valid fasta file as a record. record[transcript_name] = sequence Keyword arguments: fasta_file -- FASTA format file of the transcriptome transcript_name -- Name of the transcript as in the FASTA header """...
python
{ "resource": "" }
q47787
get_three_frame_orfs
train
def get_three_frame_orfs(sequence, starts=None, stops=None): """Find ORF's in frames 1, 2 and 3 for the given sequence. Positions returned are 1-based (not 0) Return format [{'start': start_position, 'stop': stop_position, 'sequence': sequence}, ] Keyword arguments: sequence -- sequence for the t...
python
{ "resource": "" }
q47788
get_longest_orf
train
def get_longest_orf(orfs): """Find longest ORF from the given list of ORFs.""" sorted_orf = sorted(orfs, key=lambda x: len(x['sequence']), reverse=True)[0] return sorted_orf
python
{ "resource": "" }
q47789
filter_ribo_counts
train
def filter_ribo_counts(counts, orf_start=None, orf_stop=None): """Filter read counts and return only upstream of orf_start or downstream of orf_stop. Keyword arguments: counts -- Ribo-Seq read counts obtained from get_ribo_counts. orf_start -- Start position of the longest ORF. orf_stop -- Sto...
python
{ "resource": "" }
q47790
check_required_arguments
train
def check_required_arguments(ribo_file, transcriptome_fasta, transcript_name=None): """Check required arguments of both riboplot and ribocount.""" # Is this a valid BAM file? i.e., can pysam read it? try: is_bam_valid(ribo_file) except ValueError: log.error('The given RiboSeq BAM file is...
python
{ "resource": "" }
q47791
check_rna_file
train
def check_rna_file(rna_file): """Check if bedtools is available and if the given RNA-Seq bam file is valid. """ try: subprocess.check_output(['bedtools', '--version']) except OSError: log.error('Could not find bedtools in PATH. bedtools is required ' 'for generating RNA cov...
python
{ "resource": "" }
q47792
is_header
train
def is_header(line): """true if we are in a header""" if re.match('^@',line): f = line.rstrip().split("\t") if(len(f) > 9): return False return True return False
python
{ "resource": "" }
q47793
sort_header
train
def sort_header(header_text): """sort the chromosomes in a header text""" lines = header_text.rstrip().split("\n") rlens = {} for ln in lines: m = re.match('@SQ\tSN:(\S+)\tLN:(\S+)',ln) if m: rlens[m.group(1)] = m.group(2) output = '' done_lens = False for ln in lines: if re.match('@SQ\t...
python
{ "resource": "" }
q47794
SAM.alignment_ranges
train
def alignment_ranges(self): """Put the heavy alignment ranges calculation called on demand and then cached""" if not self.is_aligned(): raise ValueError("you can't get alignment ranges from something that didn't align") if self._alignment_ranges: return self._alignment_ranges self._alignment_ranges ...
python
{ "resource": "" }
q47795
SAM.target_sequence_length
train
def target_sequence_length(self): """ Get the length of the target sequence. length of the entire chromosome throws an error if there is no information available :return: length :rtype: int """ if not self.is_aligned(): raise ValueError("no length for reference when read is not not alig...
python
{ "resource": "" }
q47796
SAM.query_sequence
train
def query_sequence(self): """ Overrides align. corrects orientation with reverse complement if on negative strand .. warning:: this returns the full query sequence, not just the aligned portion, but i also does not include hard clipped portions (only soft clipped) """ if not self.entries.seq: return No...
python
{ "resource": "" }
q47797
SAM.query_sequence_length
train
def query_sequence_length(self): """ does not include hard clipped""" if self.entries.seq: return len(self.entries.seq) if not self.entries.cigar: raise ValueError('Cannot give a query length if no cigar and no query sequence are present') return sum([x[0] for x in self.cigar_array if re.match('[...
python
{ "resource": "" }
q47798
SAM.original_query_sequence_length
train
def original_query_sequence_length(self): """Similar to get_get_query_sequence_length, but it also includes hard clipped bases if there is no cigar, then default to trying the sequence :return: the length of the query before any clipping :rtype: int """ if not self.is_aligned() or not self....
python
{ "resource": "" }
q47799
SAM.actual_original_query_range
train
def actual_original_query_range(self): """ This accounts for hard clipped bases and a query sequence that hasnt been reverse complemented :return: the range covered on the original query sequence :rtype: GenomicRange """ l = self.original_query_sequence_length a = self.alignment_ranges ...
python
{ "resource": "" }