_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q54500
Queue.put
train
def put(self, value, priority=100): """ Put a task into the queue. Args: value (str): Task data. priority (int): An optional priority as an integer with at most 3 digits. Lower values signify higher priority. """ task_name = '{}{:03d}_{}'....
python
{ "resource": "" }
q54501
Queue._get_avaliable_tasks
train
def _get_avaliable_tasks(self): """Get all tasks present in the queue.""" base_task = posixpath.join(self._queue_path, self.TASK_PREFIX) tasks = self._client.kv.find(prefix=base_task) return sorted(tasks.items())
python
{ "resource": "" }
q54502
Queue._counter
train
def _counter(self): """Current task counter.""" count = int(self._client.kv[self._counter_path]) count += 1 count_str = str(count).zfill(self._COUNTER_FILL) self._client.kv[self._counter_path] = count_str return count_str
python
{ "resource": "" }
q54503
madParser
train
def madParser(mad_filename, idbl="BL"): """function to parse beamline with MAD-8 input format :param mad_filename: lattice filename with mad-8 like format :param idbl: beamline to be used that defined in lattice file, default value is ``BL`` :return: list of dict that contains magneti...
python
{ "resource": "" }
q54504
Database.tables
train
def tables(self): """ Returns a list of table names. Example: >>> db.tables ["bar", "foo"] Returns: list of str: One string for each table name. """ select = ("SELECT name FROM sqlite_master",) query = self.execute(*select) ...
python
{ "resource": "" }
q54505
Database.schema
train
def schema(self): """ Returns the schema of all tables. For each table, return the name, and a list of tuples representing the columns. Each column tuple consists of a (name, type) pair. Note that additional metadata, such as whether a column may be null, or whether a co...
python
{ "resource": "" }
q54506
Database.table_info
train
def table_info(self, table): """ Returns information about the named table. See: https://www.sqlite.org/pragma.html#pragma_table_info Example: >>> db.table_info("foo") [{"name": "id", "type": "integer", "primary key": True, "notnull": False, "defa...
python
{ "resource": "" }
q54507
Database.isempty
train
def isempty(self, tables=None): """ Return whether a table or the entire database is empty. A database is empty is if it has no tables. A table is empty if it has no rows. Arguments: tables (sequence of str, optional): If provided, check that the name...
python
{ "resource": "" }
q54508
Database.create_table_from
train
def create_table_from(self, name, src): """ Create a new table with same schema as the source. If the named table already exists, nothing happens. Arguments: name (str): The name of the table to create. src (str): The name of the source table to duplicate. ...
python
{ "resource": "" }
q54509
Database.copy_table
train
def copy_table(self, src, dst): """ Create a carbon copy of the source table. Arguments: src (str): The name of the table to copy. dst (str): The name of the target duplicate table. Raises: sql.OperationalError: If source table does not exist. ...
python
{ "resource": "" }
q54510
Database.export_csv
train
def export_csv(self, table, output=None, columns="*", **kwargs): """ Export a table to a CSV file. If an output path is provided, write to file. Else, return a string. Wrapper around pandas.sql.to_csv(). See: http://pandas.pydata.org/pandas-docs/stable/io.html#io-store-...
python
{ "resource": "" }
q54511
attr
train
def attr(**context): """ Decorator that add attributes into func. Added attributes can be access outside via function's `func_dict` property. """ #TODO(Jim Zhan) FIXME def decorator(func): def wrapped_func(*args, **kwargs): for key, value in context.items(): ...
python
{ "resource": "" }
q54512
timeit
train
def timeit(func): """ Decorator that logs the cost time of a function. """ @wraps(func) def wrapped_func(*args, **kwargs): start = timer() result = func(*args, **kwargs) cost = timer() - start logger.debug('<method: %s> finished in %2.2f sec' % (func.__name__, cost...
python
{ "resource": "" }
q54513
traceback
train
def traceback(frame, parent=False): """Pick frame info from current caller's `frame`. Args: * frame: :type:`frame` instance, use :func:`inspect.currentframe`. * parent: whether to get outer frame (caller) traceback info, :data:`False` by default. Returns: :class:`inspect.Trackback`...
python
{ "resource": "" }
q54514
extend_config
train
def extend_config(config, config_items): """ We are handling config value setting like this for a cleaner api. Users just need to pass in a named param to this source and we can dynamically generate a config object for it. """ for key, val in list(config_items.items()): if hasattr(config...
python
{ "resource": "" }
q54515
WorkerProcess.write
train
def write(self, data): """Sends some data to the client.""" # I don't want to add a separate 'Client disconnected' logic for sending. # Therefore I just ignore any writes after the first error - the server # won't send that much data anyway. Afterwards the read will detect the # ...
python
{ "resource": "" }
q54516
realpath
train
def realpath(path): """ Create the real absolute path for the given path. Add supports for userdir & / supports. Args: * path: pathname to use for realpath. Returns: Platform independent real absolute path. """ if path == '~': return userdir if path == '/': ...
python
{ "resource": "" }
q54517
FS.copy
train
def copy(self, dest): """ Copy item to the given `dest` path. Args: * dest: destination path to copy. """ if os.path.isfile(self.path): shutil.copy2(self.path, dest) else: shutil.copytree(self.path, dest, symlinks=False, ignore=None)
python
{ "resource": "" }
q54518
CoolDict._ancestry_line
train
def _ancestry_line(self): ''' Returns the ancestry of this dict, back to the first dict that we don't recognize or that has more than one backer. ''' b = self._get_backers() while len(b) == 1: yield b[0] if not hasattr(b[0], '_get_backers'): ...
python
{ "resource": "" }
q54519
get
train
def get(key, default=None): """Retrieves env vars and makes Python boolean replacements""" val = os.environ.get(key, default) if val == 'True': val = True elif val == 'False': val = False return val
python
{ "resource": "" }
q54520
read
train
def read(env_file=".env"): """ Pulled from Honcho code with minor updates, reads local default environment variables from a .env file located in the project root directory. """ try: with open(env_file) as f: content = f.read() except IOError: content = '' fo...
python
{ "resource": "" }
q54521
LockFile.read
train
def read(path): """ Read the contents of a LockFile. Arguments: path (str): Path to lockfile. Returns: Tuple(int, datetime): The integer PID of the lock owner, and the date the lock was required. If the lock is not claimed, both v...
python
{ "resource": "" }
q54522
LockFile.write
train
def write(path, pid, timestamp): """ Write the contents of a LockFile. Arguments: path (str): Path to lockfile. pid (int): The integer process ID. timestamp (datetime): The time the lock was aquired. """ with open(path, "w") as lockfile: ...
python
{ "resource": "" }
q54523
import_foreign
train
def import_foreign(name, custom_name=None): """ Import a module with a custom name. NOTE this is only needed for Python2. For Python3, import the module using the "as" keyword to declare the custom name. For implementation details, see: http://stackoverflow.com/a/6032023 Example: T...
python
{ "resource": "" }
q54524
VincentyDistance
train
def VincentyDistance(lon1_in,lat1_in,lon2_in,lat2_in,ELLIPSOID='GRS-80'): """ Calculate the geodesic distance between two points using the formula devised by Thaddeus Vincenty, with an accurate ellipsoidal model of the earth. The class attribute `ELLIPSOID` indicates which ellipsoidal mode...
python
{ "resource": "" }
q54525
apply_plot_params
train
def apply_plot_params(plot_params,ax): """Apply parameters to current axis.""" import matplotlib.pyplot as plt if plot_params['xlim'] is not None: ax.set_xlim(plot_params['xlim']) if plot_params['reverse_x'] and plot_params['xlim'][0] < plot_params['xlim'][1]: ax....
python
{ "resource": "" }
q54526
create_user_profile
train
def create_user_profile(sender, instance, created, **kwargs): """Create the UserProfile when a new User is saved""" if created: profile = UserProfile.objects.get_or_create(user=instance)[0] profile.hash_pass = create_htpasswd(instance.hash_pass) profile.save() else: # update ...
python
{ "resource": "" }
q54527
body
train
def body(schema=None, types=None, required=False, default=None): """Decorator to parse and validate API body. :keyword schema: callable that accepts raw data and returns the coerced (or unchanged) data if it is valid. It should raise an error if the data is not valid. :keyword types: suppor...
python
{ "resource": "" }
q54528
paginated
train
def paginated(resource_name=None): """Decorator that handles pagination headers, params, and links. This accepts, parses, validates, and handles `limit` and `offset` optional query params according to common Rackspace APIs and passes them as kwargs to the decorated function. offset: The pagina...
python
{ "resource": "" }
q54529
validate_range_values
train
def validate_range_values(request, label, kwargs): """Ensure value contained in label is a positive integer.""" value = kwargs.get(label, request.query.get(label)) if value: kwargs[label] = int(value) if kwargs[label] < 0 or kwargs[label] > MAX_PAGE_SIZE: raise ValueError
python
{ "resource": "" }
q54530
write_pagination_headers
train
def write_pagination_headers(data, offset, limit, response, uripath, resource_name): """Add pagination headers to the bottle response. See docs in :func:`paginated`. """ items = data.get('results') or data.get('data') or {} count = len(items) try: total = in...
python
{ "resource": "" }
q54531
process_params
train
def process_params(request, standard_params=STANDARD_QUERY_PARAMS, filter_fields=None, defaults=None): """Parse query params. Parses, validates, and converts query into a consistent format. :keyword request: the bottle request :keyword standard_params: query params that are present ...
python
{ "resource": "" }
q54532
httperror_handler
train
def httperror_handler(error): """Format error responses properly, return the response body. This function can be attached to the Bottle instance as the default_error_handler function. It is also used by the FormatExceptionMiddleware. """ status_code = error.status_code or 500 output = { ...
python
{ "resource": "" }
q54533
send_email
train
def send_email(template_name, context=None, *args, **kwargs): """ Send a templated email. To generate the message used for the email, the method first searches for an HTML template with the given name (eg: <template>.html), and renders it with the provided context. The process is repeated for t...
python
{ "resource": "" }
q54534
validate
train
def validate(opts): """ Client facing validate function for command line arguments. Perform validation operations on opts, a namespace created from command line arguments. Returns True if all validation tests are successful. If an exception is raised by the validations, this gracefully exits the ...
python
{ "resource": "" }
q54535
_validate
train
def _validate(opts): """ Perform validation operations on opts, a namespace created from command-line arguments. Returns True if all validation tests are successful. Runs validation() methods in validate_input.py, validate_extensions.py, validate_overwrite.py, and validate_wrapper.py Required ...
python
{ "resource": "" }
q54536
dihedral
train
def dihedral(array_of_xyzs): """ Calculates dihedral angle between four coordinate points. Used for dihedral constraints. """ p1 = array_of_xyzs[0] p2 = array_of_xyzs[1] p3 = array_of_xyzs[2] p4 = array_of_xyzs[3] vector1 = -1.0 * (p2 - p1) vector2 = p3 - p2 vector3 = p4 - ...
python
{ "resource": "" }
q54537
find_pareto_front
train
def find_pareto_front(metrics, metadata, columns, depth=1, epsilon=None, progress=None): """ Return the subset of the given metrics that are Pareto optimal with respect to the given columns. Arguments ========= metrics: DataFrame A dataframe where each row is a different model or desig...
python
{ "resource": "" }
q54538
case_us2mc
train
def case_us2mc(x): """ underscore to mixed case notation """ return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), x)
python
{ "resource": "" }
q54539
Service.listen_init
train
def listen_init(self): """Setup the service to listen for clients.""" self.dispatcher = ObjectDispatch(self) self.factory = MsgPackProtocolFactory(self.dispatcher) self.server = UnixServer(self.loop, self.factory, self.path) self.server.start()
python
{ "resource": "" }
q54540
Service.stop
train
def stop(self, reason=None): """Shutdown the service with a reason.""" self.logger.info('stopping') self.loop.stop(pyev.EVBREAK_ALL)
python
{ "resource": "" }
q54541
Service.terminate
train
def terminate(self, reason=None): """Terminate the service with a reason.""" self.logger.info('terminating') self.loop.unloop(pyev.EVUNLOOP_ALL)
python
{ "resource": "" }
q54542
MarkdownATXWriterStrategy.modify
train
def modify(self, current_modified_line, anchors, file_path, file_lines=None, index=None): """ Removes the trailing AnchorHub tag from the end of the line being examined. :param current_modified_line: string representing the the line at file_lines[index] _after...
python
{ "resource": "" }
q54543
MarkdownInlineLinkWriterStrategy.modify
train
def modify(self, current_modified_line, anchors, file_path, file_lines=None, index=None): """ Replace all AnchorHub tag-using inline links in this line and edit them to use :param current_modified_line: string representing the the line at file_lines[index] _af...
python
{ "resource": "" }
q54544
MarkdownInlineLinkWriterStrategy._get_file_key
train
def _get_file_key(self, file_path, link_path): """ Finds the absolute path of link_path relative to file_path. The absolute path is the key to anchors dictionary used throughout the AnchorHub process :param file_path: string file path of the file that contains the link ...
python
{ "resource": "" }
q54545
MarkdownInlineLinkWriterStrategy._get_link_indices
train
def _get_link_indices(self, current_modified_line): """ Get a list of tuples containing start and end indices of inline anchor links :param current_modified_line: The line being examined for links :return: A list containing tuples of the form (start, end), the starting a...
python
{ "resource": "" }
q54546
MarkdownInlineLinkWriterStrategy._file_has_tag_anchor_keypair
train
def _file_has_tag_anchor_keypair(self, anchors, file_key, tag): """ Is there an AnchorHub tag, 'tag', registered for file 'file_key' in 'anchors'? :param anchors: Dictionary mapping string file paths to inner dictionaries. These inner dictionaries map string AnchorHub tags ...
python
{ "resource": "" }
q54547
coerce_one
train
def coerce_one(schema=str): """Expect the input sequence to contain a single value. :keyword schema: Custom schema to apply to the input value. Defaults to just string, since this is designed for query params. """ def validate(val): """Unpack a single item from the inputs sequen...
python
{ "resource": "" }
q54548
coerce_many
train
def coerce_many(schema=str): """Expect the input to be a sequence of items which conform to `schema`.""" def validate(val): """Apply schema check/version to each item.""" return [volup.Coerce(schema)(x) for x in val] return validate
python
{ "resource": "" }
q54549
schema
train
def schema(body_schema=None, body_required=False, query_schema=None, # noqa content_types=None, default_body=None): """Decorator to parse and validate API body and query string. This decorator allows one to define the entire 'schema' for an API endpoint. :keyword body_schema: Calla...
python
{ "resource": "" }
q54550
MultiValidationError._generate_message
train
def _generate_message(self): """Reformat `path` attributes of each `error` and create a new message. Join `path` attributes together in a more readable way, to enable easy debugging of an invalid Checkmatefile. :returns: Reformatted error paths and messages, as a multi-line...
python
{ "resource": "" }
q54551
multi_pop
train
def multi_pop(d, *args): """ pops multiple keys off a dict like object """ retval = {} for key in args: if key in d: retval[key] = d.pop(key) return retval
python
{ "resource": "" }
q54552
csvtolist
train
def csvtolist(inputstr): """ converts a csv string into a list """ reader = csv.reader([inputstr], skipinitialspace=True) output = [] for r in reader: output += r return output
python
{ "resource": "" }
q54553
unique
train
def unique(seq, preserve_order=True): """ Take a sequence and make it unique. Not preserving order is faster, but that won't matter so much for most uses. copied from: http://www.peterbe.com/plog/uniqifiers-benchmark/uniqifiers_benchmark.py """ if preserve_order: # f8 by Da...
python
{ "resource": "" }
q54554
prettifysql
train
def prettifysql(sql): """Returns a prettified version of the SQL as a list of lines to help in creating a useful diff between two SQL statements.""" pretty = [] for line in sql.split('\n'): pretty.extend(["%s,\n" % x for x in line.split(',')]) return pretty
python
{ "resource": "" }
q54555
diff
train
def diff(actual, expected): """ normalize whitespace in actual and expected and return unified diff """ return '\n'.join(list( difflib.unified_diff(actual.splitlines(), expected.splitlines()) ))
python
{ "resource": "" }
q54556
filter_dict
train
def filter_dict(d, cb): """ Filter a dictionary based on passed function. :param d: The dictionary to be filtered :param cb: A function which is called back for each k, v pair of the dictionary. Should return Truthy or Falsey :return: The filtered dictionary (new instance) """ return {k: v...
python
{ "resource": "" }
q54557
system_exit_exception_handler
train
def system_exit_exception_handler(*args): """ Provides a system exit exception handler. :param \*args: Arguments. :type \*args: \* :return: Definition success. :rtype: bool """ reporter = Reporter() reporter.Footer_label.setText( "The severity of this exception is critical,...
python
{ "resource": "" }
q54558
critical_exception_handler
train
def critical_exception_handler(object): """ Marks an object that would system exit in case of critical exception. :param object: Object to decorate. :type object: object :return: Object. :rtype: object """ @functools.wraps(object) def critical_exception_handler_wrapper(*args, **kwa...
python
{ "resource": "" }
q54559
install_exception_reporter
train
def install_exception_reporter(report=True): """ Installs the exceptions reporter. :param report: Report to Crittercism. :type report: bool :return: Reporter instance. :rtype: Reporter """ reporter = Reporter(report=report) sys.excepthook = reporter return reporter
python
{ "resource": "" }
q54560
Reporter.__initialize_context_ui
train
def __initialize_context_ui(self): """ Sets the context Widget ui. """ if foundations.common.is_internet_available(): text = self.__onlineText else: text = self.__offlineText self.Header_label.setText(text)
python
{ "resource": "" }
q54561
Reporter.__get_html
train
def __get_html(self, body=None): """ Returns the html content with given body tag content. :param body: Body tag content. :type body: unicode :return: Html. :rtype: unicode """ output = [] output.append("<html>") output.append("<head>") ...
python
{ "resource": "" }
q54562
Reporter.__set_html
train
def __set_html(self, html=None): """ Sets the html content in the View using given body. :param html: Html content. :type html: unicode """ self.__html = self.__get_html(html) self.__view.setHtml(self.__html)
python
{ "resource": "" }
q54563
Reporter.__update_html
train
def __update_html(self, html): """ Updates the View with given html content. :param html: Html content. :type html: unicode """ if platform.system() in ("Windows", "Microsoft"): html = re.sub(r"((?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+)", ...
python
{ "resource": "" }
q54564
Reporter.handle_exception
train
def handle_exception(self, *args): """ Handles given exception. :param \*args: Arguments. :type \*args: \* """ if not self.__enabled: return cls, instance, trcback = foundations.exceptions.extract_exception(*args) LOGGER.info("{0} | Handlin...
python
{ "resource": "" }
q54565
Reporter.report_exception_to_crittercism
train
def report_exception_to_crittercism(self, *args): """ Reports given exception to Crittercism. :param \*args: Arguments. :type \*args: \* :return: Method success. :rtype: bool """ if foundations.common.is_internet_available(): cls, instance, t...
python
{ "resource": "" }
q54566
StatsdTimingMiddleware.get_key_name
train
def get_key_name(self, environ, response_interception, exception=None): """Get the timer key name. :param environ: wsgi environment :type environ: dict :param response_interception: dictionary in form {'status': '<response status>', 'response_headers': [<response headers], '...
python
{ "resource": "" }
q54567
StatsdTimingMiddleware.send_stats
train
def send_stats(self, start, environ, response_interception, exception=None): """Send the actual timing stats. :param start: start time in seconds since the epoch as a floating point number :type start: float :param environ: wsgi environment :type environ: dict :param res...
python
{ "resource": "" }
q54568
MyPlotPanel.set_layout
train
def set_layout(self): """ set panel layout """ sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.canvas, 1, wx.EXPAND) hbox = wx.BoxSizer(wx.HORIZONTAL) if self.toolbar is not None: self.toobar = MyToolbar(self.canvas) self.toobar.Realize() ...
python
{ "resource": "" }
q54569
MyPlotPanel.set_color
train
def set_color(self, rgb_tuple): """ set figure and canvas with the same color. :param rgb_tuple: rgb color tuple, e.g. (255, 255, 255) for white color """ if rgb_tuple is None: rgb_tuple = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE).Get() clr = [c / 255.0 for ...
python
{ "resource": "" }
q54570
load_image
train
def load_image(buf, request_components=0): """Load a png or jpeg image into a bitmap buffer. Args: buf (Buffer): Buffer to load request_components (int): If you want to force number of components Returns: A tuple containing: - Bitmap buffer - width of bitmap ...
python
{ "resource": "" }
q54571
histogram
train
def histogram(data, bins=None, binsize=1., min=None, max=None, rev=False, use_weave=True, verbose=0): """ Similar to IDL histogram. For reverse indices, the fast version uses weave from scipy. This is the default. If scipy is not available a slower version is used. """ if not have_s...
python
{ "resource": "" }
q54572
_weave_dohist
train
def _weave_dohist(data, s, binsize, hist, rev, dorev=False, verbose=0): if dorev: dorev=1 else: dorev=0 """ Weave version of histogram with reverse_indices s is an index into data, sorted and possibly a subset """ code = """ int64_t nbin = hist.size(); ...
python
{ "resource": "" }
q54573
prepare_service
train
def prepare_service(args=None): """Configures application and setups logging.""" options.register_opts(cfg.CONF) services.load_service_opts(cfg.CONF) _configure(args) _setup_logging() cfg.CONF.log_opt_values(logging.getLogger(), logging.DEBUG)
python
{ "resource": "" }
q54574
base64_encode
train
def base64_encode(data): """ Base 64 encoder """ total = len(data) result = [] mod = 0 for i in range(total): cur = ord(data[i]) mod = i % 3 if mod == 0: result.append(__enc64__[cur >> 2]) elif mod == 1: prev = ord(data[i - 1]) ...
python
{ "resource": "" }
q54575
base64_decode
train
def base64_decode(data): """ Base 64 decoder """ data = data.replace(__enc64__[64], '') total = len(data) result = [] mod = 0 for i in range(total): mod = i % 4 cur = __enc64__.index(data[i]) if mod == 0: continue elif mod == 1: pre...
python
{ "resource": "" }
q54576
Bar.get_timedelta
train
def get_timedelta(self, now=None): """ Returns number of seconds that passed since ``self.started``, as float. None is returned if ``self.started`` was not set yet. """ def datetime_to_time(timestamp): atime = time.mktime(timestamp.timetuple()) atime += ti...
python
{ "resource": "" }
q54577
Bar.render
train
def render(self): """ Returns whole information on the progress for the current's bar state, as a string. """ elements = [self.render_element(e) for e in self.widgets] progressbar = self.separator.join(elements) width = get_terminal_width() if width: ...
python
{ "resource": "" }
q54578
strip_prefix
train
def strip_prefix(string, strip): """ Strips a prefix from a string, if the string starts with the prefix. :param string: String that should have its prefix removed :param strip: Prefix to be removed :return: string with the prefix removed if it has the prefix, or else it just returns the or...
python
{ "resource": "" }
q54579
strip_prefix_from_list
train
def strip_prefix_from_list(list, strip): """ Goes through a list of strings and removes the specified prefix from the beginning of each string in place. :param list: a list of strings to be modified in place :param strip: a string specifying the prefix to remove from the list """ for i in r...
python
{ "resource": "" }
q54580
calculate_rates
train
def calculate_rates(base_currency, counter_currency, forward_rate=None, fwd_points=None, spot_reference=None): """Calculate rates for Fx Forward based on others.""" if base_currency not in DIVISOR_TABLE: divisor = DIVISOR_TABLE.get(counter_currency, DEFAULT_DIVISOR) if forward_rate is None and f...
python
{ "resource": "" }
q54581
interpolate_using_previous
train
def interpolate_using_previous(pointlist): ''' Throw InterpolationError if a key has no non-null values Return pointlist without gaps ''' pl = pointlist # alias npl = [] # new, interpolated pointlist if len(pl) < 1: raise InterpolationError('Empty list c...
python
{ "resource": "" }
q54582
finalise
train
def finalise(output=None, figsize=None, tight=True, **kwargs): """ Finalise a plot. Display or show the plot, then close it. Arguments: output (str, optional): Path to save figure to. If not given, show plot. figsize ((float, float), optional): Figure size in inches. ...
python
{ "resource": "" }
q54583
ShowErrorBarCaps
train
def ShowErrorBarCaps(ax): """Show error bar caps.    Seaborn paper style hides error bar caps. Call this function on an axes object to make them visible again. """ for ch in ax.get_children(): if str(ch).startswith('Line2D'): ch.set_markeredgewidth(1) ch.set_markersiz...
python
{ "resource": "" }
q54584
JSONPRCCollection.register_class
train
def register_class(self, instance, name=None): """Add all functions of a class-instance to the RPC-services. All entries of the instance which do not begin with '_' are added. :Parameters: - myinst: class-instance containing the functions - name: | hierarchical prefix...
python
{ "resource": "" }
q54585
JSONPRCApplication.process_method
train
def process_method(self, method, args, kwargs, request_id=None, **context): """ Executes the actual method with args, kwargs provided. This step is broken out of the process_requests flow to allow for ease of overriding the call in your subclass of this class. In some cases it'...
python
{ "resource": "" }
q54586
JSONPRCApplication.process_requests
train
def process_requests(self, requests, **context): """ Turns a list of request objects into a list of response objects. :param requests: A list of tuples describing the RPC call :type requests: list[list[callable,object,object,list]] :param context: A dict with...
python
{ "resource": "" }
q54587
JSONPRCApplication.handle_request_string
train
def handle_request_string(self, request_string, **context): """Handle a RPC-Request. :param request_string: the received rpc-string :param context: A dict with additional parameters passed to process_requests and process_method Allows wrapping code to pass additional par...
python
{ "resource": "" }
q54588
AnonymousUsageTracker.track_statistic
train
def track_statistic(self, name, description='', max_rows=None): """ Create a Statistic object in the Tracker. """ if name in self._tables: raise TableConflictError(name) if max_rows is None: max_rows = AnonymousUsageTracker.MAX_ROWS_PER_TABLE self....
python
{ "resource": "" }
q54589
AnonymousUsageTracker.track_state
train
def track_state(self, name, initial_state, description='', max_rows=None, **state_kw): """ Create a State object in the Tracker. """ if name in self._tables: raise TableConflictError(name) if max_rows is None: max_rows = AnonymousUsageTracker.MAX_ROWS_PER_...
python
{ "resource": "" }
q54590
AnonymousUsageTracker.track_time
train
def track_time(self, name, description='', max_rows=None): """ Create a Timer object in the Tracker. """ if name in self._tables: raise TableConflictError(name) if max_rows is None: max_rows = AnonymousUsageTracker.MAX_ROWS_PER_TABLE self.register_...
python
{ "resource": "" }
q54591
AnonymousUsageTracker.track_sequence
train
def track_sequence(self, name, checkpoints, description='', max_rows=None): """ Create a Sequence object in the Tracker. """ if name in self._tables: raise TableConflictError(name) if max_rows is None: max_rows = AnonymousUsageTracker.MAX_ROWS_PER_TABLE ...
python
{ "resource": "" }
q54592
AnonymousUsageTracker.submit_statistics
train
def submit_statistics(self): """ Upload the database to the FTP server. Only submit new information contained in the partial database. Merge the partial database back into master after a successful upload. """ if not self._hq.get('api_key', False) or not self._enabled: ...
python
{ "resource": "" }
q54593
AnonymousUsageTracker.load_from_configuration
train
def load_from_configuration(cls, path, uuid, **kwargs): """ Load FTP server credentials from a configuration file. """ cfg = ConfigParser.ConfigParser() kw = {} with open(path, 'r') as _f: cfg.readfp(_f) if cfg.has_section('General'): ...
python
{ "resource": "" }
q54594
AnonymousUsageTracker.start_watcher
train
def start_watcher(self): """ Start the watcher thread that tries to upload usage statistics. """ if self._watcher and self._watcher.is_alive: self._watcher_enabled = True else: logger.debug('Starting watcher.') self._watcher = threading.Thread(...
python
{ "resource": "" }
q54595
AnonymousUsageTracker._requires_submission
train
def _requires_submission(self): """ Returns True if the time since the last submission is greater than the submission interval. If no submissions have ever been made, check if the database last modified time is greater than the submission interval. """ if self.dbcon_part ...
python
{ "resource": "" }
q54596
_catchall_enabled
train
def _catchall_enabled(app): """Check the bottle app for catchall.""" while hasattr(app, 'app'): if isinstance(app, bottle.Bottle): break app = app.app if hasattr(app, 'catchall'): return app.catchall else: return bottle.default_app().catchall
python
{ "resource": "" }
q54597
cmd_as_file
train
def cmd_as_file(cmd, *args, **kwargs): """Launch `cmd` and treat its stdout as a file object""" kwargs['stdout'] = subprocess.PIPE stdin = kwargs.pop('stdin', None) if isinstance(stdin, basestring): with tempfile.TemporaryFile() as stdin_file: stdin_file.write(stdin) stdi...
python
{ "resource": "" }
q54598
Database.tables
train
def tables(self): """Return the list of table names in the database""" tables = [] self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table'") for table_info in self.cursor.fetchall(): if table_info[0] != 'sqlite_sequence': tables.append(tab...
python
{ "resource": "" }
q54599
Table._get_table_info
train
def _get_table_info(self): """Inspect the base to get field names""" self.fields = [] self.field_info = {} self.cursor.execute('PRAGMA table_info (%s)' %self.name) for field_info in self.cursor.fetchall(): fname = field_info[1].encode('utf-8') self....
python
{ "resource": "" }