text stringlengths 81 112k |
|---|
Function to get potential tags for files using the file names.
:param filename: This field is the name of file.
def guess_tags(filename):
"""
Function to get potential tags for files using the file names.
:param filename: This field is the name of file.
"""
tags = []
stripped_filename = s... |
Collate local file info as preperation for Open Humans upload.
Note: Files with filesize > max_bytes are not included in returned info.
:param filedir: This field is target directory to get files from.
:param max_bytes: This field is the maximum file size to consider. Its
default value is 128m.
d... |
Check that the files listed in metadata exactly match files in target dir.
:param target_dir: This field is the target directory from which to
match metadata
:param metadata: This field contains the metadata to be matched.
def validate_metadata(target_dir, metadata):
"""
Check that the files l... |
Return the metadata as requested for a single user.
:param csv_in: This field is the csv file to return metadata from.
:param header: This field contains the headers in the csv file
:param tags_idx: This field contains the index of the tags in the csv
file.
def load_metadata_csv_single_user(csv_in... |
Return dict of metadata.
Format is either dict (filenames are keys) or dict-of-dicts (project member
IDs as top level keys, then filenames as keys).
:param input_filepath: This field is the filepath of the csv file.
def load_metadata_csv(input_filepath):
"""
Return dict of metadata.
Format i... |
Check if date is in ISO 8601 format.
:param date: This field is the date to be checked.
:param project_member_id: This field is the project_member_id corresponding
to the date provided.
:param filename: This field is the filename corresponding to the date
provided.
def validate_date(date, ... |
Check if metadata fields like project member id, description, tags, md5 and
creation date are valid for a single file.
:param file_metadata: This field is metadata of file.
:param project_member_id: This field is the project member id corresponding
to the file metadata provided.
:param filename... |
Check validity of metadata for single user.
:param filedir: This field is the filepath of the directory whose csv
has to be made.
:param metadata: This field is the metadata generated from the
load_metadata_csv function.
:param csv_in: This field returns a reader object which iterates over ... |
Check that all folders in the given directory have a corresponding
entry in the metadata file, and vice versa.
:param filedir: This field is the target directory from which to
match metadata
:param metadata: This field contains the metadata to be matched.
def validate_subfolders(filedir, metadata)... |
Check validity of metadata for multi user.
:param filedir: This field is the filepath of the directory whose csv
has to be made.
:param metadata: This field is the metadata generated from the
load_metadata_csv function.
:param csv_in: This field returns a reader object which iterates over t... |
Check validity of metadata fields.
:param filedir: This field is the filepath of the directory whose csv
has to be made.
:param outputfilepath: This field is the file path of the output csv.
:param max_bytes: This field is the maximum file size to consider. Its
default value is 128m.
def r... |
Make metadata file for all files in a directory(helper function)
:param filedir: This field is the filepath of the directory whose csv
has to be made.
:param filestream: This field is a stream for writing to the csv.
:param max_bytes: This field is the maximum file size to consider. Its
def... |
Make metadata file for all files in a directory.
:param filedir: This field is the filepath of the directory whose csv
has to be made.
:param outputfilepath: This field is the file path of the output csv.
:param max_bytes: This field is the maximum file size to consider. Its
default value i... |
Download a file.
:param download_url: This field is the url from which data will be
downloaded.
:param target_filepath: This field is the path of the file where
data will be downloaded.
:param max_bytes: This field is the maximum file size to download. Its
default value is 128m.
de... |
Get project member id from a file.
:param filepath: This field is the path of file to read.
def read_id_list(filepath):
"""
Get project member id from a file.
:param filepath: This field is the path of file to read.
"""
if not filepath:
return None
id_list = []
with open(filep... |
Function for setting the logging level.
:param debug: This boolean field is the logging level.
:param verbose: This boolean field is the logging level.
def set_log_level(debug, verbose):
"""
Function for setting the logging level.
:param debug: This boolean field is the logging level.
:param ... |
Command line function for downloading data from project members to the
target directory. For more information visit
:func:`download<ohapi.command_line.download>`.
def download_cli(directory, master_token=None, member=None, access_token=None,
source=None, project_data=False, max_size='128m',
... |
Download data from project members to the target directory.
Unless this is a member-specific download, directories will be
created for each project member ID. Also, unless a source is specified,
all shared sources are downloaded and data is sorted into subdirectories
according to source.
Projects ... |
Command line function for downloading metadata.
For more information visit
:func:`download_metadata<ohapi.command_line.download_metadata>`.
def download_metadata_cli(master_token, output_csv, verbose=False,
debug=False):
"""
Command line function for downloading metadata.
... |
Output CSV with metadata for a project's downloadable files in Open Humans.
:param master_token: This field is the master access token for the project.
:param output_csv: This field is the target csv file to which metadata is
written.
:param verbose: This boolean field is the logging level. It's de... |
Command line function for drafting or reviewing metadata files.
For more information visit
:func:`upload_metadata<ohapi.command_line.upload_metadata>`.
def upload_metadata_cli(directory, create_csv='', review='',
max_size='128m', verbose=False, debug=False):
"""
Command line fun... |
Draft or review metadata files for uploading files to Open Humans.
The target directory should either represent files for a single member (no
subdirectories), or contain a subdirectory for each project member ID.
:param directory: This field is the directory for which metadata has to be
created.
... |
Command line function for uploading files to OH.
For more information visit
:func:`upload<ohapi.command_line.upload>`.
def upload_cli(directory, metadata_csv, master_token=None, member=None,
access_token=None, safe=False, sync=False, max_size='128m',
mode='default', verbose=False,... |
Upload files for the project to Open Humans member accounts.
If using a master access token and not specifying member ID:
(1) Files should be organized in subdirectories according to project
member ID, e.g.:
main_directory/01234567/data.json
main_directory/12345678/data.json
main_... |
Command line function for obtaining the refresh token/code.
For more information visit
:func:`oauth2_token_exchange<ohapi.api.oauth2_token_exchange>`.
def oauth_token_exchange_cli(client_id, client_secret, redirect_uri,
base_url=OH_BASE_URL, code=None,
... |
Command line function for obtaining the Oauth2 url.
For more information visit
:func:`oauth2_auth_url<ohapi.api.oauth2_auth_url>`.
def oauth2_auth_url_cli(redirect_uri=None, client_id=None,
base_url=OH_BASE_URL):
"""
Command line function for obtaining the Oauth2 url.
For mo... |
Command line function for sending email to a single user or in bulk.
For more information visit
:func:`message<ohapi.api.message>`.
def message_cli(subject, message_body, access_token, all_members=False,
project_member_ids=None, base_url=OH_BASE_URL,
verbose=False, debug=False):... |
Command line function for deleting files.
For more information visit
:func:`delete_file<ohapi.api.delete_file>`.
def delete_cli(access_token, project_member_id, base_url=OH_BASE_URL,
file_basename=None, file_id=None, all_files=False):
"""
Command line function for deleting files.
For... |
Command line tools for downloading public data.
def public_data_download_cli(source, username, directory, max_size, quiet,
debug):
"""
Command line tools for downloading public data.
"""
return public_download(source, username, directory, max_size, quiet, debug) |
Download a file.
:param result: This field contains a url from which data will be
downloaded.
:param directory: This field is the target directory to which data will be
downloaded.
:param max_bytes: This field is the maximum file size in bytes.
def download_url(result, directory, max_bytes... |
Download public data from Open Humans.
:param source: This field is the data source from which to download. It's
default value is None.
:param username: This fiels is username of user. It's default value is
None.
:param directory: This field is the target directory to which data is
... |
Function returns which members have joined each activity.
:param base_url: It is URL: `https://www.openhumans.org/api/public-data`.
def get_members_by_source(base_url=BASE_URL_API):
"""
Function returns which members have joined each activity.
:param base_url: It is URL: `https://www.openhumans.org/a... |
Function returns which activities each member has joined.
:param base_url: It is URL: `https://www.openhumans.org/api/public-data`.
:param limit: It is the limit of data send by one request.
def get_sources_by_member(base_url=BASE_URL_API, limit=LIMIT_DEFAULT):
"""
Function returns which activities ea... |
Helper function to get file data of member of a project.
:param member_data: This field is data related to member in a project.
def _get_member_file_data(member_data, id_filename=False):
"""
Helper function to get file data of member of a project.
:param member_data: This field is dat... |
Returns data for all users including shared data files.
def update_data(self):
"""
Returns data for all users including shared data files.
"""
url = ('https://www.openhumans.org/api/direct-sharing/project/'
'members/?access_token={}'.format(self.master_access_token))
... |
Download files to sync a local dir to match OH member project data.
:param member_data: This field is data related to member in a project.
:param target_member_dir: This field is the target directory where data
will be downloaded.
:param max_size: This field is the maximum file size... |
Download files to sync a local dir to match OH member shared data.
Files are downloaded to match their "basename" on Open Humans.
If there are multiple files with the same name, the most recent is
downloaded.
:param member_data: This field is data related to member in a project.
... |
Download data for all users including shared data files.
:param target_dir: This field is the target directory to download data.
:param source: This field is the data source. It's default value is
None.
:param project_data: This field is data related to particular project.
... |
Upload files in target directory to an Open Humans member's account.
The default behavior is to overwrite files with matching filenames on
Open Humans, but not otherwise delete files.
If the 'mode' parameter is 'safe': matching filenames will not be
overwritten.
If the 'mode' ... |
Returns an OAuth2 authorization URL for a project, given Client ID. This
function constructs an authorization URL for a user to follow.
The user will be redirected to Authorize Open Humans data for our external
application. An OAuth2 project on Open Humans is required for this to
properly work. To learn... |
Exchange code or refresh token for a new token and refresh token. For the
first time when a project is created, code is required to generate refresh
token. Once the refresh token is obtained, it can be used later on for
obtaining new access token and refresh token. The user must store the
refresh token ... |
Get a single page of results.
:param url: This field is the url from which data will be requested.
def get_page(url):
"""
Get a single page of results.
:param url: This field is the url from which data will be requested.
"""
response = requests.get(url)
handle_error(response, 200)
dat... |
Given starting API query for Open Humans, iterate to get all results.
:param starting page: This field is the first page, starting from which
results will be obtained.
def get_all_results(starting_page):
"""
Given starting API query for Open Humans, iterate to get all results.
:param starting... |
Returns data for a specific user, including shared data files.
:param access_token: This field is the user specific access_token.
:param base_url: It is this URL `https://www.openhumans.org`.
def exchange_oauth2_member(access_token, base_url=OH_BASE_URL,
all_files=False):
"""
... |
Delete project member files by file_basename, file_id, or all_files. To
learn more about Open Humans OAuth2 projects, go to:
https://www.openhumans.org/direct-sharing/oauth2-features/.
:param access_token: This field is user specific access_token.
:param project_member_id: This field is the pro... |
Send an email to individual users or in bulk. To learn more about Open
Humans OAuth2 projects, go to:
https://www.openhumans.org/direct-sharing/oauth2-features/
:param subject: This field is the subject of the email.
:param message: This field is the body of the email.
:param access_token: This is ... |
Helper function to match reponse of a request to the expected status
code
:param r: This field is the response of request.
:param expected_code: This field is the expected status code for the
function.
def handle_error(r, expected_code):
"""
Helper function to match reponse of a request to... |
Upload a file object using the "direct upload" feature, which uploads to
an S3 bucket URL provided by the Open Humans API. To learn more about this
API endpoint see:
* https://www.openhumans.org/direct-sharing/on-site-data-upload/
* https://www.openhumans.org/direct-sharing/oauth2-data-upload/
:par... |
Upload a file from a local filepath using the "direct upload" API.
To learn more about this API endpoint see:
* https://www.openhumans.org/direct-sharing/on-site-data-upload/
* https://www.openhumans.org/direct-sharing/oauth2-data-upload/
:param target_filepath: This field is the filepath of the file t... |
Upload a file from a local filepath using the "direct upload" API.
Equivalent to upload_file. To learn more about this API endpoint see:
* https://www.openhumans.org/direct-sharing/on-site-data-upload/
* https://www.openhumans.org/direct-sharing/oauth2-data-upload/
:param target_filepath: This field is... |
Return the wire packed version of `from_`. `pack_type` should be some
subclass of `xcffib.Struct`, or a string that can be passed to
`struct.pack`. You must pass `size` if `pack_type` is a struct.pack string.
def pack_list(from_, pack_type):
""" Return the wire packed version of `from_`. `pack_type` should... |
Check that the connection is valid both before and
after the function is invoked.
def ensure_connected(f):
"""
Check that the connection is valid both before and
after the function is invoked.
"""
@functools.wraps(f)
def wrapper(*args):
self = args[0]... |
Returns the xcb_screen_t for every screen
useful for other bindings
def get_screen_pointers(self):
"""
Returns the xcb_screen_t for every screen
useful for other bindings
"""
root_iter = lib.xcb_setup_roots_iterator(self._setup)
screens = [root_iter.data]
... |
Hoist an xcb_generic_event_t to the right xcffib structure.
def hoist_event(self, e):
""" Hoist an xcb_generic_event_t to the right xcffib structure. """
if e.response_type == 0:
return self._process_error(ffi.cast("xcb_generic_error_t *", e))
# We mask off the high bit here becaus... |
Greedy serialization requires the value to either be a column
or convertible to a column, whereas non-greedy serialization
will pass through any string as-is and will only serialize
Column objects.
Non-greedy serialization is useful when preparing queries with
custom filters or ... |
Generate a query by describing it as a series of actions
and parameters to those actions. These map directly
to Query methods and arguments to those methods.
This is an alternative to the chaining interface.
Mostly useful if you'd like to put your queries
in a file, rather than in Python code.
def... |
Refine a query from a dictionary of parameters that describes it.
See `describe` for more information.
def refine(query, description):
"""
Refine a query from a dictionary of parameters that describes it.
See `describe` for more information.
"""
for attribute, arguments in description.items():... |
`set` is a way to add raw properties to the request,
for features that this module does not
support or supports incompletely. For convenience's
sake, it will serialize Column objects but will
leave any other kind of value alone.
def set(self, key=None, value=None, **kwargs):
"""... |
A list of the metrics this query will ask for.
def description(self):
"""
A list of the metrics this query will ask for.
"""
if 'metrics' in self.raw:
metrics = self.raw['metrics']
head = metrics[0:-1] or metrics[0:1]
text = ", ".join(head)
... |
Return a new query which will produce results sorted by
one or more metrics or dimensions. You may use plain
strings for the columns, or actual `Column`, `Metric`
and `Dimension` objects.
Add a minus in front of the metric (either the string or
the object) to sort in descending ... |
Most of the actual functionality lives on the Column
object and the `all` and `any` functions.
def filter(self, value=None, exclude=False, **selection):
""" Most of the actual functionality lives on the Column
object and the `all` and `any` functions. """
filters = self.meta.setdefault(... |
For queries that should run faster, you may specify a lower precision,
and for those that need to be more precise, a higher precision:
```python
# faster queries
query.range('2014-01-01', '2014-01-31', precision=0)
query.range('2014-01-01', '2014-01-31', precision='FASTER')
... |
Note that if you don't specify a granularity (either through the `interval`
method or through the `hourly`, `daily`, `weekly`, `monthly` or `yearly`
shortcut methods) you will get only a single result, encompassing the
entire date range, per metric.
def interval(self, granularity):
"""
... |
Return a new query that fetches metrics within a certain date range.
```python
query.range('2014-01-01', '2014-06-30')
```
If you don't specify a `stop` argument, the date range will end today. If instead
you meant to fetch just a single day's results, try:
```python
... |
Return a new query, limited to a certain number of results.
```python
# first 100
query.limit(100)
# 50 to 60
query.limit(50, 10)
```
Please note carefully that Google Analytics uses
1-indexing on its rows.
def limit(self, *_range):
"""
... |
Return a new query, limited to a segment of all users or sessions.
Accepts segment objects, filtered segment objects and segment names:
```python
query.segment(account.segments['browser'])
query.segment('browser')
query.segment(account.segments['browser'].any('Chrome', 'Firefox... |
Return a new query with a modified `start_index`.
Mainly used internally to paginate through results.
def next(self):
"""
Return a new query with a modified `start_index`.
Mainly used internally to paginate through results.
"""
step = self.raw.get('max_results', 1000)
... |
Run the query and return a `Report`.
This method transparently handles paginated results, so even for results that
are larger than the maximum amount of rows the Google Analytics API will
return in a single request, or larger than the amount of rows as specified
through `CoreQuery#step`... |
Return a new query, limited to a certain number of results.
Unlike core reporting queries, you cannot specify a starting
point for live queries, just the maximum results returned.
```python
# first 50
query.limit(50)
```
def limit(self, maximum):
"""
Re... |
Valid credentials are not necessarily correct, but
they contain all necessary information for an
authentication attempt.
def valid(self):
""" Valid credentials are not necessarily correct, but
they contain all necessary information for an
authentication attempt. """
two_... |
Complete credentials are valid and are either two-legged or include a token.
def complete(self):
""" Complete credentials are valid and are either two-legged or include a token. """
return self.valid and (self.access_token or self.refresh_token or self.type == 2) |
The `authenticate` function will authenticate the user with the Google Analytics API,
using a variety of strategies: keyword arguments provided to this function, credentials
stored in in environment variables, credentials stored in the keychain and, finally, by
asking for missing information interactively i... |
Given a client id, client secret and either an access token or a refresh token,
revoke OAuth access to the Google Analytics data and remove any stored credentials
that use these tokens.
def revoke(client_id, client_secret,
client_email=None, private_key=None,
access_token=None, refresh_token=No... |
e.g.
googleanalytics --identity debrouwere --account debrouwere --webproperty http://debrouwere.org \
query pageviews \
--start yesterday --limit -10 --sort -pageviews \
--dimensions pagepath \
--debug
def query(scope, blueprint, debug, output, with_metadata, re... |
Allows a method to accept one or more values,
but internally deal only with a single item,
and returning a list or a single item depending
on what is desired.
def vectorize(fn):
"""
Allows a method to accept one or more values,
but internally deal only with a single item,
and returning a li... |
A list of all web properties on this account. You may
select a specific web property using its name, its id
or an index.
```python
account.webproperties[0]
account.webproperties['UA-9234823-5']
account.webproperties['debrouwere.org']
```
def webproperties(self):... |
A list of all profiles on this web property. You may
select a specific profile using its name, its id
or an index.
```python
property.profiles[0]
property.profiles['9234823']
property.profiles['marketing profile']
```
def profiles(self):
"""
A li... |
Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen construc... |
If `apply_encoding_options` is inadequate, one can retrieve tokens from `self.token_counts`, filter with
a desired strategy and regenerate `token_index` using this method. The token index is subsequently used
when `encode_texts` or `decode_texts` methods are called.
def create_token_indices(self, token... |
Applies the given settings for subsequent calls to `encode_texts` and `decode_texts`. This allows you to
play with different settings without having to re-run tokenization on the entire corpus.
Args:
min_token_count: The minimum token count (frequency) in order to include during encoding. A... |
Encodes the given texts using internal vocabulary with optionally applied encoding options. See
``apply_encoding_options` to set various options.
Args:
texts: The list of text items to encode.
unknown_token: The token to replace words that out of vocabulary. If none, those words... |
Decodes the texts using internal vocabulary. The list structure is maintained.
Args:
encoded_texts: The list of texts to decode.
unknown_token: The placeholder value for unknown token. (Default value: "<UNK>")
inplace: True to make changes inplace. (Default value: True)
... |
Builds the internal vocabulary and computes various statistics.
Args:
texts: The list of text items to encode.
verbose: The verbosity level for progress. Can be 0, 1, 2. (Default value = 1)
**kwargs: The kwargs for `token_generator`.
def build_vocab(self, texts, verbose=1, ... |
Pads each sequence to the same fixed length (length of the longest sequence or provided override).
Args:
sequences: list of list (samples, words) or list of list of list (samples, sentences, words)
fixed_sentences_seq_length: The fix sentence sequence length to use. If None, largest sen... |
Gets the standard statistics for aux_index `i`. For example, if `token_generator` generates
`(text_idx, sentence_idx, word)`, then `get_stats(0)` will return various statistics about sentence lengths
across texts. Similarly, `get_counts(1)` will return statistics of token lengths across sentences.
... |
Builds an embedding matrix for all words in vocab using embeddings_index
def build_embedding_weights(word_index, embeddings_index):
"""Builds an embedding matrix for all words in vocab using embeddings_index
"""
logger.info('Loading embeddings for all words in the corpus')
embedding_dim = list(embeddin... |
FastText pre-trained word vectors for 294 languages, with 300 dimensions, trained on Wikipedia. It's recommended to use the same tokenizer for your data that was used to construct the embeddings. It's implemented as 'FasttextWikiTokenizer'. More information: https://fasttext.cc/docs/en/pretrained-vectors.html.
Arg... |
FastText pre-trained word vectors for 157 languages, with 300 dimensions, trained on Common Crawl and Wikipedia. Released in 2018, it succeesed the 2017 FastText Wikipedia embeddings. It's recommended to use the same tokenizer for your data that was used to construct the embeddings. This information and more can be fin... |
Retrieves embeddings index from embedding name or path. Will automatically download and cache as needed.
Args:
embedding_type: The embedding type to load.
embedding_path: Path to a local embedding to use instead of the embedding type. Ignores `embedding_type` if specified.
Returns:
The... |
Yields tokens from texts as `(text_idx, character)`
def token_generator(self, texts, **kwargs):
"""Yields tokens from texts as `(text_idx, character)`
"""
for text_idx, text in enumerate(texts):
if self.lower:
text = text.lower()
for char in text:
... |
Yields tokens from texts as `(text_idx, sent_idx, character)`
Args:
texts: The list of texts.
**kwargs: Supported args include:
n_threads/num_threads: Number of threads to use. Uses num_cpus - 1 by default.
batch_size: The number of texts to accumulate in... |
Creates `folds` number of indices that has roughly balanced multi-label distribution.
Args:
y: The multi-label outputs.
folds: The number of folds to create.
Returns:
`folds` number of indices that have roughly equal multi-label distributions.
def equal_distribution_folds(y, folds=2):... |
Builds a model that first encodes all words within sentences using `token_encoder_model`, followed by
`sentence_encoder_model`.
Args:
token_encoder_model: An instance of `SequenceEncoderBase` for encoding tokens within sentences. This model
will be applied across all sentenc... |
Process text and save as Dataset
def process_save(X, y, tokenizer, proc_data_path, max_len=400, train=False, ngrams=None, limit_top_tokens=None):
"""Process text and save as Dataset
"""
if train and limit_top_tokens is not None:
tokenizer.apply_encoding_options(limit_top_tokens=limit_top_tokens)
... |
Setup data
Args:
X: text data,
y: data labels,
tokenizer: A Tokenizer instance
proc_data_path: Path for the processed data
def setup_data(X, y, tokenizer, proc_data_path, **kwargs):
"""Setup data
Args:
X: text data,
y: data l... |
Splits data into a training, validation, and test set.
Args:
X: text data
y: data labels
ratio: the ratio for splitting. Default: (0.8, 0.1, 0.1)
Returns:
split data: X_train, X_val, X_test, y_train, y_val, y_test
def split_data(X, y, ratio=(0.8, 0.1, 0... |
Setup data while splitting into a training, validation, and test set.
Args:
X: text data,
y: data labels,
tokenizer: A Tokenizer instance
proc_data_dir: Directory for the split and processed data
def setup_data_split(X, y, tokenizer, proc_data_dir, **kwargs):
... |
Loads a split dataset
Args:
proc_data_dir: Directory with the split and processed data
Returns:
(Training Data, Validation Data, Test Data)
def load_data_split(proc_data_dir):
"""Loads a split dataset
Args:
proc_data_dir: Directory with the split and p... |
Builds a model using the given `text_model`
Args:
token_encoder_model: An instance of `SequenceEncoderBase` for encoding all the tokens within a document.
This encoding is then fed into a final `Dense` layer for classification.
trainable_embeddings: Whether or not to fin... |
Computes softmax along a specified dim. Keras currently lacks this feature.
def _softmax(x, dim):
"""Computes softmax along a specified dim. Keras currently lacks this feature.
"""
if K.backend() == 'tensorflow':
import tensorflow as tf
return tf.nn.softmax(x, dim)
elif K.backend() is ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.