_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q49600
Video.preprocess
train
def preprocess(self, data): """ Processes popcorn JSON and builds a sane data model out of it @param data : The popcorn editor project json blob """ print 'Beginning pre-process...' for url, video in data['media'][0]['clipData'].iteritems(): print 'Downloadin...
python
{ "resource": "" }
q49601
Video.parse_duration
train
def parse_duration(self): """ Corrects for any offsets that may have been created by loop and skip events """ for edit in self.track_edits: if edit.edit_type == 'loopPlugin': self.duration += ( (edit.options['end'] - ...
python
{ "resource": "" }
q49602
wrap_lines
train
def wrap_lines(content, length=80): """Wraps long lines to a maximum length of 80. :param content: the content to wrap. :param legnth: the maximum length to wrap the content. :type content: str :type length: int :returns: a string containing the wrapped content. :rtype: str """ r...
python
{ "resource": "" }
q49603
format_numbers
train
def format_numbers(number, prefix=""): """Formats number in the scientific notation for LaTeX. :param number: the number to format. :param prefix: a prefix to add before the number (e.g. "p < "). :type number: str :type prefix: str :returns: a string containing the scientific notation of the ...
python
{ "resource": "" }
q49604
sanitize_tex
train
def sanitize_tex(original_text): """Sanitize TeX text. :param original_text: the text to sanitize for LaTeX. :type original_text: str :returns: the sanitize text. Text is sanitized by following these steps: 1. Replaces ``\\` by ``\\textbackslash`` 2. Escapes certain characters (such as ...
python
{ "resource": "" }
q49605
_CodeTextEdit.saveToFile
train
def saveToFile(self): """ Save the current text to file """ filename = self.codeEditor.dialog.getSaveFileName() if filename and filename != '.': with open(filename, 'w') as f: f.write(self.toPlainText()) print('saved script under %s' % file...
python
{ "resource": "" }
q49606
Publisher.publish
train
def publish(self, payload): '''Publish payload to the topic .. note:: If you publishes just after creating Publisher instance, it will causes lost of message. You have to add sleep if you just want to publish once. >>> pub = jps.Publisher('topic') >>> time.sleep(0.1) ...
python
{ "resource": "" }
q49607
XlsReader.formatrow
train
def formatrow(self, types, values, wanttupledate): """ Internal function used to clean up the incoming excel data """ ## Data Type Codes: ## EMPTY 0 ## TEXT 1 a Unicode string ## NUMBER 2 float ## DATE 3 float ## BOOLEAN 4 int; 1 means TRUE, 0 means FALSE ...
python
{ "resource": "" }
q49608
DspamMilter.connect
train
def connect(self, hostname, family, hostaddr): """ Log new connections. """ self.client_ip = hostaddr[0] self.client_port = hostaddr[1] self.time_start = time.time() logger.debug('<{}> Connect from {}[{}]:{}'.format( self.id, hostname, self.client_ip,...
python
{ "resource": "" }
q49609
DspamMilter.envrcpt
train
def envrcpt(self, rcpt, *params): """ Send all recipients to DSPAM. """ if rcpt.startswith('<'): rcpt = rcpt[1:] if rcpt.endswith('>'): rcpt = rcpt[:-1] if self.recipient_delimiter_re: rcpt = self.recipient_delimiter_re.sub('', rcpt) ...
python
{ "resource": "" }
q49610
DspamMilter.header
train
def header(self, name, value): """ Store all message headers, optionally clean them up. This simply stores all message headers so we can send them to DSPAM. Additionally, headers that have the same prefix as the ones we're about to add are deleted. """ self.mess...
python
{ "resource": "" }
q49611
DspamMilter.body
train
def body(self, block): """ Store message body. """ self.message += block logger.debug('<{}> Received {} bytes of message body'.format( self.id, len(block))) return Milter.CONTINUE
python
{ "resource": "" }
q49612
DspamMilter.close
train
def close(self): """ Log disconnects. """ time_spent = time.time() - self.time_start logger.debug( '<{}> Disconnect from [{}]:{}, time spent {:.3f} seconds'.format( self.id, self.client_ip, self.client_port, time_spent)) return Milter.CONTINUE
python
{ "resource": "" }
q49613
DspamMilter.compute_verdict
train
def compute_verdict(self, results): """ Match results to the configured reject, quarantine and accept classes, and return a verdict based on that. The verdict classes are matched in the order: reject_classes, quarantine_classes, accept_classes. This means that you can configure ...
python
{ "resource": "" }
q49614
DspamMilter.add_dspam_headers
train
def add_dspam_headers(self, results): """ Format DSPAM headers with passed results, and add them to the message. Args: results -- A results dictionary from DspamClient. """ for header in self.headers: hname = self.header_prefix + header if header....
python
{ "resource": "" }
q49615
DspamMilterDaemon.configure
train
def configure(self, config_file): """ Parse configuration, and setup objects to use it. """ cfg = configparser.RawConfigParser() try: cfg.readfp(open(config_file)) except IOError as err: logger.critical( 'Error while reading config...
python
{ "resource": "" }
q49616
list_instances
train
def list_instances( deployment_name='', cloud_name='EC2 us-east-1', view='tiny', ): """ Returns a list of instances from your account. :param str deployment_name: If provided, only lists servers in the specified deployment. :param str cloud_name: The friendly na...
python
{ "resource": "" }
q49617
run_script_on_server
train
def run_script_on_server( script_name, server_name, inputs=None, timeout_s=10, output=sys.stdout ): """ Runs a RightScript and polls for status. Sample usage:: from rightscale import run_script_on_server run_script_on_server( ...
python
{ "resource": "" }
q49618
get_by_path
train
def get_by_path(path, first=False): """ Search for resources using colon-separated path notation. E.g.:: path = 'deployments:production:servers:haproxy' haproxies = get_by_path(path) :param bool first: Always use the first returned match for all intermediate searches along the...
python
{ "resource": "" }
q49619
plot
train
def plot(x, y, z, ax=None, **kwargs): r""" Plot iso-probability mass function, converted to sigmas. Parameters ---------- x, y, z : numpy arrays Same as arguments to :func:`matplotlib.pyplot.contour` ax: axes object, optional :class:`matplotlib.axes._subplots.AxesSubplot` to pl...
python
{ "resource": "" }
q49620
plot_lines
train
def plot_lines(x, fsamps, ax=None, downsample=100, **kwargs): """ Plot function samples as a set of line plots. Parameters ---------- x: 1D array-like x values to plot fsamps: 2D array-like set of functions to plot at each x. As returned by :func:`fgivenx.compute_sample...
python
{ "resource": "" }
q49621
SolidityObjectDocumenter.add_content
train
def add_content(self, more_content): """Add content from source docs and user.""" sourcename = self.get_sourcename() if self.object.docs: self.add_line('', sourcename) for line in self.object.docs.splitlines(): self.add_line(line, sourcename) # a...
python
{ "resource": "" }
q49622
SolidityObjectDocumenter.document_members
train
def document_members(self, all_members=False): # type: (bool) -> None """Generate reST for member documentation. If *all_members* is True, do all members, else those given by *self.options.members*. """ sourcename = self.get_sourcename() want_all = all_members o...
python
{ "resource": "" }
q49623
Lab.addParameter
train
def addParameter( self, k, r ): """Add a parameter to the experiment's parameter space. k is the parameter name, and r is its range. :param k: parameter name :param r: parameter range""" if isinstance(r, six.string_types) or not isinstance(r, collections.Iterable): ...
python
{ "resource": "" }
q49624
Lab._crossProduct
train
def _crossProduct( self, ls ): """Internal method to generate the cross product of all parameter values, creating the parameter space for the experiment. :param ls: an array of parameter names :returns: list of dicts""" p = ls[0] ds = [] if len(ls) == 1: ...
python
{ "resource": "" }
q49625
Lab.parameterSpace
train
def parameterSpace( self ): """Return the parameter space of the experiment as a list of dicts, with each dict mapping each parameter name to a value. :returns: the parameter space as a list of dicts""" ps = self.parameters() if len(ps) == 0: return [] else: ...
python
{ "resource": "" }
q49626
Lab.runExperiment
train
def runExperiment( self, e ): """Run an experiment over all the points in the parameter space. The results will be stored in the notebook. :param e: the experiment""" # create the parameter space ps = self.parameterSpace() # run the experiment at each point nb ...
python
{ "resource": "" }
q49627
_getsetting
train
def _getsetting(setting, default): """Get `setting` if set, fallback to `default` if not This method tries to return the value of the specified setting from Django's settings module, after prefixing the name with _DJANGO_SETTING_PREFIX. If this fails for any reason, the value supplied in `default` will...
python
{ "resource": "" }
q49628
_setsetting
train
def _setsetting(setting, default): """Dynamically sets the variable named in `setting` This method uses `_getsetting()` to either fetch the setting from Django's settings module, or else fallback to the default value; it then sets a variable in this module with the returned value. """ value = _...
python
{ "resource": "" }
q49629
runPlink
train
def runPlink(options): """Run Plink with the ``mind`` option. :param options: the options. :type options: argparse.Namespace """ # The plink command plinkCommand = [ "plink", "--noweb", "--bfile" if options.is_bfile else "--tfile", options.ifile, "--min...
python
{ "resource": "" }
q49630
attribute_dependend_key
train
def attribute_dependend_key(key_function, *dependencies): """Return a cache key for the specified hashable arguments with additional dependent arguments.""" def dependend_key_function(self, *args, **kwargs): key = hash_key(*args, **kwargs) if len(dependencies) > 0: dependec...
python
{ "resource": "" }
q49631
raw
train
def raw(func, **func_args): """Decorator for eager functions checking input array and stripping away the weld_type. Stripping the weld_type is required to keep the same code in Series.apply and because Numpy functions don't (all) have kwargs. Passing weld_type to NumPy functions is unexpected and r...
python
{ "resource": "" }
q49632
Run.AssertRC
train
def AssertRC(self, rc=0): """ Assert used for testing on certain RC values :raises: ``AssertionError`` """ assert self.rc == rc, "Command `%s` failed. $? expected: %d, $? given: %d" % (self.command, rc, self.rc)
python
{ "resource": "" }
q49633
Run.command
train
def command(cls, command, stdin=None, shell=False): """ Runs specified command. The command can be fed with data on stdin with parameter ``stdin``. The command can also be treated as a shell command with parameter ``shell``. Please refer to subprocess.Popen on how does this stuff work ...
python
{ "resource": "" }
q49634
LazyResult.evaluate
train
def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1, apply_experimental_transforms=True): """Evaluate the stored expression. Parameters ---------- verbose : bool, optional Whether to print output for each Weld compilation step. ...
python
{ "resource": "" }
q49635
numpy_to_weld_type
train
def numpy_to_weld_type(np_dtype): """Convert from NumPy dtype to Weld type. Note that support for strings is intended to be only for Python 2 str and Python 3 bytes. No unicode. Parameters ---------- np_dtype : numpy.dtype or str NumPy dtype. Returns ------- WeldType ...
python
{ "resource": "" }
q49636
run
train
def run(filepath, wsgiapp, host, port, reload, interval, static, static_root, static_dirs, lineprof, lineprof_file, validate): """ Runs a development server for WSGI Application. Usage: $ wsgicli run hello.py app -h 0.0.0.0 -p 5000 --reload $ wsgicli run hello.py app --static --st...
python
{ "resource": "" }
q49637
shell
train
def shell(filepath, wsgiapp, interpreter, models): """ Runs a python shell. Usage: $ wsgicli shell app.py app -i ipython """ model_base_classes = get_model_base_classes() imported_objects = {} if models and model_base_classes: insert_import_path_to_sys_modules(filepath) ...
python
{ "resource": "" }
q49638
DictRegister.dfilter
train
def dfilter(self, **kwds): """Returns a DictRegister which contains only the elements that match the given specifications. """ starting_list = self[:] filtered_list = [] for key, value in six.iteritems(kwds): for item in starting_list: if self....
python
{ "resource": "" }
q49639
DictRegister.dpop
train
def dpop(self, **kwds): """Pops and returns the first element that matches the given specification. If no elements are found raises IndexError. """ item = self.dget(**kwds) self.remove(item) return item
python
{ "resource": "" }
q49640
DictRegister.dremove
train
def dremove(self, **kwds): """Removes from the object any element that matches the given specification. """ filtered_dr = self.dfilter(**kwds) for item in filtered_dr: self.remove(item) return filtered_dr
python
{ "resource": "" }
q49641
DictRegister.dremove_copy
train
def dremove_copy(self, **kwds): """Returns a copy of the object without any element that matches the given specification. """ copy_dr = DictRegister(self) copy_dr.dremove(**kwds) return copy_dr
python
{ "resource": "" }
q49642
get_media_with_naming
train
def get_media_with_naming (output_dir, media_url, uuid, size): """ Download a media file to a directory and name it based on the input parameters. 'output_dir' controls where the download is placed. 'media_url' is the url / link to the media that will be downloaded. 'uuid' is used to uniquely identify the out...
python
{ "resource": "" }
q49643
extend_webfont_settings
train
def extend_webfont_settings(webfont_settings): """ Validate a webfont settings and optionally fill missing ``csspart_path`` option. Args: webfont_settings (dict): Webfont settings (an item value from ``settings.ICOMOON_WEBFONTS``). Returns: dict: Webfont settings ""...
python
{ "resource": "" }
q49644
main
train
def main(url, lamson_host, lamson_port, lamson_debug): """ Create, connect, and block on the Lamson worker. """ try: worker = LamsonWorker(url=url, lamson_host=lamson_host, lamson_port=lamson_port, lamson_d...
python
{ "resource": "" }
q49645
LamsonWorker.received_new
train
def received_new(self, msg): """ As new messages arrive, deliver them to the lamson relay. """ logger.info("Receiving msg, delivering to Lamson...") logger.debug("Relaying msg to lamson: From: %s, To: %s", msg['From'], msg['To']) self._relay.deliver(m...
python
{ "resource": "" }
q49646
ResourceManager.add_path
train
def add_path(self, path, base=None, index=None, create=False): ''' Add a new path to the list of search paths. Return False if it does not exist. :param path: The new search path. Relative paths are turned into an absolute and normalized form. If the path looks like a fi...
python
{ "resource": "" }
q49647
add_file_handler_to_root
train
def add_file_handler_to_root(log_fn): """Adds a file handler to the root logging. :param log_fn: the name of the log file. :type log_fn: str """ file_handler = logging.FileHandler(log_fn, mode="w") file_handler.setFormatter(logging.Formatter( fmt="[%(asctime)s %(name)s %(levelname)s] ...
python
{ "resource": "" }
q49648
register
train
def register(reg_signal=signal.SIGQUIT, reg_unhandled=True, commands=[]): """ Registers exconsole hooks :param reg_signal: if not None, register signal handler (default: ``signal.SIGQUIT``) :param reg_unhandled: if ``True``, register unhandled exception hook (``sys.excepthook``) :param commands: li...
python
{ "resource": "" }
q49649
Scan.add_params
train
def add_params(self, p): """Add new variables or change values to be used for particular parameter names that will not be jointly varied.""" new_params = p.copy() for key,val in new_params.items(): if not isinstance(val, collections.Iterable): new_params[key] ...
python
{ "resource": "" }
q49650
RasterSet.GetRGB
train
def GetRGB(self, scheme='infrared', names=None): """Get an RGB color scheme based on predefined presets or specify your own band names to use. A given set of names always overrides a scheme. Note: Available schemes are defined in ``RGB_SCHEMES`` and include: - ``true`` ...
python
{ "resource": "" }
q49651
HTTPClient.login
train
def login(self): """ Gets and stores an OAUTH token from Rightscale. """ log.debug('Logging into RightScale...') login_data = { 'grant_type': 'refresh_token', 'refresh_token': self.refresh_token, } response = self._request('post', self....
python
{ "resource": "" }
q49652
HTTPClient.request
train
def request(self, method, path='/', url=None, ignore_codes=[], **kwargs): """ Wrapper for the ._request method that verifies if we're logged into RightScale before making a call, and sanity checks the oauth expiration time. :param str method: An HTTP method (e.g. 'get', 'post', ...
python
{ "resource": "" }
q49653
HTTPClient._request
train
def _request(self, method, path='/', url=None, ignore_codes=[], **kwargs): """ Performs HTTP request. :param str method: An HTTP method (e.g. 'get', 'post', 'PUT', etc...) :param str path: A path component of the target URL. This will be appended to the value of ``self.end...
python
{ "resource": "" }
q49654
validate
train
def validate(epub_path): """Minimal validation. :return bool: True if valid else False """ try: subprocess.check_call([c.JAVA, '-jar', c.EPUBCHECK, epub_path]) return True except subprocess.CalledProcessError: return False
python
{ "resource": "" }
q49655
rename_next_state_fluent
train
def rename_next_state_fluent(name: str) -> str: '''Returns next state fluent canonical name. Args: name (str): The current state fluent name. Returns: str: The next state fluent name. ''' i = name.index('/') functor = name[:i-1] arity = name[i+1:] return "{}/{}".format(...
python
{ "resource": "" }
q49656
rename_state_fluent
train
def rename_state_fluent(name: str) -> str: '''Returns current state fluent canonical name. Args: name (str): The next state fluent name. Returns: str: The current state fluent name. ''' i = name.index('/') functor = name[:i] arity = name[i+1:] return "{}'/{}".format(fun...
python
{ "resource": "" }
q49657
admin_url
train
def admin_url(model, url, object_id=None): """ Returns the URL for the given model and admin url name. """ opts = model._meta url = "admin:%s_%s_%s" % (opts.app_label, opts.object_name.lower(), url) args = () if object_id is not None: args = (object_id,) return reverse(url, args=...
python
{ "resource": "" }
q49658
SingletonAdmin.add_view
train
def add_view(self, *args, **kwargs): """ Redirect to the change view if the singleton instance exists. """ try: singleton = self.model.objects.get() except (self.model.DoesNotExist, self.model.MultipleObjectsReturned): kwargs.setdefault("extra_context", {}...
python
{ "resource": "" }
q49659
SingletonAdmin.changelist_view
train
def changelist_view(self, *args, **kwargs): """ Redirect to the add view if no records exist or the change view if the singleton instance exists. """ try: singleton = self.model.objects.get() except self.model.MultipleObjectsReturned: return super(...
python
{ "resource": "" }
q49660
SingletonAdmin.change_view
train
def change_view(self, *args, **kwargs): """ If only the singleton instance exists, pass ``True`` for ``singleton`` into the template which will use CSS to hide the "save and add another" button. """ kwargs.setdefault("extra_context", {}) kwargs["extra_context"]["s...
python
{ "resource": "" }
q49661
pub
train
def pub(topic_name, json_msg, repeat_rate=None, host=jps.env.get_master_host(), pub_port=jps.DEFAULT_PUB_PORT): '''publishes the data to the topic :param topic_name: name of the topic :param json_msg: data to be published :param repeat_rate: if None, publishes once. if not None, it is used as [Hz]. ...
python
{ "resource": "" }
q49662
echo
train
def echo(topic_name, num_print=None, out=sys.stdout, host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT): '''print the data for the given topic forever ''' class PrintWithCount(object): def __init__(self, out): self._printed = 0 self._out = out def print_...
python
{ "resource": "" }
q49663
show_list
train
def show_list(timeout_in_sec, out=sys.stdout, host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT): '''get the name list of the topics, and print it ''' class TopicNameStore(object): def __init__(self): self._topic_names = set() def callback(self, msg, topic): ...
python
{ "resource": "" }
q49664
record
train
def record(file_path, topic_names=[], host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT): '''record the topic data to the file ''' class TopicRecorder(object): def __init__(self, file_path, topic_names): self._topic_names = topic_names self._file_path = file_path...
python
{ "resource": "" }
q49665
topic_command
train
def topic_command(): '''command line tool for jps ''' parser = argparse.ArgumentParser(description='json pub/sub tool') pub_common_parser = jps.ArgumentParser(subscriber=False, add_help=False) sub_common_parser = jps.ArgumentParser(publisher=False, add_help=False) command_parsers = parser.add_su...
python
{ "resource": "" }
q49666
str_to_class
train
def str_to_class(class_name): """ Returns a class based on class name """ mod_str, cls_str = class_name.rsplit('.', 1) mod = __import__(mod_str, globals(), locals(), ['']) cls = getattr(mod, cls_str) return cls
python
{ "resource": "" }
q49667
get_hierarchy_uploader
train
def get_hierarchy_uploader(root): """ Returns uploader, that uses get_hierarch_path to store files """ # Workaround to avoid Django 1.7 makemigrations wierd behaviour: # More details: https://code.djangoproject.com/ticket/22436 import sys if len(sys.argv) > 1 and sys.argv[1] in ('makemigrati...
python
{ "resource": "" }
q49668
load_config_from_setup
train
def load_config_from_setup(app): """ Replace values in app.config from package metadata """ # for now, assume project root is one level up root = os.path.join(app.confdir, '..') setup_script = os.path.join(root, 'setup.py') fields = ['--name', '--version', '--url', '--author'] dist_info_...
python
{ "resource": "" }
q49669
TreeWalk.list_to_tree
train
def list_to_tree(cls, files): """Converts a list of filenames into a directory tree structure.""" def attach(branch, trunk): """Insert a branch of directories on its trunk.""" parts = branch.split('/', 1) if len(parts) == 1: # branch is a file trunk[...
python
{ "resource": "" }
q49670
AuthToken.create_token_for_user
train
def create_token_for_user(user: get_user_model()) -> bytes: """ Create a new random auth token for user. """ token = urandom(48) AuthToken.objects.create( hashed_token=AuthToken._hash_token(token), user=user) return token
python
{ "resource": "" }
q49671
Series.str
train
def str(self): """Get Access to string functions. Returns ------- StringMethods Examples -------- >>> sr = bl.Series([b' aB ', b'GoOsfrABA']) >>> print(sr.str.lower().evaluate()) <BLANKLINE> --- --------- 0 ab 1 go...
python
{ "resource": "" }
q49672
Series.evaluate
train
def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1, apply_experimental=True): """Evaluates by creating a Series containing evaluated data and index. See `LazyResult` Returns ------- Series Series with evaluated data and index. Example...
python
{ "resource": "" }
q49673
Series.tail
train
def tail(self, n=5): """Return Series with the last n values. Parameters ---------- n : int Number of values. Returns ------- Series Series containing the last n values. Examples -------- >>> sr = bl.Series(np.ara...
python
{ "resource": "" }
q49674
Series.unique
train
def unique(self): """Return unique values in the Series. Note that because it is hash-based, the result will NOT be in the same order (unlike pandas). Returns ------- LazyArrayResult Unique values in random order. """ return LazyArrayResult(weld_uni...
python
{ "resource": "" }
q49675
Series.fillna
train
def fillna(self, value): """Returns Series with missing values replaced with value. Parameters ---------- value : {int, float, bytes, bool} Scalar value to replace missing values with. Returns ------- Series With missing values replaced. ...
python
{ "resource": "" }
q49676
Series.apply
train
def apply(self, func, mapping=None, new_dtype=None, **kwargs): """Apply an element-wise UDF to the Series. There are currently 6 options for using a UDF. First 4 are lazy, other 2 are eager and require the use of the raw decorator: - One of the predefined functions in baloo.functions. ...
python
{ "resource": "" }
q49677
Series.from_pandas
train
def from_pandas(cls, series): """Create baloo Series from pandas Series. Parameters ---------- series : pandas.series.Series Returns ------- Series """ from pandas import Index as PandasIndex, MultiIndex as PandasMultiIndex if isinstanc...
python
{ "resource": "" }
q49678
read_source_manifest
train
def read_source_manifest(file_name): """Reads Illumina manifest.""" alleles = {} open_function = open if file_name.endswith(".gz"): open_function = gzip.open with open_function(file_name, 'rb') as input_file: header_index = dict([ (col_name, i) for i, col_name in ...
python
{ "resource": "" }
q49679
read_source_alleles
train
def read_source_alleles(file_name): """Reads an allele file.""" alleles = {} open_function = open if file_name.endswith(".gz"): open_function = gzip.open with open_function(file_name, 'rb') as input_file: for line in input_file: row = line.rstrip("\r\n").split("\t") ...
python
{ "resource": "" }
q49680
check_fam_for_samples
train
def check_fam_for_samples(required_samples, source, gold): """Check fam files for required_samples.""" # Checking the source panel source_samples = set() with open(source, 'r') as input_file: for line in input_file: sample = tuple(line.rstrip("\r\n").split(" ")[:2]) if sa...
python
{ "resource": "" }
q49681
read_same_samples_file
train
def read_same_samples_file(filename, out_prefix): """Reads a file containing same samples.""" # The same samples same_samples = [] # Creating the extraction files gold_file = None try: gold_file = open(out_prefix + ".gold_samples2keep", 'w') except IOError: msg = "{}: can't ...
python
{ "resource": "" }
q49682
flipSNPs
train
def flipSNPs(inPrefix, outPrefix, flipFileName): """Flip SNPs using Plink.""" plinkCommand = ["plink", "--noweb", "--bfile", inPrefix, "--flip", flipFileName, "--make-bed", "--out", outPrefix] runCommand(plinkCommand)
python
{ "resource": "" }
q49683
exclude_SNPs_samples
train
def exclude_SNPs_samples(inPrefix, outPrefix, exclusionSNP=None, keepSample=None, transpose=False): """Exclude some SNPs and keep some samples using Plink.""" if (exclusionSNP is None) and (keepSample is None): msg = "Something wront with development... work on that source code....
python
{ "resource": "" }
q49684
renameSNPs
train
def renameSNPs(inPrefix, updateFileName, outPrefix): """Updates the name of the SNPs using Plink.""" plinkCommand = ["plink", "--noweb", "--bfile", inPrefix, "--update-map", updateFileName, "--update-name", "--make-bed", "--out", outPrefix] runCommand(plinkCommand)
python
{ "resource": "" }
q49685
BinnedResult._read_binary
train
def _read_binary(self): """Reads data and metadata from binary format.""" # NOTE: binary files store binned data using Fortran-like ordering. # Dimensions are iterated like z, y, x (so x changes fastest) header_path = self.path + 'header' with open(header_path) as f_header: ...
python
{ "resource": "" }
q49686
BinnedResult._read_ascii
train
def _read_ascii(self): """Reads data and metadata from ASCII format.""" # NOTE: ascii files store binned data using C-like ordering. # Dimensions are iterated like x, y, z (so z changes fastest) header_str = '' with open(self.path) as f: for line in f: ...
python
{ "resource": "" }
q49687
BinnedResult._read_header
train
def _read_header(self, header_str): """Reads metadata from the header.""" # regular expressions re_float = '[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?' re_uint = '\d+' re_binning = '{d} in (?P<nbins>' + re_uint + ') bin[ s] ' re_binning += 'of (?P<binwidth>' + re_float + ')...
python
{ "resource": "" }
q49688
createGenderPlot
train
def createGenderPlot(bfile, intensities, problematic_samples, format, out_prefix): """Creates the gender plot. :param bfile: the prefix of the input binary file. :param intensities: the file containing the intensities. :param problematic_samples: the file containing the problematic...
python
{ "resource": "" }
q49689
createLrrBafPlot
train
def createLrrBafPlot(raw_dir, problematic_samples, format, dpi, out_prefix): """Creates the LRR and BAF plot. :param raw_dir: the directory containing the intensities. :param problematic_samples: the file containing the problematic samples. :param format: the format of the plot. :param dpi: the DPI...
python
{ "resource": "" }
q49690
checkBim
train
def checkBim(fileName, minNumber, chromosome): """Checks the BIM file for chrN markers. :param fileName: :param minNumber: :param chromosome: :type fileName: str :type minNumber: int :type chromosome: str :returns: ``True`` if there are at least ``minNumber`` markers on ...
python
{ "resource": "" }
q49691
computeNoCall
train
def computeNoCall(fileName): """Computes the number of no call. :param fileName: the name of the file :type fileName: str Reads the ``ped`` file created by Plink using the ``recodeA`` options (see :py:func:`createPedChr24UsingPlink`) and computes the number and percentage of no calls on the c...
python
{ "resource": "" }
q49692
computeHeteroPercentage
train
def computeHeteroPercentage(fileName): """Computes the heterozygosity percentage. :param fileName: the name of the input file. :type fileName: str Reads the ``ped`` file created by Plink using the ``recodeA`` options (see :py:func:`createPedChr23UsingPlink`) and computes the heterozygosity pe...
python
{ "resource": "" }
q49693
readCheckSexFile
train
def readCheckSexFile(fileName, allProblemsFileName, idsFileName, femaleF, maleF): """Reads the Plink check-sex output file. :param fileName: the name of the input file. :param allProblemsFileName: the name of the output file that will contain all the pro...
python
{ "resource": "" }
q49694
createPedChr23UsingPlink
train
def createPedChr23UsingPlink(options): """Run Plink to create a ped format. :param options: the options. :type options: argparse.Namespace Uses Plink to create a ``ped`` file of markers on the chromosome ``23``. It uses the ``recodeA`` options to use additive coding. It also subsets the data ...
python
{ "resource": "" }
q49695
createPedChr24UsingPlink
train
def createPedChr24UsingPlink(options): """Run plink to create a ped format. :param options: the options. :type options: argparse.Namespace Uses Plink to create a ``ped`` file of markers on the chromosome ``24``. It uses the ``recodeA`` options to use additive coding. It also subsets the data ...
python
{ "resource": "" }
q49696
ClusterLab.sync_imports
train
def sync_imports( self, quiet = False ): """Return a context manager to control imports onto all the engines in the underlying cluster. This method is used within a ``with`` statement. Any imports should be done with no experiments running, otherwise the method will block until the clus...
python
{ "resource": "" }
q49697
ClusterLab.runExperiment
train
def runExperiment( self, e ): """Run the experiment across the parameter space in parallel using all the engines in the cluster. This method returns immediately. The experiments are run asynchronously, with the points in the parameter space being explored randomly so that intermediate r...
python
{ "resource": "" }
q49698
ClusterLab.updateResults
train
def updateResults( self ): """Update our results within any pending results that have completed since we last retrieved results from the cluster. :returns: the number of pending results completed at this call""" # we do all the tests for pending results against the notebook directly, ...
python
{ "resource": "" }
q49699
ClusterLab._availableResultsFraction
train
def _availableResultsFraction( self ): """Private method to return the fraction of results available, as a real number between 0 and 1. This does not update the results fetched from the cluster. :returns: the fraction of available results""" tr = self.notebook().numberOfResults() + self...
python
{ "resource": "" }