text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
**Project Name:** MakeHuman
**Product Home Page:** http://www.makehumancommunity.org/
**Github Code Home Page:** https://github.com/makehumancommunity/
**Authors:** <NAME>, <NAME>,
<NAME>
**Copyright(c):** MakeHuman T... |
from __future__ import division
from __future__ import print_function
import argparse
import os
import pickle
import sys
# sys.path.append(".")
import numpy as np
from dss_vae.structs.dataset import Dataset
from dss_vae.structs.vocab import Vocab
from dss_vae.structs.vocab import VocabEntry
def data_details(train_... |
import pytest
import copy
from datetime import timedelta
import maya
from maya.core import _seconds_or_timedelta # import private function
def test_rfc2822():
r = maya.parse('February 21, 1994').rfc2822()
d = maya.MayaDT.from_rfc2822(r)
assert r == 'Mon, 21 Feb 1994 00:00:00 GMT'
assert r == d.rfc28... |
import numpy as np
import scipy as sp
import scipy.optimize
import matplotlib.pyplot as plt
from dimension_reduction import get_rank_reduction_matrix
import idw
import time
import glpk
glpk.env.term_on = False
#Given a data matrix X [dxn, columns are samples]
#a d-dimensional starting vector z and a d-dimensional
#di... |
#!/usr/bin/env python3.6
"""
Created on Feb 20 2019
"""
import json
import hashlib
import os
import sys
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
from dateutil.parser import parse
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from objects... |
import torch
from transformers import AutoModel,AutoTokenizer, DataCollatorWithPadding, AutoConfig
from transformers import get_scheduler
import json
from torch.utils.data import DataLoader
from datasets import Dataset
from tqdm.auto import tqdm
import re
from transformers import AdamW
import torch.nn as nn
from sklear... |
import os
import numpy as np
import tensorflow as tf
from cgms_data_seg import CGMSDataSeg
# from multiprocessing import Pool
def regressor(
low_fid_data,
k_size,
nblock,
nn_size,
nn_layer,
learning_rate,
batch_size,
epoch,
beta,
loss_type,
outdir,
):
tf.compat.v1.re... |
import operator
from phidl.quickplotter import _get_layerprop
def write_lyp(filename, layerset):
""" Creates a KLayout .lyp Layer Properties file from a set of
PHIDL layers """
stipple_default = ['I2','I5','I9','I17','I19','I22','I33','I38']
stipple_count = 0
if filename[-4:] != '.lyp': filename =... |
import os
from datetime import date, datetime
import dateparser
def parse_date(value):
"""
Function used to cast value to datetime from String or date objects.
Uses the `dateparser` library for String objects.
All strings will be parsed in UTC timezone, but returned value will be
timezone unawar... |
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from sys import argv
import logging
import requests, praw
import random as rd
from time import time, strftime, gmtime
import auth # Telegram Bot Token
from utils import *
def start(bot, update):
printCommandExecution(bot, update)... |
# -*- coding: utf-8 -*-
#
# test_xlsm_era.py
# pangaea
#
# Author : <NAME>, 2017.
# License: BSD 3-Clause
from os import path
from numpy.testing import assert_almost_equal
import pandas as pd
from affine import Affine
import pytest
import xarray as xr
import pangaea as pa
from .conftest import compare_proj4
pa... |
"""
Function for the detection of sleep boundaries, here defined as the total sleep opportunity window.
<NAME>
Copyright (c) 2021. Pfizer Inc. All rights reserved.
"""
from numpy import min, max, percentile, zeros, bool_, pad, sin, arange, pi, concatenate
from numpy.random import default_rng
from skdh.utility import ... |
from re import search, match as test, IGNORECASE, DOTALL
from datetime import datetime
from querier import DataQuerier
from outputs import ResultsWriterFactory
import logging
APPLICATION_NAME = 'downdrag'
APPLICATION_CONFIG_SCHEMA = 'schema.yml'
APPLICATION_CONFIG_FILENAME = 'downdrag.yml'
KEY_DETAILS = 'details'
KEY_... |
import numpy as np
import pandas as pd
import pickle
import torch
from torch import nn
import torch.nn.functional as F
import time, math
# init_converter()
midi2note = pickle.load(open("conversion/midi2note.pkl", "rb"))
note2midi = pickle.load(open("conversion/note2midi.pkl", "rb"))
train_on_gpu = torch.cuda.is_ava... |
import date_utils.calendar_util
# Returns the weekday from a given hebrew date (0 for Sunday,
# 1 for Monday,...)
def getWeekdayOfHebrewDate(hebDay, hebMonth, hebYear):
# Calculating the julian date
julian = date_utils.calendar_util.hebrew_to_jd(hebYear, hebMonth, hebDay)
weekday = (int(julian) + 2) % 7
... |
from __future__ import annotations
import contextlib
import inspect
import string
import sys
import termios
from contextlib import contextmanager
from copy import deepcopy
from dataclasses import dataclass
from enum import Enum, unique
from io import UnsupportedOperation
from itertools import product
from pathlib impo... |
import chainer
import chainer.functions as F
import chainer.links as L
class ResNet(chainer.Chain):
def __init__(self, n_layers, class_labels):
super(ResNet, self).__init__()
w = chainer.initializers.HeNormal()
# expected insize = 224
if n_layers == 18:
block = [2, 2,... |
# Copyright 2012 VPAC, http://www.vpac.org
# Copyright 2013-2016 <NAME> <<EMAIL>>
#
# This file is part of Patchman.
#
# Patchman 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, version 3 only.
#
# Patchman is... |
# Copyright (c) 2019, NVIDIA CORPORATION. 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 applic... |
import numpy as np
def conv2d(img, kernel, padding='valid'):
assert img.ndim == 2, 'Image needs to be in 2d array'
assert kernel.ndim == 2, 'Kernel needs to be in 2d array'
assert kernel.shape[0] % 2 == 1 and kernel.shape[1] % 2 == 1, 'Please make odd kernel size'
if img.dtype == 'uint8':
img ... |
import json
import logging
from django.conf import settings
from django.contrib.postgres.fields import JSONField
from django.contrib.postgres.indexes import GinIndex
from django.db import models, transaction, connection
from django.utils.functional import cached_property
from psycopg2.extras import execute_batch
impo... |
import math
import sys
if sys.version_info >= (3,0):
xrange = range
def binarySearch(list, value, start=None, end=None):
if start is None:
start = 0
if end is None:
end = len(list)
while start < end:
mid = (start+end) // 2
if list[mid] < value:
... |
# -*- coding: utf-8 -*-
# Copyright 2019 Open End AB
#
# 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 o... |
from types import FunctionType, MethodType
from .resource import HttpResponseUnauthorized
from .resource import Resource
class authenticate(object):
def __init__(self, authentication):
self.authentication = authentication
def __call__(self, obj):
if isinstance(obj, type) and issubclass(obj, R... |
import io
import math
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw
from skimage import measure
import tensorflow as tf
import yaml
# Example input and output:
# /Users/Paullaptop/Desktop/DATA/ DATA 2018/04/60D/ HR 48/IMG_1763.png
# 202012 Paul/training/DATA - Aggregation 2018/04 - 180... |
import numpy as np
import scipy.signal
def reclassify(array, class_dict):
"""Reclassifies values in a ndarray according to the rules provided in class_dict.
:param array: Array that holds categorical class values. (ndarray).
:param class_dict: Dictionary that maps input class values to output class value... |
# Image compression
#
# You'll need Python 2.7 and must install these packages:
#
# scipy, numpy
#
# You can run this *only* on PNM images, which the netpbm library is used for.
#
# You can also display a PNM image using the netpbm library as, for example:
#
# python netpbm.py images/cortex.pnm
import sys, os, ma... |
import socket
from multiprocessing.pool import ThreadPool
from time import sleep
import six
from kombu import Connection, Consumer, Queue
from kombu.exceptions import MessageStateError
from kombu.utils import nested
from microservices.helpers.logs import InstanceLogger
from microservices.utils import get_logger
_log... |
#Common functions for the codes in this directory
#Function to check if the output paths exist
#Function to check if the required prop is there (different for each request)
#Function to launch the request
#!/usr/bin/env python3
#Initial script for questioning the Disgenet API and see how it works.
#Local instantiat... |
import os
import sys
import warnings
import contextlib
import numpy as np
from scipy.integrate import odeint
from scipy.interpolate import interp1d
warnings.filterwarnings('ignore')
# Global constants
G = 6.674e-8 # Gravitational constant (cgs)
c = 3.e10 # Speed of light (cm/s)
R = 1.e6 ... |
# audio-offset-finder
#
# Copyright (c) 2014 British Broadcasting Corporation
# Copyright (c) 2018 <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/LI... |
#######################################################################
#
# Copyright 2009-2010 by <NAME>
#
# This file is part of the VIGRA comp... |
from __future__ import print_function
import matplotlib.pyplot as plt
#from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import scipy as sp
import sys
import scipy.ndimage as ndimage
import scipy.interpolate as si
import contmaker as cm
#Takes in an array of chi-squared test results and plots them as a functi... |
"""
This module implements the formatting
for create_report(df) function.
"""
from typing import Any, Dict, List, Optional
import numpy as np
import pandas as pd
from bokeh.embed import components
from bokeh.models import Title
from bokeh.plotting import Figure
from ..distribution import compute, render
from ... |
# ADB File Explorer `tool`
# Copyright (C) 2022 <NAME> <EMAIL>
#
# 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.
#
# Th... |
from os import listdir
from os.path import join
import matplotlib.pyplot as plt
import pandas as pd
from utils import utils
from utils.enums import MetricCaptions, MetricNames
def visualize_classifier(properties, models, metric_name, metric_caption):
path = join(utils.app_dir, properties["output_folder"], "resu... |
import numpy as np
from . import measure_moms
from . import acs_model_e as acs_model
from . import drizzle_position as dp
import os as os
from astropy.io import fits
from . import directories
def acs_determine_focus_metric( true, model ):
'''
SO A is the flag to check if the quadrupole moments
match
''... |
import numpy as np
import matplotlib.pyplot as plt
from dmsuite import chebdif
from scipy.optimize import fsolve
def bvp_fsolve(ode,bc,solinit,options):
#left and right end points of the interval [a,b]
sol = {}
sol['a'] = solinit['boundaries'][0]
sol['b'] = solinit['boundaries'][-1]
sol['ode'] = o... |
import NLU
s_map = dict();
s_set = set();
likes_map = dict();
sim_likes = dict();
# intended control flow:
# 1. determine speaker - in: utterance - out: speaker
# 2. find similar speakers - in: speaker - out: speakers
# 3. find entities - in: utterance - out: entities... |
"""This module implements the generation of connector config generation UI."""
import json
from typing import Any, Dict, Generator, Optional, Tuple
from IPython.display import display
from ipywidgets import (
HTML,
Box,
Button,
Dropdown,
GridspecLayout,
HBox,
Layout,
Output,
Radio... |
import sys
import os
from platform import system
import psutil
import webbrowser
from time import sleep
from subprocess import PIPE, Popen
from ..core.helpers import console
from ..parameters import NAME, VERSION
from ..applib.app import findApp, findAppConfig
from .command import (
argDebug,
argNoweb,
a... |
import tensorflow as tf
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import random
import math
import scipy.stats as stats
np.random.seed(1234)
random.seed(1234)
plt.switch_backend("TkAgg")
def plotScatter(points, color):
xs = [x[0] for x in points]
ys = [y[1] for y in points]
... |
# -*- coding: utf-8 -*-
import cv2
from cvzone.HandTrackingModule import HandDetector
from time import sleep
import cvzone
from pynput.keyboard import Key, Controller
keyboard_layout1 = [[((25,100),(45,45)), ((85,100),(45,45)), ((145,100),(45,45)), ((205,100),(45,45)), ((265,100),(45,45)), ((325,100),(45,45)), ((385,... |
# Copyright (c) 2015-2016 Sippy Software, Inc. All rights reserved.
#
# 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. Redistributions of source code must retain the above copyright notice, ... |
import os
from collections import defaultdict
from tqdm import tqdm
import numpy as np
import cv2
from detect import YOLODetector, VOC_CLASS_BGR
def compute_average_precision(recall, precision):
""" Compute AP for one class.
Args:
recall: (numpy array) recall values of precision-recall curve.
... |
from appJar import gui
import _thread
#import driveGUI
from driveGUI import calc_steering,reset_stop_flag,set_stop_flag,set_autonomer_modus,set_manueller_modus,lese_von_ST,set_Gaspedal_Stellung,show_Frame,get_model_steering_angle,set_Fummelfaktor_Stellwinkel
app = gui("control panel","550x550")
import time
Start=Fa... |
import numpy as np
import torch
import bandmat as bm
import bandmat.linalg as bla
def _build_win_mats(windows, num_frames):
r"""For MLPG. Builds a window matrix of a given size for each window in a collection.
Parameters
----------
windows : list[window]
Specifies the collection of windows a... |
# django-salesforce
#
# by <NAME>
# (c) 2012-2013 Freelancers Union (http://www.freelancersunion.org)
# See LICENSE.md for details
#
"""
Django models for accessing Salesforce objects. (like django.db.models)
The Salesforce database is somewhat un-UNIXy or non-Pythonic, in that
column names are all in CamelCase. No a... |
import numpy as np
from pyquaternion import Quaternion
def so3_vee(Phi):
if Phi.ndim < 3:
Phi = np.expand_dims(Phi, axis=0)
if Phi.shape[1:3] != (3, 3):
raise ValueError("Phi must have shape ({},{}) or (N,{},{})".format(3, 3, 3, 3))
phi = np.empty([Phi.shape[0], 3])
phi[:, 0] = Phi[:... |
# TODO: Add an appropriate license to your skill before publishing. See
# the LICENSE file for more information.
# Below is the list of outside modules you'll be using in your skill.
# They might be built-in to Python, from mycroft-core or from external
# libraries. If you use an external library, be sure to include... |
from flask_admin.menu import MenuLink
from flask_babelex import Babel
from model.QuantAdminModels import *
from model.modelBase import app as app_model
from model.adminModels import *
from model.NetAdminModels import *
from service.ShopService import ShopService
from views.timer import timer
from views.user i... |
'''
Created on Apr 30, 2020
@author: <NAME>
'''
import sys
sys.path.append('../')
import os
import time
import argparse
import cv2
import numpy as np
import tensorflow as tf
from tqdm import tqdm
from skimage import io, color
from PIL import Image
from common.eval_noshift import multi_compute as measure_noshift
from ... |
import jsonschema
import logging
import time
from copy import deepcopy
from secrets import token_hex
# Helper for Interaction.validate(): ensure the objects' IDs are unique and do not contain |
def _check_ids(objects):
ids = [obj['id'] for obj in objects]
if len(ids) != len(set(ids)):
raise RuntimeErr... |
"""
tests.app
~~~~~~~~~~~~~~~~~~~
Tests the Memory Storage container.
:copyright: (c) 2016 by <NAME>.
:license: BSD, see LICENSE for more details.
"""
import json
import pytest
from app import app, reinit_db
'''
HELPER FUNCTIONS
'''
def create_schema(c, name, status_code=201):
postresp = c.p... |
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn import Parameter
def init_xavier_uniform(layer):
if hasattr(layer, "weight"):
torch.nn.init.xavier_uniform_(layer.weight)
if hasattr(layer, "bias"):
if hasattr(layer.bias, "data"):
layer.bias.data... |
import boto3
import json
import re
from datetime import datetime
from .common import utils
from .common.exceptions import PassthroughException
from anlogger import Logger
_logger = Logger("virtualmail-handler", 'INFO')
logger = _logger.get()
from anawsutils import dynamodb
ddb = dynamodb.DDB()
from anenvconf impor... |
# Author: <NAME> <<EMAIL>>
# Copyright (c) 2020 <NAME>
#
# This file is part of Monet.
import logging
import time
import sys
from typing import Union, Tuple, Dict, Iterable
from sklearn.neighbors import NearestNeighbors
from sklearn.manifold import TSNE
import plotly.graph_objs as go
import pandas as pd
import numpy ... |
# Copyright 2019-2019 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" fil... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
import imutils
def img_equal_clahe_yuv(img):
"""Apply equalize, clahe into image with YUV channels.
Args:
img (image) : Image
Returns:
img_eq (image): Image with equalize applied
img_clahe (image): Image with clahe app... |
import getopt
import os
import sys
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pylab
from matplotlib.font_manager import FontProperties
from matplotlib.ticker import LinearLocator, LogLocator, MaxNLocator
from numpy import double
OPT_FONT_NAME = 'Helvetica'
TICK_FONT_SIZE = 24
LABEL_FO... |
"""Utils for Semantic Segmentation"""
# pylint: disable=consider-using-enumerate,redefined-builtin,broad-except
import threading
from mxnet import autograd
from mxnet.gluon.utils import split_and_load
from mxnet.ndarray import NDArray
try:
import Queue as queue
except ImportError:
import queue
__all__ = ['Da... |
import sys
import time
import math
import logging
import argparse
import numpy as np
from datetime import datetime
def eval_str_list(x, type=float):
if x is None:
return None
if isinstance(x, str):
x = eval(x)
try:
return list(map(type, x))
except TypeError:
return [ty... |
import argparse
import functools
import glob
import pickle
import itertools
import json
import os
import random
import sys
import torch
import torch.nn.functional as F
import os
import json
import seaborn as sns; sns.set()
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_g... |
# -*- coding: utf-8 -*-
#
# Copyright 2014 <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 a... |
from itertools import product
from quantlib.instruments.option import EuropeanExercise
from quantlib.instruments.payoffs import PlainVanillaPayoff
from quantlib.instruments.option import Put, Call
from quantlib.instruments.asian_options import (
ContinuousAveragingAsianOption, DiscreteAveragingAsianOption, Geome... |
"""
This module contains views necessary for external drivers to interact with metagov. Django-based apps
can call the underlying methods directly.
"""
import logging
from http import HTTPStatus
import jsonschema
import metagov.httpwrapper.openapi_schemas as MetagovSchemas
from django.http import HttpResponse, HttpRes... |
#!/usr/bin/env python3
"""utility.py
Various common utility functions, classes and decorators.
"""
__author__ = '<NAME>'
import heapq
import itertools
from collections import deque
from typing import (
Any,
Callable,
Deque,
Dict,
Iterable,
List,
Mapping,
Optional,
Sequence,
S... |
"""
Sprites can be stored in many ways
A really cool way, is to have the image with an ANDable section so that the background is cleared before printing it.
This way it doesn't need to be xor'ed, but just ORed.
The AND section can be stored interlaced with the actual graphic for example:
Before Af... |
from typing import List, Dict, Set
from pathlib import PurePosixPath
from collections import deque
import re
from alipcs_py.alipcs import AliPCSApi, PcsFile
from alipcs_py.commands.list_files import list_files
from alipcs_py.commands.sifter import Sifter
from alipcs_py.commands.display import display_shared_links
from... |
"""Contains various utility functions for Dynet models."""
import dynet as dy
import numpy as np
def add_dim(variable, dim=0):
""" Adds a dimension to a vector dy.Expression.
Inputs:
variable (dy.Expression): A vector Dynet expression.
dim (int, optional): The dimension to add.
Returns:... |
import sqlite3
import numpy as np
import pdb
from utils.nlp import normalize
# loading databases
domains = ['restaurant', 'hotel', 'attraction', 'train']
# 3 domains do not have DB: 'taxi', 'hospital', 'police']
dbs = {}
for domain in domains:
db = 'data2.0/db/{}-dbase.db'.format(domain)
print("Connect to ... |
import requests
import sys
import os
from types import SimpleNamespace
import time
import json
from api_client import AIBrushAPI
import base64
import traceback
import subprocess
from PIL import Image
import torch
import argparse
from io import BytesIO
import clip_rank
# from vqgan_clip.generate import run, default_arg... |
"""Contains utilities for downloading and converting datasets."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tensorflow as tf
import inception_preprocessing
import math
import sys
slim = tf.contrib.slim
LABELS_FILENAME = 'labels.txt'
... |
import random
from copy import deepcopy
from itertools import groupby
import numpy as np
from scipy.ndimage import rotate
from rendering.ConsoleColours import ConsoleColours
from rendering.display_board import display_board
from rendering.render_table_row import render_table_row
from rendering.display_user_input_menu i... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import copy
from torch.nn.modules.container import ModuleList
from transformers import BertModel
class ArgModule(nn.Module):
def __init__(self, arg_layer, n_layers):
"""
Module for extracting arguments based on given encoder output... |
"""
Chapter Two - Linked Lists
"""
# Creating a simple node class.
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
# Build a linked list from a list for testing.
def llist_from_list(lst):
if len(lst) == 0:
return None
n = N... |
# 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, software
# distributed under t... |
from __future__ import division, print_function
import numpy
import scipy
import cplex
import copy
import itertools
from .rba_Matrix import RBA_Matrix
class RBA_LP(RBA_Matrix):
"""
Attributes
----------
A : scipy.sparse.coo_matrix
Lefthandside of constraint Matrix (aka Constraint Matrix)
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms
import os
import numpy as np
import json
import gdown
from PIL import Image
import cv2
from .models.fcn_net import _build_fcn
from .util.utils import make_color_seg_map
__PREFIX__ = os.path.dirname(os.path... |
# Fetch special event info (Birthdays, Holidays, Anniversaries, etc. with image)
import datetime
'''
Entry fields:
year [optional]: year of event
month: month of event
day: day of event
header [optional]: Will be used as the header of the event entry when displayed on calendar
title [optional]:... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 22 14:37:29 2018
@author: Brettmccausland
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import operator
from operator import itemgetter, attrgetter
from sklearn.preprocessing import Imputer
from sk... |
import tornado.ioloop
import tornado.web
import tornado.platform.asyncio
from tornado.options import define, options, parse_command_line
from tornado.httpclient import AsyncHTTPClient
from asyncio import sleep
from datetime import datetime
import time
import random
import platform
import asyncio
import logging
if plat... |
import numpy as np
from keras.preprocessing import sequence
from keras.datasets import imdb
import torch
from torch.autograd import Variable
from torch.optim import Adam
import Model.Constants as Constants
from Model.Modules import Encoder, Generator, Discriminator
from utils import check_cuda
max_features = 10000
ma... |
import numpy as np
import cortecx.construction.cxsession as cxsession
class HELP:
def __init__(self):
self.pos_codes = {
'CC': 'Coordinating Conjunction',
'CD': 'Cardinal number',
'DT': 'Determiner',
'EX': 'Existential "there"',
'FW': 'Foreign W... |
import enum
import torch
from torch import optim
import torch.nn.functional as F
from torch import nn
from torchvision import datasets, transforms, models
from PIL import Image
import numpy as np
class Phase(enum.Enum):
train = 'train'
valid = 'valid'
test = 'test'
def load_data(phase = Phase.train, bat... |
import numpy as np
import scipy.optimize
import time
# ----------------------------------------------------------------#
class RhsParam(object):
def __init__(self, param):
self.param = param
def __call__(self, x, y, z):
return self.param
# ---------------------------------------------------... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
import os
import time
import shutil
import sys
import os.path
import json
import codecs
import re
import argparse
def copy_file(src, dst):
shutil.copyfile(src, dst)
def copy_dir(src, dst):
shutil.copytree(src, dst)
def read_file(src):
f = open(src, 'r')
s ... |
import os
import simplejson as json
import codecs
import uuid
import utils
def makeServerDefine(svrCfg, env, svrType, hcount, hosts, portsStart, extras):
#print("makeServerDefine ", env, svrType, hcount)
if hosts["local"] not in svrCfg["Cluster"]["Hosts"]:
svrCfg["Cluster"]["Hosts"][hosts["local"]] = 1
... |
import scipy
from scipy import signal
import numpy as np
import cv2
from matplotlib import pyplot as plt
import os
import matplotlib.colors as colors
def read_img(path):
return cv2.imread(path, 0)
def save_img(img, path):
cv2.imwrite(path,img)
print(path, "is saved!")
def display_img... |
# Copyright 2020 LMNT, 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 applicable law or ag... |
import numpy as np
from functools import reduce
from PyQt5 import QtGui
from app.utils import Shape
from app.math_functions import (
transformations_functions_dict,
build_homogeneous_coordinates,
calculate_object_center,
multiply_coordinates_by_transformations,
normalize_point,
calculate_bezier... |
import os
from pyivle.pyivle import Pyivle
from models import User, Module
import datetime
import html_stripper
import userstr
API_KEY = os.environ['API_KEY']
auth_token = None
IVLE = Pyivle(API_KEY)
MODULE_ID_NULL_STRING='00000000-0000-0000-0000-000000000000'
async def do(auth_token, func, params={}):
IVLE.set_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
from copy import deepcopy
import numpy as np
import pandas as pd
import networkx as nx
import statsmodels.formula.api as smf
import statsmodels.api as sm
from scipy.cluster.vq import kmeans, whiten, vq
from gmeterpy.core.readings import Readings
from gm... |
# coding: utf8
import PIL.Image
import pkg_resources
import unittest
import zeit.cms.testing
import zeit.content.image.testing
import zeit.imp.interfaces
import zeit.imp.mask
import zeit.imp.source
import zope.interface.verify
product_config = """
<product-config zeit.imp>
scale-source file://%s
color-source ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 27 16:38:35 2020
@author: bart
This should contain all functionality regarding input. Both an input file
and the terminal argparsing is included. If any functionality would require
user input, that should be handled here.
"""
import argparse
impor... |
import argparse
import math
import subprocess
from datetime import datetime
import numpy as np
import tensorflow as tf
from tensorflow.contrib.framework import get_variables
import socket
import importlib
import os,ast
import sys
import time
from sklearn import metrics
BASE_DIR = os.path.dirname(os.path.abspath(__fil... |
#!/usr/bin/env python
import rospy
import math
from std_msgs.msg import Bool
from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport
from geometry_msgs.msg import TwistStamped, PoseStamped
from styx_msgs.msg import Lane, Waypoint
from tf.transformations import euler_from_quaternion
import math
... |
"""
Contains all routes for the application
Uses GET and POST methods to interact with the database
"""
from flask import render_template, request, url_for, redirect, flash, Blueprint
from flask_login import login_user, login_required, logout_user, current_user
from .models import Game, Round, Player, Score, calculate... |
import pytest
import re
from base64 import b64encode
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from ipaddress import IPv4Address, IPv6Address
from typing import Any
from uuid import UUID
from chocs.json_schema import StringFormat
from chocs.json_schema.errors import FormatValidat... |
"""Synthetic datasets."""
import numpy as np
import tensorflow as tf
def gaussian_in_nd(
n_dims,
n_centers,
n_points,
stddev,
limit=1.0,
splits=None,
seed=None
):
"""Randomly sample 2D points on a plane.
The centers are uniformly sampled in [-limit, limit] range.
Parameters
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.