text stringlengths 8 6.05M |
|---|
"""
LeetCode - Easy
"""
class Solution(object):
def removeVowels(self, S):
"""
:type S: str
:rtype: str
"""
dictOfVowels = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4, 'A': 5, 'E': 6, 'I': 7, 'O': 8, 'U': 9}
char = 0
while len(S) != 0:
if S[char] in di... |
output = pd.DataFrame()
# these are all variables that can be tweaked to see which ones generate the best performing model:
param_grid = {
"DEG_log2FC_cutoff": [0],
"DEG_pvalue": [0.05],
"H3K27ac_var_cutoff": [0],
"H3K27ac_cutoff": [0],#[2.3],
"H3K4me3_cutoff": [0],#[2.7],
"H3K4me3_var_cutoff":... |
#-*- coding: utf-8 -*-
class ResultOutputer(object):
def __init__(self):
self.datas = []
def collect_data(self, data):
if data is None:
return
self.datas.append(data)
def output_html(self, fileName):
with open(fileName+'.html', 'w', enco... |
#!/usr/bin/python
#Apply operation for every combination in collection.
def ForEachCombination(collection, operation, pre_seq=[]):
if len(collection)==0:
return
if len(collection)==1:
operation(pre_seq+list(collection))
return
for item in collection:
ForEachCombination(set(collection)-set([item])... |
# Find the best selling item for each month where the biggest total invoice was paid.
# The best selling item is calculated using the formula (unitprice * quantity).
# Output the description of the item along with the amount paid.
# Import your libraries
import pandas as pd
# Start writing code
online_retail['month... |
# Generated by Django 3.0.2 on 2020-06-03 19:55
import apps.bboard.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bboard', '0007_img'),
]
operations = [
migrations.AlterField(
model_name='img',
name='img'... |
from .api import LinkedDataFrame
from .constants import LinkageSpecificationError, LinkAggregationRequired
|
capital = 'London is the capitel of Great Britain'
#template = '{1} is the capital of {0}'
#print(template.format("London", "Great Britain"))
#print(template.format("Vaduz", "Liechtenstein"))
#print(template.format.__doc__)
#template = '{capital} is the capital of {country}'
#print(template.format(capital="London", co... |
#!/usr/bin/env python
import xml.etree.ElementTree as ET
from math import fabs,log
import sys
ns = {'pep': 'http://regis-web.systemsbiology.net/pepXML'}
mass_tol = 0.01
mass_norm_AA = {
"G" : 57.02146,
"A" : 71.03711,
"S" : 87.03203,
"P" : 97.05276,
"V" : 99.06841,
"T" :101.04768,
"C" :103.00918,
"L" :113.08406,
"I"... |
#!/usr/bin/env python
'''
We shall say that an n-digit number is pandigital if it
makes use of all the digits 1 to n exactly once.
For example,2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
'''
from itertools import permutations
import math
def is_prime(n)... |
# Copyright, the authors - see LICENSE.rst
try:
from .version import version as __version__
except ImportError:
# TODO: Issue a warning...
__version__ = ''
# The version number can be found in the "version" variable of version.py
# set up the test command
from astropy.tests.helper import TestRunner
_test_... |
#The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from fake_useragent import UserAgent
CITY_NAME = '长沙'
JOB_NAME = '爬虫'
COLUMN = ['职业名', '月薪', '公司名', '公司url', '职位条件', '岗位职责与技能要求', '工作地址',
'创建日期', '更新日期','截止日期', '职位亮点', '职位url']
HEADERS = {'User-Agent': UserAgent().random}
WORK_LIST = []
|
class SlackError(Exception):
"""General exception class for all Slack-related errors"""
pass
|
from django import forms
from django.forms import ModelForm
from smile.models import USER
'''
GENDER=[
('male', 'Male')
('female', 'Female')
]
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
gender = forms.CharField(label='Gender', widget=forms.Select(choices=GENDER))
class M... |
# Copyright 2016 Husky Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... |
import os
from unittest import TestCase
from testfixtures.comparison import compare
from testfixtures.tempdirectory import TempDirectory
import hex_generator as hg
class BoardGenerationTests(TestCase):
def test_generate_board_parallelogram(self):
board = hg.generate_parallelogrammatic_board(5, 3)
... |
from rest_framework import serializers
from rest_framework.serializers import Serializer, ModelSerializer
from TestOnline.exam.serializers import QuestionSerializer
from TestOnline.models import Paper, PaperPermission, Question, Type
class TypeSeiralizer(ModelSerializer):
class Meta:
model = Type
... |
from django.db.models import *
# Create your models here.
class WJ(Model):
id = AutoField(primary_key=True)
q1 = BooleanField(default=True, verbose_name="是否需要公共交通")
q2 = CharField(max_length=8, verbose_name="交通方式",
choices=(("minibus", "小型公交车"), ("ecar", "电瓶车"), ("railway", "轨道交通")))
... |
from google.appengine.ext import ndb
class TaskListSettings(ndb.Model):
user_id = ndb.StringProperty()
list_id = ndb.StringProperty()
settings = ndb.JsonProperty() |
#!/usr/bin/env python
#!-*-coding:utf-8 -*-
# Time :2020/5/19 15:05
# Author : zhoudong
# File : target_data.py
import numpy as np
import matplotlib.pyplot as plt
class Target_Position:
def __init__(self, N):
self.s = np.zeros((4, N, 4), dtype=np.float32) # 状态向量
self.n = np.zeros((4, ... |
thisdict = dict(brand="Ford", model="Mustang", year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 27 11:46:11 2020
@author: matty
"""
"""
This script is used to examine specific regions of interest by comparing area-average regions between model output and observations.
The script compares multiple observations to the model output, in order to ... |
from django import forms
from accounts.models import User
from payments.models import CreditCard
from django.contrib.auth.forms import UserCreationForm
class UserSignupForm(UserCreationForm):
class Meta:
model = User
fields = ['email', 'first_name', 'last_name', 'password1', 'password2']
class U... |
"""Author Arianna Delgado
Created on May 28, 2020
"""
"""Showing List is mutable"""
l1 = [2,3,4,5,8,4,3,5,2,1,8,8,6,3,4,5,7,9]
set1 =(set(l1))
l2 = list(set1)
print(l2)
#list are mutable
l2[0] = 100
print(l2)
"""Showing tuples are immutable"""
#tuples are immutable
tuple1 = tuple(l2)
tuple1[0] = 1 #this line will... |
# @Title: 相交链表 (Intersection of Two Linked Lists)
# @Author: 2464512446@qq.com
# @Date: 2019-11-06 15:28:23
# @Runtime: 212 ms
# @Memory: 40.7 MB
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/9/22 15:03
# @Author : TheTAO
# @Site :
# @File : build_inputs.py
# @Software: PyCharm
import pickle
import jieba.posseg as psg
from cnradical import Radical, RunOption
# 全角转半角
def full_to_half(s):
n = []
for char in s:
num = ord(... |
from django.db import models
class Term(models.Model):
details=models.CharField(max_length=500)
last_updated_at=models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.details
|
# coding:utf-8
__author__ = 'yann'
import datetime
import functions
import time
from flashsale.dinghuo.models_stats import SupplyChainStatsOrder, DailySupplyChainStatsOrder
from shopback.items.models import Product, ProductSku
from flashsale.dinghuo.models import OrderDetail
def get_daily_order_stats(prev_day):
"... |
from django.shortcuts import render, HttpResponse
from apscheduler.schedulers.background import BackgroundScheduler
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from MeasureThickness.settings import Ba... |
from ED6ScenarioHelper import *
def main():
# 格兰赛尔
CreateScenaFile(
FileName = 'T4205 ._SN',
MapName = 'Grancel',
Location = 'T4205.x',
MapIndex = 1,
MapDefaultBGM = "ed60017",
Flags = 0,
... |
Import("env_rovinj_numopt_tut_ext")
env = env_rovinj_numopt_tut_ext.Clone()
env.SharedLibrary(target='#lib/rovinj_numopt_tut_constraints_ext',
source=["constraints_ext.cpp"])
|
import numpy as np
import math
import cv2
from PIL import Image
class ImageProcessor:
def __init__(self):
pass
def process(self, filename):
image = cv2.imread(filename)
self.num_pixels = image.shape[0] * image.shape[1]
return image
def histogram(self, image, bins=256):
... |
#/usr/bin/env python
# Author:tjy
'''
file = open("username_passwd.txt", 'r')
line = file.readline()
while line:
print(line) ,
line = file.readline()
file.close()
'''
'''
for line in open("username_passwd.txt", 'r') :
print(line)
'''
file = open("username_passwd.txt", 'r')
lines = file.readlines()
print(... |
#!/usr/bin/env python2
"""Parse and download images from an Imgur gallery.
The creation of this script was inspired by Methos25's rice [1]. I loved the
wallpaper he was using, and looking on the Imgur gallery [2] he told us he got
the image, I had the idea to create a script to download all images from there
and rando... |
import tkinter as tk
root = tk.Tk()
anchors = [tk.E, tk.W, tk.S]
texts = ["Hello","Python","Language"]
for i in range(3):
b = tk.Button(root, text=texts[i])
b.pack(anchor=anchors[i])
root.mainloop()
|
def wrapper(f):
def fun(l):
f(['+91 ' + c[-10:-5] + ' ' + c[-5:] for c in l])
return fun
|
# @Title: 验证栈序列 (Validate Stack Sequences)
# @Author: 2464512446@qq.com
# @Date: 2020-06-18 17:11:12
# @Runtime: 112 ms
# @Memory: 13.4 MB
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
res = []
i = 0
for num in pushed:
res.app... |
from flask import Response
from tests.test_client import flask_app
from pypi_org.views import home_views
def test_int_homepage(client):
r: Response = client.get('/')
assert r.status_code == 200
assert b'Find, install and publish Python packages' in r.data
def test_v_homepage_directly():
with flask_... |
def num_teachers (value):
#print(kwargs)
#print("{Kenneth Love}".format(**kwargs))
print(len(value.keys()))
def num_courses (value):
course_total = 0
for course in value.values():
course_total += len(course)
return course_total
def courses (value):
courses_list = []
for courses in valu... |
import argparse
import pickle
import collections
import logging
import math,copy
import os,sys,time
import errno
import random
from sys import maxsize
import pickle
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.autograd as autograd
import torch.optim as optim
im... |
import msgpackrpc
import sys
import time
import logging
from functools import wraps
RETRY_COUNT = 3
RETRY_WAIT_TIME = 10
logging.basicConfig(level=logging.DEBUG)
def retry_call(preretry_method):
def _retry_call(func):
@wraps(func)
def __retry_call(*args, **kwargs):
cnt = RETRY_COUNT ... |
import time
from multiprocessing import Process
from main.info import config
#from main.data_structure import vector as vector1
from main.data_structure import sparseVector as vector
user_mean_matrix = {}
def init_user_mean_matrix(dao):
maxuserid = config.Config().configdict['dataset']['maxuserid']
for i in r... |
import pandas as pd
class polutantSlicer :
def __init__(self,keep_wind) :
#These indexes are kept for slicing the input data on the type of polutants
self.index_PM2 =[]
self.index_PM10 =[]
self.index_O3 =[]
self.index_NO2 =[]
"""
self.index_PM2_label =[]
... |
from random import randint, seed, choice
# 🚨 Don't change the code below 👇
test_seed = int(input("Create a seed number: "))
seed(test_seed)
# Split string method
namesAsCSV = input("Give me everybody's names, seperated by a comma.\n")
names = namesAsCSV.split(", ")
# 🚨 Don't change the code above 👆
#Write your ... |
from PyQt5.QtWidgets import *
from src.UI.item_widget import ItemWidget
from src.item import Item
class TodayTasks(QWidget):
def __init__(self, userList):
QWidget.__init__(self)
self.userList = userList
self.itemIndex = {}
self.index = 0
self.initUI()
def initUI(self):
... |
from app import db
class Assets(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255), unique=True)
model = db.Column(db.String(255))
osversion = db.Column(db.String(255))
assignee = db.Column(db.Integer, db.ForeignKey('users.id'))
def __init__(self, name, mod... |
"""
You are given a binary tree. You need to write a function that can determine if
it is a valid binary search tree.
The rules for a valid binary search tree are:
- The node's left subtree only contains nodes with values less than the node's
value.
- The node's right subtree only contains nodes with values greater t... |
import unittest
class GridBoxAreaTests(unittest.TestCase):
def test_gridboxarea(self):
pass |
sum([x for x in range(0,1000) if (x%3==0 or x%5==0)])
|
# coding: utf-8
# Copyright 2013 The Font Bakery Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... |
from django.contrib.auth.decorators import permission_required
def researcher_permission_required():
"""
Custome decorator for researcher with a login url set based on this application
"""
return permission_required('research.is_researcher', login_url="/login/")
|
from extensions import db
from flask import Blueprint, make_response, jsonify, request
from models import User, Activity, Action, Book, Review, Achievement
from follow.routes import get_followed_users
from sqlalchemy.sql import label, func
import datetime
activity = Blueprint('activity', __name__)
@activity.route("/... |
while True:
try:
number = input("Enter a number: ")
except NameError:
pass
|
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Organization)
admin.site.register(Project)
admin.site.register(Team)
admin.site.register(ProjectTeam)
admin.site.register(Person)
admin.site.register(TeamMember)
admin.site.register(OrganizationalRole)
admin.site.re... |
from datetime import datetime
import os
import sqlite3
import pandas as pd
import boto3
s3 = boto3.client("s3")
COVID_BASE_DATE = datetime(2019, 12, 31)
DATA_PATH = "M:\Documents\@Projects\Covid_consolidate\output"
os.chdir(DATA_PATH)
list_of_files = os.listdir(DATA_PATH)
STANDARD_COL = [
"incidence",
"notif... |
# implementação do método iterativo SOR para o EP3.
import matplotlib.pyplot as plt # Para plotar gráficos
import math # Para trabalhar com funções matemáticas
import numpy as np # Para trabalhar com matrizes
import random # Para gerar números aleatórios
... |
from lxml import etree
import vobject
hcard = """<div class="vcard">
<a class="fn org url" href="http://www.commerce.net/">CommerceNet</a>
<div class="adr">
<span class="type">Work</span>:
<div class="street-address">169 University Avenue</div>
<span class="locality">Palo Alto</span>,
<abbr class="... |
import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import pandas as pd
import xlrd
def namesAndEmails():
loc = "pathToAlumniListCSV"
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(4)
master = []
for i in range(1,5746):
if (s... |
def solution(tickets) :
vertexList = set()
adjacencyList = {}
visitedVertex = []
stack = []
for vertex in tickets:
for i in range(2):
vertexList.add(vertex[i])
if vertex[0] == 'ICN' :
stack.append('ICN')
edgeList = tickets[:]
for vertex in vertexList:
... |
from __future__ import print_function
import time
from pyinstrument import Profiler
# Utilities #
def do_nothing():
pass
def busy_wait(duration):
end_time = time.time() + duration
while time.time() < end_time:
do_nothing()
def long_function_a():
time.sleep(0.25)
def long_function_b():
... |
import re
import threading
import BasicLogger
import numpy as np
import Configs
from Searcher import Search
def get_pattern(c, matrix):
pattern = r'\b'
for i in c:
if ord(matrix[i[0]][i[1]]) == 32 or ord(matrix[i[0]][i[1]]) == 36:
pattern += r'[a-zA-Z]'
else:
... |
import pickle
import numpy as np
import PIL.Image
for i in range (5,13):
f = open('/run/media/rvolpi/data/renvision_data/P38_06_03_14_ret1/experiments/t0_modSmall_single_pca_cond_' + str(i) +'/crbm_tmp.pkl')
data = pickle.load(f)
W = data.params[0].get_value(borrow=True)
A = data.params[1].get_val... |
import time
a,b,c = 4,5,6
# 3 ta bir xil False False False
# agar istalgan 2 ta ozg qiymati bir xil bolsa natija False
# brortasi 0 ga teng bolsa True
bosh_vaqti = time.time()
for i in range(10000):
if a > 0:
if a == b == c :
print('False False False')
elif a==b or b==c or a==c:
... |
from .models import Post, Reply
import datetime
'''
This function can be used to insert a main post in the forum.
It takes in three parameters, user, title and content.
user is an entry to a user (can be either a pet owner, a vet or a clinic) of the app.
No check of the user inside the function is provided so the va... |
from collections import Counter
X = int(input())
shoe_sizes = Counter(list(map(int, input().split())))
N = int(input())
collected_money = 0
for customer in range(N):
desired_shoe, price = tuple(map(int, input().split()))
if desired_shoe in shoe_sizes.keys() and shoe_sizes[desired_shoe] > 0:
collected_m... |
# -*- coding: utf-8 -*-
import urllib
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.util.compat import Directive
IMG_TAG = """\
<img alt="{alt}" src="http://maps.googleapis.com/maps/api/staticmap?{query}">\
"""
IFRAME_TAG = """\
<iframe
width="{width}"
height="{height}"
fr... |
# Generated by Django 3.0.8 on 2020-11-28 11:54
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('LandingPage', '0006_auto_20201120_1645'),
]
operations = [
migrations.RenameField(
model_name='queries',
old_name='reply',
... |
import os
import sys
main_dir = os.path.split(os.getcwd())[0]
result_dir = main_dir + '/results'
sys.path.append(main_dir)
from data import fmri_data_cv as fmril
from data import fmri_data_cv_rh as fmrir
from data import meg_data_cv as meg
from model import procedure_function as fucs
from sklearn.externals import jo... |
import cv2 as cv
import sys
# 적응형 이진화 Adaptive thresholding : 이미지를 작은 영역으로 나누어 각 영역별로 다른 임계값을 적용
img_color = cv.imread("../sample/copy_paper.png", cv.IMREAD_COLOR)
if img_color is None:
print("이미지 파일을 읽어올 수 없습니다.")
sys.exit(1)
img_gray = cv.cvtColor(img_color, cv.COLOR_BGR2GRAY)
img_binary = cv.adaptiveThr... |
import logging
import argparse
from dynaconf import settings
from app.commands import available_commands
def main():
commands = available_commands()
parser = argparse.ArgumentParser(description=settings('application_description'))
parser.add_argument('--rds',
help='Desired action... |
# Find the correlation between the annual salary and the length of the service period of a Lyft driver.
import pandas as pd
# Start writing code
lyft_drivers.end_date.fillna(pd.Timestamp.now(), inplace=True)
lyft_drivers['service'] = (lyft_drivers.end_date - lyft_drivers.start_date)\
.dt.day... |
import socket
import numpy as np
import os
import sys
import threading
import time
import signal
import termios
import queue
import weakref
from datetime import datetime
import cv2
import uuid
from controllers import Controller
import traceback
# Socket server configuration
SERVER_IP = "0.0.0.0"
SERVER_PORT = 953
MAX_... |
from __future__ import annotations
from .mypy_helpers import MypyAssert
def test_model_init(assert_mypy_output: MypyAssert) -> None:
assert_mypy_output(
"""
from pynamodb.attributes import NumberAttribute
from pynamodb.models import Model
class MyModel(Model):
my_hash_key = NumberAtt... |
#!/usr/bin/env python3
import json
import requests
import random
import sys
from io import BytesIO
from optparse import OptionParser
from pathlib import Path
from PIL import Image, ImageChops
def cutImage(im, width, height, resample = Image.BILINEAR):
ratio = width / height
if (im.width < width):
im = im.resize(... |
List = [ 12, 23, "Hello", 60.6, "Chennai" ]
List1 = [ 21, 32, 60 ]
a = List [ 1:3 ]
b = List * 2
c = List + List1
print List
print "\n", a
print "\n", b
print "\n", c
|
class Queue(object):
def __init__(self, alist):
self.alist = alist
def enqueue(self, param):
self.alist.append(param)
return param
def dequeue(self):
aparam = self.alist[0]
self.alist = self.alist[1:]
return aparam
alist = [5, 4, 8, 7]
queue = Queue(alist)... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import io
import os
from glob import glob
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import relpath
from os.path import splitext
from setupto... |
import os
from Services.RetinaFaceLocatorService import RetinaFacesLocatorService
from Services.Img2PoseLocatorService import Img2PoseLocatorService
from Services.SaveFacesJson import SaveFacesJson
from Services.SaveFacesJpg import SaveFacesJpg
from Utils.Heuristics.FaceHeuristic import FaceHeuristic
from Utils.Heuris... |
from gym_RTStrade.envs.rtsTrade_env import rtsTrade_env |
# Generated by Django 2.1.2 on 2019-02-16 17:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('experiments', '0002_auto_20190108_1450'),
]
operations = [
migrations.AddField(
model_name='experiment',
name='check... |
# -*- coding: utf-8 -*-
import os
import irc3
from irc3 import asyncio
from irc3.plugins.command import Commands
__doc__ = '''
=================================================
:mod:`irc3.plugins.shell_command` Shell commands
=================================================
Allow to quickly add commands map to a shel... |
# -*- coding: utf-8 -*-
# 爬取斗鱼直播颜值区主播图片并保存在本地
# imagepipeline的使用
import scrapy
import json
from douyu_yz.items import DouyuYzItem
class DouyuspiderSpider(scrapy.Spider):
name = 'douyuSpider'
allowed_domains = ['douyucdn.cn']
offset = 0
url = 'http://capi.douyucdn.cn/api/v1/getVerticalRoom?limit=20&off... |
'''
Author: Guanghan Ning
E-mail: guanghan.ning@jd.com
April 23rd, 2019
LightTrack: A Generic Framework for Online Top-Down Human Pose Tracking
Demo on videos using YOLOv3 detector and Mobilenetv1-Deconv.
'''
import time
import argparse
# import vision essentials
import cv2
# import Network
from n... |
from __future__ import unicode_literals
from django.core.exceptions import PermissionDenied
class RateLimited(PermissionDenied):
pass
|
checkpoint_folder = './checkpoint'
log_folder = './log'
embedding_dim = 300
encoder_hidden_dim = 150
decoder_hidden_dim = 150
dot_attention_dim = 150
max_question_len = 20
NULL = '--NULL--'
OOV = '--OOV--'
SOS = '--SOS--'
EOS = '--EOS--'
NULL_ID = 0
OOV_ID = 1
SOS_ID = 2
EOS_ID = 3
keep_prob = 0.7
raw_train_file = './d... |
# Write a function that will sum up all the elements in a list up to but not including the first even number.
def testEqual(s1,s2):
print(s1, " | ", s2, " : ", s1==s2)
def sum_of_initial_odds(nums):
sum = 0
for item in nums:
if item%2 == 0:
break
sum += item
return sum
testEqual(sum_of_initial_... |
from datetime import datetime
from typing import Optional
from pydantic import BaseModel
import pydantic
from models.location import BeerPlace
class ReviewSubmittal(BaseModel):
beerplace: BeerPlace
description: str
rating: int
@pydantic.validator('rating')
@classmethod
def rating_boud(cls, ra... |
import numpy as np
import sys
import math
import operator
import csv
import glob,os
import xlrd
import cv2
import pandas as pd
import os
import glob
import matplotlib.pyplot as plt
from reordering import readinput
from random import randint
from augmentation import *
def augment_crop(image, style, row=224, col=224, ... |
import asyncio
from aiohttp import web
async def handle_health(request):
return web.Response(
status=200,
content_type='text/html',
text="<html><head><title>Dragonbot</title></head><body>Healthy</body></html>",
)
print('Starting web server')
app = web.Application()
app.add_routes([web.... |
import unittest
from libs.models.math import MainMatrix, Nan
class TestMainMatrix(unittest.TestCase):
"""Class to test basic methods of the
MainMatrix() class
"""
@classmethod
def setUpClass(cls):
"""Prepares 5 different matrices and
their `nan`s coordinates (i, j) as global
... |
import os
from day_2 import main
test_input_condition_list = []
test_input_password_list = []
current_dir = os.path.dirname(os.path.abspath(__file__))
input_file = os.path.join(current_dir, 'test_input.txt')
with open(input_file, "r") as openfile:
for line in openfile:
line = line.strip()
test_inpu... |
from decimal import Decimal
from django.test import TestCase
from main import models
class TestModel(TestCase):
def test_active_manager_work(self):
models.Product.object.create(name="The cathedral and the bazaar", price=Decimal("10.00"))
models.Product.object.create(name="Pride and Prejudice", price=Dec... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def count_depth(node):
return -1 if node is None else count_depth(node.left) + 1
def find_leaf(node, n, shift):
if (shift == -1):
... |
number = int(input("Enter a number: "))
def fact(number):
if number == 0 or number==1:
return 1
else:
return number*fact(number-1)
factorial=fact(number)
print("Factorial is {}".format(factorial)) |
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 6 19:52:33 2019
@author: BaX Cruiser
"""
def birthdayCakeCandles(ar):
return ar.count(max(ar))
if __name__ == '__main__':
n= int(input())
ar=list(map(int, input().rstrip().split()))
print(birthdayCakeCandles(ar))
|
"""Utilities for interacting with Pandas objects
"""
import re
from typing import List
import pandas as pd
import numpy as np
def _pdfilt(df, fstr):
m = re.match("(\S*)\s*(<=|>=|==|>|<)\s*(.*)", fstr)
column, op, value = m.groups()
op_table = {"<": "lt", "<=": "ge", ">": "gt", ">=": "ge", "==": "eq"}
... |
## input data
str_path = '//deqhq1/tmdl/TMDL_WR/MidCoast/Models/Dissolved Oxygen/PEST-Synthetic-data/Upper_Yaquina_PEST/python'
str_file_in = str_path + '/' + 'UY_do.out'
str_ins_in = str_path + '/' + 'model_ins.txt'
str_model_out = str_path + '/' + 'model.out'
## functions
## function to read the model ins info file
... |
import logging
import os
from flask import Flask
from werkzeug.utils import import_string
from . import config, db, io
from flasgger import Swagger
from flask_cors import CORS, cross_origin
import csv
import traceback
from flask_rest_api.problems.models import Problem
logger = logging.getLogger(__name__)
def load_da... |
import numpy as np
import matplotlib.pyplot as plt
from CIFtoTensor import CIFtoTensor
cif_file = CIFtoTensor.get_cif_file()
struc = CIFtoTensor.get_pymat_struct(cif_file)
mol_tensor = CIFtoTensor.to3DTensor(struc)
print(mol_tensor.shape) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.