repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
EpistasisLab/scikit-rebate | skrebate/relieff.py | ReliefF._distarray_missing | python | def _distarray_missing(self, xc, xd, cdiffs):
cindices = []
dindices = []
# Get Boolean mask locating missing values for continuous and discrete features separately. These correspond to xc and xd respectively.
for i in range(self._datalen):
cindices.append(np.where(np.isnan(x... | Distance array calculation for data with missing values | train | https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/relieff.py#L357-L374 | null | class ReliefF(BaseEstimator):
"""Feature selection using data-mined expert knowledge.
Based on the ReliefF algorithm as introduced in:
Igor et al. Overcoming the myopia of inductive learning
algorithms with RELIEFF (1997), Applied Intelligence, 7(1), p39-55"""
"""Note that ReliefF class establishe... |
EpistasisLab/scikit-rebate | skrebate/relieff.py | ReliefF._find_neighbors | python | def _find_neighbors(self, inst):
# Make a vector of distances between target instance (inst) and all others
dist_vect = []
for j in range(self._datalen):
if inst != j:
locator = [inst, j]
if inst < j:
locator.reverse()
... | Identify k nearest hits and k nearest misses for given instance. This is accomplished differently based on the type of endpoint (i.e. binary, multiclass, and continuous). | train | https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/relieff.py#L379-L454 | null | class ReliefF(BaseEstimator):
"""Feature selection using data-mined expert knowledge.
Based on the ReliefF algorithm as introduced in:
Igor et al. Overcoming the myopia of inductive learning
algorithms with RELIEFF (1997), Applied Intelligence, 7(1), p39-55"""
"""Note that ReliefF class establishe... |
EpistasisLab/scikit-rebate | skrebate/turf.py | TuRF.fit | python | def fit(self, X, y, headers):
self.X_mat = X
self._y = y
self.headers = headers
self._num_attributes = len(self.X_mat[0])
self._lost = {}
#Combine TuRF with specified 'core' Relief-based algorithm
if self.core_algorithm.lower() == "multisurf":
... | Uses the input `core_algorithm` to determine feature importance scores at each iteration.
At every iteration, a certain number(determined by input parameter `pct`) of least important
features are removed, until the feature set is reduced down to the top `n_features_to_select` features.
Paramete... | train | https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/turf.py#L62-L175 | null | class TuRF(BaseEstimator, TransformerMixin):
"""Feature selection using data-mined expert knowledge.
Based on the ReliefF algorithm as introduced in:
Kononenko, Igor et al. Overcoming the myopia of inductive learning
algorithms with RELIEFF (1997), Applied Intelligence, 7(1), p39-55
"""
def... |
EpistasisLab/scikit-rebate | skrebate/surfstar.py | SURFstar._find_neighbors | python | def _find_neighbors(self, inst, avg_dist):
NN_near = []
NN_far = []
min_indices = []
max_indices = []
for i in range(self._datalen):
if inst != i:
locator = [inst, i]
if i > inst:
locator.reverse()
d... | Identify nearest as well as farthest hits and misses within radius defined by average distance over whole distance array.
This works the same regardless of endpoint type. | train | https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/surfstar.py#L46-L70 | null | class SURFstar(SURF):
"""Feature selection using data-mined expert knowledge.
Based on the SURF* algorithm as introduced in:
Moore, Jason et al. Multiple Threshold Spatially Uniform ReliefF
for the Genetic Analysis of Complex Human Diseases.
"""
############################# SURF* #############... |
EpistasisLab/scikit-rebate | skrebate/scoring_utils.py | get_row_missing | python | def get_row_missing(xc, xd, cdiffs, index, cindices, dindices):
""" Calculate distance between index instance and all other instances. """
row = np.empty(0, dtype=np.double) # initialize empty row
cinst1 = xc[index] # continuous-valued features for index instance
dinst1 = xd[index] # discrete-val... | Calculate distance between index instance and all other instances. | train | https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/scoring_utils.py#L31-L83 | null | # -*- coding: utf-8 -*-
"""
scikit-rebate was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Pete Schmitt (pschmitt@upenn.edu)
- Ryan J. Urbanowicz (ryanurb@upenn.edu)
- Weixuan Fu (weixuanf@upenn.edu)
- and many more generous open source contrib... |
EpistasisLab/scikit-rebate | skrebate/scoring_utils.py | ramp_function | python | def ramp_function(data_type, attr, fname, xinstfeature, xNNifeature):
""" Our own user simplified variation of the ramp function suggested by Hong 1994, 1997. Hong's method requires the user to specifiy two thresholds
that indicate the max difference before a score of 1 is given, as well a min difference befo... | Our own user simplified variation of the ramp function suggested by Hong 1994, 1997. Hong's method requires the user to specifiy two thresholds
that indicate the max difference before a score of 1 is given, as well a min difference before a score of 0 is given, and any in the middle get a
score that is the no... | train | https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/scoring_utils.py#L86-L108 | null | # -*- coding: utf-8 -*-
"""
scikit-rebate was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Pete Schmitt (pschmitt@upenn.edu)
- Ryan J. Urbanowicz (ryanurb@upenn.edu)
- Weixuan Fu (weixuanf@upenn.edu)
- and many more generous open source contrib... |
EpistasisLab/scikit-rebate | skrebate/scoring_utils.py | compute_score | python | def compute_score(attr, mcmap, NN, feature, inst, nan_entries, headers, class_type, X, y, labels_std, data_type, near=True):
"""Flexible feature scoring method that can be used with any core Relief-based method. Scoring proceeds differently
based on whether endpoint is binary, multiclass, or continuous. This ... | Flexible feature scoring method that can be used with any core Relief-based method. Scoring proceeds differently
based on whether endpoint is binary, multiclass, or continuous. This method is called for a single target instance
+ feature combination and runs over all items in NN. | train | https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/scoring_utils.py#L111-L349 | [
"def ramp_function(data_type, attr, fname, xinstfeature, xNNifeature):\n \"\"\" Our own user simplified variation of the ramp function suggested by Hong 1994, 1997. Hong's method requires the user to specifiy two thresholds\n that indicate the max difference before a score of 1 is given, as well a min differe... | # -*- coding: utf-8 -*-
"""
scikit-rebate was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Pete Schmitt (pschmitt@upenn.edu)
- Ryan J. Urbanowicz (ryanurb@upenn.edu)
- Weixuan Fu (weixuanf@upenn.edu)
- and many more generous open source contrib... |
EpistasisLab/scikit-rebate | skrebate/scoring_utils.py | ReliefF_compute_scores | python | def ReliefF_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN, headers, class_type, X, y, labels_std, data_type):
""" Unique scoring procedure for ReliefF algorithm. Scoring based on k nearest hits and misses of current target instance. """
scores = np.zeros(num_attributes)
for feature_nu... | Unique scoring procedure for ReliefF algorithm. Scoring based on k nearest hits and misses of current target instance. | train | https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/scoring_utils.py#L352-L358 | [
"def compute_score(attr, mcmap, NN, feature, inst, nan_entries, headers, class_type, X, y, labels_std, data_type, near=True):\n \"\"\"Flexible feature scoring method that can be used with any core Relief-based method. Scoring proceeds differently\n based on whether endpoint is binary, multiclass, or continuou... | # -*- coding: utf-8 -*-
"""
scikit-rebate was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Pete Schmitt (pschmitt@upenn.edu)
- Ryan J. Urbanowicz (ryanurb@upenn.edu)
- Weixuan Fu (weixuanf@upenn.edu)
- and many more generous open source contrib... |
EpistasisLab/scikit-rebate | skrebate/scoring_utils.py | SURFstar_compute_scores | python | def SURFstar_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN_near, NN_far, headers, class_type, X, y, labels_std, data_type):
""" Unique scoring procedure for SURFstar algorithm. Scoring based on nearest neighbors within defined radius, as well as
'anti-scoring' of far instances outside of r... | Unique scoring procedure for SURFstar algorithm. Scoring based on nearest neighbors within defined radius, as well as
'anti-scoring' of far instances outside of radius of current target instance | train | https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/scoring_utils.py#L372-L384 | [
"def compute_score(attr, mcmap, NN, feature, inst, nan_entries, headers, class_type, X, y, labels_std, data_type, near=True):\n \"\"\"Flexible feature scoring method that can be used with any core Relief-based method. Scoring proceeds differently\n based on whether endpoint is binary, multiclass, or continuou... | # -*- coding: utf-8 -*-
"""
scikit-rebate was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Pete Schmitt (pschmitt@upenn.edu)
- Ryan J. Urbanowicz (ryanurb@upenn.edu)
- Weixuan Fu (weixuanf@upenn.edu)
- and many more generous open source contrib... |
EpistasisLab/scikit-rebate | skrebate/multisurf.py | MultiSURF._run_algorithm | python | def _run_algorithm(self):
nan_entries = np.isnan(self._X)
NNlist = [self._find_neighbors(datalen) for datalen in range(self._datalen)]
scores = np.sum(Parallel(n_jobs=self.n_jobs)(delayed(
MultiSURF_compute_scores)(instance_num, self.attr, nan_entries, self._num_attributes, self.mc... | Runs nearest neighbor (NN) identification and feature scoring to yield MultiSURF scores. | train | https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/multisurf.py#L74-L85 | null | class MultiSURF(SURFstar):
"""Feature selection using data-mined expert knowledge.
Based on the MultiSURF algorithm as introduced in:
Moore, Jason et al. Multiple Threshold Spatially Uniform ReliefF
for the Genetic Analysis of Complex Human Diseases.
"""
############################# MultiSURF ... |
EpistasisLab/scikit-rebate | skrebate/vlsrelief.py | VLSRelief.fit | python | def fit(self, X, y, headers):
self.X_mat = X
self._y = y
self.headers = headers
if self.core_algorithm.lower() == "multisurf":
core = MultiSURF(n_features_to_select=self.n_features_to_select, discrete_threshold=self.discrete_threshold, verbose=self.verbose, n_jobs=self.n_jo... | Generates `num_feature_subset` sets of features each of size `size_feature_subset`.
Thereafter, uses the input `core_algorithm` to determine feature importance scores
for each subset. The global feature score is determined by the max score for that feature
from all its occurences in the subsets ... | train | https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/vlsrelief.py#L65-L145 | null | class VLSRelief(BaseEstimator, TransformerMixin):
"""Feature selection using data-mined expert knowledge.
Based on the ReliefF algorithm as introduced in:
Kononenko, Igor et al. Overcoming the myopia of inductive learning
algorithms with RELIEFF (1997), Applied Intelligence, 7(1), p39-55
"""
... |
EpistasisLab/scikit-rebate | skrebate/multisurfstar.py | MultiSURFstar._find_neighbors | python | def _find_neighbors(self, inst):
dist_vect = []
for j in range(self._datalen):
if inst != j:
locator = [inst, j]
if inst < j:
locator.reverse()
dist_vect.append(self._distance_array[locator[0]][locator[1]])
dist_vec... | Identify nearest as well as farthest hits and misses within radius defined by average distance and standard deviation of distances from target instanace.
This works the same regardless of endpoint type. | train | https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/multisurfstar.py#L46-L75 | null | class MultiSURFstar(SURFstar):
"""Feature selection using data-mined expert knowledge.
Based on the MultiSURF algorithm as introduced in:
Moore, Jason et al. Multiple Threshold Spatially Uniform ReliefF
for the Genetic Analysis of Complex Human Diseases.
"""
############################# MultiS... |
EpistasisLab/scikit-rebate | skrebate/surf.py | SURF._find_neighbors | python | def _find_neighbors(self, inst, avg_dist):
NN = []
min_indicies = []
for i in range(self._datalen):
if inst != i:
locator = [inst, i]
if i > inst:
locator.reverse()
d = self._distance_array[locator[0]][locator[1]]
... | Identify nearest hits and misses within radius defined by average distance over whole distance array.
This works the same regardless of endpoint type. | train | https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/surf.py#L71-L87 | null | class SURF(ReliefF):
"""Feature selection using data-mined expert knowledge.
Based on the SURF algorithm as introduced in:
Moore, Jason et al. Multiple Threshold Spatially Uniform ReliefF
for the Genetic Analysis of Complex Human Diseases.
"""
def __init__(self, n_features_to_select=10, dis... |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/management/templates/python-engine/project_package/_logging.py | get_logger | python | def get_logger(name, namespace='{{project.package}}',
log_level=DEFAULT_LOG_LEVEL, log_dir=DEFAULT_LOG_DIR):
log_level = (os.getenv('{}_LOG_LEVEL'.format(namespace.upper())) or
os.getenv('LOG_LEVEL', log_level))
log_dir = (os.getenv('{}_LOG_DIR'.format(namespace.upper())) or
... | Build a logger that outputs to a file and to the console, | train | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/management/templates/python-engine/project_package/_logging.py#L36-L77 | null | #!/usr/bin/env python
# coding=utf-8
"""Custom logging module.
This module is responsible to manage log messages and log file.
"""
import sys
import os
import os.path
import logging
DEFAULT_LOG_LEVEL = logging.WARNING
DEFAULT_LOG_DIR = '/tmp'
class Logger(logging.getLoggerClass()):
"""Custom logger class.
... |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/config.py | Configuration.get | python | def get(cls, key, section=None, **kwargs):
section = section or cls._default_sect
if section not in cls._conf:
cls._load(section=section)
value = cls._conf[section].get(key)
# if not found in context read default
if not value and section != cls._default_sect:
... | Retrieves a config value from dict.
If not found twrows an InvalidScanbooconfigException. | train | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/config.py#L90-L118 | [
"def from_json(json_str):\n return simplejson.loads(json_str, object_hook=_from_json_object_hook)\n",
"def _load(cls, section=None):\n section = section or cls._default_sect\n cls._conf[section] = load_conf_from_file(section=section)\n"
] | class Configuration(object):
"""
Abstracts persistent configuration.
Reads configurations and defaults from a `/etc/marvin/marvin.ini` file.
Usage:
Configuration.get('my.key')
"""
_conf = {}
_default_sect = DEFAULT_SECT
PREFIX = DEFAULT_PREFIX
@classmethod
def reset(... |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/config.py | Configuration.keys | python | def keys(cls, section=None):
section = section or cls._default_sect
if section not in cls._conf:
cls._load(section=section)
return cls._conf[section].keys() | Get a list with all config keys | train | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/config.py#L121-L126 | [
"def _load(cls, section=None):\n section = section or cls._default_sect\n cls._conf[section] = load_conf_from_file(section=section)\n"
] | class Configuration(object):
"""
Abstracts persistent configuration.
Reads configurations and defaults from a `/etc/marvin/marvin.ini` file.
Usage:
Configuration.get('my.key')
"""
_conf = {}
_default_sect = DEFAULT_SECT
PREFIX = DEFAULT_PREFIX
@classmethod
def reset(... |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/management/templates/python-engine/setup.py | _get_version | python | def _get_version():
with open(join(dirname(__file__), '{{project.package}}/VERSION'), 'rb') as f:
version = f.read().decode('ascii').strip()
return version | Return the project version from VERSION file. | train | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/management/templates/python-engine/setup.py#L20-L25 | null | from __future__ import print_function
import os
import shutil
from os.path import dirname, join
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
from setuptools.command.develop import develop as _develop
from setuptools.command.install import install as _install
REQ... |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/http_client.py | HttpClient.parse_response | python | def parse_response(self, response):
status = response.status_code
if response.ok:
data = response.json()
return HttpResponse(ok=response.ok, status=status, errors=None, data=data)
else:
try:
errors = response.json()
except ValueErro... | Parse the response and build a `scanboo_common.http_client.HttpResponse` object.
For successful responses, convert the json data into a dict.
:param response: the `requests` response
:return: [HttpResponse] response object | train | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/http_client.py#L69-L87 | null | class HttpClient(object):
"""
Http REST client
used as superclass for the specific API classes
override the `host` property method to return the api server host
usage:
class MyApiClient(object):
@property
def host(self):
return "http://myapiurl:8000... |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/http_client.py | HttpClient.get_all | python | def get_all(self, path, data=None, limit=100):
return ListResultSet(path=path, data=data or {}, limit=limit) | Encapsulates GET all requests | train | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/http_client.py#L101-L103 | null | class HttpClient(object):
"""
Http REST client
used as superclass for the specific API classes
override the `host` property method to return the api server host
usage:
class MyApiClient(object):
@property
def host(self):
return "http://myapiurl:8000... |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/http_client.py | HttpClient.get | python | def get(self, path, data=None):
data = data or {}
response = requests.get(self.url(path), params=data, headers=self.request_header())
return self.parse_response(response) | Encapsulates GET requests | train | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/http_client.py#L105-L109 | [
"def url(self, path):\n \"\"\"\n Build url for the specified path.\n\n :param path: [string] the url path for the api endpoint\n\n :return: [string] formated url\n \"\"\"\n\n if 'http://' in path or 'https://' in path:\n return path\n else:\n return self.host + path\n",
"def par... | class HttpClient(object):
"""
Http REST client
used as superclass for the specific API classes
override the `host` property method to return the api server host
usage:
class MyApiClient(object):
@property
def host(self):
return "http://myapiurl:8000... |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/http_client.py | HttpClient.post | python | def post(self, path, data=None):
data = data or {}
response = requests.post(self.url(path), data=to_json(data), headers=self.request_header())
return self.parse_response(response) | Encapsulates POST requests | train | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/http_client.py#L111-L115 | [
"def to_json(data):\n \"\"\"Convert non default objects to json.\"\"\"\n return json.dumps(data, default=_to_json_default)\n",
"def url(self, path):\n \"\"\"\n Build url for the specified path.\n\n :param path: [string] the url path for the api endpoint\n\n :return: [string] formated url\n \"... | class HttpClient(object):
"""
Http REST client
used as superclass for the specific API classes
override the `host` property method to return the api server host
usage:
class MyApiClient(object):
@property
def host(self):
return "http://myapiurl:8000... |
marvin-ai/marvin-python-toolbox | setup.py | _get_version | python | def _get_version():
with open(os.path.join(os.path.dirname(__file__), PACKAGE_NAME, 'VERSION'), 'rb') as f:
version = f.read().decode('ascii').strip()
return version | Return the project version from VERSION file. | train | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/setup.py#L104-L108 | null | #!/usr/bin/env python
# coding=utf-8
# Copyright [2017] [B2W Digital]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/data.py | MarvinData.get_data_path | python | def get_data_path(cls):
marvin_path = os.environ.get(cls._key)
if not marvin_path:
raise InvalidConfigException('Data path not set!')
is_path_created = check_path(marvin_path, create=True)
if not is_path_created:
raise InvalidConfigException('Data path does not e... | Read data path from the following sources in order of priority:
1. Environment variable
If not found raises an exception
:return: str - datapath | train | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/data.py#L47-L65 | [
"def check_path(path, create=False):\n \"\"\"\n Check for a path on filesystem\n\n :param path: str - path name\n :param create: bool - create if do not exist\n :return: bool - path exists\n \"\"\"\n if not os.path.exists(path):\n if create:\n os.makedirs(path)\n re... | class MarvinData(with_metaclass(AbstractMarvinData)):
_key = 'MARVIN_DATA_PATH'
@classmethod
@classmethod
def _convert_path_to_key(cls, path):
if path.startswith(os.path.sep):
path = os.path.relpath(path, start=cls.data_path)
return '/'.join(path.split(os.path.sep))
@... |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/data.py | MarvinData.load_data | python | def load_data(cls, relpath):
filepath = os.path.join(cls.data_path, relpath)
with open(filepath) as fp:
content = fp.read()
return content | Load data from the following sources in order of priority:
1. Filesystem
:param relpath: path relative to "data_path"
:return: str - data content | train | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/data.py#L74-L87 | null | class MarvinData(with_metaclass(AbstractMarvinData)):
_key = 'MARVIN_DATA_PATH'
@classmethod
def get_data_path(cls):
"""
Read data path from the following sources in order of priority:
1. Environment variable
If not found raises an exception
:return: str - datapat... |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/data.py | MarvinData.download_file | python | def download_file(cls, url, local_file_name=None, force=False, chunk_size=1024):
local_file_name = local_file_name if local_file_name else url.split('/')[-1]
filepath = os.path.join(cls.data_path, local_file_name)
if not os.path.exists(filepath) or force:
try:
heade... | Download file from a given url | train | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/data.py#L90-L132 | null | class MarvinData(with_metaclass(AbstractMarvinData)):
_key = 'MARVIN_DATA_PATH'
@classmethod
def get_data_path(cls):
"""
Read data path from the following sources in order of priority:
1. Environment variable
If not found raises an exception
:return: str - datapat... |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/utils.py | chunks | python | def chunks(lst, size):
for i in xrange(0, len(lst), size):
yield lst[i:i + size] | Yield successive n-sized chunks from lst. | train | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/utils.py#L110-L113 | null | #!/usr/bin/env python
# coding=utf-8
# Copyright [2017] [B2W Digital]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/utils.py | _to_json_default | python | def _to_json_default(obj):
# Datetime
if isinstance(obj, datetime.datetime):
return obj.isoformat()
# UUID
if isinstance(obj, uuid.UUID):
return str(obj)
# numpy
if hasattr(obj, 'item'):
return obj.item()
# # Enum
# if hasattr(obj, 'value'):
# return ob... | Helper to convert non default objects to json.
Usage:
simplejson.dumps(data, default=_to_json_default) | train | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/utils.py#L116-L141 | null | #!/usr/bin/env python
# coding=utf-8
# Copyright [2017] [B2W Digital]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/utils.py | _from_json_object_hook | python | def _from_json_object_hook(obj):
for key, value in obj.items():
# Check for datetime objects
if isinstance(value, str):
dt_result = datetime_regex.match(value)
if dt_result:
year, month, day, hour, minute, second = map(
lambda x: int(x), d... | Converts a json string, where datetime and UUID objects were converted
into strings using the '_to_json_default', into a python object.
Usage:
simplejson.loads(data, object_hook=_from_json_object_hook) | train | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/utils.py#L148-L169 | null | #!/usr/bin/env python
# coding=utf-8
# Copyright [2017] [B2W Digital]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/utils.py | check_path | python | def check_path(path, create=False):
if not os.path.exists(path):
if create:
os.makedirs(path)
return os.path.exists(path)
else:
return False
return True | Check for a path on filesystem
:param path: str - path name
:param create: bool - create if do not exist
:return: bool - path exists | train | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/utils.py#L245-L260 | null | #!/usr/bin/env python
# coding=utf-8
# Copyright [2017] [B2W Digital]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/utils.py | url_encode | python | def url_encode(url):
if isinstance(url, text_type):
url = url.encode('utf8')
return quote(url, ':/%?&=') | Convert special characters using %xx escape.
:param url: str
:return: str - encoded url | train | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/utils.py#L286-L295 | null | #!/usr/bin/env python
# coding=utf-8
# Copyright [2017] [B2W Digital]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/data_source_provider.py | get_spark_session | python | def get_spark_session(enable_hive=False, app_name='marvin-engine', configs=[]):
# Prepare spark context to be used
import findspark
findspark.init()
from pyspark.sql import SparkSession
# prepare spark sesseion to be returned
spark = SparkSession.builder
spark = spark.appName(app_name)
... | Return a Spark Session object | train | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/data_source_provider.py#L25-L43 | null | #!/usr/bin/env python
# coding=utf-8
# Copyright [2017] [B2W Digital]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/management/pkg.py | get_version | python | def get_version(path):
with open(os.path.join(path, 'VERSION'), 'rb') as f:
version = f.read().decode('ascii').strip()
return version.strip() | Return the project version from VERSION file. | train | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/management/pkg.py#L248-L253 | null | #!/usr/bin/env python
# coding=utf-8
# Copyright [2017] [B2W Digital]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
myint/cppclean | cpp/tokenize.py | get_tokens | python | def get_tokens(source):
if not source.endswith('\n'):
source += '\n'
# Cache various valid character sets for speed.
valid_identifier_first_chars = VALID_IDENTIFIER_FIRST_CHARS
valid_identifier_chars = VALID_IDENTIFIER_CHARS
hex_digits = HEX_DIGITS
int_or_float_digits = INT_OR_FLOAT_DIG... | Returns a sequence of Tokens.
Args:
source: string of C++ source code.
Yields:
Token that represents the next token in the source. | train | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/tokenize.py#L104-L286 | [
"def _find(string, sub_string, start_index):\n \"\"\"Return index of sub_string in string.\n\n Raise TokenError if sub_string is not found.\n \"\"\"\n result = string.find(sub_string, start_index)\n if result == -1:\n raise TokenError(\"expected '{0}'\".format(sub_string))\n return result\n... | # Copyright 2007 Neal Norwitz
# Portions Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
myint/cppclean | cpp/tokenize.py | _find | python | def _find(string, sub_string, start_index):
result = string.find(sub_string, start_index)
if result == -1:
raise TokenError("expected '{0}'".format(sub_string))
return result | Return index of sub_string in string.
Raise TokenError if sub_string is not found. | train | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/tokenize.py#L289-L297 | null | # Copyright 2007 Neal Norwitz
# Portions Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
myint/cppclean | cpp/ast.py | builder_from_source | python | def builder_from_source(source, filename, system_includes,
nonsystem_includes, quiet=False):
return ASTBuilder(tokenize.get_tokens(source),
filename,
system_includes,
nonsystem_includes,
quiet=quiet) | Utility method that returns an ASTBuilder from source code.
Args:
source: 'C++ source code'
filename: 'file1'
Returns:
ASTBuilder | train | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/ast.py#L1654-L1669 | [
"def get_tokens(source):\n \"\"\"Returns a sequence of Tokens.\n\n Args:\n source: string of C++ source code.\n\n Yields:\n Token that represents the next token in the source.\n \"\"\"\n if not source.endswith('\\n'):\n source += '\\n'\n\n # Cache various valid character sets for ... | # Copyright 2007 Neal Norwitz
# Portions Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
myint/cppclean | cpp/ast.py | VariableDeclaration.to_string | python | def to_string(self):
suffix = '%s %s' % (self.type, self.name)
if self.initial_value:
suffix += ' = ' + self.initial_value
return suffix | Return a string that tries to reconstitute the variable decl. | train | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/ast.py#L201-L206 | null | class VariableDeclaration(_GenericDeclaration):
def __init__(self, start, end, name, var_type, initial_value, namespace):
_GenericDeclaration.__init__(self, start, end, name, namespace)
self.type = var_type
self.initial_value = initial_value
def __str__(self):
return self._str... |
myint/cppclean | cpp/ast.py | TypeConverter.to_type | python | def to_type(self, tokens):
result = []
name_tokens = []
reference = pointer = array = False
inside_array = False
empty_array = True
templated_tokens = []
def add_type():
if not name_tokens:
return
# Partition tokens into n... | Convert [Token,...] to [Class(...), ] useful for base classes.
For example, code like class Foo : public Bar<x, y> { ... };
the "Bar<x, y>" portion gets converted to an AST.
Returns:
[Class(...), ...] | train | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/ast.py#L408-L475 | [
"def _get_template_end(self, tokens, start):\n count = 1\n end = start\n while count and end < len(tokens):\n token = tokens[end]\n end += 1\n if token.name == '<':\n count += 1\n elif token.name == '>':\n count -= 1\n return tokens[start:end - 1], end\n... | class TypeConverter(object):
def __init__(self, namespace_stack):
self.namespace_stack = namespace_stack
def _get_template_end(self, tokens, start):
count = 1
end = start
while count and end < len(tokens):
token = tokens[end]
end += 1
if toke... |
myint/cppclean | cpp/ast.py | ASTBuilder.get_name | python | def get_name(self, seq=None):
if seq is not None:
it = iter(seq)
def get_next_token():
return next(it)
else:
get_next_token = self._get_next_token
next_token = get_next_token()
tokens = []
last_token_was_name = False
w... | Returns ([tokens], next_token_info). | train | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/ast.py#L913-L941 | [
"def _get_matching_char(self, open_paren, close_paren, get_next_token=None):\n if get_next_token is None:\n get_next_token = self._get_next_token\n # Assumes the current token is open_paren and we will consume\n # and return up to the close_paren.\n count = 1\n while count != 0:\n token... | class ASTBuilder(object):
def __init__(self, token_stream, filename, system_includes=tuple(),
nonsystem_includes=tuple(), in_class=None,
namespace_stack=None, quiet=False):
if namespace_stack is None:
namespace_stack = []
self.system_includes = system_... |
myint/cppclean | cpp/symbols.py | SymbolTable._lookup_namespace | python | def _lookup_namespace(self, symbol, namespace):
for namespace_part in symbol.parts:
namespace = namespace.get(namespace_part)
if namespace is None:
break
if not isinstance(namespace, dict):
return namespace
raise Error('%s not found' % ... | Helper for lookup_symbol that only looks up variables in a
namespace.
Args:
symbol: Symbol
namespace: pointer into self.namespaces | train | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/symbols.py#L48-L62 | null | class SymbolTable(object):
"""Symbol table that can perform namespace operations."""
def __init__(self):
# None is the global namespace.
self.namespaces = {None: {}}
def _lookup_global(self, symbol):
"""Helper for lookup_symbol that only looks up global variables.
Args:
... |
myint/cppclean | cpp/symbols.py | SymbolTable._lookup_global | python | def _lookup_global(self, symbol):
assert symbol.parts
namespace = self.namespaces
if len(symbol.parts) == 1:
# If there is only one part, look in globals.
namespace = self.namespaces[None]
try:
# Try to do a normal, global namespace lookup.
... | Helper for lookup_symbol that only looks up global variables.
Args:
symbol: Symbol | train | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/symbols.py#L64-L85 | [
"def _lookup_namespace(self, symbol, namespace):\n \"\"\"Helper for lookup_symbol that only looks up variables in a\n namespace.\n\n Args:\n symbol: Symbol\n namespace: pointer into self.namespaces\n \"\"\"\n for namespace_part in symbol.parts:\n namespace = namespace.get(namespace_p... | class SymbolTable(object):
"""Symbol table that can perform namespace operations."""
def __init__(self):
# None is the global namespace.
self.namespaces = {None: {}}
def _lookup_namespace(self, symbol, namespace):
"""Helper for lookup_symbol that only looks up variables in a
... |
myint/cppclean | cpp/symbols.py | SymbolTable._lookup_in_all_namespaces | python | def _lookup_in_all_namespaces(self, symbol):
namespace = self.namespaces
# Create a stack of namespaces.
namespace_stack = []
for current in symbol.namespace_stack:
namespace = namespace.get(current)
if namespace is None or not isinstance(namespace, dict):
... | Helper for lookup_symbol that looks for symbols in all namespaces.
Args:
symbol: Symbol | train | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/symbols.py#L87-L109 | [
"def _lookup_namespace(self, symbol, namespace):\n \"\"\"Helper for lookup_symbol that only looks up variables in a\n namespace.\n\n Args:\n symbol: Symbol\n namespace: pointer into self.namespaces\n \"\"\"\n for namespace_part in symbol.parts:\n namespace = namespace.get(namespace_p... | class SymbolTable(object):
"""Symbol table that can perform namespace operations."""
def __init__(self):
# None is the global namespace.
self.namespaces = {None: {}}
def _lookup_namespace(self, symbol, namespace):
"""Helper for lookup_symbol that only looks up variables in a
... |
myint/cppclean | cpp/symbols.py | SymbolTable.lookup_symbol | python | def lookup_symbol(self, name, namespace_stack):
# TODO(nnorwitz): a convenient API for this depends on the
# representation of the name. e.g., does symbol_name contain
# ::, is symbol_name a list of colon separated names, how are
# names prefixed with :: handled. These have different loo... | Returns AST node and module for symbol if found.
Args:
name: 'name of the symbol to lookup'
namespace_stack: None or ['namespaces', 'in', 'current', 'scope']
Returns:
(ast.Node, module (ie, any object stored with symbol)) if found
Raises:
Error if the s... | train | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/symbols.py#L111-L141 | [
"def _lookup_global(self, symbol):\n \"\"\"Helper for lookup_symbol that only looks up global variables.\n\n Args:\n symbol: Symbol\n \"\"\"\n assert symbol.parts\n namespace = self.namespaces\n if len(symbol.parts) == 1:\n # If there is only one part, look in globals.\n namespa... | class SymbolTable(object):
"""Symbol table that can perform namespace operations."""
def __init__(self):
# None is the global namespace.
self.namespaces = {None: {}}
def _lookup_namespace(self, symbol, namespace):
"""Helper for lookup_symbol that only looks up variables in a
... |
myint/cppclean | cpp/symbols.py | SymbolTable._add | python | def _add(self, symbol_name, namespace, node, module):
result = symbol_name in namespace
namespace[symbol_name] = node, module
return not result | Helper function for adding symbols.
See add_symbol(). | train | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/symbols.py#L143-L150 | null | class SymbolTable(object):
"""Symbol table that can perform namespace operations."""
def __init__(self):
# None is the global namespace.
self.namespaces = {None: {}}
def _lookup_namespace(self, symbol, namespace):
"""Helper for lookup_symbol that only looks up variables in a
... |
myint/cppclean | cpp/symbols.py | SymbolTable.add_symbol | python | def add_symbol(self, symbol_name, namespace_stack, node, module):
# TODO(nnorwitz): verify symbol_name doesn't contain :: ?
if namespace_stack:
# Handle non-global symbols (ie, in some namespace).
last_namespace = self.namespaces
for namespace in namespace_stack:
... | Adds symbol_name defined in namespace_stack to the symbol table.
Args:
symbol_name: 'name of the symbol to lookup'
namespace_stack: None or ['namespaces', 'symbol', 'defined', 'in']
node: ast.Node that defines this symbol
module: module (any object) this symbol is define... | train | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/symbols.py#L152-L172 | [
"def _add(self, symbol_name, namespace, node, module):\n \"\"\"Helper function for adding symbols.\n\n See add_symbol().\n \"\"\"\n result = symbol_name in namespace\n namespace[symbol_name] = node, module\n return not result\n"
] | class SymbolTable(object):
"""Symbol table that can perform namespace operations."""
def __init__(self):
# None is the global namespace.
self.namespaces = {None: {}}
def _lookup_namespace(self, symbol, namespace):
"""Helper for lookup_symbol that only looks up variables in a
... |
myint/cppclean | cpp/symbols.py | SymbolTable.get_namespace | python | def get_namespace(self, name_seq):
namespaces = self.namespaces
result = []
for name in name_seq:
namespaces = namespaces.get(name)
if not namespaces:
break
result.append(name)
return result | Returns the prefix of names from name_seq that are known namespaces.
Args:
name_seq: ['names', 'of', 'possible', 'namespace', 'to', 'find']
Returns:
['names', 'that', 'are', 'namespaces', 'possibly', 'empty', 'list'] | train | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/symbols.py#L174-L190 | null | class SymbolTable(object):
"""Symbol table that can perform namespace operations."""
def __init__(self):
# None is the global namespace.
self.namespaces = {None: {}}
def _lookup_namespace(self, symbol, namespace):
"""Helper for lookup_symbol that only looks up variables in a
... |
myint/cppclean | cpp/find_warnings.py | WarningHunter._verify_include_files_used | python | def _verify_include_files_used(self, file_uses, included_files):
for include_file, use in file_uses.items():
if not use & USES_DECLARATION:
node, module = included_files[include_file]
if module.ast_list is not None:
msg = "'{}' does not need to be ... | Find all #include files that are unnecessary. | train | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/find_warnings.py#L211-L221 | null | class WarningHunter(object):
# Cache filename: ast_list
_module_cache = {}
def __init__(self, filename, source, ast_list, include_paths,
system_include_paths, nonsystem_include_paths,
quiet=False):
self.filename = filename
self.source = source
self... |
myint/cppclean | cpp/find_warnings.py | WarningHunter._verify_forward_declarations_used | python | def _verify_forward_declarations_used(self, forward_declarations,
decl_uses, file_uses):
for cls in forward_declarations:
if cls in file_uses:
if not decl_uses[cls] & USES_DECLARATION:
node = forward_declarations[cls]
... | Find all the forward declarations that are not used. | train | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/find_warnings.py#L223-L237 | null | class WarningHunter(object):
# Cache filename: ast_list
_module_cache = {}
def __init__(self, filename, source, ast_list, include_paths,
system_include_paths, nonsystem_include_paths,
quiet=False):
self.filename = filename
self.source = source
self... |
myint/cppclean | cpp/find_warnings.py | WarningHunter._determine_uses | python | def _determine_uses(self, included_files, forward_declarations):
file_uses = dict.fromkeys(included_files, UNUSED)
decl_uses = dict.fromkeys(forward_declarations, UNUSED)
symbol_table = self.symbol_table
for name, node in forward_declarations.items():
try:
sy... | Set up the use type of each symbol. | train | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/find_warnings.py#L239-L447 | null | class WarningHunter(object):
# Cache filename: ast_list
_module_cache = {}
def __init__(self, filename, source, ast_list, include_paths,
system_include_paths, nonsystem_include_paths,
quiet=False):
self.filename = filename
self.source = source
self... |
myint/cppclean | cpp/find_warnings.py | WarningHunter._check_public_functions | python | def _check_public_functions(self, primary_header, all_headers):
public_symbols = {}
declared_only_symbols = {}
if primary_header:
for name, symbol in primary_header.public_symbols.items():
if isinstance(symbol, ast.Function):
public_symbols[name] =... | Verify all the public functions are also declared in a header
file. | train | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/find_warnings.py#L521-L560 | null | class WarningHunter(object):
# Cache filename: ast_list
_module_cache = {}
def __init__(self, filename, source, ast_list, include_paths,
system_include_paths, nonsystem_include_paths,
quiet=False):
self.filename = filename
self.source = source
self... |
myint/cppclean | cpp/static_data.py | _find_unused_static_warnings | python | def _find_unused_static_warnings(filename, lines, ast_list):
static_declarations = dict(_get_static_declarations(ast_list))
def find_variables_use(body):
for child in body:
if child.name in static_declarations:
static_use_counts[child.name] += 1
static_use_counts = coll... | Warn about unused static variables. | train | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/static_data.py#L84-L112 | [
"def _get_static_declarations(ast_list):\n for node in ast_list:\n if (isinstance(node, ast.VariableDeclaration) and\n 'static' in node.type.modifiers):\n for name in node.name.split(','):\n yield (name, node)\n",
"def get_line_number(self, index):\n \"\"\"Ret... | # Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
myint/cppclean | cpp/utils.py | read_file | python | def read_file(filename, print_error=True):
try:
for encoding in ['utf-8', 'latin1']:
try:
with io.open(filename, encoding=encoding) as fp:
return fp.read()
except UnicodeDecodeError:
pass
except IOError as exception:
if ... | Returns the contents of a file. | train | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/utils.py#L29-L41 | null | # Copyright 2007 Neal Norwitz
# Portions Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/tracers.py | Tracer.end | python | def end(self):
'''Ends the tracer.
May be called in any state. Transitions the state to ended and releases
any SDK resources owned by this tracer (this includes only internal
resources, things like passed-in
:class:`oneagent.common.DbInfoHandle` need to be released manually).
... | Ends the tracer.
May be called in any state. Transitions the state to ended and releases
any SDK resources owned by this tracer (this includes only internal
resources, things like passed-in
:class:`oneagent.common.DbInfoHandle` need to be released manually).
Prefer using the tr... | train | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/tracers.py#L113-L126 | null | class Tracer(object):
'''Base class for tracing of operations.
Note that tracer are not only not thread-safe but thread-affine: They may
only ever be used on the thread that created them.
If a tracer object evaluates to :data:`False` (i.e., is falsy), tracing has
been rejected for some reason (e.g... |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/tracers.py | Tracer.mark_failed | python | def mark_failed(self, clsname, msg):
'''Marks the tracer as failed with the given exception class name
:code:`clsname` and message :code:`msg`.
May only be called in the started state and only if the tracer is not
already marked as failed. Note that this does not end the tracer! Once a
... | Marks the tracer as failed with the given exception class name
:code:`clsname` and message :code:`msg`.
May only be called in the started state and only if the tracer is not
already marked as failed. Note that this does not end the tracer! Once a
tracer is marked as failed, attempts to ... | train | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/tracers.py#L128-L144 | null | class Tracer(object):
'''Base class for tracing of operations.
Note that tracer are not only not thread-safe but thread-affine: They may
only ever be used on the thread that created them.
If a tracer object evaluates to :data:`False` (i.e., is falsy), tracing has
been rejected for some reason (e.g... |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/tracers.py | Tracer.mark_failed_exc | python | def mark_failed_exc(self, e_val=None, e_ty=None):
'''Marks the tracer as failed with the given exception :code:`e_val` of
type :code:`e_ty` (defaults to the current exception).
May only be called in the started state and only if the tracer is not
already marked as failed. Note that this... | Marks the tracer as failed with the given exception :code:`e_val` of
type :code:`e_ty` (defaults to the current exception).
May only be called in the started state and only if the tracer is not
already marked as failed. Note that this does not end the tracer! Once a
tracer is marked as ... | train | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/tracers.py#L146-L168 | [
"def error_from_exc(nsdk, tracer_h, e_val=None, e_ty=None):\n \"\"\"Attach appropriate error information to tracer_h.\n\n If e_val and e_ty are None, the current exception is used.\"\"\"\n\n if not tracer_h:\n return\n\n if e_ty is None and e_val is None:\n e_ty, e_val = sys.exc_info()[:2]... | class Tracer(object):
'''Base class for tracing of operations.
Note that tracer are not only not thread-safe but thread-affine: They may
only ever be used on the thread that created them.
If a tracer object evaluates to :data:`False` (i.e., is falsy), tracing has
been rejected for some reason (e.g... |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/__init__.py | _get_kvc | python | def _get_kvc(kv_arg):
'''Returns a tuple keys, values, count for kv_arg (which can be a dict or a
tuple containing keys, values and optinally count.'''
if isinstance(kv_arg, Mapping):
return six.iterkeys(kv_arg), six.itervalues(kv_arg), len(kv_arg)
assert 2 <= len(kv_arg) <= 3, \
'Ar... | Returns a tuple keys, values, count for kv_arg (which can be a dict or a
tuple containing keys, values and optinally count. | train | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/__init__.py#L57-L67 | null | # -*- coding: utf-8 -*-
#
# Copyright 2018 Dynatrace LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/__init__.py | SDK.create_database_info | python | def create_database_info(
self,
name,
vendor,
channel):
'''Creates a database info with the given information for use with
:meth:`trace_sql_database_request`.
:param str name: The name (e.g., connection string) of the database.
:param str ... | Creates a database info with the given information for use with
:meth:`trace_sql_database_request`.
:param str name: The name (e.g., connection string) of the database.
:param str vendor: The type of the database (e.g., sqlite, PostgreSQL,
MySQL).
:param Channel channel: The... | train | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/__init__.py#L91-L108 | null | class SDK(object):
'''The main entry point to the Dynatrace SDK.'''
def _applytag(self, tracer, str_tag, byte_tag):
if str_tag is None and byte_tag is None:
return
if byte_tag is not None:
if str_tag is not None:
warn = self._nsdk.agent_get_logging_callba... |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/__init__.py | SDK.create_web_application_info | python | def create_web_application_info(
self, virtual_host, application_id, context_root):
'''Creates a web application info for use with
:meth:`trace_incoming_web_request`.
See
<https://www.dynatrace.com/support/help/server-side-services/introduction/how-does-dynatrace-detect-and-... | Creates a web application info for use with
:meth:`trace_incoming_web_request`.
See
<https://www.dynatrace.com/support/help/server-side-services/introduction/how-does-dynatrace-detect-and-name-services/#web-request-services>
for more information about the meaning of the parameters.
... | train | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/__init__.py#L110-L133 | null | class SDK(object):
'''The main entry point to the Dynatrace SDK.'''
def _applytag(self, tracer, str_tag, byte_tag):
if str_tag is None and byte_tag is None:
return
if byte_tag is not None:
if str_tag is not None:
warn = self._nsdk.agent_get_logging_callba... |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/__init__.py | SDK.trace_sql_database_request | python | def trace_sql_database_request(self, database, sql):
'''Create a tracer for the given database info and SQL statement.
:param DbInfoHandle database: Database information (see
:meth:`create_database_info`).
:param str sql: The SQL statement to trace.
:rtype: tracers.DatabaseR... | Create a tracer for the given database info and SQL statement.
:param DbInfoHandle database: Database information (see
:meth:`create_database_info`).
:param str sql: The SQL statement to trace.
:rtype: tracers.DatabaseRequestTracer | train | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/__init__.py#L136-L147 | null | class SDK(object):
'''The main entry point to the Dynatrace SDK.'''
def _applytag(self, tracer, str_tag, byte_tag):
if str_tag is None and byte_tag is None:
return
if byte_tag is not None:
if str_tag is not None:
warn = self._nsdk.agent_get_logging_callba... |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/__init__.py | SDK.trace_incoming_web_request | python | def trace_incoming_web_request(
self,
webapp_info,
url,
method,
headers=None,
remote_address=None,
str_tag=None,
byte_tag=None):
'''Create a tracer for an incoming webrequest.
:param WebapplicationInfoHandle... | Create a tracer for an incoming webrequest.
:param WebapplicationInfoHandle webapp_info: Web application
information (see :meth:`create_web_application_info`).
:param str url: The requested URL (including scheme, hostname/port,
path and query).
:param str method: The HTT... | train | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/__init__.py#L149-L217 | [
"def _get_kvc(kv_arg):\n '''Returns a tuple keys, values, count for kv_arg (which can be a dict or a\n tuple containing keys, values and optinally count.'''\n if isinstance(kv_arg, Mapping):\n return six.iterkeys(kv_arg), six.itervalues(kv_arg), len(kv_arg)\n assert 2 <= len(kv_arg) <= 3, \\\... | class SDK(object):
'''The main entry point to the Dynatrace SDK.'''
def _applytag(self, tracer, str_tag, byte_tag):
if str_tag is None and byte_tag is None:
return
if byte_tag is not None:
if str_tag is not None:
warn = self._nsdk.agent_get_logging_callba... |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/__init__.py | SDK.trace_outgoing_web_request | python | def trace_outgoing_web_request(self, url, method, headers=None):
'''Create a tracer for an outgoing webrequest.
:param str url: The request URL (including scheme, hostname/port, path and query).
:param str method: The HTTP method of the request (e.g., GET or POST).
:param headers: The H... | Create a tracer for an outgoing webrequest.
:param str url: The request URL (including scheme, hostname/port, path and query).
:param str method: The HTTP method of the request (e.g., GET or POST).
:param headers: The HTTP headers of the request. Can be either a
dictionary mapping h... | train | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/__init__.py#L219-L264 | [
"def _get_kvc(kv_arg):\n '''Returns a tuple keys, values, count for kv_arg (which can be a dict or a\n tuple containing keys, values and optinally count.'''\n if isinstance(kv_arg, Mapping):\n return six.iterkeys(kv_arg), six.itervalues(kv_arg), len(kv_arg)\n assert 2 <= len(kv_arg) <= 3, \\\... | class SDK(object):
'''The main entry point to the Dynatrace SDK.'''
def _applytag(self, tracer, str_tag, byte_tag):
if str_tag is None and byte_tag is None:
return
if byte_tag is not None:
if str_tag is not None:
warn = self._nsdk.agent_get_logging_callba... |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/__init__.py | SDK.trace_outgoing_remote_call | python | def trace_outgoing_remote_call(
self,
method,
service,
endpoint,
channel,
protocol_name=None):
'''Creates a tracer for outgoing remote calls.
:param str method: The name of the service method/operation.
:param str service: ... | Creates a tracer for outgoing remote calls.
:param str method: The name of the service method/operation.
:param str service: The name of the service class/type.
:param str endpoint: A string identifying the "instance" of the the
service. See also `the general documentation on servic... | train | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/__init__.py#L266-L303 | null | class SDK(object):
'''The main entry point to the Dynatrace SDK.'''
def _applytag(self, tracer, str_tag, byte_tag):
if str_tag is None and byte_tag is None:
return
if byte_tag is not None:
if str_tag is not None:
warn = self._nsdk.agent_get_logging_callba... |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/__init__.py | SDK.trace_incoming_remote_call | python | def trace_incoming_remote_call(
self,
method,
name,
endpoint,
protocol_name=None,
str_tag=None,
byte_tag=None):
'''Creates a tracer for incoming remote calls.
For the parameters, see :ref:`tagging` (:code:`str_tag` and
... | Creates a tracer for incoming remote calls.
For the parameters, see :ref:`tagging` (:code:`str_tag` and
:code:`byte_tag`) and :meth:`trace_outgoing_remote_call` (all others).
:rtype: tracers.IncomingRemoteCallTracer | train | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/__init__.py#L305-L327 | [
"def _applytag(self, tracer, str_tag, byte_tag):\n if str_tag is None and byte_tag is None:\n return\n if byte_tag is not None:\n if str_tag is not None:\n warn = self._nsdk.agent_get_logging_callback()\n if warn:\n warn('Both str_tag and byte_tag specified. ... | class SDK(object):
'''The main entry point to the Dynatrace SDK.'''
def _applytag(self, tracer, str_tag, byte_tag):
if str_tag is None and byte_tag is None:
return
if byte_tag is not None:
if str_tag is not None:
warn = self._nsdk.agent_get_logging_callba... |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/__init__.py | SDK.trace_in_process_link | python | def trace_in_process_link(self, link_bytes):
'''Creates a tracer for tracing asynchronous related processing in the same process.
For more information see :meth:`create_in_process_link`.
:param bytes link_bytes: An in-process link created using :meth:`create_in_process_link`.
:rtype: ... | Creates a tracer for tracing asynchronous related processing in the same process.
For more information see :meth:`create_in_process_link`.
:param bytes link_bytes: An in-process link created using :meth:`create_in_process_link`.
:rtype: tracers.InProcessLinkTracer
.. versionadded:: 1... | train | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/__init__.py#L357-L369 | null | class SDK(object):
'''The main entry point to the Dynatrace SDK.'''
def _applytag(self, tracer, str_tag, byte_tag):
if str_tag is None and byte_tag is None:
return
if byte_tag is not None:
if str_tag is not None:
warn = self._nsdk.agent_get_logging_callba... |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/__init__.py | SDK.add_custom_request_attribute | python | def add_custom_request_attribute(self, key, value):
'''Adds a custom request attribute to the current active tracer.
:param str key: The name of the custom request attribute, the name is mandatory and
may not be None.
:param value: The value of the custom request attribu... | Adds a custom request attribute to the current active tracer.
:param str key: The name of the custom request attribute, the name is mandatory and
may not be None.
:param value: The value of the custom request attribute. Currently supported types
are integer, floa... | train | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/__init__.py#L430-L453 | null | class SDK(object):
'''The main entry point to the Dynatrace SDK.'''
def _applytag(self, tracer, str_tag, byte_tag):
if str_tag is None and byte_tag is None:
return
if byte_tag is not None:
if str_tag is not None:
warn = self._nsdk.agent_get_logging_callba... |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/common.py | SDKHandleBase.close | python | def close(self):
'''Closes the handle, if it is still open.
Usually, you should prefer using the handle as a context manager to
calling :meth:`close` manually.'''
if self.handle is not None:
self.close_handle(self.nsdk, self.handle)
self.handle = None | Closes the handle, if it is still open.
Usually, you should prefer using the handle as a context manager to
calling :meth:`close` manually. | train | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/common.py#L285-L292 | [
"def close_handle(self, nsdk, handle):\n raise NotImplementedError(\n 'Must implement close_handle in derived class')\n"
] | class SDKHandleBase(object):
'''Base class for SDK handles that must be closed explicitly.
You can use this class as a context manager (i.e. with a :code:`with`-block)
to automatically close the handle.'''
def __init__(self, nsdk, handle):
self.handle = handle
self.nsdk = nsdk
... |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/_impl/native/sdkmockiface.py | TracerHandle.all_original_children | python | def all_original_children(self):
'''Yields all (direct and indirect) children with LINK_CHILD.'''
return chain.from_iterable(
c.all_nodes_in_subtree()
for lnk, c in self.children
if lnk == self.LINK_CHILD) | Yields all (direct and indirect) children with LINK_CHILD. | train | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/_impl/native/sdkmockiface.py#L99-L104 | null | class TracerHandle(_Handle, ThreadBoundObject):
CREATED = 0
STARTED = 1
ENDED = 2
LINK_CHILD = 0
LINK_TAG = 1
_TAG_STRUCT = struct.Struct('>Q') # Big/network-endian unsigned long long
is_in_taggable = False
has_out_tag = False
is_entrypoint = False
def __init__(self, _nsdk, *... |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/__init__.py | sdkopts_from_commandline | python | def sdkopts_from_commandline(argv=None, remove=False, prefix='--dt_'):
'''Creates a SDK option list for use with the :code:`sdkopts` parameter of
:func:`.initialize` from a list :code:`argv` of command line parameters.
An element in :code:`argv` is treated as an SDK option if starts with
:code:`prefix`... | Creates a SDK option list for use with the :code:`sdkopts` parameter of
:func:`.initialize` from a list :code:`argv` of command line parameters.
An element in :code:`argv` is treated as an SDK option if starts with
:code:`prefix`. The return value of this function will then contain the
remainder of tha... | train | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/__init__.py#L116-L152 | null | # -*- coding: utf-8 -*-
#
# Copyright 2018 Dynatrace LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/__init__.py | initialize | python | def initialize(sdkopts=(), sdklibname=None):
'''Attempts to initialize the SDK with the specified options.
Even if initialization fails, a dummy SDK will be available so that SDK
functions can be called but will do nothing.
If you call this function multiple times, you must call :func:`shutdown`
j... | Attempts to initialize the SDK with the specified options.
Even if initialization fails, a dummy SDK will be available so that SDK
functions can be called but will do nothing.
If you call this function multiple times, you must call :func:`shutdown`
just as many times. The options from all but the firs... | train | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/__init__.py#L172-L205 | [
"def _try_init_noref(sdkopts=(), sdklibname=None):\n global _should_shutdown #pylint:disable=global-statement\n\n sdk = nativeagent.try_get_sdk()\n if sdk:\n logger.debug(\n 'Attempt to re-initialize agent'\n ' with options=%s, libname=%s only increases'\n ' referenc... | # -*- coding: utf-8 -*-
#
# Copyright 2018 Dynatrace LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/__init__.py | shutdown | python | def shutdown():
'''Shut down the SDK.
:returns: An exception object if an error occurred, a falsy value otherwise.
:rtype: Exception
'''
global _sdk_ref_count #pylint:disable=global-statement
global _sdk_instance #pylint:disable=global-statement
global _should_shutdown #pylint:disable=glob... | Shut down the SDK.
:returns: An exception object if an error occurred, a falsy value otherwise.
:rtype: Exception | train | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/__init__.py#L266-L305 | [
"def try_get_sdk():\n return _sdk\n"
] | # -*- coding: utf-8 -*-
#
# Copyright 2018 Dynatrace LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/_impl/util.py | error_from_exc | python | def error_from_exc(nsdk, tracer_h, e_val=None, e_ty=None):
if not tracer_h:
return
if e_ty is None and e_val is None:
e_ty, e_val = sys.exc_info()[:2]
if e_ty is None and e_val is not None:
e_ty = type(e_val)
nsdk.tracer_error(tracer_h, getfullname(e_ty), str(e_val)) | Attach appropriate error information to tracer_h.
If e_val and e_ty are None, the current exception is used. | train | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/_impl/util.py#L28-L40 | [
"def getfullname(val):\n \"\"\"Get the module-qualified name of type or function val.\"\"\"\n return (val.__module__ or '<UNKNOWN_MODULE>') + '.' + getqualname(val)\n"
] | # Copyright 2018 Dynatrace LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
edx/edx-django-utils | edx_django_utils/monitoring/middleware.py | MonitoringCustomMetricsMiddleware.accumulate_metric | python | def accumulate_metric(cls, name, value):
metrics_cache = cls._get_metrics_cache()
metrics_cache.setdefault(name, 0)
metrics_cache.set(name, value) | Accumulate a custom metric (name and value) in the metrics cache. | train | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/monitoring/middleware.py#L57-L63 | [
"def _get_metrics_cache(cls):\n \"\"\"\n Get a reference to the part of the request cache wherein we store New\n Relic custom metrics related to the current request.\n \"\"\"\n return RequestCache(namespace=_REQUEST_CACHE_NAMESPACE)\n",
"def set(self, key, value):\n \"\"\"\n Caches the value ... | class MonitoringCustomMetricsMiddleware(object):
"""
The middleware class for adding custom metrics.
Make sure to add below the request cache in MIDDLEWARE_CLASSES.
"""
def __init__(self):
super(MonitoringCustomMetricsMiddleware, self).__init__()
# checks proper dependency order as... |
edx/edx-django-utils | edx_django_utils/monitoring/middleware.py | MonitoringCustomMetricsMiddleware._batch_report | python | def _batch_report(cls, request):
if not newrelic:
return
metrics_cache = cls._get_metrics_cache()
try:
newrelic.agent.add_custom_parameter('user_id', request.user.id)
except AttributeError:
pass
for key, value in metrics_cache.data.items():
... | Report the collected custom metrics to New Relic. | train | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/monitoring/middleware.py#L66-L78 | [
"def _get_metrics_cache(cls):\n \"\"\"\n Get a reference to the part of the request cache wherein we store New\n Relic custom metrics related to the current request.\n \"\"\"\n return RequestCache(namespace=_REQUEST_CACHE_NAMESPACE)\n"
] | class MonitoringCustomMetricsMiddleware(object):
"""
The middleware class for adding custom metrics.
Make sure to add below the request cache in MIDDLEWARE_CLASSES.
"""
def __init__(self):
super(MonitoringCustomMetricsMiddleware, self).__init__()
# checks proper dependency order as... |
edx/edx-django-utils | edx_django_utils/monitoring/middleware.py | MonitoringMemoryMiddleware.process_request | python | def process_request(self, request):
if self._is_enabled():
self._cache.set(self.guid_key, six.text_type(uuid4()))
log_prefix = self._log_prefix(u"Before", request)
self._cache.set(self.memory_data_key, self._memory_data(log_prefix)) | Store memory data to log later. | train | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/monitoring/middleware.py#L115-L122 | [
"def _is_enabled(self):\n \"\"\"\n Returns whether this middleware is enabled.\n \"\"\"\n return waffle.switch_is_active(u'edx_django_utils.monitoring.enable_memory_middleware')\n"
] | class MonitoringMemoryMiddleware(object):
"""
Middleware for monitoring memory usage.
Make sure to add below the request cache in MIDDLEWARE_CLASSES.
"""
memory_data_key = u'memory_data'
guid_key = u'guid_key'
def __init__(self):
super(MonitoringMemoryMiddleware, self).__init__()
... |
edx/edx-django-utils | edx_django_utils/monitoring/middleware.py | MonitoringMemoryMiddleware.process_response | python | def process_response(self, request, response):
if self._is_enabled():
log_prefix = self._log_prefix(u"After", request)
new_memory_data = self._memory_data(log_prefix)
log_prefix = self._log_prefix(u"Diff", request)
cached_memory_data_response = self._cache.get_ca... | Logs memory data after processing response. | train | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/monitoring/middleware.py#L124-L136 | [
"def _is_enabled(self):\n \"\"\"\n Returns whether this middleware is enabled.\n \"\"\"\n return waffle.switch_is_active(u'edx_django_utils.monitoring.enable_memory_middleware')\n"
] | class MonitoringMemoryMiddleware(object):
"""
Middleware for monitoring memory usage.
Make sure to add below the request cache in MIDDLEWARE_CLASSES.
"""
memory_data_key = u'memory_data'
guid_key = u'guid_key'
def __init__(self):
super(MonitoringMemoryMiddleware, self).__init__()
... |
edx/edx-django-utils | edx_django_utils/monitoring/middleware.py | MonitoringMemoryMiddleware._log_prefix | python | def _log_prefix(self, prefix, request):
# After a celery task runs, the request cache is cleared. So if celery
# tasks are running synchronously (CELERY_ALWAYS _EAGER), "guid_key"
# will no longer be in the request cache when process_response executes.
cached_guid_response = self._cache.... | Returns a formatted prefix for logging for the given request. | train | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/monitoring/middleware.py#L145-L154 | null | class MonitoringMemoryMiddleware(object):
"""
Middleware for monitoring memory usage.
Make sure to add below the request cache in MIDDLEWARE_CLASSES.
"""
memory_data_key = u'memory_data'
guid_key = u'guid_key'
def __init__(self):
super(MonitoringMemoryMiddleware, self).__init__()
... |
edx/edx-django-utils | edx_django_utils/monitoring/middleware.py | MonitoringMemoryMiddleware._memory_data | python | def _memory_data(self, log_prefix):
machine_data = psutil.virtual_memory()
process = psutil.Process()
process_data = {
'memory_info': process.get_memory_info(),
'ext_memory_info': process.get_ext_memory_info(),
'memory_percent': process.get_memory_percent(),
... | Returns a dict with information for current memory utilization.
Uses log_prefix in log statements. | train | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/monitoring/middleware.py#L156-L175 | null | class MonitoringMemoryMiddleware(object):
"""
Middleware for monitoring memory usage.
Make sure to add below the request cache in MIDDLEWARE_CLASSES.
"""
memory_data_key = u'memory_data'
guid_key = u'guid_key'
def __init__(self):
super(MonitoringMemoryMiddleware, self).__init__()
... |
edx/edx-django-utils | edx_django_utils/monitoring/middleware.py | MonitoringMemoryMiddleware._log_diff_memory_data | python | def _log_diff_memory_data(self, prefix, new_memory_data, old_memory_data):
def _vmem_used(memory_data):
return memory_data['machine_data'].used
def _process_mem_percent(memory_data):
return memory_data['process_data']['memory_percent']
def _process_rss(memory_data):
... | Computes and logs the difference in memory utilization
between the given old and new memory data. | train | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/monitoring/middleware.py#L177-L202 | null | class MonitoringMemoryMiddleware(object):
"""
Middleware for monitoring memory usage.
Make sure to add below the request cache in MIDDLEWARE_CLASSES.
"""
memory_data_key = u'memory_data'
guid_key = u'guid_key'
def __init__(self):
super(MonitoringMemoryMiddleware, self).__init__()
... |
edx/edx-django-utils | edx_django_utils/cache/utils.py | _RequestCache.data | python | def data(self, namespace):
assert namespace
if namespace in self._data:
return self._data[namespace]
new_data = {}
self._data[namespace] = new_data
return new_data | Gets the thread.local data (dict) for a given namespace.
Args:
namespace (string): The namespace, or key, of the data dict.
Returns:
(dict) | train | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/cache/utils.py#L33-L51 | null | class _RequestCache(threading.local):
"""
A thread-local for storing the per-request caches.
The data is a dict of dicts, keyed by namespace.
"""
def __init__(self):
super(_RequestCache, self).__init__()
self._data = {}
def clear(self):
"""
Clears all data for a... |
edx/edx-django-utils | edx_django_utils/cache/utils.py | RequestCache.get_cached_response | python | def get_cached_response(self, key):
cached_value = self.data.get(key, _CACHE_MISS)
is_found = cached_value is not _CACHE_MISS
return CachedResponse(is_found, key, cached_value) | Retrieves a CachedResponse for the provided key.
Args:
key (string)
Returns:
A CachedResponse with is_found status and value. | train | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/cache/utils.py#L94-L107 | null | class RequestCache(object):
"""
A namespaced request cache for caching per-request data.
"""
def __init__(self, namespace=None):
"""
Creates a request cache with the provided namespace.
Args:
namespace (string): (optional) uses 'default' if not provided.
"""... |
edx/edx-django-utils | edx_django_utils/cache/utils.py | TieredCache.get_cached_response | python | def get_cached_response(cls, key):
request_cached_response = DEFAULT_REQUEST_CACHE.get_cached_response(key)
if not request_cached_response.is_found:
django_cached_response = cls._get_cached_response_from_django_cache(key)
cls._set_request_cache_if_django_cache_hit(key, django_cac... | Retrieves a CachedResponse for the provided key.
Args:
key (string)
Returns:
A CachedResponse with is_found status and value. | train | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/cache/utils.py#L152-L169 | [
"def get_cached_response(self, key):\n \"\"\"\n Retrieves a CachedResponse for the provided key.\n\n Args:\n key (string)\n\n Returns:\n A CachedResponse with is_found status and value.\n\n \"\"\"\n cached_value = self.data.get(key, _CACHE_MISS)\n is_found = cached_value is not _C... | class TieredCache(object):
"""
A two tiered caching object with a request cache backed by a django cache.
"""
@classmethod
@staticmethod
def set_all_tiers(key, value, django_cache_timeout=DEFAULT_TIMEOUT):
"""
Caches the value for the provided key in both the request cache and... |
edx/edx-django-utils | edx_django_utils/cache/utils.py | TieredCache.set_all_tiers | python | def set_all_tiers(key, value, django_cache_timeout=DEFAULT_TIMEOUT):
DEFAULT_REQUEST_CACHE.set(key, value)
django_cache.set(key, value, django_cache_timeout) | Caches the value for the provided key in both the request cache and the
django cache.
Args:
key (string)
value (object)
django_cache_timeout (int): (Optional) Timeout used to determine
if and for how long to cache in the django cache. A timeout of
... | train | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/cache/utils.py#L172-L187 | [
"def set(self, key, value):\n \"\"\"\n Caches the value for the provided key.\n\n Args:\n key (string)\n value (object)\n\n \"\"\"\n self.data[key] = value\n"
] | class TieredCache(object):
"""
A two tiered caching object with a request cache backed by a django cache.
"""
@classmethod
def get_cached_response(cls, key):
"""
Retrieves a CachedResponse for the provided key.
Args:
key (string)
Returns:
A ... |
edx/edx-django-utils | edx_django_utils/cache/utils.py | TieredCache._get_cached_response_from_django_cache | python | def _get_cached_response_from_django_cache(key):
if TieredCache._should_force_django_cache_miss():
return CachedResponse(is_found=False, key=key, value=None)
cached_value = django_cache.get(key, _CACHE_MISS)
is_found = cached_value is not _CACHE_MISS
return CachedResponse(is... | Retrieves a CachedResponse for the given key from the django cache.
If the request was set to force cache misses, then this will always
return a cache miss response.
Args:
key (string)
Returns:
A CachedResponse with is_found status and value. | train | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/cache/utils.py#L218-L237 | null | class TieredCache(object):
"""
A two tiered caching object with a request cache backed by a django cache.
"""
@classmethod
def get_cached_response(cls, key):
"""
Retrieves a CachedResponse for the provided key.
Args:
key (string)
Returns:
A ... |
edx/edx-django-utils | edx_django_utils/cache/utils.py | TieredCache._set_request_cache_if_django_cache_hit | python | def _set_request_cache_if_django_cache_hit(key, django_cached_response):
if django_cached_response.is_found:
DEFAULT_REQUEST_CACHE.set(key, django_cached_response.value) | Sets the value in the request cache if the django cached response was a hit.
Args:
key (string)
django_cached_response (CachedResponse) | train | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/cache/utils.py#L240-L250 | null | class TieredCache(object):
"""
A two tiered caching object with a request cache backed by a django cache.
"""
@classmethod
def get_cached_response(cls, key):
"""
Retrieves a CachedResponse for the provided key.
Args:
key (string)
Returns:
A ... |
edx/edx-django-utils | edx_django_utils/cache/utils.py | TieredCache._get_and_set_force_cache_miss | python | def _get_and_set_force_cache_miss(request):
if not (request.user and request.user.is_active and request.user.is_staff):
force_cache_miss = False
else:
force_cache_miss = request.GET.get(FORCE_CACHE_MISS_PARAM, 'false').lower() == 'true'
DEFAULT_REQUEST_CACHE.set(SHOULD_FO... | Gets value for request query parameter FORCE_CACHE_MISS
and sets it in the default request cache.
This functionality is only available for staff.
Example:
http://clobert.com/api/v1/resource?force_cache_miss=true | train | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/cache/utils.py#L253-L268 | [
"def set(self, key, value):\n \"\"\"\n Caches the value for the provided key.\n\n Args:\n key (string)\n value (object)\n\n \"\"\"\n self.data[key] = value\n"
] | class TieredCache(object):
"""
A two tiered caching object with a request cache backed by a django cache.
"""
@classmethod
def get_cached_response(cls, key):
"""
Retrieves a CachedResponse for the provided key.
Args:
key (string)
Returns:
A ... |
edx/edx-django-utils | edx_django_utils/cache/utils.py | TieredCache._should_force_django_cache_miss | python | def _should_force_django_cache_miss(cls):
cached_response = DEFAULT_REQUEST_CACHE.get_cached_response(SHOULD_FORCE_CACHE_MISS_KEY)
return False if not cached_response.is_found else cached_response.value | Returns True if the tiered cache should force a cache miss for the
django cache, and False otherwise. | train | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/cache/utils.py#L271-L278 | null | class TieredCache(object):
"""
A two tiered caching object with a request cache backed by a django cache.
"""
@classmethod
def get_cached_response(cls, key):
"""
Retrieves a CachedResponse for the provided key.
Args:
key (string)
Returns:
A ... |
edx/edx-django-utils | edx_django_utils/private_utils.py | _check_middleware_dependencies | python | def _check_middleware_dependencies(concerned_object, required_middleware):
declared_middleware = getattr(settings, 'MIDDLEWARE', None)
if declared_middleware is None:
declared_middleware = settings.MIDDLEWARE_CLASSES # Django 1.8 support
# Filter out all the middleware except the ones we care abou... | Check required middleware dependencies exist and in the correct order.
Args:
concerned_object (object): The object for which the required
middleware is being checked. This is used for error messages only.
required_middleware (list of String): An ordered list representing the
... | train | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/private_utils.py#L12-L48 | null | """
Private utility methods.
These utilities are designated for internal use only (i.e. inside
edx-django-utils). In some cases, these utilities could be elevated to public
methods once they get some burn-in time and find a more permanent home in the
library.
"""
from django.conf import settings
|
edx/edx-django-utils | edx_django_utils/monitoring/utils.py | set_custom_metrics_for_course_key | python | def set_custom_metrics_for_course_key(course_key):
if not newrelic:
return
newrelic.agent.add_custom_parameter('course_id', six.text_type(course_key))
newrelic.agent.add_custom_parameter('org', six.text_type(course_key.org)) | Set monitoring custom metrics related to a course key.
This is not cached, and only support reporting to New Relic Insights. | train | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/monitoring/utils.py#L65-L75 | null | """
This is an interface to the monitoring_utils middleware. Functions
defined in this module can be used to report monitoring custom metrics.
Usage:
from edx_django_utils import monitoring as monitoring_utils
...
monitoring_utils.accumulate('xb_user_state.get_many.num_items', 4)
There is no need to do ... |
edx/edx-django-utils | edx_django_utils/monitoring/utils.py | set_monitoring_transaction_name | python | def set_monitoring_transaction_name(name, group=None, priority=None):
if not newrelic:
return
newrelic.agent.set_transaction_name(name, group, priority) | Sets the transaction name for monitoring.
This is not cached, and only support reporting to New Relic. | train | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/monitoring/utils.py#L90-L99 | null | """
This is an interface to the monitoring_utils middleware. Functions
defined in this module can be used to report monitoring custom metrics.
Usage:
from edx_django_utils import monitoring as monitoring_utils
...
monitoring_utils.accumulate('xb_user_state.get_many.num_items', 4)
There is no need to do ... |
edx/edx-django-utils | edx_django_utils/monitoring/utils.py | function_trace | python | def function_trace(function_name):
if newrelic:
nr_transaction = newrelic.agent.current_transaction()
with newrelic.agent.FunctionTrace(nr_transaction, function_name):
yield
else:
yield | Wraps a chunk of code that we want to appear as a separate, explicit,
segment in our monitoring tools. | train | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/monitoring/utils.py#L103-L113 | null | """
This is an interface to the monitoring_utils middleware. Functions
defined in this module can be used to report monitoring custom metrics.
Usage:
from edx_django_utils import monitoring as monitoring_utils
...
monitoring_utils.accumulate('xb_user_state.get_many.num_items', 4)
There is no need to do ... |
django-cumulus/django-cumulus | cumulus/management/commands/syncfiles.py | Command.set_options | python | def set_options(self, options):
# COMMAND LINE OPTIONS
self.wipe = options.get("wipe")
self.test_run = options.get("test_run")
self.quiet = options.get("test_run")
self.container_name = options.get("container")
self.verbosity = int(options.get("verbosity"))
self.s... | Sets instance variables based on an options dict | train | https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/management/commands/syncfiles.py#L45-L97 | null | class Command(BaseCommand):
help = "Synchronizes project static *or* media files to cloud files."
def add_arguments(self, parser):
parser.add_argument("-i", "--include", action="append", default=[],
dest="includes", metavar="PATTERN",
help="Incl... |
django-cumulus/django-cumulus | cumulus/management/commands/syncfiles.py | Command.match_cloud | python | def match_cloud(self, includes, excludes):
cloud_objs = [cloud_obj.name for cloud_obj in self.container.get_objects()]
includes_pattern = r"|".join([fnmatch.translate(x) for x in includes])
excludes_pattern = r"|".join([fnmatch.translate(x) for x in excludes]) or r"$."
excludes = [o for ... | Returns the cloud objects that match the include and exclude patterns. | train | https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/management/commands/syncfiles.py#L143-L152 | null | class Command(BaseCommand):
help = "Synchronizes project static *or* media files to cloud files."
def add_arguments(self, parser):
parser.add_argument("-i", "--include", action="append", default=[],
dest="includes", metavar="PATTERN",
help="Incl... |
django-cumulus/django-cumulus | cumulus/management/commands/syncfiles.py | Command.match_local | python | def match_local(self, prefix, includes, excludes):
includes_pattern = r"|".join([fnmatch.translate(x) for x in includes])
excludes_pattern = r"|".join([fnmatch.translate(x) for x in excludes]) or r"$."
matches = []
for root, dirs, files in os.walk(prefix, topdown=True):
# exc... | Filters os.walk() with include and exclude patterns.
See: http://stackoverflow.com/a/5141829/93559 | train | https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/management/commands/syncfiles.py#L154-L175 | null | class Command(BaseCommand):
help = "Synchronizes project static *or* media files to cloud files."
def add_arguments(self, parser):
parser.add_argument("-i", "--include", action="append", default=[],
dest="includes", metavar="PATTERN",
help="Incl... |
django-cumulus/django-cumulus | cumulus/management/commands/syncfiles.py | Command.upload_files | python | def upload_files(self, abspaths, relpaths, remote_objects):
for relpath in relpaths:
abspath = [p for p in abspaths if p[len(self.file_root):] == relpath][0]
cloud_datetime = remote_objects[relpath] if relpath in remote_objects else None
local_datetime = datetime.datetime.utc... | Determines files to be uploaded and call ``upload_file`` on each. | train | https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/management/commands/syncfiles.py#L177-L195 | null | class Command(BaseCommand):
help = "Synchronizes project static *or* media files to cloud files."
def add_arguments(self, parser):
parser.add_argument("-i", "--include", action="append", default=[],
dest="includes", metavar="PATTERN",
help="Incl... |
django-cumulus/django-cumulus | cumulus/management/commands/syncfiles.py | Command.upload_file | python | def upload_file(self, abspath, cloud_filename):
if not self.test_run:
content = open(abspath, "rb")
content_type = get_content_type(cloud_filename, content)
headers = get_headers(cloud_filename, content_type)
if headers.get("Content-Encoding") == "gzip":
... | Uploads a file to the container. | train | https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/management/commands/syncfiles.py#L197-L224 | [
"def get_content_type(name, content):\n \"\"\"\n Checks if the content_type is already set.\n Otherwise uses the mimetypes library to guess.\n \"\"\"\n if hasattr(content, \"content_type\"):\n content_type = content.content_type\n else:\n mime_type, encoding = mimetypes.guess_type(na... | class Command(BaseCommand):
help = "Synchronizes project static *or* media files to cloud files."
def add_arguments(self, parser):
parser.add_argument("-i", "--include", action="append", default=[],
dest="includes", metavar="PATTERN",
help="Incl... |
django-cumulus/django-cumulus | cumulus/management/commands/syncfiles.py | Command.delete_extra_files | python | def delete_extra_files(self, relpaths, cloud_objs):
for cloud_obj in cloud_objs:
if cloud_obj not in relpaths:
if not self.test_run:
self.delete_cloud_obj(cloud_obj)
self.delete_count += 1
if not self.quiet or self.verbosity > 1:
... | Deletes any objects from the container that do not exist locally. | train | https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/management/commands/syncfiles.py#L226-L236 | null | class Command(BaseCommand):
help = "Synchronizes project static *or* media files to cloud files."
def add_arguments(self, parser):
parser.add_argument("-i", "--include", action="append", default=[],
dest="includes", metavar="PATTERN",
help="Incl... |
django-cumulus/django-cumulus | cumulus/management/commands/syncfiles.py | Command.delete_cloud_obj | python | def delete_cloud_obj(self, cloud_obj):
self._connection.delete_object(
container=self.container_name,
obj=cloud_obj,
) | Deletes an object from the container. | train | https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/management/commands/syncfiles.py#L238-L245 | null | class Command(BaseCommand):
help = "Synchronizes project static *or* media files to cloud files."
def add_arguments(self, parser):
parser.add_argument("-i", "--include", action="append", default=[],
dest="includes", metavar="PATTERN",
help="Incl... |
django-cumulus/django-cumulus | cumulus/management/commands/syncfiles.py | Command.wipe_container | python | def wipe_container(self):
if self.test_run:
print("Wipe would delete {0} objects.".format(len(self.container.object_count)))
else:
if not self.quiet or self.verbosity > 1:
print("Deleting {0} objects...".format(len(self.container.object_count)))
self._... | Completely wipes out the contents of the container. | train | https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/management/commands/syncfiles.py#L247-L256 | null | class Command(BaseCommand):
help = "Synchronizes project static *or* media files to cloud files."
def add_arguments(self, parser):
parser.add_argument("-i", "--include", action="append", default=[],
dest="includes", metavar="PATTERN",
help="Incl... |
django-cumulus/django-cumulus | cumulus/management/commands/syncfiles.py | Command.print_tally | python | def print_tally(self):
self.update_count = self.upload_count - self.create_count
if self.test_run:
print("Test run complete with the following results:")
print("Skipped {0}. Created {1}. Updated {2}. Deleted {3}.".format(
self.skip_count, self.create_count, self.update_co... | Prints the final tally to stdout. | train | https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/management/commands/syncfiles.py#L258-L266 | null | class Command(BaseCommand):
help = "Synchronizes project static *or* media files to cloud files."
def add_arguments(self, parser):
parser.add_argument("-i", "--include", action="append", default=[],
dest="includes", metavar="PATTERN",
help="Incl... |
django-cumulus/django-cumulus | cumulus/management/commands/container_list.py | Command.handle | python | def handle(self, *args, **options):
self._connection = Auth()._get_connection()
if len(args) == 0:
containers = self._connection.list_containers()
if not containers:
print("No containers were found for this account.")
elif len(args) == 1:
cont... | Lists all the items in a container to stdout. | train | https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/management/commands/container_list.py#L13-L31 | [
"def _get_connection(self):\n if not hasattr(self, \"_connection\"):\n if self.use_pyrax:\n public = not self.use_snet # invert\n self._connection = pyrax.connect_to_cloudfiles(public=public)\n elif swiftclient:\n self._connection = swiftclient.Connection(\n ... | class Command(BaseCommand):
help = ("List all the items in a container to stdout.\n\n"
"We recommend you run it like this:\n"
" ./manage.py container_list <container> | pv --line-mode > <container>.list\n\n"
"pv is Pipe Viewer: http://www.ivarch.com/programs/pv.shtml")
arg... |
django-cumulus/django-cumulus | cumulus/management/commands/collectstatic.py | Command.delete_file | python | def delete_file(self, path, prefixed_path, source_storage):
if isinstance(self.storage, CumulusStorage):
if self.storage.exists(prefixed_path):
try:
etag = self.storage._get_object(prefixed_path).etag
digest = "{0}".format(hashlib.md5(source_st... | Checks if the target file should be deleted if it already exists | train | https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/management/commands/collectstatic.py#L10-L24 | null | class Command(collectstatic.Command):
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.