_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q52000
RefField.dereference
train
def dereference(self, session, ref, allow_none=False): """ Dereference a pymongo "DBRef" to this field's underlying type """ from ommongo.document import collection_registry # TODO: namespace support ref.type = collection_registry['global'][ref.collection] obj = session.dereferen...
python
{ "resource": "" }
q52001
Api.register
train
def register(self, resource=None, **meta): """ Add resource to the API. :param resource: Resource class for registration :param **meta: Redefine Meta options for the resource :return adrest.views.Resource: Generated resource. """ if resource is None: def wr...
python
{ "resource": "" }
q52002
Api.urls
train
def urls(self): """ Provide URLconf details for the ``Api``. And all registered ``Resources`` beneath it. :return list: URL's patterns """ urls = [] for url_name in sorted(self.resources.keys()): resource = self.resources[url_name] urls.ap...
python
{ "resource": "" }
q52003
Api.call
train
def call(self, name, request=None, **params): """ Call resource by ``Api`` name. :param name: The resource's name (short form) :param request: django.http.Request instance :param **params: Params for a resource's call :return object: Result of resource's execution """ ...
python
{ "resource": "" }
q52004
get_disk_usage
train
def get_disk_usage(path): """ Returns the allocated disk space for the given path in bytes. :param path: String representing the path as it would be given to the `du` command. Best to give an absolute path here. """ cmd = 'du -sh --block-size=1 {0}'.format(path) total = getoutput(cmd).sp...
python
{ "resource": "" }
q52005
get_section_list_name
train
def get_section_list_name(section): """ Return the list address of UW course section email list """ return get_course_list_name(section.curriculum_abbr, section.course_number, section.section_id, section.term...
python
{ "resource": "" }
q52006
exists_secondary_combined_list
train
def exists_secondary_combined_list(curriculum_abbr, course_number, primary_section_id, quarter, year): """ Return True if a combined mailman list exists for all the sec...
python
{ "resource": "" }
q52007
_announce_theta
train
def _announce_theta(theta): """ Announce theta values to the log. """ c = 299792.458 # km/s is_a_redshift = lambda p: p == "z" or p[:2] == "z_" for parameter, value in theta.items(): try: value[0] except (IndexError, TypeError): message = "\t{0}: {1:.3f}...
python
{ "resource": "" }
q52008
_default_output_prefix
train
def _default_output_prefix(filenames): """ Return a default filename prefix for output files based on the input files. :param filenames: The input filename(s): :type filenames: str or list of str :returns: The extensionless common prefix of the input filenames: :rtype...
python
{ "resource": "" }
q52009
estimate
train
def estimate(args, **kwargs): """ Return a point estimate of the model parameters theta given the data. """ expected_output_files = kwargs.pop("expected_output_files", None) if not expected_output_files: expected_output_files = ["estimate.pkl"] if args.plotting: expected...
python
{ "resource": "" }
q52010
optimise
train
def optimise(args, **kwargs): """ Optimise the model parameters. """ expected_output_files = kwargs.pop("expected_output_files", None) if not expected_output_files: expected_output_files = ["optimised.pkl"] if args.plotting: expected_output_files.extend([ ...
python
{ "resource": "" }
q52011
load_file_or_directory
train
def load_file_or_directory(path): """ given a path, determine if the path is a file or directory, and yield a list of absolute file paths """ assert os.path.exists(path), "{0} does not exist!".format(path) absolute_path = os.path.abspath(path) if not os.path.isdir(path): yield absolu...
python
{ "resource": "" }
q52012
retrieve_data
train
def retrieve_data(file_paths): """ passed an iterable list of file_paths, loop through all of them and generate a dictionary containing all the context """ data_dict = {} for file_path in file_paths: with open(file_path) as fh: try: content = yaml.load(fh.rea...
python
{ "resource": "" }
q52013
filter_data
train
def filter_data(data, filter_dict): """ filter a data dictionary for values only matching the filter """ for key, match_string in filter_dict.items(): if key not in data: logger.warning("{0} doesn't match a top level key".format(key)) continue values = data[key] m...
python
{ "resource": "" }
q52014
Rapt.to_sql
train
def to_sql(self, instring, schema, use_bag_semantics=False): """ Translate a relational algebra string into a SQL string. :param instring: a relational algebra string to translate :param schema: a mapping of relation names to their attributes :param use_bag_semantics: flag for u...
python
{ "resource": "" }
q52015
Rapt.to_sql_sequence
train
def to_sql_sequence(self, instring, schema, use_bag_semantics=False): """ Translate a relational algebra string into a list of SQL strings generated by a post-order traversal of the parse tree for the input string. :param instring: a relational algebra string to translate :param...
python
{ "resource": "" }
q52016
Rapt.to_qtree
train
def to_qtree(self, instring, schema): """ Translate a relational algebra string into a string representing a latex tree, using the grammar. """ root_list = self.to_syntax_tree(instring, schema) return qtree_translator.translate(root_list)
python
{ "resource": "" }
q52017
tcache
train
def tcache(parser, token): """ This will cache the contents of a template fragment for a given amount of time with support tags. Usage:: {% tcache [expire_time] [fragment_name] [tags='tag1,tag2'] %} .. some expensive processing .. {% endtcache %} This tag also supports ...
python
{ "resource": "" }
q52018
ResultSet.count
train
def count(self): """Total count of the matching items. It sums up the count of partial results, and returns the total count of matching items in the table. """ count = 0 operation = self._get_operation() kwargs = self.kwargs.copy() kwargs['select'] = 'COU...
python
{ "resource": "" }
q52019
CourseAvailableEvent.get_surrogate_id
train
def get_surrogate_id(self): """ This is responsible for building the surrogate id from the model """ surrogate_id = "%s,%s,%s,%s,%s" % (self.year, self.quarter, self.curriculum_abbr.lower(), ...
python
{ "resource": "" }
q52020
GPG._verify
train
def _verify(self): """Some sanity checks on GPG.""" if not self.keyid: raise ValueError('No GPG key specified for signing, did you mean to use --no-sign?') sign = self.gpg.sign('', keyid=self.keyid) if 'secret key not available' in sign.stderr: raise ValueError('K...
python
{ "resource": "" }
q52021
index_normalize
train
def index_normalize(index_val): """Normalize dictionary calculated key When parsing, keys within a dictionary may come from the input text. To ensure there is no space or other special caracters, one should use this function. This is useful because DictExt dictionaries can be access with a dotted notat...
python
{ "resource": "" }
q52022
SequenceField.wrap_value
train
def wrap_value(self, value): ''' A function used to wrap a value used in a comparison. It will first try to wrap as the sequence's sub-type, and then as the sequence itself''' try: return self.item_type.wrap_value(value) except BadValueException: ...
python
{ "resource": "" }
q52023
ListField.unwrap
train
def unwrap(self, value, session=None): ''' Unwraps the elements of ``value`` using ``ListField.item_type`` and returns them in a list''' kwargs = {} if self.has_autoload: kwargs['session'] = session self.validate_unwrap(value, **kwargs) return [ self.item_...
python
{ "resource": "" }
q52024
SetField.unwrap
train
def unwrap(self, value, session=None): ''' Unwraps the elements of ``value`` using ``SetField.item_type`` and returns them in a set''' self.validate_unwrap(value) return set([self.item_type.unwrap(v, session=session) for v in value])
python
{ "resource": "" }
q52025
find_function
train
def find_function(root, function_name): """Search an AST for a function with the given name. A KeyError is raised if the function is not found. root: an AST node function_name: function to search for (string) """ finder = _FindFunctionVisitor(function_name) finder.visit(root) if find...
python
{ "resource": "" }
q52026
load_version_as_string
train
def load_version_as_string(): """Get the current version from version.py as a string.""" with open(VERSION_PATH, 'r') as rfile: contents = rfile.read().strip() _, version = contents.split('=') version = version.strip() # Remove quotes return version.strip('"\'')
python
{ "resource": "" }
q52027
load_from_tarfile
train
def load_from_tarfile(session, tarfile_path, check_for_duplicates, pkts_per_commit=1000): """ Iterate through xml files in a tarball and attempt to load into database. .. warning:: Very slow with duplicate checking enabled. Returns: tuple: (n_parsed, n_loaded) - T...
python
{ "resource": "" }
q52028
EntryAdminMarkItUpMixin.content_preview
train
def content_preview(self, request): """ Admin view to preview Entry.content in HTML, useful when using markups to write entries. """ data = request.POST.get('data', '') entry = self.model(content=data) return TemplateResponse( request, 'admin/zinnia/en...
python
{ "resource": "" }
q52029
EntryAdminMarkItUpMixin.get_urls
train
def get_urls(self): """ Overload the admin's urls for MarkItUp. """ entry_admin_urls = super(EntryAdminMarkItUpMixin, self).get_urls() urls = [ url(r'^markitup/$', self.admin_site.admin_view(self.markitup), name='zinnia_entry_markitup')...
python
{ "resource": "" }
q52030
recast
train
def recast(args): """ Create a model by recasting an existing model. """ import yaml from numpy import arange from sick.models import Model # Load in the original model. model = Model(args.original_model_filename) # Load in the channel information with open(args.channel_descriptio...
python
{ "resource": "" }
q52031
create
train
def create(args): """ Create a model from wavelength and flux files. """ from sick.models.create import create return create(os.path.join(args.output_dir, args.model_name), args.grid_points_filename, args.wavelength_filenames, clobber=args.clobber)
python
{ "resource": "" }
q52032
earliest_date
train
def earliest_date(dates, full_date=False): """Return the earliest among the schema-compliant dates. This is a convenience wrapper around :ref:`PartialDate`, which should be used instead if more features are needed. Args: dates(list): List of dates from which oldest/earliest one will be returne...
python
{ "resource": "" }
q52033
ensure_scheme
train
def ensure_scheme(url, default_scheme='http'): """Adds a scheme to a url if not present. Args: url (string): a url, assumed to start with netloc default_scheme (string): a scheme to be added Returns: string: URL with a scheme """ parsed = urlsplit(url, scheme=default_scheme...
python
{ "resource": "" }
q52034
initialize
train
def initialize(album_cache, image_cache, albums, images): """Instantiate Album or Image instances not already in cache. :param dict album_cache: Cache of Imgur albums to update. Keys are Imgur IDs, values are Album instances. :param dict image_cache: Cache of Imgur images to update. Keys are Imgur IDs, val...
python
{ "resource": "" }
q52035
prune_cache
train
def prune_cache(album_cache, image_cache, app, doctree_album_ids=None, doctree_image_ids=None): """Remove Images and Albums from the cache if they are no longer used. :param dict album_cache: Cache of Imgur albums to update. Keys are Imgur IDs, values are Album instances. :param dict image_cache: Cache of ...
python
{ "resource": "" }
q52036
update_cache
train
def update_cache(album_cache, image_cache, app, client_id, ttl, album_whitelist, image_whitelist): """Update cache items with expired TTLs. :param dict album_cache: Cache of Imgur albums to update. Keys are Imgur IDs, values are Album instances. :param dict image_cache: Cache of Imgur images to update. Key...
python
{ "resource": "" }
q52037
CoreGrammar.expression
train
def expression(self): """ A relation algebra expression. An expression is either a relation or a combination of relations that uses the previously defined operators and follows precedence rules. """ return operatorPrecedence(self.relation, [ (self.unary_op, 1,...
python
{ "resource": "" }
q52038
CoreGrammar.statement
train
def statement(self): """ A terminated relational algebra statement. """ return (self.assignment ^ self.expression) + Suppress( self.syntax.terminator)
python
{ "resource": "" }
q52039
CoreGrammar.parameter
train
def parameter(self, parser): """ Return a parser the parses parameters. """ return (Suppress(self.syntax.params_start).leaveWhitespace() + Group(parser) + Suppress(self.syntax.params_stop))
python
{ "resource": "" }
q52040
CoreGrammar.parametrize
train
def parametrize(self, operator, params): """ Return a parser that parses an operator with parameters. """ return (CaselessKeyword(operator, identChars=alphanums) + self.parameter(params))
python
{ "resource": "" }
q52041
download_script
train
def download_script(script_file_name): '''Send a script directly from the scripts directory''' return "Sorry! Temporarily disabled." if script_file_name[:-3] in registered_modules: loaded_module = registered_modules[script_file_name[:-3]] package_path = os.sep.join(loaded_module.__package__....
python
{ "resource": "" }
q52042
download_file
train
def download_file(file_id, file_name): '''Download a file from UPLOAD_FOLDER''' extracted_out_dir = os.path.join(app.config['UPLOAD_FOLDER'], file_id) return send_file(os.path.join(extracted_out_dir, file_name))
python
{ "resource": "" }
q52043
script_input
train
def script_input(module_name): '''Render a module's input page. Forms are created based on objects in the module's WebAPI class.''' if module_name not in registered_modules: return page_not_found(module_name) form = registered_modules[module_name].WebAPI() return render_template('script_inde...
python
{ "resource": "" }
q52044
order_by_header
train
def order_by_header(table, headers): '''Convert a list of dicts to a list or OrderedDicts ordered by headers''' ordered_table = [] for row in table: # Tricky list comprehension got tricky when needing special handling # Lets do this the simplest way we can: row = {k:v for k,v in row....
python
{ "resource": "" }
q52045
load_scripts
train
def load_scripts(): '''Import all of the modules named in REGISTERED_SCRIPTS''' # Add scrypture package package to the path before importing # so everything can import everything else regardless of package scrypture_dir = os.path.realpath( os.path.abspath( ...
python
{ "resource": "" }
q52046
IpCorePackager.serialzeValueToTCL
train
def serialzeValueToTCL(self, val, do_eval=False) -> Tuple[str, str, bool]: """ Serialize value to TCL :return: tuple (serialized value, serialized evaluated value of value, value is constant flag) """ return str(val), str(val), True
python
{ "resource": "" }
q52047
is_higher_permission
train
def is_higher_permission(level1, level2): """ Return True if the level1 is higher than level2 """ return (is_publish_permission(level1) and not is_publish_permission(level2) or (is_edit_permission(level1) and not is_publish_permission(level2) and not is_...
python
{ "resource": "" }
q52048
_extract_mock_name
train
def _extract_mock_name(in_mock): """Prints the mock access path Code from __repr__ code in mock.py Given a mock prints the whole access chain since the root mock """ _name_list = [in_mock._mock_new_name] _parent = in_mock._mock_new_parent last = in_mock dot = '.' if _name_list == ...
python
{ "resource": "" }
q52049
_get_child_mock
train
def _get_child_mock(mock, **kw): """Intercepts call to generate new mocks and raises instead""" attribute = "." + kw["name"] if "name" in kw else "()" mock_name = _extract_mock_name(mock) + attribute raise AttributeError(mock_name)
python
{ "resource": "" }
q52050
seal
train
def seal(mock): """Disable the automatic generation of "submocks" Given an input Mock, seals it to ensure no further mocks will be generated when accessing an attribute that was not already defined. Submocks are defined as all mocks which were created DIRECTLY from the parent. If a mock is assigne...
python
{ "resource": "" }
q52051
Problem.add_constraint
train
def add_constraint(self, func, variables, default_values=None): """Adds a constraint that applies to one or more variables. The function must return true or false to indicate which combinations of variable values are valid. """ self._constraints.append((func, variables, default_...
python
{ "resource": "" }
q52052
viewport_to_screen_space
train
def viewport_to_screen_space(framebuffer_size: vec2, point: vec4) -> vec2: """Transform point in viewport space to screen space.""" return (framebuffer_size * point.xy) / point.w
python
{ "resource": "" }
q52053
parse_incoming_query
train
def parse_incoming_query(factory, static_conditions=None, include_value=[], model_aggregations=dict()): ''' Effect factory parsing the query value from params and merging in the static_conditions specified. @param factory: IQueryView @param static_conditions: effect to be c...
python
{ "resource": "" }
q52054
draw_cloud
train
def draw_cloud(width=140, height=60, color=rgb(255, 255, 255)): """ Draw a cloud with the given width, height, and color. """ cairo_color = color / rgb(255, 255, 255) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) ctx = cairo.Context(surface) # A cloud consists of 4 circles ...
python
{ "resource": "" }
q52055
to_dc
train
def to_dc(data): """ Convert WA-KAT `data` to Dublin core XML. Args: data (dict): Nested WA-KAT data. See tests for example. Returns: unicode: XML with dublin core. """ root = odict[ "metadata": odict[ "@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance...
python
{ "resource": "" }
q52056
GnuPG.recv_keys
train
def recv_keys(self, keyserver, keys): ''' Import the keys with the given key IDs from a HKP keyserver. :param keyserver: Keyserver name. The format of the name is a URI: ``scheme:[//]keyservername[:port]``. The scheme is the type of keyserver:"hkp" for the HTTP (or compatible) keyse...
python
{ "resource": "" }
q52057
GnuPG.delete_keys
train
def delete_keys(self, keys, secret=False): ''' Remove keys from the public or secret keyrings. :param keys: Single key ID or list of mutiple IDs :param secret: Delete secret keys :rtype: DeleteResult ''' return self.execute( DeleteResult(), ...
python
{ "resource": "" }
q52058
GnuPG.key_exists
train
def key_exists(self, key, secret=False): ''' Check is given key exists. :param key: Key ID :param secret: Check secret key :rtype: bool ''' if len(key) < 8: return False key = key.upper() res = self.list_keys(secret) for finger...
python
{ "resource": "" }
q52059
InfoMessage.calculate_authentication_data
train
def calculate_authentication_data(self, key): ''' Calculate the authentication data based on the current key-id and the given key. ''' # This one is easy if self.key_id == KEY_ID_NONE: return '' # Determine the digestmod and how long the authenticatio...
python
{ "resource": "" }
q52060
InfoMessage.verify_authentication_data
train
def verify_authentication_data(self, key): ''' Verify the current authentication data based on the current key-id and the given key. ''' correct_authentication_data = self.calculate_authentication_data(key) return self.authentication_data == correct_authentication_data
python
{ "resource": "" }
q52061
InfoMessage.insert_authentication_data
train
def insert_authentication_data(self, key): ''' Insert authentication data based on the current key-id and the given key. ''' correct_authentication_data = self.calculate_authentication_data(key) self.authentication_data = correct_authentication_data
python
{ "resource": "" }
q52062
track_model
train
def track_model(model): ''' Perform designated transformations on model, when it saves. Calls :py:func:`~simpleimages.utils.perform_transformation` on every model saves using :py:data:`django.db.models.signals.post_save`. It uses the ``update_fields`` kwarg to tell what fields it should tr...
python
{ "resource": "" }
q52063
_inner_product
train
def _inner_product(y,yr,psd): """ Compute inner product between two time domain waveforms, weighted by noisecurve. """ fmin = 40. fmax = 2000. fs = 16384. # fourier transform y and yr #y = sp.fft(y,n=None) #yr = sp.fft(yr,n=None) # compute product y = (1./fs)*y yr = (1./f...
python
{ "resource": "" }
q52064
_overlap
train
def _overlap(y,yr,psd): """ returns the detector noise weighted inner product """ yyr = _inner_product(y,yr,psd) yy = _inner_product(y,y,psd) yryr = _inner_product(yr,yr,psd) olap = yyr/np.sqrt(yy*yryr) return olap
python
{ "resource": "" }
q52065
Multivar._run_arguement_object_fits
train
def _run_arguement_object_fits(self): """ This function fits objects passed to Multivar, guarantees wave ordering in Catalog object and DesignMatrix object matches up """ # run fits # fit catalog object Y_dict = self._catalog_object.get_transformed_Y() # f...
python
{ "resource": "" }
q52066
Multivar.fit
train
def fit(self): """ fit waveforms in any domain""" # solve for estimator of B n,p = np.shape(self._X) self._df = float(n - p) self._Cx = np.linalg.pinv(np.dot(self._X.T,self._X)) self._Bhat = np.dot(np.dot(self._Cx, self._X.T), self._A) self._Y_r...
python
{ "resource": "" }
q52067
Multivar.summary
train
def summary(self): """ prints results of hotellings T2 """ transform = self._catalog_object._transform if transform == 'time': self._hotellings_time() elif transform == 'fourier': self._hotellings_fourier() elif transform == 'spectrogram': se...
python
{ "resource": "" }
q52068
Multivar._hotellings_time
train
def _hotellings_time(self): """ hotelling's T2 tests for time domain waveforms""" # get residuals df = self._df R = self._A - np.dot(self._X, self._Bhat) Sigma_Z = np.dot(R.T,R)*(1./df) # compute p-values T_2_list = [] p_value_list = [] for i in np...
python
{ "resource": "" }
q52069
Multivar._hotellings_fourier
train
def _hotellings_fourier(self): """ hotelling's T2 tests for fourier domain waveforms""" sigma_2 = self._catalog_object.sigma**2 # compute residual df = self._df #degrees of freedom R = self._A - np.dot(self._X, self._Bhat) R = np.matrix(R) # residual covariance ma...
python
{ "resource": "" }
q52070
Multivar._make_summary_tables
train
def _make_summary_tables(self): """ prints the summary of the regression. It shows the waveform metadata, diagnostics of the fit, and results of the hypothesis tests for each comparison encoded in the design matrix """ try: self._Bhat except: ...
python
{ "resource": "" }
q52071
Multivar.overlap_summary
train
def overlap_summary(self): """ print summary of reconstruction overlaps """ olaps = self.compute_overlaps() # compute min, 25% 50% (median), mean, 75%, max table = [["5%: ",np.percentile(olaps,5)], ["25%: ",np.percentile(olaps,25)], ["50%: ",np.percent...
python
{ "resource": "" }
q52072
Multivar._compute_prediction
train
def _compute_prediction(self,X): """ compute predictions given a new X """ A_pred = np.dot(X,self._Bhat) Y_pred = self._basis_object.inverse_transform(A_pred) return Y_pred
python
{ "resource": "" }
q52073
Multivar.predict
train
def predict(self,param_dict): """ predict new waveforms using multivar fit """ encoder_dict = self._designmatrix_object.encoder X, col_names = self._designmatrix_object.run_encoder(param_dict, encoder_dict) # compute predictions Y_pred = self._compute_prediction(X) return...
python
{ "resource": "" }
q52074
CovController.set_env
train
def set_env(self): """Put info about coverage into the env so that subprocesses can activate coverage.""" if self.cov_source is None: os.environ['COV_CORE_SOURCE'] = '' else: os.environ['COV_CORE_SOURCE'] = UNIQUE_SEP.join(self.cov_source) os.environ['COV_CORE_DA...
python
{ "resource": "" }
q52075
CovController.unset_env
train
def unset_env(): """Remove coverage info from env.""" os.environ.pop('COV_CORE_SOURCE', None) os.environ.pop('COV_CORE_DATA_FILE', None) os.environ.pop('COV_CORE_CONFIG', None)
python
{ "resource": "" }
q52076
CovController.summary
train
def summary(self, stream): """Produce coverage reports.""" # Output coverage section header. if len(self.node_descs) == 1: self.sep(stream, '-', 'coverage: %s' % ''.join(self.node_descs)) else: self.sep(stream, '-', 'coverage') for node_desc in sorted...
python
{ "resource": "" }
q52077
Central.finish
train
def finish(self): """Stop coverage, save data to file and set the list of coverage objects to report on.""" self.unset_env() self.cov.stop() self.cov.combine() self.cov.save() node_desc = self.get_node_desc(sys.platform, sys.version_info) self.node_descs.add(node...
python
{ "resource": "" }
q52078
DistMaster.start
train
def start(self): """Ensure coverage rc file rsynced if appropriate.""" if self.cov_config and os.path.exists(self.cov_config): self.config.option.rsyncdir.append(self.cov_config) self.cov = coverage.coverage(source=self.cov_source, data_file=sel...
python
{ "resource": "" }
q52079
DistMaster.configure_node
train
def configure_node(self, node): """Slaves need to know if they are collocated and what files have moved.""" node.slaveinput['cov_master_host'] = socket.gethostname() node.slaveinput['cov_master_topdir'] = self.topdir node.slaveinput['cov_master_rsync_roots'] = [str(root) for root in nod...
python
{ "resource": "" }
q52080
DistMaster.finish
train
def finish(self): """Combines coverage data and sets the list of coverage objects to report on.""" # Combine all the suffix files into the data file. self.cov.stop() self.cov.combine() self.cov.save()
python
{ "resource": "" }
q52081
DistSlave.start
train
def start(self): """Determine what data file and suffix to contribute to and start coverage.""" # Determine whether we are collocated with master. self.is_collocated = bool(socket.gethostname() == self.config.slaveinput['cov_master_host'] and self.topdir == sel...
python
{ "resource": "" }
q52082
DistSlave.finish
train
def finish(self): """Stop coverage and send relevant info back to the master.""" self.unset_env() self.cov.stop() self.cov.combine() self.cov.save() if self.is_collocated: # If we are collocated then just inform the master of our # data file to i...
python
{ "resource": "" }
q52083
filter_req_paths
train
def filter_req_paths(paths, func): """Return list of filtered libs.""" if not isinstance(paths, list): raise ValueError("Paths must be a list of paths.") libs = set() junk = set(['\n']) for p in paths: with p.open(mode='r') as reqs: lines = set([line for line in reqs if ...
python
{ "resource": "" }
q52084
urlopen
train
def urlopen(url, method=None, params=None, data=None, json=None, headers=None, allow_redirects=False, timeout=30, verify_ssl=True, user_agent=None): """ A slightly safer version of ``urlib2.urlopen`` which prevents redirection and ensures the URL isn't attempting to hit a blacklisted...
python
{ "resource": "" }
q52085
extract_response
train
def extract_response(raw_response): """Extract requests response object. only extract those status_code in [200, 300). :param raw_response: a requests.Resposne object. :return: content of response. """ data = urlread(raw_response) if is_success_response(raw_response): return data ...
python
{ "resource": "" }
q52086
dispatch_webhook_request
train
def dispatch_webhook_request(url=None, method='GET', params=None, json=None, data=None, headers=None, timeout=5): """Task dispatching to an URL. :param url: The URL location of the HTTP callback task. :param method: Method to use when dispatching the callback. Usually `...
python
{ "resource": "" }
q52087
chkstr
train
def chkstr(s, v): """ Small routine for checking whether a string is empty even a string :param s: the string in question :param v: variable name """ if type(s) != str: raise TypeError("{var} must be str".format(var=v)) if not s: raise ValueError("{var} cannot be empty"....
python
{ "resource": "" }
q52088
Scene.activate
train
async def activate(self): """Activate this scene.""" _val = await self.request.get(self._base_path, params={ATTR_SCENE_ID: self._id}) return _val
python
{ "resource": "" }
q52089
Device.state_attributes
train
def state_attributes(self): """Return all attributes of the vehicle.""" address_attributes = None if (self.current_address is not None): address_attributes = self.current_address.state_attributes() return { 'id': self.identifier, 'make': self.make, ...
python
{ "resource": "" }
q52090
Device.get_trips
train
def get_trips(self, authentication_info, start, end): """Get trips for this device between start and end.""" import requests if (authentication_info is None or not authentication_info.is_valid()): return [] data_url = "https://api.ritassist.nl/api/trips/GetTrips...
python
{ "resource": "" }
q52091
Device.get_extra_vehicle_info
train
def get_extra_vehicle_info(self, authentication_info): """Get extra data from the API.""" import requests base_url = "https://secure.ritassist.nl/GenericServiceJSONP.ashx" query = "?f=CheckExtraVehicleInfo" \ "&token={token}" \ "&equipmentId={identifier}"...
python
{ "resource": "" }
q52092
Device.update_from_json
train
def update_from_json(self, json_device): """Set all attributes based on API response.""" self.identifier = json_device['Id'] self.license_plate = json_device['EquipmentHeader']['SerialNumber'] self.make = json_device['EquipmentHeader']['Make'] self.model = json_device['EquipmentH...
python
{ "resource": "" }
q52093
done_item
train
def done_item(item, code): '''Succeed or fail an item based on the return code of a program''' try: if const('FSQ_SUCCESS') == code: success(item) chirp('{0}: succeeded'.format(item.id)) elif const('FSQ_FAIL_TMP') == code: fail_tmp(item) shout('{0}...
python
{ "resource": "" }
q52094
setenv
train
def setenv(item, timefmt): '''Set environment, based on item. Usually done in a baby fork''' for env, att in (( 'FSQ_ITEM_PID', 'pid', ), ( 'FSQ_ITEM_ENTROPY', 'entropy', ), ( 'FSQ_ITEM_HOSTNAME', 'hostname', ), ( 'FSQ_ITEM_HOST', 'host', ), ...
python
{ "resource": "" }
q52095
was_init
train
def was_init(): """This function returns the subsystems which have previously been initialized. Returns: Set[InitFlag]: Flags indicating which subsystems have been initialized. """ mask = lib.SDL_WasInit(0) return enumtools.get_items(InitFlags, mask, {InitFlags.everything})
python
{ "resource": "" }
q52096
backup_file
train
def backup_file(*, file, host): """ Backup a file on S3 :param file: full path to the file to be backed up :param host: this will be used to locate the file on S3 :raises TypeError: if an argument in kwargs does not have the type expected :raises ValueError: if an argument within kwargs has an ...
python
{ "resource": "" }
q52097
_get_from_c_api
train
def _get_from_c_api(): """dictproxy does exist in previous versions, but the Python constructor refuses to create new objects, so we must be underhanded and sneaky with ctypes. """ from ctypes import pythonapi, py_object PyDictProxy_New = pythonapi.PyDictProxy_New PyDictProxy_New.argtypes =...
python
{ "resource": "" }
q52098
CourseCatalog.from_string
train
def from_string(html_str, url=None): "Creates a new CourseCatalog instance from an string containing xml." return CourseCatalog(BeautifulSoup(_remove_divs(html_str), convertEntities=BeautifulSoup.HTML_ENTITIES ), url)
python
{ "resource": "" }
q52099
CourseCatalog.crosslisted_with
train
def crosslisted_with(self, crn): """Returns all the CRN courses crosslisted with the given crn. The returned crosslisting does not include the original CRN. """ raise NotImplemented return tuple([c for c in self.crosslistings[crn].crns if c != crn])
python
{ "resource": "" }