id
stringlengths
3
8
content
stringlengths
100
981k
9877971
import logging from django.db import models from django.db.models import ForeignKey from django.utils import timezone from django_rq import get_queue from extras.choices import JobResultStatusChoices from .abstract import BigIDModel logger = logging.getLogger(f"netbox_config_backup") class BackupJob(BigIDModel): ...
9877977
import re import sublime_plugin try: # Python 3 from .haxe_generate_code_helper import * except (ValueError): # Python 2 from haxe_generate_code_helper import * class HaxeGenerateGetSet(sublime_plugin.WindowCommand): @staticmethod def poll(ctx): view = ctx.view cmds = [] i...
9877998
from topaz.module import ClassDef from topaz.objects.numericobject import W_NumericObject class W_IntegerObject(W_NumericObject): classdef = ClassDef("Integer", W_NumericObject.classdef)
9878032
from __future__ import absolute_import, division, print_function import numpy as np import pandas as pd from itertools import product import units import moments def _format_obs_history(obs_history, field, save_to_disk=None): """ Parameters ---------- obs_history : Pandas.DataFrame field : Pandas.D...
9878099
from ._title import Title from plotly.graph_objs.heatmapgl.colorbar import title from ._tickformatstop import Tickformatstop from ._tickfont import Tickfont
9878164
from shinytest import ShinyTestCase class TestArea(ShinyTestCase): def test_create_area(self): from shinymud.models.area import Area area = Area.create({'name': 'foo'}) #make sure that the area exists in the world self.assertTrue(self.world.area_exists('foo')) a = self.worl...
9878198
import json import os.path import sys from datalabs.operations.edit.editing import editing sys.path.append( os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../")) ) @editing( name="britishize_americanize", contributor="xl_augmenter", task="Any", description="This transformation...
9878228
import glob import io import logging import os import tarfile from multiprocessing import Pool from typing import Optional, Union import pandas import requests from pydantic import Field, HttpUrl from typing_extensions import Literal from openff.evaluator.datasets.curation.components import ( CurationComponent, ...
9878233
import os import pickle import numpy as np def cifar10_download(dst='cifar10'): from six.moves import urllib import tarfile if not os.path.exists(dst): os.makedirs(dst) path = 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' filepath, _ = urllib.request.urlretrieve(path, './') ...
9878247
from bc4py.config import V, P, stream from bc4py.database import obj from logging import getLogger import asyncio log = getLogger('bc4py') loop = asyncio.get_event_loop() async def system_safe_exit(): """system safe exit method""" log.info("start system stop process") try: P.F_STOP = True ...
9878277
import base64 from IPython.display import Image, display def state_diagram(graph): """Plot a state diagram for a graph. See http://mermaid-js.github.io/mermaid/#/Tutorials?id=jupyter-integration-with-mermaid-js Example: state_diagram( '''stateDiagram-v2 s1 : (1) Primary surger...
9878343
import argparse import tensorflow as tf from model import inceptionv1 from dataloader import load parser = argparse.ArgumentParser() parser.add_argument( "--channels", type=int, default=10, help="Number of channels in the dataset." ) parser.add_argument("--epochs", type=int, default=120) parser.add_argument("--b...
9878347
import logging import grpc from google.protobuf import empty_pb2 from sqlalchemy.sql import func from couchers import errors from couchers.constants import GUIDELINES_VERSION, TOS_VERSION from couchers.crypto import cookiesafe_secure_token, hash_password, verify_password from couchers.db import session_scope from cou...
9878403
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import mplfinance as mpl plt.rcParams['legend.facecolor'] = 'darkgray' ############################## STOCKS DATA ############################## def process_stocks(path): data = pd.read_csv('Raw Data/stocks_data.csv', par...
9878420
from mednorm.datasets.base import CsvDatasetConverter class TacConverter(CsvDatasetConverter): def __init__(self, dataset_path, dataset_name=None): super(TacConverter, self).__init__( dataset_path=dataset_path, dataset_name=dataset_name, sep='\t', input_col=1, target_col=2, header=...
9878448
from numpy import array import scipy.sparse as sp from vec4ir.base import match_bool_or def test_matching(): X = array([[0,0,1], [0,1,0], [0,1,1], [1,0,0], [1,0,1], [1,1,0]]) assert (match_bool_or(X, array([[0,0,0]])) == array([])).all() assert (match_bool_or(X, array([[0,0,1]])) == array([0, 2, 4]))....
9878454
from base_regression import BasicRegression from utils.metrics import mean_squared_error import numpy as np class LinearRegressionGD(BasicRegression): """Linear regression with gradient descent optimizer.""" def _loss(self, theta): X, y = self.X, self.y loss = (1.0 / 2) * mean_squared_error(y...
9878470
import json import sys sys.path.insert(0, '') from TypeRacerStats.config import MAIN_COLOR from TypeRacerStats.file_paths import SUPPORTERS_FILE_PATH from TypeRacerStats.Core.Common.accounts import check_account def load_supporters(): with open(SUPPORTERS_FILE_PATH, 'r') as jsonfile: supporters = json.loa...
9878486
import base64 import pytest from emrichen import Context, Template from emrichen.tags.compose import Compose CONTEXT = {'thing': 'world'} def test_compose_tag(): comp = Compose( { 'tags': ['Base64', 'Format'], 'value': 'hello {thing}', } ) ctx = Context(CONTEXT) ...
9878501
import requests from plugins.oob import verify_request, gen_oob_domain # Vuln Base Info def info(): return { "author": "cckuailong", "name": '''The Button Generator WordPress plugin < 2.3.3 - RFI''', "description": '''The Button Generator WordPress plugin before 2.3.3 within the wow-compa...
9878579
from PaginaWeb import PaginaWeb from SitioWeb import SitioWeb #Se crea decorador el cual recibe la funcion buscador la cual manda la pagina a buscar y el objeto sitio web def buscarD(f): def new_function(a, b): paginas = [] for i in range(0, len(b.paginas)): paginas.append(b.paginas[i]....
9878582
import socks import socket temp_socket = socket.socket temp_create_connection = socket.create_connection def disable_proxy(): socket.socket = temp_socket socket.create_connection = temp_create_connection def enable_proxy(host="127.0.0.1", port=9050): def create_connection(address, timeout=None,...
9878602
from __future__ import print_function import logging import plotly from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.views.generic import TemplateView from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.http import J...
9878609
import pygame def load(): # path of player with different states PLAYER_PATH = ( 'flappy_bird/images/redbird-upflap.png', 'flappy_bird/images/redbird-midflap.png', 'flappy_bird/images/redbird-downflap.png' ) # path of background BACKGROUND_PATH = 'flappy_bird/images/backgr...
9878610
from app import app_config, kafka_consumer, kafka_producer import requests import os import json import datetime def get_abuse_blacklist(): abuse_blacklist = set() if os.path.isfile('data/abuse_blacklist.txt') == False: print (app_config.abuse_blacklist_url) r = requests.get( app_config.abuse_...
9878632
import torch.nn as nn import pytest import numpy as np from test.utils import convert_and_test class LayerLogSigmoid(nn.Module): """ Test for nn.layers based types """ def __init__(self): super(LayerLogSigmoid, self).__init__() self.sig = nn.LogSigmoid() def forward(self, x): ...
9878705
from torch.utils.data import Dataset class MyTensorDataset(Dataset): def __init__(self, *tensors, transforms=None): if transforms: assert tensors[0][0].dim() == 3 # Only Images for now self.transforms = transforms assert all(tensors[0].size(0) == tensor.size(0) for tensor in ...
9878723
import pandas as pd from matplotlib import pyplot import os os.chdir('/Desktop/web_scraping/') data=pd.read_csv('final_movie_details.csv') # plot pyplot.scatter(data['imdb'],data['metascore']) pyplot.show() # plot pyplot.scatter(data['metascore'],data['votes']) pyplot.show() # We can see a bit of linear relationship...
9878760
import re import sys import time from datetime import date, datetime from decimal import Decimal, localcontext from .otypes import OrientRecordLink, OrientRecord, OrientBinaryObject from .exceptions import PyOrientBadMethodCallException try: import pyorient_native binary_support = True except: binary_suppor...
9878792
def method1(ll: list) -> list: def swap(i, j): ll[i], ll[j] = ll[j], ll[i] def heapify(end, i): l = 2 * i + 1 r = 2 * (i + 1) max = i if l < end and ll[i] < ll[l]: max = l if r < end and ll[max] < ll[r]: max = r if max != i: ...
9878811
import platform import os def get_platform(): """Return the current OS platform. For example: if current os platform is Ubuntu then a string "ubuntu" will be returned (which is the name of the module). This string is used to decide which platform module should be imported. """ # linux_distrib...
9878840
from dnsdumpster import DNSDumpsterAPI import socket import binascii ''' ############################################ # SUBDOMAINS # ############################################ ''' def subdomains_search(host): dnsdumpster_data = DNSDumpsterAPI.DNSDumpsterAPI().search(host) ret...
9878843
import argparse import os os.environ['CUDA_VISIBLE_DEVICES'] = '0' import torchvision.datasets as datasets import tensorflow as tf from utils import preprocess_for_eval from pnasnet import build_pnasnet_large, pnasnet_large_arg_scope slim = tf.contrib.slim parser = argparse.ArgumentParser() parser.add_argument('--va...
9878874
from distutils import version from typing import Tuple def version_key(version_tuple: Tuple[str, int]): return (version.LooseVersion(version_tuple[0]), version_tuple[1])
9878918
from django.core.urlresolvers import reverse from django.test.client import Client from main.tests.test_base import MainTestCase from main import views class TestBasicHttpAuthentication(MainTestCase): def setUp(self): MainTestCase.setUp(self) self._create_user_and_login(username='bob', password='...
9878920
from setuptools import setup with open("README.md", "r") as fh: long_description = fh.read() setup( name = 'lifestream', version = '0.0.18', description = 'The fastest way to make sense of a transaction log.', py_modules = ["lifestream"], package_dir = {'': 'src'}, install_requires = [ ...
9878925
import requests import json from dotenv import load_dotenv import os load_dotenv() band_token = os.getenv('BAND_TOKEN') band_key = os.getenv('BAND_KEY') # Get Post def get_post(): get_post_url = 'https://openapi.band.us/v2/band/posts' return json.loads(requests.get( get_post_url, params={ ...
9878933
import itertools import types import unittest from cupy.testing import _bundle from cupy.testing import _pytest_impl def _param_to_str(obj): if isinstance(obj, type): return obj.__name__ elif hasattr(obj, '__name__') and isinstance(obj.__name__, str): # print __name__ attribute for classes, f...
9878949
import torch def sample_joint(simulator, prior, n=1): r"""""" inputs = prior.sample(torch.Size([n])).view(n, -1) outputs = simulator(inputs) return inputs, outputs def joint_sampler(simulator, prior): r"""""" yield sample_joint(simulator, prior, n=1) def sample_marginal(simulator, prio...
9878951
from boto.s3.connection import S3Connection import boto from boto.s3.key import Key from socket import gaierror from ConfigParser import NoOptionError import settings import logger l = logger.setup(__name__) def connect(): """ Return a connected S3 bucket based on settings in config.cfg. """ # Red...
9878998
from statuscheck.services.bases._statuspageio import BaseStatusPageAPI class ServiceAPI(BaseStatusPageAPI): name = "ServiceMax" domain_id = "jtvt0b51c5wy" status_url = "https://servicemax.statuspage.io/" service_url = "https://www.servicemax.com/"
9879013
from guillotina import configure from guillotina._settings import app_settings from guillotina.catalog.utils import reindex_in_future from guillotina.component import query_adapter from guillotina.component import query_utility from guillotina.interfaces import ICatalogUtility from guillotina.interfaces import IContain...
9879029
from armulator.armv6.opcodes.abstract_opcodes.strb_immediate_thumb import StrbImmediateThumb from armulator.armv6.opcodes.opcode import Opcode from armulator.armv6.bits_ops import zero_extend from armulator.armv6.arm_exceptions import UndefinedInstructionException class StrbImmediateThumbT2(StrbImmediateThumb, Opcode...
9879057
import os import ssl import json import time import pandas as pd from tqdm import * from selenium import webdriver class ImageCrawler(object): SETTINGS = { 'baidu': {'url': 'https://image.baidu.com/search/index?tn=baiduimage&word=${KEYWORD}', 'see_more': None, 'xpath'...
9879076
from typing import Tuple import os import argparse import math import tensorflow as tf import json from tqdm import tqdm def _bytes_feature(value): """Returns a bytes_list from a string / byte.""" if isinstance(value, type(tf.constant(0))): value = value.numpy() # BytesList won't unpack a string from an EagerT...
9879090
import jwe from website import settings SENSITIVE_DATA_KEY = jwe.kdf(settings.SENSITIVE_DATA_SECRET.encode('utf-8'), settings.SENSITIVE_DATA_SALT.encode('utf-8')) def ensure_bytes(value): """Helper function to ensure all inputs are encoded to the proper value utf-8 value regardless of input type""" if isins...
9879095
import setuptools import json setuptools.setup( name='fairing', version='0.0.3', author="<NAME>", description="Easily train and serve ML models on Kubernetes, directly from your python code.", url="https://github.com/wbuchwalter/fairing", packages=setuptools.find_packages(), package_data={}...
9879137
import json import boto3 import logging import os from boto3.dynamodb.conditions import Key, Attr logger = logging.getLogger() logger.setLevel(logging.INFO) dynamodb_client = boto3.client('dynamodb') s3_client = boto3.client('s3') cloudformation_client = boto3.client('cloudformation') dynamodb_client = boto3.client...
9879152
import core.globals # Gain access to global objects from remi.gui import * # Import all REMI GUI Elements class Container(Container): def __init__(self, AppInst=None, *args, **kwargs): super().__init__(*args, **kwargs) self.AppInst = AppInst self.userI...
9879187
import pytest from autocnet.examples import get_path from autocnet.graph.network import CandidateGraph from autocnet.io.network import load import numpy as np import pandas as pd @pytest.mark.xfail(strict=True) def test_save_project(tmpdir, candidategraph): path = tmpdir.join('prject.proj') candidategraph.s...
9879210
import ocean import sys def exceptionMsg() : print("Expected error: %s" % str(sys.exc_info()[1])) def failTest(command) : try : eval(command) except : exceptionMsg() A = ocean.asTensor([[1+2j,3+1j],[1,2+2j]],ocean.gpu[0]) print(A) print(ocean.maximumAbs(A)) failTest("ocean.maximumAbs([[]])")
9879213
from rest_framework import serializers class GeoCodeSerializer(serializers.Serializer): address = serializers.CharField(required=True)
9879223
import tensorflow as tf import numpy as np import PIL.Image import time import functools import os import copy from rotation import rotation_tensor, extensive_rotation_tensor def vgg_layers(layer_names): """ Creates a vgg model that returns a list of intermediate output values.""" # Load our model. Load pretra...
9879240
import os from os import path import numpy as np import autofit as af test_path = path.join("{}".format(path.dirname(path.realpath(__file__))), "files", "path") class TestJson: def test__numpy_array_to_json__output_and_load(self): if path.exists(test_path + "array_out.json"): os....
9879247
import os os.environ['CUDA_VISIBLE_DEVICES'] = '0' import cv2 import keras import numpy as np import matplotlib.pyplot as plt import albumentations as A # Data loader and visualization functions # helper function for data visualization def visualize(**images): """PLot images in one row.""" n = len(images) ...
9879306
import os import shutil import capnp def remove_dir_content(path): """Remove content of the directory but not the directory itself""" for item in os.listdir(path): p = os.path.join(path, item) if os.path.isdir(p): shutil.rmtree(p) else: os.unlink(p) def fresh...
9879311
import cv2 import numpy as np class CRect(object): def __init__(self, tL, bR): self.tL = tL self.tR = (bR[0], tL[1]) self.bL = (tL[0], bR[1]) self.bR = bR self.top = tL[1] self.bottom = bR[1] self.left = tL[0] self.right = bR[0] self.width = b...
9879325
from generate_text import train_keras, generate_keras import os DIR = os.path.dirname(os.path.abspath(__file__)) train_keras(maxlen=40, batchsize=64, num_words=5000, num_units=128, epochs=1, mode='length', file='poem', len_min=0, ...
9879349
import logging from typing import List import lxml import re from django.db import transaction from django.urls import resolve, Resolver404 from django.urls import reverse from tkapi.persoon import Persoon as TKPersoon from tkapi.document import Document as TKDocument from tkapi.document import DocumentSoort as TKDo...
9879393
from .utils import split import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.feature_extraction.text import CountVectorizer from sklearn.pipeline import FeatureUnion, Pipeline from sklearn.preprocessing import FunctionTransformer from learn.transformers import ( ...
9879413
import unittest import pysam from Bio.Seq import Seq from Bio import SeqIO from Bio.Alphabet import generic_dna from Bio.SeqRecord import SeqRecord from scripts.seq_classes import allele, checkORF,classify class test_checkORF(unittest.TestCase): def tearDown(self): """ This method is calle...
9879425
import responses from compal import Compal def load_login_responses(ip): # Response required by constructor responses.add( responses.Response( method="GET", url=f"http://{ip}/", status=302, headers={"Location": "../common_page/login.html"}, ) ...
9879494
import json import demistomock as demisto from FeedIntegrationErrorWidget import get_feed_integration_errors def test_get_feed_integration_errors(mocker): ''' Given: - Integration search result which contains the following: - Enabled feed integration instance with error - Feed...
9879548
from setuptools import setup, find_packages setup( name='cf-helloworld', version='1.0', description='CF Python Hello World', install_requires=[ 'flask>=0.11', 'gunicorn>=19.0'], packages=find_packages() )
9879563
import psycopg2 class ArkDB: def __init__(self, db, u, pw, pk): self.connection = psycopg2.connect( dbname = db, user = u, password= pw, host='localhost', port='5432' ) self.PublicKey = pk self.BlockPublicKey = '\\x' + ...
9879593
import sys, os import numpy as np import pandas as pd import ujson from scipy.interpolate import interp1d import scipy.ndimage from ast import literal_eval from get_workflow_info import get_workflow_info project_name = "planetary-response-network-and-rescue-global-caribbean-storms-2017" # st thomas DG #ssid = 1475...
9879594
import dominate as dm from dominate import tags as tg def base_html(): """ Create home page of TimeFlow. """ doc = dm.document(title="TimeFlow", doctype="<!DOCTYPE html>") doc.head += tg.meta(charset="UTF-8") doc.head += tg.link( rel="css/styles.css", type="text/css", href="static/css/...
9879599
import logging import pytest import salt.states.file as filestate log = logging.getLogger(__name__) @pytest.mark.skip_on_windows(reason="Do not run on Windows") def test__find_keep_files_unix(): keep = filestate._find_keep_files( "/test/parent_folder", ["/test/parent_folder/meh.txt"] ) expected ...
9879618
from pathlib import Path import importlib class LibUtil: @staticmethod def home(root_folder=".falconcv") -> Path: usr_folder = Path.home() home_folder = usr_folder.joinpath(root_folder) home_folder.mkdir(exist_ok=True) return home_folder @classmethod def models_home(cl...
9879668
import numpy as np from bokeh.plotting import figure, save from bokeh.layouts import gridplot N = 10000 x = np.random.normal(0, np.pi, N) y = np.sin(x) + np.random.normal(0, 0.2, N) p1 = figure(output_backend="webgl") p1.circle(x, y, fill_alpha=0.1) p2 = figure(output_backend="webgl") p2.circle(x, y, fill_alpha=0.1...
9879669
import traceback def round_up(x, d): return (x + d - 1) // d * d def get_traceback(pos=None): if pos is None: return "\n\n".join(traceback.format_stack()) return traceback.format_stack(limit=10)[pos]
9879683
import logging from handlers.upstream import Upstream from handlers.dummy import DummyResponse, ExceptionResponse from handlers import is_uuid, CDE, CDE_PATH import calibre, devices, postprocess import features def _process_books_on_device(device, book_ids): # need to better express this, without exposing device.bo...
9879733
import logging log = logging.getLogger('features.resources') import struct import path import common.asynchttp as asynchttp import util.net as net import util.callbacks as callbacks import util.primitives.funcs as funcs def default_feature_location(): import stdpaths return stdpaths.userdata / 'features' cla...
9879741
from django import forms from django.utils.text import slugify from django.utils.translation import ugettext as _ from .models import Badge, SkillName, Skill ############################################################################# class SkillSearchForm(forms.Form): LEARN = 'LEA' TEACH = 'TEA' PARTNE...
9879796
import datetime import feedparser from actstream import follow from django.contrib.auth.models import User from django.contrib.sites.models import Site from django.core.urlresolvers import reverse from django.test import TestCase from committees.models import Committee from laws.models import Law, PrivateProposal, Bi...
9879860
import numpy as np import numpy.ma as ma from numpy.testing import assert_array_equal import netCDF4 import pytest from cloudnetpy.cloudnetarray import CloudnetArray from cloudnetpy import utils from cloudnetpy.metadata import MetaData @pytest.fixture(scope='session') def fake_nc_file(tmpdir_factory): """Creates ...
9879879
import json import logging import math import os import re import socket from collections import defaultdict, Counter from datetime import datetime from os import mkdir, makedirs, getpid from time import perf_counter import h5py import torch from numbers import Number from os.path import join, exists, dirname from typ...
9879895
from battle_city.basic import Direction from uuid import UUID, uuid4 from pygame import Rect from battle_city.collections.sliced_array import SlicedArray class Monster(object): id = None # type: UUID direction = Direction.UP speed = 0 is_freeze = False position = None # type: Rect old_posi...
9879916
import os import re searchDir = '/Users/jessebeach/code/quailjs/quail/lib/assessments' exclude = ['.git', 'node_modules','bin'] os.chdir(searchDir) for root, dirs, files in os.walk(searchDir): dirs[:] = [d for d in dirs if d not in exclude] for f in files: if re.match(r'[a-z]', f): fullPat...
9879980
import numpy as np import pandas as pd import eggplant as eg import torch as t import unittest import gpytorch as gp from . import utils as ut from matplotlib.pyplot import ioff class TestBaseGP(unittest.TestCase): def test_init_model_default( self, ): model_input = ut.create_model_input() ...
9879986
from ...simulator.m68k import M68K from ...core.opcodes.opcode import Opcode from ...core.util import opcode_util from ..enum.op_size import OpSize import binascii class Simhalt(Opcode): pass class Simhalt(Opcode): def __init__(self): pass # Nothing to initialize: SIMHALT is parameterless def a...
9880036
import json class Record: startRegister = 0 endRegister = 1 numberOfRegisters = 2 description = 'L1 to Earth' recordType = 'Single' address = '' dataValue = '' units = '' def __init__(self, startRegister, numberOfRegisters, description, recordType = None, units = ''): ...
9880084
from typing import List import pytest from repokid.datasource.access_advisor import AccessAdvisorDatasource from repokid.datasource.iam import ConfigDatasource from repokid.datasource.iam import IAMDatasource from repokid.datasource.plugin import DatasourcePlugin @pytest.fixture(autouse=True) def purge_datasources(...
9880106
import torch import fast_multihead_attn class MaskSoftmaxDropout(torch.autograd.Function): @staticmethod def forward(ctx, is_training, heads, inputs, pad_mask, mask_additive, dropout_prob): heads_t = torch.tensor([heads]) dropout_prob_t = torch.tensor([dropout_prob]) null_tensor = tor...
9880123
import cv2 import sys def play_video(cap): is_paused = False while (cap.isOpened()): if not is_paused: ret, frame = cap.read() if ret: cv2.imshow('Frame', frame) key = cv2.waitKey(25) if key == 113: break elif key == 3...
9880133
from sublime_plugin import WindowCommand class DeviotHideConsoleCommand(WindowCommand): """ Hide the deviot console Extends: sublime_plugin.WindowCommand """ def run(self): self.window.run_command("hide_panel", {"panel": "output.deviot"})
9880157
from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages tests_require = [ ] version = '0.0.0' try: import ec2_costs version = ec2_costs.__version__ except ImportError: pass setup( name='ec2-costs', version=version, packages=find_packages(), insta...
9880166
import json import os from jsonschema import validate from draco.run import run from draco.helper import read_data_to_asp from draco.js import cql2asp EXAMPLES_DIR = os.path.join("examples") class TestFull: def test_output_schema(self): json_files = [ os.path.join(EXAMPLES_DIR, fname) ...
9880199
from rest_framework import serializers from rest_framework import fields from cigar_example.app import models from django.db.models.base import get_absolute_url class CigarSerializer(serializers.ModelSerializer): manufacturer_id = fields.WritableField() url = fields.URLField(source='get_absolute_url', read_on...
9880200
SAVE_SOLUTIONREF = { "test_phreeqpython_nahco3_cacl2_closed_open": [ { "I": 0.004936849508865382, "pH": 8.122771293869038, "sc": 427.3184913000945, "temperature": 25.0, "mass": 1.0000005199749562, "pe": 9.753221298383908, "p...
9880203
import pbge import gears import pygame import copy import random class MSRPBlock(object): def __init__(self, model, width=360, **kwargs): self.model = model self.width = width self.image = pbge.render_text(pbge.BIGFONT, "${:,}".format(model.cost), width, ...
9880212
class Solution(object): def isSubsequence(self, s, t): """ :type s: str :type t: str :rtype: bool """ i, j = 0, 0 while i < len(s) and j < len(t): if s[i] == t[j]: i += 1 j += 1 return i == len(s) if __name__ ==...
9880246
def test_no_elision_on_call(): import requests '''TEST requests.get$ @. get() @. get(url) @! ... …(url) status: ok '''
9880254
import turtle make = turtle.Pen() turtle.bgcolor('mistyrose') #You can change the bg to your fav color colors = ["red", "orange", "yellow", "green", "blue", "purple", "gray", "brown", "aqua", "sea green"] your_name = turtle.textinput("Waiting for your Input :) ", "Enter Something or it will return nothing :D") s...
9880273
import pyb start = pyb.millis() count = 0 while True: pyb.disable_irq() m = pyb.millis() u = pyb.micros() & 0x7fffffff pyb.enable_irq() m2 = u // 1000 if m2 != m: if m2 != (m + 1) or (u % 1000) > 100: print("msec %d usec %d" % (m, u)) count += 1 if (m - start...
9880356
from twisted.internet import reactor import dds import twistedds class TestProtocol(object): def connectionMade(self): print 'connection made!' def messageReceived(self, msg): print 'message received:', msg def connectionLost(self, reason): print 'connection lost! reason:...
9880383
from mopidy_local import Extension def test_get_default_config(): ext = Extension() config = ext.get_default_config() assert "[local]" in config assert "enabled = true" in config def test_get_config_schema(): ext = Extension() schema = ext.get_config_schema() assert "library" in sche...
9880438
from behave import given from typing import Any @given('successful execution of the "{pipeline_name}" data pipeline') def step_impl(context: Any, pipeline_name: str) -> None: if pipeline_name in context.pipeline_results.keys(): assert context.pipeline_results[pipeline_name] is True else: raise Exception(...
9880505
def balancepar(string): s=[] for i in string: if i in "({[": s.append(i) elif i == ")": if(not s or s[-1]!="("): return False s.pop() elif i == "}": if(not s or s[-1]!="{"): return False s.pop() ...
9880516
import os from typing import Optional, Union import yaml config: Optional[dict[str, dict[str, Union[str, int, bool]]]] = None '''全局配置字典''' def config_init(): ''' 初始化读取配置文件,需要在所有项目之前启动 ''' global config with open('config.yml', 'r', encoding='utf-8') as f: cfg = f.read() config = y...