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 and the watchdog timer is started to make sure the drone receives a command at least every second. """ |
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 your application to close all sockets, pipes, processes and threads related with this object. """ |
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: front left command m2 -- Integer: front right command m3 -- Integer: back right command m4 -- Integer: back left command """ |
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 the animation d -- Integer: total duration in seconds of the animation """ |
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:
raise ValueError('filename must be non-empty string')
if filename[-4:]!='.vtk':
filename += '.vtk'
f = open(filename,'wb')
f.write(self.to_string(format))
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 _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 callable it will be called and the result will be returned. Optionally accepts a default value to return if the attribute is missing. Defaults to `None` 'baz' False 'hi' """ |
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 boolean and a result type. Default result types can be found in zebra.conf.defaults and can be overridden in your project's settings. """ |
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 be a more specific exception class?
raise Exception("Unable to locate a result set for \
subscription status %s in ZEBRA_AUDIT_RESULTS") % str(err)
else:
result = AUDIT_RESULTS['no_subscription']
return result |
<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 possible number """ |
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(obj):
if len(obj)>9:
log.warning('ignoring elements obj[i], i>=9')
r = obj[:9]
r = [self.get_3_tuple(r[j:j+3],default) for j in range(0,len(r),3)]
if len(r)<3:
log.warning('filling with default value (%s) to obtain size=3'%(default[0]))
while len(r)<3:
r.append(self.get_3_tuple(default,default))
return tuple(r)
log.warning('filling with default value (%s) to obtain size=3'%(default[0]))
r1 = self.get_3_tuple(obj,default)
r2 = self.get_3_tuple(default,default)
r3 = self.get_3_tuple(default,default)
return (r1,r2,r3) |
<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': current_app.config.get('BOTO3_SECRET_KEY'),
'profile_name': current_app.config.get('BOTO3_PROFILE'),
'region_name': region
}
sess = boto3.session.Session(**sess_params)
try:
cns = {}
for svc in requested_services:
# Check for optional parameters
params = current_app.config.get(
'BOTO3_OPTIONAL_PARAMS', {}
).get(svc, {})
# Get session params and override them with kwargs
# `profile_name` cannot be passed to clients and resources
kwargs = sess_params.copy()
kwargs.update(params.get('kwargs', {}))
del kwargs['profile_name']
# Override the region if one is defined as an argument
args = params.get('args', [])
if len(args) >= 1:
del kwargs['region_name']
if not(isinstance(args, list) or isinstance(args, tuple)):
args = [args]
# Create resource or client
if svc in sess.get_available_resources():
cns.update({svc: sess.resource(svc, *args, **kwargs)})
else:
cns.update({svc: sess.client(svc, *args, **kwargs)})
except UnknownServiceError:
raise
return cns |
<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
:param hostname: hostname the service runs under
:type hostname: str
'''
global _SERVICE_NAME
_SERVICE_NAME = "%s@%s" % (service, hostname)
if 'KRB5_KTNAME' not in environ:
app.logger.warn("Kerberos: set KRB5_KTNAME to your keytab file")
else:
try:
principal = kerberos.getServerPrincipalDetails(service, hostname)
except kerberos.KrbError as exc:
app.logger.warn("Kerberos: %s" % exc.message[0])
else:
app.logger.info("Kerberos: server is %s" % principal) |
<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]
objects.append(o)
# сериализуем
json_qs = json.dumps(objects, 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 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 example: c['current_url'] = url_path(request, use_urllib=True, is_full=False) <a href="{{ current_url }}">Лабораторный номер</a> """ |
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 url |
<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_params=('sort',)) <a href="{{ sort_url }}&sort=lab_number">Лабораторный номер</a> """ |
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(params)
else:
str_params = '?' + '&'.join(params)
str_params = urlquote(str_params)
return mark_safe(str_params) |
<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. May make multiple requests if there are more names than can be retrieved in one call. :param names: List of names. :type names: Iterable[str] :param country_id: Optional ISO 3166-1 alpha-2 country code. :type country_id: Optional[str] :param language_id: Optional ISO 639-1 language code. :type language_id: Optional[str] :param retheader: Optional :type retheader: Optional[boolean] :return: If retheader is False: List of dicts containing 'name', 'gender', 'probability', 'count' keys. If 'gender' is None, 'probability' and 'count' will be omitted. else: A dict containing 'data' and 'headers' keys. Data is the same as when retheader is False. Headers are the response header (a requests.structures.CaseInsensitiveDict). If multiple requests were made, the header will be from the last one. :rtype: Union[dict, Sequence[dict]] :raises GenderizeException: if API server returns HTTP error code. """ |
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:
return {
"data": data,
"headers": responses[-1].headers,
}
else:
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 saveVarsInMat(filename, varNamesStr, outOf=None, **opts):
"""Hacky convinience function to dump a couple of python variables in a .mat file. See `awmstools.saveVars`. """ |
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:
assert varnames
mlab._do("clear('%s')" % "', '".join(varnames), nout=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 _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
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 _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 use function call syntax and not. If no `args` are specified, the ``cmd`` not ``result = cmd()`` form is used in Matlab -- this also makes literal Matlab commands legal (eg. cmd=``get(gca, 'Children')``). If ``nout=0`` is specified, the Matlab command is executed as procedure, otherwise it is executed as function (default), nout specifying how many values should be returned (default 1). **Beware that if you use don't specify ``nout=0`` for a `cmd` that never returns a value will raise an error** (because assigning a variable to a call that doesn't return a value is illegal in matlab). ``cast`` specifies which typecast should be applied to the result (e.g. `int`), it defaults to none. XXX: should we add ``parens`` parameter? """ |
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 with matlab screen output
argnames = []
tempargs = []
try:
for count, arg in enumerate(args):
if isinstance(arg, MlabObjectProxy):
argnames.append(arg._name)
else:
nextName = 'arg%d__' % count
argnames.append(nextName)
tempargs.append(nextName)
# have to convert these by hand
## try:
## arg = self._as_mlabable_type(arg)
## except TypeError:
## raise TypeError("Illegal argument type (%s.:) for %d. argument" %
## (type(arg), type(count)))
mlabraw.put(self._session, argnames[-1], arg)
if args:
cmd = "%s(%s)%s" % (cmd, ", ".join(argnames),
('',';')[kwargs.get('show',0)])
# got three cases for nout:
# 0 -> None, 1 -> val, >1 -> [val1, val2, ...]
if nout == 0:
handle_out(mlabraw.eval(self._session, cmd))
return
# deal with matlab-style multiple value return
resSL = ((["RES%d__" % i for i in range(nout)]))
handle_out(mlabraw.eval(self._session, '[%s]=%s;' % (", ".join(resSL), cmd)))
res = self._get_values(resSL)
if nout == 1: res = res[0]
else: res = tuple(res)
if kwargs.has_key('cast'):
if nout == 0: raise TypeError("Can't cast: 0 nout")
return kwargs['cast'](res)
else:
return res
finally:
if len(tempargs) and self._clear_call_args:
mlabraw.eval(self._session, "clear('%s');" %
"','".join(tempargs)) |
<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 isinstance(var, ndarray):
if self._flatten_row_vecs and numpy.shape(var)[0] == 1:
var.shape = var.shape[1:2]
elif self._flatten_col_vecs and numpy.shape(var)[1] == 1:
var.shape = var.shape[0:1]
if self._array_cast:
var = self._array_cast(var)
else:
var = None
if self._dont_proxy.get(vartype):
# manual conversions may fail (e.g. for multidimensional
# cell arrays), in that case just fall back on proxying.
try:
var = self._manually_convert(varname, vartype)
except MlabConversionError: pass
if var is None:
# we can't convert this to a python object, so we just
# create a proxy, and don't delete the real matlab
# reference until the proxy is garbage collected
var = self._make_proxy(varname)
if remove:
mlabraw.eval(self._session, "clear('%s');" % varname)
return var |
<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 list of variable names. If it is a variable name, the values is returned. If it is a list, a dictionary of variable_name -> value is returned. If convert_to_numpy is true, the method will all array values to numpy arrays. Scalars are left as regular python objects. """ |
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 if this a row vector?
while isinstance(ret[name], (tuple, list)) and len(ret[name]) == 1:
ret[name] = ret[name][0]
if convert_to_numpy and isinstance(ret[name], (tuple, list)):
ret[name] = np.array(ret[name])
if single_itme:
return ret.values()[0]
return ret |
<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 is_linux():
base_path = '/usr/local/MATLAB/R%d%s/bin/matlab'
else:
# assume mac
base_path = '/Applications/MATLAB_R%d%s.app/bin/matlab'
years = range(2050,1990,-1)
release_letters = ('h', 'g', 'f', 'e', 'd', 'c', 'b', 'a')
for year in years:
for letter in release_letters:
release = 'R%d%s' % (year, letter)
matlab_path = base_path % (year, letter)
if os.path.exists(matlab_path):
yield (release, matlab_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 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):
return None
return 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 = subprocess.Popen(
[self.matlab_process_path, '-nojvm', '-nodesktop'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
flags = fcntl.fcntl(self.process.stdout, fcntl.F_GETFL)
fcntl.fcntl(self.process.stdout, fcntl.F_SETFL, flags| os.O_NONBLOCK)
if print_matlab_welcome:
self._sync_output()
else:
self._sync_output(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 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.matlab.savemat function: oned_as : {'column', 'row'}, optional If 'column', write 1-D numpy arrays as column vectors. If 'row', write 1D numpy arrays as row vectors. """ |
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')
self._read_until('ack load stdio\n', on_new_output=on_new_output)
self.process.stdin.write(temp_str)
#print 'sent %d kb' % (len(temp_str) / 1024)
self._read_until('ack load finished\n', on_new_output=on_new_output)
self._sync_output(on_new_output=on_new_output) |
<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 a variable name, a list of variable names, or None. If it is a variable name, the values is returned. If it is a list, a dictionary of variable_name -> value is returned. If it is None, a dictionary with all variables is returned. If extract_numpy_scalars is true, the method will convert numpy scalars (0-dimension arrays) to a regular python variable. """ |
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 names are not defined.
for name in names_to_get:
self.eval('%s;' % name, print_expression=False, on_new_output=on_new_output)
#print 'save(\'stdio\', \'%s\');\n' % '\', \''.join(names_to_get)
self.process.stdin.write(
"save('stdio', '%s', '-v7');\n" % '\', \''.join(names_to_get))
# We have to read to a temp buffer because mlabio.loadmat needs
# random access :(
self._read_until('start_binary\n', on_new_output=on_new_output)
#print 'got start_binary'
temp_str = self._sync_output(on_new_output=on_new_output)
#print 'got all outout'
# Remove expected output and "\n>>"
# TODO(dani): Get rid of the unecessary copy.
# MATLAB 2010a adds an extra >> so we need to remove more spaces.
if self.matlab_version == (2010, 'a'):
temp_str = temp_str[:-len(self.expected_output_end)-6]
else:
temp_str = temp_str[:-len(self.expected_output_end)-3]
temp = StringIO(temp_str)
#print ('____')
#print len(temp_str)
#print ('____')
ret = mlabio.loadmat(temp, chars_as_strings=True, squeeze_me=True)
#print '******'
#print ret
#print '******'
temp.close()
if single_item:
return ret.values()[0]
for key in ret.iterkeys():
while ret[key].shape and ret[key].shape[-1] == 1:
ret[key] = ret[key][0]
if extract_numpy_scalars:
if isinstance(ret[key], np.ndarray) and not ret[key].shape:
ret[key] = ret[key].tolist()
#print 'done'
return ret |
<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 `mode`; if `expand` is true also expand user and vars. """ |
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` and `dir` are like in `tempfile.mkstemp`. """ |
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: [1, 2, 3] [1] """ |
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'] [3] """ |
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 same value an error is raised, unless `allowManyToOne` is true, in which case one of those key-value pairs is chosen at random for the inversion. Examples: True Traceback (most recent call last):
File "<stdin>", line 1, in ? ValueError: d can't be inverted! [2] """ |
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', 'b', 'c'] [0, 1, 2, 3] """ |
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 False """ |
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 )
finally:
if f: 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 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 added to a history comment field of a data file were it is important to keep track of what programs modified it and how. !!!:`args` should be a **``list``** not a ``str``.""" |
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(),
dir=dir or os.getcwd(),
args=" ".join(args or sys.argv)) |
<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: return funcs[0]
else:
def composed(*args,**kwargs):
y = funcs[-1](*args,**kwargs)
for f in funcs[:0:-1]: y = f(y)
return y
return composed |
<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")):
yield Bridge(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 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'.format(name))
else:
raise ValueError("Unknown category")
return os.path.join(base_dir, 'lib', 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 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 ):
""" Import required Javascript libraries to Jupyter Notebook. """ |
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 = populate_template(css_template, graph_id=graph_id)
return populate_template(
html_template,
graph_id=graph_id,
css=css,
js=js
) |
<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([java_path, '-version'],
stderr=subprocess.STDOUT,
universal_newlines=True)
# https://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html
match = re.search(
r'^java version "(?P<major1>\d+)\.(?P<major2>\d+)\.[^"]+"$',
output,
re.MULTILINE)
if not match:
raise SystemExit(
'Could not parse Java version from """{}""".'.format(output))
java_version = (int(match.group('major1')), int(match.group('major2')))
if java_version >= (1, 7):
return LATEST_VERSION
elif java_version >= (1, 6):
warn('grammar-check would be able to use a newer version of '
'LanguageTool if you had Java 7 or newer installed')
return JAVA_6_COMPATIBLE_VERSION
else:
raise SystemExit(
'You need at least Java 6 to use grammar-check') |
<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:
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 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(['%02X' % i for i in mac]) |
<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 ethernet frame type with a simple two-field payload, and by setting it explicitly. http://en.wikipedia.org/wiki/Ethernet_flow_control """ |
# 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 = struct.pack('16sP', self.name, buf_addr)
fcntl.ioctl(sockfd, SIOCETHTOOL, 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 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') for arg in sys.argv):
generate_py2k(config)
packages_root = get_cfg_value(config, 'files', 'packages_root')
packages_root = os.path.join(PY2K_DIR, packages_root)
set_cfg_value(config, 'files', 'packages_root', packages_root) |
<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
if not gw_from_route:
return None
for i in range(8, 1, -2):
octet = gw_from_route[i-2:i]
octet = int(octet, 16)
octet_list.append(str(octet))
gw_ip = ".".join(octet_list)
return gw_ip |
<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_type, ", ".join(validate_init_types)))
# Use TCP to send data to the plain text receiver on the graphite server.
if init_type in ['plaintext_tcp', 'plaintext', 'plain']:
_module_instance = GraphiteClient(*args, **kwargs)
# Use TCP to send pickled data to the pickle receiver on the graphite
# server.
if init_type in ['pickle_tcp', 'pickle']:
_module_instance = GraphitePickleClient(*args, **kwargs)
return _module_instance |
<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', type=int,
help='value of metric as int')
args = parser.parse_args()
metric = args.metric
value = args.value
graphitesend_instance = init()
graphitesend_instance.send(metric, 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_seconds, self.addr))
except socket.gaierror:
raise GraphiteSendException(
"No address associated with hostname %s:%s" % self.addr)
except Exception as error:
raise GraphiteSendException(
"unknown exception while connecting to %s - %s" %
(self.addr, error)
)
return 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 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 = 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 _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
try:
if self.asynchronous and gevent:
gevent.spawn(sending_function, message)
else:
sending_function(message)
except Exception as e:
self._handle_send_error(e)
return "sent {0} long message: {1}".format(len(message), message[:75]) |
<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 reconnect if first send fails. :raises AttributeError: When the socket has not been set. :raises socket.error: When the socket connection is no longer valid. """ |
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 not is_monkey_patched():
raise Exception("To activate asynchonoucity, please monkey patch"
" the socket module with gevent")
return True |
<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_message += "\n"
tpl_list = []
for line in string_message.split('\n'):
line = line.strip()
if not line:
continue
path, metric, timestamp = (None, None, None)
try:
(path, metric, timestamp) = line.split()
except ValueError:
raise ValueError(
"message must contain - metric_name, value and timestamp '%s'"
% line)
try:
timestamp = float(timestamp)
except ValueError:
raise ValueError("Timestamp must be float or int")
tpl_list.append((path, (timestamp, metric)))
if len(tpl_list) == 0:
raise GraphiteSendException("No messages to send")
payload = pickle.dumps(tpl_list)
header = struct.pack("!L", len(payload))
message = header + payload
return message |
<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.
except socket.gaierror as error:
raise GraphiteSendException(
"Failed to send data to %s, with error: %s" %
(self.addr, error)) # noqa
# Capture socket closure before send.
except socket.error as error:
raise GraphiteSendException(
"Socket closed before able to send data to %s, "
"with error: %s" %
(self.addr, error)) # noqa
except Exception as error:
raise GraphiteSendException(
"Unknown error while trying to send data down socket to %s, "
"error: %s" %
(self.addr, error)) # noqa
return "sent %d long pickled message" % len(message) |
<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 is overridden in djangocms-page-meta. This is triggered in the page add view and in the change view if the meta description of the page is empty. """ |
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 using the address parameter (defaults to 0x5A). Optional i2c parameter allows specifying a custom I2C bus source (defaults to platform's I2C bus). Returns True if communication with the MPR121 was established, otherwise returns False. """ |
# 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 repeated starts to read all
# the registers.
I2C.require_repeated_start()
# Save a reference to the I2C device instance for later communication.
self._device = i2c.get_i2c_device(address, **kwargs)
return self._reset() |
<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('cumtime').print_stats()
except KeyError:
pass # breaks in python 2.6
return retval
return wrapper |
<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 on the Model corresponding to the columns on the Model. :rtype: tuple """ |
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)
return tuple(fields) |
<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 model: The SQLAlchemy ORM model. :return: A tuple of Relationship/ListRelationship instances corresponding to the relationships on the Model. :rtype: tuple """ |
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__)
relationships.append(rel)
return tuple(relationships) |
<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, paginate_by=100, auto_relationships=True, pks=None, create_fields=None, update_fields=None, list_fields=None, append_slash=False):
""" Creates a ResourceBase subclass by inspecting a SQLAlchemy Model. This is somewhat more restrictive than explicitly creating managers and resources. However, if you only need any of the basic CRUD+L operations, :param sqlalchemy.Model model: This is the model that will be inspected to create a Resource and Manager from. By default, all of it's fields will be exposed, although this can be overridden using the fields attribute. :param tuple resource_bases: A tuple of ResourceBase subclasses. Defaults to the restmixins.CRUDL class only. However if you only wanted Update and Delete you could pass in ```(restmixins.Update, restmixins.Delete)``` which would cause the resource to inherit from those two. Additionally, you could create your own mixins and pass them in as the resource_bases :param tuple relationships: extra relationships to pass into the ResourceBase constructor. If auto_relationships is set to True, then they will be appended to these relationships. :param tuple links: Extra links to pass into the ResourceBase as the class _links attribute. Defaults to an empty tuple. :param tuple preprocessors: Preprocessors for the resource class attribute. :param tuple postprocessors: Postprocessors for the resource class attribute. :param ripozo_sqlalchemy.SessionHandler|ripozo_sqlalchemy.ScopedSessionHandler session_handler: A session handler to use when instantiating an instance of the Manager class created from the model. This is responsible for getting and handling sessions in both normal cases and exceptions. :param tuple fields: The fields to expose on the api. Defaults to all of the fields on the model. :param bool auto_relationships: If True, then the SQLAlchemy Model will be inspected for relationships and they will be automatically appended to the relationships on the resource class attribute. :param list create_fields: A list of the fields that are valid when creating a resource. By default this will be the fields without any primary keys included :param list update_fields: A list of the fields that are valid when updating a resource. By default this will be the fields without any primary keys included :param list list_fields: A list of the fields that will be returned when the list endpoint is requested. Defaults to the fields attribute. :param bool append_slash: A flag to forcibly append slashes to the end of urls. :return: A ResourceBase subclass and AlchemyManager subclass :rtype: ResourceMetaClass """ |
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 = fields or _get_fields_for_model(model)
list_fields = list_fields or fields
create_fields = create_fields or [x for x in fields if x not in set(pks)]
update_fields = update_fields or [x for x in fields if x not in set(pks)]
manager_cls_attrs = dict(paginate_by=paginate_by, fields=fields, model=model,
list_fields=list_fields, create_fields=create_fields,
update_fields=update_fields)
manager_class = type(str(model.__name__), (AlchemyManager,), manager_cls_attrs)
manager = manager_class(session_handler)
resource_cls_attrs = dict(preprocessors=preprocessors,
postprocessors=postprocessors,
_relationships=relationships, _links=links,
pks=pks, manager=manager, append_slash=append_slash)
res_class = ResourceMetaClass(str(model.__name__), resource_bases, resource_cls_attrs)
return res_class |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.