text stringlengths 3.07k 22.1k |
|---|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pycocotools.coco as coco
from pycocotools.cocoeval import COCOeval
import numpy as np
import json
import os
import copy
from .prophesee_src.io.psee_loader import PSEELoader
from .prophesee_src.visualize.... |
from PIL import Image
import glob, os, sys, errno
import numpy as np
import argparse
BOUNDARY_WIDTH = 1
# return a tuple of total size and paste position
def get_new_size(image):
# Set requisite dimensions. Center original image within new image.
max_dimension = max(image.width, image.height)
return (max_... |
import collections
import csv
import os
import re
import lib
import over_time
DRIVER_NODE = "192.168.1.19"
def extract_data(last_eight_lines):
def parse(header_line, data_line, suffix=""):
if "elapsed" not in header_line:
return {}
fields = data_line.strip().split()
if "read" in fields[-1]:
... |
"""
Stability Evaluation
"""
import os
import pickle
import re
from collections import OrderedDict
from statistics import stdev
import numpy as np
import pandas as pd
from keras.wrappers.scikit_learn import KerasClassifier
from scipy.spatial.distance import cdist
from sklearn.feature_extraction.text import TfidfVector... |
from pathlib import Path
from typing import Dict, List, Union
import dash
import dash_bootstrap_components as dbc
import pickle
import plotly.express as px
from dash import Input, Output, callback_context, dcc, html
from plotly.graph_objs import Figure # Only used for type hint!
from prepare_results import TSNE_PARAM... |
import glob
import itertools
import os
import numpy as np
import tqdm
from . import utils
class TIMITReader(object):
def __init__(self):
self.train_dataset_path = os.environ['TIMIT_TRAINING_PATH']
self.test_dataset_path = os.environ['TIMIT_TESTING_PATH']
self.data_root = os.environ['MODE... |
import subprocess
import pathlib
import sys
import os
import argparse
import shutil
from pathlib import Path
from multiprocessing import Pool
from duplicates_tags import bam_has_XD_tag
from has_read_groups import read_group_checks
from bam_finder import ShopVersion
# Check to see if a bam has any reads
def bam_has_ali... |
#!/usr/bin/env python3
"""
This is a script to append an Archivematica UUID as
an Internal-Sender-Identifier to existing born-digital bags.
When run this will create a "target" folder in the same directory
to work within. It will leave "some_bag_id.log" files for each
bag it migrates.
"""
import datetime
import hashl... |
import os
import sys
import re
import gzip
import csv
import json
import logging
from contextlib import contextmanager
from collections import defaultdict, OrderedDict
import numpy as np
import pandas as pd
import h5py as h5
logger = logging.getLogger('yanocomp')
pd.options.mode.chained_assignment = None
# Functions... |
from __future__ import absolute_import
import argparse
from typing import List, Union, Optional
import logging
import sys
import os
from subprocess import Popen, PIPE
import json
import inspect
import io
import numpy as np
import spacy
import torch
from allennlp.common import Params
from allennlp.data import Token
d... |
# Copyright 2021 NVIDIA 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 agreed to in wr... |
import discord
from discord.ext import commands
import asyncio
import sqlite3
import yaml
import datetime
import inspect
import math
import re
client = commands.Bot(command_prefix= "k!")
with open("config.yml") as f:
conf = yaml.load(f)
TOKEN = conf["token"]
conn = sqlite3.connect("main.db")
cur = conn.curso... |
from email.policy import HTTP
from sqlalchemy.sql.expression import null, true
from sqlalchemy.sql.sqltypes import Boolean
from fastapi import FastAPI, Depends
from pydantic import BaseModel
import datetime as dt
from datetime import datetime, date, timedelta
from sqlalchemy import func
from typing import Optional, Lis... |
#!/usr/bin/env python
import argparse
import os
import sys
from functools import wraps
from inspect import Parameter
from pprint import pprint
import requests
from halocoin import custom
from halocoin import engine
from halocoin import tools
class Colors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN ... |
import copy
import random
class test:
def __init__(self):
self.width = 20
self.height = 20
pp = test()
MAX_BOARD = 20
board = [[0 for i in range(MAX_BOARD)] for j in range(MAX_BOARD)]
# board[10][10] = 2
# board[10][9]=2
# board[3][5]=2
import hash
import Data as dt
dt._init()
d... |
import numpy as np
from numpy import linalg as LA
from scipy.stats import pearsonr
import nltk
import io
import random
EPS = 5e-7
emb_matrix = np.load("data/emb_{0}.npy".format("lexvec"), allow_pickle=True, encoding = 'latin1')
word2id = np.load("data/word2id_{0}.npy".format("lexvec"), allow_pickle=True, en... |
import os
import h5py
import yaml
import logging
import numpy as np
from PIL import Image
from scipy.spatial.transform import Rotation as R
from progress.bar import Bar
from multiprocessing import Pool, cpu_count
from omegaconf import OmegaConf
from tools.utils import io
# from tools.visualization import Viewer
from ... |
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from Dashboard.forms import *
from django.contrib import messages
from Dashboard.data_visualiza... |
"""
Probing using PoI algorithm in "The Price of Information in Combinatorial Optimization"
"""
import logging
from collections import defaultdict
from typing import Tuple
from scipy.stats import rv_continuous
from pup.algorithms.privacy_helper import buy_data_at_price
from pup.algorithms.util import cal_prod_dist_n... |
import logging
from typing import List
import torch
from allennlp.common import Params
from torch import nn
from transformers import T5Tokenizer, AutoConfig, T5ForConditionalGeneration, AutoTokenizer
from iconary.data.datasets import IconaryGame
from iconary.models.drawing_to_text import DrawingEncoder, get_icon_toke... |
"""Helper Functions for Design of Experiments With Two Factors in Combination."""
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
import pandas as pd
import tellurium as te
import seaborn as sns
import util_doe1
import wolf_model as wm
def runExperimentsTwoParameters(paramet... |
# -*- coding: 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/.
import json
import re
import sys
from pathlib import Path
import click
import yaml
from .bhr_... |
"""
Formatter for PubAnnotation JSON output.
http://www.pubannotation.org/docs/annotation-format/
"""
__author__ = "<NAME>, <NAME>"
__all__ = ['PubAnnoJSONLoader', 'PubAnnoTGZLoader',
'PubAnnoJSONFormatter', 'PubAnnoTGZFormatter']
import io
import json
import time
import tarfile
import warnings
import ... |
from typing import TYPE_CHECKING, List, Dict, Any
if TYPE_CHECKING:
from Platforms.Web.main_web import PhaazebotWeb
import json
from aiohttp.web import Response
from Utils.Classes.extendedrequest import ExtendedRequest
from Utils.Classes.storagetransformer import StorageTransformer
from Utils.Classes.webrequestconten... |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import configparser
import itertools
import json
from dataclasses import dataclass
from io import StringIO
from pathlib import PurePath
from textwrap import dedent
from typing import Optio... |
"""Routes for user authentication."""
from flask import redirect, render_template, flash, Blueprint, request, url_for, session, jsonify
from flask_login import current_user, login_user
from ..forms import LoginForm, SignupForm, ReSentEmailConfirmationForm, PasswordResetFirstStepForm, PasswordResetSecondStepForm
from ..... |
import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
from matplotlib.colors import LinearSegmentedColormap
from mpl_toolkits.axes_grid1.inset_locator import (
inset_axes, Bbox, BboxConnector, BboxPatch, TransformedBbox)
import src.visualization.grid_viz as grid_viz
def time_evol_ling(li... |
import pytest
from ebl.dictionary.domain.word import WordId
from ebl.lemmatization.domain.lemmatization import (
LemmatizationError,
LemmatizationToken,
)
from ebl.transliteration.domain.enclosure_tokens import (
BrokenAway,
Determinative,
DocumentOrientedGloss,
Erasure,
)
from ebl.transliterat... |
"""Module for determining optimal double spikes."""
import itertools
import numpy as np
from scipy.special import binom
from scipy.optimize import minimize
from scipy.special import expit
from .errors import errorestimate
def optimalspike(
isodata,
type_="pure",
isospike=None,
isoinv=None,
errorr... |
from __future__ import print_function
import os
import logging
import torch
import shutil
import torch.optim as optim
import random
import torch.backends.cudnn as cudnn
from torchvision import transforms
from torch.autograd import Variable
from utils import *
from test import test
os.environ["CUDA_VISIBLE_DEVICES"] =... |
import matplotlib
# matplotlib.use('Agg')
# from pyvirtualdisplay import Display
# disp = Display(visible=1,size=(640,480)).start()
from stable_baselines import PPO2, PPO2Repr, logger
from stable_baselines.common.cmd_util import make_atari_env, atari_arg_parser
from stable_baselines.common.vec_env import VecFrameStac... |
#!/usr/bin/env python
"""
Computes a clustered time-segmentation from a multi-frame contact file using TICC [1].
The input is a contact-file and a desired number of clusters, k. The output is a file
with the contents of the segmentation. It can either be a tab-separated file where each
line records a frame-number and ... |
import pickle
import re
import time
import numpy as np
import tensorflow as tf
from keras_preprocessing.image import ImageDataGenerator
from sklearn.utils import shuffle
from tensorflow.python.keras.utils import to_categorical
from lib.plot_curves import learning_curves
from lib.helper_functions import validation_spl... |
"""
run the mesh tying algorithm
"""
import numpy as np
import scipy as sp
from scipy import spatial
from matplotlib import pyplot as plt
import amfe
#%%
def quad4_shape_functions(xi_vec):
xi, eta = xi_vec
N = np.array([(-eta + 1)*(-xi + 1)/4,
(-eta + 1)*(xi + 1)/4,
(eta +... |
from util import partial, Record
from util_np import np
from util_tf import tf, placeholder, trim, get_shape
scope = partial(tf.variable_scope, reuse=tf.AUTO_REUSE)
init_bias = tf.zeros_initializer()
init_kern = tf.variance_scaling_initializer(1.0, 'fan_avg', 'uniform')
init_relu = tf.variance_scaling_initializer(2.... |
from encodings.utf_8 import encode
from enum import auto
from re import M
from tensorflow.keras import Model
from tensorflow.keras.layers import Input, Conv2D, Conv2DTranspose, Activation, BatchNormalization, Flatten, Dense, Reshape, Activation, Concatenate,MaxPool2D,UpSampling2D
from tensorflow.keras import backend as... |
'''
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torchvision.transforms as transforms
from . import auto_augment as augment
from PIL import Image
# mean and std fr https://github.com/pytorch/examples/blob/master/imagenet/main.py
... |
"""
Derived from train.py by <NAME> (jocicmarko) for Ultrasound Nerve Segmentation
https://github.com/jocicmarko/ultrasound-nerve-segmentation/blob/master/train.py
Author: <NAME>
"""
from __future__ import print_function
import os
from skimage.transform import resize
from skimage.io import imsave
import numpy as np
... |
### DLINVEMI_1D_Training: program to train 1D CNN for EMI inversion
### Written by <NAME>
### Brandenburg University of Technology (BTU), Cottbus-Senftenberg
### Version: 05.09.2020
###
### libraries
import numpy as np
import pandas as pd
from tensorflow import keras
from numpy.random import seed
from tensorf... |
import math
import re
import types
import numpy as np
class InfoNotFoundError(RuntimeError):
pass
def _getMatricesFromDft2Outfile(outPath):
""" Parses all hamiltonian and overlap matrices from a dft2 file
Args:
outPath: Full path to the output file
Returns
allMatrices: types.SimpleNamespace with two ... |
from __future__ import division, print_function
from .echelle import echelle
from .utils import smooth_power
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import numpy as np
__all__ = ["interact_echelle"]
def interact_echelle(
freq,
power,
dnu_min,
dnu_max,
step=None,
... |
#! /usr/bin/env python3
# This file is a part of the Pepper project, https://github.com/devosoft/Pepper
# (C) Michigan State University, under the MIT License
# See LICENSE.txt for more information
"""
This is the lexer for PEPPr
It's responsible for tokenizing the incoming character stream. The Parser will ingest t... |
# ROS imports
import roslib; roslib.load_manifest('freemovr_engine')
import scipy.optimize
import imageio
from pymvg.camera_model import CameraModel
from pymvg.util import get_rotation_matrix_and_quaternion
import freemovr_engine.simple_geom as simple_geom
import numpy as np
import os
import cv2
PLOT=int(os.environ.g... |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
"""
Pytorch Classifier class in the style of scikit-learn
Classifiers include Logistic Regression and MLP
"""
from __future__ ... |
#!/usr/bin/env python2.6
"""
Tue Nov 27 14:50:38 PST 2012
Parse Blast XML output files and call the different cluster types.
This is applied in searching for similar (but not identical) clones to the expanded clones.
The input blast was done on the top clones of each patients:
For each V-J recombination:
Blast th... |
# Lint as: python3
"""Adds middle hops as distant supervision for OpenCSR data."""
import json
from absl import app
from absl import flags
from absl import logging
from tqdm import tqdm
import networkx as nx
import os
import numpy as np
import itertools
from scipy import sparse
import tensorflow.compat.v1 as tf
from ... |
from classes import db, Teacher, Paper, Invigilation, Version, Pool, Fixed_Invigilation
import datetime
from sqlalchemy.orm import noload
from openpyxl import Workbook
cohort = ["Year 1", "Year 2", "Year 3", "Year 4", "JC 1", "JC 2"]
def export_analytics():
versions = Version.query.options(noload("Invigilations")).a... |
'''
Module to create HDFS performance testing environment
Master node runs HDFS NameNode and YARN Resource manager daemons.
Worker nodes are where data is stored and computations are performed. They run HDFS DataNode and YARN NodeManager daemons.
'''
from __future__ import print_function
import os
import os.path
im... |
# MIT License
#
# Copyright (c) 2020 MiscellaneousStuff
#
# 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,... |
#!/usr/bin/env python
#url = "http://203.247.232.147:8080/rb.10x8/rb.mpd?172.16.31.10"
#url = 'http://549.ipdisk.co.kr/gpac/rb.10x8/rb.mpd'
import http.server
import sys
import xml.etree.ElementTree as elemTree
import re
import time
import os
import gc
import requests
import threading
import hashlib
from urllib.parse ... |
# Compute and analyze the results of cost_measurement.py
# Use correlation analysis and other methods to compute the relations between user complaints and costs
# -*- coding: utf-8 -*-
# __author__ = "<NAME>"
# __version__ = "2.0"
# __date__ = "3/12/2018"
import os, sys
import json
import numpy as np
from datetim... |
"""
Compute validation accuracies.
"""
import json
import argparse
import numpy as np
# torch modules
import torch
import torch.backends.cudnn as cudnn
# custom
from utils.learner import valid, valid_quantize
from utils.datasets import load_dataset_w_asample
from utils.networks import load_network, load_trained_n... |
import os
import asyncio
import logging
from functools import partial
from binascii import hexlify, unhexlify
from io import StringIO
from typing import Dict, Type, Iterable
from operator import itemgetter
from collections import namedtuple
from torba.client import baseaccount, basenetwork, basetransaction
from torba... |
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['figure.figsize'] = (16, 4)
def displayPlot(xlim=[-10, 10], ylim=[-0.1, 1.1], ncol=2):
legend = plt.legend(loc=1, ncol=ncol, framealpha=0, bbox_to_anchor=(1, -0.1))
plt.setp(legend.get_texts(), color='0.75', size=12)
plt.grid(True, alpha=0.2... |
'''
standardization -- same position in the vector
hstack -- stack columns
'''
from sklearn.preprocessing import StandardScaler,RobustScaler, MinMaxScaler, Normalizer
from pathlib import Path, PurePosixPath
import numpy as np
import pandas as pd
import joblib
from sklearn.preprocessing import LabelEncoder
fro... |
import socket
import random
import math
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from collections import namedtuple
from itertools import count
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision.transforms as T
print(torch.cuda... |
import numpy as np
import numpy.testing as npt
from cesium.features import lomb_scargle
from cesium.features.graphs import LOMB_SCARGLE_FEATS
from cesium.features.tests.util import (generate_features, irregular_random,
regular_periodic, irregular_periodic)
# These values are c... |
"""Collection of Helm related rules"""
load(
"//build:copy.bzl",
"copy",
)
load(
"@rules_pkg//:path.bzl",
"dest_path",
)
def helm_repos(ctx, srcs, repos):
"""Add the given Helm repositories returning the resulting configuration file"""
info = ctx.toolchains["//build/toolchains/helm:toolchain_... |
#! /usr/bin/env python3
IV = [
0x6A09E667,
0xBB67AE85,
0x3C6EF372,
0xA54FF53A,
0x510E527F,
0x9B05688C,
0x1F83D9AB,
0x5BE0CD19,
]
MSG_SCHEDULE = [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
[14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
[11, 8, 12, 0, 5... |
'''
File name: psy.py
Author: <NAME>
Date created: 10/31/2017
Date last modified: 10/31/2017
Python Version: 2.7
Description: Script to clean up database
Project: Psychosis
'''
from distutils.dir_util import copy_tree
from collections import Counter
from datetime import datetime
import pand... |
#
# Copyright (C) 2021 <NAME>
#
# This file is subject to the terms and conditions defined in the file 'LICENSE', which is part of
# this source code package.
#
'''
Secure fields.
'''
import os
import hashlib
import base64
import binascii
from typing import Union, Any, Optional, Callable, NamedTuple, Dict
from ..core ... |
#-----------------------------------------------------------------------------
"""
NXP Firmware Images
"""
#-----------------------------------------------------------------------------
import soc
import util
#-----------------------------------------------------------------------------
# IVT: The image vector tabl... |
#!/bin/python
import sys, numpy, os.path, re, os
import argparse
from Bio import SeqIO
import gzip, bz2, tarfile
def remove_false_files(filelist): #We remove empty files that otherwise would make everything crash
clean_list = []
for i in filelist:
if os.path.getsize(i) < 10000: #I probably need a better way to ju... |
from datetime import date
import spotipy
from decouple import config
from spotipy.oauth2 import SpotifyOAuth
def get_playlist(sp, name: str,
must_be_owner: bool = config('SURFACE_OWNED_PLAYLIST', default=False, cast=bool)):
"""Search Spotify for the playlist called `name` owned by the authentic... |
# -*- coding: utf-8 -*-
from __future__ import annotations
from typing import Any, Iterable, List, Optional, Type, TypeVar, Union
from collections.abc import Sequence
from dataclasses import asdict, dataclass, field, fields
from yaml import load, dump
try:
from yaml import CSafeLoader as Loader, CSafeDumper as D... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Copyright (c) 2012 <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:
#
... |
## MobileNet:
class DepthwiseConv2D(Conv2D):
def __init__(self,
kernel_size,
strides=(1, 1),
padding='valid',
depth_multiplier=1,
data_format=None,
activation=None,
use_bias=True,
... |
from django.http.response import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from .models import *
from .forms import *
from django.contrib.auth.models import User
from django.contrib.sessions.models import Session
from django.utils import timezone
from django.contrib.auth.decorators imp... |
"""
Bootstrap Particle Filter
"""
import numpy as np
import functools
def pf(particles, log_weights, kernel):
""" Algorithm 1 of PaRIS
{particles_t, weights_t} -> {particles_{t+1}, weights_{t+1}}
Args:
particles (ndarray): N by n, latent states (xi_t)
log_weights (ndarray): N, log importa... |
'''
Gui/Views/Dialogs/FindReplace
_____________________________
Binding for executing find/replace queries in QTableWidgets.
:copyright: (c) 2015 The Regents of the University of California.
:license: GNU GPL, see licenses/GNU GPLv3.txt for more details.
'''
# load modules/submodules
from PySide ... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from const import LINE_WIDTH, FONT_DICT_SMALL, FONT_SIZE, FONT_DICT_X_SMALL
class PaperFigure:
pass
@staticmethod
def format_plot():
ax = plt.gca()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_vis... |
# SPDX-FileCopyrightText: 2021 <NAME>ios
# SPDX-License-Identifier: MIT
# magic_eye.py
# 2021-12-12 v2.3
import displayio
import vectorio
from math import pi, pow, sin, cos, sqrt
from adafruit_display_shapes.circle import Circle
class Colors:
# Define a few default colors
BLACK = 0x000000
CYAN = 0x00FFF... |
"""
Module containing some popular mathematical functions,\n
that either have no specific category or were just forced here:
** exp(x) (Taylor Expansion or just e**x) #float -> float
** ln(x) #float (positive or not),complex -> float,Complex
** log(x) look above
** factorial(n) #... |
import time
import gym
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from gym.spaces.discrete import Discrete
from tensorboardX import SummaryWriter
from torch.distributions.categorical import Categorical
from purls.algorithms.base import ReinforcementLearningAlgorithm
from pur... |
#!/usr/bin/env python3.10
# -*- coding: utf-8 -*-
import unittest
import fill3
import fill3.terminal as terminal
import termstr
class WidgetTests(unittest.TestCase):
TEXT_A = fill3.Text("A")
TEXT_B = fill3.Text("B")
def assert_string(self, appearance, expected_string):
self.assertEqual(str(te... |
from src.shared_libs.guid import Guid
import random
from copy import deepcopy
__all__ = ['Player', 'AIPlayer']
class Player:
def __init__(self, token: str, *, name: str=None, id: str=None, discord_id: int=None):
if len(token) != 1:
raise Warning('Token must be exactly one character long.')
... |
#!/usr/bin/env python
#---------------------
import sys
import os
import os.path
import string
import time
import glob
import pwd
import glideinwms.lib.subprocessSupport
import common
from VDT import VDT
#STARTUP_DIR=sys.path[0]
#sys.path.append(os.path.join(STARTUP_DIR,"../lib"))
class Certificates(VDT):
def __... |
# Python3
'''HFT trading script python v=3.x'''
# from __future__ import print_function
import sys
import socket
import time
import json
import math
import numpy as np
# define the average number of transactions_per_tick, to be used in the max array length
transactions_per_tick = 3
# tracking 1 minutes worth of data... |
# my stupid attempt at a Snake game.
import pygame, random
from collections import deque
from pygame.locals import *
BLACK = (0, 0, 0)
AMBER = (255, 128, 0)
PLAY_WIDTH = 40
PLAY_HEIGHT = 40
CHAR_WIDTH = 9
CHAR_HEIGHT = 18
HALF_CHAR_HEIGHT = CHAR_HEIGHT//2
SCREEN_WIDTH = CHAR_WIDTH*80
SCREEN_HEIGHT... |
import logging
import numpy as np
import os
import os.path
import pacoUtils as pu
import subprocess
import yaml
def fvm(vv, q, u, where): # finite volume method
"""Finite volume method.
Inputs:
vv: int, 3. Vertices defining this face: v1, v2, v3. Zero-based (!)
q : float, 3 x 2. For each of t... |
from concurrent import futures
from enum import Enum
import grpc
import gpt_2_server_pb2
import gpt_2_server_pb2_grpc
import argparse
import sys
import fire
import json
import os
import numpy as np
import tensorflow as tf
import train
import model
import sample
import encoder
import spacy
import train
class Opperat... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import matplotlib.cm as cm
from scipy.interpolate import griddata
import os
import sys
import concurrent
from pyqstrat.pq_utils import set_defaults, has_display
from... |
#!usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Traveling Salesman Problem (TSP)
This problem can be solves in a brute-force way, namely n! permutations of the
vertices.
However, it can be solved smarter and faster.
Algorithm: (Dynamic programming)
Optimal Substructure Lemma:
Let P(v, S) be the shortest path from ... |
import torch
import torch.nn as nn
import torchvision.transforms as T
import torchvision.utils as vutils
from torch.autograd import Variable
from torch.utils.data import DataLoader
from PIL import Image
import os
from tqdm import tqdm
from torch.utils.tensorboard import SummaryWriter
from U2Net import U2Net
... |
import numpy as np
import cv2
import math
def edge_detect(lidar_img):
#lidar_img = lidar_img / np.max(lidar_img) * 255
edge_y = cv2.Sobel(lidar_img, cv2.CV_64F, 0, 2, ksize=1)
edge_x = cv2.Sobel(lidar_img, cv2.CV_64F, 2, 0, ksize=1)
#edge = np.append(np.expand_dims(edge_y, axis=2), np.expand_di... |
#!/usr/bin/python2.4
#
# Copyright 2009 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
import json
from keras.models import load_model
from keras.models import Model
from keras.layers import Input, LSTM, Dense
from shorttext.utils import compactmodel_io as cio
import shorttext.utils.classification_exceptions as e
# Reference: https://blog.keras.io/a-ten-minute-introduction-to-sequence-to-sequence-lea... |
# -*- coding: utf-8 -*-
from os import environ as env
# Third party
from flask import request
from flask import render_template
from flask import send_from_directory
from flask import jsonify
from flask import abort
from flask.views import View, MethodView
from almanak.cloud import InventoryService
# Application
imp... |
import datetime
import json
import logging
from abc import abstractmethod
from aim.sdk.query_utils import RunView, MetricView
from aim.storage import treeutils
from aim.storage.arrayview import ArrayView
from aim.storage.context import Context
from aim.storage.hashing import hash_auto
from aim.storage.query import Re... |
"""
@author : arjun-krishna
@desc :
The MLP class, with the methods to train and test
"""
from __future__ import print_function
import numpy as np
from mnist_reader import display_img
def sigmoid(x, derivative=False) :
if derivative :
y = sigmoid(x)
return y*(1 - y)
else :
return 1 / (1 + np.exp(-x))
def rel... |
import os
import time
import timeit
from utils import *
import torch
from torch.utils.data import DataLoader
import torch.nn as nn
from torch.nn import DataParallel
from models.model import define_G
from models.model_ENET_SAD import ENet_SAD
from models.loss import Perceptual, Wgangp, Naive, Hinge
from tensorboardX i... |
import copy
import torch
import numpy as np
from collections import defaultdict
from tqdm import tqdm
import shapely.geometry
import pycocotools.mask as mask_util
from pycocotools.cocoeval import COCOeval
from pycocotools.coco import COCO
from lydorn_utils import polygon_utils
class CocoEvaluator:
def __init__... |
import logging
import psycopg2
import psycopg2.extras
import os
import sys
from dotenv import load_dotenv
import geopandas as gpd
from shapely.wkt import dumps
from sqlalchemy import create_engine
from sqlalchemy.sql import text
from geoalchemy2 import Geometry, WKTElement
logger = logging.getLogger(__name__)
logger.s... |
#!/usr/bin/python
import os.path as path
from datetime import datetime
from six import PY2
from ExcelRobot.reader import ExcelReader
from ExcelRobot.utils import DataType
from nose.tools import assert_in, eq_, raises
from parameterized import parameterized
CURRENT_DIR = path.dirname(path.abspath(__file__))
DATA_DIR ... |
#!/usr/bin/env python
# Author: <NAME> (@Cyb3rPandaH)
###### Importing Python Libraries
# Libraries to handle execution errors
import sys
# Libraries to interact with up-to-date ATT&CK content available in STIX format via public TAXII server
from attackcti import attack_client
# Libraries to manipulate data
import... |
# code from gmum/MLinPL2019_cheminfo_workshops and gmum/geo-gcn
import os
import logging
import numpy as np
import pandas as pd
import torch
from torch_geometric.data import Data
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem import MolFromSmiles
from dmpnn_utils import MolGraph
def load_datas... |
import copy
import json
import dash
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
import pandas as pd
import plotly.graph_objs as go
from dash_app.components import consensustable, consensustree, tools
from dash_app.server import app
class Node:
def __init__(self, i... |
#!/usr/bin/env python3
"""
A script for collecting EXP results. Currently somewhat hardcoded for BR & WCP.
Requires Python 3.5 or later to run. Pass the target experiment basename directory as the first argument to collect the results.
Depending on which configurations were executed, different results will be availab... |
import csv
import re
from datetime import date, timedelta
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.urls import reverse
from django.utils import timezone
from multiselectfield import MultiSelec... |
#/u/goldensights
import datetime
import praw
import time
import sqlite3
import traceback
''' USER CONFIGURATION '''
USERAGENT = ""
APP_ID = ""
APP_SECRET = ""
APP_URI = ""
APP_REFRESH = ""
# https://www.reddit.com/comments/3cm1p8/how_to_make_your_bot_use_oauth2/
SUBREDDIT = "GoldTesting"
# Subreddit to scan for post... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.