text stringlengths 38 1.54M |
|---|
#-*- coding:utf-8 -*-
"""
Created on 2020/03/03
------
@author: Chao Li; Mengshi Dong; Shaoqiang Han; Lili Tang; Ning Yang; Peng Zhang; Weixiang Liu
Email: lichao19870617@gmail.com; dongmengshi1990@163.com; 867727390@qq.com;
lilyseyo@gmail.com; 1157663200@qq.com; 1597403028@qq.com; wxliu@szu.edu.cn.
"... |
# -*- coding: utf-8 -*-
import re
from nltk.corpus import stopwords
from nltk.collocations import BigramCollocationFinder
from nltk.metrics import BigramAssocMeasures
import os
import math
import pandas as pd
from pandas import ExcelWriter
def stopword_filtered(words):
filtered_list = []
stop_set = set(stopwor... |
"""
Jason Slocum
5.28.2014
DPW
Final API
"""
import webapp2
from pages import Page
import urllib2 #open url, request receive and open info obtained there
from xml.dom import minidom#parse xml
class MainHandler(webapp2.RequestHandler):
"""controls the interaction between the model and the view"""
def get(self):... |
import socket
import tkinter
from tkinter import *
from threading import Thread
import time
def receive():
while True:
try:
msg = s.recv(1024).decode("utf8")
msg_list.insert(tkinter.END,msg)
except:
print("There is an error receiving the message")
... |
#import mhat
LARGE = 1e12
POSITIVE_INFINITY = float("inf")
NEGATIVE_INFINITY = float("-inf")
PI = 3.141592653589793238462643383279502884197169399375
PI2 = PI * 2.0
RADIANS_TO_DEGREES = 180.0 / PI
DEGREES_TO_RADIANS = PI / 180.0 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import copy
import numpy as np
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.INFO)
def predict(image):
y_logit = tf.placeholder(tf.fl... |
result = False
def isAnagram(s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
counter = 0
my_dict = {'a':0, 'b':0, 'c':0, 'd':0, 'e':0, 'f':0, 'g':0, 'h':0, 'i':0, 'j':0, 'k':0, 'l':0, 'm':0, 'n':0, 'o':0, 'p':0, 'q':0, 'r':0, 's':0, 't':0, 'u':0, 'v':0, 'w':... |
import time
from optparse import OptionParser
from math import ceil, log
CROSS_OVER = 1
#hello christi
# standard matrix multiplication
def matrixProduct(X, Y):
n = len(X)
C = [[0 for i in xrange(n)] for j in xrange(n)]
for i in xrange(n):
for k in xrange(n):
for j in xrange(n):
... |
# Generated by Django 2.2.1 on 2019-09-11 09:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tickets', '0007_auto_20190911_1136'),
]
operations = [
migrations.AlterField(
model_name='ticket',
name='quantity_2'... |
#!usr/bin/env python
#coding:utf-8
import os
import time
from base.relay08 import Relayed_device
from base.baseflash import Command
from base.baseflash import check_adb_device
from base.dumbase import base
path = r'/home/buildbot/flashfile/flash'
cmd_list = [r'sudo fastboot boot loader.efi',r'sudo fastboot oem un... |
# search through the titles first
# if books returned list them
# then tags
# dict tuple: [{title, [pages]}]
# list pages the tags show up on
import sys, json, os, pprint
pp = pprint.PrettyPrinter(indent=4)
# json_data = []
# for f in sys.argv[1:]:
# with open(f) as data_file:
# json_data.append(json.load(d... |
import threading
import time
import pygame
from color_constants import GREEN, BLUE, CRIMSON, CORNSILK3, FORESTGREEN, WHITE
class Visualization(object):
CH_1 = 1 # Broken relay
CH_2 = 2 # Red box
CH_4 = 4 # Blue box
CH_8 = 8 # Green box
CH_16 = 16 # Santa
CH_32 = 32 # Dog
CH_64 = 64... |
# (c) 2013-2014 mPlane Consortium (http://www.ict-mplane.eu)
# Author: Danilo Cicalese
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or... |
from cs50 import SQL
import csv
import sys
db = SQL("sqlite:///students.db")
def main():
# Check command-line arguments for valid syntax
if len(sys.argv) != 2:
print('Error: Incorrect usage at command line. Format is import.py database.csv')
sys.exit(1)
# Open CSV file given by command-... |
from django.contrib.auth import authenticate
from django.http import Http404
from rest_framework import status
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import AllowAny
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response... |
#! coding: utf-8
from __future__ import absolute_import, unicode_literals
from os.path import dirname
import environ
from django_datajsonar import strings
from .api.api import *
from .api.metadata import *
from elasticsearch_dsl.connections import connections
SETTINGS_DIR = environ.Path(__file__) - 1
ROOT_DIR = env... |
# Generated by Django 2.2.24 on 2021-08-06 21:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('remplissages', '0002_auto_20210805_1048'),
]
operations = [
migrations.AddField(
model_name='site',
name='descripti... |
import logging
import os
import sys
import threading
import time
import unittest
from aorta.const import CHANNEL
from aorta.const import HOST
from aorta.const import PORT
from aorta.message import Message
from aorta.listener import Listener
import aorta.backends
logger = logging.getLogger()
logger.level = logging.DEB... |
# coding: utf-8
# In[1]:
import sys
if sys.version_info[0] == 2:
import Tkinter as tk
import tkFont as font
else:
import tkinter as tk
from tkinter import font
import PIL.Image, PIL.ImageTk
import cv2
import numpy as np
from keras.models import load_model
from scipy.misc import imresize
from skimage... |
import datetime
import scrapy
from config import BASE_URL
TODAY = datetime.datetime.now()
class TGHeadlinesSpider(scrapy.Spider):
name = 'tg-headlines'
allowed_domains = ['theguardian.com']
def __init__(self, *args, **kwargs):
super(TGHeadlinesSpider, self).__init__(*args, **kwargs)
date ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Profile(models.Model):
username = models.CharField(max_length=200, default="username")
talk = models.NullBooleanField()
sleep = models.NullBooleanField()
drink = models.NullBooleanField()... |
#!/bin/env python3
import datetime
from jobconfig import *
import raconfig
DATA_INICIO = datetime.datetime(2018, 9, 19)
QUANTIDADE_DIAS_PLANEJAR = 7
class Bandeira:
def __init__(self, bandeira, centros_fornecedores, planejadores_mrp, aplicaPasso10=True):
self.bandeira = bandeira
self.centros_for... |
from wcontrol.conf.config import BMI, BFP, MUSCLE, VISCERAL
class results(object):
def __init__(self, control, gender):
self.weight = ''
self.bmi = self.get_bmi(control.bmi)
self.fat = self.get_fat(control.fat, gender)
self.muscle = self.get_muscle(control.muscle, gender)
s... |
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class Userpune(models.Manager):
def get_queryset(self):
return super(Userpune, self).get_queryset().filter(city='Apune')
class Userprofile(models.Model):
user = models.OneToOneFiel... |
# Ask user how many days they worked
ndays = input("Enter the number of days worked: ")
pay = 0.005
for day in range(1,ndays+1):
pay *= 2.0
print("Day", day, "Salary", pay)
print("Your salary on day", ndays, "would be $%.2f" % pay)
|
from django.conf.urls import url
from django.urls import path, include
from apps.scoreboard import views
app_name = "scoreboard"
urlpatterns = [
url(r'^(?P<event_id>\d+)/$', views.scoreboard, name='scoreboard'),
url(r'^$', views.scoreboard, name='scoreboard'),
]
|
# -*- coding: utf-8 -*-
import json
import urllib
import base64
import logging
import hashlib
import words
from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Hash import MD5
from tornado.httpclient import HTTPRequest
from util_tools import gen_order_id
from model.order_model import Th... |
from acp_times import open_time
from acp_times import close_time
import arrow
start = arrow.get("2017-01-01T00:00")
# invalid input
# def test_open_bad_time():
assert (open_time(0, 1200, start) is None)
# def test_close_bad_time():
assert (open_time(0, 1500, start) is None)
# def test_open_control_greater():
a... |
import pandas as pd
import numpy as np
import re
# 固定参数
## 底
base = 1
## 番数
fan_amt = {'门清': 1, '自摸': 1, '庄': 1, '七对': 1, '一条龙': 1, '没混': 1, '海底捞': 1, '海捞': 1,
'杠开花': 1, '杠开': 1, '杠上开花': 1, '捉五魁': 1, '捉五': 1, '混一色': 1, '混清': 1,
'豪华七对': 2, '豪七': 2, '本混龙': 2, '十三幺': 3, '双豪七': 3, '清一色': 3, '风一色': 4, '三豪七': 4}
## 锅外钱数
# m... |
def get_f1(prec, recall):
return 2.0 * prec * recall / (prec + recall)
k = int(input())
cm = [[int(x) for x in input().split()] for _ in range(k)]
sums = [sum(line) for line in cm]
all_sum = sum(sums)
micro_f, precW, recallW = 0, 0, 0
for idx, line in enumerate(cm):
TP = line[idx]
FN = sums[idx] - TP
... |
import settings
import game
def main():
cfg = settings.Settings()
g = game.Game(cfg)
g.setup()
g.main_loop()
main()
|
"""A simple web server that accepts POSTS containing a list of feed urls,
and returns the titles of those feeds.
"""
import eventlet
feedparser = eventlet.import_patched('feedparser')
# the pool provides a safety limit on our concurrency
pool = eventlet.GreenPool()
def fetch_title(url):
d = feedparser.parse(url)... |
from os import lstat
import sqlite3
import json
import codecs
conn = sqlite3.connect('hospitals.sqlite')
cur = conn.cursor()
cur.execute('SELECT * FROM Locations')
fhand = codecs.open('location.js', 'w', "utf-8")
fhand.write("const myData = [\n")
count = 0
for row in cur :
data = str(row[1])
loc... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.listLen = 0
def addToTail(self, data):
self.listLen += 1
if self.head is None:
self.head ... |
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[:4])
thistuple = ("apple", "banana", "cherry", "orange", "kiw... |
graph = {'A': set(['B', 'C']),'B': set(['A', 'D', 'E']),'C': set(['A', 'F']),'D': set(['B']),'E': set(['B', 'F']),'F': set(['C', 'E'])}
# first implementation
def dfs(graph, start):
visited, stack = set(), [start]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.a... |
from numpy import *
from physics import *
from scipy.interpolate import interp1d
def sigma1DNorm(chan,rs):
if chan == 'sWave':
return 1.
elif chan == 'pWave':
return rs*1e-11/sqrt(100.)
def getstructform(chan,structFormType):
if chan == 'sWave':
structFormFName = (
{'rho_eff_Einasto_subs':'structFormDat... |
from ZeroScenarioHelper import *
def main():
SetCodePage("ms932")
CreateScenaFile(
"t4020.bin", # FileName
"t4020", # MapName
"t4020", # Location
0x005D, # MapIndex
"ed7124",
0x00002000, ... |
#!/usr/local/python
#author: george karystianis
import sys
import re
new_file = open(sys.argv[3],'w')
mega={}
mega2={}
for line in open(sys.argv[1],'r'):
if "dose_number" in line:
continue
if "amount\n" == line:
break
boundary = line.find('pr.')
boundary2 = line.find('.txt')
line... |
import numpy as np
import matplotlib.pyplot as plt
A_shape = 200, 300, 3
A = np.zeros(A_shape, dtype=np.uint8)
A[:, :, :] = 255
r = 3/5 * 100
for i in range(A.shape[0]):
for j in range(A.shape[1]):
if (i-A.shape[0]/2)**2 + (j-A.shape[1]/2)**2 <= r**2:
A[i, j, 0] = 255
A[i... |
import vrep, math, time
#Configura conexão com o Vrep, seleciona modo síncrono e inicia simulação
clientID = vrep.simxStart('127.0.0.1', 19997 , True, True, 5000, 5)
vrep.simxSynchronous(clientID, False)
vrep.simxStartSimulation(clientID, vrep.simx_opmode_oneshot_wait)
#Handlers para os objetos no Vrep
ret, roda_d = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from time import gmtime, strftime
from array import array
import re
import shutil
import json
import time
def log(txt):
print txt
try:
file_stat = open('status.json','r')
file_cmd = open('cmd.j... |
from tkinter import *
root =Tk()
root.title("CALCULATOR")
"""inputs"""
num = Entry(root, text="Enter A Number", width=40,borderwidth=5)
num.grid(row = 1, column = 0, columnspan =3)
"""NUMERIC"""
def numb(num_pass):
temp = num.get()
num.delete(0, END)
num.insert(0, str(temp) + str(num_pass))
"""ARITHMETIC OPERATOR... |
"""Demonstrates how to use the StatViewAssist class
This sample requires an already loaded configuration with at least 2 connected vports.
"""
from ixnetwork_restpy import SessionAssistant, StatViewAssistant
session_assistant = SessionAssistant(
IpAddress="127.0.0.1",
UserName="admin",
Password="admin",... |
from .attacker import Attacker
HYDRA_HEALTH = {
"hydra1": 5946906,
"hydra2": 17699730,
"hydra3": 54533157,
"hydra4": 106981939,
"hydra5": 220606896
}
HYDRA_ELEMENTS = ['light', 'darkness', 'earth', 'water', 'fire', 'wind']
class Hydra(object):
def __init__(self, hydra_type: str, element: st... |
# -*- coding: UTF-8 -*-
import unittest
from romme import conversion as conv
republican_leap_years = {3, 7, 11}
# Let's do exhaustive tests because they aren't so many dates
def all_dates():
for y in range(1, 14+1):
for m in range(1, 13+1):
max_days = 30
if m == 13:
... |
from telebot.types import InlineKeyboardMarkup,InlineKeyboardButton, ReplyKeyboardMarkup
inline_key = InlineKeyboardMarkup()
btn = InlineKeyboardButton('Да',callback_data='yes')
btn1 = InlineKeyboardButton('Нет',callback_data='no')
inline_key.add(btn,btn1) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 9 07:16:48 2017
SOLUTIONS TECHNICAL INTERVIEW PRACTICE
@author: jpinzon
"""
'''
QUESTION 1:
Given two strings s and t, determine whether some anagram of t is a
substring of s. For example: if s = "udacity" and t = "ad", then the
funct... |
import pandas as pd
import os
from requests import get
from bs4 import BeautifulSoup
class MovieTitlesExtractor:
__URL = 'https://www.taquillaespana.es/estadisticas/peliculas-espanolas-mas-taquilleras-de-todos-los-tiempos/'
__DIR = './files'
__FILENAME = 'movie_titles.csv'
__COLUMNS = ['Movie', 'Year']
# Pu... |
from idaapi import *
from idautils import *
from idc import *
from ugo.structs import add_struct, add_struct_member
# ADD PCLNENTRY STRUCT
class myplugin_t(idaapi.plugin_t):
flags = idaapi.PLUGIN_UNL
comment = "This is a comment"
help = "This is help"
wanted_name = "My Python plugin"
wanted_hotk... |
from ..q import get_q
from .s import get_s
def get_letters():
return get_q() + ["r"] + get_s()
|
import requests
import json
with open('my.json') as fs:
data=json.load(fs)
f = requests.post('http://127.0.0.1:9999/web/getCoord?width=100&height=100&offset=11',data=json.dumps(data))
result = f.text
print(result) |
"""
2021-3-28
"""
import os
import numpy as np
import torch
from torch.autograd import Variable
import torch.nn as nn
import os
from tqdm import tqdm
# from local_ernie_model import Local_Bert_score
# from global_gcn_model import Global_Fai_score
from global_score_model_3 import Global_Fai_score
from local_cnn_model_1... |
seq = "CTTGAACGCGTCCCGGCTTG"
length = len(seq)
def mutate(base):
assert base in ['A', 'T', 'C', 'G']
if base == 'A':
return ['T', 'C', 'G']
elif base == 'T':
return ['A', 'C', 'G']
elif base == 'C':
return ['A', 'T', 'G']
else:
return ['A', 'T', 'C']
... |
class GlobalKeyword:
scores = 0
def update_scores(new_score):
global scores
scores = new_score
print(scores)
if __name__ == '__main__':
GlobalKeyword()
|
__author__ = 'Michael Redmond'
import vtk
class ModelBaseData(object):
def __init__(self):
super(ModelBaseData, self).__init__()
self.data = vtk.vtkUnstructuredGrid()
self.points = None
self.global_ids = vtk.vtkIdTypeArray()
self.global_ids.SetName("global_ids")
... |
import agent
import environment
import numpy as np
import pandas as pd
import random
import matplotlib.pyplot as plt
env = environment.Environment()
learning_rate = 0.01
gamma = 0.99
MAX_EPISODES = 50000
MAX_STEPS = 10
ACTION_SIZE = 200 # per step 2 dollars
u1 = 100
# Q table contains states x acitons
# states conta... |
#!/usr/bin/python3
"""This module creates a class named Square"""
class Square:
"""A class named Square
Attributes:
attr1 (size): size of square
"""
def __init__(self, size):
"""
Args:
size: size for __size attribute of class instance
"""
self.__size = size
|
#!/usr/bin/env python3
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Import generated translations from Google's internal Translation Console."""
from __future__ import print_function
import glob... |
import numpy as np
import cv2
import random
import math
# running virtual environment on windows
###############################################
# virtualenv env
# .\env\Scripts\activate.bat
# python app.py
# read the image file
img = cv2.imread('maps/atl-2.png', 2)
# convert to binary image
ret, bw_img = cv2.thresh... |
import os
base = os.path.join(os.path.dirname(__file__), '../sample_htdocs')
with open(base + "/index.html", "rb") as f:
root_index = f.read()
with open(base + "/subdir1/index.html", "rb") as f:
subdir1_index = f.read()
with open(base + "/subdir1/subdir11/maoyo.giaogiao", "rb") as f:
maoyo_giaogiao = f.read(... |
# Generated by Django 3.1.8 on 2021-04-16 07:27
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('lockers', '0002_qr'),
... |
from django.urls import path
from tasks import views
urlpatterns = [
path('', views.TasksListView.as_view(), name='tasks_list'),
path('create/', views.TaskCreateView.as_view(), name='task_create'),
path(
'<int:pk>/update/',
views.TaskUpdateView.as_view(),
name='task_update',
),... |
from flask_babel import lazy_gettext
from flask_login import current_user
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms import ValidationError
from wtforms.validators import DataRequired, Length, Email, Regexp, EqualTo
from ..models import User
... |
num = input("Enter the X and Y? ")
X, Y = num.split(',')
result = []
for i in range(int(X)):
result.append([])
for j in range(int(Y)):
result[i].append(i *j)
print(result) |
# Generate Documents
# O(n+m)
# n = len(characters) | m = len(document)
def generateDocument(characters, document):
counter = {}
for char in characters:
if char in counter:
counter[char] += 1
else:
counter[char] = 1
for char in document:
if not char in counter or counter[char] <= 0:
return Fa... |
import pytest
from src.bot import *
bot = telegram.Bot(token=config.BOT_TOKEN)
updater = Updater(token=config.BOT_TOKEN)
def test_main():
result = main()
assert result == 0
def test_main_menu():
global bot
res = main_menu()
assert res == 0
def start(bot, update):
bot.send_message(chat_... |
import pandas as pd
import numpy as np
import re, nltk
from nltk.stem.porter import PorterStemmer
from sklearn.svm import LinearSVC
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.neighbors import *
from sklearn.metrics import classification_report
from sklearn.preprocessing import Impu... |
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import sys
from selenium import webdriver
driver_profile = webdriver.FirefoxProfile()
driver_profile.set_preference('browser.privatebrowsing.autostart', True)
driver = webdriver.Firefox(firefox_profile=driver_profile... |
import argparse
import configparser
import json
import os
import requests
import urllib
from jira import JIRA
jira_user = ''
jira_password = ''
ini_file = ''
parser = argparse.ArgumentParser()
parser.add_argument('--user_name', required=True, help='Enter JIRA user name')
parser.add_argument('--password', required=T... |
from optparse import OptionParser
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import selenium.webdriver.chrome.... |
#This script generates hindi/telugu subtitle file from parallel translated files using eng srt file
from argparse import ArgumentParser
import re
import os
import sys
import pysrt
import nltk
import logger as log
parser = ArgumentParser(description='This script will align Subtitle translation files\n\r'+
"How to... |
def pay(hours, baserate):
if (hours<=40):
pay = hours * baserate
else:
pay = (40 * baserate) + ((hours - 40) * (baserate * 1.5))
return pay
def main():
hours, baserate = eval(input("Please input hours and hourly rate: "))
print ("Total pay: " + str(pay(hours, baserate)))
main() |
# Generated by Django 3.1.7 on 2021-03-03 19:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0019_auto_20210301_2027'),
]
operations = [
migrations.AddField(
model_name='messages',
name='receiver_name'... |
# file: image.py
# author: Muhammad Mushfiqur Rahman <mushfiq.rahman@tum.de>
# date: 05-21-2019
# This is a image model file.
import sys, os
import uuid
from database.dbutility import time_iso8601
from database.models.project import Project
class Image(object):
def __init__(self):
#All object parameters ... |
import pandas as pd
import os
ratings_small_input_file = os.path.join(os.path.dirname(__file__), "../../", "input", "ratings_small.csv")
ratings_input_file = os.path.join(os.path.dirname(__file__), "../../", "input", "ratings.csv")
movies_input_file = os.path.join(os.path.dirname(__file__), "../../", "input", "movies_... |
# -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
plt.plot([1,2,3,2,1,2,3,4,5,6,5,4,3,2,1])
plt.show()
|
#!/usr/bin/python
import argparse
import sys
import os
import re
def getReadFromFasta(fin):
output = ""
for line in fin:
if line.strip("\n").strip() != "":
if line[0] != ">":
output += line
else:
if output != "":
yield output... |
import sys
assert sys.version_info[0] >= 3, "Python 3 required."
from collections import OrderedDict
def label_to_nl(label_file, nl_file, range_min, range_max):
labels = []
try:
of = open(label_file, "rt")
labels = of.readlines()
except IOError:
print("skipped: "+label_f... |
import pandas as pd
import mido
def midi2nmat(path):
"""Returns a Note Matrix from a given MIDI files"""
assert (type(path) is str), "Filepath must be a string: %r" % path
mid = mido.MidiFile(path)
tpb = mid.ticks_per_beat
output=pd.DataFrame(columns=["Type", "Voice", "Pitch", "Velocity", "Ti... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
# path('upload', NewAudio.as_view())),
path('uploads', views.index, name='index'),
path('subscriptions', views.index, name='index'),
# path('<int:id>', AudioListen.as_view()),
# path('comment'... |
class Product:
def __init__(self):
self.name='Iphone'
self.description='High Price'
self.price = 1000
pl=Product()
print(pl.name)
print(pl.description)
print(pl.price)
|
#!/usr/bin/env python3
nums = map(int, input().split())
def metasum(nums):
cs, ms = next(nums), next(nums)
n = sum(metasum(nums) for i in range(cs))
n += sum(next(nums) for i in range(ms))
return n
print(metasum(nums))
|
import numpy as np
from utils import im2col
class ConvolutionalNet():
"""
Description:
The definition of our naive CNN, it is made of
One convolution layer
One ReLU layer
One pooling layer
One fully connected layer
One softmax la... |
"""
======================COPYRIGHT/LICENSE START==========================
EditPeakAliasing.py: Part of the CcpNmr Analysis program
Copyright (C) 2003-2010 Wayne Boucher and Tim Stevens (University of Cambridge)
=======================================================================
The CCPN license can be found ... |
#This example talks about all the basic comaprision operators
x = 2
y = 3
print(x == y)
print(x+1 == y)
print(x < y)
print(x > y)
print(x >= y)
print(x <= y)
print(x != y)
def compare_integors(x, y) :
if x == y or x < y :
return 'x is less than or equal to y'
return 'y is always greater than x'
print(comp... |
#!/usr/bin/env python
# -*- coding: CP1252 -*-
#
# generated by wxGlade 0.6.8 (standalone edition) on Tue Oct 07 12:53:43 2014
#
import wx,wx.grid,win32com.client,json,os,subprocess,win32clipboard,time,win32con
from threading import Thread
from Queue import Queue, Empty
class NonBlockingStreamReader... |
def answer(x):
result = []
for item in x:
if item not in result:
if item[::-1] not in result:
result.append(item)
return len(result)
#test = ["abc", "cba", "bac"]
#test = ["foo", "bar", "oof", "bar"]
test = ["x", "y", "xy", "yy", "", "yx"]
print answer(test)
|
def flatten(l):
if type(l) != type([]): return [l]
if l == []: return l
else:
return flatten(l[0]) + flatten(l[1:])
assert(flatten([1,[2]]) == [1,2])
print "hi2"
assert(flatten([1,2,[3,[4,5],6],7]) == [1,2,3,4,5,6,7])
print "hi3"
assert(flatten(['wow', [2,[[]]], [True]]) ==['wow', 2, True])... |
#Project Euler problem 9
#pythagorean triple that sums to 1000
'''
SOME MATH
Observing that squaring any imaginary number yields
an integer pythagorean triplet, and using this fact to
generalize, I found a formula for generating pythagorean triples.
it is: (u^2-v^2,2uv,u^2+v^2)
summing those variables and setting it eq... |
# Contributors: Aure, Kowther
from flask import url_for
from app.models import User
from tests.test_main import BaseTestCase
class TestPosts(BaseTestCase):
def test_login_fails_with_invalid_details(self):
response = self.login(email='atlas@gmail.com', password='password')
self.assertIn(b'Invalid... |
import os
import re
import os.path
from iptcinfo import IPTCInfo
from galleryitem import JpegPicture, JpegDirectory, directory_name_to_html_file_name
from ..utils.inject import assign_injectables
def is_jpeg_file(file_name):
"""
Determine if a file is labeled as a JPEG.
Args:
file_name the name of the file.... |
class Solution:
def totalMoney(self, n: int) -> int:
d, m = divmod(n, 7)
return (49 + 7 * d) * d // 2 + (2 * d + m + 1) * m // 2
|
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from django.template import loader
from core.decoratos import login_required, admin_required
from order.forms import OrderCreateForm
# External Architecture
from order.repository.repository_django_orm import Repository
from orde... |
import MySQLdb
# conn=MySQLdb.connect(host='localhost',port=3306,user='root',passwd='ws940113ZYF',db='test',charset='utf8')
# cur=conn.cursor()
#
# cur.execute("""
# create table if not EXISTS account
# (
# accid int(10) PRIMARY KEY ,
# money int(10)
# )
# """)
#
# cur.execute('insert into account(accid,money) VALU... |
# Create your tasks here
from __future__ import absolute_import, unicode_literals
from mobility_5g_rest_api.models import Event, RadarEvent
import json
from datetime import datetime, timedelta
from celery import shared_task
from celery.utils.log import get_task_logger
from mobility_5g_rest_api.utils import process_dai... |
import math
from collections import namedtuple
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize
Record = namedtuple("Record", ['freq', 'delta', 'length'])
baseFreq = 440.0
data = [
# 1
[[30.0 - 2.95], [495.0, 499.0]],
[[30.0 + 0.05], [456.0, 469.5]],
... |
# -*- coding:utf-8 -*-#
# --------------------------------------------------------------
# NAME: 08
# Description: 使用字典:键值对格式存储,相当于java中的map
# Author: xuezy
# Date: 2020/7/6 17:48
# --------------------------------------------------------------
def main():
scores = {'张三': 11, '李四': 12,... |
from .logistic_regression import LogisticRegression
from .linear_regression import LinearRegression
from .dnn import DNN
|
x = 42
if x < 10:
print 'one digit number'
elif x < 100:
print 'two digit number'
else:
print 'a big number'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.