_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q46400
Container._get_attrs
train
def _get_attrs(self, names): """ Convenience function to extract multiple attributes at once :param names: string of names separated by comma or space :return: """ assert isinstance(names, str) names = names.replace(",", " ").split(" ") res = [] ...
python
{ "resource": "" }
q46401
parsemsg
train
def parsemsg(s): # stolen from twisted.words """Breaks a message from an IRC server into its prefix, command, and arguments. """ prefix = '' trailing = [] if not s: raise Exception("Empty line.") if s[0] == ':': prefix, s = s[1:].split(' ', 1) if s.find(' :') != -1: ...
python
{ "resource": "" }
q46402
Connection.pull
train
def pull(self): """This coroutine handles the server connection, does a basic parse on the received messages and put them in a queue named events. The controllers pull method will take the messages from that queue. """ self.sock = sockets.Socket() self.sock.settimeo...
python
{ "resource": "" }
q46403
IrcController.connect
train
def connect(self, server): "Connects to a server and return a connection id." if 'connections' not in session: session['connections'] = {} session.save() conns = session['connections'] id = str(len(conns)) conn = Connection(server) conns[...
python
{ "resource": "" }
q46404
IrcController.pull
train
def pull(self, id): """Take the messages from the queue and if there are none wait 30 seconds till returning an empty message. Also, cogen's wsgi async extensions are in the environ and prefixed with 'cogen.' """ conn = session['connections'].get(id, None) ...
python
{ "resource": "" }
q46405
XMLDecoder.decode
train
def decode(cls, root_element): """ Decode the object to the object :param root_element: the parsed xml Element :type root_element: xml.etree.ElementTree.Element :return: the decoded Element as object :rtype: object """ new_object = cls() field_nam...
python
{ "resource": "" }
q46406
Scheduler.next_timer_delta
train
def next_timer_delta(self): "Returns a timevalue that the proactor will wait on." if self.timeouts and not self.active: now = getnow() timo = self.timeouts[0].timeout if now >= timo: #looks like we've exceded the time return 0 ...
python
{ "resource": "" }
q46407
CreateNoteCallMixin.add_note
train
def add_note(self, body): """ Create a Note to current object :param body: the body of the note :type body: str :return: newly created Note :rtype: Tag """ from highton.models.note import Note created_id = self._post_request( endpoint=...
python
{ "resource": "" }
q46408
ListEmailCallMixin.list_emails
train
def list_emails(self, page=0, since=None): """ Get the emails of current object :param page: the page starting at 0 :type since: int :param since: get all notes since a datetime :type since: datetime.datetime :return: the emails :rtype: list """ ...
python
{ "resource": "" }
q46409
Tween.tween
train
def tween(self, t): """ t is number between 0 and 1 to indicate how far the tween has progressed """ if t is None: return None if self.method in self.method_to_tween: return self.method_to_tween[self.method](t) elif self.method in self.method_1par...
python
{ "resource": "" }
q46410
Tween.tween2
train
def tween2(self, val, frm, to): """ linearly maps val between frm and to to a number between 0 and 1 """ return self.tween(Mapping.linlin(val, frm, to, 0, 1))
python
{ "resource": "" }
q46411
Encoder._encode_list
train
def _encode_list(self, obj):# do """Returns a JSON representation of a Python list""" self._increment_nested_level() buffer = [] for element in obj: buffer.append(self._encode(element)) self._decrement_nested_level() return '['+ ','.join(buffer) + ']'
python
{ "resource": "" }
q46412
Encoder._encode_dict
train
def _encode_dict(self, obj): """Returns a JSON representation of a Python dict""" self._increment_nested_level() buffer = [] for key in obj: buffer.append(self._encode_key(key) + ':' + self._encode(obj[key])) self._decrement_nested_level() return '{'+ ','....
python
{ "resource": "" }
q46413
Encoder._encode_key
train
def _encode_key(self, obj): """Encodes a dictionary key - a key can only be a string in std JSON""" if obj.__class__ is str: return self._encode_str(obj) if obj.__class__ is UUID: return '"' + str(obj) + '"' # __mm_serialize__ is called before any isinstance ch...
python
{ "resource": "" }
q46414
Encoder._encode
train
def _encode(self, obj): """Returns a JSON representation of a Python object - see dumps. Accepts objects of any type, calls the appropriate type-specific encoder. """ if self._use_hook: obj = self.encode_hook(obj) # first try simple strict checks _objtype =...
python
{ "resource": "" }
q46415
Encoder.dumps
train
def dumps(self, obj, *, max_nested_level=100): """Returns a string representing a JSON-encoding of ``obj``. The second optional ``max_nested_level`` argument controls the maximum allowed recursion/nesting level. See class description for details. """ self._max_...
python
{ "resource": "" }
q46416
download_file
train
def download_file(url, filename=None, show_progress=draw_pbar): ''' Download a file and show progress url: the URL of the file to download filename: the filename to download it to (if not given, uses the url's filename part) show_progress: callback function to update a progress bar the show_pr...
python
{ "resource": "" }
q46417
main
train
def main(): ''' entry point of the application. Parses the CLI commands and runs the actions. ''' args = CLI.parse_args(__doc__) if args['--verbose']: requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(logging.DEBUG) logging.basicConfig(...
python
{ "resource": "" }
q46418
autoescape
train
def autoescape(context, nodelist, setting): """ Force autoescape behaviour for this block. """ old_setting = context.autoescape context.autoescape = setting output = nodelist.render(context) context.autoescape = old_setting if setting: return mark_safe(output) else: r...
python
{ "resource": "" }
q46419
debug
train
def debug(context): """ Outputs a whole load of debugging information, including the current context and imported modules. Sample usage:: <pre> {% debug %} </pre> """ from pprint import pformat output = [pformat(val) for val in context] output.append('\n\n'...
python
{ "resource": "" }
q46420
filter
train
def filter(context, nodelist, filter_exp): """ Filters the contents of the block through variable filters. Filters can also be piped through each other, and they can have arguments -- just like in variable syntax. Sample usage:: {% filter force_escape|lower %} This text will b...
python
{ "resource": "" }
q46421
regroup
train
def regroup(target, expression): """ Regroups a list of alike objects by a common attribute. This complex tag is best illustrated by use of an example: say that ``people`` is a list of ``Person`` objects that have ``first_name``, ``last_name``, and ``gender`` attributes, and you'd like to display ...
python
{ "resource": "" }
q46422
now
train
def now(format_string): """ Displays the date, formatted according to the given string. Uses the same format as PHP's ``date()`` function; see http://php.net/date for all the possible values. Sample usage:: It is {% now "jS F Y H:i" %} """ from datetime import datetime from dj...
python
{ "resource": "" }
q46423
spaceless
train
def spaceless(context, nodelists): """ Removes whitespace between HTML tags, including tab and newline characters. Example usage:: {% spaceless %} <p> <a href="foo/">Foo</a> </p> {% endspaceless %} This example would return this HTML:: ...
python
{ "resource": "" }
q46424
widthratio
train
def widthratio(value, maxvalue, max_width): """ For creating bar charts and such, this tag calculates the ratio of a given value to a maximum value, and then applies that ratio to a constant. For example:: <img src='bar.gif' height='10' width='{% widthratio this_value max_value 100 %}' /> ...
python
{ "resource": "" }
q46425
Type2JoinHelper._additional_rows_date2int
train
def _additional_rows_date2int(self, keys, rows): """ Replaces start and end dates of the additional date intervals in the row set with their integer representation :param list[tuple[str,str]] keys: The other keys with start and end date. :param list[dict[str,T]] rows: The list of rows. ...
python
{ "resource": "" }
q46426
Type2JoinHelper._intersection
train
def _intersection(self, keys, rows): """ Computes the intersection of the date intervals of two or more reference data sets. If the intersection is empty the row is removed from the group. :param list[tuple[str,str]] keys: The other keys with start and end date. :param list[dict...
python
{ "resource": "" }
q46427
Type2JoinHelper.merge
train
def merge(self, keys): """ Merges the join on pseudo keys of two or more reference data sets. :param list[tuple[str,str]] keys: For each data set the keys of the start and end date. """ deletes = [] for pseudo_key, rows in self._rows.items(): self._additional...
python
{ "resource": "" }
q46428
PollProactor.run
train
def run(self, timeout = 0): """ Run a proactor loop and return new socket events. Timeout is a timedelta object, 0 if active coros or None. """ # poll timeout param is a integer number of miliseconds (seconds/1000). ptimeout = int( timeout.days * 864000...
python
{ "resource": "" }
q46429
ObjectField.to_serializable_value
train
def to_serializable_value(self): """ Run through all fields of the object and parse the values :return: :rtype: dict """ return { name: field.to_serializable_value() for name, field in self.value.__dict__.items() if isinstance(field, F...
python
{ "resource": "" }
q46430
ListField.encode
train
def encode(self): """ Just iterate over the child elements and append them to the current element :return: the encoded element :rtype: xml.etree.ElementTree.Element """ element = ElementTree.Element( self.name, attrib={'type': FieldConstants.ARRAY...
python
{ "resource": "" }
q46431
export_context
train
def export_context(target_zip): """ Append context.json to target_zip """ from django_productline import utils context_file = tasks.get_context_path() return utils.create_or_append_to_zip(context_file, target_zip, 'context.json')
python
{ "resource": "" }
q46432
get_context_template
train
def get_context_template(): """ Features which require configuration parameters in the product context need to refine this method and update the context with their own data. """ import random return { 'SITE_ID': 1, 'SECRET_KEY': ''.join( [random.SystemRandom().choice(...
python
{ "resource": "" }
q46433
generate_context
train
def generate_context(force_overwrite=False, drop_secret_key=False): """ Generates context.json """ print('... generating context') context_fp = '%s/context.json' % os.environ['PRODUCT_DIR'] context = {} if os.path.isfile(context_fp): print('... augment existing context.json') ...
python
{ "resource": "" }
q46434
_delim_accum
train
def _delim_accum(control_files, filename_template, keys=None, exclude_keys=None, separator=DEFAULT_SEP, missing_action='fail'): """ Accumulator for delimited files Combines each file with values from JSON dictionary in same directory :param iterable control_files: Iterable of control files ...
python
{ "resource": "" }
q46435
delim
train
def delim(arguments): """ Execute delim action. :param arguments: Parsed command line arguments from :func:`main` """ if bool(arguments.control_files) == bool(arguments.directory): raise ValueError( 'Exactly one of control_files and `-d` must be specified.') if argumen...
python
{ "resource": "" }
q46436
DeleteCallMixin.delete
train
def delete(self): """ Deletes the object :return: :rtype: None """ return self._delete_request(endpoint=self.ENDPOINT + '/' + str(self.id))
python
{ "resource": "" }
q46437
Socket.recv
train
def recv(self, bufsize, **kws): """Receive data from the socket. The return value is a string representing the data received. The amount of data may be less than the ammount specified by _bufsize_. """ return Recv(self, bufsize, timeout=self._timeout, **kws)
python
{ "resource": "" }
q46438
Socket.sendall
train
def sendall(self, data, **kws): """Send data to the socket. The socket must be connected to a remote socket. All the data is guaranteed to be sent.""" return SendAll(self, data, timeout=self._timeout, **kws)
python
{ "resource": "" }
q46439
SchemaUpdater.creating_schema_and_index
train
def creating_schema_and_index(self, models, func): """ Executes given functions with given models. Args: models: models to execute func: function name to execute Returns: """ waiting_models = [] self.base_thread.do_with_submit(func, mode...
python
{ "resource": "" }
q46440
SchemaUpdater.create_schema
train
def create_schema(self, model, waiting_models): """ Creates search schemas. Args: model: model to execute waiting_models: if riak can't return response immediately, model is taken to queue. After first execution session, method is executed with waiting models...
python
{ "resource": "" }
q46441
SchemaUpdater.create_index
train
def create_index(self, model, waiting_models): """ Creates search indexes. Args: model: model to execute waiting_models: if riak can't return response immediately, model is taken to queue. After first execution session, method is executed with waiting models ...
python
{ "resource": "" }
q46442
SchemaUpdater.compile_schema
train
def compile_schema(fields): """ joins schema fields with base solr schema :param list[str] fields: field list :return: compiled schema :rtype: byte """ path = os.path.dirname(os.path.realpath(__file__)) # path = os.path.dirname( # os.path.absp...
python
{ "resource": "" }
q46443
func2
train
def func2(q1, q2): """ to demonstrate debugging on exception """ a = q1/q2 if q2 == 5: z = 100 IPS() # start embedded ipython shell in the local scope # -> explore global namespace return a
python
{ "resource": "" }
q46444
QuerySet.save_model
train
def save_model(self, model, meta_data=None, index_fields=None): """ saves the model instance to riak Args: meta (dict): JSON serializable meta data for logging of save operation. {'lorem': 'ipsum', 'dolar': 5} index_fields (list): Tuple list for secondary...
python
{ "resource": "" }
q46445
QuerySet._make_model
train
def _make_model(self, data, key=None): """ Creates a model instance with the given data. Args: data: Model data returned from DB. key: Object key Returns: pyoko.Model object. """ if data['deleted'] and not self.adapter.want_deleted: ...
python
{ "resource": "" }
q46446
QuerySet.exclude
train
def exclude(self, **filters): """ Applies query filters for excluding matching records from result set. Args: **filters: Query filters as keyword arguments. Returns: Self. Queryset object. Examples: >>> Person.objects.exclude(age=None) ...
python
{ "resource": "" }
q46447
QuerySet.get_or_create
train
def get_or_create(self, defaults=None, **kwargs): """ Looks up an object with the given kwargs, creating a new one if necessary. Args: defaults (dict): Used when we create a new object. Must map to fields of the model. \*\*kwargs: Used both for filtering ...
python
{ "resource": "" }
q46448
QuerySet.update
train
def update(self, **kwargs): """ Updates the matching objects for specified fields. Note: Post/pre save hooks and signals will NOT triggered. Unlike RDBMS systems, this method makes individual save calls to backend DB store. So this is exists as more of a com...
python
{ "resource": "" }
q46449
QuerySet.get
train
def get(self, key=None, **kwargs): """ Ensures that only one result is returned from DB and raises an exception otherwise. Can work in 3 different way. - If no argument is given, only does "ensuring about one and only object" job. - If key given as only argument, retriev...
python
{ "resource": "" }
q46450
QuerySet.delete
train
def delete(self): """ Deletes all objects that matches to the queryset. Note: Unlike RDBMS systems, this method makes individual save calls to backend DB store. So this is exists as more of a comfortable utility method and not a performance enhancement. ...
python
{ "resource": "" }
q46451
QuerySet.dump
train
def dump(self): """ Dump raw JSON output of matching queryset objects. Returns: List of dicts. """ results = [] for data in self.data(): results.append(data) return results
python
{ "resource": "" }
q46452
QuerySet.or_filter
train
def or_filter(self, **filters): """ Works like "filter" but joins given filters with OR operator. Args: **filters: Query filters as keyword arguments. Returns: Self. Queryset object. Example: >>> Person.objects.or_filter(age__gte=16, name__s...
python
{ "resource": "" }
q46453
QuerySet.OR
train
def OR(self): """ Switches default query joiner from " AND " to " OR " Returns: Self. Queryset object. """ clone = copy.deepcopy(self) clone.adapter._QUERY_GLUE = ' OR ' return clone
python
{ "resource": "" }
q46454
QuerySet.raw
train
def raw(self, query): """ make a raw query Args: query (str): solr query \*\*params: solr parameters """ clone = copy.deepcopy(self) clone.adapter._pre_compiled_query = query clone.adapter.compiled_query = query return clone
python
{ "resource": "" }
q46455
userForCert
train
def userForCert(store, cert): """Gets the user for the given certificate. """ return store.findUnique(User, User.email == emailForCert(cert))
python
{ "resource": "" }
q46456
UserMixin.user
train
def user(self): """The current user. This property is cached in the ``_user`` attribute. """ if self._user is not None: return self._user cert = self.transport.getPeerCertificate() self._user = user = userForCert(self.store, cert) return user
python
{ "resource": "" }
q46457
_TOFUContextFactory._verify
train
def _verify(self, connection, cert, errorNumber, errorDepth, returnCode): """Verify a certificate. """ try: user = userForCert(self.store, cert) except ItemNotFound: log.msg("Connection attempt by {0!r}, but no user with that " "e-mail address...
python
{ "resource": "" }
q46458
Linter.run
train
def run(path, code, params=None, ignore=None, select=None, **meta): """Pylint code checking. :return list: List of errors. """ logger.debug('Start pylint') clear_cache = params.pop('clear_cache', False) if clear_cache: MANAGER.astroid_cache.clear() ...
python
{ "resource": "" }
q46459
get_line_segments
train
def get_line_segments(line): """ Split up a line into lhs, rhs, comment, flags lhs ist defined as the leftmost assignment (line does not need to be an assignment) :param line: :return: lhs, rhs, comment """ line = line.strip() tokens = tk.generate_tokens(io.StringIO(line).r...
python
{ "resource": "" }
q46460
collectstatic
train
def collectstatic(force=False): """ collect static files for production httpd If run with ``settings.DEBUG==True``, this is a no-op unless ``force`` is set to ``True`` """ # noise reduction: only collectstatic if not in debug mode from django.conf import settings if force or not setting...
python
{ "resource": "" }
q46461
PluginLoader.load_manifests
train
def load_manifests(self): """ Loads all plugin manifests on the plugin path """ for path in self.plugin_paths: for item in os.listdir(path): item_path = os.path.join(path, item) if os.path.isdir(item_path): self.load_manifes...
python
{ "resource": "" }
q46462
PluginLoader.load_manifest
train
def load_manifest(self, path): """ Loads a plugin manifest from a given path :param path: The folder to load the plugin manifest from """ manifest_path = os.path.join(path, "plugin.json") self._logger.debug("Attempting to load plugin manifest from {}.".format(manifest_pa...
python
{ "resource": "" }
q46463
PluginLoader.load_plugin
train
def load_plugin(self, manifest, *args): """ Loads a plugin from the given manifest :param manifest: The manifest to use to load the plugin :param args: Arguments to pass to the plugin """ if self.get_plugin_loaded(manifest["name"]): self._logger.debug("Plugin...
python
{ "resource": "" }
q46464
PluginLoader.load_plugins
train
def load_plugins(self, *args): """ Loads all plugins :param args: Arguments to pass to the plugins """ for manifest in self._manifests: self.load_plugin(manifest, *args)
python
{ "resource": "" }
q46465
PluginLoader.get_all_plugins
train
def get_all_plugins(self): """ Gets all loaded plugins :return: List of all plugins """ return [{ "manifest": i, "plugin": self.get_plugin(i["name"]), "module": self.get_module(i["name"]) } for i in self._manifests]
python
{ "resource": "" }
q46466
PluginLoader.reload_all_manifests
train
def reload_all_manifests(self): """ Reloads all loaded manifests, and loads any new manifests """ self._logger.debug("Reloading all manifests.") self._manifests = [] self.load_manifests() self._logger.debug("All manifests reloaded.")
python
{ "resource": "" }
q46467
PluginLoader.reload_plugin
train
def reload_plugin(self, name, *args): """ Reloads a given plugin :param name: The name of the plugin :param args: The args to pass to the plugin """ self._logger.debug("Reloading {}.".format(name)) self._logger.debug("Disabling {}.".format(name)) self.ge...
python
{ "resource": "" }
q46468
PluginLoader.reload_all_plugins
train
def reload_all_plugins(self, *args): """ Reloads all initialized plugins """ for manifest in self._manifests[:]: if self.get_plugin(manifest["name"]) is not None: self.reload_plugin(manifest["name"], *args)
python
{ "resource": "" }
q46469
UniversalCsvReader.next
train
def next(self): """ Yields the next row from the source files. """ for self._filename in self._filenames: self._open() for row in self._csv_reader: self._row_number += 1 if self._fields: yield dict(zip_longest(se...
python
{ "resource": "" }
q46470
UniversalCsvReader._open_file
train
def _open_file(self, mode, encoding=None): """ Opens the next current file. :param str mode: The mode for opening the file. :param str encoding: The encoding of the file. """ if self._filename[-4:] == '.bz2': self._file = bz2.open(self._filename, mode=mode, e...
python
{ "resource": "" }
q46471
UniversalCsvReader._get_sample
train
def _get_sample(self, mode, encoding): """ Get a sample from the next current input file. :param str mode: The mode for opening the file. :param str|None encoding: The encoding of the file. None for open the file in binary mode. """ self._open_file(mode, encoding) ...
python
{ "resource": "" }
q46472
UniversalCsvReader._detect_delimiter
train
def _detect_delimiter(self): """ Detects the field delimiter in the sample data. """ candidate_value = ',' candidate_count = 0 for delimiter in UniversalCsvReader.delimiters: count = self._sample.count(delimiter) if count > candidate_count: ...
python
{ "resource": "" }
q46473
UniversalCsvReader._detect_line_ending
train
def _detect_line_ending(self): """ Detects the line ending in the sample data. """ candidate_value = '\n' candidate_count = 0 for line_ending in UniversalCsvReader.line_endings: count = self._sample.count(line_ending) if count > candidate_count: ...
python
{ "resource": "" }
q46474
UniversalCsvReader._open
train
def _open(self): """ Opens the next current file with proper settings for encoding and delimiter. """ self._sample = None formatting_parameters0 = {'encoding': 'auto', 'delimiter': 'auto', 'line_ter...
python
{ "resource": "" }
q46475
BasePaste.list_syntax
train
def list_syntax(self): ''' Prints a list of available syntax for the current paste service ''' syntax_list = ['Available syntax for %s:' %(self)] logging.info(syntax_list[0]) for key in self.SYNTAX_DICT.keys(): syntax = '\t%-20s%-30s' %(key, self.SYNTAX_DICT[k...
python
{ "resource": "" }
q46476
BasePaste.process_commmon
train
def process_commmon(self): ''' Some data processing common for all services. No need to override this. ''' data = self.data data_content = data['content'][0] ## Paste the output of a command # This is deprecated after piping support if data['comma...
python
{ "resource": "" }
q46477
BasePaste.get_response
train
def get_response(self): ''' Returns response according submitted the data and method. ''' self.process_commmon() self.process_data() urlencoded_data = urllib.urlencode(self.data) if self.METHOD == POST: req = urllib2.Request(self.URL, urlencoded_data) ...
python
{ "resource": "" }
q46478
BasePaste.url
train
def url(self): ''' Executes the methods to send request, process the response and then publishes the url. ''' self.get_response() url = self.process_response() if url: logging.info('Your paste has been published at %s' %(url)) return url ...
python
{ "resource": "" }
q46479
PastebinPaste.get_api_user_key
train
def get_api_user_key(self, api_dev_key, username=None, password=None): ''' Get api user key to enable posts from user accounts if username and password available. Not getting an api_user_key means that the posts will be "guest" posts ''' username = username or get_config(...
python
{ "resource": "" }
q46480
has_any
train
def has_any(): "Returns the best available proactor implementation for the current platform." return get_first(has_ctypes_iocp, has_iocp, has_stdlib_kqueue, has_kqueue, has_stdlib_epoll, has_epoll, has_poll, has_select)
python
{ "resource": "" }
q46481
Container.slice_naive
train
def slice_naive(self, key): """ Naively slice each data object in the container by the object's index. Args: key: Int, slice, or list by which to extra "sub"-container Returns: sub: Sub container of the same format with a view of the data Warning: ...
python
{ "resource": "" }
q46482
Container.cardinal_groupby
train
def cardinal_groupby(self): """ Create an instance of this class for every step in the cardinal dimension. """ if self._cardinal: g = self.network(fig=False) cardinal_indexes = self[self._cardinal].index.values selfs = {} cls = self.__class...
python
{ "resource": "" }
q46483
Container.memory_usage
train
def memory_usage(self, string=False): """ Get the memory usage estimate of the container. Args: string (bool): Human readable string (default false) See Also: :func:`~exa.core.container.Container.info` """ if string: n = getsizeof(sel...
python
{ "resource": "" }
q46484
Container.save
train
def save(self, path=None, complevel=1, complib='zlib'): """ Save the container as an HDF5 archive. Args: path (str): Path where to save the container """ if path is None: path = self.hexuid + '.hdf5' elif os.path.isdir(path): path += o...
python
{ "resource": "" }
q46485
Container.load
train
def load(cls, pkid_or_path=None): """ Load a container object from a persistent location or file path. Args: pkid_or_path: Integer pkid corresponding to the container table or file path Returns: container: The saved container object """ path = pk...
python
{ "resource": "" }
q46486
SConsWrap.add_target
train
def add_target(self, name=None): """ Add an SCons target to this nest. The function decorated will be immediately called with each of the output directories and current control dictionaries. Each result will be added to the respective control dictionary for later nests to ...
python
{ "resource": "" }
q46487
SConsWrap.add_target_with_env
train
def add_target_with_env(self, environment, name=None): """Add an SCons target to this nest, with an SCons Environment The function decorated will be immediately called with three arguments: * ``environment``: A clone of the SCons environment, with variables populated for all values i...
python
{ "resource": "" }
q46488
SConsWrap.add_aggregate
train
def add_aggregate(self, name, data_fac): """ Add an aggregate target to this nest. Since nests added after the aggregate can access the construct returned by the factory function value, it can be mutated to provide additional values for use when the decorated function is called...
python
{ "resource": "" }
q46489
SConsWrap.add_controls
train
def add_controls(self, env, target_name='control', file_name='control.json', encoder_cls=SConsEncoder): """ Adds a target to build a control file at each of the current leaves. :param env: SCons Environment object :param target_name: Name for ta...
python
{ "resource": "" }
q46490
MoneyCleaner.clean
train
def clean(amount): """ Converts a number to a number with decimal point. :param str amount: The input number. :rtype: str """ # Return empty input immediately. if not amount: return amount if re.search(r'[\. ][0-9]{3},[0-9]{1,2}$', amount): ...
python
{ "resource": "" }
q46491
Type2ReferenceDimension.get_id
train
def get_id(self, natural_key, date, enhancement=None): """ Returns the technical ID for a natural key at a date or None if the given natural key is not valid. :param T natural_key: The natural key. :param str date: The date in ISO 8601 (YYYY-MM-DD) format. :param T enhancement: ...
python
{ "resource": "" }
q46492
BaseFields.factory
train
def factory(coords, dependent_variables, helper_functions): """Fields factory generating specialized container build around a triflow Model and xarray. Parameters ---------- coords: iterable of str: coordinates name. First co...
python
{ "resource": "" }
q46493
BaseFields.factory1D
train
def factory1D(dependent_variables, helper_functions): """Fields factory generating specialized container build around a triflow Model and xarray. Wrapper for 1D data. Parameters ---------- dependent_variables : iterable for str n...
python
{ "resource": "" }
q46494
BaseBackend.complete
train
def complete(self, request, response): """ Complete net auth. """ extra = self.get_extra_data(response) data = {} for form_field, backend_field in self.PROFILE_MAPPING.items(): data[form_field] = self.extract_data(extra, backend_field) request.session['extra']...
python
{ "resource": "" }
q46495
BaseBackend.login_user
train
def login_user(self, request): """ Try to login user by net identity. Do nothing in case of failure. """ # only actavted users can login if activation required. user = auth.authenticate(identity=self.identity, provider=self.provider) if user and settings.ACTIVATIO...
python
{ "resource": "" }
q46496
BaseBackend.fill_extra_fields
train
def fill_extra_fields(self, request, data): """ Try to fetch extra data from provider, if this data is enough to validate settings.EXTRA_FORM then call save method of form class and login the user. The extra parameter can be some complex object this is why we use method ...
python
{ "resource": "" }
q46497
GlobCondition.match
train
def match(self, row): """ Returns True if the field matches the glob expression of this simple condition. Returns False otherwise. :param dict row: The row. :rtype: bool """ return fnmatch.fnmatchcase(row[self._field], self._expression)
python
{ "resource": "" }
q46498
template_string
train
def template_string(context, template): 'Return the rendered template content with the current context' if not isinstance(context, Context): context = Context(context) return Template(template).render(context)
python
{ "resource": "" }
q46499
raster_to_shape
train
def raster_to_shape(raster): """Take a raster and return a polygon representing the outer edge.""" left = raster.bounds.left right = raster.bounds.right top = raster.bounds.top bottom = raster.bounds.bottom top_left = (left, top) top_right = (right, top) bottom_left = (left, bottom) ...
python
{ "resource": "" }