text stringlengths 2 999k |
|---|
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 12 20:07:42 2021
@author: AKayal
"""
from functools import lru_cache
import math
class Polygon:
"""
this class has following logic
where initializer takes in:
number of edges/vertices
circumradius
that can provide these properties:
... |
from mathutils.geometry import interpolate_bezier
from compas.geometry import add_vectors
from compas_blender.geometry._geometry import BaseBlenderGeometry
__all__ = [
'BlenderCurve',
]
class BlenderCurve(BaseBlenderGeometry):
def __init__(self, obj):
super().__init__(obj)
@classmethod
de... |
# -*- coding: utf-8 -*-
import hashlib
import re
from django import template
from django.core.cache import cache
from asterisk.models import ExternalPhoneNumber
register = template.Library()
@register.filter()
def website_info(userfield):
if not userfield.strip():
return '-'
pattern = re.compile(r'... |
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
import glob
import os
import os.path as osp
import time
import numpy as np
def parse_args():
parser = argparse.ArgumentParser(
description='Generate the information of GOT10k dataset')
parser.add_argument(
'-i',
'--input'... |
# 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)
from spack import *
class IntelParallelStudio(IntelPackage):
"""Intel Parallel Studio."""
homepage = "https://s... |
import json
import requests
from utils.classes.Const import config
file_path = '../../data'
def download_gamestrings(dir):
gs_file = 'gamestrings'
languages = ['dede', 'enus', 'ruru']
for lang in languages:
gs_url = f'https://raw.githubusercontent.com/HeroesToolChest/heroes-data/master/heroesdata/... |
def DFT(graph, node, edge):
print(edge, end = ' ')
node.remove(edge)
for a in graph[edge]:
if a in node:
DFT(graph, node, a)
def BFT(graph, visited, edge):
if edge == []:
return ''
print(edge[0], end = ' ')
for a in graph[edge[0]]:
if a not in visited:
... |
# Copyright 2004-2008 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
from pygccxml import declarations
from pyplusplus import decl_wrappers
class COLOR:
WHITE = 0
GRAY = 1
... |
#!/usr/bin/env python3
import unittest
# noinspection PyUnresolvedReferences
from test.coind_test import CoindTest
# Test
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/env python
# Copyright (C) 2015, 2019 IBM Corp. 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 r... |
import os
ls=["python main.py --configs configs/eval_medseg_unetplusplus_timm-regnetx_002_0_Posterize.yml",
"python main.py --configs configs/eval_medseg_unetplusplus_timm-regnetx_002_1_Posterize.yml",
"python main.py --configs configs/eval_medseg_unetplusplus_timm-regnetx_002_2_Posterize.yml",
"python main.py --confi... |
"""
Commands for goals
"""
from evennia.utils.evtable import EvTable
from commands.base import ArxCommand
from commands.mixins import CommandError
from .models import Goal, GoalUpdate
from server.utils.helpdesk_api import create_ticket, resolve_ticket
from web.helpdesk.models import Ticket
from world.dominion.models i... |
import warnings
import numpy as np
import pandas as pd
import streamlit as st
from benchmark import (
EXPERIMENT_NAMES,
get_result,
load_augmentation,
load_config,
load_lightning_module,
normalize,
)
from kvt.initialization import initialize as kvt_initialize
from kvt.utils import QueryExpansio... |
# File: S (Python 2.4)
from direct.gui.DirectGui import *
from pandac.PandaModules import *
from pirates.piratesgui import PiratesGuiGlobals
from pirates.piratesgui import InventoryItemList
from pirates.piratesgui import ShipItemGUI
from pirates.piratesbase import PiratesGlobals
class ShipItemList(InventoryItemList.I... |
from .mix_normal import MixtureNormal
from .normal import Normal
|
#!/usr/bin/env python
import SimpleHTTPServer
import SocketServer
import logging
import cgi
import base64
import argparse
import os
class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
logging.warning("======= GET STARTED =======")
logging.warning(self.headers)
Simp... |
import math
import torch as th
import torch.nn as nn
class LSTMCell(nn.Module):
def __init__(self, input_size, hidden_size, bias=True):
super(LSTMCell, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.bias = bias
self.i2h = nn.Linear(input... |
import time
from datetime import datetime, timedelta
try:
import cv2
import numpy as np
except:
print("For aproximate match of images please install opencv-python and numpy")
try:
import pyautogui as pag
import pyperclip as clip
except:
raise Exception("Checkout pyautogui documentation on how ... |
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
import jax
import jax.numpy as jnp
import jax.test_util as jtu
from jax.config import config
from ttax.base_class import TT
from ttax.base_class import TTMatrix
from ttax import random_
from ttax import ops
config.parse_flags... |
"""photo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based v... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.us_classified_docs import us_classified_docs
def test_us_classified_docs():
"""Test module us_classified_docs.py by downloading
us_classified... |
from colorama import Style,Fore
import random
all_col= [Style.BRIGHT+Fore.RED,Style.BRIGHT+Fore.CYAN,Style.BRIGHT+Fore.LIGHTCYAN_EX, Style.BRIGHT+Fore.LIGHTBLUE_EX, Style.BRIGHT+Fore.LIGHTCYAN_EX,Style.BRIGHT+Fore.LIGHTMAGENTA_EX,Style.BRIGHT+Fore.LIGHTYELLOW_EX]
ran = random.choice(all_col)
lg = Style.BRIGH... |
from cumulusci.salesforce_api.metadata import ApiRetrieveUnpackaged
from cumulusci.tasks.salesforce import BaseRetrieveMetadata
retrieve_unpackaged_options = BaseRetrieveMetadata.task_options.copy()
retrieve_unpackaged_options.update(
{
"package_xml": {
"description": "The path to a package.xm... |
from FeedProofpoint import Client, fetch_indicators_command
from CommonServerPython import FeedIndicatorType
url = "https://example.com"
auth_code = "cool"
client = Client(url, auth_code)
def test_fetch_ips(requests_mock):
ip_path = "./TestData/detailed-iprep.txt"
with open(ip_path) as f:
data = f.re... |
"""
WSGI config for community project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SET... |
import uvicore
from uvicore.package import ServiceProvider
from uvicore.http.provider import Http
from uvicore.database.provider import Db
from uvicore.console.provider import Cli
from uvicore.redis.provider import Redis
from uvicore.support.dumper import dump, dd
@uvicore.provider()
class App1(ServiceProvider, Cli, ... |
# done by Kysan the gay pp farmer thanks
# return pos of the first char of the comment or -1 if there is no comment
import os
from collections import OrderedDict
from configparser import ConfigParser
from osr2mp4 import logger
def detect_comments(line):
ancient_char = ''
for k in range(len(line)):
if line[k] ... |
# Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Model-related exceptions and related logic."""
import re
from logging import getLogger
from sqlalchemy.exc import IntegrityError
logger = getLogger(__name__)
def field_lookup(field_string):
"""Find... |
from django.conf import settings
from django.core.cache import cache
from pusher import Pusher
class PusherProvider(object):
"""
This class provides a wrapper to Pusher so that we can mock it or disable it easily
"""
def __init__(self):
self._pusher = None
self._disabled = False
... |
def set_from_string(indexes_info: str):
indexes_info = indexes_info.split(',')
start_index = int(indexes_info[0])
end_index = int(indexes_info[1])
result = {x for x in range(start_index, end_index + 1)}
return result
longest_intersection = []
for _ in range(int(input())):
ranges_info = input(... |
#!/usr/bin/env python3
import abc
import inspect
import logging
from typing import List, Optional
from reagent.core.registry_meta import RegistryMeta
from reagent.core.result_registries import ValidationResult
from reagent.workflow.types import RLTrainingOutput
from reagent.workflow.types import TableSpec
logger = l... |
def test_fn(a,b,c):
print('%d' %(a+b-c))
import inspect
print(inspect.getsource(test_fn))
|
import unittest
import util
TEST_LINE = 'acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf'
class UtilTest(unittest.TestCase):
def test_part1(self):
self.assertEqual(26, util.part1('test_input.txt'))
def test_map_wires(self):
m = util.map_wires(TEST_LINE)
self.as... |
import requests
import os
import requests
from io import BytesIO
from pyzbar import pyzbar
from PIL import Image
def get_ewm(img_adds):
"""
读取二维码的内容: img_adds:二维码地址(网址or本地路径)
从网上复制的,来源:https://blog.csdn.net/qq_30068487/article/details/96833002
"""
if os.path.isfile(img_adds):
# 从本地加载二维码图片... |
def add(x, y):
"""Add Function"""
return x + y
def subtract(x, y):
"""Subtract Function"""
return x - y
def multiply(x, y):
"""Multiply Function"""
return x * y
def divide(x, y):
"""Divide Function"""
if y == 0:
raise ValueError('Can not divide by zero!')
return x / y
|
# -*- coding: utf-8 -*-
import inspect
import sys
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str
else:
string_types = basestring
def listify(o):
if isinstance(o, (list, tuple)):
return o
else:
return [o]
class Rule(object):
def __init__(self, base_behavior, action, su... |
from cloudify.workflows import ctx, parameters
from cloudify.manager import get_rest_client
instance = next(ctx.node_instances)
instance.execute_operation('custom_lifecycle.custom_operation',
kwargs={'update_id': parameters.update_id})
rest_client = get_rest_client()
rest_client.deploymen... |
import markdown
class EscapeHtml(markdown.Extension):
def extendMarkdown(self, md):
md.preprocessors.deregister('html_block')
md.inlinePatterns.deregister('html')
def makeExtension(*args, **kwargs):
return EscapeHtml(*args, **kwargs)
if __name__ == "__main__":
import doctest
doct... |
#!/usr/bin/env python
# Copyright 2015-2019 Yelp Inc.
#
# 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 ... |
from construct import *
construct_map = Struct(
Const(b'\xff\xff\xff\xff'),
# Preview
"preview" / Struct(
"size" / Int32sl,
"uncompr_size" / Int32sl,
"compr_size" / Int32sl,
"crc_32" / Int32sl,
"data" / Bytes(this.compr_size),
),
# Desc... |
import os
import platform
import shlex
import shutil
import subprocess
from setuptools import find_packages, setup
from setuptools.command.egg_info import egg_info
from sqllineage import NAME, STATIC_FOLDRE, VERSION
with open("README.md", "r") as f:
long_description = f.read()
class EggInfoWithJS(egg_info):
... |
from roche import *
from diffrot import * |
#!/usr/bin/env python -u
# -*- coding: utf-8 -*-
"""
Usage:
time python -u ${PATH}/insertMECOEnergyData.py > ${LOG_FILE}
Optional flags include `--testing` and `--email` that insert to the testing
database and send email notifications, respectively.
From the **current working directory**, recursively descend in... |
import os
import os.path as osp
import numpy as np
import random
import matplotlib.pyplot as plt
import collections
import torch
import torchvision.transforms as transforms
import torchvision
import cv2
from torch.utils import data
import sys
from PIL import Image
palette = [128, 64, 128, 244, 35, 232, 70, 70, 70, 102... |
"""Create an animation asset."""
import bpy
from avalon import api
from avalon.blender import lib, ops
from avalon.blender.pipeline import AVALON_INSTANCES
from openpype.hosts.blender.api import plugin
class CreateAnimation(plugin.Creator):
"""Animation output for character rigs"""
name = "animationMain"
... |
#by johnny minor on 9.20.15
import matplotlib.pyplot as plot
from pylab import *
import math
import numpy as np
#not sure what these do but apparently they have to be here
#in order to show the linear regression equation.
fig = plt.figure()
ax = fig.add_subplot(111)
#newtons gravitational constant
G = 6.67e-1... |
import pandas as pd
import numpy as np
import time
from datetime import timedelta, date, datetime
class TransformData(object):
def __init__(self):
pass
# get data and preprocessing
def format_timestamp(self, utc_datetime):
now_timestamp = time.time()
offset = datetime.fromtimestamp... |
from . import stats_wrappers
from . import dl_wrappers |
"""
Invoice Query Exception gets raised when request for invoice retrieval gets failed .
"""
from .invoice_exception import InvoiceException
class InvoiceQueryException(InvoiceException):
"""
InvoiceQueryException
"""
__bitpay_message = "Failed to retrieve invoice"
__bitpay_code = "BITPAY-INVOICE... |
# Copyright 2016-2020 Swiss National Supercomputing Centre (CSCS/ETH Zurich)
# ReFrame Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
import reframe as rfm
import reframe.utility.sanity as sn
@rfm.required_version('>=2.16')
@rfm.parameterized_test(['producti... |
#!/usr/bin/env python
# coding: utf-8
# Use the file 'gnparser_python.py" To make the files you need for input
in_file = open('ferntaxa_3.txt', 'r')
out_file_t = open('taxonomy.tsv', 'w')
out_file_t.write('uid | parent_uid | name | rank | sourceinfo | ' + '\n')
for line in in_file:
line = line.strip('\n')
row = l... |
import httplib
from django.core.urlresolvers import reverse
from oscar_testsupport.factories import create_order
from oscar_testsupport.testcases import WebTestCase
class TestAnAnonymousUser(WebTestCase):
def test_gets_a_404_when_requesting_an_unknown_order(self):
path = reverse('customer:anon-order', ... |
class DictDiffer(object):
"""
Calculate the difference between two dictionaries as:
(1) items added
(2) items removed
(3) keys same in both but changed values
(4) keys same in both and unchanged values
from:
https://github.com/hughdbrown/dictdiffer
"""
def __init__(self, curre... |
from django.test import TestCase, RequestFactory
from oscar.test.factories import create_order
from soap.tests import SoapTest
from wellsfargo.fraud import screen_transaction, WFRS_FRAUD_PROTECTION
from wellsfargo.tests import responses
import mock
def patch_fraud_protection(klass, **klass_kwargs):
def decorate(... |
from flask_wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
class NameForm(Form):
name = StringField('What is your name?', validators=[DataRequired()])
submit = SubmitField('Submit')
|
from setuptools import setup, find_packages
import io
def read_all(f):
with io.open(f, encoding="utf-8") as I:
return I.read()
requirements = list(map(str.strip, open("requirements.txt").readlines()))
setup(
name='test-release-rts-py',
version="1.4.7",
description='Test Release for RedisTimeS... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# !! This program must run with all version of Python since 2.3 included.
import os
import sys
min_version = (2, 3)
error_msg = ("Sorry, this package is for Python %d.%d and higher only." %
min_version)
try:
if sys.version_info < min_version:
sy... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import division # so that 1/3=0.333 instead of 1/3=0
from psychopy import visual, core, data, event, logging, gui
from psychopy.constants import * # things like STARTED, FINISHED
import pandas as pd
import numpy as np # whole numpy lib is available, prep... |
#coding=utf-8
import sys
import os
import cv2
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class MainUI(QMainWindow):
def __init__(self):
super().__init__()
self._count = -1
self._filelist = []
self._labellist = []
se... |
"""server URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Clas... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the Safari cookie parser."""
from __future__ import unicode_literals
import unittest
from plaso.formatters import safari_cookies as _ # pylint: disable=unused-import
from plaso.lib import definitions
from plaso.parsers import safari_cookies
from tests impo... |
"""
Этот файл содержит слушатели на текстовые сообщения в боте
"""
import asyncio
from aiogram import types
from app.misc import dp, bot, i18n
from app.utils.message import msgToLog
_ = i18n.gettext
@dp.message_handler()
async def echo_message(msg: types.Message):
msgToLog(msg)
await bot.send_message(msg.f... |
# Copyright (c) 2017 Intel Corporation
#
# 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 i... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
# -*- coding: utf-8 -*-
import pickle
from _thread import start_new_thread
from pysimplelog import Logger
import traceback
from FoodScan.BarcodeSync import BarcodeReader
class BarcodeSync:
def __init__(self, barcode_descriptor, config, shopList, asynchron=True):
self.logger = Logger('BarcodeSync')
... |
def score_word(word):
score = 0
for letter in word:
if (letter != '"'):
score += ord(letter) - ord('A') + 1
return score
text_file = open("input/p022_names.txt", "r")
lines = sorted(text_file.read().split(','))
score = 0
position = 0
while (position < len(lines)):
score += (position... |
# Copyright 2016 The TensorFlow Authors. 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 applica... |
import curses
from orient import Orientation
from position import Position, Size
from block import Block, Entity, Room
class Display(object):
def __init__(self, rows=1, cols=1, pos_row=0, pos_col=0):
"""
The class that other displays inherit from
"""
self._win = curses.newwin(rows... |
# coding=utf-8
# Copyright 2022 The TensorFlow Datasets Authors.
#
# 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 appl... |
import openpyxl
from PIL import Image
from PIL import GifImagePlugin
import glob
import os
# Image to colored Excel cells
def image_to_excel(file, output, percentage, zoom):
# Open picture and create a workbook instance
im = Image.open(file)
wb = openpyxl.Workbook()
sheet = wb.active
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from libpredweb import myfunc
import argparse
import hashlib
def OutputRecord(seqnumber, seqid, description, seq, fpout):# {{{
md5_key = hashlib.md5(seq.encode('utf-8')).hexdigest()
subfoldername = md5_key[:2]
cachedir = "%s/%s/%s"%(g_par... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... |
#! /usr/bin/python2
# -*- coding: utf-8 -*-
import unittest
from dominos import Domino, PostCorrespondenceState, DominoSpace
class PostCorrespondenceStateTest(unittest.TestCase):
def testIsValid(self):
states = [
PostCorrespondenceState(),
PostCorrespondenceState(("a", ""), []),
PostCorre... |
from GeneralUtils import flatten
def collatz(n):
while n > 1:
yield n
if n % 2 == 0:
n = n//2
else:
n = 3*n+1
yield n
def collatz_inv(n):
if n % 6 == 4:
return 2*n, (n-1)//3
return 2*n
def collatz_inv_graph(n,levels):
S = [n]
for i in ra... |
"""
A Cairo backend for matplotlib
Author: Steve Chaplin
Cairo is a vector graphics library with cross-device output support.
Features of Cairo:
* anti-aliasing
* alpha channel
* saves image files as PNG, PostScript, PDF
http://cairographics.org
Requires (in order, all available from Cairo website):
cairo, pyc... |
#!/usr/bin/env python
#
# Copyright 2010 Google Inc.
#
# 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 o... |
from celery_app import celery_server,app
from flask_mail import Message
from dysms_python.demo_sms_send import send_sms
from exts import mail
@celery_server.task
def setmail(data,r):
with app.app_context():
msg = Message("我的邮箱验证码", recipients=[data], body="验证码为" + r)
mail.send(msg)
@celery_server.ta... |
"""Empty init file to ensure documentation for multi-agent envs is created."""
from flow.envs.multiagent.base import MultiEnv
from flow.envs.multiagent.ring.wave_attenuation import \
MultiWaveAttenuationPOEnv
from flow.envs.multiagent.ring.wave_attenuation import \
MultiAgentWaveAttenuationPOEnv
from flow.envs... |
print []
print {}
print 1
print : meta.item-access.python, source.python, support.function.builtin.python
: meta.item-access.python, source.python
[ : meta.item-access.python, punctuation.definition.arguments.begin.python, source.python
] : meta.item-access.python, punct... |
import nose.tools as nt
from topik.models.tests.test_data import test_vectorized_output
from topik.models.lda import lda
def test_train():
model_output = lda(test_vectorized_output, ntopics=2)
for doc in model_output.doc_topic_matrix.values():
nt.assert_almost_equal(sum(doc), 1)
for topic in mode... |
from model.contact import Contact
from selenium.webdriver.support.ui import Select
import re
class ContactHelper:
def __init__(self, app):
self.app = app
def create(self, contact):
wd = self.app.wd
self.open_add_new()
self.fill_contact_form(contact)
wd.find_element_by_... |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""Fixture based DE Server for the de-client tests"""
# pylint: disable=redefined-outer-name
import io
import sys
import pytest
from decisionengine.framework.tests.fixtures import ( # noqa: F401
DEServer,
PG_D... |
import pandas as pd
import argparse
import os
import matplotlib
import utils
if "DISPLAY" not in os.environ:
matplotlib.use('Agg')
import matplotlib.pyplot as plt
SHOW_PLOT = False
SAVE_PLOT = True
RESHUFFLE = False
AUGMENT_TRAIN = False
colors = {
"train": "blue",
"valid": "green",
"test": "red"... |
# ----------------------------------------------------------------------------
# Copyright (c) 2019-, The Microsetta Initiative development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ----------------------------------... |
class PhaseSetStats:
def __init__(self, switch_count, mismatch_count, phased_snp, N50, AN50, spanned_snp):
self.switch_count = switch_count
self.mismatch_count = mismatch_count
self.phased_snp = phased_snp
self.N50 = N50
self.AN50 = AN50
self.spanned_snp = spanned_snp... |
from podcomm.protocol_common import PdmMessage, PdmRequest, PodMessage, PodResponse
from podcomm.protocol import *
from podcomm.nonce import Nonce
from podcomm.protocol_radio import PdmRadio, RadioPacket, RadioPacketType, TxPower
from podcomm.crc import crc16, crc8
from tests.mock_radio import MockPacketRadio
from podc... |
from django.contrib import admin
from .models import Theme, CurrentTheme
@admin.register(Theme)
class ThemeAdmin(admin.ModelAdmin):
list_display = ('label',)
search_fields = ('label',)
@admin.register(CurrentTheme)
class CurrentThemeAdmin(admin.ModelAdmin):
list_display = ('theme',) |
#!/usr/bin/env python2
# Copyright (c) 2014-2015 The Syscoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Base class for RPC testing
# Add python-syscoinrpc to module search path:
import os
import sys
import... |
# Copyright 2009-2012 10gen, Inc.
#
# 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... |
"""
Edabit's Encryption Scheme
An English text needs to be encrypted using Edabit’s encryption scheme. First, the spaces are removed from the text. Let L be the length of this text. Then, characters are written into a grid, whose rows and columns have the following constraints:
For example, the sentence "if man was me... |
import pytest
def test_import():
from dask_cloudprovider import ECSCluster
from dask_cloudprovider import FargateCluster
# def test_ecscluster_raises():
# from dask_cloudprovider import ECSCluster
# with pytest.raises(RuntimeError):
# _ = ECSCluster()
|
from calculate_tax import CalculateTax
class TaxOther(CalculateTax):
def tax(self, net_price: float) -> float:
return net_price + 1
|
# Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
# input: S = "ab#c", T = "ad#c"
# output: true
# Explanation: Both S and T become "ac".
# input: S = "ab##", T = "c#d#"
# output: true
# Explanation: Both S and T become "". # is a specia... |
import sqlite3
from prettytable.prettytable import from_db_cursor
from matplotlib.pyplot import table
import kraken.performance_scenarios.utils as utils
import kraken.performance_scenarios.log as log
import yaml
class Basic_function(object):
def __init__(self):
TABLE_NAME = ''
def view_sql_data(sel... |
from rest_framework.routers import DefaultRouter
from .views import WorkoutTemplateViewSet, WorkoutViewSet
router = DefaultRouter()
router.register(r'templates', WorkoutTemplateViewSet, basename='workout-template')
router.register(r'', WorkoutViewSet, basename='workout')
urlpatterns = router.urls
|
# -*- coding: utf-8 -*-
'''
Reuben Brewer, Ph.D.
reuben.brewer@gmail.com
www.reubotics.com
Apache 2 License
Software Revision F, 05/22/2022
Verified working on: Python 2.7, 3.8 for Windows 8.1, 10 64-bit and Raspberry Pi Buster (no Mac testing yet).
'''
__author__ = 'reuben.brewer'
from LowPassFilte... |
# -*- coding: utf-8 -*-
from PyQt4 import QtCore
class Module(QtCore.QObject):
# User-readable name for this module
moduleDisplayName = None
# Override this class attribute to have this module appear
# under different category sections in the manager window's module list
moduleCategory = None
... |
from tensorflow import keras as K
def conv2d(x, filters, shape, padding="same", strides=(1, 1), activation="relu"):
"""
2D Convolutional layers with Batch Normalization
Arguments:
x: Keras layer, the input to the feature map
filters: Int representing the number of filters to use
... |
# Return True if the given string contains an appearance of "xyz" where the xyz is not directly preceeded
# by a period (.). So "xxyz" counts but "x.xyz" does not.
#
# xyz_there('abcxyz') → True
# xyz_there('abc.xyz') → False
# xyz_there('xyz.abc') → True
def xyz_there(str):
z = True
for i in range(0, len(str)... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 26 12:46:36 2020
This class defines t-Student distribution for ARMA-GARCH models
@author: Ian Khrashchevskyi
"""
from .distModel import DistModel
import numpy as np
import scipy.stats as stats
from scipy.special import gamma
class tStudent(DistModel):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.