code
stringlengths
1
18.2k
def full_url(url='', domain=None, protocol='https'): """ Prepend protocol (default to https) and domain name (default from the Site framework) to an url """ if domain is None: from django.contrib.sites.models import Site domain = Site.objects.get_current().domain return f'{protocol}://{domain}{url}'
def query_sum(queryset, field): """ Let the DBMS perform a sum on a queryset """ return queryset.aggregate(s=models.functions.Coalesce(models.Sum(field), 0))['s']
def get_env(env_file='.env'): """ Set default environment variables from .env file """ try: with open(env_file) as f: for line in f.readlines(): try: key, val = line.split('=', maxsplit=1) os.environ.setdefault(key.strip(), val.strip()) except ValueError: pass except FileNotFoundError: pass
def to_dict_formatter(row, cursor): """ Take a row and use the column names from cursor to turn the row into a dictionary. Note: converts column names to lower-case! :param row: one database row, sequence of column values :type row: (value, ...) :param cursor: the cursor which was used to make the query :type cursor: D...
def show(self, *args, **kwds): """ Show how the SQL looks like when executed by the DB. This might not be supported by all connection types. For example: PostgreSQL does support it, SQLite does not. :rtype: str """ # Same as in __call__, arguments win over keywords arg = args if not arg: arg = kwds # pylint: disable=re...
def _produce_return(self, cursor): """ Get the rows from the cursor and apply the row formatter. :return: sequence of rows, or a generator if a row formatter has to be applied """ results = cursor.fetchall() # Format rows within a generator? if self._row_formatter is not None: return (self._row_formatter(r, cursor) for...
def _produce_return(self, cursor): """ Return the one result. """ results = cursor.fetchmany(2) if len(results) != 1: return None # Return the one row, or the one column. row = results[0] if self._row_formatter is not None: row = self._row_formatter(row, cursor) elif len(row) == 1: row = row[0] return row
def _row_generator(self, cursor): """ Yields individual rows until no more rows exist in query result. Applies row formatter if such exists. """ rowset = cursor.fetchmany(self._arraysize) while rowset: if self._row_formatter is not None: rowset = (self._row_formatter(r, cursor) for r in rowset) for row in rowset: yield...
def _produce_return(self, cursor): """ Calls callback once with generator. :rtype: None """ self.callback(self._row_generator(cursor), *self.cb_args) return None
def _produce_return(self, cursor): """ Return the rowcount property from the used cursor. Checks the count first, if a count was given. :raise ManipulationCheckError: if a row count was set but does not match """ rowcount = cursor.rowcount # Check the row count? if self._rowcount is not None and self._rowcount != rowco...
def get_monitor(host=PINBA_SERVER, port=PINBA_PORT, *args, **kwargs): """ todo: memory + cpu """ kwargs['servername'] = PINBA_SERVER_NAME kwargs['scriptname'] = __file__ for item in inspect.stack(): if item and __file__ not in item: kwargs['scriptname'] = item[3] break return ScriptMonitor((host, port), *args, **kwargs...
def get_results(self): """Run the linter, parse, and return result list. If a linter specified by the user is not found, return an error message as result. """ try: stdout, stderr = self._lint() # Can't return a generator from a subprocess return list(stdout), stderr or [] except FileNotFoundError as exception: # Error...
def _get_command(self): """Return command with options and targets, ready for execution.""" targets = ' '.join(self.targets) cmd_str = self._linter.command_with_options + ' ' + targets cmd_shlex = shlex.split(cmd_str) return list(cmd_shlex)
def _lint(self): """Run linter in a subprocess.""" command = self._get_command() process = subprocess.run(command, stdout=subprocess.PIPE, # nosec stderr=subprocess.PIPE) LOG.info('Finished %s', ' '.join(command)) stdout, stderr = self._get_output_lines(process) return self._linter.parse(stdout), self._parse_stderr(std...
def lint(self, targets): """Run linters in parallel and sort all results. Args: targets (list): List of files and folders to lint. """ LinterRunner.targets = targets linters = self._config.get_linter_classes() with Pool() as pool: out_err_none = pool.map(LinterRunner.run, linters) out_err = [item for item in out_err_no...
def run_from_cli(self, args): """Read arguments, run and print results. Args: args (dict): Arguments parsed by docopt. """ if args['--dump-config']: self._config.print_config() else: stdout, stderr = self.lint(args['<path>']) self.print_results(stdout, stderr)
def print_results(cls, stdout, stderr): """Print linter results and exits with an error if there's any.""" for line in stderr: print(line, file=sys.stderr) if stdout: if stderr: # blank line to separate stdout from stderr print(file=sys.stderr) cls._print_stdout(stdout) else: print(':) No issues found.')
def download(self, *ids): """ Downloads the subtitles with the given ids. :param ids: The subtitles to download :return: Result instances :raises NotOKException """ bundles = sublists_of(ids, 20) # 20 files at once is an API restriction for bundle in bundles: download_response = self._rpc.DownloadSubtitles(self._token,...
def notification_on_post_create_historical_record( instance, history_date, history_user, history_change_reason, **kwargs ): """Checks and processes any notifications for this model. Processes if `label_lower` is in site_notifications.models. Note, this is the post_create of the historical model. """ if ( site_notificat...
def manage_mailists_on_userprofile_m2m_changed( action, instance, pk_set, sender, **kwargs ): """Updates the mail server mailing lists based on the selections in the UserProfile model. """ try: instance.email_notifications except AttributeError: pass else: if action == "post_remove": update_mailing_lists_in_m2m( sender...
def addMobileResource(self, pluginSubPath: bytes, resource: BasicResource) -> None: """ Add Site Resource Add a cusotom implementation of a served http resource. :param pluginSubPath: The resource path where you want to serve this resource. :param resource: The resource to serve. :return: None """ pluginSubPath = plugi...
def parse(file_contents, file_name): ''' Takes a list of files which are assumed to be jinja2 templates and tries to parse the contents of the files Args: file_contents (str): File contents of a jinja file Raises: Exception: An exception is raised if the contents of the file cannot be parsed. ''' env = Environment() re...
def write_response( self, status_code: Union[ int, constants.HttpStatusCode ]=constants.HttpStatusCode.BAD_REQUEST, *, headers: Optional[_HeaderType]=None ) -> "writers.HttpResponseWriter": """ When this exception is raised on the server side, this method is used to send a error response instead of :method:`BaseHttpStr...
async def read(self, n: int=-1, exactly: bool=False) -> bytes: """ Read at most n bytes data or if exactly is `True`, read exactly n bytes data. If the end has been reached before the buffer has the length of data asked, it will raise a :class:`ReadUnsatisfiableError`. When :method:`.finished()` is `True`, this method ...
except asyncio.CancelledError: # pragma: no cover raise except Exception as e: raise ReadUnsatisfiableError from e elif n < 0: while True: if len(self) > self.max_buf_len: raise MaxBufferLengthReachedError try: await self._wait_for_data() except asyncio.CancelledError: # pragma: no cover raise except Exception: data = ...
async def read_until( self, separator: bytes=b"\n", *, keep_separator: bool=True) -> bytes: """ Read until the separator has been found. When the max size of the buffer has been reached, and the separator is not found, this method will raise a :class:`MaxBufferLengthReachedError`. Similarly, if the end has been reached...
if new_start_pos > 0: start_pos = new_start_pos full_pos = separator_pos + len(separator) if keep_separator: data_pos = full_pos else: data_pos = separator_pos data = bytes(self._buf[0:data_pos]) del self._buf[0:full_pos] return data
def write_response( self, status_code: Union[int, constants.HttpStatusCode], *, headers: Optional[_HeaderType]=None ) -> "writers.HttpResponseWriter": """ Write a response to the client. """ self._writer = self.__delegate.write_response( constants.HttpStatusCode(status_code), headers=headers) return self._writer
def createDbusProxyObject(bus_name, object_path, bus=None): ''' Create dbus proxy object ''' bus = bus or dbus.SessionBus.get_session() return bus.get_object(bus_name, object_path)
def translate(text, target_lang='en', source_lang=None): """ Use the Google v2 API to translate the text. You had better have set the API key on this function before calling it. """ url_base = 'https://www.googleapis.com/language/translate/v2' params = dict( key=translate.API_key, q=text, target=target_lang, ) if sourc...
def from_credentials(cls: Type[SigningKeyType], salt: Union[str, bytes], password: Union[str, bytes], scrypt_params: Optional[ScryptParams] = None) -> SigningKeyType: """ Create a SigningKey object from credentials :param salt: Secret salt passphrase credential :param password: Secret password credential :param scrypt_...
def save_seedhex_file(self, path: str) -> None: """ Save hexadecimal seed file from seed :param path: Authentication file path """ seedhex = convert_seed_to_seedhex(self.seed) with open(path, 'w') as fh: fh.write(seedhex)
def from_seedhex_file(path: str) -> SigningKeyType: """ Return SigningKey instance from Seedhex file :param str path: Hexadecimal seed file path """ with open(path, 'r') as fh: seedhex = fh.read() return SigningKey.from_seedhex(seedhex)
def from_seedhex(cls: Type[SigningKeyType], seedhex: str) -> SigningKeyType: """ Return SigningKey instance from Seedhex :param str seedhex: Hexadecimal seed string """ regex_seedhex = compile("([0-9a-fA-F]{64})") match = search(regex_seedhex, seedhex) if not match: raise Exception('Error: Bad seed hexadecimal format')...
def from_private_key(path: str) -> SigningKeyType: """ Read authentication file Add public key attribute :param path: Authentication file path """ key = load_key(path) key.pubkey = Base58Encoder.encode(key.vk) return key
def decrypt_seal(self, data: bytes) -> bytes: """ Decrypt bytes data with a curve25519 version of the ed25519 key pair :param data: Encrypted data :return: """ curve25519_public_key = libnacl.crypto_sign_ed25519_pk_to_curve25519(self.vk) curve25519_secret_key = libnacl.crypto_sign_ed25519_sk_to_curve25519(self.sk) retu...
def from_pubsec_file(cls: Type[SigningKeyType], path: str) -> SigningKeyType: """ Return SigningKey instance from Duniter WIF file :param path: Path to WIF file """ with open(path, 'r') as fh: pubsec_content = fh.read() # line patterns regex_pubkey = compile("pub: ([1-9A-HJ-NP-Za-km-z]{43,44})", MULTILINE) regex_signke...
def save_pubsec_file(self, path: str) -> None: """ Save a Duniter PubSec file (PubSec) v1 :param path: Path to file """ # version version = 1 # base58 encode keys base58_signing_key = Base58Encoder.encode(self.sk) base58_public_key = self.pubkey # save file with open(path, 'w') as fh: fh.write( """Type: PubSec Version:...
def from_wif_or_ewif_file(path: str, password: Optional[str] = None) -> SigningKeyType: """ Return SigningKey instance from Duniter WIF or EWIF file :param path: Path to WIF of EWIF file :param password: Password needed for EWIF file """ with open(path, 'r') as fh: wif_content = fh.read() # check data field regex = com...
def from_wif_or_ewif_hex(wif_hex: str, password: Optional[str] = None) -> SigningKeyType: """ Return SigningKey instance from Duniter WIF or EWIF in hexadecimal format :param wif_hex: WIF or EWIF string in hexadecimal format :param password: Password of EWIF encrypted seed """ wif_bytes = Base58Encoder.decode(wif_hex) ...
def from_wif_file(path: str) -> SigningKeyType: """ Return SigningKey instance from Duniter WIF file :param path: Path to WIF file """ with open(path, 'r') as fh: wif_content = fh.read() # check data field regex = compile('Data: ([1-9A-HJ-NP-Za-km-z]+)', MULTILINE) match = search(regex, wif_content) if not match: raise...
def from_wif_hex(cls: Type[SigningKeyType], wif_hex: str) -> SigningKeyType: """ Return SigningKey instance from Duniter WIF in hexadecimal format :param wif_hex: WIF string in hexadecimal format """ wif_bytes = Base58Encoder.decode(wif_hex) if len(wif_bytes) != 35: raise Exception("Error: the size of WIF is invalid") ...
def save_wif_file(self, path: str) -> None: """ Save a Wallet Import Format file (WIF) v1 :param path: Path to file """ # version version = 1 # add format to seed (1=WIF,2=EWIF) seed_fi = b"\x01" + self.seed # calculate checksum sha256_v1 = libnacl.crypto_hash_sha256(seed_fi) sha256_v2 = libnacl.crypto_hash_sha256(sha2...
def from_ewif_file(path: str, password: str) -> SigningKeyType: """ Return SigningKey instance from Duniter EWIF file :param path: Path to EWIF file :param password: Password of the encrypted seed """ with open(path, 'r') as fh: wif_content = fh.read() # check data field regex = compile('Data: ([1-9A-HJ-NP-Za-km-z]+)',...
def from_ewif_hex(cls: Type[SigningKeyType], ewif_hex: str, password: str) -> SigningKeyType: """ Return SigningKey instance from Duniter EWIF in hexadecimal format :param ewif_hex: EWIF string in hexadecimal format :param password: Password of the encrypted seed """ ewif_bytes = Base58Encoder.decode(ewif_hex) if len(e...
aes.decrypt(encryptedhalf1) decryptedhalf2 = aes.decrypt(encryptedhalf2) # XOR seed1 = xor_bytes(decryptedhalf1, derivedhalf1[0:16]) seed2 = xor_bytes(decryptedhalf2, derivedhalf1[16:32]) seed = bytes(seed1 + seed2) # Password Control signer = SigningKey(seed) salt_from_seed = libnacl.crypto_hash_sha256( libnacl.crypto...
def save_ewif_file(self, path: str, password: str) -> None: """ Save an Encrypted Wallet Import Format file (WIF v2) :param path: Path to file :param password: """ # version version = 1 # add version to seed salt = libnacl.crypto_hash_sha256( libnacl.crypto_hash_sha256( Base58Encoder.decode(self.pubkey)))[0:4] # SCRYPT...
fh.write( """Type: EWIF Version: {version} Data: {data}""".format(version=version, data=ewif_key) )
def get(type=None, **ArgConfig): r"""Helps to interactively get user input. Args: desc (str): The description for input. type (type / CustomType): The type of the input (defaults to None). """ ArgConfig.update(type=type) return gatherInput(**reconfigArg(ArgConfig))
def get_product_version(path: typing.Union[str, Path]) -> VersionInfo: """ Get version info from executable Args: path: path to the executable Returns: VersionInfo """ path = Path(path).absolute() pe_info = pefile.PE(str(path)) try: for file_info in pe_info.FileInfo: # pragma: no branch if isinstance(file_info, list): ...
def start(self): """this function will start the queing thread that executes the iterator and feeds jobs into the queue. It also starts the worker threads that just sit and wait for items to appear on the queue. This is a non blocking call, so the executing thread is free to do other things while the other threads work...
def wait_for_completion(self, waiting_func=None): """This is a blocking function call that will wait for the queuing thread to complete. parameters: waiting_func - this function will be called every one second while waiting for the queuing thread to quit. This allows for logging timers, status indicators, etc.""" self....
def blocking_start(self, waiting_func=None): """this function is just a wrapper around the start and wait_for_completion methods. It starts the queuing thread and then waits for it to complete. If run by the main thread, it will detect the KeyboardInterrupt exception (which is what SIGTERM and SIGHUP have been translat...
you may have to send ' 'SIGKILL (kill -9)')
def wait_for_empty_queue(self, wait_log_interval=0, wait_reason=''): """Sit around and wait for the queue to become empty parameters: wait_log_interval - while sleeping, it is helpful if the thread periodically announces itself so that we know that it is still alive. This number is the time in seconds between log entri...
def _responsive_join(self, thread, waiting_func=None): """similar to the responsive sleep, a join function blocks a thread until some other thread dies. If that takes a long time, we'd like to have some indicaition as to what the waiting thread is doing. This method will wait for another thread while calling the waitin...
def _kill_worker_threads(self): """This function coerces the consumer/worker threads to kill themselves. When called by the queuing thread, one death token will be placed on the queue for each thread. Each worker thread is always looking for the death token. When it encounters it, it immediately runs to completion with...
def _queuing_thread_func(self): """This is the function responsible for reading the iterator and putting contents into the queue. It loops as long as there are items in the iterator. Should something go wrong with this thread, or it detects the quit flag, it will calmly kill its workers and then quit itself.""" self.lo...
that we've killed all the workers, we can set the quit flag # to True. This will cause any other threads to die and shut down # the application. Originally, the setting of this flag was at the # start of this "finally" block. However, that meant that the # workers would abort their currently running jobs. In the case o...
def run(self): """The main routine for a thread's work. The thread pulls tasks from the task queue and executes them until it encounters a death token. The death token is a tuple of two Nones. """ try: quit_request_detected = False while True: function, arguments = self.task_queue.get() if function is None: # this allo...
self.config.logger.critical("Failure in task_queue", exc_info=True)
def easter(year, method=EASTER_WESTERN): """ This method was ported from the work done by GM Arts, on top of the algorithm by Claus Tondering, which was based in part on the algorithm of Ouding (1940), as quoted in "Explanatory Supplement to the Astronomical Almanac", P. Kenneth Seidelmann, editor. This algorithm imple...
at: http://users.chariot.net.au/~gmarts/eastalg.htm and http://www.tondering.dk/claus/calendar.html """ if not (1 <= method <= 3): raise ValueError("invalid method") # g - Golden year - 1 # c - Century # h - (23 - Epact) mod 30 # i - Number of days from March 21 to Paschal Full Moon # j - Weekday for PFM (0=Sunday, etc...
# Extra dates to convert Julian to Gregorian date e = 10 if y > 1600: e = e+y//100-16-(y//100-16)//4 else: # New method c = y//100 h = (c-c//4-(8*c+13)//25+19*g+15)%30 i = h-(h//28)*(1-(h//28)*(29//(h+1))*((21-g)//11)) j = (y+y//4+i+2-c+c//4)%7 # p can be from -6 to 56 corresponding to dates 22 March to 23 May # (later...
def patch(module, external=(), internal=()): """ Temporarily monkey-patch dependencies which can be external to, or internal to the supplied module. :param module: Module object :param external: External dependencies to patch (full paths as strings) :param internal: Internal dependencies to patch (short names as string...
patched external # dependencies are accounted for. reload_module(module) # Patch objects in the module itself. with __nested(patch_internal(n) for n in internal): return fn(master_mock, *args, **kwargs) finally: if external: # When all patches have been discarded, reload the module # to bring it back to its original st...
def create(cls, description="", message=""): """ :param description: :type description: str :param message: :type message: str """ instance = cls() instance.revision_id = make_hash_id() instance.release_date = datetime.datetime.now() if len(description) > 0: instance.description = description if len(message) > 0: insta...
def parse(self, rev_string): """ :param rev_string: :type rev_string: str """ elements = rev_string.split(MESSAGE_LINE_SEPARATOR) heading = elements[0] heading_elements = heading.split(" ") self.revision_id = heading_elements[2] datetime_str = "{} {}".format( heading_elements[0], heading_elements[1] ) self.release_date...
def to_markdown(self): """ :return: :rtype: str """ return "## {} {}\n\n{}\n\n{}\n\n".format( self.release_date.strftime(DATETIME_FORMAT), self.revision_id, self.description, self.message )
def _linear_interp(curve, test_x, round_result=False): """ Take a series of points and interpolate between them at ``test_x``. Args: curve (list[tuple]): A list of ``(x, y)`` points sorted in nondecreasing ``x`` value. If multiple points have the same ``x`` value, all but the last will be ignored. test_x (float): The `...
for index in range(len(curve) - 1): # Ignore points which share an x value with the following point if curve[index][0] == curve[index + 1][0]: continue if curve[index][0] <= test_x <= curve[index + 1][0]: slope = ((curve[index + 1][1] - curve[index][1]) / (curve[index + 1][0] - curve[index][0])) y_intercept = curve[ind...
def _clamp_value(value, minimum, maximum): """ Clamp a value to fit between a minimum and a maximum. * If ``value`` is between ``minimum`` and ``maximum``, return ``value`` * If ``value`` is below ``minimum``, return ``minimum`` * If ``value is above ``maximum``, return ``maximum`` Args: value (float or int): The numbe...
def _normal_function(x, mean, variance): """ Find a value in the cumulative distribution function of a normal curve. See https://en.wikipedia.org/wiki/Normal_distribution Args: x (float): Value to feed into the normal function mean (float): Mean of the normal function variance (float): Variance of the normal function R...
def _is_valid_options_weights_list(value): '''Check whether ``values`` is a valid argument for ``weighted_choice``.''' return ((isinstance(value, list)) and len(value) > 1 and (all(isinstance(opt, tuple) and len(opt) == 2 and isinstance(opt[1], (int, float)) for opt in value)))
def bound_weights(weights, minimum=None, maximum=None): """ Bound a weight list so that all outcomes fit within specified bounds. The probability distribution within the ``minimum`` and ``maximum`` values remains the same. Weights in the list with outcomes outside of ``minimum`` and ``maximum`` are removed. If weights ...
maximum (float): Highest allowed outcome for the weight list Returns: list: A list of 2-tuples of form ``(float, float)``, the bounded weight list. Raises: ValueError: if ``maximum < minimum`` Example: >>> weights = [(0, 0), (2, 2), (4, 0)] >>> bound_weights(weights, 1, 3) [(1, 1), (2, 2), (3, 1)] """ # Copy weights to...
else: # Both minimum and maximum are None - the bound list is the same # as the original return bounded_weights # If weights were removed, attach new endpoints where they would have # appeared in the original curve if (bounded_weights[0][0] > weights[0][0] and bounded_weights[0][0] != minimum): bounded_weights.insert(0...
def normal_distribution(mean, variance, minimum=None, maximum=None, weight_count=23): """ Return a list of weights approximating a normal distribution. Args: mean (float): The mean of the distribution variance (float): The variance of the distribution minimum (float): The minimum outcome possible to bound the output di...
(11.73, 0.14), (15.2, 0.0)] """ # Pin 0 to +- 5 sigma as bounds, or minimum and maximum # if they cross +/- sigma standard_deviation = math.sqrt(variance) min_x = (standard_deviation * -5) + mean max_x = (standard_deviation * 5) + mean step = (max_x - min_x) / weight_count current_x = min_x weights = [] while current_x...
def weighted_rand(weights, round_result=False): """ Generate a non-uniform random value based on a list of weight tuples. Treats weights as coordinates for a probability distribution curve and rolls accordingly. Constructs a piece-wise linear curve according to coordinates given in ``weights`` and rolls random values i...
number int: A weighted random number rounded to the nearest ``int`` Example: >>> weighted_rand([(-3, 4), (0, 10), (5, 1)]) # doctest: +SKIP -0.650612268193731 >>> weighted_rand([(-3, 4), (0, 10), (5, 1)]) # doctest: +SKIP -2 """ # If just one weight is passed, simply return the weight's name if len(weights) == 1: retur...
is under the curve if round_result: return int(round(sample[0])) else: return sample[0] attempt_count += 1 else: warnings.warn( 'Point not being found in weighted_rand() after 500000 ' 'attempts, defaulting to a random weight point. ' 'If this happens often, it is probably a bug.') return random.choice(weights)[0]
def weighted_choice(weights, as_index_and_value_tuple=False): """ Generate a non-uniform random choice based on a list of option tuples. Treats each outcome as a discreet unit with a chance to occur. Args: weights (list): a list of options where each option is a tuple of form ``(Any, float)`` corresponding to ``(outcom...
a 2-tuple of form ``(int, Any)`` corresponding to ``(index, value)``. the index as well as value of the item that was picked. Example: >>> choices = [('choice one', 10), ('choice two', 3)] >>> weighted_choice(choices) # doctest: +SKIP # Often will be... 'choice one' >>> weighted_choice(choices, ... as_index_and_value_t...
' 'Probability distribution is undefined.') sample = random.uniform(0, prob_sum) current_pos = 0 i = 0 while i < len(weights): if current_pos <= sample <= (current_pos + weights[i][1]): if as_index_and_value_tuple: return (i, weights[i][0]) else: return weights[i][0] current_pos += weights[i][1] i += 1 else: raise Asse...
def weighted_order(weights): """ Non-uniformally order a list according to weighted priorities. ``weights`` is a list of tuples of form ``(Any, float or int)`` corresponding to ``(item, strength)``. The output list is constructed by repeatedly calling ``weighted_choice()`` on the weights, adding items to the end of the...
repeatedly calling ``weighted_choice()`` on the weights, appending items to the output list as they are picked. Returns: list: the newly ordered list Raises: ProbabilityUndefinedError: if any weight's strength is below 0. Example: >>> weights = [('Probably Earlier', 100), ... ('Probably Middle', 20), ... ('Probably Las...
def tokenize(cls, text, mode='c'): """ Converts text into tokens :param text: string to be tokenized :param mode: split into chars (c) or words (w) """ if mode == 'c': return [ch for ch in text] else: return [w for w in text.split()]
def karbasa(self, result): """ Finding if class probabilities are close to eachother Ratio of the distance between 1st and 2nd class, to the distance between 1st and last class. :param result: The dict returned by LM.calculate() """ probs = result['all_probs'] probs.sort() return float(probs[1] - probs[0]) / float(prob...
def classify(self, text=u''): """ Predicts the Language of a given text. :param text: Unicode text to be classified. """ result = self.calculate(doc_terms=self.tokenize(text)) #return (result['calc_id'], result) return (result['calc_id'], self.karbasa(result))
def is_mention_line(cls, word): """ Detects links and mentions :param word: Token to be evaluated """ if word.startswith('@'): return True elif word.startswith('http://'): return True elif word.startswith('https://'): return True else: return False
def strip_mentions_links(self, text): """ Strips Mentions and Links :param text: Text to be stripped from. """ #print 'Before:', text new_text = [word for word in text.split() if not self.is_mention_line(word)] #print 'After:', u' '.join(new_text) return u' '.join(new_text)
def normalize(self, text): """ Normalizes text. Converts to lowercase, Unicode NFC normalization and removes mentions and links :param text: Text to be normalized. """ #print 'Normalize...\n' text = text.lower() text = unicodedata.normalize('NFC', text) text = self.strip_mentions_links(text) return text
def on_data(self, raw_data): """Called when raw data is received from connection. Override this method if you wish to manually handle the stream data. Return False to stop stream and close connection. """ data = json.loads(raw_data) message_type = data['meta'].get('type') prepare_method = 'prepare_%s' % (message_type) ...
def output_files(self): """Returns all output files from all of the current module's rules.""" for dep in self.subgraph.successors(self.address): dep_rule = self.subgraph.node[dep]['target_obj'] for out_file in dep_rule.output_files: yield out_file
async def write_request( self, method: constants.HttpRequestMethod, *, uri: str="/", authority: Optional[str]=None, scheme: Optional[str]=None, headers: Optional[_HeaderType]=None) -> \ "writers.HttpRequestWriter": """ Send next request to the server. """ return await self._delegate.write_request( method, uri=uri, auth...
def solarzenithangle(time: datetime, glat: float, glon: float, alt_m: float) -> tuple: """ Input: t: scalar or array of datetime """ time = totime(time) obs = EarthLocation(lat=glat*u.deg, lon=glon*u.deg, height=alt_m*u.m) times = Time(time, scale='ut1') sun = get_sun(times) sunobs = sun.transform_to(AltAz(obstime=time...
def check_order(self): """ Performs the check and store the violations in self.violations. :return: boolean indicating the error state """ for feature, info in self.constraints.items(): self._check_feature(feature, info, 'before') self._check_feature(feature, info, 'after') self._check_position(feature, info) return no...
def _check_feature(self, feature, info, mode): """ Private helper method performing the order check. :param feature: the feature to check. :param info: the info dict containing the before and after constraints :param mode: after | before string :return: None """ op = dict( before=operator.gt, after=operator.lt )[mode] ...
def _check_position(self, feature, info): """ Takes the featur and the info dict and checks for the forced position :param feature: :param info: :return: """ pos = info.get('position') if pos is not None: feature_pos = self.get_feature_position(feature) if feature_pos is not None: if feature_pos != pos: message = '{fea...