_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q37300
_build_join
train
def _build_join(t): """ Populates join token fields. """ t.source.name = t.source.parsed_name t.source.alias = t.source.parsed_alias[0] if t.source.parsed_alias else '' return t
python
{ "resource": "" }
q37301
substitute_vids
train
def substitute_vids(library, statement): """ Replace all of the references to tables and partitions with their vids. This is a bit of a hack -- it ought to work with the parser, but instead it just looks for common SQL tokens that indicate an identifier. :param statement: an sqlstatement. String. ...
python
{ "resource": "" }
q37302
find_indexable_materializable
train
def find_indexable_materializable(sql, library): """ Parse a statement, then call functions to install, materialize or create indexes for partitions referenced in the statement. :param sql: :param materialize_f: :param install_f: :param index_f: :return: """ derefed, tables, pa...
python
{ "resource": "" }
q37303
FIMRecord.update
train
def update(self, rec=None, drop=None, tables=None, install=None, materialize=None, indexes=None, joins=0, views=0): """ Updates current record. Args: rec (FIMRecord): """ if not drop: drop = [] if not tables: tables = set() ...
python
{ "resource": "" }
q37304
ProductReleaseRest.support_level
train
def support_level(self, support_level): """ Sets the support_level of this ProductReleaseRest. :param support_level: The support_level of this ProductReleaseRest. :type: str """ allowed_values = ["UNRELEASED", "EARLYACCESS", "SUPPORTED", "EXTENDED_SUPPORT", "EOL"] ...
python
{ "resource": "" }
q37305
callLater
train
def callLater(self, when, what, *a, **kw): """ Copied from twisted.internet.task.Clock, r20480. Fixes the bug where the wrong DelayedCall would sometimes be returned. """ dc = base.DelayedCall(self.seconds() + when, what, a, kw, self.calls.remo...
python
{ "resource": "" }
q37306
clockIsBroken
train
def clockIsBroken(): """ Returns whether twisted.internet.task.Clock has the bug that returns the wrong DelayedCall or not. """ clock = Clock() dc1 = clock.callLater(10, lambda: None) dc2 = clock.callLater(1, lambda: None) if dc1 is dc2: return True else: return False
python
{ "resource": "" }
q37307
shrink_patch
train
def shrink_patch(patch_path, target_file): """ Shrinks a patch on patch_path to contain only changes for target_file. :param patch_path: path to the shrinked patch file :param target_file: filename of a file of which changes should be kept :return: True if the is a section containing changes for ta...
python
{ "resource": "" }
q37308
BuildSetStatusChangedEvent.new_status
train
def new_status(self, new_status): """ Sets the new_status of this BuildSetStatusChangedEvent. :param new_status: The new_status of this BuildSetStatusChangedEvent. :type: str """ allowed_values = ["NEW", "DONE", "REJECTED"] if new_status not in allowed_values: ...
python
{ "resource": "" }
q37309
BuildSetStatusChangedEvent.old_status
train
def old_status(self, old_status): """ Sets the old_status of this BuildSetStatusChangedEvent. :param old_status: The old_status of this BuildSetStatusChangedEvent. :type: str """ allowed_values = ["NEW", "DONE", "REJECTED"] if old_status not in allowed_values: ...
python
{ "resource": "" }
q37310
find_previous
train
def find_previous(element, l): """ find previous element in a sorted list >>> find_previous(0, [0]) 0 >>> find_previous(2, [1, 1, 3]) 1 >>> find_previous(0, [1, 2]) >>> find_previous(1.5, [1, 2]) 1 >>> find_previous(3, [1, 2]) 2 """ length = len(l) for index, cur...
python
{ "resource": "" }
q37311
Remote.update
train
def update(self): """Cache the list into the data section of the record""" from ambry.orm.exc import NotFoundError from requests.exceptions import ConnectionError, HTTPError from boto.exception import S3ResponseError d = {} try: for k, v in self.list(full=T...
python
{ "resource": "" }
q37312
Remote.list
train
def list(self, full=False): """List all of the bundles in the remote""" if self.is_api: return self._list_api(full=full) else: return self._list_fs(full=full)
python
{ "resource": "" }
q37313
Remote._update_fs_list
train
def _update_fs_list(self): """Cache the full list for http access. This creates a meta file that can be read all at once, rather than requiring a list operation like S3 access does""" from json import dumps full_list = [ e[1] for e in self._list_fs(full=True) ] remote = self._f...
python
{ "resource": "" }
q37314
Remote.checkin
train
def checkin(self, package, no_partitions=False, force=False, cb=None): """ Check in a bundle package to the remote. :param package: A Database, referencing a sqlite database holding the bundle :param cb: a two argument progress callback: cb(message, num_records) :return: ...
python
{ "resource": "" }
q37315
Remote._put_metadata
train
def _put_metadata(self, fs_remote, ds): """Store metadata on a pyfs remote""" from six import text_type from fs.errors import ResourceNotFoundError identity = ds.identity d = identity.dict d['summary'] = ds.config.metadata.about.summary d['title'] = ds.config....
python
{ "resource": "" }
q37316
Remote.checkout
train
def checkout(self, ref, cb=None): """Checkout a bundle from the remote. Returns a file-like object""" if self.is_api: return self._checkout_api(ref, cb=cb) else: return self._checkout_fs(ref, cb=cb)
python
{ "resource": "" }
q37317
Remote.remove
train
def remove(self, ref, cb=None): """Check in a bundle to the remote""" if self.is_api: return self._remove_api(ref, cb) else: return self._remove_fs(ref, cb)
python
{ "resource": "" }
q37318
Remote.s3
train
def s3(self, url, account_acessor=None, access=None, secret=None): """Setup an S3 pyfs, with account credentials, fixing an ssl matching problem""" from ambry.util.ambrys3 import AmbryS3FS from ambry.util import parse_url_to_dict import ssl pd = parse_url_to_dict(url) i...
python
{ "resource": "" }
q37319
withdict
train
def withdict(parser, token): """ Take a complete context dict as extra layer. """ bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError("{% withdict %} expects one argument") nodelist = parser.parse(('endwithdict',)) parser.delete_first_token() return WithD...
python
{ "resource": "" }
q37320
WithDictNode.render
train
def render(self, context): """ Render the tag, with extra context layer. """ extra_context = self.context_expr.resolve(context) if not isinstance(extra_context, dict): raise TemplateSyntaxError("{% withdict %} expects the argument to be a dictionary.") with c...
python
{ "resource": "" }
q37321
oscillating_setpoint
train
def oscillating_setpoint(_square_wave=False, shift=0): """A basic example of a target that you may want to approximate. If you have a thermostat, this is a temperature setting. This target can't change too often """ import math c = 0 while 1: if _square_wave: yield ((c %...
python
{ "resource": "" }
q37322
bash_echo_metric
train
def bash_echo_metric(): """A very basic example that monitors a number of currently running processes""" import subprocess # import random # more predictable version of the metric cmd = ( 'set -o pipefail ' ' ; pgrep -f "^bash.*sleep .*from bash: started relay launcher"' ...
python
{ "resource": "" }
q37323
bash_echo_warmer
train
def bash_echo_warmer(n): """A very basic example of how to create n additional tasks. This is a warmer function with randomly delayed effects on the bash_echo_metric and random task lengths to make the metric less predictable """ import subprocess import random cmd = ( 'set -o pi...
python
{ "resource": "" }
q37324
bash_echo_cooler
train
def bash_echo_cooler(n): """A very basic example of how to destroy n running tasks This is a cooler function """ import subprocess cmd = ( 'set -o pipefile ' ' ; kill `pgrep -f "from bash: started relay launcher task"' ' | tail -n %s` 2>/dev/null' % n) subprocess.Popen(cm...
python
{ "resource": "" }
q37325
stop_if_mostly_diverging
train
def stop_if_mostly_diverging(errdata): """This is an example stop condition that asks Relay to quit if the error difference between consecutive samples is increasing more than half of the time. It's quite sensitive and designed for the demo, so you probably shouldn't use this is a production settin...
python
{ "resource": "" }
q37326
Task.has_resolved_dependencies
train
def has_resolved_dependencies(self): """Return True if all dependencies are in State.DONE""" for dependency in self.dependencies: if dependency.state != Task.State.DONE: return False return True
python
{ "resource": "" }
q37327
Task.dependencies_as_list
train
def dependencies_as_list(self): """Returns a list of dependency names.""" dependencies = [] for dependency in self.dependencies: dependencies.append(dependency.name) return dependencies
python
{ "resource": "" }
q37328
Tasks.get_task
train
def get_task(self, name): """Get task by name or create it if it does not exists.""" if name in self.tasks.keys(): task = self.tasks[name] else: task = Task(name) self.tasks[name] = task return task
python
{ "resource": "" }
q37329
Tasks.get_next
train
def get_next(self): """Return next task from the stack that has all dependencies resolved. Return None if there are no tasks with resolved dependencies or is there are no more tasks on stack. Use `count` to check is there are still some task left on the stack. raise ValueError if total ...
python
{ "resource": "" }
q37330
Tasks.count_buildable_tasks
train
def count_buildable_tasks(self): """Count tasks that are new and have dependencies in non FAILED state.""" self.update_tasks_status() buildable_tasks_count = 0 for key, task in self.tasks.iteritems(): if task.state is Task.State.NEW: if self.are_dependencies_b...
python
{ "resource": "" }
q37331
Tasks.tsort
train
def tsort(self): """Given a partial ordering, return a totally ordered list. part is a dict of partial orderings. Each value is a set, which the key depends on. The return value is a list of sets, each of which has only dependencies on items in previous entries in the list. ...
python
{ "resource": "" }
q37332
Config._load_config
train
def _load_config(self): """ Load project's config and return dict. TODO: Convert the original dotted representation to hierarchical. """ config = import_module('config') variables = [var for var in dir(config) if not var.startswith('_')] return {var: getattr(conf...
python
{ "resource": "" }
q37333
Config.get
train
def get(name, default=None): """ Return variable by name from the project's config. Name can be a dotted path, like: 'rails.db.type'. """ if '.' not in name: raise Exception("Config path should be divided by at least one dot") section_name, var_path = name.sp...
python
{ "resource": "" }
q37334
SortedCollection.find_lt
train
def find_lt(self, k): """Return last item with a key < k. Raise ValueError if not found. """ i = bisect_left(self._keys, k) if i: return self._items[i - 1] raise ValueError('No item found with key below: %r' % (k,))
python
{ "resource": "" }
q37335
SortedCollection.find_ge_index
train
def find_ge_index(self, k): 'Return first item with a key >= equal to k. Raise ValueError if not found' i = bisect_left(self._keys, k) if i != len(self): return i raise ValueError('No item found with key at or above: %r' % (k,))
python
{ "resource": "" }
q37336
start
train
def start( loop: abstract_loop = None, interval: float = 0.5, hook: hook_type = None) -> asyncio.Task: """ Start the reloader. Create the task which is watching loaded modules and manually added files via ``watch()`` and reloading the process in case of modification. Att...
python
{ "resource": "" }
q37337
strftime
train
def strftime(dt, fmt): ''' `strftime` implementation working before 1900 ''' if _illegal_s.search(fmt): raise TypeError("This strftime implementation does not handle %s") if dt.year > 1900: return dt.strftime(fmt) fmt = fmt.replace('%c', '%a %b %d %H:%M:%S %Y')\ .re...
python
{ "resource": "" }
q37338
_detect_timezone_windows
train
def _detect_timezone_windows(): """Detect timezone on the windows platform.""" # pylint: disable=global-statement global win32timezone_to_en # Try and fetch the key_name for the timezone using # Get(Dynamic)TimeZoneInformation tzi = DTZI_c() kernel32 = ctypes.windll.kernel32 getter = kernel32.GetTimeZo...
python
{ "resource": "" }
q37339
CookieAuth.login
train
def login(self, template='login'): ''' This property will return component which will handle login requests. auth.login(template='login.html') ''' def _login(env, data): form = self._login_form(env) next = env.request.GET.get('next', '/') ...
python
{ "resource": "" }
q37340
CookieAuth.logout
train
def logout(self, redirect_to='/'): ''' This property will return component which will handle logout requests. It only handles POST requests and do not display any rendered content. This handler deletes session id from `storage`. If there is no session id provided or id is incorre...
python
{ "resource": "" }
q37341
SupportLevelPage.content
train
def content(self, content): """ Sets the content of this SupportLevelPage. :param content: The content of this SupportLevelPage. :type: list[str] """ allowed_values = ["UNRELEASED", "EARLYACCESS", "SUPPORTED", "EXTENDED_SUPPORT", "EOL"] if not set(content).issubs...
python
{ "resource": "" }
q37342
copy_file_or_flo
train
def copy_file_or_flo(input_, output, buffer_size=64 * 1024, cb=None): """ Copy a file name or file-like-object to another file name or file-like object""" assert bool(input_) assert bool(output) input_opened = False output_opened = False try: if isinstance(input_, string_types): ...
python
{ "resource": "" }
q37343
TropoBackend.execute_tropo_program
train
def execute_tropo_program(self, program): """ Ask Tropo to execute a program for us. We can't do this directly; we have to ask Tropo to call us back and then give Tropo the program in the response body to that request from Tropo. But we can pass data to Tropo and ask Tr...
python
{ "resource": "" }
q37344
TropoBackend.send
train
def send(self, id_, text, identities, context=None): """ Send messages when using RapidSMS 0.14.0 or later. We can send multiple messages in one Tropo program, so we do that. :param id_: Unused, included for compatibility with RapidSMS. :param string text: The message t...
python
{ "resource": "" }
q37345
CensusTractGeoid.dotted
train
def dotted(self): """Return just the tract number, excluding the state and county, in the dotted format""" v = str(self.geoid.tract).zfill(6) return v[0:4] + '.' + v[4:]
python
{ "resource": "" }
q37346
GeoCensusVT.subclass
train
def subclass(cls, vt_code, vt_args): """Return a dynamic subclass that has the extra parameters built in""" from geoid import get_class import geoid.census parser = get_class(geoid.census, vt_args.strip('/')).parse cls = type(vt_code.replace('/', '_'), (cls,), {'vt_code': vt_co...
python
{ "resource": "" }
q37347
TailedFile._open
train
def _open(self, path, skip_to_end = True, offset = None): """Open `path`, optionally seeking to the end if `skip_to_end` is True.""" fh = os.fdopen(os.open(path, os.O_RDONLY | os.O_NONBLOCK)) # If the file is being opened for the first time, jump to the end. # Otherwise, it is being reopened af...
python
{ "resource": "" }
q37348
TailedFile._read
train
def _read(self, limit = None): """Checks the file for new data and refills the buffer if it finds any.""" # The code that used to be here was self._fh.read(limit) # However, this broke on OSX. os.read, however, works fine, but doesn't # take the None argument or have any way to specify "read to ...
python
{ "resource": "" }
q37349
TailedFile.hasBeenRotated
train
def hasBeenRotated(self): """Returns a boolean indicating whether the file has been removed and recreated during the time it has been open.""" try: # If the inodes don't match, it means the file has been replaced. # The inode number cannot be recycled as long as we hold the # file...
python
{ "resource": "" }
q37350
TailedFile.reopen
train
def reopen(self): """Reopens the file. Usually used after it has been rotated.""" # Read any remaining content in the file and store it in a buffer. self._read() # Close it to ensure we don't leak file descriptors self._close() # Reopen the file. try: self._open...
python
{ "resource": "" }
q37351
TailedFile.readlines
train
def readlines(self): """A generator producing lines from the file.""" # If the file is not open, there's nothing to return if not self._fh: raise StopIteration at_eof = False while True: # Clean the buffer sometimes. if self._bufoffset > (self._maxreadsize / 2)...
python
{ "resource": "" }
q37352
MultiTail._rescan
train
def _rescan(self, skip_to_end = True): """Check for new files, deleted files, and rotated files.""" # Get listing of matching files. paths = [] for single_glob in self._globspec: paths.extend(glob.glob(single_glob)) # Remove files that don't appear in the new list. for pat...
python
{ "resource": "" }
q37353
Route.connectTo
train
def connectTo(self, remoteRouteName): """ Set the name of the route which will be added to outgoing boxes. """ self.remoteRouteName = remoteRouteName # This route must not be started before its router is started. If # sender is None, then the router is not started. When...
python
{ "resource": "" }
q37354
Route.sendBox
train
def sendBox(self, box): """ Add the route and send the box. """ if self.remoteRouteName is _unspecified: raise RouteNotConnected() if self.remoteRouteName is not None: box[_ROUTE] = self.remoteRouteName.encode('ascii') self.router._sender.sendBox(b...
python
{ "resource": "" }
q37355
Router.bindRoute
train
def bindRoute(self, receiver, routeName=_unspecified): """ Create a new route to associate the given route name with the given receiver. @type routeName: C{unicode} or L{NoneType} @param routeName: The identifier for the newly created route. If C{None}, boxes with n...
python
{ "resource": "" }
q37356
Router.startReceivingBoxes
train
def startReceivingBoxes(self, sender): """ Initialize route tracking objects. """ self._sender = sender for routeName, route in self._unstarted.iteritems(): # Any route which has been bound but which does not yet have a # remote route name should not yet b...
python
{ "resource": "" }
q37357
push_build
train
def push_build(id, tag_prefix): """ Push build to Brew """ req = swagger_client.BuildRecordPushRequestRest() req.tag_prefix = tag_prefix req.build_record_id = id response = utils.checked_api_call(pnc_api.build_push, 'push', body=req) if response: return utils.format_json_list(res...
python
{ "resource": "" }
q37358
push_build_set
train
def push_build_set(id, tag_prefix): """ Push build set to Brew """ req = swagger_client.BuildConfigSetRecordPushRequestRest() req.tag_prefix = tag_prefix req.build_config_set_record_id = id response = utils.checked_api_call(pnc_api.build_push, 'push_record_set', body=req) if response: ...
python
{ "resource": "" }
q37359
push_build_status
train
def push_build_status(id): """ Get status of Brew push. """ response = utils.checked_api_call(pnc_api.build_push, 'status', build_record_id=id) if response: return utils.format_json(response)
python
{ "resource": "" }
q37360
FileManager.create_transient
train
def create_transient(self, input_stream, original_name, length=None): '''Create TransientFile and file on FS from given input stream and original file name.''' ext = os.path.splitext(original_name)[1] transient = self.new_transient(ext) if not os.path.isdir(self.transient_root):...
python
{ "resource": "" }
q37361
FileManager.new_transient
train
def new_transient(self, ext=''): '''Creates empty TransientFile with random name and given extension. File on FS is not created''' name = random_name(self.transient_length) + ext return TransientFile(self.transient_root, name, self)
python
{ "resource": "" }
q37362
FileManager.get_transient
train
def get_transient(self, name): '''Restores TransientFile object with given name. Should be used when form is submitted with file name and no file''' # security checks: basically no folders are allowed assert not ('/' in name or '\\' in name or name[0] in '.~') transient = Transie...
python
{ "resource": "" }
q37363
FileManager.store
train
def store(self, transient_file, persistent_file): '''Makes PersistentFile from TransientFile''' #for i in range(5): # persistent_file = PersistentFile(self.persistent_root, # persistent_name, self) # if not os.path.exists(persistent_file....
python
{ "resource": "" }
q37364
trace
train
def trace(fn): # pragma: no cover """ Prints parameteters and return values of the each call of the wrapped function. Usage: decorate appropriate function or method: @trace def myf(): ... """ def wrapped(*args, **kwargs): msg = [] msg.appe...
python
{ "resource": "" }
q37365
patch_file_open
train
def patch_file_open(): # pragma: no cover """A Monkey patch to log opening and closing of files, which is useful for debugging file descriptor exhaustion.""" openfiles = set() oldfile = builtins.file class newfile(oldfile): def __init__(self, *args, **kwargs): self.x = args[0] ...
python
{ "resource": "" }
q37366
PasswordChallengeResponse.determineFrom
train
def determineFrom(cls, challenge, password): """ Create a nonce and use it, along with the given challenge and password, to generate the parameters for a response. @return: A C{dict} suitable to be used as the keyword arguments when calling this command. """ ...
python
{ "resource": "" }
q37367
_AMPUsernamePassword.checkPassword
train
def checkPassword(self, password): """ Check the given plaintext password against the response in this credentials object. @type password: C{str} @param password: The known correct password associated with C{self.username}. @return: A C{bool}, C{True} if thi...
python
{ "resource": "" }
q37368
CredReceiver.passwordLogin
train
def passwordLogin(self, username): """ Generate a new challenge for the given username. """ self.challenge = secureRandom(16) self.username = username return {'challenge': self.challenge}
python
{ "resource": "" }
q37369
CredReceiver._login
train
def _login(self, credentials): """ Actually login to our portal with the given credentials. """ d = self.portal.login(credentials, None, IBoxReceiver) def cbLoggedIn((interface, avatar, logout)): self.logout = logout self.boxReceiver = avatar s...
python
{ "resource": "" }
q37370
CredReceiver.passwordChallengeResponse
train
def passwordChallengeResponse(self, cnonce, response): """ Verify the response to a challenge. """ return self._login(_AMPUsernamePassword( self.username, self.challenge, cnonce, response))
python
{ "resource": "" }
q37371
CredReceiver.connectionLost
train
def connectionLost(self, reason): """ If a login has happened, perform a logout. """ AMP.connectionLost(self, reason) if self.logout is not None: self.logout() self.boxReceiver = self.logout = None
python
{ "resource": "" }
q37372
LiveLyric.on_position_changed
train
def on_position_changed(self, position): """bind position changed signal with this""" if not self._lyric: return pos = find_previous(position*1000 + 300, self._pos_list) if pos is not None and pos != self._pos: self.current_sentence = self._pos_s_map[pos] ...
python
{ "resource": "" }
q37373
LiveLyric.on_song_changed
train
def on_song_changed(self, song): """bind song changed signal with this""" if song is None or song.lyric is None: self._lyric = None self._pos_s_map = {} else: self._lyric = song.lyric.content self._pos_s_map = parse(self._lyric) self._pos_l...
python
{ "resource": "" }
q37374
sanitizeStructTime
train
def sanitizeStructTime(struct): """ Convert struct_time tuples with possibly invalid values to valid ones by substituting the closest valid value. """ maxValues = (9999, 12, 31, 23, 59, 59) minValues = (1, 1, 1, 0, 0, 0) newstruct = [] for value, maxValue, minValue in zip(struct[:6], max...
python
{ "resource": "" }
q37375
Time.fromHumanly
train
def fromHumanly(klass, humanStr, tzinfo=None, now=None): """Return a new Time instance from a string a human might type. @param humanStr: the string to be parsed. @param tzinfo: A tzinfo instance indicating the timezone to assume if none is specified in humanStr. If None, assume UTC. ...
python
{ "resource": "" }
q37376
Time.fromStructTime
train
def fromStructTime(klass, structTime, tzinfo=None): """Return a new Time instance from a time.struct_time. If tzinfo is None, structTime is in UTC. Otherwise, tzinfo is a datetime.tzinfo instance coresponding to the timezone in which structTime is. Many of the functions in the ...
python
{ "resource": "" }
q37377
Time.fromDatetime
train
def fromDatetime(klass, dtime): """Return a new Time instance from a datetime.datetime instance. If the datetime instance does not have an associated timezone, it is assumed to be UTC. """ self = klass.__new__(klass) if dtime.tzinfo is not None: self._time = ...
python
{ "resource": "" }
q37378
Time.fromPOSIXTimestamp
train
def fromPOSIXTimestamp(klass, secs): """Return a new Time instance from seconds since the POSIX epoch. The POSIX epoch is midnight Jan 1, 1970 UTC. According to POSIX, leap seconds don't exist, so one UTC day is exactly 86400 seconds, even if it wasn't. @param secs: a number of...
python
{ "resource": "" }
q37379
Time.fromRFC2822
train
def fromRFC2822(klass, rfc822string): """ Return a new Time instance from a string formated as described in RFC 2822. @type rfc822string: str @raise ValueError: if the timestamp is not formatted properly (or if certain obsoleted elements of the specification are used). ...
python
{ "resource": "" }
q37380
Time.asDatetime
train
def asDatetime(self, tzinfo=None): """Return this time as an aware datetime.datetime instance. The returned datetime object has the specified tzinfo, or a tzinfo describing UTC if the tzinfo parameter is None. """ if tzinfo is None: tzinfo = FixedOffset(0, 0) ...
python
{ "resource": "" }
q37381
Time.asRFC2822
train
def asRFC2822(self, tzinfo=None, includeDayOfWeek=True): """Return this Time formatted as specified in RFC 2822. RFC 2822 specifies the format of email messages. RFC 2822 says times in email addresses should reflect the local timezone. If tzinfo is a datetime.tzinfo instance, the retur...
python
{ "resource": "" }
q37382
Time.asISO8601TimeAndDate
train
def asISO8601TimeAndDate(self, includeDelimiters=True, tzinfo=None, includeTimezone=True): """Return this time formatted as specified by ISO 8861. ISO 8601 allows optional dashes to delimit dates and colons to delimit times. The parameter includeDelimiters (default ...
python
{ "resource": "" }
q37383
Time.asStructTime
train
def asStructTime(self, tzinfo=None): """Return this time represented as a time.struct_time. tzinfo is a datetime.tzinfo instance coresponding to the desired timezone of the output. If is is the default None, UTC is assumed. """ dtime = self.asDatetime(tzinfo) if tzinfo i...
python
{ "resource": "" }
q37384
Time.asHumanly
train
def asHumanly(self, tzinfo=None, now=None, precision=Precision.MINUTES): """Return this time as a short string, tailored to the current time. Parts of the date that can be assumed are omitted. Consequently, the output string depends on the current time. This is the format used for displ...
python
{ "resource": "" }
q37385
Time.getBounds
train
def getBounds(self, tzinfo=None): """ Return a pair describing the bounds of self. This returns a pair (min, max) of Time instances. It is not quite the same as (self, self + self.resolution). This is because timezones are insignificant for instances with a resolution greater or...
python
{ "resource": "" }
q37386
Time.oneDay
train
def oneDay(self): """Return a Time instance representing the day of the start of self. The returned new instance will be set to midnight of the day containing the first instant of self in the specified timezone, and have a resolution of datetime.timedelta(days=1). """ da...
python
{ "resource": "" }
q37387
expiring_memoize
train
def expiring_memoize(obj): """Like memoize, but forgets after 10 seconds.""" cache = obj.cache = {} last_access = obj.last_access = defaultdict(int) @wraps(obj) def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if last_access[key] and last_access[key] + 10 < time(): ...
python
{ "resource": "" }
q37388
md5_for_file
train
def md5_for_file(f, block_size=2 ** 20): """Generate an MD5 has for a possibly large file by breaking it into chunks.""" md5 = hashlib.md5() try: # Guess that f is a FLO. f.seek(0) return md5_for_stream(f, block_size=block_size) except AttributeError: # Nope, not a...
python
{ "resource": "" }
q37389
make_acro
train
def make_acro(past, prefix, s): # pragma: no cover """Create a three letter acronym from the input string s. Args: past: A set object, for storing acronyms that have already been created prefix: A prefix added to the acronym before storing in the set s: The string to create the acronym...
python
{ "resource": "" }
q37390
ensure_dir_exists
train
def ensure_dir_exists(path): """Given a file, ensure that the path to the file exists""" import os f_dir = os.path.dirname(path) if not os.path.exists(f_dir): os.makedirs(f_dir) return f_dir
python
{ "resource": "" }
q37391
init_log_rate
train
def init_log_rate(output_f, N=None, message='', print_rate=None): """Initialze the log_rate function. Returnas a partial function to call for each event. If N is not specified but print_rate is specified, the initial N is set to 100, and after the first message, the N value is adjusted to emit prin...
python
{ "resource": "" }
q37392
_log_rate
train
def _log_rate(output_f, d, message=None): """Log a message for the Nth time the method is called. d is the object returned from init_log_rate """ if d[2] <= 0: if message is None: message = d[4] # Average the rate over the length of the deque. d[6].append(int(d[3...
python
{ "resource": "" }
q37393
count_open_fds
train
def count_open_fds(): """return the number of open file descriptors for current process. .. warning: will only work on UNIX-like os-es. http://stackoverflow.com/a/7142094 """ pid = os.getpid() procs = subprocess.check_output( ['lsof', '-w', '-Ff', '-p', str(pid)]) nprocs = len( ...
python
{ "resource": "" }
q37394
parse_url_to_dict
train
def parse_url_to_dict(url): """Parse a url and return a dict with keys for all of the parts. The urlparse function() returns a wacky combination of a namedtuple with properties. """ p = urlparse(url) return { 'scheme': p.scheme, 'netloc': p.netloc, 'path': p.path, ...
python
{ "resource": "" }
q37395
set_url_part
train
def set_url_part(url, **kwargs): """Change one or more parts of a URL""" d = parse_url_to_dict(url) d.update(kwargs) return unparse_url_dict(d)
python
{ "resource": "" }
q37396
filter_url
train
def filter_url(url, **kwargs): """filter a URL by returning a URL with only the parts specified in the keywords""" d = parse_url_to_dict(url) d.update(kwargs) return unparse_url_dict({k: v for k, v in list(d.items()) if v})
python
{ "resource": "" }
q37397
print_yaml
train
def print_yaml(o): """Pretty print an object as YAML.""" print(yaml.dump(o, default_flow_style=False, indent=4, encoding='utf-8'))
python
{ "resource": "" }
q37398
qualified_class_name
train
def qualified_class_name(o): """Full name of an object, including the module""" module = o.__class__.__module__ if module is None or module == str.__class__.__module__: return o.__class__.__name__ return module + '.' + o.__class__.__name__
python
{ "resource": "" }
q37399
drop_empty
train
def drop_empty(rows): """Transpose the columns into rows, remove all of the rows that are empty after the first cell, then transpose back. The result is that columns that have a header but no data in the body are removed, assuming the header is the first row. """ return zip(*[col for col in zip(*rows) i...
python
{ "resource": "" }