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 write_queryset_to_csv(qs, filename):
"""Write a QuerySet or ValuesListQuerySet to a CSV file based on djangosnippets by zbyte64 and http://palewi.re Argument... |
model = qs.model
with open(filename, 'w') as fp:
writer = csv.writer(fp)
try:
headers = list(qs._fields)
except:
headers = [field.name for field in model._meta.fields]
writer.writerow(headers)
for obj in qs:
row = []
for c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_date(dt, date_parser=parse_date):
"""Coerce a datetime or string into datetime.date object Arguments: dt (str or datetime.datetime or atetime.time or nu... |
if not dt:
return datetime.date(1970, 1, 1)
if isinstance(dt, basestring):
dt = date_parser(dt)
try:
dt = dt.timetuple()[:3]
except:
dt = tuple(dt)[:3]
return datetime.date(*dt) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_time(dt, date_parser=parse_date):
"""Ignore date information in a datetime string or object Arguments: dt (str or datetime.datetime or atetime.time or n... |
if not dt:
return datetime.time(0, 0)
if isinstance(dt, basestring):
try:
dt = date_parser(dt)
except:
print 'Unable to parse {0}'.format(repr(dt))
print_exc()
return datetime.time(0, 0)
try:
dt = dt.timetuple()[3:6]
except... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten_excel(path='.', ext='xlsx', sheetname=0, skiprows=None, header=0, date_parser=parse_date, verbosity=0, output_ext=None):
"""Load all Excel files in t... |
date_parser = date_parser or (lambda x: x)
dotted_ext, dotted_output_ext = None, None
if ext != None and output_ext != None:
dotted_ext = ('' if ext.startswith('.') else '.') + ext
dotted_output_ext = ('' if output_ext.startswith('.') else '.') + output_ext
table = {}
for file_prop... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hash_model_values(model, clear=True, hash_field='values_hash', hash_fun=hash, ignore_pk=True, ignore_fields=[]):
"""Hash values of DB table records to facili... |
qs = getattr(model, 'objects', model)
model = qs.model
if ignore_pk:
ignore_fields += [model._meta.pk.name]
if not hasattr(model, hash_field):
warnings.warn("%r doesn't have a field named %s in which to store a hash value. Skipping." % (model, hash_field))
return
for obj 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 bulk_update(object_list, ignore_errors=False, delete_first=False, verbosity=0):
'''Bulk_create objects in provided list of model instances, delete database rows for the original pks in the object list.
Returns any delta in the number of rows in the database table that resulted from the update.
If nonze... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_queryset_batches(queryset, batch_len=1000, verbosity=1):
"""Filter a queryset by the pk in such a way that no batch is larger than the requested bat... |
if batch_len == 1:
for obj in queryset:
yield obj
N = queryset.count()
if not N:
raise StopIteration("Queryset is empty!")
if N == 1:
for obj in queryset:
yield obj
if verbosity > 0:
widgets = [pb.Counter(), '/%d rows: ' % N, pb.Percentag... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def optimize_filter_dict(filter_dict, trgm=True):
"""Improve query speed for a Django queryset `filter` or `exclude` kwargs dict WARNING: Wtthout `trgm`, this on... |
optimized = {}
for k, v in filter_dict.iteritems():
if k.endswith('__in'):
v = set(v)
if len(v) == 1:
optimized[k[:-4]] = tuple(v)[0]
else:
optimized[k] = v
else:
optimized[k] = v
# This is the only optimization... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump_json(model, batch_len=200000, use_natural_keys=True, verbosity=1):
"""Dump database records to .json Django fixture file, one file for each batch of `ba... |
model = get_model(model)
N = model.objects.count()
if verbosity > 0:
widgets = [pb.Counter(), '/%d rows: ' % (N,), pb.Percentage(), ' ', pb.RotatingMarker(), ' ', pb.Bar(),' ', pb.ETA()]
i, pbar = 0, pb.ProgressBar(widgets=widgets, maxval=N).start()
JSONSerializer = serializers.get_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 filter_exclude_dicts(filter_dict=None, exclude_dict=None, name='acctno', values=[], swap=False):
"""Produces kwargs dicts for Django Queryset `filter` and `e... |
filter_dict = filter_dict or {}
exclude_dict = exclude_dict or {}
if not name.endswith('__in'):
name += '__in'
filter_dict[name], exclude_dict[name] = [], []
for v in values:
# "NOT " means switch from include (filter) to exclude for that one account number
if v.startswith... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_kwargs(self, kwargs, prefix='default_', delete=True):
""" set self attributes based on kwargs, optionally deleting kwargs that are processed """ |
processed = []
for k in kwargs:
if hasattr(self, prefix + k):
processed += [k]
setattr(self, prefix + k, kwargs[k])
for k in processed:
del(kwargs[k])
return kwargs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_column_wise_lists(self, transpose=False):
"""Generator over the columns of lists""" |
# make this a generator of generators?
if transpose:
ans = self.from_row_wise_lists(self.as_column_wise_lists(transpose=False))
return ans
#print self
return self.values() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def randint(self, a: int, b: int, n: Optional[int] = None) -> Union[List[int], int]: """ Generate n numbers as a list or a single one if no n is given. n is used ... |
max_n = self.config.MAX_NUMBER_OF_INTEGERS
return self._generate_randoms(self._request_randints, max_n=max_n, a=a, b=b, n=n) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_quota(self):
""" If IP can't make requests, raise BitQuotaExceeded. Called before generating numbers. """ |
self._request_remaining_quota_if_unset()
if self.quota_estimate < self.quota_limit:
raise BitQuotaExceeded(self.quota_estimate) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _construct_timeseries(self, timeseries, constraints={}):
""" wraps response_from for timeseries calls, returns the resulting dict """ |
self.response_from(timeseries, constraints)
if self.response == None:
return None
return {'data':self.response['data'],
'period':self.response['period'],
'start time':datetime.datetime.fromtimestamp(self.response['start_time']),
'end t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def edit_channel_info(self, new_ch_name, ch_dct):
"""Parent widget calls this whenever the user edits channel info. """ |
self.ch_name = new_ch_name
self.dct = ch_dct
if ch_dct['type'] == 'analog':
fmter = fmt.green
else:
fmter = fmt.blue
self.ch_name_label.setText(fmt.b(fmter(self.ch_name)))
self.generateToolTip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connections(request, edges):
""" Plot a force-directed graph based on the edges provided """ |
edge_list, node_list = parse.graph_definition(edges)
data = {'nodes': json.dumps(node_list), 'edges': json.dumps(edge_list)}
return render_to_response('miner/connections.html', 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 csv_response_from_context(context=None, filename=None, field_names=None, null_string='', eval_python=True):
"""Generate the response for a Download CSV butto... |
filename = filename or context.get('filename') or 'table_download.csv'
field_names = field_names or context.get('field_names', [])
# FIXME: too slow!
if field_names and all(field_names) and all(all(c in (string.letters + string.digits + '_.') for c in s) for s in field_names):
eval_python=False... |
<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_to_response(self, context, indent=None):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context, indent=indent)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def report(self, reporter, ignore_nfd=False, ignore_ws=False):
""" Adds the problems that have been found so far to the given Reporter instance. The two ke... |
if self.strip_errors and not ignore_ws:
reporter.add(self.strip_errors, 'leading or trailing whitespace')
if self.norm_errors and not ignore_nfd:
reporter.add(self.norm_errors, 'not in Unicode NFD') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
""" The main loop for the logger process. Will receive remote processes orders one by one and wait for the next one. Then return from this method ... |
# Initialize the file logger
self.log = getLogger()
# Deserialize configuration
self.set_config_command = dill.loads(self.set_config_command)
self.set_configuration(self.set_config_command)
for handler in self.file_handlers:
if isinstance(handler, StreamHan... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def redraw(self):
""" Clears the console and performs a complete redraw of all progress bars and then awaiting logger messages if the minimum time elapsed since ... |
# Check if the refresh time lapse has elapsed and if a change requires to redraw
lapse_since_last_refresh = millis() - self.refresh_timer
if not lapse_since_last_refresh > self.redraw_frequency_millis or not self.changes_made:
return
# If yes, then reset change indicator an... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetServices(self,filename):
"""Returns a list of service objects handling this file type""" |
objlist=[]
for sobj in self.services:
if sobj.KnowsFile(filename) :
objlist.append(sobj)
if len(objlist)==0:
return None
return objlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetServiceObj(self,servicename):
"""Given a service name string, returns the object that corresponds to the service""" |
for sobj in self.services:
if sobj.GetName().lower()==servicename.lower():
return sobj
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 object_path(collection, id):
"""Returns path to the backing file of the object with the given ``id`` in the given ``collection``. Note that the ``id`` is mad... |
_logger.debug(type(id))
_logger.debug(id)
if isinstance(id, dict) and 'id' in id:
id = id['id']
normalized_id = normalize_text(str(id), lcase=False)
return os.path.join(_basepath, collection,
'%s.%s' % (normalized_id, _ext)) |
<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_object_at_path(path):
"""Load an object from disk at explicit path""" |
with open(path, 'r') as f:
data = _deserialize(f.read())
return aadict(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 add_collection(collection, cache_size=1000, cache_cls=LRUCache, **cache_args):
"""Add a collection named ``collection``.""" |
assert collection not in _db
cache = cache_cls(maxsize=cache_size,
missing=lambda id: load_object(collection, id),
**cache_args)
_db[collection] = aadict(cache=cache, indexes={}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare(base_path='data', serialize=json.dumps, deserialize=json.loads, file_ext='json'):
"""After you have added your collections, prepare the database for ... |
global _basepath, _deserialize, _serialize, _ext
_basepath = base_path
assert callable(serialize)
assert callable(deserialize)
_serialize = serialize
_deserialize = deserialize
_ext = file_ext
_logger.debug('preparing with base path %s and file ext %s',
_basepath, _ext)
asse... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def each_object(collection):
"""Yields each object in the given ``collection``. The objects are loaded from cache and failing that, from disk.""" |
c_path = collection_path(collection)
paths = glob('%s/*.%s' % (c_path, _ext))
for path in paths:
yield load_object_at_path(path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def each_object_id(collection):
"""Yields each object ID in the given ``collection``. The objects are not loaded.""" |
c_path = collection_path(collection)
paths = glob('%s/*.%s' % (c_path, _ext))
for path in paths:
match = regex.match(r'.+/(.+)\.%s$' % _ext, path)
yield match.groups()[0] |
<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_object(collection, obj):
"""Save an object ``obj`` to the given ``collection``. ``obj.id`` must be unique across all other existing objects in the given... |
if 'id' not in obj:
obj.id = uuid()
id = obj.id
path = object_path(collection, id)
temp_path = '%s.temp' % path
with open(temp_path, 'w') as f:
data = _serialize(obj)
f.write(data)
shutil.move(temp_path, path)
if id in _db[collection].cache:
_db[collection].c... |
<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_index(collection, name, fields, transformer=None, unique=False, case_insensitive=False):
""" Add a secondary index for a collection ``collection`` on one... |
assert len(name) > 0
assert len(fields) > 0
indexes = _db[collection].indexes
index = indexes.setdefault(name, aadict())
index.transformer = transformer
index.value_map = {} # json([value]) => set(object_id)
index.unique = unique
index.case_insensitive = case_insensitive
index.fiel... |
<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_to_index(index, obj):
"""Adds the given object ``obj`` to the given ``index``""" |
id_set = index.value_map.setdefault(indexed_value(index, obj), set())
if index.unique:
if len(id_set) > 0:
raise UniqueConstraintError()
id_set.add(obj.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 _remove_from_index(index, obj):
"""Removes object ``obj`` from the ``index``.""" |
try:
index.value_map[indexed_value(index, obj)].remove(obj.id)
except KeyError:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def each_indexed_object(collection, index_name, **where):
"""Yields each object indexed by the index with name ``name`` with ``values`` matching on indexed field... |
index = _db[collection].indexes[index_name]
for id in index.value_map.get(indexed_value(index, where), []):
yield get_object(collection, 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 _update_indexes_for_mutated_object(collection, obj):
"""If an object is updated, this will simply remove it and re-add it to the indexes defined on the colle... |
for index in _db[collection].indexes.values():
_remove_from_index(index, obj)
_add_to_index(index, obj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_indexes_for_deleted_object(collection, obj):
"""If an object is deleted, it should no longer be indexed so this removes the object from all indexes o... |
for index in _db[collection].indexes.values():
_remove_from_index(index, obj) |
<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_delta(__string: str) -> datetime.timedelta: """Parse ISO-8601 duration string. Args: __string: Duration string to parse Returns: Parsed delta object """ |
if not __string:
return datetime.timedelta(0)
match = re.fullmatch(r"""
P
((?P<days>\d+)D)?
T?
((?P<hours>\d{1,2})H)?
((?P<minutes>\d{1,2})M)?
((?P<seconds>\d{1,2})?((?:\.(?P<microseconds>\d+))?S)?)
""", __string, re.VERBOSE)
if not match:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_delta(__timedelta: datetime.timedelta) -> str: """Format ISO-8601 duration string. Args: __timedelta: Duration to process Returns: ISO-8601 representat... |
if __timedelta == datetime.timedelta(0):
return ''
days_s = '{}D'.format(__timedelta.days) if __timedelta.days else ''
hours, minutes = divmod(__timedelta.seconds, 3600)
minutes, seconds = divmod(minutes, 60)
hours_s = '{:02d}H'.format(hours) if hours else ''
minutes_s = '{:02d}M'.forma... |
<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_datetime(__string: str) -> datetime.datetime: """Parse ISO-8601 datetime string. Args: __string: Datetime string to parse Returns: Parsed datetime objec... |
if not __string:
datetime_ = datetime.datetime.now(datetime.timezone.utc)
else:
# pylint: disable=no-member
datetime_ = ciso8601.parse_datetime(__string)
if datetime_.tzinfo is None:
datetime_ = datetime_.replace(tzinfo=datetime.timezone.utc)
return datetime_ |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_device_info(dev_name):
"""Prints information about the given device. Usage: print_device_info("Dev1") """ |
string_buffer = ctypes.create_string_buffer(1024)
attributes = [pydaq.DAQmx_Dev_ProductType, pydaq.DAQmx_Dev_SerialNum,
pydaq.DAQmx_Dev_AO_PhysicalChans,
pydaq.DAQmx_Dev_CI_PhysicalChans,
pydaq.DAQmx_Dev_CO_PhysicalChans,
pydaq.DAQmx_Dev_D... |
<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_device_name_list():
"""Returns a list of device names installed.""" |
dev_names = ctypes.create_string_buffer(1024)
pydaq.DAQmxGetSysDevNames(dev_names, len(dev_names))
return dev_names.value.split(', ') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset_analog_sample_clock(state=False):
"""Reset the clock line. Use this just before starting a run to avoid timing issues. """ |
set_digital_line_state(expt_settings.dev1_clock_out_name, state)
set_digital_line_state(expt_settings.dev2_clock_out_name, state)
set_digital_line_state(expt_settings.dev3_clock_out_name, state)
set_digital_line_state(expt_settings.dev4_clock_out_name, state) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_digital_line_state(line_name, state):
"""Set the state of a single digital line. line_name (str) - The physical name of the line. e.g line_name="Dev1/por... |
# get the line number from the line name. Thats the number of bits to shift
bits_to_shift = int(line_name.split('line')[-1])
dig_data = np.ones(2, dtype="uint32")*bool(state)*(2**bits_to_shift)
# Note here that the number of samples written here are 2, which is the
# minimum required for a buffered... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def StartAndWait(self):
"""Starts the task and waits until it is done.""" |
self.StartTask()
self.WaitUntilTaskDone(pydaq.DAQmx_Val_WaitInfinitely)
self.ClearTask() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isDone(self):
"""Returns true if task is done.""" |
done = pydaq.bool32()
self.IsTaskDone(ctypes.byref(done))
return done.value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def padDigitalData(self, dig_data, n):
"""Pad dig_data with its last element so that the new array is a multiple of n. """ |
n = int(n)
l0 = len(dig_data)
if l0 % n == 0:
return dig_data # no need of padding
else:
ladd = n - (l0 % n)
dig_data_add = np.zeros(ladd, dtype="uint32")
dig_data_add.fill(dig_data[-1])
return np.concatenate((dig_data, dig_da... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def EveryNCallback(self):
"""Called by PyDAQmx whenever a callback event occurs.""" |
# print('ncall ', self.n_callbacks)
if self.do_callbacks:
if self.n_callbacks >= self.callback_step:
# print('n_callbacks', self.n_callbacks)
for func, func_dict in self.callback_funcs:
func(func_dict)
print('func:::', ... |
<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_vads_trans_id(vads_site_id, vads_trans_date):
""" Returns a default value for vads_trans_id field. vads_trans_id field is mandatory. It is composed by 6 ... |
vads_trans_id = ""
for i in range(0, 6):
vads_trans_id += str(random.randint(0, 9))
return vads_trans_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_signature(payment_request):
""" Returns the signature for the transaction. To compute the signature, first you have to get the value of all the fields th... |
vads_args = {}
for field in payment_request._meta.fields:
if field.name[:5] == 'vads_':
field_value = field.value_from_object(payment_request)
if field_value:
vads_args.update({
field.name: field_value
})
base_str = ''
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_response(data):
"""Process a payment response.""" |
# We check if the signature is valid. If not return
if not is_signature_valid(data):
logger.warning(
"Django-Payzen : Response signature detected as invalid",
extra={"stack": True}
)
return None
from . import forms
from . import models
# The signatu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply(self):
"""Create substitution nodes for hyperlinks""" |
# In this phase, we look for hyperlinks (references nodes)
# that contain substitutions (of the form "|foo|").
# We then add actual "substitution"s nodes to those references,
# so that they can be replaced by the substitution processor.
subst_re = re.compile(self.subst_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 apply(self):
"""Replace substitutions in hyperlinks with their contents""" |
# In this phase, we replace the substitutions in hyperlinks
# with the contents of the sub-nodes introduced during phase 1.
# We also remove those temporary nodes from the tree.
subst_re = re.compile(self.subst_pattern)
# Apply the substitutions to hyperlink references.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def set_global_config(path_dict_or_stream):
'''Set the global configuration.
Call this from `main()` with a file system path, stream
object, or a dict. Calling it repeatedly with the same path is
safe. Calling it with a different path or repeatedly with a
stream or dict requires an explicit call ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _temporary_config():
'''Temporarily replace the global configuration.
Use this in a 'with' statement. The inner block may freely manipulate
the global configuration; the original global configuration is restored
at exit.
>>> with yakonfig.yakonfig._temporary_config():
... yakonfig.yakon... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def include_yaml(self, node):
'''
load another yaml file from the path specified by node's value
'''
filename = self.construct_scalar(node)
if not filename.startswith('/'):
if self._root is None:
raise Exception('!include_yaml %s is a relative path, '
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def paystealth(stealthaddr,ephempriv=None,_doctest_nonce=-1):
'''
Input a stealth address, and optionally an ephemeral private key,
and generate a payment pubkey and stealth OP_RETURN data.
(The OP_RETURN data is just a nonce and the ephemeral public key.)
Works with standard single spend key stea... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def receivestealth(scanpriv,spendpriv,ephempub):
'''
Derive the private key for a stealth payment, using the scan and
spend private keys, and the ephemeral public key.
Input private keys should be 64-char hex strings, and ephemeral
public key should be a 66-char hex compressed public key.
>>> ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def proxy(request):
"""Pass an HTTP request on to another server.""" |
# TODO: don't hardcode http
uri = "http://" + HOST + request.META['PATH_INFO']
if request.META['QUERY_STRING']:
uri += '?' + request.META['QUERY_STRING']
headers = {}
for name, val in six.iteritems(request.environ):
if name.startswith('HTTP_'):
name = header_name(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 tabulate(data, header=True, headers=None, accessors=None, **table_options):
""" Shortcut function to produce tabular output of data without the need to creat... |
if header and not headers:
data = iter(data)
try:
headers = next(data)
except StopIteration:
pass
if headers and hasattr(headers, 'items') and accessors is None:
# Dict mode; Build accessors and headers from keys of data.
data = itertools.chain([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 render_filter(self, next_filter):
""" Produce formatted output from the raw data stream. """ |
next(next_filter)
while True:
data = (yield)
res = [self.cell_format(access(data)) for access in self.accessors]
next_filter.send(res) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def viewable_width(self):
""" The available combined character width when all padding is removed. """ |
return sum(self.widths) + sum(x['padding'] for x in self.colspec) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_row(self, row, rstrip=True):
""" Format and print the pre-rendered data to the output device. """ |
line = ''.join(map(str, row))
print(line.rstrip() if rstrip else line, file=self.table.file) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_fullwidth(self, value):
""" Return a full width column. Note that the padding is inherited from the first cell which inherits from column_padding. """ |
assert isinstance(value, VTMLBuffer)
pad = self.colspec[0]['padding']
fmt = self.make_formatter(self.width - pad, pad,
self.table.title_align)
return VTMLBuffer('\n').join(fmt(value)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_formatter(self, width, padding, alignment, overflow=None):
""" Create formatter function that factors the width and alignment settings. """ |
if overflow is None:
overflow = self.overflow_default
if overflow == 'clip':
overflower = lambda x: [x.clip(width, self.table.cliptext)]
elif overflow == 'wrap':
overflower = lambda x: x.wrap(width)
elif overflow == 'preformatted':
overflo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_formatters(self):
""" Create a list formatter functions for each column. They can then be stored in the render spec for faster justification processing.... |
return [self.make_formatter(inner_w, spec['padding'], spec['align'],
spec['overflow'])
for spec, inner_w in zip(self.colspec, self.widths)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _uniform_dist(self, spread, total):
""" Produce a uniform distribution of `total` across a list of `spread` size. The result is non-random and uniform. """ |
fraction, fixed_increment = math.modf(total / spread)
fixed_increment = int(fixed_increment)
balance = 0
dist = []
for _ in range(spread):
balance += fraction
withdrawl = 1 if balance > 0.5 else 0
if withdrawl:
balance -= withd... |
<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_filters(self):
""" Coroutine based filters for render pipeline. """ |
return [
self.compute_style_filter,
self.render_filter,
self.calc_widths_filter,
self.format_row_filter,
self.align_rows_filter,
] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_row_filter(self, next_filter):
""" Apply overflow, justification, padding and expansion to a row. """ |
next(next_filter)
while True:
items = (yield)
assert all(isinstance(x, VTMLBuffer) for x in items)
raw = (fn(x) for x, fn in zip(items, self.formatters))
for x in itertools.zip_longest(*raw):
next_filter.send(x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def width_normalize(self, width):
""" Handle a width style, which can be a fractional number representing a percentage of available width or positive integers wh... |
if width is not None:
if width > 0 and width < 1:
return int(width * self.usable_width)
else:
return int(width) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_widths_filter(self, next_filter):
""" Coroutine to analyze the incoming data stream for creating optimal column width choices. This may buffer some of t... |
window_sent = not not self.data_window
next_primed = False
genexit = None
if not self.data_window:
start = time.monotonic()
while len(self.data_window) < self.min_render_prefill or \
(len(self.data_window) < self.max_render_prefill and
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_flex(self, data, max_width, cols, preformatted=None):
""" Scan data returning the best width for each column given the max_width constraint. If some col... |
if preformatted is None:
preformatted = []
colstats = []
for i in cols:
lengths = [len(xx) for x in data
for xx in x[i].text().splitlines()]
if self.headers:
lengths.append(len(self.headers[i]))
lengths.appen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def adjust_widths(self, max_width, colstats):
""" Adjust column widths based on the least negative affect it will have on the viewing experience. We take note of... |
adj_colstats = []
for x in colstats:
if not x['preformatted']:
adj_colstats.append(x)
else:
max_width -= x['offt']
next_score = lambda x: (x['counts'][x['offt']] + x['chop_mass'] +
x['chop_count']) / x['tota... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_key(self, value):
""" Make camelCase variant of value. """ |
if value:
parts = [self.key_filter.sub('', x)
for x in self.key_split.split(value.lower())]
key = parts[0] + ''.join(map(str.capitalize, parts[1:]))
else:
key = ''
if key in self.seen_keys:
i = 1
while '%s%d' % (ke... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_type_validator(value_type):
"""Build a validator that only checks the type of a value.""" |
def type_validator(data):
"""Validate instances of a particular type."""
if isinstance(data, value_type):
return data
raise NotValid('%r is not of type %r' % (data, value_type))
return type_validator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_static_validator(exact_value):
"""Build a validator that checks if the data is equal to an exact value.""" |
def static_validator(data):
"""Validate by equality."""
if data == exact_value:
return data
raise NotValid('%r is not equal to %r' % (data, exact_value))
return static_validator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_iterable_validator(iterable):
"""Build a validator from an iterable.""" |
sub_schemas = [parse_schema(s) for s in iterable]
def item_validator(value):
"""Validate items in an iterable."""
for sub in sub_schemas:
try:
return sub(value)
except NotValid:
pass
raise NotValid('%r invalidated by anything 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 _determine_keys(dictionary):
"""Determine the different kinds of keys.""" |
optional = {}
defaults = {}
mandatory = {}
types = {}
for key, value in dictionary.items():
if isinstance(key, Optional):
optional[key.value] = parse_schema(value)
if isinstance(value, BaseSchema) and\
value.default is not UNSPECIFIED:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_mandatory_keys(mandatory, validated, data, to_validate):
"""Validate the manditory keys.""" |
errors = []
for key, sub_schema in mandatory.items():
if key not in data:
errors.append('missing key: %r' % (key,))
continue
try:
validated[key] = sub_schema(data[key])
except NotValid as ex:
errors.extend(['%r: %s' % (key, arg) for arg 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 _validate_optional_key(key, missing, value, validated, optional):
"""Validate an optional key.""" |
try:
validated[key] = optional[key](value)
except NotValid as ex:
return ['%r: %s' % (key, arg) for arg in ex.args]
if key in missing:
missing.remove(key)
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_type_key(key, value, types, validated):
"""Validate a key's value by type.""" |
for key_schema, value_schema in types.items():
if not isinstance(key, key_schema):
continue
try:
validated[key] = value_schema(value)
except NotValid:
continue
else:
return []
return ['%r: %r not matched' % (key, value)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_other_keys(optional, types, missing, validated, data, to_validate):
"""Validate the rest of the keys present in the data.""" |
errors = []
for key in to_validate:
value = data[key]
if key in optional:
errors.extend(
_validate_optional_key(
key, missing, value, validated, optional))
continue
errors.extend(_validate_type_key(key, value, types, validated)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_dict_validator(dictionary):
"""Build a validator from a dictionary.""" |
mandatory, optional, types, defaults = _determine_keys(dictionary)
def dict_validator(data):
"""Validate dictionaries."""
missing = list(defaults.keys())
if not isinstance(data, dict):
raise NotValid('%r is not of type dict' % (data,))
validated = {}
to_val... |
<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_schema(schema):
"""Parse a val schema definition.""" |
if isinstance(schema, BaseSchema):
return schema.validate
if type(schema) is type:
return _build_type_validator(schema)
if isinstance(schema, dict):
return _build_dict_validator(schema)
if type(schema) in (list, tuple, set):
return _build_iterable_validator(schema)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate(self, data):
"""Validate data. Raise NotValid error for invalid data.""" |
validated = self._validated(data)
errors = []
for validator in self.additional_validators:
if not validator(validated):
errors.append(
"%s invalidated by '%s'" % (
validated, _get_repr(validator)))
if errors:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validated(self, data):
"""Validate data if any subschema validates it.""" |
errors = []
for sub in self.schemas:
try:
return sub(data)
except NotValid as ex:
errors.extend(ex.args)
raise NotValid(' and '.join(errors)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validated(self, data):
"""Validate data if all subschemas validate it.""" |
for sub in self.schemas:
data = sub(data)
return 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 _validated(self, data):
"""Convert data or die trying.""" |
try:
return self.convert(data)
except (TypeError, ValueError) as ex:
raise NotValid(*ex.args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validated(self, values):
"""Validate if the values are validated one by one in order.""" |
if self.length != len(values):
raise NotValid(
"%r does not have exactly %d values. (Got %d.)" % (
values, self.length, len(values)))
return type(self.schemas)(
self.schemas[i].validate(v) for i, v in enumerate(values)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _connectToFB(self):
"""Establish the actual TCP connection to FB""" |
if self.connected_to_fb:
logger.debug("Already connected to fb")
return True
logger.debug("Connecting to fb")
token = facebook_login.get_fb_token()
try:
self.fb = facebook.GraphAPI(token)
except:
print("Couldn't connect to fb")... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def KnowsFile(self,filename):
"""Looks at extension and decides if it knows how to manage this file""" |
if self._isMediaFile(filename) or self._isConfigFile(filename):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Remove(self,directory,filename):
"""Deletes files from fb""" |
if self._isMediaFile(filename):
return self._remove_media(directory,filename)
elif self._isConfigFile(filename):
return True
print "Not handled!"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_config(self,directory,filename):
"""Manages FB config files""" |
basefilename=os.path.splitext(filename)[0]
ext=os.path.splitext(filename)[1].lower()
#if filename==LOCATION_FILE:
#return self._update_config_location(directory)
#FIXME
#elif filename==TAG_FILE:
#return self._update_config_tags(directory)
if filen... |
<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_title(self,directory,filename):
"""Loads image title if any""" |
# =========== LOAD TITLE ========
fullfile=os.path.join(directory,filename+'.title')
try:
logger.debug('trying to open [%s]'%(fullfile))
_title=(open(fullfile).readline().strip())
logger.debug("_updatemeta: %s - title is '%s'",filename,_title)
except:... |
<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_megapixels(self,directory):
"""Opens megapixel file, if contains '3.5' for instance, will scale all uploaded photos in directory this this size, the or... |
#FIXME: should check if DB tracking file before using it
fullfile=os.path.join(directory,MEGAPIXEL_FILE)
try:
mp=float(open(fullfile).readline())
logger.debug("_load_megapixel: MP from file is %f",mp)
except:
logger.warning("Couldn't open image size ... |
<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_sets(self,directory):
"""Loads sets from set file and return as list of strings """ |
# --- Read sets out of file
_sets=[]
try:
fullfile=os.path.join(directory,SET_FILE)
lsets=open(fullfile).readline().split(',')
for tag in lsets:
_sets.append(tag.strip())
except:
logger.error("No sets found in %s, FB needs ... |
<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_album(self,directory):
""" Loads set name from SET_FILE, looks up album_id on fb, it it doesn't exists, creates album. Returns album id and album name "... |
if not self._connectToFB():
print("%s - Couldn't connect to fb"%(directory))
return None,None
# Load sets from SET_FILE
_sets=self._load_sets(directory)
# Only grab the first set, FB supports only one set per photo
myset=_sets[0]
logger.debug(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getphoto_originalsize(self,pid):
"""Asks fb for photo original size returns tuple with width,height """ |
logger.debug('%s - Getting original size from fb'%(pid))
i=self.fb.get_object(pid)
width=i['images'][0]['width']
height=i['images'][0]['height']
return (width,height) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getphoto_location(self,pid):
"""Asks fb for photo location information returns tuple with lat,lon,accuracy """ |
logger.debug('%s - Getting location from fb'%(pid))
lat=None
lon=None
accuracy=None
resp=self.fb.photos_geo_getLocation(photo_id=pid)
if resp.attrib['stat']!='ok':
logger.error("%s - fb: photos_geo_getLocation failed with status: %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 _remove_media(self,directory,files=None):
"""Removes specified files from fb""" |
# Connect if we aren't already
if not self._connectToFB():
logger.error("%s - Couldn't connect to fb")
return False
db=self._loadDB(directory)
# If no files given, use files from DB in dir
if not files:
files=db.keys()
#If only one f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.