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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5a154b6f6bbb925f4254565f | train | class | class Serializable(object):
"""Base class for objects that can be serialized in JSON format.
Subclasses must implement `from_dict()`, which defines how to construct a
serializable object from a JSON dictionary.
Serializable objects can be easily converted read and written from any of
the following... | class Serializable(object):
| """Base class for objects that can be serialized in JSON format.
Subclasses must implement `from_dict()`, which defines how to construct a
serializable object from a JSON dictionary.
Serializable objects can be easily converted read and written from any of
the following formats:
- JSON fil... | a numpy array.
Args:
array: a numpy array
Returns:
the serialized string
"""
#
# We currently serialize in numpy format. Other alternatives considered
# were `pickle.dumps(array)` and HDF5
#
with io.BytesIO() as f:
allow_pickle = array.dtype == object
n... | 256 | 256 | 1,580 | 4 | 252 | ErfanTagh/eta | eta/core/serial.py | Python | Serializable | Serializable | 294 | 512 | 294 | 294 | 67a5e448407434181336ff4ea89eb049279bd00a | bigcode/the-stack | train |
9d4536af48d659c5e230933b | train | function | def _load_json(str_or_bytes):
try:
return json.loads(str_or_bytes)
except TypeError:
# Must be a Python version for which json.loads() cannot handle bytes
return json.loads(str_or_bytes.decode("utf-8"))
| def _load_json(str_or_bytes):
| try:
return json.loads(str_or_bytes)
except TypeError:
# Must be a Python version for which json.loads() cannot handle bytes
return json.loads(str_or_bytes.decode("utf-8"))
| (","):
k, v = etau.remove_escape_chars(chunk, ",").split("=")
d[k] = _load_json(v)
return d
except ValueError:
raise ValueError("Unable to load JSON from '%s'" % path_or_str)
def _load_json(str_or_bytes):
| 64 | 64 | 53 | 8 | 56 | ErfanTagh/eta | eta/core/serial.py | Python | _load_json | _load_json | 85 | 90 | 85 | 85 | f01a65965b0f4aa17240988b3205c13b077c2a9d | bigcode/the-stack | train |
ee89f8df405a64e28a1086b5 | train | function | def load_ndjson(path_or_str):
"""Loads NDJSON from the input argument.
The input argument can be any of the following:
(a) the path to a NDJSON file on disk
(b) a string that can be directly parsed via `ndjson.loads`
Args:
path_or_str: the NDJSON path or string
Returns:
... | def load_ndjson(path_or_str):
| """Loads NDJSON from the input argument.
The input argument can be any of the following:
(a) the path to a NDJSON file on disk
(b) a string that can be directly parsed via `ndjson.loads`
Args:
path_or_str: the NDJSON path or string
Returns:
the loaded NDJSON
Raise... | (path):
"""Reads the NDJSON from file.
Args:
path: the path to the NDJSON file
Returns:
a list of JSON dicts
"""
with open(path, "rt") as f:
return ndjson.load(f)
def load_ndjson(path_or_str):
| 64 | 64 | 129 | 8 | 56 | ErfanTagh/eta | eta/core/serial.py | Python | load_ndjson | load_ndjson | 141 | 160 | 141 | 141 | 21c2c2293d7040a61495d9b457e17ea3c5b85773 | bigcode/the-stack | train |
b9094c623fd8213fd5a68de7 | train | class | class NpzWriteable(object):
"""Base class for dictionary-like objects that contain numpy.array values
that can be written to disk as .npz files.
"""
@staticmethod
def is_npz_path(path):
"""Returns True/False if the provided path is an .npz file."""
return path.endswith(".npz")
... | class NpzWriteable(object):
| """Base class for dictionary-like objects that contain numpy.array values
that can be written to disk as .npz files.
"""
@staticmethod
def is_npz_path(path):
"""Returns True/False if the provided path is an .npz file."""
return path.endswith(".npz")
def attributes(self):
... | kl file.
Args:
path: the path to the .pkl file
Returns:
the loaded instance
"""
return read_pickle(path)
@staticmethod
def is_pickle_path(path):
"""Checks the path to see if it has a pickle (.pkl) extension."""
return path.endswith(".pkl... | 78 | 78 | 263 | 7 | 71 | ErfanTagh/eta | eta/core/serial.py | Python | NpzWriteable | NpzWriteable | 2,855 | 2,891 | 2,855 | 2,855 | eee5dad01746846f4b41fc7c3126a3cb5e0cef97 | bigcode/the-stack | train |
7d4f050c2fb99472bd998852 | train | class | class SetError(Exception):
"""Exception raised when an invalid Set is encountered."""
pass
| class SetError(Exception):
| """Exception raised when an invalid Set is encountered."""
pass
| _load_ele(self, path):
return self._ELE_CLS.from_json(path)
def _load_ele_by_uuid(self, uuid):
return self._load_ele(self._ele_path_by_uuid(uuid))
@staticmethod
def _make_uuid():
return str(uuid4())
class SetError(Exception):
| 64 | 64 | 19 | 5 | 59 | ErfanTagh/eta | eta/core/serial.py | Python | SetError | SetError | 1,780 | 1,783 | 1,780 | 1,780 | f9aa6a98d57bc2546532e0688f2f60645604071f | bigcode/the-stack | train |
7a1b32deff15ad14581f8351 | train | class | class Container(Serializable):
"""Abstract base class for flexible containers that store homogeneous lists
of elements of a `Serializable` class.
Containers provide native support for all common array operations like
getting, setting, deleting, length, and slicing. So, for example,
`container[:5]` ... | class Container(Serializable):
| """Abstract base class for flexible containers that store homogeneous lists
of elements of a `Serializable` class.
Containers provide native support for all common array operations like
getting, setting, deleting, length, and slicing. So, for example,
`container[:5]` will return a `Container` that ... | self[key]
return match(f(ele) for f in filters)
return OrderedDict(
(k, e) for k, e in iteritems(self.__elements__) if run_filters(k)
)
@property
def _ele_paths(self):
return iter(self._ele_path(key) for key in self.__elements__)
def _ele_filename(self, ke... | 256 | 256 | 3,755 | 5 | 250 | ErfanTagh/eta | eta/core/serial.py | Python | Container | Container | 1,786 | 2,347 | 1,786 | 1,786 | a373cff12bb3694801941477b7117a7c115cfcab | bigcode/the-stack | train |
138e10ad3a14f1179c8d6c84 | train | function | def _load_ndjson(str_or_bytes):
try:
return ndjson.loads(str_or_bytes)
except TypeError:
# Must be a Python version for which ndjson.loads() cannot handle bytes
return ndjson.loads(str_or_bytes.decode("utf-8"))
| def _load_ndjson(str_or_bytes):
| try:
return ndjson.loads(str_or_bytes)
except TypeError:
# Must be a Python version for which ndjson.loads() cannot handle bytes
return ndjson.loads(str_or_bytes.decode("utf-8"))
|
Returns:
the loaded NDJSON
Raises:
ValueError: if no NDJSON could be decoded
"""
if os.path.isfile(path_or_str):
return read_ndjson(path_or_str)
return _load_ndjson(path_or_str)
def _load_ndjson(str_or_bytes):
| 64 | 64 | 57 | 9 | 55 | ErfanTagh/eta | eta/core/serial.py | Python | _load_ndjson | _load_ndjson | 163 | 168 | 163 | 163 | 599cd7bafc238b7cc5af4796c2012a816296fb99 | bigcode/the-stack | train |
ece39d366b6be44dd9aff360 | train | class | class ContainerError(Exception):
"""Exception raised when an invalid Container is encountered."""
pass
| class ContainerError(Exception):
| """Exception raised when an invalid Container is encountered."""
pass
| _load_ele(self, path):
return self._ELE_CLS.from_json(path)
def _load_ele_by_uuid(self, uuid):
return self._load_ele(self._ele_path_by_uuid(uuid))
@staticmethod
def _make_uuid():
return str(uuid4())
class ContainerError(Exception):
| 64 | 64 | 19 | 5 | 59 | ErfanTagh/eta | eta/core/serial.py | Python | ContainerError | ContainerError | 2,820 | 2,823 | 2,820 | 2,820 | e5610b46b9b24a04efab47a35264a311930e0c01 | bigcode/the-stack | train |
1612b5a7a05f420915a33b5c | train | function | def read_pickle(path):
"""Loads the object from the given .pkl file.
This function attempts to gracefully load a python 2 pickle in python 3
(if a unicode error is encountered) by assuming "latin1" encoding.
Args:
path: the path to the .pkl file
Returns:
the loaded instance
""... | def read_pickle(path):
| """Loads the object from the given .pkl file.
This function attempts to gracefully load a python 2 pickle in python 3
(if a unicode error is encountered) by assuming "latin1" encoding.
Args:
path: the path to the .pkl file
Returns:
the loaded instance
"""
try:
with... | ensure_ascii=False,
**kwargs
)
return str(s)
def pretty_str(obj):
"""Wrapper for the pprint.pformat function that generates a formatted
string representation of the input object.
"""
return pprint.pformat(obj, indent=4, width=79)
def read_pickle(path):
| 64 | 64 | 138 | 5 | 59 | ErfanTagh/eta | eta/core/serial.py | Python | read_pickle | read_pickle | 220 | 238 | 220 | 220 | b99aad30680cf8edef62f71dcf1391e2fc265c81 | bigcode/the-stack | train |
5ae4a0038d68f91d8ef117e5 | train | function | def write_json(obj, path, pretty_print=False):
"""Writes JSON object to file.
Args:
obj: is either an object that can be directly dumped to a JSON file or
an instance of a subclass of Serializable
path: the output path
pretty_print: whether to render the JSON in human readab... | def write_json(obj, path, pretty_print=False):
| """Writes JSON object to file.
Args:
obj: is either an object that can be directly dumped to a JSON file or
an instance of a subclass of Serializable
path: the output path
pretty_print: whether to render the JSON in human readable format with
newlines and indenta... | ValueError: if the JSON file was invalid
"""
try:
with open(path, "rt") as f:
return json.load(f)
except ValueError:
raise ValueError("Unable to parse JSON file '%s'" % path)
def write_json(obj, path, pretty_print=False):
| 64 | 64 | 125 | 11 | 53 | ErfanTagh/eta | eta/core/serial.py | Python | write_json | write_json | 112 | 125 | 112 | 112 | 1e3a3ffd8742c1474b6f6b4fdd1e2db9eb704111 | bigcode/the-stack | train |
1b0b8b4e02cbf643f0287e20 | train | function | def write_ndjson(obj, path, append=False):
"""Writes the list of JSON dicts to disk in NDJSON format.
Args:
obj: a list of JSON dicts
path: the output path
append: whether to append to an existing file, if necessary
"""
etau.ensure_basedir(path)
if append and os.path.exists... | def write_ndjson(obj, path, append=False):
| """Writes the list of JSON dicts to disk in NDJSON format.
Args:
obj: a list of JSON dicts
path: the output path
append: whether to append to an existing file, if necessary
"""
etau.ensure_basedir(path)
if append and os.path.exists(path) and os.path.getsize(path) > 0:
... | (str_or_bytes):
try:
return ndjson.loads(str_or_bytes)
except TypeError:
# Must be a Python version for which ndjson.loads() cannot handle bytes
return ndjson.loads(str_or_bytes.decode("utf-8"))
def write_ndjson(obj, path, append=False):
| 63 | 64 | 137 | 11 | 52 | ErfanTagh/eta | eta/core/serial.py | Python | write_ndjson | write_ndjson | 171 | 188 | 171 | 171 | 8c6ca5ad9399d3f5ef52225edf3aeda4ea1c178c | bigcode/the-stack | train |
31a4ef365673228d122fd939 | train | function | def write_pickle(obj, path):
"""Writes the object to disk at the given path as a .pkl file.
Args:
obj: the pickable object
path: the path to write the .pkl file
"""
etau.ensure_basedir(path)
with open(path, "wb") as f:
pickle.dump(obj, f)
| def write_pickle(obj, path):
| """Writes the object to disk at the given path as a .pkl file.
Args:
obj: the pickable object
path: the path to write the .pkl file
"""
etau.ensure_basedir(path)
with open(path, "wb") as f:
pickle.dump(obj, f)
| with open(path, "rb") as f:
return pickle.load(f)
except UnicodeDecodeError:
with open(path, "rb") as f:
# https://stackoverflow.com/q/28218466
return _pickle.load(f, encoding="latin1")
def write_pickle(obj, path):
| 64 | 64 | 77 | 7 | 57 | ErfanTagh/eta | eta/core/serial.py | Python | write_pickle | write_pickle | 241 | 250 | 241 | 241 | 7579f6b4cf441e7719ee60b11ab4201c823e1bbb | bigcode/the-stack | train |
4f6242598191cb08e6d65162 | train | function | def pretty_str(obj):
"""Wrapper for the pprint.pformat function that generates a formatted
string representation of the input object.
"""
return pprint.pformat(obj, indent=4, width=79)
| def pretty_str(obj):
| """Wrapper for the pprint.pformat function that generates a formatted
string representation of the input object.
"""
return pprint.pformat(obj, indent=4, width=79)
| ):
obj = obj.serialize()
kwargs = {"indent": 4} if pretty_print else {}
s = json.dumps(
obj,
separators=(",", ": "),
cls=ETAJSONEncoder,
ensure_ascii=False,
**kwargs
)
return str(s)
def pretty_str(obj):
| 64 | 64 | 44 | 5 | 59 | ErfanTagh/eta | eta/core/serial.py | Python | pretty_str | pretty_str | 213 | 217 | 213 | 213 | cae2f748b6439995c855aff97ff5ddeedcf59897 | bigcode/the-stack | train |
33792b1dbbf38fc7fc627401 | train | function | def load_json(path_or_str):
"""Loads JSON from the input argument.
The input argument can be any of the following:
(a) the path to a JSON file on disk
(b) a string that can be directly parsed via `json.loads`
(c) a string containing a comma-seperated list of key=val values
d... | def load_json(path_or_str):
| """Loads JSON from the input argument.
The input argument can be any of the following:
(a) the path to a JSON file on disk
(b) a string that can be directly parsed via `json.loads`
(c) a string containing a comma-seperated list of key=val values
defining a JSON dictionary, w... | import copy
import datetime as dt
import dill as pickle
import glob
import io
import json
import logging
import numbers
import os
import pickle as _pickle
import pprint
from uuid import uuid4
import zlib
import ndjson
import numpy as np
import eta.core.utils as etau
logger = logging.getLogger(__name__)
def load_jso... | 82 | 82 | 274 | 7 | 75 | ErfanTagh/eta | eta/core/serial.py | Python | load_json | load_json | 46 | 82 | 46 | 46 | bafaf9d93d11d9a96648eac6bb238dfbfbc233f1 | bigcode/the-stack | train |
c89d757cf0746114ed624cb9 | train | function | def serialize_numpy_array(array):
"""Serializes a numpy array.
Args:
array: a numpy array
Returns:
the serialized string
"""
#
# We currently serialize in numpy format. Other alternatives considered
# were `pickle.dumps(array)` and HDF5
#
with io.BytesIO() as f:
... | def serialize_numpy_array(array):
| """Serializes a numpy array.
Args:
array: a numpy array
Returns:
the serialized string
"""
#
# We currently serialize in numpy format. Other alternatives considered
# were `pickle.dumps(array)` and HDF5
#
with io.BytesIO() as f:
allow_pickle = array.dtype ==... | a .pkl file.
Args:
obj: the pickable object
path: the path to write the .pkl file
"""
etau.ensure_basedir(path)
with open(path, "wb") as f:
pickle.dump(obj, f)
def serialize_numpy_array(array):
| 64 | 64 | 118 | 6 | 58 | ErfanTagh/eta | eta/core/serial.py | Python | serialize_numpy_array | serialize_numpy_array | 253 | 271 | 253 | 253 | 8de1b0535d0d414315600dc282155f1c9f67a31c | bigcode/the-stack | train |
73c9a0e77268a5dd6e266744 | train | class | class Picklable(object):
"""Mixin class for objects that can be pickled."""
def pickle(self, path):
"""Saves the instance to disk as a .pkl file.
Args:
path: the path to write the .pkl file
"""
write_pickle(self, path)
@classmethod
def from_pickle(cls, path... | class Picklable(object):
| """Mixin class for objects that can be pickled."""
def pickle(self, path):
"""Saves the instance to disk as a .pkl file.
Args:
path: the path to write the .pkl file
"""
write_pickle(self, path)
@classmethod
def from_pickle(cls, path):
"""Loads the o... | _load_ele_by_uuid(self, uuid):
return self._load_ele(self._ele_path_by_uuid(uuid))
@staticmethod
def _make_uuid():
return str(uuid4())
class ContainerError(Exception):
"""Exception raised when an invalid Container is encountered."""
pass
class Picklable(object):
| 64 | 64 | 158 | 6 | 57 | ErfanTagh/eta | eta/core/serial.py | Python | Picklable | Picklable | 2,826 | 2,852 | 2,826 | 2,826 | 20c17e896be341514ade9943e0f86e9cbcc7b146 | bigcode/the-stack | train |
c8eaa20b1c09fe7a99e16d33 | train | class | class window(QMainWindow):
def __init__(self):
super(window, self).__init__()
self.setGeometry(50, 50, 800, 500)
self.setWindowTitle('pyqt5 Tut')
# self.setWindowIcon(QIcon('pic.png'))
extractAction = QAction('&Get to the choppah', self)
extractAction.setShortcut('C... | class window(QMainWindow):
| def __init__(self):
super(window, self).__init__()
self.setGeometry(50, 50, 800, 500)
self.setWindowTitle('pyqt5 Tut')
# self.setWindowIcon(QIcon('pic.png'))
extractAction = QAction('&Get to the choppah', self)
extractAction.setShortcut('Ctrl+Q')
extractActio... | #! /usr/bin/env python3
# -*- coding:utf-8 -*-
###############################################################
# kenwaldek MIT-license
# Title: PyQt5 lesson 13 Version: 1.0
# Date: 09-01-17 Language: python3
# Description: pyqt5 gui and editor
# pythonprogra... | 200 | 256 | 888 | 6 | 193 | AnshulPorwal1/pythonprogramming | pyqt5_lesson_13.py | Python | window | window | 21 | 144 | 21 | 22 | d5fd3d75feff91f23595959b8b7c614401481d4c | bigcode/the-stack | train |
549877d2a11dafdf4f5ed9c6 | train | function | def to_tuple(t):
if t is None or isinstance(t, (str, int, complex)):
return t
elif isinstance(t, list):
return [to_tuple(e) for e in t]
result = [t.__class__.__name__]
if hasattr(t, 'lineno') and hasattr(t, 'col_offset'):
result.append((t.lineno, t.col_offset))
if t._fields i... | def to_tuple(t):
| if t is None or isinstance(t, (str, int, complex)):
return t
elif isinstance(t, list):
return [to_tuple(e) for e in t]
result = [t.__class__.__name__]
if hasattr(t, 'lineno') and hasattr(t, 'col_offset'):
result.append((t.lineno, t.col_offset))
if t._fields is None:
r... | import sys, unittest
from test import support
import ast
def to_tuple(t):
| 18 | 64 | 121 | 5 | 12 | deadsnakes/python3.1 | Lib/test/test_ast.py | Python | to_tuple | to_tuple | 5 | 17 | 5 | 5 | 9e693b7be52a5ee51fb2e4d3ac7359a8eaf482f8 | bigcode/the-stack | train |
b7b7fd41821e01af4e14aef9 | train | class | class AST_Tests(unittest.TestCase):
def _assertTrueorder(self, ast_node, parent_pos):
if not isinstance(ast_node, ast.AST) or ast_node._fields is None:
return
if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)):
node_pos = (ast_node.lineno, ast_node.col_offset)
... | class AST_Tests(unittest.TestCase):
| def _assertTrueorder(self, ast_node, parent_pos):
if not isinstance(ast_node, ast.AST) or ast_node._fields is None:
return
if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)):
node_pos = (ast_node.lineno, ast_node.col_offset)
self.assertTrue(node_pos ... | # Lambda
"lambda:None",
# Dict
"{ 1:2 }",
# ListComp
"[a for b in c if d]",
# GeneratorExp
"(a for b in c if d)",
# Yield - yield expressions can't work outside a function
#
# Compare
"1 < 2 < 3",
# Call
"f(1,2,c=3,*d,**e)",
# Num
"10",
# Str
"'string'",
# Attribute
"a.b",
# Sub... | 226 | 226 | 755 | 8 | 217 | deadsnakes/python3.1 | Lib/test/test_ast.py | Python | AST_Tests | AST_Tests | 117 | 194 | 117 | 118 | 71e5e252d79c2d02a7535b30763c4e579087d3ed | bigcode/the-stack | train |
fd3035e188de8d2caca276a3 | train | function | def main():
if __name__ != '__main__':
return
if sys.argv[1:] == ['-g']:
for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
(eval_tests, "eval")):
print(kind+"_results = [")
for s in statements:
print(... | def main():
| if __name__ != '__main__':
return
if sys.argv[1:] == ['-g']:
for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
(eval_tests, "eval")):
print(kind+"_results = [")
for s in statements:
print(repr(to_tupl... | Equal(ast.literal_eval('1.5 - 2j'), 1.5 - 2j)
self.assertRaises(ValueError, ast.literal_eval, '2 + (3 + 4j)')
def test_main():
support.run_unittest(AST_Tests, ASTHelpers_Test)
def main():
| 64 | 64 | 110 | 3 | 61 | deadsnakes/python3.1 | Lib/test/test_ast.py | Python | main | main | 304 | 316 | 304 | 304 | a956486b059f836a393d0c4e4b88a7c1ff73fb99 | bigcode/the-stack | train |
16d63a964397ec80ccf75336 | train | function | def test_main():
support.run_unittest(AST_Tests, ASTHelpers_Test)
| def test_main():
| support.run_unittest(AST_Tests, ASTHelpers_Test)
| 10 + 2j'), 10 + 2j)
self.assertEqual(ast.literal_eval('1.5 - 2j'), 1.5 - 2j)
self.assertRaises(ValueError, ast.literal_eval, '2 + (3 + 4j)')
def test_main():
| 63 | 64 | 17 | 4 | 60 | deadsnakes/python3.1 | Lib/test/test_ast.py | Python | test_main | test_main | 301 | 302 | 301 | 301 | 90498ef7c3db09f92c2d06a3a9a2eefc51821431 | bigcode/the-stack | train |
16056e8f90c0dd105674b01d | train | class | class ASTHelpers_Test(unittest.TestCase):
def test_parse(self):
a = ast.parse('foo(1 + 1)')
b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST)
self.assertEqual(ast.dump(a), ast.dump(b))
def test_dump(self):
node = ast.parse('spam(eggs, "and cheese")')
sel... | class ASTHelpers_Test(unittest.TestCase):
| def test_parse(self):
a = ast.parse('foo(1 + 1)')
b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST)
self.assertEqual(ast.dump(a), ast.dump(b))
def test_dump(self):
node = ast.parse('spam(eggs, "and cheese")')
self.assertEqual(ast.dump(node),
"... | )
self.assertEqual(x.op, 2)
self.assertEqual(x.right, 3)
self.assertEqual(x.lineno, 0)
# this used to fail because Sub._fields was None
x = ast.Sub()
def test_pickling(self):
import pickle
mods = [pickle]
try:
import cPickle
m... | 256 | 256 | 1,344 | 8 | 248 | deadsnakes/python3.1 | Lib/test/test_ast.py | Python | ASTHelpers_Test | ASTHelpers_Test | 197 | 298 | 197 | 198 | 8581db7ff4e1900474cab4c6628aebe8681e5bc9 | bigcode/the-stack | train |
ea90db24e91ee602c1b34e8b | train | function | def archive_get_members(arch):
if isinstance(arch, zipfile.ZipFile):
members = arch.namelist()
elif isinstance(arch, tarfile.TarFile):
members = [ i.name for i in arch.getmembers() ]
return members
| def archive_get_members(arch):
| if isinstance(arch, zipfile.ZipFile):
members = arch.namelist()
elif isinstance(arch, tarfile.TarFile):
members = [ i.name for i in arch.getmembers() ]
return members
| (name):
return 'zip'
else: return None
def archive_open(name):
if tarfile.is_tarfile(name):
return tarfile.open(name)
elif zipfile.is_zipfile(name):
return zipfile.ZipFile(name)
else: return None
def archive_get_members(arch):
| 64 | 64 | 56 | 7 | 56 | bopopescu/conpaas-1 | conpaas-services/src/conpaas/core/misc.py | Python | archive_get_members | archive_get_members | 62 | 67 | 62 | 62 | 00199aed4ce20d7ae1ff16dcc85ee9eea89991e4 | bigcode/the-stack | train |
8b3b4f8f61333cb3fad7dc76 | train | function | def verify_ip_port_list(l):
'''Check l is a list of [IP, PORT]. Raise appropriate Error if invalid types
or values were found
'''
if type(l) != list:
raise TypeError('Expected a list of [IP, PORT]')
for pair in l:
if len(pair) != 2:
raise TypeError('List should contain IP... | def verify_ip_port_list(l):
| '''Check l is a list of [IP, PORT]. Raise appropriate Error if invalid types
or values were found
'''
if type(l) != list:
raise TypeError('Expected a list of [IP, PORT]')
for pair in l:
if len(pair) != 2:
raise TypeError('List should contain IP,PORT values')
if 'i... | and type(ip) != unicode):
raise TypeError('IP is should be a string')
try:
socket.gethostbyname(ip)
except Exception as e:
raise ValueError('Invalid IP string "%s" -- %s' % (ip, e))
def verify_ip_port_list(l):
| 64 | 64 | 130 | 7 | 57 | bopopescu/conpaas-1 | conpaas-services/src/conpaas/core/misc.py | Python | verify_ip_port_list | verify_ip_port_list | 34 | 46 | 34 | 34 | fe1275e5f06140c5de87568ec4bcd5c0e307e19a | bigcode/the-stack | train |
0a6fa7685433cd339fad8a6a | train | function | def run_cmd(cmd, directory='/'):
pipe = Popen(cmd, shell=True, cwd=directory, stdout=PIPE, stderr=PIPE)
out, error = pipe.communicate()
pipe.wait()
return out, error
| def run_cmd(cmd, directory='/'):
| pipe = Popen(cmd, shell=True, cwd=directory, stdout=PIPE, stderr=PIPE)
out, error = pipe.communicate()
pipe.wait()
return out, error
| .SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
def run_cmd(cmd, directory='/'):
| 64 | 64 | 49 | 8 | 56 | bopopescu/conpaas-1 | conpaas-services/src/conpaas/core/misc.py | Python | run_cmd | run_cmd | 88 | 92 | 88 | 88 | a2ce75236ede323309e090fd7e4b8a2530824eb9 | bigcode/the-stack | train |
4661a394ac63d6834e82c03d | train | function | def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
| def get_ip_address(ifname):
| s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
| .extractall(path)
elif isinstance(arch, tarfile.TarFile):
arch.extractall(path=path)
def archive_close(arch):
if isinstance(arch, zipfile.ZipFile)\
or isinstance(arch, tarfile.TarFile):
arch.close()
def get_ip_address(ifname):
| 64 | 64 | 73 | 7 | 57 | bopopescu/conpaas-1 | conpaas-services/src/conpaas/core/misc.py | Python | get_ip_address | get_ip_address | 80 | 86 | 80 | 80 | 08aa153e312c222ff27310268dd5dd068c9bdd94 | bigcode/the-stack | train |
c479dae697238a8cce44f490 | train | function | def archive_close(arch):
if isinstance(arch, zipfile.ZipFile)\
or isinstance(arch, tarfile.TarFile):
arch.close()
| def archive_close(arch):
| if isinstance(arch, zipfile.ZipFile)\
or isinstance(arch, tarfile.TarFile):
arch.close()
| .name for i in arch.getmembers() ]
return members
def archive_extract(arch, path):
if isinstance(arch, zipfile.ZipFile):
arch.extractall(path)
elif isinstance(arch, tarfile.TarFile):
arch.extractall(path=path)
def archive_close(arch):
| 64 | 64 | 33 | 6 | 58 | bopopescu/conpaas-1 | conpaas-services/src/conpaas/core/misc.py | Python | archive_close | archive_close | 75 | 78 | 75 | 75 | ab110b2a9fa8c44ab488331858a1738541eeaa96 | bigcode/the-stack | train |
0b45e7807a9f17ce7b715994 | train | function | def archive_get_type(name):
if tarfile.is_tarfile(name):
return 'tar'
elif zipfile.is_zipfile(name):
return 'zip'
else: return None
| def archive_get_type(name):
| if tarfile.is_tarfile(name):
return 'tar'
elif zipfile.is_zipfile(name):
return 'zip'
else: return None
| raise TypeError('List should contain IP,PORT values')
if 'ip' not in pair or 'port' not in pair:
raise TypeError('List should contain IP,PORT values')
verify_ip_or_domain(pair['ip'])
verify_port(pair['port'])
def archive_get_type(name):
| 64 | 64 | 40 | 6 | 58 | bopopescu/conpaas-1 | conpaas-services/src/conpaas/core/misc.py | Python | archive_get_type | archive_get_type | 48 | 53 | 48 | 48 | fc4b7f48f84a5ceb960cef0f8a728d99377b4dae | bigcode/the-stack | train |
15d0b3311b0d1e999a71bd19 | train | function | def file_get_contents(filepath):
f = open(filepath, 'r')
filecontent = f.read()
f.close()
return filecontent
| def file_get_contents(filepath):
| f = open(filepath, 'r')
filecontent = f.read()
f.close()
return filecontent
| import socket
import fcntl
import struct
import zipfile
import tarfile
import readline
from subprocess import Popen, PIPE
def file_get_contents(filepath):
| 36 | 64 | 31 | 6 | 29 | bopopescu/conpaas-1 | conpaas-services/src/conpaas/core/misc.py | Python | file_get_contents | file_get_contents | 10 | 14 | 10 | 10 | 4191ce7a9a67f0c136253acfa27d301108046330 | bigcode/the-stack | train |
9e0f111b0a0f6bdb09fe87db | train | function | def verify_ip_or_domain(ip):
'''Raise TypeError f ip is not a string.
Raise ValueError if ip is an invalid IP address in dot notation.
'''
if (type(ip) != str and type(ip) != unicode):
raise TypeError('IP is should be a string')
try:
socket.gethostbyname(ip)
except Exception as e... | def verify_ip_or_domain(ip):
| '''Raise TypeError f ip is not a string.
Raise ValueError if ip is an invalid IP address in dot notation.
'''
if (type(ip) != str and type(ip) != unicode):
raise TypeError('IP is should be a string')
try:
socket.gethostbyname(ip)
except Exception as e:
raise ValueError('I... | Raise ValueError if port is an invlid integer value.
'''
if type(port) != int: raise TypeError('port should be an integer')
if port < 1 or port > 65535: raise ValueError('port should be a valid port number')
def verify_ip_or_domain(ip):
| 64 | 64 | 101 | 7 | 57 | bopopescu/conpaas-1 | conpaas-services/src/conpaas/core/misc.py | Python | verify_ip_or_domain | verify_ip_or_domain | 23 | 32 | 23 | 23 | 1138b06b08ced469abe4c41e01e3ae3d1f3c62d1 | bigcode/the-stack | train |
57c8cd3d42c16adbee6b8e46 | train | function | def archive_open(name):
if tarfile.is_tarfile(name):
return tarfile.open(name)
elif zipfile.is_zipfile(name):
return zipfile.ZipFile(name)
else: return None
| def archive_open(name):
| if tarfile.is_tarfile(name):
return tarfile.open(name)
elif zipfile.is_zipfile(name):
return zipfile.ZipFile(name)
else: return None
| PORT values')
verify_ip_or_domain(pair['ip'])
verify_port(pair['port'])
def archive_get_type(name):
if tarfile.is_tarfile(name):
return 'tar'
elif zipfile.is_zipfile(name):
return 'zip'
else: return None
def archive_open(name):
| 64 | 64 | 44 | 5 | 58 | bopopescu/conpaas-1 | conpaas-services/src/conpaas/core/misc.py | Python | archive_open | archive_open | 55 | 60 | 55 | 55 | 5daae59622450b30f8878343d298a55f618c53ca | bigcode/the-stack | train |
aebb4efb4cd9af5f0188a871 | train | function | def verify_port(port):
'''Raise Type Error if port is not an integer.
Raise ValueError if port is an invlid integer value.
'''
if type(port) != int: raise TypeError('port should be an integer')
if port < 1 or port > 65535: raise ValueError('port should be a valid port number')
| def verify_port(port):
| '''Raise Type Error if port is not an integer.
Raise ValueError if port is an invlid integer value.
'''
if type(port) != int: raise TypeError('port should be an integer')
if port < 1 or port > 65535: raise ValueError('port should be a valid port number')
|
import fcntl
import struct
import zipfile
import tarfile
import readline
from subprocess import Popen, PIPE
def file_get_contents(filepath):
f = open(filepath, 'r')
filecontent = f.read()
f.close()
return filecontent
def verify_port(port):
| 64 | 64 | 75 | 5 | 58 | bopopescu/conpaas-1 | conpaas-services/src/conpaas/core/misc.py | Python | verify_port | verify_port | 16 | 21 | 16 | 16 | daa9d4befcb8eb7f62e3e2276adc54d2bf2490d2 | bigcode/the-stack | train |
a253fda504f01b4cfdcf8ab6 | train | function | def archive_extract(arch, path):
if isinstance(arch, zipfile.ZipFile):
arch.extractall(path)
elif isinstance(arch, tarfile.TarFile):
arch.extractall(path=path)
| def archive_extract(arch, path):
| if isinstance(arch, zipfile.ZipFile):
arch.extractall(path)
elif isinstance(arch, tarfile.TarFile):
arch.extractall(path=path)
| def archive_get_members(arch):
if isinstance(arch, zipfile.ZipFile):
members = arch.namelist()
elif isinstance(arch, tarfile.TarFile):
members = [ i.name for i in arch.getmembers() ]
return members
def archive_extract(arch, path):
| 64 | 64 | 45 | 8 | 55 | bopopescu/conpaas-1 | conpaas-services/src/conpaas/core/misc.py | Python | archive_extract | archive_extract | 69 | 73 | 69 | 69 | 444f1c6e79b809e1262666ff356f7d7ef104a395 | bigcode/the-stack | train |
2000f04498d3cdc0b8f50499 | train | function | def rlinput(prompt, prefill=''):
readline.set_startup_hook(lambda: readline.insert_text(prefill))
try:
return raw_input(prompt)
finally:
readline.set_startup_hook()
| def rlinput(prompt, prefill=''):
| readline.set_startup_hook(lambda: readline.insert_text(prefill))
try:
return raw_input(prompt)
finally:
readline.set_startup_hook()
| )[20:24])
def run_cmd(cmd, directory='/'):
pipe = Popen(cmd, shell=True, cwd=directory, stdout=PIPE, stderr=PIPE)
out, error = pipe.communicate()
pipe.wait()
return out, error
def rlinput(prompt, prefill=''):
| 64 | 64 | 42 | 9 | 54 | bopopescu/conpaas-1 | conpaas-services/src/conpaas/core/misc.py | Python | rlinput | rlinput | 94 | 99 | 94 | 94 | 13bc058f40e8fb0b591e2fa8f7b4beedeb2f94c2 | bigcode/the-stack | train |
80d92a831a2c9eb368fb9fb7 | train | class | class Line(Field, GeometryLogic):
OID = LINE
__slots__ = Field.__slots__
def __call__(self, value=Field.empty):
""" Lines are represented by the linear equation Ax + By + C = 0,
where A and B are not both zero.
@value: (#tuple) |(A, B, C)|
"""
if value is no... | class Line(Field, GeometryLogic):
| OID = LINE
__slots__ = Field.__slots__
def __call__(self, value=Field.empty):
""" Lines are represented by the linear equation Ax + By + C = 0,
where A and B are not both zero.
@value: (#tuple) |(A, B, C)|
"""
if value is not Field.empty:
if valu... |
class _LineAdapter(_PointAdapter):
def getquoted(self):
a = adapt(self.value.a)
b = adapt(self.value.b)
c = adapt(self.value.c)
return b"'{%s, %s, %s}'::line" % (a.getquoted(),
b.getquoted(),
c.ge... | 79 | 79 | 266 | 7 | 72 | jaredlunde/cargo-orm | cargo/fields/geometry.py | Python | Line | Line | 223 | 261 | 223 | 223 | 41a00767d26bd7d4dd56bfcaf04711d58498baa4 | bigcode/the-stack | train |
8e1637bc355dc3dfa5941c90 | train | class | class LSeg(Box):
OID = LSEG
__slots__ = Field.__slots__
def __call__(self, value=Field.empty):
""" Lines are represented by the linear equation Ax + By + C = 0,
where A and B are not both zero.
@value: (#tuple) |(A, B, C)|
"""
if value is not Field.empty:
... | class LSeg(Box):
| OID = LSEG
__slots__ = Field.__slots__
def __call__(self, value=Field.empty):
""" Lines are represented by the linear equation Ax + By + C = 0,
where A and B are not both zero.
@value: (#tuple) |(A, B, C)|
"""
if value is not Field.empty:
if valu... | adapt(self.value.a.y)
bx = adapt(self.value.b.x)
by = adapt(self.value.b.y)
box = b"((%s, %s), (%s, %s))" % (ax.getquoted(), ay.getquoted(),
bx.getquoted(), by.getquoted())
return b"'%s'::lseg" % box
class LSeg(Box):
| 81 | 81 | 272 | 5 | 75 | jaredlunde/cargo-orm | cargo/fields/geometry.py | Python | LSeg | LSeg | 279 | 312 | 279 | 279 | 011fd3067fca84fe3276fbe4b63ab65127df5d4a | bigcode/the-stack | train |
80fc062826165468469ba449 | train | class | class _LineAdapter(_PointAdapter):
def getquoted(self):
a = adapt(self.value.a)
b = adapt(self.value.b)
c = adapt(self.value.c)
return b"'{%s, %s, %s}'::line" % (a.getquoted(),
b.getquoted(),
c.getqu... | class _LineAdapter(_PointAdapter):
| def getquoted(self):
a = adapt(self.value.a)
b = adapt(self.value.b)
c = adapt(self.value.c)
return b"'{%s, %s, %s}'::line" % (a.getquoted(),
b.getquoted(),
c.getquoted())
| CircleAdapter)
CIRCLETYPE = reg_type('CIRCLETYPE', CIRCLE, Circle.to_python)
reg_array_type('CIRCLEARRAYTYPE', CIRCLEARRAY, CIRCLETYPE)
CircleRecord = namedtuple('CircleRecord', ('center', 'radius'))
class _LineAdapter(_PointAdapter):
| 63 | 64 | 71 | 8 | 55 | jaredlunde/cargo-orm | cargo/fields/geometry.py | Python | _LineAdapter | _LineAdapter | 212 | 220 | 212 | 213 | f655772098f2ceba9abadeea8013f39ababd9af5 | bigcode/the-stack | train |
42cb563df45e9061dfa08174 | train | class | class _LSegAdapter(_PointAdapter):
def getquoted(self):
ax = adapt(self.value.a.x)
ay = adapt(self.value.a.y)
bx = adapt(self.value.b.x)
by = adapt(self.value.b.y)
box = b"((%s, %s), (%s, %s))" % (ax.getquoted(), ay.getquoted(),
bx.ge... | class _LSegAdapter(_PointAdapter):
| def getquoted(self):
ax = adapt(self.value.a.x)
ay = adapt(self.value.a.y)
bx = adapt(self.value.b.x)
by = adapt(self.value.b.y)
box = b"((%s, %s), (%s, %s))" % (ax.getquoted(), ay.getquoted(),
bx.getquoted(), by.getquoted())
r... | , _LineAdapter)
LINETYPE = reg_type('LINETYPE', LINE, Line.to_python)
reg_array_type('LINEARRAYTYPE', LINEARRAY, LINETYPE)
LineRecord = namedtuple('LineRecord', ('a', 'b', 'c'))
class _LSegAdapter(_PointAdapter):
| 63 | 64 | 103 | 9 | 54 | jaredlunde/cargo-orm | cargo/fields/geometry.py | Python | _LSegAdapter | _LSegAdapter | 267 | 276 | 267 | 268 | ad8d35b72a335c917ec697bdabf0b378e89698ed | bigcode/the-stack | train |
2a6d7c069a585e63dcdba378 | train | class | class Circle(Field, GeometryLogic):
OID = CIRCLE
__slots__ = Field.__slots__
def __call__(self, value=Field.empty):
""" @value: (#tuple) center, radius e.g., |((0, 5), 1)| """
if value is not Field.empty:
if value is not None:
value = CircleRecord(PointRecord(*va... | class Circle(Field, GeometryLogic):
| OID = CIRCLE
__slots__ = Field.__slots__
def __call__(self, value=Field.empty):
""" @value: (#tuple) center, radius e.g., |((0, 5), 1)| """
if value is not Field.empty:
if value is not None:
value = CircleRecord(PointRecord(*value[0]), value[1])
self.... | PointAdapter):
def getquoted(self):
cx = adapt(self.value.center.x)
cy = adapt(self.value.center.y)
r = adapt(self.value.radius)
circ = b"((%s, %s), %s)" % (cx.getquoted(), cy.getquoted(),
r.getquoted())
return b"'%s'::circle" % circ
class... | 85 | 85 | 285 | 7 | 77 | jaredlunde/cargo-orm | cargo/fields/geometry.py | Python | Circle | Circle | 171 | 206 | 171 | 171 | d7cef0e169fb23725fdba68391c770c96105f3fe | bigcode/the-stack | train |
8f425f8f33fcdc49a4871098 | train | class | class _PolygonAdapter(_PointAdapter):
def getquoted(self):
points = (b"(%s, %s)" % (adapt(point.x).getquoted(),
adapt(point.y).getquoted())
for point in self.value)
points = b"(%s)" % b", ".join(points)
return b"'%s'::polygon" % points
| class _PolygonAdapter(_PointAdapter):
| def getquoted(self):
points = (b"(%s, %s)" % (adapt(point.x).getquoted(),
adapt(point.y).getquoted())
for point in self.value)
points = b"(%s)" % b", ".join(points)
return b"'%s'::polygon" % points
| for _ in paths))
f.append(closed)
self.data = nt(*f)
def __getattr__(self, name):
try:
return self.__getattribute__(name)
except AttributeError:
return self.data.__getattribute__(name)
class _PolygonAdapter(_PointAdapter):
| 64 | 64 | 78 | 8 | 56 | jaredlunde/cargo-orm | cargo/fields/geometry.py | Python | _PolygonAdapter | _PolygonAdapter | 431 | 438 | 431 | 432 | aea808303bd7e8ebe1c1fcc79a3d99684e25e10e | bigcode/the-stack | train |
e219ac4308802045e4f9d664 | train | class | class _PathAdapter(_PointAdapter):
def getquoted(self):
points = (b"(%s, %s)" % (adapt(x).getquoted(), adapt(y).getquoted())
for x, y in self.value[:-1])
ctype = b"(%s)" if self.value.closed else b"[%s]"
ctype = ctype % b", ".join(points)
return b"'%s'::path" % cty... | class _PathAdapter(_PointAdapter):
| def getquoted(self):
points = (b"(%s, %s)" % (adapt(x).getquoted(), adapt(y).getquoted())
for x, y in self.value[:-1])
ctype = b"(%s)" if self.value.closed else b"[%s]"
ctype = ctype % b", ".join(points)
return b"'%s'::path" % ctype
| LSEGTYPE = reg_type('LSEGTYPE', LSEG, LSeg.to_python)
reg_array_type('LSEGARRAYTYPE', LSEGARRAY, LSEGTYPE)
LSegRecord = namedtuple('LSegRecord', ('a', 'b'))
class _PathAdapter(_PointAdapter):
| 63 | 64 | 97 | 8 | 55 | jaredlunde/cargo-orm | cargo/fields/geometry.py | Python | _PathAdapter | _PathAdapter | 318 | 325 | 318 | 319 | 4a7e7e2064014a32e7547045ed2ac42342b1b9de | bigcode/the-stack | train |
6afd59024b9e72ce7a7756c1 | train | class | class _BoxAdapter(_PointAdapter):
def getquoted(self):
ax = adapt(self.value.a.x)
ay = adapt(self.value.a.y)
bx = adapt(self.value.b.x)
by = adapt(self.value.b.y)
box = b"((%s, %s), (%s, %s))" % (ax.getquoted(), ay.getquoted(),
bx.get... | class _BoxAdapter(_PointAdapter):
| def getquoted(self):
ax = adapt(self.value.a.x)
ay = adapt(self.value.a.y)
bx = adapt(self.value.b.x)
by = adapt(self.value.b.y)
box = b"((%s, %s), (%s, %s))" % (ax.getquoted(), ay.getquoted(),
bx.getquoted(), by.getquoted())
r... | register_adapter(PointRecord, _PointAdapter)
POINTTYPE = reg_type('POINTTYPE', POINT, Point.to_python)
reg_array_type('POINTARRAYTYPE', POINTARRAY, POINTTYPE)
PointRecord = namedtuple('PointRecord', ('x', 'y'))
class _BoxAdapter(_PointAdapter):
| 63 | 64 | 101 | 8 | 55 | jaredlunde/cargo-orm | cargo/fields/geometry.py | Python | _BoxAdapter | _BoxAdapter | 97 | 106 | 97 | 98 | 9fab154ff2694c9dd901cf68547b63fe473c142f | bigcode/the-stack | train |
debdfaebd2eed36103a85b84 | train | class | class _PointAdapter(object):
def __init__(self, value):
self.value = value
def prepare(self, conn):
self.conn = conn
def getquoted(self):
ax = adapt(self.value.x)
ay = adapt(self.value.y)
p = b"(%s, %s)" % (ax.getquoted(), ay.getquoted())
return b"'%s'::poi... | class _PointAdapter(object):
| def __init__(self, value):
self.value = value
def prepare(self, conn):
self.conn = conn
def getquoted(self):
ax = adapt(self.value.x)
ay = adapt(self.value.y)
p = b"(%s, %s)" % (ax.getquoted(), ay.getquoted())
return b"'%s'::point" % p
| .etc.types import *
from cargo.expressions import *
from cargo.fields import Field
from cargo.logic import GeometryLogic
__all__ = (
'Box',
'Circle',
'Line',
'LSeg',
'Path',
'Point',
'Polygon')
class _PointAdapter(object):
| 64 | 64 | 90 | 6 | 58 | jaredlunde/cargo-orm | cargo/fields/geometry.py | Python | _PointAdapter | _PointAdapter | 36 | 48 | 36 | 37 | 548e3a639b1d2d0720ed6947b19424c0e6609102 | bigcode/the-stack | train |
c619b3fdb9077c716039feb5 | train | class | class PathRecord(UserList):
__slots__ = ('data',)
def __init__(self, *paths, closed=False):
p = list('_' for _ in paths)
p.append('closed')
nt = namedtuple('PathRecord', p, rename=True)
f = list((PointRecord(_[0], _[1])
if not isinstance(_, PointRecord) else _
... | class PathRecord(UserList):
| __slots__ = ('data',)
def __init__(self, *paths, closed=False):
p = list('_' for _ in paths)
p.append('closed')
nt = namedtuple('PathRecord', p, rename=True)
f = list((PointRecord(_[0], _[1])
if not isinstance(_, PointRecord) else _
for _ in pat... | ), closed=closed)
@staticmethod
def register_adapter():
register_adapter(PathRecord, _PathAdapter)
PATHTYPE = reg_type('PATHTYPE', PATH, Path.to_python)
reg_array_type('PATHARRAYTYPE', PATHARRAY, PATHTYPE)
class PathRecord(UserList):
| 64 | 64 | 141 | 6 | 58 | jaredlunde/cargo-orm | cargo/fields/geometry.py | Python | PathRecord | PathRecord | 411 | 428 | 411 | 411 | 0a5b5c2a7ff717f255d81b980cb36b18024eec49 | bigcode/the-stack | train |
655fea017941affa83d260f1 | train | class | class Path(Field, GeometryLogic):
OID = PATH
__slots__ = ('field_name', 'primary', 'unique', 'index', 'not_null',
'value', 'validator', '_alias', 'default', 'table',
'_closed')
def __init__(self, closed=None, value=Field.empty, *args, **kwargs):
""" Lines are repre... | class Path(Field, GeometryLogic):
| OID = PATH
__slots__ = ('field_name', 'primary', 'unique', 'index', 'not_null',
'value', 'validator', '_alias', 'default', 'table',
'_closed')
def __init__(self, closed=None, value=Field.empty, *args, **kwargs):
""" Lines are represented by the linear equation Ax +... | None:
return val
return LSegRecord(*eval(val))
@staticmethod
def register_adapter():
register_adapter(LSegRecord, _LSegAdapter)
LSEGTYPE = reg_type('LSEGTYPE', LSEG, LSeg.to_python)
reg_array_type('LSEGARRAYTYPE', LSEGARRAY, LSEGTYPE)
LSegRecord = namedtuple('LSeg... | 197 | 197 | 658 | 7 | 189 | jaredlunde/cargo-orm | cargo/fields/geometry.py | Python | Path | Path | 328 | 408 | 328 | 328 | 842643f7f1253e25c19bfbd4f093295cd6765f95 | bigcode/the-stack | train |
62ed9f0e1c1983eccb0191e6 | train | class | class Polygon(Field, GeometryLogic):
OID = POLYGON
__slots__ = Field.__slots__
def __call__(self, value=Field.empty):
""" Lines are represented by the linear equation Ax + By + C = 0,
where A and B are not both zero.
@value: (#tuple) |((x1, y1), (x2, y2), ...)|
"""
... | class Polygon(Field, GeometryLogic):
| OID = POLYGON
__slots__ = Field.__slots__
def __call__(self, value=Field.empty):
""" Lines are represented by the linear equation Ax + By + C = 0,
where A and B are not both zero.
@value: (#tuple) |((x1, y1), (x2, y2), ...)|
"""
if value is not Field.empty:
... | __(name)
class _PolygonAdapter(_PointAdapter):
def getquoted(self):
points = (b"(%s, %s)" % (adapt(point.x).getquoted(),
adapt(point.y).getquoted())
for point in self.value)
points = b"(%s)" % b", ".join(points)
return b"'%s'::polygon" % ... | 88 | 88 | 296 | 7 | 80 | jaredlunde/cargo-orm | cargo/fields/geometry.py | Python | Polygon | Polygon | 441 | 481 | 441 | 441 | 93b8febd929bf9eadbb18f09c0e829d1168f2698 | bigcode/the-stack | train |
63e9164f255f139b7d60575c | train | class | class Box(Field, GeometryLogic):
OID = BOX
__slots__ = Field.__slots__
def __call__(self, value=Field.empty):
if value is not Field.empty:
if value is not None:
value = BoxRecord(PointRecord(*value[0]),
PointRecord(*value[1]))
... | class Box(Field, GeometryLogic):
| OID = BOX
__slots__ = Field.__slots__
def __call__(self, value=Field.empty):
if value is not Field.empty:
if value is not None:
value = BoxRecord(PointRecord(*value[0]),
PointRecord(*value[1]))
self.value = value
retu... | ax = adapt(self.value.a.x)
ay = adapt(self.value.a.y)
bx = adapt(self.value.b.x)
by = adapt(self.value.b.y)
box = b"((%s, %s), (%s, %s))" % (ax.getquoted(), ay.getquoted(),
bx.getquoted(), by.getquoted())
return b"'%s'::box" % box
class B... | 93 | 93 | 310 | 7 | 85 | jaredlunde/cargo-orm | cargo/fields/geometry.py | Python | Box | Box | 109 | 154 | 109 | 109 | 885bb9a72b2c6f444035e448f29759ab5782b741 | bigcode/the-stack | train |
949b0e1fa4dad3759d7adedc | train | class | class PolygonRecord(UserList):
__slots__ = ('data',)
def __init__(self, poly):
nt = namedtuple('PolygonRecord', ('_' for _ in poly), rename=True)
self.data = nt(*(PointRecord(x, y) for x, y in poly))
def __getattr__(self, name):
try:
return self.__getattribute__(name)
... | class PolygonRecord(UserList):
| __slots__ = ('data',)
def __init__(self, poly):
nt = namedtuple('PolygonRecord', ('_' for _ in poly), rename=True)
self.data = nt(*(PointRecord(x, y) for x, y in poly))
def __getattr__(self, name):
try:
return self.__getattribute__(name)
except AttributeError:
... | register_adapter(PolygonRecord, _PolygonAdapter)
POLYGONTYPE = reg_type('POLYGONTYPE', POLYGON, Polygon.to_python)
POLYGONARRAYTYPE = reg_array_type('POLYGONARRAYTYPE',
POLYGONARRAY,
POLYGONTYPE)
class PolygonRec... | 64 | 64 | 99 | 6 | 58 | jaredlunde/cargo-orm | cargo/fields/geometry.py | Python | PolygonRecord | PolygonRecord | 484 | 495 | 484 | 484 | 227ea11cde1aef29272ce5cd73b53da52b479bf7 | bigcode/the-stack | train |
6190840fd720c69b4c7bfb85 | train | class | class _CircleAdapter(_PointAdapter):
def getquoted(self):
cx = adapt(self.value.center.x)
cy = adapt(self.value.center.y)
r = adapt(self.value.radius)
circ = b"((%s, %s), %s)" % (cx.getquoted(), cy.getquoted(),
r.getquoted())
return b"'%s'... | class _CircleAdapter(_PointAdapter):
| def getquoted(self):
cx = adapt(self.value.center.x)
cy = adapt(self.value.center.y)
r = adapt(self.value.radius)
circ = b"((%s, %s), %s)" % (cx.getquoted(), cy.getquoted(),
r.getquoted())
return b"'%s'::circle" % circ
| _adapter(BoxRecord, _BoxAdapter)
BOXTYPE = reg_type('BOXTYPE', BOX, Box.to_python)
reg_type('BOXARRAYTYPE', BOXARRAY, Box.array_to_python)
BoxRecord = namedtuple('BoxRecord', ('a', 'b'))
class _CircleAdapter(_PointAdapter):
| 63 | 64 | 83 | 8 | 55 | jaredlunde/cargo-orm | cargo/fields/geometry.py | Python | _CircleAdapter | _CircleAdapter | 160 | 168 | 160 | 161 | b256ab8dfc376fc692a6043e8ec6cfb7c3ca28e1 | bigcode/the-stack | train |
3cd468a02ca3824cb1b88417 | train | class | class Point(Field, GeometryLogic):
OID = POINT
__slots__ = Field.__slots__
def __call__(self, value=Field.empty):
if value is not Field.empty:
if value is not None:
value = PointRecord(*value)
self.value = value
return self.value
@property
de... | class Point(Field, GeometryLogic):
| OID = POINT
__slots__ = Field.__slots__
def __call__(self, value=Field.empty):
if value is not Field.empty:
if value is not None:
value = PointRecord(*value)
self.value = value
return self.value
@property
def x(self):
try:
... | conn):
self.conn = conn
def getquoted(self):
ax = adapt(self.value.x)
ay = adapt(self.value.y)
p = b"(%s, %s)" % (ax.getquoted(), ay.getquoted())
return b"'%s'::point" % p
class Point(Field, GeometryLogic):
| 71 | 71 | 239 | 7 | 63 | jaredlunde/cargo-orm | cargo/fields/geometry.py | Python | Point | Point | 51 | 91 | 51 | 51 | d2b546d271da98a13c6200fececd61354b9b0ab6 | bigcode/the-stack | train |
292de4aadcc61387efb32f1d | train | function | @pytest.fixture
def minio_server(s3_server):
s3_server.kill()
server_url = s3_server.boto_endpoint_url
return urlparse(server_url).netloc
| @pytest.fixture
def minio_server(s3_server):
| s3_server.kill()
server_url = s3_server.boto_endpoint_url
return urlparse(server_url).netloc
| import pytest
from urllib.parse import urlparse
@pytest.fixture
def minio_server(s3_server):
| 21 | 64 | 39 | 11 | 9 | AFCYBER-DREAM/python-piperci | tests/unit/storeman/conftest.py | Python | minio_server | minio_server | 5 | 9 | 5 | 6 | 766abc5264123ca34d786e36f8a8245c9070f051 | bigcode/the-stack | train |
29d37c03d2fb45351e7c17e3 | train | function | @pytest.fixture
def minio_bucket_with_files(s3_bucket):
bucket = s3_bucket.name
object = s3_bucket.client.Object(bucket, "test")
object.put(Body="test")
return bucket
| @pytest.fixture
def minio_bucket_with_files(s3_bucket):
| bucket = s3_bucket.name
object = s3_bucket.client.Object(bucket, "test")
object.put(Body="test")
return bucket
| import pytest
from urllib.parse import urlparse
@pytest.fixture
def minio_server(s3_server):
s3_server.kill()
server_url = s3_server.boto_endpoint_url
return urlparse(server_url).netloc
@pytest.fixture
def minio_bucket_with_files(s3_bucket):
| 62 | 64 | 46 | 13 | 48 | AFCYBER-DREAM/python-piperci | tests/unit/storeman/conftest.py | Python | minio_bucket_with_files | minio_bucket_with_files | 12 | 17 | 12 | 13 | 8c430f4ce0079d2b8f28b48baa266ade56b018e1 | bigcode/the-stack | train |
0c18f255e6810185c3c900db | train | function | def unconstrain_stationary_univariate(constrained):
"""
Transform constrained parameters used in likelihood evaluation
to unconstrained parameters used by the optimizer
Parameters
----------
constrained : array
Constrained parameters of, e.g., an autoregressive or moving average
... | def unconstrain_stationary_univariate(constrained):
| """
Transform constrained parameters used in likelihood evaluation
to unconstrained parameters used by the optimizer
Parameters
----------
constrained : array
Constrained parameters of, e.g., an autoregressive or moving average
component, to be transformed to arbitrary parameter... | strained / ((1 + unconstrained**2)**0.5)
for k in range(n):
for i in range(k):
y[k, i] = y[k - 1, i] + r[k] * y[k - 1, k - i - 1]
y[k, k] = r[k]
return -y[n - 1, :]
def unconstrain_stationary_univariate(constrained):
| 91 | 92 | 309 | 10 | 81 | jbrockmendel/sm2 | sm2/tsa/statespace/tools.py | Python | unconstrain_stationary_univariate | unconstrain_stationary_univariate | 477 | 512 | 477 | 477 | 5974ef36bfded4e42935147e1ff587baf926987b | bigcode/the-stack | train |
3ca47496098ee4c5ad7f8a20 | train | function | def set_mode(compatibility=None):
# Determine mode automatically if none given
if compatibility is True: # pragma: no cover
raise NotImplementedError("compatibility_mode=True not ported from"
"upstream, since sm2 requires relatively "
... | def set_mode(compatibility=None):
# Determine mode automatically if none given
| if compatibility is True: # pragma: no cover
raise NotImplementedError("compatibility_mode=True not ported from"
"upstream, since sm2 requires relatively "
"recent scipy.")
from scipy.linalg import cython_blas # noqa:F401,F811
fr... | """
Statespace Tools
Author: Chad Fulton
License: Simplified-BSD
"""
from __future__ import division, absolute_import, print_function
import numpy as np
# from scipy import linalg
# from scipy.linalg import solve_sylvester
# from scipy.linalg.blas import find_best_blas_type
import pandas as pd
from sm2.tools.data i... | 248 | 256 | 858 | 17 | 231 | jbrockmendel/sm2 | sm2/tsa/statespace/tools.py | Python | set_mode | set_mode | 38 | 120 | 38 | 39 | e02a4c3ae0ca4f730a5903a175ece9e255ac1bb6 | bigcode/the-stack | train |
4a50f50978fd4e350162798a | train | function | def prepare_exog(exog):
k_exog = 0
if exog is not None:
exog_is_using_pandas = _is_using_pandas(exog, None)
if not exog_is_using_pandas:
exog = np.asarray(exog)
# Make sure we have 2-dimensional array
if exog.ndim == 1:
if not exog_is_using_pandas:
... | def prepare_exog(exog):
| k_exog = 0
if exog is not None:
exog_is_using_pandas = _is_using_pandas(exog, None)
if not exog_is_using_pandas:
exog = np.asarray(exog)
# Make sure we have 2-dimensional array
if exog.ndim == 1:
if not exog_is_using_pandas:
exog = exog[:,... | or convert it to a numpy array
try:
if not a.is_f_contig():
raise ValueError()
except:
a = np.asfortranarray(a)
copy(a, b, np.asfortranarray(index))
return b
'''
def prepare_exog(exog):
| 63 | 64 | 134 | 7 | 56 | jbrockmendel/sm2 | sm2/tsa/statespace/tools.py | Python | prepare_exog | prepare_exog | 1,535 | 1,550 | 1,535 | 1,535 | f45338542d153a20c152092c1f427c06d32a0a72 | bigcode/the-stack | train |
4e1f52a04f4cb172549987e5 | train | function | def constrain_stationary_univariate(unconstrained):
"""
Transform unconstrained parameters used by the optimizer to constrained
parameters used in likelihood evaluation
Parameters
----------
unconstrained : array
Unconstrained parameters used by the optimizer, to be transformed to
... | def constrain_stationary_univariate(unconstrained):
| """
Transform unconstrained parameters used by the optimizer to constrained
parameters used in likelihood evaluation
Parameters
----------
unconstrained : array
Unconstrained parameters used by the optimizer, to be transformed to
stationary coefficients of, e.g., an autoregressi... | else:
aH = a.transpose()
aHI_inv = np.linalg.inv(aH + eye)
b = np.dot(aH - eye, aHI_inv)
c = 2 * np.dot(np.dot(np.linalg.inv(a + eye), q), aHI_inv)
return solve_sylvester(b.transpose(), b, -c)
'''
def constrain_stationary_univariate(unconstrained):
| 85 | 86 | 288 | 10 | 75 | jbrockmendel/sm2 | sm2/tsa/statespace/tools.py | Python | constrain_stationary_univariate | constrain_stationary_univariate | 441 | 474 | 441 | 441 | 40775fb49b8e167df43e85434d0002db7289a1c5 | bigcode/the-stack | train |
4a5b4e42e7f15b9acd97d354 | train | function | @pytest.mark.kubernetes
def test_k8s_portless_pods_with_declared_port(k8s_cluster):
with k8s_cluster.create_resources([TEST_SERVICES_DIR / "redis" / "redis-k8s.yaml"]):
config = """
observers:
- type: k8s-api
monitors:
- type: collectd/redis
dis... | @pytest.mark.kubernetes
def test_k8s_portless_pods_with_declared_port(k8s_cluster):
| with k8s_cluster.create_resources([TEST_SERVICES_DIR / "redis" / "redis-k8s.yaml"]):
config = """
observers:
- type: k8s-api
monitors:
- type: collectd/redis
discoveryRule: target == "pod" && kubernetes_pod_name =~ "redis-deployment"
... | 9
"""
with k8s_cluster.run_agent(config) as agent:
assert wait_for(p(has_datapoint, agent.fake_services, metric_name="bytes.used_memory_rss"))
@pytest.mark.kubernetes
def test_k8s_portless_pods_with_declared_port(k8s_cluster):
| 63 | 64 | 144 | 23 | 40 | manang-splunk/signalfx-agent | tests/observers/k8s_api_test.py | Python | test_k8s_portless_pods_with_declared_port | test_k8s_portless_pods_with_declared_port | 156 | 169 | 156 | 157 | 14349e4dc51e47fc582dd8dee54e6f512bd31682 | bigcode/the-stack | train |
d63abc4d16facd0f16e89767 | train | function | @pytest.mark.kubernetes
def test_k8s_annotations_in_discovery(k8s_cluster):
nginx_yaml = TEST_SERVICES_DIR / "nginx/nginx-k8s.yaml"
with k8s_cluster.create_resources([nginx_yaml]):
config = """
observers:
- type: k8s-api
monitors:
- type: collectd/nginx
... | @pytest.mark.kubernetes
def test_k8s_annotations_in_discovery(k8s_cluster):
| nginx_yaml = TEST_SERVICES_DIR / "nginx/nginx-k8s.yaml"
with k8s_cluster.create_resources([nginx_yaml]):
config = """
observers:
- type: k8s-api
monitors:
- type: collectd/nginx
discoveryRule: 'Get(kubernetes_annotations, "allowScraping") ==... | oint, agent.fake_services, metric_name="nginx_requests"), timeout_seconds=10)
wait_for(p(has_datapoint, agent.fake_services, metric_name="sfxagent.active_monitors", value=2))
@pytest.mark.kubernetes
def test_k8s_annotations_in_discovery(k8s_cluster):
| 64 | 64 | 142 | 19 | 45 | manang-splunk/signalfx-agent | tests/observers/k8s_api_test.py | Python | test_k8s_annotations_in_discovery | test_k8s_annotations_in_discovery | 100 | 113 | 100 | 101 | 58d04b2c2e08d256a8a670afdcb5795e51b6e900 | bigcode/the-stack | train |
978b751e4cb9b3230ab900b5 | train | function | @pytest.mark.kubernetes
def test_k8s_annotations_with_alt_ports(k8s_cluster):
consul_yaml = list(yaml.safe_load_all((TEST_SERVICES_DIR / "consul/k8s.yaml").read_bytes()))
# Remove the declared port so we make sure the additionalPortAnnotations is
# what is causing it to be discovered.
consul_yaml[0]["sp... | @pytest.mark.kubernetes
def test_k8s_annotations_with_alt_ports(k8s_cluster):
| consul_yaml = list(yaml.safe_load_all((TEST_SERVICES_DIR / "consul/k8s.yaml").read_bytes()))
# Remove the declared port so we make sure the additionalPortAnnotations is
# what is causing it to be discovered.
consul_yaml[0]["spec"]["template"]["spec"]["containers"][0]["ports"] = []
with k8s_cluster.... | ubernetes_annotations, "allowScraping") == "true" && port == 80'
"""
with k8s_cluster.run_agent(config) as agent:
assert wait_for(p(has_datapoint, agent.fake_services, dimensions={"plugin": "nginx"}))
@pytest.mark.kubernetes
def test_k8s_annotations_with_alt_ports(k8s_cluster):
| 75 | 75 | 253 | 19 | 56 | manang-splunk/signalfx-agent | tests/observers/k8s_api_test.py | Python | test_k8s_annotations_with_alt_ports | test_k8s_annotations_with_alt_ports | 116 | 137 | 116 | 117 | 995701cef4cc21b82d7643ab20266021693ba47f | bigcode/the-stack | train |
09b2d6debe7bd337baab864d | train | function | @pytest.mark.kubernetes
def test_merges_config_from_annotations_and_agent_yaml(k8s_cluster):
nginx_yaml = TEST_SERVICES_DIR / "nginx/nginx-k8s.yaml"
nginx_with_annotations = yaml.dump_all(
add_pod_spec_annotations(
yaml.safe_load_all(nginx_yaml.read_bytes()),
{
"a... | @pytest.mark.kubernetes
def test_merges_config_from_annotations_and_agent_yaml(k8s_cluster):
| nginx_yaml = TEST_SERVICES_DIR / "nginx/nginx-k8s.yaml"
nginx_with_annotations = yaml.dump_all(
add_pod_spec_annotations(
yaml.safe_load_all(nginx_yaml.read_bytes()),
{
"agent.signalfx.com/monitorType.http": "collectd/nginx",
"agent.signalfx.com/co... | myapp"}))
assert ensure_always(
p(
has_no_datapoint,
agent.fake_services,
metric_name="nginx_connections.active",
dimensions={"source": "myapp"},
)
)
for dp in agent.fake_s... | 112 | 112 | 376 | 20 | 92 | manang-splunk/signalfx-agent | tests/observers/k8s_api_test.py | Python | test_merges_config_from_annotations_and_agent_yaml | test_merges_config_from_annotations_and_agent_yaml | 63 | 97 | 63 | 64 | 04760c742b6ad9f4db79908c08ca106792918e65 | bigcode/the-stack | train |
5d4a482fd9fb7d3bf1dc210c | train | function | @pytest.mark.kubernetes
def test_k8s_portless_pod(k8s_cluster):
with k8s_cluster.create_resources([TEST_SERVICES_DIR / "redis" / "redis-k8s-portless.yaml"]):
config = """
observers:
- type: k8s-api
monitors:
- type: collectd/redis
discoveryRule:... | @pytest.mark.kubernetes
def test_k8s_portless_pod(k8s_cluster):
| with k8s_cluster.create_resources([TEST_SERVICES_DIR / "redis" / "redis-k8s-portless.yaml"]):
config = """
observers:
- type: k8s-api
monitors:
- type: collectd/redis
discoveryRule: target == "pod" && kubernetes_pod_name =~ "redis-portless-only"... | /path", "/metrics")'
"""
with k8s_cluster.run_agent(config) as agent:
assert wait_for(p(has_datapoint, agent.fake_services, metric_name="consul_runtime_malloc_count"))
@pytest.mark.kubernetes
def test_k8s_portless_pod(k8s_cluster):
| 63 | 64 | 143 | 19 | 44 | manang-splunk/signalfx-agent | tests/observers/k8s_api_test.py | Python | test_k8s_portless_pod | test_k8s_portless_pod | 140 | 153 | 140 | 141 | 236d44aaaaf386f0d2752b33870ce1a85fd231d0 | bigcode/the-stack | train |
fef00bb5fe123356e8c00ee2 | train | function | @pytest.mark.kubernetes
def test_k8s_api_observer_basic(k8s_cluster):
nginx_yaml = TEST_SERVICES_DIR / "nginx/nginx-k8s.yaml"
with k8s_cluster.create_resources([nginx_yaml]):
config = f"""
observers:
- type: k8s-api
monitors:
- type: collectd/nginx
... | @pytest.mark.kubernetes
def test_k8s_api_observer_basic(k8s_cluster):
| nginx_yaml = TEST_SERVICES_DIR / "nginx/nginx-k8s.yaml"
with k8s_cluster.create_resources([nginx_yaml]):
config = f"""
observers:
- type: k8s-api
monitors:
- type: collectd/nginx
discoveryRule: 'discovered_by == "k8s-api" && kubernetes_nam... | , has_dim_key, has_no_datapoint
from tests.helpers.kubernetes.utils import add_pod_spec_annotations
from tests.helpers.util import ensure_always, wait_for
from tests.paths import TEST_SERVICES_DIR
@pytest.mark.kubernetes
def test_k8s_api_observer_basic(k8s_cluster):
| 64 | 64 | 186 | 19 | 44 | manang-splunk/signalfx-agent | tests/observers/k8s_api_test.py | Python | test_k8s_api_observer_basic | test_k8s_api_observer_basic | 11 | 24 | 11 | 12 | 3dd476f8c1c41ba864191b52361e7c7ea7dbc546 | bigcode/the-stack | train |
436887de75a5d58d17c30014 | train | function | @pytest.mark.kubernetes
def test_config_from_annotations(k8s_cluster):
nginx_yaml = TEST_SERVICES_DIR / "nginx/nginx-k8s.yaml"
nginx_with_annotations = yaml.dump_all(
add_pod_spec_annotations(
yaml.safe_load_all(nginx_yaml.read_bytes()),
{
"agent.signalfx.com/moni... | @pytest.mark.kubernetes
def test_config_from_annotations(k8s_cluster):
| nginx_yaml = TEST_SERVICES_DIR / "nginx/nginx-k8s.yaml"
nginx_with_annotations = yaml.dump_all(
add_pod_spec_annotations(
yaml.safe_load_all(nginx_yaml.read_bytes()),
{
"agent.signalfx.com/monitorType.http": "collectd/nginx",
"agent.signalfx.com/co... | .test_namespace}" && port == 80 && container_spec_name == "nginx"'
url: "http://{{{{.Host}}}}:{{{{.Port}}}}/nginx_status"
"""
with k8s_cluster.run_agent(config) as agent:
assert wait_for(p(has_datapoint, agent.fake_services, dimensions={"plugin": "nginx"}))
@pytest.mark.kubern... | 95 | 95 | 318 | 15 | 80 | manang-splunk/signalfx-agent | tests/observers/k8s_api_test.py | Python | test_config_from_annotations | test_config_from_annotations | 27 | 60 | 27 | 28 | 451113f857367d89dd7dc564b411faaf9b447038 | bigcode/the-stack | train |
1626fdf315daddc16f4a96b8 | train | class | class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(500, 500)
Form.setMinimumSize(QtCore.QSize(500, 500))
Form.setMaximumSize(QtCore.QSize(500, 500))
Form.setStyleSheet("QWidget#Form{\n"
" border-image: url(:/login/bg.png);\n"
"}")
... | class Ui_Form(object):
| def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(500, 500)
Form.setMinimumSize(QtCore.QSize(500, 500))
Form.setMaximumSize(QtCore.QSize(500, 500))
Form.setStyleSheet("QWidget#Form{\n"
" border-image: url(:/login/bg.png);\n"
"}")
self.verticalLayout =... | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'login.ui'
#
# Created by: PyQt5 UI code generator 5.13.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
| 71 | 256 | 2,680 | 5 | 65 | Kenny-Z/IOT-Message-Board-with-Face-Recognition | resource/login.py | Python | Ui_Form | Ui_Form | 13 | 222 | 13 | 13 | ea509188c47c34ef342918c2f839f9bc336ba399 | bigcode/the-stack | train |
6d34c95d203d3e520ed29487 | train | class | class InterpolatorBase:
"""Base class for performing predictions based on just the input. Subclasses
are expected to provide a predict_single classmethod specifying their
predictions.
Its predict and evaluate methods are designed to resemble that of
tf.estimator.Estimator's, so that we can call... | class InterpolatorBase:
| """Base class for performing predictions based on just the input. Subclasses
are expected to provide a predict_single classmethod specifying their
predictions.
Its predict and evaluate methods are designed to resemble that of
tf.estimator.Estimator's, so that we can call them in the same way. (... | """Provides simple interpolation methods; useful to give a baseline to compare
neural network models against."""
import numpy as np
import sklearn.base as skb
import sklearn.preprocessing as skpr
import sklearn.pipeline as skpi
import sklearn.linear_model as sklm
# https://github.com/patrick-kidger/tools
import tools... | 80 | 152 | 509 | 6 | 73 | patrick-kidger/CamassaHolmProject | project/base/interpolation.py | Python | InterpolatorBase | InterpolatorBase | 16 | 77 | 16 | 16 | 1932e0b2bfa40b740047ca37355d68d38dfabcc6 | bigcode/the-stack | train |
1802c923de9652eb80d8cdf3 | train | class | class PolyInterpGrid(PolyInterpMixin, InterpolatorGrid):
pass
| class PolyInterpGrid(PolyInterpMixin, InterpolatorGrid):
| pass
| t_n_x_n = Xi[grid._index_tol(cg, (t_nearest, x_nearest))]
return t_n_x_n
class BilinearInterpGrid(BilinearInterpMixin, InterpolatorGrid):
pass
class PolyInterpGrid(PolyInterpMixin, InterpolatorGrid):
| 64 | 64 | 17 | 14 | 49 | patrick-kidger/CamassaHolmProject | project/base/interpolation.py | Python | PolyInterpGrid | PolyInterpGrid | 240 | 241 | 240 | 240 | 988ea201d9b302c783716f1ca9aa8f3f997d8bd9 | bigcode/the-stack | train |
0c974525dc38a3466c650ad1 | train | class | class BilinearInterpGrid(BilinearInterpMixin, InterpolatorGrid):
pass
| class BilinearInterpGrid(BilinearInterpMixin, InterpolatorGrid):
| pass
| round')
# The value of :Xi: at those grid points.
t_n_x_n = Xi[grid._index_tol(cg, (t_nearest, x_nearest))]
return t_n_x_n
class BilinearInterpGrid(BilinearInterpMixin, InterpolatorGrid):
| 64 | 64 | 19 | 16 | 47 | patrick-kidger/CamassaHolmProject | project/base/interpolation.py | Python | BilinearInterpGrid | BilinearInterpGrid | 236 | 237 | 236 | 236 | 67ce9b8544009a942c43cce8d5d64cf683f5b83d | bigcode/the-stack | train |
3fffaac7fc5f73ac5394e3a2 | train | class | class Perfect(InterpolatorBase):
"""Regressor that cheats to always give the perfect prediction."""
def predict_single(self, Xi, yi):
return yi
| class Perfect(InterpolatorBase):
| """Regressor that cheats to always give the perfect prediction."""
def predict_single(self, Xi, yi):
return yi
| Grid):
pass
class PolyInterpGrid(PolyInterpMixin, InterpolatorGrid):
pass
class BilinearInterpPoint(BilinearInterpMixin, InterpolatorPoint):
pass
class PolyInterpPoint(PolyInterpMixin, InterpolatorPoint):
pass
class Perfect(InterpolatorBase):
| 64 | 64 | 34 | 6 | 57 | patrick-kidger/CamassaHolmProject | project/base/interpolation.py | Python | Perfect | Perfect | 252 | 256 | 252 | 252 | 57e5c5ea6f4f237bdc0d1c564ae27415d016a122 | bigcode/the-stack | train |
262c2cb58f564c939ab64a62 | train | class | class BilinearInterpPoint(BilinearInterpMixin, InterpolatorPoint):
pass
| class BilinearInterpPoint(BilinearInterpMixin, InterpolatorPoint):
| pass
| x_nearest))]
return t_n_x_n
class BilinearInterpGrid(BilinearInterpMixin, InterpolatorGrid):
pass
class PolyInterpGrid(PolyInterpMixin, InterpolatorGrid):
pass
class BilinearInterpPoint(BilinearInterpMixin, InterpolatorPoint):
| 64 | 64 | 19 | 16 | 47 | patrick-kidger/CamassaHolmProject | project/base/interpolation.py | Python | BilinearInterpPoint | BilinearInterpPoint | 244 | 245 | 244 | 244 | 25a9fdbfa325424443c3e6d41eadd8e820ca5f4a | bigcode/the-stack | train |
80edff0e801ef89dde9ba2ec | train | class | class PolyInterpMixin(InterpolatorBase):
"""Mixin to help perform polynomial interpolation."""
def __init__(self, poly_deg, *args, **kwargs):
self.poly_deg = poly_deg
self._poly_coefs = None
super(PolyInterpMixin, self).__init__(*args, **kwargs)
def poly(self, point):
... | class PolyInterpMixin(InterpolatorBase):
| """Mixin to help perform polynomial interpolation."""
def __init__(self, poly_deg, *args, **kwargs):
self.poly_deg = poly_deg
self._poly_coefs = None
super(PolyInterpMixin, self).__init__(*args, **kwargs)
def poly(self, point):
"""Interprets its currently stored... | ) * (x ** x_power)
try:
next_coef = next(coefs)
except StopIteration:
return result
else:
raise RuntimeError('coef_: {coef_}, poly_deg: {poly_deg}, '
'coef that shouldn\'t exist: {next_coef}'
.format(coef_=coef_,
... | 95 | 96 | 323 | 8 | 87 | patrick-kidger/CamassaHolmProject | project/base/interpolation.py | Python | PolyInterpMixin | PolyInterpMixin | 180 | 213 | 180 | 180 | 438d1f5d1b4aee87806a85323b413a1ca821fcdd | bigcode/the-stack | train |
a1a2eda82c90c7e169fd9461 | train | class | class PolyInterpPoint(PolyInterpMixin, InterpolatorPoint):
pass
| class PolyInterpPoint(PolyInterpMixin, InterpolatorPoint):
| pass
| (BilinearInterpMixin, InterpolatorGrid):
pass
class PolyInterpGrid(PolyInterpMixin, InterpolatorGrid):
pass
class BilinearInterpPoint(BilinearInterpMixin, InterpolatorPoint):
pass
class PolyInterpPoint(PolyInterpMixin, InterpolatorPoint):
| 64 | 64 | 17 | 14 | 49 | patrick-kidger/CamassaHolmProject | project/base/interpolation.py | Python | PolyInterpPoint | PolyInterpPoint | 248 | 249 | 248 | 248 | 5e0662adc27c186af00b212d7683eb452f55fb66 | bigcode/the-stack | train |
3d0be7b2beb18939548ad0be | train | function | def poly(point, poly_coefs, poly_deg):
"""Interprets the given :poly_coefs: as a polynomial, and
evaluates them at the specified :point:.
The argument :poly_deg: is used to check that poly_coefs
is of a suitable length to be interpreted as polynomial
coefficients.
"""
t, x = point
coef... | def poly(point, poly_coefs, poly_deg):
| """Interprets the given :poly_coefs: as a polynomial, and
evaluates them at the specified :point:.
The argument :poly_deg: is used to check that poly_coefs
is of a suitable length to be interpreted as polynomial
coefficients.
"""
t, x = point
coefs = iter(poly_coefs)
result = next... | t_b_x_b
returnval += t_scale * (1 - x_scale) * t_a_x_b
returnval += (1 - t_scale) * x_scale * t_b_x_a
returnval += t_scale * x_scale * t_a_x_a
return returnval
def poly(point, poly_coefs, poly_deg):
| 74 | 74 | 247 | 11 | 62 | patrick-kidger/CamassaHolmProject | project/base/interpolation.py | Python | poly | poly | 151 | 177 | 151 | 151 | 166646b54d291aa8026d629696ef63dc2bf4d619 | bigcode/the-stack | train |
ff118d770cbf593498d70a68 | train | class | class BilinearInterpMixin(InterpolatorBase):
"""Mixin to help perform bilinear interpolation."""
def _interp(self, Xi, point):
# The actual t, x values for the grid don't matter from this point
# onwards; so this is just a translation from wherever X was actually
# cal... | class BilinearInterpMixin(InterpolatorBase):
| """Mixin to help perform bilinear interpolation."""
def _interp(self, Xi, point):
# The actual t, x values for the grid don't matter from this point
# onwards; so this is just a translation from wherever X was actually
# calculated. So WLOG assume it was around 0.
... | the _prepare and _interp methods provided by one of the mixins
above."""
def predict_single(self, Xi, yi):
# Separate the location data and the grid data
t_offset = Xi[-2]
x_offset = Xi[-1]
Xi = Xi[:-2]
self._prepare(Xi)
# Wrapped in a list for consistency: ... | 137 | 138 | 462 | 9 | 129 | patrick-kidger/CamassaHolmProject | project/base/interpolation.py | Python | BilinearInterpMixin | BilinearInterpMixin | 115 | 148 | 115 | 115 | 23a9e5963db324edafe211229b392a36914653e4 | bigcode/the-stack | train |
ccd7063a4be9376569ce66ad | train | class | class NearestInterpMixin(InterpolatorBase):
"""Mixin to help perform nearest-neighbour interpolation."""
def _interp(self, Xi, point):
# The actual t, x values for the grid don't matter from this point
# onwards; so this is just a translation from wherever X was actually
... | class NearestInterpMixin(InterpolatorBase):
| """Mixin to help perform nearest-neighbour interpolation."""
def _interp(self, Xi, point):
# The actual t, x values for the grid don't matter from this point
# onwards; so this is just a translation from wherever X was actually
# calculated. So WLOG assume it was aroun... | = grid.coarse_grid((0, 0))
poly_pipe.fit(cg, Xi)
self._poly_coefs = poly_pipe.named_steps['lr'].coef_
def _interp(self, Xi, point):
return self.poly(point)
class NearestInterpMixin(InterpolatorBase):
| 63 | 64 | 195 | 9 | 54 | patrick-kidger/CamassaHolmProject | project/base/interpolation.py | Python | NearestInterpMixin | NearestInterpMixin | 216 | 233 | 216 | 216 | 9c6e4ebabb2da695b25218d05b735781cf18c55a | bigcode/the-stack | train |
4d67bc47f1648c9b1f1ed3fa | train | class | class InterpolatorGrid(InterpolatorBase):
"""Provides the predict_single function for predictions on a fine grid.
Requires the _prepare and _interp methods provided by one of the mixins
above."""
def predict_single(self, Xi, yi):
returnval = []
# Translation doesn't matter at t... | class InterpolatorGrid(InterpolatorBase):
| """Provides the predict_single function for predictions on a fine grid.
Requires the _prepare and _interp methods provided by one of the mixins
above."""
def predict_single(self, Xi, yi):
returnval = []
# Translation doesn't matter at this point so WLOG the fine grid is
... | val = []
X, y = input_fn()
for Xi, yi in zip(X, y):
returnval.append(self.predict_single(Xi, yi))
returnval = np.array(returnval)
while True:
yield returnval
class InterpolatorGrid(InterpolatorBase):
| 63 | 64 | 141 | 9 | 53 | patrick-kidger/CamassaHolmProject | project/base/interpolation.py | Python | InterpolatorGrid | InterpolatorGrid | 80 | 94 | 80 | 80 | a5dd486de2af753a422fb2b2ebb75091843b8f31 | bigcode/the-stack | train |
79a6f87f2afa26de994b6fb4 | train | class | class InterpolatorPoint(InterpolatorBase):
"""Provides the predict_single function for predictions at a single point.
Requires the _prepare and _interp methods provided by one of the mixins
above."""
def predict_single(self, Xi, yi):
# Separate the location data and the grid data
... | class InterpolatorPoint(InterpolatorBase):
| """Provides the predict_single function for predictions at a single point.
Requires the _prepare and _interp methods provided by one of the mixins
above."""
def predict_single(self, Xi, yi):
# Separate the location data and the grid data
t_offset = Xi[-2]
x_offset = Xi[... | cls._interp makes the same assumption; these assumptions
# must be consistent)
for point in grid.fine_grid((0, 0)):
self._prepare(Xi)
returnval.append(self._interp(Xi, point))
return returnval
class InterpolatorPoint(InterpolatorBase):
| 64 | 64 | 154 | 9 | 54 | patrick-kidger/CamassaHolmProject | project/base/interpolation.py | Python | InterpolatorPoint | InterpolatorPoint | 97 | 112 | 97 | 97 | 10dbd6c5ebeb61ae2ebc4e043e8b77fad9ff8ee3 | bigcode/the-stack | train |
d78c215e5fad5be29a0b6555 | train | function | def create_folder(path):
if not os.path.isdir(path):
os.makedirs(path)
| def create_folder(path):
| if not os.path.isdir(path):
os.makedirs(path)
| 'wb') as f:
pickle.dump(raw_photos, f)
f.close()
del raw_photos
except:
if verbose:
print('Could not get info for: %s. ' % image_tag)
errors = image_tag
return errors
def create_folder(path):
| 64 | 64 | 18 | 5 | 58 | isaac-chung/insight | scripts/flickr_images_download.py | Python | create_folder | create_folder | 65 | 67 | 65 | 65 | a09569f80663a7bb2d4413abee8e1241f53da989 | bigcode/the-stack | train |
4235122fb9047829f906e17d | train | function | def get_places(path='../places365/IO_places365.txt', verbose=1):
places = pd.read_csv(path, sep=' ', names=['key', 'label'])
# retrieve all outdoor scene categories. We clean up the 'key' column, remove duplicates,
# and re-index the dataframe.
places['key'] = places['key'].str[3:].str.split('/', 1, ex... | def get_places(path='../places365/IO_places365.txt', verbose=1):
| places = pd.read_csv(path, sep=' ', names=['key', 'label'])
# retrieve all outdoor scene categories. We clean up the 'key' column, remove duplicates,
# and re-index the dataframe.
places['key'] = places['key'].str[3:].str.split('/', 1, expand=True)
places = places[places.label == 2]
places = pla... | as outfile:
outfile.write(response.content)
outfile.close()
except:
if verbose:
print('...Error occured at idx: %d' % idx)
if verbose:
print('...download completed.')
def get_places(path='../places365/IO_places365.txt', verbose=1):
| 63 | 64 | 164 | 17 | 46 | isaac-chung/insight | scripts/flickr_images_download.py | Python | get_places | get_places | 94 | 107 | 94 | 95 | bb0cffee409a7420b5c7bc97889bce02ec747389 | bigcode/the-stack | train |
9b09df20508dd75c8492bcb8 | train | function | def run_flickr_download(places, data_folder_path='data', verbose=1):
errors = []
for idx, row in places.iterrows():
# change this idx when it crashes. It will give an error for a few indices.
# It probably means Flickr does not have geotagged images for these keywords.
# We skip over th... | def run_flickr_download(places, data_folder_path='data', verbose=1):
| errors = []
for idx, row in places.iterrows():
# change this idx when it crashes. It will give an error for a few indices.
# It probably means Flickr does not have geotagged images for these keywords.
# We skip over those. Should have a total of 130 keywords at the end.
if idx <... | .strip('\'')
places['key'] = places['key'].replace(to_replace='_', value=' ', regex=True)
if verbose:
print(places.count()) # should have 199
return places
def run_flickr_download(places, data_folder_path='data', verbose=1):
| 64 | 64 | 175 | 18 | 45 | isaac-chung/insight | scripts/flickr_images_download.py | Python | run_flickr_download | run_flickr_download | 110 | 128 | 110 | 110 | 61544da301314a463dcb3f2640ea0f9bdc0a0316 | bigcode/the-stack | train |
205c79f7cd3f2616d1bfb64d | train | function | def download_images(df, keyword, verbose=1):
path = ''.join(['data/', keyword])
create_folder(path)
if verbose:
print('...df length: %d' % len(df.index))
print('...going through each row of dataframe')
for idx, row in df.iterrows():
try:
image_path = ''.join([path, '... | def download_images(df, keyword, verbose=1):
| path = ''.join(['data/', keyword])
create_folder(path)
if verbose:
print('...df length: %d' % len(df.index))
print('...going through each row of dataframe')
for idx, row in df.iterrows():
try:
image_path = ''.join([path, '/', row.id, '.jpg'])
response = r... |
except:
if verbose:
print('Could not get info for: %s. ' % image_tag)
errors = image_tag
return errors
def create_folder(path):
if not os.path.isdir(path):
os.makedirs(path)
def download_images(df, keyword, verbose=1):
| 64 | 64 | 154 | 11 | 53 | isaac-chung/insight | scripts/flickr_images_download.py | Python | download_images | download_images | 70 | 91 | 70 | 70 | 21c08c4e5d6a0914fc94be7166402800d7e8a496 | bigcode/the-stack | train |
0f756664cf36538875097ec5 | train | function | def get_photos(image_tag, path='data', verbose=1):
# setup dataframe for data
raw_photos = pd.DataFrame(columns=['latitude', 'longitude', 'farm', 'server', 'id', 'secret'])
# initialize api
flickr = flickrapi.FlickrAPI(secrets.api_key, secrets.api_secret, format='parsed-json')
errors = ''
try:... | def get_photos(image_tag, path='data', verbose=1):
# setup dataframe for data
| raw_photos = pd.DataFrame(columns=['latitude', 'longitude', 'farm', 'server', 'id', 'secret'])
# initialize api
flickr = flickrapi.FlickrAPI(secrets.api_key, secrets.api_secret, format='parsed-json')
errors = ''
try:
# search photos based on settings
photos = flickr.photos.search(t... | import argparse
from time import time
import secrets
import flickrapi
import requests
import os
import pandas as pd
import pickle
from PIL import Image
def get_photos(image_tag, path='data', verbose=1):
# setup dataframe for data
| 57 | 129 | 431 | 22 | 34 | isaac-chung/insight | scripts/flickr_images_download.py | Python | get_photos | get_photos | 12 | 62 | 12 | 13 | 6f5f95958f289a19609434c1624ace83f71914c4 | bigcode/the-stack | train |
4eeba7b41983d96f81579f45 | train | class | class SynthXYPad(Gtk.EventBox):
def __init__(self, *args, **kwargs):
super(SynthXYPad, self).__init__(*args,**kwargs)
self.adj_x = Gtk.Adjustment(value = 64, lower=0, upper=127, step_increment = 1)
self.adj_y = Gtk.Adjustment(value = 64, lower=0, upper=127, step_increment = 1)
self.... | class SynthXYPad(Gtk.EventBox):
| def __init__(self, *args, **kwargs):
super(SynthXYPad, self).__init__(*args,**kwargs)
self.adj_x = Gtk.Adjustment(value = 64, lower=0, upper=127, step_increment = 1)
self.adj_y = Gtk.Adjustment(value = 64, lower=0, upper=127, step_increment = 1)
self.is_clicked = False
self... | # -*- coding: utf-8 -*-
#
#
#
"""synth_xy_pad.py
standard XY Pad
Todo:
"""
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
import math
###############################################################
class SynthXYPad(Gtk.EventBox):
| 64 | 190 | 635 | 8 | 56 | KiyohitoSUZUKI/gmidisw | midisw/gtk3/synth_xy_pad.py | Python | SynthXYPad | SynthXYPad | 20 | 92 | 20 | 20 | 4cfd16c1d504775a4907d4a7e3d1a662ac5e951b | bigcode/the-stack | train |
85a862aa051db17f696740e8 | train | function | def main():
"""Print the RedBaron syntax tree for a Python module."""
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("path", help="Python module path")
args = parser.parse_args()
r = d1_dev.util.redbaron_... | def main():
| """Print the RedBaron syntax tree for a Python module."""
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("path", help="Python module path")
args = parser.parse_args()
r = d1_dev.util.redbaron_module_path_... | software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import sys
import d1_dev.util
def main():
| 64 | 64 | 85 | 3 | 60 | DataONEorg/d1_python | dev_tools/src/d1_dev/src-print-redbaron-tree.py | Python | main | main | 27 | 36 | 27 | 27 | 5e79b73467c486e7d4532d19ee7f9125514234e0 | bigcode/the-stack | train |
336583b4099b881ff49e2dca | train | class | class CustomClassificationNNCFTestCaseSmall(
create_image_classification_nncf_test_case(
model_name='mobilenet-v3-small',
compression_cmd_line_parameters='--nncf-quantization',
**kwargs,
compression_cfg_update_dict={
'nncf_quantization.train.batch_... | class CustomClassificationNNCFTestCaseSmall(
create_image_classification_nncf_test_case(
model_name='mobilenet-v3-small',
compression_cmd_line_parameters='--nncf-quantization',
**kwargs,
compression_cfg_update_dict={
'nncf_quantization.train.batch_... | """ NNCF test case for mobilenet v3 small model. """
| class CustomClassificationNNCFTestCaseSmall(
create_image_classification_nncf_test_case(
model_name='mobilenet-v3-small',
compression_cmd_line_parameters='--nncf-quantization',
**kwargs,
compression_cfg_update_dict={
'nncf_quantization.train.batch_... | 162 | 64 | 178 | 162 | 0 | a-ignatyev/training_extensions | models/image_classification/tests/nncf_tests_custom_classification.py | Python | CustomClassificationNNCFTestCaseSmall | CustomClassificationNNCFTestCaseSmall | 26 | 44 | 26 | 43 | a1abec53c7ccf6db6ff722505156de84cdf2b7fa | bigcode/the-stack | train |
35d922e62d83a2a7d778c5fc | train | function | def before_all(context):
root = context.config.userdata.get("root", "./")
"""Set up flask app and blueprints"""
database_uri = ":memory:"
attacks_folder = root + "attacks"
planners_folder = root + "planners"
cme_timezone = "Europe/Madrid"
configure_engine(database_uri, attacks_folder, plan... | def before_all(context):
| root = context.config.userdata.get("root", "./")
"""Set up flask app and blueprints"""
database_uri = ":memory:"
attacks_folder = root + "attacks"
planners_folder = root + "planners"
cme_timezone = "Europe/Madrid"
configure_engine(database_uri, attacks_folder, planners_folder, cme_timezone... | from chaosmonkey.engine.cme_manager import manager as cme_manager
from chaosmonkey.engine.app import configure_engine
from chaosmonkey.dal.executor_model import Executor
from chaosmonkey.dal.plan_model import Plan
from chaosmonkey.api.app import flask_app
def before_all(context):
| 62 | 64 | 159 | 5 | 56 | BBVA/chaos-monkey-engine | test/acceptance/environment.py | Python | before_all | before_all | 8 | 29 | 8 | 8 | 80a7cf306c1599bef136de904c4bbb994beba559 | bigcode/the-stack | train |
b5b958b12b190886df56d6a6 | train | function | def after_scenario(context, scenario):
Plan.query.delete()
Executor.query.delete()
context.manager.planners_store.set_modules([])
context.manager.attacks_store.set_modules([])
context.manager.scheduler.remove_all_jobs()
| def after_scenario(context, scenario):
| Plan.query.delete()
Executor.query.delete()
context.manager.planners_store.set_modules([])
context.manager.attacks_store.set_modules([])
context.manager.scheduler.remove_all_jobs()
| _manager.scheduler.resume()
# Empty the module stores
cme_manager.attacks_store.set_modules([])
cme_manager.planners_store.set_modules([])
context.app = flask_app
context.client = flask_app.test_client()
context.manager = cme_manager
def after_scenario(context, scenario):
| 64 | 64 | 44 | 8 | 55 | BBVA/chaos-monkey-engine | test/acceptance/environment.py | Python | after_scenario | after_scenario | 32 | 37 | 32 | 32 | ef23cce5c85e44cc61c8567e6cef5af5689bc8d8 | bigcode/the-stack | train |
53bb41248048d456db3e2538 | train | class | class Collector(object):
def __init__(self, workload_type, delete_files=False, test_mode=None, collection_frequency=1):
# often used as the "tool_instance" property of analysis
self.fqdn = socket.getfqdn()
# the type of work this collector collects
# this maps to incoming_workload_t... | class Collector(object):
| def __init__(self, workload_type, delete_files=False, test_mode=None, collection_frequency=1):
# often used as the "tool_instance" property of analysis
self.fqdn = socket.getfqdn()
# the type of work this collector collects
# this maps to incoming_workload_type.name in the database
... | status = 'ERROR'
WHERE group_id = %s AND work_id = %s""",
(self.group_id, work_id), commit=True)
# if we skipped it or we sent it, then we're done with it
if not submission_failed:
... | 256 | 256 | 2,671 | 4 | 252 | KarmaPenny/ACE | lib/saq/collectors/__init__.py | Python | Collector | Collector | 483 | 808 | 483 | 483 | 1c3a28117d7897496a5c2b02741af41471e29349 | bigcode/the-stack | train |
48eec4a7e8de4bc1d2db7b05 | train | class | class RemoteNodeGroup(object):
"""Represents a collection of one or more RemoteNode objects that share the
same group configuration property."""
def __init__(self, name, coverage, full_delivery, company_id, database, group_id, workload_type_id, shutdown_event, batch_size=32):
assert isinstance(n... | class RemoteNodeGroup(object):
| """Represents a collection of one or more RemoteNode objects that share the
same group configuration property."""
def __init__(self, name, coverage, full_delivery, company_id, database, group_id, workload_type_id, shutdown_event, batch_size=32):
assert isinstance(name, str) and name
asse... | , submission.uuid, os.path.basename(f)), 'rb')))
#files = [ (os.path.basename(f), open(os.path.join(self.incoming_dir, submission.uuid, os.path.basename(f)), 'rb')) for f in submission.files]
result = ace_api.submit(
submission.description,
remote_host=self.location,
... | 256 | 256 | 2,747 | 6 | 249 | KarmaPenny/ACE | lib/saq/collectors/__init__.py | Python | RemoteNodeGroup | RemoteNodeGroup | 155 | 481 | 155 | 155 | 0b0c020bb303250483b8e6e0ecc87c5e4cfa1c85 | bigcode/the-stack | train |
65f482a1c9ffb5195ecaca70 | train | class | class RemoteNode(object):
def __init__(self, id, name, location, any_mode, last_update, analysis_mode, workload_count):
self.id = id
self.name = name
self.location = location
self.any_mode = any_mode
self.last_update = last_update
self.analysis_mode = analysis_mode
... | class RemoteNode(object):
| def __init__(self, id, name, location, any_mode, last_update, analysis_mode, workload_count):
self.id = id
self.name = name
self.location = location
self.any_mode = any_mode
self.last_update = last_update
self.analysis_mode = analysis_mode
self.workload_count ... |
self.event_time = event_time
self.details = details
self.observables = observables
self.tags = tags
self.files = files
self.uuid = str(uuid.uuid4())
# list of RemoteNodeGroup.name values
# empty list means send to all configured groups
self.group... | 180 | 180 | 601 | 5 | 174 | KarmaPenny/ACE | lib/saq/collectors/__init__.py | Python | RemoteNode | RemoteNode | 89 | 153 | 89 | 89 | b1e7e6ade8e9ee42b739f1c03ddad0b6904d1039 | bigcode/the-stack | train |
6a77724ad9733265083428ff | train | class | class Submission(object):
"""A single analysis submission.
Keep in mind that this object gets serialized into a database blob via the pickle module.
NOTE - The files parameter MUST be either a list of file names or a list of tuples of (source, dest)
NOT file descriptors."""
# this i... | class Submission(object):
| """A single analysis submission.
Keep in mind that this object gets serialized into a database blob via the pickle module.
NOTE - The files parameter MUST be either a list of file names or a list of tuples of (source, dest)
NOT file descriptors."""
# this is basically just all the a... | get_db_connection, \
enable_cached_db_connections, \
disable_cached_db_connections
from saq.error import report_exception
import urllib3.exceptions
import requests.exceptions
# some constants used as return values
WORK_SUBMITTED = 1
NO_WORK_AVAILABLE = 2
NO_NODES_AV... | 99 | 99 | 332 | 4 | 95 | KarmaPenny/ACE | lib/saq/collectors/__init__.py | Python | Submission | Submission | 40 | 87 | 40 | 40 | 6b2c150b40f01dc9cc685fff74522a5b159ee171 | bigcode/the-stack | train |
baa5007363ffa39ffeedabef | train | class | class AlipayCommerceEducateCampusInstitutionsAddRequest(object):
def __init__(self, biz_model=None):
self._biz_model = biz_model
self._biz_content = None
self._version = "1.0"
self._terminal_type = None
self._terminal_info = None
self._prod_code = None
self._... | class AlipayCommerceEducateCampusInstitutionsAddRequest(object):
| def __init__(self, biz_model=None):
self._biz_model = biz_model
self._biz_content = None
self._version = "1.0"
self._terminal_type = None
self._terminal_info = None
self._prod_code = None
self._notify_url = None
self._return_url = None
self._ud... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.AlipayCommerceEducateCampusInstitutionsAddModel import AlipayCommerceEducateCampusInstitutionsAddModel
class AlipayCommerceEducateCampu... | 82 | 256 | 855 | 13 | 68 | antopen/alipay-sdk-python-all | alipay/aop/api/request/AlipayCommerceEducateCampusInstitutionsAddRequest.py | Python | AlipayCommerceEducateCampusInstitutionsAddRequest | AlipayCommerceEducateCampusInstitutionsAddRequest | 12 | 144 | 12 | 13 | b3c09b01afc95708a6aae1a8e3e7aea36b733111 | bigcode/the-stack | train |
a2c5e2364503f521d006ab06 | train | function | def EBIC(emp_cov, precision, n=100, epsilon=0.5):
"""E - Bayesian Information Criterion for Gaussian models.
It penalizes more then BIC by multplying the degrees of freedom also based
on sample size.
"""
likelihood = log_likelihood(emp_cov, precision)
of_nonzero = np.sum(precision != 0) - prec... | def EBIC(emp_cov, precision, n=100, epsilon=0.5):
| """E - Bayesian Information Criterion for Gaussian models.
It penalizes more then BIC by multplying the degrees of freedom also based
on sample size.
"""
likelihood = log_likelihood(emp_cov, precision)
of_nonzero = np.sum(precision != 0) - precision.shape[0]
penalty = np.log(n) / n * of_no... | precision)
def BIC(emp_cov, precision):
"""Bayesian Information Criterion for Gaussian models"""
return log_likelihood(emp_cov, precision) - (np.sum(precision != 0) - precision.shape[0])
def EBIC(emp_cov, precision, n=100, epsilon=0.5):
| 64 | 64 | 125 | 18 | 46 | fdtomasi/rgi | regain/scores.py | Python | EBIC | EBIC | 45 | 55 | 45 | 45 | b29a976b575acc5a60966950936287d9ec8d4b56 | bigcode/the-stack | train |
50fe9dba73701e463600b3da | train | function | def EBIC_m(emp_cov, precision, n=100, epsilon=0.5):
"""E - Bayesian Information Criterion for Gaussian models.
It penalizes more then BIC and E-BIC by multplying the degrees of freedom
based on sample size and the number of variables.
"""
likelihood = log_likelihood(emp_cov, precision)
of_nonze... | def EBIC_m(emp_cov, precision, n=100, epsilon=0.5):
| """E - Bayesian Information Criterion for Gaussian models.
It penalizes more then BIC and E-BIC by multplying the degrees of freedom
based on sample size and the number of variables.
"""
likelihood = log_likelihood(emp_cov, precision)
of_nonzero = np.sum(precision != 0) - precision.shape[0]
... | precision.shape[0]
penalty = np.log(n) / n * of_nonzero + 4 * epsilon * np.log(precision.shape[0]) / n * of_nonzero
return likelihood - penalty
def EBIC_m(emp_cov, precision, n=100, epsilon=0.5):
| 64 | 64 | 148 | 19 | 44 | fdtomasi/rgi | regain/scores.py | Python | EBIC_m | EBIC_m | 58 | 68 | 58 | 58 | d0668a0e3e797bbd84094c7297a5019b71ae956c | bigcode/the-stack | train |
ddc28f88c349fbcb5c00decf | train | function | def log_likelihood_t(emp_cov, precision):
"""Gaussian log-likelihood without constant term in time"""
score = 0
for e, p in zip(emp_cov, precision):
score += fast_logdet(p) - np.sum(e * p)
return score
| def log_likelihood_t(emp_cov, precision):
| """Gaussian log-likelihood without constant term in time"""
score = 0
for e, p in zip(emp_cov, precision):
score += fast_logdet(p) - np.sum(e * p)
return score
| p = precision.shape[0]
penalty = np.log(n) / n * of_nonzero + 4 * epsilon * np.log(p * (p - 1) / 2) / n * of_nonzero
return likelihood - penalty
def log_likelihood_t(emp_cov, precision):
| 64 | 64 | 59 | 10 | 53 | fdtomasi/rgi | regain/scores.py | Python | log_likelihood_t | log_likelihood_t | 71 | 76 | 71 | 71 | c9f78114a885103624c0927c5ec42ab72e2d50b7 | bigcode/the-stack | train |
0e5fadc999978d5ca35f6846 | train | function | def BIC(emp_cov, precision):
"""Bayesian Information Criterion for Gaussian models"""
return log_likelihood(emp_cov, precision) - (np.sum(precision != 0) - precision.shape[0])
| def BIC(emp_cov, precision):
| """Bayesian Information Criterion for Gaussian models"""
return log_likelihood(emp_cov, precision) - (np.sum(precision != 0) - precision.shape[0])
| THE POSSIBILITY OF SUCH DAMAGE.
import numpy as np
from sklearn.utils.extmath import fast_logdet
def log_likelihood(emp_cov, precision):
"""Gaussian log-likelihood without constant term."""
return fast_logdet(precision) - np.sum(emp_cov * precision)
def BIC(emp_cov, precision):
| 64 | 64 | 44 | 8 | 56 | fdtomasi/rgi | regain/scores.py | Python | BIC | BIC | 40 | 42 | 40 | 40 | f4af86e8acbd737d6ea8a6e1e342a87a17264558 | bigcode/the-stack | train |
86bd88967a0cce87b707f91e | train | function | def EBIC_t(emp_cov, precision, n=100, epsilon=0.5):
"""E - Bayesian Information Criterion for Gaussian models in time.
It penalizes more then BIC by multplying the degrees of freedom also based
on sample size.
"""
likelihood = log_likelihood_t(emp_cov, precision)
n_variables = precision.shape[1... | def EBIC_t(emp_cov, precision, n=100, epsilon=0.5):
| """E - Bayesian Information Criterion for Gaussian models in time.
It penalizes more then BIC by multplying the degrees of freedom also based
on sample size.
"""
likelihood = log_likelihood_t(emp_cov, precision)
n_variables = precision.shape[1] * precision.shape[0]
of_nonzero = np.sum(preci... | models in time."""
precision = np.array(precision)
return log_likelihood_t(emp_cov, precision) - (np.sum(precision != 0) - precision.shape[1] * precision.shape[0])
def EBIC_t(emp_cov, precision, n=100, epsilon=0.5):
| 64 | 64 | 139 | 19 | 45 | fdtomasi/rgi | regain/scores.py | Python | EBIC_t | EBIC_t | 86 | 96 | 86 | 86 | 95b808792413e6e5756b73ff61c888bc5b892a79 | bigcode/the-stack | train |
773274f601410a934166056a | train | function | def BIC_t(emp_cov, precision):
"""Bayesian Information Criterion for Gaussian models in time."""
precision = np.array(precision)
return log_likelihood_t(emp_cov, precision) - (np.sum(precision != 0) - precision.shape[1] * precision.shape[0])
| def BIC_t(emp_cov, precision):
| """Bayesian Information Criterion for Gaussian models in time."""
precision = np.array(precision)
return log_likelihood_t(emp_cov, precision) - (np.sum(precision != 0) - precision.shape[1] * precision.shape[0])
| _t(emp_cov, precision):
"""Gaussian log-likelihood without constant term in time"""
score = 0
for e, p in zip(emp_cov, precision):
score += fast_logdet(p) - np.sum(e * p)
return score
def BIC_t(emp_cov, precision):
| 64 | 64 | 62 | 9 | 54 | fdtomasi/rgi | regain/scores.py | Python | BIC_t | BIC_t | 79 | 83 | 79 | 79 | aedf9f5e6e04344485062fd04aeccec2de379b8d | bigcode/the-stack | train |
2ec6d81e814873aa28391d4e | train | function | def EBIC_m_t(emp_cov, precision, n=100, epsilon=0.5):
"""E - Bayesian Information Criterion for Gaussian models in time.
It penalizes more then BIC and E-BIC by multplying the degrees of freedom
based on sample size and the number of variables.
"""
likelihood = log_likelihood_t(emp_cov, precision)
... | def EBIC_m_t(emp_cov, precision, n=100, epsilon=0.5):
| """E - Bayesian Information Criterion for Gaussian models in time.
It penalizes more then BIC and E-BIC by multplying the degrees of freedom
based on sample size and the number of variables.
"""
likelihood = log_likelihood_t(emp_cov, precision)
n_variables = precision.shape[1] * precision.shape... | 0) - n_variables
penalty = np.log(n) / n * of_nonzero + 4 * epsilon * np.log(n_variables) / n * of_nonzero
return likelihood - penalty
def EBIC_m_t(emp_cov, precision, n=100, epsilon=0.5):
| 64 | 64 | 159 | 20 | 43 | fdtomasi/rgi | regain/scores.py | Python | EBIC_m_t | EBIC_m_t | 99 | 109 | 99 | 99 | e5717a67e124d067925c6ce87bcb89fd28a11071 | bigcode/the-stack | train |
675bb2505d2aa440b0feac9e | train | function | def log_likelihood(emp_cov, precision):
"""Gaussian log-likelihood without constant term."""
return fast_logdet(precision) - np.sum(emp_cov * precision)
| def log_likelihood(emp_cov, precision):
| """Gaussian log-likelihood without constant term."""
return fast_logdet(precision) - np.sum(emp_cov * precision)
| WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import numpy as np
from sklearn.utils.extmath import fast_logdet
def log_likelihood(emp_cov, precision):
| 64 | 64 | 35 | 9 | 54 | fdtomasi/rgi | regain/scores.py | Python | log_likelihood | log_likelihood | 35 | 37 | 35 | 35 | 14d52aeaa289d1457246f08b092769b83c3f4e5f | bigcode/the-stack | train |
5e03ebd46d6ecc1c74a0c913 | train | class | class EntityValues:
"""Class to store entity id based values."""
def __init__(
self,
exact: Optional[Dict] = None,
domain: Optional[Dict] = None,
glob: Optional[Dict] = None,
) -> None:
"""Initialize an EntityConfigDict."""
self._cache: Dict[str, Dict] = {}
... | class EntityValues:
| """Class to store entity id based values."""
def __init__(
self,
exact: Optional[Dict] = None,
domain: Optional[Dict] = None,
glob: Optional[Dict] = None,
) -> None:
"""Initialize an EntityConfigDict."""
self._cache: Dict[str, Dict] = {}
self._exact =... | """A class to hold entity values."""
from collections import OrderedDict
import fnmatch
import re
from typing import Any, Dict, Optional, Pattern
from homeassistant.core import split_entity_id
class EntityValues:
| 45 | 90 | 300 | 4 | 40 | domwillcode/home-assistant | homeassistant/helpers/entity_values.py | Python | EntityValues | EntityValues | 10 | 52 | 10 | 10 | a02c6f5a54652797c447fb09aac5aa7c84a102c9 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.