_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q44600
MySQLDriver._execute
train
def _execute(self, sql, params): """Execute statement with reconnecting by connection closed error codes. 2006 (CR_SERVER_GONE_ERROR): MySQL server has gone away 2013 (CR_SERVER_LOST): Lost connection to MySQL server during query 2055 (CR_SERVER_LOST_EXTENDED): Lost connection to MySQL ...
python
{ "resource": "" }
q44601
MountSmbSharesOld.requirements
train
def requirements(self): """ Verifica che tutti i pacchetti apt necessari al "funzionamento" della classe siano installati. Se cosi' non fosse li installa. """ cache = apt.cache.Cache() for pkg in self.pkgs_required: try: pkg = cache[pkg] ...
python
{ "resource": "" }
q44602
makeOrmValuesSubqueryCondition
train
def makeOrmValuesSubqueryCondition(ormSession, column, values: List[Union[int, str]]): """ Make Orm Values Subquery :param ormSession: The orm session instance :param column: The column from the Declarative table, eg TableItem.colName :param values: A list of string or int values """ if isPostG...
python
{ "resource": "" }
q44603
makeCoreValuesSubqueryCondition
train
def makeCoreValuesSubqueryCondition(engine, column, values: List[Union[int, str]]): """ Make Core Values Subquery :param engine: The database engine, used to determine the dialect :param column: The column, eg TableItem.__table__.c.colName :param values: A list of string or int values """ if i...
python
{ "resource": "" }
q44604
Connection._open_connection
train
def _open_connection(self): """ Open a new connection socket to the CPS.""" if self._scheme == 'unix': self._connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0) self._connection.connect(self._path) elif self._scheme == 'tcp': self._connection = s...
python
{ "resource": "" }
q44605
Connection._send_request
train
def _send_request(self, xml_request): """ Send the prepared XML request block to the CPS using the corect protocol. Args: xml_request -- A fully formed xml request string for the CPS. Returns: The raw xml response string. Raises: ...
python
{ "resource": "" }
q44606
Connection._send_http_request
train
def _send_http_request(self, xml_request): """ Send a request via HTTP protocol. Args: xml_request -- A fully formed xml request string for the CPS. Returns: The raw xml response string. """ headers = {"Host": self._host, "Content-Type": ...
python
{ "resource": "" }
q44607
Connection.similar_text
train
def similar_text(self, *args, **kwargs): """ Search for documents that are similar to directly supplied text or to the textual content of an existing document. Args: text -- Text to found something similar to. len -- Number of keywords to extract from the source. quo...
python
{ "resource": "" }
q44608
makedirs_safe
train
def makedirs_safe(fulldir): """Creates a directory if it does not exists. Takes into consideration concurrent access support. Works like the shell's 'mkdir -p'. """ try: if not os.path.exists(fulldir): os.makedirs(fulldir) except OSError as exc: # Python >2.5 import errno if exc.errno == errno.EE...
python
{ "resource": "" }
q44609
str_
train
def str_(name): """Return the string representation of the given 'name'. If it is a bytes object, it will be converted into str. If it is a str object, it will simply be resurned.""" if isinstance(name, bytes) and not isinstance(name, str): return name.decode('utf8') else: return name
python
{ "resource": "" }
q44610
qstat
train
def qstat(jobid, context='grid'): """Queries status of a given job. Keyword parameters: jobid The job identifier as returned by qsub() context The setshell context in which we should try a 'qsub'. Normally you don't need to change the default. This variable can also be set to a context dictio...
python
{ "resource": "" }
q44611
qdel
train
def qdel(jobid, context='grid'): """Halts a given job. Keyword parameters: jobid The job identifier as returned by qsub() context The setshell context in which we should try a 'qsub'. Normally you don't need to change the default. This variable can also be set to a context dictionary in which...
python
{ "resource": "" }
q44612
update_state
train
def update_state(world): """ Increment the world state, determining which cells live, die, or appear. Args: world (list[list]): A square matrix of cells Returns: None """ world_size = len(world) def wrap(index): """Wrap an index around the other end of the array""" ...
python
{ "resource": "" }
q44613
click_event
train
def click_event(event): """On click, bring the cell under the cursor to Life""" grid_x_coord = int(divmod(event.x, cell_size)[0]) grid_y_coord = int(divmod(event.y, cell_size)[0]) world[grid_x_coord][grid_y_coord].value = True color = world[x][y].color_alive.get_as_hex() canvas.itemconfig(canvas...
python
{ "resource": "" }
q44614
draw_canvas
train
def draw_canvas(): """Render the tkinter canvas based on the state of ``world``""" for x in range(len(world)): for y in range(len(world[x])): if world[x][y].value: color = world[x][y].color_alive.get_as_hex() else: color = world[x][y].color_dead.ge...
python
{ "resource": "" }
q44615
_make_context
train
def _make_context(context=None): """Create the namespace of items already pre-imported when using shell. Accepts a dict with the desired namespace as the key, and the object as the value. """ namespace = {'db': db, 'session': db.session} namespace.update(_iter_context()) if context is not ...
python
{ "resource": "" }
q44616
init
train
def init(**kwargs): """Initialize the specified names in the specified databases. The general process is as follows: - Ensure the database in question exists - Ensure all tables exist in the database. """ # TODO: Iterate through all engines in name set. database = kwargs.pop('database'...
python
{ "resource": "" }
q44617
clear
train
def clear(**kwargs): """Clear the specified names from the specified databases. This can be highly destructive as it destroys tables and when all names are removed from a database, the database itself. """ database = kwargs.pop('database', False) expression = lambda target, table: table.drop(t...
python
{ "resource": "" }
q44618
flush
train
def flush(**kwargs): """Flush the specified names from the specified databases. This can be highly destructive as it destroys all data. """ expression = lambda target, table: target.execute(table.delete()) test = lambda target, table: not table.exists(target) op(expression, reversed(metadata.s...
python
{ "resource": "" }
q44619
is_table_included
train
def is_table_included(table, names): """Determines if the table is included by reference in the names. A table can be named by its component or its model (using the short-name or a full python path). eg. 'package.models.SomeModel' or 'package:SomeModel' or 'package' would all include 'SomeMode...
python
{ "resource": "" }
q44620
CavageSignature.secret_loader
train
def secret_loader(self, callback): """ Decorate a method that receives a key id and returns a secret key """ if not callback or not callable(callback): raise Exception("Please pass in a callable that loads secret keys") self.secret_loader_callback = callback r...
python
{ "resource": "" }
q44621
CavageSignature.context_loader
train
def context_loader(self, callback): """ Decorate a method that receives a key id and returns an object or dict that will be available in the request context as g.cavage_context """ if not callback or not callable(callback): raise Exception("Please pass in a callable t...
python
{ "resource": "" }
q44622
CavageSignature.replay_checker
train
def replay_checker(self, callback): """ Decorate a method that receives the request headers and returns a bool indicating whether we should proceed with the request. This can be used to protect against replay attacks. For example, this method could check the request date header v...
python
{ "resource": "" }
q44623
makeicons
train
def makeicons(source): """ Create all the neccessary icons from source image """ im = Image.open(source) for name, (_, w, h, func) in icon_sizes.iteritems(): print('Making icon %s...' % name) tn = func(im, (w, h)) bg = Image.new('RGBA', (w, h), (255, 255, 255)) x = (w...
python
{ "resource": "" }
q44624
dump_element
train
def dump_element(element): """ Dumps the content of the given ElementBase object to a string :param element: An ElementBase object :return: A full description of its content :raise TypeError: Invalid object """ # Check type try: assert isinstance(element, sleekxmpp.ElementBase) ...
python
{ "resource": "" }
q44625
RoomCreator.create_room
train
def create_room(self, room, service, nick, config=None, callback=None, errback=None, room_jid=None): """ Prepares the creation of a room. The callback is a method with two arguments: - room: Bare JID of the room - nick: Nick used to create the room ...
python
{ "resource": "" }
q44626
RoomCreator.__on_presence
train
def __on_presence(self, data): """ Got a presence stanza """ room_jid = data['from'].bare muc_presence = data['muc'] room = muc_presence['room'] nick = muc_presence['nick'] with self.__lock: try: # Get room state machine ...
python
{ "resource": "" }
q44627
MarksCallback.__call
train
def __call(self): """ Calls the callback method """ try: if self.__callback is not None: self.__callback(self.__successes, self.__errors) except Exception as ex: self.__logger.exception("Error calling back count down " ...
python
{ "resource": "" }
q44628
MarksCallback.__mark
train
def __mark(self, element, mark_set): """ Marks an element :param element: The element to mark :param mark_set: The set corresponding to the mark :return: True if the element was known """ try: # The given element can be of a different type than the or...
python
{ "resource": "" }
q44629
AwsEni.do_refresh
train
def do_refresh(self,args): """Refresh the view of the eni""" pprint(AwsConnectionFactory.getEc2Client().describe_network_interfaces(NetworkInterfaceIds=[self.physicalId]));
python
{ "resource": "" }
q44630
do_super
train
def do_super(parser, token): ''' Access the parent templates block. {% super name %} ''' name = token.strip() return ast.YieldFrom( value=_a.Call(_a.Attribute(_a.Call(_a.Name('super')), name), [ # _a.Attribute(_a.Name('context'), 'parent'), _a.Name('context'), ...
python
{ "resource": "" }
q44631
macro
train
def macro(parser, token): ''' Works just like block, but does not render. ''' name = token.strip() parser.build_method(name, endnodes=['endmacro']) return ast.Yield(value=ast.Str(s=''))
python
{ "resource": "" }
q44632
AbstractRouter.get_link
train
def get_link(self, peer): """ Retrieves a link to the peer :param peer: A Peer description :return: A link to the peer, None if none available """ assert isinstance(peer, Peer) for protocol in self._protocols: try: # Try to get a link...
python
{ "resource": "" }
q44633
resolve_composed_functions
train
def resolve_composed_functions(data, recursive=True): """ Calls `ComposedFunction`s and returns its return value. By default, this function will recursively iterate dicts, lists, tuples, and sets and replace all `ComposedFunction`s with their return value. """ if isinstance(data, ComposedFuncti...
python
{ "resource": "" }
q44634
SectionStruct._sync_and_resolve
train
def _sync_and_resolve(self, config, resolver): '''Synchronize all items represented by the config according to the resolver and return a set of keys that have been resolved.''' resolved = set() for key, theirs in config.items(self._name): theirs = self._real_value_of(theirs) ...
python
{ "resource": "" }
q44635
Work.upload
train
def upload(self, baseurl, filename): """Upload filename to this work""" # Prof is really dirty, we need to re-get the project page before upload payload = { 'id_projet': self.field } prof_session.post(baseurl+"/main.php", params=payload) # We also need to get ...
python
{ "resource": "" }
q44636
get_all_classes
train
def get_all_classes(module_name): """Load all non-abstract classes from package""" module = importlib.import_module(module_name) return getmembers(module, lambda m: isclass(m) and not isabstract(m))
python
{ "resource": "" }
q44637
Tabs.get
train
def get(self, table_name): """Load table class by name, class not yet initialized""" assert table_name in self.tabs, \ "Table not avaiable. Avaiable tables: {}".format( ", ".join(self.tabs.keys()) ) return self.tabs[table_name]
python
{ "resource": "" }
q44638
Tabs._update_sys_path
train
def _update_sys_path(self, package_path=None): """Updates and adds current directory to sys path""" self.package_path = package_path if not self.package_path in sys.path: sys.path.append(self.package_path)
python
{ "resource": "" }
q44639
Tabs.find_tabs
train
def find_tabs(self, custom_table_classes=None): """Finds all classes that are subcalss of Table and loads them into a dictionary named tables.""" for module_name in get_all_modules(self.package_path): for name, _type in get_all_classes(module_name): # pylint: disable...
python
{ "resource": "" }
q44640
SQLiteDB._connect
train
def _connect(self): """Try to create a connection to the database if not yet connected. """ if self._connection is not None: raise RuntimeError('Close connection first.') self._connection = connect(self._database, **self._kwds) self._connection.isolation_level = None
python
{ "resource": "" }
q44641
DiffCommand.diff
train
def diff(self, report_a, report_b): """ Generate a diff for two data reports. """ arguments = GLOBAL_ARGUMENTS + ['run_date'] output = OrderedDict([ ('a', OrderedDict([(arg, report_a[arg]) for arg in arguments])), ('b', OrderedDict([(arg, report_b[arg]) f...
python
{ "resource": "" }
q44642
Origin.copy_data
train
def copy_data(self): """ Copy the data from the it's point of origin, serializing it, storing it serialized as well as in it's raw form and calculate a running hash of the serialized representation """ HASH_FUNCTION = hashlib.sha256() try: raw_iterato...
python
{ "resource": "" }
q44643
OriginURL.get_binary_iterator
train
def get_binary_iterator(self): """ Generator to stream the remote file piece by piece. """ CHUNK_SIZE = 1024 return (item for item in requests.get(self.url).iter_content(CHUNK_SIZE))
python
{ "resource": "" }
q44644
TaggedRelationWidget.get_add_link
train
def get_add_link(self): """ Appends the popup=1 query string to the url so the destination url treats it as a popup. """ url = super(TaggedRelationWidget, self).get_add_link() if url: qs = self.get_add_qs() if qs: url = "%s&%s" % (...
python
{ "resource": "" }
q44645
render_view
train
def render_view(parser, token): """ Return an string version of a View with as_string method. First argument is the name of the view. Any other arguments should be keyword arguments and will be passed to the view. Example: {% render_view viewname var1=xx var2=yy %} """ bits = token.spl...
python
{ "resource": "" }
q44646
bundle_view
train
def bundle_view(parser, token): """ Returns an string version of a bundle view. This is done by calling the `get_string_from_view` method of the provided bundle. This tag expects that the request object as well as the the original url_params are available in the context. Requires two arguments...
python
{ "resource": "" }
q44647
bundle_url
train
def bundle_url(parser, token): """ Returns an a url for given a bundle and a view name. This is done by calling the `get_view_url` method of the provided bundle. This tag expects that the request object as well as the the original url_params are available in the context. Requires two argum...
python
{ "resource": "" }
q44648
user_url
train
def user_url(user, bundle): """ Filter for a user object. Checks if a user has permission to change other users. """ if not user: return False bundle = bundle.admin_site.get_bundle_for_model(User) edit = None if bundle: edit = bundle.get_view_url('main', user) retur...
python
{ "resource": "" }
q44649
Guild.from_content
train
def from_content(cls, content): """Creates an instance of the class from the HTML content of the guild's page. Parameters ----------- content: :class:`str` The HTML content of the page. Returns ---------- :class:`Guild` The guild containe...
python
{ "resource": "" }
q44650
Guild.from_tibiadata
train
def from_tibiadata(cls, content): """Builds a guild object from a TibiaData character response. Parameters ---------- content: :class:`str` The json string from the TibiaData response. Returns ------- :class:`Guild` The guild contained in...
python
{ "resource": "" }
q44651
Guild._parse_current_member
train
def _parse_current_member(self, previous_rank, values): """ Parses the column texts of a member row into a member dictionary. Parameters ---------- previous_rank: :class:`dict`[int, str] The last rank present in the rows. values: tuple[:class:`str`] ...
python
{ "resource": "" }
q44652
Guild._parse_application_info
train
def _parse_application_info(self, info_container): """ Parses the guild's application info. Parameters ---------- info_container: :class:`bs4.Tag` The parsed content of the information container. """ m = applications_regex.search(info_container.text) ...
python
{ "resource": "" }
q44653
Guild._parse_guild_disband_info
train
def _parse_guild_disband_info(self, info_container): """ Parses the guild's disband info, if available. Parameters ---------- info_container: :class:`bs4.Tag` The parsed content of the information container. """ m = disband_regex.search(info_container...
python
{ "resource": "" }
q44654
Guild._parse_guild_guildhall
train
def _parse_guild_guildhall(self, info_container): """ Parses the guild's guildhall info. Parameters ---------- info_container: :class:`bs4.Tag` The parsed content of the information container. """ m = guildhall_regex.search(info_container.text) ...
python
{ "resource": "" }
q44655
Guild._parse_guild_homepage
train
def _parse_guild_homepage(self, info_container): """ Parses the guild's homepage info. Parameters ---------- info_container: :class:`bs4.Tag` The parsed content of the information container. """ m = homepage_regex.search(info_container.text) i...
python
{ "resource": "" }
q44656
Guild._parse_guild_info
train
def _parse_guild_info(self, info_container): """ Parses the guild's general information and applies the found values. Parameters ---------- info_container: :class:`bs4.Tag` The parsed content of the information container. """ m = founded_regex.search(...
python
{ "resource": "" }
q44657
Guild._parse_logo
train
def _parse_logo(self, parsed_content): """ Parses the guild logo and saves it to the instance. Parameters ---------- parsed_content: :class:`bs4.Tag` The parsed content of the page. Returns ------- :class:`bool` Whether the logo w...
python
{ "resource": "" }
q44658
Guild._parse_guild_members
train
def _parse_guild_members(self, parsed_content): """ Parses the guild's member and invited list. Parameters ---------- parsed_content: :class:`bs4.Tag` The parsed content of the guild's page """ member_rows = parsed_content.find_all("tr", {'bgcolor': [...
python
{ "resource": "" }
q44659
Guild._parse_invited_member
train
def _parse_invited_member(self, values): """ Parses the column texts of an invited row into a invited dictionary. Parameters ---------- values: tuple[:class:`str`] A list of row contents. """ name, date = values if date != "Invitation Date": ...
python
{ "resource": "" }
q44660
BaseIRGenerator.merge_text_nodes_on
train
def merge_text_nodes_on(self, node): """Merges all consecutive non-translatable text nodes into one""" if not isinstance(node, ContainerNode) or not node.children: return new_children = [] text_run = [] for i in node.children: if isinstance(i, Text) and ...
python
{ "resource": "" }
q44661
BaseIRGenerator.push_state
train
def push_state(self): """ Push a copy of the topmost state on top of the state stack, returns the new top. """ new = dict(self.states[-1]) self.states.append(new) return self.state
python
{ "resource": "" }
q44662
BaseDOMIRGenerator.enter_node
train
def enter_node(self, ir_node): """ Enter the given element; keeps track of `cdata`; subclasses may extend by overriding """ this_is_cdata = (isinstance(ir_node, Element) and ir_node.name in self.cdata_elements) self.state['is_cdata'] = bool(self.s...
python
{ "resource": "" }
q44663
watch
train
def watch(static_root, watch_paths=None, on_reload=None, host='localhost', port=5555, server_base_path="/", watcher_interval=1.0, recursive=True, open_browser=True, open_browser_delay=1.0): """Initialises an HttpWatcherServer to watch the given path for changes. Watches until the IO loop is terminated...
python
{ "resource": "" }
q44664
Query.query
train
def query(self): """Parse query string using given grammar. :returns: AST that represents the query in the given grammar. """ tree = pypeg2.parse(self._query, parser(), whitespace="") for walker in query_walkers(): tree = tree.accept(walker) return tree
python
{ "resource": "" }
q44665
ConfigUtil.normalise_key
train
def normalise_key(self, key): """Make sure key is a valid python attribute""" key = key.replace('-', '_') if key.startswith("noy_"): key = key[4:] return key
python
{ "resource": "" }
q44666
ConfigUtil.find_value
train
def find_value(self, key): """Find a value and return it""" values = self.values if key not in values: raise AttributeError("Config has no value for {}".format(key)) val = values[key] if isinstance(val, Default): return val.val else: r...
python
{ "resource": "" }
q44667
ConfigUtil.use_options
train
def use_options(self, options, extractor=None): """ If extractor isn't specified, then just update self.values with options. Otherwise update values with whatever the result of calling extractor with our template and these options returns Also make sure all keys...
python
{ "resource": "" }
q44668
ConfigUtil.find_config_file
train
def find_config_file(self): """ Find where our config file is if there is any If the value for the config file is a default and it doesn't exist then it is silently ignored. If however, the value isn't a default and it doesn't exist, an error is raised "...
python
{ "resource": "" }
q44669
ConfigUtil.apply_config_file
train
def apply_config_file(self, filename): """ Add options from config file to self.values Leave alone existing values that are not an instance of Default """ def extractor(template, options): """Ignore things that are existing non default values""" fo...
python
{ "resource": "" }
q44670
ConfigUtil.use_config_file
train
def use_config_file(self): """Find and apply the config file""" self.config_file = self.find_config_file() if self.config_file: self.apply_config_file(self.config_file)
python
{ "resource": "" }
q44671
Config.setup
train
def setup(self, options=None, extractor=None): """ Put options onto the config and put anything from a config file onto the config. If extractor is specified, it is used to extract values from the options dictionary """ # Get our programmatic options self._util.u...
python
{ "resource": "" }
q44672
recursive_asdict
train
def recursive_asdict(d): """Convert Suds object into serializable format.""" out = {} for k, v in asdict(d).iteritems(): if hasattr(v, '__keylist__'): out[k] = recursive_asdict(v) elif isinstance(v, list): out[k] = [] for item in v: if hasa...
python
{ "resource": "" }
q44673
index
train
def index(): """Query Elasticsearch using "collection" param in query string.""" collection_names = request.values.getlist('collection') # Validation of collection names. collections = Collection.query if collection_names: collections = collections.filter( Collection.name.in_(co...
python
{ "resource": "" }
q44674
World._parse_battleye_status
train
def _parse_battleye_status(self, battleye_string): """Parses the BattlEye string and applies the results. Parameters ---------- battleye_string: :class:`str` String containing the world's Battleye Status. """ m = battleye_regexp.search(battleye_string) ...
python
{ "resource": "" }
q44675
World._parse_tables
train
def _parse_tables(cls, parsed_content): """ Parses the information tables found in a world's information page. Parameters ---------- parsed_content: :class:`bs4.BeautifulSoup` A :class:`BeautifulSoup` object containing all the content. Returns ------...
python
{ "resource": "" }
q44676
AssetBase.reset_crops
train
def reset_crops(self): """ Reset all known crops to the default crop. If settings.ASSET_CELERY is specified then the task will be run async """ if self._can_crop(): if settings.CELERY or settings.USE_CELERY_DECORATOR: # this means that we are...
python
{ "resource": "" }
q44677
AssetBase.ensure_crops
train
def ensure_crops(self, *required_crops): """ Make sure a crop exists for each crop in required_crops. Existing crops will not be changed. If settings.ASSET_CELERY is specified then the task will be run async """ if self._can_crop(): if settings.CELERY...
python
{ "resource": "" }
q44678
AssetBase.create_crop
train
def create_crop(self, name, x, x2, y, y2): """ Create a crop for this asset. """ if self._can_crop(): spec = get_image_cropper().create_crop(name, self.file, x=x, x2=x2, y=y, y2=y2) ImageDetail.save_crop_spec(self...
python
{ "resource": "" }
q44679
AssetBase.save
train
def save(self, *args, **kwargs): """ For new assets, creates a new slug. For updates, deletes the old file from storage. Calls super to actually save the object. """ if not self.pk and not self.slug: self.slug = self.generate_slug() if self.__origina...
python
{ "resource": "" }
q44680
AssetBase.delete
train
def delete(self, *args, **kwargs): """ Deletes the actual file from storage after the object is deleted. Calls super to actually delete the object. """ file_obj = self.file super(AssetBase, self).delete(*args, **kwargs) self.delete_real_file(file_obj)
python
{ "resource": "" }
q44681
_get_not_annotated
train
def _get_not_annotated(func, annotations=None): """Return non-optional parameters that are not annotated.""" argspec = inspect.getfullargspec(func) args = argspec.args if argspec.defaults is not None: args = args[:-len(argspec.defaults)] if inspect.isclass(func) or inspect.ismethod(func): ...
python
{ "resource": "" }
q44682
_parse_args
train
def _parse_args(func, variables, annotations=None): """Return a list of arguments with the variable it reads. NOTE: Multiple arguments may read the same variable. """ arg_read_var = [] for arg_name, anno in (annotations or func.__annotations__).items(): if arg_name == 'return': ...
python
{ "resource": "" }
q44683
_parse_arg
train
def _parse_arg(func, variables, arg_name, anno): """Parse an argument's annotation.""" if isinstance(anno, str): var = variables[anno] return var, var.read_latest elif (isinstance(anno, list) and len(anno) == 1 and isinstance(anno[0], str)): var = variables[anno[0]] ...
python
{ "resource": "" }
q44684
_parse_ret
train
def _parse_ret(func, variables, annotations=None): """Parse func's return annotation and return either None, a variable, or a tuple of variables. NOTE: * _parse_ret() also notifies variables about will-writes. * A variable can be written multiple times per return annotation. """ anno = ...
python
{ "resource": "" }
q44685
_write_values
train
def _write_values(kwargs, variables): """Write values of kwargs and return thus-satisfied closures.""" writeto = [] for var_name, value in kwargs.items(): var = variables[var_name] var.notify_will_write() var.write(value) writeto.append(var) return _notify_reader_writes(w...
python
{ "resource": "" }
q44686
_notify_reader_writes
train
def _notify_reader_writes(writeto): """Notify reader closures about these writes and return a sorted list of thus-satisfied closures. """ satisfied = [] for var in writeto: if var.readable: for reader in var.readers: reader.notify_read_ready() i...
python
{ "resource": "" }
q44687
Startup._release
train
def _release(self): """Destroy self since closures cannot be called again.""" del self.funcs del self.variables del self.variable_values del self.satisfied
python
{ "resource": "" }
q44688
Startup.call
train
def call(self, **kwargs): """Call all the functions that have previously been added to the dependency graph in topological and lexicographical order, and then return variables in a ``dict``. You may provide variable values with keyword arguments. These values will be written an...
python
{ "resource": "" }
q44689
extract_tonnikala
train
def extract_tonnikala(fileobj, keywords, comment_tags, options): """Extract messages from Tonnikala files. :param fileobj: the file-like object the messages should be extracted from :param keywords: a list of keywords (i.e. function names) that should be recognized ...
python
{ "resource": "" }
q44690
KanaConv._clear_char
train
def _clear_char(self): ''' Clears the current character and makes the machine ready to accept the next character. ''' self.lvmarker_count = 0 self.geminate_count = 0 self.next_char_info = None self.next_char_type = None self.active_vowel = None ...
python
{ "resource": "" }
q44691
KanaConv._append_unknown_char
train
def _append_unknown_char(self): ''' Appends the unknown character, in case one was encountered. ''' if self.unknown_strategy == UNKNOWN_INCLUDE and \ self.unknown_char is not None: self._append_to_stack(self.unknown_char) self.unknown_char = None
python
{ "resource": "" }
q44692
KanaConv._promote_solitary_xvowel
train
def _promote_solitary_xvowel(self): ''' "Promotes" the current xvowel to a regular vowel, in case it is not otherwise connected to a character. Used to print small vowels that would otherwise get lost; normally small vowels always form a pair, but in case one is by itself...
python
{ "resource": "" }
q44693
KanaConv._add_unknown_char
train
def _add_unknown_char(self, string): ''' Adds an unknown character to the stack. ''' if self.has_xvowel: # Ensure an xvowel gets printed if we've got an active # one right now. self._promote_solitary_xvowel() self.unknown_char = string ...
python
{ "resource": "" }
q44694
KanaConv._set_digraph_b
train
def _set_digraph_b(self, char): ''' Sets the second part of a digraph. ''' self.has_digraph_b = True # Change the active vowel to the one provided by the second part # of the digraph. self.active_vowel_ro = di_b_lt[char][0] self.active_dgr_b_info = di_b_lt...
python
{ "resource": "" }
q44695
KanaConv._postprocess_output
train
def _postprocess_output(self, output): ''' Performs the last modifications before the output is returned. ''' # Replace long vowels with circumflex characters. if self.vowel_style == CIRCUMFLEX_STYLE: try: output = output.translate(vowels_to_circumflex...
python
{ "resource": "" }
q44696
KanaConv._flush_stack
train
def _flush_stack(self): ''' Returns the final output and resets the machine's state. ''' output = self._postprocess_output(''.join(self.stack)) self._clear_char() self._empty_stack() if not PYTHON_2: return output else: return unic...
python
{ "resource": "" }
q44697
KanaConv._preprocess_input
train
def _preprocess_input(self, input): ''' Preprocesses the input before it's split into a list. ''' if not re.search(preprocess_chars, input): # No characters that we need to preprocess, so continue without. return input input = self._add_punctuation_spacin...
python
{ "resource": "" }
q44698
KanaConv._add_punctuation_spacing
train
def _add_punctuation_spacing(self, input): ''' Adds additional spacing to punctuation characters. For example, this puts an extra space after a fullwidth full stop. ''' for replacement in punct_spacing: input = re.sub(replacement[0], replacement[1], input) re...
python
{ "resource": "" }
q44699
BaseView.get_render_data
train
def get_render_data(self, **kwargs): """ Because of the way mixin inheritance works we can't have a default implementation of get_context_data on the this class, so this calls that method if available and returns the resulting context. """ if hasattr(self,...
python
{ "resource": "" }