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 unflag_message(current): """ remove flag of a message .. code-block:: python # request: { 'view':'_zops_flag_message', 'key': key, } # response: { ' 'status'...
current.output = {'status': 'OK', 'code': 200} FlaggedMessage(current).objects.filter(user_id=current.user_id, message_id=current.input['key']).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 get_message_actions(current): """ Returns applicable actions for current user for given message key .. code-block:: python # request: { 'view':'_zops_get_mes...
current.output = {'status': 'OK', 'code': 200, 'actions': Message.objects.get( current.input['key']).get_actions_for(current.user)}
<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_favorites(current): """ Favorite a message .. code-block:: python # request: { 'view':'_zops_add_to_favorites, 'key': key, } # response: { 'status': '...
msg = Message.objects.get(current.input['key']) current.output = {'status': 'Created', 'code': 201} fav, new = Favorite.objects.get_or_create(user_id=current.user_id, message=msg) current.output['favorite_key'] = fav.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_from_favorites(current): """ Remove a message from favorites .. code-block:: python # request: { 'view':'_zops_remove_from_favorites, 'key': key, } # ...
try: current.output = {'status': 'OK', 'code': 200} Favorite(current).objects.get(user_id=current.user_id, key=current.input['key']).delete() except ObjectDoesNotExist: raise HTTPError(404, "")
<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_favorites(current): """ List user's favorites. If "channel_key" given, will return favorites belong to that channel. .. code-block:: python # request: {...
current.output = {'status': 'OK', 'code': 200, 'favorites': []} query_set = Favorite(current).objects.filter(user_id=current.user_id) if current.input['channel_key']: query_set = query_set.filter(channel_id=current.input['channel_key']) current.output['favorites'] = [{ ...
<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_or_create_direct_channel(cls, initiator_key, receiver_key): """ Creates a direct messaging channel between two user Args: initiator: User, who want's to ...
existing = cls.objects.OR().filter( code_name='%s_%s' % (initiator_key, receiver_key)).filter( code_name='%s_%s' % (receiver_key, initiator_key)) receiver_name = UserModel.objects.get(receiver_key).full_name if existing: channel = existing[0] 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 create_exchange(self): """ Creates MQ exchange for this channel Needs to be defined only once. """
mq_channel = self._connect_mq() mq_channel.exchange_declare(exchange=self.code_name, exchange_type='fanout', durable=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 delete_exchange(self): """ Deletes MQ exchange for this channel Needs to be defined only once. """
mq_channel = self._connect_mq() mq_channel.exchange_delete(exchange=self.code_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_channel_listing(self): """ serialized form for channel listing """
return {'name': self.name, 'key': self.channel.key, 'type': self.channel.typ, 'read_only': self.read_only, 'is_online': self.is_online(), 'actions': self.get_actions(), 'unread': self.unread_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 create_exchange(self): """ Creates user's private exchange Actually user's private channel needed to be defined only once, and this should be happened when u...
channel = self._connect_mq() channel.exchange_declare(exchange=self.user.prv_exchange, exchange_type='fanout', durable=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 serialize(self, user=None): """ Serializes message for given user. Note: Should be called before first save(). Otherwise "is_update" will get wrong value. Ar...
return { 'content': self.body, 'type': self.typ, 'updated_at': self.updated_at, 'timestamp': self.updated_at, 'is_update': not hasattr(self, 'unsaved'), 'attachments': [attachment.serialize() for attachment in self.attachment_set], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _republish(self): """ Re-publishes updated message """
mq_channel = self.channel._connect_mq() mq_channel.basic_publish(exchange=self.channel.key, routing_key='', body=json.dumps(self.serialize()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def defaultCrawlId(): """ Provide a reasonable default crawl name using the user name and date """
timestamp = datetime.now().isoformat().replace(':', '_') user = getuser() return '_'.join(('crawl', user, timestamp))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(argv=None): """Run Nutch command using REST API."""
global Verbose, Mock if argv is None: argv = sys.argv if len(argv) < 5: die('Bad args') try: opts, argv = getopt.getopt(argv[1:], 'hs:p:mv', ['help', 'server=', 'port=', 'mock', 'verbose']) except getopt.GetoptError as err: # print help information and exit: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call(self, verb, servicePath, data=None, headers=None, forceText=False, sendJson=True): """Call the Nutch Server, do some error checking, and return the resp...
default_data = {} if sendJson else "" data = data if data else default_data headers = headers if headers else JsonAcceptHeader.copy() if not sendJson: headers.update(TextSendHeader) if verb not in RequestVerbs: die('Server call verb must be one of %s'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list(self, allJobs=False): """ Return list of jobs at this endpoint. Call get(allJobs=True) to see all jobs, not just the ones managed by this Client """
jobs = self.server.call('get', '/job') return [Job(job['id'], self.server) for job in jobs if allJobs or self._job_owned(job)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _nextJob(self, job, nextRound=True): """ Given a completed job, start the next job in the round, or return None :param nextRound: whether to start jobs from ...
jobInfo = job.info() assert jobInfo['state'] == 'FINISHED' roundEnd = False if jobInfo['type'] == 'INJECT': nextCommand = 'GENERATE' elif jobInfo['type'] == 'GENERATE': nextCommand = 'FETCH' elif jobInfo['type'] == 'FETCH': nextComma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def progress(self, nextRound=True): """ Check the status of the current job, activate the next job if it's finished, and return the active job If the current job...
currentJob = self.currentJob if currentJob is None: return currentJob jobInfo = currentJob.info() if jobInfo['state'] == 'RUNNING': return currentJob elif jobInfo['state'] == 'FINISHED': nextJob = self._nextJob(currentJob, nextRound) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nextRound(self): """ Execute all jobs in the current round and return when they have finished. If a job fails, a NutchCrawlException will be raised, with all...
finishedJobs = [] if self.currentJob is None: self.currentJob = self.jobClient.create('GENERATE') activeJob = self.progress(nextRound=False) while activeJob: oldJob = activeJob activeJob = self.progress(nextRound=False) # updates self.currentJob ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def waitAll(self): """ Execute all queued rounds and return when they have finished. If a job fails, a NutchCrawlException will be raised, with all completed job...
finishedRounds = [self.nextRound()] while self.currentRound < self.totalRounds: finishedRounds.append(self.nextRound()) return finishedRounds
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Jobs(self, crawlId=None): """ Create a JobClient for listing and creating jobs. The JobClient inherits the confId from the Nutch client. :param crawlId: craw...
crawlId = crawlId if crawlId else defaultCrawlId() return JobClient(self.server, crawlId, self.confId)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, attr, default=None): """Get an attribute defined by this session"""
attrs = self.body.get('attributes') or {} return attrs.get(attr, default)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all(self, cat): """ if data can't found in cache then it will be fetched from db, parsed and stored to cache for each lang_code. :param cat: cat of catal...
return self._get_from_local_cache(cat) or self._get_from_cache(cat) or self._get_from_db(cat)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fill_get_item_cache(self, catalog, key): """ get from redis, cache locally then return :param catalog: catalog name :param key: :return: """
lang = self._get_lang() keylist = self.get_all(catalog) self.ITEM_CACHE[lang][catalog] = dict([(i['value'], i['name']) for i in keylist]) return self.ITEM_CACHE[lang][catalog].get(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 run(self, host, port, debug=True, validate_requests=True): """Utility method to quickly get a server up and running. :param debug: turns on Werkzeug debugger...
if debug: # Turn on all alexandra log output logging.basicConfig(level=logging.DEBUG) app = self.create_wsgi_app(validate_requests) run_simple(host, port, app, use_reloader=debug, use_debugger=debug)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dispatch_request(self, body): """Given a parsed JSON request object, call the correct Intent, Launch, or SessionEnded function. This function is called after...
req_type = body.get('request', {}).get('type') session_obj = body.get('session') session = Session(session_obj) if session_obj else None if req_type == 'LaunchRequest': return self.launch_fn(session) elif req_type == 'IntentRequest': intent = body['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 intent(self, intent_name): """Decorator to register a handler for the given intent. The decorated function can either take 0 or 2 arguments. If two are speci...
# nested decorator so we can have params. def _decorator(func): arity = func.__code__.co_argcount if arity not in [0, 2]: raise ValueError("expected 0 or 2 argument function") self.intent_map[intent_name] = func return func ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encrypt_password(self): """ encrypt password if not already encrypted """
if self.password and not self.password.startswith('$pbkdf2'): self.set_password(self.password)
<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_client_cmd(self, data, cmd=None, via_queue=None): """ Send arbitrary cmd and data to client if queue name passed by "via_queue" parameter, that queue wi...
mq_channel = self._connect_mq() if cmd: data['cmd'] = cmd if via_queue: mq_channel.basic_publish(exchange='', routing_key=via_queue, body=json.dumps(data)) else: mq_channel.basi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assign_yourself(self): """ Assigning the workflow to itself. The selected job is checked to see if there is an assigned role. If it does not have a role assi...
task_invitation = TaskInvitation.objects.get(self.task_invitation_key) wfi = task_invitation.instance if not wfi.current_actor.exist: wfi.current_actor = self.current.role wfi.save() [inv.delete() for inv in TaskInvitation.objects.filter(instance=wfi) if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_workflow(self): """ With the workflow instance and the task invitation is assigned a role. """
task_invitation = TaskInvitation.objects.get(self.task_invitation_key) wfi = task_invitation.instance select_role = self.input['form']['select_role'] if wfi.current_actor == self.current.role: task_invitation.role = RoleModel.objects.get(select_role) wfi.current_...
<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_date(self): """ Invitations with the same workflow status are deleted. Workflow instance and invitation roles change. """
task_invitation = TaskInvitation.objects.get(self.task_invitation_key) wfi = task_invitation.instance if wfi.current_actor.exist and wfi.current_actor == self.current.role: dt_start = datetime.strptime(self.input['form']['start_date'], "%d.%m.%Y") dt_finish = datetime.s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def suspend(self): """ If there is a role assigned to the workflow and it is the same as the user, it can drop the workflow. If it does not exist, it can not do ...
task_invitation = TaskInvitation.objects.get(self.task_invitation_key) wfi = task_invitation.instance if wfi.current_actor.exist and wfi.current_actor == self.current.role: for m in RoleModel.objects.filter(abstract_role=self.current.role.abstract_role, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_home_row(self, location=None): """ Finds out if the piece is on the home row. :return: bool for whether piece is on home row or not """
location = location or self.location return (self.color == color.white and location.rank == 1) or \ (self.color == color.black and location.rank == 6)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def would_move_be_promotion(self, location=None): """ Finds if move from current get_location would result in promotion :type: location: Location :rtype: bool ""...
location = location or self.location return (location.rank == 1 and self.color == color.black) or \ (location.rank == 6 and self.color == color.white)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def square_in_front(self, location=None): """ Finds square directly in front of Pawn :type: location: Location :rtype: Location """
location = location or self.location return location.shift_up() if self.color == color.white else location.shift_down()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forward_moves(self, position): """ Finds possible moves one step and two steps in front of Pawn. :type: position: Board :rtype: list """
if position.is_square_empty(self.square_in_front(self.location)): """ If square in front is empty add the move """ if self.would_move_be_promotion(): for move in self.create_promotion_moves(notation_const.PROMOTE): yield move ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _one_diagonal_capture_square(self, capture_square, position): """ Adds specified diagonal as a capture move if it is one """
if self.contains_opposite_color_piece(capture_square, position): if self.would_move_be_promotion(): for move in self.create_promotion_moves(status=notation_const.CAPTURE_AND_PROMOTE, location=capture_square): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def capture_moves(self, position): """ Finds out all possible capture moves :rtype: list """
try: right_diagonal = self.square_in_front(self.location.shift_right()) for move in self._one_diagonal_capture_square(right_diagonal, position): yield move except IndexError: pass try: left_diagonal = self.square_in_front(self.loc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_en_passant_valid_location(self): """ Finds out if pawn is on enemy center rank. :rtype: bool """
return (self.color == color.white and self.location.rank == 4) or \ (self.color == color.black and self.location.rank == 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 _is_en_passant_valid(self, opponent_pawn_location, position): """ Finds if their opponent's pawn is next to this pawn :rtype: bool """
try: pawn = position.piece_at_square(opponent_pawn_location) return pawn is not None and \ isinstance(pawn, Pawn) and \ pawn.color != self.color and \ position.piece_at_square(opponent_pawn_location).just_moved_two_steps except Ind...
<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_one_en_passant_move(self, direction, position): """ Yields en_passant moves in given direction if it is legal. :type: direction: function :type: position...
try: if self._is_en_passant_valid(direction(self.location), position): yield self.create_move( end_loc=self.square_in_front(direction(self.location)), status=notation_const.EN_PASSANT ) except IndexError: pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def en_passant_moves(self, position): """ Finds possible en passant moves. :rtype: list """
# if pawn is not on a valid en passant get_location then return None if self.on_en_passant_valid_location(): for move in itertools.chain(self.add_one_en_passant_move(lambda x: x.shift_right(), position), self.add_one_en_passant_move(lambda x: x.shift...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def respond(text=None, ssml=None, attributes=None, reprompt_text=None, reprompt_ssml=None, end_session=True): """ Build a dict containing a valid response to an ...
obj = { 'version': '1.0', 'response': { 'outputSpeech': {'type': 'PlainText', 'text': ''}, 'shouldEndSession': end_session }, 'sessionAttributes': attributes or {} } if text: obj['response']['outputSpeech'] = {'type': 'PlainText', 'text': te...
<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_request_timestamp(req_body, max_diff=150): """Ensure the request's timestamp doesn't fall outside of the app's specified tolerance. Returns True if ...
time_str = req_body.get('request', {}).get('timestamp') if not time_str: log.error('timestamp not present %s', req_body) return False req_ts = datetime.strptime(time_str, "%Y-%m-%dT%H:%M:%SZ") diff = (datetime.utcnow() - req_ts).total_seconds() if abs(diff) > max_diff: l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_request_certificate(headers, data): """Ensure that the certificate and signature specified in the request headers are truely from Amazon and correct...
# Make sure we have the appropriate headers. if 'SignatureCertChainUrl' not in headers or \ 'Signature' not in headers: log.error('invalid request headers') return False cert_url = headers['SignatureCertChainUrl'] sig = base64.b64decode(headers['Signature']) cert = _get_ce...
<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_certificate(cert_url): """Download and validate a specified Amazon PEM file."""
global _cache if cert_url in _cache: cert = _cache[cert_url] if cert.has_expired(): _cache = {} else: return cert url = urlparse(cert_url) host = url.netloc.lower() path = posixpath.normpath(url.path) # Sanity check location so we don't get som...
<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_processed(self, db_versions): """Check if version is already applied in the database. :param db_versions: """
return self.number in (v.number for v in db_versions if v.date_done)
<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_noop(self): """Check if version is a no operation version. """
has_operations = [mode.pre_operations or mode.post_operations for mode in self._version_modes.values()] has_upgrade_addons = [mode.upgrade_addons or mode.remove_addons for mode in self._version_modes.values()] noop = not any((has_upgrade_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 _get_version_mode(self, mode=None): """Return a VersionMode for a mode name. When the mode is None, we are working with the 'base' mode. """
version_mode = self._version_modes.get(mode) if not version_mode: version_mode = self._version_modes[mode] = VersionMode(name=mode) return version_mode
<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_operation(self, operation_type, operation, mode=None): """Add an operation to the version :param mode: Name of the mode in which the operation is execute...
version_mode = self._get_version_mode(mode=mode) if operation_type == 'pre': version_mode.add_pre(operation) elif operation_type == 'post': version_mode.add_post(operation) else: raise ConfigurationError( u"Type of operation must be '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 add_backup_operation(self, backup, mode=None): """Add a backup operation to the version. :param backup: To either add or skip the backup :type backup: Boolea...
try: if self.options.backup: self.options.backup.ignore_if_operation().execute() except OperationError: self.backup = backup
<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_operations(self, mode=None): """ Return pre-operations only for the mode asked """
version_mode = self._get_version_mode(mode=mode) return version_mode.pre_operations
<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_operations(self, mode=None): """ Return post-operations only for the mode asked """
version_mode = self._get_version_mode(mode=mode) return version_mode.post_operations
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upgrade_addons_operation(self, addons_state, mode=None): """ Return merged set of main addons and mode's addons """
installed = set(a.name for a in addons_state if a.state in ('installed', 'to upgrade')) base_mode = self._get_version_mode() addons_list = base_mode.upgrade_addons.copy() if mode: add_mode = self._get_version_mode(mode=mode) addons_list |...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self): """ get copy of object :return: ReactionContainer """
return type(self)(reagents=[x.copy() for x in self.__reagents], meta=self.__meta.copy(), products=[x.copy() for x in self.__products], reactants=[x.copy() for x in self.__reactants])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def implicify_hydrogens(self): """ remove explicit hydrogens if possible :return: number of removed hydrogens """
total = 0 for ml in (self.__reagents, self.__reactants, self.__products): for m in ml: if hasattr(m, 'implicify_hydrogens'): total += m.implicify_hydrogens() if total: self.flush_cache() return total
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compose(self): """ get CGR of reaction reagents will be presented as unchanged molecules :return: CGRContainer """
rr = self.__reagents + self.__reactants if rr: if not all(isinstance(x, (MoleculeContainer, CGRContainer)) for x in rr): raise TypeError('Queries not composable') r = reduce(or_, rr) else: r = MoleculeContainer() if self.__products: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_positions(self): """ fix coordinates of molecules in reaction """
shift_x = 0 for m in self.__reactants: max_x = self.__fix_positions(m, shift_x, 0) shift_x = max_x + 1 arrow_min = shift_x if self.__reagents: for m in self.__reagents: max_x = self.__fix_positions(m, shift_x, 1.5) shi...
<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_permissions(self): """ Permissions of the user. Returns: List of Permission objects. """
user_role = self.last_login_role() if self.last_login_role_key else self.role_set[0].role return user_role.get_permissions()
<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_permission_by_name(self, code, save=False): """ Adds a permission with given name. Args: code (str): Code name of the permission. save (bool): If False...
if not save: return ["%s | %s" % (p.name, p.code) for p in Permission.objects.filter(code__contains=code)] for p in Permission.objects.filter(code__contains=code): if p not in self.Permissions: self.Permissions(permission=p) if 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 send_notification(self, title, message, typ=1, url=None, sender=None): """ sends a message to user of this role's private mq exchange """
self.user.send_notification(title=title, message=message, typ=typ, url=url, sender=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 would_move_be_promotion(self): """ Finds if move from current location would be a promotion """
return (self._end_loc.rank == 0 and not self.color) or \ (self._end_loc.rank == 7 and self.color)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self, receiver, sender=None, weak=True, dispatch_uid=None): """ Connect receiver to sender for signal. Arguments: receiver A function or an instance ...
if dispatch_uid: lookup_key = (dispatch_uid, _make_id(sender)) else: lookup_key = (_make_id(receiver), _make_id(sender)) if weak: ref = weakref.ref receiver_object = receiver # Check for bound methods if hasattr(receiver, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disconnect(self, receiver=None, sender=None, dispatch_uid=None): """ Disconnect receiver from sender for signal. If weak references are used, disconnect need...
if dispatch_uid: lookup_key = (dispatch_uid, _make_id(sender)) else: lookup_key = (_make_id(receiver), _make_id(sender)) disconnected = False with self.lock: self._clear_dead_receivers() for index in range(len(self.receivers)): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def migrate(config): """Perform a migration according to config. :param config: The configuration to be applied :type config: Config """
webapp = WebApp(config.web_host, config.web_port, custom_maintenance_file=config.web_custom_html) webserver = WebServer(webapp) webserver.daemon = True webserver.start() migration_parser = YamlParser.parse_from_file(config.migration_file) migration = migration_parser.parse...
<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_permissions(cls): """ Generates permissions for all CrudView based class methods. Returns: List of Permission objects. """
perms = [] for kls_name, kls in cls.registry.items(): for method_name in cls.__dict__.keys(): if method_name.endswith('_view'): perms.append("%s.%s" % (kls_name, method_name)) return perms
<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_object_menu_models(): """ we need to create basic permissions for only CRUD enabled models """
from pyoko.conf import settings enabled_models = [] for entry in settings.OBJECT_MENU.values(): for mdl in entry: if 'wf' not in mdl: enabled_models.append(mdl['name']) return enabled_models
<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(cls, code_name, name='', description=''): """ create a custom permission """
if code_name not in cls.registry: cls.registry[code_name] = (code_name, name or code_name, description) return code_name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_mapping(self, other): """ get self to other mapping """
m = next(self._matcher(other).isomorphisms_iter(), None) if m: return {v: k for k, v in m.items()}
<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_substructure_mapping(self, other, limit=1): """ get self to other substructure mapping :param limit: number of matches. if 0 return iterator for all poss...
i = self._matcher(other).subgraph_isomorphisms_iter() if limit == 1: m = next(i, None) if m: return {v: k for k, v in m.items()} return elif limit == 0: return ({v: k for k, v in m.items()} for m in i) return [{v: k for k, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shift(self, direction): """ Shifts in direction provided by ``Direction`` enum. :type: direction: Direction :rtype: Location """
try: if direction == Direction.UP: return self.shift_up() elif direction == Direction.DOWN: return self.shift_down() elif direction == Direction.RIGHT: return self.shift_right() elif direction == Direction.LEFT: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shift_up(self, times=1): """ Finds Location shifted up by 1 :rtype: Location """
try: return Location(self._rank + times, self._file) except IndexError as e: raise IndexError(e)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shift_down(self, times=1): """ Finds Location shifted down by 1 :rtype: Location """
try: return Location(self._rank - times, self._file) except IndexError as e: raise IndexError(e)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shift_right(self, times=1): """ Finds Location shifted right by 1 :rtype: Location """
try: return Location(self._rank, self._file + times) except IndexError as e: raise IndexError(e)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shift_left(self, times=1): """ Finds Location shifted left by 1 :rtype: Location """
try: return Location(self._rank, self._file - times) except IndexError as e: raise IndexError(e)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shift_up_right(self, times=1): """ Finds Location shifted up right by 1 :rtype: Location """
try: return Location(self._rank + times, self._file + times) except IndexError as e: raise IndexError(e)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shift_up_left(self, times=1): """ Finds Location shifted up left by 1 :rtype: Location """
try: return Location(self._rank + times, self._file - times) except IndexError as e: raise IndexError(e)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shift_down_right(self, times=1): """ Finds Location shifted down right by 1 :rtype: Location """
try: return Location(self._rank - times, self._file + times) except IndexError as e: raise IndexError(e)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shift_down_left(self, times=1): """ Finds Location shifted down left by 1 :rtype: Location """
try: return Location(self._rank - times, self._file - times) except IndexError as e: raise IndexError(e)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def standardize(self): """ standardize functional groups :return: number of found groups """
self.reset_query_marks() seen = set() total = 0 for n, atom in self.atoms(): if n in seen: continue for k, center in central.items(): if center != atom: continue shell = tuple((bond, self._node[m...
<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_staged_files(): """Get all files staged for the current commit. """
proc = subprocess.Popen(('git', 'status', '--porcelain'), stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, _ = proc.communicate() staged_files = modified_re.findall(out) return staged_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 runserver(host=None, port=None): """ Run Tornado server """
host = host or os.getenv('HTTP_HOST', '0.0.0.0') port = port or os.getenv('HTTP_PORT', '9001') zioloop = ioloop.IOLoop.instance() # setup pika client: pc = QueueManager(zioloop) app.pc = pc pc.connect() app.listen(port, host) zioloop.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self): """ Called on new websocket connection. """
sess_id = self._get_sess_id() if sess_id: self.application.pc.websockets[self._get_sess_id()] = self self.write_message(json.dumps({"cmd": "status", "status": "open"})) else: self.write_message(json.dumps({"cmd": "error", "error": "Please login", "code": 401}...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_message(self, message): """ called on new websocket message, """
log.debug("WS MSG for %s: %s" % (self._get_sess_id(), message)) self.application.pc.redirect_incoming_message(self._get_sess_id(), message, self.request)
<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_redundancy(self, log): """Removes duplicate data from 'data' inside log dict and brings it out. {'data': {'a': 1, 'b': 2}, 'type': 'metric', 'id': 46...
for key in log: if key in log and key in log['data']: log[key] = log['data'].pop(key) return log
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _scan_fpatterns(self, state): ''' For a list of given fpatterns, this starts a thread collecting log lines from file >>> os.path.isfile = lambda path: path == '/path/to/log_file.log' >>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 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_links(self, **kw): """ Prepare links of form by mimicing pyoko's get_links method's result Args: **kw: Returns: list of link dicts """
links = [a for a in dir(self) if isinstance(getattr(self, a), Model) and not a.startswith('_model')] return [ { 'field': l, 'mdl': getattr(self, l).__class__, } for l in links ]
<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_data(self, data): """ Fills form with data Args: data (dict): Data to assign form fields. Returns: Self. Form object. """
for name in self._fields: setattr(self, name, data.get(name)) 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 get_input(source, files, threads=4, readtype="1D", combine="simple", names=None, barcoded=False): """Get input and process accordingly. Data can be: - a unco...
proc_functions = { 'fastq': ex.process_fastq_plain, 'fasta': ex.process_fasta, 'bam': ex.process_bam, 'summary': ex.process_summary, 'fastq_rich': ex.process_fastq_rich, 'fastq_minimal': ex.process_fastq_minimal, 'cram': ex.process_cram, 'ubam': ex.pr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combine_dfs(dfs, names, method): """Combine dataframes. Combination is either done simple by just concatenating the DataFrames or performs tracking by adding...
if method == "track": res = list() for df, identifier in zip(dfs, names): df["dataset"] = identifier res.append(df) return pd.concat(res, ignore_index=True) elif method == "simple": return pd.concat(dfs, ignore_index=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 calculate_start_time(df): """Calculate the star_time per read. Time data is either a "time" (in seconds, derived from summary files) or a "timestamp" (in UTC...
if "time" in df: df["time_arr"] = pd.Series(df["time"], dtype='datetime64[s]') elif "timestamp" in df: df["time_arr"] = pd.Series(df["timestamp"], dtype="datetime64[ns]") else: return df if "dataset" in df: for dset in df["dataset"].unique(): time_zero = df.l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parser_from_buffer(cls, fp): """Construct YamlParser from a file pointer."""
yaml = YAML(typ="safe") return cls(yaml.load(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 check_dict_expected_keys(self, expected_keys, current, dict_name): """ Check that we don't have unknown keys in a dictionary. It does not raise an error if w...
if not isinstance(current, dict): raise ParseError(u"'{}' key must be a dict".format(dict_name), YAML_EXAMPLE) expected_keys = set(expected_keys) current_keys = {key for key in current} extra_keys = current_keys - expected_keys if extra_k...
<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_message(self, title, msg, typ, url=None): """ Sets user notification message. Args: title: Msg. title msg: Msg. text typ: Msg. type url: Additional URL (...
return self.user.send_notification(title=title, message=msg, typ=typ, url=url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_auth(self): """ A property that indicates if current user is logged in or not. Returns: Boolean. """
if self.user_id is None: self.user_id = self.session.get('user_id') return bool(self.user_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 msg_box(self, msg, title=None, typ='info'): """ Create a message box :param str msg: :param str title: :param str typ: 'info', 'error', 'warning' """
self.output['msgbox'] = {'type': typ, "title": title or msg[:20], "msg": 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 _update_task(self, task): """ Assigns current task step to self.task then updates the task's data with self.task_data Args: task: Task object. """
self.task = task self.task.data.update(self.task_data) self.task_type = task.task_spec.__class__.__name__ self.spec = task.task_spec self.task_name = task.get_name() self.activity = getattr(self.spec, 'service_class', '') self._set_lane_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 set_client_cmds(self): """ This is method automatically called on each request and updates "object_id", "cmd" and "flow" client variables from current.input....
self.task_data['cmd'] = self.input.get('cmd') self.task_data['flow'] = self.input.get('flow') filters = self.input.get('filters', {}) try: if isinstance(filters, dict): # this is the new form, others will be removed when ui be ready self.ta...
<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_move(self, position): """ Returns valid and legal move given position :type: position: Board :rtype: Move """
while True: print(position) raw = input(str(self.color) + "\'s move \n") move = converter.short_alg(raw, self.color, position) if move is None: continue return move