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 get_active_threads_involving_all_participants(self, *participant_ids): """ Gets the threads where the specified participants are active and no one has left. ...
query = Thread.objects.\ exclude(participation__date_left__lte=now()).\ annotate(count_participants=Count('participants')).\ filter(count_participants=len(participant_ids)) for participant_id in participant_ids: query = query.filter(participants__id=par...
<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_thread(self, request, name=None, *participant_ids): """ When a Participant posts a message to other participants without specifying an existing...
# we get the current participant # or create him if he does not exit participant_ids = list(participant_ids) if request.rest_messaging_participant.id not in participant_ids: participant_ids.append(request.rest_messaging_participant.id) # we need at least one other...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def return_daily_messages_count(self, sender): """ Returns the number of messages sent in the last 24 hours so we can ensure the user does not exceed his messagi...
h24 = now() - timedelta(days=1) return Message.objects.filter(sender=sender, sent_at__gte=h24).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 check_who_read(self, messages): """ Check who read each message. """
# we get the corresponding Participation objects for m in messages: readers = [] for p in m.thread.participation_set.all(): if p.date_last_check is None: pass elif p.date_last_check > m.sent_at: # the messag...
<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_is_notification(self, participant_id, messages): """ Check if each message requires a notification for the specified participant. """
try: # we get the last check last_check = NotificationCheck.objects.filter(participant__id=participant_id).latest('id').date_check except Exception: # we have no notification check # all the messages are considered as new for m in messages: ...
<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_lasts_messages_of_threads(self, participant_id, check_who_read=True, check_is_notification=True): """ Returns the last message in each thread """
# we get the last message for each thread # we must query the messages using two queries because only Postgres supports .order_by('thread', '-sent_at').distinct('thread') threads = Thread.managers.\ get_threads_where_participant_is_active(participant_id).\ annotate(last_...
<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_messages_in_thread(self, participant_id, thread_id, check_who_read=True): """ Returns all the messages in a thread. """
try: messages = Message.objects.filter(thread__id=thread_id).\ order_by('-id').\ select_related('thread').\ prefetch_related('thread__participation_set', 'thread__participation_set__participant') except Exception: return Message.ob...
<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, request, *args, **kwargs): """ We ensure the Thread only involves eligible participants. """
serializer = self.get_serializer(data=compat_get_request_data(request)) compat_serializer_check_is_valid(serializer) self.perform_create(request, serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, head...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mark_thread_as_read(self, request, pk=None): """ Pk is the pk of the Thread to which the messages belong. """
# we get the thread and check for permission thread = Thread.objects.get(id=pk) self.check_object_permissions(request, thread) # we save the date try: participation = Participation.objects.get(thread=thread, participant=request.rest_messaging_participant) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def process(self, quoted=False): ''' Parse an URL ''' self.p = urlparse(self.raw) self.scheme = self.p.scheme self.netloc = self.p.netloc self.opath = self.p.path if not quoted else quote(self.p.path) self.path = [x for x in self.opath.split('/') if x] self.params...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def fetch(self, url, encoding=None, force_refetch=False, nocache=False, quiet=True): ''' Fetch a HTML file as binary''' try: if not force_refetch and self.cache is not None and url in self.cache: # try to look for content in cache logging.debug('Retrieving con...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _platform(self) -> Optional[str]: """Extract platform."""
try: return str(self.journey.MainStop.BasicStop.Dep.Platform.text) except AttributeError: return 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 _delay(self) -> int: """Extract departure delay."""
try: return int(self.journey.MainStop.BasicStop.Dep.Delay.text) except AttributeError: return 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 _departure(self) -> datetime: """Extract departure time."""
departure_time = datetime.strptime( self.journey.MainStop.BasicStop.Dep.Time.text, "%H:%M" ).time() if departure_time > (self.now - timedelta(hours=1)).time(): return datetime.combine(self.now.date(), departure_time) return datetime.combine(self.now.date() + time...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract(self, attribute) -> str: """Extract train information."""
attr_data = self.journey.JourneyAttributeList.JourneyAttribute[ self.attr_types.index(attribute) ].Attribute attr_variants = attr_data.xpath("AttributeVariant/@type") data = attr_data.AttributeVariant[attr_variants.index("NORMAL")].Text.pyval return str(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 _pass_list(self) -> List[Dict[str, Any]]: """Extract next stops along the journey."""
stops: List[Dict[str, Any]] = [] for stop in self.journey.PassList.BasicStop: index = stop.get("index") station = stop.Location.Station.HafasName.Text.text station_id = stop.Location.Station.ExternalId.text stops.append({"index": index, "stationId": stati...
<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(style): """Check `style` against pyout.styling.schema. Parameters style : dict Style object to validate. Raises ------ StyleValidationError if `styl...
try: import jsonschema except ImportError: return try: jsonschema.validate(style, schema) except jsonschema.ValidationError as exc: new_exc = StyleValidationError(exc) # Don't dump the original jsonschema exception because it is already # included in the...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def value_type(value): """Classify `value` of bold, color, and underline keys. Parameters value : style value Returns ------- str, {"simple", "lookup", "re_looku...
try: keys = list(value.keys()) except AttributeError: return "simple" if keys in [["lookup"], ["re_lookup"], ["interval"]]: return keys[0] raise ValueError("Type of `value` could not be determined")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _register_mecab_loc(location): ''' Set MeCab binary location ''' global MECAB_LOC if not os.path.isfile(location): logging.getLogger(__name__).warning("Provided mecab binary location does not exist {}".format(location)) logging.getLogger(__name__).info("Mecab binary is switched to: {}"....
<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_mecab_process(content, *args, **kwargs): ''' Use subprocess to run mecab ''' encoding = 'utf-8' if 'encoding' not in kwargs else kwargs['encoding'] mecab_loc = kwargs['mecab_loc'] if 'mecab_loc' in kwargs else None if mecab_loc is None: mecab_loc = MECAB_LOC proc_args = [mecab_...
<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(content, *args, **kwargs): ''' Use mecab-python3 by default to parse JP text. Fall back to mecab binary app if needed ''' global MECAB_PYTHON3 if 'mecab_loc' not in kwargs and MECAB_PYTHON3 and 'MeCab' in globals(): return MeCab.Tagger(*args).parse(content) else: return r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def voice(self): """tuple. contain text and lang code """
dbid = self.lldb.dbid text, lang = self._voiceoverdb.get_text_lang(dbid) return text, lang
<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, src): """ store an audio file to storage dir :param src: audio file path :return: checksum value """
if not audio.get_type(src): raise TypeError('The type of this file is not supported.') return super().add(src)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_cmd(command, arguments): """Merge command with arguments."""
if arguments is None: arguments = [] if command.endswith(".py") or command.endswith(".pyw"): return [sys.executable, command] + list(arguments) else: return [command] + list(arguments)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def argparse(argv, parser, arguments): """ A command line argument parser. Parses arguments coming from the argv Observable and outputs them as Argument items in...
def add_arg(parser, arg_spec): parser.add_argument(arg_spec.name, help=arg_spec.help) return parser parse_request = parser \ .map(lambda i: ArgumentParser(description=i.description)) \ .combine_latest(arguments, lambda parser, arg_def: add_arg(parser,arg_def)) \ .last(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def qn(phi, *n): """ Calculate the complex flow vector `Q_n`. :param array-like phi: Azimuthal angles. :param int n: One or more harmonics to calculate. :returns...
phi = np.ravel(phi) n = np.asarray(n) i_n_phi = np.zeros((n.size, phi.size), dtype=complex) np.outer(n, phi, out=i_n_phi.imag) qn = np.exp(i_n_phi, out=i_n_phi).sum(axis=1) if qn.size == 1: qn = qn[0] return qn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def correlation(self, n, k, error=False): r""" Calculate `\langle k \rangle_n`, the `k`-particle correlation function for `n`\ th-order anisotropy. :param int n:...
self._calculate_corr(n, k) corr_nk = self._corr[n][k] if error: self._calculate_corr_err(n, k) return corr_nk, self._corr_err[n][k] else: return corr_nk
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pdf(self, phi): """ Evaluate the _unnormalized_ flow PDF. """
pdf = np.inner(self._vn, np.cos(np.outer(phi, self._n))) pdf *= 2. pdf += 1. return pdf
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _uniform_phi(M): """ Generate M random numbers in [-pi, pi). """
return np.random.uniform(-np.pi, np.pi, 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 sample(self, multiplicity): r""" Randomly sample azimuthal angles `\phi`. :param int multiplicity: Number to sample. :returns: Array of sampled angles. """
if self._n is None: return self._uniform_phi(multiplicity) # Since the flow PDF does not have an analytic inverse CDF, I use a # simple accept-reject sampling algorithm. This is reasonably # efficient since for normal-sized vn, the PDF is close to flat. Now # due ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dumps(obj, *args, **kwargs): ''' Typeless dump an object to json string ''' return json.dumps(obj, *args, cls=TypelessSONEncoder, ensure_ascii=False, **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 txt2mecab(text, **kwargs): ''' Use mecab to parse one sentence ''' mecab_out = _internal_mecab_parse(text, **kwargs).splitlines() tokens = [MeCabToken.parse(x) for x in mecab_out] return MeCabSent(text, tokens)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def lines2mecab(lines, **kwargs): ''' Use mecab to parse many lines ''' sents = [] for line in lines: sent = txt2mecab(line, **kwargs) sents.append(sent) return sents
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pos3(self): ''' Use pos-sc1-sc2 as POS ''' parts = [self.pos] if self.sc1 and self.sc1 != '*': parts.append(self.sc1) if self.sc2 and self.sc2 != '*': parts.append(self.sc2) return '-'.join(parts)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def to_ruby(self): ''' Convert one MeCabToken into HTML ''' if self.need_ruby(): surface = self.surface reading = self.reading_hira() return '<ruby><rb>{sur}</rb><rt>{read}</rt></ruby>'.format(sur=surface, read=reading) elif self.is_eos: 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 add(self, sentence_text, **kwargs): ''' Parse a text string and add it to this doc ''' sent = MeCabSent.parse(sentence_text, **kwargs) self.sents.append(sent) return sent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def output(self, response, accepts): """ Formats a response from a view to handle any RDF graphs If a view function returns an RDF graph, serialize it based...
graph = self.get_graph(response) if graph is not None: # decide the format mimetype, format = self.format_selector.decide(accepts, graph.context_aware) # requested content couldn't find anything if mimetype is None: return self.make_406_response() # explicitly mark text mimetypes as utf-8 i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decorate(self, view): """ Wraps a view function to return formatted RDF graphs Uses content negotiation to serialize the graph to the client-preferred f...
from functools import wraps @wraps(view) def decorated(*args, **kwargs): response = view(*args, **kwargs) accept = self.get_accept() return self.output(response, accept) return decorated
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ecc(self, n): r""" Calculate eccentricity harmonic `\varepsilon_n`. :param int n: Eccentricity order. """
ny, nx = self._profile.shape xmax, ymax = self._xymax xcm, ycm = self._cm # create (X, Y) grids relative to CM Y, X = np.mgrid[ymax:-ymax:1j*ny, -xmax:xmax:1j*nx] X -= xcm Y -= ycm # create grid of weights = profile * R^n Rsq = X*X + Y*Y ...
<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, var, default=None): """Return a value from configuration. Safe version which always returns a default value if the value is not found. """
try: return self.__get(var) except (KeyError, IndexError): return 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 insert(self, var, value, index=None): """Insert at the index. If the index is not provided appends to the end of the list. """
current = self.__get(var) if not isinstance(current, list): raise KeyError("%s: is not a list" % var) if index is None: current.append(value) else: current.insert(index, value) if self.auto_save: self.save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def keys(self): """Return a merged set of top level keys from all configurations."""
s = set() for config in self.__configs: s |= config.keys() return 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 split(s, posix=True): """Split the string s using shell-like syntax. Args: s (str): String to split posix (bool): Use posix split Returns: list of str: Lis...
if isinstance(s, six.binary_type): s = s.decode("utf-8") return shlex.split(s, posix=posix)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(path, matcher="*", dirs=False, files=True): """Recursive search function. Args: path (str): Path to search recursively matcher (str or callable): St...
if callable(matcher): def fnmatcher(items): return list(filter(matcher, items)) else: def fnmatcher(items): return fnmatch.filter(items, matcher) for root, directories, filenames in os.walk(os.path.abspath(path)): to_match = [] if dirs: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chdir(directory): """Change the current working directory. Args: directory (str): Directory to go to. """
directory = os.path.abspath(directory) logger.info("chdir -> %s" % directory) try: if not os.path.isdir(directory): logger.error( "chdir -> %s failed! Directory does not exist!", directory ) return False os.chdir(directory) 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 goto(directory, create=False): """Context object for changing directory. Args: directory (str): Directory to go to. create (bool): Create directory if it d...
current = os.getcwd() directory = os.path.abspath(directory) if os.path.isdir(directory) or (create and mkdir(directory)): logger.info("goto -> %s", directory) os.chdir(directory) try: yield True finally: logger.info("goto <- %s", directory) ...
<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(path): """Delete a file or directory. Args: path (str): Path to the file or directory that needs to be deleted. Returns: bool: True if the operation ...
if os.path.isdir(path): return __rmtree(path) else: return __rmfile(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 read(path, encoding="utf-8"): """Read the content of the file. Args: path (str): Path to the file encoding (str): File encoding. Default: utf-8 Returns: st...
try: with io.open(path, encoding=encoding) as f: return f.read() except Exception as e: logger.error("read: %s failed. Error: %s", path, e) 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 touch(path, content="", encoding="utf-8", overwrite=False): """Create a file at the given path if it does not already exists. Args: path (str): Path to the ...
path = os.path.abspath(path) if not overwrite and os.path.exists(path): logger.warning('touch: "%s" already exists', path) return False try: logger.info("touch: %s", path) with io.open(path, "wb") as f: if not isinstance(content, six.binary_type): ...
<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(path="", obj=None): """Return an object from a dot path. Path can either be a full path, in which case the `get_object` function will try to impor...
if not path: return obj path = path.split(".") if obj is None: obj = importlib.import_module(path[0]) path = path[1:] for item in path: if item == "*": # This is the star query, returns non hidden objects return [ getattr(obj, 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 load_subclasses(klass, modules=None): """Load recursively all all subclasses from a module. Args: klass (str or list of str): Class whose subclasses we want...
if modules: if isinstance(modules, six.string_types): modules = [modules] loader = Loader() loader.load(*modules) return klass.__subclasses__()
<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_exception(): """Return full formatted traceback as a string."""
trace = "" exception = "" exc_list = traceback.format_exception_only( sys.exc_info()[0], sys.exc_info()[1] ) for entry in exc_list: exception += entry tb_list = traceback.format_tb(sys.exc_info()[2]) for entry in tb_list: trace += entry return "%s\n%s" % (excepti...
<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, *modules): """Load one or more modules. Args: modules: Either a string full path to a module or an actual module object. """
for module in modules: if isinstance(module, six.string_types): try: module = get_object(module) except Exception as e: self.errors[module] = e continue self.modules[module.__package__] = module ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _product_filter(products) -> str: """Calculate the product filter."""
_filter = 0 for product in {PRODUCTS[p] for p in products}: _filter += product return format(_filter, "b")[::-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 _base_url() -> str: """Build base url."""
_lang: str = "d" _type: str = "n" _with_suggestions: str = "?" return BASE_URI + STBOARD_PATH + _lang + _type + _with_suggestions
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def get_departures( self, station_id: str, direction_id: Optional[str] = None, max_journeys: int = 20, products: Optional[List[str]] = None, ) -> Dict[str, ...
self.station_id: str = station_id self.direction_id: str = direction_id self.max_journeys: int = max_journeys self.products_filter: str = _product_filter(products or ALL_PRODUCTS) base_url: str = _base_url() params: Dict[str, Union[str, int]] = { "selectDa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data(self) -> Dict[str, Any]: """Return travel data."""
data: Dict[str, Any] = {} data["station"] = self.station data["stationId"] = self.station_id data["filter"] = self.products_filter journeys = [] for j in sorted(self.journeys, key=lambda k: k.real_departure)[ : self.max_journeys ]: journe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _station(self) -> str: """Extract station name."""
return str(self.obj.SBRes.SBReq.Start.Station.HafasName.Text.pyval)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def current_time(self) -> datetime: """Extract current time."""
_date = datetime.strptime(self.obj.SBRes.SBReq.StartT.get("date"), "%Y%m%d") _time = datetime.strptime(self.obj.SBRes.SBReq.StartT.get("time"), "%H:%M") return datetime.combine(_date.date(), _time.time())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def process_file(path, processor, encoding='utf-8', mode='rt', *args, **kwargs): ''' Process a text file's content. If the file name ends with .gz, read it as gzip file ''' if mode not in ('rU', 'rt', 'rb', 'r'): raise Exception("Invalid file reading mode") with open(path, encoding=encoding, mode=mo...
<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_file(path, encoding='utf-8', *args, **kwargs): ''' Read text file content. If the file name ends with .gz, read it as gzip file. If mode argument is provided as 'rb', content will be read as byte stream. By default, content is read as string. ''' if 'mode' in kwargs and kwargs['mode'] == 'r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def write_file(path, content, mode=None, encoding='utf-8'): ''' Write content to a file. If the path ends with .gz, gzip will be used. ''' if not mode: if isinstance(content, bytes): mode = 'wb' else: mode = 'wt' if not path: raise ValueError("Output path is i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forbid_multi_line_headers(name, val): """Forbid multi-line headers, to prevent header injection."""
val = smart_text(val) if "\n" in val or "\r" in val: raise BadHeaderError( "Header values can't contain newlines " "(got %r for header %r)" % (val, name) ) try: val = val.encode("ascii") except UnicodeEncodeError: if name.lower() in ("to...
<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): """Close the connection to the email server."""
try: try: self.connection.quit() except socket.sslerror: # This happens when calling quit() on a TLS connection # sometimes. self.connection.close() except Exception as e: logger.error( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send(self, message): """Send an email. Helper method that does the actual sending. """
if not message.recipients(): return False try: self.connection.sendmail( message.sender, message.recipients(), message.message().as_string(), ) except Exception as e: logger.error( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attach_file(self, path, mimetype=None): """Attache a file from the filesystem."""
filename = os.path.basename(path) content = open(path, "rb").read() self.attach(filename, content, 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 _create_attachment(self, filename, content, mimetype=None): """Convert the filename, content, mimetype triple to attachment."""
if mimetype is None: mimetype, _ = mimetypes.guess_type(filename) if mimetype is None: mimetype = DEFAULT_ATTACHMENT_MIME_TYPE basetype, subtype = mimetype.split("/", 1) if basetype == "text": attachment = SafeMIMEText( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attach_alternative(self, content, mimetype=None): """Attach an alternative content representation."""
self.attach(content=content, 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 setup_logging(verbose=False, logger=None): """Setup console logging. Info and below go to stdout, others go to stderr. :param bool verbose: Print debug state...
if not verbose: logging.getLogger('requests').setLevel(logging.WARNING) format_ = '%(asctime)s %(levelname)-8s %(name)-40s %(message)s' if verbose else '%(message)s' level = logging.DEBUG if verbose else logging.INFO handler_stdout = logging.StreamHandler(sys.stdout) handler_stdout.setFor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def with_log(func): """Automatically adds a named logger to a function upon function call. :param func: Function to decorate. :return: Decorated function. :rtype...
@functools.wraps(func) def wrapper(*args, **kwargs): """Inject `log` argument into wrapped function. :param list args: Pass through all positional arguments. :param dict kwargs: Pass through all keyword arguments. """ decorator_logger = logging.getLogger('@with_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 get_arguments(argv=None, environ=None): """Get command line arguments or values from environment variables. :param list argv: Command line argument list to p...
name = 'appveyor-artifacts' environ = environ or os.environ require = getattr(pkg_resources, 'require') # Stupid linting error. commit, owner, pull_request, repo, tag = '', '', '', '', '' # Run docopt. project = [p for p in require(name) if p.project_name == name][0] version = project.ver...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_api(endpoint, log): """Query the AppVeyor API. :raise HandledError: On non HTTP200 responses or invalid JSON response. :param str endpoint: API endpoin...
url = API_PREFIX + endpoint headers = {'content-type': 'application/json'} response = None log.debug('Querying %s with headers %s.', url, headers) for i in range(QUERY_ATTEMPTS): try: try: response = requests.get(url, headers=headers, timeout=10) exce...
<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(config, log): """Validate config values. :raise HandledError: On invalid config values. :param dict config: Dictionary from get_arguments(). :param ...
if config['always_job_dirs'] and config['no_job_dirs']: log.error('Contradiction: --always-job-dirs and --no-job-dirs used.') raise HandledError if config['commit'] and not REGEX_COMMIT.match(config['commit']): log.error('No or invalid git commit obtained.') raise HandledError ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_build_version(config, log): """Find the build version we're looking for. AppVeyor calls build IDs "versions" which is confusing but whatever. Job IDs a...
url = '/projects/{0}/{1}/history?recordsNumber=10'.format(config['owner'], config['repo']) # Query history. log.debug('Querying AppVeyor history API for %s/%s...', config['owner'], config['repo']) json_data = query_api(url) if 'builds' not in json_data: log.error('Bad JSON reply: "builds" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_job_ids(build_version, config, log): """Get one or more job IDs and their status associated with a build version. Filters jobs by name if --job-name is...
url = '/projects/{0}/{1}/build/{2}'.format(config['owner'], config['repo'], build_version) # Query version. log.debug('Querying AppVeyor version API for %s/%s at %s...', config['owner'], config['repo'], build_version) json_data = query_api(url) if 'build' not in json_data: log.error('Bad J...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_artifacts(job_ids, log): """Query API again for artifacts. :param iter job_ids: List of AppVeyor jobIDs. :param logging.Logger log: Logger for this fun...
jobs_artifacts = list() for job in job_ids: url = '/buildjobs/{0}/artifacts'.format(job) log.debug('Querying AppVeyor artifact API for %s...', job) json_data = query_api(url) for artifact in json_data: jobs_artifacts.append((job, artifact['fileName'], artifact['size'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def artifacts_urls(config, jobs_artifacts, log): """Determine destination file paths for job artifacts. :param dict config: Dictionary from get_arguments(). :par...
artifacts = dict() # Determine if we should create job ID directories. if config['always_job_dirs']: job_dirs = True elif config['no_job_dirs']: job_dirs = False elif len(set(i[0] for i in jobs_artifacts)) == 1: log.debug('Only one job ID, automatically setting job_dirs = F...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_urls(config, log): """Wait for AppVeyor job to finish and get all artifacts' URLs. :param dict config: Dictionary from get_arguments(). :param logging.Lo...
# Wait for job to be queued. Once it is we'll have the "version". build_version = None for _ in range(3): build_version = query_build_version(config) if build_version: break log.info('Waiting for job to be queued...') time.sleep(SLEEP_FOR) if not build_versio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mangle_coverage(local_path, log): """Edit .coverage file substituting Windows file paths to Linux paths. :param str local_path: Destination path to save file...
# Read the file, or return if not a .coverage file. with open(local_path, mode='rb') as handle: if handle.read(13) != b'!coverage.py:': log.debug('File %s not a coverage file.', local_path) return handle.seek(0) # I'm lazy, reading all of this into memory. What ...
<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(config, log): """Main function. Runs the program. :param dict config: Dictionary from get_arguments(). :param logging.Logger log: Logger for this functi...
validate(config) paths_and_urls = get_urls(config) if not paths_and_urls: log.warning('No artifacts; nothing to download.') return # Download files. total_size = 0 chunk_size = max(min(max(v[1] for v in paths_and_urls.values()) // 50, 1048576), 1024) log.info('Downloading f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def entry_point(): """Entry-point from setuptools."""
signal.signal(signal.SIGINT, lambda *_: getattr(os, '_exit')(0)) # Properly handle Control+C config = get_arguments() setup_logging(config['verbose']) try: main(config) except HandledError: if config['raise']: raise logging.critical('Failure.') sys.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 incoming_messages(self) -> t.List[t.Tuple[float, bytes]]: """Consume the receive buffer and return the messages. If there are new messages added to the queue ...
approximate_messages = self._receive_buffer.qsize() messages = [] for _ in range(approximate_messages): try: messages.append(self._receive_buffer.get_nowait()) except queue.Empty: break return messages
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _safe_get(mapping, key, default=None): """Helper for accessing style values. It exists to avoid checking whether `mapping` is indeed a mapping before trying ...
try: return mapping.get(key, default) except AttributeError: return 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 strip_callables(row): """Extract callable values from `row`. Replace the callable values with the initial value (if specified) or an empty string. Parameters...
callables = [] to_delete = [] to_add = [] for columns, value in row.items(): if isinstance(value, tuple): initial, fn = value else: initial = NOTHING # Value could be a normal (non-callable) value or 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 build(self, columns): """Build the style and fields. Parameters columns : list of str Column names. """
self.columns = columns default = dict(elements.default("default_"), **_safe_get(self.init_style, "default_", {})) self.style = elements.adopt({c: default for c in columns}, self.init_style) # Store special keys in _style so tha...
<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, name, attributes): """Construct a style taking `attributes` from the column styles. Parameters name : str Name of main style (e.g., "header_")...
name_style = _safe_get(self.init_style, name, elements.default(name)) if self.init_style is not None and name_style is not None: result = {} for col in self.columns: cstyle = {k: v for k, v in self.style[col].items() if k in attributes} ...
<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_widths(self, row, proc_group): """Update auto-width Fields based on `row`. Parameters row : dict proc_group : {'default', 'override'} Whether to conside...
width_free = self.style["width_"] - sum( [sum(self.fields[c].width for c in self.columns), self.width_separtor]) if width_free < 0: width_fixed = sum( [sum(self.fields[c].width for c in self.columns if c not in self.autowidth_co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _proc_group(self, style, adopt=True): """Return whether group is "default" or "override". In the case of "override", the self.fields pre-format and post-form...
fields = self.fields if style is not None: if adopt: style = elements.adopt(self.style, style) elements.validate(style) for column in self.columns: fields[column].add( "pre", "override", *(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 render(self, row, style=None, adopt=True): """Render fields with values from `row`. Parameters row : dict A normalized row. style : dict, optional A style th...
group = self._proc_group(style, adopt=adopt) if group == "override": # Override the "default" processor key. proc_keys = ["width", "override"] else: # Use the set of processors defined by _setup_fields. proc_keys = None adjusted = self._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 get_config(self): """ Sets up the basic config from the variables passed in all of these are from what Heroku gives you. """
self.create_ssl_certs() config = { "bootstrap_servers": self.get_brokers(), "security_protocol": 'SSL', "ssl_cafile": self.ssl["ca"]["file"].name, "ssl_certfile": self.ssl["cert"]["file"].name, "ssl_keyfile": self.ssl["key"]["file"].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_ssl_certs(self): """ Creates SSL cert files """
for key, file in self.ssl.items(): file["file"] = self.create_temp_file(file["suffix"], file["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 create_temp_file(self, suffix, content): """ Creates file, because environment variables are by default escaped it encodes and then decodes them before write...
temp = tempfile.NamedTemporaryFile(suffix=suffix) temp.write(content.encode('latin1').decode('unicode_escape').encode('utf-8')) temp.seek(0) # Resets the temp file line to 0 return temp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self, topic, *args, **kwargs): """ Appends the prefix to the topic before sendingf """
prefix_topic = self.heroku_kafka.prefix_topic(topic) return super(HerokuKafkaProducer, self).send(prefix_topic, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, variable_path: str, default: t.Optional[t.Any] = None, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None, **kwargs): "...
raise NotImplementedError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coerce(val: t.Any, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None) -> t.Any: """ Casts a type of ``val`` to ``coerce_type`` wi...
if not coerce_type and not coercer: return val if coerce_type and type(val) is coerce_type: return val if coerce_type and coerce_type is bool and not coercer: coercer = coerce_str_to_bool if coercer is None: coercer = coerce_type ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _splice(value, n): """Splice `value` at its center, retaining a total of `n` characters. Parameters value : str n : int The total length of the returned ends...
if n <= 0: raise ValueError("n must be positive") value_len = len(value) center = value_len // 2 left, right = value[:center], value[center:] if n >= value_len: return left, right n_todrop = value_len - n right_idx = n_todrop // 2 left_idx = right_idx + n_todrop % 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 add(self, kind, key, *values): """Add processor functions. Any previous list of processors for `kind` and `key` will be overwritten. Parameters kind : {"pre"...
if kind == "pre": procs = self.pre elif kind == "post": procs = self.post else: raise ValueError("kind is not 'pre' or 'post'") self._check_if_registered(key) procs[key] = values
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _format(self, _, result): """Wrap format call as a two-argument processor function. """
return self._fmt.format(six.text_type(result))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(function): """Return a processor for a style's "transform" function. """
def transform_fn(_, result): if isinstance(result, Nothing): return result lgr.debug("Transforming %r with %r", result, function) try: return function(result) except: exctype, value, tb = sys.exc_info() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def by_key(self, style_key, style_value): """Return a processor for a "simple" style value. Parameters style_key : str A style key. style_value : bool or str A "...
if self.style_types[style_key] is bool: style_attr = style_key else: style_attr = style_value def proc(_, result): return self.render(style_attr, result) return proc