id
stringlengths
3
8
content
stringlengths
100
981k
1748401
import warnings from django.test import TestCase from .factories import PhotoFactory, PhotoSizeFactory class PhotologueBaseTest(TestCase): def setUp(self): self.s = PhotoSizeFactory(name='testPhotoSize', width=100, height=100) ...
1748450
from rest_framework import serializers from rest_framework.fields import IntegerField from pipeline.models.users.user import User from .assignments import AssignmentsSerializer class UserGetSerializer(serializers.ModelSerializer): assignments = AssignmentsSerializer(required=False) """ User serializer to...
1748462
import matplotlib.pyplot as plt import statsmodels.api as sm from tsdata import generate_sample_data sample_ts, _ = generate_sample_data() ts_fig, ts_ax = plt.subplots(tight_layout=True) sample_ts.plot(ax=ts_ax, label="Observed") ts_ax.set_title("Time series data") ts_ax.set_xlabel("Date") ts_ax.set_ylabel("Value")...
1748464
from typing import Tuple import gdb class ASTSelectQueryPrinter: def __init__(self, val: gdb.Value) -> None: self.val: gdb.Value = val def to_string(self) -> str: eval_string = "info vtbl (*("+str(self.val.type).strip('&')+" *)("+str(self.val.address)+"))" #example: "info vtbl (*(DB::I...
1748512
from rest_framework import serializers from pipeline.models import Action class ActionSerializer(serializers.ModelSerializer): index = serializers.CharField() vacancy = serializers.CharField(source='pipeline.vacancy', read_only=True) action_type = serializers.CharField(source='action_type.title', read_on...
1748518
import sys, json, os, datetime, glob from shapely.geometry import asShape, mapping from fiona import collection from core import Dump # # Opens a directory containing all the shapefiles, and extracts # def extract_shapefile(shapefile, uri_name, simplify_tolerance): #with collection(shapefile, 'r') as source: ...
1748619
import sys from collections import defaultdict import numpy as np from ..dimension import dimension_name from ..util import isscalar, unique_iterator, pd, unique_array from .interface import DataError, Interface from .multipath import MultiInterface, ensure_ring from .pandas import PandasInterface class SpatialPan...
1748666
import random import numpy as np from absl import app from pysc2.agents import base_agent from pysc2.lib import actions, features, units from pysc2.env import sc2_env, run_loop class RawAgent(base_agent.BaseAgent): def step(self, obs): super(RawAgent, self).step(obs) return actions.RAW_FUNCTIONS.no_op()...
1748693
include("$(PORT_DIR)/boards/manifest.py") freeze("$(PORT_DIR)/boards/UM_TINYPICO/modules", "dotstar.py") freeze("modules")
1748699
from rx import Observable list1 = [23, 38, 43, 23] list2 = [1,2,3,4] source1 = Observable.from_(list1) source2 = Observable.from_(list2) sources = [source1, source2] def main(): Observable.from_(sources) \ .merge_all() \ .subscribe(lambda x: print(x)) if __name__ == '__main__': main() input("Pres...
1748743
def linearSearch(arr, x): pos = -1 for i in range(len(arr)): if arr[i] == x: pos = i print("Found at {}".format(pos)) if pos == -1: print("Not Found")
1748751
import numpy as np def get_seq_len(input_data): if isinstance(input_data, (list, tuple)): return input_data[0].shape elif isinstance(input_data, dict): for k in input_data: return input_data[k].shape elif isinstance(input_data, np.ndarray): return input_data.shape el...
1748777
from unittest import mock import pytest from git import exc as git_exceptions @pytest.fixture def mock_git(): git = mock.MagicMock() git.exc = git_exceptions return git
1748871
import pytest import numpy as np import keras.backend as K from keras.layers import Input from keras_fcn.decoders import ( Decoder, VGGDecoder, VGGUpsampler ) from keras.utils.test_utils import keras_test def test_decoder(): with pytest.raises(ValueError): Decoder(pyramid=['fake1', 'fake2'], ...
1748882
import numpy as np from numpy.linalg import multi_dot from scipy import stats from scipy.linalg import inv from joblib import Parallel, delayed from sklearn.utils.validation import check_memory from sklearn.linear_model import Lasso from .noise_std import reid, group_reid from .stat_tools import pval_from_two_sided_pv...
1748894
import sst from sst.merlin.base import * platdef = PlatformDefinition("platform_dragon_128") PlatformDefinition.registerPlatformDefinition(platdef) platdef.addParamSet("topology",{ "hosts_per_router" : 4, "routers_per_group" : 8, "intergroup_links" : 4, "num_groups" : 4, "algorithm" : "adaptive-l...
1748918
from django.contrib.auth import get_user_model from rest_framework import permissions, viewsets from rest_framework.throttling import UserRateThrottle from .serializers import UserSerializer UserModel = get_user_model() class UserViewSet(viewsets.ModelViewSet): """API endpoint that allows users to be viewed or ...
1748919
from django.apps import apps def handler_auto_admin_account_password_change(sender, instance, **kwargs): AutoAdminSingleton = apps.get_model( app_label='autoadmin', model_name='AutoAdminSingleton' ) auto_admin_properties, created = AutoAdminSingleton.objects.get_or_create() if instance == au...
1748938
import maya.OpenMaya as OpenMaya import maya.cmds as cmds import maya import re def repNameChanged(repNameControl): """ Callback invoked when the render settings UI control for the representation name regular expression text field changes. """ pass def readFromGlobalsNode(): pass def activateR...
1748965
from readthedocs.core.utils.extend import SettingsOverrideObject from readthedocs.embed.v3.views import EmbedAPIBase from readthedocs.core.mixins import ProxiedAPIMixin class ProxiedEmbedAPIBase(ProxiedAPIMixin, EmbedAPIBase): pass class ProxiedEmbedAPI(SettingsOverrideObject): _default_class = ProxiedEmb...
1748967
import asyncio from nats.aio.client import Client as NATS async def example(): # [begin connect_status] nc = NATS() await nc.connect( servers=["nats://demo.nats.io:4222"], ) # Do something with the connection. print("The connection is connected?", nc.is_connected) while True: if...
1748996
from .. import utils from .scatter import _ScatterParams from .tools import generate_colorbar from .tools import generate_legend from .tools import label_axis from .utils import _get_figure from .utils import _with_default from .utils import parse_fontsize from .utils import show from .utils import temp_fontsize impor...
1748997
import fileinput import sys import datetime import json import os def main(): script_dir = os.path.dirname(__file__) currentTime = datetime.datetime.now().time() timer=(int(sys.argv[1])) file_loc = os.path.join(script_dir, 'upgrade-users.json') new_file_loc = os.path.join(script_dir, 'new-upgrade-u...
1749013
from .config import * from .activations_autofn import * from .activations_jit import * from .activations import * _ACT_FN_DEFAULT = dict( swish=swish, mish=mish, relu=F.relu, relu6=F.relu6, sigmoid=sigmoid, tanh=tanh, hard_sigmoid=hard_sigmoid, hard_swish=hard_swish, ) _ACT_FN_AUTO = ...
1749039
import datetime import os import stat import pytest from flask import current_app from flask_app.models import Beam, BeamType, Pin from flask_app.tasks import beam_up, delete_beam, vacuum from flask_app.utils.remote_combadge import _COMBADGE_UUID_PART_LENGTH from flask_app.utils.remote_host import RemoteHost _TEMPDI...
1749057
import copy import uuid from dataclasses import dataclass, field from typing import ( Dict, Optional, TYPE_CHECKING, Union, List, Iterable, Any, Mapping, ) import numpy as np from elasticsearch import Elasticsearch from elasticsearch.helpers import bulk from ..base.backend import BaseB...
1749062
from __future__ import unicode_literals, print_function, absolute_import, division import logging, logging.handlers import sys import os import atexit import errno import signal import pwd from ConfigParser import RawConfigParser from .sniffer import get_sniffer from .daemon import drop_privileges, write_pid, daemoni...
1749118
from modules.android.super_base import Super_base from modules.stix.stix_base import Bundled from utils.logger import Logger from utils.mitigations import load_mitigation class Certificate_keystore_disclosure(Super_base): """ Check if the application has a certificate or keystore """ stix = Bundled(...
1749145
import pytest from traitlets import HasTraits, TraitError from dask_gateway_server.traitlets import Command, Type def test_Type_traitlet(): class Foo(HasTraits): typ = Type(klass="dask_gateway_server.auth.Authenticator") with pytest.raises(TraitError) as exc: Foo(typ="dask_gateway_server.aut...
1749203
from typing import Optional from omnibolt import OmniBolt from omnicore_connection import OmnicoreConnection import os class TestRunner: @staticmethod def generate_omni_bolt(address: str) -> OmniBolt: omni_bolt = OmniBolt(address) user = omni_bolt.connect() omni_bolt.login(user) ...
1749256
from bokeh.io import output_file, show from bokeh.plotting import figure from bokeh.layouts import layout from bokeh.models import Toggle, BoxAnnotation, CustomJS # We set-up the same standard figure with two lines and now a box over top p = figure(plot_width=600, plot_height=200, tools='') visible_line = p.line([1, 2...
1749307
import logging from components.component import Component logger = logging.getLogger() class Armor(Component): NAME = "armor" """ Component to make an object wearable. """ def __init__(self, armor_category, worn_layer, wearable_body_parts_uid, base_armor_class=0, required_streng...
1749318
from setuptools import setup, find_packages import os HERE = os.path.dirname(__file__) def read_file(filename): with open(os.path.join(HERE, filename)) as fh: return fh.read().strip(' \t\n\r') README = read_file("README.rst") setup( name='mongoquery', version=read_file("VERSION.txt"), classi...
1749332
from .logging import logger import os from . import yaml from .launch import launch, substitute def folder(directory, browser_local): # TODO later migrate to flask based server logger.debug(os.listdir(directory)) url = None if '.problem.yml' in os.listdir(directory): problem = yaml.read(os.pat...
1749333
import panda3d.bullet as pb from direct.showbase.PythonUtil import getBase as get_base from game.nodes.attributes import Connection from game.nodes.nongraphobject import NonGraphObject from game.nodes.componentmetaclass import ComponentMetaClass def get_physics_world(scene): return scene.physics_world def set_...
1749347
import time from datetime import datetime import json import sys import os from argparse import ArgumentParser import signal import logging from kafka import KafkaProducer, KafkaConsumer from kafka.errors import CommitFailedError from digsandpaper.elasticsearch_indexing.index_knowledge_graph import index_knowledge_gra...
1749353
from neupy import layers from neupy.exceptions import LayerConnectionError from base import BaseTestCase class InputTestCase(BaseTestCase): def test_input_exceptions(self): layer = layers.Input(10) error_message = "Input layer got unexpected input" with self.assertRaisesRegexp(LayerConne...
1749370
import argparse import os.path import sys import time from binascii import hexlify, unhexlify from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException from bitcoinrpc.config import read_default_config from pai.pouw.mining.blkmaker import blktemplate from pai.pouw.mining.blkmaker.blkmaker import double_sha25...
1749397
from test_utils import run_query, redshift_connector import pytest def test_voronoi_lines_success(): fixture_file = open('./test/integration/voronoi_fixtures/in/wkts.txt', 'r') points = fixture_file.readlines() fixture_file.close() results = run_query( f"""SELECT @@RS_PREFIX@@processing.ST_VO...
1749420
from collections import Counter #collections #counter + - & | most_common with open('a.txt', 'r') as f: c=Counter() for line in f: line_list=line.split() c+=Counter(line_list) print c.most_common()
1749459
import pytest from buildpg import BuildError, MultipleValues, Renderer, SetValues, UnsafeError, Values, VarLiteral, render args = 'template', 'ctx', 'expected_query', 'expected_params' TESTS = [ {'template': 'simple: :v', 'ctx': lambda: dict(v=1), 'expected_query': 'simple: $1', 'expected_params': [1]}, { ...
1749461
from atom.views import CreateMessageMixin, DeleteMessageMixin, UpdateMessageMixin from braces.views import ( FormValidMessageMixin, PrefetchRelatedMixin, SelectRelatedMixin, UserFormKwargsMixin, ) from cached_property import cached_property from dal import autocomplete from django.urls import reverse_l...
1749468
from git import Repo import re from pathlib import Path from unicodedata import name REPO_ROOT = Path(__file__).parent.parent COZETTE_SFD = REPO_ROOT / "Cozette" / "Cozette.sfd" repo = Repo(REPO_ROOT) last_ver = sorted(repo.tags, key=lambda tag: tag.commit.committed_date)[-1] last_cozette_sfd: str = ( last_ver ...
1749497
import datetime as dt import math import random from itertools import chain from django.conf import settings from django.utils import timezone from django.utils.translation import gettext_lazy as _ from authlib.email import render_to_mail from workbench.accounts.features import FEATURES from workbench.accounts.model...
1749519
from sparknlp.annotator import * class ContextSpellChecker: @staticmethod def get_default_model(): return ContextSpellCheckerModel.pretrained() \ .setInputCols(["token"]) \ .setOutputCol("spell") @staticmethod def get_pretrained_model(name, language,bucket=None): ...
1749536
from collections import namedtuple from math import asin, pi, sqrt BORDER_FACTOR = 0.1 Range = namedtuple('Range', ['start', 'end']) GrpRanges = namedtuple('GrpRanges', ['r', 'ranges']) def range_occupied(curr_ranges, prms): """namedtuple('ObjParams', ['shape', 'r', 'fi', 'args'])""" width = get_angular_wid...
1749547
import json import numpy as np import os import pytest from numpy_encoder import NumpyEncoder, ndarray_hook test_vector = np.array([1.0, 2.0, 3.0]) test_mat = np.eye(3) here = os.path.dirname(os.path.realpath(__file__)) def write_encoded(obj, tdir): fp = tdir.mkdir("sub").join("obj.json") fp.write(obj) ...
1749555
import pytest from addons import * from utils import * tdir = 'Symmetry-Adapted-Perturbation-Theory' def test_SAPT0ao(workspace): exe_py(workspace, tdir, 'SAPT0ao') def test_SAPT0(workspace): exe_py(workspace, tdir, 'SAPT0') @pytest.mark.long def test_SAPT0_ROHF(workspace): exe_py(workspace, tdir, '...
1749563
import unittest from ansible.modules.cloud.google.gcp_forwarding_rule import _build_global_forwarding_rule_dict class TestGCPFowardingRule(unittest.TestCase): """Unit tests for gcp_fowarding_rule module.""" params_dict = { 'forwarding_rule_name': 'foo_fowarding_rule_name', 'address': 'foo_ext...
1749583
from armulator.armv6.opcodes.abstract_opcode import AbstractOpcode class It(AbstractOpcode): def __init__(self, firstcond, mask): super(It, self).__init__() self.firstcond = firstcond self.mask = mask def execute(self, processor): processor.registers.cpsr.set_it(self.firstcond...
1749646
import pytest from sqllineage.exceptions import SQLLineageException from sqllineage.runner import LineageRunner def test_select_without_table(): with pytest.raises(SQLLineageException): LineageRunner("select * from where foo='bar'")._eval() def test_insert_without_table(): with pytest.raises(SQLLin...
1749723
import io import os import random from typing import List, Optional, Text, Tuple import numpy as np import pytorch_lightning as pl import torch from torch.nn.utils.rnn import pad_sequence from torch.utils.data import DataLoader, Dataset, random_split from varclr.data.preprocessor import Preprocessor from varclr.data....
1749726
import os import tensorflow as tf import operator from pathlib import Path from transformers import AutoTokenizer, TFAutoModelForSequenceClassification, AutoConfig from .config import model_params, model_location from .get_weights import Download from .label_mapping import LabelMapping from . import __version__ cl...
1749829
from django.shortcuts import render from django.http import HttpResponse import urllib.request import time import subprocess from django.views.decorators.csrf import csrf_exempt from sim.exceptions import * import traceback SIM_CONTAINER_PORT = '31819' PROJECT_PREFIX = 'openuavapp_' ERROR_LEVEL = 2 def index(request)...
1749832
from django.test import Client from django.urls import reverse def test_main_page(client: Client, main_heading: str) -> None: """This test ensures that main page works.""" response = client.get('/') assert response.status_code == 200 assert main_heading in str(response.content) def test_hello_page(...
1749838
from __future__ import absolute_import, division, print_function try: from builtins import (bytes, str, open, super, range, zip, round, input, int, pow, object) except: pass import matplotlib.pyplot as plt '''Simple pdf plot for quick visual check. ''' colors = ['black', 'red', 'green', 'blue', ...
1749841
import unittest from .base import BaseTestCase class AnswersApiTestCase(BaseTestCase): def test_list_answers_unexpected(self): """ Without JWT authorization header """ response = self.client.get( '/api/v1/questions/answers' ) self.assertEqual(response.status_code, 200)...
1749844
import torch import torch.nn as nn from vq_modules import Encoder, Decoder from vq_modules import VectorQuantizer2 as VectorQuantizer class VQModel(nn.Module): def __init__(self, ckpt_path=None): super().__init__() ddconfig = {'double_z': False, 'z_channels': 256, 'resolution': 256, 'in_c...
1749852
import os def iter_files(base_path): for fn in os.listdir(base_path): yield os.path.join(base_path, fn) def process_dir(base_path, process_func): for fp in iter_files(base_path): process_func(fp)
1749877
from django.contrib import messages from django.db.models import Q from django.http import HttpResponseRedirect from django.urls import reverse_lazy, reverse from django.utils.translation import ugettext_lazy as _ from django.views.generic import ListView, DetailView, View, DeleteView from django.views.generic.detail i...
1749901
import config import boto3 import botocore from flask import Flask from sqlalchemy import create_engine from flask_cors import CORS from model import UserDao, TweetDao from service import UserService, TweetService from view import create_endpoints class Services: pass ################################ # Create...
1749941
class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: minSum = triangle[-1] for i in range(len(triangle) - 2, -1, -1): for j in range(i + 1): minSum[j] = min(minSum[j], minSum[j + 1]) + triangle[i][j] return minSum[0]
1749950
import numpy as np import tensorflow as tf from sleap.nn.system import use_cpu_only use_cpu_only() # hide GPUs for test from sleap.nn.architectures import upsampling from sleap.nn.architectures import resnet from sleap.nn.config import ResNetConfig class ResnetTests(tf.test.TestCase): def test_resnet50(self): ...
1749974
import pytest from memo import memlist, Runner, grid @pytest.mark.parametrize( "kw", [{"backend": "loky"}, {"backend": "threading"}, {"backend": "multiprocessing"}], ) def test_base_multiple_calls(kw): data = [] g = [{"a": 1}] * 100 @memlist(data=data) def count_values(n_jobs=-1, **kwargs): ...
1750012
from pythran.tests import TestEnv from pythran.syntax import PythranSyntaxError class TestNamedParameters(TestEnv): def test_call_with_named_argument(self): self.run_test(""" def foo(a): return a def call_with_named_argument(n): return foo(a=n)""", 1, call_with_named_argument=[int]) def test_...
1750023
from django.contrib import admin from basic.inlines.models import * admin.site.register(InlineType)
1750053
import pytest from tests.factories.tag import ( tag_lazy_marketing, tag_lazy_necessary, tag_lazy_preferences, tag_instant_necessary, ) from tests.factories.trigger import TriggerFactory, TriggerConditionFactory from wagtail_tag_manager.models import ( Tag, Trigger, Constant, Variable, ...
1750060
import asyncio import telepot from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton from bot import public_plugins from message import Message def show_help(num): res = [] t = [] counter = 10 * num for plugin in public_plugins[counter:]: if not plugin['sudo'] and 'usage' ...
1750070
import torch import torch.nn as nn import torch.nn.functional as func from torchsupport.data.io import netwrite from torchsupport.training.training import Training, BasicTraining class RelabelTraining(BasicTraining): """Relabelling training process. Arguments: net (Module) : a trainable network module. t...
1750078
import os from yacs.config import CfgNode as CN import soco_openqa.helper as helper _C = CN() _C.config_name = None # dataset _C.data = CN() _C.data.lang = 'en' _C.data.name = None _C.data.split = None # ranker _C.ranker = CN() _C.ranker.use_cached = True _C.ranker.cached_ranker_file = None ## online ranker if u...
1750129
class EvenOnly(list): def append(self, integer): if not isinstance(integer, int): raise TypeError("Only integers can be added") if integer % 2: raise ValueError("Only even numbers can be added") super().append(integer)
1750134
import execjs import requests import re import random import time class Reply(object): def __init__(self): self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36', ...
1750164
from os import mkdir from os.path import isdir from pathlib import Path from typing import List from guet.committers import Committers2 as Committers from guet.files import FileSystem from guet.steps.preparation import Preparation from guet.util import project_root class LocalFilesInitialization(Preparation): de...
1750177
class INotifyPropertyChanging: """ Notifies clients that a property value is changing. """ def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass PropertyChanging=None
1750226
import struct import GLWindow import ModernGL wnd = GLWindow.create_window() ctx = ModernGL.create_context() prog = ctx.program( ctx.vertex_shader(''' #version 330 in vec2 vert; in vec2 pos; in float scale; in vec3 color; out vec3 v_color; void main() { ...
1750252
from .substructure import * from .similarity import * def PrepareForSearch(db, mol_collection, count_collection, perm_collection): print("Preparing database and collections for search...") AddPatternFingerprints(mol_collection) AddMorganFingerprints(mol_collection, count_collection) similarity.AddRand...
1750289
import numpy as np from sklearn import preprocessing from sklearn import linear_model from sklearn import model_selection input_data = [2, 8, 8, 18, 25, 21, 32, 44, 32, 48, 61, 45, 62] features = preprocessing.scale(input_data) label = np.array(range(13)) (x_train, x_test, y_train, y_test) = model_selection.train_tes...
1750293
import hashlib from datetime import datetime from typing import Dict, List from requests import Session class WallabagAPI: def __init__(self, host: str, user_agent="RSS2Wallabag +https://github.com/Findus23/rss2wallabag", requests_session: Session = None ) -> No...
1750294
import numpy as np from Orange import data def _get_variable(variable, dat, attr_name, expected_type=None, expected_name=""): failed = False if isinstance(variable, data.Variable): datvar = getattr(dat, "variable", None) if datvar is not None and datvar is not variable: raise Valu...
1750323
from typing import Tuple, Union from numpy import array import gdsfactory as gf Coordinate = Union[Tuple[float, float], array] @gf.cell_without_validator def bbox( bbox: Tuple[Coordinate, Coordinate] = ((-1.0, -1.0), (3.0, 4.0)), layer: Tuple[int, int] = (1, 0), top: float = 0, bottom: float = 0, ...
1750358
import cv2 import numpy as np from menpo.image import Image def is_gray(image): r""" Returns True if the image has one channel per pixel. """ return image.ndim < 3 def width_height_divided_by(image, divisor): r""" Returns the height and width of the image divided by a value. """ h, ...
1750367
import random from PIL import Image, ImageDraw size = 256 trial = 100 im = Image.new("RGB", (size, size), 'white') draw = ImageDraw.Draw(im) draw.ellipse((-size, -size, size, size), fill='white', outline='black') for _ in range(trial): x = random.random() y = random.random() s = 4 color ...
1750386
import time from collections import Counter from diora.logging.accumulator import Accumulator from diora.logging.configuration import get_logger class ExperimentLogger(object): def __init__(self): super(ExperimentLogger, self).__init__() self.logger = get_logger() self.A = None s...
1750415
import math print(math.e) # 2.718281828459045 print(2**4) # 16 print(pow(2, 4)) # 16 print(math.pow(2, 4)) # 16.0 print(pow(1 + 1j, 2)) # 2j # print(math.pow(1 + 1j, 2)) # TypeError: can't convert complex to float print(pow(2, 4, 5)) # 1 print(2**0.5) # 1.4142135623730951 print(math.sqrt(2)) # 1.41421356237309...
1750421
from typing import List, Tuple, Dict from torch.utils.data import DataLoader, Dataset from gr_nlp_toolkit.domain.dataset import DatasetImpl from gr_nlp_toolkit.domain.document import Document from gr_nlp_toolkit.processors.abstract_processor import AbstractProcessor import unicodedata from gr_nlp_toolkit.domain.toke...
1750448
import sys import filecmp import subprocess import sys import os # 主函数 def main(): #print(sys.argv[0] + ' ' + sys.argv[1] + ' ' + sys.argv[2]) # 1.将bin文件转成mem文件 cmd = r'python ../tools/BinToMem_CLI.py' + ' ' + sys.argv[1] + ' ' + sys.argv[2] f = os.popen(cmd) f.close() # 2.编译rtl文件 cmd = ...
1750461
import time class War: def __init___(self, war_type, pop_affected, side_one, side_two): self.destructiveness = war_type.bloodiness * pop_affected self.casulties = 0 self.round = 1 self.resolved = False self.side_one = side_one self.side_two = side_two ...
1750464
def fibonacci(n): fib = [1, 1] for i in range(2, n): fib.append(fib[i-1] + fib[i-2]) return fib[-1] for i in range(1,10): print(fibonacci(i))
1750639
from core.advbase import * from slot.a import * def module(): return Elias class Elias(Adv): a3 = ('lo',0.4) conf = {} conf['slots.paralysis.a'] = RR()+Spirit_of_the_Season() conf['acl'] = """ `dragon `s1, fsc `s3, fsc `s2, fsc `s4, fsc `fs, x=4 ...
1750641
import json import os import boto3 print('Loading function') def init(): print('init() enter') my_config = json.loads(os.environ['botoConfig']) from botocore import config config = config.Config(**my_config) global personalize personalize = boto3.client('personalize', config=config) def la...
1750642
from twisted.application.service import Service, IService from twisted.python import filepath from twisted.trial import unittest from axiom.store import Store from axiom.item import Item from axiom.substore import SubStore from axiom.attributes import text, bytes, boolean, inmemory class SubStored(Item): sche...
1750700
import pytest def test_cython_api_deprecation(): match = ("`scipy._lib._test_deprecation_def.foo_deprecated` " "is deprecated, use `foo` instead!\n" "Deprecated in Scipy 42.0.0") with pytest.warns(DeprecationWarning, match=match): from .. import _test_deprecation_call ass...
1750728
import secrets import pytest import trio from libp2p.host.ping import ID, PING_LENGTH from libp2p.tools.factories import host_pair_factory @pytest.mark.trio async def test_ping_once(security_protocol): async with host_pair_factory(security_protocol=security_protocol) as ( host_a, host_b, ): ...
1750744
from multiprocessing import Process import multiprocessing import os import datetime import time import numpy as np from tqdm import tqdm import trilearn.graph from trilearn import set_process as sp from trilearn.distributions import sequential_junction_tree_distributions as seqdist from trilearn.graph import traject...
1750868
import pytest def test_dog1(): assert True def test_dog2(): assert True def test_dog3(): assert True def test_dog4(): assert True def test_dog5_failing(): assert False def test_dog6(): assert True
1750880
import heapq class Solution: def tilingRectangle(self, n: int, m: int) -> int: total_area = n * m dp = [0] * (total_area + 1) for i in range(1, total_area): dp[i] = 1 + min(dp[i - k * k] for k in range(1, int(i ** 0.5) + 1)) height = [0] * m pq = [] for i...
1750882
import torch from mmcv.runner import force_fp32 from torch import nn as nn from typing import List from .furthest_point_sample import (furthest_point_sample, furthest_point_sample_with_dist) from .utils import calc_square_dist def get_sampler_type(sampler_type): """Get the typ...
1750940
import sys from setuptools import setup try: from setuptools_rust import Binding, RustExtension except ImportError: import subprocess errno = subprocess.call([sys.executable, '-m', 'pip', 'install', 'setuptools-rust']) if errno: print('Please install setuptools-rust package') raise Sy...
1751044
from os import environ from launch import LaunchDescription from launch_ros.actions import Node def generate_launch_description(): reporter = Node( package='epas_translator', executable='reporter', parameters=[("/opt/param/"+environ["reporter_param_name"])], remappings=[ ...
1751048
import unittest import torch from torch import nn import torch_testing as tt from all.core import State from all.approximation.feature_network import FeatureNetwork STATE_DIM = 2 class TestFeatureNetwork(unittest.TestCase): def setUp(self): torch.manual_seed(2) self.model = nn.Sequential(nn.Linea...