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 generate(self, overwrite=False): """Generate service files and returns a list of them. Note that env var names will be capitalized using a Jinja filter. This is template dependent. Even though a param might be named `key` and have value `value`, it will be rendered as `KEY=value`. We retrieve the names of the template files and see the paths where the generated files will be deployed. These are files a user can just take and use. If the service is also installed, those files will be moved to the relevant location on the system. Note that the parameters required to generate the file are propagated automatically which is why we don't pass them explicitly to the generating function. `self.template_prefix` and `self.generate_into_prefix` are set in `base.py` `self.files` is an automatically generated list of the files that were generated during the process. It should be returned so that the generated files could be printed out for the user. """
super(SystemD, self).generate(overwrite=overwrite) self._validate_init_system_specific_params() svc_file_template = self.template_prefix + '.service' env_file_template = self.template_prefix self.svc_file_path = self.generate_into_prefix + '.service' self.env_file_path = self.generate_into_prefix self.generate_file_from_template(svc_file_template, self.svc_file_path) self.generate_file_from_template(env_file_template, self.env_file_path) return self.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 install(self): """Install the service on the local machine This is where we deploy the service files to their relevant locations and perform any other required actions to configure the service and make it ready to be `start`ed. """
super(SystemD, self).install() self.deploy_service_file(self.svc_file_path, self.svc_file_dest) self.deploy_service_file(self.env_file_path, self.env_file_dest) sh.systemctl.enable(self.name) sh.systemctl('daemon-reload')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self): """Stop the service. """
try: sh.systemctl.stop(self.name) except sh.ErrorReturnCode_5: self.logger.debug('Service not running.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uninstall(self): """Uninstall the service. This is supposed to perform any cleanup operations required to remove the service. Files, links, whatever else should be removed. This method should also run when implementing cleanup in case of failures. As such, idempotence should be considered. """
sh.systemctl.disable(self.name) sh.systemctl('daemon-reload') if os.path.isfile(self.svc_file_dest): os.remove(self.svc_file_dest) if os.path.isfile(self.env_file_dest): os.remove(self.env_file_dest)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def status(self, name=''): """Return a list of the statuses of the `name` service, or if name is omitted, a list of the status of all services for this specific init system. There should be a standardization around the status fields. There currently isn't. `self.services` is set in `base.py` """
super(SystemD, self).status(name=name) svc_list = sh.systemctl('--no-legend', '--no-pager', t='service') svcs_info = [self._parse_service_info(svc) for svc in svc_list] if name: names = (name, name + '.service') # return list of one item for specific service svcs_info = [s for s in svcs_info if s['name'] in names] self.services['services'] = svcs_info return self.services
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort(self, *sort): """ Sort the results. Define how the results should be sorted. The arguments should be tuples of string defining the key and direction to sort by. For example `('name', 'asc')` and `('version', 'desc')`. The first sorte rule is considered first by the API. See also the API documentation on `sorting`_. Arguments: `*sort` (`tuple`) The rules to sort by .. _sorting: https://github.com/XereoNet/SpaceGDN/wiki/API#sorting """
self.add_get_param('sort', FILTER_DELIMITER.join( [ELEMENT_DELIMITER.join(elements) for elements in sort])) 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 where(self, *where): """ Filter the results. Filter the results by provided rules. The rules should be tuples that look like this:: ('<key>', '<operator>', '<value>') For example:: ('name', '$eq', 'Vanilla Minecraft') This is also covered in the documentation_ of the SpaceGDN API. .. _documentation: https://github.com/XereoNet/SpaceGDN/wiki/API#where """
filters = list() for key, operator, value in where: filters.append(ELEMENT_DELIMITER.join((key, operator, value))) self.add_get_param('where', FILTER_DELIMITER.join(filters)) 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 fetch(self): """ Run the request and fetch the results. This method will compile the request, send it to the SpaceGDN endpoint defined with the `SpaceGDN` object and wrap the results in a :class:`pyspacegdn.Response` object. Returns a :class:`pyspacegdn.Response` object. """
response = Response() has_next = True while has_next: resp = self._fetch(default_path='v2') results = None if resp.success: results = resp.data['results'] self.add_get_param('page', resp.data['pagination']['page'] + 1) has_next = resp.data['pagination']['has_next'] response.add(results, resp.status_code, resp.status_reason) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def singleton(cls): """ Decorator function that turns a class into a singleton. """
import inspect # Create a structure to store instances of any singletons that get # created. instances = {} # Make sure that the constructor for this class doesn't take any # arguments. Since singletons can only be instantiated once, it doesn't # make any sense for the constructor to take arguments. If the class # doesn't implement its own constructor, don't do anything. This case is # considered specially because it causes a TypeError in python 3.3 but not # in python 3.4. if cls.__init__ is not object.__init__: argspec = inspect.getfullargspec(cls.__init__) if len(argspec.args) != 1 or argspec.varargs or argspec.varkw: raise TypeError("Singleton classes cannot accept arguments to the constructor.") def get_instance(): """ Creates and returns the singleton object. This function is what gets returned by this decorator. """ # Check to see if an instance of this class has already been # instantiated. If it hasn't, create one. The `instances` structure # is technically a global variable, so it will be preserved between # calls to this function. if cls not in instances: instances[cls] = cls() # Return a previously instantiated object of the requested type. return instances[cls] # Return the decorator function. return get_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 from_dict(doc): """Create a model output file object from a dictionary. """
if 'path' in doc: path = doc['path'] else: path = None return ModelOutputFile( doc['filename'], doc['mimeType'], path=path )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_dict(doc): """Create a model output object from a dictionary. """
return ModelOutputs( ModelOutputFile.from_dict(doc['prediction']), [ModelOutputFile.from_dict(a) for a in doc['attachments']] )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(self, model): """Create a dictionary serialization for a model. Parameters model : ModelHandle Returns ------- dict Dictionary serialization for a model """
# Get the basic Json object from the super class obj = super(ModelRegistry, self).to_dict(model) # Add model parameter obj['parameters'] = [ para.to_dict() for para in model.parameters ] obj['outputs'] = model.outputs.to_dict() obj['connector'] = model.connector return 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 _snake_to_camel(name, strict=False): """Converts parameter names from snake_case to camelCase. Args: name, str. Snake case. strict: bool, default True. If True, will set name to lowercase before converting, otherwise assumes original name is proper camel case. Set to False if name may already be in camelCase. Returns: str: CamelCase. """
if strict: name = name.lower() terms = name.split('_') return terms[0] + ''.join([term.capitalize() for term in terms[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_default_attr(self, default_attr): """Sets default attributes when None. Args: default_attr: dict. Key-val of attr, default-value. """
for attr, val in six.iteritems(default_attr): if getattr(self, attr, None) is None: setattr(self, attr, 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 to_json(self, drop_null=True, camel=False, indent=None, sort_keys=False): """Serialize self as JSON Args: drop_null: bool, default True. Remove 'empty' attributes. See to_dict. camel: bool, default True. Convert keys to camelCase. indent: int, default None. See json built-in. sort_keys: bool, default False. See json built-in. Return: str: object params. """
return json.dumps(self.to_dict(drop_null, camel), indent=indent, sort_keys=sort_keys)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(self, drop_null=True, camel=False): """Serialize self as dict. Args: drop_null: bool, default True. Remove 'empty' attributes. camel: bool, default True. Convert keys to camelCase. Return: dict: object params. """
#return _to_dict(self, drop_null, camel) def to_dict(obj, drop_null, camel): """Recursively constructs the dict.""" if isinstance(obj, (Body, BodyChild)): obj = obj.__dict__ if isinstance(obj, dict): data = {} for attr, val in six.iteritems(obj): if camel: attr = _snake_to_camel(attr) valid_null = (isinstance(val, bool) or val == 0 or (val and to_dict(val, drop_null, camel))) if not drop_null or (drop_null and valid_null): data[attr] = to_dict(val, drop_null, camel) return data elif isinstance(obj, list): data = [] for val in obj: valid_null = (isinstance(val, bool) or val == 0 or (val and to_dict(val, drop_null, camel))) if not drop_null or (drop_null and valid_null): data.append(to_dict(val, drop_null, camel)) return data else: return obj return to_dict(self, drop_null, camel)
<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(self, body): """Parse JSON request, storing content in object attributes. Args: body: str. HTTP request body. Returns: self """
if isinstance(body, six.string_types): body = json.loads(body) # version version = body['version'] self.version = version # session session = body['session'] self.session.new = session['new'] self.session.session_id = session['sessionId'] application_id = session['application']['applicationId'] self.session.application.application_id = application_id if 'attributes' in session and session['attributes']: self.session.attributes = session.get('attributes', {}) else: self.session.attributes = {} self.session.user.user_id = session['user']['userId'] self.session.user.access_token = session['user'].get('accessToken', 0) # request request = body['request'] # launch request if request['type'] == 'LaunchRequest': self.request = LaunchRequest() # intent request elif request['type'] == 'IntentRequest': self.request = IntentRequest() self.request.intent = Intent() intent = request['intent'] self.request.intent.name = intent['name'] if 'slots' in intent and intent['slots']: for name, slot in six.iteritems(intent['slots']): self.request.intent.slots[name] = Slot() self.request.intent.slots[name].name = slot['name'] self.request.intent.slots[name].value = slot.get('value') # session ended request elif request['type'] == 'SessionEndedRequest': self.request = SessionEndedRequest() self.request.reason = request['reason'] # common - keep after specific requests to prevent param overwrite self.request.type = request['type'] self.request.request_id = request['requestId'] self.request.timestamp = request['timestamp'] 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 set_speech_text(self, text): """Set response output speech as plain text type. Args: text: str. Response speech used when type is 'PlainText'. Cannot exceed 8,000 characters. """
self.response.outputSpeech.type = 'PlainText' self.response.outputSpeech.text = text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_speech_ssml(self, ssml): """Set response output speech as SSML type. Args: ssml: str. Response speech used when type is 'SSML', should be formatted with Speech Synthesis Markup Language. Cannot exceed 8,000 characters. """
self.response.outputSpeech.type = 'SSML' self.response.outputSpeech.ssml = ssml
<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_card_simple(self, title, content): """Set response card as simple type. title and content cannot exceed 8,000 characters. Args: title: str. Title of Simple or Standard type card. content: str. Content of Simple type card. """
self.response.card.type = 'Simple' self.response.card.title = title self.response.card.content = content
<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_card_standard(self, title, text, smallImageUrl=None, largeImageUrl=None): """Set response card as standard type. title, text, and image cannot exceed 8,000 characters. Args: title: str. Title of Simple or Standard type card. text: str. Content of Standard type card. smallImageUrl: str. URL of small image. Cannot exceed 2,000 characters. Recommended pixel size: 720w x 480h. largeImageUrl: str. URL of large image. Cannot exceed 2,000 characters. Recommended pixel size: 1200w x 800h. """
self.response.card.type = 'Standard' self.response.card.title = title self.response.card.text = text if smallImageUrl: self.response.card.image.smallImageUrl = smallImageUrl if largeImageUrl: self.response.card.image.largeImageUrl = largeImageUrl
<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_reprompt_text(self, text): """Set response reprompt output speech as plain text type. Args: text: str. Response speech used when type is 'PlainText'. Cannot exceed 8,000 characters. """
self.response.reprompt.outputSpeech.type = 'PlainText' self.response.reprompt.outputSpeech.text = text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_reprompt_ssml(self, ssml): """Set response reprompt output speech as SSML type. Args: ssml: str. Response speech used when type is 'SSML', should be formatted with Speech Synthesis Markup Language. Cannot exceed 8,000 characters. """
self.response.reprompt.outputSpeech.type = 'SSML' self.response.reprompt.outputSpeech.ssml = ssml
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def flush(self): ''' Flushes the buffer to socket. Only call when the write is done. Calling flush after each write will prevent the buffer to act as efficiently as possible ''' # return if empty if self.__bufferidx == 0: return # send here the data self.conn.send("%s\r\n" % hex(self.__bufferidx)[2:]) self.conn.send("%s\r\n" % ''.join(self.__buffer[0:self.__bufferidx])) # reset buffer index = 0 (beginning of the buffer) self.__bufferidx = 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 close(self): ''' Closes the stream to output. It destroys the buffer and the buffer pointer. However, it will not close the the client connection ''' #write all that is remained in buffer self.flush() # delete buffer self.__buffer = None #reset buffer index to -1 to indicate no where self.__bufferidx = -1 #writing the final empty chunk to the socket # send here the data self.conn.send("0\r\n") self.conn.send("\r\n" ) #set closed flag self.__closed = 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 create_ui(self): ''' Create UI elements and connect signals. ''' box = Gtk.Box() rotate_left = Gtk.Button('Rotate left') rotate_right = Gtk.Button('Rotate right') flip_horizontal = Gtk.Button('Flip horizontal') flip_vertical = Gtk.Button('Flip vertical') reset = Gtk.Button('Reset') load = Gtk.Button('Load...') save = Gtk.Button('Save...') rotate_left.connect('clicked', lambda *args: self.rotate_left()) rotate_right.connect('clicked', lambda *args: self.rotate_right()) flip_horizontal.connect('clicked', lambda *args: self.flip_horizontal()) flip_vertical.connect('clicked', lambda *args: self.flip_vertical()) reset.connect('clicked', lambda *args: self.reset()) load.connect('clicked', lambda *args: GObject.idle_add(self.load)) save.connect('clicked', lambda *args: GObject.idle_add(self.save)) for b in (rotate_left, rotate_right, flip_horizontal, flip_vertical, reset, load, save): box.pack_start(b, False, False, 0) box.show_all() self.widget.pack_start(box, False, False, 0) if self.warp_actor.parent_corners is None: for b in (rotate_left, rotate_right, flip_horizontal, flip_vertical, reset, load, save): b.set_sensitive(False) def check_init(): if self.warp_actor.parent_corners is not None: for b in (rotate_left, rotate_right, flip_horizontal, flip_vertical, reset, load, save): b.set_sensitive(True) return False return True GObject.timeout_add(100, check_init)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def save(self): ''' Save warp projection settings to HDF file. ''' response = pu.open(title='Save perspective warp', patterns=['*.h5']) if response is not None: self.warp_actor.save(response)
<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): ''' Load warp projection settings from HDF file. ''' response = pu.open(title='Load perspective warp', patterns=['*.h5']) if response is not None: self.warp_actor.load(response)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simple_logger(**kwargs): """ Creates a simple logger :param int base_level: Lowest level allowed to log (Default: DEBUG) :param str log_format: Logging format used for STDOUT (Default: logs.FORMAT) :param bool should_stdout: Allows to log to stdout (Default: True) :param int stdout_level: Lowest level allowed to log to STDOUT (Default: DEBUG) :param bool should_http: Allows to log to HTTP server :param int http_level: Lowest level allowed to log to the HTTP server (Has to be superior or equals to base_level) :param str http_host: Address of the HTTP Server :param str http_url: Url of the HTTP Server """
# Args logger_name = kwargs.get('name') base_level = kwargs.get('base_level', logging.DEBUG) should_stdout = kwargs.get('should_stdout', True) should_http = kwargs.get('should_http', False) # Generate base logger logger = logging.getLogger(logger_name) logger.setLevel(base_level) # Define stdout handler if should_stdout: logger.addHandler(_add_stream_handler(**kwargs)) if should_http: logger.addHandler(_add_http_handler(**kwargs)) return logger
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare_dicts(d1, d2): """ Returns a diff string of the two dicts. """
a = json.dumps(d1, indent=4, sort_keys=True) b = json.dumps(d2, indent=4, sort_keys=True) # stolen from cpython # https://github.com/python/cpython/blob/01fd68752e2d2d0a5f90ae8944ca35df0a5ddeaa/Lib/unittest/case.py#L1091 diff = ('\n' + '\n'.join(difflib.ndiff( a.splitlines(), b.splitlines()))) return diff
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diff_analysis(using): """ Returns a diff string comparing the analysis defined in ES, with the analysis defined in Python land for the connection `using` """
python_analysis = collect_analysis(using) es_analysis = existing_analysis(using) return compare_dicts(es_analysis, python_analysis)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_analysis(using): """ generate the analysis settings from Python land """
python_analysis = defaultdict(dict) for index in registry.indexes_for_connection(using): python_analysis.update(index._doc_type.mapping._collect_analysis()) return stringer(python_analysis)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def existing_analysis(using): """ Get the existing analysis for the `using` Elasticsearch connection """
es = connections.get_connection(using) index_name = settings.ELASTICSEARCH_CONNECTIONS[using]['index_name'] if es.indices.exists(index=index_name): return stringer(es.indices.get_settings(index=index_name)[index_name]['settings']['index'].get('analysis', {})) return DOES_NOT_EXIST
<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_analysis_compatible(using): """ Returns True if the analysis defined in Python land and ES for the connection `using` are compatible """
python_analysis = collect_analysis(using) es_analysis = existing_analysis(using) if es_analysis == DOES_NOT_EXIST: return True # we want to ensure everything defined in Python land is exactly matched in ES land for section in python_analysis: # there is an analysis section (analysis, tokenizers, filters, etc) defined in Python that isn't in ES if section not in es_analysis: return False # for this section of analysis (analysis, tokenizer, filter, etc), get # all the items defined in that section, and make sure they exist, and # are equal in Python land subdict_python = python_analysis[section] subdict_es = es_analysis[section] for name in subdict_python: # this analyzer, filter, etc isn't defined in ES if name not in subdict_es: return False # this analyzer, filter etc doesn't match what is in ES if subdict_python[name] != subdict_es[name]: 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 combined_analysis(using): """ Combine the analysis in ES with the analysis defined in Python. The one in Python takes precedence """
python_analysis = collect_analysis(using) es_analysis = existing_analysis(using) if es_analysis == DOES_NOT_EXIST: return python_analysis # we want to ensure everything defined in Python land is added, or # overrides the things defined in ES for section in python_analysis: if section not in es_analysis: es_analysis[section] = python_analysis[section] subdict_python = python_analysis[section] subdict_es = es_analysis[section] for name in subdict_python: subdict_es[name] = subdict_python[name] return es_analysis
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flaskify(response, headers=None, encoder=None): """Format the response to be consumeable by flask. The api returns mostly JSON responses. The format method converts the dicts into a json object (as a string), and the right response is returned (with the valid mimetype, charset and status.) Args: response (Response): The dictionary object to convert into a json object. If the value is a string, a dictionary is created with the key "message". headers (dict): optional headers for the flask response. encoder (Class): The class of the encoder (if any). Returns: flask.Response: The flask response with formatted data, headers, and mimetype. """
status_code = response.status data = response.errors or response.message mimetype = 'text/plain' if isinstance(data, list) or isinstance(data, dict): mimetype = 'application/json' data = json.dumps(data, cls=encoder) return flask.Response( response=data, status=status_code, headers=headers, mimetype=mimetype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self): """Ask politely, first, with SIGINT and SIGQUIT."""
if hasattr(self, 'process'): if self.process is not None: try: is_running = self.process.poll() is None except AttributeError: is_running = False if is_running: self.bundle_engine.logline("Stopping {0}".format(self.service.name)) self.term_signal_sent = True # Politely ask all child processes to die first try: for childproc in psutil.Process(self.process.pid).children(recursive=True): childproc.send_signal(signal.SIGINT) except psutil.NoSuchProcess: pass except AttributeError: pass try: self.process.send_signal(self.service.stop_signal) except OSError as e: if e.errno == 3: # No such process pass else: self.bundle_engine.warnline("{0} stopped prematurely.".format(self.service.name)) else: self.bundle_engine.warnline("{0} stopped prematurely.".format(self.service.name)) else: self.bundle_engine.warnline("{0} was never successfully started.".format(self.service.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 kill(self): """Murder the children of this service in front of it, and then murder the service itself."""
if not self.is_dead(): self.bundle_engine.warnline("{0} did not shut down cleanly, killing.".format(self.service.name)) try: if hasattr(self.process, 'pid'): for child in psutil.Process(self.process.pid).children(recursive=True): os.kill(child.pid, signal.SIGKILL) self.process.kill() except psutil.NoSuchProcess: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def cascade_delete(self, name): "this fails under diamond inheritance" for child in self[name].child_tables: self.cascade_delete(child.name) del self[name]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def create(self, ex): "helper for apply_sql in CreateX case" if ex.name in self: if ex.nexists: return raise ValueError('table_exists',ex.name) if any(c.pkey for c in ex.cols): if ex.pkey: raise sqparse2.SQLSyntaxError("don't mix table-level and column-level pkeys",ex) # todo(spec): is multi pkey permitted when defined per column? ex.pkey = sqparse2.PKeyX([c.name for c in ex.cols if c.pkey]) if ex.inherits: # todo: what if child table specifies constraints etc? this needs work. if len(ex.inherits) > 1: raise NotImplementedError('todo: multi-table inherit') parent = self[ex.inherits[0]] = copy.deepcopy(self[ex.inherits[0]]) # copy so rollback works child = self[ex.name] = table.Table(ex.name, parent.fields, parent.pkey) parent.child_tables.append(child) child.parent_table = parent else: self[ex.name]=table.Table(ex.name,ex.cols,ex.pkey.fields if ex.pkey else [])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def drop(self, ex): "helper for apply_sql in DropX case" # todo: factor out inheritance logic (for readability) if ex.name not in self: if ex.ifexists: return raise KeyError(ex.name) table_ = self[ex.name] parent = table_.parent_table if table_.child_tables: if not ex.cascade: raise table.IntegrityError('delete_parent_without_cascade',ex.name) self.cascade_delete(ex.name) else: del self[ex.name] if parent: parent.child_tables.remove(table_)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _prepare_uri(self, path, query_params={}): """ Prepares a full URI with the selected information. ``path``: Path can be in one of two formats: - If :attr:`server` was defined, the ``path`` will be appended to the existing host, or - an absolute URL ``query_params``: Used to generate a query string, which will be appended to the end of the absolute URL. Returns an absolute URL. """
query_str = urllib.urlencode(query_params) # If we have a relative path (as opposed to a full URL), build it of # the connection info if path.startswith('/') and self.server: protocol = self.protocol server = self.server else: protocol, server, path, _, _, _ = urlparse.urlparse(path) assert server, "%s is not a valid URL" % path return urlparse.urlunparse(( protocol, server, path, None, query_str, 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 retrieve_page(self, method, path, post_params={}, headers={}, status=200, username=None, password=None, *args, **kwargs): """ Makes the actual request. This will also go through and generate the needed steps to make the request, i.e. basic auth. ``method``: Any supported HTTP methods defined in :rfc:`2616`. ``path``: Absolute or relative path. See :meth:`_prepare_uri` for more detail. ``post_params``: Dictionary of key/value pairs to be added as `POST` parameters. ``headers``: Dictionary of key/value pairs to be added to the HTTP headers. ``status``: Will error out if the HTTP status code does not match this value. Set this to `None` to disable checking. ``username``, ``password``: Username and password for basic auth; see :meth:`_prepare_basicauth` for more detail. An important note is that when ``post_params`` is specified, its behavior depends on the ``method``. That is, for `PUT` and `POST` requests, the dictionary is multipart encoded and put into the body of the request. For everything else, it is added as a query string to the URL. """
# Copy headers so that making changes here won't affect the original headers = headers.copy() # Update basic auth information basicauth = self._prepare_basicauth(username, password) if basicauth: headers.update([basicauth]) # If this is a POST or PUT, we can put the data into the body as # form-data encoded; otherwise, it should be part of the query string. if method in ["PUT", "POST"]: datagen, form_hdrs = poster.encode.multipart_encode(post_params) body = "".join(datagen) headers.update(form_hdrs) uri = self._prepare_uri(path) else: body = "" uri = self._prepare_uri(path, post_params) # Make the actual request response = self._make_request(uri, method, body, headers) # Assert that the status we received was expected. if status: real_status = int(response.status_int) assert real_status == int(status), \ "expected %s, received %s." % (status, real_status) return response
<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_track_token(request): """Returns ``TrackToken``. ``TrackToken' contains request and user making changes. It can be passed to ``TrackedModel.save`` instead of ``request``. It is intended to be used when passing ``request`` is not possible e.g. when ``TrackedModel.save`` will be called from celery task. """
from tracked_model.models import RequestInfo request_pk = RequestInfo.create_or_get_from_request(request).pk user_pk = None if request.user.is_authenticated(): user_pk = request.user.pk return TrackToken(request_pk=request_pk, user_pk=user_pk)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, *args, **kwargs): """Saves changes made on model instance if ``request`` or ``track_token`` keyword are provided. """
from tracked_model.models import History, RequestInfo if self.pk: action = ActionType.UPDATE changes = None else: action = ActionType.CREATE changes = serializer.dump_model(self) request = kwargs.pop('request', None) track_token = kwargs.pop('track_token', None) super().save(*args, **kwargs) if not changes: changes = self._tracked_model_diff() if changes: hist = History() hist.model_name = self._meta.model.__name__ hist.app_label = self._meta.app_label hist.table_name = self._meta.db_table hist.table_id = self.pk hist.change_log = serializer.to_json(changes) hist.action_type = action if request: if request.user.is_authenticated(): hist.revision_author = request.user req_info = RequestInfo.create_or_get_from_request(request) hist.revision_request = req_info elif track_token: hist.revision_author_id = track_token.user_pk hist.revision_request_id = track_token.request_pk hist.save() self._tracked_model_initial_state = serializer.dump_model(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 _tracked_model_diff(self): """Returns changes made to model instance. Returns None if no changes were made. """
initial_state = self._tracked_model_initial_state current_state = serializer.dump_model(self) if current_state == initial_state: return None change_log = {} for field in initial_state: old_value = initial_state[field][Field.VALUE] new_value = current_state[field][Field.VALUE] if old_value == new_value: continue field_data = initial_state.copy()[field] del field_data[Field.VALUE] field_data[Field.OLD] = old_value field_data[Field.NEW] = new_value change_log[field] = field_data return change_log or 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 tracked_model_history(self): """Returns history of a tracked object"""
from tracked_model.models import History return History.objects.filter( table_name=self._meta.db_table, table_id=self.pk)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def replace_placeholders(path: Path, properties: Dict[str, str]): '''Replace placeholders in a file with the values from the mapping.''' with open(path, encoding='utf8') as file: file_content = Template(file.read()) with open(path, 'w', encoding='utf8') as file: file.write(file_content.safe_substitute(properties))
<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, document): '''Check if the selected template exists.''' template = document.text if template not in self.builtin_templates: raise ValidationError( message=f'Template {template} not found. ' + f'Available templates are: {", ".join(self.builtin_templates)}.', cursor_position=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 get_start_of_line(self): """Return index of start of last line stored in self.buf. This function never fetches more data from the file; therefore, if it returns zero, meaning the line starts at the beginning of the buffer, the caller should then fetch more data and retry. """
if self.newline in ('\r', '\n', '\r\n'): return self.buf.rfind(self.newline.encode('ascii'), 0, -1) + 1 if self.newline: raise ValueError(r"ropen newline argument must be one of " r"None, '', '\r', '\n', '\r\n'.") # self.newline is None or ''; universal newlines mode end_of_search = -1 if len(self.buf) >= 2 and self.buf[-2:] == b'\r\n': end_of_search = -2 return max(self.buf.rfind(b'\n', 0, end_of_search), self.buf.rfind(b'\r', 0, end_of_search)) + 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 read_next_into_buf(self): """Read data from the file in self.bufsize chunks until we're certain we have a full line in the buffer. """
file_pos = self.fileobject.tell() if (file_pos == 0) and (self.buf == b''): raise StopIteration while file_pos and (self.get_start_of_line() == 0): bytes_to_read = min(self.bufsize, file_pos) file_pos = file_pos - bytes_to_read self.fileobject.seek(file_pos) new_stuff = self.fileobject.read(bytes_to_read)[:bytes_to_read] self.fileobject.seek(file_pos) self.buf = new_stuff + self.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 _add_to(self, db, index, item, default=OOSet): """ Add `item` to `db` under `index`. If `index` is not yet in `db`, create it using `default`. Args: db (dict-obj): Dict-like object used to connect to database. index (str): Index used to look in `db`. item (obj): Persistent object, which may be stored in DB. default (func/obj): Reference to function/object, which will be used to create the object under `index`. Default :class:`OOSet`. """
row = db.get(index, None) if row is None: row = default() db[index] = row row.add(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 add_tree(self, tree, parent=None): """ Add `tree` into database. Args: tree (obj): :class:`.Tree` instance. parent (ref, default None): Reference to parent tree. This is used for all sub-trees in recursive call. """
if tree.path in self.path_db: self.remove_tree_by_path(tree.path) # index all indexable attributes for index in tree.indexes: if not getattr(tree, index): continue self._add_to( getattr(self, index + "_db"), getattr(tree, index), tree, ) if parent: self._add_to(self.parent_db, tree.path, parent) # make sure, that all sub-trees starts with path of parent tree for sub_tree in tree.sub_trees: assert sub_tree.path.startswith(tree.path) for sub_tree in tree.sub_trees: self.add_tree(sub_tree, parent=tree)
<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_tree_by_path(self, path): """ Remove the tree from database by given `path`. Args: path (str): Path of the tree. """
with transaction.manager: trees = self.path_db.get(path, None) if not trees: return for tree in trees: return self._remove_tree(tree)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _remove_from(self, db, index, item): """ Remove `item` from `db` at `index`. Note: This function is inverse to :meth:`._add_to`. Args: db (dict-obj): Dict-like object used to connect to database. index (str): Index used to look in `db`. item (obj): Persistent object, which may be stored in DB. """
with transaction.manager: row = db.get(index, None) if row is None: return with transaction.manager: if item in row: row.remove(item) with transaction.manager: if not row: del db[index]
<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_tree(self, tree, parent=None): """ Really remove the tree identified by `tree` instance from all indexes from database. Args: tree (obj): :class:`.Tree` instance. parent (obj, default None): Reference to parent. """
# remove sub-trees for sub_tree in tree.sub_trees: self._remove_tree(sub_tree, parent=tree) # remove itself for index in tree.indexes: if not getattr(tree, index): continue self._remove_from( getattr(self, index + "_db"), getattr(tree, index), tree, ) if parent: self._remove_from(self.parent_db, tree.path, parent) self.zeo.pack()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trees_by_issn(self, issn): """ Search trees by `issn`. Args: issn (str): :attr:`.Tree.issn` property of :class:`.Tree`. Returns: set: Set of matching :class:`Tree` instances. """
return set( self.issn_db.get(issn, OOSet()).keys() )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trees_by_path(self, path): """ Search trees by `path`. Args: path (str): :attr:`.Tree.path` property of :class:`.Tree`. Returns: set: Set of matching :class:`Tree` instances. """
return set( self.path_db.get(path, OOSet()).keys() )
<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_parent(self, tree, alt=None): """ Get parent for given `tree` or `alt` if not found. Args: tree (obj): :class:`.Tree` instance, which is already stored in DB. alt (obj, default None): Alternative value returned when `tree` is not found. Returns: obj: :class:`.Tree` parent to given `tree`. """
parent = self.parent_db.get(tree.path) if not parent: return alt return list(parent)[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 yearfrac_365q(d1, d2): """date difference "d1-d2" as year fractional"""
# import modules from datetime import date from oxyba import date_to_datetime # define yearfrac formula # toyf = lambda a,b: (a - b).days / 365.2425 def toyf(a, b): a = date_to_datetime(a) if isinstance(a, date) else a b = date_to_datetime(b) if isinstance(b, date) else b return (a - b).days / 365.2425 # deal with scalars and vectors n1 = len(d1) if hasattr(d1, "__iter__") else 1 n2 = len(d2) if hasattr(d2, "__iter__") else 1 # compute yearfrac if n1 == 1 and n2 == 1: return toyf(d1, d2) elif n1 > 1 and n2 == 1: return [toyf(elem, d2) for elem in d1] elif n1 == 1 and n2 > 1: return [toyf(d1, elem) for elem in d2] elif n1 > 1 and n1 == n2: return [toyf(e1, e2) for e1, e2 in zip(d1, d2)] else: raise Exception("d1 and d2 have the wrong dimensions.")
<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(self, name, value, unit=None): """Add symbolic link to Dynamic Number list. name -- name of the symbolic link value -- value of the link (if not a string, conversion is done with str()) unit -- if value is a numerical value, a unit can be added to invoke the \unit{}{} LaTeX command """
# check if unit provided if unit is not None: add_unit = True unit = str(unit) else: add_unit = False # convert value to string value = str(value) # write to file f = open(self.file_dir, 'a') if add_unit: f.write("\\pgfkeys{dynamicnumber/%s/%s = \unit{%s}{%s}}\n" % (self.name, name, value, unit)) else: f.write("\\pgfkeys{dynamicnumber/%s/%s = %s}\n" % (self.name, name, value)) 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 _init_zeo(): """ Start asyncore thread. """
if not _ASYNCORE_RUNNING: def _run_asyncore_loop(): asyncore.loop() thread.start_new_thread(_run_asyncore_loop, ()) global _ASYNCORE_RUNNING _ASYNCORE_RUNNING = 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 retry_and_reset(fn): """ Decorator used to make sure, that operation on ZEO object will be retried, if there is ``ConnectionStateError`` exception. """
@wraps(fn) def retry_and_reset_decorator(*args, **kwargs): obj = kwargs.get("self", None) if not obj: obj = args[0] try: return fn(*args, **kwargs) except ConnectionStateError: obj._on_close_callback() return fn(*args, **kwargs) return retry_and_reset_decorator
<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_zeo_root(self, attempts=3): """ Get and initialize the ZEO root object. Args: attempts (int, default 3): How many times to try, if the connection was lost. """
try: db_root = self._connection.root() except ConnectionStateError: if attempts <= 0: raise self._open_connection() return self._init_zeo_root(attempts=attempts-1) # init the root, if it wasn't already declared if self.project_key and self.project_key not in db_root: with transaction.manager: db_root[self.project_key] = self.default_type() self._root = db_root[self.project_key] if self.project_key else db_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 create_dataclass_loader(cls, registry, field_getters): """create a loader for a dataclass type"""
fields = cls.__dataclass_fields__ item_loaders = map(registry, map(attrgetter('type'), fields.values())) getters = map(field_getters.__getitem__, fields) loaders = list(starmap(compose, zip(item_loaders, getters))) def dloader(obj): return cls(*(g(obj) for g in loaders)) return dloader
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rand_block(minimum, scale, maximum=1): """ block current thread at random pareto time ``minimum < block < 15`` and return the sleep time ``seconds`` :param minimum: :type minimum: :param scale: :type scale: :param slow_mode: a tuple e.g.(2, 5) :type slow_mode: tuple :return: """
t = min(rand_pareto_float(minimum, scale), maximum) time.sleep(t) return t
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _print_divide(self): """Prints all those table line dividers."""
for space in self.AttributesLength: self.StrTable += "+ " + "- " * space self.StrTable += "+" + "\n"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_table(self): """ Creates a pretty-printed string representation of the table as ``self.StrTable``. """
self.StrTable = "" self.AttributesLength = [] self.Lines_num = 0 # Prepare some values.. for col in self.Table: # Updates the table line count if necessary values = list(col.values())[0] self.Lines_num = max(self.Lines_num, len(values)) # find the length of longest value in current column key_length = max([self._disp_width(v) for v in values] or [0]) # and also the table header key_length = max(key_length, self._disp_width(list(col.keys())[0])) self.AttributesLength.append(key_length) # Do the real thing. self._print_head() self._print_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 _print_head(self): """Generates the table header."""
self._print_divide() self.StrTable += "| " for colwidth, attr in zip(self.AttributesLength, self.Attributes): self.StrTable += self._pad_string(attr, colwidth * 2) self.StrTable += "| " self.StrTable += '\n' self._print_divide()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _print_value(self): """Generates the table values."""
for line in range(self.Lines_num): for col, length in zip(self.Table, self.AttributesLength): vals = list(col.values())[0] val = vals[line] if len(vals) != 0 and line < len(vals) else '' self.StrTable += "| " self.StrTable += self._pad_string(val, length * 2) self.StrTable += "|" + '\n' self._print_divide()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pad_string(self, str, colwidth): """Center-pads a string to the given column width using spaces."""
width = self._disp_width(str) prefix = (colwidth - 1 - width) // 2 suffix = colwidth - prefix - width return ' ' * prefix + str + ' ' * suffix
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def basic_auth_string(username, password): """ Encode a username and password for use in an HTTP Basic Authentication header """
b64 = base64.encodestring('%s:%s' % (username, password)).strip() return 'Basic %s' % b64
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def equivalent_relshell_type(val): """Returns `val`'s relshell compatible type. :param val: value to check relshell equivalent type :raises: `NotImplementedError` if val's relshell compatible type is not implemented. """
builtin_type = type(val) if builtin_type not in Type._typemap: raise NotImplementedError("builtin type %s is not convertible to relshell type" % (builtin_type)) relshell_type_str = Type._typemap[builtin_type] return Type(relshell_type_str)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self, *args, **kwargs): """ Set the arguments for the callback function and start the thread """
self.runArgs = args self.runKwargs = kwargs Thread.start(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 init(name, languages, run): """Initializes your CONFIG_FILE for the current submission"""
contents = [file_name for file_name in glob.glob("*.*") if file_name != "brains.yaml"] with open(CONFIG_FILE, "w") as output: output.write(yaml.safe_dump({ "run": run, "name": name, "languages": languages, # automatically insert all root files into contents "contents": contents, }, default_flow_style=False)) print "" cprint("Automatically including the follow files in brain contents:", "cyan") for file_name in contents: print "\t", file_name print "" cprint("done! brains.yaml created", 'green')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def push(description, datasets, wait, verbose): """Publish your submission to brains"""
# Loading config config = _get_config() file_patterns = config["contents"] if not isinstance(file_patterns, type([])): # put it into an array so we can iterate it, if it isn't already an array file_patterns = [file_patterns] if datasets: datasets_string = datasets.split(',') else: datasets_string = config.get("datasets", '') # Getting all file names/globs -- making sure we get CONFIG_FILE files = {CONFIG_FILE} # use a set so we don't get duplicates for pattern in file_patterns: files.update(glob.glob(pattern)) if not files: print "No files could be found? Check your contents section in `CONFIG_FILE`!" exit(-1) if verbose: print "" print "gatherered files:" for path in files: print "\t", path print "" # Zipping _print("zipping...") if not os.path.exists("brains_history"): os.mkdir("brains_history") zip_path = 'brains_history/%s.zip' % str(datetime.datetime.now()) with ZipFile(zip_path, 'w') as zip_file: for path in files: zip_file.write(path) cprint("done", 'green') # Sending to server with open(zip_path, 'rb') as zip_file: _print("sending to server...") try: response = requests.post( URL_SUBMIT, files={ "zip_file": zip_file, }, data={ "name": config["name"], "description": description or '', "languages": config["languages"], "datasets": datasets_string, "wait": wait, }, stream=wait # if we're waiting for response then stream ) if response.status_code == 200: cprint("done", 'green') if wait: _print("\nOutput: ") cprint(" " * 72, 'green', attrs=('underline',)) chunk_buffer = "" # read in 1 chunk at a time for carriage return detection for chunk in response.iter_content(chunk_size=1): chunk_buffer += chunk if chunk == '\r': # We hit the end of a message! try: data = json.loads(chunk_buffer) if "stdout" not in data or "stderr" not in data: print "dis one" continue except (ValueError,): continue if data["stdout"]: # Get rid of termination string, if it's there data["stdout"] = data["stdout"].replace("-%-%-%-%-END BRAIN SEQUENCE-%-%-%-%-", "") _print(data["stdout"]) if data["stderr"]: _print(colored(data["stderr"], 'red')) # Clear buffer after reading message chunk_buffer = "" else: cprint(response.json()["error"], 'red') except requests.exceptions.ConnectionError: cprint("failed to connect to server!", 'red') exit(-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 run(dataset): """Run brain locally"""
config = _get_config() if dataset: _print("getting dataset from brains...") cprint("done", 'green') # check dataset cache for dataset # if not exists # r = requests.get('https://api.github.com/events', stream=True) # with open(filename, 'wb') as fd: # for chunk in r.iter_content(chunk_size): # fd.write(chunk) cprint('Running "%s"' % config["run"], 'green', attrs=("underline",)) call(config["run"].split())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def diskMonitor(self): '''Primitive monitor which checks whether new data is added to disk.''' while self.loop(): try: newest = max(glob.iglob("%s/*" % (self.kwargs.directory)), key=os.path.getmtime) except Exception: pass else: if time() - os.path.getctime(newest) >= self.kwargs.idle_time: self.reading.set() else: self.reading.clear() sleep(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 update(self, **kwargs): """ Update selected objects with the given keyword parameters and mark them as changed """
super(ModelQuerySet, self).update(_changed=True, **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 update(cls): """ Update rows to include known network interfaces """
ifaddrs = getifaddrs() # Create new interfaces for ifname in ifaddrs.keys(): if filter(ifname.startswith, cls.NAME_FILTER): cls.objects.get_or_create(name=ifname) # Delete no longer existing ones cls.objects.exclude(name__in=ifaddrs.keys()).delete()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def admin_page_ordering(request): """ Updates the ordering of pages via AJAX from within the admin. """
def get_id(s): s = s.split("_")[-1] return int(s) if s.isdigit() else None page = get_object_or_404(Page, id=get_id(request.POST['id'])) old_parent_id = page.parent_id new_parent_id = get_id(request.POST['parent_id']) new_parent = Page.objects.get(id=new_parent_id) if new_parent_id else None try: page.get_content_model().can_move(request, new_parent) except PageMoveException as e: messages.error(request, e) return HttpResponse('error') # Perform the page move if new_parent_id != page.parent_id: # Parent changed - set the new parent and re-order the # previous siblings. page.set_parent(new_parent) pages = Page.objects.filter(parent_id=old_parent_id) for i, page in enumerate(pages.order_by('_order')): Page.objects.filter(id=page.id).update(_order=i) # Set the new order for the moved page and its current siblings. for i, page_id in enumerate(request.POST.getlist('siblings[]')): Page.objects.filter(id=get_id(page_id)).update(_order=i) return HttpResponse("ok")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def page(request, slug, template=u"pages/page.html", extra_context=None): """ Select a template for a page and render it. The request object should have a ``page`` attribute that's added via ``yacms.pages.middleware.PageMiddleware``. The page is loaded earlier via middleware to perform various other functions. The urlpattern that maps to this view is a catch-all pattern, in which case the page attribute won't exist, so raise a 404 then. For template selection, a list of possible templates is built up based on the current page. This list is order from most granular match, starting with a custom template for the exact page, then adding templates based on the page's parent page, that could be used for sections of a site (eg all children of the parent). Finally at the broadest level, a template for the page's content type (it's model class) is checked for, and then if none of these templates match, the default pages/page.html is used. """
from yacms.pages.middleware import PageMiddleware if not PageMiddleware.installed(): raise ImproperlyConfigured("yacms.pages.middleware.PageMiddleware " "(or a subclass of it) is missing from " + "settings.MIDDLEWARE_CLASSES or " + "settings.MIDDLEWARE") if not hasattr(request, "page") or request.page.slug != slug: raise Http404 # Check for a template name matching the page's slug. If the homepage # is configured as a page instance, the template "pages/index.html" is # used, since the slug "/" won't match a template name. template_name = str(slug) if slug != home_slug() else "index" templates = [u"pages/%s.html" % template_name] method_template = request.page.get_content_model().get_template_name() if method_template: templates.insert(0, method_template) if request.page.content_model is not None: templates.append(u"pages/%s/%s.html" % (template_name, request.page.content_model)) for parent in request.page.get_ascendants(for_user=request.user): parent_template_name = str(parent.slug) # Check for a template matching the page's content model. if request.page.content_model is not None: templates.append(u"pages/%s/%s.html" % (parent_template_name, request.page.content_model)) # Check for a template matching the page's content model. if request.page.content_model is not None: templates.append(u"pages/%s.html" % request.page.content_model) templates.append(template) return TemplateResponse(request, templates, extra_context or {})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vector_unit_nonull(v): """Return unit vectors. Any null vectors raise an Exception. Parameters Cartesian vectors, with last axis indexing the dimension. Returns ------- v_new: array, shape of v """
if v.size == 0: return v return v / vector_mag(v)[..., np.newaxis]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vector_unit_nullnull(v): """Return unit vectors. Any null vectors remain null vectors. Parameters Cartesian vectors, with last axis indexing the dimension. Returns ------- v_new: array, shape of v """
if v.size == 0: return v mag = vector_mag(v) v_new = v.copy() v_new[mag > 0.0] /= mag[mag > 0.0][..., np.newaxis] return v_new
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vector_unit_nullrand(v, rng=None): """Return unit vectors. Any null vectors are mapped to a uniformly picked unit vector. Parameters Cartesian vectors, with last axis indexing the dimension. Returns ------- v_new: array, shape of v """
if v.size == 0: return v mag = vector_mag(v) v_new = v.copy() v_new[mag == 0.0] = sphere_pick(v.shape[-1], (mag == 0.0).sum(), rng) v_new[mag > 0.0] /= mag[mag > 0.0][..., np.newaxis] return v_new
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def polar_to_cart(arr_p): """Return polar vectors in their cartesian representation. Parameters Polar vectors, with last axis indexing the dimension, using (radius, inclination, azimuth) convention. Returns ------- arr_c: array, shape of arr_p Cartesian vectors. """
if arr_p.shape[-1] == 1: arr_c = arr_p.copy() elif arr_p.shape[-1] == 2: arr_c = np.empty_like(arr_p) arr_c[..., 0] = arr_p[..., 0] * np.cos(arr_p[..., 1]) arr_c[..., 1] = arr_p[..., 0] * np.sin(arr_p[..., 1]) elif arr_p.shape[-1] == 3: arr_c = np.empty_like(arr_p) arr_c[..., 0] = arr_p[..., 0] * np.sin( arr_p[..., 1]) * np.cos(arr_p[..., 2]) arr_c[..., 1] = arr_p[..., 0] * np.sin( arr_p[..., 1]) * np.sin(arr_p[..., 2]) arr_c[..., 2] = arr_p[..., 0] * np.cos(arr_p[..., 1]) else: raise Exception('Invalid vector for polar representation') return arr_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 cart_to_polar(arr_c): """Return cartesian vectors in their polar representation. Parameters Cartesian vectors, with last axis indexing the dimension. Returns ------- arr_p: array, shape of arr_c Polar vectors, using (radius, inclination, azimuth) convention. """
if arr_c.shape[-1] == 1: arr_p = arr_c.copy() elif arr_c.shape[-1] == 2: arr_p = np.empty_like(arr_c) arr_p[..., 0] = vector_mag(arr_c) arr_p[..., 1] = np.arctan2(arr_c[..., 1], arr_c[..., 0]) elif arr_c.shape[-1] == 3: arr_p = np.empty_like(arr_c) arr_p[..., 0] = vector_mag(arr_c) arr_p[..., 1] = np.arccos(arr_c[..., 2] / arr_p[..., 0]) arr_p[..., 2] = np.arctan2(arr_c[..., 1], arr_c[..., 0]) else: raise Exception('Invalid vector for polar representation') return arr_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 sphere_pick_polar(d, n=1, rng=None): """Return vectors uniformly picked on the unit sphere. Vectors are in a polar representation. Parameters d: float The number of dimensions of the space in which the sphere lives. n: integer Number of samples to pick. Returns ------- r: array, shape (n, d) Sample vectors. """
if rng is None: rng = np.random a = np.empty([n, d]) if d == 1: a[:, 0] = rng.randint(2, size=n) * 2 - 1 elif d == 2: a[:, 0] = 1.0 a[:, 1] = rng.uniform(-np.pi, +np.pi, n) elif d == 3: u, v = rng.uniform(0.0, 1.0, (2, n)) a[:, 0] = 1.0 a[:, 1] = np.arccos(2.0 * v - 1.0) a[:, 2] = 2.0 * np.pi * u else: raise Exception('Invalid vector for polar representation') return 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 rejection_pick(L, n, d, valid, rng=None): """Return cartesian vectors uniformly picked in a space with an arbitrary number of dimensions, which is fully enclosed by a cube of finite length, using a supplied function which should evaluate whether a picked point lies within this space. The picking is done by rejection sampling in the cube. Parameters L: float Side length of the enclosing cube. n: integer Number of points to return d: integer The number of dimensions of the space Returns ------- r: array, shape (n, d) Sample cartesian vectors """
if rng is None: rng = np.random rs = [] while len(rs) < n: r = rng.uniform(-L / 2.0, L / 2.0, size=d) if valid(r): rs.append(r) return np.array(rs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ball_pick(n, d, rng=None): """Return cartesian vectors uniformly picked on the unit ball in an arbitrary number of dimensions. The unit ball is the space enclosed by the unit sphere. The picking is done by rejection sampling in the unit cube. In 3-dimensional space, the fraction `\pi / 6 \sim 0.52` points are valid. Parameters n: integer Number of points to return. d: integer Number of dimensions of the space in which the ball lives Returns ------- r: array, shape (n, d) Sample cartesian vectors. """
def valid(r): return vector_mag_sq(r) < 1.0 return rejection_pick(L=2.0, n=n, d=d, valid=valid, rng=rng)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disk_pick_polar(n=1, rng=None): """Return vectors uniformly picked on the unit disk. The unit disk is the space enclosed by the unit circle. Vectors are in a polar representation. Parameters n: integer Number of points to return. Returns ------- r: array, shape (n, 2) Sample vectors. """
if rng is None: rng = np.random a = np.zeros([n, 2], dtype=np.float) a[:, 0] = np.sqrt(rng.uniform(size=n)) a[:, 1] = rng.uniform(0.0, 2.0 * np.pi, size=n) return 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 smallest_signed_angle(source, target): """Find the smallest angle going from angle `source` to angle `target`."""
dth = target - source dth = (dth + np.pi) % (2.0 * np.pi) - np.pi return dth
<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, vpn_id: int) -> Vpn: """ Updates the Vpn Resource with the name. """
vpn = self._get_or_abort(vpn_id) self.update(vpn) session.commit() return vpn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post(self) -> Vpn: """ Creates the vpn with the given data. """
vpn = Vpn() session.add(vpn) self.update(vpn) session.flush() session.commit() return vpn, 201, { 'Location': url_for('vpn', vpn_id=vpn.id) }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_token(cls, parser, token): """Class method to parse render_comment_list and return a Node."""
tokens = token.contents.split() if tokens[1] != 'for': raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0]) # {% render_comment_list for obj %} if len(tokens) == 3: return cls(object_expr=parser.compile_filter(tokens[2])) # {% render_comment_list for app.models pk %} elif len(tokens) == 4: return cls( ctype = BaseCommentNode.lookup_content_type(tokens[2], tokens[0]), object_pk_expr = parser.compile_filter(tokens[3]) )
<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_current_data(self): """Return the calibration data for the current IMU, if any."""
if self.current_imuid in self.calibration_data: return self.calibration_data[self.current_imuid] 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 update_battery(self): """Updates the battery level in the UI for the connected SK8, if any"""
if self.sk8 is None: return battery = self.sk8.get_battery_level() self.lblBattery.setText('Battery: {}%'.format(battery))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def imu_changed(self, val): """Handle clicks on the IMU index spinner."""
self.current_imuid = '{}_IMU{}'.format(self.sk8.get_device_name(), val) self.update_data_display(self.get_current_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 accel_calibration(self): """Perform accelerometer calibration for current IMU."""
self.calibration_state = self.CAL_ACC self.acc_dialog = SK8AccDialog(self.sk8.get_imu(self.spinIMU.value()), self) if self.acc_dialog.exec_() == QDialog.Rejected: return self.calculate_acc_calibration(self.acc_dialog.samples)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gyro_calibration(self): """Perform gyroscope calibration for current IMU."""
QtWidgets.QMessageBox.information(self, 'Gyro calibration', 'Ensure the selected IMU is in a stable, unmoving position, then click OK. Don\'t move the the IMU for a few seconds') self.calibration_state = self.CAL_GYRO self.gyro_dialog = SK8GyroDialog(self.sk8.get_imu(self.spinIMU.value()), self) if self.gyro_dialog.exec_() == QDialog.Rejected: return self.calculate_gyro_calibration(self.gyro_dialog.samples)