content stringlengths 5 1.05M |
|---|
from requests import get, delete
import matplotlib.pyplot as plt
import numpy as np
import scipy.cluster.hierarchy as shc
import sys
# This function will help us to convert our dendrogram...
# ...to a result that can be used to D3 (A JSON data structure)
# It is just a function that, recursively, adds everything to a... |
"""Intrinsics of TVM-Python Hybrid Script for Python emulation runtime"""
import numpy
class bind(object): #pylint: disable=invalid-name
"""GPU bind software emulataion runtime."""
def __init__(self, _, ext):
self.ext = ext
def __iter__(self):
i = 0
while i < self.ext:
... |
from __future__ import absolute_import, division, print_function
from glue.external.echo import keep_in_sync, CallbackProperty
from glue.core.layer_artist import LayerArtistBase
from glue.viewers.common.state import LayerState
__all__ = ['LayerArtist']
class LayerArtist(LayerArtistBase):
zorder = CallbackPrope... |
from setuptools import setup, find_packages
setup(
name='picren',
version='1.0.0',
author='sengyh',
author_email='sengyh.dev@gmail.com',
packages=find_packages(),
include_package_data=True,
pymodules='picren',
install_requires=[
'pathlib',
'Click',
'sqlalchemy',
... |
import unittest
class ArrayTests(unittest.TestCase):
def test_can_access(self):
data = [1, 2, 3]
self.assertEqual(data[0], 1)
def test_subselect(self):
data = [1, 2, 3, 4]
self.assertEqual(data[1:3], [2, 3])
def test_multiply(self):
data = [1, 2, 3, 4]
self... |
import os
import sys
import lnkr
import term
KEY_LOCAL = 'local'
KEY_REMOTE = 'remote'
KEY_MODE = 'mode'
KEY_MODE_WIN = 'mode_win'
MODE_COPY = 'copy'
MODE_LINK = 'link'
MODE_SYMLINK = 'symlink'
windows_mode = sys.platform.startswith('win')
class ImportSection:
def __init__(self, path, key, values):
self... |
import pyglet
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm
from PIL import Image
# %%
class Mandelbrot():
width = 200
height = 200
y_center = 0
x_center = 0
scale = 1
threshold = int(200/scale)
def __init__(self, width, height):
self.width = wi... |
"""Tests for the google_maps integration."""
|
import base64
import logging
import random
import re
import typing
from abc import ABC, abstractmethod
from redshift_connector.credentials_holder import CredentialsHolder
from redshift_connector.error import InterfaceError
from redshift_connector.plugin.credential_provider_constants import SAML_RESP_NAMESPACES
from re... |
"""API example"""
import config as cfg
from eodhistoricaldata import APIClient
def main() -> None:
"""Main"""
api = APIClient(cfg.API_KEY)
resp = api.get_exchanges()
print(resp)
#print(resp.dtypes)
#print(resp.describe())
resp = api.get_exchange_symbols("US")
print(resp)
#print... |
from typing import Dict
import requests
from requests.models import Response
from pyforward.static import SCHEME
from pyforward.network import IGD
class Requester:
def __init__(self, igd: IGD):
self.igd = igd
@staticmethod
def make_headers(action: str) -> Dict[str, str]:
"""
Gene... |
"""
Part2
・敵プレイヤーを表示
・プレイヤーを動かす
・キー操作
"""
# pygameを読み込む
import pygame
# pygameを初期化
pygame.init()
# ゲーム画面の横幅
SCREEN_WIDTH = 800
# ゲーム画面の縦幅、横幅の80%にする
SCREEN_HEIGHT = int(SCREEN_WIDTH * 0.8)
# ゲーム画面を作成
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# ゲーム画面の上部にキャプション(ゲームタイトル)を設定
pygame.display.set_capt... |
from proxypool import RedisProxyPoolClient
from log import Logger
from rss_news.rss_news_producer import NewsProducer
from rss_news.rss_news_exporter import NewsExporter
from rss_news.rss_news_validator import NewsValidator
from retry import RetryOnException as retry
@retry(5)
def export_news_to_broker(config, rss_fe... |
#!/usr/bin/env python3
"""
Minecraft railroad with setblock commands in vanilla minecraft
E.g. usage:
./dome -x 82 -z 358 -y 63 -l 40
Capture the output and paste it into the console
"""
import argparse
def main():
parser = argparse.ArgumentParser(description="create commands for " +
... |
#!/usr/bin/python
import sys
from keystone import *
from unicorn import *
from unicorn.arm_const import *
from capstone import *
from capstone.arm import *
from capstone.x86 import *
# architectures and modes for the assembler, disassembler, and emulator
ks_arch = KS_ARCH_ARM
ks_mode = KS_MODE_THUMB
cs_arch = CS_ARCH... |
"""Create utilities for dynamic systems, state estimation etc."""
import copy
from typing import Any, Callable, Union
import numpy as np
from scipy import integrate
import pydrake.solvers.mathematicalprogram as math_prog
from pydrake.systems.controllers import LinearQuadraticRegulator
from systems.trajectory import ... |
from django.db import models
from ordered_model.models import OrderedModel
from softdelete.models import SoftDeleteModel
class Parametre(OrderedModel, SoftDeleteModel):
code = models.CharField(
"code",
help_text="LIEN_FOOTER, LOGO_FOOTER, ou ENTITY_PICTURE",
max_length=255,
)
titl... |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright SAS Institute
#
# 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 b... |
#!/usr/bin/env python3
from panda import Panda
Panda().set_esp_power(False)
|
from __future__ import with_statement
import h5py
import os
import re
import time
import unittest
import numpy as np
from datetime import datetime
from mock import Mock, patch
from datafeed.exchange import SH
from datafeed.datastore import *
from datafeed.tests import helper
class ManagerTest(unittest.TestCase):... |
import numpy
import cupy
from cupy import cublas
from cupy import cusparse
from cupy.cuda import device
from cupy_backends.cuda.libs import cusparse as _cusparse
from cupyx.scipy.sparse import csr
def cg(A, b, x0=None, tol=1e-5, maxiter=None, M=None, callback=None,
atol=None):
"""Uses Conjugate Gradient i... |
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from typing import List, Text, Union
def preprocess_text(text: Text, tokens_only=False) -> Union[Text, List]:
result = None
# tokenize text
preproccesed_tokens = word_tokenize(text.strip())
# s... |
from __future__ import division
# needed for customized candlestick from matplotlib.finance
from matplotlib.lines import Line2D
from matplotlib.patches import Rectangle
def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r',
alpha=1.0, colorline=None):
"""
Modified from matplotlib.... |
from numbers import Number
import random
from protocolbuffers.Localization_pb2 import LocalizedString, LocalizedStringToken
from distributor.rollback import ProtocolBufferRollback
from sims4.tuning.tunable import Tunable, get_default_display_name, TunableVariant, TunableList, TunableFactory
from sims4.tuning.tunable_ba... |
# %% [markdown]
# # Effect of the sample size in cross-validation
#
# In the previous notebook, we presented the general cross-validation framework
# and how to assess if a predictive model is underfiting, overfitting, or
# generalizing. Besides these aspects, it is also important to understand how
# the different erro... |
"""Dpc API Client."""
import asyncio
import json
import re
import socket
from datetime import date, datetime, time, timedelta
from math import *
import aiohttp
import async_timeout
from geojson_utils import geometry_within_radius, point_distance, point_in_polygon
from .const import (
ATTR_AFTERTOMORROW,
ATTR_... |
import sys
from inject.shellcode import Shellcode
from inject.output import Output
from inject.pe_manager import PEManager
from inject.common import CommonMixin
from typing import List
from pathlib import Path
from shutil import copy
from utils import shellcode_encoder
import mmap
from struct import pack
from pefile im... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-05-18 22:53
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('welcome', '0003_welcomepage'),
]
operations = [
migrations.CreateModel(
... |
#!/usr/bin/env python
import os, sys
from jinja2 import Environment, FileSystemLoader
# Project imports.
from slimish_jinja import SlimishExtension
cur_dir = os.path.dirname(os.path.realpath(__file__))
demo_template = os.path.join(cur_dir, 'demo.slim')
env = Environment(loader=FileSystemLoader(cur_dir), extensions=[Sl... |
#!/usr/bin/python
import sys
NUMERIC_OUTPUT = True
try:
filename = sys.argv[1]
except:
print "Usage:", sys.argv[0], "<filename>"
raise SystemExit
try:
inFile = file(filename)
except:
print "Error when opening", filename
raise SystemExit
# code is kept as a list of voices, each voice a strin... |
from __future__ import print_function
from requests import NullHandler
try:
input = raw_input
except NameError:
pass
import ax_lib_api_ax
import ax_lib_general
import argparse
import json
# --Execution Block-- #
# --Parse command line arguments-- #
parser = argparse.ArgumentParser()
parser.add_argument(
... |
import argparse
import torch
from bunch import Bunch
from ruamel.yaml import safe_load
from torch.utils.data import DataLoader
import models
from dataset import vessel_dataset
from tester import Tester
from utils import losses
from utils.helpers import get_instance
def main(data_path, weight_path, CFG, show):
che... |
bot_major_version = 0
bot_minor_version = 1
bot_patch_version = 2
def bot_version_string():
return f'{bot_major_version}.{bot_minor_version}.{bot_patch_version}'
|
'''
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
'''
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(np.sqrt(n)) + 1, 2))
prime_factors = []
for i in range(2,775146):
if is_prime(i)... |
defhitung():
umur=int(input("masukanumurkamu:"))
jj = umur * 369 * 24 * 60 * 60
print("kamusudahhidupselama {jj}.detik")
print ("selamatdatang di program hitungdetikumur")
hitung(
input_barang(a,b)
|
import argparse
import logging
import os
import random
import sys
import time
import numpy as np
import torch
import wandb
sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../../")))
import singleMachine.myUtils as mu
## data
from fedml_api.data_preprocessing.spectrum.data_loader import load_partiti... |
import os
from six.moves import input
import yaml
from copy import deepcopy
from argparse import ArgumentParser
from hobo.api import Hobo
from commandsession import CommandSession
def main():
"""cli entry point.
"""
argparser = ArgumentParser()
argparser.add_argument('--verbose', action='store_true', ... |
"""
SMTP发送邮件
"""
from email.mime.text import MIMEText # 构建纯文本邮件
import getpass
mail_msg = MIMEText('hello python', 'plain', 'utf-8')
# 发送邮件
from_addr = input('From: ')
password = input('Password: ')
to_addr = input('To: ')
# 输入SMTP地址
smtp_server = 'smtp.qq.com'
import smtplib
server = smtplib.SMTP(smtp_server, 25)
s... |
import re
from .multi_line_attribute import MultiLineAttribute
class Body(MultiLineAttribute):
regex = re.compile(r'^\s*BODY:\s*$')
if __name__ == '__main__':
import doctest
doctest.testmod()
|
import copy
import itertools
from typing import Iterable, List, Set, Tuple
from allennlp.data.dataset_readers.dataset_utils import bio_tags_to_spans
from allennlp.data.dataset_readers.dataset_utils.span_utils import TypedStringSpan, InvalidTagSequence
from mare.defs import relation_mandatory_args, replacable_args, re... |
# @nolint
def bar():
return __testSource()
def qux(arg):
__testSink(arg)
def bad(ok, arg):
qux(arg)
def some_source():
return bar()
def match_flows():
x = some_source()
bad(5, x)
|
# NeoPixel library dna example
# Authors: Neil and Rick
#
# Direct port of the Arduino NeoPixel library strandtest example. Showcases
# various animations on a strip of NeoPixels.
import time
from neopixel import *
import argparse
import signal
import sys
def signal_handler(signal, frame):
colorWipe(strip, C... |
#!/usr/bin/env python3
# Write a program that asks the user their name, if they enter your name say
# "That is a nice name", if they enter "John Cleese" or "Michael Palin", tell
# them how you feel about them :), otherwise tell them "You have a nice
# name."
name = input('Your name: ')
if name == 'Bryn':
print('T... |
from testdriver import *
x = torch.tensor(((3.,2.,5.)))
y = torch.empty([3])
y.set_(x.storage(), storage_offset=0, size=[2], stride=[0])
# force materialization
y.storage()
print(x)
print(y)
|
# Generated by Django 3.0.6 on 2020-06-24 20:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vet', '0004_auto_20200624_2014'),
]
operations = [
migrations.AlterField(
model_name='surgery',
name='duration',
... |
from trump.aggregation.symbol_aggs import FeedAggregator
import pandas as pd
def make_fake_feed_data(l=10):
dr = pd.date_range(start='2015-01-10', periods=l, freq='D')
data = pd.np.random.rand(l)
return pd.Series(data,dr)
class TestSymbolAggregation(object):
@classmethod
def setup_class(self):
... |
#!/usr/bin/env python
from . import main
import random as rng
from datetime import datetime
import app.defaults as AppDefaults
from app import db, pages
from app.models import Annotation, Source, Author, Tag, Collection
from app.tools import home_url, SortIt
from app.main.tools import SearchAnnotations, paginated_a... |
# Generated by Django 2.2.2 on 2019-06-25 08:16
import uuid
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [("sidekick", "0010_modify-consent-body")]
operations = [
migrations.CreateModel(
... |
# Licensed under an MIT open source license - see LICENSE
import os
import numpy as np
from .util import parse_dendrogram
from .handler import IOHandler
# Import and export
# FITS file signature as per RFC 4047
FITS_SIGNATURE = (b"\x53\x49\x4d\x50\x4c\x45\x20\x20\x3d\x20\x20\x20\x20\x20"
b"\x20\x... |
#
# PySNMP MIB module ChrTrap-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ChrTrap-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:36:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... |
from typing import Any, TypeVar, cast
import structlog
__all__ = ["bind"]
BL = TypeVar("BL", bound=structlog.types.BindableLogger)
def bind(logger: BL, **new_values: Any) -> BL:
"""
A plain wrapper around logger.bind(**new_values) that preserves the type
annotation of the logger. Does not check at runt... |
#!/usr/bin/python3
# Written by David McDougall, 2017
"""
Graphical User Interface for labeling datasets
Outstanding Tasks
The floodfill tool should discard probable foreground areas which arent
connected to any definate forground areas.
Pending flood fill operations should remember which label they a... |
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Created by: Yaoyao Liu
## NUS School of Computing
## Email: yaoyao.liu@mail.m2i.ac.cn
## Copyright (c) 2019
##
## This source code is licensed under the MIT-style license found in the
## LICENSE file in the root directory of this source tree... |
#!/usr/bin/python3
import os
import re
from os.path import abspath
from os.path import join as pj
from lib.argparse import parse_args
from lib.init import Init
from lib.sanitize import Sanitize
from lib.util import read_xml, write_xml
if __name__ == '__main__':
dirs = {}
dirs['base'] = re.search(r'.*rdmo-cat... |
from path import Path
import numpy as np
data = Path('./poles')
out=Path('./out')
out.mkdir_p()
files =data.files()
import cv2
import matplotlib.pyplot as plt
kernel = np.array([0, 1, 0,
0, 1, 0,
0, 1, 0]).reshape([3, 3]).astype(np.uint8)
kernel_ = np.array([0, 0, 0,
... |
# coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Un... |
import math
d = input("").split(" ")
n = 5
dis = [0 for n in range(5)]
d.insert(0, 0)
def show():
for z in range(5):
if z == 4:
print(int(math.fabs(dis[z])))
else:
print(int(math.fabs(dis[z])), end = " ")
for i in range(5):
for x in range(i + 1):
... |
import os
import sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from tessellation import Tessellation
name = "tesspy"
__version__ = "0.0.1"
__author__ = "Siavash Saki and Jonas Hamann"
__author_email__ = "jonas.hamann@fb3.fra-uas.de"
|
from django.conf.urls.defaults import *
from django.conf import settings
from pyppp.django.forms import AuthenticationForm, PasscodeForm, LoginWizard
urlpatterns = patterns('',
url(r'^login/$', LoginWizard([AuthenticationForm, PasscodeForm])),
url(r'^logout/$', 'django.contrib.auth.views.logout'),
url(r'^c... |
from axil_cdc import AxilCDC
from axilite2bft import AxiLite2Bft
from bft import Bft
from litex.soc.interconnect.axi import AXILiteInterface, AXIStreamInterface
from litex.soc.interconnect.stream import (ClockDomainCrossing, Converter,
Endpoint)
from migen import *
from pld_ax... |
from pySPIRALTAP import SPIRALTAP
|
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
from datetime import datetime
from base64 import b64decode, b64encode
from nacl.secret import SecretBox
from nacl.public import PrivateKey
import sqlite3
API_KEY = "5MsHBAGgmulDbS2AsX9bNY9fd5SVKd3IG5SXc9JTVic="
DATABASE = 'gmit.db'
CREATE... |
from enum import Enum, unique
# 0 = SYN
# 1 = ACK
# 2 = SYNACK
# 3 = DATA
# 4 = FIN
@unique
class RIPPPacketType(Enum):
SYN = 'SYN'
ACK = 'ACK'
SYN_ACK = 'SYNACK'
DATA = 'DATA'
FIN = 'FIN'
@unique
class StateType(Enum):
LISTEN = 'LISTEN'
SYN_SENT = 'SYN-SENT'
SYN_RECEIVED = 'SYN-REC... |
"""`oteapi.interfaces` module.
This module hosts the strategy interfaces.
The strategy interfaces can be considered to be the abstract classes for the
strategies.
"""
from .idownloadstrategy import IDownloadStrategy
from .ifilterstrategy import IFilterStrategy
from .imappingstrategy import IMappingStrategy
from .ipars... |
from math import ceil
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.db.models import Q
from django.http import HttpResponseForbidden, HttpResponseRedirect
from django.urls import reverse, reverse_lazy
from django.utils.datetime_safe import datetime
from django.utils.translation import gett... |
#!/usr/bin/env python
import sys
import logging
import math
import numpy as np
from numpy import linalg as LA
from CodeEntropy.poseidon.extractData.generalFunctions import com, MOI, vector, distance
from collections import defaultdict
nested_dict = lambda: defaultdict(nested_dict)
#create nested dict in one ... |
base_url = '<BASE_URL>'
consumer_token = '<CONSUMER_TOKEN>'
employee_token = 'EMPLOYEE_TOKEN'
expiration_date = 'EXPIRATION_DATE'
class Config():
def __init__(self):
self.base_url = base_url
self.consumer_token = consumer_token
self.employee_token = employee_token
self.expiration_d... |
# import main
import subprocess
import pandas as pd
# # Run main.py to chunk audio file
# subprocess.run(["python","main.py"])
# Get chunk audio files
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(r"H:\UOB\integrate\uob_integrated_proj\stt") if isfile(join(r"H:\UOB\integra... |
import pytest
from django.conf import settings
from rest_framework import status
from rest_framework.test import APIClient
pytestmark = pytest.mark.django_db
class TestPostView:
uri = "/api/posts/"
def test_create_post(self, all_entities):
post_data = {
"event": all_entities["event"].slu... |
from app.functions.integrate_trajectory import integrate_with_events
from app.parameters.trajectory import TrajectoryParameters
from app.models.trajectory import Trajectory
import logging
from app.utils.config_logging import config_logging
from app.models.job_metadata import JobMetadata
from app.utils.heartbeat import... |
from django.db import models
from django.test import TestCase
import mock
from . import archivable
from .archive import _add_field_to_class, _replace_manager
class BaseModel(models.Model):
""" Since the `archivable` adds a mixin instead of overriding
the methods, we need to make sure the mixin methods are us... |
import sys
import os
import pytest
import numpy as np
ROOT = os.path.realpath(os.path.dirname(__file__) + '/..') + '/'
sys.path.append(ROOT)
import pytips as t
def test_iso():
np.testing.assert_equal(t.iso(6), np.array([211, 311, 212, 312]))
def test_pf_iso():
molID = 6
isoID = t.iso(molID)
np.tes... |
# Given a binary tree, find the length of the longest consecutive sequence path.
#
# The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).
#
# Example 1:
#
# Input... |
""" test pyvista.utilities """
import os
import numpy as np
import pytest
import pyvista
from pyvista import examples as ex
from pyvista import utilities
from pyvista import fileio
# Only set this here just the once.
pyvista.set_error_output_file(os.path.join(os.path.dirname(__file__), 'ERROR_OUTPUT.txt'))
def tes... |
import os
import numpy as np
import torch
import lib.utils as utils
from torchvision.datasets.utils import download_url
class Periodic1d(object):
def __init__(
self,
root,
download=False,
min_t=0.,
max_t=2.,
n_t=10,
n_samples=10**... |
from .Resnet_32 import *
from .MobileNet import *
from .InceptionV1 import *
from .WRN_28_10 import *
##'ResNet_32', 'MobileNet', 'InceptionV1','WRN_28_10'
|
"""Copyright (c) Microsoft Corporation. Licensed under the MIT license.
VCR dataset
"""
import copy
import json
import torch
from torch.nn.utils.rnn import pad_sequence
from toolz.sandbox import unzip
from cytoolz import concat
from .data import (
DetectFeatTxtTokDataset,
TxtTokLmdb,
DetectFeatLmdb,
Tx... |
Mein Neuer code..:
|
import smartpy as sp
class TestCheckSignature(sp.Contract):
def __init__(self, boss_pk):
self.init(currentValue = 'Hello World', counter = 0, bossPublicKey = boss_pk)
@sp.entry_point
def setCurrentValue(self, params):
# We will also need Michelson SELF and CHAIN_ID to avoid all replay atta... |
import abc
import os
from typing import Any, Dict, Optional
class Wrapper(metaclass=abc.ABCMeta):
"""
Parent class for classes that generate Python code, i.e. wrappers, for calling a stored procedures and functions.
"""
# -------------------------------------------------------------------------------... |
import json
import requests
import os
import random
from flask import Flask, request, current_app, render_template
from flask_wtf import FlaskForm
from wtforms.fields import StringField, TextAreaField, SelectMultipleField, SubmitField, BooleanField
from . import api
from .utilities import get_random_article, make_cho... |
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
import click
from jina.clients import py_client
def read_query_data(text):
yield "{}".format(text).encode("utf8")
def print_topk(resp, word):
for d in resp.search.docs:
print(f"Ta-Dah🔮, here are ... |
import uuid
from hashlib import sha3_256
from Crypto.Cipher import AES
from .config import *
import random
import string
import struct
from .results import SplunkResult
RANDOM_KEY = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(40))
class StoredSplunkResult(object):
DATA_KEY = None
... |
#!/usr/bin/env python3
import subprocess
import deploy_keys
subprocess.run(['docker','build','-t','atube_webserver','-f','website/Dockerfile','.'])
subprocess.run(deploy_keys.docker_login_cmd)
subprocess.run(['docker', 'tag', 'atube_webserver:latest', '355023123875.dkr.ecr.us-east-1.amazonaws.com/atube_webserver:lates... |
# Generated by Django 3.2.2 on 2021-06-04 13:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kra', '0019_suggestion_split_reason'),
]
operations = [
migrations.AddField(
model_name='workload',
name='affinity',... |
from os import makedirs
from os.path import dirname, abspath, join
from PIL import Image
from pickle import dumps, loads
from neo4j import GraphDatabase
from redis import Redis
import face_recognition
# Remove documentation and create global README
class FaceProcessor:
def __init__(self, neo4j_credentials, redi... |
from setuptools import setup, find_packages
try:
with open('README.md') as f:
readme = f.read()
except:
pass
try:
with open('LICENSE.txt') as f:
license = f.read()
except:
pass
setup(
name='PlantNannyDB',
version='1.4.6',
description='Enable read/write functionality for Pl... |
from django.db import models
class Album(models.Model):
album_id = models.CharField(primary_key=True, max_length=100)
title = models.CharField(max_length=100, blank=True, null=True)
artist_username = models.ForeignKey('Artist', models.DO_NOTHING, db_column='artist_username', blank=True, null=True)
... |
"""vetted URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based ... |
"""
Metrics used
"""
import numpy as np
def BHS_standard(err):
"""
Computes the BHS Standard metric
Arguments:
err {array} -- array of absolute error
Returns:
tuple -- tuple of percentage of samples with <=5 mmHg, <=10 mmHg and <=15 mmHg error
"""
leq5 = 0
leq10 = 0
leq1... |
""" WORKSPACE dependencies for the nRF SDK """
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def nRF5_deps():
# SDK: nRF5.
http_archive(
name = "nrf_sdk",
build_file = "@nRF5//sdk:nrf_sdk.BUILD",
sha256 = "28f336d929b64f501d826187f7208d4c0e3cde6a4de6c9f1ce1ee7b34... |
# Copyright 2017 Yahoo Inc.
# Licensed under the terms of the Apache 2.0 license.
# Please see LICENSE file in the project root for terms.
import ctypes as ct
import logging
import platform
import random
import subprocess
import time
MAX_RETRIES=3
def get_gpu():
"""Allocates first available GPU using cudaSetDevice... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
import sys, os, timeit, argparse
import pandas as pd
import numpy as np
import h5py
import tables
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer, LabelEncoder
from scipy import sparse
from rdkit import Chem
from rdkit.Chem import AllChem, rdChemReactions, rdmolfil... |
import random
import pandas as pd
import numpy as np
# A counter to be used when creating fresh names
import time_blender
def fresh_id():
fresh_id.counter += 1
return fresh_id.counter
fresh_id.counter = -1
def set_random_seed(seed):
if seed is not None:
random.seed(seed)
np.random.see... |
import pandas as pd
from itertools import chain
from operator import add
from functools import reduce
from pydigree.common import table
class IndividualContainer(object):
def apply_inplace(self, func):
'''
Calls a function on each individual object in the collection
:param func: A func... |
from chatterbot.logic import BestMatch
from chatterbot.conversation import Statement
from tests.base_case import ChatBotTestCase
class BestMatchTestCase(ChatBotTestCase):
"""
Unit tests for the BestMatch logic adapter.
"""
def setUp(self):
super().setUp()
self.adapter = BestMatch(self... |
"""This module contains all the neural network components, needed to
set up and train a neural network.
Author:
- Johannes Cartus, QCIEP, TU Graz
"""
import tensorflow as tf
import numpy as np
from datetime import datetime
class AbstractNeuralNetwork(object):
"""This is an abstract template for a neural net... |
'''
Created on 2 Mar 2012
@author: samgeen
'''
# Abstract chunk of Hamu (e.g. Suite, Simulation, etc)
# Sets up a generic chunk with file location, allows the creation of children objects, etc
class AbstractBlock(object):
'''
classdocs
'''
# storeLocation: Where to store temporary data and dump figur... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
"""
The MetadataWizard(pymdwizard) software was developed by the
U.S. Geological Survey Fort Collins Science Center.
See: https://github.com/usgs/fort-pymdwizard for current project source code
See: https://usgs.github.io/fort-pymdwizard/ for current user documentation
See: ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.