text stringlengths 8 6.05M |
|---|
import mock
import unittest
import numpy
from six.moves import cPickle
from smqtk.representation.descriptor_element.local_elements import \
DescriptorFileElement
class TestDescriptorFileElement (unittest.TestCase):
def test_configuration1(self):
default_config = DescriptorFileElement.get_default_co... |
import os
import re
import sys
# All regular expressions to look for
PUB_IP = re.compile(r'(\d+)(?<!10)\.(\d+)(?<!192\.168)(?<!172\.(1[6-9]|2\d|3[0-1]))(?<!100\.64)\.(\d+)\.(\d+)')
LOCAL_IP = re.compile(r'\d+.\d+.\d+.\d+')
# Which folders to ignore
IGNORED_FOLDERS = ['.\.git']
ALL_RESULTS = {}
def get_parsers():
... |
from fenics import *
from pandas import DataFrame
import numpy as np
set_log_active(False)
def solve_system(N, degree_V, degree_Q, file_dump=False):
mesh = UnitSquareMesh(N, N)
# Create mixed element space
V = VectorElement("Lagrange", mesh.ufl_cell(), degree_V)
Q = FiniteElement("Lagrange", mesh.u... |
# Generated by Django 3.0.3 on 2020-03-04 17:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main_app', '0002_auto_20200301_1655'),
]
operations = [
migrations.CreateModel(
name='Membre',
fields=[
... |
import pytest
def fun(x):
if not isinstance(x, int):
raise TypeError('x不是数字')
elif x != 100:
raise ValueError('x值不对')
def test_raises():
with pytest.raises(ValueError) as e:
fun(101)
exec_msg = e.value.args[0]
print(exec_msg)
assert exec_msg == 'x值不对'
|
list= [1,3,5,7,9]
length= len(list)
for i in range(length):
print(list[i])
|
import sys
import urllib2
def Management_Transit(conf,inputs,outputs):
start_point = inputs["StartPoint"]["value"]
start_time = inputs["StartTime"]["value"]
walking_time_period = inputs["WalkingTimePeriod"]["value"]
walking_speed = inputs["WalkingSpeed"]["value"]
bus_waiting_time = inputs["BusWaitingTime"]["valu... |
def sieve (n):
num_dict = dict([num,True] for num in xrange(1,n+1))
for i in xrange(2, int(n**.5) + 1 ):
if num_dict [i]:
for j in xrange(i*2,n+1,i):
num_dict[j] = False
return [i for i in xrange(1,n+1) if num_dict[i]]
while True:
num = raw_input ("Enter a number or end to quit: ")
try:
int(num)... |
#
# Assignment 4
#
# Student Name : Aausuman Deep
# Student Number : 119220605
#
# Assignment Creation Date : February 22, 2020
import docx
import pyexcel
import os.path
def analyze(docfile):
# This function creates an excel file with word frequencies of the desired document file
doc = docx.Document(docfile)
... |
import networkx as nx
import numpy as np
def skelToLength(vertices, edges, res = [1,1,1]):
"""
Returns cable length of connected skeleton vertices in the same
metric that this volume uses (typically nanometers).
"""
if vertices.shape[0] == 0:
return 0
v1 = vertices[edges[:,0]]
v2 = ... |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import csv
import datetime
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("https://news.qq... |
# -*- coding: utf-8 -*-
# Module author: Official Repo, @GovnoCodules
import logging
from .. import loader, utils
import telethon
import io
from telethon.errors.rpcerrorlist import MessageNotModifiedError
import asyncio
logger = logging.getLogger(__name__)
@loader.tds
class TextEditorMod(loader.Module):
"""Tex... |
import re
from urllib import request
from argparse import ArgumentParser
from sys import exit
import os
class ThreadDownloader:
def __init__(self, lnk, path):
try:
self.page = request.urlopen(lnk).read().decode("utf-8")
except request.HTTPError as e:
print(str(e))
... |
from flask import flash, render_template, redirect, request
from flask_mail import Mail, Message
from app import app
from .forms import RequestForm
import uuid
import bdb_scraper
mail = Mail(app)
@app.route('/', methods=['GET', 'POST'])
def req():
form = RequestForm()
if form.validate_on_submit():
re... |
from spack import *
import sys,os
sys.path.append(os.path.join(os.path.dirname(__file__), '../../common'))
from scrampackage import write_scram_toolfile
class TauolaToolfile(Package):
url = 'file://' + os.path.dirname(__file__) + '/../../common/junk.xml'
version('1.0', '68841b7dcbd130afd7d236afe8fd5b949f0176... |
'''
Created on Apr 8, 2012
@author: bogdan
'''
import FinVol_2D_Conv_Diff
import LidCavity
import numpy
#import the TDMA module
from thomas import *
import linalg
# Create a mesh class that holds a vector of nodes
class SIMPLE(object):
'''
classdocs
The NS equation is solved for Fi = u and Fi =... |
#!/usr/bin/env python
"""
"""
import os
from collections import defaultdict
import ujson as json
from util import liblogger
import math
using_cache = bool(os.environ["using_cache"])
cooc_dict_file = os.environ["cooc_dict_file"]
weighted_cooc_dict_file = os.environ["weighted_cooc_dict_file"]
lex_count_file = os.envi... |
#!/usr/bin/env python2
import os
import ConfigParser
import time
import subprocess
import readline
class color:
HEADER = '\033[95m'
IMPORTANT = '\33[35m'
NOTICE = '\033[33m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
RED = '\033[91m'
WHITE = '\033[37m'
END = '\03... |
import os, shutil
from glob import glob
# Option Values
file_path = "D:\python_test"
new_file_path='D:\python_test\\test'
file_count_limit = 1
# Check if a variable is Int type or not
def is_int(var):
try:
int(var)
return True
except Exception:
return False
# Go to files directory an... |
# МЦ с погл-м состоянием (3 состояния).
# Путём моделирования и расчёта вычислить среднее время дост-я полглащ. сост.
# Сделать теоретический расчёт. Решить систему уравнений с f с помощью матричного способа.
# 19/02/18. СЛУ
from random import *
def show_matrix(matrix, name):
if name == 1:
print("М... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import time
import subprocess
import locale
import codecs
import os
import multiprocessing
# import FileRW
import socket, sys
from adbExtend import adbExtend
import xml.sax
# import xml.dom.minidom
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import parse
... |
# script_version=1
# %%
try:
import pykefcontrol as pkf
import sys
import socket
from rich import print
from rich.console import Console
import ipaddress
import time
import requests
except Exception as e:
print("Error:", e, style="red")
print("Please install the required packages... |
#encoding:utf-8
import smtplib
import os
from email.mime.text import MIMEText # MIMEText()定义邮件正文
from email.header import Header # Header()定义邮件标题
report=os.path.join(os.path.dirname(__file__),'result_report.html')
# 发送邮箱服务器
smtpserver = 'smtp.exmail.qq.com'
# 发送邮箱用户/密码(登录邮箱操作)
user = "mengdebin@shaoziketang.com"
pas... |
import os
import sys
import curses
import time
class Console:
def __init__(self, board):
self.__board = board
pass
def run(self):
my_window = curses.initscr()
while True:
self.__board.update_board()
my_window.refresh()
time.sleep(1)
|
import numpy as np
import os
import nibabel as nib
import re
import warnings
from os.path import join as jph
# --- text-files utils ---
def unique_words_in_string(in_string):
ulist = []
[ulist.append(s) for s in in_string.split() if s not in ulist]
return ulist[0]
def indians_file_parser(s, sh=None):
... |
# File: p (Python 2.4)
from direct.distributed.DistributedObjectGlobal import DistributedObjectGlobal
class AwardMaker(DistributedObjectGlobal):
pass
|
from flask.ext.socketio import emit
from uuid import uuid4
from .. import socketio
@socketio.on('unsplash')
def unsplash():
url = 'https://source.unsplash.com/random?t=%s' % uuid4().hex
emit('image', {'url': url})
|
#-*- coding: utf-8 -*-
from django.contrib import admin
from models import Cliente, Pedido, Produto, Recebimento, Remessa, ItemPedido
tiny_mce_js = [
'/static/grappelli/tinymce/jscripts/tiny_mce/tiny_mce.js',
'/static/grappelli/tinymce_setup/tinymce_setup.js',
]
class ProdutoAdmin(admin.ModelAdmin):
list... |
x=5
y="Rajeev"
print(type(x))
print(type(y)) |
<<<<<<< HEAD
x = 1
print(x)
x = x+10
print(x)
=======
x = 1
print(x)
x = x+10
print(x)
>>>>>>> 48c87e4df57a1d3ad60f3bceb45f0d38faf9cd9b
exit() |
import math, random, util
class RadioNetwork():# (x,y)(x,y)
"""ToDo"""
NUM_BITS = 5 # 11
limit_area = 2 ** NUM_BITS # 2048
fitness = 0.2 # 80% ?
covered_area = 0.8 # 80%
covered_bs = 2
amount_bs = int(math.ceil(((limit_area**2) * covered_area) / (math.pi * (covered_bs**2))))
def num_b... |
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError, UserError, Warning
class ProductTemplateEmployee(models.Model):
_name = 'product.template.employee'
product_template_id = fields.Many2one('product.template','Product')
employee_id = fields.Many2one('hr.employee','Employe... |
from alchemyapi import AlchemyAPI
import json
import numpy as np
import matplotlib.pyplot as plt
from operator import itemgetter
alchemyapi = AlchemyAPI()
import random
#classData = pickle.load(open("reviewClassifier.p", "rb", -1))
#def classifyGame(game):
# myClassifier = Classifier()
# return... |
import random
def accountNumberCreate():
#Variables
minRandom = 1000000000000000
maxRandom = 9999999999999999
countryCode = "PL"
tCheckSum = "00"
bankNumber = "2500000"
CheckSumOfBankNumber=0
for i in bankNumber:
CheckSumOfBankNumber += int(i)
bankNumberFull = bankNumber+st... |
from utils import *
import math
def min_dist(x0,y0,x1,y1,dimx,dimy):
points = [(x1+dimx*i,y1+dimy*j) for i in [-1,0,1] for j in [-1,0,1]]
min_dist = -1
for point in points:
dist = math.sqrt((x0-point[0])**2+(y0-point[1])**2)
if (min_dist < 0 or dist < min_dist):
min_dist = dist
return min_dist
... |
from .base import EntityRef
from .exchange_ref import ExchangeRef
class MultipleReferences(Exception):
pass
class NoReference(Exception):
pass
class ProcessRef(EntityRef):
"""
Processes can lookup:
"""
_etype = 'process'
_ref_field = 'referenceExchange'
@property
def _addl(sel... |
# ****************************************************************** #
# *********************** <<Byte of Python>> *********************** #
# ****************************************************************** #
########################
# if
########################
# number = 23
# guess = int(input("Enter an... |
'''
Tensorflow - Neural Network
'''
import tensorflow as tf
import numpy as np
# XOR 문제
x_data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.float32)
y_data = np.array([[0], [1], [1], [0]], dtype=np.float32)
X = tf.placeholder(tf.float32, shape=[None, 2])
Y = tf.placeholder(tf.float32, shape=[None, 1])
# la... |
# coding:utf-8
import pandas as pd
import numpy as np
import datetime
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVR
import ShortTermPredict as STP
import matplotlib.pyplot as plt
import math
from sklearn.metrics import mean_absolute_error,mean_squared_error,r2_score
test_dt = '20141229'
... |
class Servo:
def __init__(self, ser):
self.last_sent = {"finger":0, "thumb":0, "under":180}
self.servo_table = {"finger":0, "thumb":1, "under":2}
self.ser = ser
def add_zeros_to_int(self, int_val):
if(len(str(int_val)) == 1):
return "00" + str(int_val)
elif(len(str(int_val)) == 2):
return "0" + str(i... |
#this one is imported for mobile
from appium import webdriver
from time import sleep
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
#this one is not used for mobile
import time, requests
from selenium... |
#Decision Tree Regression
#Regression Template
#Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing the DataSet
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values
"""
#Spliting the Datase into The Training ... |
"""
Run the nested cross-validation for the NMTF class, on the Sanger dataset.
Since we want to find co-clusters of significantly higher/lower drug sensitivity
values, we should use the unstandardised Sanger dataset.
"""
import sys
sys.path.append("/home/tab43/Documents/Projects/libraries/")#("/home/thomas/Documenten... |
# creating a bot
import discord
from discord.ext import commands
from discord import colour
import youtube_dl
import os
# creating a command
client = commands.Bot(command_prefix='-')
@client.command(name='version')
async def version(context):
myEmbed = discord.Embed(
title="Current version", description... |
import unittest
from katas.kyu_8.find_the_slope import find_slope
class FindSlopeTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(find_slope([19, 3, 20, 3]), '0')
def test_equals_2(self):
self.assertEqual(find_slope([-7, 2, -7, 4]), 'undefined')
def test_equals_3(sel... |
import unittest, logging, copy
from pyfiles import characterController, playerController
from pyfiles.model import characterClass
from pony.orm import db_session
TEST_SESSIONID = 12345678
TEST_USERNAME = 'foo'
TEST_CHARNAME = 'Woody'
TEST_CHARCLASS = characterClass.CharacterClass.Fighter
DEFAULT_SCORES = {'Strength'... |
import cv2
image = cv2.imread("./boxing-fisheye/00000.jpg",1)
imagegt = cv2.imread("./boxing-fisheye/00000.png",1)
imageinfo = image.shape
imagegtinfo = imagegt.shape
print("imageinfo:",imageinfo)
print("imageftinfo:",imagegtinfo)
height = imageinfo[0]
width = imageinfo[1]
channel = imageinfo[2]
dstheight = int(heigh... |
'''
Candidate ordering by TSP Optimization
Code adopted from:
https://mlrose.readthedocs.io/en/stable/source/tutorial2.html
'''
import os
import numpy as np
import mlrose
from .df_utils import load, write
def mat2tuples(mat):
# assumes mat as dense matrix
# extracts lower-triangular elements
L = []
n... |
# Day 8: Handhelp Halting
# <ryc> 2021
def inputdata():
stream = open('day_08_2020.input')
program = [ line for line in stream ]
stream.close()
return program
def processing(program):
accumulator = 0
pointer = 0
exit = False
while pointer < len(program) and not exit:
instructio... |
# -*- coding: utf-8 -*-
import dgl
import time
import torch as th
import numpy as np
import matplotlib.pyplot as plt
from src.utils import *
from sklearn.metrics import roc_auc_score, roc_curve
from sklearn.metrics import average_precision_score, precision_recall_curve
from sklearn.model_selection import train_test_s... |
import sys
from src.crawler import Crawler
if __name__== "__main__":
crawler = Crawler([url for url in sys.stdin])
crawler.crawl()
|
import pandas as pd
import plotly_express as px
line1 = pd.read_csv("data.csv")
graph = px.scatter(line1, x="Population", y="InternetUsers", color ="Country", size="Percentage", title="Population VS Internet Users")
print("Adios!")
graph.show() |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 27 21:15:04 2018
@author: Iswariya Manivannan
"""
import sys
import os
from collections import deque
from helper import maze_map_to_tree, write_to_file, assign_character_for_nodes
from helper import start_pose, print_maze, clear_screen
import time
... |
#!/usr/bin/env python3
"""
usage : unzip unFichierZippé.zip
Un exemple simple de scripting en ligne de commande.
Prend en argument le nom d'une archive zippée (fichier.zip).
Extrait les fichiers et les sauvegarde dans des sous-répertoires
par nom d'extension.
"""
# import des modules et fonction... |
from os import urandom
import hashlib
import hmac
from epqcrypto.persistence import save_data, load_data
def hash_password(password, iterations, algorithm="pbkdf2hmac", sub_algorithm="sha512",
salt=None, salt_size=16, output_size=32):
salt = urandom(salt_size)
heade... |
# Generated by Django 3.0.1 on 2019-12-21 09:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cat', '0006_auto_20191221_1647'),
]
operations = [
migrations.AlterField(
model_name='catphoto',
name='photo',
... |
command script import {YOUR_PATH}/ignore_exception.py
|
import os
import psycopg2
from dotenv import load_dotenv
load_dotenv()
DATABASE_URL = os.getenv('DATABASE_URL')
def get_db_connection():
if os.getenv('ENVIRONMENT') == 'LOCAL':
conn = psycopg2.connect(os.getenv('POSTGRES_CONN_DETAIL'))
else:
conn = psycopg2.connect(DATABASE_URL, sslmode='req... |
import unittest
from collections import defaultdict
import torch
import torchvision.transforms as transforms
from sampler import PKSampler
from torch.utils.data import DataLoader
from torchvision.datasets import FakeData
class Tester(unittest.TestCase):
def test_pksampler(self):
p, k = 16, 4
# E... |
def evaluationFunction(gameState):
|
from settings import settings
from office365.sharepoint.client_context import ClientContext
ctx = ClientContext(settings["url"]).with_user_credentials(settings.get('user_credentials').get('username'),
settings.get('user_credentials').get('password'))
web = c... |
#coding:utf-8
import numpy as np
import matplotlib.pyplot as plt
import sys
import tensorflow as tf
N = 100
K = 3
D = 2
def createData():
X = np.zeros((N * K, D),dtype=float)
Y = np.zeros(N * K, dtype=float)
for k in range(K):
idx = range(N * k, N * (k + 1))
r = np.linspace(0.0, 1.0, N)
... |
import numpy as np
def coin_tosses(n=10, p=0.5):
total = sum(np.random.choice(np.arange(2), size=10, p=[p, 1 - p]))
if total == n:
return 1
else:
return 0
bag = ["F" for i in range(99)] + ["UF"]
a = 0 # number of times we see 10 heads in a row and coin was unfair
b = 0 # number of tim... |
data = [4, 10, 4, 1, 8, 4, 9, 14, 5, 1, 14, 15, 0, 15, 3, 5]
data1 = [0, 2, 7, 0]
def reallocate(data):
j = 0
maxBlock = max(data)
for i in range(0, len(data)):
if data[i] == maxBlock:
data[i] = 0
j = i + 1
break
while maxBlock > 0:
if j > len(data)... |
from django.http import Http404
class Post() :
POSTS = [
{'id':1, 'title': 'First post', 'body':'This is my first post'},
{'id':2, 'title': 'Second post', 'body':'This is my second post'},
{'id':3, 'title': 'Third post', 'body':'This is my Third post'},
]
@classmethod
def all(cls) :
return cls.POSTS
... |
import numpy
import pandas
import random
from pymatgen.core.structure import Structure
from sklearn.svm import SVR
from sklearn.preprocessing import scale
import util.crystal_conv as cc
list_crys = list()
id_target = numpy.array(pandas.read_csv('../data/crystal/nlhm/id_target.csv'))
num_train_ins = int(id_target.shap... |
"""
Creates a NIR image from .jpg upload by filtering out the blue bands.
Provides a custom bar to help users understand healthiness of plant.
"""
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_web_app.settings')
import warnings
warnings.filterwarnings('ignore')
from django.core.files.images import I... |
#!/usr/bin/python3
#minimalist python pe library
import sys
import argparse
import struct
from Utils import spaces
import DOSHeader
import DOSHeaderDecoder
import PEHeaderDecoder
class PEHeader:
__PEHeaderMachineTypes_dict = {\
0x0 :["IMAGE_FILE_MACHINE_UNKNOWN ","The contents of this field are assumed to be ap... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Dusan Klinec, ph4r05
import os
import ctypes as ct
from trezor_crypto import trezor_ctypes as tt
from trezor_crypto import mod_base
# Loaded library instance
CLIB = None
def open_lib(lib_path=None, try_env=False, no_init=False):
"""
Opens the library
... |
class Atom:
def __init__(self, neg, literal):
self.negated = neg
self.literal = literal
def neg(self):
return Atom(not self.negated, self.literal)
def contrary(self, atom):
return self.neg() == atom
def __hash__(self):
return hash((self.negated, self.literal))
... |
class Solution:
def longestPalindrome(self, words: List[str]) -> int:
dp = [[0]*2 for _ in range(20000)]
for s in words:
temp = ord(s[0])*100 + ord(s[1])
temp2 = ord(s[1])*100 + ord(s[0])
if s[0] == s[1]:
dp[temp][0] += 1
dp[temp][1... |
"""
Crear un programa que cambie todas las 'A' o 'a' por la strin 'VACA' de una string introducida por el usuario
"""
string_usuario=input("Escribe una frase: ")
mi_string="VACA"
frase_final=""
contador=0
for caracter in string_usuario:
if caracter == "a" or caracter == "A":
frase_final+=mi_string
els... |
import json
import csv
import boto3
iam = boto3.client("iam")
marker = None
field = ['UserName', 'Effect', 'Action', 'NotAction', 'Resource', 'Condition', 'Permission Source']
row = []
paginator = iam.get_paginator('list_users')
response_iterator = paginator.paginate( PaginationConfig={'PageSize': 1000,'StartingTo... |
from chaban.utils import MetaSingleton
class _Helper(metaclass=MetaSingleton):
def __init__(self, a):
self.a = a
def test_attrs():
x = _Helper(1)
y = _Helper(2)
assert x.a == y.a == 1
def test_is():
x = _Helper(1)
y = _Helper(2)
assert x is y
|
f = open("restricted_foods.csv").read()
f = f.lower()
lines = f.split('\n')
header = lines[0]
content = lines[1:]
del f
del lines
headers = [h.strip() for h in header.split(',')]
#print(headers)
c = []
for line in content:
aux = [i.strip() for i in line.split(',')]
assert(len(aux) == 19)
c.append(aux)
'''
is_fru... |
from django.http import HttpResponse
from django.shortcuts import render
import operator
def home(requests):
return render(requests,'wcount/home.html')
def me(requests):
return render(requests,'wcount/me.html')
def hobies(requests):
return HttpResponse('<h1>Playing badminton, Listening to Music.</h1>')
# C... |
from xlwt import Workbook
from tkinter.filedialog import asksaveasfile
wb_obj = Workbook()
my_sheet = wb_obj.add_sheet('Imdb')
my_sheet.write(0, 0, 'Title')
my_sheet.write(1, 0, 'Joker')
my_sheet.write(2, 0, 'Interstellar')
my_sheet.write(3, 0, 'Inception')
my_sheet.write(4, 0, 'Avengers Endgame')
f = asksaveasfile... |
# encoding: utf-8
import matplotlib as mpl
import matplotlib.pyplot as plt
import os
from natsort import natsorted, ns
import numpy
import re
import xlsxwriter
def start():
directory = 'result_exe1/'
arq = os.listdir(directory)
arquivosDiretorio = natsorted(arq, alg=ns.IGNORECASE) #ordena arquivos para plot
size =... |
#리스트안의 데이터를 요소라고 부를게요!
print("===요소 수정===")
a = [1, 2, 3]
a[1] = 22
print(a)
#리스트는 슬라이싱과 인덱싱의 연산결과가 다릅니다.
a = [1, 2, 3]
a[1:2] = ["a", "b", "c"]
print(a)
a = [1, 2, 3]
a[1] = ["a", "b", "c"]
print(a)
print("\n===요소 삭제===")
a = [1, 2, 3, 4, 5]
a[1:3] = []
print(a)
a = [1, 2, 3, 4, 5]
a[1] = []
... |
"""
This module implements training and evaluation of a multi-layer perceptron in PyTorch.
You should fill in code into indicated sections.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import numpy as np
import os
from mlp_pytorch impo... |
# %% imports
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
plt.ion()
import sys
import time
import pathlib
import numpy as np
import pandas as pd
import scipy.io.wavfile
import libtiff
_code_git_version="11d174e8861127a6b334e9795795573452655401"
_code_repository="https://git... |
import unittest
from katas.kyu_6.iq_test import iq_test
class IQTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(iq_test('2 4 7 8 10'), 3)
def test_equals_2(self):
self.assertEqual(iq_test('1 2 1 1'), 2)
def test_equals_3(self):
self.assertEqual(iq_test('1 2 ... |
from flask import Flask, render_template, request, Markup
import sqlite3 as sql
from flask import flash, redirect, session, abort
from datetime import date, datetime
app = Flask(__name__)
app.secret_key = "super secret key"
@app.route('/')
def home():
if not session.get('logged_in'):
return render_t... |
#!/Users/duffrind/miniconda3/bin/python
from app import app
app.run(debug=True)
#if __name__ == '__main__':
# app.run(debug=True)
|
from _typeshed import Incomplete
from collections.abc import Generator
def graph_edit_distance(
G1,
G2,
node_match: Incomplete | None = None,
edge_match: Incomplete | None = None,
node_subst_cost: Incomplete | None = None,
node_del_cost: Incomplete | None = None,
node_ins_cost: Incomplete |... |
import pandas as pd
import numpy as np
import datetime
import lightgbm as lgb
from sklearn.metrics import f1_score
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
from sklearn.model_selection import StratifiedKFold
pd.set_option('display.max_columns', None)
df_t... |
#!/bin/env python
# Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... |
from django.shortcuts import render
def home(request):
return render(request, 'accounts/login.html', name = 'login')
def signup(request):
return render(request, 'accounts/signup.html', name= 'signtup') |
import numpy as np
from prettytable import PrettyTable
UNIFORM_FRONT = np.sqrt(3)
TESTS_NUM = 1000
TRUNCATION = 0.25
POISSON_PARAM = 3
def generate_laplace(x):
return np.random.laplace(0, 1 / np.sqrt(3), x)
def generate_uniform(x):
return np.random.uniform(-UNIFORM_FRONT, UNIFORM_FRONT, x)
def generate_p... |
#!/usr/bin/env python3
# Copyright 2016 The Dart project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import os
import platform
import subprocess
import sys
import time
import utils
HOST_OS = utils.GuessOS()
HOST_AR... |
import numpy as np
import cv2
from decimal import *
from matplotlib import pyplot as plt
from sklearn.svm import SVC
from sklearn import cross_validation
from sklearn import datasets, neighbors, linear_model
from sklearn.preprocessing import MinMaxScaler, Normalizer
from sklearn.decomposition import PCA as sklearnPCA, ... |
import warnings
from functools import partial
from typing import Any, List, Optional, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from torchvision.models import inception as inception_module
from torchvision.models.inception import Inception_V3_Weights, InceptionOu... |
# import necessary libraries
import plotly
import plotly.graph_objs as go
import plotly.io as pio
import numpy as np
import pandas as pd
# define function to calculate time given time and distance
def calculate_time(speed, distance):
# test and catch errors
try:
# convert parameter values to float
s = floa... |
from google.cloud import bigquery
# Create a "Client" object
client = bigquery.Client()
# construct a reference to the dataset. The project name is "bigquery-public-data", the name of the dataset is "stackoverflow"
dataset_ref = client.dataset("stackoverflow", project="bigquery-public-data")
# API request... |
import myLib
import matplotlib.pyplot as plt
import datetime
import time
import csv
import threading
import numpy as np
class HordePlotter:
horde = None
gvfList = []
graphSpan = 100 # width of plot
graphSpanL = 900 # width of large plot
currentAngle = 0.0
currentLoad = 0.0
currentTempera... |
#!/usr/bin/env python
"""
::
LV=box abprofile.py
LV=box python2.7 abprofile.py
ip abprofile.py --cat cvd_1_rtx_0_1M --pfx scan-pf-0 --tag 0
OKG4Test run
"""
from __future__ import print_function
import os, sys, logging, numpy as np
log = logging.getLogger(__name__)
from opticks.ana.profi... |
from torchfly_dev.training.checkpointer.advanced_checkpointer import AdavancedCheckpointer
import time
import os
# class Net(nn.Module):
# def __init__(self):
# super().__init__()
# self.model = nn.Sequential( nn.Linear(5000,4000) )
# def forward(self):
# return 0
net = {"weights": 0, "bias":0}
saver ... |
# -*- coding: utf-8 -*-
from typing import List
class Solution:
def sumBase(self, n: int, k: int) -> int:
return sum(self.toBaseK(n, k))
def toBaseK(self, n: int, k: int) -> List[int]:
digits = []
while n:
digits.append(n % k)
n //= k
return digits
i... |
import maya.cmds as cmds
def ChangeSuffix(sufx):
print 'Suffix is now' + sufx
def windowCreator():
#get user parameters via window
if (cmds.window('Renaming', exists=True)): cmds.deleteUI('Renaming')
Renaming = cmds.window('Renaming')
colLayout = cmds.columnLayout(parent=Renaming, adj... |
from django.urls import path
from . import views
urlpatterns=[
path('',views.InformacioneListView.as_view(),name='Naruto'),
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.