docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Download file process:
- Open the url
- Check if it has been downloaded and it hanged.
- Download it to the destination folder.
Args:
:urls: url to take the file.
:destionation: place to store the downloaded file. | def download_file(url, destination, **kwargs):
web_file = open_remote_url(url, **kwargs)
file_size = 0
if not web_file:
logger.error(
"Remote file not found. Attempted URLs: {}".format(url))
return
modified = is_remote_file_modified(web_file, destination)
if modifi... | 1,020,871 |
Open the url and check that it stores a file.
Args:
:urls: Endpoint to take the file | def open_remote_url(urls, **kwargs):
if isinstance(urls, str):
urls = [urls]
for url in urls:
try:
web_file = requests.get(url, stream=True, **kwargs)
if 'html' in web_file.headers['content-type']:
raise ValueError("HTML source file retrieved.")
... | 1,020,872 |
Check if online file has been modified.
Args:
:web_file: online file to check.
:destination: path of the offline file to compare. | def is_remote_file_modified(web_file, destination):
try:
# check datetime of last modified in file.
last_mod = web_file.headers.get('last-modified')
if last_mod:
web_file_time = time.strptime(
web_file.headers.get(
'last-modified'), '%a, %... | 1,020,873 |
Check if exist the destination path, and copy the online resource
file to local.
Args:
:web_file: reference to online file resource to take.
:destination: path to store the file. | def copy_remote_file(web_file, destination):
size = 0
dir_name = os.path.dirname(destination)
if not os.path.exists(dir_name):
os.makedirs(dir_name)
with open(destination, 'wb') as file_:
chunk_size = 8 * 1024
for chunk in web_file.iter_content(chunk_size=chunk_size):
... | 1,020,874 |
Fetch a number of samples from self.wave_cache
Args:
sample_count (int): Number of samples to fetch
Returns: ndarray | def get_samples(self, sample_count):
if self.amplitude.value <= 0:
return None
# Build samples by rolling the period cache through the buffer
rolled_array = numpy.roll(self.wave_cache,
-1 * self.last_played_sample)
# Append remaining... | 1,020,906 |
Optionally set all attributes.
Args:
path (str): Relative file path.
line (int): Line number.
msg (str): Explanation of what is wrong.
col (int): Column where the problem begins. | def __init__(self, linter_name, path, msg, line_nr=None, col=None):
# Set all attributes in the constructor for convenience.
# pylint: disable=too-many-arguments
if line_nr:
line_nr = int(line_nr)
if col:
col = int(col)
self._linter_name = linter_... | 1,020,921 |
Match pattern line by line and return Results.
Use ``_create_output_from_match`` to convert pattern match groups to
Result instances.
Args:
lines (iterable): Output lines to be parsed.
pattern: Compiled pattern to match against lines.
result_fn (function): R... | def _parse_by_pattern(self, lines, pattern):
for line in lines:
match = pattern.match(line)
if match:
params = match.groupdict()
if not params:
params = match.groups()
yield self._create_output_from_match(params... | 1,020,927 |
Create Result instance from pattern match results.
Args:
match: Pattern match. | def _create_output_from_match(self, match_result):
if isinstance(match_result, dict):
return LinterOutput(self.name, **match_result)
return LinterOutput(self.name, *match_result) | 1,020,928 |
Merges two refs
Args:
ref_name: ref to merge in the current one | def merge(self, ref_name: str):
if self.is_dirty():
LOGGER.error('repository is dirty; cannot merge: %s', ref_name)
sys.exit(-1)
LOGGER.info('merging ref: "%s" into branch: %s', ref_name, self.get_current_branch())
self.repo.git.merge(ref_name) | 1,021,108 |
Creates a new branch
Args:
branch_name: name of the branch | def create_branch(self, branch_name: str):
LOGGER.info('creating branch: %s', branch_name)
self._validate_branch_name(branch_name)
if branch_name in self.list_branches():
LOGGER.error('branch already exists')
sys.exit(-1)
new_branch = self.repo.create_hea... | 1,021,115 |
Creates a new branch if it doesn't exist
Args:
branch_name: branch name | def create_branch_and_checkout(self, branch_name: str):
self.create_branch(branch_name)
self.checkout(branch_name) | 1,021,116 |
Writes the requirement files
Args:
amend: amend last commit with changes
stage: stage changes | def _write_reqs(amend: bool = False, stage: bool = False):
LOGGER.info('writing requirements')
base_cmd = 'pipenv lock -r'
_write_reqs_file(f'{base_cmd}', 'requirements.txt')
_write_reqs_file(f'{base_cmd} -d', 'requirements-dev.txt')
files_to_add = ['Pipfile', 'requirements.txt', 'requirements... | 1,021,227 |
Write requirements files
Args:
amend: amend last commit with changes
stage: stage changes | def reqs(amend: bool = False, stage: bool = False):
changed_files = CTX.repo.changed_files()
if 'requirements.txt' in changed_files or 'requirements-dev.txt' in changed_files:
LOGGER.error('Requirements have changed; cannot update them')
sys.exit(-1)
_write_reqs(amend, stage) | 1,021,228 |
This takes a list of filenames and their paths of expected yaml files and
tried to parse them, erroring if there are any parsing issues.
Args:
file_contents (str): Contents of a yml file
Raises:
yaml.parser.ParserError: Raises an error if the file contents cannot be
... | def parse(file_contents, file_name):
try:
yaml.load(file_contents)
except Exception:
_, exc_value, _ = sys.exc_info()
return("Cannot Parse: {file_name}: \n {exc_value}"
.format(file_name=file_name, exc_value=exc_value)) | 1,021,556 |
Execute a python code object in the given environment.
Args:
globals_map: Dictionary to use as the globals context.
Returns:
locals_map: Dictionary of locals from the environment after execution. | def exec_function(ast, globals_map):
locals_map = globals_map
exec ast in globals_map, locals_map
return locals_map | 1,021,742 |
Entry point to parsing a BUILD file.
Args:
**global_args: Variables to include in the parsing environment. | def parse(self, **global_args):
if self.build_file not in ParseContext._parsed:
# http://en.wikipedia.org/wiki/Abstract_syntax_tree
# http://martinfowler.com/books/dsl.html
butcher_context = {}
for str_to_exec in self._strs_to_exec:
ast =... | 1,021,744 |
Turn csv into dict.
Args:
:csv_filepath: path to csv file to turn into dict.
:limits: path to csv file to turn into dict | def csv_to_dict(csv_filepath, **kwargs):
callbacks = {'to_list': csv_tolist,
'row_csv_limiter': row_csv_limiter,
'csv_row_cleaner': csv_row_cleaner,
'row_headers_count': row_headers_count,
'get_col_header': get_csv_col_headers,
... | 1,021,877 |
Turn excel into dict.
Args:
:excel_filepath: path to excel file to turn into dict.
:limits: path to csv file to turn into dict | def excel_to_dict(excel_filepath, encapsulate_filepath=False, **kwargs):
result = {}
try:
callbacks = {'to_dictlist': excel_todictlist} # Default callback
callbacks.update(kwargs.get('alt_callbacks', {}))
# Retrieve excel data as dict of sheets lists
excel_data = callbacks... | 1,021,878 |
Creates a filename with md5 cache string based on settings list
Args:
filename (str): the filename without extention
extention (str): the file extention without dot. (i.e. 'pkl')
settings_list (dict|list): the settings list as list (optional)
NB! The dictiona... | def get_cached_filename(self, filename, extention, settings_list=None):
cached_name = "_".join([filename, self.get_hash()])
return ".".join([cached_name, extention]) | 1,021,992 |
Fetches the table and applies all post processors.
Args:
rebuild (bool): Rebuild the table and ignore cache. Default: False
cache (bool): Cache the finished table for faster future loading.
Default: True | def fetch(self, rebuild=False, cache=True):
if rebuild:
return self._process_table(cache)
try:
return self.read_cache()
except FileNotFoundError:
return self._process_table(cache) | 1,021,995 |
Required by flake8
add the possible options, called first
Args:
parser (OptionsManager): | def add_options(cls, parser):
kwargs = {'action': 'store', 'default': '', 'parse_from_config': True,
'comma_separated_list': True}
for num in range(cls.min_check, cls.max_check):
parser.add_option(None, "--filename_check{}".format(num), **kwargs) | 1,022,004 |
Required by flake8
parse the options, called after add_options
Args:
options (dict): options to be parsed | def parse_options(cls, options):
d = {}
for filename_check, dictionary in cls.filename_checks.items():
# retrieve the marks from the passed options
filename_data = getattr(options, filename_check)
if len(filename_data) != 0:
parsed_params = {}... | 1,022,005 |
Construct Retsly client
Args:
token (string): access token
vendor (string): vendor ID | def __init__(self, token, vendor='test'):
self.token = token
self.vendor = vendor | 1,022,007 |
Amends last commit
Args:
append_to_msg: string to append to previous message
new_message: new commit message
files_to_add: optional list of files to commit | def amend_commit(
self,
append_to_msg: typing.Optional[str] = None,
new_message: typing.Optional[str] = None,
files_to_add: typing.Optional[typing.Union[typing.List[str], str]] = None,
):
| 1,022,117 |
Sets environment variable on AV
Args:
key: variable name
value: variable value | def set_env_var(key: str, value: str):
elib_run.run(f'appveyor SetVariable -Name {key} -Value {value}')
AV.info('Env', f'set "{key}" -> "{value}"') | 1,022,144 |
Parse a JSON BUILD file.
Args:
builddata: dictionary of buildfile data
reponame: name of the repo that it came from
path: directory path within the repo | def _parse(self, stream):
builddata = json.load(stream)
log.debug('This is a JSON build file.')
if 'targets' not in builddata:
log.warn('Warning: No targets defined here.')
return
for tdata in builddata['targets']:
# TODO: validate name
... | 1,022,159 |
Runs all linters
Args:
ctx: click context
amend: whether or not to commit results
stage: whether or not to stage changes | def lint(ctx: click.Context, amend: bool = False, stage: bool = False):
_lint(ctx, amend, stage) | 1,022,290 |
Build xml documents from a list of document ids.
Args:
doc_ids -- A document id or a lost of those. | def set_doc_ids(self, doc_ids):
if isinstance(doc_ids, list):
self.set_documents(dict.fromkeys(doc_ids))
else:
self.set_documents({doc_ids: None}) | 1,022,318 |
Set properies of atributes stored in content using stored common fdel and fget and given fset.
Args:
set_property -- Function that sets given property.
name -- Name of the atribute this property must simulate. Used as key in content dict by default.
starting_... | def add_property(self, set_property, name, starting_value, tag_name=None):
def del_property(self, tag_name):
try:
del self._content[tag_name]
except KeyError:
pass
def get_property(self, tag_name):
try:
return ... | 1,022,319 |
Convert a dict form of query in a string of needed and store the query string.
Args:
value -- A query string or a dict with query xpaths as keys and text or
nested query dicts as values. | def set_query(self, value):
if isinstance(value, basestring) or value is None:
self._content['query'] = value
elif hasattr(value, 'keys'):
self._content['query'] = query.terms_from_dict(value)
else:
raise TypeError("Query must be a string or dict. Got... | 1,022,321 |
r"""Displays help for the given route.
Args:
route (str): A route that resolves a member. | def help(route):
r
help_text = getRouteHelp(route.split('/') if route else [])
if help_text is None:
err('Can\'t help :(')
else:
print '\n%s' % help_text | 1,022,396 |
r"""Calls a task, as if it were called from the command line.
Args:
command (str): A route followed by params (as if it were entered in the shell).
collect_missing (bool): Collects any missing argument for the command through the shell. Defaults to False.
Returns:
The return value of the called comman... | def call(command, collect_missing=False, silent=True):
r
return (_execCommand if silent else execCommand)(shlex.split(command), collect_missing) | 1,022,451 |
r"""Adds members to an existing group.
Args:
TargetGroup (Group): The target group for the addition.
NewMember (Group / Task): The member to be added.
Config (dict): The config for the member.
Args (OrderedDict): ArgConfig for the NewMember, if it's a task (optional). | def add(TargetGroup, NewMember, Config=None, Args=None):
r
Member = Task(NewMember, Args or {}, Config or {}) if isfunction(NewMember) else Group(NewMember, Config or {})
ParentMembers = TargetGroup.__ec_member__.Members
ParentMembers[Member.Config['name']] = Member
alias = Member.Config.get('alias')
if ... | 1,022,452 |
Run the python pep8 tool against the filst of supplied files.
Append any linting errors to the returned status list
Args:
files (str): list of files to run pep8 against
status (list): list of pre-receive check failures to eventually print
to the user
Returns:
... | def do_check_pep8(files, status):
for file_name in files:
args = ['flake8', '--max-line-length=120', '{0}'.format(file_name)]
output = run(*args)
if output:
status.append("Python PEP8/Flake8: {0}: {1}".format(file_name,
... | 1,022,455 |
Generic do_check helper method
Args:
func (function): Specific function to call
files (list): list of files to run against
status (list): list of pre-receive check failures to eventually print
to the user
Returns:
status list of current pre-redeive check f... | def do_check(func, files, status):
for file_name in files:
with open(file_name, 'r') as f:
output = func.parse(f.read(), file_name)
if output:
status.append("{0}: {1}".format(file_name, output))
return status | 1,022,456 |
Return singleton instance.
Args:
cls (type): the class.
args (tuple/list): initializer function arguments.
kwargs (dict): initializer function keyword arguments. | def __call__(cls, *args, **kwargs):
if cls.instance is None:
with threading.Lock():
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls.instance | 1,022,486 |
Given a dict and path '/' or '.' separated. Digs into de dict to retrieve
the specified element.
Args:
source (dict): set of nested objects in which the data will be searched
path (string): '/' or '.' string with attribute names | def get_element(source, path, separator=r'[/.]'):
return _get_element_by_names(source, re.split(separator, path)) | 1,022,518 |
Given a dict and path '/' or '.' separated. Digs into de dict to retrieve
the specified element.
Args:
source (dict): set of nested objects in which the data will be searched
path (list): list of attribute names | def _get_element_by_names(source, names):
if source is None:
return source
else:
if names:
head, *rest = names
if isinstance(source, dict) and head in source:
return _get_element_by_names(source[head], rest)
elif isinstance(source, list)... | 1,022,519 |
Format dict to string passing a list of keys as order
Args:
lista: List with elements to clean duplicates. | def format_dict(dic, format_list, separator=',', default_value=str):
dic = collections.defaultdict(default_value, dic)
str_format = separator.join(["{" + "{}".format(head) + "}" for head in format_list])
return str_format.format(**dic) | 1,022,522 |
Remove duplicated elements in a list.
Args:
lista: List with elements to clean duplicates. | def remove_list_duplicates(lista, unique=False):
result = []
allready = []
for elem in lista:
if elem not in result:
result.append(elem)
else:
allready.append(elem)
if unique:
for elem in allready:
result = list(filter((elem).__ne__, res... | 1,022,530 |
Build a neural net with the indicated input, hidden, and outout dimensions
Arguments:
params (dict or PyBrainParams namedtuple):
default: {'N_hidden': 6}
(this is the only parameter that affects the NN build)
Returns:
FeedForwardNetwork with N_input + N_hidden + N_output nodes in... | def build_ann(N_input=None, N_hidden=2, N_output=1, hidden_layer_type='Linear', verbosity=1):
N_input = N_input or 1
N_output = N_output or 1
N_hidden = N_hidden or tuple()
if isinstance(N_hidden, (int, float, basestring)):
N_hidden = (int(N_hidden),)
hidden_layer_type = hidden_layer_t... | 1,022,597 |
Prepend weather the values specified (e.g. Max TempF) to the samples[0..N]['input'] vectors
samples[0..N]['target'] should have an index with the date timestamp
If you use_cache for the curent year, you may not get the most recent data.
Arguments:
samples (list of dict): {'input': np.array(), 'ta... | def prepend_dataset_with_weather(samples, location='Fresno, CA', weather_columns=None, use_cache=True, verbosity=0):
if verbosity > 1:
print('Prepending weather data for {} to dataset samples'.format(weather_columns))
if not weather_columns:
return samples
timestamps = pd.DatetimeIndex(... | 1,022,599 |
Python 2.4 compatible memoize decorator.
It creates a cache that has a maximum size. If the cache exceeds the max,
it is thrown out and a new one made. With such behavior, it is wise to set
the cache just a little larger that the maximum expected need.
Parameters:
max_cache_size - the size to w... | def _memoizeArgsOnly (max_cache_size=1000):
def wrapper (f):
def fn (*args):
try:
return fn.cache[args]
except KeyError:
if fn.count >= max_cache_size:
fn.cache = {}
fn.count = 0
fn.cache[arg... | 1,022,674 |
turn a string representing a version into a normalized version list.
Version lists are directly comparable using standard operators such as
>, <, ==, etc.
Parameters:
version_string - such as '3.5' or '3.6.3plugin3'
max_version_parts - version strings are comprised of a series of 4 tuples.
... | def normalize(version_string, max_version_parts=4):
version_list = []
for part_count, version_part in enumerate(version_string.split('.')):
try:
groups = _version_part_re.match(version_part).groups()
except Exception, x:
raise NotAVersionException(version_string)
... | 1,022,675 |
Parse the values from a given environment against a given config schema
Args:
config_schema: A dict which maps the variable name to a Schema object
that describes the requested value.
env: A dict which represents the value of each variable in the
environment. | def parse_env(config_schema, env):
try:
return {
key: item_schema.parse(key, env.get(key))
for key, item_schema in config_schema.items()
}
except KeyError as error:
raise MissingConfigError(
"Required config not set: {}".format(error.args[0])
... | 1,022,848 |
Parse the environment value for a given key against the schema.
Args:
key: The name of the environment variable.
value: The value to be parsed. | def parse(self, key, value):
if value is not None:
try:
return self._parser(value)
except Exception:
raise ParsingError("Error parsing {}".format(key))
elif self._default is not SENTINAL:
return self._default
else:
... | 1,022,850 |
Reads one or more text files and returns them joined together.
A title is automatically created based on the file name.
Args:
*file_paths: list of files to aggregate
Returns: content of files | def read_local_files(*file_paths: str) -> str:
def _read_single_file(file_path):
with open(file_path) as f:
filename = os.path.splitext(file_path)[0]
title = f'{filename}\n{"=" * len(filename)}'
return '\n\n'.join((title, f.read()))
return '\n' + '\n\n'.join(ma... | 1,023,498 |
makes some plots
creates binned histograms of the results of each module
(ie count of results in ranges [(0,40), (40, 50), (50,60), (60, 70), (70, 80), (80, 90), (90, 100)])
Arguments:
path {str} -- path to save plots to
show {boolean} -- whether to show plots using python
goodFor... | def plotter(path, show, goodFormat):
for module in goodFormat.items(): # for each module
bins = [0, 40, 50, 60, 70, 80, 90, 100]
# cut the data into bins
out = pd.cut(module[1], bins=bins, include_lowest=True)
ax = out.value_counts().plot.bar(rot=0, color="b", figsize=(10, 6),... | 1,023,627 |
returns final result of candidateNumber in year
Arguments:
year {int} -- the year candidateNumber is in
candidateNumber {str} -- the candidateNumber of candidateNumber
badFormat {dict} -- candNumber : [results for candidate]
length {int} -- length of each row in badFormat divided by... | def myGrades(year, candidateNumber, badFormat, length):
weights1 = [1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5]
weights2 = [1, 1, 1, 1, 1, 1, 0.5, 0.5]
if year == 1:
myFinalResult = sum([int(badFormat[candidateNumber][2*(i + 1)])
* weights1[i] for i in range(length-1)]) / 6
... | 1,023,628 |
rank of candidateNumber in year
Arguments:
grade {int} -- a weighted average for a specific candidate number and year
badFormat {dict} -- candNumber : [results for candidate]
year {int} -- year you are in
length {int} -- length of each row in badFormat divided by 2
Returns:
... | def myRank(grade, badFormat, year, length):
return int(sorted(everyonesAverage(year, badFormat, length), reverse=True).index(grade) + 1) | 1,023,629 |
creates list of weighted average results for everyone in year
Arguments:
year {int}
badFormat {dict} -- candNumber : [results for candidate]
length {int} -- length of each row in badFormat divided by 2
returns:
list -- weighted average results of everyone in year | def everyonesAverage(year, badFormat, length):
return [myGrades(year, cand, badFormat, length) for cand in list(badFormat.keys())[1:]] | 1,023,630 |
plots using inquirer prompts
Arguments:
goodFormat {dict} -- module : [results for module] | def howPlotAsk(goodFormat):
plotAnswer = askPlot()
if "Save" in plotAnswer['plotQ']:
exportPlotsPath = pathlib.Path(askSave())
if "Show" in plotAnswer['plotQ']:
plotter(exportPlotsPath, True, goodFormat)
else:
plotter(exportPlotsPath, False, goodFormat)
e... | 1,023,632 |
plots using argparse if can, if not uses howPlotask()
Arguments:
goodFormat {dict} -- module : [results for module] | def howPlotArgs(goodFormat):
if args.exportplots is not None:
exportPlotsPath = pathlib.Path(args.exportplots)
if args.showplots:
plotter(exportPlotsPath, True, goodFormat)
else:
plotter(exportPlotsPath, False, goodFormat)
elif args.showplots:
plotte... | 1,023,633 |
main entry point of app
Arguments:
args {namespace} -- arguments provided in cli | def main(args):
print("\nNote it's very possible that this doesn't work correctly so take what it gives with a bucketload of salt\n")
#########################
# #
# #
# prompt #
# #
# ... | 1,023,635 |
r"""A decorator that makes the decorated function to run while ec exits.
Args:
callable (callable): The target callable.
once (bool): Avoids adding a func to the hooks, if it has been added already. Defaults to True.
Note:
Hooks are processedd in a LIFO order. | def exit_hook(callable, once=True):
r
if once and callable in ExitHooks:
return
ExitHooks.append(callable) | 1,023,653 |
a predicate that converts the key'd source to boolean.
parameters:
raw_crash - dict
dumps - placeholder in a fat interface - unused
processed_crash - placeholder in a fat interface - unused
processor - placeholder in a fat interface - unused | def is_not_null_predicate(
raw_crash, dumps, processed_crash, processor, key=''
):
try:
return bool(raw_crash[key])
except KeyError:
return False | 1,023,664 |
Makes sure that an executable can be found on the system path.
Will exit the program if the executable cannot be found
Args:
exe_name: name of the executable
paths: optional path(s) to be searched; if not specified, search the whole system | def ensure_exe(exe_name: str, *paths: str): # pragma: no cover
if not elib_run.find_executable(exe_name, *paths):
LOGGER.error('could not find "%s.exe" on this system', exe_name)
sys.exit(-1) | 1,024,016 |
Scan an ast object for targetvar and return its value.
Only handles single direct assignment of python literal types. See docs on
ast.literal_eval for more info:
http://docs.python.org/2/library/ast.html#ast.literal_eval
Args:
syntree: ast.Module object
targetvar: name of global variable t... | def getvar(syntree, targetvar):
for node in syntree.body:
if isinstance(node, ast.Assign):
for var in node.targets:
if var.id == targetvar:
return ast.literal_eval(node.value) | 1,024,303 |
Writes the changelog
Args:
amend: amend last commit with changes
stage: stage changes | def _chglog(amend: bool = False, stage: bool = False, next_version: str = None, auto_next_version: bool = False):
if config.CHANGELOG_DISABLE():
LOGGER.info('skipping changelog update as per config')
else:
epab.utils.ensure_exe('git')
epab.utils.ensure_exe('gitchangelog')
LO... | 1,024,504 |
Writes the changelog
Args:
amend: amend last commit with changes
stage: stage changes
next_version: indicates next version
auto_next_version: infer next version from VCS | def chglog(amend: bool = False, stage: bool = False, next_version: str = None, auto_next_version: bool = False):
changed_files = CTX.repo.changed_files()
changelog_file_path: Path = config.CHANGELOG_FILE_PATH()
changelog_file_name = changelog_file_path.name
if changelog_file_name in changed_files:
... | 1,024,505 |
Maps a given URL path, name and namespace to a view.
Arguments:
- path: the URL regex, e.g.: '^teste/(?P<pk>[0-9])/$'.
Optional arguments:
- name: the URL name, which Django uses to identify the URL;
- include: A custom URL list, previously
set... | def umap(path, name=None, include=None, namespace=None, priority=None):
def url_wrapper(view):
# gets the module name
module = _find_urls_module(view)
# gets the view function (checking if it's a class-based view)
fn = view.as_view() if hasattr(view, 'as_view') else view
... | 1,024,799 |
Fetch json data from n.pl
Args:
date (date) - default today
url_patter (string) - default URL_PATTERN
Returns:
dict - data from api | def fetcher(date=datetime.today(), url_pattern=URL_PATTERN):
api_url = url_pattern % date.strftime('%Y-%m-%d')
headers = {'Referer': 'http://n.pl/program-tv'}
raw_result = requests.get(api_url, headers=headers).json()
return raw_result | 1,024,829 |
Parse raw result from fetcher into readable dictionary
Args:
raw_result (dict) - raw data from `fetcher`
Returns:
dict - readable dictionary | def result_to_dict(raw_result):
result = {}
for channel_index, channel in enumerate(raw_result):
channel_id, channel_name = channel[0], channel[1]
channel_result = {
'id': channel_id,
'name': channel_name,
'movies': []
}
for movie in cha... | 1,024,830 |
Send the prepared XML request block to the CPS using the corect protocol.
Args:
xml_request -- A fully formed xml request string for the CPS.
Returns:
The raw xml response string.
Raises:
ConnectionError -- Can't establish a connecti... | def _send_request(self, xml_request):
if self._scheme == 'http':
return self._send_http_request(xml_request)
else:
return self._send_socket_request(xml_request) | 1,024,958 |
Send a request via HTTP protocol.
Args:
xml_request -- A fully formed xml request string for the CPS.
Returns:
The raw xml response string. | def _send_http_request(self, xml_request):
headers = {"Host": self._host, "Content-Type": "text/xml", "Recipient": self._storage}
try: # Retry once if failed in case the socket has just gone bad.
self._connection.request("POST", self._selector_url, xml_request, headers)
... | 1,024,959 |
Send a request via protobuf.
Args:
xml_request -- A fully formed xml request string for the CPS.
Returns:
The raw xml response string. | def _send_socket_request(self, xml_request):
def to_variant(number):
buff = []
while number:
byte = number % 128
number = number // 128
if number > 0:
byte |= 0x80
buff.append(chr(byte))
... | 1,024,960 |
Increment the world state, determining which cells live, die, or appear.
Args:
world (list[list]): A square matrix of cells
Returns: None | def update_state(world):
world_size = len(world)
def wrap(index):
return index % world_size
for x in range(world_size):
for y in range(world_size):
# Decide if this node cares about the rules right now
if not world[x][y].allow_change.get():
... | 1,025,012 |
Prints description information about all tables registered
Args:
full (bool): Also prints description of post processors. | def describe_all(self, full=False):
for table in self.tabs:
yield self.tabs[table]().describe(full) | 1,025,217 |
Configure how a function should be retried.
Args:
on_exception (BaseException): The exception to catch. Use this to
set which exception and it's subclasses to catch.
limit () | def __init__(self, on_exception=Exception, limit=5, interval=None,
validator=None):
self.attempts = 0
self._on_exception = on_exception
self._setup_limit(limit)
self._setup_interval(interval)
self._setup_validator(validator) | 1,025,725 |
Constructor.
Args:
watch_paths: A list of filesystem paths to watch for changes.
on_changed: Callback to call when one or more changes to the watch path are detected.
interval: The minimum interval at which to notify about changes (in seconds).
recursive: Should ... | def __init__(self, watch_paths, on_changed=None, interval=1.0, recursive=True):
if isinstance(watch_paths, basestring):
watch_paths = [watch_paths]
watch_paths = [os.path.abspath(path) for path in watch_paths]
for path in watch_paths:
if not os.path.exists(path)... | 1,025,783 |
Determining whether the exception is thrown
Args:
error_type:
None: checking without specified exception
Specified Exception
Return: Boolean | def threw(self, error_type=None):
if not error_type:
return True if len(self.exceptions) > 0 else False
else:
return uch.obj_in_list(self.exceptions, error_type) | 1,026,183 |
Determining whether the specified exception is the ONLY thrown exception
Args:
error_type:
None: checking without specified exception
Specified Exception
Return: Boolean | def alwaysThrew(self, error_type=None): #pylint: disable=invalid-name
if self.callCount == 0:
return False
if not error_type:
return True if len(self.exceptions) == self.callCount else False
else:
return uch.obj_in_list_always(self.exceptions, error_t... | 1,026,184 |
execute by argument dictionary
Args:
args (dict): command line argument dictionary | def execute_by_options(args):
if args['subcommand'] == 'sphinx':
s = Sphinx(proj_info)
if args['quickstart']:
s.quickstart()
elif args['gen_code_api']:
s.gen_code_api()
elif args['rst2html']:
s.rst2html()
pass
elif args['subcommand... | 1,026,407 |
find the first matched line, then replace
Args:
regex_tgtline (str): regular expression used to match the target line
to_replace (str): line you wanna use to replace | def editline_with_regex(self, regex_tgtline, to_replace):
for idx, line in enumerate(self._swp_lines):
mobj = re.match(regex_tgtline, line)
if mobj:
self._swp_lines[idx] = to_replace
return | 1,026,410 |
init project info
Args:
author_fakename (str): TODO
author_truename (str): TODO
email (str): TODO
project_name (str): TODO
project_version (str): TODO | def __init__(self, **kwinfo):
self._author_fakename = getpass.getuser()
self._author_truename = ProjectInfo.find_pakcage_info(
'author', SRC_FOLDER, PROJECT_NAME, '__init__.py')
self._email = ProjectInfo.find_pakcage_info(
'email', SRC_FOLDER, PROJECT_NAME, '__in... | 1,026,412 |
TODO: to be defined1.
Args:
proj_info (ProjectInfo): TODO | def __init__(self, proj_info):
self._proj_info = proj_info
self.__docfolder = DOC_FOLDER
self.__htmlfolder = HTML_FOLDER
self.conf_fpath = os.path.abspath(
os.path.join(self.__docfolder, 'conf.py'))
self.code_fdpath = os.path.abspath(
os.path.joi... | 1,026,414 |
Copies the google spreadsheet to the backup_name and folder specified.
Args:
backup_name (str): The name of the backup document to create.
folder_key (Optional) (str): The key of a folder that the new copy will
be moved to.
folder_name (Opti... | def backup(self, backup_name, folder_key=None, folder_name=None):
folder = self._find_or_create_folder(folder_key, folder_name)
drive_service = self.drive_service
try:
source_rsrc = drive_service.files().get(fileId=self.document_key).execute()
except Exceptio... | 1,026,717 |
Equivalent to the inject method but will delete rows from the
google spreadsheet if their key is not found in the input (raw_data)
dictionary.
Args:
raw_data (dict): See inject method
row_change_callback (Optional) (func): See inject method
Returns:... | def sync(self, raw_data, row_change_callback=None):
return self._update(raw_data, row_change_callback, delete_rows=True) | 1,026,720 |
Checking and setting type to MODULE_FUNCTION
Args:
obj: ModuleType
prop: FunctionType
Return:
Boolean
Raise:
prop_type_error: When the type of prop is not valid
prop_in_obj_error: When prop is not in the obj(module/class)
prop_is_func_error: When prop is not a... | def is_module_function(obj, prop):
python_version = sys.version_info[0]
if python_version == 3:
unicode = str
if prop and (isinstance(prop, str) or isinstance(prop, unicode)): #property
if prop in dir(obj):
if (
isinstance(getattr(obj, prop), FunctionTyp... | 1,026,730 |
Checking and setting type to MODULE
Args:
obj: ModuleType / class
Note: An instance will be treated as a Class
Return:
Boolean | def is_module(obj):
return True if obj and isinstance(obj, ModuleType) or inspect.isclass(obj) else False | 1,026,731 |
Validate the given config against the `Scheme`.
Args:
config (dict): The configuration to validate.
Raises:
errors.SchemeValidationError: The configuration fails
validation against the `Schema`. | def validate(self, config):
if not isinstance(config, dict):
raise errors.SchemeValidationError(
'Scheme can only validate a dictionary config, but was given '
'{} (type: {})'.format(config, type(config))
)
for arg in self.args:
... | 1,027,516 |
Cast a value to the type required by the option, if one is set.
This is used to cast the string values gathered from environment
variable into their required type.
Args:
value: The value to cast.
Returns:
The value casted to the expected type for the option. | def cast(self, value):
# if there is no type set for the option, return the given
# value unchanged.
if self.type is None:
return value
# cast directly
if self.type in (str, int, float):
try:
return self.type(value)
ex... | 1,027,520 |
Copy all values of scope into the class SinonGlobals
Args:
scope (eg. locals() or globals())
Return:
SinonGlobals instance | def init(scope):
class SinonGlobals(object): #pylint: disable=too-few-public-methods
pass
global CPSCOPE #pylint: disable=global-statement
CPSCOPE = SinonGlobals()
funcs = [obj for obj in scope.values() if isinstance(obj, FunctionType)]
for func in funcs:
setattr(CPSCO... | 1,028,138 |
Constructor of SinonBase
It will new true base but return a proxy of weakref and store it in _queue
Args:
obj: None / function / instance method / module / class
Inspected target
prop: None / string
Inspected target when obj contains callable thing... | def __new__(cls, obj=None, prop=None, func=None):
new = super(SinonBase, cls).__new__(cls)
if func:
new.__init__(obj, prop, func)
else:
new.__init__(obj, prop)
cls._queue.append(new)
return weakref.proxy(new) | 1,028,139 |
It will create the true base
flow:
__new__ => __init__
=> set type based on arguments
=> check the arguments is valid or not based on type
=> wrap the target
Args:
obj: None / function / instance method / module / class
Inspecte... | def __init__(self, obj=None, prop=None):
if not hasattr(self, "args_type"):
self.__set_type(obj, prop)
self.obj, self.prop = obj, prop
self.__check_lock()
self.wrap2spy()
self.is_in_queue = False | 1,028,141 |
Triage type based on arguments
Here are four types of base: PURE, MODULE, MODULE_FUNCTION, FUNCTION
Args:
obj: None, FunctionType, ModuleType, Class, Instance
prop: None, string | def __set_type(self, obj, prop):
if TypeHandler.is_pure(obj, prop):
self.args_type = "PURE"
self.pure = SinonBase.Pure()
setattr(self.pure, "func", Wrapper.empty_function)
self.orig_func = None
elif TypeHandler.is_module_function(obj, prop):
... | 1,028,142 |
Wrapping the inspector as a stub based on the type
Args:
customfunc: function that replaces the original
Returns:
function, the spy wrapper around the customfunc | def wrap2stub(self, customfunc):
if self.args_type == "MODULE_FUNCTION":
wrapper = Wrapper.wrap_spy(customfunc, self.obj)
setattr(self.obj, self.prop, wrapper)
elif self.args_type == "MODULE":
wrapper = Wrapper.EmptyClass
setattr(CPSCOPE, self.obj... | 1,028,146 |
Set the data type of the cluster.
Parameters:
-----------
cluster_dtype : numpy.dtype or equivalent
Defines the dtype of the cluster array. | def set_cluster_dtype(self, cluster_dtype):
if not cluster_dtype:
cluster_dtype = np.dtype([])
else:
cluster_dtype = np.dtype(cluster_dtype)
cluster_descr = cluster_dtype.descr
for dtype_name, dtype in self._default_cluster_descr:
if self._cl... | 1,028,323 |
Merge two dictionaries (or DotDicts) together.
Args:
d: The dictionary/DotDict to merge into.
u: The source of the data to merge. | def _merge(d, u):
for k, v in u.items():
# if we have a mapping, recursively merge the values
if isinstance(v, collections.Mapping):
d[k] = _merge(d.get(k, {}), v)
# if d (the dict to merge into) is a dict, just add the
# value to the dict.
elif isinstance(d... | 1,029,303 |
Get a value from the `DotDict`.
The `key` parameter can either be a regular string key,
e.g. "foo", or it can be a string key with dot notation,
e.g. "foo.bar.baz", to signify a nested lookup.
The default value is returned if any level of the key's
components are not found.
... | def get(self, key, default=None):
# if there are no dots in the key, its a normal get
if key.count('.') == 0:
return super(DotDict, self).get(key, default)
# set the return value to the default
value = default
# split the key into the first component and th... | 1,029,307 |
Remove a value from the `DotDict`.
The `key` parameter can either be a regular string key,
e.g. "foo", or it can be a string key with dot notation,
e.g. "foo.bar.baz", to signify a nested element.
If the key does not exist in the `DotDict`, it will continue
silently.
A... | def delete(self, key):
dct = self
keys = key.split('.')
last_key = keys[-1]
for k in keys:
# if the key is the last one, e.g. 'z' in 'x.y.z', try
# to delete it from its dict.
if k == last_key:
del dct[k]
break
... | 1,029,308 |
Set a value in the `Bison` configuration.
Args:
key (str): The configuration key to set a new value for.
value: The value to set. | def set(self, key, value):
# the configuration changes, so we invalidate the cached config
self._full_config = None
self._override[key] = value | 1,029,376 |
Parse the configuration sources into `Bison`.
Args:
requires_cfg (bool): Specify whether or not parsing should fail
if a config file is not found. (default: True) | def parse(self, requires_cfg=True):
self._parse_default()
self._parse_config(requires_cfg)
self._parse_env() | 1,029,377 |
Parse the configuration file, if one is configured, and add it to
the `Bison` state.
Args:
requires_cfg (bool): Specify whether or not parsing should fail
if a config file is not found. (default: True) | def _parse_config(self, requires_cfg=True):
if len(self.config_paths) > 0:
try:
self._find_config()
except BisonError:
if not requires_cfg:
return
raise
try:
with open(self.config_fil... | 1,029,379 |
Checks if a node is the "end" keyword.
Args:
node: AST node.
Returns:
True if the node is the "end" keyword, otherwise False. | def is_end_node(node):
return (isinstance(node, ast.Expr) and
isinstance(node.value, ast.Name) and
node.value.id == 'end') | 1,030,148 |
Returns a list of bodies of a compound statement node.
Args:
node: AST node.
Returns:
A list of bodies of the node. If the given node does not represent
a compound statement, an empty list is returned. | def get_compound_bodies(node):
if isinstance(node, (ast.Module, ast.FunctionDef, ast.ClassDef, ast.With)):
return [node.body]
elif isinstance(node, (ast.If, ast.While, ast.For)):
return [node.body, node.orelse]
elif PY2 and isinstance(node, ast.TryFinally):
return [node.body, no... | 1,030,149 |
Performs end-block check.
Args:
frame: A frame object of the module to be checked.
Raises:
SyntaxError: If check failed. | def check_end_blocks(frame):
try:
try:
module_name = frame.f_globals['__name__']
except KeyError:
warnings.warn(
'Can not get the source of an uknown module. '
'End-of-block syntax check is skipped.',
EndSyntaxWarning)
... | 1,030,150 |
Internal: Do not call. Returns the status list for a list of job_ids
Args:
self
Returns:
[status...] : Status list of all jobs | def _status(self):
job_id_list = ' '.join(self.resources.keys())
jobs_missing = list(self.resources.keys())
retcode, stdout, stderr = self.channel.execute_wait("qstat {0}".format(job_id_list), 3)
for line in stdout.split('\n'):
parts = line.split()
if ... | 1,030,155 |
Cancels the jobs specified by a list of job ids
Args:
job_ids : [<job_id> ...]
Returns :
[True/False...] : If the cancel operation fails the entire list will be False. | def cancel(self, job_ids):
job_id_list = ' '.join(job_ids)
retcode, stdout, stderr = self.channel.execute_wait("qdel {0}".format(job_id_list), 3)
rets = None
if retcode == 0:
for jid in job_ids:
self.resources[jid]['status'] = translate_table['E'] #... | 1,030,157 |
Compute the gradient.
Args:
diff (`array-like`): [`m`, `m`] matrix. `D` - `d`
d (`array-like`): [`m`, `m`] matrix.
coords (`array-like`): [`m`, `n`] matrix.
Returns:
`np.array`: Gradient, shape [`m`, `n`]. | def _gradient(self, diff, d, coords):
denom = np.copy(d)
denom[denom == 0] = 1e-5
with np.errstate(divide='ignore', invalid='ignore'):
K = -2 * diff / denom
K[np.isnan(K)] = 0
g = np.empty_like(coords)
for n in range(self.n):
for i in r... | 1,030,278 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.