id
stringlengths
3
8
content
stringlengths
100
981k
4886818
import logging from functools import partial from typing import Union import numpy as np import pandas as pd from scipy.spatial import distance as dist from divik.core import ( Data, configurable, maybe_pool, ) from divik.sampler import BaseSampler, StratifiedSampler KMeans = "divik.cluster.KMeans" _BIG_...
4886891
from math import ceil import numpy as np import cutde.backend as backend from cutde.coordinators import ( check_inputs, placeholder, process_block_inputs, solve_types, source_dir, ) def check_tol_max_iter(obs_start, tol, max_iter, float_type): tol = np.array(tol) if tol.shape[0] != obs_...
4886923
from .Layer import * class Reshape(Layer): def __init__(self, model, *args, **kwargs): Layer.__init__(self, model, *args, **kwargs) self.dims = kwargs.get("dims", np.array([-1, -1, -1, -1])) def reshape(self): xshp = self.X.shape self.yshp = list(xshp) k = None v...
4886927
import pytest import torch from torch.optim import Adam from models.modules import FCNet, FCResNet, IsotropicGaussian from models.modules import ConvNet64, DeConvNet64 from models.modules_sngan import GeneratorNoBN @pytest.mark.parametrize('out_activation', ['linear', 'spherical']) def test_fcnet(out_activation): ...
4886956
import torch import os import pandas as pd import numpy as np from TLA.Analysis.lang_mapping import mapping from distutils.sysconfig import get_python_lib def analysis_table(): lang_dict = mapping() directory = "analysis" parent_dir = get_python_lib() + "/TLA/Analysis" p = os.path.join(parent_dir, dire...
4886990
from unittest import TestCase import json import pgpy from quedex_api import UserStream, UserStreamListener, Trader, Exchange class TestUserStream(TestCase): # maxDiff = None def setUp(self): self.quedex_private_key = pgpy.PGPKey() self.quedex_private_key.parse(open('keys/quedex-private-key.asc', 'r')....
4886994
class TrainingConfig(): def __init__(self) -> None: self.arbitrary_len = False self.batch_size = 100 self.checkpoints_dir = "./checkpoints/vae" self.clip_set = "./dataset/pose_clip_full.csv" self.coarse_grained = False self.dataset_type = None self.decoder...
4886996
from copy import deepcopy def wrap_agentid(agent_ids, network): group = {} for agent_id in agent_ids: group[agent_id] = deepcopy(network) return group
4887017
import rvt.default import rvt.blend_func import rvt.blend import rvt.vis import numpy as np # Test enhanced version 3 multi-scale topographic position (e3MSTP) dem_path = r"D:\RVT_py\test\Pohorje\Pohorje.tif" #r"D:\RVT_py\test\E3MSTP_TEST\Skolj_dem_05m.tif" dem_dict = rvt.default.get_raster_arr(dem_path) dem_arr = de...
4887047
from pyworkflow.node import IONode, NodeException from pyworkflow.parameters import * import pandas as pd class ReadCsvNode(IONode): """ReadCsvNode Reads a CSV file into a pandas DataFrame. Raises: NodeException: any error reading CSV file, converting to DataFrame. """ name...
4887058
import os import argparse from layered.problem import Problem from layered.trainer import Trainer def main(): parser = argparse.ArgumentParser('layered') parser.add_argument( 'problem', help='path to the YAML problem definition') parser.add_argument( '-v', '--visual', action='store...
4887107
import pytest from busy_beaver.apps.upcoming_events.workflow import add_new_group_to_configuration from busy_beaver.models import Event, UpcomingEventsConfiguration, UpcomingEventsGroup class TestUpdateSettings: @pytest.mark.vcr def test_add_new_group_to_configuration(self, factory): """Happy Path --...
4887131
from typing import (Optional, TYPE_CHECKING) from ground.hints import Point from reprit.base import generate_repr if TYPE_CHECKING: from .node import Node from .edge import Edge class Trapezoid: __slots__ = ('left', 'right', 'below', 'above', 'node', '_lower_left', '_lower_right', '_upp...
4887146
from torch import nn as nn from mmdet.models import BACKBONES import time import numpy as np import torch from torch import nn from ..model_utils import ModulatedDeformConvBlock from torchplus.tools import change_default_args from torchplus.nn.modules.common import Sequential from mmcv.runner import load_checkpoint fro...
4887164
import os dirs = [ "js", "js/collections", "js/models", "js/routers", "js/views" ] def exists(p): try: os.stat(p) return True except: return False def make_dirs(): for d in dirs: print(d) os.chdir("/www") path = d.split('/') prin...
4887171
import copy from .xcontroller import Cell, ComputedCell class _GenericHub(object): def __init__(self, controller): self.extra = {} self._ns = {} self._controller = controller def keys(self): return self._ns.keys() def has_key(self, key): return key in self._ns ...
4887199
import sys from pathlib import Path from ..utils.base_model import BaseModel sys.path.append(str(Path(__file__).parent / '../../third_party')) from SuperGluePretrainedNetwork.models.superpoint import SuperPoint as SP class SuperPoint(BaseModel): default_conf = { 'nms_radius': 4, 'keypoint_thresh...
4887264
from python_picnic_api import PicnicAPI from dotenv import load_dotenv import os load_dotenv() username = os.getenv("USERNAME") password = <PASSWORD>("PASSWORD") country_code = os.getenv("COUNTRY_CODE") picnic = PicnicAPI(username, password, country_code=country_code) def _get_amount(cart: dict, product_id: str): ...
4887315
from .tools import extract_backbone_from_pth, update_config from .config_utils import dict_to_json, json_to_dict from .basic import ListDict from .timer import Timer from .coco_utils import coco_eval
4887323
import requests import json import re from dataclasses import dataclass from typing import Iterator, Generator from itertools import islice from .dbc import DBC, http_json_res_parse from bools.functools import catch from bools.log import Logger TEMPLATE_NAME = 'bowaer' _HEADERS = { 'Content-type': 'application/js...
4887345
from __future__ import print_function, division import os import torch import pandas as pd #from skimage import io, transform import cv2 import numpy as np import random import torch from torch.utils.data import Dataset, DataLoader from torchvision import transforms import pdb import math import os import imgaug.augme...
4887364
import unittest from random import random from geo.shapes import Point, Polygon, Triangle from geo.spatial import triangulatePolygon from geo.generator import randomConvexPolygon, randomConcaveTiling from geo.drawer import plot, plotPoints, show, showPoints from min_triangle import minTriangle, boundingTriangle from gr...
4887419
from collections import defaultdict from datetime import timedelta from typing import Dict, List from celery import shared_task from django.db import connection, transaction from django.db.models import QuerySet from django.utils import timezone from django.utils.timezone import now from sentry_sdk import capture_exce...
4887427
from dict_hash import sha256, dict_hash import pytest def test_dict_hash_failure(): with pytest.raises(ValueError): dict_hash(0) with pytest.raises(ValueError): sha256(0)
4887442
import os.path as op import numpy as np import scipy as sp import scipy.stats from util.infersys import * from util.modelenv import * #------------------------------------------------------------- # Models augur_hlr = ''' (K : Int, N : Int, lam : Real, x : Vec (Vec Real)) => { param v ~ Exponential(lam) ; param ...
4887452
import launchpad as lp import reverb from . import common class ReverbNode(lp.ReverbNode): """Inherits `ReverbNode` from launchpad and remove `worker_manager` from it.""" def run(self): priority_tables = self._priority_tables_fn() if self._checkpoint_ctor is None: checkpointer = None else: ...
4887519
from datetime import datetime as date_time from dotenv import load_dotenv from os import getenv as environment_env load_dotenv() class Env: @staticmethod def api_client_secret_file(): return environment_env("API_CLIENT_SECRET_FILE") @staticmethod def api_scope(): return [environment_e...
4887615
import logging from keras.layers import Dense, Dropout, Activation, Embedding, LSTM, Input from my_layers import Attention, Average, WeightedSum from keras.models import Model logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') logger = logging.getLogger(__name_...
4887635
from .app import show if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument("--debug", action="store_true") args = parser.parse_args() if args.debug: from . import mock import pyblish.api for Plugin in mock.plugins: ...
4887641
import time import numpy as np import tensorflow as tf from resnet101_deep_metric import Resnet101_Deep_Metric from Mybase.solver import Solver def test(): mdl = Resnet101_Deep_Metric(cls_num=81, reg=1e-4, drp=0.5, typ=tf.float32) sov = Solver(mdl, opm_cfg={ "decay_r...
4887642
import pandas as pd zhihu_question = pd.read_csv('./raw_data/zhihu_question.csv', encoding="gb2312") zhihu_answer = pd.read_csv('./raw_data/zhihu_answer.csv', encoding="gb2312") with open("./cleaned_data/zhihu.txt", 'w') as f_cleaned: for title in zhihu_question["title"]: f_cleaned.write(title) f_c...
4887669
from floem import * class MyState(State): qid = Field(Int) keylen = Field(Int) key = Field(Pointer(Uint(8)), size='state.keylen') p = Field(Pointer(Int), shared='data_region') class main(Flow): state = PerPacket(MyState) class Save(Element): def configure(self): self.inp =...
4887696
import Tkinter as tk from copy import copy, deepcopy from common.parameters import PARAM from common.styles import (BODY_COLOR, BODY_FONT, CELL_TYPE_HEADER_COLOR, CELL_TYPE_HEADER_FONT, CELL_TYPE_LABELS, HEADER_COLOR, HEADER_FONT) BODY_LEFT_MARGIN = 30 LABEL_WIDTH...
4887699
class Solution: def numTilings(self, N: int) -> int: MOD = 1000000007 dp = [0] * 1001 ''' dp[i] = dp[i - 1] + dp[i - 2] + 2 * (dp[i - 3] + dp[i - 4] + ... + dp[0]) dp[i - 1] = dp[i - 2] + dp[i - 3] + 2 * (dp[i - 4] + dp[i - 4] + ... + dp[0]) dp[i] - dp[i - 1] = dp[i -...
4887704
import os import sys sys.path.append(os.path.dirname(os.path.abspath(__file__))) from commander.deploy import BadReturnCode, hostgroups, task import commander_settings as settings _src_dir = lambda *p: os.path.join(settings.SRC_DIR, *p) VIRTUALENV = os.path.join(os.path.dirname(settings.SRC_DIR), 'venv') @task d...
4887710
from typing import Any import numpy as np import numpy.linalg as la import scipy, scipy.integrate from PIL import Image as PILImage import argparse import os import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import scipy.interpolate import json from functools import reduce from deepracing.path_uti...
4887721
import datetime from django.db import models from django.conf import settings import logging from market.models import MarketPlace, MarketCategory, MarketSubCategory from auth.models import User class WishListItem(models.Model): marketplace = models.ForeignKey(MarketPlace) posted_on = models.DateTimeField(aut...
4887798
from datetime import datetime from flask_dance.consumer.storage.sqla import OAuthConsumerMixin from sqlalchemy.orm.collections import attribute_mapped_collection from flask_login import LoginManager, UserMixin from . import db, login_manager class SerializableMixin(object): def _serialize(self): """Jsoni...
4887800
import json import asyncio import logging import numpy from sanic import response from hexi.plugin.OutputPlugin import OutputPlugin _logger = logging.getLogger(__name__) class PluginOutputStewartVisualize(OutputPlugin): def __init__(self): super().__init__() self.configurable = True self.connected_cl...
4887814
from os import getenv from pytest import fixture from koreanbots import Koreanbots @fixture async def client(): yield Koreanbots(api_key=getenv("API_KEY"))
4887865
import unittest import torchaudio class TestTorchaudio(unittest.TestCase): def test_import(self): waveform, sample_rate = torchaudio.load('/input/tests/data/test.wav') self.assertEqual(2, len(waveform)) self.assertEqual(44100, sample_rate)
4887897
import asyncio import uvloop from starlette.requests import Request from .commands import bundle_vendored, migrate_databases, transpile_scss from .settings import ( DEBUG, LNBITS_COMMIT, LNBITS_DATA_FOLDER, LNBITS_SITE_TITLE, PORT, SERVICE_FEE, WALLET, ) uvloop.install() asyncio.create_t...
4887900
from enum import Enum from typing import Dict, List, Sequence, Tuple, Union import matplotlib.pyplot as plt import numpy as np import pandas as pd import scanpy as sc import seaborn as sb from adjustText import adjust_text from matplotlib import colors from rich import print class Colormaps(Enum): """ Availa...
4887905
import torch import torch.nn.functional as F from kornia.filters.gaussian import gaussian_blur2d from utils import group_sum from cam import BaseCAM blur = lambda x: gaussian_blur2d(x, kernel_size=(51, 51), sigma=(50., 50.)) class GroupCAM(BaseCAM): def __init__(self, model, target_layer="module.layer4.2", group...
4887943
import time from hslog.export import BaseExporter, CompositeExporter, FriendlyPlayerExporter from hslog.packets import Block, SubSpell from .conftest import logfile class LoggingExporter(BaseExporter): def __init__(self, packet_tree): super().__init__(packet_tree) self.flush_calls = 0 self.handle_block_cal...
4887956
from torch.nn.modules import Module import torch import torch.nn as nn import torch.nn.functional as F class NEL_Loss(Module): def __init__(self): super(NEL_Loss, self).__init__() def forward(self, target, prediction): prediction = prediction.requires_grad_() delta = t...
4887961
from pathlib import Path import pytest import subprocess from .util import random_string def test_predict_takes_string_inputs_and_returns_strings_to_stdout(): project_dir = Path(__file__).parent / "fixtures/string-project" result = subprocess.run( ["cog", "predict", "-i", "world"], cwd=projec...
4887964
import os import cv2 import easyocr import numpy as np import pandas as pd import streamlit as st import matplotlib.pyplot as plt from glob import glob from typing import Union from io import BytesIO, StringIO from scipy.stats import norm, percentileofscore if not os.path.exists('processed_images'): os.makedirs('...
4887982
import insightconnect_plugin_runtime from .schema import QuarantineFileInput, QuarantineFileOutput, Input, Output, Component # Custom imports below from insightconnect_plugin_runtime.exceptions import PluginException class QuarantineFile(insightconnect_plugin_runtime.Action): def __init__(self): super(se...
4887983
from typing import Dict, Tuple, Any from python.pipeline import ComponentBase from python.pipeline.pipeline import PipelineStage class CleanupStage(PipelineStage): """ Calls cleanup() on all live objects in the pipeline. """ def __index__(self, pos, config, config_global, logger): super(Clea...
4887991
from __future__ import division import numpy as np import numpy.random as npr import matplotlib.pyplot as plt from pybasicbayes.distributions import Regression, DiagonalRegression from pybasicbayes.util.text import progprint_xrange from pylds.models import LDS, DefaultLDS npr.seed(0) # Parameters D_obs = 1 D_laten...
4887997
import torch import torch.nn as nn class BaseQuantizer(nn.Module): def __init__( self, bit_type, observer, module_type): super(BaseQuantizer, self).__init__() self.bit_type = bit_type self.observer = observer self.module_type = module...
4888069
from aiogram.dispatcher.filters.state import StatesGroup, State class MySG(StatesGroup): main = State()
4888082
from ..helpers import filt_block_help from .. import conf from .. import gen_utils from ..gen_utils import ( get_collections_dets, get_nice_str_list, layout_comment as layout) def truncate_dict(input_dict): output_dict = {} for k, v in input_dict.items(): if len(output_dict) >= conf.MAX_ITEMS_EVALU...
4888109
from PyQt5.QtWidgets import * from PyQt5.QtCore import * from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar def ClearAllWidgetInLayout(layout): for i in reversed(range(layout.count())): w...
4888190
from __future__ import unicode_literals import json import logging from datetime import timedelta from django.conf import settings from django.utils import timezone from django.utils.crypto import constant_time_compare, get_random_string from django.utils.encoding import force_text from requests.api import request fr...
4888192
from json import loads from clutch.schema.user.method.torrent.action import TorrentActionMethod def test_torrent_action(client): try: client.torrent.action(TorrentActionMethod.START_NOW, ids=[1, 2]) except Exception: pass request_data = loads(client._connection.session.post.call_args.kwa...
4888209
from unicorn.arm_const import * import signal import os from ...exit import do_exit def return_zero(uc): uc.reg_write(UC_ARM_REG_R0, 0) def crash(uc): print("[*] Crashing handler at 0x{:08x} triggered, crashing now".format(uc.reg_read(UC_ARM_REG_PC))) os.kill(os.getpid(), signal.SIGSEGV) def exit(uc): ...
4888211
import os import time import json import requests import datetime import gzip from dateutil.relativedelta import * import pandas as pd import numpy as np import praw import boto3 from botocore.exceptions import ClientError from sqlalchemy import create_engine, MetaData, Table, insert, delete def get_submissions(fr...
4888272
from __future__ import absolute_import from celery.contrib.abortable import AbortableTask, AbortableAsyncResult from celery.tests.case import AppCase class test_AbortableTask(AppCase): def setup(self): @self.app.task(base=AbortableTask, shared=False) def abortable(): return True ...
4888395
import os import pytest from twindb_backup.cache.cache import Cache, CacheException def test_init_raises_exception(): with pytest.raises(CacheException): Cache('foo') def test_in(cache_dir): c = Cache(str(cache_dir)) assert 'bar' not in c cache_dir.mkdir('foo') assert 'foo' in c def...
4888454
import time from multiprocessing import Value import pytest import dash_html_components as html import dash_core_components as dcc import dash_table import dash from dash.dependencies import Input, Output, State from dash.exceptions import PreventUpdate def test_cbmt001_called_multiple_times_and_out_of_order(dash_d...
4888478
import json import uuid from collections import deque from threading import Lock import amqp import sys from synergy.conf import settings, context from synergy.system.decorator import thread_safe class SynergyAware(object): def __init__(self, name): self.name = name if name in context.process_co...
4888510
import logging import os import sys from threading import Thread from i3pystatus.core import io, util from i3pystatus.core.exceptions import ConfigError from i3pystatus.core.imputil import ClassFinder from i3pystatus.core.modules import Module DEFAULT_LOG_FORMAT = '%(asctime)s [%(levelname)-8s][%(name)s %(lineno)d] %...
4888535
from .util import get_img_and_data from labelme.utils import shape as shape_module def test_shapes_to_label(): img, data = get_img_and_data() label_name_to_value = {} for shape in data['shapes']: label_name = shape['label'] label_value = len(label_name_to_value) label_name_to_valu...
4888569
import plotly.graph_objects as go import plotly.express as px from pytest import fixture import pandas as pd font = {"family": "Monospace"} def simple_figure(): return go.Figure( { "data": [{"y": [1, 3, 2], "type": "scatter"}], "layout": {"title": {"text": "Title"}, "font": font} ...
4888591
import pytest from werkzeug.exceptions import Forbidden from werkzeug.exceptions import HTTPException from werkzeug.exceptions import InternalServerError from werkzeug.exceptions import NotFound import flask def test_error_handler_no_match(app, client): class CustomException(Exception): pass class U...
4888619
from fabric.api import env, local, task @task def ssh(): """ Log into the remote host using SSH """ local("ssh ubuntu@%s -i %s" % (env.hosts[0], env.key_filename[0]))
4888640
import math import ujson as json from pathlib import Path import aiocache as aiocache import aiohttp_jinja2 from aiohttp import web import sqlalchemy as sa from sqlalchemy import orm from terial import config, models from terial.database import session_scope @aiocache.cached(ttl=10) async def _get_rend_paths(datas...
4888676
from glob import glob import random import json # read the available sequence names f = glob('../hpatch-release/*') f = [k.split("/")[-1] for k in f] i = [k for k in f if 'i_' in k] v = [k for k in f if 'v_' in k] # rand seeds for reproducibility seeds = [40,41,42] names = ['a','b','c'] # init splits dict spl = {} #...
4888695
from __future__ import annotations from abc import abstractmethod from typing import TYPE_CHECKING if TYPE_CHECKING: from poetry.core.semver.version import Version from poetry.core.semver.version_range_constraint import VersionRangeConstraint class VersionConstraint: @abstractmethod def is_empty(se...
4888701
import sys import bteve as eve if sys.implementation.name == "circuitpython": gd = eve.Gameduino() else: from spidriver import SPIDriver gd = eve.Gameduino(SPIDriver(sys.argv[1])) gd.init() gd.Clear() gd.ScissorSize(480, 272) gd.ClearColorRGB(0x00, 0x20, 0x40) gd.Clear() gd.cmd_flashdetach() def showbyt...
4888729
import os from unittest import TestCase, mock from unittest.mock import Mock from osbenchmark.builder.installers.preparers.opensearch_preparer import OpenSearchPreparer from osbenchmark.builder.models.host import Host from osbenchmark.builder.models.node import Node from osbenchmark.builder.provision_config import Pro...
4888739
import time import socket import unittest import unit class TestUnitSettings(unit.TestUnitApplicationPython): def setUpClass(): unit.TestUnit().check_modules('python') def test_settings_header_read_timeout(self): self.load('empty') self.conf({'http': { 'header_read_timeout': 2 }}, '/...
4888753
from django.test.testcases import SimpleTestCase, TestCase from mock import patch from corehq.apps.app_manager.models import ( Application, Form, FormLink, Module, import_app, ) from corehq.apps.app_manager.suite_xml import xml_models as suite_models from corehq.apps.app_manager.tests.app_factory ...
4888769
from builtins import str from ctypes import * from ctypes import util from .runtime import send_message, ObjCInstance from .cocoatypes import * ###################################################################### # CORE FOUNDATION cf = cdll.LoadLibrary(util.find_library('CoreFoundation')) kCFStringEncodingUTF8 ...
4888772
import FWCore.ParameterSet.Config as cms # This version is intended for unpacking standard production data castorDigis = cms.EDProducer("CastorRawToDigi", # Optional filter to remove any digi with "data valid" off, "error" on, # or capids not rotating FilterDataQuality = cms.bool(True), # Number of th...
4888804
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'youtube_project.views.home', name='home'), (r'^youtube/', include('django_youtube.urls')), # Django youtube re...
4888817
import base64 from dataclasses import dataclass, field from functools import reduce from io import BytesIO from typing import Optional, Union from PIL import Image import httpx from nonebot import logger from nonebot.adapters.cqhttp.message import Message, MessageSegment from .plugin_config import plugin_config from ...
4888821
from allegation.factories import OfficerFactory from common.tests.core import BaseLivePhoneTestCase class MobileSimpleTabTestMixin(BaseLivePhoneTestCase): def assert_active_tab(self, tab_class): tab_selector = '.tab-nav.active.{tab_class}'.format(tab_class=tab_class) self.until(lambda: self.find_a...
4888840
import numpy as np from psecas import Solver, FourierGrid from psecas.systems.kh_hydro import KelvinHelmholtzHydroOnly import time import matplotlib.pyplot as plt # Initialize grid, system and solver for hydrodynamic KHI kxmax = 3.5128286141291243 grid = FourierGrid(N=64, zmin=0.0, zmax=2.0) system = KelvinHelmholtzHy...
4888883
import io import os import setuptools setuptools.setup( name="kconfiglib", # MAJOR.MINOR.PATCH, per http://semver.org version="14.1.0", description="A flexible Python Kconfig implementation", # Make sure that README.rst decodes on Python 3 in environments that use # the C locale (which impli...
4888900
from pytools import testutil import sys import basecase class E1photlam(basecase.effstimCase): def setUp(self): self.spectrum="bb(5000) " self.obsmode="bessell,h" self.form="photlam" self.setglobal(__file__) self.runpy() class E1flam(basecase.effstimCase): def setUp(s...
4888947
import streamlit as st from bokeh.models.widgets import Button from bokeh.models import CustomJS from streamlit_bokeh_events import streamlit_bokeh_events import leafmap.foliumap as leafmap def app(): loc_button = Button(label="Get Device Location", max_width=150) loc_button.js_on_event( "button_clic...
4888983
from django.db import models from rest_framework import serializers, viewsets from rest_framework_nested import serializers as nested_serializers from rest_framework_nested import relations class Parent(models.Model): name = models.CharField(max_length=10) class Child1(models.Model): name = models.CharField...
4889032
from .conmat_to_graph import create_pipeline_conmat_to_graph_density # noqa from .conmat_to_graph import create_pipeline_conmat_to_graph_threshold # noqa from .conmat_to_graph import create_pipeline_net_list_to_graph # noqa from .conmat_to_graph import create_pipeline_bct_graph # noqa from .nii_to_conmat import cr...
4889066
from __future__ import unicode_literals from django.test import TestCase from django.db import connections from django.test import tag import time from django_postgres_extensions.models.functions import ArrayAppend, ArrayCat from .models import Traditional, NumberArray, NumberTraditional, Array @tag('benchmark') class...
4889085
import datetime from newspaper import Article import scrapy import locale import datetime locale.setlocale(locale.LC_ALL, "es_AR.utf8") BASE_URL = 'https://www.pagina12.com.ar/' class PaginaSpider(scrapy.Spider): name = "p12" def start_requests(self): url = 'https://www.pagina12.com.ar/...
4889099
import pytest from aoc_wim.aoc2017 import q10 def test_munge_example(): assert q10.part_a("3,4,1,5", n=5) == 12 @pytest.mark.parametrize("data,expected", [ ("", "a2582a3a0e66e6e86e3812dcb672a272"), ("AoC 2017", "33efeb34ea91902bb2f59c9920caa6cd"), ("1,2,3", "3efbe78a8d82f29979031a4aa0b16a9d"), ...
4889103
import gzip import json import json as _json import logging import numbers import os import re from collections import UserList from json.decoder import JSONDecodeError from typing import Any, Callable, Dict, List, Optional, Tuple, Union from urllib.parse import urljoin import requests.utils from requests import Respo...
4889115
import time from Adafruit_BME280 import * from msense import MotionSense class Sensors: def __init__(self): self.sensor = BME280(mode=BME280_OSAMPLE_8) self.motion_sense = MotionSense() self.last = self.read() def read(self): degrees = self.sensor.read_temperature() se...
4889161
import astar import sys if __name__ == "__main__": if(len(sys.argv) != 2): print("USAGE: python {0} file.map".format(sys.argv[0])) sys.exit(1) with open(sys.argv[1], 'r') as f: fdata = f.readlines() # print map for line in fdata: print(line, end='') print() # ...
4889168
import datetime import re import os from ruamel.yaml import YAML yaml = YAML(typ='safe') yaml.default_flow_style = False yaml.representer.ignore_aliases = lambda x: True def iter_files(): outdir = 'engagements' for filename in os.listdir(outdir): fn = os.path.join(outdir, filename) state, ext ...
4889171
import math import json import numpy as np from datetime import datetime from common.basedir import BASEDIR from selfdrive.config import Conversions as CV from common.transformations.coordinates import LocalCoord, geodetic2ecef LOOKAHEAD_TIME = 10. MAPS_LOOKAHEAD_DISTANCE = 50 * LOOKAHEAD_TIME DEFAULT_SPEEDS_JSON_FIL...
4889181
import dataclasses import json import functools import os import subprocess from nixui.options import nix_eval, syntax_tree, types, environment from nixui.utils.singleton import Singleton from nixui.utils import hash_by_json from nixui.utils.logger import logger Unresolvable = Singleton('Unresolvable') Undefined = S...
4889198
import logging import logging.config from ocd_backend.settings import LOGGING logging.config.dictConfig(LOGGING) def get_source_logger(name=None): logger = logging.getLogger('ocd_backend') if name: formatter = logging.Formatter('[%(asctime)s] [%(name)s] [%(source)s] [%(module)s] [%(levelname)s] - %...
4889218
import pytest @pytest.mark.asyncio async def test_setting_key_is_noop(cache): await cache.set("test", "Ok!") assert await cache.get("test") is None @pytest.mark.asyncio async def test_versioning_key_is_noop(cache): await cache.set("test", "Ok!", version=1) await cache.set("test", "Nope!", version=2)...
4889261
font = CurrentFont() monospace = True sample_glyph = font['space'] sample_width = sample_glyph.width print("... checking font for sample width: ", sample_width) if font.selection: glyphlist = font.selection else: glyphlist = font.keys() for glyphname in glyphlist: glyph = font[glyphname] if glyph.w...
4889297
REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', 'TEST_REQUEST_DEFAULT_FORMAT': 'json', }
4889298
import json from textwrap import dedent class TestAddApplianceStorageController: def test_no_args(self, host): result = host.run('stack add appliance storage controller') assert result.rc == 255 assert result.stderr == dedent('''\ error - "appliance" argument is required {appliance ...} {arrayid=string} ...