content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 23 13:42:12 2020
@author: mehrdad
"""
import pandas as pd
import tslib.mining
class PersonDays():
def __init__(self, trips, compute_personday_values=False):
self.trips = trips
# init our person-day dataframe:
... |
#!/usr/bin/env python
#########################################################################################
#
# Vesselness filter
# hessian computation inpired from: https://code.google.com/p/pycvf/source/browse/pycvf/trunk/pycvf/nodes/image/hessian.py?spec=svn22&r=22
#
# -------------------------------------------... |
# -*- coding: utf-8 -*-
import asyncio
import json
import logging
import sys
from pastepwn.util import Request
from pastepwn.util import TemplatingEngine
from .basicaction import BasicAction
websockets_available = True
try:
import websockets
except ImportError:
websockets = None
websockets_available = Fal... |
from flask import Flask, Blueprint
from flask_redis import FlaskRedis
from flask_restplus import Api
app = Flask(__name__)
app_routes = Blueprint('v1', __name__)
api = Api(app_routes, prefix='/v1', validate=True, title='Swing By Server', description='Backend for Swing By event system')
red = FlaskRedis(app, decode_res... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import logging
from motor import MotorClient
import tornado.wsgi
import tornado.web
from tornado.options import define, options
from .const import CWD, LOG_NAME
from .views import TopicTweets
from .utils import setup_log, BaseHandler
define('config', default=o... |
"""
mb_24x256_512_example.py
Example MicroPython script for Microchip 24x256 and 24x512 I2C EEPROM driver.
Tested with Raspberry Pi Pico (RP2040), should work with other MP-capable microcontrollers
with hardware or software I2C.
Author: mark@marksbench.com
Version: 0.1, 2021-06-04
**NOTE(1): There is n... |
import os
import sys
import logging
import subprocess
import numpy as np
import cv2
import time
import json
import uuid
from typing import Any, Callable
from datetime import datetime
from capture.frame_preprocess import frame_resize
from capture.frame_save import FrameSave
from store.sql_insert import InsertInference
f... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright 2015 Raritan Inc. All rights reserved.
# To show help use the '-h' option: luaservice_client -h
import sys, os, time, signal
# If your pdu-python-api has a different location then update 'syst.path.append(..)'.
sys.path.ap... |
import json
from Message.Message import Message
from Message.ByteMessage import ByteMessage
class JsonMessage(ByteMessage):
CONTENT_TYPE = 'text/json'
def __init__(self, content, custom_headers=None, encoding='utf-8'):
super().__init__(content, custom_headers, self.CONTENT_TYPE, encoding)
@stat... |
# scratchpad program to make a QR code from scratch.
#
# this looks really bad because I'm trying to keep it as simple as possible
# for when I port this to ARM assembly.
#
# reference:
# - https://www.thonky.com/qr-code-tutorial/
# - Reed Solomon Encoding (Computerphile) https://www.youtube.com/watch?v=fBRMaEAFLE0... |
import importlib
import inspect
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch
def delegate(*decorator_args, **decorator_kwargs):
def decorator(func):
@wraps(func)
def func_wrapper(*args, **kwargs):
return func(*args, **kwargs)
... |
import os
import string
import subprocess
import sys
from typing import Text, List, Tuple, Dict, Set, NoReturn
import jinja2
from loguru import logger
from sentry_sdk import capture_exception
from rrtv_httprunner import exceptions, __version__
from rrtv_httprunner.compat import (
ensure_testcase_v3_api,
ensur... |
# Copyright (c) 2015 Cisco Systems
#
# 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 writ... |
# Adapted from:
# [1] "amazon-archives/ai-driven-social-media-dashboard", GitHub, 2020. [Online]. Available: https://github.com/amazon-archives/ai-driven-social-media-dashboard. [Accessed: 21- May- 2020].
from __future__ import print_function
import json
import boto3
import time
import os
from botocore.vendored import... |
import numpy as np
from numba import njit, prange
from numba import types
from numba.typed import Dict
from plantcelltype.utils.utils import cantor_sym_pair
def get_neighborhood_structure(x=(1, 1, 1)):
"""
Build the neighborhood structure array used in the rag generation
"""
structure = []
for i ... |
class sparse_matrix(object):
"""docstring for sparse_matrix
use less data to save sparse matrix
"""
def __init__(self):
super(sparse_matrix, self).__init__()
self.original_rows
self.original_cols
self.points = [] # point = x,y,value
|
#!/usr/bin/python3
from ..rigidbody import BodyCoordinate
from .DOF import DOF
class Joint:
id_counter = 0
def __init__(
self,
body_in_coord,
body_out_coord,
dof=None,
name=None,
):
"""
A Joint a common location for two bodies to interact, and how t... |
# -*- coding: utf-8 -*-
from pyfr.backends.base import BaseBackend, blockmats
from pyfr.template import DottedTemplateLookup
class CUDABackend(BaseBackend):
name = 'cuda'
def __init__(self, cfg):
super(CUDABackend, self).__init__(cfg)
# Create a CUDA context
from pycuda.autoinit imp... |
from datamart.materializers.materializer_base import MaterializerBase
import pandas as pd
import datetime
import csv
import requests
import typing
import os
DEFAULT_LOCATIONS = [
"new york",
"los angeles",
"chicago",
"Houston",
"Philadelphia"
]
DEFAULT_DATE_RANGE = 7
DEFAULT_DATA_TYPE = "TAVG"
DEFA... |
# Image Classification
# Uses keras 1.2
# Import libraries
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.layers import Dropout
from keras.callbacks import EarlyStopping, ModelCh... |
# ObjectID: 1000006
# ParentID: 2110001
# Character field ID when accessed: 261000000
# Object Position X: 1333
# Object Position Y: 185
|
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 30 12:21:38 2018
@author: Administrator
"""
import time
import numpy as np
import scipy, scipy.constants
import matplotlib.pyplot as plt
import qcodes as qc
from qcodes import ChannelList, Parameter
from qcodes.dataset.measurements import Measurement
from qcodes.dataset... |
from collections import Counter
class SoupStats():
def __init__(self, soup):
self.soup = soup
self.counter = Counter()
for child in soup.findChildren():
for atts in child.attrs.items():
k,v = atts
self.counter[atts] += 1
se... |
import os
# # this installs the right pip and dependencies for the fresh python
os.system('conda install ipython pip')
os.system('conda install python=3.7')
# maskrcnn_benchmark and coco api dependencies
os.system('pip install ninja yacs cython matplotlib tqdm opencv-python h5py ')
#install utils
os.system('pip insta... |
import json
import requests
import time
import logging
import sys
class TsiDataQuerier():
'''
This class contains the functions to query data from Azure TSI
'''
def __init__(self, environment_variables = {}):
self.storType_list = ['warmstore', 'coldstore']
self.environment_fqdn = enviro... |
# maratona.h
from zipfile import ZipFile, ZIP_DEFLATED
import getpass
import os
import struct
# typedef struct {
# int id;
# char login[8];
# char senha[21];
# char nome[31];
# } time;
# typedef struct {
# int dia;
# int mes;
# int ano;
# } data;
# typedef struct {
# int id;
# i... |
from django import template
from django.db.models import Max
from courseSelect.models import Curriculum, Selection, SelectControl
from basicInfo.models import course as Course, teach as Teach, teacher as Teacher, takeup as Takeup, room as Room, time as Time, student as Student, discipline as Discipline, major as Major
... |
# Write a function to find the longest common prefix string amongst an array of strings.
# If there is no common prefix, return an empty string "".
#
# Example:
# Input: strs = ["flower","flow","flight"]
# Output: "fl"
#
# Constraints:
# 0 <= strs.length <= 200
# 0 <= strs[i].length <= 200
# strs[i] consists of only lo... |
"""
@file
@brief Various functions to install some application such as `pandoc <http://johnmacfarlane.net/pandoc/>`_.
"""
from __future__ import print_function
import os
import sys
from ..installhelper.install_memoize import install_memoize2
from ..installhelper.internet_settings import default_user_agent
if sys.versi... |
import torch
import numpy as np
from picket.encoder.example_encoder import AttrEmbedding
import logging
import time
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class LookUpModelSimple(torch.nn.Module):
def __init__(self, dataset, env, attribute_info=None):
super(LookUpModelSimple, s... |
from IProcess import IProcess, EDataType
from PIL import Image
import pywt
import pywt.data
class StationaryWaveletPic(IProcess):
def __init__(self, waveletMode='bior1.3', level=1):
IProcess.__init__(self)
# See: https://pywavelets.readthedocs.io/en/latest/regression/wavelet.html
waveletFamilyValidated = Fa... |
import pygame
import pyBaba
import config
import sys
import sprites
icon_images = {pyBaba.ObjectType.ICON_BABA: 'BABA',
pyBaba.ObjectType.ICON_FLAG: 'FLAG',
pyBaba.ObjectType.ICON_WALL: 'WALL',
pyBaba.ObjectType.ICON_ROCK: 'ROCK',
pyBaba.ObjectType.ICON_TILE:... |
# gunicorn.py
import multiprocessing
import os
if os.environ.get('MODE') == 'dev':
reload = True
bind = '0.0.0.0:8080'
timeout = 300
#errorlog='/log/api.log'
loglevel=os.environ.get("LOG_LEVEL","INFO").lower()
#capture_output=True
workers = multiprocessing.cpu_count() * 2 + 1
|
import typing
from ParadoxTrading.Engine import StrategyAbstract, MarketEvent, \
SettlementEvent
from ParadoxTrading.Fetch.ChineseFutures.FetchBase import FetchBase
class MarketEventMgr:
def __init__(self, _fetcher: FetchBase, *args):
"""
manage market event, send data_dict when all
a... |
import pathlib
import setuptools
NAME = "cvxpy_leximin"
URL = "https://github.com/erelsgl/" + NAME
HERE = pathlib.Path(__file__).parent
print(f"\nHERE = {HERE.absolute()}\n")
README = (HERE / "README.md").read_text()
REQUIRES = (HERE / "requirements.txt").read_text().strip().split("\n")
REQUIRES = [lin.strip() for lin... |
# The MIT License (MIT)
#
# Copyright (c) 2018 Niklas Rosenstein
#
# 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,... |
from pathlib import Path
import numpy as np
import argparse
import torch
import torchaudio
from tqdm import tqdm
def generate(args):
args.out_dir.mkdir(exist_ok=True, parents=True)
print("Loading checkpoint")
hifigan = torch.hub.load("bshall/hifigan:main", args.model_name).cuda()
print(f"Generating ... |
import cv2
import mediapipe as mp
import time
class FaceMeshDetector():
def __init__(self, static_mode=False, maxFaces=2, minDetectionCon=0.5, MinTrackCon=0.5):
self.static_mode = static_mode
self.maxFaces = maxFaces
self.minDetectionCon = minDetectionCon
self.MinTrackCon = MinTrac... |
import html
from typing import Optional
from telegram import Chat, Message, User, ParseMode
from telegram.error import BadRequest
from telegram.ext import CommandHandler, Filters
from telegram.utils.helpers import mention_html
from YorForger import dispatcher, LOGGER
from YorForger.modules.disable import DisableAble... |
"""
Dan Thayer - playing with python and indicators in pursuit of profit
Oct 2021
"""
import pandas as pd
import os
from ta.others import daily_return
from ta.utils import dropna
import plots
import matplotlib.pyplot as plt
def runner(path):
print("reading data from: ", path)
df = pd.read_csv(path)
df = ... |
"""test_ridge.py: tests for ridge module."""
from functools import wraps
import unittest
from sklearn.datasets import load_linnerud
from sklearn.linear_model import Ridge, RidgeCV
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import GroupKFold, KFold
import torch
import torch.nn.function... |
from keydb import *
import time
if __name__ == "__main__":
pool = ConnectionPool(host='localhost', password='password')
db = KeyDB(connection_pool=pool)
db.set("A", 10)
db.sadd("SS", 11, 12, 13, 14, 15)
print(f'Set size: {db.scard("SS")}')
db.expiremember("SS", 12, 5)
time.sleep(6)
... |
"""SRGB Linear color class."""
from ..spaces import RE_DEFAULT_MATCH
from .srgb import SRGB
import re
from ..util import MutableVector
from typing import cast
from ..import util
RGB_TO_XYZ = [
[0.4123907992659593, 0.357584339383878, 0.18048078840183432],
[0.21263900587151024, 0.715168678767756, 0.072192315360... |
# support num action as input
# for eps greedy: generate scores array based on input, output pdf
# soft max: straight forward
# bag: generate scores tensor 2-dimensional: k-actions, m-models
|
import arcade
from arcade import FACE_RIGHT, FACE_DOWN, FACE_UP, FACE_LEFT
class AnimatedWalkingSprite(arcade.Sprite):
def __init__(self, scale: float = 1,
image_x: float = 0, image_y: float = 0,
center_x: float = 0, center_y: float = 0, *,
stand_left, stand_righ... |
"""
Author: Abas Farah
This is code for breadthFirstSearch Method on a graph (AdjecencyMatrix)
Code can be easily adaptable on other graph implementations
Runtime for BreadthFirstSearch:
O(E) running time
O(V + E) to list unreachable values from v (starting vertex)
"""
import sys
impo... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
######################## Part3: Journal Record #############################
############### General Journal Record class ###############################
class Jrecord(object):
'''Basic journal record information'''
def __init__(self):
... |
"""
File : __init__.py
Author : Daljeet Singh Chhabra
Date Created : 03-07-2020
Date Modified : 03-07-2020
"""
|
"""
MIT License
Copyright (c) 2021 UltronRoBo
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, di... |
# Copyright (c) 2020, 2022, Oracle and/or its affiliates.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2.0,
# as published by the Free Software Foundation.
#
# This program is also distributed with certain software (including
# ... |
# Libraries
import pandas as pd
import numpy as np
import sklearn
import nltk
from nltk.corpus import stopwords
# List of stopwords
stopw = stopwords.words("english")
l1 = [')','(',',','.',';',':','/','?','{','}','[',']','&','!','@','#','$','%','^','*']
for i in l1:stopw.append(i)
stopw
def remove_stopwords(filepath... |
from contextlib import contextmanager
from hashlib import sha256
from psycopg2 import connect
from sm.engine.config import SMConfig
LOCK_KEY = 894951
class DBMutex:
"""
Database-backed mutex for preventing multiple threads/processes from accessing the same
shared resource simultaneously. Resources are ... |
import argparse
import snowflake.connector
from snowflake.connector.errors import DatabaseError, ForbiddenError, ProgrammingError
import sys
EXIT_CODE_UNKNOWN_ERROR = 3
EXIT_CODE_INVALID_CREDENTIALS = 200
EXIT_CODE_INVALID_ACCOUNT = 201
EXIT_CODE_INVALID_WAREHOUSE = 202
EXIT_CODE_INVALID_DATABASE = 203
EXIT_CODE_INVAL... |
from django.contrib import admin
from django.contrib.contenttypes.admin import GenericTabularInline
from . import models
@admin.register(models.Organization)
class OrganizationAdmin(admin.ModelAdmin):
pass
@admin.register(models.TaxRate)
class TaxRateAdmin(admin.ModelAdmin):
pass
class PaymentInline(Gene... |
"""
Django settings for zuessite project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
i... |
import fisherman
from pond import renderPondSurface, checkForFish, castLine
from random import randint
# array of ints to represent fish and boots in each cell of the pond grid
pondLife = []
# array of bools to represent which cells have already been visited
# this data is displayed to the player each turn (hides ... |
# TODO: we should combine this logic with the settings service
DB_LOCATION = "uttt_database.db"
USING_OSX = False
|
from lightgbm_ray.main import RayParams, train, predict
from xgboost_ray.matrix import RayDMatrix, RayDeviceQuantileDMatrix,\
RayFileType, RayShardingMode, \
Data, combine_data
from lightgbm_ray.sklearn import RayLGBMClassifier, RayLGBMRegressor
__version__ = "0.1.4"
__all__ = [
"__version__", "RayParams... |
import unittest
from app.models import User, BLOG
from app import db
class BloghModelTest(unittest.TestCase):
def setUp(self):
self.user_francis = User(username = 'Francis',password = 'Password')
self.new_blog = BLOG(m_blog_title='Test',m_blog_content='Test',m_blog_posted_on='2019-02-18',m_user_id... |
from flask import g
from flask_wtf import Form
from wtforms import TextField, TextAreaField, IntegerField
from wtforms.validators import DataRequired
from wtforms.widgets import HiddenInput
from .application import db
from .models import Group, Membership, ROLE_GROUP_LEADER
from .exceptions import GroupFullException
... |
#!/usr/bin/env python
# This command line utility gives you a quick and easy TAR.csv file.
# By default it saves the file into the current directory, but
# you can specify the output directory as an optional argument.
#
# Username and password will be read from jamberry.ini.
#
# After the file is saved, it is launched... |
"""HGNC."""
import re
import sys
import json
import logging
import numpy as np
import pandas as pd
from tqdm import tqdm
from typing import Dict
from pyorient import OrientDB
from collections import namedtuple
from ebel.tools import get_file_path
from ebel.manager.orientdb.constants import HGNC
from ebel.manager.orie... |
from django.contrib import admin
from django.urls import reverse
from django.utils.safestring import mark_safe
from .models import (
Pais,
Estado,
Ciudad,
)
class EstadoOnPaisTabularAdmin(admin.TabularInline):
model = Estado
fields = ['nombre', 'edit']
readonly_fields = ['edit']
extra = 0... |
from cryptography.fernet import Fernet
KEY = b'pRmgMa8T0INjEAfksaq2aafzoZXEuwKI7wDe4c1F8AY='
def encrypted_password(password):
'''Takes an unencrypted password and encrypts it'''
cipher_suite = Fernet(KEY)
encrypted_password = cipher_suite.encrypt(password.encode('utf-8'))
return encrypted_password
... |
# coding: utf-8
import os
import sys
import dotbot
from subprocess import check_output, call
sys.path.append(
os.path.join(os.path.dirname(os.path.realpath(__file__)), "lib", "whichcraft")
)
from whichcraft import which
class VSCode(dotbot.Plugin):
DIRECTIVE_VSCODE = "vscode"
DIRECTIVE_VSCODE_FILE = "... |
#!/usr/bin/env python3
from hicprediction.createTrainingSet import createTrainSet
from hicprediction.configurations import *
import json
@allset_options
@click.command()
def createAllSets(chromosomes, basefile, centromeresfile, windowsize,
datasetoutputdirectory, setparamsfile):
for setting in ... |
#!/usr/bin/env python
import sys
from PySide2.QtWidgets import QApplication, QWidget
# import QtGui and QtCore only so that they are also frozen
import PySide2.QtGui
import PySide2.QtCore
def main():
app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle("Simple")
window.show()
re... |
#
# main.py
# asdfasdf
#
# Created by Bill Bumgarner on 11/24/07.
# Copyright __MyCompanyName__ 2007. All rights reserved.
#
#import modules required by application
import objc
try:
import Foundation
except:
print "handled foundation exception"
try:
import AppKit
except:
print "handled appkit exce... |
class Row(object):
pass
|
"""
Sample script of collada.
See documentation in:
https://pycollada.readthedocs.io/en/latest/creating.html
"""
from collada import Collada, material, geometry, source, scene
import numpy
def main():
"""
Generate .dae file.
"""
mesh = Collada()
effect = material.Effect(
'effect0', [], ... |
import random
from uuid import uuid4
from robottelo.config import settings
class ContainerError(Exception):
"""Exception raised for failed container management operations."""
class DockerContainer:
"""
Gather information needed to spin up a Docker-based container.
Attributes:
image (ini... |
#############################################################################
##
# This file is part of Taurus
##
# http://taurus-scada.org
##
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
# Taurus is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General P... |
#### variable type number ###
a = 1
b = 2.5
c = 3.14j
print(type(a))
print(type(b))
print(type(c))
# a = hex(11)
# print(a)
### Arithmetic operatos
print(a+b)
print(a-b)
print(b/2)
print(2%2)
print(2**2)
|
import sys
import os
sys.path.append(os.getcwd())
from training_structures.MVAE_mixed import train_MVAE,test_MVAE
from fusions.MVAE import ProductOfExperts
from unimodals.common_models import MLP
from unimodals.MVAE import LeNetEncoder,DeLeNet
from torch import nn
import torch
from objective_functions.recon import elbo... |
"""
This class implements a pair of embedding spaces and their connection.
It utilizes the code of Alvarez-Melis & Jaakkola (2018) in several places.
The original implementation can be found on https://github.com/dmelis/otalign
I mark all adopted code as clearly as possible.
"""
from typing import List, Dict, Tuple, A... |
# -*- coding: utf-8 -*-
"""
This script generates different kind of graphs outputs using reference shapes
and demo shapes recovered from log files
@author: ferran
"""
import string
import datetime
import glob
import os.path
import re
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import ... |
import numpy as np
import cifar10_input
cifar = cifar10_input.CIFAR10Data('cifar10_data')
x_nat = cifar.eval_data.xs
print 'images', x_nat.shape, x_nat.dtype
y_nat = cifar.eval_data.ys
print 'labels', y_nat.shape, y_nat.dtype
np.save('orig_images.npy', x_nat)
np.save('orig_labels.npy', y_nat)
|
# -*- coding: utf-8 -*-
# This file is part of Viper - https://github.com/viper-framework/viper
# See the file 'LICENSE' for copying permission.
import zipfile
import tempfile
import io
import os
import json
import jbxapi
from viper.common.abstracts import Module
from viper.common.objects import File
from viper.core... |
import json
from locale import getdefaultlocale as locale
from time import time, timezone, sleep
import requests
from amino import community, socket
from amino.lib.util import exceptions, helpers
from amino.lib.util.exceptions import UnknownResponse
class Client():
def __init__(self, path="device.json", callba... |
## Copyright (c) Aslak W. Bergersen, Henrik A. Kjeldsberg. All rights reserved.
## See LICENSE file for details.
## This software is distributed WITHOUT ANY WARRANTY; without even
## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE. See the above copyright notices fo... |
# Run as:
# python3 part1.py [input|sample]
import sys
class Node:
def __init__(self, val, friends=None):
self.val = val
self.friends = friends or set()
def big_guy_4u(self):
return self.val.isupper()
# Extract the logic into a function to make the list comprehension below
# more readable.
def is_... |
from setuptools import setup, find_packages
with open("README.md", "r") as f:
long_description = f.read()
with open("requirements.txt", "r") as f:
requirements = f.readlines()
setup(
name="ser",
version="0.0.1",
author="Thomas Firth & Claudia Vanea",
description="MNIST for SER",... |
###
#
# Lenovo Redfish Library - Utility module
#
# Copyright Notice:
#
# Copyright 2020 Lenovo 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/lice... |
from hypothesis import given
from rene.exact import Point
from tests.utils import equivalence
from . import strategies
@given(strategies.points)
def test_irreflexivity(point: Point) -> None:
assert not point != point
@given(strategies.points, strategies.points)
def test_symmetry(first: Point, second: Point) ->... |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from __future__ import unicode_literals
from datetime import datetime
try:
from unittest.mock import call, patch
except ImportError:
... |
import sys
import math
if len(sys.argv) < 2:
print("Please input a resposne APDU from a GPO as first input!")
else:
x = str(sys.argv[1]).upper()
if x.startswith("80"):
x = x.replace(" ", "")
if x.endswith("9000"):
x = x[0:-4]
print("")
print("[+] -------------------- TLV decoded --------------------... |
import cv2
from threading import Thread
from utils import save_image, draw_matches, debug
class MatcherThread(Thread):
def __init__(self, res_1, res_2, name, config):
super(MatcherThread, self).__init__(name=name)
self.res_1 = res_1
self.res_2 = res_2
self.results = None
s... |
"""
The MIT License (MIT)
Copyright (c) 2021-present tag-epic
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, mer... |
from hone.utils import csv_utils
import copy
class Hone:
def __init__(self):
self.delimit_chars = [",", "_", " "]
self.csv_filepath = None
self.csv = csv_utils.CSVUtils(self.csv_filepath)
'''
Perform CSV to nested JSON conversion and return resulting JSON.
'''
def convert(se... |
from .base import FunctionalTest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class NewVisitorTest(FunctionalTest):
def test_can_start_a_squad_and_retrieve_it_later(self):
# Mike has heard of a site for keeping track of his
# Destiny squad mates, and he checks it out.
self.bro... |
# Copyright (c) 2018 Roland Zimmermann
#
# 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, d... |
# Initialize spiceypy, which interfaces with NASA's SPICE toolkit
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import spiceypy as spice
import json
import math
spice.tkvrsn("TOOLKIT")
# See README.md to download the kernels if they're not present
spice.furnsh("./meta_ker... |
import discord
import datetime
import time
import sys
import asyncio
import requests
import os
from config import discord_key, debug
from tools import *
client = discord.Client()
background_task_running = False
@client.event
async def on_ready():
global background_task_running
print('Logged in as')
print(client... |
#! /usr/bin/env python
import roslib
import rospy
import sys
from data_monster import *
from data_collector import *
import settings
from perception_msgs.srv import GetCondition, GetConditionResponse
from perception_msgs.msg import State
from geometry_msgs.msg import Point, Pose
from data_util import *
from data_settin... |
"""Allows to output DNDarrays to stdout."""
import copy
import torch
from .dndarray import DNDarray
__all__ = ["get_printoptions", "set_printoptions"]
# set the default printing width to a 120
_DEFAULT_LINEWIDTH = 120
torch.set_printoptions(profile="default", linewidth=_DEFAULT_LINEWIDTH)
# printing
__PREFIX = "D... |
import importlib
import inspect
import json
import os
from datetime import datetime
import pytest
import compas
def test_no_removed_names_from_any_package(compas_api):
generated_ver = parse_version(compas_api['metadata']['compas_version'])
current_ver = parse_version(compas.__version__)
# Raise to indi... |
import time
import who_calls
import neo_cgi
PROFILER_DATA = []
PROFILER_START = 0
PROFILER_ENABLED = 0
PROFILER_DEPTH = 0
def enable():
global PROFILER_START
global PROFILER_ENABLED
global PROFILER_DATA
PROFILER_START = time.time()
PROFILER_ENABLED = 1
PROFILER_DATA = []
def disable():
g... |
# -*- coding: utf-8 -*-
"""
tipfy.scripting
~~~~~~~~~~~~~~~
Scripting utilities.
:copyright: 2011 by tipfy.org.
:license: BSD, see LICENSE.txt for more details.
"""
import os
import sys
def set_gae_sys_path():
"""Sets sys.path including App Engine SDK and requirements."""
base_path = os.... |
# https://deeplearningcourses.com/c/cutting-edge-artificial-intelligence
import time
import joblib
import numpy as np
import tensorflow as tf
import os
tf.compat.v1.disable_eager_execution()
def set_global_seeds(i):
tf.compat.v1.set_random_seed(i)
np.random.seed(i)
def cat_entropy(logits):
a0 = logits ... |
#!/usr/bin/env python
"""
This example adds Prometheus metrics to a FastAPI application. In this
example a counter metric is instantiated and gets updated whenever the "/"
route is accessed.
A '/metrics' route is implemented using the render function and added to
the application using the standard web framework method... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.