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
6c6645f7b2d61268e8395df0
train
function
def getmethodclass(m): """Resolves a function's owner, e.g. a method's class. Note that this returns the object that the function was retrieved from, not necessarily the class where it was defined. This function relies on Python stack frame support in the interpreter, and has the same limitations that inspe...
def getmethodclass(m):
"""Resolves a function's owner, e.g. a method's class. Note that this returns the object that the function was retrieved from, not necessarily the class where it was defined. This function relies on Python stack frame support in the interpreter, and has the same limitations that inspect.currentframe. Lim...
func__'): return m.__func__ if hasattr(m, 'im_func'): return m.im_func return m def getdefiningclass(m, owner_class): """Resolves the class (e.g. one of the superclasses) that defined a method.""" # Normalize bound functions to their respective unbound versions. m = _get_unbound_function(m) for su...
184
184
614
6
177
KosingZhu/tensorflow
tensorflow/python/autograph/pyct/inspect_utils.py
Python
getmethodclass
getmethodclass
265
336
265
265
94e568f1ca78d1a49d39c8ed3fd5eb66b89b9c87
bigcode/the-stack
train
545fd28fbceae0bee84d02a9
train
function
def islambda(f): if not tf_inspect.isfunction(f): return False # TODO(mdan): Look into checking the only the code object. if not (hasattr(f, '__name__') and hasattr(f, '__code__')): return False # Some wrappers can rename the function, but changing the name of the # code object is harder. return ( ...
def islambda(f):
if not tf_inspect.isfunction(f): return False # TODO(mdan): Look into checking the only the code object. if not (hasattr(f, '__name__') and hasattr(f, '__code__')): return False # Some wrappers can rename the function, but changing the name of the # code object is harder. return ( (f.__name__ ...
len': len, 'list': list, 'print': print, 'range': range, 'tuple': tuple, 'type': type, 'zip': zip } if six.PY2: SPECIAL_BUILTINS['xrange'] = xrange def islambda(f):
64
64
108
5
58
KosingZhu/tensorflow
tensorflow/python/autograph/pyct/inspect_utils.py
Python
islambda
islambda
56
65
56
56
03eee16b28262d8ce8ae155fcdbbb786de20bb34
bigcode/the-stack
train
fc6a969dec3ce20d50e929a7
train
function
def isbuiltin(f): """Returns True if the argument is a built-in function.""" if any(f is builtin for builtin in six.moves.builtins.__dict__.values()): return True elif isinstance(f, types.BuiltinFunctionType): return True elif inspect.isbuiltin(f): return True elif f is eval: return True els...
def isbuiltin(f):
"""Returns True if the argument is a built-in function.""" if any(f is builtin for builtin in six.moves.builtins.__dict__.values()): return True elif isinstance(f, types.BuiltinFunctionType): return True elif inspect.isbuiltin(f): return True elif f is eval: return True else: return Fals...
False if not hasattr(f, '_fields'): return False fields = getattr(f, '_fields') if not isinstance(fields, tuple): return False if not all(isinstance(f, str) for f in fields): return False return True def isbuiltin(f):
64
64
84
5
58
KosingZhu/tensorflow
tensorflow/python/autograph/pyct/inspect_utils.py
Python
isbuiltin
isbuiltin
82
93
82
82
6188fedbe512b5a8f60ce568251508e1159e1ac9
bigcode/the-stack
train
ca6ac5290bd1b0dd8f25921b
train
function
def getfutureimports(entity): """Detects what future imports are necessary to safely execute entity source. Args: entity: Any object Returns: A tuple of future strings """ if not (tf_inspect.isfunction(entity) or tf_inspect.ismethod(entity)): return tuple() return tuple(sorted(name for name, v...
def getfutureimports(entity):
"""Detects what future imports are necessary to safely execute entity source. Args: entity: Any object Returns: A tuple of future strings """ if not (tf_inspect.isfunction(entity) or tf_inspect.ismethod(entity)): return tuple() return tuple(sorted(name for name, value in entity.__globals__.ite...
owners) for o in owner_types: if tf_inspect.isclass(o) and issubclass(o, tuple(owner_types)): return o raise ValueError('Found too many owners of %s: %s' % (m, owners)) return None def getfutureimports(entity):
64
64
98
6
57
KosingZhu/tensorflow
tensorflow/python/autograph/pyct/inspect_utils.py
Python
getfutureimports
getfutureimports
339
351
339
339
c8ede8759991069498bc0e327121af4f484e5d18
bigcode/the-stack
train
0956919c84e8bc6304884e80
train
function
def isconstructor(cls): """Returns True if the argument is an object constructor. In general, any object of type class is a constructor, with the exception of classes created using a callable metaclass. See below for why a callable metaclass is not a trivial combination: https://docs.python.org/2.7/reference...
def isconstructor(cls):
"""Returns True if the argument is an object constructor. In general, any object of type class is a constructor, with the exception of classes created using a callable metaclass. See below for why a callable metaclass is not a trivial combination: https://docs.python.org/2.7/reference/datamodel.html#customiz...
builtin in six.moves.builtins.__dict__.values()): return True elif isinstance(f, types.BuiltinFunctionType): return True elif inspect.isbuiltin(f): return True elif f is eval: return True else: return False def isconstructor(cls):
64
64
143
5
58
KosingZhu/tensorflow
tensorflow/python/autograph/pyct/inspect_utils.py
Python
isconstructor
isconstructor
96
113
96
96
aa81acc13b70585ec5551095ccdc1ad3986da75c
bigcode/the-stack
train
79bb6d55ad0c2b39cf3e5b74
train
function
def getnamespace(f): """Returns the complete namespace of a function. Namespace is defined here as the mapping of all non-local variables to values. This includes the globals and the closure variables. Note that this captures the entire globals collection of the function, and may contain extra symbols that i...
def getnamespace(f):
"""Returns the complete namespace of a function. Namespace is defined here as the mapping of all non-local variables to values. This includes the globals and the closure variables. Note that this captures the entire globals collection of the function, and may contain extra symbols that it does not actually u...
(obj): """A variant of inspect.getsource that ignores the __wrapped__ property.""" with _linecache_lock: _fix_linecache_record(obj) lines, lnum = inspect.findsource(obj) return ''.join(inspect.getblock(lines[lnum:])) def getnamespace(f):
63
64
185
5
58
KosingZhu/tensorflow
tensorflow/python/autograph/pyct/inspect_utils.py
Python
getnamespace
getnamespace
151
174
151
151
ac332967ca5315176b99d9501ae1c7ba4c163809
bigcode/the-stack
train
64acb9f37b4d8929e4c1a6cb
train
function
def getqualifiedname(namespace, object_, max_depth=5, visited=None): """Returns the name by which a value can be referred to in a given namespace. If the object defines a parent module, the function attempts to use it to locate the object. This function will recurse inside modules, but it will not search obje...
def getqualifiedname(namespace, object_, max_depth=5, visited=None):
"""Returns the name by which a value can be referred to in a given namespace. If the object defines a parent module, the function attempts to use it to locate the object. This function will recurse inside modules, but it will not search objects for attributes. The recursion depth is controlled by max_depth....
mapping of all non-local variables to values. This includes the globals and the closure variables. Note that this captures the entire globals collection of the function, and may contain extra symbols that it does not actually use. Args: f: User defined function. Returns: A dict mapping symbol names ...
179
179
597
16
162
KosingZhu/tensorflow
tensorflow/python/autograph/pyct/inspect_utils.py
Python
getqualifiedname
getqualifiedname
177
237
177
177
b3b442f901bb8b25a9e3b2359a88687213e1f29e
bigcode/the-stack
train
219cfda195996d6e08820c68
train
class
class TestInfoExtractor(unittest.TestCase): def setUp(self): self.ie = TestIE(FakeYDL()) def test_ie_key(self): self.assertEqual(get_info_extractor(YoutubeIE.ie_key()), YoutubeIE) def test_html_search_regex(self): html = '<p id="foo">Watch this <a href="http://www.youtube.c...
class TestInfoExtractor(unittest.TestCase):
def setUp(self): self.ie = TestIE(FakeYDL()) def test_ie_key(self): self.assertEqual(get_info_extractor(YoutubeIE.ie_key()), YoutubeIE) def test_html_search_regex(self): html = '<p id="foo">Watch this <a href="http://www.youtube.com/watch?v=BaW_jenozKc">video</a></p>' ...
#!/usr/bin/env python from __future__ import unicode_literals # Allow direct execution import io import os import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from test.helper import FakeYDL, expect_dict, expect_value from youtube_dl.compat import co...
140
256
10,324
8
131
yycc179/urlp
server/external/youtube-dl/test/test_InfoExtractor.py
Python
TestInfoExtractor
TestInfoExtractor
23
602
23
23
3a592b8165f6f15753378d617cbcb5d2583b5a2d
bigcode/the-stack
train
846bcf111691fac3b58a1904
train
class
class TestIE(InfoExtractor): pass
class TestIE(InfoExtractor):
pass
from youtube_dl.compat import compat_etree_fromstring from youtube_dl.extractor.common import InfoExtractor from youtube_dl.extractor import YoutubeIE, get_info_extractor from youtube_dl.utils import encode_data_uri, strip_jsonp, ExtractorError, RegexNotFoundError class TestIE(InfoExtractor):
64
64
10
7
56
yycc179/urlp
server/external/youtube-dl/test/test_InfoExtractor.py
Python
TestIE
TestIE
19
20
19
19
bebd2ff0166b748c49ec53a271d27de643b936c7
bigcode/the-stack
train
a833915730d396afd6555bbb
train
class
class FeatureClass: def __init__(self, params, is_eval=False): """ :param params: parameters dictionary :param is_eval: if True, does not load dataset labels. """ # Input directories self._feat_label_dir = params['feat_label_dir'] self._dataset_dir = params[...
class FeatureClass:
def __init__(self, params, is_eval=False): """ :param params: parameters dictionary :param is_eval: if True, does not load dataset labels. """ # Input directories self._feat_label_dir = params['feat_label_dir'] self._dataset_dir = params['dataset_dir'] ...
# Contains routines for labels creation, features extraction and normalization # import os import numpy as np import scipy.io.wavfile as wav from sklearn import preprocessing import joblib #from sklearn.externals import joblib from IPython import embed import matplotlib.pyplot as plot import librosa plot.switch_back...
109
256
4,937
4
105
andresperezlopez/DCASE2020
baseline/cls_feature_class.py
Python
FeatureClass
FeatureClass
24
474
24
24
1e33ed1d6fdc8c9302273242d5d471f032da8813
bigcode/the-stack
train
a0d56bba54903513890e6cf9
train
function
def create_folder(folder_name): if not os.path.exists(folder_name): print('{} folder does not exist, creating it.'.format(folder_name)) os.makedirs(folder_name)
def create_folder(folder_name):
if not os.path.exists(folder_name): print('{} folder does not exist, creating it.'.format(folder_name)) os.makedirs(folder_name)
._nb_label_frames_1s def get_hop_len_sec(self): return self._hop_len_s def get_nb_frames(self): return self._max_label_frames def get_nb_mel_bins(self): return self._nb_mel_bins def create_folder(folder_name):
64
64
36
6
57
andresperezlopez/DCASE2020
baseline/cls_feature_class.py
Python
create_folder
create_folder
477
480
477
477
cf886aeddecd6f061f164e8f8e8240f5350218cb
bigcode/the-stack
train
68b5aff5bb2377ecf6121f73
train
function
def nCr(n, r): return math.factorial(n) // math.factorial(r) // math.factorial(n-r)
def nCr(n, r):
return math.factorial(n) // math.factorial(r) // math.factorial(n-r)
import scipy.io.wavfile as wav from sklearn import preprocessing import joblib #from sklearn.externals import joblib from IPython import embed import matplotlib.pyplot as plot import librosa plot.switch_backend('agg') import math import soundfile as sf def nCr(n, r):
64
64
27
7
56
andresperezlopez/DCASE2020
baseline/cls_feature_class.py
Python
nCr
nCr
20
21
20
20
56f59b64bec40031752dff5b12177ce48d283486
bigcode/the-stack
train
a993b1c84b0c8ee70371ad9c
train
class
class WithdrawTest(UnitETestFramework): def set_test_params(self): self.num_nodes = 3 esperanza_config = { 'dynastyLogoutDelay': LOGOUT_DYNASTY_DELAY, 'withdrawalEpochDelay': WITHDRAW_EPOCH_DELAY } json_params = json.dumps(esperanza_config) finalizer...
class WithdrawTest(UnitETestFramework):
def set_test_params(self): self.num_nodes = 3 esperanza_config = { 'dynastyLogoutDelay': LOGOUT_DYNASTY_DELAY, 'withdrawalEpochDelay': WITHDRAW_EPOCH_DELAY } json_params = json.dumps(esperanza_config) finalizer_node_params = ['-esperanzaconfig=' + js...
#!/usr/bin/env python3 # Copyright (c) 2018-2019 The Unit-e developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import UnitETestFramework from test_framework.util import ( assert_equal,...
145
256
2,802
8
136
thothd/unit-e
test/functional/finalization_withdraw.py
Python
WithdrawTest
WithdrawTest
24
302
24
24
d8c0bc30ad3c683ab5b28f14038fc3e5bd1d396e
bigcode/the-stack
train
d4b8428e1d934b06b46e44d0
train
class
class TestV1StatusCause(unittest.TestCase): """ V1StatusCause unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1StatusCause(self): """ Test V1StatusCause """ # FIXME: construct object with mandatory attributes with example val...
class TestV1StatusCause(unittest.TestCase):
""" V1StatusCause unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1StatusCause(self): """ Test V1StatusCause """ # FIXME: construct object with mandatory attributes with example values #model = kubernetes.client.model...
gen.git """ from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.models.v1_status_cause import V1StatusCause class TestV1StatusCause(unittest.TestCase):
64
64
94
10
53
iamneha/python
kubernetes/test/test_v1_status_cause.py
Python
TestV1StatusCause
TestV1StatusCause
25
40
25
25
cac89c0de8631c161ea2b970d3d47573d567178f
bigcode/the-stack
train
f902e0873a69cb083fbce747
train
function
@click.command() @click.argument('input_filepath', type=click.Path(exists=True)) @click.argument('output_filepath', type=click.Path()) def main(input_filepath, output_filepath): """ Runs data processing scripts to turn raw data from (../raw) into cleaned data ready to be analyzed (saved in ../processed). ...
@click.command() @click.argument('input_filepath', type=click.Path(exists=True)) @click.argument('output_filepath', type=click.Path()) def main(input_filepath, output_filepath):
""" Runs data processing scripts to turn raw data from (../raw) into cleaned data ready to be analyzed (saved in ../processed). """ logger = logging.getLogger(__name__) logger.info('making final data set from raw data')
# -*- coding: utf-8 -*- import os import click import logging from dotenv import find_dotenv, load_dotenv @click.command() @click.argument('input_filepath', type=click.Path(exists=True)) @click.argument('output_filepath', type=click.Path()) def main(input_filepath, output_filepath):
64
64
89
36
27
calangohc/titanic
src/data/make_dataset.py
Python
main
main
8
16
8
11
f4ffe60c04f0943a6aaf1c5c1b99847c4a9e98cd
bigcode/the-stack
train
b99bf66f1f7d9dfc719a655a
train
function
def add_infant_status(df): """ Add 'Male Infant' and 'Female Infant' categories :param df: Input Titanic DataFrame (with Name column) :return: df with [['Male Infant','Female Infant']] """ # Get Maximum age to max out for loop max_age = df['Age'].max() # Get Survival ra...
def add_infant_status(df):
""" Add 'Male Infant' and 'Female Infant' categories :param df: Input Titanic DataFrame (with Name column) :return: df with [['Male Infant','Female Infant']] """ # Get Maximum age to max out for loop max_age = df['Age'].max() # Get Survival rates by gender male_surv...
load_dotenv(find_dotenv()) main() def add_title(df): """ Add Title to DataFrame (Mr., Miss., etc) :param df: Input Titanic DataFrame (with Name column) :return: df with ['Title'] column """ # Creates 'names' pd.Series names = df['Name'] # Split 'names' by ', ' and get the l...
154
154
515
7
146
calangohc/titanic
src/data/make_dataset.py
Python
add_infant_status
add_infant_status
54
108
54
54
6be787a217bd8f03c95caea32e4483fcc16bff3e
bigcode/the-stack
train
ebc045ec8f7dc9c0adc853e1
train
function
def add_title(df): """ Add Title to DataFrame (Mr., Miss., etc) :param df: Input Titanic DataFrame (with Name column) :return: df with ['Title'] column """ # Creates 'names' pd.Series names = df['Name'] # Split 'names' by ', ' and get the latter value proc_names = names.str.split(...
def add_title(df):
""" Add Title to DataFrame (Mr., Miss., etc) :param df: Input Titanic DataFrame (with Name column) :return: df with ['Title'] column """ # Creates 'names' pd.Series names = df['Name'] # Split 'names' by ', ' and get the latter value proc_names = names.str.split(', ').str[-1] ...
.path.join(os.path.dirname(__file__), os.pardir, os.pardir) # find .env automagically by walking up directories until it's found, then # load up the .env entries as environment variables load_dotenv(find_dotenv()) main() def add_title(df):
64
64
136
5
59
calangohc/titanic
src/data/make_dataset.py
Python
add_title
add_title
33
51
33
33
59f485b316b894c2c8e61072256e79ec3b1aa547
bigcode/the-stack
train
69e190abf41ba984a5f5fd8a
train
class
class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('-C', '--no-center', default=True, action='store_false', dest='center', help='Do not center the pattern in the grid.'), make_option('-p', '--pattern', he...
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + ( make_option('-C', '--no-center', default=True, action='store_false', dest='center', help='Do not center the pattern in the grid.'), make_option('-p', '--pattern', help='The initial state of the gr...
from optparse import make_option import asyncio from django.core.management.base import CommandError, NoArgsCommand from ...client import reset, run class Command(NoArgsCommand):
37
179
597
6
30
aaugustin/django-c10k-demo
gameoflife/management/commands/gameoflife.py
Python
Command
Command
10
77
10
11
287b16e0c9231c3f8b1ea3d19694b879d0d7bb5b
bigcode/the-stack
train
d1ea4594ce35599d0642bc7f
train
function
def calc_fractal_dim(g): """ Calculates Fractal Dimension of Binarized Image g :param g: Binarized ndarray representing Image matrix :return D: fractal dimension of g. """ w, h = g.shape L = int(math.log2(w)) # Populating set of Scaling Factors S = [1 / 2 ** i for i in range(1, L -...
def calc_fractal_dim(g):
""" Calculates Fractal Dimension of Binarized Image g :param g: Binarized ndarray representing Image matrix :return D: fractal dimension of g. """ w, h = g.shape L = int(math.log2(w)) # Populating set of Scaling Factors S = [1 / 2 ** i for i in range(1, L - 2)] # checks if a b...
(f): d = img.filters.gaussian_filter(f, sigma=0.50, mode="reflect") - \ img.filters.gaussian_filter(f, sigma=1.00, mode="reflect") d = np.abs(d) m = d.max() d[d< 0.1*m] = 0 d[d>=0.1*m] = 1 return img.morphology.binary_closing(d) def calc_fractal_dim(g):
100
100
335
7
93
saikat-roy/Uni-Bonn-Pattern-Recognition
Project1/task1_5/fractal_dim.py
Python
calc_fractal_dim
calc_fractal_dim
18
48
18
18
040a3fc5431b0e8e66333d34796c07483f86d73c
bigcode/the-stack
train
9534b3d6de90f573dd7e79b1
train
function
def foreground2_bin_img(f): d = img.filters.gaussian_filter(f, sigma=0.50, mode="reflect") - \ img.filters.gaussian_filter(f, sigma=1.00, mode="reflect") d = np.abs(d) m = d.max() d[d< 0.1*m] = 0 d[d>=0.1*m] = 1 return img.morphology.binary_closing(d)
def foreground2_bin_img(f):
d = img.filters.gaussian_filter(f, sigma=0.50, mode="reflect") - \ img.filters.gaussian_filter(f, sigma=1.00, mode="reflect") d = np.abs(d) m = d.max() d[d< 0.1*m] = 0 d[d>=0.1*m] = 1 return img.morphology.binary_closing(d)
import math import numpy as np import scipy.misc as msc import scipy.ndimage as img def foreground2_bin_img(f):
29
64
98
7
21
saikat-roy/Uni-Bonn-Pattern-Recognition
Project1/task1_5/fractal_dim.py
Python
foreground2_bin_img
foreground2_bin_img
7
15
7
8
cbfa249c42a2321dcf07fa7fa25badfe8700750f
bigcode/the-stack
train
e7f92c634c6b2523a4962848
train
function
def main(args): print("Loading config file: ", args.config) params = utils.load_config_file(args.config) params["dataset_paths"] = utils.format_dataset_path( params["dataset_paths"]) if "nyu" not in params: params["nyu"] = False # Data loading code print("Creating data loaders....
def main(args):
print("Loading config file: ", args.config) params = utils.load_config_file(args.config) params["dataset_paths"] = utils.format_dataset_path( params["dataset_paths"]) if "nyu" not in params: params["nyu"] = False # Data loading code print("Creating data loaders...") if param...
import argparse import os import sys import time from pathlib import Path import numpy as np import torch sys.path.append(os.getcwd()) import models import utils try: dataset_path = os.environ["DATASETS_ABS_PATH"] sys.path.append(dataset_path) except KeyError: print("Datasets.py absolute path not found ...
84
121
405
4
79
appliedinnovation/fast-depth
fastdepth/scripts/compare_models.py
Python
main
main
23
75
23
24
853109750d2e1eb429ec31db47f58998daa20620
bigcode/the-stack
train
cf4896062fb17122b8846560
train
function
def compare_models(params, loader, models): with torch.no_grad(): for i, (input, target) in enumerate(loader): input, target = input.to(params["device"]), target.to( params["device"]) # Inference predictions = [] for model in models: ...
def compare_models(params, loader, models):
with torch.no_grad(): for i, (input, target) in enumerate(loader): input, target = input.to(params["device"]), target.to( params["device"]) # Inference predictions = [] for model in models: prediction = model(input) ...
output_directory = os.path.join(params["save_folder"], ".".join(model_names)) if not os.path.exists(output_directory): os.makedirs(output_directory) params["output_directory"] = output_directory print("Saving results to " + output_directory) compare_models(params, data_loader, models) def c...
73
73
244
9
64
appliedinnovation/fast-depth
fastdepth/scripts/compare_models.py
Python
compare_models
compare_models
78
111
78
78
fc0ffd41a6c6f9ecb475a6a43eb267a91c72861b
bigcode/the-stack
train
44871275a1c9a9a1462ede62
train
class
class ProjectSortKey(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ allowed enum values """ CREATED_AT = "created_at" UPDATED_AT = "updated_at" NAME = "name" allowable_values ...
class ProjectSortKey(object):
"""NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ allowed enum values """ CREATED_AT = "created_at" UPDATED_AT = "updated_at" NAME = "name" allowable_values = [CREATED_AT, UPDATED_AT, NAM...
# coding: utf-8 """ pollination-server Pollination Server OpenAPI Definition # noqa: E501 The version of the OpenAPI document: 0.16.0 Contact: info@pollination.cloud Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from pollination_sdk.configu...
93
158
529
6
86
pollination/python-sdk
pollination_sdk/models/project_sort_key.py
Python
ProjectSortKey
ProjectSortKey
22
102
22
22
9990d67d83049c71f5ee1c4eb0d8fcd7684628ba
bigcode/the-stack
train
783d6ecddd6effa46e59da38
train
class
class TestSimple(unittest.TestCase): @classmethod def setUpClass(self): # NOTE: 需要在环境变量中设置 TUSHARE_TOKEN ts_token = os.getenv("TUSHARE_TOKEN") self.start = "20190101" self.end = "20200101" self.codes = ["000001.SZ"] self.indexs = ["000001.SH", "399001.SZ"] ...
class TestSimple(unittest.TestCase): @classmethod
def setUpClass(self): # NOTE: 需要在环境变量中设置 TUSHARE_TOKEN ts_token = os.getenv("TUSHARE_TOKEN") self.start = "20190101" self.end = "20200101" self.codes = ["000001.SZ"] self.indexs = ["000001.SH", "399001.SZ"] # self.indexs = [] self.show_plot = False ...
# -*- coding:utf-8 -*- import datetime import logging import os import random import unittest from tenvs.envs.simple import SimpleEnv from tenvs.market import Market logging.root.setLevel(logging.INFO) class TestSimple(unittest.TestCase): @classmethod
57
222
741
11
46
tradingAI/tenvs
tenvs/envs/simple_test.py
Python
TestSimple
TestSimple
15
92
15
16
f2c411a300702f7f28a1483b5524170afe17963c
bigcode/the-stack
train
b76293e8fa98bb669e6e4663
train
class
class TitleListBoxRow(gtk.ListBoxRow): __gsignals__ = { "remove_row" : (GObject.SIGNAL_RUN_FIRST,None,(GObject.TYPE_PYOBJECT,)) } def __init__(self,Label_text,*args,**kwargs): gtk.ListBoxRow.__init__(self, *args,**kwargs) self.RowWidgets = {} self.RowWidgets["Box"] = gtk.Box() s...
class TitleListBoxRow(gtk.ListBoxRow):
__gsignals__ = { "remove_row" : (GObject.SIGNAL_RUN_FIRST,None,(GObject.TYPE_PYOBJECT,)) } def __init__(self,Label_text,*args,**kwargs): gtk.ListBoxRow.__init__(self, *args,**kwargs) self.RowWidgets = {} self.RowWidgets["Box"] = gtk.Box() self.RowWidgets["Title Label"] = gtk.Lab...
:0.3 # #usage :defineds a custom ListBoxRow widget # #notes : # #python_version :3.6.9 # #=======...
78
78
262
11
66
asandova/Manga-Desktop-Reader
gtk3/TitleListBoxRow.py
Python
TitleListBoxRow
TitleListBoxRow
18
40
18
18
5c7fad0812bd272e7ecd0d983877da734209b086
bigcode/the-stack
train
8cd216fda5f99dc4a51fbe4d
train
class
class DataclassJSONEncoder(json.JSONEncoder): def default(self, entity: Any) -> Any: if attr.has(type(entity)): return attr.asdict(entity) if dataclasses.is_dataclass(entity): return dataclasses.asdict(entity) if isinstance(entity, (datetime, date)): retur...
class DataclassJSONEncoder(json.JSONEncoder):
def default(self, entity: Any) -> Any: if attr.has(type(entity)): return attr.asdict(entity) if dataclasses.is_dataclass(entity): return dataclasses.asdict(entity) if isinstance(entity, (datetime, date)): return entity.isoformat() return json_util....
import dataclasses import json from datetime import datetime, date from typing import Any import attr from bson import json_util class DataclassJSONEncoder(json.JSONEncoder):
37
64
75
9
27
Ellipsanime/openpype-shotgun
shotgrid_leecher/utils/encoders.py
Python
DataclassJSONEncoder
DataclassJSONEncoder
10
18
10
10
5099ecaadb03496018affb8c018b07534974decf
bigcode/the-stack
train
96008b1999f0522bf2086274
train
class
class SentencePairDatasetForSBERT(Dataset): def __init__(self, file_dir, is_train, pretrained, shuffle_order=False, aug_data=False, len_limit=512, clip='head'): self.is_train = is_train self.shuffle_order = shuffle_order self.aug_data = aug_data self.total_source_input_ids = [] ...
class SentencePairDatasetForSBERT(Dataset):
def __init__(self, file_dir, is_train, pretrained, shuffle_order=False, aug_data=False, len_limit=512, clip='head'): self.is_train = is_train self.shuffle_order = shuffle_order self.aug_data = aug_data self.total_source_input_ids = [] # token_types are no longer neccessary if...
)+1) assert len(input_ids) <= len_limit and len(input_types) <= len_limit self.total_input_ids.append(input_ids) self.total_input_types.append(input_types) self.max_input_len = max([len(s) for s in self.total_input_ids]) print("max length: ", self.max_input_len)...
256
256
1,120
10
245
MingjieWang0606/2021-Sohu-Text-Matching-TOP2
sohu_matching/src/data.py
Python
SentencePairDatasetForSBERT
SentencePairDatasetForSBERT
111
226
111
111
c38d7b06f53e6e0bdb88a76c15a138f56d68d33d
bigcode/the-stack
train
6e2c29001d9acad25003fc05
train
class
class SentencePairDataset(Dataset): def __init__(self, file_dir, is_train, pretrained, shuffle_order=False, aug_data=False, len_limit=512, clip='tail'): self.is_train = is_train self.shuffle_order = shuffle_order self.aug_data = aug_data self.total_input_ids = [] self.total_i...
class SentencePairDataset(Dataset):
def __init__(self, file_dir, is_train, pretrained, shuffle_order=False, aug_data=False, len_limit=512, clip='tail'): self.is_train = is_train self.shuffle_order = shuffle_order self.aug_data = aug_data self.total_input_ids = [] self.total_input_types = [] # use AutoT...
import pandas as pd import torch from torch.utils.data import Dataset, DataLoader from transformers import BertTokenizer, AutoTokenizer from utils import * from sklearn.model_selection import train_test_split import json from tqdm import tqdm class SentencePairDataset(Dataset):
55
256
975
7
47
MingjieWang0606/2021-Sohu-Text-Matching-TOP2
sohu_matching/src/data.py
Python
SentencePairDataset
SentencePairDataset
11
108
11
11
4a465421a1c5e574e88523cd1ad85137974aa375
bigcode/the-stack
train
6a0760ce4a8e13b7b7f1f1bc
train
class
class SentencePairDatasetWithType(Dataset): def __init__(self, file_dir, is_train, pretrained, shuffle_order=False, aug_data=False, len_limit=512, clip='head'): self.is_train = is_train self.shuffle_order = shuffle_order self.aug_data = aug_data self.total_input_ids = [] self...
class SentencePairDatasetWithType(Dataset):
def __init__(self, file_dir, is_train, pretrained, shuffle_order=False, aug_data=False, len_limit=512, clip='head'): self.is_train = is_train self.shuffle_order = shuffle_order self.aug_data = aug_data self.total_input_ids = [] self.total_input_types = [] self.sample_...
_input_ids]) self.max_target_input_len = max([len(s) for s in self.total_target_input_ids]) print("max source length: ", self.max_source_input_len) print("max target length: ", self.max_target_input_len) def __len__(self): return len(self.total_target_input_ids) def __getitem__...
256
256
1,168
9
246
MingjieWang0606/2021-Sohu-Text-Matching-TOP2
sohu_matching/src/data.py
Python
SentencePairDatasetWithType
SentencePairDatasetWithType
229
346
229
229
1ce2db5395516bf09b27ff5119fb989c994855af
bigcode/the-stack
train
2c529d1c0f41037822bd6584
train
class
class Migration(migrations.Migration): dependencies = [ ('bukti', '0001_initial'), ] operations = [ migrations.AddField( model_name='datapembeli', name='kelurahan', field=models.CharField(default='null', max_length=100), ), migrations.Add...
class Migration(migrations.Migration):
dependencies = [ ('bukti', '0001_initial'), ] operations = [ migrations.AddField( model_name='datapembeli', name='kelurahan', field=models.CharField(default='null', max_length=100), ), migrations.AddField( model_name='datapembe...
# Generated by Django 3.2.13 on 2022-04-22 12:50 from django.db import migrations, models class Migration(migrations.Migration):
38
64
208
7
30
StevenSamuelH/motogpmerch
bukti/migrations/0002_auto_20220422_1950.py
Python
Migration
Migration
6
38
6
7
66a3ce898256260a3965aff2e9005faaa9be2e7c
bigcode/the-stack
train
d70dc505e2d6f717897557f5
train
class
class SAC(Agent): def __init__(self, obs_space, action_space, discount, lr=1e-4, seed=None): super(SAC, self).__init__(obs_space, action_space, discount, lr, seed) # epsilon decay self.initial_eps = 1.0 ...
class SAC(Agent):
def __init__(self, obs_space, action_space, discount, lr=1e-4, seed=None): super(SAC, self).__init__(obs_space, action_space, discount, lr, seed) # epsilon decay self.initial_eps = 1.0 self.end_eps ...
import os import copy import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Categorical from .agent import Agent from ..utils.evaluation import entropy from ..networks.critic import Critic from ..networks.actor import Actor class SAC(Agent):
72
256
1,794
5
66
kschweig/HopfieldOfflineRL
source/agents/sac.py
Python
SAC
SAC
14
196
14
15
f4190ad4983774dcfded5d4ad03ce08e1fd4f27d
bigcode/the-stack
train
d73c1ad89f7bf9683f4035bd
train
function
def train(model, device, train_loader, log_interval, optimizer, epoch): model.train() for batch_idx, row in enumerate(train_loader): data, target = row['image'].to(device), row['digit'].to(device) optimizer.zero_grad() output = model(data) loss = F.nll_loss(output, target) loss.backward() op...
def train(model, device, train_loader, log_interval, optimizer, epoch):
model.train() for batch_idx, row in enumerate(train_loader): data, target = row['image'].to(device), row['digit'].to(device) optimizer.zero_grad() output = model(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() if batch_idx % log_interval == 0: print('Train ...
import DEFAULT_MNIST_DATA_PATH from pycarbon.tests import DEFAULT_CARBONSDK_PATH from petastorm.pytorch import DataLoader from petastorm import TransformSpec from examples.mnist.pytorch_example import Net def train(model, device, train_loader, log_interval, optimizer, epoch):
64
64
121
16
47
pratyakshsharma/carbondata
python/pycarbon/tests/mnist/dataset_with_unischema/pytorch_example_carbon.py
Python
train
train
35
46
35
35
358cbfe65bfe987f31708bfe1c7bb1e40706957d
bigcode/the-stack
train
3e1f1a00f06da594156ef130
train
function
def evaluation(model, device, test_loader): model.eval() test_loss = 0 correct = 0 count = 0 with torch.no_grad(): for row in test_loader: data, target = row['image'].to(device), row['digit'].to(device) output = model(data) test_loss += F.nll_loss(output, target, reduction='sum').item() ...
def evaluation(model, device, test_loader):
model.eval() test_loss = 0 correct = 0 count = 0 with torch.no_grad(): for row in test_loader: data, target = row['image'].to(device), row['digit'].to(device) output = model(data) test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss pred = output.max...
_loss(output, target) loss.backward() optimizer.step() if batch_idx % log_interval == 0: print('Train Epoch: {} [{}]\tLoss: {:.6f}'.format( epoch, batch_idx * len(data), loss.item())) def evaluation(model, device, test_loader):
63
64
196
9
54
pratyakshsharma/carbondata
python/pycarbon/tests/mnist/dataset_with_unischema/pytorch_example_carbon.py
Python
evaluation
evaluation
49
65
49
49
6fce72efc8216b972c4f5dd1b48637dc9ef6a9bc
bigcode/the-stack
train
a3514767b9d650646e1a069e
train
function
def main(): # Training settings parser = argparse.ArgumentParser(description='Pycarbon MNIST Example') default_dataset_url = 'file://{}'.format(DEFAULT_MNIST_DATA_PATH) parser.add_argument('--dataset-url', type=str, default=default_dataset_url, metavar='S', help='hdfs...
def main(): # Training settings
parser = argparse.ArgumentParser(description='Pycarbon MNIST Example') default_dataset_url = 'file://{}'.format(DEFAULT_MNIST_DATA_PATH) parser.add_argument('--dataset-url', type=str, default=default_dataset_url, metavar='S', help='hdfs:// or file:/// URL to the MNIST p...
loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format( test_loss, correct, count, 100. * correct / count)) def _transform_row(mnist_row): # For this example, the images are stored as simpler ndarray (28,28), but the # training network expects 3-dim images, hence the additional lambda transform. transform = tra...
220
220
734
8
211
pratyakshsharma/carbondata
python/pycarbon/tests/mnist/dataset_with_unischema/pytorch_example_carbon.py
Python
main
main
87
151
87
88
2aed241f5aa02d454dc10618fea9a98fbe0c4e5d
bigcode/the-stack
train
b55b9159a6100c29f7551e84
train
function
def _transform_row(mnist_row): # For this example, the images are stored as simpler ndarray (28,28), but the # training network expects 3-dim images, hence the additional lambda transform. transform = transforms.Compose([ transforms.Lambda(lambda nd: nd.reshape(28, 28, 1)), transforms.ToTensor(), tran...
def _transform_row(mnist_row): # For this example, the images are stored as simpler ndarray (28,28), but the # training network expects 3-dim images, hence the additional lambda transform.
transform = transforms.Compose([ transforms.Lambda(lambda nd: nd.reshape(28, 28, 1)), transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ]) # In addition, the petastorm pytorch DataLoader does not distinguish the notion of # data or target transform, but that actually gives the user m...
format( test_loss, correct, count, 100. * correct / count)) def _transform_row(mnist_row): # For this example, the images are stored as simpler ndarray (28,28), but the # training network expects 3-dim images, hence the additional lambda transform.
64
64
174
46
18
pratyakshsharma/carbondata
python/pycarbon/tests/mnist/dataset_with_unischema/pytorch_example_carbon.py
Python
_transform_row
_transform_row
68
84
68
70
cfd37a3fe06efa31474464a0a33f05fad75148a2
bigcode/the-stack
train
1835e25c0470a86e356fa4c0
train
class
class ShingleBased: def __init__(self, k=3): self.k = k def get_k(self): return self.k def get_profile(self, string): shingles = dict() no_space_str = _SPACE_PATTERN.sub(" ", string) for i in range(len(no_space_str) - self.k + 1): shingle = no_space_str...
class ShingleBased:
def __init__(self, k=3): self.k = k def get_k(self): return self.k def get_profile(self, string): shingles = dict() no_space_str = _SPACE_PATTERN.sub(" ", string) for i in range(len(no_space_str) - self.k + 1): shingle = no_space_str[i:i + self.k] ...
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import re _SPACE_PATTERN = re.compile("\\s+") class ShingleBased:
64
64
131
5
58
lanzkron/python-string-similarity
strsimpy/shingle_based.py
Python
ShingleBased
ShingleBased
26
44
26
27
e3fbffcd7f297a45bb1c09018ca196d674a7aba0
bigcode/the-stack
train
9112c5d67064600ea5eeb4ce
train
function
def text_mining(path,white_list=None,black_list=None,lower_case=False,remove_punctuation=False,encoding='utf-8',char_counting=False): '''Manual white_list : None or str containing white list black_list : None or str containing black list lower_case : If True, convert text to lower_case remove_punctuation : r...
def text_mining(path,white_list=None,black_list=None,lower_case=False,remove_punctuation=False,encoding='utf-8',char_counting=False):
'''Manual white_list : None or str containing white list black_list : None or str containing black list lower_case : If True, convert text to lower_case remove_punctuation : remove punctuation listed in string.punctuation and predefined black list encoding : default is utf-8 char_counting : If True, cou...
import numpy as np import string import pandas as pd def text_mining(path,white_list=None,black_list=None,lower_case=False,remove_punctuation=False,encoding='utf-8',char_counting=False):
47
207
693
34
12
yasirroni/myNafiun
lib/text_mining.py
Python
text_mining
text_mining
4
85
4
4
09f89e5196ffaf08ada48ec13706cca9f699731d
bigcode/the-stack
train
587ce8fd6ee1aec09450d7c0
train
class
class JSONAdapterInterfaceConan(ConanFile): name = "JSONAdapterInterface" description = "Interface of library-agnostic API for C++ to work with JSON documents" url = "https://github.com/systelab/cpp-json-adapter" homepage = "https://github.com/systelab/cpp-json-adapter" author = "CSW <csw@werfen.com...
class JSONAdapterInterfaceConan(ConanFile):
name = "JSONAdapterInterface" description = "Interface of library-agnostic API for C++ to work with JSON documents" url = "https://github.com/systelab/cpp-json-adapter" homepage = "https://github.com/systelab/cpp-json-adapter" author = "CSW <csw@werfen.com>" topics = ("conan", "json", "adapter",...
from conans import ConanFile class JSONAdapterInterfaceConan(ConanFile):
18
64
183
11
6
systelab/cpp-json-adapter
JSONAdapterInterface/conanfile.py
Python
JSONAdapterInterfaceConan
JSONAdapterInterfaceConan
4
20
4
4
2914c9f5ee1af447eaaa80e3bc165fafc5c8b07e
bigcode/the-stack
train
327dafbed5c98ede79e1db42
train
class
class TestClient: def test_client(self): from pyEX import Client c = Client("test") def test_client_notoken(self): import os from pyEX import Client, PyEXception tmp = os.environ.pop("IEX_TOKEN", "") try: Client() assert False e...
class TestClient:
def test_client(self): from pyEX import Client c = Client("test") def test_client_notoken(self): import os from pyEX import Client, PyEXception tmp = os.environ.pop("IEX_TOKEN", "") try: Client() assert False except PyEXception:...
authors. # # This file is part of the pyEX library, distributed under the terms of # the Apache License 2.0. The full license can be found in the LICENSE file. # # for Coverage from mock import MagicMock, patch C = "AAPL" class TestClient:
64
64
89
4
60
adamklaff/pyEX
pyEX/tests/test_client.py
Python
TestClient
TestClient
15
32
15
15
668f52f7ea813355a3511777a7917b5d5e4052c4
bigcode/the-stack
train
547104347d33cea64c775e8d
train
class
class IPlottable2d(IModel2d): plot_type = Enum("line", "scatter") x_label = Str y_label = Str
class IPlottable2d(IModel2d):
plot_type = Enum("line", "scatter") x_label = Str y_label = Str
# Enthought library imports. from traits.api import Enum, Str # Local imports. from attractors.model.i_model_2d import IModel2d class IPlottable2d(IModel2d):
45
64
35
12
32
anshsrtv/envisage
examples/plugins/tasks/attractors/model/i_plottable_2d.py
Python
IPlottable2d
IPlottable2d
8
13
8
9
0ad12809134e44d0bf19286e8faef2f3e6a8d447
bigcode/the-stack
train
cde4ffe600c7d5d874a36a78
train
function
def infer_namespace(node, context=None): callsite = arguments.CallSite.from_call(node, context=context) if not callsite.keyword_arguments: # Cannot make sense of it. raise UseInferenceDefault() class_node = nodes.ClassDef("Namespace", "docstring") class_node.parent = node.parent for...
def infer_namespace(node, context=None):
callsite = arguments.CallSite.from_call(node, context=context) if not callsite.keyword_arguments: # Cannot make sense of it. raise UseInferenceDefault() class_node = nodes.ClassDef("Namespace", "docstring") class_node.parent = node.parent for attr in set(callsite.keyword_arguments):...
from astroid import arguments, inference_tip, nodes from astroid.exceptions import UseInferenceDefault from astroid.manager import AstroidManager def infer_namespace(node, context=None):
37
64
123
8
28
hwaipy/InteractionFreeNode
runtime/python/Lib/site-packages/astroid/brain/brain_argparse.py
Python
infer_namespace
infer_namespace
6
19
6
6
c691812e97d61a48119126147bccd1ccce4c7f1a
bigcode/the-stack
train
d03ff4f2e9a5b7cd2e5aaa5b
train
function
def _looks_like_namespace(node): func = node.func if isinstance(func, nodes.Attribute): return ( func.attrname == "Namespace" and isinstance(func.expr, nodes.Name) and func.expr.name == "argparse" ) return False
def _looks_like_namespace(node):
func = node.func if isinstance(func, nodes.Attribute): return ( func.attrname == "Namespace" and isinstance(func.expr, nodes.Name) and func.expr.name == "argparse" ) return False
for attr in set(callsite.keyword_arguments): fake_node = nodes.EmptyNode() fake_node.parent = class_node fake_node.attrname = attr class_node.instance_attrs[attr] = [fake_node] return iter((class_node.instantiate_class(),)) def _looks_like_namespace(node):
64
64
57
7
57
hwaipy/InteractionFreeNode
runtime/python/Lib/site-packages/astroid/brain/brain_argparse.py
Python
_looks_like_namespace
_looks_like_namespace
22
30
22
22
90f31d01a331da219009472c4ecb7b019eb935b4
bigcode/the-stack
train
cb361cc1c622815fe51d15e7
train
class
class DatabaseApi: def __init__(self, database: Database): self._database = database @property def _session(self) -> Session: return self._database.session def _query(self, cls, filters=(), preload=()) -> Query: query = self._session.query(cls).options(joinedload(rel) for rel ...
class DatabaseApi:
def __init__(self, database: Database): self._database = database @property def _session(self) -> Session: return self._database.session def _query(self, cls, filters=(), preload=()) -> Query: query = self._session.query(cls).options(joinedload(rel) for rel in preload) ...
import sqlalchemy.exc import sqlalchemy.event from sqlalchemy.orm.query import Query from sqlalchemy.orm.session import Session from sqlalchemy.orm import ( joinedload ) from .db import Database from .schema import SchemaBase class DatabaseApi:
49
108
361
4
44
1nfiniteloop/unix-accounts
src/unix_accounts/storage_sqlite/sqlite_api.py
Python
DatabaseApi
DatabaseApi
14
62
14
15
2906d4f2af34c59e791ce8b3c85370563778e5e1
bigcode/the-stack
train
5a20da69804a80293845420b
train
function
def setup_function(m): config.timeout = 4 set_driver(get_test_driver()) config.app_host = 'file://' + os.path.abspath(os.path.dirname(__file__)) + '/../../resources/orderapp/'
def setup_function(m):
config.timeout = 4 set_driver(get_test_driver()) config.app_host = 'file://' + os.path.abspath(os.path.dirname(__file__)) + '/../../resources/orderapp/'
OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os from selene import config from selene.browser import set_driver, driver from tests.acceptance.helpers.helper import get_test_driver from tests.examples.order.app_model.order_widgets import Order def setup_function(m):
64
64
44
5
58
kentastik/selene
tests/examples/order/order_test.py
Python
setup_function
setup_function
31
34
31
31
89bb29cf1a0ebb9047d16dd0fafbef265048f9b9
bigcode/the-stack
train
2df446351f77c47df3af60dd
train
function
def teardown_function(m): driver().quit() config.app_host = ''
def teardown_function(m):
driver().quit() config.app_host = ''
_test_driver from tests.examples.order.app_model.order_widgets import Order def setup_function(m): config.timeout = 4 set_driver(get_test_driver()) config.app_host = 'file://' + os.path.abspath(os.path.dirname(__file__)) + '/../../resources/orderapp/' def teardown_function(m):
63
64
16
5
58
kentastik/selene
tests/examples/order/order_test.py
Python
teardown_function
teardown_function
37
39
37
37
f49135b790d612f086ebde43dc05fdf77d3045e8
bigcode/the-stack
train
0bff324fe18845d20bcf373c
train
function
def test_it_fills_order(): order = Order() order.open() order.details.fill_with(first_name='Johanna', last_name='Smith', salutation='Mrs') item = order.add_item_with(name='New Test Item', other_data='Some other specific data') item.show_advanced_options_selector.click() item.add_advanced_optio...
def test_it_fills_order():
order = Order() order.open() order.details.fill_with(first_name='Johanna', last_name='Smith', salutation='Mrs') item = order.add_item_with(name='New Test Item', other_data='Some other specific data') item.show_advanced_options_selector.click() item.add_advanced_options( [{'option_type'...
config.timeout = 4 set_driver(get_test_driver()) config.app_host = 'file://' + os.path.abspath(os.path.dirname(__file__)) + '/../../resources/orderapp/' def teardown_function(m): driver().quit() config.app_host = '' def test_it_fills_order():
63
64
183
7
56
kentastik/selene
tests/examples/order/order_test.py
Python
test_it_fills_order
test_it_fills_order
42
62
42
42
2f97ed0967698cfb6fdd9750a01ea9cee248ebbb
bigcode/the-stack
train
b843335bddcdd50e282ced01
train
class
class ActorCritic: @store_args def __init__(self, inputs_tf, dimo, dimg, dimu, max_u, o_stats, g_stats, hidden, layers, **kwargs): """The actor-critic network and related training code. Args: inputs_tf (dict of tensors): all necessary inputs for the network: the ...
class ActorCritic: @store_args
def __init__(self, inputs_tf, dimo, dimg, dimu, max_u, o_stats, g_stats, hidden, layers, **kwargs): """The actor-critic network and related training code. Args: inputs_tf (dict of tensors): all necessary inputs for the network: the observation (o), the g...
import tensorflow as tf from util import store_args, nn class ActorCritic: @store_args
23
144
480
10
12
cerrno/fetchit-rl-grasping
lvs-exploration/actor_critic.py
Python
ActorCritic
ActorCritic
5
48
5
7
094ea670d99d0b4ebf64a17c147aaf219b22423f
bigcode/the-stack
train
5005da3202469d82c4c8e17f
train
class
class MyWindow(QWidget): def __init__(self, *args): QWidget.__init__(self, *args) # data self.tabledata = [ ("apple", "red", "small"), ("apple", "red", "medium"), ("apple", "green", "small"), ("banana", "yellow", "large"), ] se...
class MyWindow(QWidget):
def __init__(self, *args): QWidget.__init__(self, *args) # data self.tabledata = [ ("apple", "red", "small"), ("apple", "red", "medium"), ("apple", "green", "small"), ("banana", "yellow", "large"), ] self.header = ["fruit", "co...
QDialog, QApplication, QTreeView, QVBoxLayout, QWidget from PyQt5.QtWidgets import QAbstractItemView, QHBoxLayout, QPushButton, QTableView from PyQt5.Qt import QStandardItemModel, QStandardItem, QItemSelectionModel from PyQt5.QtGui import QColor from PyQt5.QtCore import Qt def main(): app = QApplication(sys.argv...
108
108
360
5
103
lbreede/pyqt-cheatsheet
QTreeView/main2.py
Python
MyWindow
MyWindow
23
80
23
23
5ca9321ffecf597a1df9d5822234c5e7fcfd5e57
bigcode/the-stack
train
d24a5ac2a07f6881494227bb
train
class
class MyTableModel(QAbstractTableModel): def __init__(self, datain, headerdata, parent=None, *args): """datain: a list of lists headerdata: a list of strings """ QAbstractTableModel.__init__(self, parent, *args) self.arraydata = datain self.headerdata = headerdata ...
class MyTableModel(QAbstractTableModel):
def __init__(self, datain, headerdata, parent=None, *args): """datain: a list of lists headerdata: a list of strings """ QAbstractTableModel.__init__(self, parent, *args) self.arraydata = datain self.headerdata = headerdata def rowCount(self, parent): ret...
hh.setStretchLastSection(True) # set column width to fit contents self.tv.resizeColumnsToContents() # set row height nrows = len(self.tabledata) for row in range(nrows): self.tv.setRowHeight(row, 18) # enable sorting self.tv.setSortingEnabled(True)...
80
80
269
9
71
lbreede/pyqt-cheatsheet
QTreeView/main2.py
Python
MyTableModel
MyTableModel
83
116
83
83
4e80fe71787db3d89d0d31d061efc9f4edef24d3
bigcode/the-stack
train
3073cd2c38ec2467072fdf9f
train
function
def main(): app = QApplication(sys.argv) w = MyWindow() w.show() sys.exit(app.exec_())
def main():
app = QApplication(sys.argv) w = MyWindow() w.show() sys.exit(app.exec_())
from PyQt5.QtWidgets import QAbstractItemView, QHBoxLayout, QPushButton, QTableView from PyQt5.Qt import QStandardItemModel, QStandardItem, QItemSelectionModel from PyQt5.QtGui import QColor from PyQt5.QtCore import Qt def main():
64
64
27
3
60
lbreede/pyqt-cheatsheet
QTreeView/main2.py
Python
main
main
16
20
16
16
39fe315f2cadfb9ccfbcf48f16983e9b807dce14
bigcode/the-stack
train
62e9b9c6d8a85bacfcc38059
train
class
class TestBigQueryTableSplitter(unittest.TestCase): def test_internal_need_default_project(self): with self.assertRaisesRegex(Exception, "INTERNAL: No default project is specified"): hook._split_tablename("dataset.table", None) @parameterized.expand([ ("project", "dataset", "table",...
class TestBigQueryTableSplitter(unittest.TestCase):
def test_internal_need_default_project(self): with self.assertRaisesRegex(Exception, "INTERNAL: No default project is specified"): hook._split_tablename("dataset.table", None) @parameterized.expand([ ("project", "dataset", "table", "dataset.table"), ("alternative", "dataset"...
another-project" schema = "SCHEMA" method_get = mock_get_service.return_value.tables.return_value.get method_execute = method_get.return_value.execute method_execute.return_value = {"schema": schema} bq_hook = hook.BigQueryHook() cursor = bq_hook.get_cursor() res...
143
143
477
10
133
dorranh/airflow
tests/providers/google/cloud/hooks/test_bigquery.py
Python
TestBigQueryTableSplitter
TestBigQueryTableSplitter
916
958
916
916
319f0058d6e23ec80553b30230a48aeadd5c23dc
bigcode/the-stack
train
83ec85a714c03be78bdc4ea3
train
class
class TestBigQueryBaseCursorMethodsDeprecationWarning(unittest.TestCase): @parameterized.expand([ ("create_empty_table",), ("create_empty_dataset",), ("get_dataset_tables",), ("delete_dataset",), ("create_external_table",), ("patch_table",), ("insert_all",), ...
class TestBigQueryBaseCursorMethodsDeprecationWarning(unittest.TestCase): @parameterized.expand([ ("create_empty_table",), ("create_empty_dataset",), ("get_dataset_tables",), ("delete_dataset",), ("create_external_table",), ("patch_table",), ("insert_all",), ...
def test_deprecation_warning(self, func_name, mock_bq_hook): args, kwargs = [1], {"param1": "val1"} new_path = re.escape(f"`airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.{func_name}`") message_pattern = r"This method is deprecated\.\s+Please use {}".format(new_path) mess...
class TestBigQueryBaseCursorMethodsDeprecationWarning(unittest.TestCase): @parameterized.expand([ ("create_empty_table",), ("create_empty_dataset",), ("get_dataset_tables",), ("delete_dataset",), ("create_external_table",), ("patch_table",), ("insert_all",), ...
203
123
412
203
0
dorranh/airflow
tests/providers/google/cloud/hooks/test_bigquery.py
Python
TestBigQueryBaseCursorMethodsDeprecationWarning
TestBigQueryBaseCursorMethodsDeprecationWarning
2,416
2,459
2,416
2,443
96200cb00ebdad61b79eeddcc0754827526c641b
bigcode/the-stack
train
54401794cd90fc31bf62e11f
train
class
class TestBigQueryHookRunWithConfiguration(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service"...
class TestBigQueryHookRunWithConfiguration(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service"...
def test_run_with_configuration_location(self, mock_get_service, mock_get_creds_and_proj_id): running_job_id = 'job_vjdi28vskdui2onru23' location = 'asia-east1' method = mock_get_service.return_value.jobs.return_value.get mock_get_service.return_value.jobs.return_value.insert.retur...
.assertEqual(bq_hook.location, 'US') class TestBigQueryHookRunWithConfiguration(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hoo...
80
80
267
70
10
dorranh/airflow
tests/providers/google/cloud/hooks/test_bigquery.py
Python
TestBigQueryHookRunWithConfiguration
TestBigQueryHookRunWithConfiguration
2,161
2,194
2,161
2,166
a9c6184c471eb6d7228ae1c9fadd127522a5fa38
bigcode/the-stack
train
102c169616af435177847d72
train
class
class TestBigQueryWithKMS(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service") def test_cr...
class TestBigQueryWithKMS(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_create_empty_table_with_kms(self, mock_get_service, mock_get_creds_and_proj_id): schema_fields = [ {"name": "id", "type": "STRING", "mode": "REQUIRED"} ] encryption_configuration = { "kms_key_name": "projects/p/locations/l/keyRings/k/cryptoKeys/c" } ...
_get_service, mock_get_creds_and_proj_id): running_job_id = 'job_vjdi28vskdui2onru23' location = 'asia-east1' method = mock_get_service.return_value.jobs.return_value.get mock_get_service.return_value.jobs.return_value.insert.return_value.execute.return_value = { 'jobRefere...
256
256
1,785
69
187
dorranh/airflow
tests/providers/google/cloud/hooks/test_bigquery.py
Python
TestBigQueryWithKMS
TestBigQueryWithKMS
2,197
2,413
2,197
2,202
9315e2b2a4eca4740e1af29a3acdd5b5afa4d01c
bigcode/the-stack
train
00be4a2a5fce134f3bb1eca4
train
class
class TestBigQueryHookLegacySql(unittest.TestCase): """Ensure `use_legacy_sql` param in `BigQueryHook` propagates properly.""" @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("ai...
class TestBigQueryHookLegacySql(unittest.TestCase):
"""Ensure `use_legacy_sql` param in `BigQueryHook` propagates properly.""" @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQuery...
) mocked_rwc.side_effect = run_with_config bq_hook = hook.BigQueryHook() bq_hook.run_query( sql='select 1', destination_dataset_table='my_dataset.my_table', cluster_fields=['field1', 'field2'], time_partitioning={'type': 'DAY'} ...
106
106
354
11
95
dorranh/airflow
tests/providers/google/cloud/hooks/test_bigquery.py
Python
TestBigQueryHookLegacySql
TestBigQueryHookLegacySql
2,111
2,140
2,111
2,111
b2083cbbebeeb695e28a20886b526b442ab64b72
bigcode/the-stack
train
1ad864d0c950228af9b94ea7
train
class
class TestBigQueryHookLocation(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service") @mock....
class TestBigQueryHookLocation(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service") @mock....
def test_location_propagates_properly( self, run_with_config, mock_get_service, mock_get_creds_and_proj_id ): bq_hook = hook.BigQueryHook(location=None) self.assertIsNone(bq_hook.location) self.assertIsNone(bq_hook.location) bq_hook.run_query(sql='select 1', location='US'...
class TestBigQueryHookLocation(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service") @mock....
89
64
192
89
0
dorranh/airflow
tests/providers/google/cloud/hooks/test_bigquery.py
Python
TestBigQueryHookLocation
TestBigQueryHookLocation
2,143
2,158
2,143
2,149
3642f9649bbf51bbd9e9b7b995b98d029a3dd55f
bigcode/the-stack
train
18ded7ad38a1c3c5db4b032c
train
class
class TestTimePartitioningInRunJob(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service") @m...
class TestTimePartitioningInRunJob(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service") @m...
def test_run_load_default(self, mocked_rwc, mock_get_service, mock_get_creds_and_proj_id): def run_with_config(config): self.assertIsNone(config['load'].get('timePartitioning')) mocked_rwc.side_effect = run_with_config bq_hook = hook.BigQueryHook() bq_hook.run_load( ...
_update_dataset(self, mock_get_service, mock_get_creds_and_proj_id): dataset_resource = { "kind": "bigquery#dataset", "location": "US", "id": "your-project:dataset_2_test", "datasetReference": { "projectId": "your-project", "dataset...
256
256
1,163
91
165
dorranh/airflow
tests/providers/google/cloud/hooks/test_bigquery.py
Python
TestTimePartitioningInRunJob
TestTimePartitioningInRunJob
1,886
2,011
1,886
1,892
6598d036c515b2800300e711c94ea023dc1ca470
bigcode/the-stack
train
60e9e680a1a5fa22d35f8116
train
class
class TestLabelsInRunJob(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service") @mock.patch(...
class TestLabelsInRunJob(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service") @mock.patch(...
def test_run_query_with_arg(self, mocked_rwc, mock_get_service, mock_get_creds_and_proj_id): def run_with_config(config): self.assertEqual( config['labels'], {'label1': 'test1', 'label2': 'test2'} ) mocked_rwc.side_effect = run_with_config bq_hook = ...
class TestLabelsInRunJob(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service") @mock.patch(...
89
67
225
89
0
dorranh/airflow
tests/providers/google/cloud/hooks/test_bigquery.py
Python
TestLabelsInRunJob
TestLabelsInRunJob
1,607
1,629
1,607
1,613
24e83fa0ead23341c1279d88b16052ad90c9a252
bigcode/the-stack
train
5fb4193aea221248d71a67a7
train
class
class TestClusteringInRunJob(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service") @mock.p...
class TestClusteringInRunJob(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service") @mock.p...
def test_run_load_default(self, mocked_rwc, mock_get_service, mock_get_creds_and_proj_id): def run_with_config(config): self.assertIsNone(config['load'].get('clustering')) mocked_rwc.side_effect = run_with_config bq_hook = hook.BigQueryHook() bq_hook.run_load( ...
1000} ) assert mocked_rwc.call_count == 1 def test_dollar_makes_partition(self): tp_out = _cleanse_time_partitioning('test.teast$20170101', {}) expect = { 'type': 'DAY' } self.assertEqual(tp_out, expect) def test_extra_time_partitioning_options(self...
248
248
827
90
158
dorranh/airflow
tests/providers/google/cloud/hooks/test_bigquery.py
Python
TestClusteringInRunJob
TestClusteringInRunJob
2,014
2,108
2,014
2,021
4735dcb0de8c073074df4d24c18c2e0f0c939931
bigcode/the-stack
train
8b03d929b6f8cb9936c78bfb
train
class
class TestTableDataOperations(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service") def tes...
class TestTableDataOperations(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_insert_all_succeed(self, mock_get_service, mock_get_creds_and_proj_id): rows = [ {"json": {"a_key": "a_value_0"}} ] body = { "rows": rows, "ignoreUnknownValues": False, "kind": "bigquery#tableDataInsertAllRequest", "skipInv...
\['CSV', " r"'NEWLINE_DELIMITED_JSON', 'AVRO', 'GOOGLE_SHEETS', 'DATASTORE_BACKUP', 'PARQUET'\]" ): bq_hook = hook.BigQueryHook() bq_hook.create_external_table( external_project_dataset_table='test.test', schema_fields='test_schema.json', ...
159
159
533
67
92
dorranh/airflow
tests/providers/google/cloud/hooks/test_bigquery.py
Python
TestTableDataOperations
TestTableDataOperations
1,000
1,059
1,000
1,005
1e3b96e44ee8d0df8ce5cdb74c8321b1b1147e94
bigcode/the-stack
train
153d73733864f7e7048877f1
train
class
class TestBigQueryHookMethods(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryConnection") @mock.patch("...
class TestBigQueryHookMethods(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryConnection") @mock.patch("...
def test_bigquery_client_creation( self, mock_build, mock_authorize, mock_bigquery_connection, mock_get_creds_and_proj_id ): bq_hook = hook.BigQueryHook() result = bq_hook.get_conn() mock_build.assert_called_once_with( 'bigquery', 'v2', http=mock_authorize.return_valu...
License for the # specific language governing permissions and limitations # under the License. import re import unittest from unittest import mock from googleapiclient.errors import HttpError from parameterized import parameterized from airflow import AirflowException from airflow.providers.google.cloud.hooks import...
256
256
8,994
102
153
dorranh/airflow
tests/providers/google/cloud/hooks/test_bigquery.py
Python
TestBigQueryHookMethods
TestBigQueryHookMethods
41
913
41
48
7eb2e9eb587498778248ba168febaacd14c69d51
bigcode/the-stack
train
71de72163b46dce7d7f88b22
train
class
class TestBigQueryExternalTableSourceFormat(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service...
class TestBigQueryExternalTableSourceFormat(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service...
def test_invalid_source_format(self, mock_get_service, mock_get_creds_and_proj_id): with self.assertRaisesRegex( Exception, r"JSON is not a valid source format. Please use one of the following types: \['CSV', " r"'NEWLINE_DELIMITED_JSON', 'AVRO', 'GOOGLE_SHEETS', 'DATASTO...
class TestBigQueryExternalTableSourceFormat(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service...
70
64
211
70
0
dorranh/airflow
tests/providers/google/cloud/hooks/test_bigquery.py
Python
TestBigQueryExternalTableSourceFormat
TestBigQueryExternalTableSourceFormat
979
997
979
984
be7b6f5b1de48da02e84ef61d2ab27a2e6a90a9e
bigcode/the-stack
train
4e173c7eeeeacac9a977a91b
train
class
class TestBigQueryHookSourceFormat(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service") de...
class TestBigQueryHookSourceFormat(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_invalid_source_format(self, mock_get_service, mock_get_creds_and_proj_id): with self.assertRaisesRegex( Exception, r"JSON is not a valid source format. Please use one of the following types: \['CSV', " r"'NEWLINE_DELIMITED_JSON', 'AVRO', 'GOOGLE_SHEETS', 'DATASTO...
class TestBigQueryHookSourceFormat(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
69
64
197
69
0
dorranh/airflow
tests/providers/google/cloud/hooks/test_bigquery.py
Python
TestBigQueryHookSourceFormat
TestBigQueryHookSourceFormat
961
976
961
966
1c20949a9ce428aa340fc9f2c53b41ca766d69ff
bigcode/the-stack
train
f391382e670f90ea97de7f91
train
class
class TestTableOperations(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service") def test_cr...
class TestTableOperations(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_create_view_fails_on_exception(self, mock_get_service, mock_get_creds_and_proj_id): view = { 'incorrect_key': 'SELECT * FROM `test-project-id.test_dataset_id.test_table_prefix*`', "useLegacySql": False } mock_service = mock_get_service.return_value m...
= [ {"json": {"a_key": "a_value_0"}} ] mock_service = mock_get_service.return_value method = mock_service.tabledata.return_value.insertAll method.return_value.execute.return_value = { "kind": "bigquery#tableDataInsertAllResponse", "insertErrors": [ ...
256
256
2,440
66
190
dorranh/airflow
tests/providers/google/cloud/hooks/test_bigquery.py
Python
TestTableOperations
TestTableOperations
1,062
1,328
1,062
1,067
71f2fd427efba003e4d17f8f8058ee1f4a0be786
bigcode/the-stack
train
43418d349136cd2c1c97f200
train
class
class TestBigQueryCursor(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service") @mock.patch...
class TestBigQueryCursor(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service") @mock.patch...
def test_execute_with_parameters(self, mocked_rwc, mock_get_service, mock_get_creds_and_proj_id): bq_hook = hook.BigQueryHook() bq_cursor = bq_hook.get_cursor() bq_cursor.execute("SELECT %(foo)s", {"foo": "bar"}) assert mocked_rwc.call_count == 1 assert mocked_rwc.has_calls( ...
id": "your-project:your_dataset.table2", "tableReference": { "projectId": "your-project", "datasetId": "your_dataset", "tableId": "table2" }, "type": "TABLE", "creation...
256
256
2,830
88
168
dorranh/airflow
tests/providers/google/cloud/hooks/test_bigquery.py
Python
TestBigQueryCursor
TestBigQueryCursor
1,331
1,604
1,331
1,338
07f79cbd9046d006d4bd8659452e4330549c3e15
bigcode/the-stack
train
b99a92d850c6d749da9b7e9b
train
class
class TestDatasetsOperations(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service") def test...
class TestDatasetsOperations(unittest.TestCase): @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook._get_credentials_and_project_id', return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_create_empty_dataset_no_dataset_id_err(self, mock_get_service, mock_get_creds_and_proj_id): with self.assertRaisesRegex( AirflowException, r"dataset_id not provided and datasetId not exist in the " r"datasetReference\. Impossible to create dataset" ): ...
return_value=(CREDENTIALS, PROJECT_ID) ) @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service") @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.run_with_configuration") def test_run_query_with_arg(self, mocked_rwc, mock_get_service, mock_get_creds_...
256
256
2,196
67
188
dorranh/airflow
tests/providers/google/cloud/hooks/test_bigquery.py
Python
TestDatasetsOperations
TestDatasetsOperations
1,632
1,883
1,632
1,637
91cf42a2d0861e0b2a81e0da843a4e27b6e80ced
bigcode/the-stack
train
fc533cef91e5b1e93583e081
train
function
def handler(event, context): print("event: {}".format(event)) return { 'bucket': event['Records'][0]['s3']['bucket']['name'], 'object': event['Records'][0]['s3']['object']['key'], }
def handler(event, context):
print("event: {}".format(event)) return { 'bucket': event['Records'][0]['s3']['bucket']['name'], 'object': event['Records'][0]['s3']['object']['key'], }
def handler(event, context):
6
64
54
6
0
uk-gov-mirror/communitiesuk.mhclg-data-collection-alpha
modules/lambda-example/main.py
Python
handler
handler
1
7
1
1
3c0ec52c091504a08a7a8ec3d1b8ed0a1004e766
bigcode/the-stack
train
b85fbf1ab9d44e0ddf6d6fed
train
function
@pytest.fixture def workflow_job_factory(workflow_job_template, admin): def factory(workflow_job_template=workflow_job_template, initial_state='new', created_by=admin): return workflow_job_template.create_unified_job(_eager_fields={ 'status': initial_state, 'created_by': created_by}) return ...
@pytest.fixture def workflow_job_factory(workflow_job_template, admin):
def factory(workflow_job_template=workflow_job_template, initial_state='new', created_by=admin): return workflow_job_template.create_unified_job(_eager_fields={ 'status': initial_state, 'created_by': created_by}) return factory
2", organization=organization) return job_template @pytest.fixture def workflow_job_template(organization): wjt = WorkflowJobTemplate(name='test-workflow_job_template', organization=organization) wjt.save() return wjt @pytest.fixture def workflow_job_factory(workflow_job_template, admin):
64
64
68
14
49
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
workflow_job_factory
workflow_job_factory
693
698
693
694
3ef7552a594c31c76f7016b3a18126c1e13beee0
bigcode/the-stack
train
25f3bea93eef3bc08e116cdd
train
function
@pytest.fixture def notification(notification_template): return Notification.objects.create(notification_template=notification_template, status='successful', notifications_sent=1, notification_type='...
@pytest.fixture def notification(notification_template):
return Notification.objects.create(notification_template=notification_template, status='successful', notifications_sent=1, notification_type='email', recipients...
@pytest.fixture def notification_template_with_encrypt(organization): return NotificationTemplate.objects.create(name='test-notification_template_with_encrypt', organization=organization, notification_type="slack", ...
63
64
51
8
55
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
notification
notification
370
377
370
371
e64471d9db44958a2b22f43586ae0988d20e5f25
bigcode/the-stack
train
6cc2fecae0ffabeaa8428565
train
function
@pytest.fixture def org_auditor(user, organization): ret = user('org-auditor', False) organization.auditor_role.members.add(ret) organization.member_role.members.add(ret) return ret
@pytest.fixture def org_auditor(user, organization):
ret = user('org-auditor', False) organization.auditor_role.members.add(ret) organization.member_role.members.add(ret) return ret
to anything" return user('rando', False) @pytest.fixture def org_admin(user, organization): ret = user('org-admin', False) organization.admin_role.members.add(ret) organization.member_role.members.add(ret) return ret @pytest.fixture def org_auditor(user, organization):
64
64
46
12
51
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
org_auditor
org_auditor
421
426
421
422
1be07a1a6ad8b472c88011e2fb6e4833103229f0
bigcode/the-stack
train
aa45ea1a739ef67a4543c642
train
function
@pytest.fixture def inventory_source_factory(inventory_factory): def invsrc(name, source=None, inventory=None): if inventory is None: inventory = inventory_factory("inv-is-%s" % name) if source is None: source = 'file' try: return inventory.inventory_sourc...
@pytest.fixture def inventory_source_factory(inventory_factory):
def invsrc(name, source=None, inventory=None): if inventory is None: inventory = inventory_factory("inv-is-%s" % name) if source is None: source = 'file' try: return inventory.inventory_sources.get(name=name) except Exception: return in...
return rf @pytest.fixture def group(inventory): return inventory.groups.create(name='single-group') @pytest.fixture def inventory_source(inventory): return InventorySource.objects.create(name='single-inv-src', inventory=inventory, source='gce') @pytest.fixture def ...
64
64
89
11
53
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
inventory_source_factory
inventory_source_factory
484
495
484
485
8acfb98e4086d572a8e900511e16ec80366f923b
bigcode/the-stack
train
cb911b616f198a1938ad23d3
train
function
@pytest.fixture def credentialtype_vault(): vault_type = CredentialType.defaults['vault']() vault_type.save() return vault_type
@pytest.fixture def credentialtype_vault():
vault_type = CredentialType.defaults['vault']() vault_type.save() return vault_type
ssh @pytest.fixture def credentialtype_aws(): aws = CredentialType.defaults['aws']() aws.save() return aws @pytest.fixture def credentialtype_net(): net = CredentialType.defaults['net']() net.save() return net @pytest.fixture def credentialtype_vault():
64
64
30
9
54
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
credentialtype_vault
credentialtype_vault
245
249
245
246
26b834ce18d6ba51fef9a595d4e98ce4e1851998
bigcode/the-stack
train
0d7bf3e3ce1265b7416f872c
train
function
@pytest.fixture def oauth_application(admin): return Application.objects.create( name='test app', user=admin, client_type='confidential', authorization_grant_type='password' )
@pytest.fixture def oauth_application(admin):
return Application.objects.create( name='test app', user=admin, client_type='confidential', authorization_grant_type='password' )
`dumps` if not isinstance(value, six.string_types): value = dumps(value) return value @pytest.fixture def monkeypatch_jsonbfield_get_db_prep_save(mocker): JSONField.get_db_prep_save = get_db_prep_save @pytest.fixture def oauth_application(admin):
64
64
40
8
55
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
oauth_application
oauth_application
738
743
738
739
14104d3254752b6960d61210daf5eb830b5d8968
bigcode/the-stack
train
a302b8c3c8a451f2971db9ac
train
function
@pytest.fixture def user(): def u(name, is_superuser=False): try: user = User.objects.get(username=name) except User.DoesNotExist: user = User(username=name, is_superuser=is_superuser) user.set_password(name) user.save() return user return ...
@pytest.fixture def user():
def u(name, is_superuser=False): try: user = User.objects.get(username=name) except User.DoesNotExist: user = User(username=name, is_superuser=is_superuser) user.set_password(name) user.save() return user return u
BROKER_URL will get us. We may need to incluence CELERY's configuration like we do in the old unit tests (see base.py) Allows django signal code to execute without the need for redis ''' settings.BROKER_URL='memory://localhost/' @pytest.fixture def user():
63
64
67
6
57
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
user
user
80
90
80
81
a3c49efb9c3485e6956be86f796dc6c44cd3cc4d
bigcode/the-stack
train
be9d01f981caa7183a1c4dd7
train
function
@pytest.fixture def hosts(group_factory): group1 = group_factory('group-1') def rf(host_count=1): hosts = [] for i in xrange(0, host_count): name = '%s-host-%s' % (group1.name, i) (host, created) = group1.inventory.hosts.get_or_create(name=name) if created: ...
@pytest.fixture def hosts(group_factory):
group1 = group_factory('group-1') def rf(host_count=1): hosts = [] for i in xrange(0, host_count): name = '%s-host-%s' % (group1.name, i) (host, created) = group1.inventory.hosts.get_or_create(name=name) if created: group1.hosts.add(host) ...
s return rf @pytest.fixture def group_factory(inventory): def g(name): try: return Group.objects.get(name=name, inventory=inventory) except Exception: return Group.objects.create(inventory=inventory, name=name) return g @pytest.fixture def hosts(group_factory):
64
64
102
8
55
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
hosts
hosts
457
470
457
458
574af579e24ff422fd3ccde10d04a7eb823644e1
bigcode/the-stack
train
95a1625cc0d20dea75b4ce6c
train
function
@pytest.fixture def fact_scans(group_factory, fact_ansible_json, fact_packages_json, fact_services_json): group1 = group_factory('group-1') def rf(fact_scans=1, timestamp_epoch=timezone.now()): facts_json = {} facts = [] module_names = ['ansible', 'services', 'packages'] timesta...
@pytest.fixture def fact_scans(group_factory, fact_ansible_json, fact_packages_json, fact_services_json):
group1 = group_factory('group-1') def rf(fact_scans=1, timestamp_epoch=timezone.now()): facts_json = {} facts = [] module_names = ['ansible', 'services', 'packages'] timestamp_current = timestamp_epoch facts_json['ansible'] = fact_ansible_json facts_json['packag...
patch') @pytest.fixture def delete(): return _request('delete') @pytest.fixture def head(): return _request('head') @pytest.fixture def options(): return _request('options') @pytest.fixture def fact_scans(group_factory, fact_ansible_json, fact_packages_json, fact_services_json):
64
64
190
23
41
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
fact_scans
fact_scans
613
633
613
614
f692efceafbb92f36340d9da720928be9da9c792
bigcode/the-stack
train
1f2c93aeb2bc5ec6ce387717
train
function
@pytest.fixture def group_factory(inventory): def g(name): try: return Group.objects.get(name=name, inventory=inventory) except Exception: return Group.objects.create(inventory=inventory, name=name) return g
@pytest.fixture def group_factory(inventory):
def g(name): try: return Group.objects.get(name=name, inventory=inventory) except Exception: return Group.objects.create(inventory=inventory, name=name) return g
1): orgs = [] for i in xrange(0, organization_count): o = Organization.objects.create(name="test-org-%d" % i, description="test-org-desc") orgs.append(o) return orgs return rf @pytest.fixture def group_factory(inventory):
64
64
50
9
54
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
group_factory
group_factory
447
454
447
448
bb662bc35fb298dc33f369236c60f3be68a63893
bigcode/the-stack
train
b39b528420bc7e74d20958e4
train
function
@pytest.fixture def org_member(user, organization): ret = user('org-member', False) organization.member_role.members.add(ret) return ret
@pytest.fixture def org_member(user, organization):
ret = user('org-member', False) organization.member_role.members.add(ret) return ret
.members.add(ret) return ret @pytest.fixture def org_auditor(user, organization): ret = user('org-auditor', False) organization.auditor_role.members.add(ret) organization.member_role.members.add(ret) return ret @pytest.fixture def org_member(user, organization):
64
64
32
10
53
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
org_member
org_member
429
433
429
430
9d2801df5f358c1d320e3a6f5c20b4d7e907e03e
bigcode/the-stack
train
eb62301e8eb49d98cc9b3660
train
function
@pytest.fixture def user_project(user): owner = user('owner') return Project.objects.create(name="test-user-project", created_by=owner, description="test-user-project-desc")
@pytest.fixture def user_project(user):
owner = user('owner') return Project.objects.create(name="test-user-project", created_by=owner, description="test-user-project-desc")
): def factory(name): try: t = Team.objects.get(name=name) except Team.DoesNotExist: t = Team.objects.create(name=name, description="description for " + name, organization=organization) return t ...
64
64
38
8
55
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
user_project
user_project
203
206
203
204
4c1430f974a0e9577a9ca882d8e449013acd1ec1
bigcode/the-stack
train
df2004b47c47252066f25756
train
function
def _fact_json(module_name): current_dir = os.path.dirname(os.path.realpath(__file__)) with open('%s/%s.json' % (current_dir, module_name)) as f: return json.load(f)
def _fact_json(module_name):
current_dir = os.path.dirname(os.path.realpath(__file__)) with open('%s/%s.json' % (current_dir, module_name)) as f: return json.load(f)
.hosts.all(): for module_name in module_names: facts.append(Fact.objects.create(host=host, timestamp=timestamp_current, module=module_name, facts=facts_json[module_name])) timestamp_current += timedelta(days=1) return facts return rf def _fact_json(module_name...
64
64
47
7
56
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
_fact_json
_fact_json
636
639
636
636
1e4161ae7d849f9d6df5b939aa4ba3e2599cd863
bigcode/the-stack
train
556700ba15666b385b74c685
train
function
@pytest.fixture def credentialtype_ssh(): ssh = CredentialType.defaults['ssh']() ssh.save() return ssh
@pytest.fixture def credentialtype_ssh():
ssh = CredentialType.defaults['ssh']() ssh.save() return ssh
_type="insights") @pytest.fixture def instance(settings): return Instance.objects.create(uuid=settings.SYSTEM_UUID, hostname="instance.example.org", capacity=100) @pytest.fixture def organization(instance): return Organization.objects.create(name="test-org", description="test-org-desc") @pytest.fixture def ...
64
64
27
9
55
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
credentialtype_ssh
credentialtype_ssh
224
228
224
225
9752a7757a8c7153c2cd0d512cc5220569f1c431
bigcode/the-stack
train
0279ae0dc5ff61b49022509f
train
function
@pytest.fixture def host(group, inventory): return group.hosts.create(name='single-host', inventory=inventory)
@pytest.fixture def host(group, inventory):
return group.hosts.create(name='single-host', inventory=inventory)
def inventory_update(inventory_source): return InventoryUpdate.objects.create(inventory_source=inventory_source) @pytest.fixture def inventory_script(organization): return CustomInventoryScript.objects.create(name='test inv script', organization=organization, ...
64
64
24
9
55
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
host
host
510
512
510
511
0a3bc7fb03a70e931025bc86c4d34e42f0ee4f1c
bigcode/the-stack
train
162c55981c599c34a151cbdf
train
function
@pytest.fixture def system_job_factory(system_job_template, admin): def factory(system_job_template=system_job_template, initial_state='new', created_by=admin): return system_job_template.create_unified_job(_eager_fields={ 'status': initial_state, 'created_by': created_by}) return factory
@pytest.fixture def system_job_factory(system_job_template, admin):
def factory(system_job_template=system_job_template, initial_state='new', created_by=admin): return system_job_template.create_unified_job(_eager_fields={ 'status': initial_state, 'created_by': created_by}) return factory
created_by': created_by}) return factory @pytest.fixture def system_job_template(): sys_jt = SystemJobTemplate(name='test-system_job_template', job_type='cleanup_jobs') sys_jt.save() return sys_jt @pytest.fixture def system_job_factory(system_job_template, admin):
64
64
66
13
50
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
system_job_factory
system_job_factory
708
713
708
709
22d04daaf318115e9ea8d184667842780a2d336e
bigcode/the-stack
train
c8c60cbd6f24886956ce2953
train
function
@pytest.fixture def inventory_update(inventory_source): return InventoryUpdate.objects.create(inventory_source=inventory_source)
@pytest.fixture def inventory_update(inventory_source):
return InventoryUpdate.objects.create(inventory_source=inventory_source)
inv-is-%s" % name) if source is None: source = 'file' try: return inventory.inventory_sources.get(name=name) except Exception: return inventory.inventory_sources.create(name=name, source=source) return invsrc @pytest.fixture def inventory_update(inventory_...
64
64
23
10
53
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
inventory_update
inventory_update
498
500
498
499
fbaff06540f3fbfd4e84f1e0769864b985c06aae
bigcode/the-stack
train
47540d60fa5d0affe3308d07
train
function
@pytest.fixture def system_job_template(): sys_jt = SystemJobTemplate(name='test-system_job_template', job_type='cleanup_jobs') sys_jt.save() return sys_jt
@pytest.fixture def system_job_template():
sys_jt = SystemJobTemplate(name='test-system_job_template', job_type='cleanup_jobs') sys_jt.save() return sys_jt
admin): def factory(workflow_job_template=workflow_job_template, initial_state='new', created_by=admin): return workflow_job_template.create_unified_job(_eager_fields={ 'status': initial_state, 'created_by': created_by}) return factory @pytest.fixture def system_job_template():
64
64
41
8
55
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
system_job_template
system_job_template
701
705
701
702
559ce95b54ef4fabd26c76f7b9196257db3cbff7
bigcode/the-stack
train
2149f78b0dd920677f59a649
train
function
@pytest.fixture def group(inventory): return inventory.groups.create(name='single-group')
@pytest.fixture def group(inventory):
return inventory.groups.create(name='single-group')
s-host-%s' % (group1.name, i) (host, created) = group1.inventory.hosts.get_or_create(name=name) if created: group1.hosts.add(host) hosts.append(host) return hosts return rf @pytest.fixture def group(inventory):
64
64
18
8
55
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
group
group
473
475
473
474
352bc010602a36a34028aef008ea3cd3f97afa42
bigcode/the-stack
train
b8b4057fdec0564812661648
train
function
@pytest.fixture def job_factory(job_template, admin): def factory(job_template=job_template, initial_state='new', created_by=admin): return job_template.create_unified_job(_eager_fields={ 'status': initial_state, 'created_by': created_by}) return factory
@pytest.fixture def job_factory(job_template, admin):
def factory(job_template=job_template, initial_state='new', created_by=admin): return job_template.create_unified_job(_eager_fields={ 'status': initial_state, 'created_by': created_by}) return factory
: prj = Project.objects.get(name=name) except Project.DoesNotExist: prj = Project.objects.create(name=name, description="description for " + name, organization=organization ...
64
64
61
11
52
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
job_factory
job_factory
182
187
182
183
85f152f6a5ca6761ddb3048076e8a26dd3118185
bigcode/the-stack
train
1eed583cb9f1cfa69296201a
train
function
@pytest.fixture def machine_credential(credentialtype_ssh): return Credential.objects.create(credential_type=credentialtype_ssh, name='machine-cred', inputs={'username': 'test_user', 'password': 'pas4word'})
@pytest.fixture def machine_credential(credentialtype_ssh):
return Credential.objects.create(credential_type=credentialtype_ssh, name='machine-cred', inputs={'username': 'test_user', 'password': 'pas4word'})
', 'password': 'secret'}) @pytest.fixture def vault_credential(credentialtype_vault): return Credential.objects.create(credential_type=credentialtype_vault, name='test-cred', inputs={'vault_password': 'secret'}) @pytest.fixture def machine_credential(credentialtype_ssh):
63
64
50
13
50
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
machine_credential
machine_credential
284
287
284
285
2d2ce3f66d9728f406bb36b47affe63e1ebb95c4
bigcode/the-stack
train
f352cb860daa906967c3608f
train
function
@pytest.fixture(scope="session", autouse=True) def celery_memory_broker(): ''' FIXME: Not sure how "far" just setting the BROKER_URL will get us. We may need to incluence CELERY's configuration like we do in the old unit tests (see base.py) Allows django signal code to execute without the need for redi...
@pytest.fixture(scope="session", autouse=True) def celery_memory_broker():
''' FIXME: Not sure how "far" just setting the BROKER_URL will get us. We may need to incluence CELERY's configuration like we do in the old unit tests (see base.py) Allows django signal code to execute without the need for redis ''' settings.BROKER_URL='memory://localhost/'
from awx.main.models.oauth import OAuth2Application as Application __SWAGGER_REQUESTS__ = {} @pytest.fixture(scope="session") def swagger_autogen(requests=__SWAGGER_REQUESTS__): return requests @pytest.fixture(scope="session", autouse=True) def celery_memory_broker():
64
64
87
16
47
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
celery_memory_broker
celery_memory_broker
69
77
69
70
14b1cb99695051512106c2773af04cd0beb0a667
bigcode/the-stack
train
075900f385f53f10bf1a5ea9
train
function
@pytest.fixture def admin(user): return user('admin', True)
@pytest.fixture def admin(user):
return user('admin', True)
, notification_type='email', recipients='admin@redhat.com', subject='email subject') @pytest.fixture def job_template_with_survey_passwords(job_template_with_survey_passwords_factory): return job_t...
64
64
15
7
57
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
admin
admin
385
387
385
386
daa725e24057869cac668f31755609f30e426b80
bigcode/the-stack
train
50107bb4c71e90f5d91a4473
train
function
@pytest.fixture def insights_inventory(inventory): inventory.scm_type = 'insights' inventory.save() return inventory
@pytest.fixture def insights_inventory(inventory):
inventory.scm_type = 'insights' inventory.save() return inventory
(credential_type=credentialtype_aws, name='test-cred', inputs={'username': 'something', 'password': 'secret'}, organization=organization) @pytest.fixture def inventory(organization): return organization.inventories.create(name="test-inv") @...
64
64
27
9
55
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
insights_inventory
insights_inventory
314
318
314
315
376cc7ba15b4fb3a3cfe7fa91f7ee12f05816f8e
bigcode/the-stack
train
64270abbf585a9fe870fb315
train
function
@pytest.fixture def alice(user): return user('alice', False)
@pytest.fixture def alice(user):
return user('alice', False)
ed=True) @pytest.fixture def admin(user): return user('admin', True) @pytest.fixture def system_auditor(user): u = user('an-auditor', False) Role.singleton('system_auditor').members.add(u) return u @pytest.fixture def alice(user):
64
64
15
7
56
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
alice
alice
397
399
397
398
de45b8af065db899a83f2c2223159084f832ec06
bigcode/the-stack
train
520c579df3b844e4d3a1514c
train
function
@pytest.fixture(scope="session") def swagger_autogen(requests=__SWAGGER_REQUESTS__): return requests
@pytest.fixture(scope="session") def swagger_autogen(requests=__SWAGGER_REQUESTS__):
return requests
.workflow import WorkflowJobTemplate from awx.main.models.ad_hoc_commands import AdHocCommand from awx.main.models.oauth import OAuth2Application as Application __SWAGGER_REQUESTS__ = {} @pytest.fixture(scope="session") def swagger_autogen(requests=__SWAGGER_REQUESTS__):
63
64
25
21
42
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
swagger_autogen
swagger_autogen
64
66
64
65
da5d23fc3cdd6ca8691487de0d847b4b84015524
bigcode/the-stack
train
6335d4d9648899143dd796c0
train
function
@pytest.fixture def credential(credentialtype_aws): return Credential.objects.create(credential_type=credentialtype_aws, name='test-cred', inputs={'username': 'something', 'password': 'secret'})
@pytest.fixture def credential(credentialtype_aws):
return Credential.objects.create(credential_type=credentialtype_aws, name='test-cred', inputs={'username': 'something', 'password': 'secret'})
scm_type = CredentialType.defaults['scm']() scm_type.save() return scm_type @pytest.fixture def credentialtype_insights(): insights_type = CredentialType.defaults['insights']() insights_type.save() return insights_type @pytest.fixture def credential(credentialtype_aws):
64
64
45
11
52
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
credential
credential
266
269
266
267
0d8b749bab10c17c3435075b7097c0b242182e31
bigcode/the-stack
train
8d688c81a8afe14c0603fd4b
train
function
@pytest.fixture def get(): return _request('get')
@pytest.fixture def get():
return _request('get')
setdefault(request.path, {})[ (request.method.lower(), response.status_code) ] = (response.get('Content-Type', None), response.content, kwargs.get('data')) return response return rf @pytest.fixture def post(): return _request('post') @pytest.fixture def get():
64
64
13
6
58
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
get
get
583
585
583
584
e8db8d1c23e8e1daf74f57b86a2b8083d104898d
bigcode/the-stack
train
0990c437a66ace17c6121013
train
function
@pytest.fixture def label(organization): return organization.labels.create(name="test-label", description="test-label-desc")
@pytest.fixture def label(organization):
return organization.labels.create(name="test-label", description="test-label-desc")
(organization): def factory(name, org=organization): try: inv = Inventory.objects.get(name=name, organization=org) except Inventory.DoesNotExist: inv = Inventory.objects.create(name=name, organization=org) return inv return factory @pytest.fixture def label(organi...
64
64
24
8
55
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
label
label
347
349
347
348
3b504a3e611c2cb96717ea6da468ff690f290873
bigcode/the-stack
train
efb0f5ce45297d0d9e1ecd2d
train
function
@pytest.fixture def credentialtype_aws(): aws = CredentialType.defaults['aws']() aws.save() return aws
@pytest.fixture def credentialtype_aws():
aws = CredentialType.defaults['aws']() aws.save() return aws
", capacity=100) @pytest.fixture def organization(instance): return Organization.objects.create(name="test-org", description="test-org-desc") @pytest.fixture def credentialtype_ssh(): ssh = CredentialType.defaults['ssh']() ssh.save() return ssh @pytest.fixture def credentialtype_aws():
64
64
27
9
54
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
credentialtype_aws
credentialtype_aws
231
235
231
232
ca2d12c5f3ebe230687a7afff3d15c284d22fb36
bigcode/the-stack
train
8126df8ea10a53c91c8a0b68
train
function
@pytest.fixture @mock.patch.object(Project, "update", lambda self, **kwargs: None) def project(instance, organization): prj = Project.objects.create(name="test-proj", description="test-proj-desc", organization=organization, ...
@pytest.fixture @mock.patch.object(Project, "update", lambda self, **kwargs: None) def project(instance, organization):
prj = Project.objects.create(name="test-proj", description="test-proj-desc", organization=organization, playbook_files=['helloworld.yml', 'alt-helloworld.yml'], local_path='_92__test_p...
__(self, obj, obj_type): return obj.playbook_files mocked = mock.patch.object(Project, 'playbooks', new_callable=PlaybooksMock) mocked.start() @pytest.fixture @mock.patch.object(Project, "update", lambda self, **kwargs: None) def project(instance, organization):
64
64
115
26
38
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
project
project
141
153
141
143
c6f9295b4c8f6236c3165f1e1e18f67aa7ae77ee
bigcode/the-stack
train
4be96bf047fc9fe81ce157e8
train
function
@pytest.fixture def sqlite_copy_expert(request): # copy_expert is postgres-specific, and SQLite doesn't support it; mock its # behavior to test that it writes a file that contains stdout from events path = tempfile.mkdtemp(prefix='job-event-stdout') def write_stdout(self, sql, fd): # simulate p...
@pytest.fixture def sqlite_copy_expert(request): # copy_expert is postgres-specific, and SQLite doesn't support it; mock its # behavior to test that it writes a file that contains stdout from events
path = tempfile.mkdtemp(prefix='job-event-stdout') def write_stdout(self, sql, fd): # simulate postgres copy_expert support with ORM code parts = sql.split(' ') tablename = parts[parts.index('from') + 1] for cls in (JobEvent, AdHocCommandEvent, ProjectUpdateEvent, ...
user=admin, client_type='confidential', authorization_grant_type='password' ) @pytest.fixture def sqlite_copy_expert(request): # copy_expert is postgres-specific, and SQLite doesn't support it; mock its # behavior to test that it writes a file that contains stdout from events
64
64
212
44
20
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
sqlite_copy_expert
sqlite_copy_expert
746
765
746
749
5ecd9d397149d1ee7b42551e5ac0998ef269b0ab
bigcode/the-stack
train
b6c616f7067492fe93ca9855
train
function
@pytest.fixture def deploy_jobtemplate(project, inventory, credential): jt = JobTemplate.objects.create( job_type='run', project=project, inventory=inventory, name='deploy-job-template' ) jt.credentials.add(credential) return jt
@pytest.fixture def deploy_jobtemplate(project, inventory, credential):
jt = JobTemplate.objects.create( job_type='run', project=project, inventory=inventory, name='deploy-job-template' ) jt.credentials.add(credential) return jt
template(project, inventory, credential): jt = JobTemplate.objects.create( job_type='check', project=project, inventory=inventory, name='check-job-template' ) jt.credentials.add(credential) return jt @pytest.fixture def deploy_jobtemplate(project, inventory, credential):
64
64
57
13
50
gitEdouble/awx
awx/main/tests/functional/conftest.py
Python
deploy_jobtemplate
deploy_jobtemplate
105
114
105
106
c09b2c40864b555e70ddcfb130bd23b93109d0c0
bigcode/the-stack
train