repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
basilfx/flask-daapserver
examples/SoundcloudServer.py
download_file
python
def download_file(url, file_name): 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 response.ok: raise Exception("Download exception. Will ...
Helper for downloading a remote file to disk.
train
https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/examples/SoundcloudServer.py#L129-L153
null
from daapserver.models import Server, Database, Item, Container, ContainerItem from daapserver import DaapServer, provider import os import sys import gevent import logging import tempfile import requests import soundcloud # Logger instance logger = logging.getLogger(__name__) class RemoteItem(Item): """ A ...
basilfx/flask-daapserver
daapserver/server.py
create_server_app
python
def create_server_app(provider, password=None, cache=True, cache_timeout=3600, debug=False): # Create Flask App app = Flask(__name__, static_folder=None) app.debug = debug # Setup cache if cache: if type(cache) == bool: cache = SimpleCache() else: ...
Create a DAAP server, based around a Flask application. The server requires a content provider, server name and optionally, a password. The content provider should return raw object data. Object responses can be cached. This may dramatically speed up connections for multiple clients. However, this is o...
train
https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/server.py#L49-L472
[ "def daap_wsgi_app(func):\n \"\"\"\n WSGI middleware which will modify the environment and strip 'daap://'\n from the path. This way, Flask can route the request properly.\n \"\"\"\n\n @wraps(func)\n def _inner(environment, start_response):\n if environment[\"PATH_INFO\"].startswith(\"daap:...
from daapserver import responses, utils from flask import Flask, Response, request from werkzeug.contrib.cache import SimpleCache from werkzeug import http from functools import wraps import hashlib import inspect import logging import time # Logger instance logger = logging.getLogger(__name__) # Mapping for query...
draperunner/fjlc
fjlc/preprocessing/filters/filters.py
Filters.string_chain
python
def string_chain(text, filters): if filters is None: return text for filter_function in filters: text = filter_function(text) return text
Chain several filters after each other, applies the filter on the entire string :param text: String to format :param filters: Sequence of filters to apply on String :return: The formatted String
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/preprocessing/filters/filters.py#L25-L38
null
class Filters: USERNAME_PLACEHOLDER = " ||username|| " HASHTAG_PLACEHOLDER = " ||hashtag|| " RTTAG_PLACEHOLDER = " ||rt|| " URL_PLACEHOLDER = " ||url|| " def __init__(self, string_filters, token_filters): self.string_filters = string_filters self.token_filters = token_filters d...
draperunner/fjlc
fjlc/preprocessing/filters/filters.py
Filters.token_chain
python
def token_chain(text, filters): if filters is None: return text sb = "" for token in RegexFilters.WHITESPACE.split(text): if not classifier_options.is_special_class_word(token): token = Filters.string_chain(token, filters) sb += token + " " ...
Chain several filters after each other, applying filters only on non special class tokens as detected by {@link ClassifierOptions#isSpecialClassWord(String)} :param text: String to format :param filters: Sequence of filters to apply to tokens :return: The formatted String
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/preprocessing/filters/filters.py#L41-L60
[ "def string_chain(text, filters):\n \"\"\"\n Chain several filters after each other, applies the filter on the entire string\n :param text: String to format\n :param filters: Sequence of filters to apply on String\n :return: The formatted String\n \"\"\"\n if filters is None:\n return te...
class Filters: USERNAME_PLACEHOLDER = " ||username|| " HASHTAG_PLACEHOLDER = " ||hashtag|| " RTTAG_PLACEHOLDER = " ||rt|| " URL_PLACEHOLDER = " ||url|| " def __init__(self, string_filters, token_filters): self.string_filters = string_filters self.token_filters = token_filters d...
draperunner/fjlc
fjlc/classifier/sentence/lexical_parser.py
lexically_parse_tweet
python
def lexically_parse_tweet(tweet, phrase_tree): lexical_tokens = [] prev = 0 while True: match = RegexFilters.SENTENCE_END_PUNCTUATION.search(tweet[prev:]) if match is None: break span = match.span() sentence = tweet[prev:prev + span[0]] punctuation = mat...
Returns list of LexicalTokens found in tweet. The list contains all the words in original tweet, but are optimally grouped up to form largest matching n-grams from lexicon. If no match is found, token is added as singleton. @param tweet Tweet to lexically parse @param phrase_tree Token tree that c...
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/classifier/sentence/lexical_parser.py#L10-L36
[ "def parse_sentence(sentence, punctuation, phrase_tree):\n sentence_tokens = RegexFilters.WHITESPACE.split(sentence)\n\n tokenized_sentence = phrase_tree.find_optimal_tokenization(sentence_tokens)\n tokens = list(map(lambda s: LexicalToken(s), tokenized_sentence))\n\n if len(tokens) > 0:\n tokens...
""" import com.freva.masteroppgave.lexicon.container.TokenTrie; """ import fjlc.classifier.classifier_options as classifier_options from fjlc.classifier.sentence.lexical_token import LexicalToken from fjlc.preprocessing.filters.regex_filters import RegexFilters def parse_sentence(sentence, punctuation, phrase_tree)...
draperunner/fjlc
fjlc/lexicon/container/token_trie.py
TokenTrie.has_tokens
python
def has_tokens(self, phrase): if len(phrase) == 1 and classifier_options.is_special_class_word(phrase[0]): return True tree = self.root for token in phrase: if not tree.has_child(token): return False tree = tree.get_child(token) retu...
Checks if phrase or sub-phrase exists in the tree. If set of phrases contains phrases such as: "state", "of the" and "state of the art", look up on: "state" returns true, "of" returns null, "of the art" returns false. :param phrase: Phrase or sub-phrase to look up. :type: phrase: list ...
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/lexicon/container/token_trie.py#L27-L50
null
class TokenTrie: def __init__(self, sentences): """ Creates a phrase trie for efficient sub-phrase look up @param sentences List of Strings of all the phrases which are whitespace delimited n-grams """ self.root = TokenTrie.Node() for sentence in sentences: ...
draperunner/fjlc
fjlc/lexicon/container/token_trie.py
TokenTrie.find_tracked_words
python
def find_tracked_words(self, tokens): tracked_words = [] for i in range(len(tokens)): for j in range(i + 1, len(tokens) + 1): phrase = tokens[i:j] status = self.has_tokens(phrase) if status is not None: if status is True: ...
Finds word-ranges all of phrases in tokens stored in TokenTrie :param tokens: Sequence of tokens to find phrases in :type tokens: list of str :return: List of Tokens found in tokens
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/lexicon/container/token_trie.py#L52-L73
[ "def has_tokens(self, phrase):\n \"\"\"\n Checks if phrase or sub-phrase exists in the tree.\n\n If set of phrases contains phrases such as: \"state\", \"of the\" and \"state of the art\", look up on:\n \"state\" returns true, \"of\" returns null, \"of the art\" returns false.\n\n :param phrase: Phra...
class TokenTrie: def __init__(self, sentences): """ Creates a phrase trie for efficient sub-phrase look up @param sentences List of Strings of all the phrases which are whitespace delimited n-grams """ self.root = TokenTrie.Node() for sentence in sentences: ...
draperunner/fjlc
fjlc/lexicon/container/token_trie.py
TokenTrie.find_optimal_allocation
python
def find_optimal_allocation(self, tokens): token_ranges = self.find_tracked_words(tokens) token_ranges.sort() for offset in range(1, len(token_ranges)): to_be_removed = [] for candidate in token_ranges[offset:]: for i in range(offset): ...
Finds longest, non-overlapping word-ranges of phrases in tokens stored in TokenTrie :param tokens: tokens tokenize :type tokens: list of str :return: Optimal allocation of tokens to phrases :rtype: list of TokenTrie.Token
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/lexicon/container/token_trie.py#L75-L98
[ "def find_tracked_words(self, tokens):\n \"\"\"\n Finds word-ranges all of phrases in tokens stored in TokenTrie\n\n :param tokens: Sequence of tokens to find phrases in\n :type tokens: list of str\n :return: List of Tokens found in tokens\n \"\"\"\n tracked_words = []\n\n for i in range(len...
class TokenTrie: def __init__(self, sentences): """ Creates a phrase trie for efficient sub-phrase look up @param sentences List of Strings of all the phrases which are whitespace delimited n-grams """ self.root = TokenTrie.Node() for sentence in sentences: ...
draperunner/fjlc
fjlc/lexicon/container/token_trie.py
TokenTrie.find_optimal_tokenization
python
def find_optimal_tokenization(self, tokens): token_ranges = self.find_optimal_allocation(tokens) tokenized_sentence = [] set_index = 0 for token in token_ranges: while set_index < token.get_start_index(): tokenized_sentence.append(tokens[set_index]) ...
Similar to {@link #findOptimalAllocation(String[])}, but also includes the words not matching any longer n-gram in TokenTrie as singletons. :param tokens: tokens to tokenize :return: Optimal allocation of tokens to phrases, with non matching tokens as singletons.
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/lexicon/container/token_trie.py#L100-L123
[ "def find_optimal_allocation(self, tokens):\n \"\"\"\n Finds longest, non-overlapping word-ranges of phrases in tokens stored in TokenTrie\n\n :param tokens: tokens tokenize\n :type tokens: list of str\n :return: Optimal allocation of tokens to phrases\n :rtype: list of TokenTrie.Token\n \"\"\"...
class TokenTrie: def __init__(self, sentences): """ Creates a phrase trie for efficient sub-phrase look up @param sentences List of Strings of all the phrases which are whitespace delimited n-grams """ self.root = TokenTrie.Node() for sentence in sentences: ...
draperunner/fjlc
fjlc/main.py
LexiconClassifier.classify
python
def classify(self, tweets): if type(tweets) == str: return self.classifier.classify(tweets) return list(map(lambda tweet: self.classifier.classify(tweet), tweets))
Classify tweet or tweets :param tweets: String or array of strings to classify. :return: String or array of strings depicting sentiment. Sentiment can be POSITIVE, NEGATIVE or NEUTRAL.
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/main.py#L78-L87
null
class LexiconClassifier: def __init__(self, lexicon=path.join(path.abspath(path.dirname(__file__)), "res/data/lexicon.pmi.json"), options=path.join(path.abspath(path.dirname(__file__)), "res/data/options.pmi.json"), dictionary=path.join(path.abspath(path.dirname(__...
draperunner/fjlc
fjlc/utils/map_utils.py
normalize_map_between
python
def normalize_map_between(dictionary, norm_min, norm_max): if len(dictionary) < 2: return {} values = list(dictionary.values()) norm_range = norm_max - norm_min map_min = min(values) map_range = max(values) - map_min range_factor = norm_range / float(map_range) normalized_map = {}...
Performs linear normalization of all values in Map between normMin and normMax :param: map Map to normalize values for :param: normMin Smallest normalized value :param: normMax Largest normalized value :return: A new map with double values within [normMin, normMax]
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/utils/map_utils.py#L11-L34
null
def sort_map_by_value(dictionary): """ Sorts Map by value. Map values must implement Comparable. :param dictionary: Map to sort :return: Sorted map """ return sorted(dictionary, key=dictionary.get) """ /** * Sorts map given a comparator * * @param map Map to sort ...
draperunner/fjlc
fjlc/classifier/classifier_options.py
load_options
python
def load_options(file_name): words = from_json(read_entire_file_into_string(file_name)) global options, intensifiers, negators, stop_words options = words["options"] intensifiers = words["intensifiers"] negators = words["negators"] stop_words = words["stopWords"]
Loads options from a JSON file. The file should contain general classifier options, intensifier words with their intensification values, negation words and stop words. @param file_name Name of file containing the options @throws IOException
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/classifier/classifier_options.py#L65-L79
null
import copy from enum import Enum from fjlc.utils.file_utils import read_entire_file_into_string from fjlc.utils.json_utils import from_json options = {} intensifiers = {} negators = set() stop_words = set() def is_stop_word(word): return word in stop_words def is_negation(word): return word in negators ...
draperunner/fjlc
fjlc/lexicon/lexicon_creator.py
LexiconCreator.create_lexicon
python
def create_lexicon(self, data_set_reader, n_grams, min_total_occurrences, min_sentiment_value, filters): counter = self.count_n_grams_py_polarity(data_set_reader, n_grams, filters) lexicon = {} pos = sum(map(lambda i: i.num_positive, counter.values())) neg = sum(map(lambda i: i.num_nega...
Generates sentiment lexicon using PMI on words and classification of context they are in. :param: dataSetReader Dataset containing tweets and their sentiment classification :param: nGrams n-grams to calculate sentiment for (with n>1, singletons are calculated automatically...
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/lexicon/lexicon_creator.py#L15-L52
[ "def count_n_grams_py_polarity(self, data_set_reader, n_grams, filters):\n \"\"\"\n Returns a map of n-gram and the number of times it appeared in positive context and the number of times it\n appeared in negative context in dataset file.\n\n :param data_set_reader: Dataset containing tweets and their c...
class LexiconCreator: def __init__(self): self.data_set_reader = None def create_lexicon(self, data_set_reader, n_grams, min_total_occurrences, min_sentiment_value, filters): """ Generates sentiment lexicon using PMI on words and classification of context they are in. :param...
draperunner/fjlc
fjlc/lexicon/lexicon_creator.py
LexiconCreator.count_n_grams_py_polarity
python
def count_n_grams_py_polarity(self, data_set_reader, n_grams, filters): self.data_set_reader = data_set_reader token_trie = TokenTrie(n_grams) counter = {} # Todo: parallelize for entry in data_set_reader.items(): tweet = filters.apply(entry.get_tweet()) ...
Returns a map of n-gram and the number of times it appeared in positive context and the number of times it appeared in negative context in dataset file. :param data_set_reader: Dataset containing tweets and their classification :param n_grams: n-grams to count occurrences for :param fil...
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/lexicon/lexicon_creator.py#L54-L86
[ "def contains_illegal_word(n_gram):\n return classifier_options.is_stop_word(n_gram[-1] or classifier_options.contains_intensifier(n_gram))\n" ]
class LexiconCreator: def __init__(self): self.data_set_reader = None def create_lexicon(self, data_set_reader, n_grams, min_total_occurrences, min_sentiment_value, filters): """ Generates sentiment lexicon using PMI on words and classification of context they are in. :param...
draperunner/fjlc
fjlc/lexicon/container/adjectives.py
form_adverb_from_adjective
python
def form_adverb_from_adjective(adjective): # If the adjective ends in -able, -ible, or -le, replace the -e with -y if adjective.endswith("able") or adjective.endswith("ible") or adjective.endswith("le"): return adjective[:-1] + "y" # If the adjective ends in -y, replace the y with i and add -ly ...
Forms an adverb from the input adjective, f.ex. "happy" => "happily". Adverbs are generated using rules from: http://www.edufind.com/english-grammar/forming-adverbs-adjectives/ :param adjective: adjective :return: adverb form of the input adjective
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/lexicon/container/adjectives.py#L87-L109
null
VOWELS = "aeiouy" SEPARATOR = "," def get_adverb_and_adjectives(word): if not consists_only_of_alphabetical_characters(word): return [] adjectives = get_comparative_and_superlative_adjectives(word) if len(adjectives) == 0: return [form_adverb_from_adjective(word)] else: adject...
draperunner/fjlc
fjlc/classifier/classifier.py
Classifier.classify
python
def classify(self, tweet): sentiment_value = self.calculate_sentiment(tweet) return Classification.classify_from_thresholds(sentiment_value, classifier_options.get_variable( classifier_opti...
Classifies the tweet into one of three classes (negative, neutral or positive) depending on the sentiment value of the tweet and the thresholds specified in the classifier_options :param tweet: String tweet to classify :return: Sentiment classification (negative, neutral or positive)
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/classifier/classifier.py#L26-L40
[ "def calculate_sentiment(self, tweet):\n if self.filters is not None:\n tweet = self.filters.apply(tweet)\n\n lexical_tokens = lexical_parser.lexically_parse_tweet(tweet, self.phrase_tree)\n for i in range(len(lexical_tokens)):\n token = lexical_tokens[i]\n phrase = token.get_phrase()\...
class Classifier: def __init__(self, lexicon, filters=None): self.lexicon = lexicon self.filters = filters self.phrase_tree = TokenTrie(lexicon.get_subjective_words()) def calculate_sentiment(self, tweet): if self.filters is not None: tweet = self.filters.apply(twee...
draperunner/fjlc
fjlc/utils/json_utils.py
to_json
python
def to_json(data, pretty): if pretty: return json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')) return json.dumps(data)
Converts object to JSON formatted string with typeToken adapter :param data: A dictionary to convert to JSON string :param pretty: A boolean deciding whether or not to pretty format the JSON string :return: The JSON string
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/utils/json_utils.py#L6-L15
null
import json import fjlc.utils.file_utils as file_utils def to_json_file(file, data, pretty): """ Writes object instance in JSON formatted String to file :param file: File to write JSON string ot :param data: Object to convert to JSON :param pretty: Use pretty formatting or not """ json...
draperunner/fjlc
fjlc/utils/json_utils.py
to_json_file
python
def to_json_file(file, data, pretty): json_string = to_json(data, pretty) file_utils.write_to_file(file, json_string)
Writes object instance in JSON formatted String to file :param file: File to write JSON string ot :param data: Object to convert to JSON :param pretty: Use pretty formatting or not
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/utils/json_utils.py#L18-L27
[ "def to_json(data, pretty):\n \"\"\"\n Converts object to JSON formatted string with typeToken adapter\n :param data: A dictionary to convert to JSON string\n :param pretty: A boolean deciding whether or not to pretty format the JSON string\n :return: The JSON string\n \"\"\"\n if pretty:\n ...
import json import fjlc.utils.file_utils as file_utils def to_json(data, pretty): """ Converts object to JSON formatted string with typeToken adapter :param data: A dictionary to convert to JSON string :param pretty: A boolean deciding whether or not to pretty format the JSON string :return: The ...
draperunner/fjlc
fjlc/preprocessing/preprocessors/tweet_n_grams_pmi.py
TweetNGramsPMI.get_frequent_n_grams
python
def get_frequent_n_grams(self, input_reader, n, min_frequency, min_pmi, filters): line_counter = 0 TweetNGramsPMI.tweet_reader = input_reader TweetNGramsPMI.n_gram_tree = self.NGramTree() # Todo: Parallelize for tweet in self.tweet_reader: line_counter += 1 ...
Finds all frequent (and meaningful) n-grams in a file, treating each new line as a new document. :param input_reader: LineReader initialized on file with documents to generate n-grams for :param n: Maximum n-gram length :param min_frequency: Smallest required frequenc...
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/preprocessing/preprocessors/tweet_n_grams_pmi.py#L12-L42
null
class TweetNGramsPMI: tweet_reader = None n_gram_tree = None def get_frequent_n_grams(self, input_reader, n, min_frequency, min_pmi, filters): """ Finds all frequent (and meaningful) n-grams in a file, treating each new line as a new document. :param input_reader: LineReader in...
inspirehep/inspire-utils
inspire_utils/dedupers.py
dedupe_list_of_dicts
python
def dedupe_list_of_dicts(ld): def _freeze(o): """Recursively freezes a dict into an hashable object. Adapted from http://stackoverflow.com/a/21614155/374865. """ if isinstance(o, dict): return frozenset((k, _freeze(v)) for k, v in six.iteritems(o)) elif isinstanc...
Remove duplicates from a list of dictionaries preserving the order. We can't use the generic list helper because a dictionary isn't hashable. Adapted from http://stackoverflow.com/a/9427216/374865.
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/dedupers.py#L43-L70
[ "def _freeze(o):\n \"\"\"Recursively freezes a dict into an hashable object.\n\n Adapted from http://stackoverflow.com/a/21614155/374865.\n \"\"\"\n if isinstance(o, dict):\n return frozenset((k, _freeze(v)) for k, v in six.iteritems(o))\n elif isinstance(o, (list, tuple)):\n return tup...
# -*- coding: utf-8 -*- # # This file is part of INSPIRE. # Copyright (C) 2014-2017 CERN. # # INSPIRE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any ...
inspirehep/inspire-utils
inspire_utils/helpers.py
force_list
python
def force_list(data): if data is None: return [] elif not isinstance(data, (list, tuple, set)): return [data] elif isinstance(data, (tuple, set)): return list(data) return data
Force ``data`` to become a list. You should use this method whenever you don't want to deal with the fact that ``NoneType`` can't be iterated over. For example, instead of writing:: bar = foo.get('bar') if bar is not None: for el in bar: ... you can write::...
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/helpers.py#L30-L70
null
# -*- coding: utf-8 -*- # # This file is part of INSPIRE. # Copyright (C) 2014-2017 CERN. # # INSPIRE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any ...
inspirehep/inspire-utils
inspire_utils/helpers.py
remove_tags
python
def remove_tags(dirty, allowed_tags=(), allowed_trees=(), strip=None): if isinstance(dirty, six.string_types): element = etree.fromstring(u''.join(('<DUMMYROOTTAG>', dirty, '</DUMMYROOTTAG>'))) elif isinstance(dirty, etree._Element): element = dirty else: # assuming scrapy Selector ...
Selectively remove tags. This removes all tags in ``dirty``, stripping also the contents of tags matching the XPath selector in ``strip``, and keeping all tags that are subtags of tags in ``allowed_trees`` and tags in ``allowed_tags``. Args: dirty(Union[str, scrapy.selector.Selector, lxml.etre...
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/helpers.py#L113-L171
null
# -*- coding: utf-8 -*- # # This file is part of INSPIRE. # Copyright (C) 2014-2017 CERN. # # INSPIRE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any ...
inspirehep/inspire-utils
inspire_utils/logging.py
getStackTraceLogger
python
def getStackTraceLogger(*args, **kwargs): logger = logging.getLogger(*args, **kwargs) return StackTraceLogger(logger)
Returns a :class:`StackTrace` logger that wraps a Python logger instance.
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/logging.py#L45-L48
null
# -*- coding: utf-8 -*- # # This file is part of INSPIRE. # Copyright (C) 2014-2017 CERN. # # INSPIRE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any ...
inspirehep/inspire-utils
inspire_utils/logging.py
StackTraceLogger.error
python
def error(self, message, *args, **kwargs): kwargs.setdefault('extra', {}).setdefault('stack', True) return self.logger.error(message, *args, **kwargs)
Log error with stack trace and locals information. By default, enables stack trace information in logging messages, so that stacktrace and locals appear in Sentry.
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/logging.py#L36-L42
null
class StackTraceLogger(object): def __init__(self, logger): self.logger = logger def __getattr__(self, item): """Preserve Python logger interface.""" return getattr(self.logger, item)
inspirehep/inspire-utils
inspire_utils/config.py
load_config
python
def load_config(paths=DEFAULT_CONFIG_PATHS): config = Config() for path in paths: if os.path.isfile(path): config.load_pyfile(path) return config
Attempt to load config from paths, in order. Args: paths (List[string]): list of paths to python files Return: Config: loaded config
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/config.py#L75-L89
[ "def load_pyfile(self, path):\n \"\"\"Load python file as config.\n\n Args:\n path (string): path to the python file\n \"\"\"\n with open(path) as config_file:\n contents = config_file.read()\n try:\n exec(compile(contents, path, 'exec'), self)\n except Exception a...
# -*- coding: utf-8 -*- # # This file is part of INSPIRE. # Copyright (C) 2018 CERN. # # INSPIRE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later...
inspirehep/inspire-utils
inspire_utils/config.py
Config.load_pyfile
python
def load_pyfile(self, path): with open(path) as config_file: contents = config_file.read() try: exec(compile(contents, path, 'exec'), self) except Exception as e: raise MalformedConfig(path, six.text_type(e))
Load python file as config. Args: path (string): path to the python file
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/config.py#L61-L72
null
class Config(dict): def __init__(self, defaults=None): super(Config, self).__init__(defaults or {})
inspirehep/inspire-utils
inspire_utils/record.py
get_value
python
def get_value(record, key, default=None): def getitem(k, v, default): if isinstance(v, string_types): raise KeyError elif isinstance(v, dict): return v[k] elif ']' in k: k = k[:-1].replace('n', '-1') # Work around for list indexes and slices ...
Return item as `dict.__getitem__` but using 'smart queries'. .. note:: Accessing one value in a normal way, meaning d['a'], is almost as fast as accessing a regular dictionary. But using the special name convention is a bit slower than using the regular access: .. code-block:: pyth...
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/record.py#L33-L91
[ "def getitem(k, v, default):\n if isinstance(v, string_types):\n raise KeyError\n elif isinstance(v, dict):\n return v[k]\n elif ']' in k:\n k = k[:-1].replace('n', '-1')\n # Work around for list indexes and slices\n try:\n return v[int(k)]\n except Inde...
# -*- coding: utf-8 -*- # # This file is part of INSPIRE. # Copyright (C) 2014-2017 CERN. # # INSPIRE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any ...
inspirehep/inspire-utils
inspire_utils/name.py
_prepare_nameparser_constants
python
def _prepare_nameparser_constants(): constants = Constants() roman_numeral_suffixes = [u'v', u'vi', u'vii', u'viii', u'ix', u'x', u'xii', u'xiii', u'xiv', u'xv'] titles = [u'Dr', u'Prof', u'Professor', u'Sir', u'Editor', u'Ed', u'Mr', u'Mrs', u'Ms', u'Chair', u'Co...
Prepare nameparser Constants. Remove nameparser's titles and use our own and add as suffixes the roman numerals. Configuration is the same for all names (i.e. instances).
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/name.py#L41-L54
null
# -*- coding: utf-8 -*- # # This file is part of INSPIRE. # Copyright (C) 2014-2017 CERN. # # INSPIRE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any ...
inspirehep/inspire-utils
inspire_utils/name.py
_generate_non_lastnames_variations
python
def _generate_non_lastnames_variations(non_lastnames): if not non_lastnames: return [] # Generate name transformations in place for all non lastnames. Transformations include: # 1. Drop non last name, 2. use initial, 3. use full non lastname for idx, non_lastname in enumerate(non_lastnames): ...
Generate variations for all non-lastnames. E.g. For 'John Richard', this method generates: [ 'John', 'J', 'Richard', 'R', 'John Richard', 'John R', 'J Richard', 'J R', ]
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/name.py#L261-L280
null
# -*- coding: utf-8 -*- # # This file is part of INSPIRE. # Copyright (C) 2014-2017 CERN. # # INSPIRE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any ...
inspirehep/inspire-utils
inspire_utils/name.py
_generate_lastnames_variations
python
def _generate_lastnames_variations(lastnames): if not lastnames: return [] split_lastnames = [split_lastname for lastname in lastnames for split_lastname in lastname.split('-')] lastnames_variations = split_lastnames if len(split_lastnames) > 1: # Generate lastnames concatenation if th...
Generate variations for lastnames. Note: This method follows the assumption that the first last name is the main one. E.g. For 'Caro Estevez', this method generates: ['Caro', 'Caro Estevez']. In the case the lastnames are dashed, it splits them in two.
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/name.py#L283-L301
null
# -*- coding: utf-8 -*- # # This file is part of INSPIRE. # Copyright (C) 2014-2017 CERN. # # INSPIRE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any ...
inspirehep/inspire-utils
inspire_utils/name.py
generate_name_variations
python
def generate_name_variations(name): def _update_name_variations_with_product(set_a, set_b): name_variations.update([ unidecode((names_variation[0] + separator + names_variation[1]).strip(''.join(_LASTNAME_NON_LASTNAME_SEPARATORS))).lower() ...
Generate name variations for a given name. Args: name (six.text_type): The name whose variations are to be generated. Returns: list: All the name variations for the given name. Notes: Uses `unidecode` for doing unicode characters transliteration to ASCII ones. This was chosen so t...
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/name.py#L304-L362
[ "def _generate_non_lastnames_variations(non_lastnames):\n \"\"\"Generate variations for all non-lastnames.\n\n E.g. For 'John Richard', this method generates: [\n 'John', 'J', 'Richard', 'R', 'John Richard', 'John R', 'J Richard', 'J R',\n ]\n \"\"\"\n if not non_lastnames:\n return []\...
# -*- coding: utf-8 -*- # # This file is part of INSPIRE. # Copyright (C) 2014-2017 CERN. # # INSPIRE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any ...
inspirehep/inspire-utils
inspire_utils/name.py
ParsedName.loads
python
def loads(cls, name): if not isinstance(name, six.string_types): raise TypeError(u'arguments to {classname} must be of type {string_types}'.format( classname=cls.__name__, string_types=repr(six.string_types) )) if not name or name.isspace(): raise Valu...
Load a parsed name from a string. Raises: TypeError: when name isn't a type of `six.string_types`. ValueError: when name is empty or None.
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/name.py#L130-L144
null
class ParsedName(object): """Class for representing a name. After construction, the instance exposes the fields exposed by `HumanName` instance, i.e. `title`, `first`, `middle`, `last`, `suffix`. """ constants = _prepare_nameparser_constants() """The default constants configuration for `HumanNa...
inspirehep/inspire-utils
inspire_utils/name.py
ParsedName.dumps
python
def dumps(self): def _is_initial(author_name): return len(author_name) == 1 or u'.' in author_name def _ensure_dotted_initials(author_name): if _is_initial(author_name) \ and u'.' not in author_name: seq = (author_name, u'.') a...
Dump the name to string, after normalizing it.
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/name.py#L146-L200
[ "def _is_initial(author_name):\n return len(author_name) == 1 or u'.' in author_name\n", "def _ensure_dotted_suffixes(author_suffix):\n if u'.' not in author_suffix:\n seq = (author_suffix, u'.')\n author_suffix = u''.join(seq)\n return author_suffix\n", "def _is_roman_numeral(suffix):\n ...
class ParsedName(object): """Class for representing a name. After construction, the instance exposes the fields exposed by `HumanName` instance, i.e. `title`, `first`, `middle`, `last`, `suffix`. """ constants = _prepare_nameparser_constants() """The default constants configuration for `HumanNa...
inspirehep/inspire-utils
inspire_utils/name.py
ParsedName.pprint
python
def pprint(self, initials_only=False): last_name = self.last suffixes = ', ' + self.suffix if self.suffix else '' if initials_only and last_name != u'': first_names = self.first_initials else: first_names = self.first return u'{} {}{}'.format(first_names...
Pretty print the name. Args: initials_only (bool): ``True`` if we want the first names to be displayed with only the initial followed by a dot. ``False`` otherwise. Examples: >>> ParsedName('Lieber, Stanley Martin').pprint() u'Stanley Martin Lieber' ...
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/name.py#L202-L226
null
class ParsedName(object): """Class for representing a name. After construction, the instance exposes the fields exposed by `HumanName` instance, i.e. `title`, `first`, `middle`, `last`, `suffix`. """ constants = _prepare_nameparser_constants() """The default constants configuration for `HumanNa...
inspirehep/inspire-utils
inspire_utils/date.py
earliest_date
python
def earliest_date(dates, full_date=False): min_date = min(PartialDate.loads(date) for date in dates) if not min_date.month and full_date: min_date.month = 1 if not min_date.day and full_date: min_date.day = 1 return min_date.dumps()
Return the earliest among the schema-compliant dates. This is a convenience wrapper around :ref:`PartialDate`, which should be used instead if more features are needed. Args: dates(list): List of dates from which oldest/earliest one will be returned full_date(bool): Adds month and/or day a...
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/date.py#L244-L261
null
# -*- coding: utf-8 -*- # # This file is part of INSPIRE. # Copyright (C) 2014-2017 CERN. # # INSPIRE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any ...
inspirehep/inspire-utils
inspire_utils/urls.py
ensure_scheme
python
def ensure_scheme(url, default_scheme='http'): parsed = urlsplit(url, scheme=default_scheme) if not parsed.netloc: parsed = SplitResult( scheme=parsed.scheme, netloc=parsed.path, path='', query=parsed.query, fragment=parsed.fragment ) ...
Adds a scheme to a url if not present. Args: url (string): a url, assumed to start with netloc default_scheme (string): a scheme to be added Returns: string: URL with a scheme
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/urls.py#L31-L51
null
# -*- coding: utf-8 -*- # # This file is part of INSPIRE. # Copyright (C) 2018 CERN. # # INSPIRE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later...
qwilka/vn-tree
vntree/node.py
Node.add_child
python
def add_child(self, node): if not issubclass(node.__class__, Node): raise TypeError("{}.add_child: arg «node»=«{}», type {} not valid.".format(self.__class__.__name__, node, type(node))) self.childs.append(node) node.parent = self return node
Add a child node to the current node instance. :param node: the child node instance. :type node: Node :returns: The new child node instance. :rtype: Node
train
https://github.com/qwilka/vn-tree/blob/f08106e9c7232d8748d78d1d39b019699a7407dd/vntree/node.py#L142-L154
null
class Node: """Class for creating vntree nodes. :param name: node name :type name: str or None :param parent: The parent node of this node. :type parent: Node or None :param data: Dictionary containing node data. :type data: dict or None :param treedict: Dictionary specifying a complete...
qwilka/vn-tree
vntree/node.py
Node.remove_child
python
def remove_child(self, idx=None, *, name=None, node=None): if (idx and isinstance(idx, int) and -len(self.childs) <= idx < len(self.childs) ): return self.childs.pop(idx) if name and isinstance(name, str): found_node = None for _n in self.childs: ...
Remove a child node from the current node instance. :param idx: Index of child node to be removed. :type idx: int :param name: The first child node found with «name» will be removed. :type name: str :param node: Child node to be removed. :type node: Node :retu...
train
https://github.com/qwilka/vn-tree/blob/f08106e9c7232d8748d78d1d39b019699a7407dd/vntree/node.py#L164-L191
null
class Node: """Class for creating vntree nodes. :param name: node name :type name: str or None :param parent: The parent node of this node. :type parent: Node or None :param data: Dictionary containing node data. :type data: dict or None :param treedict: Dictionary specifying a complete...
qwilka/vn-tree
vntree/node.py
Node._path
python
def _path(self): _path = pathlib.PurePosixPath(self.name) _node = self while _node.parent: _path = _node.parent.name / _path _node = _node.parent _path = pathlib.posixpath.sep / _path return _path.as_posix()
Attribute indicating the absolute node path for this node. Note that the absolute node path starts with a forward slash followed by the root node's name: e.g: `/root.name/child.name/grandchild.name` Warning: it should be noted that use of _path assumes that sibling ...
train
https://github.com/qwilka/vn-tree/blob/f08106e9c7232d8748d78d1d39b019699a7407dd/vntree/node.py#L194-L213
null
class Node: """Class for creating vntree nodes. :param name: node name :type name: str or None :param parent: The parent node of this node. :type parent: Node or None :param data: Dictionary containing node data. :type data: dict or None :param treedict: Dictionary specifying a complete...
qwilka/vn-tree
vntree/node.py
Node._coord
python
def _coord(self): _coord = [] _node = self while _node.parent: _idx = _node.parent.childs.index(_node) _coord.insert(0, _idx) _node = _node.parent return tuple(_coord)
Attribute indicating the tree coordinates for this node. The tree coordinates of a node are expressed as a tuple of the indices of the node and its ancestors, for example: A grandchild node with node path `/root.name/root.childs[2].name/root.childs[2].childs[0].name` would hav...
train
https://github.com/qwilka/vn-tree/blob/f08106e9c7232d8748d78d1d39b019699a7407dd/vntree/node.py#L216-L235
null
class Node: """Class for creating vntree nodes. :param name: node name :type name: str or None :param parent: The parent node of this node. :type parent: Node or None :param data: Dictionary containing node data. :type data: dict or None :param treedict: Dictionary specifying a complete...
qwilka/vn-tree
vntree/node.py
Node.set_data
python
def set_data(self, *keys, value): _datadict = self.data for ii, _key in enumerate(keys): if ii==len(keys)-1: _datadict[_key] = value else: if _key not in _datadict: _datadict[_key] = {} _datadict = _datadict[_key...
Set a value in the instance `data` dict. :param keys: the `data` dict keys referencing the value in the `data` dict. :type keys: str :param value: the value to be set in the `data` dict. Note that `value` is a keyword-only argument. :returns: `True` if successful.
train
https://github.com/qwilka/vn-tree/blob/f08106e9c7232d8748d78d1d39b019699a7407dd/vntree/node.py#L275-L292
null
class Node: """Class for creating vntree nodes. :param name: node name :type name: str or None :param parent: The parent node of this node. :type parent: Node or None :param data: Dictionary containing node data. :type data: dict or None :param treedict: Dictionary specifying a complete...
qwilka/vn-tree
vntree/node.py
Node._root
python
def _root(self): _n = self while _n.parent: _n = _n.parent return _n
Attribute referencing the root node of the tree. :returns: the root node of the tree containing this instance. :rtype: Node
train
https://github.com/qwilka/vn-tree/blob/f08106e9c7232d8748d78d1d39b019699a7407dd/vntree/node.py#L296-L305
null
class Node: """Class for creating vntree nodes. :param name: node name :type name: str or None :param parent: The parent node of this node. :type parent: Node or None :param data: Dictionary containing node data. :type data: dict or None :param treedict: Dictionary specifying a complete...
qwilka/vn-tree
vntree/node.py
Node._ancestors
python
def _ancestors(self): # return list of ancestor nodes starting with self.parent and ending with root _ancestors=[] _n = self while _n.parent: _n = _n.parent _ancestors.append(_n) return _ancestors
Attribute referencing the tree ancestors of the node instance. :returns: list of node ancestors in sequence, first item is the current node instance (`self`), the last item is root. :rtype: list of Node references
train
https://github.com/qwilka/vn-tree/blob/f08106e9c7232d8748d78d1d39b019699a7407dd/vntree/node.py#L309-L322
null
class Node: """Class for creating vntree nodes. :param name: node name :type name: str or None :param parent: The parent node of this node. :type parent: Node or None :param data: Dictionary containing node data. :type data: dict or None :param treedict: Dictionary specifying a complete...
qwilka/vn-tree
vntree/node.py
Node.get_child_by_name
python
def get_child_by_name(self, childname): _childs = [_child for _child in self.childs if _child.name==childname] if len(_childs)>1: logger.warning("%s.get_child_by_name: node:«%s» has more than 1 childnode with name=«%s»." % (self.__class__.__name__, self.name, childname)) if len(_chil...
Get a child node of the current instance by its name. :param childname: the name of the required child node. :type childname: str :returns: the first child node found with name `childname`. :rtype: Node or None
train
https://github.com/qwilka/vn-tree/blob/f08106e9c7232d8748d78d1d39b019699a7407dd/vntree/node.py#L325-L340
null
class Node: """Class for creating vntree nodes. :param name: node name :type name: str or None :param parent: The parent node of this node. :type parent: Node or None :param data: Dictionary containing node data. :type data: dict or None :param treedict: Dictionary specifying a complete...
qwilka/vn-tree
vntree/node.py
Node.get_node_by_path
python
def get_node_by_path(self, path): if path==".": return self elif path.lstrip().startswith((".", "./")) or not isinstance(path, str): logger.warning("%s.get_node_by_path: arg «path»=«%s», not correctly specified." % (self.__class__.__name__, path)) return None ...
Get a node from a node path. Warning: use of this method assumes that sibling nodes have unique names, if this is not assured the `get_node_by_coord` method can be used instead. | Example with absolute node path: | `node.get_node_by_path('/root.name/child.name/gchild.name')` ...
train
https://github.com/qwilka/vn-tree/blob/f08106e9c7232d8748d78d1d39b019699a7407dd/vntree/node.py#L343-L376
null
class Node: """Class for creating vntree nodes. :param name: node name :type name: str or None :param parent: The parent node of this node. :type parent: Node or None :param data: Dictionary containing node data. :type data: dict or None :param treedict: Dictionary specifying a complete...
qwilka/vn-tree
vntree/node.py
Node.get_node_by_coord
python
def get_node_by_coord(self, coord, relative=False): if not isinstance(coord, (list, tuple)) or False in list(map(lambda i: type(i)==int, coord)): logger.warning("%s.get_node_by_coord: node«%s», arg «coord»=«%s», «coord» must be list or tuple of integers." % (self.__class__.__name__, self.name, coord...
Get a node from a node coord. :param coord: the coordinates of the required node. :type coord: tuple or list :param relative: `True` if coord is relative to the node instance, `False` for absolute coordinates. :type relative: bool :returns: the node corresponding to...
train
https://github.com/qwilka/vn-tree/blob/f08106e9c7232d8748d78d1d39b019699a7407dd/vntree/node.py#L379-L402
null
class Node: """Class for creating vntree nodes. :param name: node name :type name: str or None :param parent: The parent node of this node. :type parent: Node or None :param data: Dictionary containing node data. :type data: dict or None :param treedict: Dictionary specifying a complete...
qwilka/vn-tree
vntree/node.py
Node.find_one_node
python
def find_one_node(self, *keys, value, decend=True): if decend: traversal = self else: traversal = self._ancestors for _node in traversal: _val = _node.get_data(*keys) if _val == value: return _node return None
Find a node on the branch of the instance with a `keys=data` item in the `data` dict. Nested values are accessed by specifying the keys in sequence. e.g. `node.get_data("country", "city")` would access `node.data["country"]["city"]` :param keys: the `data` dict key(s) referen...
train
https://github.com/qwilka/vn-tree/blob/f08106e9c7232d8748d78d1d39b019699a7407dd/vntree/node.py#L405-L432
null
class Node: """Class for creating vntree nodes. :param name: node name :type name: str or None :param parent: The parent node of this node. :type parent: Node or None :param data: Dictionary containing node data. :type data: dict or None :param treedict: Dictionary specifying a complete...
qwilka/vn-tree
vntree/node.py
Node.to_texttree
python
def to_texttree(self, indent=3, func=True, symbol='ascii'): if indent<2: indent=2 if func is True: # default func prints node.name func = lambda n: "{}".format(n.name) if isinstance(symbol, (list, tuple)): s_root, s_branch, s_spar, s_fnode = symbol e...
Method returning a text representation of the (sub-)tree rooted at the current node instance (`self`). :param indent: the indentation width for each tree level. :type indent: int :param func: function returning a string representation for each node. e.g. `func=lambda n: s...
train
https://github.com/qwilka/vn-tree/blob/f08106e9c7232d8748d78d1d39b019699a7407dd/vntree/node.py#L435-L507
[ "func = lambda n: \"{}\".format(n.name)\n" ]
class Node: """Class for creating vntree nodes. :param name: node name :type name: str or None :param parent: The parent node of this node. :type parent: Node or None :param data: Dictionary containing node data. :type data: dict or None :param treedict: Dictionary specifying a complete...
qwilka/vn-tree
vntree/node.py
Node.tree_compare
python
def tree_compare(self, othertree, vntree_meta=False): return SequenceMatcher(None, json.dumps(self.to_treedict(vntree_meta=vntree_meta), default=str), json.dumps(othertree.to_treedict(vntree_meta=vntree_meta), default=str) ).ratio()
Compare the (sub-)tree rooted at `self` with another tree. `tree_compare` converts the trees being compared into JSON string representations, and uses `difflib.SequenceMatcher().ratio()` to calculate a measure of the similarity of the strings. :param othertree: the other tree for compa...
train
https://github.com/qwilka/vn-tree/blob/f08106e9c7232d8748d78d1d39b019699a7407dd/vntree/node.py#L553-L570
[ "def to_treedict(self, recursive=True, vntree_meta=True):\n # NOTE: replace vars(self) with self.__dict__ ( and self.__class__.__dict__ ?)\n _dct = {k:v for k, v in vars(self).items() if k not in [\"parent\", \"childs\"]}\n if not vntree_meta and \"_vntree_meta\" in _dct[\"data\"]:\n _dct[\"data\"]....
class Node: """Class for creating vntree nodes. :param name: node name :type name: str or None :param parent: The parent node of this node. :type parent: Node or None :param data: Dictionary containing node data. :type data: dict or None :param treedict: Dictionary specifying a complete...
qwilka/vn-tree
vntree/node.py
Node.savefile
python
def savefile(self, filepath=None): if filepath: self._vnpkl_fpath = os.path.abspath(filepath) # if not _pfpath: # logger.error("%s.save: «%s» file path «%s» not valid." % (self.__class__.__name__, self.name, _pfpath)) # return False try: with open(...
Save (dump) the tree in a pickle file. Note that this method saves the complete tree even when invoked on a non-root node. It is recommended to use the extension `.vnpkl` for this type of file. :param filepath: the file path for the pickle file. If `filepath=None` use `sel...
train
https://github.com/qwilka/vn-tree/blob/f08106e9c7232d8748d78d1d39b019699a7407dd/vntree/node.py#L573-L597
null
class Node: """Class for creating vntree nodes. :param name: node name :type name: str or None :param parent: The parent node of this node. :type parent: Node or None :param data: Dictionary containing node data. :type data: dict or None :param treedict: Dictionary specifying a complete...
qwilka/vn-tree
vntree/node.py
Node.openfile
python
def openfile(cls, filepath): if not os.path.isfile(filepath): logger.error("%s.openfile: arg `filepath`=«%s» not valid." % (cls.__name__, filepath)) return False try: with open(filepath, "rb") as pf: pkldata = pickle.load(pf) rootnode = cls...
Class method that opens (load) a vntree pickle file. :param filepath: the file path for the pickle file. :type filepath: str :returns: root node of tree or `False` if failure. :rtype: Node or bool
train
https://github.com/qwilka/vn-tree/blob/f08106e9c7232d8748d78d1d39b019699a7407dd/vntree/node.py#L601-L620
null
class Node: """Class for creating vntree nodes. :param name: node name :type name: str or None :param parent: The parent node of this node. :type parent: Node or None :param data: Dictionary containing node data. :type data: dict or None :param treedict: Dictionary specifying a complete...
qwilka/vn-tree
vntree/node.py
Node.yaml2tree
python
def yaml2tree(cls, yamltree): if not cls.YAML_setup: cls.setup_yaml() cls.YAML_setup = True if os.path.isfile(yamltree): with open(yamltree) as fh: yaml_data = fh.read() else: yaml_data = yamltree list_of_nodes = yaml.safe_...
Class method that creates a tree from YAML. | # Example yamltree data: | - !Node &root | name: "root node" | parent: null | data: | testpara: 111 | - !Node &child1 | name: "child node" | parent: *root | - !Node &gc1 |...
train
https://github.com/qwilka/vn-tree/blob/f08106e9c7232d8748d78d1d39b019699a7407dd/vntree/node.py#L636-L668
[ "def setup_yaml(cls):\n def yamlnode_constructor(loader, yamlnode) :\n fields = loader.construct_mapping(yamlnode, deep=True)\n return cls(**fields)\n yaml.SafeLoader.add_constructor('!'+cls.__name__, yamlnode_constructor)\n" ]
class Node: """Class for creating vntree nodes. :param name: node name :type name: str or None :param parent: The parent node of this node. :type parent: Node or None :param data: Dictionary containing node data. :type data: dict or None :param treedict: Dictionary specifying a complete...
qwilka/vn-tree
examples/simple_tree.py
make_file_system_tree
python
def make_file_system_tree(root_folder, _parent=None): root_node = Node(os.path.basename(root_folder), _parent) root_node.path = root_folder for item in os.listdir(root_folder): item_path = os.path.join(root_folder, item) if os.path.isfile(item_path): file_node = Node(os.path.base...
This function makes a tree from folders and files.
train
https://github.com/qwilka/vn-tree/blob/f08106e9c7232d8748d78d1d39b019699a7407dd/examples/simple_tree.py#L126-L139
null
import itertools import os import sys # A «class» provides the specification for an «object». # An «object» is a data structure with integrated functions (called «methods» in Python). class Node: """Node class for tree data structure. Ref: https://en.wikipedia.org/wiki/Tree_(data_structure) """ # __i...
mediawiki-utilities/python-mwtypes
mwtypes/user.py
User.initialize
python
def initialize(self, id=None, text=None): self.id = none_or(id, int) self.text = none_or(text, str) """ Username or IP address of the user at the time of the edit : str | None """
Contributing user's identifier : int | None
train
https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/user.py#L28-L37
[ "def none_or(val, func):\n if val is None:\n return None\n else:\n return func(val)\n" ]
class User(jsonable.Type): """ Contributing user metadata. :Attributes: .. autoattribute:: mwtypes.User.id :annotation: = Contributing user's identifier : int | None .. autoattribute:: mwtypes.User.text :annotation: = Username or IP address of the user at the time ...
mediawiki-utilities/python-mwtypes
mwtypes/page.py
Page.initialize
python
def initialize(self, id=None, title=None, namespace=None, redirect=None, restrictions=None): self.id = none_or(id, int) self.title = none_or(title, str) """ Page title (namespace excluded) : `str` """ self.namespace = none_or(namespace, int) "...
Page ID : `int`
train
https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/page.py#L35-L60
[ "def none_or(val, func):\n if val is None:\n return None\n else:\n return func(val)\n" ]
class Page(jsonable.Type): """ Page metadata :Attributes: .. autoattribute:: mwtypes.Page.id :annotation: = Page ID : int .. autoattribute:: mwtypes.Page.title :annotation: = Page title: str .. autoattribute:: mwtypes.Page.namespace :annotation...
mediawiki-utilities/python-mwtypes
mwtypes/files/p7z.py
reader
python
def reader(path): p = subprocess.Popen( ['7z', 'e', '-so', path], stdout=subprocess.PIPE, stderr=file_open(os.devnull, "w") ) return io.TextIOWrapper(p.stdout, encoding='utf-8', errors='replace')
Turns a path to a dump file into a file-like object of (decompressed) XML data assuming that '7z' is installed and will know what to do. :Parameters: path : `str` the path to the dump file to read
train
https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/files/p7z.py#L8-L23
null
import io import os import subprocess file_open = open
mediawiki-utilities/python-mwtypes
mwtypes/log_item.py
Deleted.initialize
python
def initialize(self, action=None, comment=None, user=None, restricted=None): self.action = none_or(action, bool) self.comment = none_or(comment, bool) """ Is the comment of this revision deleted/suppressed? : `bool` """ self.user = none_or(user, bool)...
Is the text of this revision deleted/suppressed? : `bool`
train
https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/log_item.py#L38-L58
[ "def none_or(val, func):\n if val is None:\n return None\n else:\n return func(val)\n" ]
class Deleted(jsonable.Type): """ Represents information about the deleted/suppressed status of a log item and it's associated data. :Attributes: .. autoattribute:: mwtypes.log_item.Deleted.action :annotation: = Is the action of this log item deleted/suppressed? : ...
mediawiki-utilities/python-mwtypes
mwtypes/log_item.py
LogItem.initialize
python
def initialize(self, id, timestamp=None, user=None, page=None, comment=None, type=None, action=None, text=None, params=None, deleted=None): self.id = int(id) self.timestamp = none_or(timestamp, Timestamp) """ log item timestamp : :class:`mwtypes.Ti...
Log item ID : `int`
train
https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/log_item.py#L145-L197
[ "def none_or(val, func):\n if val is None:\n return None\n else:\n return func(val)\n" ]
class LogItem(jsonable.Type): """ Log item metadata :Attributes: .. autoattribute:: mwtypes.LogItem.id :annotation: = Log item ID : int .. autoattribute:: mwtypes.LogItem.timestamp :annotation: = Log item timestamp : mwtypes.Timestamp | No...
mediawiki-utilities/python-mwtypes
mwtypes/timestamp.py
Timestamp.strptime
python
def strptime(cls, string, format): return cls.from_time_struct(time.strptime(string, format))
Constructs a :class:`mw.Timestamp` from an explicitly formatted string. See `<https://docs.python.org/3/library/time.html#time.strftime>`_ for a discussion of formats descriptors. :Parameters: string : str A formatted timestamp format : str ...
train
https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/timestamp.py#L140-L155
null
class Timestamp(jsonable.Type): """ Provides a set of convenience functions for working with MediaWiki timestamps. This class can interpret and return multiple formats as well as perform basic mathematical operations. :Parameters: time_thing : `time.time_struct` | `datetime.datetime` | `st...
mediawiki-utilities/python-mwtypes
mwtypes/timestamp.py
Timestamp.from_time_struct
python
def from_time_struct(cls, time_struct): instance = super().__new__(cls, time_struct) instance.initialize(time_struct) return instance
Constructs a :class:`mw.Timestamp` from a :class:`time.time_struct`. :Parameters: time_struct : :class:`time.time_struct` A time structure :Returns: :class:`mw.Timestamp`
train
https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/timestamp.py#L158-L171
null
class Timestamp(jsonable.Type): """ Provides a set of convenience functions for working with MediaWiki timestamps. This class can interpret and return multiple formats as well as perform basic mathematical operations. :Parameters: time_thing : `time.time_struct` | `datetime.datetime` | `st...
mediawiki-utilities/python-mwtypes
mwtypes/timestamp.py
Timestamp.from_unix
python
def from_unix(cls, seconds): time_struct = datetime.datetime.utcfromtimestamp(seconds).timetuple() return cls.from_time_struct(time_struct)
Constructs a :class:`mw.Timestamp` from a unix timestamp (in seconds since Jan. 1st, 1970 UTC). :Parameters: seconds : int A unix timestamp :Returns: :class:`mw.Timestamp`
train
https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/timestamp.py#L189-L202
null
class Timestamp(jsonable.Type): """ Provides a set of convenience functions for working with MediaWiki timestamps. This class can interpret and return multiple formats as well as perform basic mathematical operations. :Parameters: time_thing : `time.time_struct` | `datetime.datetime` | `st...
mediawiki-utilities/python-mwtypes
mwtypes/timestamp.py
Timestamp.from_string
python
def from_string(cls, string): if type(string) == bytes: string = str(string, 'utf8') else: string = str(string) try: return cls.strptime(string, SHORT_MW_TIME_STRING) except ValueError as e: try: return cls.strptime(string,...
Constructs a :class:`mw.Timestamp` from a MediaWiki formatted string. This method is provides a convenient way to construct from common MediaWiki timestamp formats. E.g., ``%Y%m%d%H%M%S`` and ``%Y-%m-%dT%H:%M:%SZ``. :Parameters: string : str A formatted times...
train
https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/timestamp.py#L205-L236
null
class Timestamp(jsonable.Type): """ Provides a set of convenience functions for working with MediaWiki timestamps. This class can interpret and return multiple formats as well as perform basic mathematical operations. :Parameters: time_thing : `time.time_struct` | `datetime.datetime` | `st...
mediawiki-utilities/python-mwtypes
mwtypes/files/functions.py
extract_extension
python
def extract_extension(path): filename = os.path.basename(path) parts = filename.split(".") if len(parts) == 1: return filename, None else: return ".".join(parts[:-1]), parts[-1]
Reads a file path and returns the extension or None if the path contains no extension. :Parameters: path : str A filesystem path
train
https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/files/functions.py#L32-L46
null
import bz2 import gzip import io import os from . import p7z from ..errors import FileTypeError FILE_READERS = { 'gz': lambda fn: gzip.open(fn, 'rt', encoding='utf-8', errors='replace'), 'bz2': lambda fn: bz2.open(fn, 'rt', encoding='utf-8', errors='replace'), '7z': p7z.reader, 'json': lambda fn: open...
mediawiki-utilities/python-mwtypes
mwtypes/files/functions.py
normalize_path
python
def normalize_path(path_or_f): if hasattr(path_or_f, "read"): return path_or_f else: path = path_or_f path = os.path.expanduser(path) # Check if exists and is a file if os.path.isdir(path): raise IsADirectoryError("Is a directory: {0}".format(path)) elif not os.path.isf...
Verifies that a file exists at a given path and that the file has a known extension type. :Parameters: path_or_f : `str` | `file` the path to a dump file or a file handle
train
https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/files/functions.py#L49-L78
null
import bz2 import gzip import io import os from . import p7z from ..errors import FileTypeError FILE_READERS = { 'gz': lambda fn: gzip.open(fn, 'rt', encoding='utf-8', errors='replace'), 'bz2': lambda fn: bz2.open(fn, 'rt', encoding='utf-8', errors='replace'), '7z': p7z.reader, 'json': lambda fn: open...
mediawiki-utilities/python-mwtypes
mwtypes/files/functions.py
reader
python
def reader(path_or_f): if hasattr(path_or_f, "read"): return path_or_f else: path = path_or_f path = normalize_path(path) _, extension = extract_extension(path) reader_func = FILE_READERS[extension] return reader_func(path)
Turns a path to a compressed file into a file-like object of (decompressed) data. :Parameters: path : `str` the path to the dump file to read
train
https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/files/functions.py#L90-L109
[ "def normalize_path(path_or_f):\n \"\"\"\n Verifies that a file exists at a given path and that the file has a\n known extension type.\n\n :Parameters:\n path_or_f : `str` | `file`\n the path to a dump file or a file handle\n\n \"\"\"\n if hasattr(path_or_f, \"read\"):\n r...
import bz2 import gzip import io import os from . import p7z from ..errors import FileTypeError FILE_READERS = { 'gz': lambda fn: gzip.open(fn, 'rt', encoding='utf-8', errors='replace'), 'bz2': lambda fn: bz2.open(fn, 'rt', encoding='utf-8', errors='replace'), '7z': p7z.reader, 'json': lambda fn: open...
mediawiki-utilities/python-mwtypes
mwtypes/files/functions.py
writer
python
def writer(path): filename, extension = extract_extension(path) if extension in FILE_WRITERS: writer_func = FILE_WRITERS[extension] return writer_func(path) else: raise RuntimeError("Output compression {0} not supported. Type {1}" .format(extension, tuple(...
Creates a compressed file writer from for a path with a specified compression type.
train
https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/files/functions.py#L118-L129
[ "def extract_extension(path):\n \"\"\"\n Reads a file path and returns the extension or None if the path\n contains no extension.\n\n :Parameters:\n path : str\n A filesystem path\n \"\"\"\n filename = os.path.basename(path)\n parts = filename.split(\".\")\n if len(parts) =...
import bz2 import gzip import io import os from . import p7z from ..errors import FileTypeError FILE_READERS = { 'gz': lambda fn: gzip.open(fn, 'rt', encoding='utf-8', errors='replace'), 'bz2': lambda fn: bz2.open(fn, 'rt', encoding='utf-8', errors='replace'), '7z': p7z.reader, 'json': lambda fn: open...
mediawiki-utilities/python-mwtypes
mwtypes/revision.py
Deleted.initialize
python
def initialize(self, text=None, comment=None, user=None, restricted=None): self.text = none_or(text, bool) self.comment = none_or(comment, bool) """ Is the comment of this revision deleted/suppressed? : `bool` """ self.user = none_or(user, bool) """ Is t...
Is the text of this revision deleted/suppressed? : `bool`
train
https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/revision.py#L39-L58
[ "def none_or(val, func):\n if val is None:\n return None\n else:\n return func(val)\n" ]
class Deleted(jsonable.Type): """ Represents information about the deleted/suppressed status of a revision and it's associated data. :Attributes: .. autoattribute:: mwtypes.revision.Deleted.text :annotation: = Is the text of this revision deleted/suppressed? : ...
mediawiki-utilities/python-mwtypes
mwtypes/revision.py
Deleted.from_int
python
def from_int(cls, integer): bin_string = bin(integer) return cls( text=len(bin_string) >= 1 and bin_string[-1] == "1", comment=len(bin_string) >= 2 and bin_string[-2] == "1", user=len(bin_string) >= 3 and bin_string[-3] == "1", restricted=len(bin_string) ...
Constructs a `Deleted` using the `tinyint` value of the `rev_deleted` column of the `revision` MariaDB table. * DELETED_TEXT = 1 * DELETED_COMMENT = 2 * DELETED_USER = 4 * DELETED_RESTRICTED = 8
train
https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/revision.py#L61-L78
null
class Deleted(jsonable.Type): """ Represents information about the deleted/suppressed status of a revision and it's associated data. :Attributes: .. autoattribute:: mwtypes.revision.Deleted.text :annotation: = Is the text of this revision deleted/suppressed? : ...
mediawiki-utilities/python-mwtypes
mwtypes/revision.py
Revision.initialize
python
def initialize(self, id, timestamp=None, user=None, page=None, minor=None, comment=None, text=None, bytes=None, sha1=None, parent_id=None, model=None, format=None, deleted=None): self.id = none_or(id, int) self.timestamp = none_or(timestamp, Timestamp) """...
Revision ID : `int`
train
https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/revision.py#L136-L203
[ "def none_or(val, func):\n if val is None:\n return None\n else:\n return func(val)\n" ]
class Revision(jsonable.Type): """ Revision metadata and text :Attributes: .. autoattribute:: mwtypes.Revision.id :annotation: = Revision ID : int .. autoattribute:: mwtypes.Revision.timestamp :annotation: = Revision timestamp : mwtypes.Ti...
mediawiki-utilities/python-mwtypes
mwtypes/upload.py
Upload.initialize
python
def initialize(self, timestamp=None, user=None, comment=None, filename=None, source=None, size=None): self.timestamp = none_or(timestamp, Timestamp) self.user = none_or(user, User) """ Contributing user metadata : :class:`~mwtypes.User` """ self.comm...
Upload timestamp : mwtypes.Timestamp | None
train
https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/upload.py#L40-L71
[ "def none_or(val, func):\n if val is None:\n return None\n else:\n return func(val)\n" ]
class Upload(jsonable.Type): """ Upload event metadata :Attributes: .. autoattribute:: mwtypes.Upload.timestamp :annotation: = Upload timestamp : mwtypes.Timestamp | None .. autoattribute:: mwtypes.Upload.user :annotation: = Contributing user metadata : mwtypes.User...
hamperbot/hamper
hamper/commander.py
CommanderProtocol.signedOn
python
def signedOn(self): log.info("Signed on as %s.", self.nickname) if not self.password: # We aren't wating for auth, join all the channels self.joinChannels() else: self.msg("NickServ", "IDENTIFY %s" % self.password)
Called after successfully signing on to the server.
train
https://github.com/hamperbot/hamper/blob/6f841ec4dcc319fdd7bb3ca1f990e3b7a458771b/hamper/commander.py#L57-L64
[ "def joinChannels(self):\n self.dispatch('presence', 'signedOn')\n for c in self.factory.channels:\n self.join(*c)\n" ]
class CommanderProtocol(irc.IRCClient): """Interacts with a single server, and delegates to the plugins.""" # #### Properties ##### @property def nickname(self): return self.factory.nickname @property def password(self): return self.factory.password @property def db(se...
hamperbot/hamper
hamper/commander.py
CommanderProtocol.process_action
python
def process_action(self, raw_user, channel, raw_message): log.info("%s %s %s", channel, raw_user, raw_message) if not raw_user: # ignore server messages return # This monster of a regex extracts msg and target from a message, where # the target may not be there,...
Called when a message is received from a channel or user.
train
https://github.com/hamperbot/hamper/blob/6f841ec4dcc319fdd7bb3ca1f990e3b7a458771b/hamper/commander.py#L88-L144
[ "def dispatch(self, category, func, *args):\n \"\"\"Dispatch an event to all listening plugins.\"\"\"\n self.factory.loader.runPlugins(category, func, self, *args)\n" ]
class CommanderProtocol(irc.IRCClient): """Interacts with a single server, and delegates to the plugins.""" # #### Properties ##### @property def nickname(self): return self.factory.nickname @property def password(self): return self.factory.password @property def db(se...
hamperbot/hamper
hamper/commander.py
CommanderProtocol.connectionLost
python
def connectionLost(self, reason): self.factory.loader.db.session.commit() if reactor.running: reactor.stop()
Called when the connection is lost to the server.
train
https://github.com/hamperbot/hamper/blob/6f841ec4dcc319fdd7bb3ca1f990e3b7a458771b/hamper/commander.py#L146-L150
null
class CommanderProtocol(irc.IRCClient): """Interacts with a single server, and delegates to the plugins.""" # #### Properties ##### @property def nickname(self): return self.factory.nickname @property def password(self): return self.factory.password @property def db(se...
hamperbot/hamper
hamper/commander.py
CommanderProtocol.userKicked
python
def userKicked(self, kickee, channel, kicker, message): self.dispatch('population', 'userKicked', kickee, channel, kicker, message)
Called when I see another user get kicked.
train
https://github.com/hamperbot/hamper/blob/6f841ec4dcc319fdd7bb3ca1f990e3b7a458771b/hamper/commander.py#L164-L167
[ "def dispatch(self, category, func, *args):\n \"\"\"Dispatch an event to all listening plugins.\"\"\"\n self.factory.loader.runPlugins(category, func, self, *args)\n" ]
class CommanderProtocol(irc.IRCClient): """Interacts with a single server, and delegates to the plugins.""" # #### Properties ##### @property def nickname(self): return self.factory.nickname @property def password(self): return self.factory.password @property def db(se...
hamperbot/hamper
hamper/commander.py
CommanderProtocol.dispatch
python
def dispatch(self, category, func, *args): self.factory.loader.runPlugins(category, func, self, *args)
Dispatch an event to all listening plugins.
train
https://github.com/hamperbot/hamper/blob/6f841ec4dcc319fdd7bb3ca1f990e3b7a458771b/hamper/commander.py#L191-L193
null
class CommanderProtocol(irc.IRCClient): """Interacts with a single server, and delegates to the plugins.""" # #### Properties ##### @property def nickname(self): return self.factory.nickname @property def password(self): return self.factory.password @property def db(se...
hamperbot/hamper
hamper/commander.py
PluginLoader.dependencies_satisfied
python
def dependencies_satisfied(self, plugin): for depends in plugin.dependencies: if depends not in self.config['plugins']: log.error("{0} depends on {1}, but {1} wasn't in the " "config file. To use {0}, install {1} and add " "it to th...
Checks whether a plugin's dependencies are satisfied. Logs an error if there is an unsatisfied dependencies Returns: Bool
train
https://github.com/hamperbot/hamper/blob/6f841ec4dcc319fdd7bb3ca1f990e3b7a458771b/hamper/commander.py#L333-L346
null
class PluginLoader(object): """ I am a repository for plugins. I understand how to load plugins and how to enumerate the plugins I've loaded. Additionally, I can store configuration data for plugins. Think of me as the piece of code that isolates plugin state from the details of the network. ...
hamperbot/hamper
hamper/commander.py
PluginLoader.runPlugins
python
def runPlugins(self, category, func, protocol, *args): # Plugins are already sorted by priority for plugin in self.plugins: # If a plugin throws an exception, we should catch it gracefully. try: event_listener = getattr(plugin, func) except AttributeEr...
Run the specified set of plugins against a given protocol.
train
https://github.com/hamperbot/hamper/blob/6f841ec4dcc319fdd7bb3ca1f990e3b7a458771b/hamper/commander.py#L348-L368
null
class PluginLoader(object): """ I am a repository for plugins. I understand how to load plugins and how to enumerate the plugins I've loaded. Additionally, I can store configuration data for plugins. Think of me as the piece of code that isolates plugin state from the details of the network. ...
hamperbot/hamper
hamper/plugins/karma_adv.py
KarmaAdv.message
python
def message(self, bot, comm): super(KarmaAdv, self).message(bot, comm) # No directed karma giving or taking if not comm['directed'] and not comm['pm']: msg = comm['message'].strip().lower() # use the magic above words = self.regstr.findall(msg) # ...
Check for strings ending with 2 or more '-' or '+'
train
https://github.com/hamperbot/hamper/blob/6f841ec4dcc319fdd7bb3ca1f990e3b7a458771b/hamper/plugins/karma_adv.py#L79-L99
[ "def message(self, bot, comm):\n super(ChatCommandPlugin, self).message(bot, comm)\n for cmd in self.commands:\n stop = cmd.message(bot, comm)\n if stop:\n return stop\n", "def modify_karma(self, words):\n \"\"\"\n Given a regex object, look through the groups and modify karma...
class KarmaAdv(ChatCommandPlugin): '''Give, take, and scoreboard Internet Points''' """ Hamper will look for lines that end in ++ or -- and modify that user's karma value accordingly as well as track a few other stats about users NOTE: The user is just a string, this really could be anything...lik...
hamperbot/hamper
hamper/plugins/karma_adv.py
KarmaAdv.modify_karma
python
def modify_karma(self, words): # 'user': karma k = defaultdict(int) if words: # For loop through all of the group members for word_tuple in words: word = word_tuple[0] ending = word[-1] # This will either end with a - or +...
Given a regex object, look through the groups and modify karma as necessary
train
https://github.com/hamperbot/hamper/blob/6f841ec4dcc319fdd7bb3ca1f990e3b7a458771b/hamper/plugins/karma_adv.py#L101-L131
null
class KarmaAdv(ChatCommandPlugin): '''Give, take, and scoreboard Internet Points''' """ Hamper will look for lines that end in ++ or -- and modify that user's karma value accordingly as well as track a few other stats about users NOTE: The user is just a string, this really could be anything...lik...
hamperbot/hamper
hamper/plugins/karma_adv.py
KarmaAdv.update_db
python
def update_db(self, giver, receiverkarma): for receiver in receiverkarma: if receiver != giver: urow = KarmaStatsTable( ude(giver), ude(receiver), receiverkarma[receiver]) self.db.session.add(urow) self.db.session.commit()
Record a the giver of karma, the receiver of karma, and the karma amount. Typically the count will be 1, but it can be any positive or negative integer.
train
https://github.com/hamperbot/hamper/blob/6f841ec4dcc319fdd7bb3ca1f990e3b7a458771b/hamper/plugins/karma_adv.py#L133-L145
[ "def ude(s):\n return s.decode('utf-8')\n" ]
class KarmaAdv(ChatCommandPlugin): '''Give, take, and scoreboard Internet Points''' """ Hamper will look for lines that end in ++ or -- and modify that user's karma value accordingly as well as track a few other stats about users NOTE: The user is just a string, this really could be anything...lik...
hamperbot/hamper
hamper/plugins/karma.py
Karma.update_db
python
def update_db(self, userkarma, username): kt = self.db.session.query(KarmaTable) for user in userkarma: if user != username: # Modify the db accourdingly urow = kt.filter(KarmaTable.user == ude(user)).first() # If the user doesn't exist, creat...
Change the users karma by the karma amount (either 1 or -1)
train
https://github.com/hamperbot/hamper/blob/6f841ec4dcc319fdd7bb3ca1f990e3b7a458771b/hamper/plugins/karma.py#L142-L157
[ "def ude(s):\n return s.decode('utf-8')\n" ]
class Karma(ChatCommandPlugin): '''Give, take, and scoreboard Internet Points''' """ Hamper will look for lines that end in ++ or -- and modify that user's karma value accordingly !karma --top: shows (at most) the top 5 !karma --bottom: shows (at most) the bottom 5 !karma <username>: displ...
hamperbot/hamper
hamper/plugins/commands.py
Dice.roll
python
def roll(cls, num, sides, add): rolls = [] for i in range(num): rolls.append(random.randint(1, sides)) rolls.append(add) return rolls
Rolls a die of sides sides, num times, sums them, and adds add
train
https://github.com/hamperbot/hamper/blob/6f841ec4dcc319fdd7bb3ca1f990e3b7a458771b/hamper/plugins/commands.py#L173-L179
null
class Dice(ChatCommandPlugin): """Random dice rolls!""" name = 'dice' priority = 5 def setup(self, *args, **kwargs): super(Dice, self).setup(*args, **kwargs) log.info('dice setup') @classmethod class DiceCommand(Command): name = 'dice' regex = '^(\d*)d(?:ice)?...
hamperbot/hamper
hamper/plugins/foods.py
FoodsPlugin.describe_ingredient
python
def describe_ingredient(self): resp = random.choice(ingredients) if random.random() < .2: resp = random.choice(foodqualities) + " " + resp if random.random() < .2: resp += " with " + self.describe_additive() return resp
apple. tart apple with vinegar.
train
https://github.com/hamperbot/hamper/blob/6f841ec4dcc319fdd7bb3ca1f990e3b7a458771b/hamper/plugins/foods.py#L279-L286
null
class FoodsPlugin(ChatPlugin): """Even robots can get peckish""" name = 'foods' priority = 0 def setup(self, *args): pass def articleize(self, noun): if random.random() < .3: noun = random.choice(foodunits) + " of " + noun if noun[0] in ['a', 'e', 'i', 'o', 'u'...
hamperbot/hamper
hamper/plugins/foods.py
FoodsPlugin.describe_additive
python
def describe_additive(self): resp = random.choice(additives) if random.random() < .2: resp = random.choice(foodqualities) + ' ' + resp if random.random() < .01: resp = self.articleize(resp) return resp
vinegar. spicy vinegar. a spicy vinegar.
train
https://github.com/hamperbot/hamper/blob/6f841ec4dcc319fdd7bb3ca1f990e3b7a458771b/hamper/plugins/foods.py#L288-L295
null
class FoodsPlugin(ChatPlugin): """Even robots can get peckish""" name = 'foods' priority = 0 def setup(self, *args): pass def articleize(self, noun): if random.random() < .3: noun = random.choice(foodunits) + " of " + noun if noun[0] in ['a', 'e', 'i', 'o', 'u'...
hamperbot/hamper
hamper/plugins/foods.py
FoodsPlugin.describe_dish
python
def describe_dish(self): resp = random.choice(foodpreparations) if random.random() < .85: resp = self.describe_ingredient() + ' ' + resp if random.random() < .2: resp = self.describe_ingredient() + ' and ' + resp if random.random() < .2: ...
a burrito. a lettuce burrito with ketchup and raspberry.
train
https://github.com/hamperbot/hamper/blob/6f841ec4dcc319fdd7bb3ca1f990e3b7a458771b/hamper/plugins/foods.py#L297-L310
[ "def describe_ingredient(self):\n \"\"\" apple. tart apple with vinegar. \"\"\"\n resp = random.choice(ingredients)\n if random.random() < .2:\n resp = random.choice(foodqualities) + \" \" + resp\n if random.random() < .2:\n resp += \" with \" + self.describe_additive()\n return resp\n"...
class FoodsPlugin(ChatPlugin): """Even robots can get peckish""" name = 'foods' priority = 0 def setup(self, *args): pass def articleize(self, noun): if random.random() < .3: noun = random.choice(foodunits) + " of " + noun if noun[0] in ['a', 'e', 'i', 'o', 'u'...
hamperbot/hamper
hamper/config.py
replace_env_vars
python
def replace_env_vars(conf): d = deepcopy(conf) for key, value in d.items(): if type(value) == dict: d[key] = replace_env_vars(value) elif type(value) == str: if value[0] == '$': var_name = value[1:] d[key] = os.environ[var_name] return...
Fill `conf` with environment variables, where appropriate. Any value of the from $VAR will be replaced with the environment variable VAR. If there are sub dictionaries, this function will recurse. This will preserve the original dictionary, and return a copy.
train
https://github.com/hamperbot/hamper/blob/6f841ec4dcc319fdd7bb3ca1f990e3b7a458771b/hamper/config.py#L36-L53
[ "def replace_env_vars(conf):\n \"\"\"Fill `conf` with environment variables, where appropriate.\n\n Any value of the from $VAR will be replaced with the environment variable\n VAR. If there are sub dictionaries, this function will recurse.\n\n This will preserve the original dictionary, and return a cop...
import os import sys from copy import deepcopy import yaml def load(): try: with open('hamper.conf') as config_file: config = yaml.load(config_file) except IOError: config = {} config = replace_env_vars(config) # Fill in data from the env: for k, v in os.environ.item...
hamperbot/hamper
hamper/plugins/questions.py
YesNoPlugin.setup
python
def setup(self, *args): responses = [ ('Yes.', 'eq'), ('How should I know?', 'eq'), ('Try asking a human', 'eq'), ('Eww.', 'eq'), ('You\'d just do the opposite of whatever I tell you', 'eq'), ('No.', 'eq'), ('Nope.', 'eq'), ...
Set up the list of responses, with weights. If the weight of a response is 'eq', it will be assigned a value that splits what is left after everything that has a number is assigned. If it's weight is some fraction of 'eq' (ie: 'eq/2' or 'eq/3'), then it will be assigned 1/2, 1/3, etc of ...
train
https://github.com/hamperbot/hamper/blob/6f841ec4dcc319fdd7bb3ca1f990e3b7a458771b/hamper/plugins/questions.py#L549-L605
null
class YesNoPlugin(ChatPlugin): name = 'yesno' priority = -1 def shouldq(self, bot, comm): resp = random.choice(obliques) bot.reply(comm, '{0}: {1}'.format(comm['user'], resp)) return True def articleize(self, noun): if random.random() < .3: noun = random.c...
aleontiev/dj
dj/application.py
Application.parse_application_name
python
def parse_application_name(setup_filename): with open(setup_filename, 'rt') as setup_file: fst = RedBaron(setup_file.read()) for node in fst: if ( node.type == 'atomtrailers' and str(node.name) == 'setup' ): ...
Parse a setup.py file for the name. Returns: name, or None
train
https://github.com/aleontiev/dj/blob/0612d442fdd8d472aea56466568b9857556ecb51/dj/application.py#L67-L89
null
class Application(object): def __init__( self, stdout=None, directory=None ): self.stdout = stdout or _stdout current = os.getcwd() nearest_setup_file = find_nearest(current, 'setup.py') self.directory = directory or ( os.path.dirname( ...
aleontiev/dj
dj/application.py
Application.build
python
def build(self): if self.exists: self._build( 'requirements', self.requirements_last_modified, 'pip install -U -r %s' % self.requirements_file ) try: self._build( 'requirements (dev)', ...
Builds the app in the app's environment. Only builds if the build is out-of-date and is non-empty. Builds in 3 stages: requirements, dev requirements, and app. pip is used to install requirements, and setup.py is used to install the app itself. Raises: ValidationErr...
train
https://github.com/aleontiev/dj/blob/0612d442fdd8d472aea56466568b9857556ecb51/dj/application.py#L224-L270
[ "def yellow(message):\n return click.style(message, fg='yellow', bold=True)\n", "def _build(self, key, last_modified, cmd, verbose=True):\n token = self._get_build_token(key)\n last_built = get_last_touched(token)\n if not last_built or last_built < last_modified:\n self.stdout.write(style.form...
class Application(object): def __init__( self, stdout=None, directory=None ): self.stdout = stdout or _stdout current = os.getcwd() nearest_setup_file = find_nearest(current, 'setup.py') self.directory = directory or ( os.path.dirname( ...
aleontiev/dj
dj/application.py
Application.generate
python
def generate(self, blueprint, context, interactive=True): if not isinstance(blueprint, Blueprint): bp = self.blueprints.get(blueprint) if not bp: raise ValueError('%s is not a valid blueprint' % blueprint) blueprint = bp self.stdout.write( ...
Generate a blueprint within this application.
train
https://github.com/aleontiev/dj/blob/0612d442fdd8d472aea56466568b9857556ecb51/dj/application.py#L280-L304
[ "def format_command(a, b='', prefix=''):\n return (\n white(prefix) +\n blue('%s: ' % a) +\n white(b)\n )\n", "def refresh(self):\n if hasattr(self, '_name'):\n del self._name\n if hasattr(self, '_blueprints'):\n del self._blueprints\n if hasattr(self, '_addons'):...
class Application(object): def __init__( self, stdout=None, directory=None ): self.stdout = stdout or _stdout current = os.getcwd() nearest_setup_file = find_nearest(current, 'setup.py') self.directory = directory or ( os.path.dirname( ...
aleontiev/dj
dj/application.py
Application.add
python
def add(self, addon, dev=False, interactive=True): dependencies = self.get_dependency_manager(dev=dev) other_dependencies = self.get_dependency_manager(dev=not dev) existing = dependencies.get(addon) self.stdout.write(style.format_command('Adding', addon)) dependencies.add(addon)...
Add a new dependency and install it.
train
https://github.com/aleontiev/dj/blob/0612d442fdd8d472aea56466568b9857556ecb51/dj/application.py#L314-L347
[ "def format_command(a, b='', prefix=''):\n return (\n white(prefix) +\n blue('%s: ' % a) +\n white(b)\n )\n", "def yellow(message):\n return click.style(message, fg='yellow', bold=True)\n", "def red(message):\n return click.style(message, fg='red', bold=True)\n", "def refresh(...
class Application(object): def __init__( self, stdout=None, directory=None ): self.stdout = stdout or _stdout current = os.getcwd() nearest_setup_file = find_nearest(current, 'setup.py') self.directory = directory or ( os.path.dirname( ...
aleontiev/dj
dj/application.py
Application.remove
python
def remove(self, addon, dev=False): dependencies = self.get_dependency_manager(dev=dev) other_dependencies = self.get_dependency_manager(dev=not dev) self.stdout.write(style.format_command('Removing', addon)) removed = dependencies.remove(addon, warn=False) if not removed: ...
Remove a dependency and uninstall it.
train
https://github.com/aleontiev/dj/blob/0612d442fdd8d472aea56466568b9857556ecb51/dj/application.py#L349-L362
[ "def format_command(a, b='', prefix=''):\n return (\n white(prefix) +\n blue('%s: ' % a) +\n white(b)\n )\n", "def red(message):\n return click.style(message, fg='red', bold=True)\n", "def build(self):\n \"\"\"Builds the app in the app's environment.\n\n Only builds if the bu...
class Application(object): def __init__( self, stdout=None, directory=None ): self.stdout = stdout or _stdout current = os.getcwd() nearest_setup_file = find_nearest(current, 'setup.py') self.directory = directory or ( os.path.dirname( ...
aleontiev/dj
dj/commands/lint.py
lint
python
def lint(args): application = get_current_application() if not args: args = [application.name, 'tests'] args = ['flake8'] + list(args) run.main(args, standalone_mode=False)
Run lint checks using flake8.
train
https://github.com/aleontiev/dj/blob/0612d442fdd8d472aea56466568b9857556ecb51/dj/commands/lint.py#L13-L19
[ "def get_current_application():\n global current_application\n if not current_application:\n current_application = Application()\n return current_application\n" ]
from __future__ import absolute_import import click from dj.application import get_current_application from .run import run @click.argument('args', nargs=-1, type=click.UNPROCESSED) @click.command( context_settings={ 'ignore_unknown_options': True } )
aleontiev/dj
dj/utils/imports.py
load_module
python
def load_module(filename): path, name = os.path.split(filename) name, ext = os.path.splitext(name) (file, filename, desc) = imp.find_module(name, [path]) try: return imp.load_module(name, file, filename, desc) finally: if file: file.close()
Loads a module from anywhere in the system. Does not depend on or modify sys.path.
train
https://github.com/aleontiev/dj/blob/0612d442fdd8d472aea56466568b9857556ecb51/dj/utils/imports.py#L5-L18
null
import imp import os
aleontiev/dj
dj/commands/info.py
info
python
def info(): application = get_current_application() info = application.info() stdout.write(info) return info
Display app info. Examples: $ dj info No application, try running dj init. $ dj info Application: foo @ 2.7.9 Requirements: Django == 1.10
train
https://github.com/aleontiev/dj/blob/0612d442fdd8d472aea56466568b9857556ecb51/dj/commands/info.py#L8-L26
[ "def get_current_application():\n global current_application\n if not current_application:\n current_application = Application()\n return current_application\n", "def info(self):\n output = []\n dev_requirements = self.get_dependency_manager(dev=True).dependencies\n requirements = self.ge...
from __future__ import absolute_import import click from dj.application import get_current_application from dj.utils.system import stdout @click.command()
aleontiev/dj
dj/generator.py
Generator.render
python
def render(self): context = self.context if 'app' not in context: context['app'] = self.application.name temp_dir = self.temp_dir templates_root = self.blueprint.templates_directory for root, dirs, files in os.walk(templates_root): for directory in dirs: ...
Render the blueprint into a temp directory using the context.
train
https://github.com/aleontiev/dj/blob/0612d442fdd8d472aea56466568b9857556ecb51/dj/generator.py#L44-L66
[ "def strip_extension(string):\n if string.endswith('.j2'):\n string = string[:-3]\n return string\n", "def render_from_string(string, context):\n environment = Environment(undefined=StrictUndefined)\n return environment.from_string(string).render(**context)\n", "def render_from_file(file, con...
class Generator(object): def __init__( self, application, blueprint, context, interactive=True, stdout=None ): self.stdout = stdout or _stdout self.application = application self.interactive = interactive self.blueprint = blueprint...
aleontiev/dj
dj/generator.py
Generator.merge
python
def merge(self): temp_dir = self.temp_dir app_dir = self.application.directory for root, dirs, files in os.walk(temp_dir): for directory in dirs: directory = os.path.join(root, directory) directory = directory.replace(temp_dir, app_dir, 1) ...
Merges the rendered blueprint into the application.
train
https://github.com/aleontiev/dj/blob/0612d442fdd8d472aea56466568b9857556ecb51/dj/generator.py#L68-L143
[ "def green(message):\n return click.style(message, fg='green', bold=True)\n", "def white(message):\n return click.style(message, fg='white', bold=True)\n" ]
class Generator(object): def __init__( self, application, blueprint, context, interactive=True, stdout=None ): self.stdout = stdout or _stdout self.application = application self.interactive = interactive self.blueprint = blueprint...
aleontiev/dj
dj/commands/run.py
run
python
def run(quiet, args): if not args: raise ClickException('pass a command to run') cmd = ' '.join(args) application = get_current_application() name = application.name settings = os.environ.get('DJANGO_SETTINGS_MODULE', '%s.settings' % name) return application.run( cmd, ve...
Run a local command. Examples: $ django run manage.py runserver ...
train
https://github.com/aleontiev/dj/blob/0612d442fdd8d472aea56466568b9857556ecb51/dj/commands/run.py#L17-L41
[ "def get_current_application():\n global current_application\n if not current_application:\n current_application = Application()\n return current_application\n", "def run(self, command, **kwargs):\n self.build()\n self.stdout.write(style.format_command('Running', command))\n return self.e...
from __future__ import absolute_import import click import os from click.exceptions import ClickException from dj.application import get_current_application from dj.utils import style from .base import stdout @click.option('--quiet', is_flag=True, default=False) @click.argument('args', nargs=-1, type=click.UNPROCESSE...
aleontiev/dj
dj/commands/server.py
server
python
def server(port): args = ['python', 'manage.py', 'runserver'] if port: args.append(port) run.main(args)
Start the Django dev server.
train
https://github.com/aleontiev/dj/blob/0612d442fdd8d472aea56466568b9857556ecb51/dj/commands/server.py#L8-L13
null
from __future__ import absolute_import import click from .run import run @click.command() @click.argument('port', required=False)
aleontiev/dj
dj/commands/remove.py
remove
python
def remove(addon, dev): application = get_current_application() application.remove(addon, dev=dev)
Remove a dependency. Examples: $ django remove dynamic-rest - dynamic-rest == 1.5.0
train
https://github.com/aleontiev/dj/blob/0612d442fdd8d472aea56466568b9857556ecb51/dj/commands/remove.py#L9-L19
[ "def get_current_application():\n global current_application\n if not current_application:\n current_application = Application()\n return current_application\n", "def remove(self, addon, dev=False):\n \"\"\"Remove a dependency and uninstall it.\"\"\"\n dependencies = self.get_dependency_mana...
from __future__ import absolute_import import click from dj.application import get_current_application @click.argument('addon') @click.option('--dev', is_flag=True) @click.command()