code stringlengths 281 23.7M |
|---|
def test_collect_json_stdout(collect, capsys):
cli.cmdline(['collect', 'logic_analyzer', '--channels', str(LA_CHANNELS), '--json'])
output = json.loads(capsys.readouterr().out)
assert (len(output) == LA_CHANNELS)
assert (len(list(output.values())[0]) == EVENTS)
cli.cmdline(['collect', 'oscilloscope'... |
class OptionPlotoptionsLineSonificationTracksMappingPan(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
self._co... |
class TestLabgraphGraphvizAPI(unittest.TestCase):
def setUp(self) -> None:
self.graph: lg.Graph = Demo()
def test_identify_graph_nodes(self) -> None:
nodes = identify_graph_nodes(self.graph)
expected_node_count = 7
self.assertEqual(expected_node_count, len(nodes))
def test_ou... |
class TestExpandArrayPathsToPreserve():
def test_no_array_paths(self):
expanded_field_paths = [['A', 'B'], ['A', 'C'], ['A', 'D', 'E', 'F'], ['A', 'G', 'E', 'I']]
assert (_expand_array_paths_to_preserve(expanded_field_paths) == {})
def test_array_at_deepest_level(self):
expanded_field_pa... |
class ArtistSortPopupController(OptionsController):
def __init__(self, plugin, viewmgr):
super(ArtistSortPopupController, self).__init__()
self._viewmgr = viewmgr
self.plugin = plugin
cl = CoverLocale()
cl.switch_locale(cl.Locale.LOCALE_DOMAIN)
self.values = OrderedDi... |
def test_repr_property_is_working_properly(create_ref_test_data, create_maya_env):
data = create_ref_test_data
maya_env = create_maya_env
maya_env.save_as(data['asset2_model_take1_v001'])
ref = maya_env.reference(data['repr_version1'])
assert (ref.path == data['repr_version1'].absolute_full_path)
... |
def value_at_risk(investment: NUMERIC, mu: FLOAT, sigma: FLOAT, conf_level: FLOAT=0.95) -> FLOAT:
type_validation(investment=investment, mu=mu, sigma=sigma, conf_level=conf_level)
if ((conf_level >= 1) or (conf_level <= 0)):
raise ValueError('confidence level is expected to be between 0 and 1.')
res... |
def main(args=None):
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-s', '--suffix', required=True)
parser.add_argument('input_fonts', metavar='FONTFILE', nargs='+')
output_group = parser.add_mutually_exclusive_group()
... |
class SymbolHandler(Handler):
def __init__(self, lifter: ObserverLifter):
super().__init__(lifter)
self.SYMBOL_MAP = {SymbolType.FunctionSymbol: FunctionSymbol, SymbolType.ImportAddressSymbol: ImportedFunctionSymbol, SymbolType.ImportedFunctionSymbol: ImportedFunctionSymbol, SymbolType.DataSymbol: S... |
def extract_file_level_comments(message_string):
lines = message_string.splitlines()
index = next((i for (i, v) in enumerate(lines) if (not v.startswith(COMMENT_DELIMITER))), (- 1))
if (index != (- 1)):
file_level_comments = lines[:index]
file_content = lines[index:]
else:
file_l... |
def parse_FMT35C(buffer, dex_object, pc_point, offset):
A = (int(buffer[1]) >> 4)
G = (int(buffer[1]) & 15)
D = (int(buffer[4]) >> 4)
C = (int(buffer[4]) & 15)
F = (int(buffer[5]) >> 4)
E = (int(buffer[5]) & 15)
(bbbb,) = struct.unpack_from('H', buffer, 2)
if (int(buffer[0]) == 36):
... |
class CovarianceModule(nn.Module):
def __init__(self, iso_cov_fn, scale_param, scale_prior):
super().__init__()
self.iso_cov_fn = iso_cov_fn
self.scale_param = scale_param
self.scale_prior = scale_prior
def get_scale(self):
return (self.scale_prior * torch.exp(self.scale_... |
class Features():
def __init__(self):
self.nonempty_generators = set()
def run_func(self, func_name, *args):
func = getattr(self, func_name, None)
if (not func):
print("Error: Not a function name that's been defined")
return False
results = func(*args)
... |
()
('name', required=True)
('--admin/--no-admin', default=False)
('--proven/--no-proven', default=False)
def alter_user(name, admin, proven):
user = models.User.query.filter((models.User.username == name)).first()
if (not user):
print('No user named {0}.'.format(name))
return
user.admin = ad... |
(scope='session', autouse=True)
def _standard_os_environ():
mp = monkeypatch.MonkeyPatch()
out = ((os.environ, 'FLASK_APP', monkeypatch.notset), (os.environ, 'FLASK_ENV', monkeypatch.notset), (os.environ, 'FLASK_DEBUG', monkeypatch.notset), (os.environ, 'FLASK_RUN_FROM_CLI', monkeypatch.notset), (os.environ, 'W... |
def installdeps(modulename):
if (len(Settings.UpdateString) > 0):
if (Settings.UpdateString[0] == '!'):
misc.addLog(rpieGlobals.LOG_LEVEL_INFO, 'Update already in progress!')
return False
t = threading.Thread(target=installdeps2, args=(modulename,))
t.daemon = True
t.star... |
def build_diagnositic_cifti_files(tmean_vol, cov_vol, goodvoxels_vol, settings, meshes):
logger.info(section_header('Writing Surface Mapping Diagnotic Files'))
for Hemisphere in ['L', 'R']:
for map_name in ['mean', 'cov']:
if (map_name == 'mean'):
map_vol = tmean_vol
... |
def test_hostaliases():
config = '\ndeployment:\n enabled: true\ndaemonset:\n hostAliases:\n - ip: "127.0.0.1"\n hostnames:\n - "foo.local"\n - "bar.local"\n'
r = helm_template(config)
assert ('hostAliases' not in r['deployment'][name]['spec']['template']['spec'])
hostAliases = r['daemonset'... |
class OptionsPadding(Options):
def top(self):
return self._config_get(None)
def top(self, num):
self._config(num)
def left(self):
return self._config_get(None)
def left(self, num):
self._config(num)
def right(self):
return self._config_get(None)
def right(... |
def getPageRow(url, ignore_cache=False, session=None):
page = RemoteContentObject(url, db_session=session)
print('Page object: ', page)
try:
print('doing fetch: ')
page.fetch(ignore_cache=ignore_cache)
print('Fetched. Yielding')
(yield page)
except DownloadException:
... |
class TelemetryExtensionType(object):
swagger_types = {}
attribute_map = {}
def __init__(self):
self.discriminator = None
def to_dict(self):
result = {}
for (attr, _) in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, li... |
def stop_web(signum, frame):
global sub_process
if sub_process:
try:
sub_process.terminate()
except Exception as e:
logging.error('Fail to terminate process pid: {}, killing the process with SIGKILL'.format(sub_process.pid), exc_info=e)
finally:
sub_pr... |
class Chart(MixHtmlState.HtmlOverlayStates, Html.Html):
name = 'ChartList'
tag = 'div'
_option_cls = OptChartist.OptionsChartistLine
requirements = ('chartist',)
builder_name = 'EkChartist'
_chart__type = 'Line'
def __init__(self, page: primitives.PageModel, width, height, html_code, options... |
def find_thread_by_board_name_thread_refno(board_name: str, thread_refno: int) -> Optional[ThreadModel]:
thread_cache = cache.get(cache_key('thread', board_name, thread_refno))
if (not thread_cache):
with session() as s:
q = s.query(ThreadOrmModel)
q = q.filter((ThreadOrmModel.re... |
class AppServiceStreamlitTokenProvider(AbstractTokenProvider):
config_name = 'streamlit'
def get_token(self) -> 'str | None':
try:
return self.get_streamlit_request_headers()[APP_SERVICE_ACCESS_TOKEN_HEADER]
except (ImportError, KeyError, RuntimeError, ModuleNotFoundError, TypeError)... |
def attribute_around_constant_cube_slices():
cubefile = (EXPATH1 / 'ib_test_cube2.segy')
level1 = 1010
level2 = 1100
mycube = xtgeo.cube_from_file(cubefile)
sabove = xtgeo.surface_from_cube(mycube, level1)
sbelow = xtgeo.surface_from_cube(mycube, level2)
if DEBUG:
sabove.describe()
... |
_chunk_type
class chunk_data(chunk):
_PACK_STR = '!BBHIHHI'
_MIN_LEN = struct.calcsize(_PACK_STR)
def chunk_type(cls):
return TYPE_DATA
def __init__(self, unordered=0, begin=0, end=0, length=0, tsn=0, sid=0, seq=0, payload_id=0, payload_data=None):
assert (1 == (unordered | 1))
a... |
class _SphereItem(QGraphicsEllipseItem, _ActionDelegator):
def __init__(self, node):
self.node = node
d = node.img_style['size']
r = (d / 2.0)
QGraphicsEllipseItem.__init__(self, 0, 0, d, d)
_ActionDelegator.__init__(self)
self.setPen(QPen(QColor(self.node.img_style['... |
class TestValidateDatasetField():
def test_return_all_elements_not_string_field(self):
with pytest.raises(ValidationError):
DatasetField(name='test_field', fides_meta=FidesMeta(references=None, identity='identifiable_field_name', primary_key=False, data_type='string', length=None, return_all_ele... |
class ServiceResponse(ModelComposed):
allowed_values = {('type',): {'VCL': 'vcl', 'WASM': 'wasm'}}
validations = {}
_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def ... |
_required
def calendar(request, location_slug):
location = get_object_or_404(Location, slug=location_slug)
today = timezone.localtime(timezone.now())
month = request.GET.get('month')
year = request.GET.get('year')
(start, end, next_month, prev_month, month, year) = get_calendar_dates(month, year)
... |
def extractKrullscansCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) in tagm... |
class ValidatorsTests(TestCase):
def test_qs_exists_handles_type_error(self):
class TypeErrorQueryset():
def exists(self):
raise TypeError
assert (qs_exists(TypeErrorQueryset()) is False)
def test_qs_exists_handles_value_error(self):
class ValueErrorQueryset()... |
class CanAccessForum(Requirement):
def fulfill(self, user):
if (not current_forum):
raise FlaskBBError('Could not load forum data')
forum_groups = {g.id for g in current_forum.groups}
user_groups = {g.id for g in user.groups}
return bool((forum_groups & user_groups)) |
.parametrize('cell, degree', [(c, d) for c in (ReferenceInterval, ReferenceTriangle) for d in range(8)])
def test_tabulate_matrix_size(cell, degree):
fe = LagrangeElement(cell, 2)
points = np.ones((4, cell.dim))
shape = fe.tabulate(points).shape
correct_shape = (4, fe.nodes.shape[0])
assert (shape =... |
(help='Generates <airflow-dag-id>_diagrams.py in <output-path> directory which contains the definition to create a diagram. Run this file and you will get a rendered diagram.')
def generate(dag_id: Optional[str]=Option(None, '--airflow-dag-id', '-d', help='The dag id from which to generate the diagram. By default it ge... |
class ProductFeedUploadErrorSample(AbstractCrudObject):
def __init__(self, fbid=None, parent_id=None, api=None):
self._isProductFeedUploadErrorSample = True
super(ProductFeedUploadErrorSample, self).__init__(fbid, parent_id, api)
class Field(AbstractObject.Field):
id = 'id'
retai... |
def extractSteambunlightnovelCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [("tang yin's adventure in another world", "Tang Yin's Adventure In Another World", 'translated'),... |
def _dp_parser_v2(dps_conf, acls_conf, meters_conf, routers_conf, vlans_conf, meta_dp_state):
dp_vlans = []
for (dp_key, dp_conf) in dps_conf.items():
try:
(dp, vlans) = _parse_dp(dp_key, dp_conf, acls_conf, meters_conf, routers_conf, vlans_conf)
dp_vlans.append((dp, vlans))
... |
def clip_channels(color: 'Color', nans: bool=True) -> None:
for (i, value) in enumerate(color[:(- 1)]):
chan = color._space.CHANNELS[i]
if (chan.flags & FLG_ANGLE):
color[i] = util.constrain_hue(value)
continue
if ((not chan.bound) or math.isnan(value)):
c... |
class GPProject(ManageMembersMixin, Archivable, Document):
on_delete_cascade = ['GP Task', 'GP Discussion', 'GP Project Visit', 'GP Followed Project', 'GP Page', 'GP Pinned Project']
on_delete_set_null = ['GP Notification']
def get_list_query(query):
Project = frappe.qb.DocType('GP Project')
... |
def populate_userdir(fargs):
predefined_locations = ['www', 'secure-www']
(userdir, checkmodes) = fargs
locations = []
try:
userdir = os.path.abspath(userdir)
if (not validate_directory(userdir, checkmodes)):
return locations
public_html_location = (userdir + '/public... |
def extractAshenfeatherWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Sweet Curse! Battle-Android summoned to a Different world!', 'Sweet Curse! Battle-Android su... |
class TestDefaultFlaskBBAuthProvider(object):
provider = auth.DefaultFlaskBBAuthProvider()
def test_returns_None_if_user_doesnt_exist(self, Fred):
result = self.provider.authenticate('', 'lolnope')
assert (result is None)
def test_returns_None_if_password_doesnt_match(self, Fred):
re... |
def test_document_inheritance():
assert issubclass(MySubDoc, MyDoc)
assert issubclass(MySubDoc, document.Document)
assert hasattr(MySubDoc, '_doc_type')
assert ({'properties': {'created_at': {'type': 'date'}, 'name': {'type': 'keyword'}, 'title': {'type': 'keyword'}, 'inner': {'type': 'object', 'propert... |
class Task():
def set_run_index(self, index_provider: DynamicIndexProvider) -> None:
self._run_index = index_provider.next()
def run_index(self) -> int:
run_index = getattr(self, '_run_index', None)
assert (run_index is not None)
return run_index
def execute(self, args: argpa... |
.parametrize('middleware', [MiddlewareIncompatibleWithWSGI_A(), MiddlewareIncompatibleWithWSGI_B(), MiddlewareIncompatibleWithWSGI_C(), (MiddlewareIncompatibleWithWSGI_C(), MiddlewareIncompatibleWithWSGI_A())])
def test_raise_on_incompatible(middleware):
api = falcon.App()
with pytest.raises(falcon.Compatibilit... |
class InSet(Expression):
__slots__ = ('expression', 'container')
precedence = Comparison.precedence
def __init__(self, expression, container):
self.expression = expression
self.container = container
def is_literal(self):
return all((isinstance(v, Literal) for v in self.container)... |
class OptionPlotoptionsScatter3dDatalabels(Options):
def align(self):
return self._config_get('center')
def align(self, text: str):
self._config(text, js_type=False)
def allowOverlap(self):
return self._config_get(False)
def allowOverlap(self, flag: bool):
self._config(fl... |
def _get_solc_version_list() -> Tuple[(List, List)]:
global AVAILABLE_SOLC_VERSIONS
installed_versions = solcx.get_installed_solc_versions()
if (AVAILABLE_SOLC_VERSIONS is None):
try:
AVAILABLE_SOLC_VERSIONS = solcx.get_installable_solc_versions()
except ConnectionError:
... |
class SizeAssessmentTests(unittest.TestCase):
def test_matrix_mult(self):
bmg = BMGraphBuilder()
assessor = SizeAssessment(Sizer())
probs = bmg.add_real_matrix(torch.tensor([[0.5, 0.125, 0.125], [0.0625, 0.0625, 0.875]]))
tensor_elements = []
for row in range(0, 2):
... |
class IFrame(Widget):
DEFAULT_MIN_SIZE = (10, 10)
CSS = '\n .flx-IFrame {\n border: none;\n }\n '
url = event.StringProp('', settable=True, doc="\n The url to show. ' is automatically prepended if the url\n does not have '://' in it.\n ")
def _create_dom(... |
def select():
print(' Select which piece to move.')
selecting = True
while selecting:
col = utils.r_c('c')
row = utils.r_c('r')
if (board.Grid(row, col).piece.color != globVar.player):
Canvas.selectError()
else:
board.Grid(row, col).piece.selected = Tr... |
def test_cube_slice_w_ignore_dead_traces_trilinear(tmpdir, generate_plot):
cube1 = xtgeo.cube_from_file(XCUB2)
surf1 = xtgeo.surface_from_cube(cube1, 1000.0)
cells = [(18, 12), (20, 2), (0, 4)]
surf1.slice_cube(cube1, sampling='trilinear', snapxy=True, deadtraces=False)
if generate_plot:
plo... |
class VarGraph(BaseGraph):
var_resolver = VarResolver()
def __init__(self, cls_fields_list: List[Tuple[(_C, Dict)]], input_classes: List):
self._cls_fields_tuple = cls_fields_list
self._input_classes = input_classes
(tmp_dag, self.ref_map) = self._build()
super().__init__(tmp_dag... |
class TestClosestValue():
.parametrize(('input_value', 'expected_value'), [[0.5, 0.6], [0, 0.2], [0.522, 0.6], [1.15, 1], [0.8, 0.8]])
def test_above_value(self, input_value, expected_value):
v = closest_above_value([0.2, 0.4, 0.6, 0.8, 1], input_value)
assert (v == expected_value)
.parametr... |
def create_local_queue(executable_script: str, max_submit: int=1, num_realizations: int=10, max_runtime: Optional[int]=None, callback_timeout: Optional['Callable[[int], None]']=None, *, ens_id: Optional[str]=None, ee_uri: Optional[str]=None, ee_cert: Optional[str]=None, ee_token: Optional[str]=None):
job_queue = Jo... |
def test_triplot_3d():
fig = plt.figure()
axes = fig.add_subplot(2, 2, 1, projection='3d')
mesh = CylinderMesh(nr=32, nl=4)
collections = triplot(mesh, axes=axes, boundary_kw={'colors': ['r', 'g']})
assert collections
legend = axes.legend()
assert (len(legend.get_texts()) == 2)
axes = fi... |
class SetCommandResponder(CommandResponderBase):
SUPPORTED_PDU_TYPES = (rfc1905.SetRequestPDU.tagSet,)
SMI_ERROR_MAP = CommandResponderBase.SMI_ERROR_MAP.copy()
SMI_ERROR_MAP[pysnmp.smi.error.NoSuchObjectError] = 'notWritable'
SMI_ERROR_MAP[pysnmp.smi.error.NoSuchInstanceError] = 'notWritable'
def _... |
class JsHtmlTree(JsHtml.JsHtmlRich):
def hide(self, i: int=None):
if (i is not None):
return JsObjects.JsVoid(('\nlet treeItem = document.querySelectorAll("#%(htmlCode)s i[name=item_arrow]")[%(index)s];\nif (treeItem.getAttribute("class") == "%(iconOpen)s"){dom.click();}\n' % {'htmlCode': self.c... |
class HistoricalPriceRecord(collections.namedtuple('HistoricalPriceRecord', ['time', 'open', 'high', 'low', 'close', 'volume'])):
__slots__ = ()
_krx_timezone = get_calendar('XKRX').tz
def from_tuple(cls, tup):
if ('' in tup._fields):
dt = datetime.datetime.strptime(tup., '%Y%m%d')
... |
def rectify(self, context, me=None, bm=None, uv_layers=None):
if (me is None):
me = bpy.context.active_object.data
bm = bmesh.from_edit_mesh(me)
uv_layers = bm.loops.layers.uv.verify()
faces_loops = utilities_uv.selection_store(bm, uv_layers, return_selected_faces_loops=True)
islands... |
class VideoNoteMessageFactory(MessageFactory):
async def send_message(self, client: TelegramClient, chat_id: int, target: Message=None) -> Message:
return (await client.send_file(chat_id, file='tests/mocks/video_note_0.mp4', video_note=True, reply_to=target))
def compare_message(self, tg_msg: Message, e... |
.parametrize('test_input, expected', [('test', False), (10, False), (1.0, False), (True, False), ('/does/not/exist', False), ([], False), ({}, False)])
def test_bad_file_type(test_input, expected):
assert (config.File.type_check(test_input) == expected)
assert (str(config.File) == 'existing file') |
def extractStarrynightnovelsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Shini Yasui Koshaku Reijo to Shichi-nin no Kikoshi', 'Shini Yasui Koshaku Reijo to Shic... |
class OptionSeriesVariablepieSonificationTracks(Options):
def activeWhen(self) -> 'OptionSeriesVariablepieSonificationTracksActivewhen':
return self._config_sub_data('activeWhen', OptionSeriesVariablepieSonificationTracksActivewhen)
def instrument(self):
return self._config_get('piano')
def ... |
class TraitListNodeType(NodeType):
klass = Any()
text = Str()
trait_name = Str()
def is_type_for(self, node):
is_type_for = (isinstance(node, list) and hasattr(node, 'object') and isinstance(node.object, self.klass) and (node.name == self.trait_name))
return is_type_for
def allows_ch... |
def test_save_as_sets_the_render_file_name_for_shots(create_test_data, create_maya_env):
data = create_test_data
maya_env = create_maya_env
version1 = Version(task=data['task6'])
version1.extension = '.ma'
version1.update_paths()
maya_env.save_as(version1)
expected_path = 'renders/{take_name... |
def _fix_argv(argv, sys_path, main_module, *, platform=sys.platform, executable=sys.executable, get_executable=_get_executable, get_main_module_name=main_module_name):
if (not sys_path[0]):
name = get_main_module_name(main_module)
if (name is not None):
argv = argv[:]
argv[0]... |
class Requester():
USER_AGENTS = userAgents.split('\n')
def get(self, url, _proxies={}):
return requests.get(url, headers={'User-Agent': random.choice(self.USER_AGENTS)}, proxies=_proxies)
def head(self, url, _proxies={}):
return requests.head(url, headers={'User-Agent': random.choice(self.U... |
def create_imports() -> str:
link_btn = '../../../../website/src/components/LinkButtons.jsx'
cell_out = '../../../../website/src/components/CellOutput.jsx'
plot_out = '../../../../website/src/components/Plotting.jsx'
imports = f'''import LinkButtons from "{link_btn}";
'''
imports += f'''import CellO... |
class SyncPQServer(SyncServer):
def __init__(self, *, global_model: IFLModel, channel: Optional[ProductQuantizationChannel]=None, **kwargs):
init_self_cfg(self, component_class=__class__, config_class=SyncPQServerConfig, **kwargs)
super().__init__(global_model=global_model, channel=channel, **kwargs... |
.requires_dbt_version('1.3.0')
class TestJsonschema():
.only_on_targets(SUPPORTED_TARGETS)
def test_valid(self, test_id: str, dbt_project: DbtProject):
valid_value = json.dumps(''.join(('*' for _ in range(MIN_LENGTH))))
data = [{COLUMN_NAME: valid_value}]
result = dbt_project.test(test_i... |
class _ToolBar(QtGui.QToolBar):
def __init__(self, tool_bar_manager, parent):
QtGui.QToolBar.__init__(self, parent)
self.tools = []
self.tool_bar_manager = tool_bar_manager
self.tool_bar_manager.observe(self._on_tool_bar_manager_enabled_changed, 'enabled')
self.tool_bar_manag... |
def check_session_hijacking(uri, thisList, username, password, scanid):
for keyword in thisList:
if (keyword in uri):
attack_result = {'id': 5, 'scanid': scanid, 'url': uri, 'alert': 'Session Fixation', 'impact': 'High', 'req_headers': 'NA', 'req_body': 'NA', 'res_headers': 'NA', 'res_body': 'NA... |
def test_multi_missing(data_client):
s1 = Repository.search()
s2 = Search(index='flat-git')
s3 = Search(index='does_not_exist')
ms = MultiSearch()
ms = ms.add(s1).add(s2).add(s3)
with raises(ApiError):
ms.execute()
(r1, r2, r3) = ms.execute(raise_on_error=False)
assert (1 == len(... |
class SimpleProgressThread(ProgressThread):
def __init__(self, target, *args, **kwargs):
ProgressThread.__init__(self)
self.__target = (target, args, kwargs)
self.__stop = False
def stop(self):
self.__stop = True
def run(self):
(target, args, kwargs) = self.__target
... |
class FirewallEnforcer(object):
def __init__(self, project, compute_client, expected_rules, current_rules=None, project_sema=None, operation_sema=None, add_rule_callback=None):
self.project = project
self.compute_client = compute_client
self.expected_rules = expected_rules
if current... |
def test_matcher_start_zero_plus_not_in(matcher):
pattern = [{'ORTH': {'NOT_IN': ['t', 'z']}, 'OP': '*'}, {'ORTH': 'c'}]
matcher.add('TSTEND', [pattern])
nlp = (lambda string: Doc(matcher.vocab, words=string.split()))
assert (len(matcher(nlp('c'))) == 1)
assert (len(matcher(nlp('b c'))) == 1)
as... |
_meta(definition.SealingArrayCard)
class SealingArrayCard():
name = ''
illustrator = ''
cv = 'shoureiN'
tag = 'sealarray'
description = ',,,,'
def is_action_valid(self, c, tl):
if (len(tl) != 1):
return (False, '')
t = tl[0]
if (self.me is t):
retu... |
class Type():
def __init__(self, dtype, shape=None, strides=None, offset=0, nbytes=None):
self.shape = (tuple() if (shape is None) else wrap_in_tuple(shape))
self.size = product(self.shape)
self.dtype = dtypes.normalize_type(dtype)
self.ctype = dtypes.ctype_module(self.dtype)
... |
def match_xtgeo_214_header(header: bytes) -> bool:
first_part_match = header.startswith(b'roff-bin\x00#ROFF file#\x00#Creator: CXTGeo subsystem of XTGeo by JCR#\x00tag\x00filedata\x00int\x00byteswaptest\x00')
problem_area_match = header[99:].startswith(b'char\x00filetype\x00grid\x00char\x00creationDate\x00UNKNO... |
class FolderNode(NodeType):
def is_type_for(self, node):
return isdir(node)
def allows_children(self, node):
return True
def has_children(self, node):
return (len(listdir(node)) > 0)
def get_children(self, node):
return [join(node, filename) for filename in listdir(node)]... |
def test_correct_response_new_awards_only(client, monkeypatch, elasticsearch_transaction_index, awards_and_transactions):
setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index)
resp = client.post('/api/v2/search/spending_by_geography', content_type='application/json', data=json.dumps({'scope': '... |
def test_js_module_names():
with raises(ValueError):
create_js_module(3, CODE, ['bb'], 'aa', 'simple')
with raises(ValueError):
create_js_module('', CODE, ['bb'], 'aa', 'simple')
code = create_js_module('foo.js', CODE, ['bb'], 'aa', 'simple')
assert ('.foo =' in code) |
class Server(ModelNormal):
allowed_values = {}
validations = {('weight',): {'inclusive_maximum': 100, 'inclusive_minimum': 1}}
_property
def additional_properties_type():
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_typ... |
def setup_chromosome(axis, y_min=None, y_max=None, y_label=None):
if (y_min and y_max):
axis.set_ylim(y_min, y_max)
if (y_min < 0 < y_max):
axis.axhline(color='k')
if y_label:
axis.set_ylabel(y_label)
axis.tick_params(which='both', direction='out')
axis.get_xaxis().ti... |
class OptionSeriesBoxplotSonificationTracksMappingPlaydelay(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
self... |
class TestTKOSubsScanScan():
def setup_method(self):
self.tmp_path = Path(tempfile.mkdtemp())
self.scan = TKOSubsScan(target_file=__file__, results_dir=str(self.tmp_path), db_location=str((self.tmp_path / 'testing.sqlite')))
self.scan.exception = False
def teardown_method(self):
... |
class Page(object):
def from_raw(raw):
return Page(raw['data'], raw.get('before'), raw.get('after'))
def __init__(self, data, before=None, after=None):
self.data = data
self.before = before
self.after = after
def map_data(self, func):
return Page([func(x) for x in sel... |
def _check_dependencies_in_registry(registry: BaseRegistry, agent_config: AgentConfig, push_missing: bool) -> None:
for item_type_plural in (PROTOCOLS, CONTRACTS, CONNECTIONS, SKILLS):
dependencies = getattr(agent_config, item_type_plural)
for public_id in dependencies:
if push_missing:
... |
.parametrize('version, supported', [('3.0', True), ('3.1', True), ('3.10', True), ('30.0', False), ('31.0', False), ('4.0', False), ('4.1', False), ('4.10', False), ('40.0', False), ('41.0', False), ('2.0', False), ('2.1', False), ('2.10', False), (None, False)])
def test_supported_asgi_version(version, supported):
... |
class TestRemove():
def test_remove_dir(self, tmpdir):
path = str(tmpdir.join('test'))
makedirs(path)
remove(path)
assert (not os.path.exists(path))
def test_remove_file(self, tmpdir):
f = str(tmpdir.join('test.txt'))
touch(f)
remove(f)
assert (not... |
def upgrade():
with op.batch_alter_table('users') as batch_op:
batch_op.alter_column('date_joined', existing_type=sa.DateTime(timezone=False), type_=flaskbb.utils.database.UTCDateTime(timezone=True), existing_nullable=True)
batch_op.alter_column('lastseen', existing_type=sa.DateTime(), type_=flaskbb... |
def cole_cole(inp, p_dict):
iotc = (np.outer(((2j * np.pi) * p_dict['freq']), inp['tau']) ** inp['c'])
condH = (inp['cond_8'] + ((inp['cond_0'] - inp['cond_8']) / (1 + iotc)))
condV = (condH / (p_dict['aniso'] ** 2))
etaH = (condH + (1j * p_dict['etaH'].imag))
etaV = (condV + (1j * p_dict['etaV'].im... |
class _Take(References):
def __init__(self, parent: References, indices: types.arraydata) -> None:
assert (indices.shape[0] > 1), 'inefficient; this should have been `_Empty` or `_Uniform`'
assert (not isinstance(parent, _Uniform)), 'inefficient; this should have been `_Uniform`'
self.parent... |
def generateTCF6(iterationsMap, iteration, t):
msg = generateGenericMessage('EiffelTestCaseFinishedEvent', t, '1.0.0', 'TCF6', iteration)
link(msg, iterationsMap[iteration]['TCT6'], 'TEST_CASE_EXECUTION')
msg['data']['outcome'] = {'verdict': randomizeVerdict(0.98), 'conclusion': 'SUCCESSFUL'}
return msg |
class OptionSeriesVectorMarkerStatesSelect(Options):
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def fillColor(self):
return self._config_get('#cccccc')
def fillColor(self, text: str):
self._config(text... |
def is_under_debugger() -> bool:
frames = inspect.stack()
if (len(frames) >= 3):
filename = frames[(- 3)].filename
if filename.endswith('/pdb.py'):
return True
elif filename.endswith('/pydevd.py'):
return True
return (sys.gettrace() is not None) |
def extractEnsjTranslations(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
tagmap = [('RMB', 'Record of Muwuis Battles', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) in tagmap:
if (tagname in item['ta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.