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 move_down(self): """Make the drone decent downwards."""
self.at(ardrone.at.pcmd, True, 0, 0, -self.speed, 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 move_forward(self): """Make the drone move forward."""
self.at(ardrone.at.pcmd, True, 0, -self.speed, 0, 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 move_backward(self): """Make the drone move backwards."""
self.at(ardrone.at.pcmd, True, 0, self.speed, 0, 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 turn_left(self): """Make the drone rotate left."""
self.at(ardrone.at.pcmd, True, 0, 0, 0, -self.speed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def turn_right(self): """Make the drone rotate right."""
self.at(ardrone.at.pcmd, True, 0, 0, 0, self.speed)
<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(self): """Toggle the drone's emergency state."""
self.at(ardrone.at.ref, False, True) time.sleep(0.1) self.at(ardrone.at.ref, False, 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 at(self, cmd, *args, **kwargs): """Wrapper for the low level at commands. This method takes care that the sequence number is increased after each at command ...
with self.lock: self.com_watchdog_timer.cancel() cmd(self.host, self.sequence, *args, **kwargs) self.sequence += 1 self.com_watchdog_timer = threading.Timer(self.timer, self.commwdg) self.com_watchdog_timer.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def halt(self): """Shutdown the drone. This method does not land or halt the actual drone, but the communication with the drone. You should call it at the end of...
with self.lock: self.com_watchdog_timer.cancel() self.ipc_thread.stop() self.ipc_thread.join() self.network_process.terminate() self.network_process.join()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config(host, seq, option, value): """Set configuration parameters of the drone."""
at(host, 'CONFIG', seq, [str(option), str(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 pwm(host, seq, m1, m2, m3, m4): """ Sends control values directly to the engines, overriding control loops. Parameters: seq -- sequence number m1 -- Integer:...
at(host, 'PWM', seq, [m1, m2, m3, m4])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def led(host, seq, anim, f, d): """ Control the drones LED. Parameters: seq -- sequence number anim -- Integer: animation to play f -- Float: frequency in HZ of ...
at(host, 'LED', seq, [anim, float(f), 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 tofile(self, filename, format = 'ascii'): """Save VTK data to file. """
if not common.is_string(filename): raise TypeError('argument filename must be string but got %s'%(type(filename))) if format not in ['ascii','binary']: raise TypeError('argument format must be ascii | binary') filename = filename.strip() if not filename: ...
<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_attr_value(instance, attr, default=None): """ Simple helper to get the value of an instance's attribute if it exists. If the instance attribute is calla...
value = default if hasattr(instance, attr): value = getattr(instance, attr) if callable(value): value = value() return 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 audit_customer_subscription(customer, unknown=True): """ Audits the provided customer's subscription against stripe and returns a pair that contains a boolea...
if (hasattr(customer, 'suspended') and customer.suspended): result = AUDIT_RESULTS['suspended'] else: if hasattr(customer, 'subscription'): try: result = AUDIT_RESULTS[customer.subscription.status] except KeyError, err: # TODO should this ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_number(obj): """Check if obj is number."""
return isinstance(obj, (int, float, np.int_, np.float_))
<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_seq(self,obj,default=None): """Return sequence."""
if is_sequence(obj): return obj if is_number(obj): return [obj] if obj is None and default is not None: log.warning('using default value (%s)'%(default)) return self.get_seq(default) raise ValueError('expected sequence|number but got %s'%(type(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 get_seq_seq(self,obj,default=None): """Return sequence of sequences."""
if is_sequence2(obj): return [self.get_seq(o,default) for o in obj] else: return [self.get_seq(obj,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_3_tuple_list(self,obj,default=None): """Return list of 3-tuples from sequence of a sequence, sequence - it is mapped to sequence of 3-sequences if possib...
if is_sequence2(obj): return [self.get_3_tuple(o,default) for o in obj] elif is_sequence(obj): return [self.get_3_tuple(obj[i:i+3],default) for i in range(0,len(obj),3)] else: return [self.get_3_tuple(obj,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_3_3_tuple(self,obj,default=None): """Return tuple of 3-tuples """
if is_sequence2(obj): ret = [] for i in range(3): if i<len(obj): ret.append(self.get_3_tuple(obj[i],default)) else: ret.append(self.get_3_tuple(default,default)) return tuple(ret) if is_sequence(...
<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_3_3_tuple_list(self,obj,default=None): """Return list of 3x3-tuples. """
if is_sequence3(obj): return [self.get_3_3_tuple(o,default) for o in obj] return [self.get_3_3_tuple(obj,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 connect(self): """Iterate through the application configuration and instantiate the services. """
requested_services = set( svc.lower() for svc in current_app.config.get('BOTO3_SERVICES', []) ) region = current_app.config.get('BOTO3_REGION') sess_params = { 'aws_access_key_id': current_app.config.get('BOTO3_ACCESS_KEY'), 'aws_secret_access_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 init_kerberos(app, service='HTTP', hostname=gethostname()): ''' Configure the GSSAPI service name, and validate the presence of the appropriate principal in the kerberos keytab. :param app: a flask application :type app: flask.Flask :param service: GSSAPI service name :type service: 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 date_to_timestamp(date): """ date to unix timestamp in milliseconds """
date_tuple = date.timetuple() timestamp = calendar.timegm(date_tuple) * 1000 return timestamp
<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_to_json(obj, indent=2): """ transform object to json """
instance_json = json.dumps(obj, indent=indent, ensure_ascii=False, cls=DjangoJSONEncoder) return instance_json
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def qs_to_json(qs, fields=None): """ transform QuerySet to json """
if not fields : fields = [f.name for f in qs.model._meta.fields] # сформируем список для сериализации objects = [] for value_dict in qs.values(*fields): # сохраним порядок полей, как определено в моделе o = OrderedDict() for f in fields: o[f] = value_dict[f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mongoqs_to_json(qs, fields=None): """ transform mongoengine.QuerySet to json """
l = list(qs.as_pymongo()) for element in l: element.pop('_cls') # use DjangoJSONEncoder for transform date data type to datetime json_qs = json.dumps(l, indent=2, ensure_ascii=False, cls=DjangoJSONEncoder) return json_qs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def url_path(request, base_url=None, is_full=False, *args, **kwargs): """ join base_url and some GET-parameters to one; it could be absolute url optionally usage...
if not base_url: base_url = request.path if is_full: protocol = 'https' if request.is_secure() else 'http' base_url = '%s://%s%s' % (protocol, request.get_host(), base_url) params = url_params(request, *args, **kwargs) url = '%s%s' % (base_url, params) return ur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def url_params(request, except_params=None, as_is=False): """ create string with GET-params of request usage example: c['sort_url'] = url_params(request, except_...
if not request.GET: return '' params = [] for key, value in request.GET.items(): if except_params and key not in except_params: for v in request.GET.getlist(key): params.append('%s=%s' % (key, urlquote(v))) if as_is: str_params = '?' + '&'.join(param...
<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, names, country_id=None, language_id=None, retheader=False): """ Look up gender for a list of names. Can optionally refine search with locale info. ...
responses = [ self._get_chunk(name_chunk, country_id, language_id) for name_chunk in _chunked(names, Genderize.BATCH_SIZE) ] data = list(chain.from_iterable( response.data for response in responses )) if retheader: retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def saveVarsInMat(filename, varNamesStr, outOf=None, **opts): """Hacky convinience function to dump a couple of python variables in a .mat file. See `awmstools.s...
from mlabwrap import mlab filename, varnames, outOf = __saveVarsHelper( filename, varNamesStr, outOf, '.mat', **opts) try: for varname in varnames: mlab._set(varname, outOf[varname]) mlab._do("save('%s','%s')" % (filename, "', '".join(varnames)), nout=0) finally: ...
<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_proxy(self, varname, parent=None, constructor=MlabObjectProxy): """Creates a proxy for a variable. XXX create and cache nested proxies also here. """
# FIXME why not just use gensym here? proxy_val_name = "PROXY_VAL%d__" % self._proxy_count self._proxy_count += 1 mlabraw.eval(self._session, "%s = %s;" % (proxy_val_name, varname)) res = constructor(self, proxy_val_name, parent) self._proxies[proxy_val_name] = 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 _do(self, cmd, *args, **kwargs): """Semi-raw execution of a matlab command. Smartly handle calls to matlab, figure out what to do with `args`, and when to us...
handle_out = kwargs.get('handle_out', _flush_write_stdout) #self._session = self._session or mlabraw.open() # HACK if self._autosync_dirs: mlabraw.eval(self._session, "cd('%s');" % os.getcwd().replace("'", "''")) nout = kwargs.get('nout', 1) #XXX what to do...
<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, name, remove=False): r"""Directly access a variable in matlab space. This should normally not be used by user code."""
# FIXME should this really be needed in normal operation? if name in self._proxies: return self._proxies[name] varname = name vartype = self._var_type(varname) if vartype in self._mlabraw_can_convert: var = mlabraw.get(self._session, varname) if isinstanc...
<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(self, name, value): r"""Directly set a variable `name` in matlab space to `value`. This should normally not be used in user code."""
if isinstance(value, MlabObjectProxy): mlabraw.eval(self._session, "%s = %s;" % (name, value._name)) else: ## mlabraw.put(self._session, name, self._as_mlabable_type(value)) mlabraw.put(self._session, name, 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 open(self, visible=False): """ Dispatches the matlab COM client. Note: If this method fails, try running matlab with the -regserver flag. """
if self.client: raise MatlabConnectionError('Matlab(TM) COM client is still active. Use close to ' 'close it') self.client = win32com.client.Dispatch('matlab.application') self.client.visible = visible
<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, names_to_get, convert_to_numpy=True): """ Loads the requested variables from the matlab com client. names_to_get can be either a variable name or a...
self._check_open() single_itme = isinstance(names_to_get, (unicode, str)) if single_itme: names_to_get = [names_to_get] ret = {} for name in names_to_get: ret[name] = self.client.GetWorkspaceData(name, 'base') # TODO(daniv): Do we really want to reduce dimensions like that? what i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(self, name_to_val): """ Loads a dictionary of variable names into the matlab com client. """
self._check_open() for name, val in name_to_val.iteritems(): # First try to put data as a matrix: try: self.client.PutFullMatrix(name, 'base', val, None) except: self.client.PutWorkspaceData(name, 'base', 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 _list_releases(): ''' Tries to guess matlab process release version and location path on osx machines. The paths we will search are in the format: /Applications/MATLAB_R[YEAR][VERSION].app/bin/matlab We will try the latest version first. If no path is found, None is reutrned. ''' if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def is_valid_release_version(version): '''Checks that the given version code is valid.''' return version is not None and len(version) == 6 and version[0] == 'R' \ and int(version[1:5]) in range(1990, 2050) \ and version[5] in ('h', 'g', 'f', 'e', 'd', 'c', 'b', 'a')
<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_matlab_version(process_path): """ Tries to guess matlab's version according to its process path. If we couldn't gues the version, None is returned. """
bin_path = os.path.dirname(process_path) matlab_path = os.path.dirname(bin_path) matlab_dir_name = os.path.basename(matlab_path) version = matlab_dir_name if not is_linux(): version = matlab_dir_name.replace('MATLAB_', '').replace('.app', '') if not is_valid_release_version(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 open(self, print_matlab_welcome=False): '''Opens the matlab process.''' if self.process and not self.process.returncode: raise MatlabConnectionError('Matlab(TM) process is still active. Use close to ' 'close it') self.process = subproce...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(self, name_to_val, oned_as='row', on_new_output=None): """ Loads a dictionary of variable names into the matlab shell. oned_as is the same as in scipy.io...
self._check_open() # We can't give stdin to mlabio.savemat because it needs random access :( temp = StringIO() mlabio.savemat(temp, name_to_val, oned_as=oned_as) temp.seek(0) temp_str = temp.read() temp.close() self.process.stdin.write('load stdio;\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 get(self, names_to_get, extract_numpy_scalars=True, on_new_output=None): """ Loads the requested variables from the matlab shell. names_to_get can be either ...
self._check_open() single_item = isinstance(names_to_get, (unicode, str)) if single_item: names_to_get = [names_to_get] if names_to_get == None: self.process.stdin.write('save stdio;\n') else: # Make sure that we throw an excpetion if the 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 ipshuffle(l, random=None): r"""Shuffle list `l` inplace and return it."""
import random as _random _random.shuffle(l, random) return l
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def withFile(file, func, mode='r', expand=False): """Pass `file` to `func` and ensure the file is closed afterwards. If `file` is a string, open according to `mo...
file = _normalizeToFile(file, mode=mode, expand=expand) try: return func(file) finally: file.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def slurpChompedLines(file, expand=False): r"""Return ``file`` a list of chomped lines. See `slurpLines`."""
f=_normalizeToFile(file, "r", expand) try: return list(chompLines(f)) finally: f.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strToTempfile(s, suffix=None, prefix=None, dir=None, binary=False): """Create a new tempfile, write ``s`` to it and return the filename. `suffix`, `prefix` a...
fd, filename = tempfile.mkstemp(**dict((k,v) for (k,v) in [('suffix',suffix),('prefix',prefix),('dir', dir)] if v is not None)) spitOut(s, fd, binary) return filename
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iprotate(l, steps=1): r"""Like rotate, but modifies `l` in-place. True [2, 3, 1] [1, 2, 3] """
if len(l): steps %= len(l) if steps: firstPart = l[:steps] del l[:steps] l.extend(firstPart) return l
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def notUnique(iterable, reportMax=INF): """Returns the elements in `iterable` that aren't unique; stops after it found `reportMax` non-unique elements. Examples:...
hash = {} n=0 if reportMax < 1: raise ValueError("`reportMax` must be >= 1 and is %r" % reportMax) for item in iterable: count = hash[item] = hash.get(item, 0) + 1 if count > 1: yield item n += 1 if n >= reportMax: 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 unweave(iterable, n=2): r"""Divide `iterable` in `n` lists, so that every `n`th element belongs to list `n`. Example: [[1, 4], [2, 5], [3]] """
res = [[] for i in range(n)] i = 0 for x in iterable: res[i % n].append(x) i += 1 return 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 atIndices(indexable, indices, default=__unique): r"""Return a list of items in `indexable` at positions `indices`. Examples: [2, 2, 1] [2, 2, 1, 'default'] [...
if default is __unique: return [indexable[i] for i in indices] else: res = [] for i in indices: try: res.append(indexable[i]) except (IndexError, KeyError): res.append(default) return 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 stretch(iterable, n=2): r"""Repeat each item in `iterable` `n` times. Example: [0, 0, 1, 1, 2, 2] """
times = range(n) for item in iterable: for i in times: yield item
<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(d, e): """Return a copy of dict `d` updated with dict `e`."""
res = copy.copy(d) res.update(e) return 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 invertDict(d, allowManyToOne=False): r"""Return an inverted version of dict `d`, so that values become keys and vice versa. If multiple keys in `d` have the ...
res = dict(izip(d.itervalues(), d.iterkeys())) if not allowManyToOne and len(res) != len(d): raise ValueError("d can't be inverted!") return 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 iflatten(seq, isSeq=isSeq): r"""Like `flatten` but lazy."""
for elt in seq: if isSeq(elt): for x in iflatten(elt, isSeq): yield x else: yield elt
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def union(seq1=(), *seqs): r"""Return the set union of `seq1` and `seqs`, duplicates removed, order random. Examples: [] [1, 2, 3] [1, 2, 3, 5] ['a', 1, 2, 3, 'd...
if not seqs: return list(seq1) res = set(seq1) for seq in seqs: res.update(set(seq)) return list(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 without(seq1, seq2): r"""Return a list with all elements in `seq2` removed from `seq1`, order preserved. Examples: [2, 3, 2] """
if isSet(seq2): d2 = seq2 else: d2 = set(seq2) return [elt for elt in seq1 if elt not in d2]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def every(predicate, *iterables): r"""Like `some`, but only returns `True` if all the elements of `iterables` satisfy `predicate`. Examples: True False True True...
try: if len(iterables) == 1: ifilterfalse(predicate, iterables[0]).next() else: ifilterfalse(bool, starmap(predicate, izip(*iterables))).next() except StopIteration: return True else: 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 addVars(filename, varNamesStr, outOf=None): r"""Like `saveVars`, but appends additional variables to file."""
filename, varnames, outOf = __saveVarsHelper(filename, varNamesStr, outOf) f = None try: f = open(filename, "rb") h = cPickle.load(f) f.close() h.update(dict(zip(varnames, atIndices(outOf, varnames)))) f = open(filename, "wb") cPickle.dump( h, f , 1 ) fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loadDict(filename): """Return the variables pickled pickled into `filename` with `saveVars` as a dict."""
filename = os.path.expanduser(filename) if not splitext(filename)[1]: filename += ".bpickle" f = None try: f = open(filename, "rb") varH = cPickle.load(f) finally: if f: f.close() return varH
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def runInfo(prog=None,vers=None,date=None,user=None,dir=None,args=None): r"""Create a short info string detailing how a program was invoked. This is meant to be ...
return "%(prog)s %(vers)s;" \ " run %(date)s by %(usr)s in %(dir)s with: %(args)s'n" % \ mkDict(prog=prog or sys.argv[0], vers=vers or magicGlobals().get("__version__", ""), date=date or isoDateTimeStr(), usr=user or getpass.getuser(), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def argmin(iterable, key=None, both=False): """See `argmax`. """
if key is not None: it = imap(key, iterable) else: it = iter(iterable) score, argmin = reduce(min, izip(it, count())) if both: return argmin, score return argmin
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compose(*funcs): """Compose `funcs` to a single function. 5 'nada' [1, 2] """
# slightly optimized for most common cases and hence verbose if len(funcs) == 2: f0,f1=funcs; return lambda *a,**kw: f0(f1(*a,**kw)) elif len(funcs) == 3: f0,f1,f2=funcs; return lambda *a,**kw: f0(f1(f2(*a,**kw))) elif len(funcs) == 0: return lambda x:x # XXX single kwarg elif len(funcs) == 1: ...
<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, func, *args, **kwargs): """Same as ``self.dryRun`` if ``self.dry``, else same as ``self.wetRun``."""
if self.dry: return self.dryRun(func, *args, **kwargs) else: return self.wetRun(func, *args, **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 iterbridges(): ''' Iterate over all the bridges in the system. ''' net_files = os.listdir(SYSFS_NET_PATH) for d in net_files: path = os.path.join(SYSFS_NET_PATH, d) if not os.path.isdir(path): continue if os.path.exists(os.path.join(path, b"bridge")): yiel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def addbr(name): ''' Create new bridge with the given name ''' fcntl.ioctl(ifconfig.sockfd, SIOCBRADDBR, name) return Bridge(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 iterifs(self): ''' Iterate over all the interfaces in this bridge. ''' if_path = os.path.join(SYSFS_NET_PATH, self.name, b"brif") net_files = os.listdir(if_path) for iface in net_files: yield iface
<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_lib_filename(category, name): """ Get a filename of a built-in library file. """
base_dir = os.path.dirname(os.path.abspath(__file__)) if category == 'js': filename = os.path.join('js', '{0}.js'.format(name)) elif category == 'css': filename = os.path.join('css', '{0}.css'.format(name)) elif category == 'html': filename = os.path.join('html', '{0}.html'.form...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def output_notebook( d3js_url="//d3js.org/d3.v3.min", requirejs_url="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js", html_template=None ): ""...
if html_template is None: html_template = read_lib('html', 'setup') setup_html = populate_template( html_template, d3js=d3js_url, requirejs=requirejs_url ) display_html(setup_html) 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 create_graph_html(js_template, css_template, html_template=None): """ Create HTML code block given the graph Javascript and CSS. """
if html_template is None: html_template = read_lib('html', 'graph') # Create div ID for the graph and give it to the JS and CSS templates so # they can reference the graph. graph_id = 'graph-{0}'.format(_get_random_id()) js = populate_template(js_template, graph_id=graph_id) css = popu...
<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_newest_possible_languagetool_version(): """Return newest compatible version. True """
java_path = find_executable('java') if not java_path: # Just ignore this and assume an old version of Java. It might not be # found because of a PATHEXT-related issue # (https://bugs.python.org/issue2200). return JAVA_6_COMPATIBLE_VERSION output = subprocess.check_output([j...
<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(): ''' Initialize the library ''' globals()["sock"] = socket.socket(socket.AF_INET, socket.SOCK_STREAM) globals()["sockfd"] = globals()["sock"].fileno()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def is_up(self): ''' Return True if the interface is up, False otherwise. ''' # Get existing device flags ifreq = struct.pack('16sh', self.name, 0) flags = struct.unpack('16sh', fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1] # Set new flags if flags & IFF_UP: ...
<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_mac(self): ''' Obtain the device's mac address. ''' ifreq = struct.pack('16sH14s', self.name, AF_UNIX, b'\x00'*14) res = fcntl.ioctl(sockfd, SIOCGIFHWADDR, ifreq) address = struct.unpack('16sH14s', res)[2] mac = struct.unpack('6B8x', address) return ":".join(['%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 set_mac(self, newmac): ''' Set the device's mac address. Device must be down for this to succeed. ''' macbytes = [int(i, 16) for i in newmac.split(':')] ifreq = struct.pack('16sH6B8x', self.name, AF_UNIX, *macbytes) fcntl.ioctl(sockfd, SIOCSIFHWADDR, ifreq)
<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_index(self): ''' Convert an interface name to an index value. ''' ifreq = struct.pack('16si', self.name, 0) res = fcntl.ioctl(sockfd, SIOCGIFINDEX, ifreq) return struct.unpack("16si", res)[1]
<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_pause_param(self, autoneg, rx_pause, tx_pause): """ Ethernet has flow control! The inter-frame pause can be adjusted, by auto-negotiation through an ethe...
# create a struct ethtool_pauseparm # create a struct ifreq with its .ifr_data pointing at the above ecmd = array.array('B', struct.pack('IIII', ETHTOOL_SPAUSEPARAM, bool(autoneg), bool(rx_pause), bool(tx_pause))) buf_addr, _buf_len = ecmd.buffer_info() ifreq = struc...
<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_elements(value): """Split a string with comma or space-separated elements into a list."""
l = [v.strip() for v in value.split(',')] if len(l) == 1: l = value.split() return l
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_hook(config): """Default setup hook."""
if (any(arg.startswith('bdist') for arg in sys.argv) and os.path.isdir(PY2K_DIR) != IS_PY2K and os.path.isdir(LIB_DIR)): shutil.rmtree(LIB_DIR) if IS_PY2K and any(arg.startswith('install') or arg.startswith('build') or arg.startswith('bdist') f...
<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_default_if(): """ Returns the default interface """
f = open ('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if (int (dest) == 0): interf = words[0] break except ValueError: pass return interf
<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_default_gw(): """ Returns the default gateway """
octet_list = [] gw_from_route = None f = open ('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if (int (dest) == 0): gw_from_route = words[2] break except ValueError: 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 init(init_type='plaintext_tcp', *args, **kwargs): """ Create the module instance of the GraphiteClient. """
global _module_instance reset() validate_init_types = ['plaintext_tcp', 'plaintext', 'pickle_tcp', 'pickle', 'plain'] if init_type not in validate_init_types: raise GraphiteSendException( "Invalid init_type '%s', must be one of: %s" % (init_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 cli(): """ Allow the module to be called from the cli. """
import argparse parser = argparse.ArgumentParser(description='Send data to graphite') # Core of the application is to accept a metric and a value. parser.add_argument('metric', metavar='metric', type=str, help='name.of.metric') parser.add_argument('value', metavar='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 connect(self): """ Make a TCP connection to the graphite server on port self.port """
self.socket = socket.socket() self.socket.settimeout(self.timeout_in_seconds) try: self.socket.connect(self.addr) except socket.timeout: raise GraphiteSendException( "Took over %d second(s) to connect to %s" % (self.timeout_in_seco...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disconnect(self): """ Close the TCP connection with the graphite server. """
try: self.socket.shutdown(1) # If its currently a socket, set it to None except AttributeError: self.socket = None except Exception: self.socket = None # Set the self.socket to None, no matter what. finally: self.socket =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dispatch_send(self, message): """ Dispatch the different steps of sending """
if self.dryrun: return message if not self.socket: raise GraphiteSendException( "Socket was not created before send" ) sending_function = self._send if self._autoreconnect: sending_function = self._send_and_reconnect ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send_and_reconnect(self, message): """Send _message_ to Graphite Server and attempt reconnect on failure. If _autoreconnect_ was specified, attempt to recon...
try: self.socket.sendall(message.encode("ascii")) except (AttributeError, socket.error): if not self.autoreconnect(): raise else: self.socket.sendall(message.encode("ascii"))
<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_asynchronous(self): """Check if socket have been monkey patched by gevent"""
def is_monkey_patched(): try: from gevent import monkey, socket except ImportError: return False if hasattr(monkey, "saved"): return "socket" in monkey.saved return gevent.socket.socket == socket.socket if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def str2listtuple(self, string_message): "Covert a string that is ready to be sent to graphite into a tuple" if type(string_message).__name__ not in ('str', 'unicode'): raise TypeError("Must provide a string or unicode") if not string_message.endswith('\n'): string_mess...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send(self, message): """ Given a message send it to the graphite server. """
# An option to lowercase the entire message if self.lowercase_metric_names: message = message.lower() # convert the message into a pickled payload. message = self.str2listtuple(message) try: self.socket.sendall(message) # Capture missing socket...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_metric_name(self, metric_name): """ Make sure the metric is free of control chars, spaces, tabs, etc. """
if not self._clean_metric_name: return metric_name metric_name = str(metric_name) for _from, _to in self.cleaning_replacement_list: metric_name = metric_name.replace(_from, _to) return metric_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 _get_attrib(cls): """Get matches element attributes."""
if not cls._server_is_alive(): cls._start_server_on_free_port() params = {'language': FAILSAFE_LANGUAGE, 'text': ''} data = urllib.parse.urlencode(params).encode() root = cls._get_root(cls._url, data, num_tries=1) return root.attrib
<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_form(self, request, obj=None, **kwargs): """ Patched method for PageAdmin.get_form. Returns a page form without the base field 'meta_description' which i...
language = get_language_from_request(request, obj) form = _BASE_PAGEADMIN__GET_FORM(self, request, obj, **kwargs) if not obj or not obj.get_meta_description(language=language): form.base_fields.pop('meta_description', None) return form
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def begin(self, address=MPR121_I2CADDR_DEFAULT, i2c=None, **kwargs): """Initialize communication with the MPR121. Can specify a custom I2C address for the device...
# Assume we're using platform's default I2C bus if none is specified. if i2c is None: import Adafruit_GPIO.I2C as I2C i2c = I2C # Require repeated start conditions for I2C register reads. Unfortunately # the MPR121 is very sensitive and requires ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def touched(self): """Return touch state of all pins as a 12-bit value where each bit represents a pin, with a value of 1 being touched and 0 not being touched. ...
t = self._i2c_retry(self._device.readU16LE, MPR121_TOUCHSTATUS_L) return t & 0x0FFF
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_touched(self, pin): """Return True if the specified pin is being touched, otherwise returns False. """
assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' t = self.touched() return (t & (1 << pin)) > 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 profileit(func): """ Decorator straight up stolen from stackoverflow """
def wrapper(*args, **kwargs): datafn = func.__name__ + ".profile" # Name the data file sensibly prof = cProfile.Profile() prof.enable() retval = prof.runcall(func, *args, **kwargs) prof.disable() stats = pstats.Stats(prof) try: stats.sort_stats('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 _get_fields_for_model(model): """ Gets all of the fields on the model. :param DeclarativeModel model: A SQLAlchemy ORM Model :return: A tuple of the fields o...
fields = [] for name in model._sa_class_manager: prop = getattr(model, name) if isinstance(prop.property, RelationshipProperty): for pk in prop.property.mapper.primary_key: fields.append('{0}.{1}'.format(name, pk.name)) else: fields.append(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 _get_relationships(model): """ Gets the necessary relationships for the resource by inspecting the sqlalchemy model for relationships. :param DeclarativeMeta...
relationships = [] for name, relationship in inspect(model).relationships.items(): class_ = relationship.mapper.class_ if relationship.uselist: rel = ListRelationship(name, relation=class_.__name__) else: rel = Relationship(name, relation=class_.__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 create_resource(model, session_handler, resource_bases=(CRUDL,), relationships=None, links=None, preprocessors=None, postprocessors=None, fields=None, paginat...
relationships = relationships or tuple() if auto_relationships: relationships += _get_relationships(model) links = links or tuple() preprocessors = preprocessors or tuple() postprocessors = postprocessors or tuple() pks = pks or _get_pks(model) fields...