text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unwrap_or_else(self, callback: Callable[[], U]) -> Union[T, U]: """ Returns the contained value or computes it from ``callback``. Args: callback: The the defa... |
return self._val if self._is_some else callback() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map_or(self, callback: Callable[[T], U], default: A) -> Union[U, A]: """ Applies the ``callback`` to the contained value or returns ``default``. Args: callbac... |
return callback(self._val) if self._is_some else default |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get( self: 'Option[Mapping[K,V]]', key: K, default=None ) -> 'Option[V]': """ Gets a mapping value by key in the contained value or returns ``default`` if the... |
if self._is_some:
return self._type.maybe(self._val.get(key, default))
return self._type.maybe(default) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assure_migrations_table_setup(db):
""" Make sure the migrations table is set up in the database. """ |
from mig.models import MigrationData
if not MigrationData.__table__.exists(db.bind):
MigrationData.metadata.create_all(
db.bind, tables=[MigrationData.__table__]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sorted_migrations(self):
""" Sort migrations if necessary and store in self._sorted_migrations """ |
if not self._sorted_migrations:
self._sorted_migrations = sorted(
self.migration_registry.items(),
# sort on the key... the migration number
key=lambda migration_tuple: migration_tuple[0])
return self._sorted_migrations |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def migration_data(self):
""" Get the migration row associated with this object, if any. """ |
return self.session.query(
self.migration_model).filter_by(name=self.name).first() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def database_current_migration(self):
""" Return the current migration in the database. """ |
# If the table doesn't even exist, return None.
if not self.migration_table.exists(self.session.bind):
return None
# Also return None if self.migration_data is None.
if self.migration_data is None:
return None
return self.migration_data.version |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def migrations_to_run(self):
""" Get a list of migrations to run still, if any. Note that this will fail if there's no migration record for this class! """ |
assert self.database_current_migration is not None
db_current_migration = self.database_current_migration
return [
(migration_number, migration_func)
for migration_number, migration_func in self.sorted_migrations
if migration_number > db_current_migration] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_tables(self):
""" Create all tables relative to this package """ |
# sanity check before we proceed, none of these should be created
for model in self.models:
# Maybe in the future just print out a "Yikes!" or something?
_log.debug('Checking for table {0}'.format(model))
assert not model.__table__.exists(self.session.bind)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_new_migration_record(self):
""" Create a new migration record for this migration set """ |
migration_record = self.migration_model(
name=self.name,
version=self.latest_migration)
self.session.add(migration_record)
self.session.commit() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dry_run(self):
""" Print out a dry run of what we would have upgraded. """ |
if self.database_current_migration is None:
self.printer(
u'~> Woulda initialized: %s\n' % self.name_for_printing())
return u'inited'
migrations_to_run = self.migrations_to_run()
if migrations_to_run:
self.printer(
u'~> Wo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_or_migrate(self):
""" Initialize the database or migrate if appropriate. Returns information about whether or not we initialized ('inited'), migrated ('... |
assure_migrations_table_setup(self.session)
# Find out what migration number, if any, this database data is at,
# and what the latest is.
migration_number = self.database_current_migration
# Is this our first time? Is there even a table entry for
# this identifier?
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authenticateRequest(self, request, service_request, *args, **kwargs):
""" Authenticates the request against the service. @param request: The AMF request @typ... |
username = password = None
if 'Credentials' in request.headers:
cred = request.headers['Credentials']
username = cred['userid']
password = cred['password']
return self.gateway.authenticateRequest(service_request, username,
password, *args, **kw... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def dumpable_obj(obj):
''' takes an object that fails with json.dumps and converts it to
a json.dumps dumpable object. This is useful for debuging code when
you want to dump an object for easy reading'''
if isinstance(obj, list):
_return_list = []
for item in obj:
if isinsta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_all_paths(G, start, end, path=[]):
"""
Find all paths between vertices start and end in graph.
""" |
path = path + [start]
if start == end:
return [path]
if start not in G.vertices:
raise GraphInsertError("Vertex %s doesn't exist." % (start,))
if end not in G.vertices:
raise GraphInsertError("Vertex %s doesn't exist." % (end,))
paths = []
for vertex in G.vertic... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def system_call(command):
"""Run a command and return stdout. Would be better to use subprocess.check_output, but this works on 2.6, which is still the system Py... |
p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)
return p.stdout.read() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_headers(self, session, **kwargs):
"""Get the authentication header. If the current session has not been authenticated, this will trigger a new authentica... |
if self.auth_token is None:
try:
self._refresh_tokens(session)
self._fetch_credentials(session)
except:
raise AuthorizationFailure()
return {
'X-Auth-Token': self.auth_token,
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_endpoint(self, session, **kwargs):
"""Get the HubiC storage endpoint uri. If the current session has not been authenticated, this will trigger a new auth... |
if self.endpoint is None:
try:
self._refresh_tokens(session)
self._fetch_credentials(session)
except:
raise AuthorizationFailure()
return self.endpoint |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _refresh_tokens(self, session):
"""Request an access and a refresh token from the HubiC API. Those tokens are mandatory and will be used for subsequent file ... |
params = {
'client_id': self.client_id,
'client_secret': self.client_secret,
}
payload = {
'client_id': self.client_id,
'client_secret': self.client_secret,
}
if self.refresh_token is None:
# if we don't have a refre... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fetch_credentials(self, session):
"""Fetch the endpoint URI and authorization token for this session. Those two information are the basis for all future cal... |
headers = {
'Authorization': 'Bearer {0}'.format(self.access_token),
}
r = session.get("https://api.hubic.com/1.0/account/credentials",
headers=headers,
authenticated=False)
response = r.json()
# if we get an error h... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_authorization_token(self, session):
"""Load the HubiC form, submit it and return an authorization token. This will load the HTML form to accept if the a... |
request_scope = 'account.r,credentials.r'
params = {
'client_id': self.client_id,
'redirect_uri': self.redirect_uri,
'response_type': 'code',
'scope': request_scope,
'state': random_str_generator(),
}
r = session.get("https:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getStringForBytes(self, s):
""" Returns the corresponding string for the supplied utf-8 encoded bytes. If there is no string object, one is created. @since: ... |
h = hash(s)
u = self._unicodes.get(h, None)
if u is not None:
return u
u = self._unicodes[h] = s.decode('utf-8')
return u |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getBytesForString(self, u):
""" Returns the corresponding utf-8 encoded string for a given unicode object. If there is no string, one is encoded. @since: 0.6... |
h = hash(u)
s = self._unicodes.get(h, None)
if s is not None:
return s
s = self._unicodes[h] = u.encode('utf-8')
return s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def readElement(self):
""" Reads an AMF3 element from the data stream. @raise DecodeError: The ActionScript type is unsupported. @raise EOStream: No more data le... |
pos = self.stream.tell()
try:
t = self.stream.read(1)
except IOError:
raise pyamf.EOStream
try:
func = self._func_cache[t]
except KeyError:
func = self.getTypeFunc(t)
if not func:
raise pyamf.DecodeEr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def writeSequence(self, iterable):
""" Encodes an iterable. The default is to write If the iterable has an al """ |
try:
alias = self.context.getClassAlias(iterable.__class__)
except (AttributeError, pyamf.UnknownClassAlias):
self.writeList(iterable)
return
if alias.external:
# a is a subclassed list with a registered alias - push to the
# correct... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def writeGenerator(self, gen):
""" Iterates over a generator object and encodes all that is returned. """ |
n = getattr(gen, 'next')
while True:
try:
self.writeElement(n())
except StopIteration:
break |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collect_fragment(event, agora_host):
""" Execute a search plan for the declared graph pattern and sends all obtained triples to the corresponding collector f... |
agora = Agora(agora_host)
graph_pattern = ""
for tp in __triple_patterns:
graph_pattern += '{} . '.format(tp)
fragment, _, graph = agora.get_fragment_generator('{%s}' % graph_pattern, stop_event=event, workers=4)
__extract_pattern_nodes(graph)
log.info('querying { %s}' % graph_pattern)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(key, section='main'):
""" Get a single option from """ |
return nago.settings.get_option(option_name=key, section_name=section) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _frame_generator(self, frame_duration_ms, audio, sample_rate):
"""Generates audio frames from PCM audio data. Takes the desired frame duration in millisecond... |
n = int(sample_rate * (frame_duration_ms / 1000.0) * 2)
offset = 0
timestamp = 0.0
duration = (float(n) / sample_rate) / 2.0
while offset + n < len(audio):
yield self.Frame(audio[offset:offset + n], timestamp, duration)
timestamp += duration
o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _finaliseRequest(self, request, status, content, mimetype='text/plain'):
""" Finalises the request. @param request: The HTTP Request. @type request: C{http.R... |
request.setResponseCode(status)
request.setHeader("Content-Type", mimetype)
request.setHeader("Content-Length", str(len(content)))
request.setHeader("Server", gateway.SERVER_NAME)
request.write(content)
request.finish() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_POST(self, request):
""" Read remoting request from the client. @type request: The HTTP Request. @param request: C{twisted.web.http.Request} """ |
def handleDecodeError(failure):
"""
Return HTTP 400 Bad Request.
"""
errMesg = "%s: %s" % (failure.type, failure.getErrorMessage())
if self.logger:
self.logger.error(errMesg)
self.logger.error(failure.getTraceback())
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getStreamLevel(self):
""" Get and return current stream handler's level. """ |
shlvl = 0
for i in range(0,len(self.handlers)):
h = self.handlers[i]
if isinstance(h,logging.StreamHandler):
shlvl = h.level
return shlvl |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def logSystemInfo(self):
""" A function to be called just after a logging object is instantiated to load the log up with info about the computer it is being ran ... |
t = datetime.date.today()
infoStr = 'Date KMlogger object instantiated: '+t.strftime('%b %d, %Y')+'\n\n'
infoStr+="\n"+"="*11+' System Information Summary '+'='*11
infoStr+="\n"+'OS type = '+platform.uname()[0]
infoStr+="\n"+'OS Version = '+platform.uname()[2]
infoStr+="... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install_wrapper(cls, install, new_class):
""" Wrap the install method to call pre and post enable signals and update module status """ |
def _wrapped(self, *args, **kwargs):
if self.installed:
raise AssertionError('Module %s is already installed'
% self.verbose_name)
logger.info("Installing %s module" % self.verbose_name)
pre_install.send(sender=self)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable_wrapper(cls, enable, new_class):
""" Wrap the enable method to call pre and post enable signals and update module status """ |
def _wrapped(self, *args, **kwargs):
if not self.installed:
raise AssertionError('Module %s cannot be enabled'
', you should install it first'
% self.verbose_name)
if self.enabled:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_wrapper(cls, save, new_class):
""" Wrap the save method to call pre and post enable signals and update module status """ |
def _wrapped(self, *args, **kwargs):
if not self.installed:
raise AssertionError('Module %s is not installed' %
self.verbose_name)
logger.info("Saving %s module" % self.verbose_name)
pre_save.send(sender=self)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disable_wrapper(cls, disable, new_class):
""" Wrap the disable method to call pre and post disable signals and update module status """ |
def _wrapped(self, *args, **kwargs):
if not self.enabled:
raise AssertionError('Module %s is already disabled'
% self.verbose_name)
logger.info("Disabling %s module" % self.verbose_name)
pre_disable.send(sender=self)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _info(self):
""" Module internal status representation """ |
name = self.__class__.__module__ + '.' + self.__class__.__name__
info, created = ModuleInfo.objects.get_or_create(name=name)
if created:
# Do not set as changed
info.commit()
return info |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def models(self):
""" Return all the models defined for this module """ |
app = get_app(self.__class__.__module__.split('.')[-2])
return get_models(app) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conf_files(self):
""" List of configuration files for this module """ |
for attr in dir(self):
field = getattr(self, attr)
if isinstance(field, ConfFile):
yield field |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def daemons(self):
""" List of daemons for this module """ |
for attr in dir(self):
field = getattr(self, attr)
if isinstance(field, Daemon):
yield field |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_endpoint_by_endpoint_id(self, endpoint_id):
""" Get an endpoint by endpoint id """ |
self._validate_uuid(endpoint_id)
url = "/notification/v1/endpoint/{}".format(endpoint_id)
response = NWS_DAO().getURL(url, self._read_headers)
if response.status != 200:
raise DataFailureException(url, response.status, response.data)
data = json.loads(response.dat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_endpoint_by_subscriber_id_and_protocol( self, subscriber_id, protocol):
""" Get an endpoint by subscriber_id and protocol """ |
self._validate_subscriber_id(subscriber_id)
self._validate_endpoint_protocol(protocol)
url = "/notification/v1/endpoint?subscriber_id={}&protocol={}".format(
subscriber_id, protocol)
response = NWS_DAO().getURL(url, self._read_headers)
if response.status != 200:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_endpoint_by_address(self, endpoint_addr):
""" Get an endpoint by address """ |
url = "/notification/v1/endpoint?endpoint_address={}".format(
endpoint_addr)
response = NWS_DAO().getURL(url, self._read_headers)
if response.status != 200:
raise DataFailureException(url, response.status, response.data)
data = json.loads(response.data)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_endpoints_by_subscriber_id(self, subscriber_id):
""" Search for all endpoints by a given subscriber """ |
self._validate_subscriber_id(subscriber_id)
url = "/notification/v1/endpoint?subscriber_id={}".format(
subscriber_id)
response = NWS_DAO().getURL(url, self._read_headers)
if response.status != 200:
raise DataFailureException(url, response.status, response.data... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resend_sms_endpoint_verification(self, endpoint_id):
""" Calls NWS function to resend verification message to endpoint's phone number """ |
self._validate_uuid(endpoint_id)
url = "/notification/v1/endpoint/{}/verification".format(endpoint_id)
response = NWS_DAO().postURL(url, None, None)
if response.status != 202:
raise DataFailureException(url, response.status, response.data)
return response.status |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_subscriptions_by_subscriber_id( self, subscriber_id, max_results=10):
""" Search for all subscriptions by a given subscriber """ |
return self.search_subscriptions(
subscriber_id=subscriber_id, max_results=max_results) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_subscriptions_by_channel_id_and_subscriber_id( self, channel_id, subscriber_id):
""" Search for all subscriptions by a given channel and subscriber """ |
return self.search_subscriptions(
channel_id=channel_id, subscriber_id=subscriber_id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_subscriptions_by_channel_id_and_person_id( self, channel_id, person_id):
""" Search for all subscriptions by a given channel and person """ |
return self.search_subscriptions(
channel_id=channel_id, person_id=person_id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_subscription_by_channel_id_and_endpoint_id( self, channel_id, endpoint_id):
""" Search for subscription by a given channel and endpoint """ |
subscriptions = self.search_subscriptions(
channel_id=channel_id, endpoint_id=endpoint_id)
try:
return subscriptions[0]
except IndexError:
raise DataFailureException(url, 404, "No subscription found") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_subscriptions(self, **kwargs):
""" Search for all subscriptions by parameters """ |
params = [(key, kwargs[key]) for key in sorted(kwargs.keys())]
url = "/notification/v1/subscription?{}".format(
urlencode(params, doseq=True))
response = NWS_DAO().getURL(url, self._read_headers)
if response.status != 200:
raise DataFailureException(url, respon... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_channel_by_channel_id(self, channel_id):
""" Get a channel by channel id """ |
self._validate_uuid(channel_id)
url = "/notification/v1/channel/{}".format(channel_id)
response = NWS_DAO().getURL(url, self._read_headers)
if response.status != 200:
raise DataFailureException(url, response.status, response.data)
data = json.loads(response.data)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_channels_by_sln(self, channel_type, sln):
""" Search for all channels by sln """ |
return self.search_channels(type=channel_type, tag_sln=sln) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_channels_by_sln_year_quarter( self, channel_type, sln, year, quarter):
""" Search for all channels by sln, year and quarter """ |
return self.search_channels(
type=channel_type, tag_sln=sln, tag_year=year, tag_quarter=quarter) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_active_channels_by_year_quarter( self, channel_type, year, quarter, expires=None):
""" Search for all active channels by year and quarter """ |
if expires is None:
# Set expires_after to midnight of current day
expires = datetime.combine(datetime.utcnow().date(), time.min)
return self.search_channels(
type=channel_type, tag_year=year, tag_quarter=quarter,
expires_after=expires.isoformat()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_channels(self, **kwargs):
""" Search for all channels by parameters """ |
params = [(key, kwargs[key]) for key in sorted(kwargs.keys())]
url = "/notification/v1/channel?{}".format(
urlencode(params, doseq=True))
response = NWS_DAO().getURL(url, self._read_headers)
if response.status != 200:
raise DataFailureException(url, response.st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_first_last(details):
""" Gets a user's first and last name from details. """ |
if "first_name" in details and "last_name" in details:
return details["first_name"], details["last_name"]
elif "first_name" in details:
lst = details["first_name"].rsplit(" ", 1)
if len(lst) == 2:
return lst
else:
return lst[0], ""
elif "last_name" in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_field(field_classpath):
""" Imports a field by its dotted class path, prepending "django.db.models" to raw class names and raising an exception if the... |
if '.' in field_classpath:
fully_qualified = field_classpath
else:
fully_qualified = "django.db.models.%s" % field_classpath
try:
return import_dotted_path(fully_qualified)
except ImportError:
raise ImproperlyConfigured("The EXTRA_MODEL_FIELDS setting contains "
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_extra_model_fields(sender, **kwargs):
""" Injects custom fields onto the given sender model as defined by the ``EXTRA_MODEL_FIELDS`` setting. This is a c... |
model_key = sender._meta.app_label, sender._meta.model_name
for field_name, field in fields.get(model_key, {}):
field.contribute_to_class(sender, field_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(*args, **kwargs):
""" Simple entry-point that takes the package name and json output""" |
parser = argparse.ArgumentParser()
parser.add_argument('package_name', type=str)
parser.add_argument('output_filename', type=str)
parsed_args = parser.parse_args()
# Find all package requirements
get_all_requires(parsed_args.package_name)
# Write tmp results to a file to be read into ma... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tail( filepath = "log.txt", lines = 50 ):
""" Return a specified number of last lines of a specified file. If there is an error or the file does not exist, r... |
try:
filepath = os.path.expanduser(os.path.expandvars(filepath))
if os.path.isfile(filepath):
text = subprocess.check_output(["tail", "-" + str(lines), filepath])
if text:
return text
else:
return False
else:
re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_type_list_elements( list_object = None, element_type = str ):
""" Recursively convert all elements and all elements of all sublists of a list to a sp... |
if element_type is str:
return [str(element) if not isinstance(element, list) else convert_type_list_elements(
list_object = element,
element_type = str
) for element in list_object] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select_spread( list_of_elements = None, number_of_elements = None ):
""" This function returns the specified number of elements of a list spread approximatel... |
if len(list_of_elements) <= number_of_elements:
return list_of_elements
if number_of_elements == 0:
return []
if number_of_elements == 1:
return [list_of_elements[int(round((len(list_of_elements) - 1) / 2))]]
return \
[list_of_elements[int(round((len(list_of_elements) - ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split_list( list_object = None, granularity = None ):
""" This function splits a list into a specified number of lists. It returns a list of lists that corre... |
if granularity < 0:
raise Exception("negative granularity")
mean_length = len(list_object) / float(granularity)
split_list_object = []
last_length = float(0)
if len(list_object) > granularity:
while last_length < len(list_object):
split_list_object.append(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ustr(text):
""" Convert a string to Python 2 unicode or Python 3 string as appropriate to the version of Python in use. """ |
if text is not None:
if sys.version_info >= (3, 0):
return str(text)
else:
return unicode(text)
else:
return text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_time_variables(df, reindex = True):
""" Return a DataFrame with variables for weekday index, weekday name, timedelta through day, fraction through day, h... |
if not "datetime" in df.columns:
log.error("field datetime not found in DataFrame")
return False
df["datetime"] = pd.to_datetime(df["datetime"])
df["month"] = df["datetime"].dt.month
df["month_name"] = df["datetime"].dt.strftime("%B")
df["weekday... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def daily_plots( df, variable, renormalize = True, plot = True, scatter = False, linestyle = "-", linewidth = 1, s = 1 ):
""" Create daily plots of a variable in... |
if not df.index.dtype in ["datetime64[ns]", "<M8[ns]", ">M8[ns]"]:
log.error("index is not datetime")
return False
days = []
for group in df.groupby(df.index.day):
days.append(group[1])
scaler = MinMaxScaler()
plt.xlabel("hours")
plt.ylabel(variable);
for day in days... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def weekly_plots( df, variable, renormalize = True, plot = True, scatter = False, linestyle = "-", linewidth = 1, s = 1 ):
""" Create weekly plots of a variable ... |
if not "days_through_week" in df.columns:
log.error("field days_through_week not found in DataFrame")
return False
weeks = []
for group in df.groupby(df.index.week):
weeks.append(group[1])
scaler = MinMaxScaler()
plt.ylabel(variable);
for week in weeks:
if renorm... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def yearly_plots( df, variable, renormalize = True, horizontal_axis_labels_days = False, horizontal_axis_labels_months = True, plot = True, scatter = False, lines... |
if not df.index.dtype in ["datetime64[ns]", "<M8[ns]", ">M8[ns]"]:
log.error("index is not datetime")
return False
years = []
for group in df.groupby(df.index.year):
years.append(group[1])
scaler = MinMaxScaler()
plt.xlabel("days")
plt.ylabel(variable);
for year in y... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_rolling_statistics_variables( df = None, variable = None, window = 20, upper_factor = 2, lower_factor = 2 ):
""" Add rolling statistics variables derived... |
df[variable + "_rolling_mean"] = pd.stats.moments.rolling_mean(df[variable], window)
df[variable + "_rolling_standard_deviation"] = pd.stats.moments.rolling_std(df[variable], window)
df[variable + "_rolling_upper_bound"] = df[variable + "_rolling_mean"] + upper_factor * df[variable + "... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rescale_variables( df, variables_include = [], variables_exclude = [] ):
""" Rescale variables in a DataFrame, excluding variables with NaNs and strings, exc... |
variables_not_rescale = variables_exclude
variables_not_rescale.extend(df.columns[df.isna().any()].tolist()) # variables with NaNs
variables_not_rescale.extend(df.select_dtypes(include = ["object", "datetime", "timedelta"]).columns) # variables with strings
variables_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def histogram_hour_counts( df, variable ):
""" Create a day-long histogram of counts of the variable for each hour. It is assumed that the DataFrame index is dat... |
if not df.index.dtype in ["datetime64[ns]", "<M8[ns]", ">M8[ns]"]:
log.error("index is not datetime")
return False
counts = df.groupby(df.index.hour)[variable].count()
counts.plot(kind = "bar", width = 1, rot = 0, alpha = 0.7) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def histogram_day_counts( df, variable ):
""" Create a week-long histogram of counts of the variable for each day. It is assumed that the DataFrame index is date... |
if not df.index.dtype in ["datetime64[ns]", "<M8[ns]", ">M8[ns]"]:
log.error("index is not datetime")
return False
counts = df.groupby(df.index.weekday_name)[variable].count().reindex(calendar.day_name[0:])
counts.plot(kind = "bar", width = 1, rot = 0, alpha = 0.7) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def histogram_month_counts( df, variable ):
""" Create a year-long histogram of counts of the variable for each month. It is assumed that the DataFrame index is ... |
if not df.index.dtype in ["datetime64[ns]", "<M8[ns]", ">M8[ns]"]:
log.error("index is not datetime")
return False
counts = df.groupby(df.index.strftime("%B"))[variable].count().reindex(calendar.month_name[1:])
counts.plot(kind = "bar", width = 1, rot = 0, alpha = 0.7) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup_Jupyter():
""" Set up a Jupyter notebook with a few defaults. """ |
sns.set(context = "paper", font = "monospace")
warnings.filterwarnings("ignore")
pd.set_option("display.max_rows", 500)
pd.set_option("display.max_columns", 500)
plt.rcParams["figure.figsize"] = (17, 10) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_size( self, size = None ):
""" This function removes the least frequent elements until the size constraint is met. """ |
if size is None:
size = self.size_constraint
while sys.getsizeof(self) > size:
element_frequencies = collections.Counter(self)
infrequent_element = element_frequencies.most_common()[-1:][0][0]
self.remove(infrequent_element) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def logger_initial_config(service_name=None,
log_level=None,
logger_format=None,
logger_date_format=None):
'''Set initial logging configurations.
:param service_name: Name of the service
:type logger: String
:param log_level... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def access_log_middleware(app, handler):
"""Log each request in structured event log.""" |
event_log = app.get('smartmob.event_log') or structlog.get_logger()
clock = app.get('smartmob.clock') or timeit.default_timer
# Keep the request arrival time to ensure we get intuitive logging of
# events.
arrival_time = datetime.utcnow().replace(tzinfo=timezone.utc)
async def access_log(req... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge(profile, head, base, commit_message=None):
"""Merge the head of a branch into the base branch. Args: profile A profile generated from ``simplygithub.au... |
if not commit_message:
commit_message = "Merged " + head + " into " + base + "."
payload = {
"base": base,
"head": head,
"commit_message": commit_message,
}
response = api.post_merge_request(profile, payload)
data = None
if response.status_code == 201:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_netloc(scheme, netloc):
"""Parse netloc string.""" |
auth, _netloc = netloc.split('@')
sender, token = auth.split(':')
if ':' in _netloc:
domain, port = _netloc.split(':')
port = int(port)
else:
domain = _netloc
if scheme == 'https':
port = 443
else:
port = 80
return dict(sender=sender, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_path(path):
"""Parse path string.""" |
version, project = path[1:].split('/')
return dict(version=int(version), project=project) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_dsn(dsn):
"""Parse dsn string.""" |
parsed_dsn = urlparse(dsn)
parsed_path = parse_path(parsed_dsn.path)
return {
'scheme': parsed_dsn.scheme,
'sender': parsed_dsn.username,
'token': parsed_dsn.password,
'domain': parsed_dsn.hostname,
'port': parsed_dsn.port or 80,
'version': parsed_path.get('v... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def create_from_binary(cls, ignore_signature_check, binary_view):
'''Creates a new object MFTHeader from a binary stream. The binary
stream can be represented by a byte string, bytearray or a memoryview of the
bytearray.
Args:
binary_view (memoryview of bytearray) - A binary... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _get_dataruns(self):
'''Returns a list of dataruns, in order.
'''
if self._data_runs is None:
raise DataStreamError("Resident datastream don't have dataruns")
if not self._data_runs_sorted:
self._data_runs.sort(key=_itemgetter(0))
self._data_runs_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def add_data_attribute(self, data_attr):
'''Interprets a DATA attribute and add it to the datastream.'''
if data_attr.header.attr_type_id is not AttrTypes.DATA:
raise DataStreamError("Invalid attribute. A Datastream deals only with DATA attributes")
if data_attr.header.attr_name != s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def add_from_datastream(self, source_ds):
'''Add information from another datastream. Verifies if the datastream
added is correct and copy the relevant fields if necessary.'''
if source_ds.name != self.name:
raise DataStreamError("Data from a different stream 'f{source_ds.name}' cann... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def create_from_binary(cls, mft_config, binary_data, entry_number):
#TODO test carefully how to find the correct index entry, specially with NTFS versions < 3
'''Creates a MFTEntry from a binary stream. It correctly process
the binary data extracting the MFTHeader, all the attributes and the
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_datastream(self, name):
"""Find and return if a datastream exists, by name.""" |
for stream in self.data_streams: #search to see if this is a new datastream or a known one
if stream.name == name:
return stream
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_data_attribute(self, data_attr):
"""Add a data attribute to the datastream structure. Data attributes require processing before they can be interpreted ... |
attr_name = data_attr.header.attr_name
stream = self._find_datastream(attr_name)
if stream is None:
stream = Datastream(attr_name)
self.data_streams.append(stream)
stream.add_data_attribute(data_attr) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _load_attributes(self, mft_config, attrs_view):
'''Loads all the attributes of an entry.
Once executed, all the attributes should have been loaded in the
attribute *attrs* instance attribute.
Args:
mft_config (:obj:`MFTConfig`) - An instance of MFTConfig, as this tells
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def merge_entries(self, source_entry):
'''Merge two entries.
Allow the merging of two MFTEntries copying the attributes to the correct
place and the datastreams.
Args:
source_entry (:obj:`MFTEntry`) - Source entry where the data will be
copied from
'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_datastream_names(self):
'''Returns a set with the datastream names. If there is no datastream,
returns None
'''
ads_names = set()
for stream in self.data_streams:
ads_names.add(stream.name)
if len(ads_names):
return ads_names
else... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_main_filename_attr(self):
'''Returns the main filename attribute of the entry.
As an entry can have multiple FILENAME attributes, this function allows
to return the main one, i.e., the one with the lowest attribute id and
the "biggest" namespace.
'''
fn_attrs = s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_relationship_info(self):
"""Maps parent and child entries in the MFT. Because the library expects the MFT file to be provided, it doesn't have access t... |
mft_entry_size = self.mft_entry_size
fp = self.file_pointer
record_n = 0
#define the minimum amount that needs to be read
base_struct = struct.Struct("<Q")
base_struct_offset = 32
seq_struct = struct.Struct("<H")
seq_struct_offset = 16
buffer_bas... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _compute_full_path(self, fn_parent_ref, fn_parent_seq):
'''Based on the parent reference and sequence, computes the full path.
The majority of the files in a filesystem has a very small amount of
parent directories. By definition, a filesystem is expected to have
much smaller amount... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_full_path(self, fn_attr):
'''Returns the full path of a FILENAME.
The NTFS filesystem allows for things called hardlinks. Hard links are
saved, internally, as different filename attributes. Because of this,
an entry can, when dealing with full paths, have multiple full paths.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setFullscreen(self, fullscreen):
"""toggle between fullscreen and normal window""" |
if not fullscreen:
self.ckBox_fullscreen.setChecked(False)
self.parent().showNormal()
else:
self.ckBox_fullscreen.setChecked(True)
self.parent().showFullScreen() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match(self, string):
"""Match a string against the template. If the string matches the template, return a dict mapping template parameter names to converted ... |
m = self.regex.match(string)
if m:
c = self.type_converters
return dict((k, c[k](v) if k in c else v)
for k, v in m.groupdict().iteritems())
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def job(func_or_queue, connection=None, *args, **kwargs):
"""This decorator does all what django_rq's one, plus it group all logged messages using uuid and sets ... |
decorated_func = _job(func_or_queue, connection=connection, *args, **kwargs)
if callable(func_or_queue):
@wraps(decorated_func)
def wrapper(*args, **kwargs):
with log.fields(uuid=uuid.uuid4(),
job_name=decorated_func.__name__):
return dec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def active(parser, token):
""" tag to determine if a link is to the current page, and if it is, sets 'link_active' to True in the context. Use: {% active path vi... |
args = token.split_contents()
path = args[1]
view = args[2].replace('"', '').replace("'", '')
strict = args[3].replace('"', '').replace("'", '')
arg1 = None; arg2 = None; arg3 = None
if len(args) > 4:
arg1 = args[4]
if len(args) > 5:
arg2 = args[5]
if len(args) > 6:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.