content stringlengths 5 1.05M |
|---|
import datetime
import os
import motor
from tornado import gen
from tornado.options import options as opts
from motor_blog.api import coroutine, rpc
from motor_blog.text.link import media_link, absolute
class Media(object):
"""Handle XML-RPC calls related to images and other media.
Mixin for motor_blog.api... |
# encoding:utf-8
'''
@Author: catnlp
@Email: wk_nlp@163.com
@Time: 2018/7/10 14:26
'''
from E_util.alphabet import Alphabet
from E_util.functions import *
import sys
START = '</s>'
UNKNOWN = '</unk>'
PADDING = '</pad>'
class Config:
def __init__(self):
self.MAX_SENTENCE_LENGTH = 250
self.MAX_WOR... |
"""Base class for checks.
"""
__author__ = 'vovanec@gmail.com'
class BaseCheck(object):
"""Base class for checks.
"""
NAME = None
def __init__(self, check_config, log):
"""Constructor.
:param dict check_config: implementation specific check config.
:param (str) -> None log:... |
# Generated by Django 2.0.4 on 2018-11-05 11:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('periodicals', '0023_department_boolean_on_article'),
]
operations = [
migrations.AddField(
model_name='publication',
... |
import pdb
import random
import time
import logging
import json
from locust import TaskSet, task
from . import utils
dim = 128
logger = logging.getLogger("milvus_benchmark.runners.locust_tasks")
class Tasks(TaskSet):
@task(100)
def query(self):
op = "query"
X = utils.generate_vectors(self.pa... |
from pygoa.util import dump_assoc_frequencies, MRGOAFrecCounter
from pygoa import GOAssocSnapshot, GOSnapshot
def main():
sp = GOSnapshot()
assoc = GOAssocSnapshot(sp)
dump_assoc_frequencies(assoc, "assoc_freqs.txt")
job = MRGOAFrecCounter.run()
if __name__ == "__main__":
main()
|
from camctrl import app
if __name__ == '__main__':
app.run(debug=False,host='0.0.0.0',threaded=True,processes=1,port=5100)
# app.run(debug=True,host='0.0.0.0',threaded=True,processes=1,port=5100)
# app.run(host='0.0.0.0:5100')
|
# -*- coding: utf-8 -*-
import numpy as np
class Gm(object):
"""Gm calculator"""
def __init__(self, **kwargs):
"""init"""
allowed_kwargs = {"Id", "Vg"}
for k in kwargs:
if k not in allowed_kwargs:
raise TypeError('Unexpected keyword argument '
... |
class Solution:
def checkZeroOnes(self, s: str) -> bool:
i = 0
cnt0 = 0
cnt1 = 0
result0 = 0
result1 = 0
while i < len(s):
if s[i] == '0':
cnt0 += 1
cnt1 = 0
if s[i] == '1':
cnt1 += 1
... |
from dfm_functions import *
import argparse
parser = argparse.ArgumentParser()
# ~~~~Arguments~~~~~ #
parser.add_argument("-m", "--manifest", type=str,
help="The relative path of the manifest used to download the data")
parser.add_argument("-n", "--metadata", type=str,
help="The... |
import time
from bibliopixel.animation.circle import Circle
from bibliopixel.colors import COLORS
class ArcClock(Circle):
def __init__(self, layout, **kwds):
super().__init__(layout, **kwds)
self.hands = [
{
'rings': [0, 1],
'color': COLORS.... |
# Automatic Dice Roller
# Written by Georgia Wyatt
from random import randint
print ("Automatic Dice Roller")
print ("Press enter to roll")
import random
def roll_dice(): #Roll dice function
roll = random.randint(1,6)
print("You rolled a %d " % roll)
print("Press enter twice to roll again")
print... |
from neat import GreensTree
from _physiology import *
import numpy as np
def getGreensTree(morph_name, physiology_type='Pas', recompute=False, freqs=None):
if freqs is None:
freqs = np.array([0.])
if morph_name[-4:] == '.swc':
morph_name = morph_name[:-4]
# load a greenstree
greens_t... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 6 15:15:00 2015
@author: martasd
"""
from random import sample, seed
from math import log, ceil
from pybel import Smarts, readstring
pept_bond = Smarts("[$([NX3H2,NX4H3+]),$([NX3H](C)(C))][CX4H]([*])[CX3](=[OX1])[OX2H,OX1-,N]")
seed(2345)
min_size = 50
max_size = 100... |
def shape(A):
num_rows = len(A)
num_cols = len(A[0]) if A else 0 # número de elementos na primeira linha
return num_rows, num_cols
def get_row(A, i):
return A[i] # A[i] já é da linha A[i] é linha i-ésimo
def get_column(A, j):
return [A_i[j] # j-ésimo elemento da linha A_i
for ... |
import unittest
from unittest import mock
from motey.communication.apiserver import APIServer
from motey.communication.communication_manager import CommunicationManager
from motey.communication.mqttserver import MQTTServer
from motey.communication.zeromq_server import ZeroMQServer
from motey.models.image import Image
... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
import os
here = os.path.abspath(os.path.dirname(__file__))
# Get the long description from the README file
with open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description... |
from collections import Counter
from functools import partial
from random import Random
import pytest
from plenum.common.messages.internal_messages import NeedViewChange
from plenum.common.messages.node_messages import ViewChange, NewView
from plenum.server.consensus.batch_id import BatchID
from plenum.server.consens... |
from dl_plus import ytdl
from dl_plus.extractor import Extractor, ExtractorError, ExtractorPlugin
urljoin = ytdl.import_from('utils', 'urljoin')
__version__ = '0.1.1'
plugin = ExtractorPlugin(__name__)
class GoodGameBaseExtractor(Extractor):
DLP_BASE_URL = r'https?://(?:www\.)?goodgame\.ru/'
_API_BASE... |
from .mock import JsBackchannelServer, JvmBackchannelServer, JvmServer
from Tutkain.api import edn
from Tutkain.src import repl
from Tutkain.src import settings
from Tutkain.src import state
from concurrent import futures
import sublime
import sys
import textwrap
import types
import unittesting
import unittest
clas... |
from typing import List
from aibolit.types_decl import LineNumber
class NonFinalArgument:
def __init__(self):
pass
def value(self, filename: str) -> List[LineNumber]:
"""
Returns the line numbers of the file name which contains no final arguments
:param filename: name of the f... |
import unittest
import web3
from web3.middleware.geth_poa import geth_poa_middleware
from web3.providers.rpc import HTTPProvider
class TestEthereumNode(unittest.TestCase):
w3: web3.Web3
@classmethod
def setUpClass(cls) -> None:
# requires that the docker compose in infra is running
cls.w... |
"""hold the properties of a button"""
from enum import Enum
import utils.Colors as Colors
import pygame
class Type(Enum):
MENU = 1
PLAY = 2
SETTINGS = 3
MAP_MAKER_SLB = 4 #SLB : SAVE LOAD BACK
class ButtonPrefab:
def __init__(self):
self.button_map = {
Type.MENU : {
"s... |
#!usr/bin/python
i = 1
while i <= 12:
j = 1
while j <= 12:
print '%4d' % (j * i),
j += 1
print
i += 1
'''num = 1
while num <= 10:
i = 1
while i <= 10:
product = num * i
print num, " * ", i, " = ", product
i = i + 1
print("\n")
num = num + 1'''
|
from export_result import *
from generate_candidates import *
from generate_rules import *
from itertools import repeat
from load_database import *
from prune_itemsets import *
from timeit import default_timer
def apriori():
"""Performs the Apriori algorithm."""
# Load database and read in the support and co... |
from kubessh.authentication.ldap import LDAPAuthenticator
# Make sure this exists
c.KubeSSH.host_key_path = 'dummy-kubessh-host-key'
c.KubeSSH.debug = True
c.KubeSSH.authenticator_class = LDAPAuthenticator
c.KubeSSH.authenticator_class.ldap_servers = [ 'dc01.ncsa.tech', 'dc02.ncsa.tech' ] |
from numpy.random import RandomState
class ExperienceReplayBufferParameters:
""" Parameters to configure an experience replay buffer. """
def __init__(
self,
max_experiences: int = 50,
minimum_experiences_to_start_predicting: int = 32,
batch_size: int = 32,
random_stat... |
# -*- coding: utf-8 -*-
from imma_conversions import float1, float2
TABLE_C0 = [
(1, int, 4, 'YR', 'year UTC', 1600, 2024, '(AAAA)'),
(2, int, 2, 'MO', 'month UTC1', 1, 12, '(MM)'),
(3, int, 2, 'DY', 'day UTC1', 1, 31, '(YY)'),
(4, int, 4, 'HR', 'hour UTC1', 0, 23.99, '0.01 hour (Δ GG)'),
(5, floa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from http.server import BaseHTTPRequestHandler
import threading
import csv
import os
import gzip
import requests
import io
import re
import redis
import socket
# import logging
import coloredlogs, logging
from termcolor import colored
# logging.basicConfig(level=logging.I... |
#!/usr/bin/env python3
#-*-coding:utf-8-*-
'''
不同操作系统底层实现不同,文件系统不同
os模块可以帮助我们屏蔽操作系统的差异
'''
import os
print(os.getcwd())#返回当前目录,脚本所在目录
os.chdir('/home/shuguoqing')#改变工作目录,相当于cd命令
print(os.getcwd())#工作目录被改变
print(os.listdir('.'))#列出目录下所有文件和目录
os.mkdir('new')#在工作目录下新建一个目录
os.makedirs('new/a/b')#在工作目录下新建多层目录
os.chdir('n... |
'''
A driver for Databear on the MDL
'''
from pymdl.utilities import gpioconfig
class dbdriver:
def __init__(self):
'''
Create a new driver instance
Could load a config file here...
'''
#Map DataBear ports to hardware ports
self.ports = {
'port0':'',
... |
# Generated by Django 2.2.6 on 2019-10-11 01:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('eval', '0003_auto_20191009_0913'),
]
operations = [
migrations.AlterField(
model_name='pregunta',
name='tipo',
... |
import sys, getopt
import numpy as np
import tensorflow_hub as hub
import tensorflow_text
from app.main.lib.shared_models.shared_model import SharedModel
from app.main.lib.similarity_measures import angular_similarity
class UniversalSentenceEncoder(SharedModel):
def load(self):
model_path = self.options.g... |
def echo(msg):
return 'bot: echoing ' + msg['msg']
|
# from https://www.floydhub.com/explore/templates/reinforcement-learning/gym-retro
import matplotlib.pyplot as plt
from matplotlib import animation
def save_frames_as_gif(frames, filename=None):
"""
Save a list of frames as a gif
"""
patch = plt.imshow(frames[0])
plt.axis('off')
def animate(i)... |
from urllib.parse import urlparse
from cms.categories.models import (Category, CategorySubSite, PublicationType,
PublicationTypeSubSite)
from cms.core.blocks import PublicationsBlocks
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.db import model... |
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from vulk.math.matrix import Matrix4
from vulk.graphic.model import MeshPart
class Renderable():
def __init__(self):
self.world_transform = Matrix4()
self.mesh_part = MeshPart()
self.material = None
self.environment = None
self.shader = None
|
from abc import ABC, abstractmethod
import bm3d
import numpy as np
import torch
import torch.nn as nn
import torch.nn.init as init
class Denoiser(ABC):
"""Represents a trained denoiser."""
@abstractmethod
def forward(self, noisy_image):
"""Takes a noisy image as input, returns a denoised version... |
--- setup.py 2006-04-25 00:34:28.000000000 +0200
+++ setup.py.new 2007-04-15 23:21:45.000000000 +0200
@@ -13,9 +13,12 @@
'pgi', 'rend', 's3', 'sgis', 'sgix', 'sgi', 'sunx',
'sun', 'win']
-glew_extensions = [Extension('glew', ['src/glew.pyx'], libraries=libs)]
+glew_extensions = [Extensio... |
from boa3.compiler.compiler import Compiler
from boa3.exception.InvalidPathException import InvalidPathException
class Boa3:
"""
The main class.
Contains the methods that the final user have access to.
"""
@staticmethod
def compile(path: str) -> bytes:
"""
Load a Python file t... |
# -*- coding: utf-8 -*-
"""
Test missing headers in XLSForm.
"""
from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
class MissingHeaders(PyxformTestCase):
"""Test missing headers in XLSForm
When survey and choices columns are missing headers, it is helpful to see
an error message that prompts... |
from sty import Pin
from sty import UART
import sty
import _thread
# ---------------------------------------------------------------
# On-Board LEDs
# ---------------------------------------------------------------
led1 = sty.LED(1)
led2 = sty.LED(2)
led3 = sty.LED(3)
# ----------------------------------------------... |
#!/usr/bin/python
import os
import time
import getpass
#=== Config ==============================================================================================
framerate = "24"
startDay = "20160201"
stopDay = "20190128"
textSize = "100" #
resolution = "1080x720" # 1080x720|
originalRes ... |
# Copyright 2020-2021 Leibniz Information Centre for Economics
#
# 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 applic... |
from .menu import *
from .commenting import *
|
#!/usr/bin/env python
# Notes:
# - Used by lk_json_from_xml_schema in core.sh
# - Not intended to be invoked directly
import xmlschema
import sys
schema = None if len(sys.argv) < 2 else sys.argv[1]
xml = sys.stdin.read() if len(sys.argv) < 3 else sys.argv[2]
converter = xmlschema.XMLSchemaConverter(
preserve_roo... |
"""Generate a diffusion stencil
Supports isotropic diffusion (FE,FD), anisotropic diffusion (FE, FD), and
rotated anisotropic diffusion (FD).
The stencils include redundancy to maintain readability for simple cases (e.g.
isotropic diffusion).
-div Q A Q^T grad u
Q = [cos(theta) -sin(theta)]
[sin(theta) cos(the... |
import math
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
def make_model(args, parent=False):
return MODEL(args)
class Scale(nn.Module):
def __init__(self, init_value=1e-3):
super().__init__()
self.scale = nn.Parameter(torch.FloatTensor([init_value]))
def ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import copy
from xnas.search_space.cell_based import *
# from xnas.search_space.cell_based import _MixedOp
from torch.autograd import Variable
'''
Darts: highly copyed from https://github.com/khanrc/pt.darts
'''
class PCDartsCNNController(nn.Module)... |
from . import discord, main
|
#!/usr/bin/env python
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
from math import ceil
from time import time
import numpy as np
import cupy as cp
import fire
import h5py
from numba ... |
"""
Configuration for docs
"""
def get_context(context):
context.brand_html = "Sales Tax Reports"
|
from app.data.skill_components import SkillComponent
from app.data.components import Type
from app.engine import equations, action, item_funcs, static_random, skill_system
from app.engine.game_state import game
class Ability(SkillComponent):
nid = 'ability'
desc = "Give unit an item as an extra abilit... |
#!/usr/bin/env python
# run:
# python3 -mvenv ../ve3
# ../ve3/bin/pip install wheel
# ../ve3/bin/pip install --editable .
# ../ve3/bin/ag-pserver --listen tcp:8001 --controller tcp:localhost:8002
# the provisioning webpage is in html/index.html , edit it in place
from setuptools import setup
import os
setup(
... |
import streamlit as st
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import glob
import PIL
import pandas as pd
import numpy as np
from typing import Dict
# define layout
st.beta_set_page_... |
import os
import sys
import subprocess
import pytest
def flake8_lint(args):
print('Running flake8 code linting...')
result = subprocess.call(['flake8'] + args)
print('flake8 failed.' if result else 'flake8 passed.')
return result
sys.path.append(os.path.dirname(__file__))
pytest.main()
|
from pytest import fixture
@fixture
def authorization_required(settings):
settings.REQUIRE_AUTHORIZATION = True
@fixture
def no_authorization_required(settings):
settings.REQUIRE_AUTHORIZATION = False
|
import socket
import threading
import argparse
import json
import hashlib
import traceback
from pathlib import Path
from datetime import datetime
from hashlib import sha256
import gc
import torch
from getconfig import config, setting_info
from utils import *
from gpt2generator import GPT2Generator
from interface imp... |
import time
from collections import defaultdict
import pyglet
import copy
import matplotlib.pyplot as plt
import itertools
from torch.utils.tensorboard import SummaryWriter
import torch as th
from torch.utils.data import Dataset, DataLoader
import numpy as np
import yaml
from datetime import datetime
from boxLCD.utils ... |
# Generated by Django 3.0.7 on 2021-04-03 12:01
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('location_register', '0021_auto_20210330_1650'),
('business_register', '0078_auto_20210330_1650'),
]
operati... |
from enum import Enum
class TokenType(Enum):
ENCLOSED = 1
NOT_ENCLOSED = 2
def is_enclosed(token):
return token[0] == TokenType.ENCLOSED
class Parser:
def __init__(self, open_symbol="{", close_symbol="}", allow_escape=True):
self.open_symbol = open_symbol
self.close_symbol = close_... |
from dataclasses import dataclass
@dataclass
class Skill:
name: str
level: int
filled: bool = False
@dataclass
class Contributor:
name: str
n_skills: int
skills: [Skill]
used: bool = False
@dataclass
class Project:
name: str
days: int
score: int
before: int
n_roles: ... |
# This an autogenerated file
#
# Generated with RegularWaveLoading
from typing import Dict,Sequence,List
from dmt.entity import Entity
from dmt.blueprint import Blueprint
from .blueprints.regularwaveloading import RegularWaveLoadingBlueprint
from typing import Dict
from sima.riflex.kinematicsinwavezone import Kinemati... |
from __future__ import annotations
import statistics
from enum import Enum
from typing import Generator
from typing import Iterable
SCORES = {")": 3, "]": 57, "}": 1197, ">": 25137}
PAIR_SCORES = {"(": 1, "[": 2, "{": 3, "<": 4}
PAIRS = {"(": ")", "[": "]", "{": "}", "<": ">"}
OPEN = {"(", "[", "{", "<"}
class Sco... |
from __future__ import annotations
import inspect
import os
from collections.abc import Mapping, Iterable
from typing import Optional, Any
import aiofiles
from utils.bytes import to_bytes
try:
import jinja2
except ImportError:
pass
class Template:
"""A class for reading and rendering templates (requir... |
import os
import sys
import subprocess
import textwrap
import argparse
import time
from tkinter import *
from argparse import ArgumentParser
from subprocess import Popen, PIPE, CREATE_NEW_CONSOLE
from subprocess import *
from Payload.Vault.Installation.Progress import Progress
from Payload.Vault.Installation.Preseed... |
"""
Shared utility classes and functions.
"""
import codecs
ELEMENTS = """
Fire
Water
Thunder
Ice
Dragon
Poison
Paralysis
Sleep
Blastblight
""".split()
WEAPON_TYPES = [
"Great Sword",
"Long Sword",
"Sword and Shield",
"Dual Blades",
"Hammer",
"Hunting Hor... |
# Copyright (c) 2020, DCSO GmbH
"""
This script demonstrates:
* executes GraphQL query which support cursor-based pagination
* using machine tokens instead of credentials, reading the
an environment variable (done automatically by SDK)
"""
import os
import sys
import time
from dcso.portal import APIClient, ENV_PO... |
from django.contrib import admin
from .models import CartRule
# Register your models here.
admin.site.register(CartRule) |
# Generated by Django 2.2.3 on 2019-07-18 20:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0007_auto_20190715_1311'),
]
operations = [
migrations.AddField(
model_name='order',
name='odometer',
... |
import pandas as pd
import numpy as np
def read_pickle_file(file):
pickle_data = pd.read_pickle(file)
return pickle_data
def write_pickle_df(df, file):
df.to_pickle(file)
def read_npy(file):
return np.load(file).item()
|
import numpy as np
import os
from qtpy.QtWidgets import QHBoxLayout, QCheckBox, QSpacerItem, QSizePolicy, QWidget, QMenu, QFileDialog
from qtpy.QtWidgets import QApplication
from qtpy import QtCore, QtGui
from qtpy.QtGui import QIcon
import pyqtgraph as pg
import json
import copy
from __code._utilities.table_handler i... |
"""Compute SHA256 message digest from a file"""
from hashlib import sha256
BLOCK_SIZE = 128 * 1024
def sha256sum(filename: str) -> str:
"""Compute SHA256 message digest from a file"""
hash_func = sha256()
byte_array = bytearray(BLOCK_SIZE)
memory_view = memoryview(byte_array)
with open(filename,... |
from datetime import datetime
import pytest
from starlette import convertors
from starlette.convertors import Convertor, register_url_convertor
from starlette.responses import JSONResponse
from starlette.routing import Route, Router
@pytest.fixture(scope="module", autouse=True)
def refresh_convertor_types():
co... |
import pytest
from cowdict import CowDict
@pytest.fixture
def base_dict():
return {
"foo1": "bar1",
"foo2": "bar2",
"foo3": "bar3",
"foo4": "bar4",
"foo5": "bar5",
}
def test_same_changed(base_dict):
cd = CowDict(base_dict)
base_dict["foo2"] = "baz2"
bas... |
#
# @lc app=leetcode id=1610 lang=python3
#
# [1610] Maximum Number of Visible Points
#
# @lc code=start
import math
class Solution:
def visiblePoints(self, points: list[list[int]], angle: int, location: list[int]) -> int:
base, radians, angle = 0, [], math.radians(angle)
for x, y in points:
... |
# Copyright 2018 Rhyan Arthur
""" Contains the data models for the squad maker application.
Classes:
Player: Represents a hockey player.
Squad: Represents a hockey squad (team).
Functions:
to_rating: Converts a value to a numerical skill rating.
"""
class Player:
""" Represents a hockey player wit... |
from funkcje import *
import unittest
def test_add_enemy():
assert number_enemy_add(6, 2) == 8
def test_level():
assert level(27) == 2
def test_collision():
assert collision(1, 1, 1, 1) == True
def test_highscore():
assert highscore(-1) == False
def test_enemy_tables():
assert creating_ene... |
class Chart:
def __init__(self):
self.obj = {
"chart": {
"zoomType": "x"
},
"title": {
"text": "Title of graph"
},
"xAxis": {
"crosshair": True,
"title": {
"text": "X axis title"
},
"scrollbar": {
"enabled": True
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Project : inn.
# @File : muit_inputs_outputs
# @Time : 2020/5/18 9:31 下午
# @Author : yuanjie
# @Email : yuanjie@xiaomi.com
# @Software : PyCharm
# @Description :
import tensorflow as tf
from tensorflow.keras.layers import *
from s... |
from showml.simulations.conways_game_of_life import GameOfLife
GameOfLife().run()
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2018-05-14 11:42
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("offer", "0011_auto_20170710_1442"),
]
operations = [
migrations.AddField(
... |
import colorsys
def convert_hue_color(hue, saturaton, brightness):
color = colorsys.hsv_to_rgb(hue / 65535, saturaton / 254, brightness / 254)
return [int(value * 255) for value in color]
def generate_keybow_color(hue, saturaton, brightness):
color = colorsys.hsv_to_rgb(hue, saturaton, brightness)
ret... |
#! Copyright (C) 2017 Lukas Löhle
#!
#! This software may be modified and distributed under the terms
#! of the MIT license. See the LICENSE file for details.
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
|
import pytest
import json
import hyperjson
import string
from io import StringIO
simple_types = [1, 1.0, -1, None, "str", True, False]
@pytest.mark.parametrize("payload", simple_types)
def test_simple_types(payload):
assert json.dumps(payload) == hyperjson.dumps(payload)
def ignore_whitespace(a):
"""
C... |
import os
import tcod
from yaml_functions import read_yaml
CONFIG = read_yaml("config.yaml","!default")
# 폰트 로딩
FILE_PATH = os.path.dirname(os.path.abspath(__file__))
GRAPHIC_PATH = '\\graphics\\fonts\\'
FONT = FILE_PATH + GRAPHIC_PATH + CONFIG['FONT']
FLAGS = tcod.context.SDL_WINDOW_RESIZABLE
SCREEN_W... |
import pathlib
from setuptools import setup
description = "Apache Airflow Executor for AWS ECS, AWS Fargate, and AWS Batch"
try:
with open(str(pathlib.Path.cwd() / "readme.md"), "r") as fh:
long_description = fh.read()
except FileNotFoundError:
long_description = description
setup(
name="airflow... |
from json import loads
from lxml.etree import Element
class Composer:
def __init__(self, namespaces=None):
self.namespaces = namespaces
def compose(self, obj):
"""Compose XML element from obj dict."""
if isinstance(obj, (str, bytes)):
obj = loads(obj)
tag, content ... |
# This script invokes blender to import and save external model formats as
# .blend files to be processed further.
#
# Example usage for this importer:
# blender --background --factory-startup --python $HOME/import_3ds.py -- \
# --i="/tmp/hello.3ds" \
# --o="/tmp/hello.blend" \
#
# See blender --help... |
# 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 writing, software
# d... |
def constructTree(pre, size):
# Initialize a stack
stack = []
# Process the first element
root = Node(pre[0])
stack.append(root)
for i in range(1, size) :
if pre[i] < stack[-1].data :
ptr = Node(pre[i])
stack[-1].left = ptr
stack.append(ptr)
... |
#!/usr/bin/env python3
# Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
import socket
import threading
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES
from Crypto import Random
import base64
class server():
def __init__(self):
self.running = True
key = RSA.generate(2048) # Use RSA for public key encryption to send key at start
... |
from adventofcode.year_2021.day_01_2021 import sonar_sweep_sliding_window, sonar_sweep, count_increasing_windows, \
sonar_sweep_sliding_window_reuse
test_input = [
199,
200,
208,
210,
200,
207,
240,
269,
260,
263,
]
def test_sonar_sweep():
assert sonar_sweep(test_input... |
# Dynamic programming algorithm for Traveling Salesman Problem (TSP)
# prints out the minimum cost of a traveling salesman tour rounded down to the nearest integer
import math
g = []
with open('tsp.txt', 'r') as doc:
for line in doc:
g.append(list(map(float, line.split())))
n = int(g[0][0])
del g[0]
d = ... |
"""
The distributions module is an extension of the `torch.distributions` package intended to facilitate implementations
required for specific variational approaches through the :class:`.SimpleDistribution` class. Generally, using a
:class:`torch.distributions.Distribution` object should be preferred over a :class:`Sim... |
# -*- coding: utf-8 -*-
from re import compile as regex
from django.conf import settings
from django.core.urlresolvers import resolve, Resolver404
from django.utils.deprecation import MiddlewareMixin
RE_CLASS = regex('').__class__
class SubdomainMiddleware(MiddlewareMixin):
'''
SubdomainMiddleware maps sub... |
#!/usr/bin/env python
from __future__ import division
import back_datetime
import unittest
import sys
__author__ = 'youval.dar'
class TestBackDateTime(unittest.TestCase):
def test_start_date_time(self):
""" test deduction is done correctly """
print sys._getframe().f_code.co_name
ref = ... |
from .config import config
from .dataAccess import SecDb
from .marketData import MarketDataDb
from .syncMarketData import SynchronizeMarketData
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.