repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
tamasgal/km3pipe
km3pipe/io/aanet.py
AanetPump.blob_generator
def blob_generator(self): """Create a blob generator.""" # pylint: disable:F0401,W0612 import aa # pylint: disablF0401 # noqa from ROOT import EventFile # pylint: disable F0401 filename = self.filename log.info("Reading from file: {0}".format(filename)) ...
python
def blob_generator(self): """Create a blob generator.""" # pylint: disable:F0401,W0612 import aa # pylint: disablF0401 # noqa from ROOT import EventFile # pylint: disable F0401 filename = self.filename log.info("Reading from file: {0}".format(filename)) ...
[ "def", "blob_generator", "(", "self", ")", ":", "import", "aa", "from", "ROOT", "import", "EventFile", "filename", "=", "self", ".", "filename", "log", ".", "info", "(", "\"Reading from file: {0}\"", ".", "format", "(", "filename", ")", ")", "if", "not", "...
Create a blob generator.
[ "Create", "a", "blob", "generator", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/aanet.py#L264-L320
train
tamasgal/km3pipe
km3pipe/io/aanet.py
MetaParser.parse_string
def parse_string(self, string): """Parse ASCII output of JPrintMeta""" self.log.info("Parsing ASCII data") if not string: self.log.warning("Empty metadata") return lines = string.splitlines() application_data = [] application = lines[0].split()[...
python
def parse_string(self, string): """Parse ASCII output of JPrintMeta""" self.log.info("Parsing ASCII data") if not string: self.log.warning("Empty metadata") return lines = string.splitlines() application_data = [] application = lines[0].split()[...
[ "def", "parse_string", "(", "self", ",", "string", ")", ":", "self", ".", "log", ".", "info", "(", "\"Parsing ASCII data\"", ")", "if", "not", "string", ":", "self", ".", "log", ".", "warning", "(", "\"Empty metadata\"", ")", "return", "lines", "=", "str...
Parse ASCII output of JPrintMeta
[ "Parse", "ASCII", "output", "of", "JPrintMeta" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/aanet.py#L692-L716
train
tamasgal/km3pipe
km3pipe/io/aanet.py
MetaParser._record_app_data
def _record_app_data(self, data): """Parse raw metadata output for a single application The usual output is: ApplicationName RevisionNumber ApplicationName ROOT_Version ApplicationName KM3NET ApplicationName ./command/line --arguments --which --can contain ...
python
def _record_app_data(self, data): """Parse raw metadata output for a single application The usual output is: ApplicationName RevisionNumber ApplicationName ROOT_Version ApplicationName KM3NET ApplicationName ./command/line --arguments --which --can contain ...
[ "def", "_record_app_data", "(", "self", ",", "data", ")", ":", "name", ",", "revision", "=", "data", "[", "0", "]", ".", "split", "(", ")", "root_version", "=", "data", "[", "1", "]", ".", "split", "(", ")", "[", "1", "]", "command", "=", "b'\\n'...
Parse raw metadata output for a single application The usual output is: ApplicationName RevisionNumber ApplicationName ROOT_Version ApplicationName KM3NET ApplicationName ./command/line --arguments --which --can contain also multiple lines and --a...
[ "Parse", "raw", "metadata", "output", "for", "a", "single", "application" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/aanet.py#L718-L741
train
tamasgal/km3pipe
km3pipe/io/aanet.py
MetaParser.get_table
def get_table(self, name='Meta', h5loc='/meta'): """Convert metadata to a KM3Pipe Table. Returns `None` if there is no data. Each column's dtype will be set to a fixed size string (numpy.string_) with the length of the longest entry, since writing variable length strings does n...
python
def get_table(self, name='Meta', h5loc='/meta'): """Convert metadata to a KM3Pipe Table. Returns `None` if there is no data. Each column's dtype will be set to a fixed size string (numpy.string_) with the length of the longest entry, since writing variable length strings does n...
[ "def", "get_table", "(", "self", ",", "name", "=", "'Meta'", ",", "h5loc", "=", "'/meta'", ")", ":", "if", "not", "self", ".", "meta", ":", "return", "None", "data", "=", "defaultdict", "(", "list", ")", "for", "entry", "in", "self", ".", "meta", "...
Convert metadata to a KM3Pipe Table. Returns `None` if there is no data. Each column's dtype will be set to a fixed size string (numpy.string_) with the length of the longest entry, since writing variable length strings does not fit the current scheme.
[ "Convert", "metadata", "to", "a", "KM3Pipe", "Table", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/aanet.py#L743-L767
train
NaPs/Kolekto
kolekto/db.py
MoviesMetadata.itermovieshash
def itermovieshash(self): """ Iterate over movies hash stored in the database. """ cur = self._db.firstkey() while cur is not None: yield cur cur = self._db.nextkey(cur)
python
def itermovieshash(self): """ Iterate over movies hash stored in the database. """ cur = self._db.firstkey() while cur is not None: yield cur cur = self._db.nextkey(cur)
[ "def", "itermovieshash", "(", "self", ")", ":", "cur", "=", "self", ".", "_db", ".", "firstkey", "(", ")", "while", "cur", "is", "not", "None", ":", "yield", "cur", "cur", "=", "self", ".", "_db", ".", "nextkey", "(", "cur", ")" ]
Iterate over movies hash stored in the database.
[ "Iterate", "over", "movies", "hash", "stored", "in", "the", "database", "." ]
29c5469da8782780a06bf9a76c59414bb6fd8fe3
https://github.com/NaPs/Kolekto/blob/29c5469da8782780a06bf9a76c59414bb6fd8fe3/kolekto/db.py#L12-L18
train
LeadPages/gcloud_requests
gcloud_requests/datastore.py
DatastoreRequestsProxy._max_retries_for_error
def _max_retries_for_error(self, error): """Handles Datastore response errors according to their documentation. Parameters: error(dict) Returns: int or None: The max number of times this error should be retried or None if it shouldn't. See also: ...
python
def _max_retries_for_error(self, error): """Handles Datastore response errors according to their documentation. Parameters: error(dict) Returns: int or None: The max number of times this error should be retried or None if it shouldn't. See also: ...
[ "def", "_max_retries_for_error", "(", "self", ",", "error", ")", ":", "status", "=", "error", ".", "get", "(", "\"status\"", ")", "if", "status", "==", "\"ABORTED\"", "and", "get_transactions", "(", ")", ">", "0", ":", "return", "None", "return", "self", ...
Handles Datastore response errors according to their documentation. Parameters: error(dict) Returns: int or None: The max number of times this error should be retried or None if it shouldn't. See also: https://cloud.google.com/datastore/docs/concepts/er...
[ "Handles", "Datastore", "response", "errors", "according", "to", "their", "documentation", "." ]
8933363c4e9fa1e5ec0e90d683fca8ef8a949752
https://github.com/LeadPages/gcloud_requests/blob/8933363c4e9fa1e5ec0e90d683fca8ef8a949752/gcloud_requests/datastore.py#L56-L73
train
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
anonymous_login
def anonymous_login(services): """Initialize services without authenticating to Globus Auth. Note: Clients may have reduced functionality without authentication. Arguments: services (str or list of str): The services to initialize clients for. Returns: dict: The clients reques...
python
def anonymous_login(services): """Initialize services without authenticating to Globus Auth. Note: Clients may have reduced functionality without authentication. Arguments: services (str or list of str): The services to initialize clients for. Returns: dict: The clients reques...
[ "def", "anonymous_login", "(", "services", ")", ":", "if", "isinstance", "(", "services", ",", "str", ")", ":", "services", "=", "[", "services", "]", "clients", "=", "{", "}", "for", "serv", "in", "services", ":", "try", ":", "clients", "[", "serv", ...
Initialize services without authenticating to Globus Auth. Note: Clients may have reduced functionality without authentication. Arguments: services (str or list of str): The services to initialize clients for. Returns: dict: The clients requested, indexed by service name.
[ "Initialize", "services", "without", "authenticating", "to", "Globus", "Auth", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L364-L390
train
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
logout
def logout(token_dir=DEFAULT_CRED_PATH): """Remove ALL tokens in the token directory. This will force re-authentication to all services. Arguments: token_dir (str): The path to the directory to save tokens in and look for credentials by default. If this argument was given to a ``log...
python
def logout(token_dir=DEFAULT_CRED_PATH): """Remove ALL tokens in the token directory. This will force re-authentication to all services. Arguments: token_dir (str): The path to the directory to save tokens in and look for credentials by default. If this argument was given to a ``log...
[ "def", "logout", "(", "token_dir", "=", "DEFAULT_CRED_PATH", ")", ":", "for", "f", "in", "os", ".", "listdir", "(", "token_dir", ")", ":", "if", "f", ".", "endswith", "(", "\"tokens.json\"", ")", ":", "try", ":", "os", ".", "remove", "(", "os", ".", ...
Remove ALL tokens in the token directory. This will force re-authentication to all services. Arguments: token_dir (str): The path to the directory to save tokens in and look for credentials by default. If this argument was given to a ``login()`` function, the same value ...
[ "Remove", "ALL", "tokens", "in", "the", "token", "directory", ".", "This", "will", "force", "re", "-", "authentication", "to", "all", "services", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L393-L411
train
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
format_gmeta
def format_gmeta(data, acl=None, identifier=None): """Format input into GMeta format, suitable for ingesting into Globus Search. Formats a dictionary into a GMetaEntry. Formats a list of GMetaEntry into a GMetaList inside a GMetaIngest. **Example usage**:: glist = [] for document in al...
python
def format_gmeta(data, acl=None, identifier=None): """Format input into GMeta format, suitable for ingesting into Globus Search. Formats a dictionary into a GMetaEntry. Formats a list of GMetaEntry into a GMetaList inside a GMetaIngest. **Example usage**:: glist = [] for document in al...
[ "def", "format_gmeta", "(", "data", ",", "acl", "=", "None", ",", "identifier", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "if", "acl", "is", "None", "or", "identifier", "is", "None", ":", "raise", "ValueError", "(...
Format input into GMeta format, suitable for ingesting into Globus Search. Formats a dictionary into a GMetaEntry. Formats a list of GMetaEntry into a GMetaList inside a GMetaIngest. **Example usage**:: glist = [] for document in all_my_documents: gmeta_entry = format_gmeta(doc...
[ "Format", "input", "into", "GMeta", "format", "suitable", "for", "ingesting", "into", "Globus", "Search", ".", "Formats", "a", "dictionary", "into", "a", "GMetaEntry", ".", "Formats", "a", "list", "of", "GMetaEntry", "into", "a", "GMetaList", "inside", "a", ...
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L471-L539
train
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
gmeta_pop
def gmeta_pop(gmeta, info=False): """Remove GMeta wrapping from a Globus Search result. This function can be called on the raw GlobusHTTPResponse that Search returns, or a string or dictionary representation of it. Arguments: gmeta (dict, str, or GlobusHTTPResponse): The Globus Search result to...
python
def gmeta_pop(gmeta, info=False): """Remove GMeta wrapping from a Globus Search result. This function can be called on the raw GlobusHTTPResponse that Search returns, or a string or dictionary representation of it. Arguments: gmeta (dict, str, or GlobusHTTPResponse): The Globus Search result to...
[ "def", "gmeta_pop", "(", "gmeta", ",", "info", "=", "False", ")", ":", "if", "type", "(", "gmeta", ")", "is", "GlobusHTTPResponse", ":", "gmeta", "=", "json", ".", "loads", "(", "gmeta", ".", "text", ")", "elif", "type", "(", "gmeta", ")", "is", "s...
Remove GMeta wrapping from a Globus Search result. This function can be called on the raw GlobusHTTPResponse that Search returns, or a string or dictionary representation of it. Arguments: gmeta (dict, str, or GlobusHTTPResponse): The Globus Search result to unwrap. info (bool): If ``False`...
[ "Remove", "GMeta", "wrapping", "from", "a", "Globus", "Search", "result", ".", "This", "function", "can", "be", "called", "on", "the", "raw", "GlobusHTTPResponse", "that", "Search", "returns", "or", "a", "string", "or", "dictionary", "representation", "of", "i...
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L542-L574
train
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
translate_index
def translate_index(index_name): """Translate a known Globus Search index into the index UUID. The UUID is the proper way to access indices, and will eventually be the only way. This method will return names it cannot disambiguate. Arguments: index_name (str): The name of the index. Return...
python
def translate_index(index_name): """Translate a known Globus Search index into the index UUID. The UUID is the proper way to access indices, and will eventually be the only way. This method will return names it cannot disambiguate. Arguments: index_name (str): The name of the index. Return...
[ "def", "translate_index", "(", "index_name", ")", ":", "uuid", "=", "SEARCH_INDEX_UUIDS", ".", "get", "(", "index_name", ".", "strip", "(", ")", ".", "lower", "(", ")", ")", "if", "not", "uuid", ":", "try", ":", "index_info", "=", "globus_sdk", ".", "S...
Translate a known Globus Search index into the index UUID. The UUID is the proper way to access indices, and will eventually be the only way. This method will return names it cannot disambiguate. Arguments: index_name (str): The name of the index. Returns: str: The UUID of the index. I...
[ "Translate", "a", "known", "Globus", "Search", "index", "into", "the", "index", "UUID", ".", "The", "UUID", "is", "the", "proper", "way", "to", "access", "indices", "and", "will", "eventually", "be", "the", "only", "way", ".", "This", "method", "will", "...
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L577-L598
train
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
quick_transfer
def quick_transfer(transfer_client, source_ep, dest_ep, path_list, interval=None, retries=10, notify=True): """Perform a Globus Transfer and monitor for success. Arguments: transfer_client (TransferClient): An authenticated Transfer client. source_ep (str): The source Globus ...
python
def quick_transfer(transfer_client, source_ep, dest_ep, path_list, interval=None, retries=10, notify=True): """Perform a Globus Transfer and monitor for success. Arguments: transfer_client (TransferClient): An authenticated Transfer client. source_ep (str): The source Globus ...
[ "def", "quick_transfer", "(", "transfer_client", ",", "source_ep", ",", "dest_ep", ",", "path_list", ",", "interval", "=", "None", ",", "retries", "=", "10", ",", "notify", "=", "True", ")", ":", "if", "retries", "is", "None", ":", "retries", "=", "0", ...
Perform a Globus Transfer and monitor for success. Arguments: transfer_client (TransferClient): An authenticated Transfer client. source_ep (str): The source Globus Endpoint ID. dest_ep (str): The destination Globus Endpoint ID. path_list (list of tuple of 2 str): A list of tuples c...
[ "Perform", "a", "Globus", "Transfer", "and", "monitor", "for", "success", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L805-L863
train
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
insensitive_comparison
def insensitive_comparison(item1, item2, type_insensitive=False, string_insensitive=False): """Compare two items without regard to order. The following rules are used to determine equivalence: * Items that are not of the same type can be equivalent only when ``type_insensitive=True``. * Mapping...
python
def insensitive_comparison(item1, item2, type_insensitive=False, string_insensitive=False): """Compare two items without regard to order. The following rules are used to determine equivalence: * Items that are not of the same type can be equivalent only when ``type_insensitive=True``. * Mapping...
[ "def", "insensitive_comparison", "(", "item1", ",", "item2", ",", "type_insensitive", "=", "False", ",", "string_insensitive", "=", "False", ")", ":", "if", "not", "type_insensitive", "and", "type", "(", "item1", ")", "!=", "type", "(", "item2", ")", ":", ...
Compare two items without regard to order. The following rules are used to determine equivalence: * Items that are not of the same type can be equivalent only when ``type_insensitive=True``. * Mapping objects are equal iff the keys in each item exist in both items and have the same value ...
[ "Compare", "two", "items", "without", "regard", "to", "order", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L933-L1071
train
tapilab/brandelion
brandelion/cli/analyze.py
parse_json
def parse_json(json_file, include_date=False): """ Yield screen_name, text tuples from a json file. """ if json_file[-2:] == 'gz': fh = gzip.open(json_file, 'rt') else: fh = io.open(json_file, mode='rt', encoding='utf8') for line in fh: try: jj = json.loads(line) ...
python
def parse_json(json_file, include_date=False): """ Yield screen_name, text tuples from a json file. """ if json_file[-2:] == 'gz': fh = gzip.open(json_file, 'rt') else: fh = io.open(json_file, mode='rt', encoding='utf8') for line in fh: try: jj = json.loads(line) ...
[ "def", "parse_json", "(", "json_file", ",", "include_date", "=", "False", ")", ":", "if", "json_file", "[", "-", "2", ":", "]", "==", "'gz'", ":", "fh", "=", "gzip", ".", "open", "(", "json_file", ",", "'rt'", ")", "else", ":", "fh", "=", "io", "...
Yield screen_name, text tuples from a json file.
[ "Yield", "screen_name", "text", "tuples", "from", "a", "json", "file", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L50-L71
train
tapilab/brandelion
brandelion/cli/analyze.py
extract_tweets
def extract_tweets(json_file): """ Yield screen_name, string tuples, where the string is the concatenation of all tweets of this user. """ for screen_name, tweet_iter in groupby(parse_json(json_file), lambda x: x[0]): tweets = [t[1] for t in tweet_iter] yield screen_name, ' '.join(tweets)
python
def extract_tweets(json_file): """ Yield screen_name, string tuples, where the string is the concatenation of all tweets of this user. """ for screen_name, tweet_iter in groupby(parse_json(json_file), lambda x: x[0]): tweets = [t[1] for t in tweet_iter] yield screen_name, ' '.join(tweets)
[ "def", "extract_tweets", "(", "json_file", ")", ":", "for", "screen_name", ",", "tweet_iter", "in", "groupby", "(", "parse_json", "(", "json_file", ")", ",", "lambda", "x", ":", "x", "[", "0", "]", ")", ":", "tweets", "=", "[", "t", "[", "1", "]", ...
Yield screen_name, string tuples, where the string is the concatenation of all tweets of this user.
[ "Yield", "screen_name", "string", "tuples", "where", "the", "string", "is", "the", "concatenation", "of", "all", "tweets", "of", "this", "user", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L74-L79
train
tapilab/brandelion
brandelion/cli/analyze.py
vectorize
def vectorize(json_file, vec, dofit=True): """ Return a matrix where each row corresponds to a Twitter account, and each column corresponds to the number of times a term is used by that account. """ ## CountVectorizer, efficiently. screen_names = [x[0] for x in extract_tweets(json_file)] if dofi...
python
def vectorize(json_file, vec, dofit=True): """ Return a matrix where each row corresponds to a Twitter account, and each column corresponds to the number of times a term is used by that account. """ ## CountVectorizer, efficiently. screen_names = [x[0] for x in extract_tweets(json_file)] if dofi...
[ "def", "vectorize", "(", "json_file", ",", "vec", ",", "dofit", "=", "True", ")", ":", "screen_names", "=", "[", "x", "[", "0", "]", "for", "x", "in", "extract_tweets", "(", "json_file", ")", "]", "if", "dofit", ":", "X", "=", "vec", ".", "fit_tran...
Return a matrix where each row corresponds to a Twitter account, and each column corresponds to the number of times a term is used by that account.
[ "Return", "a", "matrix", "where", "each", "row", "corresponds", "to", "a", "Twitter", "account", "and", "each", "column", "corresponds", "to", "the", "number", "of", "times", "a", "term", "is", "used", "by", "that", "account", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L99-L109
train
tapilab/brandelion
brandelion/cli/analyze.py
read_follower_file
def read_follower_file(fname, min_followers=0, max_followers=1e10, blacklist=set()): """ Read a file of follower information and return a dictionary mapping screen_name to a set of follower ids. """ result = {} with open(fname, 'rt') as f: for line in f: parts = line.split() ...
python
def read_follower_file(fname, min_followers=0, max_followers=1e10, blacklist=set()): """ Read a file of follower information and return a dictionary mapping screen_name to a set of follower ids. """ result = {} with open(fname, 'rt') as f: for line in f: parts = line.split() ...
[ "def", "read_follower_file", "(", "fname", ",", "min_followers", "=", "0", ",", "max_followers", "=", "1e10", ",", "blacklist", "=", "set", "(", ")", ")", ":", "result", "=", "{", "}", "with", "open", "(", "fname", ",", "'rt'", ")", "as", "f", ":", ...
Read a file of follower information and return a dictionary mapping screen_name to a set of follower ids.
[ "Read", "a", "file", "of", "follower", "information", "and", "return", "a", "dictionary", "mapping", "screen_name", "to", "a", "set", "of", "follower", "ids", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L171-L184
train
tapilab/brandelion
brandelion/cli/analyze.py
jaccard_merge
def jaccard_merge(brands, exemplars): """ Return the average Jaccard similarity between a brand's followers and the followers of each exemplar. We merge all exemplar followers into one big pseudo-account.""" scores = {} exemplar_followers = set() for followers in exemplars.values(): exem...
python
def jaccard_merge(brands, exemplars): """ Return the average Jaccard similarity between a brand's followers and the followers of each exemplar. We merge all exemplar followers into one big pseudo-account.""" scores = {} exemplar_followers = set() for followers in exemplars.values(): exem...
[ "def", "jaccard_merge", "(", "brands", ",", "exemplars", ")", ":", "scores", "=", "{", "}", "exemplar_followers", "=", "set", "(", ")", "for", "followers", "in", "exemplars", ".", "values", "(", ")", ":", "exemplar_followers", "|=", "followers", "for", "br...
Return the average Jaccard similarity between a brand's followers and the followers of each exemplar. We merge all exemplar followers into one big pseudo-account.
[ "Return", "the", "average", "Jaccard", "similarity", "between", "a", "brand", "s", "followers", "and", "the", "followers", "of", "each", "exemplar", ".", "We", "merge", "all", "exemplar", "followers", "into", "one", "big", "pseudo", "-", "account", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L235-L246
train
tapilab/brandelion
brandelion/cli/analyze.py
cosine
def cosine(brands, exemplars, weighted_avg=False, sqrt=False): """ Return the cosine similarity betwee a brand's followers and the exemplars. """ scores = {} for brand, followers in brands: if weighted_avg: scores[brand] = np.average([_cosine(followers, others) for others in exem...
python
def cosine(brands, exemplars, weighted_avg=False, sqrt=False): """ Return the cosine similarity betwee a brand's followers and the exemplars. """ scores = {} for brand, followers in brands: if weighted_avg: scores[brand] = np.average([_cosine(followers, others) for others in exem...
[ "def", "cosine", "(", "brands", ",", "exemplars", ",", "weighted_avg", "=", "False", ",", "sqrt", "=", "False", ")", ":", "scores", "=", "{", "}", "for", "brand", ",", "followers", "in", "brands", ":", "if", "weighted_avg", ":", "scores", "[", "brand",...
Return the cosine similarity betwee a brand's followers and the exemplars.
[ "Return", "the", "cosine", "similarity", "betwee", "a", "brand", "s", "followers", "and", "the", "exemplars", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L319-L332
train
thebigmunch/google-music-utils
src/google_music_utils/misc.py
suggest_filename
def suggest_filename(metadata): """Generate a filename like Google for a song based on metadata. Parameters: metadata (~collections.abc.Mapping): A metadata dict. Returns: str: A filename string without an extension. """ if 'title' in metadata and 'track_number' in metadata: # Music Manager. suggested_fi...
python
def suggest_filename(metadata): """Generate a filename like Google for a song based on metadata. Parameters: metadata (~collections.abc.Mapping): A metadata dict. Returns: str: A filename string without an extension. """ if 'title' in metadata and 'track_number' in metadata: # Music Manager. suggested_fi...
[ "def", "suggest_filename", "(", "metadata", ")", ":", "if", "'title'", "in", "metadata", "and", "'track_number'", "in", "metadata", ":", "suggested_filename", "=", "f\"{metadata['track_number']:0>2} {metadata['title']}\"", "elif", "'title'", "in", "metadata", "and", "'t...
Generate a filename like Google for a song based on metadata. Parameters: metadata (~collections.abc.Mapping): A metadata dict. Returns: str: A filename string without an extension.
[ "Generate", "a", "filename", "like", "Google", "for", "a", "song", "based", "on", "metadata", "." ]
2e8873defe7d5aab7321b9d5ec8a80d72687578e
https://github.com/thebigmunch/google-music-utils/blob/2e8873defe7d5aab7321b9d5ec8a80d72687578e/src/google_music_utils/misc.py#L25-L51
train
thebigmunch/google-music-utils
src/google_music_utils/misc.py
template_to_filepath
def template_to_filepath(template, metadata, template_patterns=None): """Create directory structure and file name based on metadata template. Note: A template meant to be a base directory for suggested names should have a trailing slash or backslash. Parameters: template (str or ~os.PathLike): A filepath whic...
python
def template_to_filepath(template, metadata, template_patterns=None): """Create directory structure and file name based on metadata template. Note: A template meant to be a base directory for suggested names should have a trailing slash or backslash. Parameters: template (str or ~os.PathLike): A filepath whic...
[ "def", "template_to_filepath", "(", "template", ",", "metadata", ",", "template_patterns", "=", "None", ")", ":", "path", "=", "Path", "(", "template", ")", "if", "template_patterns", "is", "None", ":", "template_patterns", "=", "TEMPLATE_PATTERNS", "suggested_fil...
Create directory structure and file name based on metadata template. Note: A template meant to be a base directory for suggested names should have a trailing slash or backslash. Parameters: template (str or ~os.PathLike): A filepath which can include template patterns as defined by :param template_patterns:. ...
[ "Create", "directory", "structure", "and", "file", "name", "based", "on", "metadata", "template", "." ]
2e8873defe7d5aab7321b9d5ec8a80d72687578e
https://github.com/thebigmunch/google-music-utils/blob/2e8873defe7d5aab7321b9d5ec8a80d72687578e/src/google_music_utils/misc.py#L54-L138
train
thebigmunch/google-music-utils
src/google_music_utils/filter.py
_match_field
def _match_field(field_value, pattern, ignore_case=False, normalize_values=False): """Match an item metadata field value by pattern. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: field_value (list or str): A metad...
python
def _match_field(field_value, pattern, ignore_case=False, normalize_values=False): """Match an item metadata field value by pattern. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: field_value (list or str): A metad...
[ "def", "_match_field", "(", "field_value", ",", "pattern", ",", "ignore_case", "=", "False", ",", "normalize_values", "=", "False", ")", ":", "if", "normalize_values", ":", "ignore_case", "=", "True", "normalize", "=", "normalize_value", "if", "normalize_values", ...
Match an item metadata field value by pattern. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: field_value (list or str): A metadata field value to check. pattern (str): A regex pattern to check the field value(s) ...
[ "Match", "an", "item", "metadata", "field", "value", "by", "pattern", "." ]
2e8873defe7d5aab7321b9d5ec8a80d72687578e
https://github.com/thebigmunch/google-music-utils/blob/2e8873defe7d5aab7321b9d5ec8a80d72687578e/src/google_music_utils/filter.py#L14-L43
train
thebigmunch/google-music-utils
src/google_music_utils/filter.py
_match_item
def _match_item(item, any_all=any, ignore_case=False, normalize_values=False, **kwargs): """Match items by metadata. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: item (~collections.abc.Mapping, str, os.PathLike):...
python
def _match_item(item, any_all=any, ignore_case=False, normalize_values=False, **kwargs): """Match items by metadata. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: item (~collections.abc.Mapping, str, os.PathLike):...
[ "def", "_match_item", "(", "item", ",", "any_all", "=", "any", ",", "ignore_case", "=", "False", ",", "normalize_values", "=", "False", ",", "**", "kwargs", ")", ":", "it", "=", "get_item_tags", "(", "item", ")", "return", "any_all", "(", "_match_field", ...
Match items by metadata. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: item (~collections.abc.Mapping, str, os.PathLike): Item dict or filepath. any_all (callable): A callable to determine if any or all filters m...
[ "Match", "items", "by", "metadata", "." ]
2e8873defe7d5aab7321b9d5ec8a80d72687578e
https://github.com/thebigmunch/google-music-utils/blob/2e8873defe7d5aab7321b9d5ec8a80d72687578e/src/google_music_utils/filter.py#L46-L73
train
thebigmunch/google-music-utils
src/google_music_utils/filter.py
exclude_items
def exclude_items(items, any_all=any, ignore_case=False, normalize_values=False, **kwargs): """Exclude items by matching metadata. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: items (list): A list of item dicts o...
python
def exclude_items(items, any_all=any, ignore_case=False, normalize_values=False, **kwargs): """Exclude items by matching metadata. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: items (list): A list of item dicts o...
[ "def", "exclude_items", "(", "items", ",", "any_all", "=", "any", ",", "ignore_case", "=", "False", ",", "normalize_values", "=", "False", ",", "**", "kwargs", ")", ":", "if", "kwargs", ":", "match", "=", "functools", ".", "partial", "(", "_match_item", ...
Exclude items by matching metadata. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: items (list): A list of item dicts or filepaths. any_all (callable): A callable to determine if any or all filters must match to e...
[ "Exclude", "items", "by", "matching", "metadata", "." ]
2e8873defe7d5aab7321b9d5ec8a80d72687578e
https://github.com/thebigmunch/google-music-utils/blob/2e8873defe7d5aab7321b9d5ec8a80d72687578e/src/google_music_utils/filter.py#L76-L108
train
thebigmunch/google-music-utils
src/google_music_utils/filter.py
include_items
def include_items(items, any_all=any, ignore_case=False, normalize_values=False, **kwargs): """Include items by matching metadata. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: items (list): A list of item dicts o...
python
def include_items(items, any_all=any, ignore_case=False, normalize_values=False, **kwargs): """Include items by matching metadata. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: items (list): A list of item dicts o...
[ "def", "include_items", "(", "items", ",", "any_all", "=", "any", ",", "ignore_case", "=", "False", ",", "normalize_values", "=", "False", ",", "**", "kwargs", ")", ":", "if", "kwargs", ":", "match", "=", "functools", ".", "partial", "(", "_match_item", ...
Include items by matching metadata. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: items (list): A list of item dicts or filepaths. any_all (callable): A callable to determine if any or all filters must match to i...
[ "Include", "items", "by", "matching", "metadata", "." ]
2e8873defe7d5aab7321b9d5ec8a80d72687578e
https://github.com/thebigmunch/google-music-utils/blob/2e8873defe7d5aab7321b9d5ec8a80d72687578e/src/google_music_utils/filter.py#L111-L143
train
IRC-SPHERE/HyperStream
hyperstream/utils/statistics/percentile.py
percentile
def percentile(a, q): """ Compute the qth percentile of the data along the specified axis. Simpler version than the numpy version that always flattens input arrays. Examples -------- >>> a = [[10, 7, 4], [3, 2, 1]] >>> percentile(a, 20) 2.0 >>> percentile(a, 50) 3.5 >>> perc...
python
def percentile(a, q): """ Compute the qth percentile of the data along the specified axis. Simpler version than the numpy version that always flattens input arrays. Examples -------- >>> a = [[10, 7, 4], [3, 2, 1]] >>> percentile(a, 20) 2.0 >>> percentile(a, 50) 3.5 >>> perc...
[ "def", "percentile", "(", "a", ",", "q", ")", ":", "if", "not", "a", ":", "return", "None", "if", "isinstance", "(", "q", ",", "(", "float", ",", "int", ")", ")", ":", "qq", "=", "[", "q", "]", "elif", "isinstance", "(", "q", ",", "(", "tuple...
Compute the qth percentile of the data along the specified axis. Simpler version than the numpy version that always flattens input arrays. Examples -------- >>> a = [[10, 7, 4], [3, 2, 1]] >>> percentile(a, 20) 2.0 >>> percentile(a, 50) 3.5 >>> percentile(a, [20, 80]) [2.0, 7.0]...
[ "Compute", "the", "qth", "percentile", "of", "the", "data", "along", "the", "specified", "axis", ".", "Simpler", "version", "than", "the", "numpy", "version", "that", "always", "flattens", "input", "arrays", "." ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/utils/statistics/percentile.py#L33-L90
train
dgomes/pyipma
pyipma/station.py
Station._filter_closest
def _filter_closest(self, lat, lon, stations): """Helper to filter the closest station to a given location.""" current_location = (lat, lon) closest = None closest_distance = None for station in stations: station_loc = (station.latitude, station.longitude) ...
python
def _filter_closest(self, lat, lon, stations): """Helper to filter the closest station to a given location.""" current_location = (lat, lon) closest = None closest_distance = None for station in stations: station_loc = (station.latitude, station.longitude) ...
[ "def", "_filter_closest", "(", "self", ",", "lat", ",", "lon", ",", "stations", ")", ":", "current_location", "=", "(", "lat", ",", "lon", ")", "closest", "=", "None", "closest_distance", "=", "None", "for", "station", "in", "stations", ":", "station_loc",...
Helper to filter the closest station to a given location.
[ "Helper", "to", "filter", "the", "closest", "station", "to", "a", "given", "location", "." ]
cd808abeb70dca0e336afdf55bef3f73973eaa71
https://github.com/dgomes/pyipma/blob/cd808abeb70dca0e336afdf55bef3f73973eaa71/pyipma/station.py#L20-L34
train
dgomes/pyipma
pyipma/station.py
Station.get
async def get(cls, websession, lat, lon): """Retrieve the nearest station.""" self = Station(websession) stations = await self.api.stations() self.station = self._filter_closest(lat, lon, stations) logger.info("Using %s as weather station", self.station.local) ...
python
async def get(cls, websession, lat, lon): """Retrieve the nearest station.""" self = Station(websession) stations = await self.api.stations() self.station = self._filter_closest(lat, lon, stations) logger.info("Using %s as weather station", self.station.local) ...
[ "async", "def", "get", "(", "cls", ",", "websession", ",", "lat", ",", "lon", ")", ":", "self", "=", "Station", "(", "websession", ")", "stations", "=", "await", "self", ".", "api", ".", "stations", "(", ")", "self", ".", "station", "=", "self", "....
Retrieve the nearest station.
[ "Retrieve", "the", "nearest", "station", "." ]
cd808abeb70dca0e336afdf55bef3f73973eaa71
https://github.com/dgomes/pyipma/blob/cd808abeb70dca0e336afdf55bef3f73973eaa71/pyipma/station.py#L37-L48
train
IRC-SPHERE/HyperStream
hyperstream/plugin_manager.py
Plugin.load_channels
def load_channels(self): """ Loads the channels and tools given the plugin path specified :return: The loaded channels, including a tool channel, for the tools found. """ channels = [] # Try to get channels for channel_name in self.channel_names: cha...
python
def load_channels(self): """ Loads the channels and tools given the plugin path specified :return: The loaded channels, including a tool channel, for the tools found. """ channels = [] # Try to get channels for channel_name in self.channel_names: cha...
[ "def", "load_channels", "(", "self", ")", ":", "channels", "=", "[", "]", "for", "channel_name", "in", "self", ".", "channel_names", ":", "channel_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "\"channels\"", ")", "sys", "....
Loads the channels and tools given the plugin path specified :return: The loaded channels, including a tool channel, for the tools found.
[ "Loads", "the", "channels", "and", "tools", "given", "the", "plugin", "path", "specified" ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/plugin_manager.py#L38-L76
train
nsfmc/swatch
swatch/writer.py
chunk_count
def chunk_count(swatch): """return the number of byte-chunks in a swatch object this recursively walks the swatch list, returning 1 for a single color & returns 2 for each folder plus 1 for each color it contains """ if type(swatch) is dict: if 'data' in swatch: return 1 ...
python
def chunk_count(swatch): """return the number of byte-chunks in a swatch object this recursively walks the swatch list, returning 1 for a single color & returns 2 for each folder plus 1 for each color it contains """ if type(swatch) is dict: if 'data' in swatch: return 1 ...
[ "def", "chunk_count", "(", "swatch", ")", ":", "if", "type", "(", "swatch", ")", "is", "dict", ":", "if", "'data'", "in", "swatch", ":", "return", "1", "if", "'swatches'", "in", "swatch", ":", "return", "2", "+", "len", "(", "swatch", "[", "'swatches...
return the number of byte-chunks in a swatch object this recursively walks the swatch list, returning 1 for a single color & returns 2 for each folder plus 1 for each color it contains
[ "return", "the", "number", "of", "byte", "-", "chunks", "in", "a", "swatch", "object" ]
8654edf4f1aeef37d42211ff3fe6a3e9e4325859
https://github.com/nsfmc/swatch/blob/8654edf4f1aeef37d42211ff3fe6a3e9e4325859/swatch/writer.py#L18-L30
train
nsfmc/swatch
swatch/writer.py
chunk_for_color
def chunk_for_color(obj): """builds up a byte-chunk for a color the format for this is b'\x00\x01' + Big-Endian Unsigned Int == len(bytes that follow in this block) • Big-Endian Unsigned Short == len(color_name) in practice, because utf-16 takes up 2 bytes per letter ...
python
def chunk_for_color(obj): """builds up a byte-chunk for a color the format for this is b'\x00\x01' + Big-Endian Unsigned Int == len(bytes that follow in this block) • Big-Endian Unsigned Short == len(color_name) in practice, because utf-16 takes up 2 bytes per letter ...
[ "def", "chunk_for_color", "(", "obj", ")", ":", "title", "=", "obj", "[", "'name'", "]", "+", "'\\0'", "title_length", "=", "len", "(", "title", ")", "chunk", "=", "struct", ".", "pack", "(", "'>H'", ",", "title_length", ")", "chunk", "+=", "title", ...
builds up a byte-chunk for a color the format for this is b'\x00\x01' + Big-Endian Unsigned Int == len(bytes that follow in this block) • Big-Endian Unsigned Short == len(color_name) in practice, because utf-16 takes up 2 bytes per letter this will be 2 * (len(...
[ "builds", "up", "a", "byte", "-", "chunk", "for", "a", "color" ]
8654edf4f1aeef37d42211ff3fe6a3e9e4325859
https://github.com/nsfmc/swatch/blob/8654edf4f1aeef37d42211ff3fe6a3e9e4325859/swatch/writer.py#L39-L83
train
nsfmc/swatch
swatch/writer.py
chunk_for_folder
def chunk_for_folder(obj): """produce a byte-chunk for a folder of colors the structure is very similar to a color's data: • Header b'\xC0\x01' + Big Endian Unsigned Int == len(Bytes in the Header Block) note _only_ the header, this doesn't include the length of color data ...
python
def chunk_for_folder(obj): """produce a byte-chunk for a folder of colors the structure is very similar to a color's data: • Header b'\xC0\x01' + Big Endian Unsigned Int == len(Bytes in the Header Block) note _only_ the header, this doesn't include the length of color data ...
[ "def", "chunk_for_folder", "(", "obj", ")", ":", "title", "=", "obj", "[", "'name'", "]", "+", "'\\0'", "title_length", "=", "len", "(", "title", ")", "chunk_body", "=", "struct", ".", "pack", "(", "'>H'", ",", "title_length", ")", "chunk_body", "+=", ...
produce a byte-chunk for a folder of colors the structure is very similar to a color's data: • Header b'\xC0\x01' + Big Endian Unsigned Int == len(Bytes in the Header Block) note _only_ the header, this doesn't include the length of color data • Big Endian Unsigned Short == ...
[ "produce", "a", "byte", "-", "chunk", "for", "a", "folder", "of", "colors" ]
8654edf4f1aeef37d42211ff3fe6a3e9e4325859
https://github.com/nsfmc/swatch/blob/8654edf4f1aeef37d42211ff3fe6a3e9e4325859/swatch/writer.py#L85-L121
train
tapilab/brandelion
brandelion/cli/collect.py
iter_lines
def iter_lines(filename): """ Iterate over screen names in a file, one per line.""" with open(filename, 'rt') as idfile: for line in idfile: screen_name = line.strip() if len(screen_name) > 0: yield screen_name.split()[0]
python
def iter_lines(filename): """ Iterate over screen names in a file, one per line.""" with open(filename, 'rt') as idfile: for line in idfile: screen_name = line.strip() if len(screen_name) > 0: yield screen_name.split()[0]
[ "def", "iter_lines", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'rt'", ")", "as", "idfile", ":", "for", "line", "in", "idfile", ":", "screen_name", "=", "line", ".", "strip", "(", ")", "if", "len", "(", "screen_name", ")", ">",...
Iterate over screen names in a file, one per line.
[ "Iterate", "over", "screen", "names", "in", "a", "file", "one", "per", "line", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/collect.py#L47-L53
train
tapilab/brandelion
brandelion/cli/collect.py
fetch_tweets
def fetch_tweets(account_file, outfile, limit): """ Fetch up to limit tweets for each account in account_file and write to outfile. """ print('fetching tweets for accounts in', account_file) outf = io.open(outfile, 'wt') for screen_name in iter_lines(account_file): print('\nFetching tweets f...
python
def fetch_tweets(account_file, outfile, limit): """ Fetch up to limit tweets for each account in account_file and write to outfile. """ print('fetching tweets for accounts in', account_file) outf = io.open(outfile, 'wt') for screen_name in iter_lines(account_file): print('\nFetching tweets f...
[ "def", "fetch_tweets", "(", "account_file", ",", "outfile", ",", "limit", ")", ":", "print", "(", "'fetching tweets for accounts in'", ",", "account_file", ")", "outf", "=", "io", ".", "open", "(", "outfile", ",", "'wt'", ")", "for", "screen_name", "in", "it...
Fetch up to limit tweets for each account in account_file and write to outfile.
[ "Fetch", "up", "to", "limit", "tweets", "for", "each", "account", "in", "account_file", "and", "write", "to", "outfile", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/collect.py#L85-L95
train
tapilab/brandelion
brandelion/cli/collect.py
fetch_exemplars
def fetch_exemplars(keyword, outfile, n=50): """ Fetch top lists matching this keyword, then return Twitter screen names along with the number of different lists on which each appers.. """ list_urls = fetch_lists(keyword, n) print('found %d lists for %s' % (len(list_urls), keyword)) counts = Counter...
python
def fetch_exemplars(keyword, outfile, n=50): """ Fetch top lists matching this keyword, then return Twitter screen names along with the number of different lists on which each appers.. """ list_urls = fetch_lists(keyword, n) print('found %d lists for %s' % (len(list_urls), keyword)) counts = Counter...
[ "def", "fetch_exemplars", "(", "keyword", ",", "outfile", ",", "n", "=", "50", ")", ":", "list_urls", "=", "fetch_lists", "(", "keyword", ",", "n", ")", "print", "(", "'found %d lists for %s'", "%", "(", "len", "(", "list_urls", ")", ",", "keyword", ")",...
Fetch top lists matching this keyword, then return Twitter screen names along with the number of different lists on which each appers..
[ "Fetch", "top", "lists", "matching", "this", "keyword", "then", "return", "Twitter", "screen", "names", "along", "with", "the", "number", "of", "different", "lists", "on", "which", "each", "appers", ".." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/collect.py#L171-L184
train
tamasgal/km3pipe
km3pipe/io/ch.py
CHPump._init_controlhost
def _init_controlhost(self): """Set up the controlhost connection""" log.debug("Connecting to JLigier") self.client = Client(self.host, self.port) self.client._connect() log.debug("Subscribing to tags: {0}".format(self.tags)) for tag in self.tags.split(','): s...
python
def _init_controlhost(self): """Set up the controlhost connection""" log.debug("Connecting to JLigier") self.client = Client(self.host, self.port) self.client._connect() log.debug("Subscribing to tags: {0}".format(self.tags)) for tag in self.tags.split(','): s...
[ "def", "_init_controlhost", "(", "self", ")", ":", "log", ".", "debug", "(", "\"Connecting to JLigier\"", ")", "self", ".", "client", "=", "Client", "(", "self", ".", "host", ",", "self", ".", "port", ")", "self", ".", "client", ".", "_connect", "(", "...
Set up the controlhost connection
[ "Set", "up", "the", "controlhost", "connection" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/ch.py#L88-L96
train
tamasgal/km3pipe
km3pipe/io/ch.py
CHPump.process
def process(self, blob): """Wait for the next packet and put it in the blob""" # self._add_process_dt() try: log.debug("Waiting for queue items.") prefix, data = self.queue.get(timeout=self.timeout) log.debug("Got {0} bytes from queue.".format(len(data))) ...
python
def process(self, blob): """Wait for the next packet and put it in the blob""" # self._add_process_dt() try: log.debug("Waiting for queue items.") prefix, data = self.queue.get(timeout=self.timeout) log.debug("Got {0} bytes from queue.".format(len(data))) ...
[ "def", "process", "(", "self", ",", "blob", ")", ":", "try", ":", "log", ".", "debug", "(", "\"Waiting for queue items.\"", ")", "prefix", ",", "data", "=", "self", ".", "queue", ".", "get", "(", "timeout", "=", "self", ".", "timeout", ")", "log", "....
Wait for the next packet and put it in the blob
[ "Wait", "for", "the", "next", "packet", "and", "put", "it", "in", "the", "blob" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/ch.py#L140-L154
train
tamasgal/km3pipe
km3pipe/io/ch.py
CHPump.finish
def finish(self): """Clean up the JLigier controlhost connection""" log.debug("Disconnecting from JLigier.") self.client.socket.shutdown(socket.SHUT_RDWR) self.client._disconnect()
python
def finish(self): """Clean up the JLigier controlhost connection""" log.debug("Disconnecting from JLigier.") self.client.socket.shutdown(socket.SHUT_RDWR) self.client._disconnect()
[ "def", "finish", "(", "self", ")", ":", "log", ".", "debug", "(", "\"Disconnecting from JLigier.\"", ")", "self", ".", "client", ".", "socket", ".", "shutdown", "(", "socket", ".", "SHUT_RDWR", ")", "self", ".", "client", ".", "_disconnect", "(", ")" ]
Clean up the JLigier controlhost connection
[ "Clean", "up", "the", "JLigier", "controlhost", "connection" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/ch.py#L176-L180
train
ioos/pyoos
pyoos/collectors/hads/hads.py
Hads.list_variables
def list_variables(self): """ List available variables and applies any filters. """ station_codes = self._get_station_codes() station_codes = self._apply_features_filter(station_codes) variables = self._list_variables(station_codes) if hasattr(self, "_variables")...
python
def list_variables(self): """ List available variables and applies any filters. """ station_codes = self._get_station_codes() station_codes = self._apply_features_filter(station_codes) variables = self._list_variables(station_codes) if hasattr(self, "_variables")...
[ "def", "list_variables", "(", "self", ")", ":", "station_codes", "=", "self", ".", "_get_station_codes", "(", ")", "station_codes", "=", "self", ".", "_apply_features_filter", "(", "station_codes", ")", "variables", "=", "self", ".", "_list_variables", "(", "sta...
List available variables and applies any filters.
[ "List", "available", "variables", "and", "applies", "any", "filters", "." ]
908660385029ecd8eccda8ab3a6b20b47b915c77
https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/collectors/hads/hads.py#L50-L61
train
ioos/pyoos
pyoos/collectors/hads/hads.py
Hads._list_variables
def _list_variables(self, station_codes): """ Internal helper to list the variables for the given station codes. """ # sample output from obs retrieval: # # DD9452D0 # HP(SRBM5) # 2013-07-22 19:30 45.97 # HT(SRBM5) # ...
python
def _list_variables(self, station_codes): """ Internal helper to list the variables for the given station codes. """ # sample output from obs retrieval: # # DD9452D0 # HP(SRBM5) # 2013-07-22 19:30 45.97 # HT(SRBM5) # ...
[ "def", "_list_variables", "(", "self", ",", "station_codes", ")", ":", "rvar", "=", "re", ".", "compile", "(", "r\"\\n\\s([A-Z]{2}[A-Z0-9]{0,1})\\(\\w+\\)\"", ")", "variables", "=", "set", "(", ")", "resp", "=", "requests", ".", "post", "(", "self", ".", "ob...
Internal helper to list the variables for the given station codes.
[ "Internal", "helper", "to", "list", "the", "variables", "for", "the", "given", "station", "codes", "." ]
908660385029ecd8eccda8ab3a6b20b47b915c77
https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/collectors/hads/hads.py#L63-L93
train
ioos/pyoos
pyoos/collectors/hads/hads.py
Hads._apply_features_filter
def _apply_features_filter(self, station_codes): """ If the features filter is set, this will return the intersection of those filter items and the given station codes. """ # apply features filter if hasattr(self, "features") and self.features is not None: sta...
python
def _apply_features_filter(self, station_codes): """ If the features filter is set, this will return the intersection of those filter items and the given station codes. """ # apply features filter if hasattr(self, "features") and self.features is not None: sta...
[ "def", "_apply_features_filter", "(", "self", ",", "station_codes", ")", ":", "if", "hasattr", "(", "self", ",", "\"features\"", ")", "and", "self", ".", "features", "is", "not", "None", ":", "station_codes", "=", "set", "(", "station_codes", ")", "station_c...
If the features filter is set, this will return the intersection of those filter items and the given station codes.
[ "If", "the", "features", "filter", "is", "set", "this", "will", "return", "the", "intersection", "of", "those", "filter", "items", "and", "the", "given", "station", "codes", "." ]
908660385029ecd8eccda8ab3a6b20b47b915c77
https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/collectors/hads/hads.py#L124-L136
train
ioos/pyoos
pyoos/collectors/hads/hads.py
Hads._get_station_codes
def _get_station_codes(self, force=False): """ Gets and caches a list of station codes optionally within a bbox. Will return the cached version if it exists unless force is True. """ if not force and self.station_codes is not None: return self.station_codes ...
python
def _get_station_codes(self, force=False): """ Gets and caches a list of station codes optionally within a bbox. Will return the cached version if it exists unless force is True. """ if not force and self.station_codes is not None: return self.station_codes ...
[ "def", "_get_station_codes", "(", "self", ",", "force", "=", "False", ")", ":", "if", "not", "force", "and", "self", ".", "station_codes", "is", "not", "None", ":", "return", "self", ".", "station_codes", "state_urls", "=", "self", ".", "_get_state_urls", ...
Gets and caches a list of station codes optionally within a bbox. Will return the cached version if it exists unless force is True.
[ "Gets", "and", "caches", "a", "list", "of", "station", "codes", "optionally", "within", "a", "bbox", "." ]
908660385029ecd8eccda8ab3a6b20b47b915c77
https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/collectors/hads/hads.py#L158-L216
train
SentimensRG/txCelery
txcelery/defer.py
DeferredTask._monitor_task
def _monitor_task(self): """Wrapper that handles the actual asynchronous monitoring of the task state. """ if self.task.state in states.UNREADY_STATES: reactor.callLater(self.POLL_PERIOD, self._monitor_task) return if self.task.state == 'SUCCESS': ...
python
def _monitor_task(self): """Wrapper that handles the actual asynchronous monitoring of the task state. """ if self.task.state in states.UNREADY_STATES: reactor.callLater(self.POLL_PERIOD, self._monitor_task) return if self.task.state == 'SUCCESS': ...
[ "def", "_monitor_task", "(", "self", ")", ":", "if", "self", ".", "task", ".", "state", "in", "states", ".", "UNREADY_STATES", ":", "reactor", ".", "callLater", "(", "self", ".", "POLL_PERIOD", ",", "self", ".", "_monitor_task", ")", "return", "if", "sel...
Wrapper that handles the actual asynchronous monitoring of the task state.
[ "Wrapper", "that", "handles", "the", "actual", "asynchronous", "monitoring", "of", "the", "task", "state", "." ]
15b9705198009f5ce6db1bfd0a8af9b8949d6277
https://github.com/SentimensRG/txCelery/blob/15b9705198009f5ce6db1bfd0a8af9b8949d6277/txcelery/defer.py#L52-L71
train
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
_clean_query_string
def _clean_query_string(q): """Clean up a query string for searching. Removes unmatched parentheses and joining operators. Arguments: q (str): Query string to be cleaned Returns: str: The clean query string. """ q = q.replace("()", "").strip() if q.endswith("("): q...
python
def _clean_query_string(q): """Clean up a query string for searching. Removes unmatched parentheses and joining operators. Arguments: q (str): Query string to be cleaned Returns: str: The clean query string. """ q = q.replace("()", "").strip() if q.endswith("("): q...
[ "def", "_clean_query_string", "(", "q", ")", ":", "q", "=", "q", ".", "replace", "(", "\"()\"", ",", "\"\"", ")", ".", "strip", "(", ")", "if", "q", ".", "endswith", "(", "\"(\"", ")", ":", "q", "=", "q", "[", ":", "-", "1", "]", ".", "strip"...
Clean up a query string for searching. Removes unmatched parentheses and joining operators. Arguments: q (str): Query string to be cleaned Returns: str: The clean query string.
[ "Clean", "up", "a", "query", "string", "for", "searching", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L40-L66
train
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
_validate_query
def _validate_query(query): """Validate and clean up a query to be sent to Search. Cleans the query string, removes unneeded parameters, and validates for correctness. Does not modify the original argument. Raises an Exception on invalid input. Arguments: query (dict): The query to validate...
python
def _validate_query(query): """Validate and clean up a query to be sent to Search. Cleans the query string, removes unneeded parameters, and validates for correctness. Does not modify the original argument. Raises an Exception on invalid input. Arguments: query (dict): The query to validate...
[ "def", "_validate_query", "(", "query", ")", ":", "query", "=", "deepcopy", "(", "query", ")", "if", "query", "[", "\"q\"", "]", "==", "BLANK_QUERY", "[", "\"q\"", "]", ":", "raise", "ValueError", "(", "\"No query specified.\"", ")", "query", "[", "\"q\"",...
Validate and clean up a query to be sent to Search. Cleans the query string, removes unneeded parameters, and validates for correctness. Does not modify the original argument. Raises an Exception on invalid input. Arguments: query (dict): The query to validate. Returns: dict: The v...
[ "Validate", "and", "clean", "up", "a", "query", "to", "be", "sent", "to", "Search", ".", "Cleans", "the", "query", "string", "removes", "unneeded", "parameters", "and", "validates", "for", "correctness", ".", "Does", "not", "modify", "the", "original", "argu...
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L69-L107
train
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper._term
def _term(self, term): """Add a term to the query. Arguments: term (str): The term to add. Returns: SearchHelper: Self """ # All terms must be strings for Elasticsearch term = str(term) if term: self.__query["q"] += term ...
python
def _term(self, term): """Add a term to the query. Arguments: term (str): The term to add. Returns: SearchHelper: Self """ # All terms must be strings for Elasticsearch term = str(term) if term: self.__query["q"] += term ...
[ "def", "_term", "(", "self", ",", "term", ")", ":", "term", "=", "str", "(", "term", ")", "if", "term", ":", "self", ".", "__query", "[", "\"q\"", "]", "+=", "term", "return", "self" ]
Add a term to the query. Arguments: term (str): The term to add. Returns: SearchHelper: Self
[ "Add", "a", "term", "to", "the", "query", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L197-L210
train
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper._operator
def _operator(self, op, close_group=False): """Add an operator between terms. There must be a term added before using this method. All operators have helpers, so this method is usually not necessary to directly invoke. Arguments: op (str): The operator to add. Must be in the...
python
def _operator(self, op, close_group=False): """Add an operator between terms. There must be a term added before using this method. All operators have helpers, so this method is usually not necessary to directly invoke. Arguments: op (str): The operator to add. Must be in the...
[ "def", "_operator", "(", "self", ",", "op", ",", "close_group", "=", "False", ")", ":", "op", "=", "op", ".", "upper", "(", ")", ".", "strip", "(", ")", "if", "op", "not", "in", "OP_LIST", ":", "raise", "ValueError", "(", "\"Error: '{}' is not a valid ...
Add an operator between terms. There must be a term added before using this method. All operators have helpers, so this method is usually not necessary to directly invoke. Arguments: op (str): The operator to add. Must be in the OP_LIST. close_group (bool): If ``True``, ...
[ "Add", "an", "operator", "between", "terms", ".", "There", "must", "be", "a", "term", "added", "before", "using", "this", "method", ".", "All", "operators", "have", "helpers", "so", "this", "method", "is", "usually", "not", "necessary", "to", "directly", "...
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L244-L271
train
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper._and_join
def _and_join(self, close_group=False): """Combine terms with AND. There must be a term added before using this method. Arguments: close_group (bool): If ``True``, will end the current group and start a new one. If ``False``, will continue current group. ...
python
def _and_join(self, close_group=False): """Combine terms with AND. There must be a term added before using this method. Arguments: close_group (bool): If ``True``, will end the current group and start a new one. If ``False``, will continue current group. ...
[ "def", "_and_join", "(", "self", ",", "close_group", "=", "False", ")", ":", "if", "not", "self", ".", "initialized", ":", "raise", "ValueError", "(", "\"You must add a search term before adding an operator.\"", ")", "else", ":", "self", ".", "_operator", "(", "...
Combine terms with AND. There must be a term added before using this method. Arguments: close_group (bool): If ``True``, will end the current group and start a new one. If ``False``, will continue current group. Example:: If ...
[ "Combine", "terms", "with", "AND", ".", "There", "must", "be", "a", "term", "added", "before", "using", "this", "method", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L273-L294
train
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper._or_join
def _or_join(self, close_group=False): """Combine terms with OR. There must be a term added before using this method. Arguments: close_group (bool): If ``True``, will end the current group and start a new one. If ``False``, will continue current group. ...
python
def _or_join(self, close_group=False): """Combine terms with OR. There must be a term added before using this method. Arguments: close_group (bool): If ``True``, will end the current group and start a new one. If ``False``, will continue current group. ...
[ "def", "_or_join", "(", "self", ",", "close_group", "=", "False", ")", ":", "if", "not", "self", ".", "initialized", ":", "raise", "ValueError", "(", "\"You must add a search term before adding an operator.\"", ")", "else", ":", "self", ".", "_operator", "(", "\...
Combine terms with OR. There must be a term added before using this method. Arguments: close_group (bool): If ``True``, will end the current group and start a new one. If ``False``, will continue current group. Example: If th...
[ "Combine", "terms", "with", "OR", ".", "There", "must", "be", "a", "term", "added", "before", "using", "this", "method", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L296-L317
train
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper._mapping
def _mapping(self): """Fetch the entire mapping for the specified index. Returns: dict: The full mapping for the index. """ return (self.__search_client.get( "/unstable/index/{}/mapping".format(mdf_toolbox.translate_index(self.index))) ["m...
python
def _mapping(self): """Fetch the entire mapping for the specified index. Returns: dict: The full mapping for the index. """ return (self.__search_client.get( "/unstable/index/{}/mapping".format(mdf_toolbox.translate_index(self.index))) ["m...
[ "def", "_mapping", "(", "self", ")", ":", "return", "(", "self", ".", "__search_client", ".", "get", "(", "\"/unstable/index/{}/mapping\"", ".", "format", "(", "mdf_toolbox", ".", "translate_index", "(", "self", ".", "index", ")", ")", ")", "[", "\"mappings\...
Fetch the entire mapping for the specified index. Returns: dict: The full mapping for the index.
[ "Fetch", "the", "entire", "mapping", "for", "the", "specified", "index", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L418-L426
train
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper.match_term
def match_term(self, value, required=True, new_group=False): """Add a fulltext search term to the query. Warning: Do not use this method with any other query-building helpers. This method is only for building fulltext queries (in non-advanced mode). Using other helpe...
python
def match_term(self, value, required=True, new_group=False): """Add a fulltext search term to the query. Warning: Do not use this method with any other query-building helpers. This method is only for building fulltext queries (in non-advanced mode). Using other helpe...
[ "def", "match_term", "(", "self", ",", "value", ",", "required", "=", "True", ",", "new_group", "=", "False", ")", ":", "if", "self", ".", "initialized", ":", "if", "required", ":", "self", ".", "_and_join", "(", "new_group", ")", "else", ":", "self", ...
Add a fulltext search term to the query. Warning: Do not use this method with any other query-building helpers. This method is only for building fulltext queries (in non-advanced mode). Using other helpers, such as ``match_field()``, will cause the query to run in advanced m...
[ "Add", "a", "fulltext", "search", "term", "to", "the", "query", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L435-L463
train
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper.match_exists
def match_exists(self, field, required=True, new_group=False): """Require a field to exist in the results. Matches will have some value in ``field``. Arguments: field (str): The field to check. The field must be namespaced according to Elasticsearch rules ...
python
def match_exists(self, field, required=True, new_group=False): """Require a field to exist in the results. Matches will have some value in ``field``. Arguments: field (str): The field to check. The field must be namespaced according to Elasticsearch rules ...
[ "def", "match_exists", "(", "self", ",", "field", ",", "required", "=", "True", ",", "new_group", "=", "False", ")", ":", "return", "self", ".", "match_field", "(", "field", ",", "\"*\"", ",", "required", "=", "required", ",", "new_group", "=", "new_grou...
Require a field to exist in the results. Matches will have some value in ``field``. Arguments: field (str): The field to check. The field must be namespaced according to Elasticsearch rules using the dot syntax. For example, ``"mdf...
[ "Require", "a", "field", "to", "exist", "in", "the", "results", ".", "Matches", "will", "have", "some", "value", "in", "field", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L522-L541
train
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper.match_not_exists
def match_not_exists(self, field, new_group=False): """Require a field to not exist in the results. Matches will not have ``field`` present. Arguments: field (str): The field to check. The field must be namespaced according to Elasticsearch rules ...
python
def match_not_exists(self, field, new_group=False): """Require a field to not exist in the results. Matches will not have ``field`` present. Arguments: field (str): The field to check. The field must be namespaced according to Elasticsearch rules ...
[ "def", "match_not_exists", "(", "self", ",", "field", ",", "new_group", "=", "False", ")", ":", "return", "self", ".", "exclude_field", "(", "field", ",", "\"*\"", ",", "new_group", "=", "new_group", ")" ]
Require a field to not exist in the results. Matches will not have ``field`` present. Arguments: field (str): The field to check. The field must be namespaced according to Elasticsearch rules using the dot syntax. For example, ``"m...
[ "Require", "a", "field", "to", "not", "exist", "in", "the", "results", ".", "Matches", "will", "not", "have", "field", "present", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L543-L560
train
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
SearchHelper.show_fields
def show_fields(self, block=None): """Retrieve and return the mapping for the given metadata block. Arguments: block (str): The top-level field to fetch the mapping for (for example, ``"mdf"``), or the special values ``None`` for everything or ``"top"`` for just the ...
python
def show_fields(self, block=None): """Retrieve and return the mapping for the given metadata block. Arguments: block (str): The top-level field to fetch the mapping for (for example, ``"mdf"``), or the special values ``None`` for everything or ``"top"`` for just the ...
[ "def", "show_fields", "(", "self", ",", "block", "=", "None", ")", ":", "mapping", "=", "self", ".", "_mapping", "(", ")", "if", "block", "is", "None", ":", "return", "mapping", "elif", "block", "==", "\"top\"", ":", "blocks", "=", "set", "(", ")", ...
Retrieve and return the mapping for the given metadata block. Arguments: block (str): The top-level field to fetch the mapping for (for example, ``"mdf"``), or the special values ``None`` for everything or ``"top"`` for just the top-level fields. ...
[ "Retrieve", "and", "return", "the", "mapping", "for", "the", "given", "metadata", "block", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L764-L792
train
tamasgal/km3pipe
km3pipe/dataclasses.py
inflate_dtype
def inflate_dtype(arr, names): """Create structured dtype from a 2d ndarray with unstructured dtype.""" arr = np.asanyarray(arr) if has_structured_dt(arr): return arr.dtype s_dt = arr.dtype dt = [(n, s_dt) for n in names] dt = np.dtype(dt) return dt
python
def inflate_dtype(arr, names): """Create structured dtype from a 2d ndarray with unstructured dtype.""" arr = np.asanyarray(arr) if has_structured_dt(arr): return arr.dtype s_dt = arr.dtype dt = [(n, s_dt) for n in names] dt = np.dtype(dt) return dt
[ "def", "inflate_dtype", "(", "arr", ",", "names", ")", ":", "arr", "=", "np", ".", "asanyarray", "(", "arr", ")", "if", "has_structured_dt", "(", "arr", ")", ":", "return", "arr", ".", "dtype", "s_dt", "=", "arr", ".", "dtype", "dt", "=", "[", "(",...
Create structured dtype from a 2d ndarray with unstructured dtype.
[ "Create", "structured", "dtype", "from", "a", "2d", "ndarray", "with", "unstructured", "dtype", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/dataclasses.py#L48-L56
train
tamasgal/km3pipe
km3pipe/dataclasses.py
Table.from_dict
def from_dict(cls, arr_dict, dtype=None, fillna=False, **kwargs): """Generate a table from a dictionary of arrays. """ # i hope order of keys == order or values if dtype is None: names = sorted(list(arr_dict.keys())) else: dtype = np.dtype(dtype) ...
python
def from_dict(cls, arr_dict, dtype=None, fillna=False, **kwargs): """Generate a table from a dictionary of arrays. """ # i hope order of keys == order or values if dtype is None: names = sorted(list(arr_dict.keys())) else: dtype = np.dtype(dtype) ...
[ "def", "from_dict", "(", "cls", ",", "arr_dict", ",", "dtype", "=", "None", ",", "fillna", "=", "False", ",", "**", "kwargs", ")", ":", "if", "dtype", "is", "None", ":", "names", "=", "sorted", "(", "list", "(", "arr_dict", ".", "keys", "(", ")", ...
Generate a table from a dictionary of arrays.
[ "Generate", "a", "table", "from", "a", "dictionary", "of", "arrays", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/dataclasses.py#L246-L270
train
tamasgal/km3pipe
km3pipe/dataclasses.py
Table.from_template
def from_template(cls, data, template): """Create a table from a predefined datatype. See the ``templates_avail`` property for available names. Parameters ---------- data Data in a format that the ``__init__`` understands. template: str or dict N...
python
def from_template(cls, data, template): """Create a table from a predefined datatype. See the ``templates_avail`` property for available names. Parameters ---------- data Data in a format that the ``__init__`` understands. template: str or dict N...
[ "def", "from_template", "(", "cls", ",", "data", ",", "template", ")", ":", "name", "=", "DEFAULT_NAME", "if", "isinstance", "(", "template", ",", "str", ")", ":", "name", "=", "template", "table_info", "=", "TEMPLATES", "[", "name", "]", "else", ":", ...
Create a table from a predefined datatype. See the ``templates_avail`` property for available names. Parameters ---------- data Data in a format that the ``__init__`` understands. template: str or dict Name of the dtype template to use from ``kp.dataclas...
[ "Create", "a", "table", "from", "a", "predefined", "datatype", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/dataclasses.py#L314-L348
train
tamasgal/km3pipe
km3pipe/dataclasses.py
Table.append_columns
def append_columns(self, colnames, values, **kwargs): """Append new columns to the table. When appending a single column, ``values`` can be a scalar or an array of either length 1 or the same length as this array (the one it's appended to). In case of multiple columns, values must have ...
python
def append_columns(self, colnames, values, **kwargs): """Append new columns to the table. When appending a single column, ``values`` can be a scalar or an array of either length 1 or the same length as this array (the one it's appended to). In case of multiple columns, values must have ...
[ "def", "append_columns", "(", "self", ",", "colnames", ",", "values", ",", "**", "kwargs", ")", ":", "n", "=", "len", "(", "self", ")", "if", "np", ".", "isscalar", "(", "values", ")", ":", "values", "=", "np", ".", "full", "(", "n", ",", "values...
Append new columns to the table. When appending a single column, ``values`` can be a scalar or an array of either length 1 or the same length as this array (the one it's appended to). In case of multiple columns, values must have the shape ``list(arrays)``, and the dimension of each arr...
[ "Append", "new", "columns", "to", "the", "table", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/dataclasses.py#L362-L402
train
tamasgal/km3pipe
km3pipe/dataclasses.py
Table.drop_columns
def drop_columns(self, colnames, **kwargs): """Drop columns from the table. See the docs for ``numpy.lib.recfunctions.drop_fields`` for an explanation of the remaining options. """ new_arr = rfn.drop_fields( self, colnames, usemask=False, asrecarray=True, **kwargs ...
python
def drop_columns(self, colnames, **kwargs): """Drop columns from the table. See the docs for ``numpy.lib.recfunctions.drop_fields`` for an explanation of the remaining options. """ new_arr = rfn.drop_fields( self, colnames, usemask=False, asrecarray=True, **kwargs ...
[ "def", "drop_columns", "(", "self", ",", "colnames", ",", "**", "kwargs", ")", ":", "new_arr", "=", "rfn", ".", "drop_fields", "(", "self", ",", "colnames", ",", "usemask", "=", "False", ",", "asrecarray", "=", "True", ",", "**", "kwargs", ")", "return...
Drop columns from the table. See the docs for ``numpy.lib.recfunctions.drop_fields`` for an explanation of the remaining options.
[ "Drop", "columns", "from", "the", "table", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/dataclasses.py#L404-L419
train
tamasgal/km3pipe
km3pipe/dataclasses.py
Table.sorted
def sorted(self, by, **kwargs): """Sort array by a column. Parameters ========== by: str Name of the columns to sort by(e.g. 'time'). """ sort_idc = np.argsort(self[by], **kwargs) return self.__class__( self[sort_idc], h5loc=se...
python
def sorted(self, by, **kwargs): """Sort array by a column. Parameters ========== by: str Name of the columns to sort by(e.g. 'time'). """ sort_idc = np.argsort(self[by], **kwargs) return self.__class__( self[sort_idc], h5loc=se...
[ "def", "sorted", "(", "self", ",", "by", ",", "**", "kwargs", ")", ":", "sort_idc", "=", "np", ".", "argsort", "(", "self", "[", "by", "]", ",", "**", "kwargs", ")", "return", "self", ".", "__class__", "(", "self", "[", "sort_idc", "]", ",", "h5l...
Sort array by a column. Parameters ========== by: str Name of the columns to sort by(e.g. 'time').
[ "Sort", "array", "by", "a", "column", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/dataclasses.py#L421-L435
train
tamasgal/km3pipe
km3pipe/dataclasses.py
Table.merge
def merge(cls, tables, fillna=False): """Merge a list of tables""" cols = set(itertools.chain(*[table.dtype.descr for table in tables])) tables_to_merge = [] for table in tables: missing_cols = cols - set(table.dtype.descr) if missing_cols: if fi...
python
def merge(cls, tables, fillna=False): """Merge a list of tables""" cols = set(itertools.chain(*[table.dtype.descr for table in tables])) tables_to_merge = [] for table in tables: missing_cols = cols - set(table.dtype.descr) if missing_cols: if fi...
[ "def", "merge", "(", "cls", ",", "tables", ",", "fillna", "=", "False", ")", ":", "cols", "=", "set", "(", "itertools", ".", "chain", "(", "*", "[", "table", ".", "dtype", ".", "descr", "for", "table", "in", "tables", "]", ")", ")", "tables_to_merg...
Merge a list of tables
[ "Merge", "a", "list", "of", "tables" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/dataclasses.py#L447-L487
train
tamasgal/km3pipe
km3pipe/io/hdf5.py
create_index_tuple
def create_index_tuple(group_ids): """An helper function to create index tuples for fast lookup in HDF5Pump""" max_group_id = np.max(group_ids) start_idx_arr = np.full(max_group_id + 1, 0) n_items_arr = np.full(max_group_id + 1, 0) current_group_id = group_ids[0] current_idx = 0 item_count...
python
def create_index_tuple(group_ids): """An helper function to create index tuples for fast lookup in HDF5Pump""" max_group_id = np.max(group_ids) start_idx_arr = np.full(max_group_id + 1, 0) n_items_arr = np.full(max_group_id + 1, 0) current_group_id = group_ids[0] current_idx = 0 item_count...
[ "def", "create_index_tuple", "(", "group_ids", ")", ":", "max_group_id", "=", "np", ".", "max", "(", "group_ids", ")", "start_idx_arr", "=", "np", ".", "full", "(", "max_group_id", "+", "1", ",", "0", ")", "n_items_arr", "=", "np", ".", "full", "(", "m...
An helper function to create index tuples for fast lookup in HDF5Pump
[ "An", "helper", "function", "to", "create", "index", "tuples", "for", "fast", "lookup", "in", "HDF5Pump" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/hdf5.py#L892-L915
train
tamasgal/km3pipe
km3pipe/io/hdf5.py
HDF5Header._set_attributes
def _set_attributes(self): """Traverse the internal dictionary and set the getters""" for parameter, data in self._data.items(): if isinstance(data, dict) or isinstance(data, OrderedDict): field_names, field_values = zip(*data.items()) sorted_indices = np.args...
python
def _set_attributes(self): """Traverse the internal dictionary and set the getters""" for parameter, data in self._data.items(): if isinstance(data, dict) or isinstance(data, OrderedDict): field_names, field_values = zip(*data.items()) sorted_indices = np.args...
[ "def", "_set_attributes", "(", "self", ")", ":", "for", "parameter", ",", "data", "in", "self", ".", "_data", ".", "items", "(", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", "or", "isinstance", "(", "data", ",", "OrderedDict", ")", ":...
Traverse the internal dictionary and set the getters
[ "Traverse", "the", "internal", "dictionary", "and", "set", "the", "getters" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/hdf5.py#L74-L88
train
tamasgal/km3pipe
km3pipe/io/hdf5.py
HDF5Sink._write_ndarrays_cache_to_disk
def _write_ndarrays_cache_to_disk(self): """Writes all the cached NDArrays to disk and empties the cache""" for h5loc, arrs in self._ndarrays_cache.items(): title = arrs[0].title chunkshape = (self.chunksize,) + arrs[0].shape[1:] if self.chunksize is not\ ...
python
def _write_ndarrays_cache_to_disk(self): """Writes all the cached NDArrays to disk and empties the cache""" for h5loc, arrs in self._ndarrays_cache.items(): title = arrs[0].title chunkshape = (self.chunksize,) + arrs[0].shape[1:] if self.chunksize is not\ ...
[ "def", "_write_ndarrays_cache_to_disk", "(", "self", ")", ":", "for", "h5loc", ",", "arrs", "in", "self", ".", "_ndarrays_cache", ".", "items", "(", ")", ":", "title", "=", "arrs", "[", "0", "]", ".", "title", "chunkshape", "=", "(", "self", ".", "chun...
Writes all the cached NDArrays to disk and empties the cache
[ "Writes", "all", "the", "cached", "NDArrays", "to", "disk", "and", "empties", "the", "cache" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/hdf5.py#L254-L289
train
tamasgal/km3pipe
km3pipe/io/hdf5.py
HDF5Sink.flush
def flush(self): """Flush tables and arrays to disk""" self.log.info('Flushing tables and arrays to disk...') for tab in self._tables.values(): tab.flush() self._write_ndarrays_cache_to_disk()
python
def flush(self): """Flush tables and arrays to disk""" self.log.info('Flushing tables and arrays to disk...') for tab in self._tables.values(): tab.flush() self._write_ndarrays_cache_to_disk()
[ "def", "flush", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "'Flushing tables and arrays to disk...'", ")", "for", "tab", "in", "self", ".", "_tables", ".", "values", "(", ")", ":", "tab", ".", "flush", "(", ")", "self", ".", "_write_n...
Flush tables and arrays to disk
[ "Flush", "tables", "and", "arrays", "to", "disk" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/hdf5.py#L450-L455
train
cprogrammer1994/GLWindow
GLWindow/__main__.py
main
def main(): ''' Sample program to test GLWindow. ''' print('GLWindow:', GLWindow.__version__) print('Python:', sys.version) print('Platform:', sys.platform) wnd = GLWindow.create_window((480, 480), title='GLWindow Sample') wnd.vsync = False ctx = ModernGL.create_context() ...
python
def main(): ''' Sample program to test GLWindow. ''' print('GLWindow:', GLWindow.__version__) print('Python:', sys.version) print('Platform:', sys.platform) wnd = GLWindow.create_window((480, 480), title='GLWindow Sample') wnd.vsync = False ctx = ModernGL.create_context() ...
[ "def", "main", "(", ")", ":", "print", "(", "'GLWindow:'", ",", "GLWindow", ".", "__version__", ")", "print", "(", "'Python:'", ",", "sys", ".", "version", ")", "print", "(", "'Platform:'", ",", "sys", ".", "platform", ")", "wnd", "=", "GLWindow", ".",...
Sample program to test GLWindow.
[ "Sample", "program", "to", "test", "GLWindow", "." ]
521e18fcbc15e88d3c1f3547aa313c3a07386ee5
https://github.com/cprogrammer1994/GLWindow/blob/521e18fcbc15e88d3c1f3547aa313c3a07386ee5/GLWindow/__main__.py#L12-L71
train
tamasgal/km3pipe
examples/offline_analysis/k40summary.py
write_header
def write_header(fobj): """Add the header to the CSV file""" fobj.write("# K40 calibration results\n") fobj.write("det_id\trun_id\tdom_id") for param in ['t0', 'qe']: for i in range(31): fobj.write("\t{}_ch{}".format(param, i))
python
def write_header(fobj): """Add the header to the CSV file""" fobj.write("# K40 calibration results\n") fobj.write("det_id\trun_id\tdom_id") for param in ['t0', 'qe']: for i in range(31): fobj.write("\t{}_ch{}".format(param, i))
[ "def", "write_header", "(", "fobj", ")", ":", "fobj", ".", "write", "(", "\"# K40 calibration results\\n\"", ")", "fobj", ".", "write", "(", "\"det_id\\trun_id\\tdom_id\"", ")", "for", "param", "in", "[", "'t0'", ",", "'qe'", "]", ":", "for", "i", "in", "r...
Add the header to the CSV file
[ "Add", "the", "header", "to", "the", "CSV", "file" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/examples/offline_analysis/k40summary.py#L30-L36
train
tamasgal/km3pipe
km3pipe/math.py
azimuth
def azimuth(v): """Return the azimuth angle in radians. ``phi``, ``theta`` is the opposite of ``zenith``, ``azimuth``. This is the 'normal' azimuth definition -- beware of how you define your coordinates. KM3NeT defines azimuth differently than e.g. SLALIB, astropy, the AAS.org """ v = np....
python
def azimuth(v): """Return the azimuth angle in radians. ``phi``, ``theta`` is the opposite of ``zenith``, ``azimuth``. This is the 'normal' azimuth definition -- beware of how you define your coordinates. KM3NeT defines azimuth differently than e.g. SLALIB, astropy, the AAS.org """ v = np....
[ "def", "azimuth", "(", "v", ")", ":", "v", "=", "np", ".", "atleast_2d", "(", "v", ")", "azi", "=", "phi", "(", "v", ")", "-", "np", ".", "pi", "azi", "[", "azi", "<", "0", "]", "+=", "2", "*", "np", ".", "pi", "if", "len", "(", "azi", ...
Return the azimuth angle in radians. ``phi``, ``theta`` is the opposite of ``zenith``, ``azimuth``. This is the 'normal' azimuth definition -- beware of how you define your coordinates. KM3NeT defines azimuth differently than e.g. SLALIB, astropy, the AAS.org
[ "Return", "the", "azimuth", "angle", "in", "radians", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L119-L133
train
tamasgal/km3pipe
km3pipe/math.py
unit_vector
def unit_vector(vector, **kwargs): """Returns the unit vector of the vector.""" # This also works for a dataframe with columns ['x', 'y', 'z'] # However, the division operation is picky about the shapes # So, remember input vector shape, cast all up to 2d, # do the (ugly) conversion, then return uni...
python
def unit_vector(vector, **kwargs): """Returns the unit vector of the vector.""" # This also works for a dataframe with columns ['x', 'y', 'z'] # However, the division operation is picky about the shapes # So, remember input vector shape, cast all up to 2d, # do the (ugly) conversion, then return uni...
[ "def", "unit_vector", "(", "vector", ",", "**", "kwargs", ")", ":", "vector", "=", "np", ".", "array", "(", "vector", ")", "out_shape", "=", "vector", ".", "shape", "vector", "=", "np", ".", "atleast_2d", "(", "vector", ")", "unit", "=", "vector", "/...
Returns the unit vector of the vector.
[ "Returns", "the", "unit", "vector", "of", "the", "vector", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L175-L186
train
tamasgal/km3pipe
km3pipe/math.py
pld3
def pld3(pos, line_vertex, line_dir): """Calculate the point-line-distance for given point and line.""" pos = np.atleast_2d(pos) line_vertex = np.atleast_1d(line_vertex) line_dir = np.atleast_1d(line_dir) c = np.cross(line_dir, line_vertex - pos) n1 = np.linalg.norm(c, axis=1) n2 = np.linalg...
python
def pld3(pos, line_vertex, line_dir): """Calculate the point-line-distance for given point and line.""" pos = np.atleast_2d(pos) line_vertex = np.atleast_1d(line_vertex) line_dir = np.atleast_1d(line_dir) c = np.cross(line_dir, line_vertex - pos) n1 = np.linalg.norm(c, axis=1) n2 = np.linalg...
[ "def", "pld3", "(", "pos", ",", "line_vertex", ",", "line_dir", ")", ":", "pos", "=", "np", ".", "atleast_2d", "(", "pos", ")", "line_vertex", "=", "np", ".", "atleast_1d", "(", "line_vertex", ")", "line_dir", "=", "np", ".", "atleast_1d", "(", "line_d...
Calculate the point-line-distance for given point and line.
[ "Calculate", "the", "point", "-", "line", "-", "distance", "for", "given", "point", "and", "line", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L189-L200
train
tamasgal/km3pipe
km3pipe/math.py
dist
def dist(x1, x2, axis=0): """Return the distance between two points. Set axis=1 if x1 is a vector and x2 a matrix to get a vector of distances. """ return np.linalg.norm(x2 - x1, axis=axis)
python
def dist(x1, x2, axis=0): """Return the distance between two points. Set axis=1 if x1 is a vector and x2 a matrix to get a vector of distances. """ return np.linalg.norm(x2 - x1, axis=axis)
[ "def", "dist", "(", "x1", ",", "x2", ",", "axis", "=", "0", ")", ":", "return", "np", ".", "linalg", ".", "norm", "(", "x2", "-", "x1", ",", "axis", "=", "axis", ")" ]
Return the distance between two points. Set axis=1 if x1 is a vector and x2 a matrix to get a vector of distances.
[ "Return", "the", "distance", "between", "two", "points", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L207-L212
train
tamasgal/km3pipe
km3pipe/math.py
com
def com(points, masses=None): """Calculate center of mass for given points. If masses is not set, assume equal masses.""" if masses is None: return np.average(points, axis=0) else: return np.average(points, axis=0, weights=masses)
python
def com(points, masses=None): """Calculate center of mass for given points. If masses is not set, assume equal masses.""" if masses is None: return np.average(points, axis=0) else: return np.average(points, axis=0, weights=masses)
[ "def", "com", "(", "points", ",", "masses", "=", "None", ")", ":", "if", "masses", "is", "None", ":", "return", "np", ".", "average", "(", "points", ",", "axis", "=", "0", ")", "else", ":", "return", "np", ".", "average", "(", "points", ",", "axi...
Calculate center of mass for given points. If masses is not set, assume equal masses.
[ "Calculate", "center", "of", "mass", "for", "given", "points", ".", "If", "masses", "is", "not", "set", "assume", "equal", "masses", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L215-L221
train
tamasgal/km3pipe
km3pipe/math.py
circ_permutation
def circ_permutation(items): """Calculate the circular permutation for a given list of items.""" permutations = [] for i in range(len(items)): permutations.append(items[i:] + items[:i]) return permutations
python
def circ_permutation(items): """Calculate the circular permutation for a given list of items.""" permutations = [] for i in range(len(items)): permutations.append(items[i:] + items[:i]) return permutations
[ "def", "circ_permutation", "(", "items", ")", ":", "permutations", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "items", ")", ")", ":", "permutations", ".", "append", "(", "items", "[", "i", ":", "]", "+", "items", "[", ":", "i", "]...
Calculate the circular permutation for a given list of items.
[ "Calculate", "the", "circular", "permutation", "for", "a", "given", "list", "of", "items", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L224-L229
train
tamasgal/km3pipe
km3pipe/math.py
inertia
def inertia(x, y, z, weight=None): """Inertia tensor, stolen of thomas""" if weight is None: weight = 1 tensor_of_inertia = np.zeros((3, 3), dtype=float) tensor_of_inertia[0][0] = (y * y + z * z) * weight tensor_of_inertia[0][1] = (-1) * x * y * weight tensor_of_inertia[0][2] = (-1) * x ...
python
def inertia(x, y, z, weight=None): """Inertia tensor, stolen of thomas""" if weight is None: weight = 1 tensor_of_inertia = np.zeros((3, 3), dtype=float) tensor_of_inertia[0][0] = (y * y + z * z) * weight tensor_of_inertia[0][1] = (-1) * x * y * weight tensor_of_inertia[0][2] = (-1) * x ...
[ "def", "inertia", "(", "x", ",", "y", ",", "z", ",", "weight", "=", "None", ")", ":", "if", "weight", "is", "None", ":", "weight", "=", "1", "tensor_of_inertia", "=", "np", ".", "zeros", "(", "(", "3", ",", "3", ")", ",", "dtype", "=", "float",...
Inertia tensor, stolen of thomas
[ "Inertia", "tensor", "stolen", "of", "thomas" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L381-L400
train
tamasgal/km3pipe
km3pipe/math.py
qrot
def qrot(vector, quaternion): """Rotate a 3D vector using quaternion algebra. Implemented by Vladimir Kulikovskiy. Parameters ---------- vector: np.array quaternion: np.array Returns ------- np.array """ t = 2 * np.cross(quaternion[1:], vector) v_rot = vector + quater...
python
def qrot(vector, quaternion): """Rotate a 3D vector using quaternion algebra. Implemented by Vladimir Kulikovskiy. Parameters ---------- vector: np.array quaternion: np.array Returns ------- np.array """ t = 2 * np.cross(quaternion[1:], vector) v_rot = vector + quater...
[ "def", "qrot", "(", "vector", ",", "quaternion", ")", ":", "t", "=", "2", "*", "np", ".", "cross", "(", "quaternion", "[", "1", ":", "]", ",", "vector", ")", "v_rot", "=", "vector", "+", "quaternion", "[", "0", "]", "*", "t", "+", "np", ".", ...
Rotate a 3D vector using quaternion algebra. Implemented by Vladimir Kulikovskiy. Parameters ---------- vector: np.array quaternion: np.array Returns ------- np.array
[ "Rotate", "a", "3D", "vector", "using", "quaternion", "algebra", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L425-L442
train
tamasgal/km3pipe
km3pipe/math.py
qeuler
def qeuler(yaw, pitch, roll): """Convert Euler angle to quaternion. Parameters ---------- yaw: number pitch: number roll: number Returns ------- np.array """ yaw = np.radians(yaw) pitch = np.radians(pitch) roll = np.radians(roll) cy = np.cos(yaw * 0.5) sy ...
python
def qeuler(yaw, pitch, roll): """Convert Euler angle to quaternion. Parameters ---------- yaw: number pitch: number roll: number Returns ------- np.array """ yaw = np.radians(yaw) pitch = np.radians(pitch) roll = np.radians(roll) cy = np.cos(yaw * 0.5) sy ...
[ "def", "qeuler", "(", "yaw", ",", "pitch", ",", "roll", ")", ":", "yaw", "=", "np", ".", "radians", "(", "yaw", ")", "pitch", "=", "np", ".", "radians", "(", "pitch", ")", "roll", "=", "np", ".", "radians", "(", "roll", ")", "cy", "=", "np", ...
Convert Euler angle to quaternion. Parameters ---------- yaw: number pitch: number roll: number Returns ------- np.array
[ "Convert", "Euler", "angle", "to", "quaternion", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L445-L474
train
tamasgal/km3pipe
km3pipe/math.py
intersect_3d
def intersect_3d(p1, p2): """Find the closes point for a given set of lines in 3D. Parameters ---------- p1 : (M, N) array_like Starting points p2 : (M, N) array_like End points. Returns ------- x : (N,) ndarray Least-squares solution - the closest point of the ...
python
def intersect_3d(p1, p2): """Find the closes point for a given set of lines in 3D. Parameters ---------- p1 : (M, N) array_like Starting points p2 : (M, N) array_like End points. Returns ------- x : (N,) ndarray Least-squares solution - the closest point of the ...
[ "def", "intersect_3d", "(", "p1", ",", "p2", ")", ":", "v", "=", "p2", "-", "p1", "normed_v", "=", "unit_vector", "(", "v", ")", "nx", "=", "normed_v", "[", ":", ",", "0", "]", "ny", "=", "normed_v", "[", ":", ",", "1", "]", "nz", "=", "norme...
Find the closes point for a given set of lines in 3D. Parameters ---------- p1 : (M, N) array_like Starting points p2 : (M, N) array_like End points. Returns ------- x : (N,) ndarray Least-squares solution - the closest point of the intersections. Raises --...
[ "Find", "the", "closes", "point", "for", "a", "given", "set", "of", "lines", "in", "3D", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L494-L536
train
astooke/gtimer
gtimer/util.py
compat_py2_py3
def compat_py2_py3(): """ For Python 2, 3 compatibility. """ if (sys.version_info > (3, 0)): def iteritems(dictionary): return dictionary.items() def itervalues(dictionary): return dictionary.values() else: def iteritems(dictionary): return dicti...
python
def compat_py2_py3(): """ For Python 2, 3 compatibility. """ if (sys.version_info > (3, 0)): def iteritems(dictionary): return dictionary.items() def itervalues(dictionary): return dictionary.values() else: def iteritems(dictionary): return dicti...
[ "def", "compat_py2_py3", "(", ")", ":", "if", "(", "sys", ".", "version_info", ">", "(", "3", ",", "0", ")", ")", ":", "def", "iteritems", "(", "dictionary", ")", ":", "return", "dictionary", ".", "items", "(", ")", "def", "itervalues", "(", "diction...
For Python 2, 3 compatibility.
[ "For", "Python", "2", "3", "compatibility", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/util.py#L20-L36
train
tamasgal/km3pipe
km3pipe/io/jpp.py
TimeslicePump.timeslice_generator
def timeslice_generator(self): """Uses slice ID as iterator""" slice_id = 0 while slice_id < self.n_timeslices: blob = self.get_blob(slice_id) yield blob slice_id += 1
python
def timeslice_generator(self): """Uses slice ID as iterator""" slice_id = 0 while slice_id < self.n_timeslices: blob = self.get_blob(slice_id) yield blob slice_id += 1
[ "def", "timeslice_generator", "(", "self", ")", ":", "slice_id", "=", "0", "while", "slice_id", "<", "self", ".", "n_timeslices", ":", "blob", "=", "self", ".", "get_blob", "(", "slice_id", ")", "yield", "blob", "slice_id", "+=", "1" ]
Uses slice ID as iterator
[ "Uses", "slice", "ID", "as", "iterator" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/jpp.py#L185-L191
train
tamasgal/km3pipe
km3pipe/io/jpp.py
TimeslicePump.get_blob
def get_blob(self, index): """Index is slice ID""" blob = self._current_blob self.r.retrieve_timeslice(index) timeslice_info = Table.from_template({ 'frame_index': self.r.frame_index, 'slice_id': index, 'timestamp': self.r.utc_seconds, 'nan...
python
def get_blob(self, index): """Index is slice ID""" blob = self._current_blob self.r.retrieve_timeslice(index) timeslice_info = Table.from_template({ 'frame_index': self.r.frame_index, 'slice_id': index, 'timestamp': self.r.utc_seconds, 'nan...
[ "def", "get_blob", "(", "self", ",", "index", ")", ":", "blob", "=", "self", ".", "_current_blob", "self", ".", "r", ".", "retrieve_timeslice", "(", "index", ")", "timeslice_info", "=", "Table", ".", "from_template", "(", "{", "'frame_index'", ":", "self",...
Index is slice ID
[ "Index", "is", "slice", "ID" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/jpp.py#L193-L208
train
tamasgal/km3pipe
km3pipe/io/jpp.py
TimeslicePump._slice_generator
def _slice_generator(self, index): """A simple slice generator for iterations""" start, stop, step = index.indices(len(self)) for i in range(start, stop, step): yield self.get_blob(i)
python
def _slice_generator(self, index): """A simple slice generator for iterations""" start, stop, step = index.indices(len(self)) for i in range(start, stop, step): yield self.get_blob(i)
[ "def", "_slice_generator", "(", "self", ",", "index", ")", ":", "start", ",", "stop", ",", "step", "=", "index", ".", "indices", "(", "len", "(", "self", ")", ")", "for", "i", "in", "range", "(", "start", ",", "stop", ",", "step", ")", ":", "yiel...
A simple slice generator for iterations
[ "A", "simple", "slice", "generator", "for", "iterations" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/jpp.py#L270-L274
train
tapilab/brandelion
brandelion/cli/diagnose.py
correlation_by_exemplar
def correlation_by_exemplar(brands, exemplars, validation_scores, analyze_fn_str, outf): """ Report the overall correlation with the validation scores using each exemplar in isolation. """ analyze_fn = getattr(analyze, analyze_fn_str) keys = sorted(k for k in validation_scores.keys() if k in set(x[0] for x ...
python
def correlation_by_exemplar(brands, exemplars, validation_scores, analyze_fn_str, outf): """ Report the overall correlation with the validation scores using each exemplar in isolation. """ analyze_fn = getattr(analyze, analyze_fn_str) keys = sorted(k for k in validation_scores.keys() if k in set(x[0] for x ...
[ "def", "correlation_by_exemplar", "(", "brands", ",", "exemplars", ",", "validation_scores", ",", "analyze_fn_str", ",", "outf", ")", ":", "analyze_fn", "=", "getattr", "(", "analyze", ",", "analyze_fn_str", ")", "keys", "=", "sorted", "(", "k", "for", "k", ...
Report the overall correlation with the validation scores using each exemplar in isolation.
[ "Report", "the", "overall", "correlation", "with", "the", "validation", "scores", "using", "each", "exemplar", "in", "isolation", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/diagnose.py#L50-L66
train
IRC-SPHERE/HyperStream
hyperstream/node/node.py
Node.difference
def difference(self, other): """ Summarise the differences between this node and the other node. :param other: The other node :return: A tuple containing the diff, the counts of the diff, and whether this plate is a sub-plate of the other :type other: Node """ di...
python
def difference(self, other): """ Summarise the differences between this node and the other node. :param other: The other node :return: A tuple containing the diff, the counts of the diff, and whether this plate is a sub-plate of the other :type other: Node """ di...
[ "def", "difference", "(", "self", ",", "other", ")", ":", "diff", "=", "(", "tuple", "(", "set", "(", "self", ".", "plates", ")", "-", "set", "(", "other", ".", "plates", ")", ")", ",", "tuple", "(", "set", "(", "other", ".", "plates", ")", "-"...
Summarise the differences between this node and the other node. :param other: The other node :return: A tuple containing the diff, the counts of the diff, and whether this plate is a sub-plate of the other :type other: Node
[ "Summarise", "the", "differences", "between", "this", "node", "and", "the", "other", "node", "." ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/node/node.py#L113-L127
train
astooke/gtimer
gtimer/public/report.py
report
def report(times=None, include_itrs=True, include_stats=True, delim_mode=False, format_options=None): """ Produce a formatted report of the current timing data. Notes: When reporting a collection of parallel subdivisions, only the one with the gre...
python
def report(times=None, include_itrs=True, include_stats=True, delim_mode=False, format_options=None): """ Produce a formatted report of the current timing data. Notes: When reporting a collection of parallel subdivisions, only the one with the gre...
[ "def", "report", "(", "times", "=", "None", ",", "include_itrs", "=", "True", ",", "include_stats", "=", "True", ",", "delim_mode", "=", "False", ",", "format_options", "=", "None", ")", ":", "if", "times", "is", "None", ":", "if", "f", ".", "root", ...
Produce a formatted report of the current timing data. Notes: When reporting a collection of parallel subdivisions, only the one with the greatest total time is reported on, and the rest are ignored (no branching). To compare parallel subdivisions use compare(). Args: times (T...
[ "Produce", "a", "formatted", "report", "of", "the", "current", "timing", "data", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/report.py#L22-L86
train
astooke/gtimer
gtimer/public/report.py
compare
def compare(times_list=None, name=None, include_list=True, include_stats=True, delim_mode=False, format_options=None): """ Produce a formatted comparison of timing datas. Notes: If no times_list is provided, produces comparison reports on ...
python
def compare(times_list=None, name=None, include_list=True, include_stats=True, delim_mode=False, format_options=None): """ Produce a formatted comparison of timing datas. Notes: If no times_list is provided, produces comparison reports on ...
[ "def", "compare", "(", "times_list", "=", "None", ",", "name", "=", "None", ",", "include_list", "=", "True", ",", "include_stats", "=", "True", ",", "delim_mode", "=", "False", ",", "format_options", "=", "None", ")", ":", "if", "times_list", "is", "Non...
Produce a formatted comparison of timing datas. Notes: If no times_list is provided, produces comparison reports on all parallel subdivisions present at the root level of the current timer. To compare parallel subdivisions at a lower level, get the times data, navigate within it to...
[ "Produce", "a", "formatted", "comparison", "of", "timing", "datas", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/report.py#L89-L155
train
astooke/gtimer
gtimer/public/report.py
write_structure
def write_structure(times=None): """ Produce a formatted record of a times data structure. Args: times (Times, optional): If not provided, uses the current root timer. Returns: str: Timer tree hierarchy in a formatted string. Raises: TypeError: If provided argument is not ...
python
def write_structure(times=None): """ Produce a formatted record of a times data structure. Args: times (Times, optional): If not provided, uses the current root timer. Returns: str: Timer tree hierarchy in a formatted string. Raises: TypeError: If provided argument is not ...
[ "def", "write_structure", "(", "times", "=", "None", ")", ":", "if", "times", "is", "None", ":", "return", "report_loc", ".", "write_structure", "(", "f", ".", "root", ".", "times", ")", "else", ":", "if", "not", "isinstance", "(", "times", ",", "Times...
Produce a formatted record of a times data structure. Args: times (Times, optional): If not provided, uses the current root timer. Returns: str: Timer tree hierarchy in a formatted string. Raises: TypeError: If provided argument is not a Times object.
[ "Produce", "a", "formatted", "record", "of", "a", "times", "data", "structure", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/report.py#L158-L176
train
tamasgal/km3pipe
examples/plot_dom_hits.py
filter_muons
def filter_muons(blob): """Write all muons from McTracks to Muons.""" tracks = blob['McTracks'] muons = tracks[tracks.type == -13] # PDG particle code blob["Muons"] = Table(muons) return blob
python
def filter_muons(blob): """Write all muons from McTracks to Muons.""" tracks = blob['McTracks'] muons = tracks[tracks.type == -13] # PDG particle code blob["Muons"] = Table(muons) return blob
[ "def", "filter_muons", "(", "blob", ")", ":", "tracks", "=", "blob", "[", "'McTracks'", "]", "muons", "=", "tracks", "[", "tracks", ".", "type", "==", "-", "13", "]", "blob", "[", "\"Muons\"", "]", "=", "Table", "(", "muons", ")", "return", "blob" ]
Write all muons from McTracks to Muons.
[ "Write", "all", "muons", "from", "McTracks", "to", "Muons", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/examples/plot_dom_hits.py#L33-L38
train
aouyar/healthgraph-api
samples/bottle/runkeeper_demo.py
parse_conf_files
def parse_conf_files(conf_paths): """Parse the configuration file and return dictionary of configuration options. @param conf_paths: List of configuration file paths to parse. @return: Dictionary of configuration options. """ conf_file = ConfigParser.RawConfigParser() co...
python
def parse_conf_files(conf_paths): """Parse the configuration file and return dictionary of configuration options. @param conf_paths: List of configuration file paths to parse. @return: Dictionary of configuration options. """ conf_file = ConfigParser.RawConfigParser() co...
[ "def", "parse_conf_files", "(", "conf_paths", ")", ":", "conf_file", "=", "ConfigParser", ".", "RawConfigParser", "(", ")", "conf_read", "=", "conf_file", ".", "read", "(", "conf_paths", ")", "conf", "=", "{", "}", "try", ":", "if", "conf_read", ":", "conf...
Parse the configuration file and return dictionary of configuration options. @param conf_paths: List of configuration file paths to parse. @return: Dictionary of configuration options.
[ "Parse", "the", "configuration", "file", "and", "return", "dictionary", "of", "configuration", "options", "." ]
fc5135ab353ca1f05e8a70ec784ff921e686c072
https://github.com/aouyar/healthgraph-api/blob/fc5135ab353ca1f05e8a70ec784ff921e686c072/samples/bottle/runkeeper_demo.py#L148-L175
train
aouyar/healthgraph-api
samples/bottle/runkeeper_demo.py
main
def main(argv=None): """Main Block - Configure and run the Bottle Web Server.""" cmd_opts = parse_cmdline(argv)[0] if cmd_opts.confpath is not None: if os.path.exists(cmd_opts.confpath): conf_paths = [cmd_opts.confpath,] else: return "Configuration file not found: %s"...
python
def main(argv=None): """Main Block - Configure and run the Bottle Web Server.""" cmd_opts = parse_cmdline(argv)[0] if cmd_opts.confpath is not None: if os.path.exists(cmd_opts.confpath): conf_paths = [cmd_opts.confpath,] else: return "Configuration file not found: %s"...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "cmd_opts", "=", "parse_cmdline", "(", "argv", ")", "[", "0", "]", "if", "cmd_opts", ".", "confpath", "is", "not", "None", ":", "if", "os", ".", "path", ".", "exists", "(", "cmd_opts", ".", "confpa...
Main Block - Configure and run the Bottle Web Server.
[ "Main", "Block", "-", "Configure", "and", "run", "the", "Bottle", "Web", "Server", "." ]
fc5135ab353ca1f05e8a70ec784ff921e686c072
https://github.com/aouyar/healthgraph-api/blob/fc5135ab353ca1f05e8a70ec784ff921e686c072/samples/bottle/runkeeper_demo.py#L178-L204
train
NaPs/Kolekto
kolekto/helpers.py
get_hash
def get_hash(input_string): """ Return the hash of the movie depending on the input string. If the input string looks like a symbolic link to a movie in a Kolekto tree, return its movies hash, else, return the input directly in lowercase. """ # Check if the input looks like a link to a movie: ...
python
def get_hash(input_string): """ Return the hash of the movie depending on the input string. If the input string looks like a symbolic link to a movie in a Kolekto tree, return its movies hash, else, return the input directly in lowercase. """ # Check if the input looks like a link to a movie: ...
[ "def", "get_hash", "(", "input_string", ")", ":", "if", "os", ".", "path", ".", "islink", "(", "input_string", ")", ":", "directory", ",", "movie_hash", "=", "os", ".", "path", ".", "split", "(", "os", ".", "readlink", "(", "input_string", ")", ")", ...
Return the hash of the movie depending on the input string. If the input string looks like a symbolic link to a movie in a Kolekto tree, return its movies hash, else, return the input directly in lowercase.
[ "Return", "the", "hash", "of", "the", "movie", "depending", "on", "the", "input", "string", "." ]
29c5469da8782780a06bf9a76c59414bb6fd8fe3
https://github.com/NaPs/Kolekto/blob/29c5469da8782780a06bf9a76c59414bb6fd8fe3/kolekto/helpers.py#L8-L20
train
NaPs/Kolekto
kolekto/helpers.py
JsonDbm.get
def get(self, key): """ Get data associated with provided key. """ return self._object_class(json.loads(self._db[key]))
python
def get(self, key): """ Get data associated with provided key. """ return self._object_class(json.loads(self._db[key]))
[ "def", "get", "(", "self", ",", "key", ")", ":", "return", "self", ".", "_object_class", "(", "json", ".", "loads", "(", "self", ".", "_db", "[", "key", "]", ")", ")" ]
Get data associated with provided key.
[ "Get", "data", "associated", "with", "provided", "key", "." ]
29c5469da8782780a06bf9a76c59414bb6fd8fe3
https://github.com/NaPs/Kolekto/blob/29c5469da8782780a06bf9a76c59414bb6fd8fe3/kolekto/helpers.py#L35-L38
train
NaPs/Kolekto
kolekto/helpers.py
JsonDbm.save
def save(self, key, data): """ Save data associated with key. """ self._db[key] = json.dumps(data) self._db.sync()
python
def save(self, key, data): """ Save data associated with key. """ self._db[key] = json.dumps(data) self._db.sync()
[ "def", "save", "(", "self", ",", "key", ",", "data", ")", ":", "self", ".", "_db", "[", "key", "]", "=", "json", ".", "dumps", "(", "data", ")", "self", ".", "_db", ".", "sync", "(", ")" ]
Save data associated with key.
[ "Save", "data", "associated", "with", "key", "." ]
29c5469da8782780a06bf9a76c59414bb6fd8fe3
https://github.com/NaPs/Kolekto/blob/29c5469da8782780a06bf9a76c59414bb6fd8fe3/kolekto/helpers.py#L45-L49
train
IRC-SPHERE/HyperStream
hyperstream/meta_data/meta_data_manager.py
MetaDataManager.global_meta_data
def global_meta_data(self): """ Get the global meta data, which will be stored in a tree structure :return: The global meta data """ with switch_db(MetaDataModel, 'hyperstream'): return sorted(map(lambda x: x.to_dict(), MetaDataModel.objects), ...
python
def global_meta_data(self): """ Get the global meta data, which will be stored in a tree structure :return: The global meta data """ with switch_db(MetaDataModel, 'hyperstream'): return sorted(map(lambda x: x.to_dict(), MetaDataModel.objects), ...
[ "def", "global_meta_data", "(", "self", ")", ":", "with", "switch_db", "(", "MetaDataModel", ",", "'hyperstream'", ")", ":", "return", "sorted", "(", "map", "(", "lambda", "x", ":", "x", ".", "to_dict", "(", ")", ",", "MetaDataModel", ".", "objects", ")"...
Get the global meta data, which will be stored in a tree structure :return: The global meta data
[ "Get", "the", "global", "meta", "data", "which", "will", "be", "stored", "in", "a", "tree", "structure" ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/meta_data/meta_data_manager.py#L56-L65
train
IRC-SPHERE/HyperStream
hyperstream/meta_data/meta_data_manager.py
MetaDataManager.insert
def insert(self, tag, identifier, parent, data): """ Insert the given meta data into the database :param tag: The tag (equates to meta_data_id) :param identifier: The identifier (a combination of the meta_data_id and the plate value) :param parent: The parent plate identifier ...
python
def insert(self, tag, identifier, parent, data): """ Insert the given meta data into the database :param tag: The tag (equates to meta_data_id) :param identifier: The identifier (a combination of the meta_data_id and the plate value) :param parent: The parent plate identifier ...
[ "def", "insert", "(", "self", ",", "tag", ",", "identifier", ",", "parent", ",", "data", ")", ":", "if", "self", ".", "global_plate_definitions", ".", "contains", "(", "identifier", ")", ":", "raise", "KeyError", "(", "\"Identifier {} already exists in tree\"", ...
Insert the given meta data into the database :param tag: The tag (equates to meta_data_id) :param identifier: The identifier (a combination of the meta_data_id and the plate value) :param parent: The parent plate identifier :param data: The data (plate value) :return: None
[ "Insert", "the", "given", "meta", "data", "into", "the", "database" ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/meta_data/meta_data_manager.py#L76-L97
train
IRC-SPHERE/HyperStream
hyperstream/meta_data/meta_data_manager.py
MetaDataManager.delete
def delete(self, identifier): """ Delete the meta data with the given identifier from the database :param identifier: The identifier :return: None """ try: node = self.global_plate_definitions[identifier] except NodeIDAbsentError: logging...
python
def delete(self, identifier): """ Delete the meta data with the given identifier from the database :param identifier: The identifier :return: None """ try: node = self.global_plate_definitions[identifier] except NodeIDAbsentError: logging...
[ "def", "delete", "(", "self", ",", "identifier", ")", ":", "try", ":", "node", "=", "self", ".", "global_plate_definitions", "[", "identifier", "]", "except", "NodeIDAbsentError", ":", "logging", ".", "info", "(", "\"Meta data {} not present during deletion\"", "....
Delete the meta data with the given identifier from the database :param identifier: The identifier :return: None
[ "Delete", "the", "meta", "data", "with", "the", "given", "identifier", "from", "the", "database" ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/meta_data/meta_data_manager.py#L99-L125
train
htm-community/menorah
menorah/riverstream.py
RiverStream.load
def load(self): """ Loads this stream by calling River View for data. """ print "Loading data for %s..." % self.getName() self._dataHandle = self._stream.data( since=self._since, until=self._until, limit=self._limit, aggregate=self._aggregate ) self._data = self._dataHandle.data...
python
def load(self): """ Loads this stream by calling River View for data. """ print "Loading data for %s..." % self.getName() self._dataHandle = self._stream.data( since=self._since, until=self._until, limit=self._limit, aggregate=self._aggregate ) self._data = self._dataHandle.data...
[ "def", "load", "(", "self", ")", ":", "print", "\"Loading data for %s...\"", "%", "self", ".", "getName", "(", ")", "self", ".", "_dataHandle", "=", "self", ".", "_stream", ".", "data", "(", "since", "=", "self", ".", "_since", ",", "until", "=", "self...
Loads this stream by calling River View for data.
[ "Loads", "this", "stream", "by", "calling", "River", "View", "for", "data", "." ]
1991b01eda3f6361b22ed165b4a688ae3fb2deaf
https://github.com/htm-community/menorah/blob/1991b01eda3f6361b22ed165b4a688ae3fb2deaf/menorah/riverstream.py#L80-L91
train
tamasgal/km3pipe
km3pipe/plot.py
hexbin
def hexbin(x, y, color="purple", **kwargs): """Seaborn-compatible hexbin plot. See also: http://seaborn.pydata.org/tutorial/axis_grids.html#mapping-custom-functions-onto-the-grid """ if HAS_SEABORN: cmap = sns.light_palette(color, as_cmap=True) else: cmap = "Purples" plt.hexbin(...
python
def hexbin(x, y, color="purple", **kwargs): """Seaborn-compatible hexbin plot. See also: http://seaborn.pydata.org/tutorial/axis_grids.html#mapping-custom-functions-onto-the-grid """ if HAS_SEABORN: cmap = sns.light_palette(color, as_cmap=True) else: cmap = "Purples" plt.hexbin(...
[ "def", "hexbin", "(", "x", ",", "y", ",", "color", "=", "\"purple\"", ",", "**", "kwargs", ")", ":", "if", "HAS_SEABORN", ":", "cmap", "=", "sns", ".", "light_palette", "(", "color", ",", "as_cmap", "=", "True", ")", "else", ":", "cmap", "=", "\"Pu...
Seaborn-compatible hexbin plot. See also: http://seaborn.pydata.org/tutorial/axis_grids.html#mapping-custom-functions-onto-the-grid
[ "Seaborn", "-", "compatible", "hexbin", "plot", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/plot.py#L33-L42
train
tamasgal/km3pipe
km3pipe/plot.py
diag
def diag(ax=None, linecolor='0.0', linestyle='--', **kwargs): """Plot the diagonal.""" ax = get_ax(ax) xy_min = np.min((ax.get_xlim(), ax.get_ylim())) xy_max = np.max((ax.get_ylim(), ax.get_xlim())) return ax.plot([xy_min, xy_max], [xy_min, xy_max], ls=linestyle, ...
python
def diag(ax=None, linecolor='0.0', linestyle='--', **kwargs): """Plot the diagonal.""" ax = get_ax(ax) xy_min = np.min((ax.get_xlim(), ax.get_ylim())) xy_max = np.max((ax.get_ylim(), ax.get_xlim())) return ax.plot([xy_min, xy_max], [xy_min, xy_max], ls=linestyle, ...
[ "def", "diag", "(", "ax", "=", "None", ",", "linecolor", "=", "'0.0'", ",", "linestyle", "=", "'--'", ",", "**", "kwargs", ")", ":", "ax", "=", "get_ax", "(", "ax", ")", "xy_min", "=", "np", ".", "min", "(", "(", "ax", ".", "get_xlim", "(", ")"...
Plot the diagonal.
[ "Plot", "the", "diagonal", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/plot.py#L52-L60
train
tamasgal/km3pipe
km3pipe/plot.py
automeshgrid
def automeshgrid( x, y, step=0.02, xstep=None, ystep=None, pad=0.5, xpad=None, ypad=None ): """Make a meshgrid, inferred from data.""" if xpad is None: xpad = pad if xstep is None: xstep = step if ypad is None: ypad = pad if ystep is None: ystep = step xmi...
python
def automeshgrid( x, y, step=0.02, xstep=None, ystep=None, pad=0.5, xpad=None, ypad=None ): """Make a meshgrid, inferred from data.""" if xpad is None: xpad = pad if xstep is None: xstep = step if ypad is None: ypad = pad if ystep is None: ystep = step xmi...
[ "def", "automeshgrid", "(", "x", ",", "y", ",", "step", "=", "0.02", ",", "xstep", "=", "None", ",", "ystep", "=", "None", ",", "pad", "=", "0.5", ",", "xpad", "=", "None", ",", "ypad", "=", "None", ")", ":", "if", "xpad", "is", "None", ":", ...
Make a meshgrid, inferred from data.
[ "Make", "a", "meshgrid", "inferred", "from", "data", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/plot.py#L63-L79
train
tamasgal/km3pipe
km3pipe/plot.py
prebinned_hist
def prebinned_hist(counts, binlims, ax=None, *args, **kwargs): """Plot a histogram with counts, binlims already given. Example ======= >>> gaus = np.random.normal(size=100) >>> counts, binlims = np.histogram(gaus, bins='auto') >>> prebinned_hist(countsl binlims) """ ax = get_ax(ax) ...
python
def prebinned_hist(counts, binlims, ax=None, *args, **kwargs): """Plot a histogram with counts, binlims already given. Example ======= >>> gaus = np.random.normal(size=100) >>> counts, binlims = np.histogram(gaus, bins='auto') >>> prebinned_hist(countsl binlims) """ ax = get_ax(ax) ...
[ "def", "prebinned_hist", "(", "counts", ",", "binlims", ",", "ax", "=", "None", ",", "*", "args", ",", "**", "kwargs", ")", ":", "ax", "=", "get_ax", "(", "ax", ")", "x", "=", "bincenters", "(", "binlims", ")", "weights", "=", "counts", "return", "...
Plot a histogram with counts, binlims already given. Example ======= >>> gaus = np.random.normal(size=100) >>> counts, binlims = np.histogram(gaus, bins='auto') >>> prebinned_hist(countsl binlims)
[ "Plot", "a", "histogram", "with", "counts", "binlims", "already", "given", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/plot.py#L96-L108
train