_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q57200
DateService.extractDate
train
def extractDate(self, inp): """Returns the first date found in the input string, or None if not found.""" dates = self.extractDates(inp) for date in dates: return date return None
python
{ "resource": "" }
q57201
DateService.convertDay
train
def convertDay(self, day, prefix="", weekday=False): """Convert a datetime object representing a day into a human-ready string that can be read, spoken aloud, etc. Args: day (datetime.date): A datetime object to be converted into text. prefix (str): An optional argument ...
python
{ "resource": "" }
q57202
DateService.convertTime
train
def convertTime(self, time): """Convert a datetime object representing a time into a human-ready string that can be read, spoken aloud, etc. Args: time (datetime.date): A datetime object to be converted into text. Returns: A string representation of the input ti...
python
{ "resource": "" }
q57203
DateService.convertDate
train
def convertDate(self, date, prefix="", weekday=False): """Convert a datetime object representing into a human-ready string that can be read, spoken aloud, etc. In effect, runs both convertDay and convertTime on the input, merging the results. Args: date (datetime.date): A da...
python
{ "resource": "" }
q57204
FilesystemHandler._move
train
def _move(self): """ Called during a PUT request where the action specifies a move operation. Returns resource URI of the destination file. """ newpath = self.action['newpath'] try: self.fs.move(self.fp,newpath) except OSError: raise tornad...
python
{ "resource": "" }
q57205
FilesystemHandler._copy
train
def _copy(self): """ Called during a PUT request where the action specifies a copy operation. Returns resource URI of the new file. """ copypath = self.action['copypath'] try: self.fs.copy(self.fp,copypath) except OSError: raise tornado.web...
python
{ "resource": "" }
q57206
FilesystemHandler._rename
train
def _rename(self): """ Called during a PUT request where the action specifies a rename operation. Returns resource URI of the renamed file. """ newname = self.action['newname'] try: newpath = self.fs.rename(self.fp,newname) except OSError: ...
python
{ "resource": "" }
q57207
FilesystemHandler.get
train
def get(self): """ Return details for the filesystem, including configured volumes. """ res = self.fs.get_filesystem_details() res = res.to_dict() self.write(res)
python
{ "resource": "" }
q57208
FilesystemHandler.put
train
def put(self): """ Provides move, copy, and rename functionality. An action must be specified when calling this method. """ self.fp = self.get_body_argument('filepath') self.action = self.get_body_argument('action') try: ptype = self.fs.get_type_from_...
python
{ "resource": "" }
q57209
FilewatcherCreateHandler.post
train
def post(self, *args): """ Start a new filewatcher at the specified path. """ filepath = self.get_body_argument('filepath') if not self.fs.exists(filepath): raise tornado.web.HTTPError(404) Filewatcher.add_directory_to_watch(filepath) self.write({'msg...
python
{ "resource": "" }
q57210
FilewatcherDeleteHandler.delete
train
def delete(self, filepath): """ Stop and delete the specified filewatcher. """ Filewatcher.remove_directory_to_watch(filepath) self.write({'msg':'Watcher deleted for {}'.format(filepath)})
python
{ "resource": "" }
q57211
FileHandler.get
train
def get(self, filepath): """ Get file details for the specified file. """ try: res = self.fs.get_file_details(filepath) res = res.to_dict() self.write(res) except OSError: raise tornado.web.HTTPError(404)
python
{ "resource": "" }
q57212
FileHandler.put
train
def put(self, filepath): """ Change the group or permissions of the specified file. Action must be specified when calling this method. """ action = self.get_body_argument('action') if action['action'] == 'update_group': newgrp = action['group'] tr...
python
{ "resource": "" }
q57213
FileHandler.delete
train
def delete(self, filepath): """ Delete the specified file. """ try: self.fs.delete(filepath) self.write({'msg':'File deleted at {}'.format(filepath)}) except OSError: raise tornado.web.HTTPError(404)
python
{ "resource": "" }
q57214
DirectoryCreateHandler.post
train
def post(self): """ Create a new directory at the specified path. """ filepath = self.get_body_argument('filepath') try: self.fs.create_directory(filepath) encoded_filepath = tornado.escape.url_escape(filepath,plus=True) resource_uri = self.re...
python
{ "resource": "" }
q57215
FileContentsHandler.get
train
def get(self, filepath): """ Get the contents of the specified file. """ exists = self.fs.exists(filepath) if exists: mime = magic.Magic(mime=True) mime_type = mime.from_file(filepath) if mime_type in self.unsupported_types: sel...
python
{ "resource": "" }
q57216
FileContentsHandler.post
train
def post(self, filepath): """ Write the given contents to the specified file. This is not an append, all file contents will be replaced by the contents given. """ try: content = self.get_body_argument('content') self.fs.write_file(filepath, content...
python
{ "resource": "" }
q57217
FileDownloadHandler.get_content
train
def get_content(self, start=None, end=None): """ Retrieve the content of the requested resource which is located at the given absolute path. This method should either return a byte string or an iterator of byte strings. The latter is preferred for large files as it helps...
python
{ "resource": "" }
q57218
FileDownloadHandler.set_headers
train
def set_headers(self): """ Sets the content headers on the response. """ self.set_header("Accept-Ranges", "bytes") content_type = self.get_content_type() if content_type: self.set_header("Content-Type", content_type)
python
{ "resource": "" }
q57219
SharedObjectsListPlugin.__deactivate_shared_objects
train
def __deactivate_shared_objects(self, plugin, *args, **kwargs): """ Callback, which gets executed, if the signal "plugin_deactivate_post" was send by the plugin. """ shared_objects = self.get() for shared_object in shared_objects.keys(): self.unregister(shared_object)
python
{ "resource": "" }
q57220
SharedObjectsListPlugin.get
train
def get(self, name=None): """ Returns requested shared objects, which were registered by the current plugin. If access to objects of other plugins are needed, use :func:`access` or perform get on application level:: my_app.shared_objects.get(name="...") :param name: Name o...
python
{ "resource": "" }
q57221
SharedObjectsListApplication.get
train
def get(self, name=None, plugin=None): """ Returns requested shared objects. :param name: Name of a request shared object :type name: str or None :param plugin: Plugin, which has registered the requested shared object :type plugin: GwBasePattern instance or None ...
python
{ "resource": "" }
q57222
SharedObjectsListApplication.unregister
train
def unregister(self, shared_object): """ Unregisters an existing shared object, so that this shared object is no longer available. This function is mainly used during plugin deactivation. :param shared_object: Name of the shared_object """ if shared_object not in self._...
python
{ "resource": "" }
q57223
GwSignalsInfo.list_signals
train
def list_signals(self): """ Prints a list of all registered signals. Including description and plugin name. """ print("Signal list") print("***********\n") for key, signal in self.app.signals.signals.items(): print("%s (%s)\n %s\n" % (signal.name, signal.plug...
python
{ "resource": "" }
q57224
GwSignalsInfo.list_receivers
train
def list_receivers(self): """ Prints a list of all registered receivers. Including signal, plugin name and description. """ print("Receiver list") print("*************\n") for key, receiver in self.app.signals.receivers.items(): print("%s <-- %s (%s):\n %s\n"...
python
{ "resource": "" }
q57225
toxcmd_main
train
def toxcmd_main(args=None): """Command util with subcommands for tox environments.""" usage = "USAGE: %(prog)s [OPTIONS] COMMAND args..." if args is None: args = sys.argv[1:] # -- STEP: Build command-line parser. parser = argparse.ArgumentParser(description=inspect.getdoc(toxcmd_main), ...
python
{ "resource": "" }
q57226
discharge
train
def discharge(ctx, id, caveat, key, checker, locator): ''' Creates a macaroon to discharge a third party caveat. The given parameters specify the caveat and how it should be checked. The condition implicit in the caveat is checked for validity using checker. If it is valid, a new macaroon is returned w...
python
{ "resource": "" }
q57227
local_third_party_caveat
train
def local_third_party_caveat(key, version): ''' Returns a third-party caveat that, when added to a macaroon with add_caveat, results in a caveat with the location "local", encrypted with the given PublicKey. This can be automatically discharged by discharge_all passing a local key. ''' if versio...
python
{ "resource": "" }
q57228
deserialize_namespace
train
def deserialize_namespace(data): ''' Deserialize a Namespace object. :param data: bytes or str :return: namespace ''' if isinstance(data, bytes): data = data.decode('utf-8') kvs = data.split() uri_to_prefix = {} for kv in kvs: i = kv.rfind(':') if i == -1: ...
python
{ "resource": "" }
q57229
Namespace.serialize_text
train
def serialize_text(self): '''Returns a serialized form of the Namepace. All the elements in the namespace are sorted by URI, joined to the associated prefix with a colon and separated with spaces. :return: bytes ''' if self._uri_to_prefix is None or len(self._uri...
python
{ "resource": "" }
q57230
Namespace.register
train
def register(self, uri, prefix): '''Registers the given URI and associates it with the given prefix. If the URI has already been registered, this is a no-op. :param uri: string :param prefix: string ''' if not is_valid_schema_uri(uri): raise KeyError( ...
python
{ "resource": "" }
q57231
AuthContext.with_value
train
def with_value(self, key, val): ''' Return a copy of the AuthContext object with the given key and value added. ''' new_dict = dict(self._dict) new_dict[key] = val return AuthContext(new_dict)
python
{ "resource": "" }
q57232
Cardinality.make_pattern
train
def make_pattern(self, pattern, listsep=','): """Make pattern for a data type with the specified cardinality. .. code-block:: python yes_no_pattern = r"yes|no" many_yes_no = Cardinality.one_or_more.make_pattern(yes_no_pattern) :param pattern: Regular expression for ty...
python
{ "resource": "" }
q57233
TypeBuilder.with_cardinality
train
def with_cardinality(cls, cardinality, converter, pattern=None, listsep=','): """Creates a type converter for the specified cardinality by using the type converter for T. :param cardinality: Cardinality to use (0..1, 0..*, 1..*). :param converter: Type converter...
python
{ "resource": "" }
q57234
TypeBuilder.with_zero_or_one
train
def with_zero_or_one(cls, converter, pattern=None): """Creates a type converter for a T with 0..1 times by using the type converter for one item of T. :param converter: Type converter (function) for data type T. :param pattern: Regexp pattern for an item (=converter.pattern). :...
python
{ "resource": "" }
q57235
server_static
train
def server_static(filepath): """Handler for serving static files.""" mimetype = "image/svg+xml" if filepath.endswith(".svg") else "auto" return bottle.static_file(filepath, root=conf.StaticPath, mimetype=mimetype)
python
{ "resource": "" }
q57236
mouse
train
def mouse(table, day=None): """Handler for showing mouse statistics for specified type and day.""" where = (("day", day),) if day else () events = db.fetch(table, where=where, order="day") for e in events: e["dt"] = datetime.datetime.fromtimestamp(e["stamp"]) stats, positions, events = stats_mo...
python
{ "resource": "" }
q57237
keyboard
train
def keyboard(table, day=None): """Handler for showing the keyboard statistics page.""" cols, group = "realkey AS key, COUNT(*) AS count", "realkey" where = (("day", day),) if day else () counts_display = counts = db.fetch(table, cols, where, group, "count DESC") if "combos" == table: c...
python
{ "resource": "" }
q57238
inputindex
train
def inputindex(input): """Handler for showing keyboard or mouse page with day and total links.""" stats = {} countminmax = "SUM(count) AS count, MIN(day) AS first, MAX(day) AS last" tables = ("moves", "clicks", "scrolls") if "mouse" == input else ("keys", "combos") for table in tables: ...
python
{ "resource": "" }
q57239
index
train
def index(): """Handler for showing the GUI index page.""" stats = dict((k, {"count": 0}) for k, tt in conf.InputTables) countminmax = "SUM(count) AS count, MIN(day) AS first, MAX(day) AS last" for input, table in [(x, t) for x, tt in conf.InputTables for t in tt]: row = db.fetchone("counts...
python
{ "resource": "" }
q57240
stats_keyboard
train
def stats_keyboard(events, table): """Return statistics and collated events for keyboard events.""" if len(events) < 2: return [], [] deltas, prev_dt = [], None sessions, session = [], None UNBROKEN_DELTA = datetime.timedelta(seconds=conf.KeyboardSessionMaxDelta) blank = collections.defaul...
python
{ "resource": "" }
q57241
timedelta_seconds
train
def timedelta_seconds(timedelta): """Returns the total timedelta duration in seconds.""" return (timedelta.total_seconds() if hasattr(timedelta, "total_seconds") else timedelta.days * 24 * 3600 + timedelta.seconds + timedelta.microseconds / 1000000.)
python
{ "resource": "" }
q57242
init
train
def init(): """Initialize configuration and web application.""" global app if app: return app conf.init(), db.init(conf.DbPath, conf.DbStatements) bottle.TEMPLATE_PATH.insert(0, conf.TemplatePath) app = bottle.default_app() bottle.BaseTemplate.defaults.update(get_url=app.get_url) ...
python
{ "resource": "" }
q57243
start
train
def start(): """Starts the web server.""" global app bottle.run(app, host=conf.WebHost, port=conf.WebPort, debug=conf.WebAutoReload, reloader=conf.WebAutoReload, quiet=conf.WebQuiet)
python
{ "resource": "" }
q57244
download
train
def download(url, proxies=None): """ Download a PDF or DJVU document from a url, eventually using proxies. :params url: The URL to the PDF/DJVU document to fetch. :params proxies: An optional list of proxies to use. Proxies will be \ used sequentially. Proxies should be a list of proxy stri...
python
{ "resource": "" }
q57245
Field.make_format
train
def make_format(format_spec): """Build format string from a format specification. :param format_spec: Format specification (as FormatSpec object). :return: Composed format (as string). """ fill = '' align = '' zero = '' width = format_spec.width ...
python
{ "resource": "" }
q57246
FieldParser.extract_fields
train
def extract_fields(cls, schema): """Extract fields in a parse expression schema. :param schema: Parse expression schema/format to use (as string). :return: Generator for fields in schema (as Field objects). """ # -- BASED-ON: parse.Parser._generate_expression() for part ...
python
{ "resource": "" }
q57247
VSGLogger._registerHandler
train
def _registerHandler(self, handler): """ Registers a handler. :param handler: A handler object. """ self._logger.addHandler(handler) self._handlers.append(handler)
python
{ "resource": "" }
q57248
VSGLogger._unregisterHandler
train
def _unregisterHandler(self, handler, shutdown=True): """ Unregisters the logging handler. :param handler: A handler previously registered with this loggger. :param shutdown: Flag to shutdown the handler. """ if handler in self._handlers: self._handlers.remo...
python
{ "resource": "" }
q57249
VSGLogger.getLogger
train
def getLogger(cls, name=None): """ Retrieves the Python native logger :param name: The name of the logger instance in the VSG namespace (VSG.<name>); a None value will use the VSG root. :return: The instacne of the Python logger object. """ return logging.getLo...
python
{ "resource": "" }
q57250
VSGLogger.debug
train
def debug(cls, name, message, *args): """ Convenience function to log a message at the DEBUG level. :param name: The name of the logger instance in the VSG namespace (VSG.<name>) :param message: A message format string. :param args: The arguments that are are merged into m...
python
{ "resource": "" }
q57251
VSGLogger.info
train
def info(cls, name, message, *args): """ Convenience function to log a message at the INFO level. :param name: The name of the logger instance in the VSG namespace (VSG.<name>) :param message: A message format string. :param args: The arguments that are are merged into msg...
python
{ "resource": "" }
q57252
VSGLogger.warning
train
def warning(cls, name, message, *args): """ Convenience function to log a message at the WARNING level. :param name: The name of the logger instance in the VSG namespace (VSG.<name>) :param message: A message format string. :param args: The arguments that are are merged in...
python
{ "resource": "" }
q57253
VSGLogger.error
train
def error(cls, name, message, *args): """ Convenience function to log a message at the ERROR level. :param name: The name of the logger instance in the VSG namespace (VSG.<name>) :param message: A message format string. :param args: The arguments that are are merged into m...
python
{ "resource": "" }
q57254
VSGLogger.critical
train
def critical(cls, name, message, *args): """ Convenience function to log a message at the CRITICAL level. :param name: The name of the logger instance in the VSG namespace (VSG.<name>) :param message: A message format string. :param args: The arguments that are are merged ...
python
{ "resource": "" }
q57255
VSGLogger.exception
train
def exception(cls, name, message, *args): """ Convenience function to log a message at the ERROR level with additonal exception information. :param name: The name of the logger instance in the VSG namespace (VSG.<name>) :param message: A message format string. :param args: ...
python
{ "resource": "" }
q57256
AuthChecker.allow
train
def allow(self, ctx, ops): ''' Checks that the authorizer's request is authorized to perform all the given operations. Note that allow does not check first party caveats - if there is more than one macaroon that may authorize the request, it will choose the first one that does re...
python
{ "resource": "" }
q57257
AuthChecker.allow_any
train
def allow_any(self, ctx, ops): ''' like allow except that it will authorize as many of the operations as possible without requiring any to be authorized. If all the operations succeeded, the array will be nil. If any the operations failed, the returned error will be the same tha...
python
{ "resource": "" }
q57258
AuthChecker.allow_capability
train
def allow_capability(self, ctx, ops): '''Checks that the user is allowed to perform all the given operations. If not, a discharge error will be raised. If allow_capability succeeds, it returns a list of first party caveat conditions that must be applied to any macaroon granting capabilit...
python
{ "resource": "" }
q57259
RecipesListPlugin.register
train
def register(self, name, path, description, final_words=None): """ Registers a new recipe in the context of the current plugin. :param name: Name of the recipe :param path: Absolute path of the recipe folder :param description: A meaningful description of the recipe :par...
python
{ "resource": "" }
q57260
RecipesListPlugin.get
train
def get(self, name=None): """ Gets a list of all recipes, which are registered by the current plugin. If a name is provided, only the requested recipe is returned or None. :param: name: Name of the recipe """ return self.__app.recipes.get(name, self._plugin)
python
{ "resource": "" }
q57261
RecipesListPlugin.build
train
def build(self, recipe): """ Builds a recipe :param recipe: Name of the recipe to build. """ return self.__app.recipes.build(recipe, self._plugin)
python
{ "resource": "" }
q57262
RecipesListApplication.register
train
def register(self, name, path, plugin, description=None, final_words=None): """ Registers a new recipe. """ if name in self.recipes.keys(): raise RecipeExistsException("Recipe %s was already registered by %s" % (name, self.recipes["name...
python
{ "resource": "" }
q57263
RecipesListApplication.unregister
train
def unregister(self, recipe): """ Unregisters an existing recipe, so that this recipe is no longer available. This function is mainly used during plugin deactivation. :param recipe: Name of the recipe """ if recipe not in self.recipes.keys(): self.__log.warn...
python
{ "resource": "" }
q57264
RecipesListApplication.get
train
def get(self, recipe=None, plugin=None): """ Get one or more recipes. :param recipe: Name of the recipe :type recipe: str :param plugin: Plugin object, under which the recipe was registered :type plugin: GwBasePattern """ if plugin is not None: ...
python
{ "resource": "" }
q57265
RecipesListApplication.build
train
def build(self, recipe, plugin=None): """ Execute a recipe and creates new folder and files. :param recipe: Name of the recipe :param plugin: Name of the plugin, to which the recipe must belong. """ if recipe not in self.recipes.keys(): raise RecipeMissingExc...
python
{ "resource": "" }
q57266
Recipe.build
train
def build(self, output_dir=None, **kwargs): """ Buildes the recipe and creates needed folder and files. May ask the user for some parameter inputs. :param output_dir: Path, where the recipe shall be build. Default is the current working directory :return: location of the install...
python
{ "resource": "" }
q57267
where_am_i
train
def where_am_i(): """ high level function that can estimate where user is based on predefined setups. """ locations = {'Work':0, 'Home':0} for ssid in scan_for_ssids(): #print('checking scanned_ssid ', ssid) for l in logged_ssids: #print('checking logged_ssid ', l) ...
python
{ "resource": "" }
q57268
Context.summarise
train
def summarise(self): """ extrapolate a human readable summary of the contexts """ res = '' if self.user == 'Developer': if self.host == 'Home PC': res += 'At Home' else: res += 'Away from PC' elif self.user == 'Us...
python
{ "resource": "" }
q57269
Context.get_host
train
def get_host(self): """ returns the host computer running this program """ import socket host_name = socket.gethostname() for h in hosts: if h['name'] == host_name: return h['type'], h['name'] return dict(type='Unknown', name=host_nam...
python
{ "resource": "" }
q57270
Context.get_user
train
def get_user(self): """ returns the username on this computer """ for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'): user = os.environ.get(name) if user: break for u in users: if u['name'] == user: retu...
python
{ "resource": "" }
q57271
Context.get_host_usage
train
def get_host_usage(self): """ get details of CPU, RAM usage of this PC """ import psutil process_names = [proc.name for proc in psutil.process_iter()] cpu_pct = psutil.cpu_percent(interval=1) mem = psutil.virtual_memory() return str(cpu_pct), str(len(pro...
python
{ "resource": "" }
q57272
ShellConfig.schema
train
def schema(): """Provide schema for shell configuration.""" return Schema({ 'script': And(Or(type(' '), type(u' ')), len), Optional('title', default=''): str, Optional('model', default={}): {Optional(And(str, len)): object}, Optional('env', default={}): {O...
python
{ "resource": "" }
q57273
Projects.get_by_name
train
def get_by_name(self, name): """ returns an object Project which matches name """ for p in self.project_list: if p.nme == name: return p return None
python
{ "resource": "" }
q57274
Project.execute_tasks
train
def execute_tasks(self): """ run execute on all tasks IFF prior task is successful """ for t in self.tasks: print('RUNNING ' + str(t.task_id) + ' = ' + t.name) t.execute() if t.success != '__IGNORE__RESULT__': print(t) p...
python
{ "resource": "" }
q57275
Project.build_report
train
def build_report(self, op_file, tpe='md'): """ create a report showing all project details """ if tpe == 'md': res = self.get_report_md() elif tpe == 'rst': res = self.get_report_rst() elif tpe == 'html': res = self.get_report_html() ...
python
{ "resource": "" }
q57276
Project.get_report_rst
train
def get_report_rst(self): """ formats the project into a report in RST format """ res = '' res += '-----------------------------------\n' res += self.nme + '\n' res += '-----------------------------------\n\n' res += self.desc + '\n' res += self....
python
{ "resource": "" }
q57277
Project.get_report_html
train
def get_report_html(self): """ formats the project into a report in MD format - WARNING - tables missing BR """ res = '<h2>Project:' + self.nme + '</h2>' res += '<p>' + self.desc + '</p>' res += '<p>' + self.fldr + '</p>' res += '<BR><h3>TABLES</h3>' ...
python
{ "resource": "" }
q57278
Task.add_param
train
def add_param(self, param_key, param_val): """ adds parameters as key value pairs """ self.params.append([param_key, param_val]) if param_key == '__success_test': self.success = param_val
python
{ "resource": "" }
q57279
Task.execute
train
def execute(self): """ executes all automatic tasks in order of task id """ func_params = [] exec_str = self.func.__name__ + '(' for p in self.params: if p[0][0:2] != '__': # ignore custom param names exec_str += p[0] + '="' + self._force_st...
python
{ "resource": "" }
q57280
create_column_index
train
def create_column_index(annotations): """ Create a pd.MultiIndex using the column names and any categorical rows. Note that also non-main columns will be assigned a default category ''. """ _column_index = OrderedDict({'Column Name' : annotations['Column Name']}) categorical_rows = annotation_ro...
python
{ "resource": "" }
q57281
read_perseus
train
def read_perseus(path_or_file, **kwargs): """ Read a Perseus-formatted matrix into a pd.DataFrame. Annotation rows will be converted into a multi-index. By monkey-patching the returned pd.DataFrame a `to_perseus` method for exporting the pd.DataFrame is made available. :param path_or_file: Fil...
python
{ "resource": "" }
q57282
to_perseus
train
def to_perseus(df, path_or_file, main_columns=None, separator=separator, convert_bool_to_category=True, numerical_annotation_rows = set([])): """ Save pd.DataFrame to Perseus text format. :param df: pd.DataFrame. :param path_or_file: File name or file-like object. :param mai...
python
{ "resource": "" }
q57283
get_page
train
def get_page(search_text): """ formats the entire search result in a table output """ lst = search_aikif(search_text) txt = '<table class="as-table as-table-zebra as-table-horizontal">' for result in lst: txt += '<TR><TD>' + result + '</TD></TR>' txt += '</TABLE>\n\n' return txt
python
{ "resource": "" }
q57284
search_aikif
train
def search_aikif(txt, formatHTML=True): """ search for text - currently this looks in all folders in the root of AIKIF but that also contains binaries so will need to use the agent_filelist.py to specify the list of folders. NOTE - this needs to use indexes rather than full search each time ...
python
{ "resource": "" }
q57285
format_result
train
def format_result(line, line_num, txt): """ highlight the search result """ return '&nbsp;&nbsp;' + str(line_num) + ': ' + line.replace(txt, '<span style="background-color: #FFFF00">' + txt + '</span>')
python
{ "resource": "" }
q57286
TEST
train
def TEST(): """ Modules for testing happiness of 'persons' in 'worlds' based on simplistic preferences. Just a toy - dont take seriously ----- WORLD SUMMARY for : Mars ----- population = 0 tax_rate = 0.0 tradition = 0.9 equity = 0.0 Preferences for Rov...
python
{ "resource": "" }
q57287
WorldFinder.solve
train
def solve(self, max_worlds=10000, silent=False): """ find the best world to make people happy """ self.num_worlds = 0 num_unhappy = 0 for tax_rate in range(self.tax_range[0],self.tax_range[1]): for equity in range(self.equity_range[0],self.equity_range[1]): ...
python
{ "resource": "" }
q57288
Happiness.show_details
train
def show_details(self): """ extended print details of happiness parameters """ res = str(self) res += '\nDETAILS\n' for f in self.factors: res += str(f) return res
python
{ "resource": "" }
q57289
Value.match_value_to_text
train
def match_value_to_text(self, text): """ this is going to be the tricky bit - probably not possible to get the 'exact' rating for a value. Will need to do sentiment analysis of the text to see how it matches the rating. Even that sounds like it wont work - maybe a ML algorithm wo...
python
{ "resource": "" }
q57290
list2html
train
def list2html(lst): """ convert a list to html using table formatting """ txt = '<TABLE width=100% border=0>' for l in lst: txt += '<TR>\n' if type(l) is str: txt+= '<TD>' + l + '</TD>\n' elif type(l) is list: txt+= '<TD>' for i in l: ...
python
{ "resource": "" }
q57291
build_edit_form
train
def build_edit_form(title, id, cols, return_page): """ returns the html for a simple edit form """ txt = '<H3>' + title + '<H3>' txt += '<form action="' + return_page + '" method="POST">\n' # return_page = /agents txt += ' updating id:' + str(id) + '\n<BR>' txt += ' <input type="hidden" ...
python
{ "resource": "" }
q57292
build_html_listbox
train
def build_html_listbox(lst, nme): """ returns the html to display a listbox """ res = '<select name="' + nme + '" multiple="multiple">\n' for l in lst: res += ' <option>' + str(l) + '</option>\n' res += '</select>\n' return res
python
{ "resource": "" }
q57293
build_data_list
train
def build_data_list(lst): """ returns the html with supplied list as a HTML listbox """ txt = '<H3>' + List + '<H3><UL>' for i in lst: txt += '<LI>' + i + '</LI>' txt += '<UL>' return txt
python
{ "resource": "" }
q57294
filelist2html
train
def filelist2html(lst, fldr, hasHeader='N'): """ formats a standard filelist to htmk using table formats """ txt = '<TABLE width=100% border=0>' numRows = 1 if lst: for l in lst: if hasHeader == 'Y': if numRows == 1: td_begin = '<TH>' ...
python
{ "resource": "" }
q57295
link_file
train
def link_file(f, fldr): """ creates a html link for a file using folder fldr """ fname = os.path.join(fldr,f) if os.path.isfile(fname): return '<a href="/aikif/data/core/' + f + '">' + f + '</a>' else: return f
python
{ "resource": "" }
q57296
dict_to_htmlrow
train
def dict_to_htmlrow(d): """ converts a dictionary to a HTML table row """ res = "<TR>\n" for k, v in d.items(): if type(v) == str: res = res + '<TD><p>' + k + ':</p></TD><TD><p>' + v + '</p></TD>' else: res = res + '<TD><p>' + k + ':</p></TD><TD><p>' + str(v) ...
python
{ "resource": "" }
q57297
read_csv_to_html_table
train
def read_csv_to_html_table(csvFile, hasHeader='N'): """ reads a CSV file and converts it to HTML """ txt = '<table class="as-table as-table-zebra as-table-horizontal">' with open(csvFile, "r") as f: # numRows = 1 for row in f: if hasHeader == 'Y': if num...
python
{ "resource": "" }
q57298
read_csv_to_html_list
train
def read_csv_to_html_list(csvFile): """ reads a CSV file and converts it to a HTML List """ txt = '' with open(csvFile) as csv_file: for row in csv.reader(csv_file, delimiter=','): txt += '<div id="table_row">' for col in row: txt += " " ...
python
{ "resource": "" }
q57299
ExploreAgent.do_your_job
train
def do_your_job(self): """ the goal of the explore agent is to move to the target while avoiding blockages on the grid. This function is messy and needs to be looked at. It currently has a bug in that the backtrack oscillates so need a new method of doing this - probably...
python
{ "resource": "" }