content stringlengths 5 1.05M |
|---|
# Copyright 2017 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 required by applicable law or agre... |
#!/usr/bin/env python3
#
#Copyright 2022 Kurt R. Brorsen
#
# 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 a... |
import cas
import cas.common.utilities as utilities
import sys
import json
import multiprocessing
from collections.abc import Sequence, Mapping
from pathlib import Path
import simpleeval
import jsonschema
from dotmap import DotMap
def extend_validator_with_default(validator_class):
validate_properties = validat... |
"""
project = "Protecting Patron Privacy on the Web: A Study of HTTPS and Google Analytics Implementation in Academic Library Websites"
name = "2_return_url_json.py",
version = "1.0",
author = "Patrick OBrien",
date = "07/25/2018"
author_email = "patrick@revxcorp.com",
description = ("Step 2 of 3: Extract, transform, ... |
from Organism.Organism import Organism
from Organism.Animal import *
from Organism.Plant import *
|
import sys
import json
import string
import random
POPULAR_NGRAM_COUNT = 10000
#Population is all the possible items that can be generated
population = ' ' + string.ascii_lowercase
def preprocess_frequencies(frequencies, order):
'''Compile simple mapping from N-grams to frequencies into data structures to help c... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from abc import ABC
import xml.etree.ElementTree as ET
import pandas as pd
import os
import re
import sys
import logging
# setup logger
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
from .operator import IOperator
class PascalVOC(... |
from django.apps import AppConfig
class WorkouttrackerConfig(AppConfig):
name = 'workouttracker'
|
""" Unit test for the SqliteRecorder. """
import errno
import os
from shutil import rmtree
from tempfile import mkdtemp
import time
import numpy as np
from sqlitedict import SqliteDict
from openmdao.core.problem import Problem
from openmdao.core.group import Group
from openmdao.core.parallel_group import ParallelGro... |
import struct
from enum import Enum
from collections import namedtuple
from typing import List, Dict
from src.utils import *
ibeacon_base_format = '!16s2s2sb'
ibeacon_base_vars = ['UUID', 'Major', 'Minor', 'RSSI']
eddystone_base_format = '!10s6sb'
eddystone_base_vars = ['Namespace', 'InstanceID', 'RSSI']
types = ... |
from __future__ import print_function
# read a pedigree and store info in a dictionary
class Pedigree:
def __init__(self, ped, samples):
# dict of list of samples in family
self.samples_by_family = {}
# dict of family by sample
self.families_by_sample = {}
# all info from pe... |
# For statistic operation
from library.math_tool_box import StatMaker
# for random number generator
from library.linear_congruedntial_generator import random_number_gen
# For measuring elapsed time elapsed
from library.measure_time_performance import measure_elapsed_time
### 1. Generate 5 random numbers
rando... |
# add common library
from logger import logger, log
logger.setup('./logs', name='efficientDet-d5-cutmix-sgd')
from lib import *
from config import config
from dataset import WheatDataset, get_train_transforms, get_valid_transforms
from utils import seed_everything, read_csv, kfold
from trainer import Trainner, collate... |
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, TypeVar
import torch
from torch import Tensor
import pytorch_lightning as pl
class Node(dataclass):
size: torch.Size
name: str = None
pooling_function: Callable[[Tensor], Tensor] = torch.sum
activation_function: Callable[... |
from django.db import models
from django.conf import settings
import time
import json
from datetime import datetime
import hashlib
import uuid
from wsgiref.handlers import format_date_time
from django.core.urlresolvers import reverse
from authz_group.models import Crowd
class Thread(models.Model):
name = models.Ch... |
"""Change parcel attachments to parcel map
Revision ID: 98db6b34d1a3
Revises: fc8dd9d7a9d7
Create Date: 2019-11-15 07:38:48.934387
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '98db6b34d1a3'
down_revision = 'fc8dd9d7... |
#########################################################################
# Helper file for ExportTools
# Written by dane22 on the Plex Forums, UKDTOM on GitHub
#
# This one contains the valid fields and attributes for movies
#
# To disable a field not needed, simply put a # sign in front of the line,
# and it'll be om... |
"""
Copyright © retnikt <_@retnikt.uk> 2020
This software is licensed under the MIT Licence: https://opensource.org/licenses/MIT
"""
from typing import TypedDict, cast
__all__ = ["NAME", "VERSION", "URL", "LICENCE", "LICENSE"]
class _Licence(TypedDict):
name: str
url: str
class _Author(TypedDict):
name... |
"""
Django settings for back project.
Generated by 'django-admin startproject' using Django 3.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
impor... |
def partition(graph, source):
"""
The function partitions a graph into two sets if bi-partite partitioning is possible
otherwise returns 'None'
"""
visited = dict()
for node in graph:
visited[node] = False
one = set()
two = set()
flag = True
queue1 = list()
queue2 = l... |
from application import db
# class id(db.Model):
# id = db.Column(db.Integer, primary_key=True)
|
import pickle
from typing import Dict
from datetime import date as dt
import cv2
import imutils
import numpy as np
import face_recognition
from src.settings import (
DLIB_MODEL, DLIB_TOLERANCE,
ENCODINGS_FILE
)
from src.libs.base_camera import BaseCamera
from src.models import StudentModel, AttendanceModel
... |
from django.urls import path
from rest_framework.routers import SimpleRouter
from accounts.views import CreateUserView, LoginUserView
router = SimpleRouter()
router.register("accounts", CreateUserView)
urlpatterns = [
path("login/", LoginUserView.as_view()),
]
urlpatterns += router.urls
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Dataset conversion script
Author: Gertjan van den Burg
"""
import json
import argparse
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"-s",
"--subsample",
help="Number of observations to skip during subsam... |
from typing import List
import collections
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]:
trees = collections.defaultdict()
trees.default_factory ... |
# Copyright (c) 2021, Stanford niversity
"""Tests for peak finder."""
import numpy as np
import pandas as pd
from util import peak_finder
from dataclasses import dataclass
from skimage.filters import gaussian
@dataclass()
class Point:
"""A class for defining a point in 3D."""
x: int
y: int
z: int
... |
#!/usr/bin/env python
########################################################################
# FastGeneralizedSuffixArrays v0.1 #
# (c) 2011 Mark Mazumder #
# markmaz.com #
####... |
#!/usr/bin/env python3
import json, os
from cryptography.fernet import Fernet
key= b'FpOza5rnPiW1Jv1oJzF6Ef0LitGrZ2nyQcPCG5kYmFc='
fernet = Fernet(key)
def isConfig(path='config.json'):
return os.path.isfile(path)
def getConfig(path='config.json'):
if isConfig(path):
configFile= open(path, 'r')
configContent=... |
import base64
import bottle
import os
import random
import time
from bottle import run, template, error, route, request, abort, static_file
from pymongo import Connection, errors
from pymongo.errors import ConnectionFailure
from utils.utils import get_domain
while True:
try:
connection = Connection(
... |
import unittest
import numpy
import os
import sys
sys.path.insert(0, os.pardir)
sys.path.insert(0, os.path.join(os.pardir, 'openmoc'))
import openmoc
class TestMaterials(unittest.TestCase):
def setUp(self):
sigma_f = numpy.array([0.000625, 0.135416667])
nu_sigma_f = numpy.array([0.0015, 0.325])
... |
import os
import time
import argparse
import datetime
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
import math
import itertools
from tqdm import tqdm
import tools
import gen... |
from __future__ import print_function
import z5py
import h5py
import numpy as np
import collections
import datetime
import logging
def add_ds(target, name, data, chunks, resolution, offset, **kwargs):
if name not in target:
logging.info("Writing dataset {0:} to {1:}".format(name, target.path))
ds ... |
import json
from contextlib import contextmanager
from django.conf import settings
from elasticsearch import Elasticsearch
from elasticsearch.exceptions import NotFoundError, RequestError, ConnectionError
from elasticsearch.helpers import bulk
DOCTYPE = 'doc'
ES_TIMEOUT = '100s'
ES_REQUEST_TIMEOUT = 100
ES_BATCH_REQUE... |
"""
Решить в целых числах уравнение: (ax+b) / (cx+d) =0
Формат ввода
Вводятся 4 числа: a,b,c,d; c и d не равны нулю одновременно.
Формат вывода Необходимо вывести все решения, если их число конечно, “NO” (без кавычек), если решений нет,
и “INF” (без кавычек), если решений бесконечно много.
"""
a, b, c, d = int(input... |
"""
stanCode Breakout Project
Adapted from Eric Roberts's Breakout by
Sonja Johnson-Yu, Kylie Jue, Nick Bowman,
and Jerry Liao
Name: Kevin Chen
"""
from campy.graphics.gwindow import GWindow
from campy.graphics.gobjects import GOval, GRect, GLabel
from campy.gui.events.mouse import onmouseclicked, onmousemoved
from ca... |
def palindrome_pairs(list):
answer = []
for i, x in enumerate(list):
# print x, x[::-1]
if x[::-1] in list:
if i != list.index(x[::-1]):
# print 'index 1', i, 'index 2', list.index(x[::-1])
a = (i, list.index(x[::-1]))
answer.append(a)
... |
from floodsystem.stationdata import build_station_list
from floodsystem.geo import rivers_by_station_number
stations = build_station_list()
print("\n"+str(rivers_by_station_number(stations,9))+"\n")
|
"""
一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。
现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径?
网格中的障碍物和空位置分别用 1 和 0 来表示。
说明:m 和 n 的值均不超过 100。
示例 1:
输入:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
输出: 2
解释:
3x3 网格的正中间有一个障碍物。
从左上角到右下角一共有 2 条不同的路径:
1. 向右 -> 向右 -> 向下 -> 向下
2. 向下 -> 向下... |
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range
pickle_file = 'notMNIST.pickle'
with open(pickle_file, 'rb') as f:
save = pickle.load(f)
train_dataset = save['train_dataset']
train_labels = save['train_lab... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Python utilities used for setting up the resources needed to complete a
model run, i.e. generating ktools outputs from Oasis files.
"""
from __future__ import print_function
import glob
import logging
import tarfile
from itertools import chain
import shutilwh... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 17 11:27:35 2020
Compute an average iou between two images.
For each image in train_set, the pairwise iou for rest of images in dataset are computed.
@author: dipu
"""
import numpy as np
import os
import pickle
from multiprocessing import Pool, Val... |
import os
import sys
import open3d as o3d
import numpy as np
import logging
import torch
import torch.multiprocessing as mp
try:
mp.set_start_method('forkserver') # Reuse process created
except RuntimeError:
pass
import torch.distributed as dist
from config import get_config
from lib.test import test
from lib.... |
import copy
import yaml
# Global constants
N_CHROM = 6
# Set default arguments
# Base config file to use
base_cfg_id = 'H_1-combined'
path_base_cfg = 'config/H_1-combined.yml'
# Pattern for output
pattern_output = 'powerAnalysis/data/simChrom_%s.%s'
# Number of replicates
n_replicates = 10
# Path for output conf... |
#!/usr/bin/env python
# encoding: utf-8
# This file is part of CycloneDX Python
#
# 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 ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 19 2020
@author: Sergio Llana (@SergioMinuto90)
"""
from abc import ABC, abstractmethod
import pandas as pd
from utils import read_json, read_event_data, tracking_data, to_single_playing_direction
from processing import PassingNetworkBuilder
cl... |
'''
/django_api/pitch/views.py
-------------------------
Organize the views of pitch
'''
import json
from django.http import JsonResponse
from django_api.world_week.pitch.models import Pitch
def all_scores(request):
if request.method == 'GET':
all_pitchs = list(Pitch.objects.all())
scores = []
... |
#!/usr/bin/env python3
# Written by Sem Voigtlander (@userlandkernel)
# Licensed under the MIT License
# Apple if you are monitoring this, please add anti-bot verification to your identity service provider (eg: captcha!)
import os
import sys
import argparse
import requests
import time
import datetime
from bs4 import B... |
from re import search
from PyQt5 import QtWidgets
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox
from numpy.core.numeric import count_nonzero
from app import Ui_MainWindow
import sys , os
import librosa
import os
import librosa.display
from librosa.core import load
from pydub import ... |
"""
Configuration for docs
"""
# source_link = "https://github.com/[org_name]/medmanager"
# docs_base_url = "https://[org_name].github.io/medmanager"
# headline = "App that does everything"
# sub_heading = "Yes, you got that right the first time, everything"
def get_context(context):
context.brand_html = "Medical Ma... |
#!/usr/bin/env python
import sys
import numpy as np
import abipy.abilab as abilab
import abipy.flowtk as flowtk
import abipy.data as abidata
def gs_input(x=0.7, ecut=10, acell=(10, 10, 10)):
"""
This function builds an AbinitInput object to compute the total energy
of the H2 molecule in a big box.
Ar... |
import pandas as pd
import numpy as np
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import pickle
data = pd.read_csv("../data/cleaned_data.csv")
data.drop(['Unnamed: 0', 'Price_m2'], axis=1... |
import os
import sys
import time
import random
import pandas as pd
import yfinance as yf
from loguru import logger
from tqdm.auto import tqdm
from datetime import datetime
from datetime import timedelta
from finam import Exporter, Market, Timeframe
# TODO
# disabling progress bar
# disabling logs
# directory by defaul... |
from netmiko import ConnectHandler, ssh_exception
def netmiko(host: str = None, username: str = None, password: str = None) -> object:
"""Logs into device and returns a connection object to the caller. """
credentials = {
'device_type': 'cisco_ios',
'host': host,
'username': us... |
from __future__ import unicode_literals, print_function
from bs4 import BeautifulSoup
from scraper import AbsractScraper, RssFeed
import time
FOX_Latest = 'http://feeds.foxnews.com/foxnews/latest?format=xml'
FOX_Politics = 'http://feeds.foxnews.com/foxnews/politics?format=xml'
FOX_Science = 'http://feeds.foxnews.com/... |
# Generated by Django 3.1.3 on 2021-05-20 18:24
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('onlinecourse', '0002_auto_20210520_1823'),
]
operations = [
migrations.AlterField(
model_name='... |
import pytest
from web_error import error
class A404Error(error.NotFoundException):
code = "E404"
message = "a 404 message"
class A401Error(error.UnauthorisedException):
code = "E401"
message = "a 401 message"
class A400Error(error.BadRequestException):
code = "E400"
message = "a 400 mess... |
# Copyright (c) 2019 Jarret Dyrbye
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php
import time
import RPi.GPIO as GPIO
from twisted.internet import threads
from twisted.internet import reactor
from twisted.internet.task import Lo... |
import math
N = int(input())
X = [0] * N
Y = [0] * N
for i in range(N):
X[i], Y[i] = map(int, input().split())
ans = 0
for i in range(N):
for j in range(i + 1, N):
x1, y1, x2, y2 = X[i], Y[i], X[j], Y[j]
ans = max(ans, math.sqrt(abs(x1 - x2) ** 2 + abs(y1 - y2) ** 2))
print(ans)
|
class TransactionFactory:
def __init__(self, logger):
self.logger = logger
def get_transaction(self, bank_transaction):
"""
return an object HbTransaction or an object derived from him.
"""
raise NotImplementedError
|
# coding=utf8
import logging
import random
import numpy as np
import tensorflow as tf
from seq2seq_conversation_model import seq2seq_model
_LOGGER = logging.getLogger('track')
def test_tokenizer():
words = fmm_tokenizer(u'嘿,机器人同学,你都会些啥?')
for w in words:
print(w)
def test_conversation_model():
... |
from pathlib import Path
def write_schemas(schemas, directory):
for i, schema in enumerate(schemas):
filename = Path(directory) / schema.filepath.lstrip("/")
filename.parent.mkdir(parents=True, exist_ok=True)
if i == 0:
target_filename = filename
with open(filename, "wb... |
from flask import render_template, redirect, url_for, flash, session, request, g, abort
from functools import wraps
from app.admin.forms import LoginForm, AdminForm, RoleForm, AuthForm, MovieForm, TagForm, PreviewForm
from app.models import Admin, Tag, Movie, Preview, User, Comment, Moviecol, Oplog, Adminlog, Userlog, ... |
from anthill.framework.forms import Form
from anthill.framework.utils.translation import translate as _
|
from unittest import TestCase
import requests
class EmailTest(TestCase):
@classmethod
def setUpClass(cls):
cls.request = requests.Session()
cls._url = 'http://localhost:8000/api/v1/email/'
def test_email_valid(self):
data = {
"email": "at8029@srmist.edu.in",
... |
from __future__ import annotations
from dataclasses import dataclass
from base58 import b58encode
from .keypair import Keypair
from .publickey import PublicKey
from nacl.signing import VerifyKey
from nacl.exceptions import BadSignatureError
from .core.instructions import Instruction, AccountMeta
from .core.message imp... |
from json import load
import pip._vendor.requests as requests
from aws_cdk import (
core,
aws_ec2 as ec2,
aws_iam as iam,
aws_route53 as r53
)
# this ami for ap-northeats-1 region .
# amzn-ami-hvm-2016.09.0.20160923-x86_64-gp2
# find your computer public ip .
external_ip = requests.get('https://checkip... |
from maya.api import OpenMaya
from mango.vendor import apiundo
def execute_modifier(modifier):
"""
Execute a modifier object. After this the apiundo package is used to
ensure that the command is undo/redo-able within Maya.
:param OpenMaya.MDGModifier/OpenMaya.MDagModifier modifier:
"""
modif... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
plt.clf()
plt.close('all')
y = np.linspace(-4,4,1000)
lam0 = np.float(1e-1)
lam1 = np.float(1)
lam2 = np.float(1e1)
###############################################################################
f1 = np.max([np.zeros... |
# -*- coding: utf-8 -*-
from ucloud.core.exc._exc import (
UCloudException,
ValidationException,
RetCodeException,
RetryTimeoutException,
)
__all__ = [
"UCloudException",
"ValidationException",
"RetCodeException",
"RetryTimeoutException",
]
|
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'pytopo.settings')
app = Celery('pytopo')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
@app.task(bind=True)
def debug_task(self):
print('R... |
import logging
import math
import numpy as np
#TODO: Remove this line
from PySide.QtGui import QGraphicsPolygonItem, QImage
from PySide.QtGui import QColor, QGraphicsPixmapItem, QPixmap
from PySide.QtCore import QPoint, QPointF, Qt
from traits.api import Bool, Enum, DelegatesTo, Dict, HasTraits, Instance, Int, List... |
from django.apps import AppConfig
class CryptoserverConfig(AppConfig):
name = 'cryptoserver'
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re, sys, time, os, subprocess
import pickle as pk
from rtmbot.bin.run_rtmbot import main
from Settings import initSettings
def editConf(Settings):
'Will edit the rtmbot.con'
#Reading lines of rtmbot.conf
with open('rtmbot.conf',"r... |
from anthill.common.options import options
from anthill.common import server, handler, keyvalue, database, access
from . model.deploy import DeploymentModel
from . model.bundle import BundlesModel
from . model.data import DatasModel
from . model.apps import ApplicationsModel
from . import handler
from . import admin... |
"""
homeassistant.components.automation.state
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Offers state listening automation rules.
For more details about this automation rule, please refer to the documentation
at https://home-assistant.io/components/automation/#state-trigger
"""
import logging
from homeassistant.helper... |
# pylint: disable = pointless-statement, pointless-string-statement
# pylint: disable = no-value-for-parameter, expression-not-assigned
# pylint: disable = too-many-lines, redefined-outer-name
import os
import pathlib
from typing import List, Optional
from pymedphys._imports import streamlit as st
from typing_extensi... |
#!/usr/bin/python37
# -*- coding : utf-8 -*-
import os
import sys
from urllib.parse import urlparse
import re
from bs4 import BeautifulSoup
import requests
import html2epub
DIR = "C:\\Users\\baoju\\Desktop\\" # 输出epub文件的路径
html_template = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</... |
from django.conf import settings
def mediawiki_site_settings(request):
return {
'MEDIAWIKI_API_ENDPOINT': settings.MEDIAWIKI_API_ENDPOINT,
'MEDIAWIKI_BASE_URL': settings.MEDIAWIKI_BASE_URL,
'MEDIAWIKI_INDEX_ENDPOINT': settings.MEDIAWIKI_INDEX_ENDPOINT,
'PROPERTY_BASE_URL': settings.... |
import os
import re
import json
from cfg import *
class Preprocesser:
def __init__(self, origin_path, target_path, label_path):
self.origin_path = origin_path
self.target_path = target_path
self.label_path = label_path
def merge(self):
print('get original file list...')
... |
import elasticsearch
import boto3
from elasticsearch import Elasticsearch, RequestsHttpConnection
from requests_aws4auth import AWS4Auth
INDEX = "toyo_items"
host = 'search-nakamura196-rgvfh3jsqpal3gntof6o7f3ch4.us-east-1.es.amazonaws.com'
profile_name = "default"
region = "us-east-1"
if profile_name == None:
es... |
# -*- coding:utf-8 -*-
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
from decouple import config
from grpc import StatusCode
from grpc._channel import _Rendezvous, _UnaryUnaryMultiCallable
logger = logging.getLogger(__name__)
# The maximum number of retries
_MAX... |
from math import pi
from typing import List
from rlbot.utils.rendering.rendering_manager import RenderingManager
from rlbot.utils.structures.game_data_struct import GameTickPacket
from rlutilities.linear_algebra import vec3, dot, look_at, axis_to_rotation, cross
from rlutilities.simulation import Ball, Input, Cu... |
array= [0,0,0,0,0,0]
for i in range(len(array)):
array[i] = len(array)-i
|
import logging
import pytest
from pygate_grpc.client import PowerGateClient
from pygate_grpc.types import User
logger = logging.getLogger(__name__)
@pytest.fixture(scope="module")
def user(pygate_client: PowerGateClient):
return pygate_client.admin.users.create()
@pytest.fixture(scope="module")
def staged_fi... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class VaultL... |
import collections
import gym
import numpy as np
class StateOccupancyCounter(gym.Wrapper):
def __init__(self, env):
super().__init__(env)
self.reset()
def reset(self):
self.state_occupancy_counts = collections.Counter()
obs = self.env.reset()
self.prev_obs_hash = None... |
#! /usr/bin/env python3
import argparse
import yaml
def merge_two_dict(d1, d2):
result = {}
for key in set(d1) | set(d2):
if isinstance(d1.get(key), dict) or isinstance(d2.get(key), dict):
result[key] = merge_two_dict(d1.get(key, dict()), d2.get(key, dict()))
else:
res... |
"""
The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0).
https://creativecommons.org/licenses/by/4.0/
https://creativecommons.org/licenses/by/4.0/legalcode
Copyright (c) COLONOLNUTTY
"""
from typing import Union
from sims4communitylib.enums.stat... |
def printStudentDetails(name, age, marks, stream):
print('Student details')
print('Name: {}, Age: {}, Marks: {}, Stream: {}'.format(
name, age, marks, stream
))
printStudentDetails('pema', 28, 300, 'Datasci')
#unpacking
d = {'name': "john", "stream": "ece", 'age': 17, 'marks': 700}
p... |
from botlang.evaluation.values import ReturnNode
def return_node(environment, inner_node):
try:
environment.lookup(Slots.DIGRESSION_RETURN)
except NameError:
return inner_node
else:
return ReturnNode(inner_node)
def is_disgression(environment):
return Slots.digression_started... |
#Test001.py
def HelloWorld():
print ("Hello World")
def add(a, b):
return a+b
def TestDict(dict):
print (dict)
dict["Age"] = 17
return dict
class Person:
def greet(self, greetStr):
print (greetStr)
#print add(5,7)
#a = raw_input("Enter To Continue...")
|
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 4 02:33:34 2020
@author: Admin
"""
import pandas as pd
import numpy as np
import parselmouth
from parselmouth.praat import call
import nolds
from scipy import signal
from scipy.io import wavfile
from pyentrp import entropy
import sys
def measurePitch(v... |
"""Unit tests for the KDE classifier."""
import geomstats.backend as gs
import geomstats.tests
from geomstats.geometry.euclidean import Euclidean
from geomstats.geometry.hyperboloid import Hyperboloid
from geomstats.geometry.hypersphere import Hypersphere
from geomstats.geometry.poincare_ball import PoincareBall
from ... |
description = 'Verify the user can add an action to a test and save it successfully'
pages = ['common',
'index',
'tests',
'test_builder']
def setup(data):
common.access_golem(data.env.url, data.env.admin)
index.create_access_project('test')
common.navigate_menu('Tests')
tes... |
# -*- encode: utf-8 -*-
from random import random, choice, choices
from tqdm import tqdm
from models import Context, Aircraft, Airport, City, Time
from data import context, cities, airline, t
from settings import randbool, randgauss, path_number, aircraft_number, people_number_ratio
population = {}
for city in citie... |
# -*- coding: utf-8 -*-
#
# Copyright 2014 Jaime Gil de Sagredo Luna
#
# 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 a... |
import sys
import os
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QCheckBox, QLineEdit, QMessageBox, QComboBox, QLabel, QFileDialog
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot, QUrl
import sounddevice as sd
# from paddle
import argparse
from pathlib import Path
impo... |
import os
from pathlib import Path
from time import sleep
import pytest
# Trick for initializing a test database
from hypertrainer.utils import TaskStatus, yaml, deep_assert_equal, TestState
TestState.test_mode = True
from hypertrainer.experimentmanager import experiment_manager
from hypertrainer.computeplatformtyp... |
from functools import reduce
from . import GraphError, iterables
from .memo import lambdaize, memoize
from .representations import Object
_undefined = object()
class ScalarType(object):
def __init__(self, name, coerce):
self.name = name
self._coerce = coerce
def __call__(self):
ret... |
import torch
import numpy as np
from torch import nn
import torch.nn.functional as F
from IPython.display import clear_output
def make_tokens(input_text):
r"""Makes a list of all unique characters in the `input_text`.
Parameters
----------
input_text : str
Input text for RNN training. Should ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.