_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q51400
TemplateEmitter.serialize
train
def serialize(self, content): """ Render Django template. :return string: rendered content """ if self.response.error: template_name = op.join('api', 'error.%s' % self.format) else: template_name = (self.resource._meta.emit_template ...
python
{ "resource": "" }
q51401
TemplateEmitter.get_template_path
train
def get_template_path(self, content=None): """ Find template. :return string: remplate path """ if isinstance(content, Paginator): return op.join('api', 'paginator.%s' % self.format) if isinstance(content, UpdatedList): return op.join('api', 'updated.%s...
python
{ "resource": "" }
q51402
JSONPTemplateEmitter.serialize
train
def serialize(self, content): """ Move rendered content to callback. :return string: JSONP """ content = super(JSONPTemplateEmitter, self).serialize(content) callback = self.request.GET.get('callback', 'callback') return '%s(%s)' % (callback, content)
python
{ "resource": "" }
q51403
XMLTemplateEmitter.serialize
train
def serialize(self, content): """ Serialize to xml. :return string: """ return self.xmldoc_tpl % ( 'true' if self.response.status_code == HTTP_200_OK else 'false', str(self.resource.api or ''), int(mktime(datetime.now().timetuple())), sup...
python
{ "resource": "" }
q51404
match_item
train
def match_item(key, value, item): """ Check if some item matches criteria. """ if isinstance(value, (list, tuple)): return any(match_item(key, sub_value, item) for sub_value in value) else: return key not in item or str(item.get(key)).lower() == str(value).lower()
python
{ "resource": "" }
q51405
ScreenShotsAPI.browsers
train
def browsers(self, browser=None, browser_version=None, device=None, os=None, os_version=None): """ Returns list of available browsers & OS. """ response = self.execute('GET', '/screenshots/browsers.json') for key, value in list(locals().items()): if key in ('self', 'r...
python
{ "resource": "" }
q51406
ScreenShotsAPI.make
train
def make(self, url, browsers=None, destination=None, timeout=DEFAULT_TIMEOUT, retries=DEFAULT_RETRIES, **kwargs): """ Generates screenshots for given settings and saves it to specified destination. """ response = self.generate(url, browsers, **kwargs) return self.download(respons...
python
{ "resource": "" }
q51407
ScreenShotsAPI.generate
train
def generate(self, url, browsers=None, orientation=None, mac_res=None, win_res=None, quality=None, local=None, wait_time=None, callback_url=None): """ Generates screenshots for a URL. """ if isinstance(browsers, dict): browsers = [browsers] ...
python
{ "resource": "" }
q51408
ScreenShotsAPI.download
train
def download(self, job_id, destination=None, timeout=DEFAULT_TIMEOUT, retries=DEFAULT_RETRIES): """ Downloads all screenshots for given job_id to `destination` folder. If `destination` is None, then screenshots will be saved in current directory. """ self._retries_num = 0 ...
python
{ "resource": "" }
q51409
ScreenShotsAPI.save_file
train
def save_file(self, filename, content): """ Saves file on local filesystem. """ with open(filename, 'wb') as f: for chunk in content.iter_content(chunk_size=1024): if chunk: f.write(chunk)
python
{ "resource": "" }
q51410
Packer.install
train
def install(cls): """Create the required directories in the home directory""" [os.makedirs('{}/{}'.format(cls.home, cls.dirs[d])) for d in cls.dirs]
python
{ "resource": "" }
q51411
Packer.uninstall
train
def uninstall(cls): """Remove the package manager from the system.""" if os.path.exists(cls.home): shutil.rmtree(cls.home)
python
{ "resource": "" }
q51412
get_installed_distributions
train
def get_installed_distributions(skip=stdlib_pkgs): """ Return a list of installed Distribution objects. ``skip`` argument is an iterable of lower-case project names to ignore; defaults to stdlib_pkgs """ return [d for d in pkg_resources.working_set if d.key not in skip]
python
{ "resource": "" }
q51413
marshal_bson
train
def marshal_bson( obj, types=BSON_TYPES, fields=None, ): """ Recursively marshal a Python object to a BSON-compatible dict that can be passed to PyMongo, Motor, etc... Args: obj: object, It's members can be nested Python objects which will be converted to dictiona...
python
{ "resource": "" }
q51414
MongoDocument.json
train
def json( self, include_id=False, date_fmt=None, object_id_fmt=str, ): """ Helper method to convert to MongoDB documents to JSON This includes helpers to convert non-JSON compatible types to valid JSON types. HOWEVER, it cannot recurse into nested ...
python
{ "resource": "" }
q51415
ParserMixin.parse
train
def parse(self, request): """ Parse request content. :return dict: parsed data. """ if request.method in ('POST', 'PUT', 'PATCH'): content_type = self.determine_content(request) if content_type: split = content_type.split(';', 1) ...
python
{ "resource": "" }
q51416
ParserMixin.determine_content
train
def determine_content(request): """ Determine request content. :return str: request content type """ if not request.META.get('CONTENT_LENGTH', None) \ and not request.META.get('TRANSFER_ENCODING', None): return None return request.META.get('CONTENT_TYPE...
python
{ "resource": "" }
q51417
bar
train
def bar(msg='', width=40, position=None): r""" Returns a string with text centered in a bar caption. Examples: >>> bar('test', width=10) '== test ==' >>> bar(width=10) '==========' >>> bar('Richard Dean Anderson is...', position='top', width=50) '//========= Richard Dean Anderson is...
python
{ "resource": "" }
q51418
section
train
def section(msg): """ Context manager that prints a top bar to stderr upon entering and a bottom bar upon exiting. The caption of the top bar is specified by `msg`. The caption of the bottom bar is '...done!' if the context manager exits successfully. If a SectionError or SectionWarning is raised...
python
{ "resource": "" }
q51419
update
train
def update(request): """Update a current user's session.""" session = yield from app.ps.session.load(request) session['random'] = random.random() return session
python
{ "resource": "" }
q51420
Solution.keys
train
def keys(self): "Returns all the keys this object can return proper values for." return tuple(set(self.new.keys()).union(self.old.keys()))
python
{ "resource": "" }
q51421
Solution.values
train
def values(self): "Returns all values this object can return via keys." return tuple(set(self.new.values()).union(self.old.values()))
python
{ "resource": "" }
q51422
BruteForceSolver._compute_search_spaces
train
def _compute_search_spaces(self, used_variables): """Returns the size of each domain for a simple constraint size computation. This is used to pick the most constraining constraint first. """ return tuple(len(domain) for name, domain in self._vars.iteritems())
python
{ "resource": "" }
q51423
BruteForceSolver.combinations
train
def combinations(self): """Returns a generator of all possible combinations. """ keys = self._vars.keys() for result in product(*self._vars.values()): possible_solution = {} for i, v in enumerate(result): possible_solution[keys[i]] = v ...
python
{ "resource": "" }
q51424
BacktrackingSolver.derived_solutions
train
def derived_solutions(self, solution=None): """Returns all possible solutions based on the provide solution. This assumes that the given solution is incomplete. """ solution = solution or Solution() used_variables = solution.keys() unused_variables = (v for v in self._va...
python
{ "resource": "" }
q51425
BacktrackingSolver.is_feasible
train
def is_feasible(self, solution): """Returns True if the given solution's derivatives may have potential valid, complete solutions. """ newvars = solution.new.keys() for newvar in newvars: for c in self._constraints_for_var.get(newvar, []): values = c.e...
python
{ "resource": "" }
q51426
BacktrackingSolver._next
train
def _next(self, possible_solution): """Where the magic happens. Produces a generator that returns all solutions given a base solution to start searching. """ # bail out if we have seen it already. See __iter__ to where seen is initially set. # A complete solution has all its vari...
python
{ "resource": "" }
q51427
dedent
train
def dedent(lines): """De-indent based on the first line's indentation.""" if len(lines) != 0: first_lstrip = lines[0].lstrip() strip_len = len(lines[0]) - len(first_lstrip) for line in lines: if len(line[:strip_len].strip()) != 0: raise ValueError('less indent...
python
{ "resource": "" }
q51428
QPixmapWrapper.assign
train
def assign(self, pm): """Reassign pixmap or xpm string array to wrapper""" if isinstance(pm, QPixmap): self._pm = pm else: # assume xpm string list to be decoded on-demand self._xpmstr = pm self._pm = None self._icon = None
python
{ "resource": "" }
q51429
QPixmapWrapper.pm
train
def pm(self): """Get QPixmap from wrapper""" if self._pm is None: self._pm = QPixmap(self._xpmstr) return self._pm
python
{ "resource": "" }
q51430
QPixmapWrapper.icon
train
def icon(self): """Get QIcon from wrapper""" if self._icon is None: self._icon = QIcon(self.pm()) return self._icon
python
{ "resource": "" }
q51431
TreeBRD.to_node
train
def to_node(self, exp, schema): """ Return a Node that is the root of the parse tree for the the specified expression. :param exp: A list that represents a relational algebra expression. Assumes that this list was generated by pyparsing. :param schema: A dictionary of re...
python
{ "resource": "" }
q51432
TreeBRD.create_unary_node
train
def create_unary_node(self, operator, child, param=None, schema=None): """ Return a Unary Node whose type depends on the specified operator. :param schema: :param child: :param operator: A relational algebra operator (see constants.py) :param param: A list of parameters ...
python
{ "resource": "" }
q51433
TreeBRD.create_binary_node
train
def create_binary_node(self, operator, left, right, param=None): """ Return a Node whose type depends on the specified operator. :param operator: A relational algebra operator (see constants.py) :return: A Node. """ # Join operators if operator == self.grammar.s...
python
{ "resource": "" }
q51434
ChromosomeIdResolver.get_to
train
def get_to(self, ins): """ Resolve the output attribute value for 'chromosome_id'. Valid values are immutable, ie. the attribute key is not an actual entity. Mutable values will be changed to match the immutable value if unique. Otherwise an error is thrown. :param ins: iterable...
python
{ "resource": "" }
q51435
Project.time_entries
train
def time_entries(self, start_date=None, end_date=None): '''Array of all time entries''' if self.cache['time_entries']: return self.cache['time_entries'] if not start_date: start_date = datetime.date(1900, 1, 1) if not end_date: end_date = datetime.date.today() ...
python
{ "resource": "" }
q51436
Project.people
train
def people(self): '''Dictionary of people on the project, keyed by id''' if self.cache['people']: return self.cache['people'] people_xml = self.bc.people_within_project(self.id) for person_node in ET.fromstring(people_xml).findall('person'): p = Person(person_node) ...
python
{ "resource": "" }
q51437
Project.person
train
def person(self, person_id): '''Access a Person object by id''' if not self.cache['persons'].get(person_id, None): try: person_xml = self.bc.person(person_id) p = Person(person_xml) self.cache['persons'][person_id] = p except HTTPEr...
python
{ "resource": "" }
q51438
Project.comments
train
def comments(self): '''Looks through the last 3 messages and returns those comments.''' if self.cache['comments']: return self.cache['comments'] comments = [] for message in self.messages[0:3]: comment_xml = self.bc.comments(message.id) for comment_node in ET.from...
python
{ "resource": "" }
q51439
Project.milestones
train
def milestones(self): '''Array of all milestones''' if self.cache['milestones']: return self.cache['milestones'] milestone_xml = self.bc.list_milestones(self.id) milestones = [] for node in ET.fromstring(milestone_xml).findall("milestone"): milestones.append(Milestone...
python
{ "resource": "" }
q51440
with_color_stripped
train
def with_color_stripped(f): """ A function decorator for applying to `len` or imitators thereof that strips ANSI color sequences from a string before passing it on. If any color sequences are not followed by a reset sequence, an `UnterminatedColorError` is raised. """ @wraps(f) def colo...
python
{ "resource": "" }
q51441
carry_over_color
train
def carry_over_color(lines): """ Given a sequence of lines, for each line that contains a ANSI color escape sequence without a reset, add a reset to the end of that line and copy all colors in effect at the end of it to the beginning of the next line. """ lines2 = [] in_effect = '' for s...
python
{ "resource": "" }
q51442
_pprint_fasta
train
def _pprint_fasta(fasta, annotations=None, annotation_file=None, block_length=10, blocks_per_line=6): """ Pretty-print each record in the FASTA file. """ annotations = annotations or [] # Annotations by chromosome. as_by_chrom = collections.defaultdict(lambda: [a for a in anno...
python
{ "resource": "" }
q51443
_pprint_line
train
def _pprint_line(line, annotations=None, annotation_file=None, block_length=10, blocks_per_line=6): """ Pretty-print one line. """ annotations = annotations or [] if annotation_file: # We just use the first chromosome defined in the BED file. _, chrom_iter = next(_b...
python
{ "resource": "" }
q51444
normalize_map_between
train
def normalize_map_between(dictionary, norm_min, norm_max): """ Performs linear normalization of all values in Map between normMin and normMax :param: map Map to normalize values for :param: normMin Smallest normalized value :param: normMax Largest normalized value :return: A new map with do...
python
{ "resource": "" }
q51445
load_options
train
def load_options(file_name): """ Loads options from a JSON file. The file should contain general classifier options, intensifier words with their intensification values, negation words and stop words. @param file_name Name of file containing the options @throws IOException """ words = from_...
python
{ "resource": "" }
q51446
activate_debug
train
def activate_debug(): """Activate debug logging on console This function is useful when playing with python-textops through a python console. It is not recommended to use this function in a real application : use standard logging functions instead. """ ch = logging.StreamHandler() ch.setLev...
python
{ "resource": "" }
q51447
add_textop
train
def add_textop(class_or_func): """Decorator to declare custom function or custom class as a new textops op the custom function/class will receive the whole raw input text at once. Examples: >>> @add_textop ... def repeat(text, n, *args,**kwargs): ... return text * n >>...
python
{ "resource": "" }
q51448
eformat
train
def eformat(format_str,lst,dct,defvalue='-'): """ Formats a list and a dictionary, manages unkown keys It works like :meth:`string.Formatter.vformat` except that it accepts a defvalue for not matching keys. Defvalue can be a callable that will receive the requested key as argument and return a string ...
python
{ "resource": "" }
q51449
TextOp.op
train
def op(cls,text,*args,**kwargs): """ This method must be overriden in derived classes """ return cls.fn(text,*args,**kwargs)
python
{ "resource": "" }
q51450
get_timeout
train
def get_timeout(service): """ Returns either a custom timeout for the given service, or a default """ custom_timeout_key = "RESTCLIENTS_%s_TIMEOUT" % service.upper() if hasattr(settings, custom_timeout_key): return getattr(settings, custom_timeout_key) default_key = "RESTCLIENTS_DEFAULT_TIM...
python
{ "resource": "" }
q51451
StackTraceLogger.error
train
def error(self, message, *args, **kwargs): """Log error with stack trace and locals information. By default, enables stack trace information in logging messages, so that stacktrace and locals appear in Sentry. """ kwargs.setdefault('extra', {}).setdefault('stack', True) return s...
python
{ "resource": "" }
q51452
Command.get_division
train
def get_division(self, row): """ Gets the Division object for the given row of election results. """ # back out of Alaska county if ( row["level"] == geography.DivisionLevel.COUNTY and row["statename"] == "Alaska" ): print("Do not tak...
python
{ "resource": "" }
q51453
Command.get_office
train
def get_office(self, row, division): """ Gets the Office object for the given row of election results. Depends on knowing the division of the row of election results. """ AT_LARGE_STATES = ["AK", "DE", "MT", "ND", "SD", "VT", "WY"] if division.level.name not in [ ...
python
{ "resource": "" }
q51454
Command.get_race
train
def get_race(self, row, division): """ Gets the Race object for the given row of election results. In order to get the race, we must know the office. This function will get the office as well. The only way to know if a Race is a special is based on the string of the `ra...
python
{ "resource": "" }
q51455
Command.get_election
train
def get_election(self, row, race): """ Gets the Election object for the given row of election results. Depends on knowing the Race object. If this is the presidential election, this will determine the Division attached to the election based on the row's statename. This ...
python
{ "resource": "" }
q51456
Command.get_or_create_party
train
def get_or_create_party(self, row): """ Gets or creates the Party object based on AP code of the row of election data. All parties that aren't Democratic or Republican are aggregable. """ if row["party"] in ["Dem", "GOP"]: aggregable = False else: ...
python
{ "resource": "" }
q51457
Command.get_or_create_person
train
def get_or_create_person(self, row): """ Gets or creates the Person object for the given row of AP data. """ person, created = entity.Person.objects.get_or_create( first_name=row["first"], last_name=row["last"] ) return person
python
{ "resource": "" }
q51458
Command.get_or_create_candidate
train
def get_or_create_candidate(self, row, party, race): """ Gets or creates the Candidate object for the given row of AP data. In order to tie with live data, this will synthesize the proper AP candidate id. This function also calls `get_or_create_person` to get a Person o...
python
{ "resource": "" }
q51459
Command.get_or_create_candidate_election
train
def get_or_create_candidate_election( self, row, election, candidate, party ): """ For a given election, this function updates or creates the CandidateElection object using the model method on the election. """ return election.update_or_create_candidate( c...
python
{ "resource": "" }
q51460
Command.get_or_create_ap_election_meta
train
def get_or_create_ap_election_meta(self, row, election): """ Gets or creates the APElectionMeta object for the given row of AP data. """ APElectionMeta.objects.get_or_create( ap_election_id=row["raceid"], election=election )
python
{ "resource": "" }
q51461
Command.get_or_create_votes
train
def get_or_create_votes(self, row, division, candidate_election): """ Gets or creates the Vote object for the given row of AP data. """ vote.Votes.objects.get_or_create( division=division, count=row["votecount"], pct=row["votepct"], winning...
python
{ "resource": "" }
q51462
Command.process_row
train
def process_row(self, row): """ Processes a row of AP election data to determine what model objects need to be created. """ division = self.get_division(row) if not division: return None race = self.get_race(row, division) election = self.get_...
python
{ "resource": "" }
q51463
Command.handle
train
def handle(self, *args, **options): """ This management command gets data for a given election date from elex. Then, it loops through each row of the data and calls `process_row`. In order for this command to work, you must have bootstrapped all of the dependent apps: en...
python
{ "resource": "" }
q51464
bump_minor_version
train
def bump_minor_version(): """Bump the minor version in version.py.""" version = load_version_as_list() print('current version: {}'.format(format_version_string(version))) version[-1] += 1 print('new version: {}'.format(format_version_string(version))) contents = "__version__ = '{}'\n".format(fo...
python
{ "resource": "" }
q51465
apiv1_root_view
train
def apiv1_root_view(): """ API root url. Shows a list of active endpoints. """ docs_url = current_app.config.get('DOCS_URL', 'http://' + request.host + '/docs') message = "Welcome to the voeventdb REST API, " \ "interface version '{}'.".format( ...
python
{ "resource": "" }
q51466
packet_xml
train
def packet_xml(url_encoded_ivorn=None): """ Returns the XML packet contents stored for a given IVORN. The required IVORN should be appended to the URL after ``/xml/`` in :ref:`URL-encoded <url-encoding>` form. """ # Handle Apache / Debug server difference... # Apache conf must include the s...
python
{ "resource": "" }
q51467
json_or_jsonp
train
def json_or_jsonp(func): """Wrap response in JSON or JSONP style""" @wraps(func) def _(*args, **kwargs): mimetype = 'application/javascript' callback = request.args.get('callback', None) if callback is None: content = func(*args, **kwargs) else: conte...
python
{ "resource": "" }
q51468
add_response_headers
train
def add_response_headers(headers): """Add headers passed in to the response Usage: .. code::py @app.route('/') @add_response_headers({'X-Robots-Tag': 'noindex'}) def not_indexed(): # This will set ``X-Robots-Tag: noindex`` in the response headers return "Ch...
python
{ "resource": "" }
q51469
wrap_ptr_class
train
def wrap_ptr_class(struct, constructor, destructor, classname=None): """Creates wrapper class for pointer to struct class which appropriately acquires and releases memory """ class WrapperClass(ctypes.c_void_p): def __init__(self, val=None): if val: super(WrapperCla...
python
{ "resource": "" }
q51470
make_dirs_for_file_path
train
def make_dirs_for_file_path(file_path, mode=0o775): """ Make dirs for file file_path, if these dirs are not exist. """ dirname = os.path.dirname(file_path) if not os.path.exists(dirname): os.makedirs(dirname, mode=mode)
python
{ "resource": "" }
q51471
EventConsumer.connect
train
def connect(self): """Connect to RabbitMQ, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection """ logger.debug('Connecting to %s', self._url) return pika.Selec...
python
{ "resource": "" }
q51472
EventConsumer.on_connection_closed
train
def on_connection_closed(self, _, reply_code, reply_text): """Called by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection _: The closed connection object :param...
python
{ "resource": "" }
q51473
EventConsumer.on_channel_open
train
def on_channel_open(self, channel): """Called by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll start consuming. :param pika.channel.Channel channel: The channel object """ logger.deb...
python
{ "resource": "" }
q51474
EventConsumer.setup_exchange
train
def setup_exchange(self): """Declare the exchange When completed, the on_exchange_declareok method will be invoked by pika. """ logger.debug('Declaring exchange %s', self._exchange) self._channel.exchange_declare(self.on_exchange_declareok, ...
python
{ "resource": "" }
q51475
EventConsumer.setup_queue
train
def setup_queue(self): """Declare the queue When completed, the on_queue_declareok method will be invoked by pika. """ logger.debug("Declaring queue %s" % self._queue) self._channel.queue_declare(self.on_queue_declareok, self._queue, durable=True)
python
{ "resource": "" }
q51476
EventConsumer.on_queue_declareok
train
def on_queue_declareok(self, _): """Invoked by pika when queue is declared This method will start consuming or first bind the queue to the exchange if an exchange is provided. After binding, the on_bindok method will be invoked by pika. :param pika.frame.Method _: The Queue.De...
python
{ "resource": "" }
q51477
EventConsumer.on_message
train
def on_message(self, _, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the m...
python
{ "resource": "" }
q51478
EventConsumer.acknowledge_message
train
def acknowledge_message(self, delivery_tag): """Acknowledge the message delivery from RabbitMQ. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.debug('Acknowledging message %s', delivery_tag) self._channel.basic_ack(delivery_tag)
python
{ "resource": "" }
q51479
EventConsumer.open_channel
train
def open_channel(self): """Open a new channel with RabbitMQ. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ logger.debug('Creating new channel') self._connection.channel(on_open_callback=self.on_channel_open)
python
{ "resource": "" }
q51480
EventConsumer.stop
train
def stop(self): """Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again, becuase this met...
python
{ "resource": "" }
q51481
EventConsumer.stop_consuming
train
def stop_consuming(self): """Tell RabbitMQ that we would like to stop consuming.""" if self._channel: logger.debug('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok, self._consumer_tag)
python
{ "resource": "" }
q51482
O365.get_resource
train
def get_resource(self, path, params=None): """ O365 GET method. Return representation of the requested resource. """ url = '%s%s' % (path, self._param_list(params)) headers = { 'Accept': 'application/json;odata=minimalmetadata' } response = O365_DAO()...
python
{ "resource": "" }
q51483
O365.post_resource
train
def post_resource(self, path, body=None, json=None): """ O365 POST method. """ url = '%s%s' % (path, self._param_list()) headers = { 'Accept': 'application/json;odata=minimalmetadata' } if json: headers['Content-Type'] = 'application/json'...
python
{ "resource": "" }
q51484
O365.patch_resource
train
def patch_resource(self, path, body=None, json=None): """ O365 PATCH method. """ url = '%s%s' % (path, self._param_list()) headers = { 'Accept': 'application/json;odata=minimalmetadata' } if json: headers['Content-Type'] = 'application/jso...
python
{ "resource": "" }
q51485
_GpxElem.togpx
train
def togpx(self): """Generate a GPX waypoint element subtree. Returns: etree.Element: GPX element """ element = create_elem(self.__class__._elem_name, {'lat': str(self.latitude), 'lon': str(self.longitude)}) ...
python
{ "resource": "" }
q51486
_SegWrap.distance
train
def distance(self, method='haversine'): """Calculate distances between locations in segments. Args: method (str): Method used to calculate distance Returns: list of list of float: Groups of distance between points in segments """ distance...
python
{ "resource": "" }
q51487
_SegWrap.bearing
train
def bearing(self, format='numeric'): """Calculate bearing between locations in segments. Args: format (str): Format of the bearing string to return Returns: list of list of float: Groups of bearings between points in segments """ bearings...
python
{ "resource": "" }
q51488
_SegWrap.final_bearing
train
def final_bearing(self, format='numeric'): """Calculate final bearing between locations in segments. Args: format (str): Format of the bearing string to return Returns: list of list of float: Groups of bearings between points in segments """ ...
python
{ "resource": "" }
q51489
_SegWrap.inverse
train
def inverse(self): """Calculate the inverse geodesic between locations in segments. Returns: list of 2-tuple of float: Groups in bearing and distance between points in segments """ inverses = [] for segment in self: if len(segment) < 2: ...
python
{ "resource": "" }
q51490
_SegWrap.midpoint
train
def midpoint(self): """Calculate the midpoint between locations in segments. Returns: list of Point: Groups of midpoint between points in segments """ midpoints = [] for segment in self: if len(segment) < 2: midpoints.append([]) ...
python
{ "resource": "" }
q51491
_SegWrap.range
train
def range(self, location, distance): """Test whether locations are within a given range of ``location``. Args: location (Point): Location to test range against distance (float): Distance to test location is within Returns: list of list of Point: Groups of po...
python
{ "resource": "" }
q51492
_SegWrap.destination
train
def destination(self, bearing, distance): """Calculate destination locations for given distance and bearings. Args: bearing (float): Bearing to move on in degrees distance (float): Distance in kilometres Returns: list of list of Point: Groups of points shift...
python
{ "resource": "" }
q51493
_SegWrap.sunrise
train
def sunrise(self, date=None, zenith=None): """Calculate sunrise times for locations. Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate sunrise events, or end of twilight Returns: list of list of datetime.datetime: The ti...
python
{ "resource": "" }
q51494
_SegWrap.sunset
train
def sunset(self, date=None, zenith=None): """Calculate sunset times for locations. Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate sunset events, or start of twilight times Returns: list of list of datetime.datetime: ...
python
{ "resource": "" }
q51495
_GpxMeta.import_metadata
train
def import_metadata(self, elements): """Import information from GPX metadata. Args: elements (etree.Element): GPX metadata subtree """ metadata_elem = lambda name: etree.QName(GPX_NS, name) for child in elements.getchildren(): tag_ns, tag_name = child.ta...
python
{ "resource": "" }
q51496
Waypoints.export_gpx_file
train
def export_gpx_file(self): """Generate GPX element tree from ``Waypoints`` object. Returns: etree.ElementTree: GPX element tree depicting ``Waypoints`` object """ gpx = create_elem('gpx', GPX_ELEM_ATTRIB) if not self.metadata.bounds: self.metadata.bounds ...
python
{ "resource": "" }
q51497
Trackpoints.export_gpx_file
train
def export_gpx_file(self): """Generate GPX element tree from ``Trackpoints``. Returns: etree.ElementTree: GPX element tree depicting ``Trackpoints`` objects """ gpx = create_elem('gpx', GPX_ELEM_ATTRIB) if not self.metadata.bounds: self.me...
python
{ "resource": "" }
q51498
prepare_read
train
def prepare_read(data, method='readlines', mode='r'): """Prepare various input types for parsing. Args: data (iter): Data to read method (str): Method to process data with mode (str): Custom mode to process with, if data is a file Returns: list: List suitable for parsing ...
python
{ "resource": "" }
q51499
prepare_csv_read
train
def prepare_csv_read(data, field_names, *args, **kwargs): """Prepare various input types for CSV parsing. Args: data (iter): Data to read field_names (tuple of str): Ordered names to assign to fields Returns: csv.DictReader: CSV reader suitable for parsing Raises: Type...
python
{ "resource": "" }