text stringlengths 1 927k |
|---|
#!/bin/env python
# -*- coding: utf-8 -*-
import unittest
import tempfile
import os
from pympi.Praat import TextGrid
class PraatTest(unittest.TestCase):
def setUp(self):
self.tg = TextGrid(xmax=20)
self.maxdiff = None
# Test all the Praat.TextGrid functions
def test_sort_tiers(self):
... |
import tensorflow as tf
import numpy as np
from cbre.util import *
class CBRENet(object):
"""
cbre_net implements the cycly-balanced representation learning for counterfactual inference
The network is implemented as a tensorflow graph. The class constructor
creates an object containing relevant TF no... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="sorting_visualizer",
version="1.0",
author="Debdut Goswami",
author_email="debdutgoswami@gmail.com",
description="A package to visualize various sorting algorithms.",
long_description=... |
import os
from github_client.client import GitHubClient
from utils.painter import paint
if __name__ == '__main__':
user = os.environ['user_name']
password = os.environ['user_password']
client = GitHubClient(user, password)
client.connect()
repositories = client.get_repositories()
user = client.... |
# coding=utf-8
""" Tests for SimAction and action space functions. """
import unittest
from typing import Callable, Dict, List, Any
from unittest.mock import create_autospec
import numpy as np
from gym import Space
from ..action_spaces import (
SimAction,
single_charging_schedule,
zero_centered_single_cha... |
# -*- coding: utf-8 -*-
#
# complexity documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# ... |
from django.conf import settings
from django.conf.urls import patterns, url
# from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'app.views.home', name='home'),
url(r'^graph/$', 'app.views.graph', name='graph'),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root'... |
import os
import numpy as np
from addict import Dict
from PIL import Image
from .reader import Reader
from .builder import READER
__all__ = ['CCPD2019FolderReader']
@READER.register_module()
class CCPD2019FolderReader(Reader):
def __init__(self, root, **kwargs):
super(CCPD2019FolderReader, self).__init_... |
"""
ASGI config for src project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_... |
import black
class GenerationError(Exception):
"""Represents an exception while generating the Python syntax"""
class PythonSyntaxError(GenerationError):
"""Represents an exception in the python syntax"""
class InputError(GenerationError, black.InvalidInput):
"""Raised when the generated Python code i... |
from collections import deque, OrderedDict
from functools import partial
import numpy as np
from rlkit.core.eval_util import create_stats_ordered_dict
from rlkit.samplers.data_collector.base import PathCollector
from rlkit.samplers.rollout_functions import rollout
class ActionAgent():
def __init__(self):
... |
# 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 ... |
import numpy as np
import numpy.random as nr
from plaidrl.exploration_strategies.base import RawExplorationStrategy
class OUStrategy(RawExplorationStrategy):
"""
This strategy implements the Ornstein-Uhlenbeck process, which adds
time-correlated noise to the actions taken by the deterministic policy.
... |
expected_inventory_list = {
'count': 2,
'results': [{'detail': 'http://testserver/api/inventories/1/',
'groups_file': 'web_nornir/nornir_config/example_config/groups.yaml',
'hosts_file': 'web_nornir/nornir_config/example_config/hosts.yaml',
'id': 1,
... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/item/quest/force_sensitive/shared_fs_craft_puzzle_decryption_chip.if... |
# coding: utf-8
import json
import lightgbm as lgb
import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error
try:
import cPickle as pickle
except BaseException:
import pickle
print('Loading data...')
# load or create your dataset
df_train = pd.read_csv('../binary_classification/bin... |
import os
import re
import tempfile
from argparse import ArgumentParser, RawTextHelpFormatter
from typing import Any
from django.conf import settings
from django.db import connection
from django.utils.timezone import now as timezone_now
from scripts.lib.zulip_tools import TIMESTAMP_FORMAT, parse_os_release, run
from ... |
# arvestust:serializers:mixins
from .arvestust_record import ArvestustRecordSerializerMixin |
import os
from google.cloud import secretmanager
class Secret:
def __init__(self):
# Create the Secret Manager client.
self.client = secretmanager.SecretManagerServiceClient()
self.project_id = os.getenv('GOOGLE_CLOUD_PROJECT')
def get_secret(self, secret_id):
# Build the pare... |
#!/usr/bin/env python
'''
tag_generator.py
Copyright 2017 Long Qian
Contact: lqian8@jhu.edu
This script creates tags for your Jekyll blog hosted by Github page.
No plugins required.
'''
import glob
import os
post_dir = '_posts/'
tag_dir = 'tag/'
filenames = glob.glob(post_dir + '*md')
total_tags = []
for filename ... |
from env_wrapper import DIAYN_Skill_Wrapper
from stable_baselines3 import SAC
from stable_baselines3.common.env_checker import check_env
import malmoenv
import gym
from pathlib import Path
xml = Path('/home/zilizhang/DIAYN/mobchase_single_agent.xml').read_text()
env = malmoenv.make()
env.init(xml, 9000)
total_timeste... |
# Copyright (c) 2009-2017 The Regents of the University of Michigan
# This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.
# Maintainer: joaander / All Developers are free to add commands for new features
R""" Electrostatic potentials.
Charged interactions are usually long ranged, an... |
from tensorflow.keras.models import load_model
from clean import downsample_mono, envelope
from kapre.time_frequency import STFT, Magnitude, ApplyFilterbank, MagnitudeToDecibel
from sklearn.preprocessing import LabelEncoder
import numpy as np
from glob import glob
import argparse
import os
import pandas as pd
from tqdm... |
from functools import partial
from pprint import pprint
import matplotlib.pyplot as plt
# import test2
from simglucose.controller.base import Controller
#from datetime import datetime, timedelta, time
import numpy as np
import math
percent_value = 0.05
sign = lambda x: math.copysign(1, x)
normalize_f = lambda x: (x... |
from collections import Iterable
from mathsat import msat_term, msat_env
from mathsat import msat_make_true, msat_make_false
from mathsat import msat_make_constant, msat_declare_function
from mathsat import msat_get_rational_type
from mathsat import msat_make_and as _msat_make_and
from mathsat import msat_make_or as _m... |
import discord
from discord.ext import commands
import aiohttp
import random
class Meme(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def meme(self, ctx):
async with aiohttp.ClientSession() as cs:
async with cs.get("https://www.red... |
'''
Written for DigitalOcean's Hacktoberfest!
Requires cx_Freeze and must be built on Windows :(
Unfortunately, neither cx_Freeze nor py2exe support cross platform compilation
thus, this particular solution was set into motion
'''
import sys
from cx_Freeze import setup, Executable
setup(
name = "RSPET Test", ... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# 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 Apach... |
import asyncio
import dataclasses
import logging
import random
import time
import traceback
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
import aiosqlite
from blspy import AugSchemeMPL
import src.server.ws_connection as ws # lgtm [py/import-and-import-from]
from ... |
# Copyright (c) 2020
# Author: xiaoweixiang
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
__all__ = [
"__title__"... |
# Residual Dense Network for Image Super-Resolution
# https://arxiv.org/abs/1802.08797
# modified from: https://github.com/thstkdgus35/EDSR-PyTorch
from argparse import Namespace
import torch
import torch.nn as nn
from models import register
class RDB_Conv(nn.Module):
def __init__(self, inChannels, growRate, k... |
"""
Decouples SocialApp client credentials from the database
"""
from django.conf import settings
class SocialAppMixin:
class Meta:
abstract = True
# Get credentials to be used by OAuth2Client
def get_app(self, request):
app = settings.SOCIAL_APPS.get(self.id)
from allauth.social... |
import graphene
from graphene_django.types import DjangoObjectType
from .models import Category, Ingredient
class CategoryType(DjangoObjectType):
class Meta:
model = Category
class IngredientType(DjangoObjectType):
class Meta:
model = Ingredient
class Query(object):
category = graphene.Fi... |
# -*- coding: utf-8 -*-
# python-holidays
# ---------------
# A fast, efficient Python library for generating country, province and state
# specific sets of holidays on the fly. It aims to make determining whether a
# specific date is a holiday as fast and flexible as possible.
#
# Authors: dr-prodigy <maurizio.... |
#!/usr/bin/env python
from .utils import *
# This struct's endianness is of the "target"
class TargetStruct(Struct):
a = u16(0xAABB)
# while this struct's endianness is always big.
class SpecificStruct(Struct):
a = u16_be(0xAABB)
class SettingsTests(HydrasTestCase):
def test_priority(self):
s... |
# Generated by Django 2.2.4 on 2019-09-01 00:56
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
import pytest
def test_annotation_with_subtype(
testapp,
submitter_testapp,
annotation_dhs,
annotation_ccre_2,
annotation_dataset
):
testapp.patch_json(
annotation_dhs['@id'],
{'annotation_subtype': 'all'},
status=200)
# annotation_subtype can only be submitted with... |
#!/usr/bin/python
#-*- coding:utf-8 -*-
"""
Author: AsherYang
Email: 1181830457@qq.com
Date: 2017/7/24
"""
class Token():
@property
def access_token(self):
return self.access_token
@property
def access_token(self, value):
self.access_token = value
@property
def expire_in(... |
# Copyright 2015 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
"""
Kernel installation task
"""
import logging
import os
import re
import shlex
from io import StringIO
from teuthology.util.compat import urljoin
from teuthology import misc as teuthology
from teuthology.parallel import parallel
from teuthology.config import config as teuth_config
from teuthology.orchestra import ... |
import torch
import numpy as np
from torch.distributions import Categorical
from typing import Any, Dict, Tuple, Union, Optional
from tianshou.policy import SACPolicy
from tianshou.data import Batch, ReplayBuffer, to_torch
class DiscreteSACPolicy(SACPolicy):
"""Implementation of SAC for Discrete Action Settings.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This script runs tests on the system to check for compliance against different CIS Benchmarks.
No changes are made to system files by this script. Audit only.
License: MIT
"""
from argparse import ArgumentParser
from datetime import datetime
from time import sleep
imp... |
"""
Test for the SmartThings lock platform.
The only mocking required is of the underlying SmartThings API object so
real HTTP calls are not initiated during testing.
"""
from pysmartthings import Attribute, Capability
from pysmartthings.device import Status
from openpeerpower.components.lock import DOMAIN as LOCK_DO... |
# coding: utf-8
#
# Copyright 2020 The Oppia 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 requi... |
__author__ = 'Alex Gusev <alex@flancer64.com>'
import prxgt.const as const
from prxgt.domain.meta.attribute import Attribute as AttributeBase
class Attribute(AttributeBase):
"""
Attribute model contains data.
"""
def __init__(self, name=None, type_=None, value=None):
super(Attribute, self).__... |
# -*- coding: utf-8 -*-
"""
Django settings for roojet project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
from __future__ import absolute_import, unicode_lite... |
from django.test import TestCase
from rest_framework.test import APIRequestFactory, APIClient
from .models import *
from rest_framework import status
# Create your tests here.
class ProductCategoryTest(TestCase):
@classmethod
def setUpTestData(cls):
ProductCategory.objects.create(name_product_category... |
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2019-Present Datadog, Inc.
from datadog_api_client.v1.model_utils import ( # noqa: F401
ApiTypeError,
Mo... |
#!/usr/bin/env python3
"""
Polyglot v2 node server for WeatherFlow Weather Station data.
Copyright (c) 2018,2019 Robert Paauwe
"""
import polyinterface
import sys
import time
import datetime
import urllib3
import json
import socket
import math
import threading
LOGGER = polyinterface.LOGGER
class WindNode(polyinterfac... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
import cohesity_management_sdk.models.smb_active_session
class SmbActiveFilePath(object):
"""Implementation of the 'SmbActiveFilePath' model.
Specifies a file path in an SMB view that has active sessions and opens.
Attributes:
active_sessio... |
class Solvers_Class():
def __init__(self):
pass
def ProperDistanceTabulate(self, Input_Param, z_max):
from Distance_Solver import Proper_Distance_Tabulate
Proper_Distance_Tabulate(Input_Param, z_max)
def LxTxSolver(self, Halos):
from LxTx_Solver import LxTx_Solver
... |
from django.contrib.auth import get_user_model
from django.test import TestCase
# Create your tests here.
class UserManagersTests(TestCase):
def test_create_user(self):
User = get_user_model()
user = User.objects.create_user(
email="normal@user.com", password="testing@123")
s... |
__version__ = '3.1.2' |
from flask import Flask, send_from_directory, make_response, request, send_file, jsonify
import werkzeug.exceptions
from jose import jwt, exceptions
import wtforms_json
from .ays import ays_api
from .oauth import oauth_api
from .webhooks import webhooks_api
from .cockpit import cockpit_api
from JumpScale import j
app... |
import random
import networkx as nx
class Node:
def __init__(self, ID=None, message=None, highercmnd=None, lev=None,
parent=None, childNo=None, children_list=None,
cmndlineup=None, cmndnodes=None, ancestor_list=None,
descendant_list=None):
self.ID = ID # an... |
"""This module's main class reads a text corpus and assembles a list of n
most common words."""
__author__ = 'Kyle P. Johnson <kyle@kyle-p-johnson.com>'
__license__ = 'MIT License. See LICENSE.'
from cltk.corpus.utils.formatter import assemble_tlg_author_filepaths
from cltk.corpus.utils.formatter import assemble_phi... |
from bottle import route, get, post
from bottle import run, debug
from bottle import request, response, redirect, template
from bottle import static_file
import dataset
import json
from bottle import default_app
#http://localhost:8090
@route("/")
def get_midterm():
todo_list_db = dataset.connect('sqlite:///to... |
import ssl
import socket
import OpenSSL
import sqlite3
import signal
from functools import wraps
from numpy.core.numeric import count_nonzero
import requests
from multiprocessing import Process, Value
TIMEOUT = Value('i', 5)
cMax = Value('i', 2)
ca_num = Value('i', 0)
class TimeoutException(Exception):
pass
def ... |
# -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# type: igno... |
"""
Pygame setup for Some Platformer Game
Created by sheepy0125
08/10/2021
"""
import pygame
SCREEN_SIZE = (500, 500)
SCROLL_OFFSET = (SCREEN_SIZE[0] // 2, SCREEN_SIZE[1] // 2)
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption("Some Platformer Game")
clock = pygame.time.Clock() |
from platform import python_version
import hashlib
import hmac
import jwt
import os
import requests
import sys
import time
from uuid import uuid4
import warnings
if sys.version_info[0] == 3:
string_types = (str, bytes)
else:
string_types = (unicode, str)
__version__ = '2.0.0'
class Error(Exception):
pa... |
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import io
import multiprocessing
import subprocess
import sys
from abc import ABC, abstractmethod
from typing import Optional
class ProcessHandler(ABC):
"""An abstraction of process ... |
from metrics import bleu, rouge
import argparse
def get_args():
'''
Parse input arguments:
preds_path: The directory in which labels and predictions files are dumped after inference
config_id: The config id mentioned in the labels and predictions filenames
'''
parser = argparse.Argument... |
"""
Cache middleware. If enabled, each Django-powered page will be cached based on
URL. The canonical way to enable cache middleware is to set
``UpdateCacheMiddleware`` as your first piece of middleware, and
``FetchFromCacheMiddleware`` as the last::
MIDDLEWARE = [
'django.middleware.cache.UpdateCacheMiddl... |
# Copyright 2010 New Relic, 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 writ... |
from typing import Optional
from pytorch_lightning.core.optimizer import is_lightning_optimizer
from pytorch_lightning.plugins.training_type.ddp_spawn import DDPSpawnPlugin
from pytorch_lightning.utilities import _FAIRSCALE_AVAILABLE, rank_zero_only
if _FAIRSCALE_AVAILABLE:
from fairscale.optim import OSS
fr... |
# Split up the pages functionality in separate file to make the code
# easier to read
import os
import re
import webapp2
import jinja2
import json
from google.appengine.ext import ndb
from google.appengine.api import images
# Importing local .py files
from models.users import User, users_key, make_secure_val, check_... |
"""
Implementation of a network using an Encoder-Decoder architecture.
"""
import torch.nn as tnn
from torch import Tensor
from reinvent_models.link_invent.networks.decoder import Decoder
from reinvent_models.link_invent.networks.encoder import Encoder
class EncoderDecoder(tnn.Module):
"""
An encoder-decode... |
#!/usr/bin/env python
# ROS node libs
import time
import numpy as np
import rospy
import torch
# from geometry_msgs.msg import Quaternion, Pose, Point, Vector3
from pyquaternion import Quaternion
from google.protobuf import text_format
from sensor_msgs.msg import PointCloud2
from std_msgs.msg import Header, ColorRGBA... |
# -*- coding: utf-8 -*-
"""
Breneman Corresponding Chromaticities Dataset
=============================================
Defines *Breneman (1987)* results for corresponding chromaticities experiments.
See Also
--------
`Corresponding Chromaticities Prediction Jupyter Notebook
<http://nbviewer.jupyter.org/github/colour... |
import state
def change():
state.x = 2 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import os
import pickle
import torch
class ActivationAndGradientLogger:
def __init__(self, directory):
self.directory = directory
try:
os.mkdir(self.directory)
except:
pass
self.iterat... |
# Copyright 2018 Dustin Ingram
#
# 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, so... |
import os, sys
dirpath = os.getcwd()
sys.path.insert(0, dirpath + '/goal_tether_functions')
sys.path.insert(0, dirpath + '/predictive_modelers')
sys.path.insert(0, dirpath + '/predictive_modelers/assessment_resources')
sys.path.insert(0, dirpath + '/active_learners')
sys.path.insert(0, dirpath + '/data_acquisition')
sy... |
#!/usr/bin/env python
# Sourced from https://gist.github.com/seventhskye/0cc7b2804252975d36dca047ab7729e9 with some modifications
import os
import boto3
def main():
client = boto3.client('s3')
Bucket = os.environ.get('S3_BUCKET')
Prefix = os.environ.get('S3_PREFIX', '') # leave blank to delete the entire conte... |
PIWIK_DB_HOST = 'localhost'
PIWIK_DB_PORT = 3336
PIWIK_DB_USER = 'root'
PIWIK_DB_PASSWORD = 'changeme'
PIWIK_DB_NAME = 'piwik_staging' |
#!/usr/bin/env python
#coding:utf-8
__author__ = 'gkiwi'
from django.db.utils import DatabaseError
from django.db.migrations.exceptions import MigrationSchemaMissing
__all__ = ['MigrationRecorder']
class MigrationRecorder(object):
def ensure_schema(self):
"""
Ensures the table exists and has th... |
from __future__ import print_function
import os
import csv
import glob
import scipy
import sklearn
import numpy as np
import hmmlearn.hmm
import sklearn.cluster
import pickle as cpickle
import matplotlib.pyplot as plt
from scipy.spatial import distance
import sklearn.discriminant_analysis
from pyAudioAnalysis import au... |
#!/usr/bin/env python3
import unittest
from src.crawler.iCrawler import iCrawler, UndefinedDatabaseException
from src.data.MetaDataItem import MetaDataItem
from test.mock.MockDataAccessor import MockDataAccessor
class MockCrawler(iCrawler):
def __init__(self):
super().__init__()
def next_downloadabl... |
import time
import boto3
from lib.Logger import Logger
from lib.popen import subprocess_popen
def prepare():
# 0. Initialize boto3 clients
emr = boto3.client('emr')
ec2 = boto3.client('ec2')
# 1. Create an EMR cluster on AWS
logger.info("Creating the EMR cluster...")
with open("./cloud/cluste... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2020 Snowflake Computing Inc. All right reserved.
#
import json
import logging
from .auth import Auth
from .auth_by_plugin import AuthByPlugin
from .compat import unescape, urlencode, urlsplit
from .constants import HTTP_HEADER_ACCEPT, HTTP_HEADER_C... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Kyle Fitzsimmons, 2017
from datetime import datetime
import pytz
from models import db, PromptResponse
class MobilePromptsActions:
def get(self, prompts_uuids):
prompts_filters = PromptResponse.prompt_uuid.in_(prompts_uuids)
return db.session.query... |
import json, os
class GarfData:
file = os.path.join(os.getcwd(), "garf_data.json")
token: str
path_to_ffmpeg: str
jokes: list
trigger_words: list
def __init__(self):
with open(self.file, "r") as f:
json_dict = json.loads(f.read())
self.token = json_dict["token"]
... |
from models.base_model import BaseModel
import torch.nn as nn
import torch.nn.functional as F
import os, sys
import torch
import numpy as np
import itertools
from torch.autograd import Variable
from optimizers import get_optimizer
from schedulers import get_scheduler
from models.sync_batchnorm import SynchronizedBatch... |
import os
from moviepy.editor import VideoFileClip, concatenate_videoclips
import random
import numpy as np
import time
# from video_facial_landmarks_minmax import calculate_distance
from video_pose_landmarks import calculate_pose_distance
TEST = True
TEST_TIME = 20
INIT_NUM = float("Inf")
WINDOW_TIME = 10
PADDED_TIME... |
import Averager as Avg
class Average:
def __init__(self):
self.answer = 0
self.delta_time = 0
def average(self, avg, delta_t):
print("Average: " + str(avg) + " Timespan: " + str(delta_t))
self.answer = avg
self.delta_time = delta_t
def test_averager():
avg = Aver... |
#!@PYTHON_EXECUTABLE@
#ckwg +28
# Copyright 2011-2013 by Kitware, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,... |
# Copyright (c) 2019 Vitaliy Zakaznikov
#
# 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... |
import sys
sys.path.append("site-packages")
import json
import string
from unidecode import unidecode
from urllib import parse
from azure.storage.blob import BlockBlobService
from datetime import datetime
import animesources
indexedShows = {}
shows = []
with open('title-map.json') as titlemap_file:
titlemap = json.l... |
import time
import pytest
from limits.errors import ConfigurationError
from limits.storage import (
MemcachedStorage,
MemoryStorage,
MongoDBStorage,
RedisClusterStorage,
RedisSentinelStorage,
RedisStorage,
Storage,
storage_from_string,
)
from limits.strategies import MovingWindowRateLi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (... |
#! /usr/bin/env python
from tornado import httpserver
from tornado import gen
from tornado.ioloop import IOLoop
import tornado.web
import json
import single_eval as sev
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello,This is TextCNN")
class ClassifyHandler(tornado.... |
from setuptools import setup
setup(
name='flask_req_parser',
version='0.1.4',
url='https://github.com/Rhyanz46/flask-req-parser',
license='BSD',
author='Arian Saputra',
author_email='rianariansaputra@gmail.com',
description='Simple Request parser for flask',
long_description=__doc__,
... |
import sqlite3
class TorrentState:
SEARCHING = "SEARCHING" # Still being searched
DOWNLOADING = "DOWNLOADING" # Currently being downloading
SEEDING = "SEEDING" # Currently uploading
COMPLETED = "COMPLETED" # Removed from seeding
DELETING = "DELETING" # Torrent marked for deletion
PAUSED =... |
from models.resnet import ResNetBase, get_norm
from models.modules.common import ConvType, NormType, conv, conv_tr
from models.modules.resnet_block import BasicBlock, Bottleneck, BasicBlockIN, BottleneckIN, BasicBlockLN
from MinkowskiEngine import MinkowskiReLU
import MinkowskiEngine.MinkowskiOps as me
class Res16UN... |
from pygtrie import CharTrie
import copy
"""
Split a Chinese Pinyin phrase into a list of possible permutations of Pinyin words.This is the "example" module.
For example,
>>> from pinyinsplit import PinyinSplit
>>> pys = PinyinSplit()
>>> pys.split('XiangGangDaXue')
[['Xiang', 'Gang', 'Da', 'Xue'], ['Xiang', 'Gang',... |
"""
A script for generating siege files with a bunch of URL variations.
"""
import re
import sys
part_re = re.compile(r'\{([-\w]+)\}')
AMO_LANGUAGES = (
'af', 'ar', 'ca', 'cs', 'da', 'de', 'el', 'en-US', 'es', 'eu', 'fa', 'fi',
'fr', 'ga-IE', 'he', 'hu', 'id', 'it', 'ja', 'ko', 'mn', 'nl', 'pl',
'pt-BR', ... |
"""chenv."""
try:
from importlib.metadata import version, PackageNotFoundError # type: ignore
except ImportError: # pragma: no cover
from importlib_metadata import version, PackageNotFoundError # type: ignore
try:
__version__ = version(__name__)
except PackageNotFoundError: # pragma: no cover
__ve... |
import numpy as np
import pytest
from pandas import (
DataFrame,
MultiIndex,
Series,
)
import pandas._testing as tm
import pandas.core.common as com
def test_detect_chained_assignment():
# Inplace ops, originally from:
# https://stackoverflow.com/questions/20508968/series-fillna-in-a-multiindex-d... |
import matplotlib.pyplot as plt
import numpy as np
## Extra plotting functions that can be called for quick analysis
def plot_timestep_distribution(success_timesteps=None, fail_timesteps=None, all_timesteps=None, expert_saving_dir=None):
""" Plot the distribution of time steps over successful and failed episodes ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.