text stringlengths 3.07k 12.6k |
|---|
import copy
import torch
import torch.nn as nn
from torch.optim import Adam
import torch.optim.lr_scheduler as lr
from torch.utils.data import DataLoader, TensorDataset
from model.eval import accuracy
class HistEncoder(nn.Module):
def __init__(self, input_channel, mid_channel, out_channel, dropout):
sup... |
import numpy as np
import torch
from torch import nn
import argparse
import os
import sys
from torch.utils.data import DataLoader
from utils.util import *
import torch.nn.functional as F
from datasetcClass import classDataset
from models.hrnet import hrnet
from utils.ranger import Ranger
from utils.lr_scheduler import... |
"""Partially redact an image file containing credit card numbers and upload it to a
Google Cloud Storage bucket. The script redacts the second and third set of digits
of the credit card number
"""
import sys
import matplotlib
matplotlib.use('Agg')
import os
import json
from google.cloud import storage
import g... |
"""
@Time: 2018/5/10 14:03
@Author: qingyaocui
"""
import pickle
import time
import os
import pickle
from course.src import identifier
from course.conf import settings
class BaseModel:
def save(self):
'''
使用pickle 序列化 用户对象
:return:
'''
nid = str(self.nid)
... |
from typing import Dict, List, NamedTuple, Tuple
import argparse
import json
import numpy as np
import os
import tensorflow as tf
from kite.infer_expr.config import MetaInfo, Config
from kite.infer_expr.model import Model
from kite.utils.save import save_frozen_model
from kite.compress_embeddings.codebook.embed_comp... |
#SQuADのデータ処理
#必要条件:CoreNLP
#Tools/core...で
#java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer -port 9000 -timeout 15000
import os
import sys
sys.path.append("../")
import json
import gzip
import pandas as pd
import numpy as np
from tqdm import tqdm
from nltk.tokenize import word_tokenize,sent_tokenize... |
# coding=UTF-8
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import math
import random
import numpy as np
from mdkp import Colony
from machine import AllocationOfMachine
import heapq
from connection import *
import time
import thread
task_queue = []
machine_queue = []
tasks = {}
machines = {}
def get_machines():
... |
from mapoca.trainers.subprocess_env_manager import worker
import numpy as np
from typing import List, Tuple, Optional, Mapping as MappingType
from mlagents_envs.base_env import (
BehaviorSpec,
ObservationSpec,
DimensionProperty,
ObservationType,
ActionSpec,
DecisionSteps,
TerminalSteps,
... |
from pathlib import Path
import numpy as np
import pandas as pd
from sykepic.compute.prediction import prediction_dataframe, threshold_dictionary
def parse_evaluations(
evaluations,
pred_dir,
thresholds=None,
threshold_search=False,
search_precision=0.01,
empty="unclassifiable",
unsure="... |
# tricopa.py : Use etcabductionpy to solve tricopa problems
# <NAME>
# November 2015
from __future__ import print_function
import argparse
import sys
import os
import re
from context import etcabductionpy as etc
# Question class and parser
class Question(tuple):
# consider adding natural language text in the fu... |
# Copyright (c) 2021. Universidad de Pinar del Rio
# This file is part of SCEIBA (sceiba.cu).
# SCEIBA is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
"""Iroko Providers."""
import uuid
from invenio_pidstore.models import PIDS... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import json
import platform
import subprocess
import boto3
import pygraphviz
from . import global_state
from .constants import (
BLUE,
GRAY,
ORANGE,
RED,
YELLOW,
)
from .utils import (
get_available_base_domains,
get_nameservers_with_no_ip,
is_authoritative,
)
PLATFORM_SYSTEM_TO_OPEN... |
# Copyright (c) 2016 - 2017, Intel Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... |
import core.node
import basic_node
import price_node
from general_osc_node import GeneralOSCNode
class KDNode(GeneralOSCNode):
def __init__(self, nm, from_name, days1 = 6):
GeneralOSCNode.__init__(self, nm,
"%s_KD_%d" % (from_name, days1),
"%s... |
import os
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader, ConcatDataset, Sampler
from deepSM.SMData import SMFile
from deepSM import utils
import deepSM.beat_time_converter as BTC
from deepSM import wavutils
from deepSM import StepPlacement
import h5py
from importlib import reload
... |
import random
import numpy as np
import matplotlib.pyplot as plt
phi = lambda vec: np.sin(np.product(vec))
h = lambda x: np.sqrt(1 + np.sin(np.product(x)) ** 2)
# Section 1.1.5 - Analytical Evaluation
# SubSection 1
def gradient_phi(vec: np.matrix):
grad_vec = np.matrix(np.array([[vec[1] * vec[2]], [vec[0] * v... |
#!/bin/python3
import os
import re
import subprocess
import argparse
import signal
import sys
import time
from itertools import zip_longest
import pidfile
MESSAGE_SPLIT = b'\x03'
MIDDLE_SPLIT = b'\x1e'
START_MESSAGE = b'\x1e'
COMMAND_PARSE = re.compile(b'\x02([^\x1e]+)\x1e(.*)')
reset_file = False
def handler(sig... |
"""
Path tracking simulation with Stanley steering control and PID speed control.
https://www.ri.cmu.edu/pub_files/2009/2/Automatic_Steering_Methods_for_Autonomous_Automobile_Path_Tracking.pdf
Original Author: <NAME>(@Atsushi_twi)
From https://github.com/AtsushiSakai/PythonRobotics
"""
from __future__ import division... |
import os
from flask import Blueprint, request
import settings as s
import pagemaker as p
tags = Blueprint("tags", __name__)
tlist = s.tags
flist = s.friends
# tags_host("host")
# tags_load()
# tags_view(["tags"])
# tags_addthread("num", ["tags"])
def tags_load(host=""):
tagp = "/".join(["./threads", host, "tag... |
# -*- coding: utf-8 -*-
"""
General description
-------------------
This is the dispatch variant of POMMES, the POwer Market Model
of Energy and reSources Department at TU Berlin.
The fundamental power market model has been originally developed
at TU Berlin and is now maintained by a developer group of alumni.
The sour... |
import requests
from bs4 import BeautifulSoup
class UrlException(Exception):
pass
# This function takes the url of an RMP rating page,
# and returns the ratings of the prof as a dict:
# {name: <NAME>, overall_score: 3.3, would_take_again: 0.67, difficulty: 3, comments: [a_list_of_comments]}
# "comments... |
"""
Contains tests for the fields included in selenium_yaml.fields
"""
from selenium_yaml import fields
from selenium_yaml import exceptions
import pytest
import os
class FieldTestMixin:
""" Contains common methods for testing field validation successs or
failure
"""
def is_successful_validation(s... |
from dataclasses import dataclass, field
from datetime import datetime
from decimal import Decimal
from statistics import median
from paper_trader.exchange.history import PriceTimes, SymbolPriceTime
from paper_trader.exchange.orders import Fill, Side
from paper_trader.exchange.position import Position
from pap... |
"""Upgrade Assembly"""
import ast
import typing as T
from collections import defaultdict
import astor
ARG = T.TypeVar('ARG') # TODO: bind str
VALUE = T.TypeVar('VALUE') # TODO: bind Any
PATH = T.TypeVar('PATH') # TODO: bind str
RENAME_ARGUMENTS: dict = {
'default': 'dump_default',
'missing': 'load_defaul... |
import logging
import numpy as np
logger = logging.getLogger(__name__)
def _distance(Z, Y):
""" Distance function """
return Y.sum(axis=(1, 2)) - np.einsum('ijk,ljk->il', Z, np.log(Y))
def _initialize_clusters(n_el, n_clusters):
""" Initialize cluster array """
cluster_idx = np.mod(np.arange(n_el)... |
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
import sys
from PyQt5.QtWidgets import *
import win32com.client
# 복수 종목 실시간 조회 샘플 (조회는 없고 실시간만 있음)
class CpEvent:
def set_params(self, client):
self.client = client
def OnReceived(self):
code = self.client.GetHeaderValue(0) # 초
name = self.client.GetHeaderValue(1) # 초
timess... |
import logging
from time import time_ns
from typing import Any, Tuple
from hash import Hash, get_hash_fields
from did import EngineStartRemote, EngineStartNormal, EngineStartDisable, ChargePlugConnected
from did import KeyState, ChargingStatus, EvseType, GearCommanded, InferredKey
_LOGGER = logging.getLogger('mme')... |
# -*- coding: utf-8 -*-
# Global imports
import argparse as ap
import numpy as np
from sklearn import cluster
# Local imports
from MDAnalysisTools import *
# Script information
__author__ = "<NAME>"
__license__ = "MIT"
__version__ = "1.0.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
def parseArgs():
"""
Par... |
import picoweb
import ulogging as logging
import gc
import ujson
import network
import camera
try:
with open("config.json","r") as f:
swq=ujson.loads(f.read())
except Exception as e:
swq={"set_password":"<PASSWORD>","set_wifi":"camera_1","wifi":"12345678","password":"","pixel":"3"}
q=open("config.j... |
from datetime import datetime
from typing import List, Optional
from sqlalchemy import insert, delete, select
from zope.sqlalchemy import mark_changed
from wt.common import Money, Currency
from wt.costs.expenditures import (
ExpenditureType,
ExpenditureStatus,
Expenditure,
ExpendituresModel,
Bound... |
"""A Page represents a single web document.
Pages originate in Markdown and are to be rendered as HTML.
"""
import json
import os
from datetime import datetime
from typing import Any, Dict, Optional, Tuple, TypeVar
from jinja2 import Environment, FileSystemLoader, Template
from markdown import Markdown
from scrivo.m... |
import subprocess
import pickle
import sqlite3
from sqlite3 import Error
def read_database_size(db_name, db_type):
result = subprocess.run(["blastdbcmd", "-db", db_name, "-dbtype", db_type, "-info", "-exact_length"], stdout=subprocess.PIPE)
db_info = result.stdout.decode('utf-8')
db_info = db_info.split("\... |
""" The definition of the Open Reaction Database chemical reaction entry processing utility functions. """
from typing import Optional, List
from google.protobuf.json_format import MessageToDict
from ord_schema.proto.reaction_pb2 import Reaction, ReactionIdentifier, CompoundIdentifier
# noinspection PyBroadExceptio... |
import os
import json
import boto3
import base64
from ipaddress import ip_network, ip_address
from botocore.exceptions import ClientError
def lambda_handler(event, context):
# Get the required parameters
required_param_list = ["serverId", "username", "protocol", "sourceIp"]
for parameter in required_param... |
from typing import List, Union, Callable, Optional, Dict, Tuple
from pathlib import Path
import pandas as pd
import numpy as np
import dask.dataframe as dd
import plotly.express as px
import plotly.graph_objs as go
import folium
def read_multiple_csv(
fp:Union[Path, str],
engine:str='pandas',
**kwargs
) -... |
#reference: https://github1s.com/LeeSureman/Flat-Lattice-Transformer/blob/HEAD/V0/utils_.py
import re
import collections
class TrieNode:
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.is_w = False
class Trie:
def __init__(self, confusion=None, max_mutated=1):
... |
import os
import csv
import yaml
PROJECTS_FILE = "projects.csv"
PROJECTS_FOLDER = "projects"
PROJECT_YAML = "projects.yml"
ACEPTED_PROJECTS = "accepted_projects.csv"
PROJECTS_REPOSITORY = "https://github.com/elixir-europe/BioHackathon-projects-2019/tree/master/projects/{number}"
# ACEPTED PROJECTS COLUMN NAMES
ACPT_P... |
import numpy as np
import os
import re
import json
import datetime
import torch
import glob
import shutil
import subprocess
def remove_experiment_folder(experiment_path):
"""Check folder if there is a checkpoint, otherwise remove the folder"""
checkpoint_files = glob.glob(experiment_path + "/**/*.pth.tar", r... |
import os.path as osp
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
from torch_geometric.datasets import Planetoid
from torch_geometric.data import NeighborSampler
from torch_geometric.nn import SAGEConv
from torch_geometric.utils import degree
from torch_cluster import rando... |
import pandas as _pd
import os as _os
from pathlib import Path
import numpy as _np
def path2info(path, verbose = False):
path = Path(path)
if path.is_dir():
path = list(path.iterdir())[0]
#suffix
suffix = path.suffix
suffixlist = ['.nc', '.cdf']
if suffix not in suffixlist:
raise V... |
import csv
import io
from datetime import datetime
from os import system
file = open("PB.csv", "r", encoding="UTF-8")
reader = csv.DictReader(file, delimiter=';')
data = list(reader)
running = True
def clear_screen():
# Use system calls to clear the screen
system('cls')
def generate_option_list():
# L... |
# Copyright 2017 Red Hat, Inc.
# All Rights Reserved.
# Copyright 2019-2021 Hewlett Packard Enterprise Development LP
#
# 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... |
import numpy as np
from tqdm import tqdm
def UniqueRows(arr):
""" Remove duplicate row array in 2D data
* arr (narray): array with duplicate row
Example:
>> d = np.array([[0,1,2],[0,1,2],[0,0,0],[0,0,2],[0,1,2]])
>> UniqueRows(d)
array([[0, 0, 0],
... |
from __future__ import absolute_import
import pytest
from sympy import cos, Symbol # noqa
from devito import (Dimension, Eq, TimeDimension, SteppingDimension, SpaceDimension, # noqa
Constant, Function, TimeFunction, Grid, configuration) # noqa
from devito.types import Scalar, Array
from devito... |
# -*- coding: utf-8 -*-
import importlib
import json
import logging
import pickle
import threading
import requests
from redis import StrictRedis
logger = logging.getLogger(__name__)
class CanNotGetConfError(Exception):
pass
class ConfInitError(Exception):
pass
def load_callbacks(callbacks):
"""
... |
import numpy as np
import matplotlib.pyplot as plt
import sys
kdm = 4148.808 # MHz^2 / (pc cm^-3)
def dm_delay(f1, f2, DM, kdm=kdm):
return kdm * DM * (1.0 / (f1 * f1) - 1 / (f2 * f2))
def deltaT_old(ichan, dt, df, f0, kdm=kdm):
return (kdm / dt) * ((f0 + ichan * df)**-2.0 - f0**-2)
def dmdt_old(DM, ichan... |
import numpy as np
from biopal.fd.processing_FD import generalized_eigendecomp
from biopal.fd.processing_FD import _apply_index_
from biopal.fd.processing_FD import generate_pinc_pdec_RGBimages
from scipy.linalg import eig as sp_eig
def generate_cov_matrices_change(contrast_vector):
'''
Generates a simple chan... |
import random
random.seed(30)
import matplotlib
import numpy as np
import pandas as pd
import os
import csv
import torch
import pickle
from sklearn.metrics import f1_score, recall_score, accuracy_score, confusion_matrix #, precision_score
from sklearn.utils.multiclass import unique_labels
from sklearn.metrics import cl... |
from whoosh.filedb.filestore import RamStorage
from whoosh.idsets import BitSet, OnDiskBitSet, SortedIntSet
def test_bit_basics(c=BitSet):
b = c()
assert not b
assert 12 not in b
b.update([0, 2, 4, 6, 7])
assert b
assert ([(n in b) for n in range(10)] ==
[True, False, True, False,... |
# static analysis: ignore
from .implementation import assert_is_value
from .value import (
AnySource,
AnyValue,
KnownValue,
MultiValuedValue,
TypedValue,
AnnotatedValue,
)
from .test_name_check_visitor import TestNameCheckVisitorBase
from .test_node_visitor import assert_passes, skip_before
cl... |
import os
from typing import cast
from sebs.cache import Cache
from sebs.faas.config import Config, Credentials, Resources
from sebs.utils import LoggingHandlers
# FIXME: Replace type hints for static generators after migration to 3.7
# https://stackoverflow.com/questions/33533148/how-do-i-specify-that-the-return-typ... |
#!/usr/bin/env python
import numpy as np
from npsurvival_models import BasicSurvival
# some kernel functions (note that the assumption is that these are only ever
# evaluated at inputs in the range [0,1])
kernel_box = lambda s: 1
kernel_triangle = lambda s: 1 - np.abs(s)
kernel_epanechnikov = lambda s: 0.75 * (1 - s*... |
import random
import simpy
from impl.MM1LimitBuffer import MM1_sys
import math
import matplotlib.pyplot as plt
import numpy as np
class MG1_sys_gamma(MM1_sys):
def __init__(self, config):
super().__init__(config)
def calculate_service_time(self, conf):
service_config = conf["SERVICE_CONF"]
... |
import unittest
from .lmdbstore import LmdbDatabase
from uuid import uuid4
from .data import StringDelimitedKeyBuilder
import shutil
import os
from multiprocessing.pool import Pool
class EphemeralLmdb(object):
def __init__(self, dir=None):
super(EphemeralLmdb, self).__init__()
self.dir = dir or uu... |
import os
from cosmosis.datablock import option_section, names
from cosmosis.datablock.cosmosis_py import errors
import numpy as np
import scipy.interpolate
def log_interpolate(x_arr, y_arr, x):
if np.any(y_arr <= 0):
return scipy.interpolate.InterpolatedUnivariateSpline(np.log(x_arr),
... |
import imageio
import mxnet
from gluoncv import model_zoo, data, utils
from matplotlib import pyplot as plt
from PIL import Image
import sys
import numpy as np
from scipy.signal import convolve2d
# from inpainting_pipeline import expand_masks, erase_masks
import argparse
import cv2
import tensorflow as tf
import neural... |
import sys
import os
import subprocess
import stat
from datetime import datetime
import shutil
import glob
import logging
supported_archs = ["amd64"]
BUILD="packaging/build"
PACKAGING="packaging"
ROOT = os.path.abspath(os.path.dirname(__file__))
BINARY="{0}/bin/valmond".format(ROOT)
PACKAGES_PATH=os.path.join(ROOT, ... |
# -*- coding: utf-8 -*-
# this function loops through all Ground Truth frames and Detections
# and distributes both into appropriate segments based on segment ground truth
# falls into. The decision is made based on distance between detection box
# centre and nearest centre of ground truth bounding boxes
import argpar... |
#!/usr/bin/env python
# coding=utf-8
# @Su.Py~#_
import sys
import time
import re
import signal
import subprocess
import shlex
class clr(object):
"""docstring for clr"""
magenta = "\033[95m"
cyan = "\033[94m"
green = "\033[92m"
warn = "\033[93m"
err = "\033[91m"
end = "\033[0m"
bold =... |
import argparse
import os
import random
import torch
from torchvision import datasets, models, transforms
import runai.elastic.torch
import runai.ga.torch
def parse_args():
parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training with Run:AI Elasticity')
parser.add_argument('--model', default=... |
import json
from pathlib import Path, PurePosixPath
import pytest
from fsspec.implementations.local import LocalFileSystem
from gcsfs import GCSFileSystem
from s3fs.core import S3FileSystem
from kedro.extras.datasets.tracking import JSONDataSet
from kedro.io import DataSetError
from kedro.io.core import PROTOCOL_DELI... |
import tkinter
import time
import random
window = tkinter.Tk()
window.title("Sorting Algorithm Visualizer")
canvas = tkinter.Canvas(window, bg="white", height=650, width=1200)
LIGHT_GRAY = "#a9a9a9"
DARKER_GRAY = "#878787"
DARK_GRAY = "#555555"
unsorted_list = []
color_count = 1
lines = []
colors = []
def generate_... |
from invoke import task
import os
import shutil
import json
from dotenv import load_dotenv, find_dotenv, dotenv_values
import invoke
from datetime import datetime, timedelta
import sys
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from icecream import ic
from textwrap import dedent
from rich im... |
import math
import numpy as np
from proximal.lin_ops import CompGraph, scale, vstack
from proximal.utils.timings_log import TimingsLog, TimingsEntry
from .invert import get_least_squares_inverse, get_diag_quads
def partition(prox_fns, try_diagonalize=True):
"""Divide the proxable functions into sets Psi and Ome... |
# Copyright (c) 2012-2013, <NAME> <<EMAIL>>
# All rights reserved.
#
# See LICENSE file for full license.
from __future__ import annotations
import json
from re import compile
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
SupportsFloat,
SupportsInt,
TypeVar,
Union,
... |
import os
import discord
import hashlib
import json
import cryptocode as crypt
import valorant
from config import Config
# https://stackoverflow.com/a/5125636
def safe_list_get(l, idx):
try:
return l[idx]
except IndexError:
return None
async def save_credentials_to_file(region, username, passw... |
from mcstatus import MinecraftServer
from time import perf_counter
import dns.asyncresolver
from aiohttp import web
import asyncio_dgram
import asyncio
import struct
# default / offline server
DEFAULT = {
'online': False, # boolean
'players_online': 0, # int
'players_max': 0, # int
'players_names': ... |
# -*- coding: utf-8 -*-
"""
Views for the participant registration and payment for the event.
"""
# from annoying.functions import get_object_or_None
# from django.contrib.auth import login, authenticate
# from django.contrib.auth.models import User
from django.utils import timezone
from django.utils.translation import... |
"""
Programa de interseccion en 3D
Autor: <NAME>
Num. control: 18390045
"""
import numpy as np
import matplotlib.pyplot as plt
#---Coordenadas generales
xg=[]
yg=[]
zg=[]
#----Centro
xc = 80
yc = 40
zc = 40
#----Coordinates locales
x=[40, 30, 80, 0]
y=[60, 10, 60, 0]
z=[ 0, 0, 0, 0]
#Plotea las lineas del triang... |
import importlib
import os
import pickle
import numpy as np
import torch
from setup_mnist import MNIST
from setup_cifar import CIFAR
from setup_restrictedimagenet import RestrictedImagenet as restImagenet
from advex_uar.eval import Evaluator
from advex_uar.common.pyt_common import *
from advex_uar.common import Flag... |
import argparse
import atexit
import logging
import time
import yaml
from .filehandler import FileHandler
from .IC import *
from .algorithm import EvolutionaryAlgorithm, Individual
def get_logger():
# Set logger configurations.
log_format = "%(levelname)s %(asctime)s - %(message)s"
logging.basicConfig(fi... |
from application import app, models, db
from flask import Flask, render_template,request, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, IntegerField, DateField, DateTimeField
app = Flask(__name__)
app.config['SECRET_KEY'] = 'lockedout'
class UserForm(FlaskForm):
... |
# Copyright 2013 Mirantis, 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 ... |
from datetime import datetime
from dataloader.outdoor_data_mfcc import ActionsDataLoader as SoundDataLoader
from dataloader.actions_data_old import ActionsDataLoader
from models.unet_acresnet import UNetAc
from models.vision import ResNet50Model
import numpy as np
import tensorflow as tf
import os
import matplotlib.pyp... |
import math
from functools import partial
import pandas as pd
import random
import string
from calculate_frequency import calculate_frequency_norm
from ngrams import ngrams
from substitution_cipher import substitution_cipher
# ================ ALPHABET CONF ================
ALPHABET = string.ascii_uppercase
NGRAMS_S... |
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
import random
import os
from cv2 import imread
from keras.layers import Input,Conv2D,MaxPooling2D,Flatten,Dense,Dropout,Lambda,LSTM,BatchNormalization,LeakyReLU,PReLU
from keras import Sequential
from keras.datasets import ... |
# coding: utf-8
# Copyright 2013 <NAME>
#
# 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 random
import re
import time
from datetime import datetime
import pandas as pd
from requests import Session
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from requests_futures.sessions import FuturesSession
DEFAULT_TIMEOUT = 5
USER_AGENT_LIST = [
"Mozill... |
import tensorflow as tf
from tensorflow.keras import optimizers
from tensorflow.keras.layers import InputSpec, Dense, Wrapper, Input, concatenate
from tensorflow.keras.models import Model
import numpy as np
class ConcreteDropout(Wrapper):
"""This wrapper allows to learn the dropout probability for any given input... |
# coding: utf-8
from pymatgen.core import Structure
from pymatgen_diffusion.neb.io import MVLCINEBEndPointSet, MVLCINEBSet, \
get_endpoints_from_index, get_endpoint_dist
import unittest
import os
__author__ = 'hat003'
test_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)))
def get_pa... |
import os
import struct
import pandas as pd
import numpy as np
import time, datetime
import sys, getopt
# import multiprocessing
# import talib as tdx
from easyquant import MongoIo
import matplotlib.pyplot as plt
# from easyquant.indicator.base import *
# import QUANTAXIS as QA
import talib
import matplotlib.ticker as... |
import base64
import random
from time import time
def strtobin(text):
text=str(text)
ret='/'.join(map(bin,bytearray(text.encode()))).split("/")
retf=[]
for i in ret:
i=i[2:]
while len(i)<8:
i="0"+i
retf.append(i)
return retf
def bintoint(x):
... |
"""
===============
=== Purpose ===
===============
*** WARNING: This will trigger scoring and emails! ***
Performs database updates for Epicast-FLUV:
`history` update: import wILI from Epidata API
`round` update: increments the deadline by a week
=================
=== Changelog ===
=================
2017-09-... |
#!/usr/bin/env python
from __future__ import print_function, unicode_literals
import os
import io
import re
import sys
import json
import dateutil.parser
import snowflake.connector
import pygsheets
DEFAULT_DB_CONFIG_FILENAME = os.path.abspath('db.json')
DEFAULT_SERVICE_ACCOUNT_FILE = os.path.abspath('service-accoun... |
import importlib
import numpy as np
from copy import deepcopy
from types import ModuleType
# from .utils import get_logger
# logger = get_logger(__name__)
import logging
logger = logging.getLogger(__name__)
import thermal_history as th
from .model_classes import ThermalModel
def setup_model(parameters, core_method ... |
import pyfiglet
import os
import sys
import datetime
import generatepdf as reportpdf
ascii_banner = pyfiglet.figlet_format("RPI Inspector")
print(ascii_banner)
menu = {}
menu['1']="Disk Imaging"
menu['2']="Mount Image"
menu['3']="Generate Report"
menu['4']="Exit"
src_path = None
dest_path = None
path = os.getcwd()... |
# encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: <NAME> (<EMAIL>)
#
# THIS THREADING MODULE IS PERMEATED BY THE please_stop SIGNAL.
# TH... |
# -*- 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... |
import abc
import random
import numpy as np
import sklearn
class LM(abc.ABC):
@abc.abstractmethod
def loglikelihood(self, requests):
"""Compute log-likelihood of generating a continuation from a context.
Downstream tasks should attempt to use loglikelihood instead of other
LM calls whe... |
"""Tests file.
Tests for:
st_materials.py
"""
import pytest
from numpy.testing import assert_allclose
from ross.stochastic.st_materials import ST_Material
###############################################################################
# tests for a single random variables
########################################... |
import os
import time
import torch
import argparse
from models.model import YOLOv1
import matplotlib.pyplot as plt
from torchvision import utils
from torch.optim import SGD, Adam
# from torchviz import make_dot
from models import build_model
from utils.util import YOLOLoss, parse_cfg
from utils.datasets import create_d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2017 theloop, 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 req... |
"""
1: Transform file attachments (like message.txt, main.js, etc...) to a gist.
2: if the bot detect a token, it will create a gist to revoke it.
"""
import asyncio
import os
import re
import aiohttp
import discord
from discord.ext import commands
import filetype
from .utils.misc import create_new_gist, add_reactio... |
#!/usr/bin/python -u
#Copyright 2017 <NAME>
#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, dis... |
from typing import Optional, Tuple
import torch
from torch import Tensor
from torch_dftd.functions.triplets_kernel import _calc_triplets_core_gpu
def calc_triplets(
edge_index: Tensor,
shift: Optional[Tensor] = None,
dtype=torch.float32,
batch_edge: Optional[Tensor] = None,
) -> Tuple[Tensor, Tensor,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Usage: episodes.py [--series=<series> --serie=<serie> -c]
Options:
--series=<series> Path to a file containing information about the series
formatted as 'Plumcot/data/series.txt' (see CONTRIBUTING).
Defaults to ... |
# Author: <NAME>
# Email: <EMAIL>
import json
from math import ceil
import os
import numpy as np
import pandas as pd
from scipy.interpolate import interp1d
from opentraj.toolkit.core.trajdataset import TrajDataset
def image_to_world(p, Homog):
pp = np.stack((p[:, 0], p[:, 1], np.ones(len(p))), axis=1)
PP = ... |
import torch.nn as nn
import math
import torch
def conv1x1(in_planes,out_planes,stride=1):
return nn.Conv2d(in_planes,out_planes,kernel_size =1,stride =stride,bias=False)
def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.