text stringlengths 38 1.54M |
|---|
# -*- coding=utf-8 -*-
import numpy as np
import csv #需要加载numpy和csv两个包
csv_file=open('D:\\新建文件夹\\2018-12-26\\input_2018-12-26 11-07-41_zmt_sitechuang_tang.csv') #打开文件
csv_reader_lines = csv.reader(csv_file) #用csv.reader读文件
date_PyList=[]
for one_line in csv_reader_lines:
date_PyList.append(one_line... |
from __future__ import division
import sys
k = int(sys.argv[1]) # # of homozygous dominant
m = int(sys.argv[2]) # # of heterozygous
n = int(sys.argv[3]) # # of homozygous recessive
t = k + m + n # total # of organisms
# Likelihood of a dominant allele given the first organism is:
# k = homozygous dominant
k_c... |
import logging
import shutil
import requests
from import_export import resources
from import_export.fields import Field
from tablib import Dataset
from .models import Item, Category, CustomImage
logger = logging.getLogger(__name__)
class ObjectResource(resources.ModelResource):
class Meta:
model = Item... |
print('1.USD to GBP\n2.GBP to USD')
x = int(input())
c = ['GBP-USD','1.28','USD-GBP','0.883']
def USDGBP():
y = int(input('input $ amount'))
ug = float(c[3])
z = y*ug
print('a rate 1$ to ',c[3],'£ your money would equal ',z,'GBP')
def GBPUSD():
y = int(input('input $ amount'))
ug = flo... |
#!/usr/bin/python3
import numpy as np
import pyccl as ccl
import sacc
from tjpcov.covariance_clusters import CovarianceClusters
from tjpcov.covariance_cluster_counts_gaussian import ClusterCountsGaussian
from tjpcov.covariance_cluster_counts_ssc import ClusterCountsSSC
from tjpcov.clusters_helpers import FFTHelper
impo... |
import cv2
from path_names import PathNamesSegmentation as pns
import numpy as np
import matplotlib.pyplot as plt
from skimage import morphology
from scipy import ndimage as ndi
OUTPUT_FOLDER_MASK = pns.SEGMENTED + "otsu\\mask\\image4"
OUTPUT_FOLDER_SEGMENTED = pns.SEGMENTED + "otsu\\segmented\\image4"
def do_Otsu(fi... |
import sys
import os
import argparse
from flask import Flask, jsonify
from flask import request
# fix app root
app_root = os.getcwd()
sys.path.append(app_root)
from app.config import app_ip, app_version
from app.logger import get_logger
log = get_logger(__name__)
flask_app = Flask(__name__)
log.info('app root dir: ... |
from flask import Flask, render_template, session, redirect, url_for
from model import Formulario, procuraAgenciasBB
app = Flask(__name__)
app.config.from_mapping(SECRET_KEY='JAJAJKKKAHERJJCCAASS')
@app.route('/', methods=['GET', 'POST'])
def index():
form = Formulario()
if form.validate_on_submit():
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import importlib
class LibsLoader():
def load(self, lang):
module = "{}.nationalities".format(lang)
if not os.path.exists(module):
module = "nationalities"
lang_module = importlib.import_module(module)
LangClass = getattr(lang_module, "Nationalitie... |
# Generated by Django 3.1.2 on 2021-06-23 00:36
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('GestionUsuario', '0003_auto_20210621_2358'),
]
operations = [
migrations.AlterModelTable(
name='usuario',
table='USUARIO',
... |
"""CoolServer URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-ba... |
import logging
import configparser
from projectTS.lib.postData import postData
import projectTS.vals as vals
logger = logging.getLogger('projectTS.imagesProcessing.updateTrafficDensity')
config = configparser.ConfigParser()
config.read('config.ini')
default = config['DEFAULT']
server = default['server']
postDataNsp... |
# Numbers and Maths
print "I will now count my chickens:"
print "Hens", 25+30/6
print "Roosters", 100-25*3%4
print "Now I will count the eggs:"
print 3+2+1-5+4%2-1/4+6
print "Is it true that 3+2<5-7?"
print 3+2<5-7
print "What is 3+2?",3+2
print "What is 5-7?",5-7
print "Oh, that's why its false"
print "How about ... |
class ItemValue:
"""Item Value DataClass"""
def __init__(self, wt, val, ind):
self.wt = wt
self.val = val
self.ind = ind
self.cost = val // wt
def __lt__(self, other):
return self.cost < other.cost
def fractional_knapsack_max_value(wt, val, capacity):
i_val = ... |
from adapters.examination_adapter import ExaminationAdapter
def test_should_group_examinations():
fake_response = [{
'node': {
'title': '301413532',
'record_fields': [
{
'name': 'id_avaliacao_lms',
'value': '356366'
... |
def negativeindex():
# Negative indexing for accessing tuple elements
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')
print (my_tuple)
# Output: 't'
print("index -1 : ",my_tuple[-1])
# Output: 'p'
print("index -6 : ",my_tuple[-6])
negativeindex()
|
#!/usr/bin/env python
# $Id$
##
## This file is part of pyFormex 0.7.1 Release Sat May 24 13:26:21 2008
## pyFormex is a Python implementation of Formex algebra
## Website: http://pyformex.berlios.de/
## Copyright (C) Benedict Verhegghe (benedict.verhegghe@ugent.be)
##
## This program is distributed under the GNU Gene... |
"""
将 only_id:comp_full_name 放入 id_name_all
"""
import os
import sys
f = os.path.abspath(os.path.dirname(__file__))
ff = os.path.dirname(f)
fff = os.path.dirname(ff)
sys.path.extend([f, ff, fff])
import pymysql
import traceback
from dim.utility.tools import get_redis_db, in_redis_hash, in_redis_string
from dim.utilit... |
# coding=utf-8
def scramblies(str1, str2):
str1 = set(str1)
str2 = set(str2)
return str2.issubset(str1)
|
import cv2
import numpy as np
import Image
#img = Image.open('image032.png')
#img.save('image032.jpg')
res = cv2.imread('image002.jpg',1)
#img = cv2.resize(res,None,fx=0.25, fy=0.25, interpolation = cv2.INTER_CUBIC)
img = cv2.resize(res,(640,491))
cv2.imshow('initial',img)
#cv2.imshow('image',img)
# Conve... |
from Drop import Drop
global drop
def setup():
global x,y, drop
size(400,400)
background(0)
drop = Drop()
def draw():
global x,y,drop
background(0)
drop.move() #move down
drop.display() |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 24 14:04:13 2021
@author: chere
"""
import random
from rpi_ws281x import Color
class Train():
def __init__(self,master,position,speed,minSpeed,acc,goingUp, bounds, tailFactor,color=(255,255,255)):
self.master = master
self.position = position
... |
import math
class BasePlayer:
def __init__(self, maxDepth):
self.maxDepth = maxDepth
##################
# TODO #
##################
# Assign integer scores to the three terminal states
# P2_WIN_SCORE < TIE_SCORE < P1_WIN_SCORE
# Access these with "self.TIE_SCORE", etc.
... |
import django_filters
from trips import models
class TripFilter(django_filters.FilterSet):
class Meta:
model = models.Trip
fields = ['destination']
|
from flask import Blueprint, flash
coaction = Blueprint("coaction", __name__, static_folder="./static")
@coaction.route("/")
def index():
return coaction.send_static_file("index.html")
## Add your API views here |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 22 13:38:44 2019
@author: Fabiana
"""
#####################################
# CHAPTER 17 - DEPLOYING YOUR CODE
#####################################
# Go to this link to check the application online: https://stark-shore-59149.herokuapp.com/ |
# We will create a query "hello" that returns string "world"
import graphene
import json
# Create graphen root query class with subclass graphene.
class Query(graphene.ObjectType):
# First argument is hello of type string
hello = graphene.String()
# Is the new user admin?
is_admin = graphene.Boolean()
# How to... |
def mul2(x):
return x * 2
def map_yield(func, arr):
it = iter(arr)
for i in it:
yield func(i)
def test_map_rek():
assert map_yield(mul2, (1, 2, 3)) == [2, 4, 6]
assert map_yield(str, (1, 2, 3)) == ["1", "2", "3"]
print "Test map_rek passed OK!"
def is_positive(num):
return num ... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
import astropy.units as u
from astropy import constants as const
from scipy import optimize
import math
# In[2]:
############################Constants##########################
G = 4.299E-9 #Gravitational constan... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 3 15:48:18 2018
@author: bartonjo
Get the SRIM data out of the txt files and convert the data into
useable units.
"""
import sys
s = '/Users/bartonjo/PyFiles/LP/'
if s not in sys.path:
sys.path.insert(0, s)
from cookbook import savitzky_golay as smooth
import pand... |
"""
Return a list of the numerical headers
"""
def get_num_headers(values):
num_headers = []
non_num_headers = []
for elem in values:
try:
(float(values[elem][1]) or int(values[elem][1]))
num_headers.append(elem)
except:
non_num_headers.append(elem)
... |
import requests
from bs4 import BeautifulSoup
import pandas as pd
from datetime import datetime, date
main_url = "https://sagittarius.com/archive/{}"
df = pd.DataFrame(columns=['start_date', 'end_date', 'sign', 'horoscope'])
i = 0
page = 1
while page <= 113:
try:
main_req = requests.get(main_url.format(p... |
import pandas as pd
import numpy as np
from keras.models import Model, Sequential
from keras.layers import Input, Dense, Dropout, Flatten, Activation, Reshape
from keras.layers.convolutional import Conv2D, ZeroPadding2D
from keras.layers.pooling import MaxPooling2D, AveragePooling2D
from keras.optimizers import S... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import datetime as dt
from urllib.request import urlretrieve, urlopen, URLError
import os
here = os.path.dirname(os.path.realpath(__file__))
HOME = os.getenv('HOME')
## Get screen resolution
com = "xdpyinfo | grep dimensions"
res = os.popen(com).read().split()[1]
model_s... |
import sys
# def hello():
# print("Hello")
#
#
#
# def max(a, b):
# if a > b:
# return a
# else:
# return b
#
#
# print(max(5,4))
#
#
# def area(w, h):
# return w * h
#
# def welcome(name):
# print("welcome", name)
#
#
# w = 4
# h = 5
#
# print(area(w, h))
#
# welcome('hello')
#
# a=... |
import sys, pygame, glob, random
from pygame.locals import *
pygame.init()
# Game Screen Dimension
size = width,height = 640,480
screen = pygame.display.set_mode(size)
pygame.display.set_caption('BUBBLE TROUBLE')
#pygame.mouse.set_visible(True)
# Color Definition
black = 0,0,0
white = 255,255,255
blue = 0,0,255
green... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
from setuptools import find_packages, setup
NAME = 'azion-python'
DESCRIPTION = "Python client to interact with Azion's ReST API"
URL = 'https://github.com/mauricioabreu/azion-python'
EMAIL = 'mauricio.abreua@gmail.com'
AUTHOR = 'Maurício Antunes'
REQ... |
class DoubleNode:
def __init__(self, val):
self.val = val
self.next = None
self.prev = None
def traverseForward(self):
node = self
while node != None:
print (node.val) # access the node value
node = node.next # move on to the next node
def tr... |
import csv
import json
class CSVFile:
def __init__(self, path="data/alldata.csv", num_rows=1000):
self._path = path
def create_file(self, data):
with open(self._path, "w", newline="") as file:
writer = csv.writer(file, delimiter=",")
writer.writerows(data)
class JSONFi... |
from itertools import combinations
# Determine start time
import time
start = time.time()
# Data Set 1:
items = (
("Item 1", 1, 1), ("Item 2", 1, 2), ("Item 3", 1, 3), ("Item 4", 1, 4), ("Item 5", 1, 5)
)
cap = 4
#
# # Data Set 2:
# items = (
# ("Item 1", 2, 5), ("Item 2", 2, 5), ("Item 3", 2,... |
#!/usr/bin/env python
from distutils.core import setup
setup(name='Cheap Drives',
version='0.2',
description='Finds cheap hard drives',
author='John O\'Connor',
author_email='tehjcon@gmail.com',
scripts=['cheapdrives']
)
|
dee1=input()
vowels=['a','e','i','o','u']
if dee1 in vowels:
print("Vowel")
else:
print("Consonant")
|
import torch
from torchvision import transforms
from torch.autograd.variable import Variable
from torchvision.utils import make_grid
def noise(batch_size, n_features, device='cuda'):
"""creates a noise matrix for a given batch size"""
return Variable(torch.randn(batch_size, n_features)).to(device)
def make_ones(b... |
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException
import time
import json
from selenium import webdriver
"""
In this case, playstation new and upcoming link is a dynamic page so I used Selenium. Scrapy is fast, so all crawled links will be used by it.
... |
#!/usr/bin/python3
'''
Created on 2 Sep 2013
@author: dyc
'''
import sys
import os
import subprocess
from gi.repository import Gtk, Pango
print("python path: %s" % (sys.path))
import mesg_pb2
class PosTransfer:
def __init__(self, textbuffer):
self.textbuffer = textbuffer
# for hexdump: leading a... |
def compute_last_word(input_chars):
seen_so_far = ""
for current_char in input_chars:
if len(seen_so_far) == 0:
seen_so_far += current_char
else:
if current_char >= seen_so_far[0]:
seen_so_far = current_char + seen_so_far
else:
... |
from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
ld = LaunchDescription()
loc_node = Node(
package='crabe_localization',
executable='localizer',
parameters=[{'use_sim_time': True}]
)
cal_node = Node(
package='... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import os
# In[2]:
def load_train(train_path):
f = open(train_path, encoding="utf8")
lines = []
for line in f:
if line != '\n':
line = line.strip('\n').split(' ')
lines.append(line)
... |
# -*- coding: utf-8 -*-
from .deploy import deploy as pool_deploy
from .deploy import redeploy as pool_redeploy
from .deploy import undeploy as pool_undeploy
__all__ = ('pool_deploy', 'pool_redeploy', 'pool_undeploy')
|
import tornado.web
from customer import Customer
import json
class GetHandler(tornado.web.RequestHandler):
def initialize(self, customers):
self.customers = customers
def get(self):
self.write(self.customers.json_list()) |
#!/usr/bin/env python
import numpy as np
from astropy.table import table
from mpdaf.obj import Cube
import argparse
parser = argparse.ArgumentParser(description='Create a muse whitelight image')
parser.add_argument('-f', metavar='MUSE datacube filename', type=str, help='name of the MUSE to catalog', required=True)
ar... |
#============================================================================
#Name : test_configuration.py
#Part of : Helium
#Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
#All rights reserved.
#This component and the accompanying materials are made available
#under the terms ... |
from flask import Flask, render_template, request, jsonify, redirect, url_for, session
import jwt
from datetime import datetime, timedelta
import hashlib
import json
import re
from functools import wraps
from flask_socketio import SocketIO, emit, send
app = Flask(__name__)
app.config['SESSION_COOKIE_HTTPONLY'] = Fals... |
# Cracking the Code interview
# Interview question 1.7
# zero row,col of MxN matrix
def find_zero_row(matrix):
return [i for i, row in enumerate(matrix) if not all(row)]
def find_zero_column(matrix):
# this will transpose the matrix and send it to find rows
return find_zero_row(zip(*matrix))
def zero(mat... |
import tensorflow as tf
from utils.dataset import Dataset
from utils.model import NNModel
params = {
"epochs" : 100,
"batch_size" : 2,
"image_shape" : (224, 224, 3),
"classes" : {"face" : [1, 6, 11, 12, 13], "brow" : [2, 3], "eye" : [2, 3, 4, 5], "lip" : [7, 9], "non-makeup" : [0, 4, 5... |
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from graphene_django.views import GraphQLView
from .schema import schema
urlpatterns = [
path('admin/', admin.site.urls),
path('graphql/', GraphQLView.as_view(graph... |
import sys
import torch
import torch.optim as optim
import aikit.utils
class State:
def __init__(self, steps):
self.steps = steps
self.step = 0
# This is an inspired design from Horovod's `DistributedOptimizer`
def Optimizer(optimizer, steps):
'''
Wraps any valid PyTorch optimizer with Gra... |
# https://learn.adafruit.com/circuitpython-made-easy-on-circuit-playground-express/play-tone
# https://learn.adafruit.com/circuitpython-made-easy-on-circuit-playground-express/buttons
from adafruit_circuitplayground.express import cpx
while True:
if cpx.button_a:
cpx.play_tone(329.63, 1)
cpx.play_t... |
import csv
import pprint
def get_bar_party_data():
"""this function reads from a csv file and converts the data into a list of dictionaries.
each item in the list is a dictionary of a specific location and the number of complaint calls
it received in 2016"""
bar_list = []
with open('bar_locatio... |
"""
Collection of decorators to make our life a little easier
Simple Decorator is based on a recipe from here:
https://wiki.python.org/moin/PythonDecoratorLibrary
"""
### INCLUDES ###
import time
### CONSTANTS ###
## Multiple Attempt Settings ##
ATTEMPT_NUMBER = 10
ATTEMPT_TIMEOUT = 10 # second... |
#!/usr/bin/python
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
import time
from time import sleep
from time import ctime
import random
import re
from selenium.webdriver.support.select import Select
from STxlsdata import g... |
import os, re, time, yaml
import paramiko
import gspread
import xmltodict
import xlrd
from datetime import datetime
from oauth2client.service_account import ServiceAccountCredentials
from .constants import GROUPS, CISCO_USERNAME, CISCO_PASSWORD, Q_ROUTER, NOT_PHY_INTS, STANDARD_PORT_NAMES
def not_pingable(ip)... |
# enter initial amount of investment
c_init = int(input("Enter initial amount of investment:"))
r_rate = float(input("Enter the yearly rate of interest:"))
t_yrs = int(input("Enter number of years till maturation:"))
n_times = int(input("Enter number of times the interest is compounded:"))
# ===========================... |
"""
BSP 28 - Monteur
Dickbauer Yanick 1030489, Moser Patrick 1114954, Perner Manuel 0633155
WS 2016
"""
from lib import random_exp, user_input
NR_MACHINES = 4
FREQUENCY = 10 # simulation steps per hour
SIM_DURATION = 1000 # hour of simulation
STATE_MECHANIC_IDLE = 'drinking coffee'
STATE_MECHANIC_REPAIRI... |
"""
Backwards is no different than forwards but my brain is backwards so it makes
sense.
"""
def longest_subsequence(l, diff):
state = {}
max_length = 0
for n in l[::-1]:
target = n + diff
state[n] = state.get(target, 0) + 1
if state[n] > max_length:
max_length = state[n]
return ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'QtSocket_main.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
Ma... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 23.10.2009
@author: The Zero
'''
import sys
if len(sys.argv)<2:
print( 'Usage: %s <File> ' % sys.argv[0] )
sys.exit(1)
try:
stream = open(sys.argv[1], encoding = 'utf-8')
except Exception:
print( 'Unable to open source fil... |
"""
Function:pre-process data
Author:Will
Date:2019-1-15
Version:1.0
"""
import pandas as pd
from sklearn.preprocessing import Imputer, LabelEncoder, OneHotEncoder, StandardScaler
from sklearn.model_selection import train_test_split
# read data from csv
dataset = pd.read_csv('Data.csv')
X = dataset.il... |
,buyers,prices
0,Carson Busses,$29.95
1,Earl E. Byrd,$8.37
2,Patty Cakes,$15.26
3,Derri Anne Connecticut,$19.25
4,Moe Dess,$19.25
5,Leda Doggslife,$13.99
6,Dan Druff,$31.57
7,Al Fresco,$8.49
8,Ido Hoe,$14.47
9,Howie Kisses,$15.86
10,Len Lease,$11.11
11,Phil Meup,$15.98
12,Ira Pent,$16.27
13,Ben D. Rules,$7.50
14,Ave Se... |
from surprise import (
KNNBaseline, Reader, Dataset, dump
)
# First, train the algortihm to compute the similarities between items
data = Dataset.load_from_file('ratings.csv', reader=Reader(sep=',', rating_scale=(1, 10)))
trainset = data.build_full_trainset()
sim_options = {'name': 'pearson_baseline', 'user_based'... |
import os
import cv2
import numpy as np
from PIL import Image
recognizer = cv2.createLBPHFaceRecognizer()
path = 'dataset'
strvar = 'dataset\\'
def getimgid():
global path
imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
faceSamples = []
ids = []
for imagePath in im... |
# https://atcoder.jp/contests/abc098/tasks/abc098_c
N = int(input())
S = input()
sumsW = [0]
sumsE = [0]
cnt = 0
for i in range(N):
if S[i] == 'W':
cnt += 1
sumsW.append(cnt)
cnt = 0
for j in range(N-1, -1, -1):
if S[j] == 'E':
cnt += 1
sumsE.append(cnt)
sumsE.reve... |
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
bcrypt = Bcrypt()
db = SQLAlchemy()
DEFAULT_IMAGE_URL = "https://www.edmundsgovtech.com/wp-content/uploads/2020/01/default-picture_0_0.png"
def connect_db(app):
"""Connect db to flask app"""
db.app = app
db.init_app(app)
class Fo... |
import cv2
import numpy as np
def abs_sobel_thresh(img,orient='x',thresh_min=0,thresh_max=255):
#转换成灰度图
gray_img=cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
#参考代码方法
#在x和y方向上应用sobel函数
if orient=='x':
abs_sobel=np.absolute(cv2.Sobel(gray_img,cv2.CV_64F,1,0))
if orient=='y':
abs_sobel=np... |
# Example 14.1 Testing for Unit Roots
# Augmented Dickey-Fuller Test for Unit Roots
import numpy as np
import pandas as pd
import statsmodels.api as sm
from statsmodels.tsa.stattools import adfuller
data = pd.read_csv("http://web.pdx.edu/~crkl/ceR/data/usyc87.txt",index_col='YEAR',sep='\s+',nrows=66)
y = data['Y']
c... |
from obiektowosc.Human import Human
class Woman(Human):
#Nadpisywanie konstruktora klasy bazowej
def __init__(self):
#Slowko super pozwala nam odwolac sie do metody z klasy bazowej (w tym wypadku konstruktora)
super().__init__("woman", 55)
self.przedstawSie()
def makeUp(self, dut... |
from flask import Flask
from model import Question, connect_to_db, db
import sys
import random
app = Flask(__name__)
# Required to use Flask sessions and the debug toolbar
app.secret_key = "ABC"
def distribute_questions():
"""Print out num of questions based on argv"""
try:
if sys.argv[1]:
... |
#!/usr/bin/env python2.7
"""Installer for NuTermiNuX."""
import argparse
import datetime
import errno
import distutils.version
import glob
import logging
import os
import platform
import shutil
import subprocess
import sys
BREW = "brew"
BREWDIR = "/home/linuxbrew/.linuxbrew/bin"
CENTOS = "CentOS"
MIN_VERSION = "6.9"
... |
from c1 import hex_to_raw
import string
character_frequencies = {
'e': 12.02,
't': 9.10,
'a': 8.12,
'o': 7.68,
'i': 7.31,
'n': 6.95,
's': 6.28,
'r': 6.02,
'h': 5.92,
'd': 4.32,
'l': 3.98,
'u': 2.88,
'c': 2.71,
'm': 2.61,
'f': 2.30,
'y': 2.11,
'w': 2.... |
from all_anagrams import *
def pair(d):
for anagrams in d.values():
for word1 in anagrams:
for word2 in anagrams:
if word1<word2 and word_distance(word1,word2)==2:
print word1,word2
return
def word_distance(x,y):
x=list(x)
y=list(y)
c=0
for a,b in zip(x,y):
if a!=b:
... |
import nltk
from nltk import FreqDist
from nltk.collocations import*
for num in range(1,8):
print('HP'+str(num)+'.txt')
filename = 'HP'+str(num)+'.txt'
myText = open(filename)
myTexttext = myText.read()
hp1 = myTexttext
len(hp1)
hp1tokens = nltk.word_tokenize(hp1)
len(hp1tokens)
hp... |
import re
from collections import Counter
text = input("Введите текст для подсчета слов: ")
if text == "":
print("К сожалению, вы не ввели текст в консоли, поэтому текст будет загружен из файла!")
document_text = open('text.txt', 'r')
text = document_text.read()
print(text)
else:
print("Текст успеш... |
from django.conf import settings
from api.models import CronJob, CronJobStatus
def ifrc_go(request):
cron_error = CronJob.objects.filter(status=CronJobStatus.ERRONEOUS).order_by('-id').first()
return {
# Provide a variable to define current environment
'GO_ENVIRONMENT': settings.GO_ENVIRONMENT... |
import sys
num = int(sys.stdin.readline())
def findprintorder(numbers, findidx, numofnumber):
idxlst = [i for i in range(numofnumber)]
sortednumbers = sorted(numbers, reverse = True)
for i in range(numofnumber):
while(numbers[i] != sortednumbers[i]):
numbers = numbers[:i] + numbers[i+1:... |
n = int(input())
bars = list(map(int, input().split()))
bars.sort(reverse=True)
count = 0
ans = 1
multi_count = 2
for i in range(0, len(bars) - 1):
if bars[i] == bars[i + 1]:
count += 1
else:
count = 0
if count == 3:
print(bars[i] ** 2)
exit()
elif count == 1:
ans... |
from itertools import islice,count
from math import sqrt
import sys
def isPrime(n):
if n < 2: return False
for i in islice(count(3,2), int(sqrt(n)-1)//2):
if n%i ==0:
return False
return True
inputs = sys.stdin
t = int(next(inputs))
nmax = 0
best_a = 0
best_b = 0
for b in xrange(3,t,2):
... |
from pylab import *
from scipy.optimize import curve_fit
dcc, freq1, freq2 = loadtxt("freqvsdcc2.txt", usecols=(0,1,2), skiprows= 0, unpack =True)
plot(dcc,freq1, 'o')
plot(dcc,freq2, 'o')
hlines(freq2[0],dcc[0],dcc[-1],color='green')
show() |
from audiolazy import *
import matplotlib.pyplot as plt
import numpy as np
from functools import partial
import scipy.io.wavfile as wv
rate = 44100
s, Hz = sHz(rate)
ms = 1e-3 * s
notes = {'C0':16.35,'C#0':17.32,'D0':18.35,'D#0':19.45,'E0':20.60,'F0':21.83,'F#0':23.12,'G0':24.50,
'G#0':25.96,'A0':27.50,'A#0'... |
#!/usr/bin/python
my_rand_list = [5, 6, 4, 1, 7, 3, 2, 0, 8, 9]
largest = -1
for item in my_rand_list:
if(item > largest):
largest = item
print largest,
print
print 'largest number ', largest
|
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
import operator
impo... |
import sys
from _wagyu import Box
from hypothesis import given
from . import strategies
@given(strategies.boxes)
def test_basic(box: Box) -> None:
result = repr(box)
assert result.startswith(Box.__module__)
assert Box.__qualname__ in result
@given(strategies.boxes)
def test_round_trip(box: Box) -> No... |
# Generated by Django 3.0 on 2020-10-26 08:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lib', '0012_auto_20201026_1219'),
]
operations = [
migrations.AlterField(
model_name='brecord',
name='idate',
... |
from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
import json #json.loads는 json형태의 데이터를 딕셔너리로 바꿈
from django.contrib.auth.hashers import check_password
from .models import User
from rest_framework.response import Response
from rest_framework.decorators import api_vi... |
class Proxy:
def __init__(self,proxy):
pro = proxy.split(":")
self.username = pro[2]
self.password = pro[3]
self.host = pro[0]
self.port = pro[1]
return
def geUsername(self):
return self.username
def gePassword(self):
return self.password
... |
node = Node( "TestNode" )
node.i = 15
assert node.i == 15
node.set( 1 )
assert node.get() == 1
child = Node( "TestNode" )
assert not node.hasChild( child )
assert not child.parent()
child.attachToParent( node )
assert node.hasChild( child )
assert node == child.parent()
child.detachFromParent()
assert not child.pare... |
import pyxel
class App:
def __init__(self):
pyxel.init(160, 120)
self.x = 0
pyxel.run(self.update, self.draw)
def update(self):
self.x = (self.x + 1) % pyxel.width # ให้ตำแหน่ง x +1 โดย mod กับขนาดความกว้างของหน้าจอ
def draw(self):
pyxel.cls(0)
pyxel.rect(s... |
import os
import numpy as np
from edflow.data.util import *
def test_plot_datum():
test_image = np.ones((128, 128, 3), dtype=int)
test_heatmap = np.zeros((128, 128, 25), dtype=int)
test_keypoints = np.random.randint(0, 128, (25, 2))
test_example = {
"image": test_image,
"heatmap": t... |
# ---------------------------------------------------------------------------------------
# Call train contour Data set training script with different Fix Initializations of
# J_xy and J_yx
# ---------------------------------------------------------------------------------------
import numpy as np
import torch
from tr... |
from unifier.apps.drf.v1.serializers.favorite import FavoriteSerializer
from unifier.apps.drf.v1.serializers.manga import (
MangaChapterCreateSerializer,
MangaChapterDetailSerializer,
MangaChapterSerializer,
MangaCreateSerializer,
MangaSerializer,
MangaSerializerDetail,
)
from unifier.apps.drf.v... |
from team import Team
from colortext import *
import argparse
import os
import random
import shutil
import ansiwrap
from time import sleep
from match_events import *
from utils import *
from visualization import *
from PyQt5 import QtCore, QtGui, QtWidgets
import constants
#import pyautogui
def calc_score(towers, stac... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.