_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q50500
task.participant
train
def participant(self): """ True if the tasks roles meet the legion's constraints, False otherwise. """ log = self._params.get('log', self._discard) context = self._context_build(pending=True) conf = self._config_pending if conf.get('control') == 'off': ...
python
{ "resource": "" }
q50501
task._event_register
train
def _event_register(self, control): """ Do all necessary event registration with the legion for events listed in the pending config. The default event action is to stop the task. """ log = self._params.get('log', self._discard) if 'events' not in self._config_running...
python
{ "resource": "" }
q50502
task._task_periodic
train
def _task_periodic(self): """ This is a callback that is registered to be called periodically from the legion. The legion chooses when it might be called, typically when it is otherwise idle. """ log = self._params.get('log', self._discard) log.debug("periodic") ...
python
{ "resource": "" }
q50503
task._signal
train
def _signal(self, sig, pid=None): """ Send a signal to one or all pids associated with this task. Never fails, but logs signalling faults as warnings. """ log = self._params.get('log', self._discard) if pid is None: pids = self.get_pids() else: ...
python
{ "resource": "" }
q50504
task.onexit
train
def onexit(self): """ Runs any "onexit" functions present in the config. This will normally be called from the proc_exit event handler after all processes in a task have stopped. Currently the following "onexit" types are supported: 'start': Set the specified task t...
python
{ "resource": "" }
q50505
task._shrink
train
def _shrink(self, needed, running): """ Shrink the process pool from the number currently running to the needed number. The processes will be sent a SIGTERM at first and if that doesn't clear the process, a SIGKILL. Errors will be logged but otherwise ignored. """ l...
python
{ "resource": "" }
q50506
task._mark_started
train
def _mark_started(self): """ Set the state information for a task once it has completely started. In particular, the time limit is applied as of this time (ie after and start delay has been taking. """ log = self._params.get('log', self._discard) now = time.time() ...
python
{ "resource": "" }
q50507
task.terminate
train
def terminate(self): """ Called when an existing task is removed from the configuration. This sets a Do Not Resuscitate flag and then initiates a stop sequence. Once all processes have stopped, the task will delete itself. """ log = self._params.get('log', self._disc...
python
{ "resource": "" }
q50508
task.apply
train
def apply(self): """ Make the pending config become the running config for this task by triggering any necessary changes in the running task. Returns True to request a shorter period before the next call, False if nothing special is needed. """ log = self._params.get...
python
{ "resource": "" }
q50509
task.manage
train
def manage(self): """ Manage the task to handle restarts, reconfiguration, etc. Returns True to request a shorter period before the next call, False if nothing special is needed. """ log = self._params.get('log', self._discard) if self._stopping: log.debu...
python
{ "resource": "" }
q50510
Lookup.get_first_key_from_value
train
def get_first_key_from_value(self, value): """ Gets the first key from given value. :param value: Value. :type value: object :return: Key. :rtype: object """ for key, data in self.iteritems(): if data == value: return key
python
{ "resource": "" }
q50511
Lookup.get_keys_from_value
train
def get_keys_from_value(self, value): """ Gets the keys from given value. :param value: Value. :type value: object :return: Keys. :rtype: object """ return [key for key, data in self.iteritems() if data == value]
python
{ "resource": "" }
q50512
ISet_Full.setXr
train
def setXr(self, Xr): """ set genotype data of the set component """ self.Xr = Xr self.gp_block.covar.G = Xr
python
{ "resource": "" }
q50513
Chi2mixture.sf
train
def sf(self,lrt): """ computes the survival function of a mixture of a chi-squared random variable of degree 0 and a scaled chi-squared random variable of degree d """ _lrt = SP.copy(lrt) _lrt[lrt<self.tol] = 0 pv = self.mixture*STATS.chi2.sf(_lrt/self.scale,self....
python
{ "resource": "" }
q50514
stringify
train
def stringify(data): """Turns all dictionary values into strings""" if isinstance(data, dict): for key, value in data.items(): data[key] = stringify(value) elif isinstance(data, list): return [stringify(item) for item in data] else: return smart_text(data) return...
python
{ "resource": "" }
q50515
MicropubClient.init_app
train
def init_app(self, app, client_id=None): """Initialize the Micropub extension if it was not given app in the constructor. Args: app (flask.Flask): the flask application to extend. client_id (string, optional): the IndieAuth client id, will be displayed when the u...
python
{ "resource": "" }
q50516
MicropubClient.authenticate
train
def authenticate(self, me, state=None, next_url=None): """Authenticate a user via IndieAuth. Args: me (string): the authing user's URL. if it does not begin with https?://, http:// will be prepended. state (string, optional): passed through the whole auth process, ...
python
{ "resource": "" }
q50517
MicropubClient.authorize
train
def authorize(self, me, state=None, next_url=None, scope='read'): """Authorize a user via Micropub. Args: me (string): the authing user's URL. if it does not begin with https?://, http:// will be prepended. state (string, optional): passed through the whole auth process,...
python
{ "resource": "" }
q50518
MicropubClient._start_indieauth
train
def _start_indieauth(self, me, redirect_url, state, scope): """Helper for both authentication and authorization. Kicks off IndieAuth by fetching the authorization endpoint from the user's homepage and redirecting to it. Args: me (string): the authing user's URL. if it does not...
python
{ "resource": "" }
q50519
MicropubClient.authenticated_handler
train
def authenticated_handler(self, f): """Decorates the authentication callback endpoint. The endpoint should take one argument, a flask.ext.micropub.AuthResponse. """ @functools.wraps(f) def decorated(): resp = self._handle_authenticate_response() return f(r...
python
{ "resource": "" }
q50520
MicropubClient.authorized_handler
train
def authorized_handler(self, f): """Decorates the authorization callback endpoint. The endpoint should take one argument, a flask.ext.micropub.AuthResponse. """ @functools.wraps(f) def decorated(): resp = self._handle_authorize_response() return f(resp) ...
python
{ "resource": "" }
q50521
getPosNew
train
def getPosNew(data): """ get Fixed position """ pos = data.geno['col_header']['pos'][:] chrom= data.geno['col_header']['chrom'][:] n_chroms = chrom.max() pos_new = [] for chrom_i in range(1,n_chroms+1): I = chrom==chrom_i _pos = pos[I] for i in range(1,_pos.shape[...
python
{ "resource": "" }
q50522
Index.add_field
train
def add_field(self, fieldname, fieldspec=whoosh_module_fields.TEXT): """Add a field in the index of the model. Args: fieldname (Text): This parameters register a new field in specified model. fieldspec (Name, optional): This option adds various options as were described before. Returns: ...
python
{ "resource": "" }
q50523
Index.delete_documents
train
def delete_documents(self): """Deletes all the documents using the pk associated to them. """ pk = str(self._primary_key) for doc in self._whoosh.searcher().documents(): if pk in doc: doc_pk = str(doc[pk]) self._whoosh.delete_by_term(pk, doc_pk)
python
{ "resource": "" }
q50524
Index.charge_documents
train
def charge_documents(self): """ This method allow you to charge documents you already have in your database. In this way an Index would be created according to the model and fields registered. """ doc_count = self._whoosh.doc_count() objs = orm.count(e for e in self._model)...
python
{ "resource": "" }
q50525
computePCs
train
def computePCs(plink_path,k,bfile,ffile): """ compute the first k principal components Input: k : number of principal components plink_path : plink path bfile : binary bed file (bfile.bed, bfile.bim and bfile.fam are required) ffile : name of output file ...
python
{ "resource": "" }
q50526
copy_helper
train
def copy_helper(app_or_project, name, directory, dist, template_dir, noadmin): """ Replacement for django copy_helper Copies a Django project layout template into the specified distribution directory """ import shutil if not re.search(r'^[_a-zA-Z]\w*$', name): # If it's not a valid direct...
python
{ "resource": "" }
q50527
start_distribution
train
def start_distribution(project_name, template_dir, dist, noadmin): """ Custom startproject command to override django default """ directory = os.getcwd() # Check that the project_name cannot be imported. try: import_module(project_name) except ImportError: pass else: ...
python
{ "resource": "" }
q50528
variance_K
train
def variance_K(K, verbose=False): """estimate the variance explained by K""" c = SP.sum((SP.eye(len(K)) - (1.0 / len(K)) * SP.ones(K.shape)) * SP.array(K)) scalar = (len(K) - 1) / c return 1.0/scalar
python
{ "resource": "" }
q50529
as_square_array
train
def as_square_array(arr): """Return arr massaged into a square array. Raises ValueError if arr cannot be so massaged. """ arr = np.atleast_2d(arr) if len(arr.shape) != 2 or arr.shape[0] != arr.shape[1]: raise ValueError("Expected square array") return arr
python
{ "resource": "" }
q50530
postprocess
train
def postprocess(options): """ perform parametric fit of the test statistics and provide permutation and test pvalues """ resdir = options.resdir out_file = options.outfile tol = options.tol print('.. load permutation results') file_name = os.path.join(resdir,'perm*','*.res') files = glob.g...
python
{ "resource": "" }
q50531
output_keywords_for_sources
train
def output_keywords_for_sources( input_sources, taxonomy_name, output_mode="text", output_limit=None, spires=False, match_mode="full", no_cache=False, with_author_keywords=False, rebuild_cache=False, only_core_tags=False, extract_acronyms=False, **kwargs): """Output the keywo...
python
{ "resource": "" }
q50532
get_keywords_from_local_file
train
def get_keywords_from_local_file( local_file, taxonomy_name, output_mode="text", output_limit=None, spires=False, match_mode="full", no_cache=False, with_author_keywords=False, rebuild_cache=False, only_core_tags=False, extract_acronyms=False): """Output keywords reading a local file...
python
{ "resource": "" }
q50533
get_keywords_from_text
train
def get_keywords_from_text(text_lines, taxonomy_name, output_mode="text", output_limit=None, spires=False, match_mode="full", no_cache=False, with_author_keywords=False, rebuild_cache=False, only_core_tags=False,...
python
{ "resource": "" }
q50534
parse
train
def parse(infix): """Parse the given infix string to an expression which can be evaluated. Known operators are: * or * and * not With the following precedences (from high to low): * not * and * or * ) * ( :param str infix: the input str...
python
{ "resource": "" }
q50535
create_and_push_expression
train
def create_and_push_expression(token, expressions): """Creates an expression from the given token and adds it to the stack of the given expression. In the case of "and" and "or" expressions the last expression is poped from the expression stack to link it to the new created one. """ if toke...
python
{ "resource": "" }
q50536
dict_to_switch
train
def dict_to_switch(d): """Convert of dictionary with integer keys to a switch statement.""" def lookup(query): return d[query] lookup._always_inline_ = True unrolling_items = unrolling_iterable(d.items()) return lookup
python
{ "resource": "" }
q50537
mcs_to_rate
train
def mcs_to_rate(mcs, bw=20, long_gi=True): """Convert MCS index to rate in Mbps. See http://mcsindex.com/ Args: mcs (int): MCS index bw (int): bandwidth, 20, 40, 80, ... long_gi(bool): True if long GI is used. Returns: rate (float): bitrate in Mbps >>> mcs_to_rat...
python
{ "resource": "" }
q50538
rate_to_mcs
train
def rate_to_mcs(rate, bw=20, long_gi=True): """Convert bit rate to MCS index. Args: rate (float): bit rate in Mbps bw (int): bandwidth, 20, 40, 80, ... long_gi (bool): True if long GI is used. Returns: mcs (int): MCS index >>> rate_to_mcs(120, bw=40, long_gi=False) ...
python
{ "resource": "" }
q50539
extract_abbreviations
train
def extract_abbreviations(fulltext): """Extract acronyms from the fulltext. :param fulltext: utf-8 string :return: dictionary of matches in a formt { <keyword object>, [matched skw or ckw object, ....] } or empty {} """ acronyms = {} for k, v in get_acronyms(fullte...
python
{ "resource": "" }
q50540
get_keywords_output
train
def get_keywords_output(single_keywords, composite_keywords, taxonomy_name, author_keywords=None, acronyms=None, output_mode="text", output_limit=0, spires=False, only_core_tags=False): """Return a formatted string representing the keywords in ...
python
{ "resource": "" }
q50541
build_marc
train
def build_marc(recid, single_keywords, composite_keywords, spires=False, author_keywords=None, acronyms=None): """Create xml record. :var recid: integer :var single_keywords: dictionary of kws :var composite_keywords: dictionary of kws :keyword spires: please don't use, left for hist...
python
{ "resource": "" }
q50542
_output_marc
train
def _output_marc(output_complete, categories, kw_field=None, auth_field=None, acro_field=None, provenience='Classifier'): """Output the keywords in the MARCXML format. :var skw_matches: list of single keywords :var ckw_matches: list of com...
python
{ "resource": "" }
q50543
_output_text
train
def _output_text(complete_output, categories): """Output the results obtained in text format. :return: str, html formatted output """ output = "" for result in complete_output: list_result = complete_output[result] if list_result: list_result_sorted = sorted(list_result...
python
{ "resource": "" }
q50544
_get_singlekws
train
def _get_singlekws(skw_matches, spires=False): """Get single keywords. :var skw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of formatted keywords """ output = {} for single_keyword, info in skw_matches: output[single_keyword.o...
python
{ "resource": "" }
q50545
_get_compositekws
train
def _get_compositekws(ckw_matches, spires=False): """Get composite keywords. :var ckw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of formatted keywords """ output = {} for composite_keyword, info in ckw_matches: output[composi...
python
{ "resource": "" }
q50546
_get_acronyms
train
def _get_acronyms(acronyms): """Return a formatted list of acronyms.""" acronyms_str = {} if acronyms: for acronym, expansions in iteritems(acronyms): expansions_str = ", ".join(["%s (%d)" % expansion for expansion in expansions]) acron...
python
{ "resource": "" }
q50547
filter_core_keywords
train
def filter_core_keywords(keywords): """Only return keywords that are CORE.""" matches = {} for kw, info in keywords.items(): if kw.core: matches[kw] = info return matches
python
{ "resource": "" }
q50548
clean_before_output
train
def clean_before_output(kw_matches): """Return a clean copy of the keywords data structure. Stripped off the standalone and other unwanted elements. """ filtered_kw_matches = {} for kw_match, info in iteritems(kw_matches): if not kw_match.nostandalone: filtered_kw_matches[kw_ma...
python
{ "resource": "" }
q50549
_skw_matches_comparator
train
def _skw_matches_comparator(kw0, kw1): """Compare 2 single keywords objects. First by the number of their spans (ie. how many times they were found), if it is equal it compares them by lenghts of their labels. """ def compare(a, b): return (a > b) - (a < b) list_comparison = compare(le...
python
{ "resource": "" }
q50550
_kw
train
def _kw(keywords): """Turn list of keywords into dictionary.""" r = {} for k, v in keywords: r[k] = v return r
python
{ "resource": "" }
q50551
_sort_kw_matches
train
def _sort_kw_matches(skw_matches, limit=0): """Return a resized version of keywords to the given length.""" sorted_keywords = list(skw_matches.items()) sorted(sorted_keywords, key=cmp_to_key(_skw_matches_comparator)) return limit and sorted_keywords[:limit] or sorted_keywords
python
{ "resource": "" }
q50552
get_partial_text
train
def get_partial_text(fulltext): """Return a short version of the fulltext used with partial matching mode. The version is composed of 20% in the beginning and 20% in the middle of the text. """ def _get_index(x): return int(float(x) / 100 * len(fulltext)) partial_text = [ fullt...
python
{ "resource": "" }
q50553
save_keywords
train
def save_keywords(filename, xml): """Save keyword XML to filename.""" tmp_dir = os.path.dirname(filename) if not os.path.isdir(tmp_dir): os.mkdir(tmp_dir) file_desc = open(filename, "w") file_desc.write(xml) file_desc.close()
python
{ "resource": "" }
q50554
_parse_marc_code
train
def _parse_marc_code(field): """Parse marc field and return default indicators if not filled in.""" field = str(field) if len(field) < 4: raise Exception('Wrong field code: %s' % field) else: field += '__' tag = field[0:3] ind1 = field[3].replace('_', '') ind2 = field[4].repl...
python
{ "resource": "" }
q50555
isotopePattern
train
def isotopePattern(sum_formula, threshold=1e-4, rel_threshold=True, desired_prob=None): """ Calculates isotopic peaks for a sum formula. :param sum_formula: text representation of an atomic composition :type sum_formula: str :param threshold: minimum peak abundance :type threshold: float :p...
python
{ "resource": "" }
q50556
SpectrumBase.trim
train
def trim(self, n_peaks): """ Sorts mass and intensities arrays in descending intensity order, then removes low-intensity peaks from the spectrum. :param n_peaks: number of peaks to keep """ self.sortByIntensity() ims.spectrum_trim(self.ptr, n_peaks)
python
{ "resource": "" }
q50557
ProfileSpectrum.centroids
train
def centroids(self, window_size=5): """ Detects peaks in raw data. :param mzs: sorted array of m/z values :param intensities: array of corresponding intensities :param window_size: size of m/z averaging window :returns: isotope pattern containing the centroids :...
python
{ "resource": "" }
q50558
TheoreticalSpectrum.centroids
train
def centroids(self, instrument, min_abundance=1e-4, points_per_fwhm=25): """ Estimates centroided peaks for a given instrument model. :param instrument: instrument model :param min_abundance: minimum abundance for including a peak :param points_per_fwhm: grid density used for en...
python
{ "resource": "" }
q50559
TheoreticalSpectrum.envelope
train
def envelope(self, instrument): """ Computes isotopic envelope for a given instrument model :param instrument: instrument model to use :returns: isotopic envelope as a function of mass :rtype: function float(mz: float) """ def envelopeFunc(mz): if is...
python
{ "resource": "" }
q50560
read_csv
train
def read_csv(directory): ''' Scrape a twitter archive csv, yielding tweet text. Args: directory (str): CSV file or (directory containing tweets.csv). field (str): Field with the tweet's text (default: text). fieldnames (list): The column names for a csv with no header. Must contain ...
python
{ "resource": "" }
q50561
set_namespace
train
def set_namespace(namespace, attribute, namespace_splitter=NAMESPACE_SPLITTER): """ Sets given namespace to given attribute. Usage:: >>> set_namespace("parent", "child") u'parent|child' :param namespace: Namespace. :type namespace: unicode :param attribute: Attribute. :typ...
python
{ "resource": "" }
q50562
get_namespace
train
def get_namespace(attribute, namespace_splitter=NAMESPACE_SPLITTER, root_only=False): """ Returns given attribute foundations.namespace. Usage:: >>> get_namespace("grandParent|parent|child") u'grandParent|parent' >>> get_namespace("grandParent|parent|child", root_only=True) ...
python
{ "resource": "" }
q50563
remove_namespace
train
def remove_namespace(attribute, namespace_splitter=NAMESPACE_SPLITTER, root_only=False): """ Returns attribute with stripped foundations.namespace. Usage:: >>> remove_namespace("grandParent|parent|child") u'child' >>> remove_namespace("grandParent|parent|child", root_only=True) ...
python
{ "resource": "" }
q50564
get_leaf
train
def get_leaf(attribute, namespace_splitter=NAMESPACE_SPLITTER): """ Returns given attribute leaf. Usage:: >>> get_leaf("grandParent|parent|child") u'child' :param attribute: Attribute. :type attribute: unicode :param namespace_splitter: Namespace splitter character. :type ...
python
{ "resource": "" }
q50565
center_widget_on_screen
train
def center_widget_on_screen(widget, screen=None): """ Centers given Widget on the screen. :param widget: Current Widget. :type widget: QWidget :param screen: Screen used for centering. :type screen: int :return: Definition success. :rtype: bool """ screen = screen and screen or...
python
{ "resource": "" }
q50566
load_data
train
def load_data(verbose=False): "Load all VBB stop names and IDs into a Pandas dataframe." df = pd.read_csv(STOPS_PATH, usecols=['stop_id', 'stop_name']) if verbose: print('- Loaded %d entries from "%s".' % (len(df), STOPS_PATH)) return df
python
{ "resource": "" }
q50567
filter_data
train
def filter_data(df, filter_name, verbose=False): "Filter certain entries with given name." # pick only entries ending with 'Berlin' in column stop_name, incl. '(Berlin)' # df = df[df.stop_name.apply(lambda cell: 'Berlin' in cell)] df = df[df.stop_name.apply( lambda cell: filter_name.encode('ut...
python
{ "resource": "" }
q50568
get_next_departures
train
def get_next_departures(stop, filter_line=None, num_line_groups=1, verbose=False): """ Get all real-time departure times for given stop and return as filtered table. Terminate if we can assume there is no connection to the internet. """ # Get departures table from online service # (great: we ...
python
{ "resource": "" }
q50569
show_header
train
def show_header(**header): "Display a HTTP-style header on the command-line." print('%s: %s' % ('Now', header['now'])) print('%s: %s' % ('Stop-Name', header['name'])) print('%s: %s' % ('Stop-ID', header.get('id', None))) print('')
python
{ "resource": "" }
q50570
show_table
train
def show_table(args): "Output table on standard out." df = load_data(verbose=args.verbose) df = filter_data(df, filter_name=args.filter_name, verbose=args.verbose) stop = re.sub(' +', ' ', args.stop) if re.match('^\d+$', stop.decode('utf-8')): _id = stop name = df[df.stop_id==int(_...
python
{ "resource": "" }
q50571
generate_csv
train
def generate_csv(src, out): """\ Walks through `src` and generates the CSV file `out` """ writer = UnicodeWriter(open(out, 'wb'), delimiter=';') writer.writerow(('Reference ID', 'Created', 'Origin', 'Subject')) for cable in cables_from_source(src, predicate=pred.origin_filter(pred.origin_germany...
python
{ "resource": "" }
q50572
handle_cable
train
def handle_cable(cable, handler, standalone=True): """\ Emits event from the provided `cable` to the handler. `cable` A cable object. `handler` A ICableHandler instance. `standalone` Indicates if a `start` and `end` event should be issued (default: ``True``). ...
python
{ "resource": "" }
q50573
make_authorization_endpoint
train
def make_authorization_endpoint(missing_redirect_uri, authorization_endpoint_uri, authorization_template_name): """ Returns a endpoint that handles OAuth authorization requests. The template described by ``authorization_template_name`` is rendered wi...
python
{ "resource": "" }
q50574
AuthorizationCodeGenerator.validate
train
def validate(self, request): """ Check that a Client's authorization request is valid. If the request is invalid or malformed in any way, raises the appropriate exception. Read `the relevant section of the specification <http://tools.ietf.org/html/rfc6749#section-4.1 .>`_ for descriptions of each ...
python
{ "resource": "" }
q50575
AuthorizationCodeGenerator.get_request_uri_parameters
train
def get_request_uri_parameters(self, as_dict=False): """ Return the URI parameters from a request passed to the 'validate' method The query parameters returned by this method **MUST** be included in the ``action=""`` URI of the authorization form presented to the user. This carries the original authori...
python
{ "resource": "" }
q50576
AuthorizationCodeGenerator.make_error_redirect
train
def make_error_redirect(self, authorization_error=None): """ Return a Django ``HttpResponseRedirect`` describing the request failure. If the :py:meth:`validate` method raises an error, the authorization endpoint should return the result of calling this method like so: >>> auth_code_generator = ( ...
python
{ "resource": "" }
q50577
AuthorizationCodeGenerator.make_success_redirect
train
def make_success_redirect(self): """ Return a Django ``HttpResponseRedirect`` describing the request success. The custom authorization endpoint should return the result of this method when the user grants the Client's authorization request. The request is assumed to have successfully been vetted by the...
python
{ "resource": "" }
q50578
strerror
train
def strerror(errno): """Translate an error code to a message string.""" from pypy.module._codecs.locale import str_decode_locale_surrogateescape return str_decode_locale_surrogateescape(os.strerror(errno))
python
{ "resource": "" }
q50579
OperationError.async
train
def async(self, space): "Check if this is an exception that should better not be caught." return (self.match(space, space.w_SystemExit) or self.match(space, space.w_KeyboardInterrupt))
python
{ "resource": "" }
q50580
OperationError.errorstr
train
def errorstr(self, space, use_repr=False): "The exception class and value, as a string." w_value = self.get_w_value(space) if space is None: # this part NOT_RPYTHON exc_typename = str(self.w_type) exc_value = str(w_value) else: w = space.wr...
python
{ "resource": "" }
q50581
FieldPlotter.make_plot
train
def make_plot(self): """Draw the plot on the figure attribute Uses matplotlib to draw and format the chart """ X, Y, DX, DY = self._calc_partials() # Plot the values self.figure = plt.Figure() axes = self.figure.add_subplot(1, 1, 1) axes....
python
{ "resource": "" }
q50582
TCPServer.start
train
def start(self): """ Starts the TCP server. :return: Method success. :rtype: bool """ if self.__online: raise foundations.exceptions.ServerOperationError( "{0} | '{1}' TCP Server is already online!".format(self.__class__.__name__, self)) ...
python
{ "resource": "" }
q50583
get_first_mapping
train
def get_first_mapping(cls): """This allows for Django-like inheritance of mapping configurations""" from .models import Indexable if issubclass(cls, Indexable) and hasattr(cls, "Mapping"): return cls.Mapping for base in cls.__bases__: mapping = get_first_mapping(base) if mapping...
python
{ "resource": "" }
q50584
DjangoMapping.configure_field
train
def configure_field(self, field): """This configures an Elasticsearch Mapping field, based on a Django model field""" from .models import Indexable # This is for reverse relations, which do not have a db column if field.auto_created and field.is_relation: if isinstance(field...
python
{ "resource": "" }
q50585
remote.param
train
def param (self, param, kwargs, default_value=False): """gets a param from kwargs, or uses a default_value. if found, it's removed from kwargs""" if param in kwargs: value= kwargs[param] del kwargs[param] else: value= default_value setattr (sel...
python
{ "resource": "" }
q50586
IMap._set_transmaps
train
def _set_transmaps(self): """Set translation maps for our standard.""" if self._std == 'ascii': self._lower_chars = string.ascii_lowercase self._upper_chars = string.ascii_uppercase elif self._std == 'rfc1459': self._lower_chars = (string.ascii_lowercase + ...
python
{ "resource": "" }
q50587
IDict.copy
train
def copy(self): """Return a copy of ourself.""" new_dict = IDict(std=self._std) new_dict.update(self.store) return new_dict
python
{ "resource": "" }
q50588
IString._irc_lower
train
def _irc_lower(self, in_string): """Convert us to our lower-case equivalent, given our std.""" conv_string = self._translate(in_string) if self._lower_trans is not None: conv_string = conv_string.translate(self._lower_trans) return str.lower(conv_string)
python
{ "resource": "" }
q50589
IString._irc_upper
train
def _irc_upper(self, in_string): """Convert us to our upper-case equivalent, given our std.""" conv_string = self._translate(in_string) if self._upper_trans is not None: conv_string = in_string.translate(self._upper_trans) return str.upper(conv_string)
python
{ "resource": "" }
q50590
list
train
def list(request, content_type, id): """ Wrapper exposing comment's render_comment_list tag as a view. """ # get object app_label, model = content_type.split('-') ctype = ContentType.objects.get(app_label=app_label, model=model) obj = ctype.get_object_for_this_type(id=id) # setup templa...
python
{ "resource": "" }
q50591
estimate_lambda
train
def estimate_lambda(pv): """estimate lambda form a set of PV""" LOD2 = sp.median(st.chi2.isf(pv,1)) L = (LOD2/0.456) return (L)
python
{ "resource": "" }
q50592
pretty_path
train
def pretty_path(path, _home_re=re.compile('^' + re.escape(os.path.expanduser('~') + os.sep))): """Prettify path for humans, and make it Unicode.""" path = format_filename(path) path = _home_re.sub('~' + os.sep, path) return path
python
{ "resource": "" }
q50593
serror
train
def serror(message, *args, **kwargs): """Print a styled error message, while using any arguments to format the message.""" if args or kwargs: message = message.format(*args, **kwargs) return secho(message, fg='white', bg='red', bold=True)
python
{ "resource": "" }
q50594
AliasedGroup.get_command
train
def get_command(self, ctx, cmd_name): """Map some aliases to their 'real' names.""" cmd_name = self.MAP.get(cmd_name, cmd_name) return super(AliasedGroup, self).get_command(ctx, cmd_name)
python
{ "resource": "" }
q50595
Configuration.from_context
train
def from_context(cls, ctx, config_paths=None, project=None): """Create a configuration object, and initialize the Click context with it.""" if ctx.obj is None: ctx.obj = Bunch() ctx.obj.cfg = cls(ctx.info_name, config_paths, project=project) return ctx.obj.cfg
python
{ "resource": "" }
q50596
Configuration.load
train
def load(self): """Load configuration from the defined locations.""" if not self.loaded: self.values = configobj.ConfigObj({}, **self.DEFAULT_CONFIG_OPTS) for path in self.locations(): try: part = configobj.ConfigObj(infile=path, **self.DEFAULT...
python
{ "resource": "" }
q50597
Configuration.get
train
def get(self, name, default=NO_DEFAULT): """ Return the specified name from the root section. Parameters: name (str): The name of the requested value. default (optional): If set, the default value to use instead of raising :class:`Logg...
python
{ "resource": "" }
q50598
WlTrace.next
train
def next(self): """Iteration function. Note that it is possible to yield dangling ack packets as well, so user can detect if the sniffer missed the previous packet. """ try: self._fetch() pkt = self.pkt_queue.popleft() try: se...
python
{ "resource": "" }
q50599
WlTrace.peek
train
def peek(self): """Get the current packet without consuming it. """ try: self._fetch() pkt = self.pkt_queue[0] return pkt except IndexError: raise StopIteration()
python
{ "resource": "" }