text stringlengths 8 6.05M |
|---|
import numpy as np
x_train = [
[1,2,3,4,5,None, None, None, 9, 10, 11],
[2,3,4,5,6, None, None, None, 10, 11, 12],
[50,51,52,53,54, None, None, None, 58, 59, 60]]
y_train = [[6, 7, 8], [7,8,9], [55, 56, 57]]
x_test = [[35,36,37,38,39, None, None, None, 43, 44, 45]]
x_train = np.array(x_train)
y_train = n... |
from PyQt5.QtCore import Qt
from PyQt5.QtCore import QRect, QPoint
from PyQt5.QtGui import QBrush
class TextBox (QRect):
def __init__(self, parent, border=False, width=10, height=10, text=""):
super(TextBox, self).__init__()
self.parent = parent
self.setText(text)
self.border = border
def setText(self,... |
from django.db.models import Q
from django.shortcuts import render
from service.models import Service
from forum.models import Topic, Post
def search(request):
zapros = request.GET.get('zapros')
service_search = Service.objects.filter(
Q(title__contains=zapros) |
... |
#!/usr/bin/python
##
# Example builind script
# @author : Devresse Adrien
# @version : v0.2
# @date 21/03/2011
Import('*') # import SConstruct exported var
import os
import random
import shutil
import commands
src = ['example/gfal_testrw.c']
src2 = ['example/gfal_testread.c']
src3 = ['example/gfal_testdir.c']
src4 = ... |
# Distance traveled
# Calculation for traveled distance
# Anatoli Penev
# 27.10.1017
car_speed = 60 # the speed the car is moving in miles
time1 = 5 # 5 hours of travel time
time2 = 8 # 8 hours of travel time
time3 = 12 # 12 hours of travel time
distance1 = car_speed*time1 # calculate distance traveled for 5 hour... |
# -*- coding: utf-8 -*-
class Solution:
def search(self, nums, target):
first, last = 0, len(nums) - 1
while first <= last:
mid = (first + last) // 2
if nums[mid] == target:
return mid
elif (nums[first] <= nums[mid] and nums[first] <= target < n... |
import sys, random
from observer import Observer
from card import Cards, CardSet
from log import Log
class Agent:
def __init__(self, player, names):
self.player = player
self.name = names[player]
self.observer = Observer(names)
self.cards = []
def __str__(self):
return... |
from django.contrib.auth.models import Group, User
def user_is_moderator(user: User):
if not user.is_authenticated:
return False
group = Group.objects.get(name="moderators")
return group in user.groups.all()
|
import tensorflow as tf
import os
from PIL import Image
import numpy as np
import string
class GenerateTFRecord:
'''
Convert the image to binary records and store them in TFRecord format.
It is efficient to read data.
'''
def __init__(self, labels):
self.labels = labels
def _convert_... |
# -*- coding: utf-8 -*-
import random
ST=[]
t=0
while t<4 :
tem=str(random.randrange(0,9))
if not (tem in ST):
ST.append(tem)
t+=1
#宣告一個ST
#存放亂數產生要猜的一組不重覆的四位數{
time=1
while True:
print ("猜第%d次。\n請輸入一個不重覆的四位數字或輸入'STOP'以退出遊戲:" %time)
A=0
B=0
input_s=input()
... |
from 基于文本内容的垃圾短信识别.data_process import data_process
from wordcloud import WordCloud
import matplotlib.pyplot as plt
data_str, data_after_stop, labels = data_process()
# 词频统计
word_fre = {}
for i in data_after_stop[labels == 0]:
for j in i:
if j not in word_fre.keys():
word_fre[j] = 1
e... |
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('', include('portalBase.urls')),
path('portalHome/', include('portalBase.urls')),
path('admin/', admin.site.urls),
path('accounts/', inc... |
"""
Abandon hope all ye who enter the depths of this module
""" |
import spotipy
import spotipy.util as util
import config
MASTER_SCOPE = """user-library-read
playlist-read-private
user-library-modify
playlist-modify-public
user-read-recently-played
user-read-private
user-rea... |
import os
import re
import shutil
import subprocess
import get_package_info
import Retrieve_Hash_Custom_PIP_Package
import numpy as np
from colorama import Fore, Style, Back, init
def find_check_package(package=None):
found_package = None
package_info = get_package_info.get_package_info(package=package)
... |
from django.shortcuts import redirect, render
from .forms import PostForm
from .models import Volunteer
def volunteers(request):
if not request.user.is_authenticated:
return redirect('/register')
else:
volunteer_list = Volunteer.objects.order_by('-date')
context = {'volunteer_list': volunteer_list}
return re... |
def main():
try:
nimi = input("Syötä tiedoston nimi: ")
tiedostomuuttuja = open(nimi, "r")
n = sum(1 for line in open(nimi))
rivi = "dummy"
i = 1
while i <= n:
rivi = tiedostomuuttuja.readline()
rivi = rivi.rstrip()
print ... |
"""Author: Akash Shah (ass502)
unittest for test_grades method in the calculate module"""
from calculate import *
from unittest import TestCase
class GradesTest(TestCase):
def test_static_grades(self):
self.assertEqual(test_grades(['A','A','A']),0)
self.assertEqual(test_grades(['B']),0)
def test_increasing_g... |
import os
import argparse
import datetime
from copy import deepcopy
import traceback
import numpy as np
import torch
import torch.nn as nn
import torch.multiprocessing as mp
from torch.optim import SGD
from torch.utils.data import DataLoader
from omegaconf import OmegaConf
import ruamel.yaml
yaml = ruamel.yaml.YAML()
... |
from selenium import webdriver
import time
# 크롬창(웹드라이버) 열기
driver = webdriver.Chrome("./chromedriver")
# ootd 태그 검색결과 페이지 접속
driver.get("https://www.instagram.com/explore/tags/ootd/")
log = driver.find_element_by_css_selector("button.sqdOP")
log.click()
time.sleep(1)
box = driver.find_elements_by_css_selector("input._2... |
# Generated by Django 2.2.4 on 2019-09-29 02:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('job', '0021_auto_20190927_2030'),
]
operations = [
migrations.AlterField(
model_name='jobopening',
name='company_ema... |
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
def display(x,indx):
star = "************************\n"
dash = "----------"
print star + "=>>" + str(indx) + ".iteration\n" + star + "x:\n" + dash
print x
print dash + "\nf(x):\n" + dash + "\n" +str(f(x)) + "\n" + dash + "\nGrad... |
import socket
import time
import multiprocessing
from concurrent.futures import ProcessPoolExecutor as Pool
from Packet import create_packet, decode_header, Packet
from Constants import SERVER_PORT, CHUNK_SIZE, DATA_SIZE, SERVER_ADDRESS, HEADER_SIZE, WINDOW_SIZE, SEND_TIMEOUT, FINACK_WAIT
from pathlib import Path
impor... |
import random
name=input('Enter your name?')
print("Hello, "+name+" Time to play Hangman!!")
# create a variable to set secret
word="secret"
# create a variable with empty value
guesses=''
# determine the number of turns
turns=10
while turns>0:
failed=0
for char in word:
if char in gue... |
import django_filters.rest_framework
from django import shortcuts
from rest_framework import filters
from rest_framework import permissions
from rest_framework import response
from rest_framework import viewsets
import shop.models
import shop.permissions
import shop.serializers
class CategoryViewSet(viewsets.ReadOnl... |
"""记录一些算法题"""
from typing import List
from queue import Queue
def numIslands(grid: List[List[str]]) -> int:
"""广度(宽度)优先搜索-bfs"""
if not grid:
return 0
direct_coors = [(0, -1), (-1, 0), (0, 1), (1, 0)] # 四个方位offset
index = 1 # 岛屿ID
q = Queue()
for i in range(len(grid)):
for ... |
# Generated by Django 3.1.5 on 2021-01-06 19:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('Nursery_API', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Nur... |
class Inference(object):
def __init__(self, edge=None, matches=(), variables={}):
self.edge = edge
self.matches = matches
self.variables = variables
def __add__(self, other):
edge = other.edge if self.edge is None else self.edge
matches = self.matches + other.matches
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 18 19:44:46 2021
@author: DWI PRAMONO
"""
#Buat program untuk menampilakan dan menghitung biaya total Bengkel UD. Matahari
#1. set variabel merk, jumlah, harga, subtotawal, subtotakhir, diskon, ppn, total
#2. input pilihan merk oli dan harga
#3. input jumlah
#... |
import TreeNode
def sortedArrayToBST(num):
|
import calendar
import logging
from collections import defaultdict
from datetime import datetime
import lxml.html
from dateutil.parser import parse
from pyquery import PyQuery as pq
logger = logging.getLogger()
class AnimeParser:
def __init__(self, url, html):
self._url = url
self._html = html
... |
from django.shortcuts import render
from django.http import HttpResponse
def home(request):
return render(request,'shop/homepage.html') |
from carbon_black.endpoints.base_endpoint import Endpoint
from shared.models import SEC as SEC_Model, SEC_Company_Info, SEC_Employee_Stock, SEC_Merger, SEC_Secondary_Offering
from datetime import datetime
from json import loads as json_loads
class SEC(Endpoint):
def __init__(self) -> None:
super().__init... |
import re
import tokenizer
from feature_extractor_counts import FeatureExtractorCounts
from ..preprocessing import data_splitting as ds
from ..util import defines
from ..util import file_handling as fh
class FeatureExtractorCountsBrownClusters(FeatureExtractorCounts):
def __init__(self, test_fold=0, dev_subfold... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#created by liangj
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
import os
def dealWithWhite(inputArray):
output = [];
for height in range(0,inputArray.shape[0]):
for width in range(0,inputArray.sh... |
from django.contrib.sitemaps import Sitemap
from .models import Musica, Categoria, DiaLiturgico
class MusicaSitemap(Sitemap):
changefreq = "weekly"
priority = 0.6
def items(self):
return Musica.objects.all()
class CategoriaSitemap(Sitemap):
changefreq = "weekly"
priority = 0.5
def it... |
import os
import sys
import numpy as np
import cv2
import pandas as pd
from PIL import Image
import xml.etree.ElementTree as ET
from xml.dom import minidom
from bs4 import BeautifulSoup
from bs4 import Comment
import re
import random
import time
#########################################################################... |
# the notebook plugin
# handles notebook creation
import dateutil.parser
import logging
import json
import re
from docx import Document
from espresso.main import robot
from tinydb import where
# the regex used to identify an Announcement message
ANNOUNCEMENT_REGEX = r'(?is)Announcement for (?P<date>\d+/\d+/\d+): (?... |
# -*- coding: utf-8 -*-
from django.shortcuts import render,HttpResponseRedirect
from modelapp.models import Test,abc,ssr_1
from . import linux_shell,ping,tcp,ssr
from django.contrib.auth.models import auth,User
from django.contrib.auth.decorators import login_required
import requests,base64,os
last_port=1
ip='xx'
d... |
from datetime import datetime
from packaging.version import parse as version_parse
from markupsafe import Markup
from flask import current_app
# //cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment-with-locales.min.js
default_moment_version = '2.29.4'
default_moment_sri = ('sha512-42PE0rd+wZ2hNXftlM78BSehIGzezNeQu... |
from django.db import models
# Create your models here.
class CctvWorldInfo(models.Model):
news_id = models.CharField(max_length=50, default=0, verbose_name='新闻ID')
url = models.CharField(max_length=500, default='', verbose_name='地址链接')
front_image_url = models.CharField(max_length=500, default='', verb... |
import numpy as np
import timeit
from apr_max_sub_seq_test import measure_times, run_tests
# algorithm with double for loop and prices as list
def get_best_options_double_for(change_rates):
if len(change_rates) == 0:
return 0
prices = np.cumsum(change_rates).tolist()
prices.insert(0, 0)
dif... |
number=1
aumentador=2520
contador=1
divisor=1
while contador!=20:
if number%divisor==0:
divisor+=1
contador+=1
else:
divisor=1
aumentador+=1
number=aumentador*10
contador=0
print(number)
|
import random, time
class RandomBlocker:#class name is the same as file name
def __init__(self, empty, me, opponent):
self.empty = empty
self.me = me
self.opponent = opponent
self.seed = time.time()
self.board = []
def play(self):
random.seed(self.seed)
... |
import tensorflow as tf
import numpy as np
## hidden size ##
## seq length ##
## batch_size ##
tf.set_random_seed(777)
h = [1, 0, 0, 0]
e = [0, 1, 0, 0]
l = [0, 0, 1, 0]
o = [0, 0, 0, 1]
# parameter #
hidden_size = 2
sequence_length = 5
batch_size = 3
# RNN building #
cell = tf.contrib.rnn.BasicLSTMCell(num_units=... |
#!/usr/bin/python
# -*- coding: cp936 -*-
import sqlite3
import csv
import xlrd
import xlwt
from SQLiteQuery.simTradeQuery import *
from SQLiteQuery.inertialTestersQuery import *
from SQLiteQuery.kcbActQuery import *
def getSimTradeSheetFromSQLite():
with sqlite3.connect('C:\sqlite\db\hxdata.db') as db:
... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import time
from pwn import *
context.log_level = 'debug'
elf = ELF('./starbound')
# Constants
O_RDONLY = 0
# Memory locations
# .bss
username = 0x80580d0
fp_array = 0x8058154
bin_sh = elf.bss() + 0x100
flag_path = elf.bss() + 0x108
buf = elf.bss() + 0x120
... |
# -*- coding: utf-8 -*-
"""Tests for Windows AMCache (AMCache.hve) files."""
import unittest
from dtformats import amcache
from tests import test_lib
class WindowsAMCacheFileTest(test_lib.BaseTestCase):
"""Windows AMCache (AMCache.hve) file tests."""
# pylint: disable=protected-access
# TODO: add test for ... |
def counting(a,b,X):
A = [ [-1 for j in range(b + 1)] for i in range(a +1 ) ]
for i in range(a + 1):
A[i][0] = 0
for j in range(b + 1):
A[0][j] = 0
for i,j in X:
A[i][j] = 0
A[1][1] = 1
for i in range(1,a+1):
for j in range(1,b+1):
if A[i][j] == -1:... |
# -*- coding: utf-8 -*-
"""Convert support.support="never" to "no".
"never" was used to signal that the browser maintainer had decided not to
support a feature, and was usually supported by a WON'T FIX ticket. This
changes the API strategy to support="no", and (optionally) linking to
supporting documentation in a note... |
# Author:ambiguoustexture
# Date: 2020-03-08
import codecs
import snowballstemmer
from collections import Counter
from stop_words import isStopword
file_sentiment = './sentiment.txt'
file_features = './features.txt'
file_encoding = 'cp1252'
stemmer = snowballstemmer.stemmer('english')
word_counter = Count... |
import pandas as pd
import csv
import numpy as np
import matplotlib.pyplot as plt
import pickle
import pprint
from makeGraph import *
INF_val = 999999 # infinite
runOrderNumber = 100
# read in graph from pkl file
pkl_file = open('graph.pkl', 'rb')
graph = pickle.load(pkl_file)
print('Read in graph Done!')
pkl_file.c... |
'''
In this script, we practice writing exceptions.
Exceptions or exception objects are what are raised when your program encounters an error.
Exceptions contain:
- a description of what went wrong
- and a traceback of where the error occured in the script
Typically, writing exceptions come in the form of this:
try:... |
from .csp import SignupCSP
from .sma import SignupSMA
class Resolver(object):
"""Resolver object for processing waitlist or importing signups"""
__solvers = {
'CSP': SignupCSP,
'SMA': SignupSMA
}
solver = None
def __init__(self, solver):
"""set solver based on string"""
... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
题目:利用递归方法求5!。
"""
print
def fib(n):
if n == 0 or n == 1:
return 1
return n*fib(n-1)
print fib(5)
|
def cytoscape_data(G, name: str = "name", ident: str = "id"): ...
def cytoscape_graph(data, name: str = "name", ident: str = "id"): ...
|
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('gallery/', views.gallery, name='gallery'),
path('photo/<str:pk>/', views.viewImage, name='photo'),
]
|
try:
from tkinter import *
except:
from Tkinter import *
import sys
sys.path.append('../src/org')
from gameplay import Pacman as pm
from gameplay import Wall as w
from maps import Map1
from display import DrawingGenerics
import unittest
class KeyPress(object):
def __init__(self, keysym):
self.keysym = key... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
""" Regular packages
Import BaseCommand
"""
from .command import BaseCommand
__all__ = [
'BaseCommand',
]
|
#!/usr/bin/env python3
import sys,math,numpy
from itertools import permutations
def testsquare(s,bestx,besty,wid,hei):
angles=[]
sc=s.copy()
out= doMachine(sc,bestx,besty)
angles.append(out[0]==1)
sc=s.copy()
out= doMachine(sc,bestx+wid-1,besty)
angles.append(out[0]==1)
sc=s.copy()
... |
# Generated by Django 3.2.5 on 2021-07-24 22:50
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0002_rename_student_id_dashboard_student'),
]
operations = [
migrations.AlterField(
m... |
# -*- coding: utf-8 -*-
__author__ = 'Jeonghun Yoon'
'''
I will implement 'Bagging'. I will use the 'Regression tree' as a base learner.
Output will be a average of results of base learners.
'''
import urllib
import random
from sklearn.cross_validation import train_test_split
from sklearn.tree import DecisionTreeReg... |
import pandas as pd
import numpy as np
MODAL_REAL_EIGV_KEYS = {
'MODE': 'Frequency',
'EXTRACTIONORDER': 'Inverse Frequency',
'EIGENVALUE': 'Velocity',
'RADIANS': 'Damping',
'CYCLES': 'Damping',
'GENERALIZEDMASS': 'Frequency',
'GENERALIZEDSTIFF': 'Real Eigenvalue',
}
def _parse_content(cont... |
import unittest
import sys
if sys.hexversion < 0x2070000:
# Monkey-patch unittest.TestCase to add assertIsInstance on Python 2.6
def assertIsInstance(self, obj, cls, msg=None):
"""Same as self.assertTrue(isinstance(obj, cls)), with a nicer default message."""
if not isinstance(obj, cls):
... |
"""
News
"""
import requests
import canopy
app, kv, sql, view = canopy.branch(__name__, __doc__, subreddit=r"\w+")
reddit_api = "https://reddit.com/"
@app.route(r"")
class News:
def GET(self):
return view.index(self.delegate(HackerNews), self.delegate(Reddit))
@app.route(r"HackerNews")
class Hacke... |
#! /usr/bin/env python
from datetime import datetime
f = open('/home/pi/ESW/Pilot_1.x.x/ADC/datavalues.txt', 'r+')
f.write(str(datetime.now()))
f.close()
|
# Goal
#
# Create a program that prints out a multiplication table for the numbers 1 through 9. It should include the numbers 1 through 9 on the top and left axises, and it should be relatively easy to find the product of two numbers. Do not simply write out every line manually (ie print('7 14 21 28 35 49 56 63') ).
#
... |
from collections import Counter
from numpy import power
from numpy import log
from numpy import nan_to_num, prod
from Bio import SeqIO
import sh
import os
import shutil
class GeneCluster(object):
def __repr__(self): return '<%s object %s, annotated as %s with %i genes from %i genomes>' % (self.__class__.__name__... |
import pandas as pd
import os
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from stargazer.stargazer import Stargazer
from scipy.stats import ttest_ind
from tabulate import tabulate
import statsmodels.formula.api as smf
def get_data():
df = pd.read_stata("data/ReplicationDataset_ThePri... |
#This function will return the Rosetta pose number for residues in a selection, if the object were saved to a PDB file.
#This will be determined based on the object that contains the selection.
#When determining pose numbering, residues with only hydrogens will be ignored, as will HOH or WAT.
#Strange multiple states, ... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, with_statement
from fudge import patch
import cuisine
from revolver import directory
from .utils import run_result
def test_revolver_is_just_a_wrapper():
assert directory.attributes == cuisine.dir_attribs
assert directory.attributes... |
import os
import numpy as np
import tables
from scipy.ndimage import zoom
from fetal_net.utils.utils import read_img, transpose_if_needed
from .normalize import normalize_data_storage, normalize_data_storage_each, normalize_data_storage_each_clip_and_norm, \
normalize_data_storage_each_just_stretch, normalize_dat... |
# Name: Taidgh Murray
# Student ID: 15315901
# File: archery.py
############################################################################
import graphics
win = graphics.GraphWin('Archery Target')
point=graphics.Point(100,100)
Targetwhite=graphics.Circle(point, 50)
Targetwhite.setFill('White')
T... |
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# 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, ... |
import os
def program():
print("Welcome to the python program that runs python programs")
print()
path = input("What is the directory of the file? : ")
os.system("cd "+path)
print("These are all the python files in this directory : ")
input("Press 'enter' to continue")
os.system("d... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 27 12:28:37 2019
@author: kj22643
"""
# This is a first pass attempt to work with the adata file and identify the
# survivors and non-survivors from the lineage information in the sample.
|
from keras.applications import inception_resnet_v2
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten
from keras import layers
from keras.optimizers import Adam
def build_model_Inception_Resnet():
inception_resnet = inception_resnet_v2.InceptionResNetV2(
weights='imagenet',
... |
import unittest
from katas.kyu_7.easy_mathematical_callback import process_array
class ProcessArrayTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(
process_array([4, 8, 2, 7, 5], lambda val: val * 2),
[8, 16, 4, 14, 10]
)
def test_equals_2(self):
... |
# 胶囊气泡、大小头等瑕疵检测
import cv2 as cv
import os
import numpy as np
def balance_check(img_path, img_file, im, im_gray):
# 边沿提取
# sobel = cv.Sobel(im_gray, cv.CV_64F,
# 1, 1, ksize=5)
# cv.imshow("sobel", sobel)
# lap = cv.Laplacian(im_gray, cv.CV_64F)
# cv.imshow("lap", lap)
#... |
class Organs:
def __init__(self, small_finger=None, ring_finger=None, middle_finger=None, index_finger=None, thumb=None,
little_toe=None, ring_toe=None, middle_toe=None, long_toe=None, big_toe=None,
left_ear=None, right_ear=None, left_eye=None, right_eye=None, mouth=None, nose=None... |
import csv
import os
import datetime
employees_csv = 'employees.csv'
employees_temp = 'employees_temp.csv'
class Employee:
def __init__(self, employee_id, name, phone, age):
self.uid = employee_id
self.name = name
self.phone = phone
self.age = age
def add_employee(self):
... |
# -*- coding: utf-8 -*-
import os
from urllib.parse import urlparse
from scrapy.pipelines.files import FilesPipeline
class GithubPipeline(FilesPipeline):
def file_path(self, request, response=None, info=None, *, item=None):
tarball, suffix = item['name'], os.path.basename(urlparse(request.url).path)
... |
import torch
from torch import nn
from torch.autograd import Variable
import torch.nn.functional as F
from torchvision import models, transforms
from torch.utils.data import DataLoader
from torchvision.datasets import ImageFolder
import numpy as np
from sklearn import preprocessing
from tqdm import tqdm
import struct... |
'''
Created on Mar 5, 2015
@author: fan
'''
import unittest
class RefTests(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_def_var(self):
try:
print(var)
except Exception as ex:
# except: <class 'NameError'> global ... |
#!/Users/test/Documents/Dice-app-ios/AutoDelarWebsite_Django/env/bin/python
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
from .Dog import Dog
def start():
print("starting...")
def addDoggy(name,tricks):
instance = Dog(name)
for trick in tricks:
instance.add_trick(trick)
print(instance.tricks)
return instance
|
# -*- coding: utf-8 -*-
'''函数形参和实参测试:定义一个函数,实现两个数比较,并返回较大的值'''
#定义函数
def printMax(a,b): #形参a,b
'''函数功能:传入两个值,比较它们的大小,传入值必须类型一致,否则报错
created by fanwei
'''
if a > b:
print(a)
else:
print(b)
#调用函数
printMax(10, 9) #实参 10,9
#形参和实参必须一一对应
#printMax(10,20,21)
'''文档字符串(函数的注释)
程序的可... |
# Name: Taidgh Murray
# Student ID: 15315901
# File: bar.py
############################################################################
import math
num=input("Please enter a sequence of numbers, seperated by commas: ")
li=num.split(",")
numlist=[float(i) for i in li]
maximum=max(numlist)
N=math.log1... |
from kivy.app import App
from custom_camera.custom_camera import CameraWidget, CustomCamera
from kivy.base import Builder
Builder.load_file("custom_camera/custom_camera.kv")
class TestCamera(App):
def build(self):
camera = CameraWidget()
return camera
TestCamera().run()
|
from neo.io.basefromrawio import BaseFromRaw
from neo.rawio.elanrawio import ElanRawIO
class ElanIO(ElanRawIO, BaseFromRaw):
"""
Class for reading data from Elan.
Elan is software for studying time-frequency maps of EEG data.
Elan is developed in Lyon, France, at INSERM U821
https://elan.lyon.i... |
import arcpy
arcpy.env.overwriteOutput = True
inputFeatureclass = arcpy.GetParameterAsText(0) # rec_sites.shp
fileheight = arcpy.GetParameterAsText(1)
newFiles = arcpy.GetParameterAsText(2) # resultFile = "#"
newFields = arcpy.GetParameterAsText(3) # newFields = '#'
if newFields == '#' or not newFields:
... |
# Create Font Art using Python
# The PyFiglet library in Python can be used to visualize the output of your Python program with an amazing font style.
# Step:1
# pip install pyfiglet
import pyfiglet
font = pyfiglet.figlet_format('Nidhi Gupta')
print(font)
|
# Task: Implement find
#X v1: find <starting dir>
#X v2: find <starting dir> -name "*.txt"
#X v3: find <starting dir> -type d
import argparse
import glob
import os
class Cmd(object):
def __init__(self):
parser = argparse.ArgumentParser()
parser.add_argument("dir",
help="T... |
import os
import re
import glob
import cv2
import pickle
import matplotlib as plt
import numpy as np
from PIL import Image
from mlc.function import show
from keras import backend as K
np.set_printoptions(threshold=400000000)
def show_IoU():
"""
# #jpgのみにしてください
"""
datapath = "./... |
#
# datas = [1,2,3],[0.2,0.3,0.4]
# myids = ['整数',"浮点数"]
import yaml
with open('datas/test/a.yml') as f:
datas = yaml.safe_load(f)
myids = datas.keys()
mydatas = datas.values()
def test_param(param):
print(f"param= {param}")
print("动态生成测试用例")
|
from board import Board
from ai import AI
from human import Human
human = Human()
AI = AI()
gameboard = Board()
currPlayer = human
print(gameboard)
while(gameboard.gameOver() == None):
if (type(currPlayer is Human)):
print("It is the Human's turn.\n")
#gameboard.printBoard()
moves = ... |
from musket_core import image_datasets,datasets
@datasets.dataset_provider(origin="train.csv",kind="BinarySegmentationDataSet")
def get_segment1():
return image_datasets.BinarySegmentationDataSet(["test_images","train_images"],"train.csv","ImageId","EncodedPixels")
@datasets.dataset_provider(origin="train.c... |
def main ():
item_names = []
item_prices = []
item_counts = []
grandtotal = 0
print ("This program will help to calculate the customer's invoice.\n")
item_name = input ("Enter the name of the first item purchased.")
while (len(item_name) > 0):
item_names.append (it... |
class Car:
wheel_type ="Firestone"
make="Mercedes"
year_of_manufacture=2016
#Runs as soon as you create an Object
def __init__(self,milage,age):
print(" I am the constructore method")
self.milage=milage
self.miaka=age
def stopDist(self):
print("{} stopping dista... |
import base64
import json
import logging
import time
logger = logging.getLogger()
logger.setLevel(logging.INFO)
output = []
def lambda_handler(event, context):
for record in event['records']:
try:
#Input data is base64 encode, need to decode it
decodedData = base... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.