content
stringlengths
5
1.05M
# Copyright 2020 Huawei Technologies Co., Ltd # # 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...
# Generated by Django 3.2.5 on 2021-07-30 07:31 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('portal', '0001_initial'), ] operations = [ migrations.RenameField( model_name='author', old_name='first_name', n...
""" Near-replica of example from the readme. """ from pathlib import Path from typeddfs._entries import TypedDfs def run() -> None: """ Runs an example usage of typeddfs. """ # write out a CSV file path = Path("typeddfs-example.csv") contents = "key,value,note\nabc,123" path.write_text(c...
import requests from requests.auth import HTTPBasicAuth import copy # from .params_builder import ParamsBuilder class Api(): def __init__(self,host,username,password,session=None,proxies=None): self.host=host self._username=username self._password=password self.session=session ...
from sklearn.model_selection import train_test_split from sklearn.datasets import fetch_kddcup99, fetch_covtype, fetch_openml, load_svmlight_file from sklearn.preprocessing import StandardScaler, LabelBinarizer import numpy as np import pandas as pd from sklearn.utils import shuffle def fix_dtypes(df): float_cols...
"""The cuDF dropin for Kedro""" try: import cudf # pylint: disable=import-error except ImportError as ex: raise ImportError( "You need to install cuDF before using this dropin. " "See the cuDF documentation at https://rapids.ai/start.html." ) from ex from kedro_dataframe_dropin.core import...
from mpi4py import MPI import numpy as np import tensorflow as tf import time,sys class ParameterServer: def __init__(self, params, rank, num_ps, num_workers): # Set rank of parameter server # rank: 0 ~ number of parameter servers-1 self.rank = rank # Set number of paramete...
# Copyright 2017 Google Inc. 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 required by applicable law or a...
import sqlite3 db = sqlite3.connect('db.sqlite3') cursor = db.cursor() cursor.execute("delete from app1_document") #cursor.execute("update login_logindetails set username='bhupendar' where id = 2") #cursor.execute("update login_logindetails set username='' where id = 1") #cursor.execute("update login_logindetails set...
#!/usr/bin/env python from __future__ import print_function __author__ = 'xinya' from bleu.bleu import Bleu from meteor.meteor import Meteor from rouge.rouge import Rouge from cider.cider import Cider from collections import defaultdict from argparse import ArgumentParser import string import sys reload(sys) sys.setd...
# Generated by Django 2.1.5 on 2019-02-11 19:30 import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('tests', '0001_setup_extensions'), ] operations = [ migrations.CreateModel( ...
from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'btcwallet.settings') #app = Ce...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Advent of Code 2021, day seventeen.""" import re from typing import Optional MAX_ITER = 250 INPUT_FILE = 'data/day_17.txt' INPUT_RE = re.compile(r'target area:\sx=(\d+)\.\.(\d+),\s' r'y=(-?\d+)\.\.(-?\d+)') def simulate(x: int, y: int, ...
import random, string def get_rand_alphanumeric(length: int=6, lowercase: bool=False) -> str: """Return random alphanumeric string""" if lowercase: return ''.join(random.choices(string.ascii_lowercase + string.digits, k=length)) return ''.join(random.choices(string.ascii_uppercase + string.digits...
from collections import defaultdict, namedtuple, OrderedDict from copy import deepcopy from queue import Queue def topology_sort(nodes, src2dsts): def cal_in_degree(): in_degree = {} for node in nodes: in_degree[node] = 0 for src, dsts in src2dsts.items(): for dst i...
"""The tests for the analytics .""" from unittest.mock import patch from openpeerpower.components.analytics.const import ANALYTICS_ENDPOINT_URL, DOMAIN from openpeerpower.setup import async_setup_component MOCK_VERSION = "1970.1.0" async def test_setup(opp): """Test setup of the integration.""" assert await...
import pytest import fakeredis.aioredis from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from starlette.testclient import TestClient from app.main import app from app.db.database import Base from app.dependencies import get_db engine = create_engine('sqlite:///./test.db', connect_args={'...
import tensorflow as tf def mean_squared_error(y, t): loss = tf.reduce_mean(tf.square(y - t)) return loss
from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf from tensorflow import keras from tensorflow.python.keras.callbacks import TensorBoard import numpy as np import pandas as pd import matplotlib.pyplot as plt from time import time #tf.enable_eager_execution() c...
from pathlib import Path, PurePath IGNORED_FILES = {'.gitignore', '_template.md.jinja2', 'README.md'} ROOT_PATH = PurePath(__file__).parents[2] CHANGELOG_ROOT = ROOT_PATH / 'changelog' def list_news_fragments(): """Return a list of files that are probable news fragments.""" changelog_path = Path(CHANGELOG_R...
#!/usr/bin/env python """ Dump EFI cap/fd/rom file """ import sys from rom import ROM def parse_diskfile(filename): print 'Reading %s' % filename with open(filename, 'rb') as f: d = f.read() print 'Parsing %s' % filename r = ROM(d) print r r.showinfo() print 'Dumping %s' % file...
"""Validate Modbus configuration.""" from __future__ import annotations from collections import namedtuple import logging import struct from typing import Any import voluptuous as vol from homeassistant.const import ( CONF_ADDRESS, CONF_COMMAND_OFF, CONF_COMMAND_ON, CONF_COUNT, CONF_HOST, CON...
# Copyright (c) 2019 Riverbed Technology, Inc. # # This software is licensed under the terms and conditions of the MIT License # accompanying the software ("License"). This software is distributed "AS IS" # as set forth in the License. import re from collections import OrderedDict, namedtuple import copy import json ...
import json from messages import * from messages.MessageDeserializer import MessageDeserializer __author__ = 'zadjii' def test_single_message(msg_obj): print 'dict={}'.format(msg_obj.__dict__) msg_json = msg_obj.serialize() print 'json={}'.format(msg_json) copy_msg = MessageDeserializer.decode_msg(msg_...
from flask_login import current_user from datetime import datetime from app.models import Log from app import db def add_log(message, user=current_user, log_type=None): if user and hasattr(user, 'id'): user = current_user.id if log_type is not None and not isinstance(log_type, int): ...
from django.http import Http404 from rest_framework import viewsets from rest_framework.response import Response import logging logger = logging.getLogger(__name__) from .models import OrnamentDevice from .serializers import OrnamentSerializer class OrnamentViewSet(viewsets.GenericViewSet): queryset = OrnamentD...
''' This file performs the automatic testing for all the cases in ......... ''' import numpy as np import glob import os import re import pytest def readstp(fn): f = open(fn, 'r') for i in f: exec(i) f.close() globals().update(locals()) def readin(fn,nin): f = open(fn, 'r') data = f.readlines() re...
# Title: 8진수 2진수 # Link: https://www.acmicpc.net/problem/1212 import sys sys.setrecursionlimit(10 ** 6) read_single_str = lambda: sys.stdin.readline().strip() def solution(o: str): return bin(int(o, 8))[2:] def main(): o = read_single_str() print(solution(o)) if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- # ******************************************************* # ____ _ _ # / ___|___ _ __ ___ ___| |_ _ __ ___ | | # | | / _ \| '_ ` _ \ / _ \ __| | '_ ` _ \| | # | |__| (_) | | | | | | __/ |_ _| | | | | | | # \____\___/|_| |_| |_|\...
#author:Akhil P Jacob #HLDynamic-Integrations import sqlite3 def dmlLite_create(dbname,query): try: conn = sqlite3.connect(dbname) c = conn.cursor() c.execute(query) except: return ("HLEngine:Couldnt create DB "+dbname) def dmlLite_insert(dbname,query): try: conn =...
#!/usr/bin/env python3 from reporter.emailing import ( RECIPIENT_CARDIOMET_ADMIN as RECIPIENT_ADMIN ) from reporter.uhl_reports.civicrm.enrolment_dq import ( DuplicateStudyIdReport, MissingStudyNumber, MultipleRecruitementsReport, CivicrmInvalidCaseStatus ) CASE_TYPE_ID = 24 class...
from pandac.PandaModules import Point3, VBase3, Vec4, Vec3 objectStruct = {'Objects': {'1156371286.47luzd0': {'Type': 'Building Interior','Name': '','Instanced': True,'Objects': {'1165344228.45kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(8.11, -10.046, 0.0),'Scale'...
import docx from docx.shared import Cm from docx.shared import Pt from PIL import Image, ImageDraw from io import BytesIO from docx.shared import RGBColor recordset = [{'Qty':3,'Name':'Fish','Desc':'Tom'}, {'Qty':8,'Name':'Cheese','Desc':'Jerry'}, {'Qty':5,'Name':'Bacon','Desc':'Garfield'}] ...
from __future__ import unicode_literals TEST_TAG_LABEL = 'test-tag' TEST_TAG_LABEL_EDITED = 'test-tag-edited' TEST_TAG_COLOR = '#001122' TEST_TAG_COLOR_EDITED = '#221100' TEST_TAG_INDEX_HAS_TAG = 'HAS_TAG' TEST_TAG_INDEX_NO_TAG = 'NO_TAG' TEST_TAG_INDEX_NODE_TEMPLATE = ''' {{% for tag in document.tags.all %}} {{% if ...
""" This script contains function snippets for different training settings """ import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.tensorboard import SummaryWriter import numpy as np from easydict import EasyDict from visualDet3D.utils.utils import LossLog...
from polyaxon.config_manager import config INTEGRATIONS_DISCORD_WEBHOOKS = config.get_dict('POLYAXON_INTEGRATIONS_DISCORD_WEBHOOKS', is_list=True, is_optional=True, is_local=T...
from __future__ import absolute_import from time import time from .exceptions import RestartFreqExceeded class restart_state(object): RestartFreqExceeded = RestartFreqExceeded def __init__(self, maxR, maxT): self.maxR, self.maxT = maxR, maxT self.R, self.T = 0, None def step(self): ...
from bounds import UniformBounds from pulp import * from utils_io import * from utils import * from engine import Bounds from multiprocessing import cpu_count import pulp import pulp_encoding import engine import numpy as np # --- class LpLinearMetric (UniformBounds): """ Basic class to represent any linear metr...
from subprocess import call from os.path import join import argparse import logging import sys import constants as ct import os from os.path import abspath, dirname # Directories BASE_DIR = abspath(join(dirname(__file__))) logger = logging.getLogger('xgboost') def config_logger(args): # Set file log_file = sy...
# Generated by Django 2.0.9 on 2018-12-06 08:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('branch', '0003_auto_20181206_0826'), ] operations = [ migrations.RemoveField( model_name='hostfamily', name='next_ye...
#!/usr/bin/python3 uniq_add = __import__('2-uniq_add').uniq_add my_list = [1, 2, 3, 1, 4, 2, 5] result = uniq_add(my_list) print("Result: {:d}".format(result))
from numpy.random import rand from math import sqrt from sys import argv def distance(array1, array2): assert len(array1) == len(array2), "Arrays must be of the same dimension" return sqrt(sum([(array2[i] - array1[i])**2 for i in range(len(array1))])) if __name__ == '__main__': dim = int(argv[1]) assert...
from os.path import join as oj import numpy as np import pandas as pd '''Helper functions for dataset.py. To do: - any variable transformations or superfluous vars? - outcome vars: HospHeadPosCT, Intub24Head, Neurosurgery, DeathTBI, PosIntFinal, any else... ...
import sys import os curPath = os.path.abspath(os.path.dirname(__file__)) rootPath = os.path.split(curPath)[0] sys.path.append(rootPath) import argparse from util.calculateFissionsAndFusions import calculateFissionAndFussions def main(): """ Fissions Fussions number """ parser = argparse.ArgumentPars...
from setuptools import setup from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst')) as f: long_description = f.read() setup( name='libtf', version='0.1.2', license='MIT', author='Threshing Floor Security, LLC', author_email='info@threshingfloo...
import os from AdminSecurity import AdminSecurity from MiscUtils.DataTable import DataTable class DumpCSV(AdminSecurity): def filename(self): """Overidden by subclasses to specify what filename to show.""" return None def awake(self, trans): AdminSecurity.awake(self, trans) ...
import string import datetime import os text = raw_input("Full file path for sensor files:") #get path if not os.path.exists(text+"\\\\results"): # create results folder os.makedirs(text+"\\\\results") results = open(text+"\\\\results\\\\results.txt", "a") # create results txt file for file in os.lis...
# -*- coding: utf-8 -*- import os import traceback import tomli import utils_env from utils_ver import print_ver # 缓存全局的环境 DATA = {} def get_data() -> dict: """ 获取签到的配置文件。 :return: 签到配置文件对象 """ print_ver() global DATA if DATA: return DATA if check_config := os.getenv("CHE...
""" Steam and Leaf Plot ------------------- This example shows how to make a steam and leaf plot. """ # category: other charts import altair as alt import pandas as pd import numpy as np np.random.seed(42) # Generating random data original_data = pd.DataFrame({'samples': np.array(np.random.normal(50, 15, 100), dtype=n...
import matplotlib.pyplot as plt with open("beni.ciz", "r") as f: readsamples = f.readlines() samplerate = float(readsamples[0]) time = [] samples = [] for t, sample in enumerate(readsamples[1:]): time.append(t / samplerate) samples.append(float(sample)) plt.plot(time, samples) plt....
""" Regression test for general EOS 1D Riemann problems. """ # Modules import logging import sys import numpy as np import scripts.utils.athena as athena import scripts.utils.comparison as comparison from scripts.utils.RiemannSolver.riemann import riemann_problem from .eos_riemann import _tests, _thresh, _states sys.p...
# # Copyright (C) Foundry 2020 # import getpass import os import pathlib import sys import tempfile import yaml from PySide2.QtCore import QCoreApplication from PySide2.QtWidgets import (QApplication, QDialog, QErrorMessage, QHBoxLayout, QMessageBox, QProgressDialog) import flix_ui as ...
#!/usr/bin/env python # coding: utf-8 # # UNSUPERVISED FEATURE SELECTION FOR TIME-SERIES SENSOR DATA # - Evaluation based comparision with PCA, IPCA, AND variation-trend-relationship-capture algorithm within MSDA package # In[ ]: We test PCA/IPCA/MSDA on one of Alibaba cloud virtual machine’s data containing t...
#from gym.envs.registration import register # # #register( # id="objcollection-v0", # entry_point="gym_objcollection.envs:ObjCollectionEnv", # timestep_limit=50) import logging from gym.envs.registration import register logger = logging.getLogger(__name__) register( id='objcollection-v0', entry_poin...
from django.contrib import admin # Register your models here. from .models import Picture,Category admin.site.register(Picture), admin.site.register(Category)
import time import os import subprocess import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from nw_util import * from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common import utils chrome_options = Options() chrome_optio...
from typing import Any, Collection, Type def value_invalid_msg(name: str, value: Any, valid_values: Collection[Any],) -> str: return f"`{name}` value = {value} is invalid; value must be one of {valid_values}." def type_invalid_msg(name: str, val_type: Type, valid_val_type: Type,) -> str: return f"`{name}` t...
import mysql.connector as mysql from script import get_isbn_details db = mysql.connect(host = 'libmgmt.heliohost.us', user = 'libmgmt', password = 'nevermindmf', database = 'libmgmt_bookstore') cur = db.cursor() def add_book(): # Get ISBN # Print exisiting details from ISBN # Details from ISBN Author PubYe...
def threshold_adjustment(threshold, highlow, **kwargs): if (threshold <= -10000) or (threshold == 0): output = highlow else: output = threshold return output
# Copyright 2013 by Richard Olsson # # 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 writ...
import unittest #Write the import statement for the Die class from src.homework.homework9.die import Die class TestHomework9(unittest.TestCase): def test_rolls_values_1_to_6(self): ''' Write a test case to ensure that the Die class only rolls values from 1 to 6 ''' self.rolling = ...
from django.contrib import admin from .models import WordLog # Register your models here. admin.site.register(WordLog)
#!/usr/bin/env python from __future__ import print_function import random import sys import re def roll(n=1, d=6): result = [] for i in range(1, n+1): result.append(random.randint(1, d)) return result def main(): n = 1 d = 6 for arg in sys.argv[1:]: try: n, d = ar...
from django.apps import AppConfig class WagtailShellTestAppConfig(AppConfig): label = "wagtail_shell_test" name = "wagtail_shell.test" verbose_name = "Wagtail Shell tests"
#!/usr/bin/env python3 """Parse prices of a device from the Geizhals website.""" import logging import re from enum import Enum from bs4 import BeautifulSoup import requests _LOGGER = logging.getLogger(__name__) _REGEX = r'\D\s(\d*)[\,|\.](\d*)' class Domain(Enum): """Possible localisations.""" AT = 'geizh...
class MockGeoserverCatalogueWorkspace: def __init__(self, name): self.name = name class MockGeoserverCatalogueStyle: def __init__(self, name, workspace): self.name = name self.style_format = 'sld10' self.workspace = MockGeoserverCatalogueWorkspace(name=workspace).name class M...
'''配置文件''' import os '''定义一些颜色''' BLACK = (0, 0, 0) WHITE = (255, 255, 255) BLUE = (0, 0, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) YELLOW = (255, 255, 0) PURPLE = (255, 0, 255) SKYBLUE = (0, 191, 255) '''游戏素材路径''' BGMPATH = os.path.join(os.getcwd(), 'resources/sounds/bg.mp3') ICONPATH = os.path.join(os.getcwd(), 'r...
from __future__ import division, print_function import numpy as np import cPickle as pickle import os, glob import argparse from utils import models from utils.sample_helpers import JumpProposal, get_parameter_groups from enterprise.pulsar import Pulsar from enterprise import constants as const from PTMCMCSampler.PT...
## Automatically adapted for numpy.oldnumeric Jul 23, 2007 by import numpy.oldnumeric as Numeric import numpy class Grid3D: """Class to represent 3D discret volumetric data. The data has to be a Numeric array od shape 3 """ def __init__(self, data, origin, stepSize, header, crystal=None): asser...
from app.models import Comments,User from app import db def tearDown(self): Review.query.delete() User.query.delete() def test_save_comment(self): self.new_comment.save_review() self.assertTrue(len(Comment.query.all())>0)
# Copyright (c) 2018-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # # Adapted from fairseq-py import torch import torch.nn as nn import torch.nn.functional as F class LayerNorm(nn.Module): ...
import sys from ipam.models import RouteTarget from startup_script_utils import load_yaml, pop_custom_fields, set_custom_fields_values from tenancy.models import Tenant route_targets = load_yaml("/opt/netbox/initializers/route_targets.yml") if route_targets is None: sys.exit() optional_assocs = {"tenant": (Tena...
from typing import List, Set from neuralmonkey.evaluators.evaluator import Evaluator class F1Evaluator(Evaluator[List[str]]): """F1 evaluator for BIO tagging, e.g. NP chunking. The entities are annotated as beginning of the entity (B), continuation of the entity (I), the rest is outside the entity (O). ...
from __future__ import annotations from restdoctor.utils.pydantic import convert_pydantic_errors_to_drf_errors def test_convert_pydantic_errors_to_drf_errors(): pydantic_errors = [ {'loc': ('created_at',), 'msg': 'invalid datetime format', 'type': 'value_error.datetime'}, {'loc': ('field_a',), 'm...
import pandas as pd import os import sys import numpy as np from math import log from nltk import bigrams, trigrams from collections import Counter, defaultdict from scipy.stats import entropy #from scipy.special import softmax, rel_entr from datetime import datetime, timedelta class BigramModel: def __init__(se...
# Copyright 2018 Jeremy Whipple # Copyright 2018 Simon Redman # Copyright 2018 Michael Zhang # # 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...
from settings import * memberfile = open("clustering/membership.dat","r") members = dict() for line in memberfile: key = line.strip().split()[0] val = line.strip().split()[1] members[int(key)]=int(val) memberfile.close() for time in range(START_IDX,NUM_TIMES): infile = open("local_models/time-"+str(time)+".m...
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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 ...
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # Author : Li Jixue # Date : 2017/6/27 # Description: sftp下载上传 # ------------------------------------------------------------------------------ import os import paramiko def ssh(host, port, username, password, cm...
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
from dataclasses import dataclass from pathlib import PurePath from injector import inject from core_get.configuration.project_directory_finder import ProjectDirectoryManager from core_get.configuration.serialization.toml_serializer import TomlSerializer from core_get.file.file_system import FileSystem from core_get....
import torch torch.set_grad_enabled(False) import logging import math from glob import glob from os import path import torch.nn as nn from cached_conv import use_buffer_conv from effortless_config import Config from termcolor import colored logging.basicConfig(level=logging.INFO, format=colored("[%(relativeCreated)....
#Write a python script to print convert a number into str type x= str(4) print(x)
from dataclasses import dataclass @dataclass class Response: doc_id: int uri: str
import psycopg2, time from core.utils import api_message from core.config import AppState class PGDatabase: def connect_to_api(self) -> bool: for i in range(2, 6): try: AppState.Database.CONN = psycopg2.connect( host=AppState.Database.HOST, ...
class OnLogRecord(object): """Trigger a callback when a certain log record is found. Parameters ---------- record_name : str The record name to check. """ def __init__(self, record_name): self.record_name = record_name def __call__(self, log): return bool(log.curre...
# Copyright 2017 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. def PostUploadHook(cl, change, output_api): """git cl upload will call this hook after the issue is created/modified. This will add extra trybot coverag...
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] square = lambda x: x * x cube = lambda x: x * x * x [print(x, '\tsquare: ', square(x), ' cube: ', cube(x)) for x in l]
from models.user import User from models.tweet import Tweet from utils import log from flask import ( request, Blueprint, redirect, url_for, session, jsonify, ) from routes import ( login_required, current_user, ) main = Blueprint('ajax_tweet', __name__) @main.route('/index', method...
from .abc import ( Model, ) from .declarative import ( DeclarativeModel, MinosModel, ) from .dynamic import ( BucketModel, DataTransferObject, DynamicModel, ) from .fields import ( Field, ModelField, ) from .serializers import ( AvroDataDecoder, AvroDataEncoder, AvroSchemaDec...
import math import sys BOARD_TRANS = {-1: '-', 1: 'x'} def chess2ord(a): return ord(a[0]) - ord('a'), int(a[1]) - 1 def ord2chess(a): return chr(a[0] + ord('a')), str(a[1] + 1) def check_horizontal(board, ipos, ix, y): moves = [] for x in range(ix - 1, -1, -1): px, py = ord2chess((x, y)) ...
def unique(l: list): """Return sorted unique elements in a list >>> unique([5, 3, 5, 2, 3, 3, 9, 0, 123]) [0, 2, 3, 5, 9, 123] Example solution: # line 1 st = set(l) # line 2 lst = list(st) # line 3 lst = lst.sort() # line 4 return lst """ # Please print...
from Board import Board from Board import Card from BestFirstSolitaire import BestFirstSolitaire from BestFirstSolitaire import TAB_TO_FOUND from BestFirstSolitaire import TAB_TO_STOCK from BestFirstSolitaire import STOCK_TO_TAB from BestFirstSolitaire import STOCK_TO_FOUND from BestFirstSolitaire import TAB_TO_TAB fro...
from PIL import Image import glob import os def rotate(image_path, degrees_to_rotate, saved_location): """ Rotate the given photo the amount of given degrees, show it and save it @param image_path: The path to the image to edit @param degrees_to_rotate: The number of degrees to rotate the image @p...
# coding: utf-8 """ ASN.1 type classes for the online certificate status protocol (OCSP). Exports the following items: - OCSPRequest() - OCSPResponse() Other type classes are defined that help compose the types listed above. """ from __future__ import unicode_literals, division, absolute_import, print_function f...
from Crypto.Util.number import * size = 2048 rand_state = getRandomInteger(size // 2) def keygen(size): q = getPrime(size) k = 2 while True: p = q * k + 1 if isPrime(p): break k += 1 g = 2 while True: if pow(g, q, p) == 1: break g +=...
"""devtool config junk""" import logging import os import yaml from ftplib import FTP LOG = logging.getLogger(__name__) DIMENSION_DIRS = { -1: 'DIM-1/region', 0: 'region', 1: 'region', 1001: 'DIM1001/region' } class Config(object): """Config object Used by basically every actionable object i...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from . import transponder_pb2 as transponder_dot_transponder__pb2 class TransponderServiceStub(object): """ Allow users to get ADS-B information and set ADS-B update rates. """ def __init__(self, channel): """Constructor...
# get_config is made available by jupyter notebook c = get_config() # noqa: F821 c.ServePostProcessor.port = 0
import pymysql def get_connection(host, user, pwd, database_name): return pymysql.connect(host, user, pwd, database_name)