content stringlengths 5 1.05M |
|---|
# Generated by Django 2.0 on 2017-12-12 16:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0013_auto_20171212_1955'),
]
operations = [
migrations.AlterField(
model_name='driverprofile',
name='car_pic',
... |
#!/usr/bin/env python
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (t... |
from elmo.modules.elmo import Elmo, batch_to_ids
|
from django.conf.urls import url
from rest_framework import renderers
from .views import AssetViewSet, CatalogViewSet, CategoryViewSet,\
ProductViewSet, SiteViewSet, ProductByCategory, AssetsBulk
app_name = 'API'
category_list = CategoryViewSet.as_view({
'get': 'list'
})
category_detail = CategoryViewSet.as_... |
"""
Code to test the hydrotools module.
"""
# Import the nwm Client
from hydrotools.nwm_client import http as nwm
import pandas as pd
# Path to server (NOMADS in this case)
server = "https://nomads.ncep.noaa.gov/pub/data/nccf/com/nwm/prod/"
# Instantiate model data service
model_data_service = nwm.NWMDataService(ser... |
import os
from dotenv import load_dotenv
load_dotenv()
BOT_TOKEN = os.getenv('bot_token') |
program1 = [ [] ,
[] ,
[] ,
[] ]
programs_dict = {"program1" : program1}
|
# Generated by Django 2.2.11 on 2020-05-19 16:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('contentPages', '0036_auto_20200519_1615'),
]
operations = [
migrations.RenameField(
model_name='createnewresourcetype',
old... |
"""
conference_helper.py -- Udacity conference server-side Python App Engine
HTTP controller handlers for memcache & task queue access
created by @Robert_Avram on 2015 June 6
"""
import endpoints
from google.appengine.ext import ndb
from google.appengine.api import search
from google.appengine.api i... |
# Zip Function
""" Zip function combines two or more into one... """
friend = {'Rolf','Jen','Bob','Anne'}
time_since_seen = [3, 7, 15, 4]
long_timers = dict(zip(friend, time_since_seen))
print(long_timers) # O/P - {'Anne': 3, 'Jen': 7, 'Rolf': 15, 'Bob': 4}
# Also we can make it in list too...
long_t... |
"""
workplane
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from OpenGL import GL
from mcedit2.rendering.scenegraph import scenenode
from mcedit2.rendering.scenegraph.matrix import Translate
from mcedit2.rendering.scenegraph.vertex_array import VertexNode
fr... |
import argparse
import yaml
import os
from common import MacrobaseArgAction
from macrobase_cmd import run_macrobase
from time import strftime
def bench_directory(workload):
sub_dir = os.path.join(
os.getcwd(),
'bench',
'workflows',
workload['macrobase.query.name'],
strftime('%m-%d-... |
from PIL.PngImagePlugin import PngImageFile, PngInfo
from utils import *
import numpy as np
import itertools
import PIL
import os
def rgbChannels(inFile: PIL.PngImagePlugin.PngImageFile, message: str="", quantizationWidths: list=[],
traversalOrder: list=[], outFile="./IO/outColor.png", veri... |
'''
To convert this Fetch code to be a member function of a class:
1. The sqliteConnection should be a data member of the class and connected
2. The function should take a string parameter for select statement. See line 16.
3. It should return 'true' if connected, otherwise 'false'
'''
import sqlite3
#co... |
def inverse(x: int, p: int) -> int:
inv1 = 1
inv2 = 0
while p != 1 and p != 0:
inv1, inv2 = inv2, inv1 - inv2 * (x // p)
x, p = p, x % p
return inv2
def double(pt: tuple, p: int) -> tuple:
if pt is None:
return
(x, y) = pt
if y == 0:
return
# Calculate... |
# Generated by Django 2.2.1 on 2021-02-17 05:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('webapi', '0052_image_video'),
]
operations = [
migrations.RemoveField(
model_name='image',
name='image_url',
... |
import bpy
from math import radians
from . import utils
from .utils import update
from .utils import generate_armature
from .utils import generate_shapekey_dict
from .utils import bone_convert
from .armature_rename import armature_rename, bone_rename
def anim_armature(action):
satproperties = bpy.context.scene.s... |
"""Support for Velbus light."""
from __future__ import annotations
from typing import Any
from velbusaio.channels import (
Button as VelbusButton,
Channel as VelbusChannel,
Dimmer as VelbusDimmer,
)
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_FLASH,
ATTR_TRANSITION,
... |
'''
Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k.
Example 1:
Input: nums = [1,1,1], k = 2
Output: 2
Example 2:
Input: nums = [1,2,3], k = 3
Output: 2
Constraints:
1 <= nums.length <= 2 * 10^4
-1000 <= nums[i] <= 1000
-10^7 <= k... |
N = 5
def add_3(a1, a2, a3):
return a1 + a2 + a3
|
# -----------------------------------------------------------------------------
# lex_optimize4.py
# -----------------------------------------------------------------------------
import re
import sys
if ".." not in sys.path: sys.path.insert(0,"..")
import ply.lex as lex
tokens = [
"PLUS",
"MINUS",
"NUMBER... |
from aiogram import Dispatcher
from loguru import logger
from .common import register_common_handlers
from .decryption import register_decryption_handlers
from .encryption import register_encryption_handlers
from .exception import register_exception_handlers
def register_handlers(dp: Dispatcher):
"""Sets all bo... |
# coding: utf8
from __future__ import unicode_literals, print_function
import pytest
import time
import os
from wasabi.printer import Printer
from wasabi.util import MESSAGES, NO_UTF8, supports_ansi
SUPPORTS_ANSI = supports_ansi()
def test_printer():
p = Printer(no_print=True)
text = "This is a test."
... |
import pandas as pd
import matplotlib.pyplot as plt
from asreview.state.utils import open_state
from scipy.stats import spearmanr
def probability_matrix_from_h5_state(state_fp):
"""Get the probability matrix from an .h5 state file.
Arguments
----------
state_fp: str
Path to state file.
R... |
from asyncio import AbstractEventLoop
from collections import OrderedDict
from functools import partial
from typing import Any, Iterator, List
from aiohttp.http_writer import HttpVersion11
from aiohttp.web import BaseRunner
from aiohttp.web import Server as WebServer
from aiohttp.web_exceptions import HTTPExpectationF... |
import sys
#import cv2
import numpy as np
import os
import Calibration
WORKING_DIR = os.getcwd()
VIDEO_DIR = os.path.join(WORKING_DIR,'Projects')
mode = 'none'
if __name__ == '__main__':
if len(sys.argv) > 1:
if str(sys.argv[1]) == 'help':
print('')
print('=======================... |
from __future__ import absolute_import, division, print_function
from libtbx import Auto
import os.path
import sys
master_phil_str = """
map_type = *2mFo-DFc mFo-DFc anom anom_residual llg
.type = choice
exclude_free_r_reflections = True
.type = bool
fill_missing_f_obs = False
.type = bool
b_sharp = None
.typ... |
import urllib.request
import os
import sys
def downloadImages(strQueryString, arrUrls):
for url in arrUrls:
downloadImage(strQueryString, url)
def downloadImage(strQueryString, url):
try:
strPath = setup(strQueryString)
print(f"Downloading {url} to {strQueryString}")
image_na... |
# Layout / Size
# How to adjust the size of cards on a page.
# ---
from h2o_wave import site, ui
# Every page has a grid system in place.
# The grid has 12 columns and 10 rows.
# A column is 134 pixels wide.
# A row is 76 pixels high.
# The gap between rows and columns is set to 15 pixels.
# Cards have a `box` attri... |
from machine import Pin
import machine
from time import sleep
# Global value to communicate with the IRQ routine
isAwake = 1
# GPIO16 (D0) is the internal LED for NodeMCU
led = Pin(16, Pin.OUT)
# Callback should be as short as possible
def timer_callback(timer):
# Require to specify that isPirActive and led are ... |
"""
Copyright 2019, Aleksandar Stojimirovic <stojimirovic@yahoo.com>
Licence: MIT
Source: https://github.com/hooppler/wormnet/
"""
import pygame
class Button(object):
def __init__(self, width=60, height=20, pos_x=0, pos_y=0, title='Button'):
self.width = width
self.height = height
... |
import os
import sys
import scipy
import numpy as np
import imageio
import tensorflow as tf
from cityscapelabels import trainId2RGB
import os
os.environ['TF_CPP_MIN_LOG_LEVLE'] = '2'
def load_graph(frozen_graph_filename):
# We load the protobuf file from the disk and parse it to retrieve the
# unserialized ... |
from rest_framework import request, response
from rest_framework.decorators import action
from rest_framework.exceptions import NotFound
from ee.clickhouse.models.person import delete_person
from ee.clickhouse.queries.clickhouse_retention import ClickhouseRetention
from ee.clickhouse.queries.clickhouse_stickiness impo... |
from domain.database import DBSession
from domain.subreply import SubReply
import datetime
# 从x位置获取n个跟帖的评论
def selectSubReplyFromXGetN(replyId, x, n):
try:
session = DBSession()
offset = x
num = x + n
subreply = session.query(SubReply).filter(SubReply.replyId == replyId).s... |
import smtplib
from email.message import EmailMessage
from string import Template
from pathlib import Path
html=Template(Path('ht.html').read_text())
email=EmailMessage()
email['from']='Vasudeva'
email['to']='k.k@gmail.com'
email['subject']='Hi'
#email.set_content('greetings:hiiiii!')
email.set_content(html.substitute(... |
import tkinter as tk
from tkinter.ttk import *
from tkinter import ttk
from pandas import DataFrame
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import os
import sys
import matplotlib
import numpy as np
import pandas as pd
from matplotlib import interactive
import matp... |
import errno
import os
import shutil
import subprocess
from pathlib import Path
class Utils:
def create_dir(self, path, permissions=0o755):
if not os.path.exists(path):
os.makedirs(path, permissions)
def write_to_file(self, file, content=""):
with open(file, 'wb') as f:
... |
from Jumpscale import j
# import asyncio
from urllib.parse import urlparse
# import logging
# class AllHandler(logging.Handler):
# def emit(self, record):
# print(record)
# class WgetReturnProtocol(asyncio.SubprocessProtocol):
# def __init__(self, exit_future):
# self.exit_future = exit_fut... |
#!/usr/bin/env python
import angr, claripy, time, sys, os, simuvex
import os, datetime, ntpath, struct, shutil
from xml.dom import minidom
TIMEOUT = 7
result_dir = os.path.join(os.getcwd(), "angr-out-" + datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
def check_argv(argv):
xml_path = list()
if len(ar... |
from primes import sieve
primes = sieve()
result = 0
for prime in primes:
if prime > 2000000:
break
result += prime
print result, prime
|
# Copyright 2018 Division of Medical Image Computing, German Cancer Research Center (DKFZ).
#
# 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
... |
import tensorflow as tf
in_ = tf.compat.v1.placeholder(tf.float32, shape=[1, 2, 2, 1], name="Hole")
pd_ = tf.constant([[0, 0], [0, 0]], name="Hole")
op_ = tf.space_to_batch(in_, pd_, 2)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: lingquan
"""
from statsmodels.tsa.arima_model import ARMA
import pandas
import numpy
import statsmodels.api as sm
prices = pandas.read_csv("prices.csv",parse_dates=['Date'],index_col=0)
tickers = prices.columns[:-2]
prices = prices.resample('W').agg(lambda x... |
# -----------------------------------------------------.
# ポリゴンメッシュの重複頂点で、1つの頂点のみを選択.
#
# @title \en Select single vertex of polygon mesh \enden
# @title \ja ポリゴンメッシュの重複頂点の選択を単一に \endja
# -----------------------------------------------------.
import math
scene = xshade.scene()
# 階層をたどってポリゴンメッシュを格納.
def getPolygonmesh... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
对半搜索,
"""
import random
def test(search):
l = sorted(random.sample(range(99), 10))
i = random.randrange(len(l))
assert search(l, l[i]) == i
assert search(l, 999) == None
def _bsearch(l, x, a, b):
if a >= b:
return None
m = (a + b) // ... |
"""mapper.py - defines mappers for domain objects, mapping operations"""
import zblog.tables as tables
import zblog.user as user
from zblog.blog import *
from sqlalchemy import *
import sqlalchemy.util as util
def zblog_mappers():
# User mapper. Here, we redefine the names of some of the columns
# to differe... |
class DexChangeEvent:
"""
general event when the dex is updated.
This event must be called if no other event is called to describe a modification of the dex
"""
NAME = "DEX_CHANGE_EVENT"
def __init__(self, directory, key, prevData, newData):
self.directory = directory
self.ke... |
# Script to retrieve results in offline mode
import json, pickle
from authentication import ws
import pandas as pd
from azureml.core.model import Model, Dataset
from azureml.core.run import Run#, _OfflineRun
run_id = 'f96fd978-f615-4e34-8ae5-6a0c668d10e8' # main run, under Experiment
experiment = ws.experiments['doubl... |
from werkzeug.utils import secure_filename
from datetime import datetime as DT
from flask.helpers import flash, send_file
from getpass import getpass
from pathlib import Path
from passlib.hash import pbkdf2_sha256
from subprocess import Popen
from markupsafe import escape
from functools import wraps
from flask import F... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
##===-----------------------------------------------------------------------------*- Python -*-===##
##
## S E R I A L B O X
##
## This file is distributed under terms of BSD license.
## See LICENSE.txt for more information.
##
##===----------... |
from django.conf import settings
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from swingers import models
from swingers.models import Audit
from swingers.utils.auth import make_nonce
from model_utils import Choices
from reversion import revision
import threading
im... |
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# str is a built-in class
# RevStr is inheriting from str class and
# we are overriding the string representation method to instead of returning the string itself, to
# return a slice of the string where the step goes backwards. And so, this will reverse ... |
#!/usr/bin/python3
#
# MIT License
#
# Copyright (c) 2018 Erriez
#
# 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,... |
# Copyright 2015 The TensorFlow 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
#
# Unless required by applica... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 12 11:53:50 2021
@author: user
"""
import os
import tensorflow as tf
import numpy as np
from keras.models import load_model
from keras.optimizers import Adam
from keras.initializers import RandomNormal
from keras.models import Model
from keras.models impo... |
# Generated by Django 3.0.7 on 2020-06-12 18:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('kpis', '0002_auto_20200611_1535'),
]
operations = [
migrations.CreateModel(
name='KPICategory',... |
__author__ = 'waziz'
import numpy as np
import sys
from collections import defaultdict
from chisel.smt import Solution
from chisel.util import npvec2str, fmap_dot
from chisel.smt import groupby
from chisel.util import obj2id
class EmpiricalDistribution(object):
"""
"""
def __init__(self,
der... |
# mock backend classes from peeringdb-py client
from django_peeringdb.models import all_models
def reftag_to_cls(fn):
return fn
class Resource:
def __init__(self, tag):
self.tag = tag
class Interface:
REFTAG_RESOURCE = {
model.HandleRef.tag: Resource(model.HandleRef.tag) for model in ... |
import pytest
from libband.commands.facilities import Facility
from libband.commands.helpers import (
lookup_command, make_command, lookup_packet
)
EXAMPLE_COMMANDS = [
# GET_TILES
(54400, Facility.ModuleInstalledAppList, True, 0),
# SET_THEME_COLOR
(55296, Facility.ModuleThemeColor, False, 0),
... |
default_app_config = 'common.apps.CommonConfig' |
class UserException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class ServiceUnreachable(Exception):
def __init__(self, service_name: str):
self.value = service_name
def __str__(self):
return self.value + 'Servi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import boto3
import json
import time
import traceback
from ecs_crd.canaryReleaseDeployStep import CanaryReleaseDeployStep
from ecs_crd.destroyGreenStackStep import DestroyGreenStackStep
from ecs_crd.applyStrategyStep import CheckGreenHealthStep
from ecs_crd.destroyGreenS... |
# !/usr/bin/env python3
#######################################################################################
# #
# Program purpose: Get the size of a file. #
# Program Author : Happi... |
import numpy as np
import csv
from scipy.stats import circmean, circvar, binned_statistic
def load_channel(mouse='28', session='140313', channel='1', freq=20000):
'''
freq is frequency in Hz
'''
mouse = 'Mouse' + mouse + '-' + session
basedata = mouse + '/'
data = []
with open(basedata + m... |
from gensim.models import Word2Vec
import numpy as np
import pickle
import multiprocessing
import time
data_root = '/nosave/lange/cu-ssp/data/'
'''
EMB_DIM = 50
WINDOW_SIZE = 20
NB_NEG = 5
NB_ITER = 10
'''
EMB_DIM = 230
WINDOW_SIZE = 20
NB_NEG = 3
NB_ITER = 24
N_GRAM = 1
def onehot_to_seq(oh_seq, index):
s = ... |
import re
import socket
import requests
from BaseSearch import BaseSearch
from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup
socket.setdefaulttimeout(15)
def getLink(url):
f = None
try:
r = requests.get(url,headers={'Accept-encoding':'gzip'})
f = r.text
soup = BeautifulSoup(f)... |
# Author: He Ye (Alex)
# Date: 2019-11-13
import cv2
#import copy
from threading import Thread
from queue import Queue
#from Queue import Queue
VDEV = "/dev/video0"
def showVideoInfo(cap):
try:
fps = cap.get(cv2.CAP_PROP_FPS)
fourcc = cap.get(cv2.CAP_PROP_FOURCC)
#count = cap.get(cv2.CAP_... |
import MySQLdb
from model.endereco import Endereco
class EnderecoDao:
conexao = MySQLdb.connect(host='localhost', database='aulabd', user='root', passwd='')
cursor = conexao.cursor()
def listar_todos(self):
comando_sql_select = "SELECT * FROM endereco"
self.cursor.execute(comando_sql_s... |
class HeaderMismatchException(Exception): pass
class ChunkFailedToExist(Exception): pass
class EverythingWentFine(Exception): pass
class ProcessingOverlapError(Exception): pass
class BadTimecodeError(Exception): pass
class BadFileNameError(Exception): pass
|
#- Python 3 source code
#- compute-csc108-max-nodes.py ~~
#
# This program is for verifying claims made in the PMBS 2018 submission.
# There are prettier ways to do it, but I'm in a hurry.
#
# ~~ (c) SRW, 28 Aug 2018
# ... |
"""Functions for interacting with the IAM service."""
import json
import boto3
from boto3_assistant import account
IAM = boto3.client('iam')
def create_role(name, description):
"""
Create a role that is assumable by the callers account.
The role will be created with no policies.
Parameters:
... |
"""
Test cases targeting streamingphish/database.py.
"""
import pytest
@pytest.fixture(scope="module")
def artifacts():
return {'classifier_name': 'classifier_v1', 'key_one': 'value_one'}
### Helper function ###
def spoofed_find_function():
return [{'_id': 'something', 'classifier_v1': 'blob'}]
def test_save... |
import os
def pytest_configure():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_test_settings')
|
from __future__ import absolute_import
from __future__ import unicode_literals
import warnings
import hashlib
from quickcache.django_quickcache import get_django_quickcache
from quickcache import ForceSkipCache
from celery._state import get_current_task
from corehq.util.global_request import get_request
from corehq.ut... |
#!/usr/bin/env python
COPY_GOOGLE_DOC_KEY = '1exAtJogmunF-R70TvaWDUeSI_l3hBNGAQqIlfiz7uP8'
|
# reformat.py
# Trevor Pottinger
# Tue Sep 22 00:22:49 PDT 2020
import sys
def main() -> None:
for line in sys.stdin:
start_str, end_str, len_str, word = line.rstrip('\n').split('\t')
print('{start:0.3f}\t{end:0.3f}\t{duration:0.3f}\t{content}'.format(
start=float(start_str),
... |
# Generated by Django 3.0.5 on 2020-10-07 04:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('moex', '0029_auto_20200816_2114'),
]
operations = [
migrations.AlterField(
model_name='security',
name='faceunit',
... |
from pandas import DataFrame
#---------------------------------------------------------------------------------------------------
#
# Order class
#---------------------------------------------------------------------------------------------------
class Order:
def __init__(self, exec_time, type, amount, uprice) -> ... |
#!/usr/bin/python
import os
import sys
import fnmatch
import glob
import shutil
import subprocess
def glob_recursive(base_path, pattern):
matches = []
for root, dirnames, filenames in os.walk(base_path):
for filename in fnmatch.filter(filenames, pattern):
matches.append(os.path.join(root, filename))
return ... |
from chainer import function
from chainer.utils import type_check
class Swapaxes(function.Function):
"""Swap two axes of an array."""
def __init__(self, axis1, axis2):
self.axis1 = axis1
self.axis2 = axis2
def check_type_forward(self, in_types):
type_check.expect(in_types.size() ... |
# -*- coding: utf-8 -*-
from numpy import*
import numpy as np
import matplotlib.pyplot as plt
def loadDataSet(fileName):
dataMat=[];labelMat=[]
fr=open(fileName)
for line in fr.readlines():
lineArr=line.strip().split()
dataMat.append([1.0,float(lineArr[0]),float(lineArr[1])])
labelMa... |
#
# Copyright (C) 2020 Red Hat, 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 to in ... |
from neat import nn
def eval_mono_image(genome, width, height):
net = nn.create_feed_forward_phenotype(genome)
image = []
for r in range(height):
y = -2.0 + 4.0 * r / (height - 1)
row = []
for c in range(width):
x = -2.0 + 4.0 * c / (width - 1)
output = net.... |
#!/usr/bin/env python3
from pathlib import Path
import re
#from itertools import groupby
from io import StringIO
def updatePathContents(path, newContents):
originalContents = ''
try:
with path.open('r') as tio:
originalContents = tio.read()
except FileNotFoundError:
pass
if originalContents != newContents:
... |
from flask import Flask, request, Response, jsonify
from sesamutils import sesam_logger, VariablesConfig, Dotdictify
from sesamutils.flask import serve
import sys
import msal
import pem
import json
from cryptography import x509
from cryptography.hazmat.backends import default_backend
import requests
app = Flask(__nam... |
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from django.test import TestCase
from models import Survey
class SurveyTestCase(TestCase):
def test_basic(self):
instance = Survey.objects.get(n... |
'''
T-primes
find how many divisors a integers have.
Oouput:
3 divisors return yes else no
3 important facts:
first it must be equally divided integer = x*x
second no other divisors besides 1 and itself
third: it is T-prime as long as it's sqrt is a prime number except 4
'''
import math
# find all prime no lar... |
"""
Created on Mar 27, 2018
@author: lubo
"""
import pytest
import numpy as np
from dae.utils.regions import Region
@pytest.mark.parametrize(
"region,worst_effect",
[
(Region("1", 878109, 878109), ("missense", "missense")),
(Region("1", 901921, 901921), ("synonymous", "missense")),
(... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
import random
import cv2
import numpy as np
'''
COCO order:
0: "nose",
1: "left_eye",
2: "right_eye",
3: "left_ear",
4: "right_ear",
5: "left_shoulder",
6: "right_shoulder",
7: "left_elbow",
8: "right_elbow",
9: "left_wrist",
10: "right_wrist",
11: "left_hip"... |
import os
import flanautils
os.environ |= flanautils.find_environment_variables('../.env')
import sys
import uvicorn
from fastapi import FastAPI
import flanaapis.geolocation.routes
import flanaapis.scraping.routes
import flanaapis.weather.routes
sub_app = FastAPI()
sub_app.include_router(flanaapis.geolocation.rou... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Module
from typing import Tuple
from ProcessData.NormData import norm_feature
from ProcessData.NormData import *
class LSTMCell(nn.Module):
def __init__(self, input_size, hidden_size):
super(LSTMCell, self).__init__(... |
from math import ceil
from ea import individual, musicPlayer, modelTrainer, initialisation, crossover, mutation, fitness, selection, \
constants, metrics, modelUpdater
from ea.individual import Individual
import random
import time
import sys
class Simulation:
pitch_matrix = None
backoff_matrix = None
... |
import unittest
from c_largest_prime_factor import *
class TestLargestPrimeFactor(unittest.TestCase):
def test_problem_statement(self):
self.assertEqual(29, solve(13195))
def test_given(self):
self.assertEqual(5, solve(10))
self.assertEqual(17, solve(17))
def test_one(self):
... |
from bubble_sort import Solution
example = Solution()
def test_single_sort_c1():
assert example.single_sort([4, 3, 2, 1], 4) == [3, 2, 1, 4]
def test_single_sort_c2():
assert example.single_sort([2, 4, 3, 1], 4) == [2, 3, 1, 4]
def test_single_sort_c3():
assert example.single_sort([3, 1, 2, 4], 4) == [1... |
import os
import json
import time
import datetime
from flask import Flask
from flask_redis import FlaskRedis
import requests
from .twilio_utils import send_runair_sms
# See .env.example for required environment variables
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
app.config['REDIS_URL'] = o... |
# Generated by Django 3.2.6 on 2021-08-08 10:11
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0003_auto_2021080... |
from starlette.testclient import TestClient
from app.main import app
def test_home():
client = TestClient(app)
r = client.get('/')
assert r.status_code == 200
|
import timeit
import numpy as np
from psyneulink import *
from gym_forager.envs.forager_env import ForagerEnv
# Runtime Switches:
RENDER = False
PNL_COMPILE = False
PERCEPTUAL_DISTORT = False
RUN = False
SHOW_GRAPH = True
# ********************************************************************************************... |
"""Package for image processing."""
from .segmentation import *
__author__ = 'Seu Sim'
__email__ = 'shsim@caltech.edu'
__version__ = '0.0.1'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.