_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q51000
parse_variables
train
def parse_variables(args): """ Parse variables as passed on the command line. Returns ------- dict Mapping variable name to the value. """ if args is None: return {} def parse_variable(string): tokens = string.split('=') name = tokens[0] value =...
python
{ "resource": "" }
q51001
Fsdb._copy_content
train
def _copy_content(self, origin, dstPath): """copy the content of origin into dstPath Due to concurrency problem, the content will be first copied to a temporary file alongside `dstPath` and then atomically moved to `dstPath` """ if hasattr(origin, 'read'): ...
python
{ "resource": "" }
q51002
Fsdb.add
train
def add(self, origin): """Add new element to fsdb. Args: origin -- could be the path of a file or a readable/seekable object ( fileobject, stream, stringIO...) Returns: String rapresenting the digest of the file """ digest = self._calc_digest(origin) ...
python
{ "resource": "" }
q51003
Fsdb.exists
train
def exists(self, digest): """Check file existence in fsdb Returns: True if file exists under this instance of fsdb, false otherwise """ if not isinstance(digest, string_types): raise TypeError("digest must be a string") return os.path.isfile(self.get_fi...
python
{ "resource": "" }
q51004
Fsdb.get_file_path
train
def get_file_path(self, digest): """Retrieve the absolute path to the file with the given digest Args: digest -- digest of the file Returns: String rapresenting the absolute path of the file """ relPath = Fsdb.generate_tree_path(digest, self._conf['de...
python
{ "resource": "" }
q51005
Fsdb.check
train
def check(self, digest): """Check the integrity of the file with the given digest Args: digest -- digest of the file to check Returns: True if the file is not corrupted """ path = self.get_file_path(digest) if self._calc_digest(path) != digest...
python
{ "resource": "" }
q51006
Fsdb.size
train
def size(self): """Return the total size in bytes of all the files handled by this instance of fsdb. Fsdb does not use auxiliary data structure, so this function could be expensive. Look at _iter_over_paths() functions for more details. """ tot = 0 for p in self.__iter__...
python
{ "resource": "" }
q51007
parse_set
train
def parse_set(string): """Parse set from comma separated string.""" string = string.strip() if string: return set(string.split(",")) else: return set()
python
{ "resource": "" }
q51008
minver_error
train
def minver_error(pkg_name): """Report error about missing minimum version constraint and exit.""" print( 'ERROR: specify minimal version of "{}" using ' '">=" or "=="'.format(pkg_name), file=sys.stderr ) sys.exit(1)
python
{ "resource": "" }
q51009
AbstractIgRestSession.get
train
def get(self, endpoint: str, **kwargs) -> dict: """HTTP GET operation to API endpoint.""" return self._request('GET', endpoint, **kwargs)
python
{ "resource": "" }
q51010
AbstractIgRestSession.post
train
def post(self, endpoint: str, **kwargs) -> dict: """HTTP POST operation to API endpoint.""" return self._request('POST', endpoint, **kwargs)
python
{ "resource": "" }
q51011
AbstractIgRestSession.put
train
def put(self, endpoint: str, **kwargs) -> dict: """HTTP PUT operation to API endpoint.""" return self._request('PUT', endpoint, **kwargs)
python
{ "resource": "" }
q51012
AbstractIgRestSession.delete
train
def delete(self, endpoint: str, **kwargs) -> dict: """HTTP DELETE operation to API endpoint.""" return self._request('DELETE', endpoint, **kwargs)
python
{ "resource": "" }
q51013
Selector.resolve_selector_type
train
def resolve_selector_type(self): """Resolve the selector type This make sure that all the selectors provided are of the same type (in case of a list of selector) """ resolved_selector_type_list = [] for current_selector in self._effective_selector_list: resol...
python
{ "resource": "" }
q51014
Selector.resolve_function
train
def resolve_function(self): """Resolve the selenium function that will be use to find the element """ selector_type = self._effective_selector_type # NAME if selector_type == 'name': return ('find_elements_by_name', 'NAME') # XPATH elif selector_type...
python
{ "resource": "" }
q51015
cache_git_tag
train
def cache_git_tag(): """ Try to read the current version from git and, if read successfully, cache it into the version cache file. If the git folder doesn't exist or if git isn't installed, this is a no-op. I.E. it won't blank out a pre-existing version cache file upon failure. :return: Project ver...
python
{ "resource": "" }
q51016
get_version
train
def get_version(pypi=False): """ Get the project version string. Returns the most-accurate-possible version string for the current project. This order of preference this is: 1. The actual output of ``git describe --tags`` 2. The contents of the version cache file 3. The default version, ``...
python
{ "resource": "" }
q51017
system_exit
train
def system_exit(object): """ Handles proper system exit in case of critical exception. :param object: Object to decorate. :type object: object :return: Object. :rtype: object """ @functools.wraps(object) def system_exit_wrapper(*args, **kwargs): """ Handles proper s...
python
{ "resource": "" }
q51018
trace_walker
train
def trace_walker(module): """ Defines a generator used to walk into modules. :param module: Module to walk. :type module: ModuleType :return: Class / Function / Method. :rtype: object or object """ for name, function in inspect.getmembers(module, inspect.isfunction): yield None...
python
{ "resource": "" }
q51019
get_object_name
train
def get_object_name(object): """ Returns given object name. :param object: Object to retrieve the name. :type object: object :return: Object name. :rtype: unicode """ if type(object) is property: return object.fget.__name__ elif hasattr(object, "__name__"): return o...
python
{ "resource": "" }
q51020
get_trace_name
train
def get_trace_name(object): """ Returns given object trace name. :param object: Object. :type object: object :return: Object trace name. :rtype: unicode """ global TRACE_NAMES_CACHE global TRACE_WALKER_CACHE trace_name = TRACE_NAMES_CACHE.get(object) if trace_name is None:...
python
{ "resource": "" }
q51021
get_method_name
train
def get_method_name(method): """ Returns given method name. :param method: Method to retrieve the name. :type method: object :return: Method name. :rtype: unicode """ name = get_object_name(method) if name.startswith("__") and not name.endswith("__"): name = "_{0}{1}".forma...
python
{ "resource": "" }
q51022
validate_tracer
train
def validate_tracer(*args): """ Validate and finishes a tracer by adding mandatory extra attributes. :param \*args: Arguments. :type \*args: \* :return: Validated wrapped object. :rtype: object """ object, wrapped = args if is_traced(object) or is_untracable(object) or get_object_n...
python
{ "resource": "" }
q51023
untracable
train
def untracable(object): """ Marks decorated object as non tracable. :param object: Object to decorate. :type object: object :return: Object. :rtype: object """ @functools.wraps(object) def untracable_wrapper(*args, **kwargs): """ Marks decorated object as non tracab...
python
{ "resource": "" }
q51024
trace_function
train
def trace_function(module, function, tracer=tracer): """ Traces given module function using given tracer. :param module: Module of the function. :type module: object :param function: Function to trace. :type function: object :param tracer: Tracer. :type tracer: object :return: Defin...
python
{ "resource": "" }
q51025
untrace_function
train
def untrace_function(module, function): """ Untraces given module function. :param module: Module of the function. :type module: object :param function: Function to untrace. :type function: object :return: Definition success. :rtype: bool """ if not is_traced(function): ...
python
{ "resource": "" }
q51026
trace_method
train
def trace_method(cls, method, tracer=tracer): """ Traces given class method using given tracer. :param cls: Class of the method. :type cls: object :param method: Method to trace. :type method: object :param tracer: Tracer. :type tracer: object :return: Definition success. :rtype...
python
{ "resource": "" }
q51027
untrace_method
train
def untrace_method(cls, method): """ Untraces given class method. :param cls: Class of the method. :type cls: object :param method: Method to untrace. :type method: object :return: Definition success. :rtype: bool """ if not is_traced(method): return False name = g...
python
{ "resource": "" }
q51028
trace_property
train
def trace_property(cls, accessor, tracer=tracer): """ Traces given class property using given tracer. :param cls: Class of the property. :type cls: object :param accessor: Property to trace. :type accessor: property :param tracer: Tracer. :type tracer: object :return: Definition suc...
python
{ "resource": "" }
q51029
untrace_property
train
def untrace_property(cls, accessor): """ Untraces given class property. :param cls: Class of the property. :type cls: object :param accessor: Property to untrace. :type accessor: property :return: Definition success. :rtype: bool """ if not is_traced(accessor.fget) or not is_tr...
python
{ "resource": "" }
q51030
trace_class
train
def trace_class(cls, tracer=tracer, pattern=r".*", flags=0): """ Traces given class using given tracer. :param cls: Class to trace. :type cls: object :param tracer: Tracer. :type tracer: object :param pattern: Matching pattern. :type pattern: unicode :param flags: Matching regex fla...
python
{ "resource": "" }
q51031
untrace_class
train
def untrace_class(cls): """ Untraces given class. :param cls: Class to untrace. :type cls: object :return: Definition success. :rtype: bool """ for name, method in inspect.getmembers(cls, inspect.ismethod): untrace_method(cls, method) for name, function in inspect.getmembe...
python
{ "resource": "" }
q51032
trace_module
train
def trace_module(module, tracer=tracer, pattern=r".*", flags=0): """ Traces given module members using given tracer. :param module: Module to trace. :type module: ModuleType :param tracer: Tracer. :type tracer: object :param pattern: Matching pattern. :type pattern: unicode :param f...
python
{ "resource": "" }
q51033
untrace_module
train
def untrace_module(module): """ Untraces given module members. :param module: Module to untrace. :type module: ModuleType :return: Definition success. :rtype: bool """ for name, function in inspect.getmembers(module, inspect.isfunction): untrace_function(module, function) ...
python
{ "resource": "" }
q51034
register_module
train
def register_module(module=None): """ Registers given module or caller introspected module in the candidates modules for tracing. :param module: Module to register. :type module: ModuleType :return: Definition success. :rtype: bool """ global REGISTERED_MODULES if module is None: ...
python
{ "resource": "" }
q51035
install_tracer
train
def install_tracer(tracer=tracer, pattern=r".*", flags=0): """ Installs given tracer in the candidates modules for tracing matching given pattern. :param tracer: Tracer. :type tracer: object :param pattern: Matching pattern. :type pattern: unicode :param flags: Matching regex flags. :ty...
python
{ "resource": "" }
q51036
uninstall_tracer
train
def uninstall_tracer(pattern=r".*", flags=0): """ Installs the tracer in the candidates modules for tracing matching given pattern. :param pattern: Matching pattern. :type pattern: unicode :param flags: Matching regex flags. :type flags: int :return: Definition success. :rtype: bool ...
python
{ "resource": "" }
q51037
evaluate_trace_request
train
def evaluate_trace_request(data, tracer=tracer): """ Evaluate given string trace request. Usage:: Umbra -t "{'umbra.engine' : ('.*', 0), 'umbra.preferences' : (r'.*', 0)}" Umbra -t "['umbra.engine', 'umbra.preferences']" Umbra -t "'umbra.engine, umbra.preferences" :param data:...
python
{ "resource": "" }
q51038
HttpClient._init_session
train
def _init_session(self): ''' Delayed initialization of Requests Session object. This is done in order *not* to share the Session object across a multiprocessing pool. ''' self._real_session = requests.Session() # FIXME: this fails when one runs HTTPS on non-stand...
python
{ "resource": "" }
q51039
HttpClient._login
train
def _login(self, username, password): '''Authenticates a TissueMAPS user. Parameters ---------- username: str name password: str password ''' logger.debug('login in as user "%s"' % username) url = self._build_url('/auth') p...
python
{ "resource": "" }
q51040
check_password
train
def check_password(password, encoded, setter=None, preferred='default'): """ Return a boolean of whether the raw password matches the three part encoded digest. If setter is specified, it'll be called when you need to regenerate the password. """ if password is None: return False ...
python
{ "resource": "" }
q51041
mask_hash
train
def mask_hash(hash, show=6, char="*"): """ Return the given hash, with only the first ``show`` number shown. The rest are masked with ``char`` for security reasons. """ masked = hash[:show] masked += char * len(hash[show:]) return masked
python
{ "resource": "" }
q51042
LIMIX_runner.load_data
train
def load_data(self): """ Run the job specified in data_script """ options=self.options command = open(self.options.data_script).read() self.result["data_script"]=command t0=time.time() data=None #fallback data exec(command) #creates variabl...
python
{ "resource": "" }
q51043
LIMIX_runner.run_experiment
train
def run_experiment(self): """ Run the job specified in experiment_script """ data=self.data options=self.options result=self.result command = open(self.options.experiment_script).read() result["experiment_script"]=command t0=time.time() ex...
python
{ "resource": "" }
q51044
LIMIX_runner.write_resultfiles
train
def write_resultfiles(self): """ Write the output to disk """ t0=time.time() writer = ow.output_writer(output_dictionary=self.result) if len(self.options.outpath)>=3 and self.options.outpath[-3:]==".h5": writer.write_hdf5(filename=self.options.outpath,timestam...
python
{ "resource": "" }
q51045
generate_signature_class
train
def generate_signature_class(cls): """ Generate a declarative model for storing signatures related to the given cls parameter. :param class cls: The declarative model to generate a signature class for. :return: The signature class, as a declarative derived from Base. """ return type("%sSigs...
python
{ "resource": "" }
q51046
create_session_engine
train
def create_session_engine(uri=None, cfg=None): """ Create an sqlalchemy session and engine. :param str uri: The database URI to connect to :param cfg: The configuration object with database URI info. :return: The session and the engine as a list (in that order) """ if uri is not None: ...
python
{ "resource": "" }
q51047
power
train
def power(maf=0.5,beta=0.1, N=100, cutoff=5e-8): """ estimate power for a given allele frequency, effect size beta and sample size N Assumption: z-score = beta_ML distributed as p(0) = N(0,1.0(maf*(1-maf)*N))) under the null hypothesis the actual beta_ML is distributed as p(alt) = N( beta , 1.0/(maf*(1-maf)N) )...
python
{ "resource": "" }
q51048
CommandWrapper._call_cmd_line
train
def _call_cmd_line(self): """Run the command line tool.""" try: logging.info("Calling Popen with: {}".format(self.args)) p = Popen(self.args, stdin=PIPE, stdout=PIPE, stderr=PIPE) except OSError: raise(RuntimeError("No such command found in PATH")) # ...
python
{ "resource": "" }
q51049
download_file
train
def download_file(url, file_name): """ Helper for downloading a remote file to disk. """ logger.info("Downloading URL: %s", url) file_size = 0 if not os.path.isfile(file_name): response = requests.get(url, stream=True) with open(file_name, "wb") as fp: if not respo...
python
{ "resource": "" }
q51050
check
train
def check(mod): """Check the parsed ASDL tree for correctness. Return True if success. For failure, the errors are printed out and False is returned. """ v = Check() v.visit(mod) for t in v.types: if t not in mod.types and not t in builtin_types: v.errors += 1 ...
python
{ "resource": "" }
q51051
parse
train
def parse(filename): """Parse ASDL from the given file and return a Module node describing it.""" with open(filename) as f: parser = ASDLParser() return parser.parse(f.read())
python
{ "resource": "" }
q51052
tokenize_asdl
train
def tokenize_asdl(buf): """Tokenize the given buffer. Yield Token objects.""" for lineno, line in enumerate(buf.splitlines(), 1): for m in re.finditer(r'\s*(\w+|--.*|.)', line.strip()): c = m.group(1) if c[0].isalpha(): # Some kind of identifier if...
python
{ "resource": "" }
q51053
ASDLParser.parse
train
def parse(self, buf): """Parse the ASDL in the buffer and return an AST with a Module root. """ self._tokenizer = tokenize_asdl(buf) self._advance() return self._parse_module()
python
{ "resource": "" }
q51054
ASDLParser._advance
train
def _advance(self): """ Return the value of the current token and read the next one into self.cur_token. """ cur_val = None if self.cur_token is None else self.cur_token.value try: self.cur_token = next(self._tokenizer) except StopIteration: se...
python
{ "resource": "" }
q51055
ASDLParser._match
train
def _match(self, kind): """The 'match' primitive of RD parsers. * Verifies that the current token is of the given kind (kind can be a tuple, in which the kind must match one of its members). * Returns the value of the current token * Reads in the next token """ ...
python
{ "resource": "" }
q51056
bytes2iec
train
def bytes2iec(size, compact=False): """ Convert a size value in bytes to its equivalent in IEC notation. See `<http://physics.nist.gov/cuu/Units/binary.html>`_. Parameters: size (int): Number of bytes. compact (bool): If ``True``, the result contains no spaces. Ret...
python
{ "resource": "" }
q51057
iec2bytes
train
def iec2bytes(size_spec, only_positive=True): """ Convert a size specification, optionally containing a scaling unit in IEC notation, to a number of bytes. Parameters: size_spec (str): Number, optionally followed by a unit. only_positive (bool): Allow only positive values? ...
python
{ "resource": "" }
q51058
merge_adjacent
train
def merge_adjacent(numbers, indicator='..', base=0): """ Merge adjacent numbers in an iterable of numbers. Parameters: numbers (list): List of integers or numeric strings. indicator (str): Delimiter to indicate generated ranges. base (int): Passed to the `int()` conversi...
python
{ "resource": "" }
q51059
HMM._emitHMM
train
def _emitHMM(self, token_type, past_states, past_emissions): """ emits a word based on previous tokens """ assert token_type in self.emissions return utils.weighted_choice(self.emissions[token_type].items())
python
{ "resource": "" }
q51060
inurl
train
def inurl(needles, haystack, position='any'): """convenience function to make string.find return bool""" count = 0 # lowercase everything to do case-insensitive search haystack2 = haystack.lower() for needle in needles: needle2 = needle.lower() if position == 'any': if...
python
{ "resource": "" }
q51061
sniff_link
train
def sniff_link(url): """performs basic heuristics to detect what the URL is""" protocol = None link = url.strip() # heuristics begin if inurl(['service=CSW', 'request=GetRecords'], link): protocol = 'OGC:CSW' elif inurl(['service=SOS', 'request=GetObservation'], link): protocol...
python
{ "resource": "" }
q51062
LocalhostInstance.startup
train
def startup(self): """Start the instance This is mainly use to start the proxy """ self.runner.info_log("Startup") if self.browser_config.config.get('enable_proxy'): self.start_proxy()
python
{ "resource": "" }
q51063
calc_padding
train
def calc_padding(fmt, align): """Calculate how many padding bytes needed for ``fmt`` to be aligned to ``align``. Args: fmt (str): :mod:`struct` format. align (int): alignment (2, 4, 8, etc.) Returns: str: padding format (e.g., various number of 'x'). >>> calc_padding('b', ...
python
{ "resource": "" }
q51064
align_up
train
def align_up(offset, align): """Align ``offset`` up to ``align`` boundary. Args: offset (int): value to be aligned. align (int): alignment boundary. Returns: int: aligned offset. >>> align_up(3, 2) 4 >>> align_up(3, 1) 3 """ remain = offset % align if ...
python
{ "resource": "" }
q51065
bin_to_mac
train
def bin_to_mac(bin, size=6): """Convert 6 bytes into a MAC string. Args: bin (str): hex string of lenth 6. Returns: str: String representation of the MAC address in lower case. Raises: Exception: if ``len(bin)`` is not 6. """ if len(bin) != size: raise Exceptio...
python
{ "resource": "" }
q51066
cache_page
train
def cache_page(**kwargs): """ This decorator is similar to `django.views.decorators.cache.cache_page` """ cache_timeout = kwargs.pop('cache_timeout', None) key_prefix = kwargs.pop('key_prefix', None) cache_min_age = kwargs.pop('cache_min_age', None) decorator = decorators.decorator_from_midd...
python
{ "resource": "" }
q51067
Entity.tell
train
def tell(self, message): """Send text to this entity.""" if self.hearing: self.zone.send_message(self.id, json.dumps(message))
python
{ "resource": "" }
q51068
get_system_application_data_directory
train
def get_system_application_data_directory(): """ Returns the system Application data directory. Examples directories:: - 'C:\\Users\\$USER\\AppData\\Roaming' on Windows 7. - 'C:\\Documents and Settings\\$USER\\Application Data' on Windows XP. - '/Users/$USER/Library/Preferences' on...
python
{ "resource": "" }
q51069
Environment.get_values
train
def get_values(self, *args): """ Gets environment variables values. Usage:: >>> environment = Environment("HOME") >>> environment.get_values() {'HOME': u'/Users/JohnDoe'} >>> environment.get_values("USER") {'HOME': u'/Users/JohnDoe', ...
python
{ "resource": "" }
q51070
Environment.set_values
train
def set_values(self, **kwargs): """ Sets environment variables values. Usage:: >>> environment = Environment() >>> environment.set_values(JOHN="DOE", DOE="JOHN") True >>> import os >>> os.environ["JOHN"] 'DOE' ...
python
{ "resource": "" }
q51071
Environment.get_value
train
def get_value(self, variable=None): """ Gets given environment variable value. :param variable: Variable to retrieve value. :type variable: unicode :return: Variable value. :rtype: unicode :note: If the **variable** argument is not given the first **self.__varia...
python
{ "resource": "" }
q51072
BasicModem.read
train
def read(self, timeout=1.0): """read from modem port, return null string on timeout.""" self.ser.timeout = timeout if self.ser is None: return '' return self.ser.readline()
python
{ "resource": "" }
q51073
BasicModem.write
train
def write(self, cmd='AT'): """write string to modem, returns number of bytes written.""" self.cmd_response = '' self.cmd_responselines = [] if self.ser is None: return 0 cmd += '\r\n' return self.ser.write(cmd.encode())
python
{ "resource": "" }
q51074
BasicModem.sendcmd
train
def sendcmd(self, cmd='AT', timeout=1.0): """send command, wait for response. returns response from modem.""" import time if self.write(cmd): while self.get_response() == '' and timeout > 0: time.sleep(0.1) timeout -= 0.1 return self.get_lines(...
python
{ "resource": "" }
q51075
BasicModem._modem_sm
train
def _modem_sm(self): """Handle modem response state machine.""" import datetime read_timeout = READ_IDLE_TIMEOUT while self.ser: try: resp = self.read(read_timeout) except (serial.SerialException, SystemExit, TypeError): _LOGGER.de...
python
{ "resource": "" }
q51076
ServerConnection.set_user_info
train
def set_user_info(self, nick, user='*', real='*'): """Sets user info for this server, to be used before connection. Args: nick (str): Nickname to use. user (str): Username to use. real (str): Realname to use. """ if self.connected: raise E...
python
{ "resource": "" }
q51077
ServerConnection.istring
train
def istring(self, in_string=''): """Return a string that uses this server's IRC casemapping. This string's equality with other strings, ``lower()``, and ``upper()`` takes this server's casemapping into account. This should be used for things such as nicks and channel names, where compar...
python
{ "resource": "" }
q51078
ServerConnection.ilist
train
def ilist(self, in_list=[]): """Return a list that uses this server's IRC casemapping. All strings in this list are lowercased using the server's casemapping before inserting them into the list, and the ``in`` operator takes casemapping into account. """ new_list = IList(in_list...
python
{ "resource": "" }
q51079
ServerConnection.idict
train
def idict(self, in_dict={}): """Return a dict that uses this server's IRC casemapping. All keys in this dictionary are stored and compared using this server's casemapping. """ new_dict = IDict(in_dict) new_dict.set_std(self.features.get('casemapping')) if not self._casem...
python
{ "resource": "" }
q51080
ServerConnection.connect
train
def connect(self, *args, auto_reconnect=False, **kwargs): """Connects to the given server. Args: auto_reconnect (bool): Automatically reconnect on disconnection. Other arguments to this function are as usually supplied to :meth:`asyncio.BaseEventLoop.create_connection`. ...
python
{ "resource": "" }
q51081
ServerConnection.quit
train
def quit(self, message=None): """Quit from the server.""" if message is None: message = 'Quit' if self.connected: self.send('QUIT', params=[message])
python
{ "resource": "" }
q51082
ServerConnection.send
train
def send(self, verb, params=None, source=None, tags=None): """Send a generic IRC message to the server. A message is created using the various parts of the message, then gets assembled and sent to the server. Args: verb (str): Verb, such as PRIVMSG. params (list...
python
{ "resource": "" }
q51083
ServerConnection.action
train
def action(self, target, message, formatted=True, tags=None): """Send an action to the given target.""" if formatted: message = unescape(message) self.ctcp(target, 'ACTION', message)
python
{ "resource": "" }
q51084
ServerConnection.msg
train
def msg(self, target, message, formatted=True, tags=None): """Send a privmsg to the given target.""" if formatted: message = unescape(message) self.send('PRIVMSG', params=[target, message], source=self.nick, tags=tags)
python
{ "resource": "" }
q51085
ServerConnection.ctcp
train
def ctcp(self, target, ctcp_verb, argument=None): """Send a CTCP request to the given target.""" # we don't support complex ctcp encapsulation because we're somewhat sane atoms = [ctcp_verb] if argument is not None: atoms.append(argument) X_DELIM = '\x01' self...
python
{ "resource": "" }
q51086
ServerConnection.ctcp_reply
train
def ctcp_reply(self, target, ctcp_verb, argument=None): """Send a CTCP reply to the given target.""" # we don't support complex ctcp encapsulation because we're somewhat sane atoms = [ctcp_verb] if argument is not None: atoms.append(argument) X_DELIM = '\x01' ...
python
{ "resource": "" }
q51087
ServerConnection.join_channel
train
def join_channel(self, channel, key=None, tags=None): """Join the given channel.""" params = [channel] if key: params.append(key) self.send('JOIN', params=params, tags=tags)
python
{ "resource": "" }
q51088
ServerConnection.part_channel
train
def part_channel(self, channel, reason=None, tags=None): """Part the given channel.""" params = [channel] if reason: params.append(reason) self.send('PART', params=params, tags=tags)
python
{ "resource": "" }
q51089
ServerConnection.mode
train
def mode(self, target, mode_string=None, tags=None): """Sends new modes to or requests existing modes from the given target.""" params = [target] if mode_string: params += mode_string self.send('MODE', params=params, source=self.nick, tags=tags)
python
{ "resource": "" }
q51090
ServerConnection.topic
train
def topic(self, channel, new_topic=None, tags=None): """Requests or sets the topic for the given channel.""" params = [channel] if new_topic: params += new_topic self.send('TOPIC', params=params, source=self.nick, tags=tags)
python
{ "resource": "" }
q51091
ServerConnection.start
train
def start(self): """Start our welcome!""" if ('sasl' in self.capabilities.enabled and self._sasl_info and (not self.capabilities.available['sasl']['value'] or (self.capabilities.available['sasl']['value'] and self._sasl_info['method'] in ...
python
{ "resource": "" }
q51092
ServerConnection.sasl_plain
train
def sasl_plain(self, name, password, identity=None): """Authenticate to a server using SASL plain, or does so on connection. Args: name (str): Name to auth with. password (str): Password to auth with. identity (str): Identity to auth with (defaults to name). ...
python
{ "resource": "" }
q51093
find_executable
train
def find_executable(executable, path=None): """Tries to find 'executable' in the directories listed in 'path'. A string listing directories separated by 'os.pathsep'; defaults to os.environ['PATH']. Returns the complete filename or None if not found. """ if path is None: path = os.environ['PATH'] path...
python
{ "resource": "" }
q51094
measure_states
train
def measure_states(states, measurement_matrix, measurement_covariance): """ Measure a list of states with a measurement matrix in the presence of measurement noise. Args: states (array): states to measure. Shape is NxSTATE_DIM. measurement_matrix (array): Each state in *states* is measu...
python
{ "resource": "" }
q51095
generate_states
train
def generate_states(state_count, process_matrix, process_covariance, initial_state=None): """ Generate states by simulating a linear system with constant process matrix and process noise covariance. Args: state_count (int): Number of states to generate. process_matri...
python
{ "resource": "" }
q51096
Singer.calcular_limite
train
def calcular_limite(self): """ Calcula el numero maximo que se puede imprimir """ self.exponentes = sorted(list(exponentes_plural.keys()), reverse=True) exp = self.exponentes[0] self.limite = 10 ** (exp + 6) - 1
python
{ "resource": "" }
q51097
Singer.sing
train
def sing(self, number): """Interfaz publica para convertir numero a texto""" if type(number) != Decimal: number = Decimal(str(number)) if number > self.limite: msg = "El maximo numero procesable es {} ({})".format(self.limite, ...
python
{ "resource": "" }
q51098
Singer.__to_text
train
def __to_text(self, number, indice = 0, sing=False): """Convierte un numero a texto, recursivamente""" number = int(number) exp = self.exponentes[indice] indice += 1 divisor = 10 ** exp if exp == 3: func = self.__numero_tres_cifras else: ...
python
{ "resource": "" }
q51099
Singer.__numero_tres_cifras
train
def __numero_tres_cifras(self, number, indice=None, sing=False): """Convierte a texto numeros de tres cifras""" number = int(number) if number < 30: if sing: return especiales_apocopado[number] else: return especiales_masculino[number] ...
python
{ "resource": "" }