text stringlengths 3.07k 12.6k |
|---|
import sys
import json
from collections import Counter
import time
import pymongo
def inter(a,b):
return list(set(a)&set(b))
def same_path(path0,path):
if inter(path0["top"],list(path["top"]))!=[] and (((inter(path0["end1"],list(path["end1"]))!=[]) and (inter(path0["end2"],list(path["end2"]))!=[])) ... |
from typing import List, Optional, Union, Iterable
import aiotfm
from aiotfm.enums import Game
from aiotfm.errors import CantFriendPlayerError, CommunityPlatformError, FriendLimitError, InvalidAccountError
from aiotfm.packet import Packet
from aiotfm.player import Player
from aiotfm.utils import Date
class FriendLis... |
import numpy as np
import pyqmc
import pandas as pd
from pyqmc.reblock import reblock
from pyqmc.pbc import enforce_pbc
from pyqmc.coord import PeriodicConfigs
from pyscf.pbc import gto, scf
from pyscf.pbc.dft.multigrid import multigrid
from pyscf.scf.addons import remove_linear_dep_
def test_cubic_with_ecp(kind=1, n... |
import functools
import os
from typing import Any, List, Optional, Sequence
from fvcore.common.registry import Registry as _Registry
from tabulate import tabulate
from meerkat.config import ContribOptions
from meerkat.datapanel import DataPanel
class Registry(_Registry):
"""Extension of fvcore's registry that s... |
from __future__ import print_function, unicode_literals, division, absolute_import
import sys
import ipaddress
from struct import pack, unpack
from binascii import hexlify, unhexlify
import enum
PY2 = sys.version_info.major == 2
if PY2:
str = unicode
from StringIO import StringIO as BytesIO
else:
from io i... |
from flask import request, jsonify, make_response, json
from datetime import datetime, timezone
import pytz
import urllib.parse
from google.cloud import firestore, storage
from common.exceptions import exception_common
from config.secret import get_storage_name
STORAGE_NAME = get_storage_name()
db = firestore.Client(... |
# -*- coding: utf-8 -*-
"""Supports the Neutral Atmosphere Composition Spectrometer (NACS) instrument
on Dynamics Explorer 2 (DE2).
From CDAWeb:
The Neutral Atmosphere Composition Spectrometer (NACS) was designed to obtain
in situ measurements of the neutral atmospheric composition and to study the
variations of the ... |
from datetime import datetime, timedelta
import pandas as pd
import measures as m
import cases as c
import hospitalizations as h
import temperature as t
def get_prediction_train_data() -> pd.DataFrame:
# VACCINATIONS ARE EXCLUDED AS PREDICTOR VARIABLE
# bc NSW has only one week (last) of vaccination data
... |
import numpy as np
import pandas as pd
import os
import glob
import arrow
import csv
def get_stockpools(date, stocknum=(10, 20)):
first = str(int(date[:4]) - 2) + date[4:]
date0 = date[:4] + '-' + date[4:]
date0 = arrow.get(date0)
second = date0.shift(months=-1)
second = second.format('YYYYMM')
... |
from multiprocessing import Process
from pathlib import Path
from time import sleep
import click
import libtmux
import structlog
import sys
from . import GeneralConfiguration
from . import ServerConfiguration
from . import ClientConfiguration
from .log import configure_logs
from .client import Client
from .repl imp... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""Eisenstein Rational Fractions Type Implementation - Python 3.x
Defined operations on Eisenstein integers:
https://en.wikipedia.org/wiki/Eisenstein_integer
"""
# https://docs.python.org/3.7/reference/datamodel.html
import sys
from fractions import Fraction
if ... |
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q, Sum
from django.shortcuts import get_object_or_404, redirect
from django.utils.decorators import method_decorator
from django.views.decorators.http im... |
#! /usr/bin/env python2
# -*- coding: UTF-8 -*-
import gi
from gi.repository import Gtk as gtk
from gi.repository import Gdk as gdk
from gi.repository import AppIndicator3 as appindicator
from gi.repository import Notify as notify
import click
import json
import logging
import signal
import sqlite3
import subprocess
i... |
from Tkinter import *
import tkMessageBox as Box
from MyTab import MyTab
from Splash import Splash
import Cleanup
import MyTrack
class CleanupTab(MyTab):
def __init__(self, *args, **kwargs):
MyTab.__init__(self, *args, **kwargs)
self.classes = {1: "CE500",
2: "AMB_IP"}
... |
import numpy as np
import matplotlib.pyplot as plt
import time
from pystorm.hal import HAL
from pystorm.hal.hal import parse_hal_spikes, parse_hal_binned_tags
HAL = HAL()
from pystorm.hal.neuromorph import graph # to describe HAL/neuromorph network
from pystorm.PyDriver import bddriver as bd # expose Driver function... |
import re
from .propagation import sgp4
from .inout import twoline2rv
from .earth_gravity import EarthGravity, wgs84
from math import pi, sqrt, floor, pow
from numpy import dot, linalg, arange, copy, char
from math import fabs as abs
from .inout import jday
from datetime import datetime
from operator import attrgetter
... |
'''
This module is created to enable simulation of games between bots MCTS v MCTS + NN
'''
import argparse
from copy import deepcopy
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib.ticker import PercentFormatter
from board import Board
import math
from bot import Node
fr... |
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
from wann_genetic.individual.torch.ffnn import Network as TorchNetwork
import torch
def node_names(net):
return (
[f"$x_{{{i}}}$" for i in range(net.n_in)] # inputs
+ ["$b$"] # bias
... |
from django.utils.translation import ugettext_lazy as _
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import send_mail
from django.views.decorators.debug import sensitive_post_parameters
from django.utils.decorators import method_decorator
from django.utils import timezone
from rest_... |
#!/usr/bin/env python
"""
Example of (almost) all Elements, that you can use in PySimpleGUI.
Shows you the basics including:
Naming convention for keys
Menubar format
Right click menu format
Table format
Running an async event loop
Theming your application (requir... |
import pandas as pd
import numpy as np
import torch
import sys
from tqdm import tqdm
import mysql.connector
import io
import time
import ML
import numpy
import csv
import os
from tqdm import tqdm
class uci_loader():
def __init__(self):
import os
self.path="/mnt/prod_uci/check/"
self.a=os.li... |
"""Application logic"""
# Import standard library
import random
import itertools
from typing import Tuple, List
# Import modules
import matplotlib as mpl
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import numpy as np
import seagull as sg
import seagull.lifeforms as lf
from loguru import logger
from sci... |
from fastcore.all import store_attr
import functools
from fastcore.all import L
L = L
#? Dict, but cool
class Struct(object):
def __init__(self, *args, **kwargs):
store_attr()
for k, v in kwargs.items():
vars(self)[k] = v
def get(self, key):
return vars(self).get(key)
... |
#!/usr/bin/python3
import os
import sys
from elementals import Prompter
from scout_debugger.scout_compiler import *
##############################
## Dynamic Configurations ##
##############################
SCOUT_DIR = '../../../src/scout'
SCOUT_LOADER_ELF = 'scout_loader.elf'
EMBEDDED_SCOUT_ELF = ... |
#! /usr/bin/env python
'''
LICENSE
-------------------------------------------------------------------------------
Copyright (c) 2015 to 2018 <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. R... |
from .common import InfoExtractor
from ..utils import (
determine_ext,
float_or_none,
join_nonempty,
traverse_obj,
url_or_none,
)
class DailyWireBaseIE(InfoExtractor):
_JSON_PATH = {
'episode': ('props', 'pageProps', 'episodeData', 'episode'),
'videos': ('props', 'pageProps', '... |
from ..graph import get_default_graph
from ..tensors import *
from ..ops.array_ops import *
from ..ops.ctrl_ops import *
from ..ops.constant import *
from ..ops.math_ops import *
from ..ops.placeholder import *
from ..ops.variable import *
def constant(name, out_shape, value=None, graph=None):
if graph is None:
... |
# coding=utf-8
# Copyright 2019 Google LLC.
# Copyright 2021 Shortest Path RL 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
#
# U... |
import os.path
import sys
import urllib.parse
import lxml.etree
import healpy as hp
import numpy as np
from mocpy import MOC, WCS
from math import log
import matplotlib
from matplotlib.path import Path
from matplotlib.patches import PathPatch
import astropy
from astropy.utils.data import download_file
from astropy... |
import torch
import torch.distributions as dist
import os
from im2mesh.encoder import encoder_temporal_dict
from im2mesh.onet4d import models, training, generation
from im2mesh import data
def get_decoder(cfg, device, c_dim=0, z_dim=0):
''' Returns a decoder instance.
Args:
cfg (yaml): yaml config
... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
from asdf.extension import Converter
__all__ = ["WCSConverter", "CelestialFrameConverter", "CompositeFrameConverter",
"FrameConverter", "SpectralFrameConverter", "StepConverter",
"TemporalFrameConverter", "S... |
import sys
from PySide.QtCore import *
from PySide.QtGui import *
from image import SegmentedImage
class Main(QWidget):
def __init__(self, image_path, parent=None):
super(Main, self).__init__(parent)
layout = QVBoxLayout(self)
picture = PictureLabel(image_path, self)
picture.s... |
import numpy as np
import os
import platform
import xdg
import py4dgeo._py4dgeo as _py4dgeo
class Py4DGeoError(Exception):
pass
def find_file(filename):
"""Find a file of given name on the file system.
This function is intended to use in tests and demo applications
to locate data files without res... |
#!/usr/bin/python
#coding: utf-8
import os
from pymongo import MongoClient
from bson.son import SON
import pandas as pd
import numpy as np
import xlsxwriter
import smtplib
import traceback
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
from email.... |
from collections import Counter
import math
from sympy import Symbol, factor, expand, Rational
import numpy as np
# Generating All Partitions: A Comparison Of Two Encodings
# https://arxiv.org/abs/0909.2331
def accel_asc(n):
a = [0 for unused_variable in range(n + 1)]
k = 1
y = n - 1
while k != 0:
... |
import os
import cv2
import time
import shutil
import numpy as np
import matplotlib.pyplot as plt
from open3d import *
# Display utilities
def visualize_joints_2d(ax, joints, joint_idxs=True, links=None, alpha=1):
"""Draw 2d skeleton on matplotlib axis"""
if links is None:
links = [(0, 1, 2, 3, 4), (... |
# -*- coding: utf-8 -*-
"""
Coursework 6 Extra: Phase space of Lorenz Attractor
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Compute the derivative dq from an array of consecutive points q with initial
# derivative dq0 with timestep d
def deriv(q,d=0.001):
dq = (... |
from math import pi, log
from itertools import accumulate
from typing import Union, List
import numpy as np
import torch as th
from torch import nn
import torch.nn.functional as F
from scipy.signal import lfilter
from ail.common.utils import zip_strict
LOG2PI = log(2 * pi)
def pure_discount_cumsum(x: Union[list, ... |
from os import linesep
import array
import random
class RBN:
N = 12
K = 2
def __init__(self):
pass
@classmethod
def new(cls, n=N, k=K):
obj = cls()
obj.k = k
obj.n = n
# Create new node objects.
obj.nodes = [RBNNode(i) for i in list(range(n))]
... |
#!/usr/bin/python
#-*- coding: UTF-8 -*-
#
# @file: kafka_bulkload.py
#
# 大量写入消息到 kafka topic.
#
# Dependencies:
# python2.7
# kafka-python-2.0.2.tar.gz
#
# 测试
# $ /opt/anaconda2/bin/python2.7 kafka_bulkload.py -T mpaylog
#
# See Also:
# http://kafka-python.readthedocs.io/en/master/apidoc/KafkaProducer.html
... |
import sys
import typing
from datetime import datetime
import discord
from discord.ext import commands
from sweeperbot.utilities.helpers import set_sentry_scope
class UserStats(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=["us", "user"])
@commands.guild_only(... |
from pixget import pix
import cv2
import os
import sys
from readwrite import write
import time
import shutil
from compile import compile
from multiprocessing import Process
from stringcolor import cs
from pytube import YouTube, Playlist
import datetime
total = 0
date = str(datetime.datetime.now()).split(" ")[0]
res... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
# -*- coding: utf-8 -*-
import socket
import hashlib
import base64
import logging
GEVENT = None
TCP_BUF_SIZE = 8192
WS_MAGIC_STRING = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
RESPONSE_STRING = 'HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n' \
'Connection: Upgrade\r\nSec-WebSocket-Accept: ... |
import numpy as np
import pandas as pd
from metrics import scores
from sklearn.model_selection import train_test_split
#load datasets
def load(filepath):
data = pd.read_csv(filepath, sep=" ", dtype=float,header=None)
data = data.drop(22, axis=1)
data = data.drop(23, axis=1)
data_np = data.to_nump... |
import dis
import opcode
import weakref
import types
import copy
import importlib
def is_class_instance(o):
return bool(type(o).__flags__ & (1 << 9))
def walk_global_ops(code):
for instr in dis.get_instructions(code):
op = instr.opcode
if op in (opcode.opmap['STORE_GLOBAL'], opcode.opmap['DE... |
import torch
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
def data_norm(A):
max_A = torch.max(A).expand_as(A)
min_A = torch.min(A).expand_as(A) # nn.MSELoss(rec[mask], data[mask])
A = (A - min_A) / (max_A - min_A)
return A
def loss_function(nu,data_center,outputs,radius... |
# -*- coding:utf-8 -*-
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope tha... |
from copy import deepcopy
import os
os.environ['LAMMPS_COMMAND'] = '/n/home08/xiey/lammps-16Mar18/src/lmp_mpi'
import sys
sys.path.append('../flare')
import datetime
import time
import multiprocessing as mp
from typing import List
import numpy as np
from flare.mff.mff import MappedForceField
from flare.otf import OTF
... |
import json
from dataclasses import dataclass
from py2neo import Graph, Node, Relationship
from typing import List
from src.exception import IdNotFound, NoStartNodeFound
from src.model.exe_status import StatusInfo, Status, AdditionalInfo
from src.model.node_data import NodeData, RelationshipData, Identifier, Relation,... |
# -*- coding: utf-8 -*-
from configparser import ConfigParser
from flask import Flask, jsonify, request
import logging.handlers
import logging
from bin.ram import RAM
from bin.cpu import CPU
from bin.network import Network
from bin.load_avg import LoadAvg
from bin.boot_time import BootTime
from bin.disk import Disk
... |
from typing import List, Optional
import torch
class AddFeatsByKeys(object):
"""This transform takes a list of attributes names and if allowed, add them to x
Example:
Before calling "AddFeatsByKeys", if data.x was empty
- transform: AddFeatsByKeys
params:
list_add_to_x:... |
"""
Lifted and lightly modified (but heavily condensed) from:
https://github.com/GSS-Cogs/family-trade/blob/fca3be954d0b4ed216a4a0989182b19a5c58b23c/datasets/ONS-UK-SA-Trade-in-goods/main.py
"""
from datetime import datetime
from typing import Tuple, Optional, List
import gssutils
import pandas
import re
import requ... |
import os
from PIL import Image
import numpy as np
from scipy.interpolate import griddata
import cv2
import argparse
def getSymXYcoordinates(iuv, resolution=256, dp_uv_lookup_256_np=None):
if dp_uv_lookup_256_np is None:
dp_uv_lookup_256_np = np.load('util/dp_uv_lookup_256.npy')
xy, xyMask = getXYcoor(... |
import os
from enum import IntEnum
import random
import re
import time
from study_tool.card import Card, CardSide, SourceLocation
from study_tool.card_attributes import CardAttributes
from study_tool.external import googledocs
from study_tool.russian.types import *
from study_tool.russian.word import *
from study_tool.... |
import asyncio
import base64
import os
import re
import subprocess
import sys
from html import escape
from time import asctime
from typing import Awaitable, Callable, Optional, Union
import nonebot
from bs4 import BeautifulSoup as bs
from nonebot.adapters.onebot.v11 import MessageSegment
from nonebot.log import defaul... |
import numpy as np
from utils.text_analyzer import TextStats
from utils.text_analyzer import compute_score
from utils.dictionary import Dictionary
from itertools import permutations as permutations
def crack_transposition(stats: TextStats, dictionary: Dictionary, verbose: bool=False):
"""
Method to crack tabl... |
import numpy as np
def find_unimodal_range(x0, h, f):
l = x0 - h
r = x0 + h
m = x0
step = 1
fm = f(x0)
fl = f(l)
fr = f(r)
if fl > fm and fm < fr:
return l, r
elif fm > fr:
while True:
l = m
m = r
fm = fr
step *= 2
... |
'''
Xlpy/Tools/frozen
_________________
Tools for freezing common data structures to give them a hash
function.
:copyright: (c) 2015 The Regents of the University of California.
:license: GNU GPL, see licenses/GNU GPLv3.txt for more details.
'''
# load modules
from collections import Counter,... |
"""
.. module:: utils
:platform: Unix, Windows
:synopsis: a module for auxiliary tasks.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
from collections import OrderedDict
from copy import deepcopy
from simtk import openmm
from simtk import unit
kB = unit.BOLTZMANN_CONSTANT_kB*unit.AVOGADRO_CONSTANT_NA
class InputE... |
#Quicksort
"""
#include "src/defines.h"
.section ".text.init"
.globl sort
.globl kth_smallest
.globl violation
/*
QUICKSORT & PARTITION
C implementation (for reference)
int partition(int* p, int start, int end) {
int x = p[end]; // select pivot
int j, tmp, i = start - 1;
for (j = start; j < ... |
# Copyright (c) 2017-present, Facebook, 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... |
from pathlib import Path
from dataclasses import dataclass
from typing import Union
import toml
from semver import VersionInfo
from typeguard import typechecked
from wheel_inspect import inspect_wheel
from balsa import get_logger
from pyship import __application_name__ as pyship_application_name
from pyship import py... |
import sys
import matplotlib.pyplot as plt
import numpy as np
MB = 1048576
data = {
"lens": [],
"cpu_times": [],
"sending_times": [],
"cpu_usages": [],
"lats": []
}
data_packets = {
"lens": [],
"bytes_trans": [],
"packets": [],
"avg_packet_size": []
}
oper_costs = {
"movistar":... |
'''Trains a convolutional neural network on sample images from the environment
using neuroevolution to maximize the ability to discriminate between input
images.
Reference:
Koutnik, Jan, <NAME>, and <NAME>. "Evolving deep
unsupervised convolutional networks for vision-based reinforcement
learning." Proceedings of the ... |
import random
from kf_lib.fighting import fight
from kf_lib.utils import rnd
from .tournament import Tournament
# chances
CH_SCHOOL_VS_SCHOOL = 0.04
CH_STORY_BEGINS = 0.1
CH_TOURNAMENT_BEGINS = 0.15
# tournaments
DEFAULT_TOURN_FEE = 100
TOURN_FEES = (50, 75, 100, 125, 150)
TOURN_PRIZE_MULT = 4
TOURN_TYPES = (
'... |
"""Configuration details for specific server types.
This module contains functions that help with initializing a Fabric environment
for standard server types.
"""
import os
import subprocess
from fabric.api import env, run, sudo
def _setup_distribution_environment():
"""Setup distribution environment
"""
... |
import os, datetime, requests
import tensorflow as tf
from sklearn.model_selection import train_test_split as sk_train_test_split
import matplotlib.pyplot as plt
import numpy as np
from .datagen import DataGen
def train_test_split(ids):
IDs_train, IDs_test = sk_train_test_split(ids, train_size=0.75)
return ... |
import logging
from abc import ABC
from typing import Any, Dict, Type, Union
from torch.optim import Optimizer
from torch.tensor import Tensor
from torch.utils.data import DataLoader, TensorDataset
from melbe.collections.pipelines.torch.configs import TorchConfig
from melbe.data import PREDICTIONS, TEXT_SENTENCE, LIS... |
import os
import re
import yaml
import cerberus
import logging
from watsor.config.schema import schema
_LOGGER = logging.getLogger(__name__)
_ENV_pattern = re.compile('.*?\${(\w+)}.*?')
SECRETS_YAML = "secrets.yaml"
__SECRET_CACHE = {}
def _load_yaml(filename: str, loader: yaml.Loader = yaml.SafeLoader):
_LOG... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class DnCNN(nn.Module):
def __init__(self, channels, num_of_layers=17, **kwargs):
super(DnCNN, self).__init__()
kernel_size = 3
padding = 1
features = 64
layers = []
layers.append(nn.Conv2d(in_channe... |
import contextlib
import os
import pathlib
import platform
import subprocess
import tempfile
from unittest import TestCase
if platform.system() == "Windows":
import _winapi
exeext = ".exe"
else:
exeext = ""
repository_root_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
user_scripts_di... |
### SCIPY Y MATPLOTLIB
import numpy as np
#from scipy.special import jn
# ejemplo con funcion Bessel (foto de Rosalind Franklin)
#x = np.linspace(xmin, xmax, npts)
#layers = np.array([jn(i, x)**2 for i in range(nlayers)])
#maxi = [(np.diff(np.sign(np.diff(layers[i,:]))) < 0).nonzero()[0] + 1
# ... |
# 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 may ... |
# -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# 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... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Filename: access.py
# Project: routes
# Author: <NAME>
# Created: Wednesday, 16th September 2020 6:16:40 pm
# License: BSD 3-clause "New" or "Revised" License
# Copyright (c) 2020 <NAME>
# Last Modified: Wednesday, 16th September 2020 6:16:40 pm
# Modified By: <NAME>
... |
"""Contains Datasets for Trainer class."""
import numpy as np
import pickle
from scipy.io import loadmat
from torch.utils.data import Dataset
def load(path):
"""Load file depending on type.
Convenience wrapper.
Args:
path (str): Valid path to dataset as created by envs/envs.py.
Returns:
... |
from future.standard_library import install_aliases
install_aliases()
from builtins import str
import os
import sys
import csv
import cssutils
import re
import requests
from urllib.parse import urljoin
from lxml import etree
from lxml.cssselect import CSSSelector, ExpressionError
_url_re = re.compile(r'''url\((['"]?... |
import json
from typing import Tuple
import librosa
import torch
from pororo.models.tts.hifigan.checkpoint import load_checkpoint
from pororo.models.tts.hifigan.model import Generator
from pororo.models.tts.synthesis import synthesize
from pororo.models.tts.tacotron.params import Params as tacotron_hp
from pororo.mod... |
from environment.game import *
from learningAgents import ReinforcementAgent
from featureExtractors import *
from collections import defaultdict
import random, math
import environment.util as util
class QLearningAgent(ReinforcementAgent):
"""
Q-Learning Agent
Functions you should fill in:
... |
import os
import re
import sys
import json
import asyncio
import logging
import discord
from config import log_config
from config.config import AppConfig, DiscordBotConfig
from unity_cloud_build_worker import UnityCloudBuildWorker
log_config.setup_logging()
class DiscordBot(discord.Client):
def __init__(self):
... |
"""
functions for reading and writing the filesystem
"""
import automol
import elstruct
import autofile
from mechroutines.es import runner as es_runner
def structure(run_fs, save_fs, locs, job, mod_thy_info,
zma_locs=(0,), in_zma_fs=False, cart_to_zma=False):
""" Save a geometry and associated inf... |
import torch.nn as nn
import torch
import random
import librosa
import numpy as np
import mido
import os
num_epochs = 10
batch_size = 1
learning_rate = 0.001
input_size = 1025
output_size = 88
# sequence_length = 28
hidden_size = 128
num_layers = 2
device = torch.device('cpu')
FRAME_SIZE = 2048
HOP_SIZE = 512
SAMPL... |
import os
import logging
import json
from typing import List, Dict
import torch
from .discrete_tuning import preprocess
from ..config import Config
from ..util import load_language_model
from ..trainer import BaseTrainer
os.environ["TOKENIZERS_PARALLELISM"] = "false" # to turn off warning message
__all__ = 'Continuo... |
"""
Retrain the YOLO model for your own dataset.
"""
import os
import sys
import h5py
import argparse
from keras.optimizers import Adam
from keras.callbacks import TensorBoard, ModelCheckpoint, ReduceLROnPlateau, EarlyStopping
from keras_yolo3.yolo3.utils import read_classes, create_model, create_tiny_model, data_gen... |
from __future__ import print_function
import sys
import json
from tqdm import tqdm
import six
from .cli_command_wrapper import CLICommandWrapper, CLIUserError
from .command import POW, GenericUserError
from .git_repo import GitRepoProvider
from .text_util import format_table
from .command_util import GeneratorWithData
... |
"""
Functions to calculate different visualisations for 1D models
"""
from tensorflow.keras.models import Model
from signal_screen_tools import add_zeros, change_last_activation_to_linear, normalise_array
import numpy as np
import tensorflow as tf
def calculate_occlusion_sensitivity(model: Model, data: np.ndarray, ... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import logging
import os
from gamelogic import Controller
from multienv import MultiEnv
from malmopy.agents import QLearnerAgent, RewardMetrics, ExploreExploit
from malmopy.backe... |
from dataHandler import dataHandler
from settingsHandler import SettingsHandler
from mcd_interface import MCDInterface
import dataHandler
import constants
import modules_helpers
from tqdm import tqdm
import os
from tkinter import *
import tkinter.filedialog
settings_handler = SettingsHandler()
mcd_interface = MCDIn... |
# why is is called foundry?
# because HoT MetaL.
# *groan*
import requests
import lxml.html
import shutil
import hashlib
import os
from urllib.parse import urljoin, urlparse
from pathlib import Path
import shutil
from .lxml_tools import global_hyperlink, absolve, handle_youtube, globalise
from .bits import get_resour... |
#--------------------------------------------------------------------------------------------------
# Import required libraries
from tkinter import *
from tkinter import colorchooser
from tkinter import messagebox
from tkinter import ttk
from tkinter import filedialog
import cv2
from PIL import Image, ImageTk
import n... |
# Copyright (c) 2018 FlashX, LLC
#
# 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 limitation the rights
# to use, copy, modify, merge, publish, distri... |
import logging
from typing import Callable, Protocol, Sequence
from scipy.integrate import nquad
from scipy.stats import dirichlet
# this is the currently supported way to annotate callables with *args of a certain type,
# see https://mypy.readthedocs.io/en/latest/protocols.html#callback-protocols
# hopefully at som... |
import copy
import os
from typing import Any, AnyStr, Optional # noqa: F401
import numpy as np
import torch
import thelper
from tests.train.train_utils import ( # noqa: F401 isort:skip
mnist_config, test_classif_mnist_ft_path, test_classif_mnist_name,
test_classif_mnist_path, test_save_path
)
config = mni... |
#!/usr/bin/env python
from random import shuffle
from ants import *
import logging
import sys
from optparse import OptionParser
from logutils import initLogging,getLogger
turn_number = 0
bot_version = 'v0.1'
class LogFilter(logging.Filter):
"""
This is a filter that injects stuff like TurnNumber into the log
""... |
# -*- mode: python; coding: utf-8 -*-
# Copyright 2017 the HERA Collaboration
# Licensed under the 2-clause BSD license.
"""Functions to handle various cm revision queries and checks.
"""
from __future__ import absolute_import, division, print_function
import six
import warnings
from tabulate import tabulate
from a... |
from tracking_model.qp import qp_solver
from random import randint, choices, uniform, sample
import pandas as pd
import numpy as np
from time import time
def track_index(
data:pd.DataFrame,
K:int,
index_name:str,
P:int=15,
cross:float=1,
mut:float=0.85,
cut:int=4,
weight_limits:np.ndarr... |
# -*- coding: utf-8 -*-
import hashlib
import io
import os
import requests
from datetime import datetime
from ..messages import *
# Manifest creation relies on these data structures.
# Add to them whenever new types of data files are created.
knownFiles = [
"biblio-keys.json",
"biblio-numeric-suffixes.json"... |
"""
INCLUDE ONLY, DO NOT EXECUTE
"""
from settings import *
import numpy as np
from tensorflow.keras.utils import Sequence
import cv2 as cv
src_train_folder = os.path.join(data_folder, 'IM_SAT_TRAIN', 'img')
src_train_folder_gt = os.path.join(data_folder, 'IM_SAT_TRAIN', 'gt')
src_test_folder = os.path.join(data_fold... |
import requests, json
from enum import Enum
from flask import current_app
from app.config import Config
from app.api.constants import CORE_PURPLE_LOGO_BASE64_ENCODED
class EmailBodyType(Enum):
HTML = 'html'
TEXT = 'text'
class EmailEncoding(Enum):
BASE64 = 'base64'
BINARY = 'binary'
HEX = 'hex... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.