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 initializerepo(self): """ Fill empty directory with products and make first commit """
try: os.mkdir(self.repopath) except OSError: pass cmd = self.repo.init(bare=self.bare, shared=self.shared) if not self.bare: self.write_testing_data([], []) self.write_training_data([], []) self.write_classifier(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 isvalid(self): """ Checks whether contents of repo are consistent with standard set. """
gcontents = [gf.rstrip('\n') for gf in self.repo.bake('ls-files')()] fcontents = os.listdir(self.repopath) return all([sf in gcontents for sf in std_files]) and all([sf in fcontents for sf in std_files])
<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_version(self, version, force=True): """ Sets the version name for the current state of repo """
if version in self.versions: self._version = version if 'working' in self.repo.branch().stdout: if force: logger.info('Found working branch. Removing...') cmd = self.repo.checkout('master') cmd = self.repo.bran...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def training_data(self): """ Returns data dictionary from training.pkl """
data = pickle.load(open(os.path.join(self.repopath, 'training.pkl'))) return data.keys(), data.values()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def classifier(self): """ Returns classifier from classifier.pkl """
clf = pickle.load(open(os.path.join(self.repopath, 'classifier.pkl'))) return clf
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_training_data(self, features, targets): """ Writes data dictionary to filename """
assert len(features) == len(targets) data = dict(zip(features, targets)) with open(os.path.join(self.repopath, 'training.pkl'), 'w') as fp: pickle.dump(data, fp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_classifier(self, clf): """ Writes classifier object to pickle file """
with open(os.path.join(self.repopath, 'classifier.pkl'), 'w') as fp: pickle.dump(clf, fp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def commit_version(self, version, msg=None): """ Add tag, commit, and push changes """
assert version not in self.versions, 'Will not overwrite a version name.' if not msg: feat, targ = self.training_data msg = 'Training set has {0} examples. '.format(len(feat)) feat, targ = self.testing_data msg += 'Testing set has {0} examples.'.format(...
<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_all_usb_devices(idVendor, idProduct): """ Returns a list of all the usb devices matching the provided vendor ID and product ID."""
all_dev = list(usb.core.find(find_all = True, idVendor = idVendor, idProduct = idProduct)) for dev in all_dev: try: dev.detach_kernel_driver(0) except usb.USBError: pass return all_dev
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_device_address(usb_device): """ Returns the grizzly's internal address value. Returns a negative error value in case of error. """
try: usb_device.ctrl_transfer(0x21, 0x09, 0x0300, 0, GrizzlyUSB.COMMAND_GET_ADDR) internal_addr = usb_device.ctrl_transfer(0xa1, 0x01, 0x0301, 0, 2)[1] return internal_addr >> 1 except usb.USBError as e: return GrizzlyUSB.USB_DEVICE_ERROR
<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_all_ids(idVendor = GrizzlyUSB.ID_VENDOR, idProduct=GrizzlyUSB.ID_PRODUCT): """ Scans for grizzlies that have not been bound, or constructed, and returns ...
all_dev = GrizzlyUSB.get_all_usb_devices(idVendor, idProduct) if len(all_dev) <= 0: raise usb.USBError("Could not find any GrizzlyBear device (idVendor=%d, idProduct=%d)" % (idVendor, idProduct)) else: all_addresses = [] # bound devices is a lis...
<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_register(self, addr, data): """Sets an arbitrary register at @addr and subsequent registers depending on how much data you decide to write. It will autom...
assert len(data) <= 14, "Cannot write more than 14 bytes at a time" cmd = chr(addr) + chr(len(data) | 0x80) for byte in data: cmd += chr(cast_to_byte(byte)) cmd += (16 - len(cmd)) * chr(0) self._dev.send_bytes(cmd)
<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_mode(self, controlmode, drivemode): """Higher level abstraction for setting the mode register. This will set the mode according the the @controlmode and ...
self.set_register(Addr.Mode, [0x01 | controlmode | drivemode])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_as_int(self, addr, numBytes): """Convenience method. Oftentimes we need to read a range of registers to represent an int. This method will automaticall...
buf = self.read_register(addr, numBytes) if len(buf) >= 4: return struct.unpack_from("<i", buf)[0] else: rtn = 0 for i, byte in enumerate(buf): rtn |= byte << 8 * i return rtn
<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_as_int(self, addr, val, numBytes = 1): """Convenience method. Oftentimes we need to set a range of registers to represent an int. This method will autom...
if not isinstance(val, int): raise ValueError("val must be an int. You provided: %s" % str(val)) buf = [] for i in range(numBytes): buf.append(cast_to_byte(val >> 8 * i)) self.set_register(addr, buf)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_reset(self): """Checks the grizzly to see if it reset itself because of voltage sag or other reasons. Useful to reinitialize acceleration or current limi...
currentTime = self._read_as_int(Addr.Uptime, 4) if currentTime <= self._ticks: self._ticks = currentTime return True self._ticks = currentTime 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 limit_current(self, curr): """Sets the current limit on the Grizzly. The units are in amps. The internal default value is 5 amps."""
if curr <= 0: raise ValueError("Current limit must be a positive number. You provided: %s" % str(curr)) current = int(curr * (1024.0 / 5.0) * (66.0 / 1000.0)) self._set_as_int(Addr.CurrentLimit, current, 2)
<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_pid(self, kp, ki, kd): """Sets the PID constants for the PID modes. Arguments are all floating point numbers."""
p, i, d = map(lambda x: int(x * (2 ** 16)), (kp, ki, kd)) self._set_as_int(Addr.PConstant, p, 4) self._set_as_int(Addr.IConstant, i, 4) self._set_as_int(Addr.DConstant, d, 4)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_pid_constants(self): """Reads back the PID constants stored on the Grizzly."""
p = self._read_as_int(Addr.PConstant, 4) i = self._read_as_int(Addr.IConstant, 4) d = self._read_as_int(Addr.DConstant, 4) return map(lambda x: x / (2 ** 16), (p, i, 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 getReposPackageFolder(): """Returns the folder the package is located in."""
libdir = sysconfig.get_python_lib() repodir = os.path.join(libdir, "calcrepo", "repos") return repodir
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replaceNewlines(string, newlineChar): """There's probably a way to do this with string functions but I was lazy. Replace all instances of \r or \n in a st...
if newlineChar in string: segments = string.split(newlineChar) string = "" for segment in segments: string += segment return string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getScriptLocation(): """Helper function to get the location of a Python file."""
location = os.path.abspath("./") if __file__.rfind("/") != -1: location = __file__[:__file__.rfind("/")] return location
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_param(key, val): """ Parse the query param looking for sparse fields params Ensure the `val` or what will become the sparse fields is always an array....
regex = re.compile(r'fields\[([A-Za-z]+)\]') match = regex.match(key) if match: if not isinstance(val, list): val = val.split(',') fields = [field.lower() for field in val] rtype = match.groups()[0].lower() return rtype, 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 _validate_param(rtype, fields): """ Ensure the sparse fields exists on the models """
try: # raises ValueError if not found model = rtype_to_model(rtype) model_fields = model.all_fields except ValueError: raise InvalidQueryParams(**{ 'detail': 'The fields query param provided with a ' 'field type of "%s" is unknown.' % rtype, ...
<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(req, model): # pylint: disable=unused-argument """ Determine the sparse fields to limit the response to Return a dict where the key is the resource type...
params = {} for key, val in req.params.items(): try: rtype, fields = _parse_param(key, val) params[rtype] = fields except TypeError: continue if params: _validate_req(req) for rtype, fields in params.items(): _validate_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 query_mxrecords(self): """ Looks up for the MX DNS records of the recipient SMTP server """
import dns.resolver logging.info('Resolving DNS query...') answers = dns.resolver.query(self.domain, 'MX') addresses = [answer.exchange.to_text() for answer in answers] logging.info( '{} records found:\n{}'.format( len(addresses), '\n '.join(addresse...
<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): """ Attempts the delivery through recipient's domain MX records. """
try: for mx in self.mxrecords: logging.info('Connecting to {} {}...'.format(mx, self.port)) server = smtplib.SMTP(mx, self.port) server.set_debuglevel(logging.root.level < logging.WARN) server.sendmail( self.sender,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dispatch(self, requestProtocol, requestPayload): """ Dispatch the request to the appropriate handler. :param requestProtocol: <AbstractApplicationInterfacePr...
# method decoding method = requestPayload["method"].split(".") if len(method) != 3: requestProtocol.failRequestWithErrors(["InvalidMethod"]) return # parsing method name methodModule = method[0] methodController = method[1] methodAction =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare(self, configuration_folder, args_dict, environment): """Make a temporary configuration file from the files in our folder"""
self.configuration_folder = configuration_folder if not os.path.isdir(configuration_folder): raise BadOption("Specified configuration folder is not a directory!", wanted=configuration_folder) available = [os.path.join(configuration_folder, name) for name in os.listdir(configuration_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extra_prepare_after_activation(self, configuration, args_dict): """Setup our connection to amazon"""
aws_syncr = configuration['aws_syncr'] configuration["amazon"] = Amazon(configuration['aws_syncr'].environment, configuration['accounts'], debug=aws_syncr.debug, dry_run=aws_syncr.dry_run)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_configuration(self, configuration, collect_another_source, done, result, src): """Used to add a file to the configuration, result here is the yaml.load o...
if "includes" in result: for include in result["includes"]: collect_another_source(include) configuration.update(result, source=src)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def template_name_from_class_name(class_name): """ Remove the last 'Template' in the name. """
suffix = 'Template' output = class_name if (class_name.endswith(suffix)): output = class_name[:-len(suffix)] return 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 run_list(): """ Print the list of all available templates. """
term = TerminalView() term.print_info("These are the available templates:") import pkgutil, projy.templates pkgpath = os.path.dirname(projy.templates.__file__) templates = [name for _, name, _ in pkgutil.iter_modules([pkgpath])] for name in templates: # the father of all templates, not ...
<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_info(template): """ Print information about a specific template. """
template.project_name = 'TowelStuff' # fake project name, always the same name = template_name_from_class_name(template.__class__.__name__) term = TerminalView() term.print_info("Content of template {} with an example project " \ "named 'TowelStuff':".format(term.text_in_color(name, TERM_GREE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def template_class_from_name(name): """ Return the template class object from agiven name. """
# import the right template module term = TerminalView() template_name = name + 'Template' try: __import__('projy.templates.' + template_name) template_mod = sys.modules['projy.templates.' + template_name] except ImportError: term.print_error_and_exit("Unable to find {}".for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def iteration_length(N, start=0, step=1): '''Return the number of iteration steps over a list of length N, starting at index start, proceeding step elements at a time. ''' if N < 0: raise ValueError('N cannot be negative') if start < 0: start += N if start < 0: raise...
<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, **kwargs): ''' Run all benchmarks. Extras kwargs are passed to benchmarks construtors. ''' self.report_start() for bench in self.benchmarks: bench = bench(before=self.report_before_method, after=self.report_after_method, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_module(self, filename): '''Load a benchmark module from file''' if not isinstance(filename, string_types): return filename basename = os.path.splitext(os.path.basename(filename))[0] basename = basename.replace('.bench', '') modulename = 'benchmarks.{0}'.forma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_from_module(self, module): '''Load all benchmarks from a given module''' benchmarks = [] for name in dir(module): obj = getattr(module, name) if (inspect.isclass(obj) and issubclass(obj, Benchmark) and obj != Benchmark): benchm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def boundingBox(booleanArray): """ return indices of the smallest bounding box enclosing all non-zero values within an array (slice(1, 3, None), slice(0, 3, None...
w = np.where(booleanArray) p = [] for i in w: if len(i): p.append(slice(i.min(), i.max())) else: p.append(slice(0, 0)) # return None return tuple(p)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def FromMessageGetSimpleElementDeclaration(message): '''If message consists of one part with an element attribute, and this element is a simpleType return a string representing the python type, else return None. ''' assert isinstance(message, WSDLTools.Message), 'expecting WSDLTools.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 getAttributeName(self, name): '''represents the aname ''' if self.func_aname is None: return name assert callable(self.func_aname), \ 'expecting callable method for attribute func_aname, not %s' %type(self.func_aname) f = self.func_aname 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 getPyClass(self): '''Name of generated inner class that will be specified as pyclass. ''' # --> EXTENDED if self.hasExtPyClass(): classInfo = self.extPyClasses[self.name] return ".".join(classInfo) # <-- return 'Holder'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getPyClassDefinition(self): '''Return a list containing pyclass definition. ''' kw = KW.copy() # --> EXTENDED if self.hasExtPyClass(): classInfo = self.extPyClasses[self.name] kw['classInfo'] = classInfo[0] return ["%(ID3)simport %...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def nsuriLogic(self): '''set a variable "ns" that represents the targetNamespace in which this item is defined. Used for namespacing local elements. ''' if self.parentClass: return 'ns = %s.%s.schema' %(self.parentClass, self.getClassName()) return 'ns = %s.%s.schema...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _getOccurs(self, e): '''return a 3 item tuple ''' minOccurs = maxOccurs = '1' nillable = True return minOccurs,maxOccurs,nillable
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getAttributeNames(self): '''returns a list of anames representing the parts of the message. ''' return map(lambda e: self.getAttributeName(e.name), self.tcListElements)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _setContent(self): '''GED defines element name, so also define typecode aname ''' kw = KW.copy() try: kw.update(dict(klass=self.getClassName(), element='ElementDeclaration', literal=self.literalTag(), su...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _resolve_model(obj): """ Resolve supplied `obj` to a Django model class. `obj` must be a Django model class itself, or a string representation of one. Useful...
if isinstance(obj, six.string_types) and len(obj.split('.')) == 2: app_name, model_name = obj.split('.') resolved_model = apps.get_model(app_name, model_name) if resolved_model is None: msg = "Django did not return a model for {0}.{1}" raise ImproperlyConfigured(msg....
<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_abstract_model(model): """ Given a model class, returns a boolean True if it is abstract and False if it is not. """
return hasattr(model, '_meta') and hasattr(model._meta, 'abstract') and model._meta.abstract
<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): """ Queues all services to be polled. Should be run via beat. """
services = Service.objects.all() for service in services: poll_service.apply_async(kwargs={"service_id": str(service.id)}) return "Queued <%s> Service(s) for Polling" % services.count()
<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, service_id, user_id, email, **kwargs): """ Create and Retrieve a token from remote service. Save to DB. """
log = self.get_logger(**kwargs) log.info("Loading Service for token creation") try: service = Service.objects.get(id=service_id) log.info("Getting token for <%s> on <%s>" % (email, service.name)) response = self.create_token(service.url, email, service.token...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ Queues all services to be polled for metrics. Should be run via beat. """
services = Service.objects.all() for service in services: service_metric_sync.apply_async( kwargs={"service_id": str(service.id)}) key = "services.downtime.%s.sum" % ( utils.normalise_string(service.name)) check = WidgetData.objects....
<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, service_id, **kwargs): """ Retrieve a list of metrics. Ensure they are set as metric data sources. """
log = self.get_logger(**kwargs) log.info("Loading Service for metric sync") try: service = Service.objects.get(id=service_id) log.info("Getting metrics for <%s>" % (service.name)) metrics = self.get_metrics(service.url, service.token) result = me...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def end_timing(self): """ Ends timing of an execution block, calculates elapsed time and updates the associated counter. """
if self._callback != None: elapsed = time.perf_counter() * 1000 - self._start self._callback.end_timing(self._counter, elapsed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prune_directory(self): """Delete any objects that can be loaded and are expired according to the current lifetime setting. A file will be deleted if the foll...
glob = '*.{ext}'.format(ext=self.backend.file_extension) totalsize = 0 totalnum = 0 for f in self._path.glob(glob): filesize = f.stat().st_size key_hash = f.stem in_cache = key_hash in self._cache try: self._get_obj_from_ha...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync(self): """Commit deferred writes to file."""
for key_hash, obj in six.iteritems(self._cache): # Objects are checked for expiration in __getitem__, # but we can check here to avoid unnecessary writes. if not obj.has_expired(): file_path = self._path_for_hash(key_hash) with open(str(file_p...
<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_url(self, resource, params=None): """ Generate url for request """
# replace placeholders pattern = r'\{(.+?)\}' resource = re.sub(pattern, lambda t: str(params.get(t.group(1), '')), resource) # build url parts = (self.endpoint, '/api/', resource) return '/'.join(map(lambda x: str(x).strip('/'), parts))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request(self, method, resource, params=None): """ Make request to the server and parse response """
url = self.get_url(resource, params) # headers headers = { 'Content-Type': 'application/json' } auth = requests.auth.HTTPBasicAuth(self.username, self.password) # request log.info('Request to %s. Data: %s' % (url, params)) response = re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modify_attached_policies(self, role_name, new_policies): """Make sure this role has just the new policies"""
parts = role_name.split('/', 1) if len(parts) == 2: prefix, name = parts prefix = "/{0}/".format(prefix) else: prefix = "/" name = parts[0] current_attached_policies = [] with self.ignore_missing(): current_attached_po...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assume_role_credentials(self, arn): """Return the environment variables for an assumed role"""
log.info("Assuming role as %s", arn) # Clear out empty values for name in ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SECURITY_TOKEN', 'AWS_SESSION_TOKEN']: if name in os.environ and not os.environ[name]: del os.environ[name] sts = self.amazon.sessi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _validate_token(self): ''' a method to validate active access token ''' title = '%s._validate_token' % self.__class__.__name__ # construct access token url import requests url = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % self.access_...
<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_id(self, file_path): ''' a helper method for retrieving id of file or folder ''' title = '%s._get_id' % self.__class__.__name__ # construct request kwargs list_kwargs = { 'spaces': self.drive_space, 'fields': 'files(id, parents)' ...
<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_space(self): ''' a helper method to retrieve id of drive space ''' title = '%s._space_id' % self.__class__.__name__ list_kwargs = { 'q': "'%s' in parents" % self.drive_space, 'spaces': self.drive_space, 'fields': 'files(name, parents...
<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_data(self, file_id): ''' a helper method for retrieving the byte data of a file ''' title = '%s._get_data' % self.__class__.__name__ # request file data try: record_data = self.drive.get_media(fileId=file_id).execute() except: r...
<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_metadata(self, file_id, metadata_fields=''): ''' a helper method for retrieving the metadata of a file ''' title = '%s._get_metadata' % self.__class__.__name__ # construct fields arg if not metadata_fields: metadata_fields = ','.join(self.objec...
<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_directory(self, folder_id=''): ''' a generator method for listing the contents of a directory ''' title = '%s._list_directory' % self.__class__.__name__ # construct default response file_list = [] # construct request kwargs list_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 _walk(self, root_path='', root_id=''): ''' a generator method which walks the file structure of the dropbox collection ''' title = '%s._walk' % self.__class__.__name__ if root_id: pass elif root_path: root_id, root_parent = self._get...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load(self, record_key, secret_key=''): ''' a method to retrieve byte data of appdata record :param record_key: string with name of record :param secret_key: [optional] string used to decrypt data :return: byte data for record body ''' title = '%s.load'...
<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(self, prefix='', delimiter='', filter_function=None, max_results=1, previous_key=''): ''' a method to list keys in the google drive collection :param prefix: string with prefix value to filter results :param delimiter: string with value which results must not cont...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delete(self, record_key): ''' a method to delete a file :param record_key: string with name of file :return: string reporting outcome ''' title = '%s.delete' % self.__class__.__name__ # validate inputs input_fields = { 'record_key': record_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 remove(self): ''' a method to remove all records in the collection NOTE: this method removes all the files in the collection, but the collection folder itself created by oauth2 cannot be removed. only the user can remove access to the app fold...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_message(self): """Try to read a message from the buffered data. A message is defined as a 32-bit integer size, followed that number of bytes. First we t...
with self.__class__.__locker: result = self.__passive_read(4) if result is None: return None (four_bytes, last_buffer_index, updates1) = result (length,) = unpack('>I', four_bytes) result = self.__passive_read(length, last_buffer_in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __cleanup(self): """Clip buffers that the top of our list that have been completely exhausted. """
# TODO: Test this. with self.__class__.__locker: while self.__read_buffer_index > 0: del self.__buffers[0] self.__read_buffer_index -= 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 ls(dataset_uri): """ List the overlays in the dataset. """
dataset = dtoolcore.DataSet.from_uri(dataset_uri) for overlay_name in dataset.list_overlay_names(): click.secho(overlay_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 show(dataset_uri, overlay_name): """ Show the content of a specific overlay. """
dataset = dtoolcore.DataSet.from_uri(dataset_uri) try: overlay = dataset.get_overlay(overlay_name) except: # NOQA click.secho( "No such overlay: {}".format(overlay_name), fg="red", err=True ) sys.exit(11) formatted_json = json.dumps(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def canonicalize_header(key): """Returns the canonicalized header name for the header name provided as an argument. The canonicalized header name according to th...
bits = key.split('-') for idx, b in enumerate(bits): bits[idx] = b.capitalize() return '-'.join(bits)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self): """Validates the URL object. The URL object is invalid if it does not represent an absolute URL. Returns True or False based on this. """
if (self.scheme is None or self.scheme != '') \ and (self.host is None or self.host == ''): return False 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 request_uri(self): """Returns the request URL element of the URL. This request URL is the path, the query and the fragment appended as a relative URL to the ...
result = '/{0}'.format(self.path.lstrip('/')) if self.query is not None and self.query != '' and self.query != {}: result += '?{0}'.format(self.encoded_query()) if self.fragment is not None and self.fragment != '': result += '#{0}'.format(self.fragment) return re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encoded_query(self): """Returns the encoded query string of the URL. This may be different from the rawquery element, as that contains the query parsed by ur...
if self.query is not None and self.query != '' and self.query != {}: try: return urlencode(self.query, doseq=True, quote_via=urlquote) except TypeError: return '&'.join(["{0}={1}".format(urlquote(k), urlquote(self.query[k][0])) for k in self.query]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def with_url(self, url): """Sets the request's URL and returns the request itself. Automatically sets the Host header according to the URL. Keyword arguments: ur...
self.url = URL(url) self.header["Host"] = self.url.host return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def with_headers(self, headers): """Sets multiple headers on the request and returns the request itself. Keyword arguments: headers -- a dict-like object which c...
for key, value in headers.items(): self.with_header(key, value) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def with_body(self, body): # @todo take encoding into account """Sets the request body to the provided value and returns the request itself. Keyword arguments: b...
try: self.body = body.encode('utf-8') except: try: self.body = bytes(body) except: raise ValueError("Request body must be a string or bytes-like object.") hasher = hashlib.sha256() hasher.update(self.body) diges...
<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_header(self, key): """Returns the requested header, or an empty string if the header is not set. Keyword arguments: key -- The header name. It will be ca...
key = canonicalize_header(key) if key in self.header: return self.header[key] return ''
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do(self): """Executes the request represented by this object. The requests library will be used for this purpose. Returns an instance of requests.Response. "...
data = None if self.body is not None and self.body != b'': data = self.body return requests.request(self.method, str(self.url), data=data, headers=self.header)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setWriteToShell(self, writeToShell=True): """connect sysout to the qtSignal"""
if writeToShell and not self._connected: self.message.connect(self.stdW) self._connected = True elif not writeToShell and self._connected: try: self.message.disconnect(self.stdW) except TypeError: pass # was not co...
<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_app(self, appname): """ returns app object or None """
try: app = APPS.get_app_config(appname) except Exception as e: self.err(e) return return app
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_model(self, appname, modelname): """ return model or None """
app = self._get_app(appname) models = app.get_models() model = None for mod in models: if mod.__name__ == modelname: model = mod return model msg = "Model " + modelname + " not found"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _count_model(self, model): """ return model count """
try: res = model.objects.all().count() except Exception as e: self.err(e) return 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 find_setup_file_name(self): # type: () ->None """ Usually setup.py or setup """
for file_path in [ x for x in os.listdir(".") if os.path.isfile(x) and x in ["setup.py", "setup"] ]: if self.file_opener.is_python_inside(file_path): self.setup_file_name = file_path break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clause_tokenize(sentence): """ Split on comma or parenthesis, if there are more then three words for each clause ['While I was walking home,', ' this bird fe...
clause_re = re.compile(r'((?:\S+\s){2,}\S+,|(?:\S+\s){3,}(?=\((?:\S+\s){2,}\S+\)))') clause_stem = clause_re.sub(r'\1###clausebreak###', sentence) return [c for c in clause_stem.split('###clausebreak###') if 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 word_tokenize(sentence): """ A generator which yields tokens based on the given sentence without deleting anything. ['I', ' ', 'love', ' ', 'you', '.', ' ', ...
date_pattern = r'\d\d(\d\d)?[\\-]\d\d[\\-]\d\d(\d\d)?' number_pattern = r'[\+-]?(\d+\.\d+|\d{1,3},(\d{3},)*\d{3}|\d+)' arr_pattern = r'(?: \w\.){2,3}|(?:\A|\s)(?:\w\.){2,3}|[A-Z]\. [a-z]' word_pattern = r'[\w]+' non_space_pattern = r'[{}]|\w'.format(re.escape('!"#$%&()*,./:;<=>?@[\]^_-`{|}~')) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def slim_stem(token): """ A very simple stemmer, for entity of GO stemming. 'interact' """
target_sulfixs = ['ic', 'tic', 'e', 'ive', 'ing', 'ical', 'nal', 'al', 'ism', 'ion', 'ation', 'ar', 'sis', 'us', 'ment'] for sulfix in sorted(target_sulfixs, key=len, reverse=True): if token.endswith(sulfix): token = token[0:-len(sulfix)] break if token.endswith('ll'): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ngram(n, iter_tokens): """ Return a generator of n-gram from an iterable """
z = len(iter_tokens) return (iter_tokens[i:i+n] for i in range(z-n+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_overcloud_passwords(self, parameters, parsed_args): """Add passwords to the parameters dictionary :param parameters: A dictionary for the passwords to be...
undercloud_ceilometer_snmpd_password = utils.get_config_value( "auth", "undercloud_ceilometer_snmpd_password") self.passwords = passwords = utils.generate_overcloud_passwords() ceilometer_pass = passwords['OVERCLOUD_CEILOMETER_PASSWORD'] ceilometer_secret = passwords['OVER...
<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_stack(self, orchestration_client, stack_name): """Get the ID for the current deployed overcloud stack if it exists."""
try: stack = orchestration_client.stacks.get(stack_name) self.log.info("Stack found, will be doing a stack update") return stack except HTTPNotFound: self.log.info("No stack found, will be doing a stack create")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _heat_deploy(self, stack, stack_name, template_path, parameters, environments, timeout): """Verify the Baremetal nodes are available and do a stack update"""
self.log.debug("Processing environment files") env_files, env = ( template_utils.process_multiple_environments_and_files( environments)) self.log.debug("Getting template contents") template_files, template = template_utils.get_template_contents( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pre_heat_deploy(self): """Setup before the Heat stack create or update has been done."""
clients = self.app.client_manager compute_client = clients.compute self.log.debug("Checking hypervisor stats") if utils.check_hypervisor_stats(compute_client) is None: raise exceptions.DeploymentError( "Expected hypervisor stats not met") 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 _deploy_tripleo_heat_templates(self, stack, parsed_args): """Deploy the fixed templates in TripleO Heat Templates"""
clients = self.app.client_manager network_client = clients.network parameters = self._update_paramaters( parsed_args, network_client, stack) utils.check_nodes_count( self.app.client_manager.rdomanager_oscplugin.baremetal(), stack, parame...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def well_fields(self, well_x=1, well_y=1): """All ScanFieldData elements of given well. Parameters well_x : int well_y : int Returns ------- list of lxml.objecti...
xpath = './ScanFieldArray/ScanFieldData' xpath += _xpath_attrib('WellX', well_x) xpath += _xpath_attrib('WellY', well_y) return self.root.findall(xpath)