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 saveform(cls, form): """ Create and save form model data to database """
columns = dict() for name, field in cls.form_fields.iteritems(): columns[name] = getattr(form, field).data instance = cls(**columns) return instance.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 get_by_id(cls, id): """ Get model by identifier """
if any((isinstance(id, basestring) and id.isdigit(), isinstance(id, (int, float)))): return cls.query.get(int(id)) 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 update(self, commit=True, **kwargs): """ Update model attributes and save to database """
for (attr, value) in kwargs.iteritems(): setattr(self, attr, value) return commit and self.save() or 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 save(self, commit=True): """ Save model to database """
db.session.add(self) if commit: db.session.commit() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, commit=True): """ Delete model from database """
db.session.delete(self) return commit and db.session.commit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def verify_dir_structure(full_path): '''Check if given directory to see if it is usable by s2. Checks that all required directories exist under the given directory, and also checks that they are writable. ''' if full_path == None: return False r = True for d2c in PREDEFINED_DIR_NA...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dir_param_valid(d): '''True if d is a string and it's an existing directory.''' r = True if not isinstance(d, str) : r = False raise TypeError if not os.path.isdir(d): r = False raise ValueError 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 dir_empty(d): '''Return True if given directory is empty, false otherwise.''' flist = glob.glob(os.path.join(d,'*')) return (len(flist) == 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 is_base_dir(d): '''True if the dir is valid and it contains a dir called s2''' if not dir_param_valid(d): # pragma: no cover raise else: mfn = os.path.join(d,'s2') #marker name. it must be a directory. return os.path.isdir(mfn)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def discover_base_dir(start_dir): '''Return start_dir or the parent dir that has the s2 marker. Starting from the specified directory, and going up the parent chain, check each directory to see if it's a base_dir (contains the "marker" directory *s2*) and return it. Otherwise, return the start_dir....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def package_data_location(): '''Get the locations of themes distributed with this package. Just finds if there are templates, and returns a dictionary with the corresponding values. ''' pkg_dir = os.path.split(__file__)[0] pkg_data_dir = os.path.join(pkg_dir,'data') return pkg_data_dir
<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_directories(self): '''Initialize variables based on evidence about the directories.''' if self._dirs['initial'] == None: self._dirs['base'] = discover_base_dir(self._dirs['run']) else: self._dirs['base'] = discover_base_dir(self._dirs['initial']) # no...
<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_dirs_on_base(self): '''Fill up the names of dirs based on the contents of 'base'.''' if self._dirs['base'] != None: for d in self._predefined_dir_names: dstr = d #if d == "s2": # dstr = '.'+d self._dirs[d] = os.pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def init_structure(self): '''Initialize a directory to serve as a Simply Static site. Initialization is done on the base_dir (base_dir is set upon __init__, so it has a value when this method is called), and it is only performed if base_dir is empty and it is writeable. This op...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def random_page(self, title=None, content=None, creation_date=None, tags=None): '''Generate random page, write it and return the corresponding \ object.''' if title == None: title = util.random_title() if content == None: content = util.random_md_page...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def page_exists_on_disk(self, slug): '''Return true if post directory and post file both exist.''' r = False page_dir = os.path.join(self.dirs['source'], slug) page_file_name = os.path.join(page_dir, slug + '.md') if os.path.isdir(page_dir): if os.path.isfile(page_fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rename_page(self, old_slug, new_title): '''Load the page corresponding to the slug, and rename it.''' #load page p = s2page.Page(self, old_slug, isslug=True) p.rename(new_title)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _wipe_www_page(self, slug): '''Remove all data in www about the page identified by slug.''' wd = os.path.join(self._dirs['www'], slug) if os.path.isdir(wd): # pragma: no cover shutil.rmtree(wd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _pages_to_generate(self): '''Return list of slugs that correspond to pages to generate.''' # right now it gets all the files. In theory, It should only # get what's changed... but the program is not doing that yet. all_pages = self.get_page_names() # keep only those whose st...
<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_default_config(self): '''Create and write to disk a default site config file.''' # maybe I should read the default config from somewhere in the package? cfg = { 'site_title': '', 'site_subtitle': '', 'default_author': '', 'site_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 _read_site_config(self): '''Read and return the site config, as a dictionary.''' file_name = os.path.join(self._dirs['s2'],'config.yml') if os.path.isfile(file_name): f = open(file_name,'r') cfg = yaml.load(f.read()) f.close() else: cfg...
<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(template_class,*extensions): ''' Register a template for a given extension or range of extensions ''' for ext in extensions: ext = normalize(ext) if not Lean.template_mappings.has_key(ext): Lean.template_mappings[ext] = [] Lean.template_mappings[ext].insert(0,template_class) Lean.templ...
<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_registered(ext): ''' Returns true when a template exists on an exact match of the provided file extension ''' return Lean.template_mappings.has_key(ext.lower()) and len(Lean.template_mappings[ext])
<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(file,line=None,options={},block=None): ''' Create a new template for the given file using the file's extension to determine the the template mapping. ''' template_class = Lean.get_template(file) if template_class: return template_class(file,line,options,block) else: rai...
<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_template(file): ''' Lookup a template class for the given filename or file extension. Return nil when no implementation is found. ''' pattern = str(file).lower() while len(pattern) and not Lean.is_registered(pattern): pattern = os.path.basename(pattern) pattern = re.sub(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 generate(organization, package, destination): """Generates the Sphinx configuration and Makefile. Args: organization (str): the organization name. package (...
gen = ResourceGenerator(organization, package) tmp = tempfile.NamedTemporaryFile(mode='w+t', delete=False) try: tmp.write(gen.conf()) finally: tmp.close() shutil.copy(tmp.name, os.path.join(destination, 'conf.py')) tmp = tempfile.NamedTemporaryFile(mode='w+t', delete=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 get_self_uri(self, content_type): "return the first self uri with the content_type" try: return [self_uri for self_uri in self.self_uri_list if self_uri.content_type == content_type][0] except IndexError: 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 pretty(self): "sort values and format output for viewing and comparing in test scenarios" pretty_obj = OrderedDict() for key, value in sorted(iteritems(self.__dict__)): if value is None: pretty_obj[key] = None elif is_str_or_unicode(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 _support_directory(): """Get the path of the support_files directory"""
from os.path import join, dirname, abspath return join(dirname(abspath(__file__)), 'support_files')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_uo(self, configuration=None, tpl=None, keys=None, obj_type=None): """ Create a new UserObject from the given template. :param configuration: EB config...
if configuration is not None: self.configuration = configuration if tpl is not None: self.tpl = tpl if keys is not None: self.keys = keys if self.keys is None: self.keys = dict() # generate comm keys if not present Templat...
<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_type(spec, obj_type): """ Updates type integer in the cerate UO specification. Type has to already have generations flags set correctly. Generation field...
if spec is None: raise ValueError('Spec cannot be None') if TemplateFields.generation not in spec: spec[TemplateFields.generation] = {} spec[TemplateFields.generation][TemplateFields.commkey] = \ Gen.CLIENT if (obj_type & (int(1) << TemplateFields.FLAG_COMM_...
<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_uo_type(obj_type, comm_keys_provided=True, app_keys_provided=True): """ Constructs UO type from the operation and keys provided, clears bits set ib obj_t...
if comm_keys_provided is not None and comm_keys_provided == False: obj_type &= ~(int(1) << TemplateFields.FLAG_COMM_GEN) elif comm_keys_provided: obj_type |= (int(1) << TemplateFields.FLAG_COMM_GEN) if app_keys_provided is not None and app_keys_provided == 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 template_request(configuration, spec): """ Calls the get template request :param configuration: :param spec: :return: """
# Template request, nonce will be regenerated. req = CreateUO.get_template_request(configuration, spec) # Do the request with retry. caller = RequestCall(req) resp = caller.call() return resp
<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_imported_object(configuration, tpl_import_req, import_resp): """ Builds uo from the imported object to the EB. Imported object = result of CreateUserOb...
if import_resp is None \ or import_resp.response is None \ or 'result' not in import_resp.response \ or 'handle' not in import_resp.response['result']: logger.info('Invalid result: %s', import_resp) raise InvalidResponse('Invalid import re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_serialized_rsa_pub_key(serialized): """ Reads serialized RSA pub key TAG|len-2B|value. 81 = exponent, 82 = modulus :param serialized: :return: n, e """
n = None e = None rsa = from_hex(serialized) pos = 0 ln = len(rsa) while pos < ln: tag = bytes_to_byte(rsa, pos) pos += 1 length = bytes_to_short(rsa, pos) pos += 2 if tag == 0x81: e = bytes_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 env(var_name, default=False): """ Get the environment variable or assume a default, but let the user know about the error."""
try: value = os.environ[var_name] if str(value).strip().lower() in ['false', 'no', 'off' '0', 'none', 'null']: return None return value except: from traceback import format_exc msg = format_exc() + '\n' + "Unable to find the %s environment variable.\nUsing th...
<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_negated_goals(self,safe_variables,query): ''' Create a list of variables which occur in negated goals. ''' variables_in_negated_goals = \ [y for x in query.relations for y in list(x.variables) if x.is_negated()] # And check them: for variable in variables_in_negate...
<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_non_equality_explicit_constraints(self,safe_variables,query): ''' Checking variables which occur in explicit constraints with non equality operators ''' # Create a list of variables which occur in explicit constraints with non # equality operators variables_in_constrain...
<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_database(destroy_existing=False): """ Create db and tables if it doesn't exist """
if not os.path.exists(DB_NAME): logger.info('Create database: {0}'.format(DB_NAME)) open(DB_NAME, 'a').close() Show.create_table() Episode.create_table() Setting.create_table()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def magic_api(word): """ This is our magic API that we're simulating. It'll return a random number and a cache timer. """
result = sum(ord(x)-65 + randint(1,50) for x in word) delta = timedelta(seconds=result) cached_until = datetime.now() + delta return result, cached_until
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def portfolio_prices( symbols=("AAPL", "GLD", "GOOG", "$SPX", "XOM", "msft"), start=datetime.datetime(2005, 1, 1), end=datetime.datetime(2011, 12, 31), # data sto...
symbols = normalize_symbols(symbols) start = util.normalize_date(start) end = util.normalize_date(end) if allocation is None: allocation = [1. / len(symbols)] * len(symbols) if len(allocation) < len(symbols): allocation = list(allocation) + [1. / len(symbols)] * (len(symbols) - ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def symbol_bollinger(symbol='GOOG', start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='close', cleaner=clean_dataframe, window=...
symbols = normalize_symbols(symbol) prices = price_dataframe(symbols, start=start, end=end, price_type=price_type, cleaner=cleaner) return series_bollinger(prices[symbols[0]], window=window, sigma=sigma, plot=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 symbols_bollinger(symbols='sp5002012', start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='adjusted_close', cleaner=clean_da...
symbols = normalize_symbols(symbols) prices = price_dataframe(symbols, start=start, end=end, price_type=price_type, cleaner=cleaner) return frame_bollinger(prices, window=window, sigma=sigma, plot=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 metrics(prices, fudge=False, sharpe_days=252., baseline='$SPX'): """Calculate the volatiliy, average daily return, Sharpe ratio, and cumulative return Argume...
if isinstance(prices, basestring) and os.path.isfile(prices): prices = open(prices, 'rU') if isinstance(prices, file): values = {} csvreader = csv.reader(prices, dialect='excel', quoting=csv.QUOTE_MINIMAL) for row in csvreader: # print row values[tuple(in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def buy_on_drop(symbol_set="sp5002012", dataobj=dataobj, start=datetime.datetime(2008, 1, 3), end=datetime.datetime(2009, 12, 28), market_sym='$SPX', threshold=6, sell_delay=5, ): '''Compute and display an "event profile" for mul...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_orders(events, sell_delay=5, sep=','): """Generate CSV orders based on events indicated in a DataFrame Arguments: events (pandas.DataFrame): Table ...
sell_delay = float(unicode(sell_delay)) or 1 for i, (t, row) in enumerate(events.iterrows()): for sym, event in row.to_dict().iteritems(): # print sym, event, type(event) # return events if event and not np.isnan(event): # add a sell event `sell_delay...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_file(save_path, file_url): """ Download file from http url link """
r = requests.get(file_url) # create HTTP response object with open(save_path, 'wb') as f: f.write(r.content) return save_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 make_url(domain, location): """ This function helps to make full url path."""
url = urlparse(location) if url.scheme == '' and url.netloc == '': return domain + url.path elif url.scheme == '': return 'http://' + url.netloc + url.path else: return url.geturl()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getlist(self, key): """Returns a Storage value as a list. If the value is a list it will be returned as-is. If object is None, an empty list will be returned...
value = self.get(key, []) if value is None or isinstance(value, (list, tuple)): return value else: return [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 getfirst(self, key, default=None): """Returns the first value of a list or the value itself when given a `request.vars` style key. If the value is a list, it...
values = self.getlist(key) return values[0] if values else 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 getlast(self, key, default=None): """Returns the last value of a list or value itself when given a `request.vars` style key. If the value is a list, the last...
values = self.getlist(key) return values[-1] if values else 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 _eval_variables(self): """evaluates callable _variables """
for k, v in listitems(self._variables): self._variables[k] = v() if hasattr(v, '__call__') else v
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def defer(callable): '''Defers execution of the callable to a thread. For example: >>> def foo(): ... print('bar') >>> join = defer(foo) >>> join() ''' t = threading.Thread(target=callable) t.start() return t.join
<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_fds(): '''Close extraneous file descriptors. On Linux, close everything but stdin, stdout, and stderr. On Mac, close stdin, stdout, and stderr and everything owned by our user id. ''' def close(fd): with ignored(OSError): os.close(fd) if sys.platform == 'linux': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind(self, extension: Extension) -> 'DictMentor': """ Add any predefined or custom extension. Args: extension: Extension to add to the processor. Returns: The...
if not Extension.is_valid_extension(extension): raise ValueError("Cannot bind extension due to missing interface requirements") self._extensions.append(extension) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def augment(self, dct: NonAugmentedDict, document: Optional[YamlDocument] = None) -> AugmentedDict: """ Augments the given dictionary by using all the bound exten...
Validator.instance_of(dict, raise_ex=True, dct=dct) # Apply any configured loader for instance in self._extensions: nodes = list(dict_find_pattern(dct, **instance.config())) for parent, k, val in nodes: parent.pop(k) fragment = instance.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 Date(value): """Custom type for managing dates in the command-line."""
from datetime import datetime try: return datetime(*reversed([int(val) for val in value.split('/')])) except Exception as err: raise argparse.ArgumentTypeError("invalid date '%s'" % 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 create(clients_num, clients_host, clients_port, people_num, throttle): """ Prepare clients to execute :return: Modules to execute, cmd line function :rtype: ...
res = [] for number in range(clients_num): sc = EchoClient({ 'id': number, 'listen_bind_ip': clients_host, #'multicast_bind_ip': "127.0.0.1", 'listen_port': clients_port + number }) people = [] for person_number in range(people_num...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _packet_loop(self): """ Packet processing loop :rtype: None """
while self._is_running: # Only wait if there are no more packets in the inbox if self.inbox.empty() \ and not self.new_packet.wait(self._packet_timeout): continue ip, port, packet = self.inbox.get() if self.inbox.empty(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dechex(num,zfill=0): ''' Simple integer to hex converter. The zfill is the number of bytes, even though the input is a hex string, which means that the actual zfill is 2x what you might initially think it would be. For example: >>> dechex(4,2) '0004' ''' if not isitint(num...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def selenol_params(**kwargs): """Decorate request parameters to transform them into Selenol objects."""
def params_decorator(func): """Param decorator. :param f: Function to decorate, typically on_request. """ def service_function_wrapper(service, message): """Wrap function call. :param service: SelenolService object. :param message: SelenolMessag...
<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_value(data_structure, key): """Return the value of a data_structure given a path. :param data_structure: Dictionary, list or subscriptable object. :para...
if len(key) == 0: raise KeyError() value = data_structure[key[0]] if len(key) > 1: return _get_value(value, key[1:]) return 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_value_from_session(key): """Get a session value from the path specifed. :param key: Array that defines the path of the value inside the message. """
def value_from_session_function(service, message): """Actual implementation of get_value_from_session function. :param service: SelenolService object. :param message: SelenolMessage request. """ return _get_value(message.session, key) return value_from_session_function
<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_value_from_content(key): """Get a value from the path specifed. :param key: Array that defines the path of the value inside the message. """
def value_from_content_function(service, message): """Actual implementation of get_value_from_content function. :param service: SelenolService object. :param message: SelenolMessage request. """ return _get_value(message.content, key) return value_from_content_function
<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_from_content(entity, key): """Get an object from the database given an entity and the content key. :param entity: Class type of the object to retr...
def object_from_content_function(service, message): """Actual implementation of get_object_from_content function. :param service: SelenolService object. :param message: SelenolMessage request. """ id_ = get_value_from_content(key)(service, message) result = 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_object_from_session(entity, key): """Get an object from the database given an entity and the session key. :param entity: Class type of the object to retr...
def object_from_session_function(service, message): """Actual implementation of get_object_from_session function. :param service: SelenolService object. :param message: SelenolMessage request. """ id_ = get_value_from_session(key)(service, message) result = 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 _process_json(data): """ return a list of GradPetition objects. """
requests = [] for item in data: petition = GradPetition() petition.description = item.get('description') petition.submit_date = parse_datetime(item.get('submitDate')) petition.decision_date = parse_datetime(item.get('decisionDate')) if item.get('deptRecommend') and len(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def example_add_line_to_file(): """ Different methods to append a given line to the file, all work the same. """
my_file = FileAsObj('/tmp/example_file.txt') my_file.add('foo') my_file.append('bar') # Add a new line to my_file that contains the word 'lol' and print True|False if my_file was changed. print(my_file + 'lol') # Add line even if it already exists in the file. my_file.unique = False my_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def example_write_file_to_disk_if_changed(): """ Try to remove all comments from a file, and save it if changes were made. """
my_file = FileAsObj('/tmp/example_file.txt') my_file.rm(my_file.egrep('^#')) if my_file.changed: my_file.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 example_all(): """ Use a bunch of methods on a file. """
my_file = FileAsObj() my_file.filename = '/tmp/example_file.txt' my_file.add('# First change!') my_file.save() my_file = FileAsObj('/tmp/example_file.txt') my_file.unique = True my_file.sorted = True my_file.add('1') my_file.add('1') my_file.add('2') my_file.add('20 foo') ...
<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_cal_data(data_df, cal_dict, param): '''Get data along specified axis during calibration intervals Args ---- data_df: pandas.DataFrame Pandas dataframe with lleo data cal_dict: dict Calibration dictionary Returns ------- lower: pandas dataframe slice of l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def read_cal(cal_yaml_path): '''Load calibration file if exists, else create Args ---- cal_yaml_path: str Path to calibration YAML file Returns ------- cal_dict: dict Key value pairs of calibration meta data ''' from collections import OrderedDict import datetim...
<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(data_df, cal_dict, param, bound, start, end): '''Update calibration times for give parameter and boundary''' from collections import OrderedDict if param not in cal_dict['parameters']: cal_dict['parameters'][param] = OrderedDict() if bound not in cal_dict['parameters'][param]: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def fit1d(lower, upper): '''Fit acceleration data at lower and upper boundaries of gravity Args ---- lower: pandas dataframe slice of lleo datafram containing points at -1g calibration position upper: pandas dataframe slice of lleo datafram containing points at -1g calibration posit...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def un_comment(s, comment='#', strip=True): """Uncomment a string or list of strings truncate s at first occurrence of a non-escaped comment character remove esc...
def _un_comment(string): result = re.split(r'(?<!\\)' + comment, string, maxsplit=1)[0] result = re.sub(r'\\' + comment, comment, result) if strip: return result.strip() return result if isinstance(s, (tuple, list)): return [_un_comment(line) for line in 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_smooth_step_function(min_val, max_val, switch_point, smooth_factor): """Returns a function that moves smoothly between a minimal value and a maximal one ...
dif = max_val - min_val def _smooth_step(x): return min_val + dif * tanh((x - switch_point) / smooth_factor) return _smooth_step
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stack_sources(): """A list of sources for frames above this"""
# lazy imports import linecache result = [] for frame_info in reversed(inspect.stack()): _frame, filename, line_number, _function, _context, _index = frame_info linecache.lazycache(filename, {}) _line = linecache.getline(filename, line_number).rstrip() # Each record contain...
<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_leftmost_selector(selector_list): """ Because we aren't building a DOM tree to transverse, the only way to get the most general selectors is to take ...
classes = set() ids = set() elements = set() # print "Selector list: %s \n\n\n\n\n\n" % selector_list for selector in selector_list: selector = selector.split()[0] if selector[0] == '.': classes.add(selector) elif selector[0] == '#': ids.add(select...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_styles(self, tag, attrs): """ Append classes found in HTML elements to the list of styles used. Because we haven't built the tree, we aren't using the...
dattrs = dict(attrs) if 'class' in dattrs: #print "Found classes '%s'" % dattrs['class'] class_names = dattrs['class'].split() dotted_names = map(prepend_dot,class_names) dotted_names.sort() self.used_classes.extend(' '.join(dotted_names)) ...
<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_after(filename): """Decorator to be sure the file given by parameter is deleted after the execution of the method. """
def delete_after_decorator(function): def wrapper(*args, **kwargs): try: return function(*args, **kwargs) finally: if os.path.isfile(filename): os.remove(filename) if os.path.isdir(filename): shu...
<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_geocode(city, state, street_address="", zipcode=""): """ For given location or object, takes address data and returns latitude and longitude coordinates ...
try: key = settings.GMAP_KEY except AttributeError: return "You need to put GMAP_KEY in settings" # build valid location string location = "" if street_address: location += '{}+'.format(street_address.replace(" ", "+")) location += '{}+{}'.format(city.replace(" ", "+"),...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list(self,walkTrace=tuple(),case=None,element=None): """List section titles. """
if case == 'sectionmain': print(walkTrace,self.title)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listFigures(self,walkTrace=tuple(),case=None,element=None): """List section figures. """
if case == 'sectionmain': print(walkTrace,self.title) if case == 'figure': caption,fig = element try: print(walkTrace,fig._leopardref,caption) except AttributeError: fig._leopardref = next(self._reportSection._fignr) pr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listTables(self,walkTrace=tuple(),case=None,element=None): """List section tables. """
if case == 'sectionmain': print(walkTrace,self.title) if case == 'table': caption,tab = element try: print(walkTrace,tab._leopardref,caption) except AttributeError: tab._leopardref = next(self._reportSection._tabnr) pri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sectionOutZip(self,zipcontainer,zipdir='',figtype='png'): """Prepares section for zip output """
from io import StringIO, BytesIO text = self.p if not self.settings['doubleslashnewline'] else self.p.replace('//','\n') zipcontainer.writestr( zipdir+'section.txt', '# {}\n{}'.format(self.title,text).encode() ) c = count(1) for ftitle,f in self.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 sectionsWord(self,walkTrace=tuple(),case=None,element=None,doc=None): """Prepares section for word output. """
from docx.shared import Inches from io import BytesIO #p.add_run('italic.').italic = True if case == 'sectionmain': if self.settings['clearpage']: doc.add_page_break() doc.add_heading(self.title, level = len(walkTrace)) 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 sectionFromFunction(function,*args,**kwargs): """ This staticmethod executes the function that is passed with the provided args and kwargs. The first line of...
figures, tables = function(*args,**kwargs) title = inspect.getcomments(function)[1:].strip() text = inspect.getdoc(function) code = inspect.getsource(function) return Section(title=title,text=text,figures=figures,tables=tables,code=code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list(self): """ Get an overview of the report content list """
for i in range(len(self.sections)): self.sections[i].list(walkTrace=(i+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 outputZip(self,figtype='png'): """ Outputs the report in a zip container. Figs and tabs as pngs and excells. Args: figtype (str): Figure type of images in t...
from zipfile import ZipFile with ZipFile(self.outfile+'.zip', 'w') as zipcontainer: zipcontainer.writestr( 'summary.txt', '# {}\n\n{}\n{}'.format( self.title, self.p, ('\n## Conclusion\n' if self.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 outputWord(self): """Output report to word docx """
import docx from docx.enum.text import WD_ALIGN_PARAGRAPH doc = docx.Document() doc.styles['Normal'].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY doc.add_heading(self.title, level=0) if self.addTime: from time import localtime, st...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getReportTable(reportzipfile,tablefilename,inReportsDir=True,verbose=False): """Get a pandas table from a previous report Args: reportzipfile (str): Zip fol...
import zipfile, io, re # zipfilename preparation if not reportzipfile.endswith('.zip'): reportzipfile+='.zip' if inReportsDir: reportzipfile = os.path.join(reportsDir,reportzipfile) with zipfile.ZipFile(reportzipfile) as z: # print all table filenames if tablefilena...
<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_standard_normal(df): """Transform a series or the rows of a dataframe to the values of a standard normal based on rank."""
import pandas as pd import scipy.stats as stats if type(df) == pd.core.frame.DataFrame: gc_ranks = df.rank(axis=1) gc_ranks = gc_ranks / (gc_ranks.shape[1] + 1) std_norm = stats.norm.ppf(gc_ranks) std_norm = pd.DataFrame(std_norm, index=gc_ranks.index, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_gzipped_text_url(url): """Read a gzipped text file from a URL and return contents as a string."""
import urllib2 import zlib from StringIO import StringIO opener = urllib2.build_opener() request = urllib2.Request(url) request.add_header('Accept-encoding', 'gzip') respond = opener.open(request) compressedData = respond.read() respond.close() opener.close() compressedDat...
<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_worst_flag_level(self, flags): ''' Determines the worst flag present in the provided flags. If no flags are given then a 'minor' value is returned. ''' worst_flag_level = 0 for flag_level_name in flags: flag_level = self.FLAG_LEVELS[flag_level_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 parse(line): """ Parse accesslog line to map Python dictionary. Returned dictionary has following keys: - time: access time (datetime; naive) - utcoffset: UT...
m = LOG_FORMAT.match(line) if m is None: return access = Access._make(m.groups()) entry = { 'host': access.host, 'path': access.path, 'query': access.query, 'method': access.method, 'protocol': access.protocol, 'status': int(access.status) } ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logparse(*args, **kwargs): """ Parse access log on the terminal application. If list of files are given, parse each file. Otherwise, parse standard input. :p...
from clitool.cli import clistream from clitool.processor import SimpleDictReporter lst = [parse] + args reporter = SimpleDictReporter() stats = clistream(reporter, *lst, **kwargs) return stats, reporter.report()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def std_filter(array, n_std=2.0, return_index=False): """Standard deviation outlier detector. :param array: array of data. :param n_std: default 2.0, exclude dat...
if not isinstance(array, np.ndarray): array = np.array(array) mean, std = array.mean(), array.std() good_index = np.where(abs(array - mean) <= n_std * std) bad_index = np.where(abs(array - mean) > n_std * std) if return_index: return good_index[0], bad_index[0] else: 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 box_filter(array, n_iqr=1.5, return_index=False): """Box plot outlier detector. :param array: array of data. :param n_std: default 1.5, exclude data out of `...
if not isinstance(array, np.ndarray): array = np.array(array) Q3 = np.percentile(array, 75) Q1 = np.percentile(array, 25) IQR = Q3 - Q1 lower, upper = Q1 - n_iqr * IQR, Q3 + n_iqr * IQR good_index = np.where(np.logical_and(array >= lower, array <= upper)) bad_index = np.where(np.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 resize_compute_width_height(fullfile,_megapixels): """Given image file and desired megapixels, computes the new width and height"""
img = Image.open(fullfile) width,height=img.size current_megapixels=width*height/(2.0**20) scale=sqrt(_megapixels/float(current_megapixels)) logger.debug('A resize scale would be %f'%(scale)) # Can't make bigger, return original if scale>= 1.0: logger.warning('Image is %0.1f MP, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getexif_location(directory,fn): """ directory - Dir where file is located fn - filename to check for EXIF GPS Returns touple of lat,lon if EXIF eg. (34.03546...
lat=None lon=None sign_lat=+1.0 sign_lon=+1.0 # Check if photo as geo info already exif_tags=exifread.process_file(\ open(os.path.join(directory,fn),'rb')) try: d,m,s=exif_tags['GPS GPSLongitude'].values # West is negative longitudes, change sign if exif...