content stringlengths 5 1.05M |
|---|
from sklearn.metrics import classification_report, confusion_matrix
import sklearn.ensemble
from sklearn import metrics
from sklearn import svm
from scipy.fftpack import fft
import pickle
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPClassifier
from sklearn.ensemble import Ra... |
# Copyright 2015-2016 F5 Networks 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... |
# Copyright 2020 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 rando.core.tests import NavigationTest
class BackpackNavigationTest(NavigationTest):
def test_backpack(self):
self.assertTrue(self.casper(self._get_tests_file('test_backpack.js')))
|
from unittest.case import SkipTest
import uuid
import cloudinitd
import cloudinitd.nosetests
from cloudinitd.statics import REMOTE_WORKING_DIR_ENV_STR
from cloudinitd.user_api import CloudInitD
import tempfile
import unittest
import os
class RemoteDirInspectionTests(unittest.TestCase):
def setUp(self):
se... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 7 15:09:54 2017
@author: gonzalo Hernandez
"""
import sqlite3
from sqlite3 import Error
import datetime
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.dates as md
import pandas as pd
from pandas import DataFrame, Series
im... |
from .common import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env['DJANGO_SECRET_KEY']
STATIC_URL = env['STATIC_URL']
STATIC_ROOT = env['STATIC_TMPDIR']
|
import ellipse_lib as el
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
data = el.make_test_ellipse()
lsqe = el.LSqEllipse()
lsqe.fit(data)
center, width, height, phi = lsqe.parameters()
plt.close('all')
fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111)
ax.axis('equ... |
#!/usr/bin/env/python3
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import os
os.environ["LOGLEVEL"] = "INFO"
# Since logger initialized during imoprt stat... |
def take_order(menu):
print('MENU\n====\n\n')
for i, menu_item in sorted(menu.items()):
print('{:<2} {:<15} {:0.2f}'.format(i, menu_item.get('item', ''),
menu_item.get('cost', 0)))
return raw_input('Select number to order or (q)uit: ')
def ring_up_custome... |
"""
Disassembler: only enabled if HAS_DISASSEMBLER is True.
"""
try:
from ptrace.cpu_info import CPU_I386, CPU_X86_64
try:
from distorm3 import Decode
if CPU_X86_64:
from distorm3 import Decode64Bits as DecodeBits
MAX_INSTR_SIZE = 11
elif CPU_I386:
fr... |
#!/usr/bin/env python
import akshare as ak
from util.half import half
from os.path import dirname, abspath, basename
from tzutil.cout import cout
from time import sleep
def format_a(name):
return half(name.replace(' ', '').replace("*", '')).lower()
class Name:
def __init__(self):
self.exist = set()
def ... |
import os
import sys
from enum import IntEnum
##########################
# Definitions
class RenameArguments(IntEnum):
WorkingDirectory = 1
OldName = 2
NewName = 3
ValidArgumentsCount = 4
def multiple_rename(directory, old_name, new_name):
for file in os.listdir(directory):
... |
# _*_ coding: utf-8 _*_
import threading
import queue
class ParseThreadBase(threading.Thread):
'''解析线程基类,守护线程'''
queue: 'queue.Queue' = None
def __init__(self):
super(ParseThreadBase, self).__init__()
if self.queue is None:
raise AttributeError("未设置属性`队列对象`.")
# 守护为真
... |
from flask_unchained.bundles.sqlalchemy import db
from flask_unchained.utils import utcnow
from ..enums import Frequency
class AssetDataVendor(db.Model):
"""Join table between Asset and DataVendor"""
class Meta:
repr = ('asset_id', 'data_vendor_id', 'ticker')
asset_id = db.foreign_key('Asset', p... |
# -*- coding: utf-8 -*-
__author__ = 'ScrapingHub'
__email__ = 'info@scrapinghub.com'
__version__ = '0.1.0'
from .flatson import Flatson # NOQA
|
# -*- coding: utf-8 -*-
#
"""iBook updata
Please click on the link:www.ibook.Support.com
check iBook the latest version
Copyright (C)2019.ibook.support.com
"""
import tkinter
def updata():
WIDTH_HEIGHT = '450x400'
WINDOW_POSITION = '+520+220'
updata = tkinter.Toplevel()
updata.title('updata')
... |
from astropy.coordinates import SkyCoord
from astropy import units as u, constants as c
from astropy.table import Table
import pandas as pd
t = Table.read('../data/gaia_csvs/gaia_vizier_asu.fits')
t['source_id'] = t['DR2Name'].astype(str)
df = t.to_pandas()
a = '5251470948229949568'
b = '5251470948222139904' # neare... |
from __future__ import print_function
import sys
sys.path.append('..')
sys.path.append('/usr/share/armory')
import getpass
import os
from armoryengine import *
# Use the parseDownloadList from verify script
from extras.verify_dl_list import *
wltfile = open(os.path.join(ARMORY_HOME_DIR, 'signingwlt.txt'),'r')
wltna... |
from opts import parse_opts
from utils.log import Log
from utils.utils import create_directory
from pipeline import S2TFiltering
# Code for KIT Hector School Master Thesis "Source to Target Similarity Filtering for Unsupervised Domain Adaptation"
# https://github.com/jonasnoll/s2t-sim
# If you consider using this cod... |
from const import *
import numpy as np
class HaasoscopeOversample():
def __init__(self):
self.dooversample=np.zeros(HAAS_NUM_BOARD*HAAS_NUM_CHAN_PER_BOARD, dtype=int) # 1 is oversampling, 0 is no oversampling, 9 is over-oversampling
def ToggleOversamp(self,chan):
#tell it to toggle oversamplin... |
# METHOD 1 - Preferred method (using two pointers for partitioning)
def quickSort(arr, low, high):
if low < high:
p = partition(arr, low, high)
quickSort(arr, low, p - 1)
quickSort(arr, p + 1, high)
def partition(arr, low, high):
pivot = arr[low]
left = low + 1
right = high
while left <= ... |
from distutils.core import setup
setup(
name='brap-compiler-proxy',
packages=['brap-compiler-proxy'],
version='0.0.1',
description='brap compiler: proxy',
author='Brian Graham',
author_email='drakain@gmail.com',
url='https://github.com/brap/brap-compiler-proxy',
download_url='https://git... |
import glob
import os
import time
def check_file_exists(filename):
"""Check every 5 seconds if file exists in current working directory."""
ctr = 0
while not os.path.isfile(filename):
if ctr == 60:
return False
time.sleep(5)
ctr += 1
return True
def delete_files_of_this_ilk(ilk):
"""Delete 'Foo.csv', ... |
import numpy as np
from . import window
class SDFT(window.Window):
"""Sliding Discrete Fourier Transform (SDFT).
Initially, the coefficients are all equal to 0, up until enough values have been seen. A call
to `numpy.fft.fft` is triggered once ``window_size`` values have been seen. Subsequent values
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from ... |
# Generated by Django 3.2.6 on 2021-08-14 21:09
import ckeditor.fields
from django.db import migrations, models
import stdimage.models
class Migration(migrations.Migration):
dependencies = [
('core', '0008_post_image'),
]
operations = [
migrations.CreateModel(
name='Banner',... |
import logging
import boost_histogram as bh
import numpy as np
import pytest
from cabinetry import histo
class ExampleHistograms:
"""a collection of different kinds of histograms"""
@staticmethod
def normal():
bins = [1, 2, 3]
yields = [1.0, 2.0]
stdev = [0.1, 0.2]
retur... |
from pyradioconfig.parts.jumbo.profiles.Profile_WiSUN import Profile_WiSUN_Jumbo
from pyradioconfig.parts.common.profiles.ocelot_regs import build_modem_regs_ocelot
from pyradioconfig.parts.common.profiles.profile_common import buildCrcOutputs, buildFecOutputs, buildFrameOutputs, \
buildWhiteOutputs, build_ircal_sw... |
import logging
import pygame
import src.blocks as blocks
import src.virus as viruses
import src.world as world
from src.turn_simulation import simulate_turn
from src.virus import Virus
from src.world import World, INDUSTRIES
log = logging.getLogger("main.game")
log.setLevel(logging.INFO)
log.info("game logger initia... |
from __future__ import with_statement # this is to work with python2.5
# Here we add an example for interacting with PoCC
# it requires that polycc is in the PATH
# we can't run it in the validation because PoCC isn't installed
from pyps import workspace
import pocc
with workspace("pocc_example.c",name="poly",delete... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 18 07:30:49 2018
@author: adrian
"""
# Regla de Simpson 1/3
import math
from scipy.optimize import fsolve
from numpy import sign
from numpy import exp
# Función f(x)
def f(x):
return 4+math.cos(x+1)
# Función g(x)
def g(x):
return (math.exp(x))*(math.sin(x))
... |
>>> class MyClassName:
__private = 123
non_private = __private * 2
>>> mine = MyClassName()
>>> mine.non_private
246
>>> mine.__private
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
mine.__private
AttributeError: 'MyClassName' object has no attribute '__private'
>>> mine._MyClas... |
from ._CircularMotion import *
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import, division, print_function, unicode_literals
import platform
import re
import shlex
import sys
def is... |
# pylint: skip-file
import matplotlib.pyplot as plt
from probs import Normal, Uniform
u = Normal(mu=1.5, sigma=0.3)
u.plot()
v = Normal(mu=-0.7)
(u + v).plot()
plt.show()
u = Uniform(a=2, b=3)
u.plot()
v = Uniform()
(u + v).plot()
plt.show()
|
'''
Heros beta-0.0.1
mastershu
2017-10-26
'''
hp = 100
helpTitle = "'a' for left, 'd' for right!"
print('welcome Heros world')
print("the world is like this ##### , 'a' for left, 'd' for right!")
# 获取用户输入的英雄名
name = input("input your name: ")
if not name:
name = 'player01'
userMsg = [name, hp]
# print(userMsg)
pri... |
def linear_service_fee(principal, fee=0.0):
"""Calculate service fee proportional to the principal.
If :math:`S` is the principal and :math:`g` is the fee aliquot, then the
fee is given by :math:`gS`.
"""
return float(principal * fee)
|
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
from kids.cmd import cmd
from kids.data.mdict import mdict
from .common import OemCommand, find_root
class Command(OemCommand):
"""Oem configuration manager"""
def _get_target_cfg(self, args, write=True, first_has_key=None):
... |
import asyncio
import sys
from .utils import LemkPgUtils
from .exceptions import LemkPgError
from .constants import JOINS_LIST
class LemkPgApi:
"""
LemkPgApi class give API interface for quick access to PostgreSQL DB via async way.
You can use CRUD and other DB operations with some methods above.
Thi... |
import time
from .base import FunctionalTest
from selenium.webdriver.common.keys import Keys
class LoginAndBasicFunctionality(FunctionalTest):
def test_admin_can_create_and_browse(self):
#Admin goes to fv2 key mgmt site, sees it's named Crypt post-redirect to a login
self.browser.get(self.live_serv... |
import numpy as np
import config as cfg
class Board:
def __init__(self,board_size = cfg.board_size, win_row_size = cfg.win_row_size):
self.board_size = board_size
self.win_row_size = win_row_size
self.state = np.zeros([self.board_size,self.board_size,2])
self.available_move_location... |
import asyncio
import random
import bili_statistics
from reqs.tv_raffle_handler import TvRaffleHandlerReq
from tasks.utils import UtilsTask
import utils
from .task_func_decorator import normal
from .base_class import ForcedTask
class TvRaffleJoinTask(ForcedTask):
TASK_NAME = 'join_tv_raffle'
# 这是superuser做的,... |
"""Exercise models module"""
from django.db import models
from django.conf import settings
from equipment.models import Equipment
from levels.models import Level
from bodyparts.models import BodyPart
class Exercise(models.Model):
"""Exercise table mapping class"""
name = models.CharField(max_length=100)
u... |
# -*- coding: utf-8 -*-
import os, sys
import uuid, time
import requests
path = os.path.join(os.path.dirname(__file__),'../model')
sys.path.insert(0, path)
from auth import *
from etc import *
from error import *
def needLoggedin(f):
def wrap_kargs(*args, **kws):
this = args[0]
if this.logged_in:
return f(*a... |
from channels.exceptions import DenyConnection
from channels.generic.websocket import JsonWebsocketConsumer
from django.contrib.auth import get_user_model
class NonAnonymousJsonWebsocketConsumer(JsonWebsocketConsumer):
"""
Only allows non anonymous users to connect
"""
user = None
def connect(se... |
from django.contrib.auth.models import User
def _can_add_virtualhost(request):
'''
Check if user can to add a new virtual host
'''
return request.user.has_perm('manager.add_virtualhost')
def auth(request):
'''
Additional context processor for hostmanager
'''
response = {
'us... |
# Copyright 2016 The Bazel 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 applicable la... |
# SPDX-FileCopyrightText: (c) 2021 Artёm IG <github.com/rtmigo>
# SPDX-License-Identifier: MIT
from typing import Optional, Iterable, Tuple
class FilterBase:
def __init__(self):
self._pairs = dict()
def _set_or_remove(self, key: str, val: Optional[str]):
if val is not None:
self.... |
import oembed
consumer = oembed.OEmbedConsumer()
endpoint = oembed.OEmbedEndpoint('http://www.flickr.com/services/oembed', \
['http://*.flickr.com/*'])
consumer.addEndpoint(endpoint)
response = consumer.embed('http://www.flickr.com/photos/wizardbt/2584979382/')
print response['url']
... |
from flask import Flask, jsonify, request
import numpy as np
import PIL
from PIL import Image
from keras.engine.saving import model_from_json
from keras.models import load_model
app = Flask(__name__)
json_file = open('model/model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
model = model_from_js... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
... |
from setuptools import setup
setup(
name='cdiscountpriceparser',
version='0.0.2',
description='price parser of cdiscount product.',
package_dir={'cdiscount_parser': 'cdiscount_parser'},
packages=["cdiscount_parser"],
install_requires=[
"beautifulsoup4 ~= 4.9.0",
"urllib3 ~= 1.25.... |
from pyzeta.datatypes.maybe import Maybe, Just, Nothing, fold
from pyzeta.typeclasses.semigroup import Semigroup, mappend
from pyzeta.registry import register
class MaybeSemigroup(Semigroup):
@staticmethod
def mappend(x, y):
if x is Nothing: return y
if y is Nothing: return x
return J... |
import FWCore.ParameterSet.Config as cms
pfSimpleInclusiveSecondaryVertexHighPurBJetTags = cms.EDProducer("JetTagProducer",
jetTagComputer = cms.string('candidateSimpleSecondaryVertex3TrkComputer'),
tagInfos = cms.VInputTag(cms.InputTag("pfInclusiveSecondaryVertexFinderTagInfos"))
)
|
# -*- coding: utf-8 -*-
"""
Please read the function`s docstring :)
"""
import math
import bisect
import numpy as np
from tixi import tixiwrapper
from tigl import tiglwrapper
tixi = tixiwrapper.Tixi()
tixi.open('./aircraft.xml')
tigl = tiglwrapper.Tigl()
tigl.open(tixi, 'AircraftModel')
def get_airfoil_points(wing_... |
"""
***************************************************************************************
* Title: RouterAdmin.py
* Author: Ashwin V Prabhu
* Date: May 23, 2017 (last commit)
* Code version: 1.0
* Availability: https://github.com/prabhuvashwin/Computer-Networks/blob/master/Distance%20Vector%20Routing/R... |
# Author : Babu Baskaran
# Date : 07/04/2019 Time : 23:52 pm
# Solution for problem number 9
# Version 1.0
# Importing sys funtion
import sys
#assigning file name into variable
fileName =sys.argv[1]
#Open the file in read mode
fileOpen=open(fileName,'r')
#open the entire lines in the file
totalLines=fileOpen.read... |
from rrutil import *
send_gdb('b breakpoint')
expect_gdb('Breakpoint 1')
send_gdb('c')
expect_gdb('Breakpoint 1, breakpoint')
send_gdb('c')
expect_gdb('Breakpoint 1, breakpoint')
# Now we should be in the clone() thread. checkpoint here.
send_gdb('checkpoint');
expect_gdb('= 1')
send_gdb('restart 1');
expect_gdb('Br... |
from typing import List
from pyhcl.ir.low_ir import *
from pyhcl.ir.low_prim import *
from pyhcl.passes._pass import Pass
@dataclass
class ExpandAggregate(Pass):
def run(self, c: Circuit) -> Circuit:
modules: List[DefModule] = []
def flip_direction(d: Direction) -> Direction:
if isinst... |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... |
from flask import render_template
from flask_login import login_required
from flask_paginate import get_page_args
from app import db
from app.controllers.dashboard_controller import dashboard_controller
from app.controllers.pagination import get_pagination
from app.models.questions import Questions
from app.models.ele... |
import itertools
import pytest
from flex.loading.schema import (
swagger_schema_validator,
)
from flex.loading.schema.host import decompose_hostname
from flex.exceptions import ValidationError
from flex.error_messages import MESSAGES
from tests.utils import (
assert_message_in_errors,
assert_path_not_in_e... |
#
# Clipart Studio 0.5.3
# Zack Hable
# Python 3.4 & PyGame 1.9.2 Alpha
#
# please note that all print statements are NOT shown in the program window, as pygame makes its own window for graphics
# these are simply left for debug purposes
import pygame, time, os
def resetboxcolor():
circlebox = pygame.d... |
class Solution:
# @param {TreeNode} root
# @return {boolean}
def isBalanced(self, root):
self.compute_height(root)
def get_balance(node):
if not node:
return True
if node.left:
l = node.left.height
else:
l =... |
class EPOPatent:
def __init__(self, patent_number, applicants, inventor_names, patent_title, patent_abstract, patent_labels):
self.patent_number = patent_number
self.applicants = applicants
self.inventor_names = inventor_names
self.patent_title = patent_title
self.patent_abs... |
# import classes and functions
from pytorch_trainer.training.extensions._snapshot import snapshot # NOQA
from pytorch_trainer.training.extensions._snapshot import snapshot_object # NOQA
from pytorch_trainer.training.extensions.evaluator import Evaluator # NOQA
from pytorch_trainer.training.extensions.fail_on_nonnumb... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/12/23 20:10
# @Author : uyplayer
# @Site : uyplayer.pw
# @File : Transformer-tweets.py
# @Software: PyCharm
'''
http://jalammar.github.io/illustrated-transformer/
https://medium.com/inside-machine-learning/what-is-a-transformer-d07dd1fbec... |
# **************************************************************************** #
# Air Hockey Table Project
# Author: Ricardo Valverde
# -------------------------
#This Code is Created for UCR's EE175 Senior Design Project
# This Code contains The Object Border
#For Pygame Documentation please see:
#https://www.pyg... |
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sys
import seaborn as sns
import random
import sys
import datetime
sys.path.append(os.path.abspath(".."))
import config
def pie_chart(dataset,var_aim, topf = None, contr... |
import itertools
from snailfish import Pair
input_pairs = []
with open('input.txt') as input_file:
for line in input_file:
input_pairs.append(Pair.from_string(line.rstrip()))
max_magnitude = max((x + y).clone().reduce().magnitude() for x, y in itertools.permutations(input_pairs, 2))
print("Largest magni... |
try:
arquivo = open('')
except OSError:
print('Ocorreu um erro!')
else:
print('Nao houve erro! Continuando...')
finally:
print('Finanlizando processo!')
if 'close' in dir(arquivo):
arquivo.close()
|
from .point import Point
class Input(Point):
"""
Input of a block
"""
def __init__(self, x: float, y: float, direction: str = None):
"""initializes an input"""
super().__init__(x, y, direction)
def __repr__(self):
"""represents an input"""
return f'Input({self.... |
# Basic Calculator
# assumption: the expression is valid, integers are non-negative
# may have white space
class Solution(object):
def calculate(self, s):
stack = [[]] # for s that starts without "("
num = 0
for i, char in enumerate(s):
if char == ' ':
continue
... |
#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "L... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##############################################################################
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# #
# Licensed under the Amazon Software Lic... |
#!/usr/bin/env python
#
# Author: Yipeng Sun
# License: BSD 2-clause
# Last Change: Fri May 28, 2021 at 03:43 AM +0200
from pathlib import Path
from itertools import permutations
from collections.abc import Iterable
from pyUTM.io import WirelistNaiveReader, PcadNaiveReader
from UT_Aux_mapping.const import input_dir
... |
import curses
from castero import helpers
from castero.config import Config
from castero.menu import Menu
from castero.menus.chronomenu import ChronoMenu
from castero.perspective import Perspective
from castero.player import Player
class ChronoPerspective(Perspective):
"""The chronological perspective.
This... |
import numpy as np
import soundfile as sf
import streamlit as st
from pedalboard import Pedalboard
import viz
from plugins import plugins
def load_audio(filename: str) -> tuple:
"""Load input audio file.
Args:
filename (str): Audio filename
Returns:
audio (np.array), sample_rate (float)... |
""" Test API Client """
import os
import pytest
from mars_insight.api import Client
from mars_insight.models import (
InsightMeasurement,
InsightWeather,
)
API_KEY = os.environ['INSIGHT_API_KEY']
def test_client_class():
""" Test object creation """
client = Client(API_KEY)
assert isinstance(cl... |
def func(x):
return x ** 2
__transonic__ = ("0.3.0.post0",)
|
# Copyright (c) 2021, Xu Chen, FUNLab, Xiamen University
# All rights reserved.
from envs.sse.scenarios import load
from envs.sse.environment import SiteSpecificEnv
def SSEEnv(args, is_base, seed=0):
'''
TODO:
'''
# load scenario from script
scenario = load(args.scenario_name + ".py").Scenario()
... |
"""Tests for the HomeKit AID manager."""
import os
from zlib import adler32
from asynctest import patch
import pytest
from homeassistant.components.homekit.aidmanager import (
AID_MANAGER_STORAGE_KEY,
AccessoryAidStorage,
get_system_unique_id,
)
from homeassistant.helpers import device_registry
from homea... |
test = {
'name': 'shuffle',
'points': 0,
'suites': [
{
'cases': [
{
'code': r"""
>>> shuffle(range(6))
[0, 3, 1, 4, 2, 5]
>>> suits = ['♡', '♢', '♤', '♧']
>>> cards = [card(n) + suit for n in range(1,14) for suit in suits]
>>> cards[:12... |
from types import FunctionType, MethodType, GeneratorType
from .just import Just
JustType = Just(type, identifier='JustType')
JustBool = Just(bool, identifier='JustBool')
JustInt = Just(int, identifier='JustInt')
JustFloat = Just(float, identifier='JustFoat')
JustComplex = Just(complex, identifier='JustComplex')
JustS... |
#
# PySNMP MIB module DS3-3COM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DS3-3COM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:39:35 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# The MIT License (MIT)
# Copyright (c) 2015 @ Toan Tran
# 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 li... |
from math import pi
import jax.numpy as jnp
# from ..constants import C, G, MSUN
def Psi(f: jnp.ndarray, theta: jnp.ndarray) -> jnp.ndarray:
"""
Computes the phase of the waveform. Sets time and phase of coealence to be zero.
Returns:
--------
phase (array): Phase of the GW as a function of freq... |
# Copyright 2020 Chen Bainian
# Licensed under the Apache License, Version 2.0
import argparse
from colcon_core.package_discovery import add_package_discovery_arguments
from colcon_core.plugin_system import satisfies_version
from colcon_core.verb import VerbExtensionPoint
from colcon_ed.edit_tools import edit_target_... |
import re
S = input()
print("\n".join(filter(None, re.split("[\.,]*", S))))
|
'''
> Simulation constants:
n_actions:
Number of allowed actions. The first 4 actions correspond to N,S,E,W.
The 5th action is toggle dig, if that option is set to True.
Set this number to one higher than the number of actions to allow
for a "do nothing" action.
allow_dig_toggle:
Set the 5th action to toggle between ... |
import unittest
import ray
from ray.rllib.agents.a3c import A2CTrainer
class TestA2C(unittest.TestCase):
"""Sanity tests for A2C exec impl."""
def setUp(self):
ray.init()
def tearDown(self):
ray.shutdown()
def test_a2c_exec_impl(ray_start_regular):
trainer = A2CTrainer(
... |
import xml.etree.ElementTree as ET
import re
import json
from os import walk
def getFiles():
dataDir = '.\\data\\' # set the dir to walk.
for rootDir, dirs, files in walk(dataDir): # loop through the files in dataDir.
return rootDir, files
def parseXML(file):
tree = ET.parse(file) #... |
# pylint:disable=unused-argument,useless-return
import ailment
from ...errors import UnsupportedNodeTypeError
from .region_identifier import MultiNode
from .structurer_nodes import CodeNode, SequenceNode, ConditionNode, SwitchCaseNode, LoopNode, CascadingConditionNode
class SequenceWalker:
"""
Walks a Sequen... |
from enum import Enum
from selve.communication import Command
from selve.protocol import MethodCall, ServiceState
from selve.protocol import ParameterType
from selve.protocol import DeviceType
from selve.protocol import CommandType
from selve.commands import Commands, CommeoCommandCommand, CommeoDeviceCommand, CommeoE... |
def my_sqrt(x):
left = 0
right = x
while left <= right:
mid = (left + right) // 2
if (x - mid ** 2) >= 0 and (x - (mid + 1) ** 2) < 0:
return mid
elif mid ** 2 > x:
right = mid - 1
else:
left = mid + 1
return 0
if __name__ == '__mai... |
#Copyright (c) 2020 Hanwei Wu
import torch
def data_standlization(dataset):
"""standardize a tensor dataset
Args:
dataset -- tensors of shape (n, T)
Returns:
dataset -- tensors of shape (n, T), contains normalized values.
"""
means = dataset.mean()
stds = dataset.std()
dataset = (d... |
class BifrostError(Exception):
pass |
"""Time series feature generators as Scikit-Learn compatible transformers."""
from itertools import combinations
from typing import List, Optional
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from s... |
from django.db import models
from django_camunda.fields import ProcessDefinitionField
class Camunda(models.Model):
process_definition = ProcessDefinitionField(blank=True)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.