_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q46700
User.me
train
def me(cls): """ Returns information about the currently authenticated user. :return: :rtype: User """ return fields.ObjectField(name=cls.ENDPOINT, init_class=cls).decode( cls.element_from_string( cls._get_request(endpoint=cls.ENDPOINT + '/me'...
python
{ "resource": "" }
q46701
ckm_standard
train
def ckm_standard(t12, t13, t23, delta): r"""CKM matrix in the standard parametrization and standard phase convention. Parameters ---------- - `t12`: CKM angle $\theta_{12}$ in radians - `t13`: CKM angle $\theta_{13}$ in radians - `t23`: CKM angle $\theta_{23}$ in radians - `delta`: CKM...
python
{ "resource": "" }
q46702
ckm_wolfenstein
train
def ckm_wolfenstein(laC, A, rhobar, etabar): r"""CKM matrix in the Wolfenstein parametrization and standard phase convention. This function does not rely on an expansion in the Cabibbo angle but defines, to all orders in $\lambda$, - $\lambda = \sin\theta_{12}$ - $A\lambda^2 = \sin\theta_{23}$...
python
{ "resource": "" }
q46703
ckm_tree
train
def ckm_tree(Vus, Vub, Vcb, gamma): r"""CKM matrix in the tree parametrization and standard phase convention. In this parametrization, the parameters are directly measured from tree-level $B$ decays. It is thus particularly suited for new physics analyses because the tree-level decays should be dom...
python
{ "resource": "" }
q46704
debug
train
def debug(trace=True, backtrace=1, other=None, output=sys.stderr): """A decorator for debugging purposes. Shows the call arguments, result and instructions as they are runned.""" from pprint import pprint import traceback def debugdeco(func): def tracer(frame, event, arg): ...
python
{ "resource": "" }
q46705
bind_context
train
def bind_context(context_filename): """ loads context from file and binds to it :param: context_filename absolute path of the context file called by featuredjango.startup.select_product prior to selecting the individual features """ global PRODUCT_CONTEXT if PRODUCT_CONTEXT is None: ...
python
{ "resource": "" }
q46706
Protocol.connectionMade
train
def connectionMade(self): """Keep a reference to the protocol on the factory, and uses the factory's store to find multiplexed connection factories. Unfortunately, we can't add the protocol by TLS certificate fingerprint, because the TLS handshake won't have completed yet, so ``...
python
{ "resource": "" }
q46707
Protocol.connectionLost
train
def connectionLost(self, reason): """Lose the reference to the protocol on the factory. """ self.factory.protocols.remove(self) super(AMP, self).connectionLost(reason)
python
{ "resource": "" }
q46708
SqlLoaderWriter._write_field
train
def _write_field(self, value): """ Write a single field to the destination file. :param T value: The value of the field. """ class_name = str(value.__class__) if class_name not in self.handlers: raise ValueError('No handler has been registered for class: {0!s...
python
{ "resource": "" }
q46709
ListNoteCallMixin.list_notes
train
def list_notes(self, page=0, since=None): """ Get the notes 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 notes :rtype: list """ ...
python
{ "resource": "" }
q46710
token
train
def token(function): """Attach a CSRF token for POST requests.""" def wrapped(session, *args): """Wrap function.""" resp = session.get(TOKEN_URL).json() session.headers.update({'mopar-csrf-salt': resp['token']}) return function(session, *args) return wrapped
python
{ "resource": "" }
q46711
get_profile
train
def get_profile(session): """Get complete profile.""" try: profile = session.get(PROFILE_URL).json() if 'errorCode' in profile and profile['errorCode'] == '403': raise MoparError("not logged in") return profile except JSONDecodeError: raise MoparError("not logged ...
python
{ "resource": "" }
q46712
get_report
train
def get_report(session, vehicle_index): """Get vehicle health report summary.""" vhr = get_vehicle_health_report(session, vehicle_index) if 'reportCard' not in vhr: raise MoparError("no vhr found") return _traverse_report(vhr['reportCard'])
python
{ "resource": "" }
q46713
get_vehicle_health_report
train
def get_vehicle_health_report(session, vehicle_index): """Get complete vehicle health report.""" profile = get_profile(session) _validate_vehicle(vehicle_index, profile) return session.get(VHR_URL, params={ 'uuid': profile['vehicles'][vehicle_index]['uuid'] }).json()
python
{ "resource": "" }
q46714
_traverse_report
train
def _traverse_report(data): """Recursively traverse vehicle health report.""" if 'items' not in data: return {} out = {} for item in data['items']: skip = (item['severity'] == 'NonDisplay' or item['itemKey'] == 'categoryDesc' or item['value'] in [None, 'Nu...
python
{ "resource": "" }
q46715
get_tow_guide
train
def get_tow_guide(session, vehicle_index): """Get tow guide information.""" profile = get_profile(session) _validate_vehicle(vehicle_index, profile) return session.post(TOW_URL, { 'vin': profile['vehicles'][vehicle_index]['vin'] }).json()
python
{ "resource": "" }
q46716
_get_model
train
def _get_model(vehicle): """Clean the model field. Best guess.""" model = vehicle['model'] model = model.replace(vehicle['year'], '') model = model.replace(vehicle['make'], '') return model.strip().split(' ')[0]
python
{ "resource": "" }
q46717
get_summary
train
def get_summary(session): """Get vehicle summary.""" profile = get_profile(session) return { 'user': { 'email': profile['userProfile']['eMail'], 'name': '{} {}'.format(profile['userProfile']['firstName'], profile['userProfile']['lastName']) ...
python
{ "resource": "" }
q46718
_remote_status
train
def _remote_status(session, service_id, uuid, url, interval=3): """Poll for remote command status.""" _LOGGER.info('polling for status') resp = session.get(url, params={ 'remoteServiceRequestID':service_id, 'uuid':uuid }).json() if resp['status'] == 'SUCCESS': return 'complet...
python
{ "resource": "" }
q46719
remote_command
train
def remote_command(session, command, vehicle_index, poll=True): """Send a remote command.""" if command not in SUPPORTED_COMMANDS: raise MoparError("unsupported command: " + command) profile = get_profile(session) _validate_vehicle(vehicle_index, profile) if command in [COMMAND_LOCK, COMMAND...
python
{ "resource": "" }
q46720
get_session
train
def get_session(username, password, pin, cookie_path=COOKIE_PATH): """Get a new session.""" class MoparAuth(AuthBase): # pylint: disable=too-few-public-methods """Authentication wrapper.""" def __init__(self, username, password, pin, cookie_path): """Init.""" self.usern...
python
{ "resource": "" }
q46721
ErrorController.img
train
def img(self, id): """Serve Pylons' stock images""" return self._serve_file(os.path.join(media_path, 'img', id))
python
{ "resource": "" }
q46722
ErrorController.style
train
def style(self, id): """Serve Pylons' stock stylesheets""" return self._serve_file(os.path.join(media_path, 'style', id))
python
{ "resource": "" }
q46723
rcfile
train
def rcfile(appname, args={}, strip_dashes=True, module_name=None): """ Read environment variables and config files and return them merged with predefined list of arguments. Arguments: appname - application name, used for config files and environemnt variable names. args - ar...
python
{ "resource": "" }
q46724
color_parts
train
def color_parts(parts): """Adds colors to each part of the citation""" return parts._replace( title=Fore.GREEN + parts.title + Style.RESET_ALL, doi=Fore.CYAN + parts.doi + Style.RESET_ALL )
python
{ "resource": "" }
q46725
get_common_parts
train
def get_common_parts(r): """Gets citation parts which are common to all types of citation""" title = format_title(r.get('title')) author_list = format_author_list(r.get('author')) container = format_container(r.get('container-title')) date = format_date(r.get('issued')) doi = r.get('DOI') ...
python
{ "resource": "" }
q46726
safeReadJSON
train
def safeReadJSON(url, logger, max_check=6, waittime=30): '''Return JSON object from URL''' counter = 0 # try, try and try again .... while counter < max_check: try: with contextlib.closing(urllib.request.urlopen(url)) as f: res = json.loads(f.read().decode('utf8')) ...
python
{ "resource": "" }
q46727
numpy_compiler
train
def numpy_compiler(model): """Take a triflow model and return optimized numpy routines. Parameters ---------- model: triflow.Model: Model to compile Returns ------- (numpy function, numpy function): Optimized routine that compute the evolution equations and their ja...
python
{ "resource": "" }
q46728
_Crc64Calculator.update
train
def update(self, content): """Enumerates the bytes of the supplied bytearray and updates the CRC-64. No return value. """ for byte in content: self._crc64 = (self._crc64 >> 8) ^ self._lookup_table[(self._crc64 & 0xff) ^ byte]
python
{ "resource": "" }
q46729
_Crc64Calculator._construct_lookup_table
train
def _construct_lookup_table(self, polynomial): """Precomputes a CRC-64 lookup table seeded from the supplied polynomial. No return value. """ self._lookup_table = [] for i in range(0, 256): lookup_value = i for _ in range(0, 8): if lo...
python
{ "resource": "" }
q46730
Socket.send
train
def send(self, data, **kws): """Send data to the socket. The socket must be connected to a remote socket. Ammount sent may be less than the data provided.""" return yield_(Send(self, data, timeout=self._timeout, **kws))
python
{ "resource": "" }
q46731
Socket.connect
train
def connect(self, address, **kws): """Connect to a remote socket at _address_. """ return yield_(Connect(self, address, timeout=self._timeout, **kws))
python
{ "resource": "" }
q46732
NetBackend.authenticate
train
def authenticate(identity=None, provider=None): " Authenticate user by net identity. " if not identity: return None try: netid = NetID.objects.get(identity=identity, provider=provider) return netid.user except NetID.DoesNotExist: return No...
python
{ "resource": "" }
q46733
check
train
def check(ty, val): "Checks that `val` adheres to type `ty`" if isinstance(ty, basestring): ty = Parser().parse(ty) return ty.enforce(val)
python
{ "resource": "" }
q46734
RegularDimension.get_id
train
def get_id(self, natural_key, enhancement=None): """ Returns the technical ID for a natural key or None if the given natural key is not valid. :param T natural_key: The natural key. :param T enhancement: Enhancement data of the dimension row. :rtype: int|None """ ...
python
{ "resource": "" }
q46735
_get_video_ts_file_paths
train
def _get_video_ts_file_paths(dvd_path): """Returns a sorted list of paths for files contained in th VIDEO_TS folder of the specified DVD path. """ video_ts_folder_path = join(dvd_path, "VIDEO_TS") video_ts_file_paths = [] for video_ts_folder_content_name in listdir(video_ts_folder_path): ...
python
{ "resource": "" }
q46736
_convert_timedelta_to_seconds
train
def _convert_timedelta_to_seconds(timedelta): """Returns the total seconds calculated from the supplied timedelta. (Function provided to enable running on Python 2.6 which lacks timedelta.total_seconds()). """ days_in_seconds = timedelta.days * 24 * 3600 return int((timedelta.microseconds + (ti...
python
{ "resource": "" }
q46737
_get_file_size
train
def _get_file_size(file_path): """Returns the size of the file at the specified file path, formatted as a 4-byte unsigned integer bytearray. """ size = getsize(file_path) file_size = bytearray(4) pack_into(b"I", file_size, 0, size) return file_size
python
{ "resource": "" }
q46738
_get_file_name
train
def _get_file_name(file_path): """Returns the name of the file at the specified file path, formatted as a UTF-8 bytearray terminated with a null character. """ file_name = basename(file_path) utf8_file_name = bytearray(file_name, "utf8") utf8_file_name.append(0) return utf8_file_name
python
{ "resource": "" }
q46739
logSysInfo
train
def logSysInfo(): """Write system info to log file""" logger.info('#' * 70) logger.info(datetime.today().strftime("%A, %d %B %Y %I:%M%p")) logger.info('Running on [{0}] [{1}]'.format(platform.node(), platform.platform())) logger.info('Python [{0}]'.for...
python
{ "resource": "" }
q46740
logEndTime
train
def logEndTime(): """Write end info to log""" logger.info('\n' + '#' * 70) logger.info('Complete') logger.info(datetime.today().strftime("%A, %d %B %Y %I:%M%p")) logger.info('#' * 70 + '\n')
python
{ "resource": "" }
q46741
get_config
train
def get_config(section, option, allow_empty_option=True, default=""): ''' Get data from configs ''' try: value = config.get(section, option) if value is None or len(value) == 0: if allow_empty_option: return "" else: return default ...
python
{ "resource": "" }
q46742
getboolean_config
train
def getboolean_config(section, option, default=False): ''' Get data from configs which store boolean records ''' try: return config.getboolean(section, option) or default except ConfigParser.NoSectionError: return default
python
{ "resource": "" }
q46743
InListCondition.populate_values
train
def populate_values(self, rows, field): """ Populates the filter values of this filter using list of rows. :param list[dict[str,T]] rows: The row set. :param str field: The field name. """ self._values.clear() for row in rows: condition = SimpleCondit...
python
{ "resource": "" }
q46744
InListCondition.match
train
def match(self, row): """ Returns True if the field is in the list of conditions. Returns False otherwise. :param dict row: The row. :rtype: bool """ if row[self._field] in self._values: return True for condition in self._conditions: if ...
python
{ "resource": "" }
q46745
solveAndNotify
train
def solveAndNotify(proto, exercise): """The user at the given AMP protocol has solved the given exercise. This will log the solution and notify the user. """ exercise.solvedBy(proto.user) proto.callRemote(ce.NotifySolved, identifier=exercise.identifier, tit...
python
{ "resource": "" }
q46746
Exercise.solvedBy
train
def solvedBy(self, user): """Stores that this user has just solved this exercise. You probably want to notify the user when this happens. For that, see ``solveAndNotify``. """ _Solution(store=self.store, who=user, what=self)
python
{ "resource": "" }
q46747
Exercise.wasSolvedBy
train
def wasSolvedBy(self, user): """Checks if this exercise has previously been solved by the user. """ thisExercise = _Solution.what == self byThisUser = _Solution.who == user condition = q.AND(thisExercise, byThisUser) return self.store.query(_Solution, condition, limit=1)...
python
{ "resource": "" }
q46748
Locator.getExerciseDetails
train
def getExerciseDetails(self, identifier): """Gets the details for a particular exercise. """ exercise = self._getExercise(identifier) response = { b"identifier": exercise.identifier, b"title": exercise.title, b"description": exercise.description, ...
python
{ "resource": "" }
q46749
split
train
def split(s): """ Split a string into a list, respecting any quoted strings inside Uses ``shelx.split`` which has a bad habbit of inserting null bytes where they are not wanted """ return map(lambda w: filter(lambda c: c != '\x00', w), lexsplit(s))
python
{ "resource": "" }
q46750
lookup
train
def lookup(parser, var, context, resolve=True, apply_filters=True): """ Try to resolve the varialbe in a context If ``resolve`` is ``False``, only string variables are returned """ if resolve: try: return Variable(var).resolve(context) except VariableDoesNotExist: ...
python
{ "resource": "" }
q46751
get_cache_key
train
def get_cache_key(bucket, name, args, kwargs): """ Gets a unique SHA1 cache key for any call to a native tag. Use args and kwargs in hash so that the same arguments use the same key """ u = ''.join(map(str, (bucket, name, args, kwargs))) return 'native_tags.%s' % sha_constructor(u).hexdigest()
python
{ "resource": "" }
q46752
do_function
train
def do_function(parser, token): """ Performs a defined function on the passed arguments. Normally this returns the output of the function into the template. If the second to last argument is ``as``, the result of the function is stored in the context and is named whatever the last argument is. Synt...
python
{ "resource": "" }
q46753
do_block
train
def do_block(parser, token): """ Process several nodes inside a single block Block functions take ``context``, ``nodelist`` as first arguments If the second to last argument is ``as``, the rendered result is stored in the context and is named whatever the last argument is. Syntax:: {% [blo...
python
{ "resource": "" }
q46754
ModelMeta.process_attributes_of_node
train
def process_attributes_of_node(attrs, node_name, class_type): """ prepare the model fields, nodes and relations Args: node_name (str): name of the node we are currently processing attrs (dict): attribute dict class_type (str): Type of class. C...
python
{ "resource": "" }
q46755
ModelMeta.process_models
train
def process_models(attrs, base_model_class): """ Attach default fields and meta options to models """ attrs.update(base_model_class._DEFAULT_BASE_FIELDS) attrs['_instance_registry'] = set() attrs['_is_unpermitted_fields_set'] = False attrs['save_meta_data'] = None...
python
{ "resource": "" }
q46756
ModelMeta.process_objects
train
def process_objects(kls): """ Applies default Meta properties. """ # first add a Meta object if not exists if 'Meta' not in kls.__dict__: kls.Meta = type('Meta', (object,), {}) if 'unique_together' not in kls.Meta.__dict__: kls.Meta.unique_together...
python
{ "resource": "" }
q46757
get_user
train
async def get_user(username: str, api_key: str, **kwargs) -> User: """ Creates a new user, validate its credentials and returns it |funccoro| Args: username: username as specified on the challonge website api_key: key as found on the challonge `settings <https://challonge.com/s...
python
{ "resource": "" }
q46758
User.get_tournaments
train
async def get_tournaments(self, subdomain: str = None, force_update: bool = False) -> list: """ gets all user's tournaments |methcoro| Args: subdomain: *optional* subdomain needs to be given explicitely to get tournaments in a subdomain force_update: *optional* set to T...
python
{ "resource": "" }
q46759
User.create_tournament
train
async def create_tournament(self, name: str, url: str, tournament_type: TournamentType = TournamentType.single_elimination, **params) -> Tournament: """ creates a simple tournament with basic options |methcoro| Args: name: name of the new tournament url: url of the new ...
python
{ "resource": "" }
q46760
User.destroy_tournament
train
async def destroy_tournament(self, t: Tournament): """ completely removes a tournament from Challonge |methcoro| Note: |from_api| Deletes a tournament along with all its associated records. There is no undo, so use with care! Raises: APIException """ ...
python
{ "resource": "" }
q46761
get_object_from_path
train
def get_object_from_path(path): """ Import's object from given Python path. """ try: return sys.IMPORT_CACHE[path] except KeyError: _path = path.split('.') module_path = '.'.join(_path[:-1]) class_name = _path[-1] module = importlib.import_module(module_path) ...
python
{ "resource": "" }
q46762
pprnt
train
def pprnt(input, return_data=False): """ Prettier print for nested data Args: input: Input data return_data (bool): Default False. Print outs if False, returns if True. Returns: None | Pretty formatted text representation of input data. """ HEADER = '\033[95m' OKBLUE...
python
{ "resource": "" }
q46763
wrapped_sendfile
train
def wrapped_sendfile(act, offset, length): """ Calls the sendfile system call or simulate with file read and socket send if unavailable. """ if sendfile: offset, sent = sendfile.sendfile( act.sock.fileno(), act.file_handle.fileno(), offset, length...
python
{ "resource": "" }
q46764
ProactorBase.set_options
train
def set_options(self, multiplex_first=True, **bogus_options): "Takes implementation specific options. To be overriden in a subclass." self.multiplex_first = multiplex_first self._warn_bogus_options(**bogus_options)
python
{ "resource": "" }
q46765
ProactorBase._warn_bogus_options
train
def _warn_bogus_options(self, **opts): """ Shows a warning for unsupported options for the current implementation. Called form set_options with remainig unsupported options. """ if opts: import warnings for i in opts: warnings.warn(...
python
{ "resource": "" }
q46766
ProactorBase.request_connect
train
def request_connect(self, act, coro): "Requests a connect for `coro` corutine with parameters and completion \ passed via `act`" result = self.try_run_act(act, perform_connect) if result: return result, coro else: self.add_token(act, coro, perform_c...
python
{ "resource": "" }
q46767
ProactorBase.add_token
train
def add_token(self, act, coro, performer): """ Adds a completion token `act` in the proactor with associated `coro` corutine and perform callable. """ assert act not in self.tokens act.coro = coro self.tokens[act] = performer self.register_fd(act, ...
python
{ "resource": "" }
q46768
ProactorBase.handle_event
train
def handle_event(self, act): """ Handle completion for a request. Calls the scheduler to run or schedule the associated coroutine. """ scheduler = self.scheduler if act in self.tokens: coro = act.coro op = self.try_run_act(act, self.token...
python
{ "resource": "" }
q46769
ProactorBase.handle_error_event
train
def handle_error_event(self, act, detail, exc=SocketError): """ Handle an errored event. Calls the scheduler to schedule the associated coroutine. """ del self.tokens[act] self.scheduler.active.append(( CoroutineException(exc, exc(detail)), ...
python
{ "resource": "" }
q46770
add_to_dumper
train
def add_to_dumper(dumper: Type, classes: List[Type]) -> None: """Register user-defined classes with the Dumper. This enables the Dumper to write objects of your classes to a \ YAML file. Note that all the arguments are types, not instances! Args: dumper: Your dumper class(!), derived from yati...
python
{ "resource": "" }
q46771
Ontospy.sparql
train
def sparql(self, stringa): """ wrapper around a sparql query """ qres = self.rdfgraph.query(stringa) return list(qres)
python
{ "resource": "" }
q46772
Ontospy.__extractOntologies
train
def __extractOntologies(self, exclude_BNodes = False, return_string=False): """ returns Ontology class instances [ a owl:Ontology ; vann:preferredNamespacePrefix "bsym" ; vann:preferredNamespaceUri "http://bsym.bloomberg.com/sym/" ], """ out = [] ...
python
{ "resource": "" }
q46773
Ontospy.nextClass
train
def nextClass(self, classuri): """Returns the next class in the list of classes. If it's the last one, returns the first one.""" if classuri == self.classes[-1].uri: return self.classes[0] flag = False for x in self.classes: if flag == True: return...
python
{ "resource": "" }
q46774
Ontospy.nextProperty
train
def nextProperty(self, propuri): """Returns the next property in the list of properties. If it's the last one, returns the first one.""" if propuri == self.properties[-1].uri: return self.properties[0] flag = False for x in self.properties: if flag == True: ...
python
{ "resource": "" }
q46775
Ontospy.nextConcept
train
def nextConcept(self, concepturi): """Returns the next skos concept in the list of concepts. If it's the last one, returns the first one.""" if concepturi == self.skosConcepts[-1].uri: return self.skosConcepts[0] flag = False for x in self.skosConcepts: if flag ==...
python
{ "resource": "" }
q46776
Ontospy.printSkosTree
train
def printSkosTree(self, element = None, showids=False, labels=False, showtype=False): """ Print nicely into stdout the SKOS tree of an ontology Note: indentation is made so that ids up to 3 digits fit in, plus a space. [123]1-- [1]123-- [12]12-- """ TYPE_...
python
{ "resource": "" }
q46777
highlight
train
def highlight(code, lexer, **kwargs): """ Returns highlighted code ``div`` tag from ``HtmlFormatter`` Lexer is guessed by ``lexer`` name arguments are passed into the formatter Syntax:: {% highlight [source code] [lexer name] [formatter options] %} Example:: {...
python
{ "resource": "" }
q46778
highlight_block
train
def highlight_block(context, nodelist, lexer, **kwargs): """ Code is nodelist ``rendered`` in ``context`` Returns highlighted code ``div`` tag from ``HtmlFormatter`` Lexer is guessed by ``lexer`` name arguments are passed into the formatter Syntax:: {% highlight_block [lexer na...
python
{ "resource": "" }
q46779
warning
train
def warning(message, code='WARNING'): """Display Warning. Method prints the warning message, message being given as an input. Arguments: message {string} -- The message to be displayed. """ now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') output = now + ' [' + torn.plugins.color...
python
{ "resource": "" }
q46780
info
train
def info(message, code='INFO'): """Display Information. Method prints the information message, message being given as an input. Arguments: message {string} -- The message to be displayed. """ now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') output = now + ' [' + torn.plugins.col...
python
{ "resource": "" }
q46781
error
train
def error(message, code='ERROR'): """Display Error. Method prints the error message, message being given as an input. Arguments: message {string} -- The message to be displayed. """ now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') output = now + ' [' + torn.plugins.colors.FAIL + ...
python
{ "resource": "" }
q46782
Controller.render
train
def render(self, template, **data): """Renders the template using Jinja2 with given data arguments. """ if(type(template) != str): raise TypeError("String expected") env = Environment( loader=FileSystemLoader(os.getcwd() + '/View'), autoescap...
python
{ "resource": "" }
q46783
AndCondition.match
train
def match(self, row): """ Returns True if the row matches one or more child conditions. Returns False otherwise. :param dict row: The row. :rtype: bool """ for condition in self._conditions: if condition.match(row): return True retur...
python
{ "resource": "" }
q46784
wait_until
train
def wait_until(time_label): ''' Calculates the number of seconds that the process needs to sleep ''' if time_label == 'next_minute': gevent.sleep(60 - int(time.time()) % 60) elif time_label == 'next_hour': gevent.sleep(3600 - int(time.time()) % 3600) elif time_label == 'tomorrow...
python
{ "resource": "" }
q46785
every_hour.next
train
def next(self): ''' Never return StopIteration ''' if self.started is False: self.started = True now_ = datetime.now() if self.hour: # Fixed hour in a day # Next run will be the next day scheduled = now_...
python
{ "resource": "" }
q46786
Scheduler.unschedule
train
def unschedule(self, task_name): ''' Removes a task from scheduled jobs but it will not kill running tasks ''' for greenlet in self.waiting[task_name]: try: gevent.kill(greenlet) except BaseException: pass
python
{ "resource": "" }
q46787
Scheduler.stop_task
train
def stop_task(self, task_name): ''' Stops a running or dead task ''' for greenlet in self.active[task_name]: try: # Do not need to check if greenlet is dead, gevent does it already gevent.kill(greenlet) self.active[task_name] = ...
python
{ "resource": "" }
q46788
Scheduler._remove_dead_greenlet
train
def _remove_dead_greenlet(self, task_name): ''' Removes dead greenlet or done task from active list ''' for greenlet in self.active[task_name]: try: # Allows active greenlet continue to run if greenlet.dead: self.active[task...
python
{ "resource": "" }
q46789
Scheduler.run
train
def run(self, task): ''' Runs a task and re-schedule it ''' self._remove_dead_greenlet(task.name) if isinstance(task.timer, types.GeneratorType): # Starts the task immediately greenlet_ = gevent.spawn(task.action, *task.args, **task.kwargs) sel...
python
{ "resource": "" }
q46790
Scheduler.run_tasks
train
def run_tasks(self): ''' Runs all assigned task in separate green threads. If the task should not be run, schedule it ''' pool = Pool(len(self.tasks)) for task in self.tasks: # Launch a green thread to schedule the task # A task will be managed by 2 green ...
python
{ "resource": "" }
q46791
Scheduler.run_forever
train
def run_forever(self, start_at='once'): """ Starts the scheduling engine @param start_at: 'once' -> start immediately 'next_minute' -> start at the first second of the next minutes 'next_hour' -> start 00:00 (min) next hour ...
python
{ "resource": "" }
q46792
aba_onto2nx
train
def aba_onto2nx(str_gr_id=10): """ Downloads and parse the Allen Brain Atlas ontologies into a network object More information about Allen Brain Atlas API can be found using following links: http://help.brain-map.org/display/api/Atlas+Drawings+and+Ontologies#AtlasDrawingsandOntologies-StructuresAndOntologi...
python
{ "resource": "" }
q46793
compare_version
train
def compare_version(version1, version2): """ Compares two versions. """ def normalize(v): return [int(x) for x in re.sub(r'(\.0+)*$','', v).split(".")] return (normalize(version1) > normalize(version2))-(normalize(version1) < normalize(version2))
python
{ "resource": "" }
q46794
Field.encode
train
def encode(self): """ Encodes the value of the field and put it in the element also make the check for nil=true if there is one :return: returns the encoded element :rtype: xml.etree.ElementTree.Element """ element = ElementTree.Element(self.name) element...
python
{ "resource": "" }
q46795
Field._set_nil
train
def _set_nil(self, element, value_parser): """ Method to set an attribute of the element. If the value of the field is None then set the nil='true' attribute in the element :param element: the element which needs to be modified :type element: xml.etree.ElementTree.Element ...
python
{ "resource": "" }
q46796
Metadata.format
train
def format(self, template=None): """ Substitutes variables within template with that of fields' """ pattern = r"(?:<([^<]*?)\$(\w+)([^>]*?)>)" s = sub(pattern, self._format_repl, template or self.template) s = self._str_fix_whitespace(s) return s
python
{ "resource": "" }
q46797
begin
train
def begin(request, provider): """ Display authentication form. This is also the first step in registration. The actual login is in social_complete function below. """ # store url to where user will be redirected request.session['next_url'] = request.GET.get("next") or settings.LO...
python
{ "resource": "" }
q46798
extra
train
def extra(request, provider): """ Handle registration of new user with extra data for profile """ identity = request.session.get('identity', None) if not identity: raise Http404 if request.method == "POST": form = str_to_class(settings.EXTRA_FORM)(request.POST) if fo...
python
{ "resource": "" }
q46799
Node.is_scalar
train
def is_scalar(self, typ: Type = _Any) -> bool: """Returns True iff this represents a scalar node. If a type is given, checks that the ScalarNode represents this \ type. Type may be `str`, `int`, `float`, `bool`, or `None`. If no type is given, any ScalarNode will return True. "...
python
{ "resource": "" }