uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
acdd4b06bf6e3cbb41bdb659 | train | function | def ilist_files(directory, suffix='.nc'):
"""
Return an iterator of all the files with the specified suffix in the
submission directory structure and sub-directories.
:param str directory: The root directory of the submission
:param str suffix: The suffix of the files of interest
:returns: A li... | def ilist_files(directory, suffix='.nc'):
| """
Return an iterator of all the files with the specified suffix in the
submission directory structure and sub-directories.
:param str directory: The root directory of the submission
:param str suffix: The suffix of the files of interest
:returns: A list of absolute filepaths
"""
dir_f... | in dir_files:
file_path = os.path.join(directory, filename)
if os.path.isdir(file_path):
nc_files.extend(list_files(file_path, suffix))
elif file_path.endswith(suffix):
nc_files.append(file_path)
return nc_files
def ilist_files(directory, suffix='.nc'):
| 64 | 64 | 139 | 10 | 53 | PRIMAVERA-H2020/pre-proc | pre_proc/common.py | Python | ilist_files | ilist_files | 60 | 76 | 60 | 60 | 3b767037a3a92c5d65a878ba562c2791f3ad0d1d | bigcode/the-stack | train |
daae54a3ef79c081a4093628 | train | function | def get_concrete_subclasses(parent_object):
"""
Return a list of the all the concrete (non-abstract) subclasses of
`parent_object`. It recursively works its way to the bottom
of the class hierarchy.
:param object parent_object: The parent object
:return: List of objects found
:rtype: list
... | def get_concrete_subclasses(parent_object):
| """
Return a list of the all the concrete (non-abstract) subclasses of
`parent_object`. It recursively works its way to the bottom
of the class hierarchy.
:param object parent_object: The parent object
:return: List of objects found
:rtype: list
"""
if not parent_object.__subclasses... | for filename in dir_files:
file_path = os.path.join(directory, filename)
if os.path.isdir(file_path):
for ifile in ilist_files(file_path):
yield ifile
elif file_path.endswith(suffix):
yield file_path
def get_concrete_subclasses(parent_object):
| 64 | 64 | 141 | 9 | 54 | PRIMAVERA-H2020/pre-proc | pre_proc/common.py | Python | get_concrete_subclasses | get_concrete_subclasses | 79 | 98 | 79 | 79 | 11c989f3214ca25f18fa092ddc2686326b13e5e8 | bigcode/the-stack | train |
178e566d23202d1214cd5d56 | train | function | def list_files(directory, suffix='.nc'):
"""
Return a list of all the files with the specified suffix in the submission
directory structure and sub-directories.
:param str directory: The root directory of the submission
:param str suffix: The suffix of the files of interest
:returns: A list of ... | def list_files(directory, suffix='.nc'):
| """
Return a list of all the files with the specified suffix in the submission
directory structure and sub-directories.
:param str directory: The root directory of the submission
:param str suffix: The suffix of the files of interest
:returns: A list of absolute filepaths
"""
nc_files =... | :\n{}\n'
'produced error:\n{}'.format(command, exc.output))
logger.warning(msg)
raise RuntimeError(msg)
if isinstance(cmd_out, str):
return cmd_out.rstrip().split('\n')
else:
return None
def list_files(directory, suffix='.nc'):
| 64 | 64 | 145 | 9 | 54 | PRIMAVERA-H2020/pre-proc | pre_proc/common.py | Python | list_files | list_files | 38 | 57 | 38 | 38 | 994d9d447b13899100b128cacfb25f56e87bcf7d | bigcode/the-stack | train |
dbfa79cf8e60c17518be4919 | train | function | def to_float(string_value):
"""
Convert a string starting with a float to a float and return this.
:param str string_value: The string to convert.
:returns: The float from the start of the string.
:rtype: float
:raises TypeError: if something other than a string is passed in.
:raises ValueE... | def to_float(string_value):
| """
Convert a string starting with a float to a float and return this.
:param str string_value: The string to convert.
:returns: The float from the start of the string.
:rtype: float
:raises TypeError: if something other than a string is passed in.
:raises ValueError: if a float cannot be f... | classes__:
return []
sub_classes = []
for sub_class in parent_object.__subclasses__():
if inspect.isabstract(sub_class):
sub_classes.extend(get_concrete_subclasses(sub_class))
else:
sub_classes.append(sub_class)
return sub_classes
def to_float(string_value):
| 64 | 64 | 163 | 6 | 57 | PRIMAVERA-H2020/pre-proc | pre_proc/common.py | Python | to_float | to_float | 101 | 117 | 101 | 101 | ae96bb7107d44bd3d3c57191baa98dfc19c95d67 | bigcode/the-stack | train |
ba6e3cea8e78b871078dcd02 | train | function | def run_command(command):
"""
Run the command specified and return any output to stdout or stderr as
a list of strings.
:param str command: The complete command to run.
:returns: Any output from the command as a list of strings.
:raises RuntimeError: If the command did not complete successfully.... | def run_command(command):
| """
Run the command specified and return any output to stdout or stderr as
a list of strings.
:param str command: The complete command to run.
:returns: Any output from the command as a list of strings.
:raises RuntimeError: If the command did not complete successfully.
"""
try:
... | """
common.py
Library code used by many functions.
"""
import inspect
import logging.config
import os
import re
import subprocess
logger = logging.getLogger(__name__)
def run_command(command):
| 41 | 64 | 172 | 5 | 36 | PRIMAVERA-H2020/pre-proc | pre_proc/common.py | Python | run_command | run_command | 15 | 35 | 15 | 15 | bb25f06aba5ee9639d9d855767c2019f00cbece1 | bigcode/the-stack | train |
388bd726135fabfa5c047ea9 | train | function | def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('alert', sa.Column('notified_at', sa.DateTime(), nullable=True))
op.drop_column('alert', 'max_id')
| def upgrade():
### commands auto generated by Alembic - please adjust! ###
| op.add_column('alert', sa.Column('notified_at', sa.DateTime(), nullable=True))
op.drop_column('alert', 'max_id')
| 980223
"""
# revision identifiers, used by Alembic.
revision = '670af22aca83'
down_revision = 'e73ddafacd6d'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
| 64 | 64 | 49 | 17 | 46 | jalmquist/aleph | aleph/migrate/versions/670af22aca83_use_time_for_alerts.py | Python | upgrade | upgrade | 17 | 20 | 17 | 18 | d6178d1ffe872d9f5c5e58df543dbca6b95071dc | bigcode/the-stack | train |
8c30597f9f88978da8c2cca7 | train | function | def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('alert', sa.Column('max_id', sa.BIGINT(), autoincrement=False, nullable=True))
op.drop_column('alert', 'notified_at')
| def downgrade():
### commands auto generated by Alembic - please adjust! ###
| op.add_column('alert', sa.Column('max_id', sa.BIGINT(), autoincrement=False, nullable=True))
op.drop_column('alert', 'notified_at')
| ic - please adjust! ###
op.add_column('alert', sa.Column('notified_at', sa.DateTime(), nullable=True))
op.drop_column('alert', 'max_id')
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
| 63 | 64 | 55 | 17 | 46 | jalmquist/aleph | aleph/migrate/versions/670af22aca83_use_time_for_alerts.py | Python | downgrade | downgrade | 24 | 27 | 24 | 25 | 70c928496227ee812743759ae2b900c246da124c | bigcode/the-stack | train |
f0fd8dec1001837dcb3a09f1 | train | function | def func(name):
print("hello", name)
time.sleep(3)
| def func(name):
| print("hello", name)
time.sleep(3)
| #! /usr/bin/env python3
# -*- coding:utf-8 -*-
import threading
import time
# 启线程法2(类):
def func(name):
| 35 | 64 | 17 | 4 | 30 | matiji66/python-concurrent-study | thread_start1.py | Python | func | func | 10 | 12 | 10 | 10 | 15538b1a146dfeed708c3a11ec6b1948bf98ac50 | bigcode/the-stack | train |
2682f3d147c9c500b54b9095 | train | class | class Range(object):
"""Encapsulates a ranged defined by a min and max numerical value."""
def __init__(self, minimum, maximum):
self.min = minimum
self.max = maximum
def within_range(self, value):
"""Returns True if the value is between this Range, inclusive."""
return valu... | class Range(object):
| """Encapsulates a ranged defined by a min and max numerical value."""
def __init__(self, minimum, maximum):
self.min = minimum
self.max = maximum
def within_range(self, value):
"""Returns True if the value is between this Range, inclusive."""
return value >= self.min and val... | """Data containers and other utilities."""
import time
import json
import collections
import logging
import os
import sys
LOG = logging.getLogger(__name__)
class Range(object):
| 37 | 64 | 107 | 4 | 33 | hopper-maker/openxc-python | openxc/utils.py | Python | Range | Range | 11 | 24 | 11 | 11 | 5fdc92ea6979340454eb27b0e66161db307d8a7d | bigcode/the-stack | train |
c00ca799b755a7ab71b51d80 | train | function | def merge(a, b):
"""Merge two deep dicts non-destructively
Uses a stack to avoid maximum recursion depth exceptions
>>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
>>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
>>> c = merge(a, b)
>>> from pprint import pprint; pprint(c)
{'a': 1, 'b': {1... | def merge(a, b):
| """Merge two deep dicts non-destructively
Uses a stack to avoid maximum recursion depth exceptions
>>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
>>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
>>> c = merge(a, b)
>>> from pprint import pprint; pprint(c)
{'a': 1, 'b': {1: 1, 2: 7}, 'c': ... | ()
@property
def age(self):
"""Return the age of the data in seconds."""
return time.time() - self.created_at
def quacks_like_dict(object):
"""Check if object is dict-like"""
return isinstance(object, collections.Mapping)
def quacks_like_list(object):
"""Check if object is list-... | 93 | 93 | 313 | 6 | 87 | hopper-maker/openxc-python | openxc/utils.py | Python | merge | merge | 49 | 78 | 49 | 49 | 18e5b5458ea45a3c01e2c9015488f89685b55f40 | bigcode/the-stack | train |
1821face836ba69aa3cdf506 | train | function | def fatal_error(message):
LOG.error(message)
sys.exit(1)
| def fatal_error(message):
| LOG.error(message)
sys.exit(1)
| json_file:
try:
data = json.load(json_file, object_pairs_hook=dict_raise_on_duplicates)
except ValueError as e:
fatal_error("%s does not contain valid JSON: \n%s\n" %
(filename, e))
else:
return data
def fatal_error(message):
| 64 | 64 | 16 | 5 | 58 | hopper-maker/openxc-python | openxc/utils.py | Python | fatal_error | fatal_error | 113 | 115 | 113 | 113 | fc4666e817a62ea5fe73dfb8c10cc53c8db74fcd | bigcode/the-stack | train |
86e660a086f7c9ed88da35f0 | train | function | def find_file(filename, search_paths):
for search_path in search_paths:
if filename[0] != '/':
full_path = "%s/%s" % (search_path, filename)
else:
full_path = filename
if os.path.exists(full_path):
return full_path
fatal_error("Unable to find '%s' in s... | def find_file(filename, search_paths):
| for search_path in search_paths:
if filename[0] != '/':
full_path = "%s/%s" % (search_path, filename)
else:
full_path = filename
if os.path.exists(full_path):
return full_path
fatal_error("Unable to find '%s' in search paths (%s)" % (
filen... | _dst[key], current_src[key]))
elif (quacks_like_list(current_src[key]) and
quacks_like_list(current_dst[key])):
current_dst[key].extend(current_src[key])
else:
current_dst[key] = current_src[key]
return dst
def find_file... | 64 | 64 | 87 | 8 | 55 | hopper-maker/openxc-python | openxc/utils.py | Python | find_file | find_file | 81 | 90 | 81 | 81 | 33b695ac9d46dce88bdd37bf1c3477c058d138bd | bigcode/the-stack | train |
526e9083896b59a5043d3679 | train | class | class AgingData(object):
"""Mixin to associate a class with a time of birth."""
def __init__(self):
self.created_at = time.time()
@property
def age(self):
"""Return the age of the data in seconds."""
return time.time() - self.created_at
| class AgingData(object):
| """Mixin to associate a class with a time of birth."""
def __init__(self):
self.created_at = time.time()
@property
def age(self):
"""Return the age of the data in seconds."""
return time.time() - self.created_at
| , value):
"""Returns True if the value is between this Range, inclusive."""
return value >= self.min and value <= self.max
@property
def spread(self):
"""Returns the spread between this Range's min and max."""
return self.max - self.min
class AgingData(object):
| 64 | 64 | 63 | 5 | 58 | hopper-maker/openxc-python | openxc/utils.py | Python | AgingData | AgingData | 27 | 36 | 27 | 27 | ac66d187d1ab4d07240a6e60e08df1c0392c4451 | bigcode/the-stack | train |
a0d69803f7d6262b5a6181fe | train | function | def quacks_like_dict(object):
"""Check if object is dict-like"""
return isinstance(object, collections.Mapping)
| def quacks_like_dict(object):
| """Check if object is dict-like"""
return isinstance(object, collections.Mapping)
| """Mixin to associate a class with a time of birth."""
def __init__(self):
self.created_at = time.time()
@property
def age(self):
"""Return the age of the data in seconds."""
return time.time() - self.created_at
def quacks_like_dict(object):
| 64 | 64 | 24 | 7 | 56 | hopper-maker/openxc-python | openxc/utils.py | Python | quacks_like_dict | quacks_like_dict | 39 | 41 | 39 | 39 | 41c1101d8db449bc08c347409552d3d7e01c417f | bigcode/the-stack | train |
57376742c71c5f92e2d163f8 | train | function | def quacks_like_list(object):
"""Check if object is list-like"""
return hasattr(object, '__iter__') and hasattr(object, 'append')
| def quacks_like_list(object):
| """Check if object is list-like"""
return hasattr(object, '__iter__') and hasattr(object, 'append')
| time.time()
@property
def age(self):
"""Return the age of the data in seconds."""
return time.time() - self.created_at
def quacks_like_dict(object):
"""Check if object is dict-like"""
return isinstance(object, collections.Mapping)
def quacks_like_list(object):
| 64 | 64 | 32 | 7 | 57 | hopper-maker/openxc-python | openxc/utils.py | Python | quacks_like_list | quacks_like_list | 44 | 46 | 44 | 44 | 6d3bd2136bedd109bfac6f232e1d43780272f14f | bigcode/the-stack | train |
ca4d104aee9a7bfa547d51ce | train | function | def load_json_from_search_path(filename, search_paths):
with open(find_file(filename, search_paths)) as json_file:
try:
data = json.load(json_file, object_pairs_hook=dict_raise_on_duplicates)
except ValueError as e:
fatal_error("%s does not contain valid JSON: \n%s\n" %
... | def load_json_from_search_path(filename, search_paths):
| with open(find_file(filename, search_paths)) as json_file:
try:
data = json.load(json_file, object_pairs_hook=dict_raise_on_duplicates)
except ValueError as e:
fatal_error("%s does not contain valid JSON: \n%s\n" %
(filename, e))
else:
... | """Reject duplicate keys."""
d = {}
for k, v in ordered_pairs:
if k in d:
raise ValueError("duplicate key: %r" % (k,))
else:
d[k] = v
return d
def load_json_from_search_path(filename, search_paths):
| 64 | 64 | 81 | 11 | 52 | hopper-maker/openxc-python | openxc/utils.py | Python | load_json_from_search_path | load_json_from_search_path | 103 | 111 | 103 | 103 | ea8898f45e7c573fcffda834b6701f647c750619 | bigcode/the-stack | train |
623836a86ba054ce24408db8 | train | function | def dict_raise_on_duplicates(ordered_pairs):
"""Reject duplicate keys."""
d = {}
for k, v in ordered_pairs:
if k in d:
raise ValueError("duplicate key: %r" % (k,))
else:
d[k] = v
return d
| def dict_raise_on_duplicates(ordered_pairs):
| """Reject duplicate keys."""
d = {}
for k, v in ordered_pairs:
if k in d:
raise ValueError("duplicate key: %r" % (k,))
else:
d[k] = v
return d
| s" % (search_path, filename)
else:
full_path = filename
if os.path.exists(full_path):
return full_path
fatal_error("Unable to find '%s' in search paths (%s)" % (
filename, search_paths))
def dict_raise_on_duplicates(ordered_pairs):
| 64 | 64 | 63 | 9 | 55 | hopper-maker/openxc-python | openxc/utils.py | Python | dict_raise_on_duplicates | dict_raise_on_duplicates | 93 | 101 | 93 | 93 | 4d6d8d12e0a70eb89a9879e1e10b861fd90bfe13 | bigcode/the-stack | train |
65f887894bb6567482a72b76 | train | class | class TodoModelTest(FunctionalTest, BaseWebTest):
model_id = 'todo'
@property
def valid_definition(self):
return {
"title": "todo",
"description": "A list of my stuff to do",
"fields": [
{
"name": "item",
"... | class TodoModelTest(FunctionalTest, BaseWebTest):
| model_id = 'todo'
@property
def valid_definition(self):
return {
"title": "todo",
"description": "A list of my stuff to do",
"fields": [
{
"name": "item",
"type": "string",
"label": "The ... | {'match_all': {}}}
resp = self.app.request('/models/%s/search/' % self.model_id,
method='GET',
body=json.dumps(query).encode(),
headers=self.headers)
results = resp.json.get('hits', {}).get('hits', [])
... | 80 | 80 | 268 | 12 | 68 | spiral-project/daybed | daybed/tests/test_functional.py | Python | TodoModelTest | TodoModelTest | 156 | 200 | 156 | 157 | 6f1f0bf6d7c0c2af4cf6f2aa69b0e2e224907abc | bigcode/the-stack | train |
993b768dfc8d5434dbd753de | train | class | class MushroomsModelTest(FunctionalTest, BaseWebTest):
model_id = 'mushroom_spots'
@property
def valid_definition(self):
return {
"title": "Mushroom Spots",
"description": "Where are they ?",
"fields": [
{
"name": "mushroom",
... | class MushroomsModelTest(FunctionalTest, BaseWebTest):
| model_id = 'mushroom_spots'
@property
def valid_definition(self):
return {
"title": "Mushroom Spots",
"description": "Where are they ?",
"fields": [
{
"name": "mushroom",
"type": "string",
... | "type": "enum",
"choices": [
"done",
"todo"
],
"required": True,
"label": "is it done or not",
"display": "dropdown"
}
]
}
@proper... | 182 | 182 | 609 | 13 | 169 | spiral-project/daybed | daybed/tests/test_functional.py | Python | MushroomsModelTest | MushroomsModelTest | 203 | 274 | 203 | 204 | 7908a0ff455e8e33581d2ba1e4782fd3a5563868 | bigcode/the-stack | train |
8dd3f8ff4085d2d9a2e4193b | train | class | class FunctionalTest(object):
"""These are the functional tests for daybed.
The goal is to have them reproduce every possible scenario that we want to
support in the application.
The test suite is created in a way that each test is a different scenario.
We reset the database each time we start a n... | class FunctionalTest(object):
| """These are the functional tests for daybed.
The goal is to have them reproduce every possible scenario that we want to
support in the application.
The test suite is created in a way that each test is a different scenario.
We reset the database each time we start a new test to avoid sharing
c... | # -*- coding: utf-8 -*-
import json
from daybed.tests.support import BaseWebTest, force_unicode
class FunctionalTest(object):
| 29 | 256 | 1,155 | 5 | 23 | spiral-project/daybed | daybed/tests/test_functional.py | Python | FunctionalTest | FunctionalTest | 7 | 153 | 7 | 7 | 6201d3a38c3679263922ed87b701baa8bcb13406 | bigcode/the-stack | train |
b367397ee90f05af977b3a59 | train | class | class AnnotationModelTest(BaseWebTest):
def test_annotation_attribute_can_be_provided(self):
resp = self.app.put_json('/models/annotation', {
'definition': {
"title": "annotation",
"description": "A list of my stuff to do",
"fields": [
... | class AnnotationModelTest(BaseWebTest):
| def test_annotation_attribute_can_be_provided(self):
resp = self.app.put_json('/models/annotation', {
'definition': {
"title": "annotation",
"description": "A list of my stuff to do",
"fields": [
{
"type"... | '))
self.assertEquals(feature['geometry']['type'], 'Polygon')
# after update
self.assertCountEqual(feature['geometry']['coordinates'],
[[[0, 0], [0, 1], [1, 1], [0, 0]]])
class AnnotationModelTest(BaseWebTest):
| 64 | 64 | 165 | 8 | 56 | spiral-project/daybed | daybed/tests/test_functional.py | Python | AnnotationModelTest | AnnotationModelTest | 277 | 302 | 277 | 278 | 75f9f7eff74f84391e241c2509775f915ff37ec3 | bigcode/the-stack | train |
1e9d5db7f1931a4097d9c312 | train | class | class OrderedModelBase(models.Model):
"""
An abstract model that allows objects to be ordered relative to each other.
Usage (See ``OrderedModel``):
- create a model subclassing ``OrderedModelBase``
- add an indexed ``PositiveIntegerField`` to the model
- set ``order_field_name`` to the name o... | class OrderedModelBase(models.Model):
| """
An abstract model that allows objects to be ordered relative to each other.
Usage (See ``OrderedModel``):
- create a model subclassing ``OrderedModelBase``
- add an indexed ``PositiveIntegerField`` to the model
- set ``order_field_name`` to the name of that field
- use the same field... | import warnings
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models import Max, Min, F
from django.utils.translation import ugettext as _
import six
"""
Convert a string containing module.submodule.classname to a Class.
"""
def _order_model_get_class(classpa... | 120 | 256 | 2,200 | 7 | 112 | preranaandure/wildlifecompliance | wildlifecompliance/ordered_model.py | Python | OrderedModelBase | OrderedModelBase | 23 | 304 | 23 | 23 | dac03aa958932b328c6b2b64cc24b17db956bef6 | bigcode/the-stack | train |
82b68c2832440aa0f715417f | train | function | def _order_model_get_class(classpath):
parts = classpath.split('.')
module = ".".join(parts[:-1])
m = __import__(module)
for comp in parts[1:]:
m = getattr(m, comp)
return m
| def _order_model_get_class(classpath):
| parts = classpath.split('.')
module = ".".join(parts[:-1])
m = __import__(module)
for comp in parts[1:]:
m = getattr(m, comp)
return m
|
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models import Max, Min, F
from django.utils.translation import ugettext as _
import six
"""
Convert a string containing module.submodule.classname to a Class.
"""
def _order_model_get_class(classpath):
| 64 | 64 | 56 | 9 | 55 | preranaandure/wildlifecompliance | wildlifecompliance/ordered_model.py | Python | _order_model_get_class | _order_model_get_class | 14 | 20 | 14 | 14 | be3422765d2d0acdc8179aa82b8492f3f3958f67 | bigcode/the-stack | train |
6f8e526feebe4e5de166fe38 | train | class | class OrderedModel(OrderedModelBase):
"""
An abstract model that allows objects to be ordered relative to each other.
Provides an ``order`` field.
"""
order = models.PositiveIntegerField(editable=False, db_index=True)
order_field_name = 'order'
class Meta:
abstract = True
o... | class OrderedModel(OrderedModelBase):
| """
An abstract model that allows objects to be ordered relative to each other.
Provides an ``order`` field.
"""
order = models.PositiveIntegerField(editable=False, db_index=True)
order_field_name = 'order'
class Meta:
abstract = True
ordering = ('order',)
| =None):
"""
Move this object to the bottom of the ordered stack.
"""
o = self.get_ordering_queryset().aggregate(Max(self.order_field_name)
).get(self.order_field_name + '__max')
self.to(o, extra_update=extra_update)
class Ordered... | 64 | 64 | 74 | 8 | 56 | preranaandure/wildlifecompliance | wildlifecompliance/ordered_model.py | Python | OrderedModel | OrderedModel | 307 | 318 | 307 | 307 | 89aef8f7fddbbf1de4ac1757e4c7781cf3500ca1 | bigcode/the-stack | train |
bd9cf245e7d394b9722a6d57 | train | function | def mpi2vch(s):
r = s[4:] # strip size
r = r[::-1] # reverse string, converting BE->LE
return r
| def mpi2vch(s):
| r = s[4:] # strip size
r = r[::-1] # reverse string, converting BE->LE
return r
| neg = True
i &= ~0x80
v_str[0] = i
v = bin2bn(v_str)
if neg:
return -v
return v
# hodlcash-specific little endian format, with implicit size
def mpi2vch(s):
| 64 | 64 | 40 | 7 | 56 | MichaelHDesigns/HodlCash | test/functional/test_framework/bignum.py | Python | mpi2vch | mpi2vch | 82 | 85 | 82 | 82 | 9f3e0059f878de6b4a7adfed19ea43326bae60ff | bigcode/the-stack | train |
84910c7fa3fdab6e745e93f8 | train | function | def vch2mpi(s):
r = struct.pack(b">I", len(s)) # size
r += s[::-1] # reverse string, converting LE->BE
return r
| def vch2mpi(s):
| r = struct.pack(b">I", len(s)) # size
r += s[::-1] # reverse string, converting LE->BE
return r
| ch(s):
r = s[4:] # strip size
r = r[::-1] # reverse string, converting BE->LE
return r
def bn2vch(v):
return bytes(mpi2vch(bn2mpi(v)))
def vch2mpi(s):
| 64 | 64 | 44 | 7 | 57 | MichaelHDesigns/HodlCash | test/functional/test_framework/bignum.py | Python | vch2mpi | vch2mpi | 90 | 93 | 90 | 90 | 363fee28a0db4dd5a8f5362f2e0bd6c43961fa12 | bigcode/the-stack | train |
3595ee248c1e0f2385aac2c2 | train | function | def bn2vch(v):
return bytes(mpi2vch(bn2mpi(v)))
| def bn2vch(v):
| return bytes(mpi2vch(bn2mpi(v)))
| return v
# hodlcash-specific little endian format, with implicit size
def mpi2vch(s):
r = s[4:] # strip size
r = r[::-1] # reverse string, converting BE->LE
return r
def bn2vch(v):
| 64 | 64 | 21 | 7 | 56 | MichaelHDesigns/HodlCash | test/functional/test_framework/bignum.py | Python | bn2vch | bn2vch | 87 | 88 | 87 | 87 | 04b0c63234fb7074277dd0f90a7754c2b7a4d08b | bigcode/the-stack | train |
0136dd96d7f94211ed0d779d | train | function | def mpi2bn(s):
if len(s) < 4:
return None
s_size = bytes(s[:4])
v_len = struct.unpack(b">I", s_size)[0]
if len(s) != (v_len + 4):
return None
if v_len == 0:
return 0
v_str = bytearray(s[4:])
neg = False
i = v_str[0]
if i & 0x80:
neg = True
i &... | def mpi2bn(s):
| if len(s) < 4:
return None
s_size = bytes(s[:4])
v_len = struct.unpack(b">I", s_size)[0]
if len(s) != (v_len + 4):
return None
if v_len == 0:
return 0
v_str = bytearray(s[4:])
neg = False
i = v_str[0]
if i & 0x80:
neg = True
i &= ~0x80
... | ext.append(0)
v_bin = bn2bin(v)
if neg:
if have_ext:
ext[0] |= 0x80
else:
v_bin[0] |= 0x80
return s + ext + v_bin
def mpi2bn(s):
| 64 | 64 | 149 | 6 | 57 | MichaelHDesigns/HodlCash | test/functional/test_framework/bignum.py | Python | mpi2bn | mpi2bn | 57 | 79 | 57 | 57 | b1a17520d9a58b343df49c91b1acef1c45c7a8b5 | bigcode/the-stack | train |
35bcb943a70e1b298ab50b34 | train | function | def bn_bytes(v, have_ext=False):
ext = 0
if have_ext:
ext = 1
return ((v.bit_length()+7)//8) + ext
| def bn_bytes(v, have_ext=False):
| ext = 0
if have_ext:
ext = 1
return ((v.bit_length()+7)//8) + ext
|
#
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Big number routines.
This file is copied from python-bitcoinlib.
"""
import struct
# generic big endian MPI format
def bn_bytes(v, have_ext=False):
| 64 | 64 | 40 | 9 | 54 | MichaelHDesigns/HodlCash | test/functional/test_framework/bignum.py | Python | bn_bytes | bn_bytes | 15 | 19 | 15 | 15 | 16bb7292a89a0f58fe55f0ee072b46347af20e5d | bigcode/the-stack | train |
3717e2b6cc0d71d041d6e3dc | train | function | def bin2bn(s):
l = 0
for ch in s:
l = (l << 8) | ch
return l
| def bin2bn(s):
| l = 0
for ch in s:
l = (l << 8) | ch
return l
| ext
def bn2bin(v):
s = bytearray()
i = bn_bytes(v)
while i > 0:
s.append((v >> ((i-1) * 8)) & 0xff)
i -= 1
return s
def bin2bn(s):
| 64 | 64 | 34 | 6 | 57 | MichaelHDesigns/HodlCash | test/functional/test_framework/bignum.py | Python | bin2bn | bin2bn | 29 | 33 | 29 | 29 | 8d1ce0d81c354fe261c4f21e6928f5913825a274 | bigcode/the-stack | train |
252987ff457afe225a69cc3c | train | function | def bn2mpi(v):
have_ext = False
if v.bit_length() > 0:
have_ext = (v.bit_length() & 0x07) == 0
neg = False
if v < 0:
neg = True
v = -v
s = struct.pack(b">I", bn_bytes(v, have_ext))
ext = bytearray()
if have_ext:
ext.append(0)
v_bin = bn2bin(v)
if neg... | def bn2mpi(v):
| have_ext = False
if v.bit_length() > 0:
have_ext = (v.bit_length() & 0x07) == 0
neg = False
if v < 0:
neg = True
v = -v
s = struct.pack(b">I", bn_bytes(v, have_ext))
ext = bytearray()
if have_ext:
ext.append(0)
v_bin = bn2bin(v)
if neg:
if ha... | ((i-1) * 8)) & 0xff)
i -= 1
return s
def bin2bn(s):
l = 0
for ch in s:
l = (l << 8) | ch
return l
def bn2mpi(v):
| 64 | 64 | 150 | 6 | 57 | MichaelHDesigns/HodlCash | test/functional/test_framework/bignum.py | Python | bn2mpi | bn2mpi | 35 | 55 | 35 | 35 | 4af433d162f7fd256282aa9b2dc4fbbcc7750a39 | bigcode/the-stack | train |
25461db6b410b27275ea00b4 | train | function | def vch2bn(s):
return mpi2bn(vch2mpi(s))
| def vch2bn(s):
| return mpi2bn(vch2mpi(s))
| return bytes(mpi2vch(bn2mpi(v)))
def vch2mpi(s):
r = struct.pack(b">I", len(s)) # size
r += s[::-1] # reverse string, converting LE->BE
return r
def vch2bn(s):
| 64 | 64 | 18 | 7 | 56 | MichaelHDesigns/HodlCash | test/functional/test_framework/bignum.py | Python | vch2bn | vch2bn | 95 | 96 | 95 | 95 | b900d22d931445e88007d48791c8e24cce38a99b | bigcode/the-stack | train |
f21ad1d59e8d9ff5f9a9650a | train | function | def bn2bin(v):
s = bytearray()
i = bn_bytes(v)
while i > 0:
s.append((v >> ((i-1) * 8)) & 0xff)
i -= 1
return s
| def bn2bin(v):
| s = bytearray()
i = bn_bytes(v)
while i > 0:
s.append((v >> ((i-1) * 8)) & 0xff)
i -= 1
return s
| copied from python-bitcoinlib.
"""
import struct
# generic big endian MPI format
def bn_bytes(v, have_ext=False):
ext = 0
if have_ext:
ext = 1
return ((v.bit_length()+7)//8) + ext
def bn2bin(v):
| 64 | 64 | 56 | 6 | 57 | MichaelHDesigns/HodlCash | test/functional/test_framework/bignum.py | Python | bn2bin | bn2bin | 21 | 27 | 21 | 21 | 7b33978b4d36565abfd98b8b2131e5ceb0392eda | bigcode/the-stack | train |
38241c30f94784ca445ad0b0 | train | class | class RootController(rest.RestController):
"""The controller in which the pecan wsgi app should be created with."""
v1 = v1_controller.V1Controller()
@wsme_pecan.wsexpose(wtypes.text)
def get(self):
# TODO(blogan): once a decision is made on how to do versions, do that
# here
re... | class RootController(rest.RestController):
| """The controller in which the pecan wsgi app should be created with."""
v1 = v1_controller.V1Controller()
@wsme_pecan.wsexpose(wtypes.text)
def get(self):
# TODO(blogan): once a decision is made on how to do versions, do that
# here
return {'versions': [{'status': 'CURRENT',
... | an
from pecan import rest
from wsme import types as wtypes
from wsmeext import pecan as wsme_pecan
from octavia.api.v1 import controllers as v1_controller
from octavia.api.v2 import controllers as v2_controller
class RootController(rest.RestController):
| 64 | 64 | 157 | 7 | 56 | BeaconFramework/Distributor | octavia/api/root_controller.py | Python | RootController | RootController | 24 | 38 | 24 | 24 | 8bcdc3373e92dc51326c415bc74258740a559872 | bigcode/the-stack | train |
9fbe3999bdd3f89045b82e5b | train | class | class Tests(unittest.TestCase):
TESTS = {
"1. Basics": [
{
"input": ["X.O", "XX.", "XOO"],
"answer": "X",
"explanation": [1, [0, 0.5], [3, 0.5]],
},
{
"input": ["OO.", "XOX", "XOX"],
"answer":... | class Tests(unittest.TestCase):
| TESTS = {
"1. Basics": [
{
"input": ["X.O", "XX.", "XOO"],
"answer": "X",
"explanation": [1, [0, 0.5], [3, 0.5]],
},
{
"input": ["OO.", "XOX", "XOX"],
"answer": "O",
"explanati... | import unittest
from x_o_referee import checkio
class Tests(unittest.TestCase):
| 18 | 256 | 964 | 6 | 11 | KenMercusLai/checkio | checkio/Home/Xs and Os Referee/test_x_o_referee.py | Python | Tests | Tests | 6 | 98 | 6 | 6 | 8b46457383493a4913532c475702675df50a802a | bigcode/the-stack | train |
3c9cc7253bce41c7ea49f533 | train | function | def _test_distrib_compute(device):
rank = idist.get_rank()
def _test(metric_device):
metric_device = torch.device(metric_device)
m = MedianRelativeAbsoluteError(device=metric_device)
torch.manual_seed(10 + rank)
size = 151
y_pred = torch.randint(1, 10, size=(size, 1), ... | def _test_distrib_compute(device):
| rank = idist.get_rank()
def _test(metric_device):
metric_device = torch.device(metric_device)
m = MedianRelativeAbsoluteError(device=metric_device)
torch.manual_seed(10 + rank)
size = 151
y_pred = torch.randint(1, 10, size=(size, 1), dtype=torch.double, device=device)
... | _batch = np_y_pred[idx : idx + batch_size]
return torch.from_numpy(y_pred_batch), torch.from_numpy(y_true_batch)
engine = Engine(update_fn)
m = MedianRelativeAbsoluteError()
m.attach(engine, "median_absolute_relative_error")
data = list(range(size // batch_size))
median_absolute_relative_... | 112 | 112 | 376 | 8 | 104 | louis-she/ignite | tests/ignite/contrib/metrics/regression/test_median_relative_absolute_error.py | Python | _test_distrib_compute | _test_distrib_compute | 110 | 150 | 110 | 110 | 543d21e4f8675cd9cb77f18ecd4aec8a45977da1 | bigcode/the-stack | train |
b3e62bb88f1d2d0a409ca126 | train | function | @pytest.mark.distributed
@pytest.mark.skipif(not idist.has_hvd_support, reason="Skip if no Horovod dist support")
@pytest.mark.skipif("WORLD_SIZE" in os.environ, reason="Skip if launched as multiproc")
def test_distrib_hvd(gloo_hvd_executor):
device = torch.device("cpu" if not torch.cuda.is_available() else "cuda"... | @pytest.mark.distributed
@pytest.mark.skipif(not idist.has_hvd_support, reason="Skip if no Horovod dist support")
@pytest.mark.skipif("WORLD_SIZE" in os.environ, reason="Skip if launched as multiproc")
def test_distrib_hvd(gloo_hvd_executor):
| device = torch.device("cpu" if not torch.cuda.is_available() else "cuda")
nproc = 4 if not torch.cuda.is_available() else torch.cuda.device_count()
gloo_hvd_executor(_test_distrib_compute, (device,), np=nproc, do_init=True)
gloo_hvd_executor(_test_distrib_integration, (device,), np=nproc, do_init=True)... | tegration(device)
@pytest.mark.distributed
@pytest.mark.skipif(not idist.has_hvd_support, reason="Skip if no Horovod dist support")
@pytest.mark.skipif("WORLD_SIZE" in os.environ, reason="Skip if launched as multiproc")
def test_distrib_hvd(gloo_hvd_executor):
| 64 | 64 | 146 | 61 | 3 | louis-she/ignite | tests/ignite/contrib/metrics/regression/test_median_relative_absolute_error.py | Python | test_distrib_hvd | test_distrib_hvd | 219 | 228 | 219 | 223 | 2db001480ec3336f6f161836ea2b9f3163d5c066 | bigcode/the-stack | train |
ff38a8c526146aa31273ce1e | train | function | @pytest.mark.distributed
@pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support")
def test_distrib_gloo_cpu_or_gpu(distributed_context_single_node_gloo):
device = idist.device()
_test_distrib_compute(device)
_test_distrib_integration(device)
| @pytest.mark.distributed
@pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support")
def test_distrib_gloo_cpu_or_gpu(distributed_context_single_node_gloo):
| device = idist.device()
_test_distrib_compute(device)
_test_distrib_integration(device)
| idist.device()
_test_distrib_compute(device)
_test_distrib_integration(device)
@pytest.mark.distributed
@pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support")
def test_distrib_gloo_cpu_or_gpu(distributed_context_single_node_gloo):
| 64 | 64 | 67 | 43 | 21 | louis-she/ignite | tests/ignite/contrib/metrics/regression/test_median_relative_absolute_error.py | Python | test_distrib_gloo_cpu_or_gpu | test_distrib_gloo_cpu_or_gpu | 210 | 216 | 210 | 213 | f9a6576480e341af9c20024dfb84397ab87b88a4 | bigcode/the-stack | train |
8ba65eaf03bd5ad9c39005e5 | train | function | def test_median_relative_absolute_error():
# See https://github.com/torch/torch7/pull/182
# For even number of elements, PyTorch returns middle element
# NumPy returns average of middle elements
# Size of dataset will be odd for these tests
size = 51
np_y_pred = np.random.rand(size)
np_y =... | def test_median_relative_absolute_error():
# See https://github.com/torch/torch7/pull/182
# For even number of elements, PyTorch returns middle element
# NumPy returns average of middle elements
# Size of dataset will be odd for these tests
| size = 51
np_y_pred = np.random.rand(size)
np_y = np.random.rand(size)
np_median_absolute_relative_error = np.median(np.abs(np_y - np_y_pred) / np.abs(np_y - np_y.mean()))
m = MedianRelativeAbsoluteError()
y_pred = torch.from_numpy(np_y_pred)
y = torch.from_numpy(np_y)
m.reset()
m.... | 2)))
def test_median_relative_absolute_error():
# See https://github.com/torch/torch7/pull/182
# For even number of elements, PyTorch returns middle element
# NumPy returns average of middle elements
# Size of dataset will be odd for these tests
| 63 | 64 | 172 | 61 | 2 | louis-she/ignite | tests/ignite/contrib/metrics/regression/test_median_relative_absolute_error.py | Python | test_median_relative_absolute_error | test_median_relative_absolute_error | 37 | 56 | 37 | 43 | 20fdf7af25296aa9b2a70982af60e042f4b22821 | bigcode/the-stack | train |
bfde70acb95a38b6a866878e | train | function | @pytest.mark.multinode_distributed
@pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support")
@pytest.mark.skipif("GPU_MULTINODE_DISTRIB" not in os.environ, reason="Skip if not multi-node distributed")
def test_multinode_distrib_nccl_gpu(distributed_context_multi_node_nccl):
de... | @pytest.mark.multinode_distributed
@pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support")
@pytest.mark.skipif("GPU_MULTINODE_DISTRIB" not in os.environ, reason="Skip if not multi-node distributed")
def test_multinode_distrib_nccl_gpu(distributed_context_multi_node_nccl):
| device = idist.device()
_test_distrib_compute(device)
_test_distrib_integration(device)
| @pytest.mark.multinode_distributed
@pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support")
@pytest.mark.skipif("GPU_MULTINODE_DISTRIB" not in os.environ, reason="Skip if not multi-node distributed")
def test_multinode_distrib_nccl_gpu(distributed_context_multi_node_nccl):
| 72 | 64 | 96 | 72 | 0 | louis-she/ignite | tests/ignite/contrib/metrics/regression/test_median_relative_absolute_error.py | Python | test_multinode_distrib_nccl_gpu | test_multinode_distrib_nccl_gpu | 241 | 248 | 241 | 245 | a7ce24d07570530edbceb0be43b9bc505e361bae | bigcode/the-stack | train |
105f6e497cff7c5a0202aaf3 | train | function | @pytest.mark.tpu
@pytest.mark.skipif("NUM_TPU_WORKERS" not in os.environ, reason="Skip if no NUM_TPU_WORKERS in env vars")
@pytest.mark.skipif(not idist.has_xla_support, reason="Skip if no PyTorch XLA package")
def test_distrib_xla_nprocs(xmp_executor):
n = int(os.environ["NUM_TPU_WORKERS"])
xmp_executor(_test_... | @pytest.mark.tpu
@pytest.mark.skipif("NUM_TPU_WORKERS" not in os.environ, reason="Skip if no NUM_TPU_WORKERS in env vars")
@pytest.mark.skipif(not idist.has_xla_support, reason="Skip if no PyTorch XLA package")
def test_distrib_xla_nprocs(xmp_executor):
| n = int(os.environ["NUM_TPU_WORKERS"])
xmp_executor(_test_distrib_xla_nprocs, args=(), nprocs=n)
| @pytest.mark.tpu
@pytest.mark.skipif("NUM_TPU_WORKERS" not in os.environ, reason="Skip if no NUM_TPU_WORKERS in env vars")
@pytest.mark.skipif(not idist.has_xla_support, reason="Skip if no PyTorch XLA package")
def test_distrib_xla_nprocs(xmp_executor):
| 71 | 64 | 106 | 71 | 0 | louis-she/ignite | tests/ignite/contrib/metrics/regression/test_median_relative_absolute_error.py | Python | test_distrib_xla_nprocs | test_distrib_xla_nprocs | 266 | 271 | 266 | 269 | 971f639bed2c25a500110b529a86ee6d3116f9b4 | bigcode/the-stack | train |
7a48da05e01cdd11d88e160c | train | function | def test_wrong_input_shapes():
m = MedianRelativeAbsoluteError()
with pytest.raises(ValueError, match=r"Predictions should be of shape"):
m.update((torch.rand(4, 1, 2), torch.rand(4, 1)))
with pytest.raises(ValueError, match=r"Targets should be of shape"):
m.update((torch.rand(4, 1), torch... | def test_wrong_input_shapes():
| m = MedianRelativeAbsoluteError()
with pytest.raises(ValueError, match=r"Predictions should be of shape"):
m.update((torch.rand(4, 1, 2), torch.rand(4, 1)))
with pytest.raises(ValueError, match=r"Targets should be of shape"):
m.update((torch.rand(4, 1), torch.rand(4, 1, 2)))
with pyte... | Engine
from ignite.exceptions import NotComputableError
def test_zero_sample():
m = MedianRelativeAbsoluteError()
with pytest.raises(
NotComputableError, match=r"EpochMetric must have at least one example before it can be computed"
):
m.compute()
def test_wrong_input_shapes():
| 64 | 64 | 166 | 6 | 58 | louis-she/ignite | tests/ignite/contrib/metrics/regression/test_median_relative_absolute_error.py | Python | test_wrong_input_shapes | test_wrong_input_shapes | 21 | 34 | 21 | 21 | b3c56bf4593a31943feb41aa7007119f5a5ff9bc | bigcode/the-stack | train |
bb6ec7173e3949cbeebffd3d | train | function | def test_median_relative_absolute_error_2():
np.random.seed(1)
size = 105
np_y_pred = np.random.rand(size, 1)
np_y = np.random.rand(size, 1)
np.random.shuffle(np_y)
np_median_absolute_relative_error = np.median(np.abs(np_y - np_y_pred) / np.abs(np_y - np_y.mean()))
m = MedianRelativeAbsolu... | def test_median_relative_absolute_error_2():
| np.random.seed(1)
size = 105
np_y_pred = np.random.rand(size, 1)
np_y = np.random.rand(size, 1)
np.random.shuffle(np_y)
np_median_absolute_relative_error = np.median(np.abs(np_y - np_y_pred) / np.abs(np_y - np_y.mean()))
m = MedianRelativeAbsoluteError()
y_pred = torch.from_numpy(np_y_p... | = MedianRelativeAbsoluteError()
y_pred = torch.from_numpy(np_y_pred)
y = torch.from_numpy(np_y)
m.reset()
m.update((y_pred, y))
assert np_median_absolute_relative_error == pytest.approx(m.compute())
def test_median_relative_absolute_error_2():
| 64 | 64 | 191 | 10 | 54 | louis-she/ignite | tests/ignite/contrib/metrics/regression/test_median_relative_absolute_error.py | Python | test_median_relative_absolute_error_2 | test_median_relative_absolute_error_2 | 59 | 79 | 59 | 60 | da8c507247a1af106f9c1dee9be47e757fa60420 | bigcode/the-stack | train |
42160798ce370f2793df6a8a | train | function | def test_zero_sample():
m = MedianRelativeAbsoluteError()
with pytest.raises(
NotComputableError, match=r"EpochMetric must have at least one example before it can be computed"
):
m.compute()
| def test_zero_sample():
| m = MedianRelativeAbsoluteError()
with pytest.raises(
NotComputableError, match=r"EpochMetric must have at least one example before it can be computed"
):
m.compute()
| import os
import numpy as np
import pytest
import torch
import ignite.distributed as idist
from ignite.contrib.metrics.regression import MedianRelativeAbsoluteError
from ignite.engine import Engine
from ignite.exceptions import NotComputableError
def test_zero_sample():
| 54 | 64 | 47 | 5 | 48 | louis-she/ignite | tests/ignite/contrib/metrics/regression/test_median_relative_absolute_error.py | Python | test_zero_sample | test_zero_sample | 13 | 18 | 13 | 13 | b0e1607269aeb4e9e1a691fdd717b0febe75e041 | bigcode/the-stack | train |
ed77f66ca485cbfe1abdfce2 | train | function | @pytest.mark.multinode_distributed
@pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support")
@pytest.mark.skipif("MULTINODE_DISTRIB" not in os.environ, reason="Skip if not multi-node distributed")
def test_multinode_distrib_gloo_cpu_or_gpu(distributed_context_multi_node_gloo):
... | @pytest.mark.multinode_distributed
@pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support")
@pytest.mark.skipif("MULTINODE_DISTRIB" not in os.environ, reason="Skip if not multi-node distributed")
def test_multinode_distrib_gloo_cpu_or_gpu(distributed_context_multi_node_gloo):
| device = idist.device()
_test_distrib_compute(device)
_test_distrib_integration(device)
| @pytest.mark.multinode_distributed
@pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support")
@pytest.mark.skipif("MULTINODE_DISTRIB" not in os.environ, reason="Skip if not multi-node distributed")
def test_multinode_distrib_gloo_cpu_or_gpu(distributed_context_multi_node_gloo):
| 73 | 64 | 97 | 73 | 0 | louis-she/ignite | tests/ignite/contrib/metrics/regression/test_median_relative_absolute_error.py | Python | test_multinode_distrib_gloo_cpu_or_gpu | test_multinode_distrib_gloo_cpu_or_gpu | 231 | 238 | 231 | 235 | cdbcd8cd2aa1c6801dedae8f7a3569b5cf89f26c | bigcode/the-stack | train |
ef09ef5e481a24da95537969 | train | function | def _test_distrib_integration(device):
rank = idist.get_rank()
torch.manual_seed(12)
def _test(n_epochs, metric_device):
metric_device = torch.device(metric_device)
n_iters = 80
size = 151
y_true = torch.rand(size=(size,)).to(device)
y_preds = torch.rand(size=(size,... | def _test_distrib_integration(device):
| rank = idist.get_rank()
torch.manual_seed(12)
def _test(n_epochs, metric_device):
metric_device = torch.device(metric_device)
n_iters = 80
size = 151
y_true = torch.rand(size=(size,)).to(device)
y_preds = torch.rand(size=(size,)).to(device)
def update(engine... | 0, e[0], axis=0)
np_res_prepend = np.median(e_prepend)
assert pytest.approx(res) == np_res_prepend
else:
np_res = np.median(e)
assert pytest.approx(res) == np_res
for _ in range(3):
_test("cpu")
if device.type != "xla":
_test(idis... | 99 | 99 | 333 | 9 | 90 | louis-she/ignite | tests/ignite/contrib/metrics/regression/test_median_relative_absolute_error.py | Python | _test_distrib_integration | _test_distrib_integration | 153 | 197 | 153 | 154 | 30ee219606d94f70cd53f4f35ee5bf723195209f | bigcode/the-stack | train |
7fdc1a9942ebf189cee583e5 | train | function | @pytest.mark.tpu
@pytest.mark.skipif("NUM_TPU_WORKERS" in os.environ, reason="Skip if NUM_TPU_WORKERS is in env vars")
@pytest.mark.skipif(not idist.has_xla_support, reason="Skip if no PyTorch XLA package")
def test_distrib_single_device_xla():
device = idist.device()
_test_distrib_compute(device)
_test_dis... | @pytest.mark.tpu
@pytest.mark.skipif("NUM_TPU_WORKERS" in os.environ, reason="Skip if NUM_TPU_WORKERS is in env vars")
@pytest.mark.skipif(not idist.has_xla_support, reason="Skip if no PyTorch XLA package")
def test_distrib_single_device_xla():
| device = idist.device()
_test_distrib_compute(device)
_test_distrib_integration(device)
| @pytest.mark.tpu
@pytest.mark.skipif("NUM_TPU_WORKERS" in os.environ, reason="Skip if NUM_TPU_WORKERS is in env vars")
@pytest.mark.skipif(not idist.has_xla_support, reason="Skip if no PyTorch XLA package")
def test_distrib_single_device_xla():
| 66 | 64 | 90 | 66 | 0 | louis-she/ignite | tests/ignite/contrib/metrics/regression/test_median_relative_absolute_error.py | Python | test_distrib_single_device_xla | test_distrib_single_device_xla | 251 | 257 | 251 | 254 | ca541986e0ef39b36764710a99e04b7a6800771b | bigcode/the-stack | train |
36d07045c643aec78e9d8377 | train | function | def test_integration_median_relative_absolute_error_with_output_transform():
np.random.seed(1)
size = 105
np_y_pred = np.random.rand(size, 1)
np_y = np.random.rand(size, 1)
np.random.shuffle(np_y)
np_median_absolute_relative_error = np.median(np.abs(np_y - np_y_pred) / np.abs(np_y - np_y.mean()... | def test_integration_median_relative_absolute_error_with_output_transform():
| np.random.seed(1)
size = 105
np_y_pred = np.random.rand(size, 1)
np_y = np.random.rand(size, 1)
np.random.shuffle(np_y)
np_median_absolute_relative_error = np.median(np.abs(np_y - np_y_pred) / np.abs(np_y - np_y.mean()))
batch_size = 15
def update_fn(engine, batch):
idx = (engi... | + 1
for i in range(n_iters + 1):
idx = i * batch_size
m.update((y_pred[idx : idx + batch_size], y[idx : idx + batch_size]))
assert np_median_absolute_relative_error == pytest.approx(m.compute())
def test_integration_median_relative_absolute_error_with_output_transform():
| 72 | 72 | 240 | 13 | 59 | louis-she/ignite | tests/ignite/contrib/metrics/regression/test_median_relative_absolute_error.py | Python | test_integration_median_relative_absolute_error_with_output_transform | test_integration_median_relative_absolute_error_with_output_transform | 82 | 107 | 82 | 83 | f05fa5af58c50d795951da81240af67aea6a0952 | bigcode/the-stack | train |
35981cb9127f415ebb460820 | train | function | def _test_distrib_xla_nprocs(index):
device = idist.device()
_test_distrib_compute(device)
_test_distrib_integration(device)
| def _test_distrib_xla_nprocs(index):
| device = idist.device()
_test_distrib_compute(device)
_test_distrib_integration(device)
| (not idist.has_xla_support, reason="Skip if no PyTorch XLA package")
def test_distrib_single_device_xla():
device = idist.device()
_test_distrib_compute(device)
_test_distrib_integration(device)
def _test_distrib_xla_nprocs(index):
| 64 | 64 | 36 | 12 | 52 | louis-she/ignite | tests/ignite/contrib/metrics/regression/test_median_relative_absolute_error.py | Python | _test_distrib_xla_nprocs | _test_distrib_xla_nprocs | 260 | 263 | 260 | 260 | 6cad04cfb823eb42be87243e208221879e5a5ec2 | bigcode/the-stack | train |
10bec3697f07fde23b3b4829 | train | function | @pytest.mark.distributed
@pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support")
@pytest.mark.skipif(torch.cuda.device_count() < 1, reason="Skip if no GPU")
def test_distrib_nccl_gpu(distributed_context_single_node_nccl):
device = idist.device()
_test_distrib_compute(dev... | @pytest.mark.distributed
@pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support")
@pytest.mark.skipif(torch.cuda.device_count() < 1, reason="Skip if no GPU")
def test_distrib_nccl_gpu(distributed_context_single_node_nccl):
| device = idist.device()
_test_distrib_compute(device)
_test_distrib_integration(device)
| metric_device)
@pytest.mark.distributed
@pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support")
@pytest.mark.skipif(torch.cuda.device_count() < 1, reason="Skip if no GPU")
def test_distrib_nccl_gpu(distributed_context_single_node_nccl):
| 64 | 64 | 85 | 61 | 3 | louis-she/ignite | tests/ignite/contrib/metrics/regression/test_median_relative_absolute_error.py | Python | test_distrib_nccl_gpu | test_distrib_nccl_gpu | 200 | 207 | 200 | 204 | f8284193099fe7eabb51d80b44532c330ab1f979 | bigcode/the-stack | train |
ffad91fc8b1978b52d55075c | train | function | def validate_linkerd():
"""
Validate Linkerd by deploying emojivoto.
"""
if platform.machine() != 'x86_64':
print("Linkerd tests are only relevant in x86 architectures")
return
wait_for_installation()
wait_for_pod_state("", "linkerd", "running", label="linkerd.io/control-plane-c... | def validate_linkerd():
| """
Validate Linkerd by deploying emojivoto.
"""
if platform.machine() != 'x86_64':
print("Linkerd tests are only relevant in x86 architectures")
return
wait_for_installation()
wait_for_pod_state("", "linkerd", "running", label="linkerd.io/control-plane-component=controller", ti... | 30
while attempt > 0:
try:
output = kubectl("get ingress")
if "simplest-query" in output:
break
except:
pass
time.sleep(2)
attempt -= 1
assert attempt > 0
def validate_linkerd():
| 64 | 64 | 141 | 5 | 58 | greenyouse/microk8s | tests/validators.py | Python | validate_linkerd | validate_linkerd | 325 | 337 | 325 | 325 | 4404274c9d05002b3459006fe8fd9a9681995f00 | bigcode/the-stack | train |
507a297bb28293e8ea3e1548 | train | function | def validate_istio():
"""
Validate istio by deploying the bookinfo app.
"""
if platform.machine() != 'x86_64':
print("Istio tests are only relevant in x86 architectures")
return
wait_for_installation()
istio_services = [
"citadel",
"egressgateway",
"galle... | def validate_istio():
| """
Validate istio by deploying the bookinfo app.
"""
if platform.machine() != 'x86_64':
print("Istio tests are only relevant in x86 architectures")
return
wait_for_installation()
istio_services = [
"citadel",
"egressgateway",
"galley",
"ingressga... | ))
time.sleep(10)
kubectl("apply -f {}".format(manifest))
wait_for_pod_state("cuda-vector-add", "default", "terminated")
result = kubectl("logs pod/cuda-vector-add")
assert "PASSED" in result
def validate_istio():
| 64 | 64 | 198 | 6 | 57 | greenyouse/microk8s | tests/validators.py | Python | validate_istio | validate_istio | 166 | 189 | 166 | 166 | 3140d49af83de35e7f06c2e6a2dab1b868a44027 | bigcode/the-stack | train |
8518bca567d15bfc7bbf7417 | train | function | def validate_knative():
"""
Validate Knative by deploying the helloworld-go app.
"""
if platform.machine() != 'x86_64':
print("Knative tests are only relevant in x86 architectures")
return
wait_for_installation()
knative_services = [
"activator",
"autoscaler",
... | def validate_knative():
| """
Validate Knative by deploying the helloworld-go app.
"""
if platform.machine() != 'x86_64':
print("Knative tests are only relevant in x86 architectures")
return
wait_for_installation()
knative_services = [
"activator",
"autoscaler",
"controller",
... | manifest = os.path.join(here, "templates", "bookinfo.yaml")
kubectl("apply -f {}".format(manifest))
wait_for_pod_state("", "default", "running", label="app=details")
kubectl("delete -f {}".format(manifest))
def validate_knative():
| 64 | 64 | 191 | 5 | 59 | greenyouse/microk8s | tests/validators.py | Python | validate_knative | validate_knative | 192 | 213 | 192 | 192 | e11fe0171dcffc2df4b3c09068820c0a2be441e8 | bigcode/the-stack | train |
833a64bc106bba6887bf2aa5 | train | function | def validate_cilium():
"""
Validate cilium by deploying the bookinfo app.
"""
if platform.machine() != 'x86_64':
print("Cilium tests are only relevant in x86 architectures")
return
wait_for_installation()
wait_for_pod_state("", "kube-system", "running", label="k8s-app=cilium")
... | def validate_cilium():
| """
Validate cilium by deploying the bookinfo app.
"""
if platform.machine() != 'x86_64':
print("Cilium tests are only relevant in x86 architectures")
return
wait_for_installation()
wait_for_pod_state("", "kube-system", "running", label="k8s-app=cilium")
here = os.path.dirn... | err_out: If command fails and this is the output, return.
Returns: the cilium response in a string
"""
cmd = '/snap/bin/microk8s.cilium ' + cmd
return run_until_success(cmd, timeout_insec, err_out)
def validate_cilium():
| 64 | 64 | 175 | 5 | 59 | greenyouse/microk8s | tests/validators.py | Python | validate_cilium | validate_cilium | 370 | 387 | 370 | 370 | c47991e65a77c02725939b293f75c28b41de6939 | bigcode/the-stack | train |
98a539732d5627a7b2850648 | train | function | def validate_gpu():
"""
Validate gpu by trying a cuda-add.
"""
if platform.machine() != 'x86_64':
print("GPU tests are only relevant in x86 architectures")
return
wait_for_pod_state("", "kube-system", "running", label="name=nvidia-device-plugin-ds")
here = os.path.dirname(os.pat... | def validate_gpu():
| """
Validate gpu by trying a cuda-add.
"""
if platform.machine() != 'x86_64':
print("GPU tests are only relevant in x86 architectures")
return
wait_for_pod_state("", "kube-system", "running", label="name=nvidia-device-plugin-ds")
here = os.path.dirname(os.path.abspath(__file__))... | _code == 200 and "microbot.png" in resp.content.decode("utf-8"):
service_ok = True
break
except:
time.sleep(5)
attempt -= 1
assert service_ok
kubectl("delete -f {}".format(manifest))
def validate_gpu():
| 64 | 64 | 196 | 4 | 60 | greenyouse/microk8s | tests/validators.py | Python | validate_gpu | validate_gpu | 142 | 163 | 142 | 142 | 6fde5614454eb5cfac19abb01fa96571d9000d5c | bigcode/the-stack | train |
802036c6d7aa03647b38daa2 | train | function | def validate_prometheus():
"""
Validate the prometheus operator
"""
if platform.machine() != 'x86_64':
print("Prometheus tests are only relevant in x86 architectures")
return
wait_for_pod_state("prometheus-k8s-0", "monitoring", "running", timeout_insec=1200)
wait_for_pod_state("... | def validate_prometheus():
| """
Validate the prometheus operator
"""
if platform.machine() != 'x86_64':
print("Prometheus tests are only relevant in x86 architectures")
return
wait_for_pod_state("prometheus-k8s-0", "monitoring", "running", timeout_insec=1200)
wait_for_pod_state("alertmanager-main-0", "moni... | kubectl("get --raw /apis/metrics.k8s.io/v1beta1/pods")
if "PodMetricsList" in output:
break
except:
pass
time.sleep(10)
attempt -= 1
assert attempt > 0
def validate_prometheus():
| 64 | 64 | 101 | 5 | 58 | greenyouse/microk8s | tests/validators.py | Python | validate_prometheus | validate_prometheus | 277 | 286 | 277 | 277 | 75cb6c9b3c5561776fb1df3141dd6842f1199e08 | bigcode/the-stack | train |
ac6745bcf7bde9c0a55e956e | train | function | def validate_jaeger():
"""
Validate the jaeger operator
"""
if platform.machine() != 'x86_64':
print("Jaeger tests are only relevant in x86 architectures")
return
wait_for_pod_state("", "default", "running", label="name=jaeger-operator")
attempt = 30
while attempt > 0:
... | def validate_jaeger():
| """
Validate the jaeger operator
"""
if platform.machine() != 'x86_64':
print("Jaeger tests are only relevant in x86 architectures")
return
wait_for_pod_state("", "default", "running", label="name=jaeger-operator")
attempt = 30
while attempt > 0:
try:
out... | ", "running")
wait_for_pod_state("", "kube-system", "running", label="k8s-app=fluentd-es")
wait_for_pod_state("", "kube-system", "running", label="k8s-app=kibana-logging")
def validate_jaeger():
| 64 | 64 | 131 | 6 | 58 | greenyouse/microk8s | tests/validators.py | Python | validate_jaeger | validate_jaeger | 302 | 322 | 302 | 302 | 4d32335d9c40b989caee8793b93c39588db9ef6a | bigcode/the-stack | train |
c4746022895f84a23bc2b0bd | train | function | def validate_forward():
"""
Validate ports are forwarded
"""
here = os.path.dirname(os.path.abspath(__file__))
manifest = os.path.join(here, "templates", "nginx-pod.yaml")
kubectl("apply -f {}".format(manifest))
wait_for_pod_state("", "default", "running", label="app=nginx")
os.system('k... | def validate_forward():
| """
Validate ports are forwarded
"""
here = os.path.dirname(os.path.abspath(__file__))
manifest = os.path.join(here, "templates", "nginx-pod.yaml")
kubectl("apply -f {}".format(manifest))
wait_for_pod_state("", "default", "running", label="app=nginx")
os.system('killall kubectl')
os.... | f {}".format(manifest))
wait_for_pod_state("busybox", "default", "running")
output = kubectl("describe po busybox")
assert "localhost:32000/my-busybox" in output
kubectl("delete -f {}".format(manifest))
def validate_forward():
| 64 | 64 | 180 | 4 | 60 | greenyouse/microk8s | tests/validators.py | Python | validate_forward | validate_forward | 234 | 255 | 234 | 234 | 6d7c608a9ff08fee0fcc784bffa648c93095945d | bigcode/the-stack | train |
05afcfe6b13edf2c1502a5e9 | train | function | def validate_ingress():
"""
Validate ingress by creating a ingress rule.
"""
daemonset = kubectl("get ds")
if "nginx-ingress-microk8s-controller" in daemonset:
wait_for_pod_state("", "default", "running", label="app=default-http-backend")
wait_for_pod_state("", "default", "running", ... | def validate_ingress():
| """
Validate ingress by creating a ingress rule.
"""
daemonset = kubectl("get ds")
if "nginx-ingress-microk8s-controller" in daemonset:
wait_for_pod_state("", "default", "running", label="app=default-http-backend")
wait_for_pod_state("", "default", "running", label="name=nginx-ingres... | apply -f {}".format(manifest))
wait_for_pod_state("hostpath-test-pod", "default", "running")
attempt = 50
while attempt >= 0:
output = kubectl("get pvc")
if "Bound" in output:
break
time.sleep(2)
attempt -= 1
# Make sure the test pod writes data sto the stor... | 169 | 169 | 566 | 5 | 164 | greenyouse/microk8s | tests/validators.py | Python | validate_ingress | validate_ingress | 80 | 139 | 80 | 80 | c69efac3c15ef0449fa5c47cbed3b839a142ae24 | bigcode/the-stack | train |
6e696217e023a4db9021c009 | train | function | def cilium(cmd, timeout_insec=300, err_out=None):
"""
Do a cilium <cmd>
Args:
cmd: left part of cilium <left_part> command
timeout_insec: timeout for this job
err_out: If command fails and this is the output, return.
Returns: the cilium response in a string
"""
cmd = '/s... | def cilium(cmd, timeout_insec=300, err_out=None):
| """
Do a cilium <cmd>
Args:
cmd: left part of cilium <left_part> command
timeout_insec: timeout for this job
err_out: If command fails and this is the output, return.
Returns: the cilium response in a string
"""
cmd = '/snap/bin/microk8s.cilium ' + cmd
return run_unt... | :default view pod", err_out='no')
assert "no" in output
output = kubectl("auth can-i --as=admin --as-group=system:masters view pod")
assert "yes" in output
def cilium(cmd, timeout_insec=300, err_out=None):
| 64 | 64 | 111 | 15 | 48 | greenyouse/microk8s | tests/validators.py | Python | cilium | cilium | 356 | 367 | 356 | 356 | 45ed07035478112c69d58d7bc4f4e2673fde59a0 | bigcode/the-stack | train |
076e266027fe7fd1b59e74cc | train | function | def validate_registry():
"""
Validate the private registry.
"""
wait_for_pod_state("", "container-registry", "running", label="app=registry")
docker("pull busybox")
docker("tag busybox localhost:32000/my-busybox")
docker("push localhost:32000/my-busybox")
here = os.path.dirname(os.path.... | def validate_registry():
| """
Validate the private registry.
"""
wait_for_pod_state("", "container-registry", "running", label="app=registry")
docker("pull busybox")
docker("tag busybox localhost:32000/my-busybox")
docker("push localhost:32000/my-busybox")
here = os.path.dirname(os.path.abspath(__file__))
ma... | templates", "knative-helloworld.yaml")
kubectl("apply -f {}".format(manifest))
wait_for_pod_state("", "default", "running", label="serving.knative.dev/service=helloworld-go")
kubectl("delete -f {}".format(manifest))
def validate_registry():
| 64 | 64 | 165 | 4 | 60 | greenyouse/microk8s | tests/validators.py | Python | validate_registry | validate_registry | 216 | 231 | 216 | 216 | 11cf27612557a61e4af7cd676c28571a82d37906 | bigcode/the-stack | train |
3579a41002b98e029967d9ca | train | function | def validate_dns_dashboard():
"""
Validate the dashboard addon by looking at the grafana URL.
Validate DNS by starting a busy box and nslookuping the kubernetes default service.
"""
wait_for_pod_state("", "kube-system", "running", label="k8s-app=influxGrafana")
cluster_info = kubectl("cluster-in... | def validate_dns_dashboard():
| """
Validate the dashboard addon by looking at the grafana URL.
Validate DNS by starting a busy box and nslookuping the kubernetes default service.
"""
wait_for_pod_state("", "kube-system", "running", label="k8s-app=influxGrafana")
cluster_info = kubectl("cluster-info")
# Cluster info output... | import time
import os
import re
import requests
import platform
from utils import (
kubectl,
wait_for_pod_state,
kubectl_get,
wait_for_installation,
docker,
update_yaml_with_arch,
run_until_success,
)
def validate_dns_dashboard():
| 61 | 100 | 334 | 5 | 56 | greenyouse/microk8s | tests/validators.py | Python | validate_dns_dashboard | validate_dns_dashboard | 18 | 47 | 18 | 18 | 34c2c8126ee478018133e431189a803e9e97d8fb | bigcode/the-stack | train |
128cda37fed3ca250576db1d | train | function | def validate_storage():
"""
Validate storage by creating a PVC.
"""
wait_for_pod_state("", "kube-system", "running", label="k8s-app=hostpath-provisioner")
here = os.path.dirname(os.path.abspath(__file__))
manifest = os.path.join(here, "templates", "pvc.yaml")
kubectl("apply -f {}".format(man... | def validate_storage():
| """
Validate storage by creating a PVC.
"""
wait_for_pod_state("", "kube-system", "running", label="k8s-app=hostpath-provisioner")
here = os.path.dirname(os.path.abspath(__file__))
manifest = os.path.join(here, "templates", "pvc.yaml")
kubectl("apply -f {}".format(manifest))
wait_for_pod... | , verify=False)
if (resp.status_code == 200 and grafana_url.startswith('http://')) or \
(resp.status_code == 401 and grafana_url.startswith('https://')):
break
time.sleep(2)
attempt -= 1
assert resp.status_code in [200, 401]
def validate_storage():
| 72 | 72 | 241 | 4 | 68 | greenyouse/microk8s | tests/validators.py | Python | validate_storage | validate_storage | 50 | 77 | 50 | 50 | 03145eed76c5e0f4f4eba630da764a6781b092b4 | bigcode/the-stack | train |
8d9b82e82904c26b046c3e61 | train | function | def validate_metrics_server():
"""
Validate the metrics server works
"""
wait_for_pod_state("", "kube-system", "running", label="k8s-app=metrics-server")
attempt = 30
while attempt > 0:
try:
output = kubectl("get --raw /apis/metrics.k8s.io/v1beta1/pods")
if "PodMe... | def validate_metrics_server():
| """
Validate the metrics server works
"""
wait_for_pod_state("", "kube-system", "running", label="k8s-app=metrics-server")
attempt = 30
while attempt > 0:
try:
output = kubectl("get --raw /apis/metrics.k8s.io/v1beta1/pods")
if "PodMetricsList" in output:
... | >= 0:
try:
resp = requests.get("http://localhost:5123")
if resp.status_code == 200:
break
except:
pass
attempt -= 1
time.sleep(2)
assert resp.status_code == 200
def validate_metrics_server():
| 64 | 64 | 119 | 5 | 58 | greenyouse/microk8s | tests/validators.py | Python | validate_metrics_server | validate_metrics_server | 258 | 274 | 258 | 258 | 877df6350f504ab68cd02abd554056e0a8e175d1 | bigcode/the-stack | train |
5666b879d536799a6a1bfa12 | train | function | def validate_fluentd():
"""
Validate fluentd
"""
if platform.machine() != 'x86_64':
print("Fluentd tests are only relevant in x86 architectures")
return
wait_for_pod_state("elasticsearch-logging-0", "kube-system", "running")
wait_for_pod_state("", "kube-system", "running", label... | def validate_fluentd():
| """
Validate fluentd
"""
if platform.machine() != 'x86_64':
print("Fluentd tests are only relevant in x86 architectures")
return
wait_for_pod_state("elasticsearch-logging-0", "kube-system", "running")
wait_for_pod_state("", "kube-system", "running", label="k8s-app=fluentd-es")
... | return
wait_for_pod_state("prometheus-k8s-0", "monitoring", "running", timeout_insec=1200)
wait_for_pod_state("alertmanager-main-0", "monitoring", "running", timeout_insec=1200)
def validate_fluentd():
| 64 | 64 | 121 | 6 | 58 | greenyouse/microk8s | tests/validators.py | Python | validate_fluentd | validate_fluentd | 289 | 299 | 289 | 289 | 110508ee164e4388bc5f2c2e5457495eece5d27a | bigcode/the-stack | train |
1d2c9188a5683da9b50d8134 | train | function | def validate_rbac():
"""
Validate RBAC is actually on
"""
output = kubectl("auth can-i --as=system:serviceaccount:default:default view pod", err_out='no')
assert "no" in output
output = kubectl("auth can-i --as=admin --as-group=system:masters view pod")
assert "yes" in output
| def validate_rbac():
| """
Validate RBAC is actually on
"""
output = kubectl("auth can-i --as=system:serviceaccount:default:default view pod", err_out='no')
assert "no" in output
output = kubectl("auth can-i --as=admin --as-group=system:masters view pod")
assert "yes" in output
| .yaml")
#kubectl("apply -f {}".format(manifest))
#wait_for_pod_state("", "emojivoto", "running", label="app=emoji-svc", timeout_insec=600)
#kubectl("delete -f {}".format(manifest))
def validate_rbac():
| 64 | 64 | 84 | 5 | 59 | greenyouse/microk8s | tests/validators.py | Python | validate_rbac | validate_rbac | 346 | 353 | 346 | 346 | 1517efe73d469dac822a98d2b558c2ea6ec8d8ea | bigcode/the-stack | train |
dbcd1c2d4acf27fc34e60e4d | train | class | class RunMixin: # pylint: disable=too-few-public-methods
"""Class providing run() method for ContainersManager."""
def run(
self,
image: Union[str, Image],
command: Union[str, List[str], None] = None,
stdout=True,
stderr=False,
remove: bool = False,
**kw... | class RunMixin: # pylint: disable=too-few-public-methods
| """Class providing run() method for ContainersManager."""
def run(
self,
image: Union[str, Image],
command: Union[str, List[str], None] = None,
stdout=True,
stderr=False,
remove: bool = False,
**kwargs,
) -> Union[Container, Union[Generator[str, None,... | """Mixin to provide Container run() method."""
import logging
from contextlib import suppress
from typing import Generator, Iterator, List, Union
from podman.domain.containers import Container
from podman.domain.images import Image
from podman.errors import ContainerError, ImageNotFound
logger = logging.getLogger("p... | 86 | 179 | 599 | 17 | 69 | kevinwylder/podman-py | podman/domain/containers_run.py | Python | RunMixin | RunMixin | 14 | 92 | 14 | 14 | 5a8e40845fa12f0dbbb06f0a840e19f1af452e38 | bigcode/the-stack | train |
79a1b94d154c7a0af20394e2 | train | class | class TelemetryTest(unittest.TestCase):
def test_scrubbing(self):
# tests the scrubbing of parameters
text1 = 'this is a --secret value wut wut'
text2 = 'this has NO secret value'
text3 = 'this is -my value -is alice --bob knows'
text4 = 'this is -my value secrets secrets2 -... | class TelemetryTest(unittest.TestCase):
| def test_scrubbing(self):
# tests the scrubbing of parameters
text1 = 'this is a --secret value wut wut'
text2 = 'this has NO secret value'
text3 = 'this is -my value -is alice --bob knows'
text4 = 'this is -my value secrets secrets2 -is alice --bob knows'
scrub_val ... | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | 58 | 64 | 211 | 8 | 49 | v-Ajnava/azure-cli | src/command_modules/azure-cli-interactive/azure/cli/command_modules/interactive/tests/test_telemetry.py | Python | TelemetryTest | TelemetryTest | 10 | 26 | 10 | 11 | 640a040000b3d85f7534c2908af703b48807115b | bigcode/the-stack | train |
6dc3f126430ce3ae79dfc918 | train | function | def add_root_segment(powerline):
root_indicators = {
'bash': ' \\$ ',
'zsh': ' %# ',
'bare': '\n$',
}
bg = Color.CMD_PASSED_BG
fg = Color.CMD_PASSED_FG
if powerline.args.prev_error != 0:
fg = Color.CMD_FAILED_FG
bg = Color.CMD_FAILED_BG
powerline.append(ro... | def add_root_segment(powerline):
| root_indicators = {
'bash': ' \\$ ',
'zsh': ' %# ',
'bare': '\n$',
}
bg = Color.CMD_PASSED_BG
fg = Color.CMD_PASSED_FG
if powerline.args.prev_error != 0:
fg = Color.CMD_FAILED_FG
bg = Color.CMD_FAILED_BG
powerline.append(root_indicators[powerline.args.shel... | def add_root_segment(powerline):
| 7 | 64 | 109 | 7 | 0 | Coopeh/powerline-shell | segments/root.py | Python | add_root_segment | add_root_segment | 1 | 12 | 1 | 1 | 24fbd2206f040d3a3ddb76c814c3ee6bfd4960fd | bigcode/the-stack | train |
febc4cfc9889a19c4a71a598 | train | class | class PolicyV1beta1PodSecurityPolicy(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute... | class PolicyV1beta1PodSecurityPolicy(object):
| """
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is ... | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.14.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteri... | 87 | 256 | 1,421 | 11 | 75 | splunkenizer/splunk_as_a_service_app | lib/kubernetes/client/models/policy_v1beta1_pod_security_policy.py | Python | PolicyV1beta1PodSecurityPolicy | PolicyV1beta1PodSecurityPolicy | 19 | 210 | 19 | 19 | 0cfe420ffab0eb24b45b157112a1c00ad96de182 | bigcode/the-stack | train |
e6f9cab0542373db4501c95a | train | function | def offline(pool_name, *vdevs, **kwargs):
'''
.. versionadded:: 2015.5.0
Ensure that the specified devices are offline
.. warning::
By default, the OFFLINE state is persistent. The device remains offline when
the system is rebooted. To temporarily take a device offline, use ``temporar... | def offline(pool_name, *vdevs, **kwargs):
| '''
.. versionadded:: 2015.5.0
Ensure that the specified devices are offline
.. warning::
By default, the OFFLINE state is persistent. The device remains offline when
the system is rebooted. To temporarily take a device offline, use ``temporary=True``.
CLI Example:
.. code-b... | return ret
dlist.append(vdev)
devs = ' '.join(dlist)
zpool = _check_zpool()
cmd = '{0} online {1} {2}'.format(zpool, pool_name, devs)
# Bring all specified devices online
res = __salt__['cmd.run'](cmd)
if res:
ret['Error'] = {}
ret['Error']['Message'] = 'Failure bringi... | 150 | 150 | 503 | 13 | 136 | kev009/salt | salt/modules/zpool.py | Python | offline | offline | 558 | 616 | 558 | 558 | ca8d9a51d60942b64acc13ffc6fa4c6d9c50087f | bigcode/the-stack | train |
0412df96d64d5993a7bf29df | train | function | def list_():
'''
.. versionadded:: 2015.5.0
Return a list of all pools in the system with health status and space usage
CLI Example:
.. code-block:: bash
salt '*' zpool.list
'''
zpool = _check_zpool()
cmd = [zpool, 'list']
res = __salt__['cmd.run'](cmd, python_shell=False... | def list_():
| '''
.. versionadded:: 2015.5.0
Return a list of all pools in the system with health status and space usage
CLI Example:
.. code-block:: bash
salt '*' zpool.list
'''
zpool = _check_zpool()
cmd = [zpool, 'list']
res = __salt__['cmd.run'](cmd, python_shell=False)
pool_li... | ostat myzpool
'''
zpool = _check_zpool()
cmd = [zpool, 'iostat', '-v', name]
res = __salt__['cmd.run'](cmd, python_shell=False)
ret = res.splitlines()
return ret
def list_():
| 64 | 64 | 114 | 4 | 59 | kev009/salt | salt/modules/zpool.py | Python | list_ | list_ | 85 | 101 | 85 | 85 | 8cfcbbb9e37334128bbea52a334cc7a57e4e4414 | bigcode/the-stack | train |
36ac61ad628479a67a12a077 | train | function | def destroy(pool_name):
'''
Destroys a storage pool
CLI Example:
.. code-block:: bash
salt '*' zpool.destroy myzpool
'''
ret = {}
if not exists(pool_name):
ret['Error'] = 'Storage pool {0} does not exist'.format(pool_name)
return ret
else:
zpool = _chec... | def destroy(pool_name):
| '''
Destroys a storage pool
CLI Example:
.. code-block:: bash
salt '*' zpool.destroy myzpool
'''
ret = {}
if not exists(pool_name):
ret['Error'] = 'Storage pool {0} does not exist'.format(pool_name)
return ret
else:
zpool = _check_zpool()
cmd = ... | = _check_zpool()
cmd = '{0} list {1}'.format(zpool, pool_name)
res = __salt__['cmd.run'](cmd, ignore_retcode=True)
if "no such pool" in res:
return None
return True
def destroy(pool_name):
| 64 | 64 | 134 | 5 | 58 | kev009/salt | salt/modules/zpool.py | Python | destroy | destroy | 144 | 164 | 144 | 144 | 6f133a8660364bf9f788895b581a03025c92c389 | bigcode/the-stack | train |
5a88257d629c6b1493cfde8e | train | function | def replace(pool_name, old, new):
'''
Replaces old device with new device.
CLI Example:
.. code-block:: bash
salt '*' zpool.replace myzpool /path/to/vdev1 /path/to/vdev2
'''
ret = {}
# Make sure pools there
if not exists(pool_name):
ret['Error'] = '{0}: pool does not e... | def replace(pool_name, old, new):
| '''
Replaces old device with new device.
CLI Example:
.. code-block:: bash
salt '*' zpool.replace myzpool /path/to/vdev1 /path/to/vdev2
'''
ret = {}
# Make sure pools there
if not exists(pool_name):
ret['Error'] = '{0}: pool does not exists.'.format(pool_name)
... | )
res = __salt__['cmd.run'](cmd, python_shell=False)
if 'errors' not in res.splitlines():
ret['Added'] = '{0} to {1}'.format(devs, pool_name)
return ret
ret['Error'] = 'Something went wrong when adding {0} to {1}'.format(devs, pool_name)
def replace(pool_name, old, new):
| 88 | 88 | 295 | 9 | 79 | kev009/salt | salt/modules/zpool.py | Python | replace | replace | 329 | 365 | 329 | 329 | c29f131323a3f1c619cf38fd0f56d2d814298bd2 | bigcode/the-stack | train |
0fa9ee7162f51ab3164dd370 | train | function | def status(name=''):
'''
Return the status of the named zpool
CLI Example:
.. code-block:: bash
salt '*' zpool.status myzpool
'''
zpool = _check_zpool()
cmd = [zpool, 'status', name]
res = __salt__['cmd.run'](cmd, python_shell=False)
ret = res.splitlines()
return ret
| def status(name=''):
| '''
Return the status of the named zpool
CLI Example:
.. code-block:: bash
salt '*' zpool.status myzpool
'''
zpool = _check_zpool()
cmd = [zpool, 'status', name]
res = __salt__['cmd.run'](cmd, python_shell=False)
ret = res.splitlines()
return ret
| file():
'''
Looks to see if mkfile is present on the system
'''
return salt.utils.which('mkfile')
def __virtual__():
'''
Provides zpool.
'''
if _check_zpool():
return 'zpool'
return False
def status(name=''):
| 64 | 64 | 89 | 5 | 58 | kev009/salt | salt/modules/zpool.py | Python | status | status | 51 | 65 | 51 | 51 | 53f8d618e3bd359de483f0b191bbf08378449730 | bigcode/the-stack | train |
327d4b5963fa8d3c17c7f659 | train | function | def create(pool_name, *vdevs, **kwargs):
'''
.. versionadded:: 2015.5.0
Create a simple zpool, a mirrored zpool, a zpool having nested VDEVs, a hybrid zpool with cache, spare and log drives or a zpool with RAIDZ-1, RAIDZ-2 or RAIDZ-3
CLI Example:
.. code-block:: bash
salt '*' zpool.creat... | def create(pool_name, *vdevs, **kwargs):
| '''
.. versionadded:: 2015.5.0
Create a simple zpool, a mirrored zpool, a zpool having nested VDEVs, a hybrid zpool with cache, spare and log drives or a zpool with RAIDZ-1, RAIDZ-2 or RAIDZ-3
CLI Example:
.. code-block:: bash
salt '*' zpool.create myzpool /path/to/vdev1 [...] [force=Tru... | = {}
if not exists(pool_name):
ret['Error'] = 'Storage pool {0} does not exist'.format(pool_name)
return ret
else:
zpool = _check_zpool()
cmd = [zpool, 'destroy', pool_name]
__salt__['cmd.run'](cmd, python_shell=False)
if not exists(pool_name):
ret[po... | 256 | 256 | 910 | 13 | 243 | kev009/salt | salt/modules/zpool.py | Python | create | create | 191 | 278 | 191 | 191 | 0d1ffaa3598dbc0b29d7f3e60c374c773da7d4aa | bigcode/the-stack | train |
1a56813a808587b75473b51b | train | function | def online(pool_name, *vdevs, **kwargs):
'''
.. versionadded:: 2015.5.0
Ensure that the specified devices are online
CLI Example:
.. code-block:: bash
salt '*' zpool.online myzpool /path/to/vdev1 [...]
'''
ret = {}
dlist = []
# Check if the pool_name exists
if not e... | def online(pool_name, *vdevs, **kwargs):
| '''
.. versionadded:: 2015.5.0
Ensure that the specified devices are online
CLI Example:
.. code-block:: bash
salt '*' zpool.online myzpool /path/to/vdev1 [...]
'''
ret = {}
dlist = []
# Check if the pool_name exists
if not exists(pool_name):
ret['Error'] = ... | {1} {2}'.format(zpool, pool_name, new_name)
else:
cmd = '{0} import {1} {2}'.format(zpool, pool_name, new_name)
res = __salt__['cmd.run'](cmd, ignore_retcode=True)
if res:
ret['Error'] = {}
ret['Error']['Message'] = 'Import failed!'
ret['Error']['... | 123 | 123 | 411 | 13 | 109 | kev009/salt | salt/modules/zpool.py | Python | online | online | 505 | 555 | 505 | 505 | d004b18074f5b5b25f2caacf18bd891e40e25080 | bigcode/the-stack | train |
c5a032e488f3d756ae6162ce | train | function | @decorators.memoize
def _check_mkfile():
'''
Looks to see if mkfile is present on the system
'''
return salt.utils.which('mkfile')
| @decorators.memoize
def _check_mkfile():
| '''
Looks to see if mkfile is present on the system
'''
return salt.utils.which('mkfile')
| ': 'import',
'list_': 'list',
}
@decorators.memoize
def _check_zpool():
'''
Looks to see if zpool is present on the system
'''
return salt.utils.which('zpool')
@decorators.memoize
def _check_mkfile():
| 64 | 64 | 39 | 13 | 51 | kev009/salt | salt/modules/zpool.py | Python | _check_mkfile | _check_mkfile | 34 | 39 | 34 | 35 | c68007224b8836e6dbf4a36cb6282fa8dcf2b19b | bigcode/the-stack | train |
4520ba1ed228c62a1b3c4ec8 | train | function | def zpool_list():
'''
.. deprecated:: 2014.7.0
Use :py:func:`~salt.modules.zpool.list_` instead.
Return a list of all pools in the system with health status and space usage
CLI Example:
.. code-block:: bash
salt '*' zpool.zpool_list
'''
salt.utils.warn_until(
'... | def zpool_list():
| '''
.. deprecated:: 2014.7.0
Use :py:func:`~salt.modules.zpool.list_` instead.
Return a list of all pools in the system with health status and space usage
CLI Example:
.. code-block:: bash
salt '*' zpool.zpool_list
'''
salt.utils.warn_until(
'Boron',
... | '''
zpool = _check_zpool()
cmd = [zpool, 'list']
res = __salt__['cmd.run'](cmd, python_shell=False)
pool_list = [l for l in res.splitlines()]
return {'pools': pool_list}
def zpool_list():
| 64 | 64 | 138 | 5 | 59 | kev009/salt | salt/modules/zpool.py | Python | zpool_list | zpool_list | 104 | 123 | 104 | 104 | a3814d0788fa934095b6994299dad51fabdc04c2 | bigcode/the-stack | train |
bc5cd161d6921b495b9497ec | train | function | def scrub(pool_name=None):
'''
Begin a scrub
CLI Example:
.. code-block:: bash
salt '*' zpool.scrub myzpool
'''
ret = {}
if not pool_name:
ret['Error'] = 'zpool name parameter is mandatory.'
return ret
if exists(pool_name):
zpool = _check_zpool()
... | def scrub(pool_name=None):
| '''
Begin a scrub
CLI Example:
.. code-block:: bash
salt '*' zpool.scrub myzpool
'''
ret = {}
if not pool_name:
ret['Error'] = 'zpool name parameter is mandatory.'
return ret
if exists(pool_name):
zpool = _check_zpool()
cmd = [zpool, 'scrub', po... | zpool = _check_zpool()
cmd = [zpool, 'destroy', pool_name]
__salt__['cmd.run'](cmd, python_shell=False)
if not exists(pool_name):
ret[pool_name] = "Deleted"
return ret
def scrub(pool_name=None):
| 64 | 64 | 149 | 6 | 57 | kev009/salt | salt/modules/zpool.py | Python | scrub | scrub | 167 | 188 | 167 | 167 | 9b0b5b39634f1c30c38f83f2c7eda8b04babd257 | bigcode/the-stack | train |
995dc6a1dfad9cbe279fa089 | train | function | def add(pool_name, *vdevs):
'''
Add the specified vdev\'s to the given pool
CLI Example:
.. code-block:: bash
salt '*' zpool.add myzpool /path/to/vdev1 /path/to/vdev2 [...]
'''
ret = {}
dlist = []
# check for pool
if not exists(pool_name):
ret['Error'] = 'Storage ... | def add(pool_name, *vdevs):
| '''
Add the specified vdev\'s to the given pool
CLI Example:
.. code-block:: bash
salt '*' zpool.add myzpool /path/to/vdev1 /path/to/vdev2 [...]
'''
ret = {}
dlist = []
# check for pool
if not exists(pool_name):
ret['Error'] = 'Storage Pool `{0}` doesn\'t exist'.f... | )
cmd = '{0} {1} {2}'.format(cmd, pool_name, devs)
# Create storage pool
res = __salt__['cmd.run'](cmd, python_shell=False)
# Check and see if the pools is available
if exists(pool_name):
ret[pool_name] = 'created'
return ret
else:
ret['Error'] = {}
ret['Error']... | 132 | 132 | 442 | 10 | 121 | kev009/salt | salt/modules/zpool.py | Python | add | add | 281 | 326 | 281 | 281 | 0ad333abe253bd2c12a8f6e84983267f385d0e65 | bigcode/the-stack | train |
9c4caf9e5c69f55335b58513 | train | function | def iostat(name=''):
'''
Display I/O statistics for the given pools
CLI Example:
.. code-block:: bash
salt '*' zpool.iostat myzpool
'''
zpool = _check_zpool()
cmd = [zpool, 'iostat', '-v', name]
res = __salt__['cmd.run'](cmd, python_shell=False)
ret = res.splitlines()
... | def iostat(name=''):
| '''
Display I/O statistics for the given pools
CLI Example:
.. code-block:: bash
salt '*' zpool.iostat myzpool
'''
zpool = _check_zpool()
cmd = [zpool, 'iostat', '-v', name]
res = __salt__['cmd.run'](cmd, python_shell=False)
ret = res.splitlines()
return ret
| zpool.status myzpool
'''
zpool = _check_zpool()
cmd = [zpool, 'status', name]
res = __salt__['cmd.run'](cmd, python_shell=False)
ret = res.splitlines()
return ret
def iostat(name=''):
| 64 | 64 | 95 | 6 | 57 | kev009/salt | salt/modules/zpool.py | Python | iostat | iostat | 68 | 82 | 68 | 68 | 70a6f1a85b6d0ad283faebadd4c6ebaa90052f60 | bigcode/the-stack | train |
7eb335eb263d0d352a8a7587 | train | function | @decorators.memoize
def _check_zpool():
'''
Looks to see if zpool is present on the system
'''
return salt.utils.which('zpool')
| @decorators.memoize
def _check_zpool():
| '''
Looks to see if zpool is present on the system
'''
return salt.utils.which('zpool')
| stat
import logging
# Import Salt libs
import salt.utils
import salt.utils.decorators as decorators
log = logging.getLogger(__name__)
__func_alias__ = {
'import_': 'import',
'list_': 'list',
}
@decorators.memoize
def _check_zpool():
| 64 | 64 | 38 | 12 | 52 | kev009/salt | salt/modules/zpool.py | Python | _check_zpool | _check_zpool | 26 | 31 | 26 | 27 | 3b34c2c1d9db1b9202532eacf66c36b72c750333 | bigcode/the-stack | train |
0a7a20f0f5d263a7253c95f2 | train | function | def exists(pool_name):
'''
Check if a ZFS storage pool is active
CLI Example:
.. code-block:: bash
salt '*' zpool.exists myzpool
'''
zpool = _check_zpool()
cmd = '{0} list {1}'.format(zpool, pool_name)
res = __salt__['cmd.run'](cmd, ignore_retcode=True)
if "no such pool" i... | def exists(pool_name):
| '''
Check if a ZFS storage pool is active
CLI Example:
.. code-block:: bash
salt '*' zpool.exists myzpool
'''
zpool = _check_zpool()
cmd = '{0} list {1}'.format(zpool, pool_name)
res = __salt__['cmd.run'](cmd, ignore_retcode=True)
if "no such pool" in res:
return N... | _until(
'Boron',
'The \'zpool_list()\' module function is being deprecated and is '
'being renamed to \'list()\'. This function \'zpool_list()\' will be removed in '
'Salt Boron.'
)
return list_()
def exists(pool_name):
| 64 | 64 | 103 | 5 | 59 | kev009/salt | salt/modules/zpool.py | Python | exists | exists | 126 | 141 | 126 | 126 | 7dd5df2dfce851a1e59d537e6f14ded76656d9be | bigcode/the-stack | train |
9e2fd323f71b58fa4e03bbf2 | train | function | def export(*pools, **kwargs):
'''
.. versionadded:: 2015.5.0
Export storage pools
CLI Example:
.. code-block:: bash
salt '*' zpool.export myzpool ... [force=True|False]
salt '*' zpool.export myzpool2 myzpool2 ... [force=True|False]
'''
ret = {}
pool_list = []
if n... | def export(*pools, **kwargs):
| '''
.. versionadded:: 2015.5.0
Export storage pools
CLI Example:
.. code-block:: bash
salt '*' zpool.export myzpool ... [force=True|False]
salt '*' zpool.export myzpool2 myzpool2 ... [force=True|False]
'''
ret = {}
pool_list = []
if not pools:
ret['Error']... | list)
__salt__['cmd.run'](cmd, python_shell=False)
# Makesure the files are there
for vdev in vdevs:
if not os.path.isfile(vdev):
ret[vdev] = 'The vdev can\'t be created'
ret['status'] = True
ret[cmd] = cmd
return ret
def export(*pools, **kwargs):
| 89 | 89 | 298 | 9 | 79 | kev009/salt | salt/modules/zpool.py | Python | export | export | 410 | 450 | 410 | 410 | 3afab3ae4ca6ed5313cd334a66b294399fb8aadb | bigcode/the-stack | train |
f6e8fb911c27920f7f979288 | train | function | def __virtual__():
'''
Provides zpool.
'''
if _check_zpool():
return 'zpool'
return False
| def __virtual__():
| '''
Provides zpool.
'''
if _check_zpool():
return 'zpool'
return False
| if zpool is present on the system
'''
return salt.utils.which('zpool')
@decorators.memoize
def _check_mkfile():
'''
Looks to see if mkfile is present on the system
'''
return salt.utils.which('mkfile')
def __virtual__():
| 64 | 64 | 31 | 5 | 59 | kev009/salt | salt/modules/zpool.py | Python | __virtual__ | __virtual__ | 42 | 48 | 42 | 42 | 2ee62d2d25759f9b91f1f99b83517d5cadd82bc7 | bigcode/the-stack | train |
e95420174bdae859e7c52411 | train | function | def create_file_vdev(size, *vdevs):
'''
Creates file based ``virtual devices`` for a zpool
``*vdevs`` is a list of full paths for mkfile to create
CLI Example:
.. code-block:: bash
salt '*' zpool.create_file_vdev 7g /path/to/vdev1 [/path/to/vdev2] [...]
.. note::
Depending ... | def create_file_vdev(size, *vdevs):
| '''
Creates file based ``virtual devices`` for a zpool
``*vdevs`` is a list of full paths for mkfile to create
CLI Example:
.. code-block:: bash
salt '*' zpool.create_file_vdev 7g /path/to/vdev1 [/path/to/vdev2] [...]
.. note::
Depending on file size, the above command may ... | =False)
# check for new vdev in pool
res = status(name=pool_name)
for line in res:
if new in line:
ret['replaced'] = '{0} with {1}'.format(old, new)
return ret
ret['Error'] = 'Does not look like devices were swapped; check status'
return ret
def create_file_vdev(size... | 90 | 90 | 300 | 12 | 77 | kev009/salt | salt/modules/zpool.py | Python | create_file_vdev | create_file_vdev | 368 | 407 | 368 | 368 | 4f7462b9dc0d7b43eca1d1dc30ab2015692b3863 | bigcode/the-stack | train |
dc1715833b478995a68541de | train | function | def import_(pool_name='', new_name='', **kwargs):
'''
.. versionadded:: 2015.5.0
Import storage pools or list pools available for import
CLI Example:
.. code-block:: bash
salt '*' zpool.import [all=True|False]
salt '*' zpool.import myzpool [mynewzpool] [force=True|False]
'''
... | def import_(pool_name='', new_name='', **kwargs):
| '''
.. versionadded:: 2015.5.0
Import storage pools or list pools available for import
CLI Example:
.. code-block:: bash
salt '*' zpool.import [all=True|False]
salt '*' zpool.import myzpool [mynewzpool] [force=True|False]
'''
ret = {}
zpool = _check_zpool()
import... | ('force', False)
if force is True:
cmd = '{0} export -f {1}'.format(zpool, pools)
else:
cmd = '{0} export {1}'.format(zpool, pools)
res = __salt__['cmd.run'](cmd, ignore_retcode=True)
if res:
ret['Error'] = {}
ret['Error']['Message'] = 'Import failed!'
ret['Error'... | 135 | 135 | 451 | 12 | 122 | kev009/salt | salt/modules/zpool.py | Python | import_ | import_ | 453 | 502 | 453 | 453 | 067831b93a4eb6939ddbe4b22863e916d3fbd3cb | bigcode/the-stack | train |
105c771fa8d16fdbed968026 | train | function | def exec_report(base_directory, verbose):
original_cwd = os.getcwd()
os.chdir(base_directory)
filenames = get_filenames_to_examine()
file_infos = [gather_file_info(f) for f in filenames]
print_report(file_infos, verbose)
os.chdir(original_cwd)
| def exec_report(base_directory, verbose):
| original_cwd = os.getcwd()
os.chdir(base_directory)
filenames = get_filenames_to_examine()
file_infos = [gather_file_info(f) for f in filenames]
print_report(file_infos, verbose)
os.chdir(original_cwd)
| file_infos if
i['classified_copyrights'] < i['all_copyrights']]
print("%d with unexpected copyright holder names" %
len(unclassified_copyrights))
print_filenames(unclassified_copyrights, verbose)
print(SEPARATOR)
def exec_report(base_directory, verbose):
| 64 | 64 | 63 | 8 | 56 | JBaczuk/learncoin | contrib/devtools/copyright_header.py | Python | exec_report | exec_report | 262 | 268 | 262 | 262 | 2575d4114347be9f65bc0133a969014e417818ae | bigcode/the-stack | train |
bee8c3e2026e31d743e5afc1 | train | function | def exec_insert_header(filename, style):
file_lines = read_file_lines(filename)
if file_already_has_core_copyright(file_lines):
sys.exit('*** %s already has a copyright by The Bitcoin Core developers'
% (filename))
start_year, end_year = get_git_change_year_range(filename)
if st... | def exec_insert_header(filename, style):
| file_lines = read_file_lines(filename)
if file_already_has_core_copyright(file_lines):
sys.exit('*** %s already has a copyright by The Bitcoin Core developers'
% (filename))
start_year, end_year = get_git_change_year_range(filename)
if style == 'python':
insert_python_he... | def insert_cpp_header(filename, file_lines, start_year, end_year):
header_lines = get_cpp_header_lines_to_insert(start_year, end_year)
for line in header_lines:
file_lines.insert(0, line)
write_file_lines(filename, file_lines)
def exec_insert_header(filename, style):
| 64 | 64 | 105 | 8 | 56 | JBaczuk/learncoin | contrib/devtools/copyright_header.py | Python | exec_insert_header | exec_insert_header | 523 | 532 | 523 | 523 | e5c0041a21313ee710fc537d11d270a814f6c5a9 | bigcode/the-stack | train |
9f042973082c8733b854d050 | train | function | def get_git_change_years(filename):
git_log_lines = call_git_log(filename)
if len(git_log_lines) == 0:
return [datetime.date.today().year]
# timestamp is in ISO 8601 format. e.g. "2016-09-05 14:25:32 -0600"
return [line.split(' ')[0].split('-')[0] for line in git_log_lines]
| def get_git_change_years(filename):
| git_log_lines = call_git_log(filename)
if len(git_log_lines) == 0:
return [datetime.date.today().year]
# timestamp is in ISO 8601 format. e.g. "2016-09-05 14:25:32 -0600"
return [line.split(' ')[0].split('-')[0] for line in git_log_lines]
|
################################################################################
GIT_LOG_CMD = "git log --pretty=format:%%ai %s"
def call_git_log(filename):
out = subprocess.check_output((GIT_LOG_CMD % filename).split(' '))
return out.decode("utf-8").split('\n')
def get_git_change_years(filename):
| 64 | 64 | 91 | 8 | 56 | JBaczuk/learncoin | contrib/devtools/copyright_header.py | Python | get_git_change_years | get_git_change_years | 313 | 318 | 313 | 313 | 654de7f0a07f6f7583e879005671e0f471f77955 | bigcode/the-stack | train |
858bab0cc4de20569d4631ae | train | function | def get_count_of_copyrights_of_any_style_any_holder(contents):
return len(ANY_COPYRIGHT_COMPILED.findall(contents))
| def get_count_of_copyrights_of_any_style_any_holder(contents):
| return len(ANY_COPYRIGHT_COMPILED.findall(contents))
| _name))
WITHOUT_C_STYLE_COMPILED[holder_name] = (
compile_copyright_regex(COPYRIGHT_WITHOUT_C, ANY_YEAR_STYLE,
holder_name))
################################################################################
# search file contents for copyright message of particular category
#... | 64 | 64 | 27 | 14 | 49 | JBaczuk/learncoin | contrib/devtools/copyright_header.py | Python | get_count_of_copyrights_of_any_style_any_holder | get_count_of_copyrights_of_any_style_any_holder | 129 | 130 | 129 | 129 | 400ba2ce041f0da894cdab78867e92792675aa6a | bigcode/the-stack | train |
046442bacc43c98214fd3345 | train | function | def parse_year_range(year_range):
year_split = year_range.split('-')
start_year = year_split[0]
if len(year_split) == 1:
return start_year, start_year
return start_year, year_split[1]
| def parse_year_range(year_range):
| year_split = year_range.split('-')
start_year = year_split[0]
if len(year_split) == 1:
return start_year, start_year
return start_year, year_split[1]
| get_updatable_copyright_line(file_lines):
index = 0
for line in file_lines:
if UPDATEABLE_LINE_COMPILED.search(line) is not None:
return index, line
index = index + 1
return None, None
def parse_year_range(year_range):
| 64 | 64 | 53 | 7 | 56 | JBaczuk/learncoin | contrib/devtools/copyright_header.py | Python | parse_year_range | parse_year_range | 356 | 361 | 356 | 356 | fac4b073254119688abb0b5423bfcfaea477ae19 | bigcode/the-stack | train |
d881cb4d9fd70b890a77d1e6 | train | function | def print_filenames(filenames, verbose):
if not verbose:
return
for filename in filenames:
print("\t%s" % filename)
| def print_filenames(filenames, verbose):
| if not verbose:
return
for filename in filenames:
print("\t%s" % filename)
| _list_style or has_without_c_style:
info['classified_copyrights'] = info['classified_copyrights'] + 1
return info
################################################################################
# report execution
################################################################################
SEPARAT... | 64 | 64 | 32 | 9 | 55 | JBaczuk/learncoin | contrib/devtools/copyright_header.py | Python | print_filenames | print_filenames | 183 | 187 | 183 | 183 | c5e86933914a18311363f14dad98181d60e9b2ab | bigcode/the-stack | train |
1acffcde29d9f67191e823a5 | train | function | def report_cmd(argv):
if len(argv) == 2:
sys.exit(REPORT_USAGE)
base_directory = argv[2]
if not os.path.exists(base_directory):
sys.exit("*** bad <base_directory>: %s" % base_directory)
if len(argv) == 3:
verbose = False
elif argv[3] == 'verbose':
verbose = True
... | def report_cmd(argv):
| if len(argv) == 2:
sys.exit(REPORT_USAGE)
base_directory = argv[2]
if not os.path.exists(base_directory):
sys.exit("*** bad <base_directory>: %s" % base_directory)
if len(argv) == 3:
verbose = False
elif argv[3] == 'verbose':
verbose = True
else:
sys.exi... | of a repository.
Usage:
$ ./copyright_header.py report <base_directory> [verbose]
Arguments:
<base_directory> - The base directory of a learncoin source code repository.
[verbose] - Includes a list of every file of each subcategory in the report.
"""
def report_cmd(argv):
| 64 | 64 | 109 | 5 | 59 | JBaczuk/learncoin | contrib/devtools/copyright_header.py | Python | report_cmd | report_cmd | 286 | 301 | 286 | 286 | 1a1efef00513b6f3fcf705061da894740c035cd3 | bigcode/the-stack | train |
8ceefeb3ba3bb4a43baafed5 | train | function | def year_range_to_str(start_year, end_year):
if start_year == end_year:
return start_year
return "%s-%s" % (start_year, end_year)
| def year_range_to_str(start_year, end_year):
| if start_year == end_year:
return start_year
return "%s-%s" % (start_year, end_year)
| def parse_year_range(year_range):
year_split = year_range.split('-')
start_year = year_split[0]
if len(year_split) == 1:
return start_year, start_year
return start_year, year_split[1]
def year_range_to_str(start_year, end_year):
| 64 | 64 | 39 | 11 | 53 | JBaczuk/learncoin | contrib/devtools/copyright_header.py | Python | year_range_to_str | year_range_to_str | 363 | 366 | 363 | 363 | aee12221735e46f41bcd0110600c3288964cfee7 | bigcode/the-stack | train |
488bbd130ed8450e991ae682 | train | function | def read_file(filename):
return open(os.path.abspath(filename), 'r', encoding="utf8").read()
| def read_file(filename):
| return open(os.path.abspath(filename), 'r', encoding="utf8").read()
| _name].search(contents)
return match is not None
def file_has_without_c_style_copyright_for_holder(contents, holder_name):
match = WITHOUT_C_STYLE_COMPILED[holder_name].search(contents)
return match is not None
################################################################################
# get file inf... | 64 | 64 | 23 | 5 | 58 | JBaczuk/learncoin | contrib/devtools/copyright_header.py | Python | read_file | read_file | 148 | 149 | 148 | 148 | a5a8d7dc0a01a09ec25ac6ba9dcb1b678c4fbed6 | bigcode/the-stack | train |
0bb0595b3ed227c21dcda8e3 | train | function | def file_has_year_list_style_copyright_for_holder(contents, holder_name):
match = YEAR_LIST_STYLE_COMPILED[holder_name].search(contents)
return match is not None
| def file_has_year_list_style_copyright_for_holder(contents, holder_name):
| match = YEAR_LIST_STYLE_COMPILED[holder_name].search(contents)
return match is not None
| ANY_COPYRIGHT_COMPILED.findall(contents))
def file_has_dominant_style_copyright_for_holder(contents, holder_name):
match = DOMINANT_STYLE_COMPILED[holder_name].search(contents)
return match is not None
def file_has_year_list_style_copyright_for_holder(contents, holder_name):
| 64 | 64 | 38 | 15 | 48 | JBaczuk/learncoin | contrib/devtools/copyright_header.py | Python | file_has_year_list_style_copyright_for_holder | file_has_year_list_style_copyright_for_holder | 136 | 138 | 136 | 136 | 7eb78cb34faab3f414b628bb73957c2a26ccadce | bigcode/the-stack | train |
b928d586ea67b37500b23d87 | train | function | def call_git_log(filename):
out = subprocess.check_output((GIT_LOG_CMD % filename).split(' '))
return out.decode("utf-8").split('\n')
| def call_git_log(filename):
| out = subprocess.check_output((GIT_LOG_CMD % filename).split(' '))
return out.decode("utf-8").split('\n')
| True
else:
sys.exit("*** unknown argument: %s" % argv[2])
exec_report(base_directory, verbose)
################################################################################
# query git for year of last change
################################################################################
GIT_LOG... | 64 | 64 | 36 | 6 | 58 | JBaczuk/learncoin | contrib/devtools/copyright_header.py | Python | call_git_log | call_git_log | 309 | 311 | 309 | 309 | ecd3510aa3bad22578e537720c63547e9c7d92e0 | bigcode/the-stack | train |
c1549448e5c31a00e5df3c90 | train | function | def insert_cmd(argv):
if len(argv) != 3:
sys.exit(INSERT_USAGE)
filename = argv[2]
if not os.path.isfile(filename):
sys.exit("*** bad filename: %s" % filename)
_, extension = os.path.splitext(filename)
if extension not in ['.h', '.cpp', '.cc', '.c', '.py']:
sys.exit("*** can... | def insert_cmd(argv):
| if len(argv) != 3:
sys.exit(INSERT_USAGE)
filename = argv[2]
if not os.path.isfile(filename):
sys.exit("*** bad filename: %s" % filename)
_, extension = os.path.splitext(filename)
if extension not in ['.h', '.cpp', '.cc', '.c', '.py']:
sys.exit("*** cannot insert for file ex... | be set to be:
"<current_year>"
If the file already has a copyright for "The Bitcoin Core developers", the
script will exit.
Usage:
$ ./copyright_header.py insert <file>
Arguments:
<file> - A source file in the learncoin repository.
"""
def insert_cmd(argv):
| 64 | 64 | 124 | 5 | 59 | JBaczuk/learncoin | contrib/devtools/copyright_header.py | Python | insert_cmd | insert_cmd | 563 | 578 | 563 | 563 | 067d7b826c5de763fd610eefe667fa1dd981d2a3 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.