text stringlengths 3.07k 12.6k |
|---|
"""
rbuffer.py
buffer class for input metric monitoring
@author: K.Edeline
"""
import statistics
import collections
import threading
from contextlib import contextmanager
import itertools
from enum import Enum
# max number of collected values
_BUFFER_SIZE=60
def init_rb_dict(keys, type=int, types=None,
... |
import PIL.Image
import numpy as np
import cv2
from matplotlib import pyplot as plt
import pytesseract
import nltk
import sys
from tkinter import *
from tkinter.ttk import *
import _thread
valores = []
class App(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.CreateUI()
... |
import unittest
from collections import defaultdict
from hecuba import config
from hecuba.tools import tokens_partitions, discrete_token_ranges
from .. import test_config
@unittest.skip("Disabled until token partition gets fixed")
class IStorageSplitLocalityTest(unittest.TestCase):
@classmethod
def setUpCl... |
import numpy as np
from keras.optimizers import SGD
from ..agent import Agent
__all__ = [
'ZeroAgent',
]
# tag::branch_struct[]
class Branch:
def __init__(self, prior):
self.prior = prior
self.visit_count = 0
self.total_value = 0.0
# end::branch_struct[]
# tag::node_class_defn[]
cl... |
from flask import Blueprint
from flask import render_template, redirect, url_for, request, session, jsonify
from flask_login import login_required
from app.transaction import bp
from app.employee.model import Employee, EmployeeAdvanceSchema
from app.master.model import Company, Performance, PerformanceSchema
from app.t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import pyrotein as pr
import givens as gv
from loaddata import load_xlsx, label_TMs
import colorsimple as cs
from scipy import spatial
# Reverse the order of all elements from element i to element k in array r.
two_opt_swap = lambda r,i,k: np.concatena... |
import os
import numpy as np
import pickle
import scipy.io as sio
import tensorflow as tf
import tensorflow_addons as tfa
from keras.preprocessing.image import ImageDataGenerator
from models import *
def data_loader(args):
def data_conversion(d_set):
images, labels = d_set
images = images / 255.0
... |
# Copyright (C) 2017-2018 <NAME> <<EMAIL>>
# 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... |
"""
Pollard rho based hash mining algorithm.
"""
from random import randint
from typing import Optional
import time
from blockchain.block import Block
from crypto.pollard_rho import func_g, func_h
from mining.pollard_rho_solution import PRSolution
class SimplePRMiner:
"""A pollard rho miner uses textbook mapping ... |
"""This module handles Planck's law of blackbody radiation.
**Global Variables**
* ``pysynphot.planck.H`` - Planck's constant in CGS units.
* ``pysynphot.planck.HS`` - Planck's constant in SI units.
* ``pysynphot.planck.C`` - Speed of light in SI units.
* ``pysynphot.planck.K`` - Boltzmann constant in SI units.
Thes... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import torch.nn as nn
class filter1():
def plot_filters_single_channel_big(t, title):
# setting the rows and columns
nrows = t.shape[0] * t.shape[2]
ncols = t.shape[1] * t.shape[3]
npimg = np.array(t.cpu().num... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 3 15:21:26 2018
@author: <NAME>
"""
import numpy as np
import time
from threading import Thread
from traits.api import HasTraits, Float, Enum, Array, Instance, Int, String, Bool, Button, List, Tuple, Dict, Directory, HTML
from traitsui.api import ... |
import discord
from discord.ext import commands
from PIL import Image, ImageOps, ImageDraw, ImageFont #Pillow Library for image manipulations
from io import BytesIO
def read_token():
with open("token.txt","r") as f:
lines = f.readlines()
return lines[0].strip()
token = read_token... |
from datetime import datetime, timedelta
from cdhweb.pages.models import RelatedLinkType
from cdhweb.projects.models import GrantType, Project, ProjectRelatedLink, Role
class TestGrantType:
def test_str(self):
grtype = GrantType(grant_type="Sponsored Project")
assert str(grtype) == grtype.grant_t... |
'''
ML Model For Predicting the Face Shape from images.
The Model utilies opencv to preprocess anr remove noise
from images and convert images to numpy arrays. Then
Sklearn svm model is trained to predict images
'''
import sys
from multiprocessing import Pool
from os import listdir, path
try:
import cv2
im... |
import boto3
import sys
import os
from requests import get
from pathlib import Path
from botocore.exceptions import ClientError
client = boto3.client('gamelift')
def create_output_dir(path_dir):
try:
Path(path_dir).mkdir(parents=True, exist_ok=True)
except OSError as e:
print(f"Failed to Crea... |
import numpy as np
import tensorflow as tf
def one_hot(indices, depth, axis=-1, dtype=np.float32):
''' Compute one hot from indices at a specific axis '''
values = np.asarray(indices)
rank = len(values.shape)
depth_range = np.arange(depth)
if axis < 0:
axis = rank + axis + 1
ls = valu... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##################################################
#
# tokenize_xml.py
#
# The XML G2P conversion module expects XML with word
# annotations (specifically, <w> elements from the
# TEI conventions). If this doesn't exist, this module
# attempts to make them. It will assu... |
import numpy as np
from specklepy.exceptions import SpecklepyTypeError, SpecklepyValueError
from specklepy.logging import logger
class Box(object):
def __init__(self, indexes=None):
# Initialize attributes with kwargs
self.x_min = None
self.x_max = None
self.y_min = None
... |
import tensorflow as tf
import numpy as np
from tsms import core
class ResidualError(tf.keras.losses.Loss):
def __init__(self,
loss_type=0,
reduction=tf.keras.losses.Reduction.AUTO,
name='residual_error'):
super(ResidualError, self).__init__(
... |
import asyncio
from datetime import datetime
from pytz import timezone
import discord
from discord.utils import get
import re
def get_streak_icon(icons):
d = datetime.today().month
return {10: icons[0], 12: icons[1]}.get(d, icons[-1]) # gives last icon as default
def format_db_date():
now = datetime.now(... |
#
# Copyright 2020- IBM Inc. All rights reserved
# SPDX-License-Identifier: Apache2.0
#
from flask import Flask, request, escape
from flask.views import MethodView
from PeerContainer import PeerContainer
from NetworkConfig import NetworkConfig
from NetworkConfigQuery import SanityQuery
class NCAResource(MethodView):... |
import discord
from discord.ext import commands
class InsufficentFundsError(Exception):
"""Exception raised when trying to do a transaction with insufficient funds."""
def __init__(self, funds, amount):
amount = amount if amount >= 0 else -amount
message = f"Insufficient funds ({funds:.2f}) f... |
import os
import stat
import sys
import django
from django.core.management import call_command, CommandError
import click
import requests
from .utils import format_help, order_manually
class Config(object):
def __init__(self):
self.url = "https://raw.githubusercontent.com/pinax/pinax/master/projects.js... |
import os
import time
import traceback
from typing import List, Tuple
from datetime import datetime
from requests_html import HTMLSession
from bs4 import BeautifulSoup
from model import Message
from subscriber.csv import CsvSubscriber
from subscriber.telegram import TelegramSubscriber
class Creeper:
... |
import argparse
import collections
import copy
import sys
Location = collections.namedtuple('Location', ['row', 'col'])
class ReachedContradiction(ValueError):
pass
class SquareMap(collections.UserDict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._side_len =... |
# -*- coding: utf-8 -*-
from setuptools import Extension, setup
from sys import platform, maxsize
from numpy import get_include
from distutils.sysconfig import get_config_vars
from glob import glob
import os
base_folder = os.path.dirname(__file__)
def getVersion():
init_path = os.path.join(base_folder, 'assimpcy... |
from app import app
from flask import render_template, request, Response, Flask, flash, redirect, url_for, jsonify, send_from_directory
import json
from random import randrange
import requests
import os
from werkzeug.utils import secure_filename
import base64
from io import BytesIO
from PIL import Image
import numpy ... |
import re
from typing import Dict, Tuple, Union
from gwv.dump import Dump
import gwv.filters as filters
from gwv.helper import GWGroupLazyLoader
from gwv.helper import RE_REGIONS
from gwv.kagedata import KageData
from gwv.validators import Validator
from gwv.validators import ErrorCodes
error_codes = ErrorCodes(
... |
import torch
import torch.nn as nn
import math
class SeparableConv1D(nn.Module):
"""This class implements separable convolution, i.e. a depthwise and a pointwise layer"""
def __init__(self, input_filters, output_filters, kernel_size):
super(SeparableConv1D, self).__init__()
self.depthwise = nn... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Read and write JSON file.
"""
import os.path as op
import sys
import logging
import json
import pandas as pd
from maize.formats.base import must_open, ndigit, prettysize
def main():
import argparse
ps = argparse.ArgumentParser(
formatter_class = ... |
import os
import numpy as np
import tensorflow as tf
import time
import argparse
from tqdm import tqdm
from tf_ncf import neural_mf
import heapq # for retrieval topK
import math
from autodist import AutoDist
from autodist.resource_spec import ResourceSpec
from autodist.strategy import PS, PSLoadBalancing, Partitioned... |
# Import requests (to download the page)
import requests
# Import BeautifulSoup (to parse what we download)
from bs4 import BeautifulSoup
import time
import datetime
import glob
import os
from sendmail import sendmail, testmail
from diffoutputs import diffoutputs
from scrape_bainbridge import scrape_bainbridge
import... |
import random
class AbstractPlayer(object):
"""
Base representation of a player. Should not be used directly, but as part
of TextPlayer(AbstractPlayer), GUIPlayer(AbstractPlayer), etc.
Also gives us a good place to contain the Computer Player logic
"""
def __init__(self, marker):
sel... |
#!/usr/bin/python3
try:
import RPi.GPIO as GPIO
except RuntimeError:
print("Error importing RPi.GPIO! This is probably because you need superuser privileges. You can achieve this by using 'sudo' to run your script")
import os
import time
myfolder = os.path.dirname(os.path.abspath(__file__))
class OutputChan... |
from django.core.mail import EmailMessage
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect
from django.views import View
from main_app.forms import *
from main_app.models import *
class Register(View):
... |
from functools import wraps
from collections import OrderedDict
import os
from gi.repository import Gtk, GObject
from .. import config
from .. import linker
from .. import font_utils
from .. import utils
def _watch_num_active(method):
"""Automatically notify if FontSet.num_active was changed by method."""
... |
""" Utility functions wrapping various HDF5 binaries """
__author__ = '<NAME>, <NAME>'
import os
import re
import shutil
import subprocess
import fcntl
import gevent
from gevent.lock import RLock
from pyon.public import log
try:
import h5py
except ImportError:
h5py = None
def repack(infile_path, outfile_pat... |
#! python
#
# Steps for canvas tests
from behave import given, then
from renderer.canvas import Canvas
from renderer.bolts import Color
@given(u'{var:w} ← canvas({width:d}, {height:d})')
def step_impl(context, var, width, height):
print(u'STEP: Given {} ← canvas({}, {})'.format(var, width, height))
if 'result... |
import warnings
from datetime import datetime
import numpy as np
from .utils import debug
from keras.callbacks import Callback
class MetricOnAll(Callback):
def __init__(
self,
metric_name,
validation_data,
validation_steps,
batch_size,
metric_fn,
pred_fn=l... |
import argparse
import torch
from PIL import Image, ImageOps
import numpy as np
import crnn_torch.utils.keys as keys
# import yaml
import crnn_torch.models.crann as crann
from torch.autograd import Variable
from torch.nn import CTCLoss
import crnn_torch.utils.util1 as util
from crnn_torch.config import crann as opt... |
from urllib.parse import urlencode
from funimation.auth import api_request, login, build_proxy
from funimation.util import get_filename, PROCESS_COUNT
import sys, subprocess, json, os, string, io, pycaption, requests
API_ENDPOINT = 'https://prod-api-funimationnow.dadcdigital.com/api'
def get_episode(session, token, u... |
#!/usr/bin/env python
# encoding: utf-8
import numpy as np
CHAR_TYPE = {
u'กขฃคฆงจชซญฎฏฐฑฒณดตถทธนบปพฟภมยรลวศษสฬอ': 'c',
u'ฅฉผฟฌหฮ': 'n',
u'ะาำิีืึุู': 'v', # า ะ ำ ิ ี ึ ื ั ู ุ
u'เแโใไ': 'w',
u'่้๊๋': 't', # วรรณยุกต์ ่ ้ ๊ ๋
u'์ๆฯ.': 's', # ์ ๆ ฯ .
u'0123456789๑๒๓๔๕๖๗๘๙': 'd',
u'"'... |
"""
Copyright (c) 2015-2016 <NAME>
license http://opensource.org/licenses/MIT
@author: <NAME>
@contact: <EMAIL>
@since: 2016-01-28
@summary: Unit tests for linear regression
"""
import os
import unittest
import numpy as np
import pandas as pd
import pynance as pn
class TestLinReg(unittest.TestCase):
def ndarr... |
"""
Copyright (c) Facebook, Inc. and its affiliates.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
---------
Script to process the w2l logs to tensorboard summary format and store them in
a new directory.
Usage: ten... |
import numpy as np
def normalize_data(x):
m = x.shape[1] # total number of examples
mean = np.mean(x, axis = 0).reshape((1, m))
std = np.std(x, axis = 0).reshape((1, m))
return (x - mean) / std # broadcasting
def initialize_parameters(layers_dims):
parameters = {}
L = l... |
#!python3
'''Printer Stats.
Stores the page count history for printers. Unless the script is provided with start
and end dates, it will default to page count development since yesterday
(Monday-Saturday) or the last week's development (Sundays).
Options:
-s --start <YYYY-MM-DD> Start date
-e --end <YYYY-MM-DD>... |
# -*- coding: utf-8 -*-
from django import forms
from core.models import *
import re
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_lazy as _l
from django.conf import settings
CURRENCIES = (('USD', 'USD'), ('EUR', 'EUR'), ('GBP', 'GBP'), ('AUD', 'AUD'), ('CAD', 'CAD'),... |
import os
import numpy as np
from astropy.table import Table
from astropy import units as u
def kda_info_table(t, glon='', glat='', vlsr='', dvlsr='', kda='',
a='', b='', pa='', factor_dvlsr=1., factor_a=1., factor_b=1.,
offset_pa=0, unit_dvlsr=u.km/u.s, unit_a=u.deg, unit_b=u.de... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Collect the bee_waggle_6 dataset.
See the README file for more information.
Author: <NAME>
License: This file is part of TCPD, see the top-level LICENSE file.
Copyright: 2019, The Alan Turing Institute
"""
import argparse
import hashlib
import json
import math
impo... |
import numpy as np
import time
import tkinter as tk
UNIT = 100
MAZE_HEIGHT = 6
MAZE_WIDTH = 6
ORIGIN = np.array([UNIT / 2, UNIT / 2])
PITS_COORDINATION = [(2, 1), (1, 2), (4, 3), (3, 3), (5, 2), (4, 4)]
DESTINATION_COORDINATION = (5, 3)
def calculate_state_number(coordination):
coordination = ((coordination[0] +... |
#!/bin/env python
# -*- coding: utf8 -*-
import pymysql as pm
def check_and_connect(args):
if 'host' not in args or not args['host']:
raise AttributeError()
if 'user' not in args or not args['user']:
raise AttributeError()
if 'database' not in args or not args['database']:
raise At... |
import logging
import os
import time
import json
import joblib
import pickle
import random
import numpy as np
from collections import OrderedDict, defaultdict
import torch
import torch.nn.functional as F
from torchviz import make_dot
from input import DataInput, DataInputTest
from model import Model
# For reproducib... |
#!/usr/bin/env python
# June 2017
# <NAME>,
# Institute of Arctic Biology
import os
import sys
import argparse
import textwrap
import netCDF4 as nc
import numpy as np
def modified_attribute_string(msg=''):
'''
Returns a string to be included as a netCDF attribute named "modified".
The string will contain t... |
import argparse
import json, os
import jsonlist
from functools import reduce
def clean_claim(claim_text_lis):
"""
Returns a list of claims with metadata removed.
Don't call multiple times, on same lis.
"""
clean_claims = []
for claim_text in claim_text_lis:
if claim_text is not None:
... |
"""
this is the main file that is involved with
"""
import re
import chess
import numpy as np
BOARD_POS = ['A1', 'B1', 'C1', 'D1', 'E1', 'F1', 'G1', 'H1', 'A2', 'B2', 'C2', 'D2', 'E2',
'F2', 'G2', 'H2', 'A3', 'B3', 'C3', 'D3', 'E3', 'F3', 'G3', 'H3', 'A4', 'B4', 'C4', 'D4',
'E4', 'F4', 'G4',... |
from datetime import datetime
from unittest.mock import Mock
import json
import mongomock
import pymongo
from src.models.channel import Channel
TEST_MONGO_SERVER = ("localhost", 27017)
TEST_MONGO_SERVERS = (TEST_MONGO_SERVER,)
def create_sample_channel():
return {
"id": "UC1opHUrw8rvnsadT-iGp7Cg",
... |
"""Replay buffer implemantaions for DQN"""
from collections import deque
from collections import namedtuple
from random import sample as randsample
import numpy as np
import torch
from blg604ehw2.dqn.sumtree import SumTree
from numba import jitclass, int64, float64, bool_, jit, njit
from numba.numpy_support import from... |
# takeonreport.py
# Copyright 2008 <NAME>
# Licence: See LICENCE (BSD licence)
"""Generate a report comparing results with schedule.
"""
import collections
from . import constants as cc
from . import convertresults
class TakeonReport(convertresults.ConvertResults):
"""Game results extracted from data take-on ... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
"""
Created on Thu Oct 18 09:55:11 2018
@author: yansl
"""
import os
import cv2
import numpy as np
from skimage import morphology
import shutil
def file_operation(folder_name):
#creating a folder to save the results
pwd = os.getcwd()
pwd = p... |
import pygame
import sys
import colors
pygame.init()
class Text(pygame.sprite.Sprite):
"""
A Text class for pygame. Is a subclass of pygame.sprite.Sprite class and can be used with pygame.sprite.Group or
other sprite group classes.
"""
def __init__(self, text: str, pos=(0, 0), origin='center', co... |
# Copyright (C) 2020 <NAME>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, soft... |
"""
Utilities and base implementation of Connectors that allow a document to access a source native file or
stream upon which the document is based or derived.
"""
import fnmatch
import inspect
import io
import logging
import mimetypes
import os
import tempfile
import urllib
from os.path import join
from typing import... |
from datetime import datetime
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.exceptions import PermissionDenied
from djang... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import functools
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.optim as optim
import models
def update_argparser(parser):
models.update_argparser(parser)
args,... |
#!/usr/bin/env python3
###
# ============LICENSE_START=======================================================
# ORAN SMO PACKAGE - PYTHONSDK TESTS
# ================================================================================
# Copyright (C) 2021-2022 AT&T Intellectual Property. All rights
# ... |
import numpy as np
from pygef import geo
import pygef.utils as utils
# TODO: at test coverage to travis.yaml Nice to have. :)
def excess_pore_pressure_ratio(df):
"""
Assign the excess pore pressure ratio, if the water pressure u2 is defined. Else, raise ERROR.
:param df: (DataFrame)
:return: (DataF... |
# uncompyle6 version 3.2.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
# Embedded file name: direct.controls.InputState
from direct.directnotify import DirectNotifyGlobal
from direct.showbase import DirectObject
class InputState... |
import base64
import os
import random
import re
import socket
import time
import logging
import datetime
def get_ip():
myname = socket.getfqdn(socket.gethostname())
# 获取本机ip
myaddr = socket.gethostbyname(myname)
# myaddr = '127.0.0.1'
return myaddr
class Util():
@staticmethod
def slice_... |
import discord
from discord.ext import commands
from Tools.utils import getConfig, getGuildPrefix, updateConfig
from datetime import datetime
from Tools.logMessage import sendLogMessage
class AntiRaid(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
... |
import os
import sys
import tempfile
import datetime
import warnings
import traceback
from collections import namedtuple
import jsonpickle
class Configuration:
TRANSACTION_STORAGE_DIRECTORY = '/tmp/'
TRANSACTION_PREFIX = 'transaction'
CLEANUP = True
CHATTY_EXCEPTIONS = True
class States:
PEN... |
import numpy as np
import glob
import os
import re
import matplotlib.pyplot as plt
from pylab import subplots_adjust
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
color_dictionary = {
0: "#1F618D", 1: "#F322CD", 2: "#E74C3C", 3: "#7FB3D5", 4: "#22DAF3",
5: "#5B2C6F", 6: ... |
# -*- coding: utf-8 -*-
from .metrics_util import (
validate_boolean_type,
validate_non_empty,
validate_non_negative,
validate_positive,
validate_string_type,
)
class ConfigOptions(object):
"""
Config options
"""
url = "URL"
# Http header options
dimension_tags = "Dimensi... |
import datetime
import logging
from PyQt6.QtCore import *
from PyQt6.QtWidgets import *
DATETODAY = datetime.date.today()
logger = logging.getLogger(__name__)
def convert_height_metric(height):
"""Converts user's height from Imperial to metric and returns a float"""
height_metric = height * 2.54
return... |
#!/usr/bin/env python3
"""Helper script to automate activation/licensing for Burp Suite"""
import argparse
import filecmp
import os
import pexpect.popen_spawn
import shutil
import signal
import sys
import tempfile
import time
import urllib.request
from defusedxml.ElementTree import parse
def check_burp_status(prefs_... |
#!/usr/bin/env python
import argparse
import subprocess
import sys
import os
import json
import boto3
import botocore
import sagemaker
from botocore.exceptions import ClientError
from sagemaker import ModelPackage
from pathlib import Path
import logging
import traceback
logging.basicConfig(level=logging.INFO)
LOGGER =... |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
class Tests:
hair_creation = (
"Hair Entity successfully created",
"P0: Hair Entity failed ... |
from plexapi.server import PlexServer
import os
from dotenv import load_dotenv
import sys
import textwrap
from tmdbapis import TMDbAPIs
import requests
import pathlib
from timeit import default_timer as timer
import time
# import tvdb_v4_official
start = timer()
load_dotenv()
def boolean_string(s):
if s not in ... |
# -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import Group
from settings import GROUP_ROLES, URL_DELIMITER
class GroupNotDefined(Exception):
"""You must assing incident_notification_group in admin panell."""
pass
... |
"""
Calculate persistence images from the persistence diagrams
"""
import pickle
from typing import (Any, Set, List, Tuple, Dict, Optional, TextIO)
import os
import numpy as np
import matplotlib.pyplot as plt
import dionysus as d
import pandas as pd
from tqdm import tqdm
from mof_tda import MOF_TDA_PATH
from multiproce... |
'''
Shuffled Camera Feed Puzzle
===========================
This demonstrates using Scatter widgets with a live camera.
You should see a shuffled grid of rectangles that make up the
camera feed. You can drag the squares around to see the
unscrambled camera feed or double click to scramble the grid
again.
'''
import c... |
# input-encoding: latin-1
from __future__ import print_function
# windows ?
import sys
iswin = sys.platform == "win32"
# make sure we only log errors and not info/debug ...
from logging import basicConfig
from logging import CRITICAL, ERROR, WARNING, INFO, DEBUG
basicConfig(level=21)
import config
from env import (Q... |
#!/usr/bin/python
#
# <NAME> <<EMAIL>> - 19/09/2018
#
import os
def object_path(entity, obj_type, global_base, obj_type_base, remote=True):
"""
Build the path of an object (key, certificate, chain, ...)
"""
if obj_type == 'key':
entity_base_key = 'path'
object_base_key = 'path'
... |
"""
-*- test-case-name: PyHouse.Modules.Lighting.test.test_lighting_controllers -*-
@name: PyHouse/src/Modules/Lighting/lighting_controllers.py
@author: <NAME>
@contact: <EMAIL>
@copyright: (c) 2010-2016 by <NAME>
@note: Created on Apr 2, 2010
@license: MIT License
@summary: Handle the home lighting... |
import os
import pg_engine as pge
from formats import conf
from pg_engine import Sprite
from pg_engine.sprite.Sprite import Frame, Tag
import pygame as pg
from formats.filesystem import NintendoDSRom
from formats.graphics.ani import AniSprite
from formats.graphics.bg import BGImage
from formats.nftr import NFTR
import... |
import matplotlib.pyplot as plt
import numpy as np
"""
Compute train running time based on the following assumptions:
- point dynamic
- constant acceleration / braking
- given maximum speed (imposed by rolling stock or rail curve)
"""
def compute_v_star(d, a, b):
return a * (2 * d / (a * (1 + a / b)))**0.5
def... |
#!/usr/bin/env python3
import lxml.etree
from os import listdir
from os.path import isfile, join
import re, sys, html
import argparse
def printVerbose(string):
if printVerbose._verbose:
print(string)
printVerbose._verbose = False
def makePrintVerbose(verbose):
printVerbose._verbose = verbose
def getHeaderName(ba... |
"""Experimental script to try out loading HydroBASINS data with shapefile"""
import sys
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import shapefile
HYDROBASINS_DIR = '/home/markmuetz/mirrors/jasmin/cosmic/mmuetz/HydroBASINS/as'
def load_shapefile(level):
return shapefile.Read... |
#!/usr/bin/env python
# coding: utf-8
# In[11]:
import sys, os
import pandas as pd
import MySQLdb
from datetime import date
from datetime import datetime
from datetime import timedelta
from datetime import *
from dateutil.relativedelta import *
import numpy as np
from fn import *
livedb = os.getcwd() + "\\robi_live... |
import math
from tqdm import tqdm
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder, QuantileTransformer
from sklearn.neighbors import NearestNeighbors
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
... |
#!/usr/bin/env python
import os, sys
import json
import fnmatch, re
from collections import namedtuple
from ..helper import slugify
from ..exceptions import *
Key = namedtuple("Key", ["name","version"])
class Repo:
"""
Class to track each repo
"""
def __init__(self, username, reponame):
self.... |
# Author: <NAME> <<EMAIL>>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard 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,... |
from django.utils.decorators import method_decorator
from drf_yasg.utils import swagger_auto_schema
from rest_framework.decorators import action, api_view, permission_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import... |
import collections
import numpy as np
from scipy.sparse import csc_matrix
from .GGPrnd import GGPrnd
def GGPgraphrnd(alpha, sigma, tau, T=0):
"""
Generate (sample) a random graph.
:param alpha: positive scalar
:param sigma: real in (-inf, 1)
:param tau: positive scalar
:param T: truncation th... |
"""
PyDataVizDay
A python implementation of the Data Viz Day visualization built from the Kaggle
IMDB 5000 Movie Dataset.
"""
import os
import io
import base64 as b64
from collections import Counter
from flask import Flask
from flask import request, render_template, make_response, jsonify, Blueprint, url_for
from ... |
import bpy
import os
import xml.etree.ElementTree as ET
def get_rgba_value(param_node):
r = float(param_node[0][0].text)
g = float(param_node[0][1].text)
b = float(param_node[0][2].text)
a = float(param_node[0][3].text)
return (r, g, b, a)
def get_float_value(param_node):
return float(param_no... |
import cv2
import numpy as np
import apriltag
import tagUtils as tud
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
class Multcamdet(object):
def __init__(self,n,debug = False):
self.n = n
self.videocaptures = []
self.videowrite = []
self.frames = []
... |
import soloact
from soloact import write_annotation, write_chords, augment_data, dataset, joint_model, model_directory, multi_class_model
import os
import glob
import argparse
from pprint import pprint
from argparse import RawTextHelpFormatter
paths = soloact.make_source_paths(os.getcwd())
pitch_classes = list(paths.g... |
"""
created by satra9chat
www.github.com/satra9chat
<EMAIL>
"""
from googlesearch import search
import requests as rq
import json
from multiprocessing.dummy import Pool as ThreadPool
def wikipedia_searcher(title, query):
"""
This function performs web-scraping on wikipedia. It finds the subcategories of the ... |
""" Translation main class """
from __future__ import unicode_literals, print_function
import torch
from onmt.inputters.text_dataset import TextMultiField
class TranslationBuilder(object):
"""
Build a word-based translation from the batch output
of translator and the underlying dictionaries.
Replace... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.