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 _instance(self, cls, *args, **kwargs): """Return the instance. :param cls: the class to create the instance from :param args: given to the ``__init__`` metho...
logger.debug(f'args: {args}, kwargs: {kwargs}') return cls(*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 instance(self, name=None, *args, **kwargs): """Create a new instance using key ``name``. :param name: the name of the class (by default) or the key name of t...
logger.info(f'new instance of {name}') t0 = time() name = self.default_name if name is None else name logger.debug(f'creating instance of {name}') class_name, params = self._class_name_params(name) cls = self._find_class(class_name) params.update(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 load(self, name=None, *args, **kwargs): "Load the instance of the object from the stash." inst = self.stash.load(name) if inst is None: inst = self.instance(name, *args, **kwargs) logger.debug(f'loaded (conf mng) instance: {inst}') return inst
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dump(self, name: str, inst): "Save the object instance to the stash." self.stash.dump(name, inst)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_global(self): """Clear only any cached global data. """
vname = self.varname logger.debug(f'global clearning {vname}') if vname in globals(): logger.debug('removing global instance var: {}'.format(vname)) del globals()[vname]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(self): """Clear the data, and thus, force it to be created on the next fetch. This is done by removing the attribute from ``owner``, deleting it from g...
vname = self.varname if self.path.exists(): logger.debug('deleting cached work: {}'.format(self.path)) self.path.unlink() if self.owner is not None and hasattr(self.owner, vname): logger.debug('removing instance var: {}'.format(vname)) delattr(sel...
<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_or_create(self, *argv, **kwargs): """Invoke the file system operations to get the data, or create work. If the file does not exist, calling ``__do_work...
if self.path.exists(): self._info('loading work from {}'.format(self.path)) with open(self.path, 'rb') as f: obj = pickle.load(f) else: self._info('saving work to {}'.format(self.path)) with open(self.path, 'wb') as f: obj ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_data(self): """Return whether or not the stash has any data available or not."""
if not hasattr(self, '_has_data'): try: next(iter(self.delegate.keys())) self._has_data = True except StopIteration: self._has_data = False return self._has_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 _get_instance_path(self, name): "Return a path to the pickled data with key ``name``." fname = self.pattern.format(**{'name': name}) logger.debug(f'path {self.create_path}: {self.create_path.exists()}') self._create_path_dir() return Path(self.create_path, fname)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shelve(self): """Return an opened shelve object. """
logger.info('creating shelve data') fname = str(self.create_path.absolute()) inst = sh.open(fname, writeback=self.writeback) self.is_open = True return inst
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delete(self, name=None): "Delete the shelve data file." logger.info('clearing shelve data') self.close() for path in Path(self.create_path.parent, self.create_path.name), \ Path(self.create_path.parent, self.create_path.name + '.db'): logger.debug(f'clearing {...
<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 shelve object, which is needed for data consistency." if self.is_open: logger.info('closing shelve data') try: self.shelve.close() self._shelve.clear() except Exception: self.is_open = False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _map(self, data_item): "Map ``data_item`` separately in each thread." delegate = self.delegate logger.debug(f'mapping: {data_item}') if self.clobber or not self.exists(data_item.id): logger.debug(f'exist: {data_item.id}: {self.exists(data_item.id)}') delegate....
<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_all(self, workers=None, limit=None, n_expected=None): """Load all instances witih multiple threads. :param workers: number of workers to use to load ins...
if not self.has_data: self._preempt(True) # we did the best we could (avoid repeat later in this method) n_expected = 0 keys = tuple(self.delegate.keys()) if n_expected is not None and len(keys) < n_expected: self._preempt(True) keys =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spawn_api(self, app, decorator=None): """Auto-generate server endpoints implementing the API into this Flask app"""
if decorator: assert type(decorator).__name__ == 'function' self.is_server = True self.app = app if self.local: # Re-generate client callers, this time as local and passing them the app self._generate_client_callers(app) return spawn_server_...
<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_expression(self): '''Update internal expression.''' self._expression = re.compile( '^{0}(?P<index>(?P<padding>0*)\d+?){1}$' .format(re.escape(self.head), re.escape(self.tail)) )
<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_contiguous(self): '''Return whether entire collection is contiguous.''' previous = None for index in self.indexes: if previous is None: previous = index continue if index != (previous + 1): return False ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def holes(self): '''Return holes in collection. Return :py:class:`~clique.collection.Collection` of missing indexes. ''' missing = set([]) previous = None for index in self.indexes: if previous is None: previous = index contin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def separate(self): '''Return contiguous parts of collection as separate collections. Return as list of :py:class:`~clique.collection.Collection` instances. ''' collections = [] start = None end = None for index in self.indexes: if start is 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 format_check(settings): """ Check the format of a osmnet_config object. Parameters settings : dict osmnet_config as a dictionary Returns ------- Nothing """
valid_keys = ['logs_folder', 'log_file', 'log_console', 'log_name', 'log_filename', 'keep_osm_tags'] for key in list(settings.keys()): assert key in valid_keys, \ ('{} not found in list of valid configuation keys').format(key) assert isinstance(key, str), ('{} mu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(self): """ Return a dict representation of an osmnet osmnet_config instance. """
return {'logs_folder': self.logs_folder, 'log_file': self.log_file, 'log_console': self.log_console, 'log_name': self.log_name, 'log_filename': self.log_filename, 'keep_osm_tags': self.keep_osm_tags }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def osm_filter(network_type): """ Create a filter to query Overpass API for the specified OSM network type. Parameters network_type : string, {'walk', 'drive'} d...
filters = {} # drive: select only roads that are drivable by normal 2 wheel drive # passenger vehicles both private and public # roads. Filter out un-drivable roads and service roads tagged as parking, # driveway, or emergency-access filters['drive'] = ('["highway"!~"cycleway|footway|path|pede...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def osm_net_download(lat_min=None, lng_min=None, lat_max=None, lng_max=None, network_type='walk', timeout=180, memory=None, max_query_area_size=50*1000*50*1000, c...
# create a filter to exclude certain kinds of ways based on the requested # network_type if custom_osm_filter is None: request_filter = osm_filter(network_type) else: request_filter = custom_osm_filter response_jsons_list = [] response_jsons = [] # server memory allocatio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def overpass_request(data, pause_duration=None, timeout=180, error_pause_duration=None): """ Send a request to the Overpass API via HTTP POST and return the JSON...
# define the Overpass API URL, then construct a GET-style URL url = 'http://www.overpass-api.de/api/interpreter' start_time = time.time() log('Posting to {} with timeout={}, "{}"'.format(url, timeout, data)) response = requests.post(url, data=data, timeout=timeout) # get the response size an...
<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_pause_duration(recursive_delay=5, default_duration=10): """ Check the Overpass API status endpoint to determine how long to wait until next slot is avail...
try: response = requests.get('http://overpass-api.de/api/status') status = response.text.split('\n')[3] status_first_token = status.split(' ')[0] except Exception: # if status endpoint cannot be reached or output parsed, log error # and return default duration lo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def project_geometry(geometry, crs, to_latlong=False): """ Project a shapely Polygon or MultiPolygon from WGS84 to UTM, or vice-versa Parameters geometry : shape...
gdf = gpd.GeoDataFrame() gdf.crs = crs gdf.name = 'geometry to project' gdf['geometry'] = None gdf.loc[0, 'geometry'] = geometry gdf_proj = project_gdf(gdf, to_latlong=to_latlong) geometry_proj = gdf_proj['geometry'].iloc[0] return geometry_proj, gdf_proj.crs
<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_node(e): """ Process a node element entry into a dict suitable for going into a Pandas DataFrame. Parameters e : dict individual node element in down...
node = {'id': e['id'], 'lat': e['lat'], 'lon': e['lon']} if 'tags' in e: if e['tags'] is not np.nan: for t, v in list(e['tags'].items()): if t in config.settings.keep_osm_tags: node[t] = v return node
<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_way(e): """ Process a way element entry into a list of dicts suitable for going into a Pandas DataFrame. Parameters e : dict individual way element i...
way = {'id': e['id']} if 'tags' in e: if e['tags'] is not np.nan: for t, v in list(e['tags'].items()): if t in config.settings.keep_osm_tags: way[t] = v # nodes that make up a way waynodes = [] for n in e['nodes']: waynodes.append({...
<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_network_osm_query(data): """ Convert OSM query data to DataFrames of ways and way-nodes. Parameters data : dict Result of an OSM query. Returns -------...
if len(data['elements']) == 0: raise RuntimeError('OSM query results contain no data.') nodes = [] ways = [] waynodes = [] for e in data['elements']: if e['type'] == 'node': nodes.append(process_node(e)) elif e['type'] == 'way': w, wn = process_way(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ways_in_bbox(lat_min, lng_min, lat_max, lng_max, network_type, timeout=180, memory=None, max_query_area_size=50*1000*50*1000, custom_osm_filter=None): """ Ge...
return parse_network_osm_query( osm_net_download(lat_max=lat_max, lat_min=lat_min, lng_min=lng_min, lng_max=lng_max, network_type=network_type, timeout=timeout, memory=memory, max_query_area_size=max_query_area_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 intersection_nodes(waynodes): """ Returns a set of all the nodes that appear in 2 or more ways. Parameters waynodes : pandas.DataFrame Mapping of way IDs to ...
counts = waynodes.node_id.value_counts() return set(counts[counts > 1].index.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 node_pairs(nodes, ways, waynodes, two_way=True): """ Create a table of node pairs with the distances between them. Parameters nodes : pandas.DataFrame Must h...
start_time = time.time() def pairwise(l): return zip(islice(l, 0, len(l)), islice(l, 1, None)) intersections = intersection_nodes(waynodes) waymap = waynodes.groupby(level=0, sort=False) pairs = [] for id, row in ways.iterrows(): nodes_in_way = waymap.get_group(id).node_id.val...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_lines(in_file): """Returns a list of lines from a input markdown file."""
with open(in_file, 'r') as inf: in_contents = inf.read().split('\n') return in_contents
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tag_and_collect(lines, id_tag=True, back_links=False, exclude_h=None, remove_dashes=False): """ Gets headlines from the markdown document and creates anchor ...
out_contents = [] headlines = [] for l in lines: saw_headline = False orig_len = len(l) l = l.lstrip() if l.startswith(('# ', '## ', '### ', '#### ', '##### ', '###### ')): # comply with new markdown standards # not a headline if '#' not followed ...
<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_toc(headlines, hyperlink=True, top_link=False, no_toc_header=False): """ Creates the table of contents from the headline list that was returned by the...
processed = [] if not no_toc_header: if top_link: processed.append('<a class="mk-toclify" id="table-of-contents"></a>\n') processed.append('# Table of Contents') for line in headlines: if hyperlink: item = '%s- [%s](#%s)' % ((line[2]-1)*' ', line[0], line...
<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_markdown(toc_headlines, body, spacer=0, placeholder=None): """ Returns a string with the Markdown output contents incl. the table of contents. Keyword ...
if spacer: spacer_line = ['\n<div style="height:%spx;"></div>\n' % (spacer)] toc_markdown = "\n".join(toc_headlines + spacer_line) else: toc_markdown = "\n".join(toc_headlines) body_markdown = "\n".join(body).strip() if placeholder: markdown = body_markdown.replace(pla...
<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_markdown(markdown_cont, output_file): """ Writes to an output file if `outfile` is a valid path. """
if output_file: with open(output_file, 'w') as out: out.write(markdown_cont)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def markdown_toclify(input_file, output_file=None, github=False, back_to_top=False, nolink=False, no_toc_header=False, spacer=0, placeholder=None, exclude_h=None,...
raw_contents = read_lines(input_file) cleaned_contents = remove_lines(raw_contents, remove=('[[back to top]', '<a class="mk-toclify"')) processed_contents, raw_headlines = tag_and_collect( cleaned_contents, id_tag=not g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def url_parse(name): """parse urls with different prefixes"""
position = name.find("github.com") if position >= 0: if position != 0: position_1 = name.find("www.github.com") position_2 = name.find("http://github.com") position_3 = name.find("https://github.com") if position_1*position_2*position_3 != 0: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_req(url): """simple get request"""
request = urllib.request.Request(url) request.add_header('Authorization', 'token %s' % API_TOKEN) try: response = urllib.request.urlopen(request).read().decode('utf-8') return response except urllib.error.HTTPError: exception() sys.exit(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 geturl_req(url): """get request that returns 302"""
request = urllib.request.Request(url) request.add_header('Authorization', 'token %s' % API_TOKEN) try: response_url = urllib.request.urlopen(request).geturl() return response_url except urllib.error.HTTPError: exception() sys.exit(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 _parse_special_fields(self, data): """ Helper method that parses special fields to Python objects :param data: response from Monzo API request :type data: di...
self.created = parse_date(data.pop('created')) if data.get('settled'): # Not always returned self.settled = parse_date(data.pop('settled')) # Merchant field can contain either merchant ID or the whole object if (data.get('merchant') and not isinstance(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 _save_token_on_disk(self): """Helper function that saves the token on disk"""
token = self._token.copy() # Client secret is needed for token refreshing and isn't returned # as a pared of OAuth token by default token.update(client_secret=self._client_secret) with codecs.open(config.TOKEN_FILE_PATH, 'w', 'utf8') as f: json.dump( ...
<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_oauth_token(self): """ Get Monzo access token via OAuth2 `authorization code` grant type. Official docs: https://monzo.com/docs/#acquire-an-access-token...
url = urljoin(self.api_url, '/oauth2/token') oauth = OAuth2Session( client_id=self._client_id, redirect_uri=config.REDIRECT_URI, ) token = oauth.fetch_token( token_url=url, code=self._auth_code, client_secret=self._client_sec...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _refresh_oath_token(self): """ Refresh Monzo OAuth 2 token. Official docs: https://monzo.com/docs/#refreshing-access :raises UnableToRefreshTokenException: w...
url = urljoin(self.api_url, '/oauth2/token') data = { 'grant_type': 'refresh_token', 'client_id': self._client_id, 'client_secret': self._client_secret, 'refresh_token': self._token['refresh_token'], } token_response = requests.post(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 _get_response(self, method, endpoint, params=None): """ Helper method to handle HTTP requests and catch API errors :param method: valid HTTP method :type met...
url = urljoin(self.api_url, endpoint) try: response = getattr(self._session, method)(url, params=params) # Check if Monzo API returned HTTP 401, which could mean that the # token is expired if response.status_code == 401: raise TokenExpi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def whoami(self): """ Get information about the access token. Official docs: https://monzo.com/docs/#authenticating-requests :returns: access token details :rtyp...
endpoint = '/ping/whoami' response = self._get_response( method='get', endpoint=endpoint, ) return response.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def accounts(self, refresh=False): """ Returns a list of accounts owned by the currently authorised user. It's often used when deciding whether to require explic...
if not refresh and self._cached_accounts: return self._cached_accounts endpoint = '/accounts' response = self._get_response( method='get', endpoint=endpoint, ) accounts_json = response.json()['accounts'] accounts = [MonzoAccount(data=account) fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def balance(self, account_id=None): """ Returns balance information for a specific account. Official docs: https://monzo.com/docs/#read-balance :param account_id...
if not account_id: if len(self.accounts()) == 1: account_id = self.accounts()[0].id else: raise ValueError("You need to pass account ID") endpoint = '/balance' response = self._get_response( method='get', endpoint=endpoint, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pots(self, refresh=False): """ Returns a list of pots owned by the currently authorised user. Official docs: https://monzo.com/docs/#pots :param refresh: dec...
if not refresh and self._cached_pots: return self._cached_pots endpoint = '/pots/listV1' response = self._get_response( method='get', endpoint=endpoint, ) pots_json = response.json()['pots'] pots = [MonzoPot(data=pot) for pot in pots_json] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transactions(self, account_id=None, reverse=True, limit=None): """ Returns a list of transactions on the user's account. Official docs: https://monzo.com/doc...
if not account_id: if len(self.accounts()) == 1: account_id = self.accounts()[0].id else: raise ValueError("You need to pass account ID") endpoint = '/transactions' response = self._get_response( method='get', endpoint=endpoin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transaction(self, transaction_id, expand_merchant=False): """ Returns an individual transaction, fetched by its id. Official docs: https://monzo.com/docs/#re...
endpoint = '/transactions/{}'.format(transaction_id) data = dict() if expand_merchant: data['expand[]'] = 'merchant' response = self._get_response( method='get', endpoint=endpoint, params=data, ) return MonzoTransaction(data=response.json()['tr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def launcher(): """Launch it."""
parser = OptionParser() parser.add_option( '-f', '--file', dest='filename', default='agents.csv', help='snmposter configuration file' ) options, args = parser.parse_args() factory = SNMPosterFactory() snmpd_status = subprocess.Popen( ["service",...
<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_auth_string(self): """Create auth string from credentials."""
auth_info = '{}:{}'.format(self.sauce_username, self.sauce_access_key) return base64.b64encode(auth_info.encode('utf-8')).decode('utf-8')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_auth_headers(self, content_type): """Add authorization header."""
headers = self.make_headers(content_type) headers['Authorization'] = 'Basic {}'.format(self.get_auth_string()) return headers
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request(self, method, url, body=None, content_type='application/json'): """Send http request."""
headers = self.make_auth_headers(content_type) connection = http_client.HTTPSConnection(self.apibase) connection.request(method, url, body, headers=headers) response = connection.getresponse() data = response.read() connection.close() if response.status not in [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 get_user(self): """Access basic account information."""
method = 'GET' endpoint = '/rest/v1/users/{}'.format(self.client.sauce_username) return self.client.request(method, endpoint)
<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_user(self, username, password, name, email): """Create a sub account."""
method = 'POST' endpoint = '/rest/v1/users/{}'.format(self.client.sauce_username) body = json.dumps({'username': username, 'password': password, 'name': name, 'email': email, }) return self.client.request(method, endpoint, body)
<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_subaccounts(self): """Get a list of sub accounts associated with a parent account."""
method = 'GET' endpoint = '/rest/v1/users/{}/list-subaccounts'.format( self.client.sauce_username) return self.client.request(method, endpoint)
<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_siblings(self): """Get a list of sibling accounts associated with provided account."""
method = 'GET' endpoint = '/rest/v1.1/users/{}/siblings'.format( self.client.sauce_username) return self.client.request(method, endpoint)
<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_subaccount_info(self): """Get information about a sub account."""
method = 'GET' endpoint = '/rest/v1/users/{}/subaccounts'.format( self.client.sauce_username) return self.client.request(method, endpoint)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_access_key(self): """Change access key of your account."""
method = 'POST' endpoint = '/rest/v1/users/{}/accesskey/change'.format( self.client.sauce_username) return self.client.request(method, endpoint)
<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_usage(self, start=None, end=None): """Access historical account usage data."""
method = 'GET' endpoint = '/rest/v1/users/{}/usage'.format(self.client.sauce_username) data = {} if start: data['start'] = start if end: data['end'] = end if data: endpoint = '?'.join([endpoint, urlencode(data)]) return self.cl...
<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_platforms(self, automation_api='all'): """Get a list of objects describing all the OS and browser platforms currently supported on Sauce Labs."""
method = 'GET' endpoint = '/rest/v1/info/platforms/{}'.format(automation_api) return self.client.request(method, endpoint)
<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_jobs(self, full=None, limit=None, skip=None, start=None, end=None, output_format=None): """List jobs belonging to a specific user."""
method = 'GET' endpoint = '/rest/v1/{}/jobs'.format(self.client.sauce_username) data = {} if full is not None: data['full'] = full if limit is not None: data['limit'] = limit if skip is not None: data['skip'] = skip if start is...
<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_job(self, job_id, build=None, custom_data=None, name=None, passed=None, public=None, tags=None): """Edit an existing job."""
method = 'PUT' endpoint = '/rest/v1/{}/jobs/{}'.format(self.client.sauce_username, job_id) data = {} if build is not None: data['build'] = build if custom_data is not None: data['custom-data'] = custom_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 stop_job(self, job_id): """Terminates a running job."""
method = 'PUT' endpoint = '/rest/v1/{}/jobs/{}/stop'.format( self.client.sauce_username, job_id) return self.client.request(method, endpoint)
<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_job_asset_url(self, job_id, filename): """Get details about the static assets collected for a specific job."""
return 'https://saucelabs.com/rest/v1/{}/jobs/{}/assets/{}'.format( self.client.sauce_username, job_id, filename)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_auth_token(self, job_id, date_range=None): """Get an auth token to access protected job resources. https://wiki.saucelabs.com/display/DOCS/Building+Links...
key = '{}:{}'.format(self.client.sauce_username, self.client.sauce_access_key) if date_range: key = '{}:{}'.format(key, date_range) return hmac.new(key.encode('utf-8'), job_id.encode('utf-8'), md5).hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_file(self, filepath, overwrite=True): """Uploads a file to the temporary sauce storage."""
method = 'POST' filename = os.path.split(filepath)[1] endpoint = '/rest/v1/storage/{}/{}?overwrite={}'.format( self.client.sauce_username, filename, "true" if overwrite else "false") with open(filepath, 'rb') as filehandle: body = filehandle.read() 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 get_stored_files(self): """Check which files are in your temporary storage."""
method = 'GET' endpoint = '/rest/v1/storage/{}'.format(self.client.sauce_username) return self.client.request(method, endpoint)
<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_tunnels(self): """Retrieves all running tunnels for a specific user."""
method = 'GET' endpoint = '/rest/v1/{}/tunnels'.format(self.client.sauce_username) return self.client.request(method, endpoint)
<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_tunnel(self, tunnel_id): """Get information for a tunnel given its ID."""
method = 'GET' endpoint = '/rest/v1/{}/tunnels/{}'.format( self.client.sauce_username, tunnel_id) return self.client.request(method, endpoint)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply(patch): """Apply a patch. The patch's :attr:`~Patch.obj` attribute is injected into the patch's :attr:`~Patch.destination` under the patch's :attr:`~Pa...
settings = Settings() if patch.settings is None else patch.settings # When a hit occurs due to an attribute at the destination already existing # with the patch's name, the existing attribute is referred to as 'target'. try: target = get_attribute(patch.destination, patch.name) except Attr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch(destination, name=None, settings=None): """Decorator to create a patch. The object being decorated becomes the :attr:`~Patch.obj` attribute of the patc...
def decorator(wrapped): base = _get_base(wrapped) name_ = base.__name__ if name is None else name settings_ = copy.deepcopy(settings) patch = Patch(destination, name_, wrapped, settings=settings_) data = get_decorator_data(base, set_default=True) data.patches.append(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patches(destination, settings=None, traverse_bases=True, filter=default_filter, recursive=True, use_decorators=True): """Decorator to create a patch for each...
def decorator(wrapped): settings_ = copy.deepcopy(settings) patches = create_patches( destination, wrapped, settings=settings_, traverse_bases=traverse_bases, filter=filter, recursive=recursive, use_decorators=use_decorators) data = get_decorator_data(_ge...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def destination(value): """Modifier decorator to update a patch's destination. This only modifies the behaviour of the :func:`create_patches` function and the :f...
def decorator(wrapped): data = get_decorator_data(_get_base(wrapped), set_default=True) data.override['destination'] = value return wrapped return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def settings(**kwargs): """Modifier decorator to update a patch's settings. This only modifies the behaviour of the :func:`create_patches` function and the :func...
def decorator(wrapped): data = get_decorator_data(_get_base(wrapped), set_default=True) data.override.setdefault('settings', {}).update(kwargs) return wrapped return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter(value): """Modifier decorator to force the inclusion or exclusion of an attribute. This only modifies the behaviour of the :func:`create_patches` func...
def decorator(wrapped): data = get_decorator_data(_get_base(wrapped), set_default=True) data.filter = value return wrapped return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_patches(destination, root, settings=None, traverse_bases=True, filter=default_filter, recursive=True, use_decorators=True): """Create a patch for each...
if filter is None: filter = _true out = [] root_patch = Patch(destination, '', root, settings=settings) stack = collections.deque((root_patch,)) while stack: parent_patch = stack.popleft() members = _get_members(parent_patch.obj, traverse_bases=traverse_bases, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_patches(modules, recursive=True): """Find all the patches created through decorators. Parameters modules : list of module Modules and/or packages to sea...
out = [] modules = (module for package in modules for module in _module_iterator(package, recursive=recursive)) for module in modules: members = _get_members(module, filter=None) for _, value in members: base = _get_base(value) decorator...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_attribute(obj, name): """Retrieve an attribute while bypassing the descriptor protocol. As per the built-in |getattr()|_ function, if the input object is...
objs = inspect.getmro(obj) if isinstance(obj, _CLASS_TYPES) else [obj] for obj_ in objs: try: return object.__getattribute__(obj_, name) except AttributeError: pass raise AttributeError("'%s' object has no attribute '%s'" % (type(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 get_decorator_data(obj, set_default=False): """Retrieve any decorator data from an object. Parameters obj : object Object. set_default : bool If no data is f...
if isinstance(obj, _CLASS_TYPES): datas = getattr(obj, _DECORATOR_DATA, {}) data = datas.setdefault(obj, None) if data is None and set_default: data = DecoratorData() datas[obj] = data setattr(obj, _DECORATOR_DATA, datas) else: data = getattr(...
<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_base(obj): """Unwrap decorators to retrieve the base object."""
if hasattr(obj, '__func__'): obj = obj.__func__ elif isinstance(obj, property): obj = obj.fget elif isinstance(obj, (classmethod, staticmethod)): # Fallback for Python < 2.7 back when no `__func__` attribute # was defined for those descriptors. obj = obj.__get__(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 _get_members(obj, traverse_bases=True, filter=default_filter, recursive=True): """Retrieve the member attributes of a module or a class. The descriptor proto...
if filter is None: filter = _true out = [] stack = collections.deque((obj,)) while stack: obj = stack.popleft() if traverse_bases and isinstance(obj, _CLASS_TYPES): roots = [base for base in inspect.getmro(obj) if base not in (type, object)] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _module_iterator(root, recursive=True): """Iterate over modules."""
yield root stack = collections.deque((root,)) while stack: package = stack.popleft() # The '__path__' attribute of a package might return a list of paths if # the package is referenced as a namespace. paths = getattr(package, '__path__', []) for path in paths: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update(self, **kwargs): """Update some attributes. If a 'settings' attribute is passed as a dict, then it updates the content of the settings, if any, inste...
for key, value in _iteritems(kwargs): if key == 'settings': if isinstance(value, dict): if self.settings is None: self.settings = Settings(**value) else: self.settings._update(**value) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_collection(self, path): """To get pagewise data."""
while True: items = self.get(path) req = self.req for item in items: yield item if req.links and req.links['next'] and\ req.links['next']['rel'] == 'next': path = req.links['next']['url'] 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 collection(self, path): """To return all items generated by get collection."""
data = [] for item in self.get_collection(path): data.append(item) return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_projects_search(self, searchstring): """List projects with searchstring."""
log.debug('List all projects with: %s' % searchstring) return self.collection('projects/search/%s.json' % quote_plus(searchstring))
<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_project(self, data): """Create a project."""
# http://teampasswordmanager.com/docs/api-projects/#create_project log.info('Create project: %s' % data) NewID = self.post('projects.json', data).get('id') log.info('Project has been created with ID %s' % NewID) return NewID
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_parent_of_project(self, ID, NewParrentID): """Change parent of project."""
# http://teampasswordmanager.com/docs/api-projects/#change_parent log.info('Change parrent for project %s to %s' % (ID, NewParrentID)) data = {'parent_id': NewParrentID} self.put('projects/%s/change_parent.json' % ID, 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 update_security_of_project(self, ID, data): """Update security of project."""
# http://teampasswordmanager.com/docs/api-projects/#update_project_security log.info('Update project %s security %s' % (ID, data)) self.put('projects/%s/security.json' % ID, 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 list_passwords_search(self, searchstring): """List passwords with searchstring."""
log.debug('List all passwords with: %s' % searchstring) return self.collection('passwords/search/%s.json' % quote_plus(searchstring))
<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_password(self, data): """Create a password."""
# http://teampasswordmanager.com/docs/api-passwords/#create_password log.info('Create new password %s' % data) NewID = self.post('passwords.json', data).get('id') log.info('Password has been created with ID %s' % NewID) return NewID
<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_password(self, ID, data): """Update a password."""
# http://teampasswordmanager.com/docs/api-passwords/#update_password log.info('Update Password %s with %s' % (ID, data)) self.put('passwords/%s.json' % ID, 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 update_security_of_password(self, ID, data): """Update security of a password."""
# http://teampasswordmanager.com/docs/api-passwords/#update_security_password log.info('Update security of password %s with %s' % (ID, data)) self.put('passwords/%s/security.json' % ID, 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 update_custom_fields_of_password(self, ID, data): """Update custom fields definitions of a password."""
# http://teampasswordmanager.com/docs/api-passwords/#update_cf_password log.info('Update custom fields of password %s with %s' % (ID, data)) self.put('passwords/%s/custom_fields.json' % ID, 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 unlock_password(self, ID, reason): """Unlock a password."""
# http://teampasswordmanager.com/docs/api-passwords/#unlock_password log.info('Unlock password %s, Reason: %s' % (ID, reason)) self.unlock_reason = reason self.put('passwords/%s/unlock.json' % 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 list_mypasswords_search(self, searchstring): """List my passwords with searchstring."""
# http://teampasswordmanager.com/docs/api-my-passwords/#list_passwords log.debug('List MyPasswords with %s' % searchstring) return self.collection('my_passwords/search/%s.json' % quote_plus(searchstring))