content
stringlengths
5
1.05M
from pyspark.sql import SparkSession spark = SparkSession \ .builder \ .appName("Python Spark SQL basic example") \ .config("saprk.come.config.option", "som-value") \ .getOrCreate() df = spark.read.csv('mtcars.csv', header=True) df = df.withColumnRenamed("_c0", "car") df.printSchema() df.count() df.s...
import shutil from bs4 import BeautifulSoup import os import random import time import tempfile from flask import Flask, request, render_template, session, jsonify from werkzeug.utils import secure_filename import requests app = Flask(__name__) rust_template = """ #![allow(warnings, unused)] use std::collections::Ha...
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import logging import re from gidgethub import sansio # View handler functions import spackbot.handlers as handlers impo...
from account.models import User from rest_framework import serializers class UserListSerializer(serializers.ModelSerializer): """用户列表序列化器""" class Meta: model = User fields = ['id', 'name', 'cn_name', 'name', 'avatar', 'wx', 'mobile']
def gen_sine_wave(n=1000, s=1, amp=1, wl=1, ns_mean=0, ns_var=1, x_range=(0,1), r_rad=0, swap_axis=False): # n - number of points to generate # s - slope gradient of wave # amp - amplitude of wave # wl - wavelength equivalent parameter # ns_mean, ns_var - noise mean and variance x = np.random.ra...
#!/usr/bin/env python2 while True: p,q = (int(x) for x in raw_input().split()) if p == 0 == q: break res = [] op,oq = p,q while True: if p % q == 0: res.extend([p//q-1, 1]) break res.append(p//q) p,q = q,p%q print "{}/{}=[{}]".format(op,oq...
import time import pytest from redisolar.dao.base import RateLimitExceededException from redisolar.dao.redis.sliding_window_rate_limiter import SlidingWindowRateLimiter TEN_SECONDS = 10 * 1000 # Challenge #7 #@pytest.mark.skip("Remove for challenge #7") def test_within_limit_inside_window(redis, key_schema): ex...
import sys from tkinter import * makemodal = (len(sys.argv) > 1) def dialog(): win = Toplevel() # make a new window Label(win, text='Hard drive reformatted!').pack() # add a few widgets Button(win, text='OK', command=win.destroy).pack() # set destroy callback if...
from typing import Hashable from enum import Enum from typing import List, Set import numpy as np class VariableType(Enum): Pose = "Pose" Landmark = "Landmark" Measurement = "Measurement" class Variable(object): def __init__(self, name: Hashable, dim: int, variable_typ...
import uuid from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from rest_framework import status from rest_framework.authtoken.models import Token from rest_framework.permissions import AllowAny from rest_framework.response imp...
""" ============================ Data set of recurrence plots ============================ A recurrence plot is an image obtained from a time series, representing the pairwise Euclidean distances for each value (and more generally for each trajectory) in the time series. The image can be binarized using a threshold. I...
# Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditi...
import sys if len(sys.argv) == 3: print ('You typed in 2:{} 1:{}'.format(sys.argv[2], sys.argv[1])) else: print ('invalid number of args. argv=[{}]'.format(str(sys.argv)))
import plotly.graph_objects as go graph = go.Figure(data=go.Bar(y=[5, 4, 2, 8, 9])) # bar => balkendiagramm graph.write_html("test.html", auto_open=True)
# -*- test-case-name: axiom.test.test_upgrading.PathUpgrade.testUpgradePath -*- from axiom.attributes import path from axiom.item import Item class Path(Item): schemaVersion = 1 typeName = 'test_upgrade_path' thePath = path()
from os.path import join as pjoin import tensorflow as tf from tensorflow import logging class RunHook(tf.train.SessionRunHook): """ interleave train and eval, periodly save summary """ def __init__(self, iter_dict, eval_steps, train_op, training, holder_handle, summary_conf, summa...
from coati.win32 import copy, execute_commandbar from coati import utils, excel, powerpoint import time import logging import re import abc class AbstractResource(): __metaclass__ = abc.ABCMeta @abc.abstractmethod def merge(self, slide): pass class Chart(AbstractResource): def __init__(self...
import httpx from retrying import retry from bs4 import BeautifulSoup from nonebot import MessageSegment import config @retry(stop_max_attempt_number=5) async def search_color(image_url: str) -> str: """ascii2d的色合搜索 Args: image_url (str): 图片的地址 Returns: str: 处理好可以直接发送的文本 """ ur...
import json from collections import defaultdict from functools import lru_cache from itertools import cycle from pathlib import Path import os import sys import requests moon = cycle('🌑🌒🌓🌔🌕🌖🌗🌘') def parse_int(s): try: return int(s) except ValueError as e: return -1 def get_wd_id(s)...
from mpl_toolkits.mplot3d import Axes3D import numpy as np import pandas as pd import sklearn import seaborn as sns import matplotlib.pyplot as plt from matplotlib import animation job= np.asarray(pd.read_csv('job.csv'))[:,1:] y_train= np.asarray(pd.read_csv('y_train.csv'))[:,1:].reshape(-1,) fig = plt.figure(figsize=...
from .base import * import os import django_heroku DEBUG = False #SECRET_KEY = os.getenv('7_a%kahpfd^nv$5^((5^_cad%cg^pne36ye+r5=!k+$*!!-b)b') ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', '').split(',') django_heroku.settings(locals())
#!/usr/bin/env python # -*- coding: utf-8 -*- # Setup script for PyPI; use CMakeFile.txt to build extension modules import contextlib import os import re import shutil import string import subprocess import sys import tempfile import io import setuptools.command.sdist DIR = os.path.abspath(os.path.dirname(__file__)...
from pprint import pprint from numpy import array, dot, linalg def g(x1, x2): g_1 = x1 * x1 - 3 * x2 * x2 + 5 g_2 = x1 * x1 + 2 * x2 * x2 - 5 return array([g_1, g_2]) def g_(x1, x2): g_11 = 2 * x1 g_12 = -6 * x2 g_21 = 2 * x1 g_22 = 4 * x2 return array([[g_11, g_12], [g_21, g_22]]) ...
from typing import Optional import itertools with open("day_04/input.txt") as file: INPUT = [int(num) for num in file.readline().split(",")] # Consume the empty line file.readline() BOARDS = [ [[int(n) for n in line.split()] for line in board.split("\n")] for board in file.read().spl...
import pytest from organize.constants import ON_HOLD from organize.models import EventApplication, Coorganizer @pytest.fixture def base_application(): return EventApplication.objects.create( date="2080-10-10", city="London", country="Country", latlng='0.0,0.0', main_organi...
import typer app = typer.Typer() @app.command() def create(user_name: str): typer.echo(f"Creating user: {user_name}") @app.command() def delete(user_name: str): typer.echo(f"Deleting user: {user_name}") if __name__ == "__main__": app()
""" Best Approximations """
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
from .instance import BlockchainInstance from .asset import Asset from .amount import Amount from bitsharesbase.operations import ( Operation ) from graphenebase.types import Array class OperationsFee(list): """ Obtain the fee associated with an actual operation :param list operations: list of operat...
# Faça um Programa que peça os 3 lados de um triângulo. # O programa deverá informar se os valores podem ser um triângulo. # Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isósceles ou escaleno. lado_a = int(input('informe o tamanho do lado do triangulo: ')) lado_b = int(input('informe o taman...
import requests import os from colorama import Fore, Style def dirbrute(): print('') print(Fore.GREEN + "[INFO]" + Style.RESET_ALL + " Make sure you do not add Backslash(/) after the URL, Your URL should be : http://example.com or https://example.com") print('') dirb = input(Fore.CYAN + "[DIR-BRUTE]" +...
from ttp import ttp import io import os import re from pathlib import Path import json # dirname = os.path.dirname(__file__) # abspath = os.path.abspath(__file__) # log_file = os.path.abspath(__file__ + "/../../logs/log_file.log") def ios_to_meraki(serial_numbers, USER): dirname = os.path.dirname(__file__) ...
""" 扩展性系统性能 - 垂直扩展 - 增加单节点处理能力 - 水平扩展 - 将单节点变成多节点(读写分离/分布式集群) 并发编程 - 加速程序执行 / 改善用户体验 耗时间的任务都尽可能独立的执行,不要阻塞代码的其他部分 - 多线程 1. 创建Thread对象指定target和args属性并通过start方法启动线程 2. 继承Thread类并重写run方法来定义线程执行的任务 3. 创建线程池对象ThreadPoolExecutor并通过submit来提交要执行的任务 第3种方式可以通过Future对象的result方法在将来获得线程的执行结果 也可以通过done方法判定线程是否执行结束 - 多进程 - 异步I/O """ ...
import tfchain.tests.types.types as tftypes import tfchain.tests.types.fullfillments as tffullfillments import tfchain.tests.types.conditiontypes as tfconditiontypes import tfchain.tests.types.transactions as tftransactions def tests(): tftypes.tests() tffullfillments.tests() tfconditiontypes.tests() t...
# -*- coding: utf-8 -*- import logging from pathlib import Path from django.conf import settings from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.core.files.storage import FileSystemStorage from django.db import models from django.db.models import Q fro...
""" Copyright 2021 Inmanta Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in ...
# Copyright (c) 2021, CRS4 # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribu...
import copy import functools from gettext import gettext as _ from .base import ErrorMessageMixin from .exceptions import BaseValidationException, InvalidDataException, NoData from .fields import Field def partition_dict(d, pred, dict_class=dict): """ Split a dict in two based on a predicate. ``d`` is a dict...
from .classifier import * from .knn import * from .svm import * from .perceptron import * from .naive_bayes import * from .linear_machines import * from .bla import *
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """An interface for holding state and result of revisions in a bisect job. When implementing support for tests other than perf, one should extend this class...
# # Copyright (c) 2019-2020 LG Electronics, Inc. # # This software contains code licensed as described in LICENSE. # from .geometry import Vector, Transform, BoundingBox from .sensor import Sensor from .utils import accepts, ObjectState as AgentState from enum import Enum from collections.abc import Iterable, Callabl...
import csv import os election_csv = os.path.join("PyPoll", "election_data.csv") analysis_output = os.path.join("PyPoll", "election_analysis.txt") voter_id = [] candidates = [] candidate_number = {} winner_vote = 0 results = [] with open(election_csv) as file_in: csvreader = csv.DictReader(file_in) for row in ...
__version__ = '0.0.1' default_app_config = 'locations_jp.apps.AppConfig'
from os import path from subprocess import check_output, PIPE from sys import stderr from yaml import safe_load, dump CONFIG_FILENAME = ".clang-format" def make_default_config(command, style): args = [command, "-dump-config"] + ["-style={}".format(style)] if style else [] config_buffer = check_output(args, ...
import builtins from larval_gonad.mock import MockSnake from larval_gonad.config import read_config builtins.snakemake = MockSnake( input="../../output/paper_submission/fig1_data_avg_tpm_per_chrom.feather", params=dict(colors=read_config("../../config/colors.yaml")), )
from typing import List from fastapi import APIRouter, Depends from database.config import get_db from schemas.car import Model from services.car import ModelService router = APIRouter() @router.get("/get-models", response_model=List[Model]) async def get_models(brand_id: int, db=Depends(get_db)): brands = awa...
# Setup TensorBoardX summary writer. import os import pickle from datetime import datetime import threading HAS_TB = True HAS_GS_ENNV = True HAS_NOTI = True # It's not a major libraries that are in anaconda, so I will check them for you. try: from tensorboardX import SummaryWriter except Exception as e: #impo...
"""Production settings.""" from .base import * # NOQA from .base import env # Base SECRET_KEY = env('DJANGO_SECRET_KEY') ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['{{ cookiecutter.domain }}']) # Databases DATABASES['default'] = env.db('DATABASE_URL') # NOQA DATABASES['default']['ATOMIC_R...
import dataclasses import unittest from unittest import mock from pygame import Surface from ppb import GameEngine, BaseScene, Vector from ppb import events from ppb.systems import System from ppb.systems import Updater from ppb.testutils import Failer from ppb.testutils import Quitter CONTINUE = True STOP = False ...
# vim: sw=4:ts=4:et import json import logging import time import saq from saq.analysis import _JSONEncoder from saq.database import enable_cached_db_connections from flask import Flask, make_response, abort, Response, request from flask_sqlalchemy import SQLAlchemy from sqlalchemy import event from sqlalchemy.engi...
# -*- coding:utf-8 -*- from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from yepes.apps import OverridableConfig class ThumbnailsConfig(OverridableConfig): name = 'yepes.contrib.thumbnails' verbose_name = _('Thumbnails')
import os import sys sys.path.append("../") from cycles import script_A, script_B, script_C def finding_F(t, m, L, gamma): val = 0 for k in range(1, m+2) : val += (L - k + 1) * F_1(t, k, m, L, gamma) return val def F_1(t, k, m, L, gamma) : return_val = 0 if k == 1 : for i1 in range(0, (m + 1) * gamma) : ...
import os.path import sys import random import numpy as np from glob import glob from natsort import natsorted import argparse from tensorflow.keras.models import load_model from attacklib import * from numpy.linalg import norm import tensorflow as tf import pdb def distance(v, u): return norm(v-u) def parse_args(...
import os import re import shutil import siliconcompiler #################################################################### # Make Docs #################################################################### def make_docs(): ''' Magic is a chip layout viewer, editor, and circuit verifier with built in DRC a...
import pytest import numpy as np import ropy.ignition as ign @pytest.mark.parametrize( "point_in, fov, im_shape, point_out", [ ((1, 0, 0), np.pi / 3, (240, 320), (120, 160)), ((3.5, 0, 0), np.pi / 2, (240, 320), (120, 160)), ((1, 0, 0), 1.5 * np.pi, (480, 640), (240, 320)), ((...
import torch.nn as nn from abc import ABCMeta, abstractmethod class Model(nn.Module, metaclass=ABCMeta): @abstractmethod def loss(self): pass
# -*- coding: utf-8 -*- import pytest import rolex import random import mongomock from datetime import datetime from crawlib2 import Status from crawlib2.entity.mongodb import query_builder @pytest.fixture def col(): client = mongomock.MongoClient() db = client["test"] col = db["test_col"] return col...
import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.tensorboard import SummaryWriter import torchvision.utils as vutils import os class Logger: def __init__(self, proc_id, log_dir=".", device="cuda"): self.proc_id = proc_id if proc_id != 0: return ...
import fnmatch import os import shutil import tarfile from multiprocessing.pool import ThreadPool from random import random from time import time from typing import List, Optional from zipfile import ZipFile from pathlib2 import Path from .cache import CacheManager from .helper import StorageHelper from .util import ...
""" Optuna example that optimizes a simple function with Hydra. In this example, we optimize a simple function with hydra's sweeper. You can run this example code as follows: python simple.py --multirun The optimization results in `multirun/` directory, for example `multirun/2021-01-31/19-26-39/optimization_res...
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-08-03 14:03 from __future__ import unicode_literals import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import model_utils.fields class Migration(migrations...
import logging import re import os from contextlib import contextmanager from queue import Queue from threading import Thread from typing import ContextManager, Iterable, Iterator, Optional import tensorflow as tf from tf_bodypix.utils.image import resize_image_to, ImageSize, ImageArray from tf_bodypix.utils.io impor...
from database import Database from flask import Flask, g, render_template app = Flask(__name__) def get_db(): db = getattr(g, '_database', None) if db is None: g._database = Database() return g._database @app.teardown_appcontext def close_connection(exception): db = getattr(g, '_database', No...
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AntMerchantExpandTradeorderRefundResponse(AlipayResponse): def __init__(self): super(AntMerchantExpandTradeorderRefundResponse, self).__init__() self._b...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Created on 2017-09-11 02:55:43 # Project: TapTap from pyspider.libs.base_handler import * DIR_PATH = '/home/xgame/Pictures/TapTap' PAGE_START = 1 PAGE_NUM = 30 GAME_TYPE = ['android_hot', 'ios_hot', 'new_hot', 'reserve', 'played'] PAGE_END = 15 class Handler(BaseHand...
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # Re-export the parent _cext so that every level of the API can get it locally. from .. import _cext
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
import os import unittest from unittest import ( mock, ) from minos.common import ( MinosConfig, ) from tests.utils import ( BASE_PATH, ) class TestMinosConfigWithEnvironment(unittest.TestCase): def setUp(self) -> None: self.config_file_path = BASE_PATH / "test_config.yml" self.config...
special.nctdtr(df, nc, t)
import re def encrypt_data(string): string = string.decode("string_escape") transl = { '70' : '6g', '60' : '5g', '50' : '4g', '40' : '3g', '30' : '2g', 'a' : ':' } tmp_lst = map(lambda x: chr(ord(x) + 1).encode("hex"), st...
# Generated by Django 3.2.5 on 2021-08-08 12:14 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
import os from multiprocessing.pool import Pool from PIL import Image def is_grayscale(fn): img = Image.open(fn).convert('RGB') w, h = img.size for i in range(w): for j in range(h): r, g, b = img.getpixel((i, j)) if r != g != b: return False return Tr...
from typing import Callable from fastapi import FastAPI from ..db.events import ( init_db, close_db ) from ..services.mail.events import init_mail_sender __all__ = [ 'get_startup_handler', 'get_shutdown_handler' ] def get_startup_handler(app: FastAPI) -> Callable: async def start_app() -> None...
from django.contrib import admin from app1.models import Kitap,Yazar admin.site.register(Kitap) admin.site.register(Yazar)
import json def check_in_bounds(limits, val): if val is not None: if val >= limits['min'] and val <= limits['max']: return True return False def check_postures_in_bounds(posture_limits, posture): is_body_angle_in_bound = True is_left_arm_angle_in_bound = True is_right_arm_angl...
# Generated by Django 3.2 on 2021-09-17 10:12 import datetime from django.db import migrations, models import django_mysql.models class Migration(migrations.Migration): dependencies = [ ("greencheck", "0017_create_dailystat"), ] operations = [ migrations.AlterField( model_na...
import torch import torch.nn as nn import torch.nn.functional as F class SparseDropout(nn.Module): def __init__(self, p=0.5): super().__init__() self.p = p def forward(self, x): x_coal = x.coalesce() drop_val = F.dropout(x_coal._values(), self.p, self.training) ...
import numpy as np import matplotlib.pyplot as plt from Berthing_Simulator_PythonCode.Berthing_Simulator_rev04 import BerthingSimulator # Initial setting # ===================================================== L = 175 # [m] d = 8.5 # [m] B = 25.4 # [m] C_b = 0.559 m = (L * B * d) * C_b * 1024 # [kg] x_G...
import torch import torch.nn as nn import torch.nn.functional as F from .flow import Flow, FlowParams eps = 0.000001 class PlanarFlowParams(nn.Module, FlowParams): def __init__(self, dim: int, positive_func: str) -> None: super(PlanarFlowParams, self).__init__() # w components are summed inside t...
import requests import rsa import time import re import random import urllib3 import base64 from urllib.parse import quote from binascii import b2a_hex urllib3.disable_warnings() # 取消警告 def get_timestamp(): return int(time.time()*1000) # 获取13位时间戳 class WeiBo(): def __init__(self,username,password): s...
import cv2 cap = cv2.VideoCapture(0, cv2.CAP_DSHOW) # Haar trained model on frontal faces only; leveraging OpenCV's property to access the classifier face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml") while(True): ret, frame = cap.read() # read frame by frame #...
import numpy as np from imblearn.under_sampling import RandomUnderSampler class DateBasedCV: """ CustomCV handles train, test splits for the ML pipeline based on date. Additionally, it maintains the skew of the whole dataset in each validation fold like stratified K-folds CV. Attributes: ...
from client import DiscorGttsClient from prompt_toolkit import prompt from time import sleep client = DiscorGttsClient('0.0.0.0', 6666) while True: try: message = prompt(':>') client.send_voice_msg(message) except AssertionError: pass
# -*- coding: utf-8 -*- # @Author: Cody Kochmann # @Date: 2018-02-17 10:42:02 # @Last Modified by: Cody Kochmann # @Last Modified time: 2018-02-17 10:59:27 from itertools import islice def first(pipe, items=1): ''' first is essentially the next() function except it's second argument determines how man...
"""Customizable tags for units """ from enum import Enum import suss.gui.config as config class ClusterTag(Enum): SINGLEUNIT = 1 MULTIUNIT = 2 NOISY = 3 STAR = 4 AUDITORY = 5 NONAUDITORY = 6 UserTag = Enum("UserTag", " ".join(config.USERS), module=__name__)
from fetcher.utils import map_attributes def collect_attributes(attributes, mapping, field, value, debug_state=None): collected = {x['attributes'][field]: x['attributes'][value] for x in attributes} return map_attributes(collected, mapping, debug_state) def handle_ak(res, mapping): # collect values ...
# -*- coding: utf-8 -*- # Copyright 2015 Pietro Brunetti <pietro.brunetti@itb.cnr.it> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2....
import os, sys from opt import get_opts import torch from collections import defaultdict import wandb from torch.utils.data import DataLoader from datasets import dataset_dict from eval import eval from rich import print from rich import pretty pretty.install() from rich import traceback traceback.install() # models ...
import matplotlib.pyplot as plt import numpy as np def comparison_result(x, y_set, labels, title, filename): plt.figure(figsize=(16,9)) for i in range(len(y_set)): plt.plot(x, y_set[i], 'o-', linewidth=3, markersize=8, label=labels[i]) # y_square = (x ** 2) * np.log(x) / 100000000 # y_c...
import os.path from pathlib import Path from kivy.properties import ListProperty, ObjectProperty, DictProperty from kivy.uix.button import Button from plyer import filechooser from kv_classes.localization import _ class FileChoose(Button): ''' Button that triggers 'filechooser.open_file()' and processes ...
from django.conf.urls import url from rest_framework.routers import DefaultRouter from rest_framework.urlpatterns import format_suffix_patterns from apps.vadmin.celery.views import IntervalScheduleModelViewSet, CrontabScheduleModelViewSet, PeriodicTaskModelViewSet, TasksAsChoices, \ OperateCeleryTask router = Def...
"""pytest tests for mytoyota.client.MyT using the online services""" import asyncio import pytest # pylint: disable=import-error from mytoyota.client import MyT from mytoyota.exceptions import ToyotaLoginError # pylint: disable=no-self-use class TestMyTOnline: """pytest functions to test MyT using the online...
#------------------------------------------------------------------------------ # Copyright (c) 2013-2019, Nucleic Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. #------------------------------------------------...
def test_rest(make): assert make('$(call rest,1 2 3 4)') == '2 3 4' assert make('$(call rest,1)') == '' assert make('$(call rest,)') == '' def test_chop(make): assert make('$(call chop,1 2 a)') == '1 2' assert make('$(call chop,1 2 a 4)') == '1 2 a' assert make('$(call chop,1)') == '' asser...
from copy import deepcopy from driftdetector import SAMPLE_INTERVAL from driftdetector import Drift from hoeffdingbound import hoeffding_bound from rollingmean import RollingMean from ruletree import RuleTree from driftdetector import ProSeedDriftAlgorithm from driftdetector import SeedDriftAlgorithm BlockCompareConf...
from ex112.utilidadesCeV import moeda, dado p = dado.leiadinheiro('Digite o valor R$:') moeda.resumo(p, 80, 35)
""" --- CRC 计算python代码实现 --- @来源 https://blog.csdn.net/heathy__/article/details/53007037 @注释 在CSDN用户__BOOM__原创代码的基础之上做的修改 @目标:修改为 CRC_CCIT_X_25 (poly=1021,width=16,init=0xffff,xor=0xffff,refin,refout) """ WIDTH = 16 POLYNOMIAL = 0x1021 INITIAL_REMAINDER = 0xFFFF FINAL_XOR_VALUE = 0xFFFF REFIN_FLAG = True REFOUT_...
from pytest_docs.formatter import Formatter class RSTFormatter(Formatter): name = "rst" marker_prefix = "\n**Markers:**" @staticmethod def module_name_format(element): return "\n{}\n{}".format(element, "*" * len(element)) @staticmethod def class_name_format(element): return "...
# -*- coding: utf-8 -*- from .chatclient import *
import os import datetime import jwt from flask import jsonify, request, make_response, Response, json from ..models.models import USER_LIST, UserModels from ..utils.validations import UserValidation from flask_restful import Resource time_now = datetime.datetime.now() class Index(Resource): """ Resource for inde...