text stringlengths 38 1.54M |
|---|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
front=head
newtail=head
index=1
if head==None or k==0:
return ... |
# A variable is a container for a value, which can be of various types
'''
This is a
multiline comment
or docstring (used to define a functions purpose)
can be single or double quotes
'''
"""
VARIABLE RULES:
- Variable names are case sensitive (name and NAME are different variables)
- Must start with a letter or... |
# import pygame
# import pgzrun
# from pygame.locals import QUIT, MOUSEBUTTONDOWN
# def win_check():
# for l in reversed(tilestatus):
# ren = 0
# for i in l:
# if i == 1:
# ren += 1
# ren = ren % 10
# elif i == 2:
# ... |
import random
class Humanbeing:
arm=2
leg=2
live=1
def limbs(self):
if(self.live!=0):
print(self.arm, "arms",self.leg,"legs")
else:
print("Human is dead now We are sorry")
def carAccident(self):
print("There was an accident. You are at h... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
COLOR_MAP = sns.light_palette('dark pink', input='xkcd')
def norm_cm(arr):
sums = arr.sum(axis=1)
arr = arr / sums[:, np.newaxis]
arr = arr.round(2)
return arr
def show_cm(arrs, n, label_cm, filename):
fig, ax = plt.subpl... |
import random
def apresentacao():
apresentacao = """
Jogo de adivinhação
Aperte enter para começar\n\n
"""
input(apresentacao)
def gera_numero_aleartorio():
print('Gerando um número entre 1 e 100...')
return random.randint(1, 100)
def main():
apresentacao()
numero_secreto = ge... |
import random
import time
import json
import requests
import datetime
def main(pk):
while(True):
sensor_input = random.uniform(-5, 110)
sensor_input = round(sensor_input, 2)
created_at = datetime.datetime.utcnow() - datetime.timedelta(days=1)
json_created_at = created_at.st... |
#!/usr/bin/env python3
"""
Created on 20 Apr 2021
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
DESCRIPTION
The configuration_monitor_check utility is used to report on the configuration monitor's attempt to access all of
the devices known to the system. Status levels are:
* NOR - NO RESPONSE
* ERR - E... |
import glob
import gzip
import os
import re
from Bio import SeqIO
IDS = [
"frdC",
"frdA",
"epmA",
"mscM",
"psd",
"rsgA",
"orn",
"queG",
"nnr",
"tsaE",
"amiB",
"mutL",
"miaA",
"hfq",
"hflX",
"hflK",
"hflC",
"nsrR",
"rnr",
]
PATTERN = re.compile(f"\[gene=({'|'.join(id_ for id_ in IDS)})\]")
seqs = {key: [] for key in I... |
import math
#Tarif Rental
TarifRental1= 200000
TarifRental2= 10000
#Keterangan Jam
JamMulaiSewa= 6
MenitMulaiSewa= 0
JamSelesaiSewa= 23
MenitSelesaiSewa= 50
#Menghitung Lama Sewa
LamaSewa= math.floor((JamSelesaiSewa-JamMulaiSewa) + MenitSelesaiSewa/60)
#Menghitung Tarif Sewa
TarifSewa= TarifRental1+(TarifRental2*(La... |
import re, os
import pandas as pd
os.chdir('C:/Learning/Python/eleven_projects_python/data_sources')
df = pd.read_csv('survey.csv')
print(df.head())
print('================')
print(df.describe())
print('================')
'1. 빈도 분석: value_counts()'
print(df.sex.value_counts())
print(df.income.value_counts())
print(... |
import opentracing
import requests
from basictracer import BasicTracer
from requests.models import Response
from opentracing_utils import trace_requests
from tests.conftest import Recorder
def assert_send_request_mock(resp):
def send_request_mock(self, request, **kwargs):
assert 'ot-tracer-traceid' in r... |
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'first_project.settings')
import django
django.setup()
## FAKE POP SCRIPT
from first_app.models import User
from faker import Faker
fakegen = Faker()
def populate(N=5):
for entry in range(N):
fake_first_name = fakegen.firs... |
# 1) Uzģenerēt 1-100 un izdrukāt: Ja skaitlis dalās ar 5 tad 'Fizz'. Ja skaitlis dalās ar 7 tad 'Buzz'. Ja skaitlis dalās ar 5 un 7 tad 'FizzBuzz'. Savādāk pats skaitlis.
for i in range(1, 101):
if i == 100:
print(i, end = '\n')
elif i % 5 == 0 and i % 7 == 0:
print('FizzBuzz', e... |
#%%
# -*- coding UTF-8 -*-
'''
@Project : MyProjects
@File : mySignDialog.py
@Author : chenbei
@Date : 2021/3/6 11:11
'''
import matplotlib.pyplot as plt
from matplotlib.pylab import mpl
plt.rcParams['font.sans-serif'] = ['Times New Roman'] # 设置字体风格,必须在前然后设置显示中文
mpl.rcParams['font.size'] = 10.5 # 图片字体大小
... |
#
# The Multiverse Platform is made available under the MIT License.
#
# Copyright (c) 2012 The Multiverse Foundation
#
# 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 restrict... |
from binance.client import Client
from binance import enums
import config
import candle
def get_winning_trends(symbol):
client = Client(config.apiKey, config.apiSecret, tld='us')
winningTrends = {} # Stores the determined trends from first pass, list of lists of candles (length of numOf... |
'''
3 Написать функцию ask_user() чтобы с помощью input() спрашивать пользователя “Как дела?”, пока он не ответит “Хорошо”
'''
def ask_user():
while True:
user_say=input('Как дела ')
if user_say=='Хорошо':
print('Ну пока, раз хорошо')
break
else:
print('... |
#!/usr/bin/env python
#
# Copyright 2007 Google 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 law o... |
from django.http import HttpResponseRedirect,HttpResponse
from django.core.exceptions import PermissionDenied
from django.conf import settings
from functools import wraps
import re
HEADER='HTTP_X_BEARER'
MODERN_HEADER='HTTP_AUTHORIZATION'
import logging
logger = logging.getLogger(__name__)
def superuser(function):... |
from django import apps
class AppConfig(apps.AppConfig):
name = 'galaxy_api.api'
label = 'galaxy_api'
|
from flask import Flask, render_template, request
import json
import urllib2
app = Flask(__name__)
def azureMl(formList):
data = {
"Inputs": {
"input1":
{
"ColumnNames": ["age", "bloodpressure", "specificgravity", "albumin", "sugar", "puscell", "puscel... |
# -*- coding: utf-8 -*-
###########################################################
# Aldebaran Behavior Complementary Development Kit
# Persistent memory: a class to store data to a shared memory, in a persistent mode (even if restarting naoqi, nao, ...)
# Aldebaran Robotics (c) 2010 All Rights Reserved - This file i... |
import zipfile
import string
import itertools
from threading import Thread
def crack(zip,pwd):
try:
zip.extracktall(pwd=str.encode(pwd))
print("Success: Password is" + pwd)
except:
pass
zipFile = zipfile.ZipFile("C:\\Users\\Timo_Zuerner\\Desktop\\nezip.zip")
myLetters = string.ascii_le... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def euler(x0, xn, y0, n, fx):
#Calculamos H la distancia entre los intervalos
h = (xn - x0) / n
yj = y0
xj = x0
#Recorremos para calcular las aproximaciones
for i in range(n):
xi = xj + (i * h)
#ff = fx(xj, fx)
yi = yj + e... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 26 14:17:13 2019
@author: schuhles
"""
'''If Som isn't initialized, his value might be randomize depending on the language'''
'''If all the values are below 0, the divider will b equal to 0, programms don't work well with it'''
tab_list=[1,2,3,4,5,6,-9]
import numpy a... |
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> from nltk.tokenize import word_tokenize
>>> from collections import Counter
>>> Counter(word_tokenize("The cat is in teh box.The cat likes... |
// https://leetcode.com/problems/monotone-increasing-digits
class Solution(object):
def monotoneIncreasingDigits(self, N):
"""
:type N: int
:rtype: int
"""
# get every digits in N
digits = map(int, list(str(N)))
l = len(digits)
# find... |
#!/usr/bin/env python
"""Exchange management classes."""
__author__ = 'Michael Meisinger'
__license__ = 'Apache 2.0'
from pyon.net import messaging
from pyon.util.log import log
ION_URN_PREFIX = "urn:ionx"
ION_ROOT_XS = "ioncore"
def valid_xname(name):
return name and str(name).find(":") == -1 and str(name).f... |
from enum import Enum
__author__ = 'attakei'
class _RadikoArea(Enum):
"""Behavior extension for RadikoArea.
"""
def get_id(self):
return 'JP{}'.format(self.value)
@property
def area_id(self):
return self.get_id()
class RadikoArea(_RadikoArea):
"""Radiko Area id enumeration... |
import numpy as np
from numba import jit
import sys
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
#from ast2000tools.solar_system import SolarSystem
np.random.seed(1)
#system = SolarSystem(seed)
def escape_velocity(M, R):
v_escape = np.sqrt((2*G*M)/R)
return v_escap... |
# Generated by Django 3.0.6 on 2020-07-03 11:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0006_auto_20200703_0950'),
]
operations = [
migrations.AddField(
model_name='addesc',
name='img_alt',
... |
from multiprocessing import process, Pipe
import os, time
#创建管道对象
#如果是单向管道,fd1-->只读,fd2-->只写
fd1, fd2 = Pipe()
def fun(name):
time.sleep(3)
fd1.send(name)
jobs = []
for i in range(5):
p = Process(target=fun, args=(i,))
jobs.append(p)
p.start()
for i in range(5):
data = fd2.recv()
print(d... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 29 17:34:01 2017
@author: dori
"""
from netCDF4 import Dataset
import matplotlib.pyplot as plt
plt.close('all')
import matplotlib.dates as md
import numpy as np
import pandas as pd
from glob import glob
import os
import argparse
from radar_settings import radarlib, hydro... |
"""Test report utility methods for retrieving summarized
test execution information from features and scenarios"""
import re
import os
import platform
from re import match
from configobj import ConfigObj
CONFIG = ConfigObj(os.path.join(os.getcwd(), "..", "config", "config.cfg"))
def gather_steps(features):
"""re... |
from tkinter import *
from time import sleep
root = Tk()
root.title("Calculator First try")
#display the input and output
e = Entry(root,width=40)
e.grid(row=0,column=0,padx=15,pady=15,columnspan = 3)
def button_add(number):
x = e.get()
e.delete(0,END)
e.insert(0,str(x) + str(number))
def b... |
# 프로그래머스와 백준의 차이점
# 1. 함수안에 들어오는 인자가 배열임!!(문자열들로 이루어진 배열)
# 2. 파이참에서 돌리는 것보다 채점사이트에서 돌리는게 더 직관적임..
# 3. 여러 문제를 풀어보면서 적응해야 할듯
def solution(record):
answer = []
user_dict = {}
for mes in record:
if mes.split(' ')[0] == 'Enter' or mes.split(' ')[0] == 'Change':
user_dict[mes.split(' ')[1]... |
#!/usr/bin/python3
from setuptools.command.setopt import config_file
import nntplib
from fastemail import FastEmail
# REST Service for managing FastEmail
# creates:
# endpoint: /addmailbox
application_name = "Thomson Reuters FastEmail"
default_port = 10285
default_mailrootdir = "/vmail"
default_mailbox_config = defa... |
from models.PyCryptoBot import PyCryptoBot
from models.exchange.binance import AuthAPI as BAuthAPI
from models.exchange.coinbase_pro import AuthAPI as CAuthAPI
# Coinbase Pro fees
app = PyCryptoBot(exchange='coinbasepro')
api = CAuthAPI(app.getAPIKey(), app.getAPISecret(), app.getAPIPassphrase(), app.getAPIURL())
#pri... |
inp1=raw_input()
inp1=inp1.split(" ")
li=list(inp1)
lis=[]
for i in range(0,9):
lis.append(int(li[i]))
print(min(lis))
|
import os
from typing import Iterable, List
import pytest
from jina.drivers.search import KVSearchDriver
from jina.executors.indexers.keyvalue import BinaryPbIndexer
from jina.flow import Flow
from jina import Document, DocumentArray
from tests import validate_callback
cur_dir = os.path.dirname(os.path.abspath(__fi... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: Top Block
# Generated: Sat Oct 20 11:58:58 2018
##################################################
if __name__ == '__main__':
import ctypes
import sys
if sys.platform.sta... |
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse
from .models import Picture, Ocassion, Person
# Create your views here.
def index(request):
# Only show the first 10 most recent photos
pictures = Picture.objects.order_by('-uploadDate')[... |
import FileOperations
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import tensorflow_docs as tfdocs
import tensorflow_docs.modeling
def build_model():
# units: Positive integer, dimensionality ... |
"""
https://contest.yandex.ru/contest/23389/problems/H/
H. Двоичная система
Ограничение времени 0.07 секунд
Ограничение памяти 39Mb
Тимофей спросил у Гоши, умеет ли тот работать с числами в двоичной системе
счисления. Он ответил, что проходил это на одной из первых лекций по
информатике. Тимофей предложил Гоше решить ... |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
INCLUDES = """
#include <openssl/x509_vfy.h>
/*
* This is par... |
from keras import *
from keras.layers import *
from keras.regularizers import *
from preprocess import Preprocess
import keras
class Model_KWS():
def __init__(self):
processed = Preprocess()
self.train_set, self.test_set, self.y_train, self.y_test = processed.train_test_split()
self.y_train = keras.utils.to_ca... |
# exam_2_star.py
# link_spam
g = {'a': ['a', 'b', 'c'], 'b': ['a'], 'c': ['d'], 'd': ['a']}
def lookup_link(graph, link_start, link_target, depth):
if link_start in graph[link_start]:
return True
elif depth == 0:
return False
elif link_start in graph[link_target]:
return True
... |
from Tkinter import *
from tkFont import Font
from math import *
from tkFont import Font
from math import *
from tkSimpleDialog import *
import tkMessageBox
import tkFileDialog
import re
import ttk
import json
CR = '\n'
# Bugfix 25.02.2019 - on MacOS with MOJAVE there is a problem with Tkinter and
# displaying some w... |
# this method return large prime list
# there is a memory restriction, you can insert by 1000000,
# if you inserted 10000000, your machine will stop.because of memory overflow
def primeTable(n):
sieve = [True for _ in xrange(n + 1)]
i = 2
while i * i <= n:
if sieve[i]:
j = i + i
... |
# Generated by Django 3.2.4 on 2021-08-03 12:48
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Cargo',
fields=[
... |
# -*- coding: utf-8 -*-
from imp import reload
__author__ = 'silencedut'
# import MySQLdb
import pymysql
import json
from flask import g
# from sae.const import (MYSQL_HOST, MYSQL_HOST_S,
# MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB
# )
import sys
reload(sys)
# sys.setdefaultencoding('utf8')
def connect():
s... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 8 11:43:50 2020
@author: goblo
"""
import numpy as np
from scipy.interpolate import RectBivariateSpline
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import os
import geomdl
from geomdl import NURBS
from geomdl.visualization import ... |
#!/usr/bin/env python3
""" Simple numpy demo"""
import os
import sys
import numpy as np
def numpy_demo():
print("NumPy has a lot of standard math functions and constants:")
print("np.linspace(0,1,11): "+str(np.linspace(0,1,11)))
print("np.pi: "+str(np.pi))
print("np.e: "+str(np.e))
pr... |
import math
import time
def rank_clusters(cluster_objects):
""" Given a list of cluster objects, ranks them according to learnt function """
# now sort them
sorted_clusters = sorted(cluster_objects, key = lambda cluster : rank_formula(cluster), reverse = True)
for cluster in sorted_clusters:
cl... |
# -*- coding: utf-8 -*-
import hashlib
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
class calcSig(object):
key1 = '57218436'
key2 = '15387264'
rstr = 'efc84c17'
def shuffle(self, p1, p2):
p = ''
p += p1[int(p2[0], 10) - 1]
p += p1[int(p2[1... |
"""CPU functionality."""
import sys
class CPU:
"""Main CPU class."""
def __init__(self):
"""Construct a new CPU."""
self.ram = [00000000] * 32
self.reg = [00000000] * 8
self.pc = 0
self.stack = [0b0] * 255
self.HLT = 0b0001
self.LDI = 0b0010
se... |
import scanorama
import scanpy as sc
base_path = '/Users/zhongyuanke/data/pbmc/'
file1 = base_path+'cd19_b/hg19'
file2 = base_path+'cd4_t/hg19'
file3 = base_path + 'cd4_r_t/hg19'
file4 = base_path+'cd14_monocytes/hg19'
file5 = base_path+'cd34/hg19'
file6 = base_path+'cd56_nk/hg19'
file7 = base_path+'cd8_c/hg19'
file... |
"""
Registery for associations. Inspired by Fantomas42/django-tagging
"""
from .models import linked_to, related_to
registry = []
class AlreadyRegistered(Exception):
"""
An attempt was made to register a model more than once.
"""
pass
def register(model, linked_attr='linked', related_attr='related'... |
def fibonacci(x):
if not isinstance(x, int):
return None # Only accept integers
a, b = 0, 1
for i in range(x):
a, b = b, a + b
return a
if __name__ == '__main__':
print map(fibonacci, range(20)) |
# -*- coding: utf-8 -*-
"""
Trong phần này mình sẽ scan snmp để lấy thông tin cơ bản của server về parse ra đồng thời brute force snmp nếu port open
, tương tự như scan tcp
thông tin
- SNMP: UDP port 161
- SNMP Version 1, 2c, v3
- SNMP Authen: community
- SNMP HEADER
|================================================... |
import numpy as np
import pytest
import xarray as xr
import climpred
from climpred import HindcastEnsemble, PerfectModelEnsemble
from climpred.constants import HINDCAST_CALENDAR_STR, PM_CALENDAR_STR
from climpred.tutorial import load_dataset
from climpred.utils import convert_time_index
CALENDAR = PM_CALENDAR_STR.str... |
import math
n = int(input())
i = 2
while i <= n:
if n%i == 0:
print (i)
break
i = i + 1 |
CONSUMER_KEY = "MlQHYIaVcsmjr2h4defzRi88H"
CONSUMER_SECRET = "2u7cPGQwiNLMQHpZh0iw0qEj6aJB6INQw35FSlnwfyL0tIlmdU"
ACCESS_TOKEN = "836816176235888640-6lFKqe8OkkUA8NxYz6cWRdv7cJTEALb"
ACCESS_SECRET = "XjrusK6qGpZtrIZkNgq4fjV8oZLO5DF7FZtrs1RxQnF4X" |
"""
Tehnyt Toni Musta. Koodin alussa on muutamia yleisesti käytettäviä funktioita, joille en löytänyt järkevämpää paikkaa. Ohjelman pääfunktio koostuu pelkästään start()-funktiosta(rivi 98), josta voidaan suurinpiirtein seurata koodia ohjelman suorittamassa järjestyksessä. Mikäli haluat arvioida vain normaalin miinahar... |
import time
import requests
from lxml import etree
class doubanTop250:
def __init__(self):
pass
def getHTMLText(self, url, code='UTF-8'):
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3... |
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import URL
class FindRedditVideoForm(FlaskForm):
reddit_url = StringField('Reddit submission URL', validators=[URL()]) |
#!/usr/bin/env python
#--------------------------------------------------------
# Linac Accelerator Nodes for Transport Matrices generation
# These nodes are using the Initial Coordinates particles Attributes.
# Each node (if it is not the first one) calculates the transport matrix
# between the previous node and itse... |
__author__ = 'vasilev_is'
import pickle
import matplotlib.pyplot as plt
from Cases.CasesUtilStuff import IterationInfoAcceptor
import numpy as np
import math
import os, sys
def norm1 (b1,b2):
absdif = [math.fabs(b11-b22) for b11,b22 in zip(b1,b2)]
return max(absdif)
def norm2 (b1,b2):
return np.linalg.... |
#!/usr/bin/python
#Major keys
SHARP_NOTES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
FLAT_NOTES = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B']
MAJOR_STEPS = [2, 2, 1, 2, 2, 2, 1]
MINOR_STEPS = [2, 1, 2, 2, 1, 2, 2]
def letterShift(note):
pos = SHARP_NOTES.index(note)... |
import pygame
import math
import numpy as np
import random
import time
def checkpattern(col, row):
if row % 2:
if col % 2: #If unequal
return True
else: #if equal
return False
else:
if col % 2: #If unequal
return False
else: #if equal
... |
"""
Define model functions for discriminators.
Author: Nikolay Lysenko
"""
import tensorflow as tf
def basic_mnist_d_network_fn(d_input: tf.Tensor, reuse: bool) -> tf.Tensor:
"""
Define network structure for a basic MNIST-related discriminator.
Here, parameters of layers are selected for the following... |
from datetime import date, datetime
import sys
class PriceCalculator():
"""
Calculates the quote price depending on the services price
and the data provided by the user
"""
def __init__(self, total=0):
self.total = total
def process_data(self, service_data, user_data):
# to... |
import sys
sys.stdin = open("input4865.txt", "r")
T = int(input())
for tc in range(1, T+1):
str1 = input()
str2 = input()
str1_list = []
for x in str1:
if x not in str1_list:
str1_list.append(x)
res = {}
for x in str2:
if x in str1_list:
if x in res:
... |
class Post:
def __init__(self, post_id, name, tagline, created_at, day, comments_count, votes_count, discussion_url,
redirect_url, screenshot_url, maker_inside, user, current_user, comments=None, votes=None,
related_links=None, install_links=None, related_posts=None, media=None, d... |
class Shelf(Object):
""" Abstract class to build the
concrete shelve classes which are
implemented as queues
"""
def pop_by_id(id: int) -> Order:
pass
def push(order: Order):
pass
def get_next() -> []Orders:
pass
|
import numpy as np
def compute_rank(array):
# implement task 2: rigorous ranking here
raise NotImplementedError
|
numbers = [ 4, 8, 3, 9]
multi_num = []
for num in numbers:
multi_num.append(num * 4)
print(multi_num)
|
import numpy as np
import os
import random
import glob
class MelSplitter(object):
"""
Note:
Split mel array into a batch with random length and random starting point
Attributes:
__init__: constructs MelSplitter class
get_seg_assignment: assign start and end frame index for each me... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from itertools import chain
from operator import attrgetter
from .._compat import ffilter
from ._summarizer import AbstractSummarizer
class EdmundsonLocationMethod(AbstractSummarizer):
... |
import os
import yaml
user_input = input()
with open(user_input) as exploit_file:
contents = yaml.safe_load(exploit_file) #ok |
import matplotlib.pyplot as plt
import math
import numpy as np
from scipy.integrate import odeint
import networkx as nx
from NORMtree import N
from NORMtree import W
from NORMtree import N_1
from NORMtree import diff_dop
#1. параметры из статьи
Beta = 2 * 10 ** (-7)
Omega = 0.8 * 10 ** -7
Lambda = 10 ** 5... |
import matplotlib
matplotlib.use("macosx")
import matplotlib.pyplot as plt
import sys
sys.path.append("/Users/lls/Documents/mlhalos_code/")
import numpy as np
from mlhalos import plot
from mlhalos import machinelearning as ml
from mlhalos import parameters
from mlhalos import distinct_colours
path = "/Users/lls/Docum... |
#https://open.kattis.com/problems/trik
cups = [True, False, False]
moves = input()
for i in range(len(moves)):
move = moves[i]
if move == 'A':
temp = cups[0]
cups[0] = cups[1]
cups[1] = temp
if move == 'B':
temp = cups[1]
cups[1] = cups[2]
cups[2] = temp
... |
infile = 'C:/Users/DELL/music-top-recommend/data/cf_result.data'
outfile = 'C:/Users/DELL/music-top-recommend/data/cf_reclist.redis'
ofile = open(outfile, 'w')
MAX_RECLIST_SIZE = 100
PREFIX = 'CF_'
rec_dict = {}
with open(infile, 'r') as fd:
for line in fd:
itemid_A, itemid_B, score = line.strip().split... |
import pandas as pd
import numpy as np
def readData():
"""Reads in Lineup and Boxscore data to pandas Data Frame"""
lu = pd.read_csv('Lineup.csv', header=1)
bs = pd.read_csv('Boxscore.csv')
lu = lu.drop(lu.index[len(lu)-1])
return lu, bs
def playerNames(lu):
"""Returns list of player names and lineup names"... |
import argparse
import torch
import logging
import json
import os
import numpy as np
from NeuralBLBF.evaluate import run_test_set
from NeuralBLBF.train import train
from NeuralBLBF.model import TinyEmbedFFNN, SmallEmbedFFNN, SparseLinear, \
LargeEmbedFFNN, CrossNetwork, SparseFFNN
if __n... |
#! /usr/bin/env python
# --*-- coding:utf-8 --*--
import json
class QueryParser(object):
def __init__(self, druidQuery):
self.druidQuery = druidQuery
self.get_json()
def get_json(self):
if isinstance(self.druidQuery, dict):
self.jsonQuery = self.druidQuery
else... |
#Django lib
from django.shortcuts import render
from rest_framework import viewsets
from general.serializers import *
from general.controllers import *
from django.http import HttpResponse
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import SessionAuthenti... |
"""Helper functions for registering and configuring IOLoop watchers."""
from julythontweets import config
from julythontweets.callbacks import JulythonLiveTwitterCallback
from julythontweets.parsers.github_parser import GitHubParser
from julythontweets.watchers.twitter_watcher import TwitterWatcher
def dummy_callbac... |
"""
A function that fills out and attaches a coversheet to a submission file.
Author: Nicholas Read
"""
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .submission import Submission
def attach_generic_coversheet(submission: 'Submission'):
"""
Fills in and attaches the generic Voiceworks cover... |
from tkinter import *
root = Tk()
label = Label(root, text=”Hello World”) # 定义标签
label.pack() # 调用pack方法
root.mainloop()
|
import os
import urllib2
from bs4 import BeautifulSoup
import random
import json
def getJoke():
siteList = [{'urlPath' : 'https://crackmeup-api.herokuapp.com/',
'categories' : ['random', 'blond', 'dark', 'dirty', 'gender', 'gross','walks-into-a-bar'],
'key' : 'joke'
}]
siteIndex = 0
site = siteList[siteIndex]
... |
n = int(input())
print(sorted([input().split() for _ in range(n)], key=lambda x: int(x[1]))[-2][0])
|
"""
Created by Tomas Knapen on 2011-04-27.
Copyright (c) 2011 __MyCompanyName__. All rights reserved.
"""
import os, _thread, time, datetime
import numpy as np
import matplotlib
matplotlib.use('Agg')
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pylab as pl
from tables import *
#class for cal... |
#!/usr/bin/env python3
"""
This file defines unit tests for the Color enum.
"""
from clarity.Color import Color
class TestColorEnum:
"""
This class tests the Color enum.
"""
def test_switch(self):
"""
Tests the switch() function of the Color enum.
"""
assert Color.WHIT... |
#!/usr/bin/python
"""
ID: ten.to.1
TASK: barn1
LANG: PYTHON3
"""
filein = open("barn1.in", "r")
fileout = open("barn1.out", "w")
num_max_boards, num_total_stalls, num_occupied_stalls = list(map(int, filein.readline().split()))
occupied_stalls = sorted(list(map(int, filein.read(... |
from collections import defaultdict
DIRS = [
(1, 0),
(-1, 0),
(0, 1),
(0, -1)
]
def solveMaze(maze):
portalToPoints = defaultdict(list)
pointToPortals = {}
def hasPortal(x, y):
for dy,dx in DIRS:
mv1 = maze[dy+y][dx+x]
if mv1.isalpha():
retu... |
def print_info(name, age, no):
print(name)
print(age)
print(no)
# 实参和形参的位置是一一对应的
# print_info("田昌", 25, "007")
print_info("007", "田昌", 25) |
def LATERAL_LOAD_TRANSFER_f(ay):
du = 2*m_wheel*ay*h_wheel/tf
ds = (xr/w)*ms*ay*(hrc_f/tf)
dr = ms*ay*(ha/tf)*(Kr_f+2*Qarb_f/tf)/(Kr_f+Kr_r+2*(Qarb_f+Qarb_r)/tf)
return du + ds + dr
def LATERAL_LOAD_TRANSFER_r(ay):
du = 2*m_wheel*ay*h_wheel/tr
ds = (xf/w)*ms*ay*(hrc_r/tr)
dr = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.