text stringlengths 3.07k 12.6k |
|---|
from csv import DictWriter
import re
from re import Pattern
import sys
from typing import Any, Dict, List, Optional
import urllib.request
import xml
from xml.etree.ElementTree import Element, ElementTree
REGEX_IMAGE_FILE_NAME: Pattern = re.compile(r"[a-zA-Z0-9-]+\.((gif)|(png)|(jpg)|(jpeg)|(bmp)|(tiff))")
REGEX_SCRIP... |
#!/usr/bin/env python
# Simple console application that works with pyrow to send data retrieved from
# a connected Concept 2 rowing erg to a client via websockets.
# ==============================================================================
# IMPORTS
# =============================================================... |
"""
Module: nvp_freq_scaling.py
interfaces to set and get the CPU and GPU frequency
"""
import os
import time
# CPU and GPU frequency scaling to get power measurements for different workloads
# https://elinux.org/Jetson/Performance
# Warning : All the commands on this page must be executed as root
CPU0 = "cpu0"
CPU1... |
def variables():
x = 4 # these are variable assignments.
y = 5 # when you reference x and y in your code they will return the stored values.
print(x,", ", y) # this will output the values of x and y to the console window.
# variables can contain alphanumeric characters and underscores.
# var... |
#!/usr/bin/env python
from flask import Flask, render_template
import pywebaudioplayer as pwa
import numpy as np
import matplotlib
matplotlib.use("agg")
import matplotlib.pyplot as plt
app = Flask(__name__, static_folder='media')
@app.route('/')
def index():
w1 = pwa.wavesurfer('media/drums.mp3',
... |
__all__ = ['prepare_auto_connect']
import warnings
from pyvmodule import viterator as viter
from pyvmodule.wire import Wire
def get_match_table(obj,pattern,io):
if pattern.count('*')>1:raise ValueError('Too many "*" to match.')
index = pattern.find('*')
cls = type(obj)
if index<0:
if pa... |
from django.contrib import messages
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.db.models import Count
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse_lazy
from django.utils... |
#
# This file is part of LUNA.
#
""" UART interface gateware."""
import unittest
from abc import ABCMeta
from enum import Enum, auto
from nmigen import Elaboratable, Module, Signal, Cat
from ..test import LunaGatewareTestCase, sync_test_case
class UARTTransmitter(Elaboratable):
""" Simple UART transitter.
... |
from abc import ABC, abstractmethod
from board import Horse, Trainer, Property
class Strategy(ABC):
@abstractmethod
def decide_whether_to_buy_property(self, controller,
property: Property) -> bool:
pass
@abstractmethod
def decide_whether_to_buy_race(self... |
import sqlalchemy
from collections import defaultdict
from contextlib import contextmanager
from sqlalchemy import event
from sqlalchemy.orm import object_session
from sqlalchemy.orm.session import SessionTransaction
def _build_add_func(time, action):
# time = before/after/failed
method = f'_add_{time}_commi... |
import time
from collections import defaultdict
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from socketserver import ThreadingMixIn
from threading import Event, Thread
import aiohttp
import lxml.etree
import pytest
@pytest.fixture(scope="function")
def museum_object(load_museu... |
import re
import math
from datetime import datetime
API_SUFFIX = '/api/json'
NODE_SLAVE = 'hudson.slaves.SlaveComputer'
NODE_LABELS = 'totalExecutors,busyExecutors,\
computer[_class,displayName,offline,numExecutors,monitorData[*]]'
SWAP_SPACE_MONITOR = 'hudson.node_monitors.SwapSpaceMonitor'
SWAP_SPACE_LABELS = [
... |
from tkinter import *
win = Tk()
win.geometry("312x324")
win.resizable(0, 0)
win.title("Calculator")
#funcs
def btn_click(item):
global expression
expression = expression + str(item)
input_text.set(expression)
def btn_clear():
global expression
expression = ""
input_... |
from pathlib import Path
from typing import List, Tuple
import matplotlib.pyplot as plt
import pandas as pd
from pylossmap import BLMData
from pylossmap.lossmap import LossMap
from tqdm.auto import tqdm
def ufo_stable_proton(ufo_meta: pd.DataFrame) -> pd.DataFrame:
ufo_meta = ufo_meta[ufo_meta["beam_mode"] == "S... |
from color_models import RGB, HSV
import gradients as grd
from PIL import Image, ImageDraw
import collections
import random
"""
Collection of misc image generators.
"""
# List of gradient shapes to use for image
shapes = (grd.diamond_gradient, grd.double_diamond_gradient, grd.star_gradient,
grd.even_diamond... |
import cv2
import os
from streamlit_webrtc import VideoTransformerBase
from tensorflow.keras.models import load_model
import numpy as np
from collections import Counter
import streamlit as st
import time
from gtts import gTTS
#loading the pre-trained model file
model = load_model('Final_model.h5')
start_ti... |
import torch
import copy
import torch.nn as nn
import torch.nn.functional as F
from typing import Optional
from.multi_head_attention import MultiheadAttention
'''
class EncoderDecoder(nn.Module):
"""
A standard Encoder-Decoder architecture. Base for this and many
other models.
"""
def __init__(se... |
#
# Copyright (C) 2022 DroneCAN Development Team <uavcan.org>
#
# This software is distributed under the terms of the MIT License.
#
'''
driver for CAN over MAVLink, using MAV_CMD_CAN_FORWARD and CAN_FRAME messages
'''
import os
import sys
import time
import multiprocessing
from logging import getLogger
from .common... |
# REINFORCE algorithm on CartPole env
import os
from random import random, shuffle
import gym
import numpy as np
import torch as T
import torch.nn.functional as F
from torch import nn
from torch import optim
from torch import distributions
from utils import models_dir, eps
class Policy(nn.Module):
'''
Si... |
import requests
import pprint
import os
import re
import tempfile
import numpy as np
import glob
import traceback
import shutil
from tqdm import tqdm
import zipfile
from rafiki.model import dataset_utils
def load(dataset_url, out_train_dataset_path, out_test_dataset_path, out_meta_tsv_path):
'''
Loads and... |
# -*- coding=utf-8 -*-
# import util
# from Segmentation import cws
import summarize.util as util
from summarize.Segmentation import cws
import codecs
import os
import re
def get_default_stopwords_file():
d = os.path.dirname(os.path.realpath(__file__))
return os.path.join(d, 'stopwords_private.txt')
class ... |
from __future__ import print_function
import numpy as np
import bayesiancoresets as bc
import time
import os
import sys
import argparse
sys.path.insert(1, os.path.join(sys.path[0], '../common'))
import results
import plotting
def plot(arguments):
# load only the results that match (avoid high mem usage)
to_mat... |
"""
Various Models.
"""
# Standard Library
import datetime
import random
from typing import Dict, Optional, Union
# Third Party Code
from dateutil.parser import parse
from dateutil.tz import tzutc
class Forecast(object):
"""
A forecast.
"""
identifier: int
def __init__(
self,
fo... |
import random
import torch
from wrapt import ObjectProxy
from omnibelt import Value as ValueWrapper, primitives, InitWall, unspecified_argument
from omnifig import Configurable
from .math import set_seed
# region Attributes
class Statelike:
def state_dict(self, *args, **kwargs):
try:
return ... |
# This python script is responsible for taking images, adding meta-data, and storing them in a shared folder
# https://www.amazon.com/gp/product/B07C1M86V5/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1
# this is the camera module used
import cv2
import numpy as np
import os
import glob
import shutil
# path variable... |
'''
This file is part of the PSL software.
Copyright 2011-2015 University of Maryland
Copyright 2013-2019 The Regents of the University of California
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
... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
#Taking input as grayscale image
def preprocessing(img):
g_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#applying Gaussian blur to remove noise
b_img = cv2.GaussianBlur(g_img, (9, 9), 0)
#applying threshold algorithm for segmetatio... |
import numpy as np
import math
from scipy.stats import skew,kurtosis
import pickle
from sklearn.ensemble import RandomForestClassifier
from core.computefeature import get_resource_contents
MODEL_FILENAME = 'core/resources/models/dataquality/classifier.p'
def get_model() -> RandomForestClassifier:
"""
:rtype: ... |
import json
import random
import secrets
import discord
from discord.ext import commands
from utils.i18n import _, locale
from classes.paginator import Choose
class Trivia(commands.Cog):
def __init__(self, bot):
self.bot = bot
def get_question(self):
with open("assets/questions.json") as f... |
"""CloudnetArray class."""
import math
from typing import Optional, Union
import numpy as np
import numpy.ma as ma
import netCDF4
from cloudnetpy import utils
from cloudnetpy.metadata import MetaData
class CloudnetArray:
"""Stores netCDF4 variables, numpy arrays and scalars as CloudnetArrays.
Args:
v... |
import auxiliary.processthread as process
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
import keywords
import random
import json
import argparse
options = keywords.getarguments()
# mode = 'any'
# mode = "all"
sns.set(style="whitegrid", rc={'figur... |
# test for irpas_classifier
import pandas as pd
import pickle
import tempfile
import time
import warnings
from sklearn.pipeline import Pipeline
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.svm import SVC
from sklearn.preprocessing import Standa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
import logging
import argparse
from collections import deque
import torch
import numpy as np
from .agent import DoubleDQNAgent as Agent, BUFFER_SIZE
from .util import load_environment, UnityEnvironmentWrapper, g... |
"""Text-based canvases.
Colours
-------
Colours can be specified as a single character string, or as a tuple of RGB
values. Tuples of floats are assumed to be in the 0.0-1.0 range, tuples of ints
in the 0-255 range. Strings map to the default terminal colours like this:
====== ====================
String Colour
====... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from urllib.parse import urlparse
import re
import random
import string
import uuid
import simplejson
import unicodedata
from io import StringIO
from io import BytesIO
import urllib.request
from django.core.files.uploadedfile import InMemo... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import datetime
import json
import requests
import tempfile
import zlib
from bs4 import BeautifulSoup
from base64 import b64encode
from urllib2 import quote
from xbmcswift2 import xbmc
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
epoch = datetime.datetime.... |
import os
from .fetch import call_fetch
import sys
from .dataobj import DataObj, Params
from PyQt6.QtWidgets import QApplication, QComboBox, QLabel, QPushButton, QFileDialog, QToolTip, QWidget
from PyQt6.QtGui import QFont
class PIMMSGui(QWidget):
ncol = 0 #number of columns found in the file
labelMap = {"inpu... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# 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... |
##
# Copyright (c) 2005-2017 Apple Inc. All rights reserved.
#
# 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, mod... |
import numpy as np
from matplotlib import pyplot as plt
import math
def f1(a0,a1,x):
return (a0+(a1*x))
def f2(a0,a1,a2,x):
return (a0+(a1*x)+(a2*x*x))
def f3(a0,a1,a2,a3,x):
return (a0+(a1*x)+(a2*x*x)+(a3*x*x*x))
inpo=open('data.txt','r').readlines()
n=len(inpo)
x=[0 for i in range(n)]
y=[0 for i in ran... |
# https://github.com/detkov/Convolution-From-Scratch/blob/main/convolution.py
import numpy as np
from typing import List, Tuple, Union
def add_padding(matrix: np.ndarray,
padding: Tuple[int, int]) -> np.ndarray:
"""Adds padding to the matrix.
Args:
matrix (np.ndarray): Matrix that ne... |
"""Tests for Vanderbilt SPC component."""
import asyncio
import aiohttp
import pytest
from aioresponses import aioresponses
from aioresponses.compat import URL
from pyspcwebgw import SpcWebGateway, Area, Zone
from pyspcwebgw.const import AreaMode, ZoneInput
info = """{"status":"success","data":{"panel":{"cfgtime": ... |
from sklearn import preprocessing
import numpy as np
from .preprocessing import Preprocessor
import os
import pickle
import pandas as pd
def get_X_y(df, target):
X = np.array(df.loc[:, df.columns != target])
y = np.array(df.loc[:, df.columns == target])
return X, y
def sample_df_dataset(df_train_name, d... |
from http import server
from threading import Condition
import base64
import io
import logging
import os
import socketserver
import numpy as np
import picamera
import argparse
import time
import edgetpu.classification.engine
# Parameters
AUTH_USERNAME = os.environ.get('AUTH_USERNAME', 'pi')
AUTH_PASSWORD = os.envir... |
# vim:set tabstop=4 shiftwidth=4 expandtab:
#
# This code has been borrowed from Kupfer
#
# Homepage: http://kaizer.se/wiki/kupfer/
# Credits: Copyright 2007-2011 <NAME> <<EMAIL>>
# Licence: GNU General Public License v3 (or any later version)
"""
Implementation of unescaping and unquoting of the Exec= key in
the... |
import json
from FHIRGroupR5 import GroupR5, CharacteristicCombinationR5, GroupCharacteristicR5, CodeableConcept, Coding, Quantity
from flask import Flask, request
from flask import jsonify
def translate_comparator(comparator):
comparator_translation = {"eq": None,
"lt": "<",
... |
#!/usr/bin/env python3
# *******************************************************
# Copyright (c) VMware, Inc. 2020-2021. All Rights Reserved.
# SPDX-License-Identifier: MIT
# *******************************************************
# *
# * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
# * WARRANTIES OR CO... |
"""Scrape data from PSA and save it to one csv-file for each card."""
import math
import os
import time
from typing import Any, List, Tuple, Union
from bs4 import BeautifulSoup
import pandas as pd
import requests
def scrape() -> None:
"""Parse urls to `scrape_psa_prizes` and store as .csv-files."""
# Read i... |
import numpy as np
import pandas as pd
import unittest
from collections import OrderedDict
from kabuki.generate import gen_rand_data, _add_noise
def gen_func_df(size=100, loc=0, scale=1):
data = np.random.normal(loc=loc, scale=scale, size=size)
return pd.DataFrame(data, columns=['data'])
class TestGenerate... |
"""Matcher compilation."""
from collections.abc import Mapping
from typing import Callable, Dict, Iterable, Tuple, Union
import hamcrest
from hamcrest.core.matcher import Matcher
from preacher.compilation.error import CompilationError, on_key
from preacher.compilation.util.functional import map_compile
from preacher... |
#!env/bin/python
# encoding: utf-8
#
# Copyright (c) 2014 <NAME> <<EMAIL>>
#
# MIT Licence. See http://opensource.org/licenses/MIT
#
# Created on 2014-06-28
#
"""Generate a PNG of the specified character and font."""
from __future__ import unicode_literals
from iconserver import app
from iconserver.util import css_c... |
import numpy as np
#from scipy.optimize import minimize_scalar
#from pysal.cg.sphere import geointerpolate, arcdist
import warnings
def _bin_phydim(dr, dim_name, bin_bound, bin_center, stacked_dim_name):
"""Binning over a physical dimension, weighted by area. Internal function
for taking zonal or meridonal a... |
"""Register models with the admin interface"""
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from ctflex import models
from ctflex import queries
# region Helpers
cl... |
import fnmatch
import json
import os
import subprocess
from fetchai.ledger.crypto import Entity
class Instance(object):
def __init__(self, cmd, root):
self._root = root
self._exit_code = None
self._cmd = cmd
self._log_path = os.path.join(root, 'node.log')
self._logfile = No... |
#!/usr/bin/env python3
import re
TYPE_IMMUNE = 0
TYPE_INFECTION = 1
immune_uid = 1
infection_uid = 1
class Unit(object):
def __init__(
self,
unit_type,
number,
hitpoints_per,
attack_type,
attack_dmg,
initiative,
weaknesses,
immunities,
... |
import os
import site
import venv
import subprocess
import time
from random import choice, randrange
from template_flask.constants import *
def generate_random_secret_key():
key = ''
for i in range(32):
alpha = choice([chr(randrange(65, 91)), chr(randrange(97, 123))])
num = chr(randrange(48, 5... |
from pathlib import Path
from urllib.request import urlretrieve
from collections import defaultdict
from bs4 import BeautifulSoup as Soup
out_dir = "/tmp"
html_file = f"{out_dir}/enchantment_list_pc.html"
HTML_FILE = Path(html_file)
URL = "https://www.digminecraft.com/lists/enchantment_list_pc.php"
class Enchantme... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import asyncio
from typing import Any, Dict, List, Optional, Union
import httpx
from .base import base_url, headers
from .repo_client import org_repos_by_attr
async def repo_labels(owner: str, repo: str) -> List[dict]:
"""List repo labels."""
url = f"{base_url(... |
"""
Description: A very simple wrapper script for ansible-playbook and Invoke-Atomic RedTeam
This script uses Ansible configuration and playbook to remote into a Windows host and run atomic tests
Author: <NAME>
Usage Examples:
Example 1:
$ python3 invoke-art.py
(Note: This runs against all hosts with host... |
import time
import unittest
import logging; logger = logging.getLogger("underworlds")
logging.basicConfig(level=logging.DEBUG)
import underworlds
import underworlds.server
from underworlds.types import Node
PROPAGATION_TIME=0.05 # time to wait for node update notification propagation (in sec)
class TestNodes(unitte... |
# stages.py
# Author: <NAME>
from . import constants as c
from .constants import Point
from .enemy_paths import EnemyPath, Wait
from .sprites import Enemy, Bee, Butterfly, Purple, GalagaSprite
# Some set enemy spawning locations
TOP_LEFT = Point(100, 0)
TOP_RIGHT = Point(c.GAME_SIZE.width - 100, 0)
BOTTOM_LEFT = Poin... |
from __future__ import unicode_literals
import frappe, json
from frappe.utils.nestedset import get_root_of
from frappe.utils import cint
from erpnext.accounts.doctype.pos_profile.pos_profile import get_item_groups
from erpnext.selling.page.point_of_sale.point_of_sale import search_serial_or_batch_or_barcode_number
@f... |
# Listing all the imports
import cv2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import time
import imutils
import math
# image_name = input("Enter the name of image to be processed : ")
image = cv2.imread('4.png')
image = imutils.resize(image, height = 520, width = 400)
# imag... |
from plotly.offline import plot
import plotly.express as px
import pandas as pd
import numpy as np
import os
import io
import urllib
import base64
import matplotlib.pyplot as plt
from Prediction.apps import PredictionConfig
import shap
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams['axes.unicode_minus'] = Fa... |
import logging
import pprint
import asyncio
import discord
from copy import copy
from collections import namedtuple
from discord.errors import Forbidden, NotFound
from discord.ext import commands
from utils import SizedDict
log = logging.getLogger(f'charfred.{__name__}')
Command = namedtuple('Command', 'msg output')
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Test functionality in the process module."""
import logging
import shlex
import subprocess
import pytest
import snafu.process
LOGGER = logging.getLogger("pytest-snafu-process")
def test_get_process_sample_runs_a_command_and_gives_output():
"""Test that get_proc... |
"""Visual Tracker Benchmark.
Code adapted from https://github.com/STVIR/pysot"""
import json
import os
from glob import glob
from tqdm import tqdm
from mxnet.gluon.data import dataset
from gluoncv.utils.filesystem import try_import_cv2
class Video(object):
"""
Abstract video class. get video class information... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
import torch
from os import path
import numpy as np
import ujson as json
from tqdm import tqdm
from torch.utils.data import TensorDataset
from transformers import T5Tokenizer
import nltk
nltk.data.path.append('./nltk_data')
nltk.download('punkt', download_dir='./nltk_data')
def process_file_t5(filename, tokenizer, l... |
# 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. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
from collections import OrderedDic... |
# -*- coding: utf-8 -*-
import time
from typing import Union, Tuple, List
import sys
import click
import cv2
import numpy as np
CANNY_TH1 = 60
CANNY_TH2 = 120
def img_stack(src: Union[Tuple, List], scale: float) -> np.ndarray:
rows: int = len(src)
cols: int = len(src[0])
height: int = src[0][0].shape[0]
width: ... |
import keras
import numpy as np
from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.layers.normalization import BatchNormalization
from keras.layers import Conv2D, Dense, Input, add, Activation, GlobalAveragePooling2D
from keras.initializers import he_normal
fro... |
import os,sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # to import shared utils
import torch
import torch.optim as optim
import torch.nn as nn
import numpy as np
import argparse
import time
import os
import copy
from IPython import embed
from DataLoader import ClevrDataLoader
from m... |
from parmatter import FormatGroup as LineMaker
import pytest
from collections import namedtuple as nt
def test_LineMaker():
assert LineMaker('EmptyLineDef')
def test_basic_LineMaker():
assert LineMaker('BasicLineDef', a='{: >5s}')
@pytest.fixture
def ALineDefClass():
'''For testing the LineMaker ... |
from pprint import pprint
import matplotlib.pyplot as plt
import numpy as np
def get_phonemes():
phonemes_count = {}
f = open('./phonemes.txt', 'r+', encoding='utf-8')
lines = f.readlines()
phonemes = []
for i in range(len(lines)):
tmp = lines[i].strip()
phonemes.append(tmp)
... |
# mapper/sync.py
# Copyright (C) 2005, 2006, 2007 <NAME> <EMAIL>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from sqlalchemy import sql, schema, exceptions
from sqlalchemy import logging
from sqlalchemy.orm import util as mapperuti... |
#!/usr/bin/env python3
import argparse
from MetaLoader import MetaLoader
from pydoc import locate
from jinja2 import Environment, FileSystemLoader, Template
import yaml
import copy
def iterateDependency(imgs):
imageList = {}
while imgs: # an empty list is falsey
imgSwp = []
for img in imgs:
print('loading ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_gp_signals
----------------------------------
Tests for GP signal modules.
"""
import unittest
import numpy as np
from enterprise.pulsar import Pulsar
from enterprise.signals import white_signals, gp_signals, parameter, selections, signal_base
from enterprise... |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../"))
# Making sure that hazelcast directory is in the sys.path so we can import modules from there in the command line.
import argparse
import threading
import logging
import time
import random
from hazelcast.client import HazelcastCl... |
from typing import Any, Callable, List, Union
from datetime import datetime
import inspect
from pathlib import Path
import random
import shutil
import numpy as np
from packaging.version import parse, Version
def set_global_seed(seed: int) -> None:
"""Sets random seed into Numpy and Random, PyTorch and TensorFlow... |
"""
Unit tests for ./preprocessing.py
"""
import numpy as np
from theano import config
import theano
from pylearn2.utils import as_floatX
from pylearn2.datasets import dense_design_matrix
from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix
from pylearn2.datasets.preprocessing import (GlobalContrastNo... |
"""
Copyright (c) 2020 jcollinscastro
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, distribute,... |
#############################################################################
#
#
# Module of BFA introducing and managing Server Class
#
#
#############################################################################
""" This module manages all direct interactions with the BF Servers managed by bfa.
Dependencies:... |
import pandas as pd
from glob import glob
from collections import defaultdict
import csv
import time
import subprocess
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('start_well_index', help='key to identify which wells to do')
args = parser.parse_args()
start_well_index = int(args.start_well_i... |
from django.shortcuts import render_to_response, redirect
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.template import RequestContext
from beanstalk.client import Client, CommandFailed, ConnectionError
from beanstalk.forms import PutForm
from beanstalk.shortcu... |
"""Utilities for the GAN."""
import itertools
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import List, Optional, Union
import tensorflow as tf
import toml
from tensorflow import Tensor
from tensorflow.distribute import Strategy
from tensorflow.python.distribute.... |
import random
import re
import sre_constants
import time
from telethon.tl.types import MessageEntityMention, MessageEntityMentionName, User
from .. import CMD_HELP, tbot
from ..utils import Cbot
from . import get_readable_time
from .mongodb import afk_db as db
options = [
"**{}** is here!, Was afk for {}",
"... |
import os
import sys
import time
import datetime
import argparse
import re
from pathlib import Path
from copy import deepcopy, copy
import traceback
import warnings
import numpy as np
from numba import jit
import pandas as pd
from sklearn.metrics import roc_auc_score, confusion_matrix, mean_squared_error
from .prepro... |
# Written by: <NAME>, @dataoutsider
# Viz: "Good Read", enjoy!
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os
from math import pi, cos, sin, exp, sqrt, atan2
#pd.set_option('display.max_rows', None)
class point:
def __init__(self, index, item, x, y, path = -1, value = ''):
... |
# A script to take all primary-mapped reads in a SAM file and report the splice
# junctions present, including the splice motif. The output format is the same
# as STAR uses:
# 1) chromosome
# 2) first intron base (1-based)
# 3) last intron base (1-based)
# 4) strand
# 0 = undefined
# 1 = +
# 2 = -
... |
from pprint import pprint
import numpy as np
import matplotlib.pyplot as plt
import sklearn
import sklearn.datasets
from init_utils import sigmoid, relu, compute_loss, forward_propagation, backward_propagation
from init_utils import update_parameters, predict, load_dataset, plot_decision_boundary, predict_dec
... |
"""
Script I use to create new Heroku applications with the following features:
- Basic implementation of default Django authentication views
- Dictionary of basic Bootstrap3 templates to choose from
- Heroku apps named PROJECT_NAME and dev-PROJECT_NAME configured in a pipeline
- Each app has its own Postgres datab... |
# Copyright (c) 2011-2016 Rackspace US, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
# Python
import json
# Django
from django.core.urlresolvers import reverse
# AWX
from awx.main.models import * # noqa
from awx.main.tests.base import BaseTest, QueueStartStopTestMixin
__all__ = ['SurveyPasswordRedactedTest']
PASSWORD="<PASSWORD>"
ENCRYPTED_STR='$encrypted$'
TEST_PLAYBOOK = u'''---
- name: test suc... |
"""
2020 Frc Infinite Recharge
Ball Intake Detection
uses contour lines, rough area calculations
width/height ratios, and radius of contours found
in masked image to find ball
"""
import cv2
from processing import colors
from processing import cvfilters
from processing import shape_util
MIN_AREA = 5
BALL_RADIUS = 3.5... |
"""Console script for telemetry."""
import sys
import click
import datetime
import telemetry
import os
@click.group()
def cli():
pass
@click.command()
@click.option(
"--tdir",
default="/test/logs/unprocessed",
help="Path to directory of unprocessed test logs",
)
@click.option("--server", default=Non... |
import pandas as pd
import numpy as np
import logging
import geojson
import os
import geopandas as gpd
from geopy.geocoders import Nominatim
from shapely.geometry import Point, Polygon, MultiPolygon, shape
import shapely.ops
from pyproj import Proj
from bs4 import BeautifulSoup
import requests
import us
logging.ba... |
""" Data transform to generate a folder of .csv files containing correction lists. """
# Python Modules
import os
import re
from typing import Dict
# Third-Party Modules
import inflection
import pandas as pd
import spacy
from tqdm import tqdm
# Local Modules
from digital_manuscript import BnF
nlp = spacy.load('en_co... |
from sklearn.naive_bayes import MultinomialNB, GaussianNB
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.svm import SVC, SVR
from sklearn.neural_network import MLPClassifier, MLPRegressor, multilayer_perceptro... |
import json
from mox3.mox import MoxTestBase, IsA
from six.moves import cPickle
import gevent
from boto.s3.bucket import Bucket
from boto.s3.key import Key
from boto.sqs.queue import Queue
from boto.sqs.message import Message
from slimta.envelope import Envelope
from slimta.cloudstorage.aws import SimpleStorageServ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.