text stringlengths 38 1.54M |
|---|
from django.test import TestCase
# from moviesapp.models import Movie
from django.urls import reverse
class MovieListView(TestCase):
def test_view_url_exists_at_desired_location(self):
resp = self.client.get('/Movies/')
self.assertEqual(resp.status_code, 200)
def test_view_url_by_name(self):... |
from plotly.graph_objs import *
from plotly.offline import plot
import numpy as np
import os
import itertools
from keras.models import load_model, Sequential
from keras.layers import Flatten, MaxPooling2D, Conv2D
from keras.utils import np_utils
from keras.layers.core import Dense, Dropout
from keras.optim... |
SHOW_SEARCH_NUMBER = 10
LIST_ORDER = [('asc','Ascending') , ('desc','Descending')]
LIST_PAGINATE = [('50','50') , ('100','100')]
DEFAULT_INITIAL_PAGE_SIZE = 50
CONV_MGMT_PAGE_SIZE = 20
TEXT_SUFFIX_LENGTH = 3
|
import os
import sys
import argparse
import shutil
from functools import partial
from multiprocessing.dummy import Pool
from subprocess import call
import glob
import math
from sound_utils import*
import getopt
'''
entries = GetEntry()
print len(entries)
render_cmd = []
'''
render_cmd=[]
#cont_entry = open('/data/visio... |
from project import db, bcrypt
from datetime import datetime
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
class BlogPost(db.Model):
__tablename__ = "posts"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String, nullable=False)
description = db.Column(db.String, ... |
#!/usr/bin/env python
from __future__ import print_function
import dns.resolver
import tldextract
import dns.flags
import dns.rcode
import xmlrpclib
import argparse
import random
import json
import time
import sys
import os
import errno
from pprint import pprint
from subprocess import call as subprocess_call
import pyg... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""=================================================
@Project -> File :LeetCode -> Remove Palindromic Subsequences
@IDE :PyCharm
@Author :Wang Ye (Wayne)
@Date :2020/1/26 10:31
@Desc :
=================================================="""
class Solution:
def ... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#===============================================================================
# Written by Rentouch 2012 - http://www.rentouch.ch
#===============================================================================
import os
import shutil
import sys
def install():
#sea... |
# -*- coding = utf-8 -*-
ecc = {
"Afghanistan":"阿富汗",
"Aland Islands":"奥兰群岛",
"Albania":"阿尔巴尼亚",
"Algeria":"阿尔及利亚",
"American Samoa":"美属萨摩亚",
"Andorra":"安道尔",
"Angola":"安哥拉",
"Anguilla":"安圭拉",
"Antigua and Barbuda":"安提瓜和巴布达",
"Argentina":"阿根廷",
"Armenia":"亚美尼亚",
"Aruba":"阿鲁巴",
"Australia":"澳大利亚",
"Austria... |
# -*- coding: utf-8 -*-
import keras_imaging.datasets
def load_data():
"""
Load Ravkin, et al.’s translocation dataset.
Ravkin, et al.’s translocation dataset is a collection of images of
cytoplasm-nucleus translocation of the Forkhead fusion protein (FKHR-EGFP)
in stably transfected human osteo... |
import pymfc
from pymfc import wnd, gdi
class OwnerDrawButton(wnd.Button):
STYLE = wnd.Button.STYLE(ownerdraw=True)
def _prepare(self, kwargs):
super(OwnerDrawButton, self)._prepare(kwargs)
self.msgproc.DRAWITEM = self.onDrawItem
def wndReleased(self):
super(Own... |
import socket
import sys
import getpass
import time
from threading import Thread
import pymongo
import select
import struct
from util import *
from Tkinter import *
import inputGUI
PRIVATE = '-p'
BROADCAST = '-b'
WHOELSE = 'whoelse'
WOISTHERE = 'whoisthere'
LOGOUT = 'logout'
BLOCK = '-block'
UNBLOCK = '-unblock'
isLog... |
import numpy as np
import matplotlib._color_data as mcd
import pandas as pd
import umap
import numpy as np
import seaborn as sns
import matplotlib.pyplot as pyplot
from numpy import array
from sklearn.cluster import DBSCAN
data_file = open("datasets/letter-recognition-visual.data" , "r")
data = []
data_label = []
for ... |
import logging
import sys
import os
import time
import everysk
everysk.api_sid = '<YOUR_ACCOUNT_SID>'
everysk.api_token = '<YOUR_AUTH_TOKEN>'
everysk.verify_ssl_certs = False # Set to True to verify if the server certificate is valid
def test_risk_attribution():
args = {
'projection': ['IND:SPX', 'IND:SX... |
from unittest import TestCase
from spiral.research.visitor.deque_visitor import DequeVisitor
from spiral.research.traverser import Traverser
from tests.research.test_traverser import TestTraverser
class TestDequeVisitor(TestTraverser.Shared, TestCase):
def visitor(self):
return DequeVisitor(self.accumulat... |
# Copyright (c) 2019-2020 Manfred Moitzi
# License: MIT License
import pytest
import ezdxf
from ezdxf.entities.polyline import Polyline
from ezdxf.lldxf.const import DXF12, DXF2000
from ezdxf.lldxf.tagwriter import TagCollector, basic_tags_from_text
from ezdxf.math import Vec3
ENTITY_R12 = """0
POLYLINE
5
0
8
0
66
1... |
# Generated by Django 3.0.8 on 2020-08-07 14:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lms', '0006_lesson_video_id'),
]
operations = [
migrations.AddField(
model_name='lesson',
name='viewed',
... |
from django.db.models import F
from django.http import Http404
from django.shortcuts import render
from django.views.decorators.cache import cache_page
from loginAndreg.models import TotalUser
from common_tools import eightlang_tools
# Create your views here.
# @cache_page(60*15)
@eightlang_tools.add_hobby
def index(r... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-01 02:32
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('event', '0008_remove_event_legislative_body'),
('legislative_body', '0003_remove_legis... |
#!/bin/python3
import sys
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
num = n * (n - 1) if n > 1 else 1
while(True):
stop = True
for i in range(1, n + 1):
if num % i != 0:
stop = False
break
if not stop:
... |
"""
Unit and regression test for the measure module.
"""
# Import package, test suite, and other packages as needed
import molecool
import numpy as np
import pytest
#@pytest.mark.skip
def test_calculate_distance():
"""Test that calculate_distance function calculates what we expect."""
r1 = np.array([0, 0,... |
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.template import loader
from django.urls import reverse
from django.views import generic
from django.utils import timezone
from .models import Choice, Question
# Create your views here... |
import math
def binn(n):
ans = []
while n:
print n, bin(n)
ans.append('1' if n % 2 == 1 else '0')
n = (n >> 1) ^ (1 << 32)
return ''.join(reversed(ans))
for i in xrange(-10, 50):
print binn(i)
|
import os
import platform
import subprocess
import time
host = "127.0.0.1"
port = "30047"
process = None
def windows():
return platform.platform().split("-")[0] == "Windows"
def url(*path, **query):
return "http://%s:%s/%s?%s" % (host, port, "/".join(path), "&".join(["%s=%s" % (key, value) for key, value ... |
import re
def summarizer(article):
summary = "";
pattern = re.compile("[^\w\s']") #removes non-word, non-white space characters
for paragraphDict in article['paragraphs']:
paragraph = paragraphDict['text'].split(".")
keyWords = paragraphDict['keywords']
key_word_counter = {}
... |
"""
Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
"e" => False
".1" => true
"-.4" => true
"3-2" => false
".-4" => false
Note: It is intended for the problem statement to be ambiguous.
You should gather all requirements up front before im... |
#!/usr/bin/python
from chelper import *
import ctypes as C
import warnings
import os
import tempfile
os.environ['MPLCONFIGDIR'] = tempfile.mkdtemp()
import shutil
import multiprocessing
from pylab import *
import sys
from scipy.ndimage.filters import uniform_filter,gaussian_filter
from scipy.ndimage.interpolation impo... |
#-*- coding:utf-8 -*-
import os
if __name__ == '__main__':
path = os.getcwd()
sku_id = '10001'
file = path + os.sep + 'test.txt'
f = open(file, 'w')
for i in range(1, 10):
f.write(sku_id)
f.write('\t')
f.write('2017-01-0{0}'.format(i))
f.write('\t')
f.write(... |
def reverse_list(list):
newlist = []
for i in reversed(list):
newlist.append(i)
return newlist
print reverse_list([1,2,3,4]) |
#!/usr/bin/python3
#
# Read A/D-conversion results from /dev/ttyUSB0, add
# timestamps and store to file.
#
# To allow users access the serial port, use e.g. the following command
#
# sudo adduser $USER dialout
#
# and then log out and log in again for the changes to be effective.
import datetime as dt
import seri... |
import unittest
import numpy as np
from decimal import *
class LinearRegressionTestCase(unittest.TestCase):
"""Test for linear regression project"""
def augmentMatrix(self,A, b):
return [AA + bb for AA, bb in zip(A, b)]
def swapRows(self, M, r1, r2):
M[r1], M[r2] = M[r2], M[r1]
def... |
from pipeline_base import PipelineBlock
import itertools
class AbstractBatchProcessorBlock(PipelineBlock):
def __init__(self, batch_size):
self.batch_size = batch_size
def run(self, input_data):
batches = self._make_batches_from_iter(input_data, self.batch_size)
processed_batches = sel... |
# Title : Find average number of digits in the list
# Author : Kiran raj R.
# Date : 15:10:2020
list1 = [111, 2222333, 444, 1, 44,
66666, 5555, 22222222]
def lengthElem(list_in):
sumDigit = 0
for elem in list_in:
elem = str(elem)
print(f"{elem} contain {len(elem)} digits")
... |
# -*- coding: utf-8 -*-
""" Module ParticleCloud
"""
__project__ = 'Exercise 4'
__module__ = 'ParticleCloud'
__author__ = 'Philipp Lohrer'
__date__ = '14.07.2015'
__version__ = '0.1'
# Standard library imports
from math import pi, sqrt, sin, cos
import bisect
import random
# Local imports
from Exercise4.util im... |
from __future__ import print_function
from graphql import graphql
from graphql.type import (GraphQLArgument,
GraphQLField, GraphQLNonNull, GraphQLObjectType,
GraphQLSchema, GraphQLString,
GraphQLInputObjectType,
Gr... |
#!/usr/bin/env python
from PyQt5 import QtWidgets
import sys
from threading import Thread
import manip_gui, joint_state_publisher, manip_plot
import rospy
import signal
from geometry_msgs.msg import Twist
from sensor_msgs.msg import JointState
rb_order = ('manual', 'twist', 'p2p_direct','p2p_interp','p2p_line','p2p_v... |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
INCLUDES = """
#include <CoreFoundation/CoreFoundation.h>
"""
... |
import pandas as pd
import numpy as np
import datetime
# 读取费率表数据和日期、回款数据
df_fee = pd.read_excel('fees.xlsx',header =2, sheet_name = 'fees')
df = pd.read_excel('fees.xlsx', sheet_name = 'dates')
# 计算计息期间
df['计算期间'] = df['计算日'].diff(1).map(lambda x:x.days)
df['计息期间'] = df['计息日'].diff(1).map(lambda x:x.days)
# 计算增值税及附加
df... |
from manimlib.imports import *
class ScalarApplication(ThreeDScene):
def construct(self):
axes = ThreeDAxes() # creates a 3D Axis
self.add(axes)
axis = TextMobject(r"X",r"Y",r"Z")
axis[0].move_to(6*RIGHT)
axis[1].move_to(6*UP)
axis[2].move_to(np.array([0... |
# -*- coding: utf-8 -*-
# Based on (root)/trunk/xbmc-addons/src/plugin.video.polishtv.live/self.HOSTs/ @ 419 - Wersja 636
###################################################
# LOCAL import
###################################################
from Plugins.Extensions.IPTVPlayer.components.ihost import CHostBase, CDisplay... |
from django import forms
from django.core.exceptions import ValidationError
from webapp.models import Article, Comment, Tag
class ArticleForm(forms.ModelForm):
tags = forms.CharField(max_length=31, required=False, label='Tag')
class Meta:
model = Article
fields = ['title', 'text', 'author', ... |
"""The main entry point for the Airbud application server.
See http://localhost:5000/ for the web interface."""
import airbud.gps
import airbud.rf
import airbud.web
airbud.gps.start()
airbud.rf.start()
airbud.web.start()
airbud.gps.stop()
airbud.rf.stop()
|
import pandas as pd
df_train = pd.read_csv("./titanic_train.csv")
df_train.drop(columns=['Name', 'Ticket', 'Cabin'], inplace=True)
df_train['Age'] = df_train['Age'].fillna(df_train['Age'].mean())
print(pd.get_dummies(df_train['Sex']).head())
onehot_columns = ['Pclass', 'Sex', 'SibSp', 'Parch', 'Embarked']
df_coded... |
import fcntl
import termios
import sys
import os
import datetime
import pytz
jst = pytz.timezone('Asia/Tokyo')
def get_key():
fno = sys.stdin.fileno()
#stdinの端末属性を取得
attr_old = termios.tcgetattr(fno)
# stdinのエコー無効、カノニカルモード無効
attr = termios.tcgetattr(fno)
attr[3] = attr[3] & ~termios.ECHO & ~... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.PaymentSchedule import PaymentSchedule
class AlipayEcapiprodDrawndnPaymentscheduleGetResponse(AlipayResponse):
def __init__(self):
super(AlipayEcapiprodD... |
from turtle import Turtle
# constants
FONT = ("Arial", 8, "bold")
STARTING_COORDINATE_X = 0
STARTING_COORDINATE_Y = 270
ALIGNMENT = "Center"
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.penup()
self.goto(STARTING_COORDINATE_X, STARTING_COORDINATE_Y)
self.h... |
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManage... |
from aetypes import Enum
from datetime import datetime
class TradeType(Enum):
BUY = "buy"
SELL = "sell"
class Trade(object):
def __init__(self, stock_symbol, trade_type, shares_quantity, price):
self.timeStamp = datetime.utcnow()
self.stock_symbol = stock_symbol
if trade_type ... |
import numpy as np
import math as m
def p(x):
#p = x**3 - 8 * x**2 + 20 * x -16
p = 3 * x -m.cos(x) -1
#p = x**3 - 7 * m.exp(-x) + 2
#p = x**4 - x - 4
return p
def dp(x):
#dp = 3 * x**2 -16 * x + 20
dp = 3 + m.sin(x)
#dp = 3 * x**2 + 7 * m.exp(-x)
#dp = 4 * x**3 -1
return dp
def ddp(x):
#ddp = 6 * x -... |
from sklearn import svm
from sklearn.externals import joblib
from extract_dataset_features_svm import load_features_from_npz
import numpy as np
import sys
import os
def test_model(classes, model_dir, feats_dir):
print 'testing'
model_path = os.path.join(model_dir, 'model.pkl')
clf = joblib.load(model_path... |
import sys
import pygame
from pygame.locals import *
from ID import ID
from Handler import Handler
from Player import Player
from Ball import Ball
from StaticObject import StaticObject
from Bricks import Map
import time
import math
def clamp(val, min, max):
if val >= max:
return max
elif val <= mi... |
#coding=utf-8
from test.base.find_element import FindElement
class WorkPage(object):
def __init__(self,driver):
self.fe=FindElement(driver)
#老师
#我的备课按钮
def get_my_work_button(self):
return self.fe.get_element("my_work_bt")
#分享按钮
def get_copy_work_button(self):
return s... |
from django import forms
class CommentForm(forms.Form):
content_type = forms.CharField(widget=forms.HiddenInput)
object_id = forms.IntegerField(widget=forms.HiddenInput)
#parent_id = forms.IntegerField(widget=forms.HiddenInput, required=False)
content = forms.CharField(label='Comment', widget=forms.T... |
from socket import *
from time import *
from datetime import *
serverName = 'localhost'
serverPort = 12000
daysOfWeek = {"Mon": 'M', "Tue": 'T', "Wed": 'W', "Thu": 'R', "Fri": 'F', "Sat": 'S', "Sun": 'U'}
clientSocket = socket(AF_INET, SOCK_DGRAM)
clientSocket.settimeout(1)
for i in range(1, 11):
c... |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np1
def kernel(point,xmat, k):
m,n = np1.shape(xmat)
weights = np1.mat(np1.eye((m)))
for j in range(m):
diff = point - X[j]
weights[j,j] = np1.exp(diff*diff.T/(-2.0*k**2))
return weights
def localWeight(p... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("Demo")
process.load("FWCore.MessageService.MessageLogger_cfi")
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) )
#process.MessageLogger.cerr.FwkReport.reportEvery = 10
process.source = cms.Source("PoolSource",
... |
# Generated by Django 2.1.15 on 2021-05-21 10:12
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('courses', '0003_auto_20210520_1740'),
]
operations = [
migrations.CreateModel(
name='Youtube',... |
import postgresql
class PostgresAdapter:
def __init__(self, uname, database, observatories, delays):
self.__db_connection = postgresql.open(user = uname, database = database)
self.__delays = delays
self.__locations = observatories
self.init_database()
def __del__(self):
... |
class Solution(object):
def permute(self, nums):
if len(nums) == 1 or len(nums) == 0:
return [nums]
allPermutations = [] #list of lists
for i in xrange(len(nums)):
#get all permuations for a list start with a specific number
subList = self.per... |
from __future__ import division
import argparse
import numpy as np
import pickle
import tensorflow as tf
from data_construct import data_construct
import data_gen
import matplotlib.pyplot as plt
# Create model
def multilayer_perceptron(x, weights, biases):
# Hidden layer with RELU activation
layer_1 = tf.add(tf.ma... |
import turtle
s = turtle.Turtle()
s.shape("blank")
wn = turtle.Screen()
wn.bgcolor("#e6e6e6")
s.pensize(5)
wn.setup(width=0.99,height=0.95,startx=None,starty=-10)
# L
s.penup()
s.backward(350)
s.left(90)
s.forward(200)
s.left(180)
s.pendown()
s.forward(200)
s.left(90)
s.forward(120)
s.penup()
s.forward(30)
# A
s.pendo... |
# Main program loop for LiSim simulation
from scipy.special import expit
import numpy as np
import matplotlib.pyplot as plt
import cv2
from cv2 import VideoWriter, VideoWriter_fourcc
import time
import sys
from LeadSim.Lidar import sim
from LeadSim.Lidar import simResultProcess as prc
from LeadSim.Lidar import path_gen... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 12 10:41:06 2016
@author: ngoldbergerr
"""
import sys
from tia.bbg import v3api
import pandas as pd
import xlrd
import os.path
import datetime as dt
import numpy as np
class impliedRate(object):
def __init__(self, path = 'L:\\Rates & FX\\Quant Analysis\\portfolioMa... |
STATUS_OK = "ok"
STATUS_ERROR = "error"
class ChallengeResolutionResultT:
url: str = None
status: int = None
headers: list = None
response: str = None
cookies: list = None
userAgent: str = None
def __init__(self, _dict):
self.__dict__.update(_dict)
class ChallengeResolutionT:
... |
import os
from azureml.core import ComputeTarget, Environment, Workspace
from azureml.core.conda_dependencies import CondaDependencies
from azureml.core.runconfig import RunConfiguration
from azureml.pipeline.core import Pipeline, PipelineData
from azureml.pipeline.steps import PythonScriptStep, EstimatorStep
from azur... |
# Generated by Django 2.2.6 on 2020-02-26 09:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("customers", "0007_make_customer_profile_id_editable"),
]
operations = [
migrations.AlterField(
model_name="customerprofile",
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 24 06:28:20 2018
@author: Admin
"""
from os import listdir
import csv
#filepath = 'C:/Users/tremp/Downloads/LearningZipfian/LearningZipfian'
output_path = './results/'
filename_freq_start = 'word_freq_'
summary_filename = 'summary.txt'
language_codes = ['... |
"""
Code to experiment with different ROMS vertical coordinate parameters.
"""
# setup
import os; import sys
pth = os.path.abspath('../../LiveOcean/alpha')
if pth not in sys.path:
sys.path.append(pth)
import Lfun
Ldir = Lfun.Lstart(gridname='sj0', tag='v0')
# NOTE hmin = 4 in the cas4 grid
import zrfun
from impor... |
def memoization(F):
results = dict()
def wrapper(*args):
k = args
if k in results:
print("caching result for {0}".format(k))
return results[k]
r = F(*args)
results[k] = r
return r
return wrapper
@memoization
def fact(n):
if n == 1:
... |
import datetime
import time
import ccxt
import csv
exchange = ccxt.binance ()
assets = ['BTC', 'ETH', 'XLM', 'CVC']
symbols = [i+'/USDT' for i in assets]
data = exchange.fetch_tickers(symbols)
params = ['ask']
target = 5 # delay target
with open('{}_{}s.csv'.format("-".join(assets), target), 'w') as r:
reader... |
#!/usr/bin/env python
import socket
host = ''
port = 3002
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
client, address = s.accept()
print "We have one"
while 1:
data = client.recv(size)
print 'data: ' + data
client.close()
|
import os
import struct
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
import generate_data as gd
from copy import deepcopy
"""
use eg6
add decay learning_rate
@20190918 the learning rate of adjusting w may matter
# generating ... |
'''
Additional functions for use with arrays in MicroPython to
allow basic, fast linear algebra computations.
The methods were implemented using MicroPython's inline
assembler as per the examples in the online documentation.
The purpose of these methods is to allow vectorization of
calculations using arrays. With mor... |
# Generated from /Users/kietteik/Documents/BKU_Stored/HK1_2020-2021/PPL/Asm1/build/src/main/bkit/parser/BKIT.g4 by ANTLR 4.8
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
from lexererr import *
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a... |
import json
def load_rs_setup():
with open('rs_setup.json') as data_file:
data = json.load(data_file)
cafeteria_tables = data["cafeteria_tables"]
return cafeteria_tables
cafeteria_tables = load_rs_setup()
print ("Hi, this is a cafeteria reservation program!")
print ("This caf... |
from .CSharpLexer import CSharpLexer as Lexer
from .CSharpParser import CSharpParser as Parser
from .CSharpParserVisitor import CSharpParserVisitor as Visitor
|
#!/usr/bin/env python3
"""
function lent5 import tensorflow
"""
import tensorflow as tf
def lenet5(x, y):
"""
Function that builds a modified version of the LeNet-5 architecture using
"""
init_ = tf.contrib.layers.variance_scaling_initializer()
cv_lyr1 = tf.layers.Conv2D(filters=6,
... |
# Generated by Django 3.0.4 on 2020-03-12 19:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0004_userprofile_uri'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='link',
... |
import pytest
from app.calculator import Calculator
class TestCalc:
def setup(self):
self.calc = Calculator
def test_multiply_calculate_correctly(self):
assert self.calc.multiply(self, 0.1, 10) == 1
def test_multiply_calculation_failed(self):
assert self.calc.multiply(sel... |
import pytest
from programs import average_grade
def test_average_grade_high_A():
assert average_grade.grade('Iwan', 25, 50, 100) == (
'Iwan achieved 100%. Final grade: A')
def test_average_grade_low_A():
assert average_grade.grade('Iwan', 18, 35, 70) == (
'Iwan achieved 70%. Final grade: A'... |
from XYDataSetProcessor import XYDataSetFunction
class CentreOfMass(XYDataSetFunction):
def __init__(self, name='com', labelList=('com', 'stddev'), formatString='The COM or centroid was at %f (com) and had a std. dev. of %f (stddev)'):
XYDataSetFunction.__init__(self, name, labelList,'com', formatString)
def _p... |
from math import sqrt
infile = open("FCC.xyz", "r")
outfile = open("FCC.clssy", "w")
cnt = 0
scale = 2.0**(2.0/3.0)
outfile.write( "boxtype cube \n" )
outfile.write( " dimension " + str(8.0*scale) + "\n" )
for line in infile:
try:
col = line.split()
x = (float(col[1]) - 4.0) * scale
y = ... |
import json
import os
import random
import zipfile
from collections import defaultdict
import uuid
import numpy as np
import requests
from PIL import Image
from app import app
from flask import render_template, jsonify, request, send_file, \
Response, redirect, url_for, session, flash
from skimage.transform impor... |
from liquidity.Liquidity import OID, DFC, Liquidity, Debt, OperatingCompany
from datetime import date
import importlib
from reportwriter.ReportWriter import ReportWriter
from scipy.optimize import fsolve
import sys
def lightstone_test():
# balance = 1725000000
# begin_date = date(2017,2,1)
# end_date =... |
from django.conf.urls import url, include
from banking import views
from bank import settings
urlpatterns = [
url(r'^$', views.default, name="index"),
url(r'^auth/$', views.auth, name="auth"),
url(r'^client/$', views.client, name="clien... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Enterprise Management Solution
# GRP Estado Uruguay
# Copyright (C) 2017 Quanam (ATEL SA., Uruguay)
#
# This program is free software: you can redistribute it and/or modify
# it... |
import sys
import math
import unittest
from io import StringIO
from unittest.mock import patch
CARD_LOCATION = {
'ally_hand': 0,
'ally_side': 1,
'ennemy_side': -1
}
class Action:
action_buffer = ''
@classmethod
def pass_turn(cls):
cls.action_buffer += 'PASS;'
@classmethod
de... |
a = 3
b = 5
print(a + b)
print(a * b)
print(a / b)
a = 4
a = a + 1
print(a)
b = 7
b = b - 3
print(b)
a = 4
a += 1
print(a)
b = 7
b -= 3
print(b)
a *= b
print(b)
a /= 10
print(a) |
#OOP
import time
class Person:
has_mouth = True
has_eyes = True
has_shield = False
has_knife = True
strength = 20
line1 = list(" 0 ")
line2 = list(" | ")
line3 = list(" /\ ")
line4 = list("/__|________________")
def __init_... |
# Copyright 2019, University of Illinois at Chicago
# This file is part of the main_finding_recognition project.
# See the ReadMe.txt for licensing information.
import pandas as pd
import csv
from sklearn.svm import SVC
import sys
import os
learning_scores=sys.argv[1]
xmlfile=sys.argv[2]
trainingdata=pd.read_csv('41... |
import random
from Genes import Genes
from DNA import DNA
from Biome import Biome
# Vision things ID system 2 hex digit long (for now)
# 00 - 0A --> Biomes in order ['empty', 'grassland', 'forest', 'jungle', 'savanna',
# 'desert', 'wetland', 'tundra', 'artic', 'reef', 'marine', 'ocean'... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import datasets
from sklearn import decomposition
iris = datasets.load_iris()
X = iris.data
y = iris.target
fig = plt.figure(1, figsize=(6, 5))
ax = Axes3D(fig, elev=48, azim=134)
for name, label in [('Setosa'... |
# Generated by Django 2.1.5 on 2019-02-28 10:14
import dashboard.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USE... |
#!/usr/local/anaconda3/bin/python3.9
###!/usr/bin/python3
import pandas as pd
import numpy as np
import sys
import os
import pwd
import re
uname = pwd.getpwuid(os.getuid()).pw_name
sys.path.append('/work/'+uname+ '/project/zlib/')
#from zutils import get_prev_business_date, get_business_date_list
from zutils_p39 impor... |
#!/usr/bin/env python
"""
Author: Kaali
Dated: 9 march, 2015
Purpose: This module deals with the clustering of the noun phrases, Evverything it uses are heuristic rules because
till now i am unable to find any good clutering algorithms which suits our needs.
"""
from sklearn.feature_extraction.text import TfidfVectori... |
# Generated by Django 3.2.7 on 2021-10-03 15:23
import datetime
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration... |
from ._ComponentWiseCartesianDifference import *
from ._GraspList import *
from ._GripperCommand import *
from ._JointDistance import *
from ._JointSpaceWayPointsList import *
from ._SphericalSamplerParameters import *
|
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from add_features import add_doc2vec, add_tf_idf
from get_data import get_data_as_dataframe
from cleanse_data import clean_text
from get_sentiments import get_sentiments
from sklearn.model_selection import train_tes... |
from flask import Flask
from flask import request
from sklearn import datasets, svm
from PIL import Image
from numpy import array
import csv
from pprint import pformat
from io import BytesIO
from urllib.request import urlopen
mine = True
train = False
if mine:
digits = []
with open('numbers.csv', newline=''... |
import os
from rocket import Rocket
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, World!"
if __name__ == "__main__":
Rocket((os.environ.get('ADDRESS', '0.0.0.0'), int(os.environ.get('PORT', 9000))), 'wsgi', {'wsgi_app': app}).start() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.