text stringlengths 8 6.05M |
|---|
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import logging
from dataclasses import dataclass
from pants.backend.java.bsp.spec import JavacOptionsItem, JavacOptionsParams, JavacOptionsResult
from pants.backend.java.target_types impor... |
# -*- coding: utf-8 -*-
from aluno import Aluno
|
# Author:Yichen Fan
# Date 12/8/2015
#ASS10
import pandas as pd
from main10 import *
import numpy as np
import matplotlib.pyplot as plt
def plot_figure(raw_data):
uniq_date = raw_data.groupby(['DATE','GRADE']).size().unstack()#gruped data by date and grade
uniq_date = uniq_date.replace(np.nan, 0)#replace none to 0 s... |
'''Basics file of beautiful soup'''
from bs4 import BeautifulSoup
import requests
source = requests.get('https://github.com/sai-sondarkar').text
soup = BeautifulSoup(source, 'lxml')
#print(soup.prettify()) #prettify and prints the entire web page
#match = soup.title.text prints the title of the web page i... |
#encoding=utf-8
from openpyxl import load_workbook
import pandas as pd
from nameout import out
R=input("输入年份:")
date=pd.date_range(R+'/01/01',R+'/12/31', freq='D')
print(date)
week=[int(i.strftime("%w")) for i in date] # 0表示星期日
dataframe = pd.DataFrame({'date':date,'week':week})
dataframe.to_excel('dates.xl... |
#The code is written by Ruiqi Zhong on April 28 to map mrna name to KEGG function
from urllib.request import urlopen
directory = input()
output = directory + '.out'
f = open(directory, 'r')
w = open(output, 'w')
for l in f:
url = 'http://rest.kegg.jp/find/genes/' + l
w.write(l)
try:
data = urlopen(url, timeout=10... |
"""Markdown parsing functions"""
from collections import namedtuple
import re
ParsedIssue = namedtuple("ParsedIssue", ["issue_number", "closes", "org", "repo"])
def _make_issue_number_regex():
"""Create regex to extract issue number and other useful things"""
# See https://help.github.com/en/github/writing... |
import z
import queue
import buy
import sliding
import statistics
debug = None
#debug = "BA"
if debug:
print ("debugging {}".format(debug))
start = 60
each = 10
istart = -1*start
req = start - 20
dates = z.getp("dates")
que = 12
firstdate = dates[istart*7]
print("firstdate : {}".format( firstdate ))
march_23_2020... |
# 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, ... |
from django.db import models
class Sizes (models.Model):
id_size = models.AutoField(primary_key=True)
size_name = models.CharField(max_length=45)
price_coef = models.FloatField(null=True, default=None)
|
#! /usr/bin/python3
import sys
import pdb
import argparse
import xml_utils as u
import datetime
from collections import defaultdict
from argparse import RawTextHelpFormatter
# from ordereddefaultdict import OrderedDefaultdict
##------------------------------------------------------------
## can be called with:
## ... |
from tkinter import messagebox
from tkinter import *
from tkinter.filedialog import *
from tkinter.colorchooser import *
# 记事本应用
class Application(Frame):
def __init__(self, master=None):
super().__init__(master) # super 代表的是父类的定义 调用父类构造器
self.master = master
self.pack()
self.cr... |
from influxdb import InfluxDBClient
import Adafruit_DHT
import socket
import time
DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 4
client = InfluxDBClient(host='192.168.0.101', port=8086, username='marc', password='marc')
client.create_database('sensors')
client.switch_database('sensors')
measurement = "rpi-dht22"
locati... |
import sys
from bioblend import galaxy
from bioblend.galaxy.users import UserClient
args = sys.argv
address = args[1]
master_key = args[2]
gi = galaxy.GalaxyInstance(url=address, key=master_key)
users = UserClient(gi)
u = users.get_users()[0]
key = users.create_user_apikey(u.get('id'))
print(key)
|
from flask_wtf import Form
from wtforms import StringField, SubmitField, IntegerField, HiddenField, TimeField
from wtforms import validators
class TaskFrom(Form):
name = StringField("Name: ", [
validators.DataRequired("Please enter student name."),
validators.Length(3, 255, "Name should be from 3... |
#!/usr/bin/env /share/share1/share_dff/anaconda3/bin/python
"""
Author: Lira Mota, lmota20@gsb.columbia.edu
Course: Big Data in Finance (Spring 2019)
Date: 2019-02
Code:
Creates stock_monthly pandas data frame.
Import CRSP MSE and MSF.
------
Dependence:
fire_pytools
"""
# %% Packages
import sys
sys.path... |
from sklearn.metrics import cohen_kappa_score
import InputOutput as io
data = io.csvIn(r'Training\Final\Labeled.csv', skip_first=True)
labels1 = []
labels2 = []
for row in data:
labels1.append(row[4])
labels2.append(row[5])
print(cohen_kappa_score(labels1, labels2))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time: 2018/8/5 11:14
# @Author: Joey66666
# @Software VSCode
import json
import logging
import time
import base64
from decimal import *
from flask import Flask, jsonify, abort, request
from flask_sqlalchemy import SQLAlchemy
from werkz... |
def hotel_cost(nights):
return 140 * nights
def plane_ride_cost(city):
if city == 'Charlotte':
return 183
elif city == 'Tampa':
return 220
elif city == 'Pittsburgh':
return 222
elif city == 'Los Angeles':
return 475
def rental_car_cost(days):
rental = 40 * days
if (days >= 7):
return... |
# Generated by Django 2.1.7 on 2019-04-20 07:36
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('amazon', '0008_auto_20190420_1212'),
]
operations = [
migrations.RenameModel(
old_name='women_shops_clothes',
new_name='wome... |
import pytest
from rubicon_ml.viz.common.colors import get_rubicon_colorscale
from rubicon_ml.viz.common.dropdown_header import dropdown_header
@pytest.mark.parametrize("num_colors,expected", [(1, 2), (4, 4)])
def test_get_rubicon_colorscale(num_colors, expected):
colors = get_rubicon_colorscale(num_colors)
... |
#!/usr/bin/python
#=============================================================================
#
# Copyright 2006 Etienne URBAH for the EGEE project
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software... |
# -*- coding: utf-8 -*-
from __future__ import division
import socket
from matplotlib import pyplot as plt
def getOpenPort():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("",0))
s.listen(1)
port = s.getsockname()[1]
s.close()
return port
def reverseDict(dictionary):
revers... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import configuration
db = SQLAlchemy();
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(configuration[config_name])
db.init_app(app)
from .main import main as main_bluprint
app.register_bluepr... |
import sys
import struct
import numpy as np
from nptyping import NDArray
from physics import Physics
class PhysicsSim(Physics):
def __init__(self, racecar) -> None:
self.__racecar = racecar
def get_linear_acceleration(self) -> NDArray[3, np.float32]:
self.__racecar._RacecarSim__send_header(
... |
# coding:utf-8
# 定义函数的一般语法:
def greetings():
"""显示简单的问候语"""
print("Hello World!")
def greeting(username):
"""显示简单的问候语 username-形参"""
print("Hello {}".format(username))
def printme(strings):
"""打印任何参入的字符串"""
print(strings)
return
# 1.函数的调用
greetings()
# 在函数的调用代码greeting("Bob")中,值"Bob"... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#############################################################################
# Copyright Vlad Popovici <popovici@bioxlab.org>
#
# Licensed under the Apache License, Version 2.0 ( the "License" );
# you may not use this file except in compliance with the License.
# You... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Student(object):
def __init__(self,name,score):
self.__name = name
self.__score = score
def get_name(self):
return self.__name
def get_score(self):
return self.__score
def set_score(self,score):
if 0<= score <= ... |
from pandas.core.common import flatten
def remove(digit_list):
digit_list = [''.join(x for x in i if x.isalpha()) for i in digit_list]
return digit_list
def can_contain_gold(bag):
if all_contents[bag][0] == 'noother':
return 'n'
else:
if 'shinygold' in ''.join(all_contents[bag]):
... |
import unittest
from operator import itemgetter
from unittest import TestCase
from unittest.mock import MagicMock, Mock, patch
import numpy as np
import pandas as pd
from sdv.data_navigator import DataNavigator, Table
from sdv.modeler import Modeler
from sdv.sampler import Sampler
class TestSampler(TestCase):
... |
import os
from app.server import app
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port, threaded=True, debug=False) |
from _collections import defaultdict
number_of_pieces = int(input())
all_pieces = defaultdict(dict)
for _ in range(number_of_pieces):
tokens = input().split("|")
piece = tokens[0]
composer = tokens[1]
key = tokens[2]
all_pieces[piece]["composer"] = composer
all_pieces[piece]["key"] = key
while... |
def archers_ready(archers):
return all(a >= 5 for a in archers) if archers else False
|
# Generated by Django 2.0.7 on 2018-09-13 10:30
import datetime
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_USER_MODEL)... |
"""django-allauth customizations for browsercompat."""
|
from django.db import models
from .validators import validate_file_extension
from django.conf import settings
from tssite import client
masechetot_by_seder = [
('Zeraim', (
('berachot', 'Berachot'),
)
),
('Moed', (
('shabbat', 'Shabbat'),
)
),
]
class Teacher(mo... |
class CompteBancaire:
def __init__(self,nom="Dupont",solde=1000):
self.nom=nom
self.solde=solde
def depot(self,somme):
self.solde+=somme
def retrait(self,somme):
self.solde -= somme
def affiche(self):
print("le titulaire "+self.nom+" ... |
#===========================================================================
#command line parsers for py.test.
#===========================================================================
def pytest_addoption(parser):
parser.addoption("--env", action="store",help="env: the env that runs the tests e.g. qa , d... |
# -*- coding: UTF-8 -*-
import os # 调用操作系统相关的功能
import sys # 调用python 解释 器相关的方法
import logging # 日志记录
import ConfigParser # 配置文件模块 ,在3.X中已经将ConfigParser改成了configParser |
import json
def main():
with open("emd.json", encoding="utf-8") as file:
dataset = json.load(file)
file = open("converted.ttl", "w", encoding="utf-8")
emds = {}
atletas = {}
modalidades = set()
clubes = {}
for data in dataset:
emds[data["_id"]] = {
"... |
from heart_server_helpers import existing_beats
import pytest
@pytest.mark.parametrize("pat_id, expected", [
(-1, True),
(-2, False),
])
def test_existing_beats(pat_id, expected):
pat_exist = existing_beats(pat_id)
assert pat_exist == expected
|
import tensorflow as tf
"""
理解:
tf.get_variable: 配合tf.variable_scope 及 scope.reuse_variables() 使得 var1 和 var12是同一个变量(name相同)
tf.Variable: var2, var21, var22是三个不同的变量
所以如果要复用变量,使用 tf.get_variable
"""
# name_scope
# with tf.name_scope("a_name_scope"):
# initializer = tf.constant_initializer(value=1)
# ... |
import numpy as np
import pandas as pd
import sklearn
import sklearn.preprocessing
import scipy
import tensorflow.keras as keras
df = pd.read_csv('WISDM_clean.csv')
df_train = df[df['user_id'] <= 30]
df_test = df[df['user_id'] > 30]
# Norm
scale_columns = ['x_axis', 'y_axis', 'z_axis']
scaler = sklearn.preprocessing... |
# noinspection PyUnresolvedReferences
from django.shortcuts import render,redirect
# noinspection PyUnresolvedReferences
from django.http import HttpResponse,HttpResponseRedirect
# noinspection PyUnresolvedReferences
from django.contrib.auth.models import User
# noinspection PyUnresolvedReferences
from django.contrib.a... |
nums = [1, 2, 3, 4, 5, 6, 7, 8]
# using reverse index to get the number I wanted
print(nums[-2])
characters = ['Asokha Tano', 'Luke Skywalker', 'Obi-Wan Kenobi']
print(characters[0])
print(characters[-1])
|
from .SelectionMode import SelectionMode
from .SelectionType import SelectionModeTransform, SelectionType
from bsp.leveleditor.menu.KeyBind import KeyBind
from bsp.leveleditor import LEGlobals
class VertexMode(SelectionMode):
Type = SelectionType.Vertices
Mask = LEGlobals.FaceMask
Key = "solidvertex"
... |
array = [6, 3, 7, 0, 9, 8, 4, 5, 1, 2]
for j in range(len(array)-1):
for i in range(len(array)-1):
if array[i] > array[i + 1]:
buffer = array[i]
array[i] = array[i + 1]
array[i + 1] = buffer
print(array)
print('test') |
from __future__ import unicode_literals
from django.db import models
import re
email_regex = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
import bcrypt
def get_passwd_hash( passwd, salt = bcrypt.gensalt() ):
return( bcrypt.hashpw( passwd, salt ) )
class UsersManager( models.Manager ):
de... |
import sys
import os
f = open("C:/Users/user/Documents/python/ant/import.txt","r")
sys.stdin = f
# -*- coding: utf-8 -*-
n = int(input())
w = []
v = []
for i in range(0,n):
temp = list(map(int,input().split()))
w.append(temp[0])
v.append(temp[1])
W = int(input())
dp = [[-1] * (n + 2)] * (... |
import numpy as np
# 통계함수
data = np.array([1, 2, 3, 4, 5, 6])
print(data.min(), data.mean(), data.max(), data.std())
print(np.sum(data), np.mean(data), np.min(data), np.max(data), np.std(data))
print(np.median(data))
print(np.quantile(data, [0.25, 0.5, 0.75]))
print(np.percentile(data, [25, 50, 75]))
# 주식 - 피보나치값 황금... |
#!/usr/bin/python
"""
PowerMon!
A script to read power meter readings from a 433MHz energy sensor and write them to a RRD file.
In my case, the power meter is an Owl CM180.
This script requires rtl_433 from https://github.com/merbanan/rtl_433, with a little hackery to
make the output parseable.
"""
i... |
"""
Python Client speaking Nedh by taking over a socket from an inherited fd
"""
__all__ = ["takeEdhFd"]
from typing import *
import asyncio
import inspect
import socket
import runpy
from edh import *
from . import log
from .mproto import *
from .peer import *
logger = log.get_logger(__name__)
async def takeEdh... |
"""
browser.switch_to.window(window_name)
first_window = browser.window_handles[0]
new_window = browser.window_handles[1]
"""
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
import math
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import... |
import copy
#グラフは隣接リストで実装する
#グラフの読み込み
def read_graph_data(linksfile,namesfile):
lf = open(linksfile)
nf = open(namesfile)
names=dict([line.strip().split() for line in nf.readlines()])
nodelist={v:[] for v in names.values()} #dict
for line in lf.readlines():
n_from,n_to,cost=line.strip().spli... |
from math import ceil
from operator import attrgetter
class Fighter(object):
""" used as a pre-loaded class inside of this kata, for local testing """
def __init__(self, name, health, damage_per_attack):
self.name = name
self.health = health
self.damage_per_attack = damage_per_attack
... |
# -*- coding: utf-8 -*-
from collections import Counter
from heapq import heappop, heappush
class MaxHeap:
def __init__(self):
self.els = []
def __len__(self):
return len(self.els)
def __nonzero__(self):
return len(self.els) > 0
def pop(self):
_, el = heappop(self.e... |
#!/usr/bin/python3
'''
Form classes
'''
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, SelectField, TextAreaField
from wtforms.validators import DataRequired
from models import storage
import models
def get_countries():
choices = []
countries = storage.all(mode... |
from django.contrib.auth import authenticate, login, get_user_model,logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from django.shortcuts import reverse
from django.utils.decorators import method_decorato... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
model_save_path = "./checkpoint/mnist.ckpt"
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
mo... |
archivo = open("./paises.txt", "r")
paises = []
for linea in archivo:
paises.append(linea.strip())
for pais in paises:
print(pais)
print ("Total de Países: " + str(len(paises)))
for pais in paises:
if pais[0] == "L":
print("País con L: " + pais)
#print(paises)
archivo.close() |
from django.http import JsonResponse
from index.models import Products
from django.core.paginator import *
# Create your views here.
def snacks(request):
if request.method == 'GET':
seek = request.GET.get('seek', 'None')
if seek == 'None':
all_snacks = Products.objects.filter(products... |
"""Datadog functions for autoscaler"""
import logging
from datadog import initialize, api
class DatadogClient:
def __init__(self, cli_args, logger=None):
if cli_args.datadog_api_key and cli_args.datadog_app_key:
self.dd_auth = dict(api_key=cli_args.datadog_api_key,
... |
##
import sys
import os, glob, pickle
from os import path, pardir
import json
import sqlite3
import h5py
import numpy as np
from Params import Params
from skimage import measure
from skimage import morphology
import trimesh
import gzip
import pymeshfix
import pyvista as pv
from Shared import Shared
main_dir = path.ab... |
from musket_core import datasets,genericcsv,context
from musket_core import image_datasets,datasets
@datasets.dataset_provider(origin="train.csv",kind="GenericDataSet")
def getBengali0():
return image_datasets.MultiOutputClassClassificationDataSet("bengaliai-cv19/train", "bengaliai-cv19/train.csv", 'image_id'... |
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python
#####################################################################################################
# #
# clean_the_data.py: remove duplicated d... |
'''Importing datetime library for recording timestamp'''
from datetime import datetime
from hashlib import sha256
#creating a block for blockhchain
class Block:
def __init__(self,transactions,previous_hash,nonce=0):
self.transactions=transactions
self.previous_hash=previous_hash
self.nonc... |
#!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
from django.forms import ModelForm, forms
from django.forms.widgets import HiddenInput
from django.http import HttpResponse
from django.utils.translation import ugettext_lazy as _
from django.core.mail import EmailMessage, BadHeaderError
f... |
#
# Copyright © 2021 Uncharted Software 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 l... |
import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
class NLTKTokenizer:
def __init__(self, lower=True, max_length=250, sos_token=None,
eos_token=None):
self.lower = lower
self.max_length = max_length
self.sos_token = sos_token
self.eos... |
import sys
import logging
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine, QQmlComponent, qmlRegisterType, QQmlEngine
from controller.bestellung_controller import BestellungController
from controller.nutzer_controller import NutzerController
from controller.artikel_controller impor... |
import numpy as np
from math import atan, acos, pi
# from sklearn.linear_model import LinearRegression
from scipy.optimize import curve_fit
import circle_fit as cf
# prev_leftdy = 0
# prev_rightdy = 0
# prev_leftc = 0
# prev_rightc = 0
def curve(left_lane, right_lane,stop):
xleft_plot = np.arange(5,40,0.01).r... |
# Generated by Django 3.1.3 on 2020-12-19 15:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api_basic', '0002_auto_20201214_1657'),
]
operations = [
migrations.AlterField(
model_name='article',
name='image',
... |
import serial
import serial.tools.list_ports
import matplotlib.pyplot as plt
import numpy as np
import sys
import pandas as pd
import argparse
import atexit
from time import sleep
import os
from openpyxl import Workbook
import datetime
# import soundfile as sf
#COMMENT
# Modules for GUI
from pyqtgraph import PlotWidg... |
class Movie:
def __init__(self, title, seeds=0):
self.title = title
self.seeds = seeds
def __hash__(self):
return hash(self.title)
def __eq__(self, other):
return self.title == other.title
|
from nltk.tokenize import word_tokenize
import numpy as np
def data_stream():
"""Stream the data in 'leipzig100k.txt' """
with open('leipzig100k.txt', 'r') as f:
for line in f:
for w in word_tokenize(line):
if w.isalnum():
yield w
def bloom_filter_set... |
from asl_test_recognizer import TestRecognize
import unittest
suite = unittest.TestLoader().loadTestsFromModule(TestRecognize())
unittest.TextTestRunner().run(suite) |
# -*- coding: utf-8 -*-
from setuptools import setup
from distutils.extension import Extension
from distutils.version import LooseVersion
import platform
import sys
import warnings
if "--without-cseabreeze" in sys.argv:
sys.argv.remove("--without-cseabreeze") # this is a hack...
# user requests to not install... |
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
from Cython.Build import cythonize
import numpy
extensions = [
Extension(
"_voidfinder_cython",
["_voidfinder_cython.pyx"],
include_dirs=[numpy.get_... |
#!/usr/bin/env python
# Script by Steven Grove (@sigwo)
# www.sigwo.com
# Reference http://stackoverflow.com/questions/3160699/python-progress-bar/15860757#15860757
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTAB... |
#!/usr/bin/env python3
"""mem2log"""
from argparse import ArgumentParser
from ctypes import CDLL
from signal import SIGHUP, SIGINT, SIGQUIT, SIGTERM, signal
from sys import exit
from time import sleep
def log(msg):
"""
"""
print(msg)
if separate_log:
logging.info(msg)
def mlockall():
""... |
def outer(func):
def inner(name, age):
if age < 0:
age = 0
func(name, age) # 执行作为参数传过来的函数
return inner
# 使用@符号作用于函数,相当于给函数加上装饰器
@outer # 相当于 myprint = outer(myprint)
def myprint(name, age):
print("{} is {} years old".format(name, age))
# myprint = outer(myprint... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 7 16:17:46 2017
@author: zx621293
"""
def myIsomap (X, color, n_neighbors, n_components=2):
t0 = time()
Y = manifold.Isomap(n_neighbors, n_components).fit_transform(X)
t1 = time()
fig = plt.figure(figsize=(15, 8))
plt.scatter(Y[:, 0], Y... |
# Generated by Django 3.1.1 on 2020-09-17 03:12
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('attend', '0011_auto_20200917_0842'),
]
operations = [
migrations.RemoveField(
model_name='face',
name='created',
),
... |
"""方法1:使用main方式执行单个测试类的全部用例"""
__author__ = 'slyang'
import unittest
from count import Count
#创建一个测试类,但是必须要继承unit
class MyTest(unittest.TestCase):
# 用例1-- 测试整数加法
def test_b_add1(self):
#测试步骤
count = Count()
result = count.add(1,2)
#实际结果
actual_result = result
... |
# encoding=utf8
"""
Author: 'jdwang'
Date: 'create date: 2017-01-13'; 'last updated date: 2017-01-13'
Email: '383287471@qq.com'
Describe: 测试发布在服务器上的API
"""
from __future__ import print_function
import requests
__version__ = '1.3'
TAG_URL = 'http://119.29.81.170:10545/id_detection/regex/rawInput=... |
"""
Creates hierarchical data format files with complexe frequency spectrograms for audio files in a given folder.
"""
__author__ = 'David Flury'
__email__ = "david@flury.email"
import os
import sys
import glob
import h5py
import time
import librosa
import warnings
import argparse
import numpy as np
import multiproce... |
from itertools import izip_longest
def solution(s):
return [''.join(a) for a in izip_longest(s[::2], s[1::2], fillvalue='_')]
|
"""
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def isPalindrome(number):
reverse = 0
n = number
while n != 0:
reverse = reverse ... |
import re
import os
import pandas as pd
import time
DIR=os.getcwd()
logfile=DIR+'/log-count.txt'
sp_names=[]
chr_names=['chr1','chr2','chr3','chr4',
'chr5','chr6','chr7','chr8',
'chr9','chr10','chr11','chr12',
'chr13','chr14','chr15','chr16',
'chr17','chr18','chr19','chr20',
... |
# Generated by Django 2.2.6 on 2019-10-20 20:33
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('checkout', '0008_promotioncode'),
]
operations = [
migrations.AddField(
model_name='promotioncode'... |
# This file is part of beets.
# Copyright 2016, Thomas Scholtes.
#
# 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 traceback
from colorama import Fore, init
init()
class Logger(object):
def __init__(self):
pass
def _print(self, color, s):
print("%s[infrabox] %s%s" % (color, s, Fore.RESET))
def log(self, s, print_header=True):
print("%s%s" % ("[infrabox] " if print_header else "", s))
... |
from hypothesis import given,example
import hypothesis.strategies as st
import numpy as np
from gInteg import Integration_GaussLegendre, calculate, solve,get_param
@given(n = st.floats(1.0,5.0), flg = st.booleans())
@example(1.0,True)
def test_calculate(n,flg):
f = "1/(x**2+4)"
result = calculate(f,n,flg)
... |
import pandas as pd
import numpy as np
import scipy.sparse
import sklearn
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction import DictVectorizer
from sklearn.linear_model import Ridge
"""
Загрузите данные об описаниях вакансий и соответствующих годовых зарплатах из файла sal... |
import util #같은 디렉토리에 있어야 가져올 수 있다
print("1 inch = ", util.INCH, "cm") #1 inch = 2.54 cm
print("1 ~ 10까지의 합계:", util.sum(10)) #1 ~ 10까지의 합계: 55
import sys
print(sys.path) #디렉토리를 문자열로 나타내는
"""
['c:\\workspace\\Day0605',
'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip',
'C:\\Users\\us... |
print("quelle année ? : ", end="")
annee = int(input())
if annee % 4 == 0 :
print("année bissextile")
if annee % 100 == 0:
print("année normale")
if annee % 400 == 0:
print("année bissextile")
else:
print("année normale")
|
from multiaddr.address import *
|
"""
MIT License
Copyright (c) 2018 Max Planck Institute of Molecular Physiology
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... |
import cv2
import docdetect
import numpy as np
import sys
import urllib.request
url='http://172.16.50.57:8080/shot.jpg'
# video = cv2.VideoCapture(video_path)
cv2.startWindowThread()
cv2.namedWindow('output')
model = sys.argv[2]
# print (model)
edge_detection = cv2.ximgproc.createStructuredEdgeDetectio... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from dataclasses import dataclass
from pants.backend.go.subsystems.gotest import GoTestSubsystem
from pants.backend.go.util_rules import coverage_html
f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.