text stringlengths 38 1.54M |
|---|
# Mini-project #6 - Blackjack
#---------------------------------------------------------------
#---------------------------------------------------------------
#---------------------------------------------------------------
import simplegui
import random
#------------------------------------------------------------... |
from django.db import models
class Item(models.Model):
EXTRA = 'Extra'
LIGHT = 'Light'
POWER = 'Power'
SOUND = 'Sound'
STAGE = 'Stage'
CATEGORIES = (
(EXTRA, 'Extra'),
(LIGHT, 'Light'),
(POWER, 'Power'),
(SOUND, 'Sound'),
(STAGE, 'Stage'),
)
... |
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 8), dpi=80) # initializing a fig with 8x8 inches
# initial some (x,y) data points in numpy array
x = np.linspace(0.,40.,1000)
y1 = np.sin(x)*np.exp(-x*0.10)
y2 = np.cos(x)*np.exp(-x*0.15)
y3 = np.sin(x*2.0)*np.sin(x*0.2)*np.random.rand(x.size)
... |
#! /usr/bin/python
'''JobObserver monitors the queue position of jobs that have been queued but are not running.'''
import sys, time, optparse, os
import PEATSA.Core as Core
import PEATSA.WebApp as WebApp
import subprocess
def getQueueStatisitcs(queue):
'''Returns a array of dictionaries.
Each dictionary correspo... |
import sys
from manifestator import Manifestator
m = Manifestator(__file__)
m.root(r".")
m.add_dirs(["."])
m.prune(".*ignored.*")
m.prune("^./.git.*")
m.prune(".*pyc")
m.main("manifest.txt", sys.argv)
#m.write_manifest("manifest.txt")
#m.compare_with_manifest("manifest.txt") |
# -*- coding: utf-8 -*-
import tomcat.CVE_2017_12615
import tomcat.example_vulnerability
import tomcat.CVE_2017_12617
import tomcat.tomcat_weakpasswd
import tomcat.CVE_2020_1938
def exec(URL):
tomcat.example_vulnerability.attack(URL)
tomcat.CVE_2017_12615.attack(URL)
tomcat.CVE_2017_12617.attack(URL)
... |
##################################################################################
# File: BayesRuleMatlabRegression.m
# Demonstration code forBayes' Rule: A Tutorial Introduction to Bayesian Analysis
# JV Stone, 2012.
# Copyright: 2012, JV Stone, Sheffield University, Sheffield, England.
# The MatLab code below is ve... |
import json
import string
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
import csv
import spacy
import operator
from jellyfish import jaro_distance
# clusters = [name of clusters]
# all_words_in_collection = set()
# collections = {word:{list:{cluster#:word_count},total_word_count:int,cluster_... |
# -*- coding: utf-8 -*-
"""
babel.messages.extract
~~~~~~~~~~~~~~~~~~~~~~
Basic infrastructure for extracting localizable messages from source files.
This module defines an extensible system for collecting localizable message
strings from a variety of sources. A native extractor for Python source
... |
from flask import Flask, request, redirect, session
import requests
import random
try:
import secret
#secret.py contains the client_id and client_secret
except ImportError:
import sys
sys.stderr.write("You need to create a secret.py file with your client_id and client_secret.\n")
sys.exit(1)
app = ... |
import cv2
import numpy as np
img1 = cv2.imread("./image_51_60/imori.jpg").astype(np.float)
img2 = cv2.imread("./image_51_60/thorino.jpg").astype(np.float)
alpha = 0.6
out = img1 * alpha + img2 * (1 - alpha)
out = out.astype(np.uint8)
cv2.imwrite("./image_51_60/answer_60.jpg", out)
cv2.imshow("result", out)
cv2.wai... |
import json
import sys
import os
import shutil
original_stdout = sys.stdout # Save a reference to the original standard output
def create_statistics(filename_json, summary_csv):
with open('/temp/statistics/json/' + filename_json + '.json', 'r') as f:
data = json.load(f)
assets = data["assets"]
... |
from kaggler.preprocessing import (
DAE,
SDAE,
TargetEncoder,
EmbeddingEncoder,
FrequencyEncoder,
)
from sklearn.model_selection import KFold, train_test_split
from ..const import RANDOM_SEED, TARGET_COL
N_FOLD = 5
def test_DAE(generate_data):
encoding_dim = 10
df = generate_data()
... |
#!/usr/bin/env python
#coding=utf-8
import rospy
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist
from tf_conversions import transformations
from math import pi
from std_msgs.msg import String
import socket
import tf
import math
import tf2_ros
from tf2_geometry_msgs import PointStamped
#from g... |
from Point import *
from Ball import *
import cs1graphics
from random import randint
class PurpleObstacle(Ball):
def __init__(self, maxSpeed=100, ballRadius=5, color='purple'):
super().__init__(2 * maxSpeed, ballRadius, color)
def checkCollision (self, other):
if isinstance (other, Ball):
if s... |
def get_grade(s1, s2, s3):
# Code here
average = (s1+s2+s3)/3
if average >= 90:
return "A"
elif average >= 80:
return "B"
elif average >= 70:
return "C"
elif average >= 60:
return "D"
else:
return "F"
'''
test.assert_equals(get_grade(95, 90, 93), "A",... |
# Generated by Django 3.2.7 on 2021-10-05 10:35
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('worker', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='worker',
old_name='admin_id',
new... |
import torch
import matplotlib
import numpy as np
import torch.nn as nn
from torch.utils.tensorboard import SummaryWriter
import matplotlib.pyplot as plt
import utils.constants as constants
import utils.skel as skel
from utils.skel import TB_vis_pose2D, prep_poses
import utils.dataset as dataset
def mean_prior(pred... |
import time
from multiprocessing.dummy import Pool
import pytest
from helpers.cluster import ClickHouseCluster
from helpers.test_tools import assert_eq_with_retry
def _fill_nodes(nodes, shard, connections_count):
for node in nodes:
node.query(
"""
CREATE DATABASE test;
... |
from i3pystatus.core.util import internet, require
from i3pystatus.scores import ScoresBackend
import copy
import pytz
import re
import time
from datetime import datetime, timezone
LIVE_URL = 'https://www.nba.com/game/{id}'
API_URL = 'https://cdn.nba.com/static/json/liveData/scoreboard/todaysScoreboard_00.json'
cla... |
"""
1.
Поработайте с переменными, создайте несколько,
выведите на экран, запросите у пользователя несколько
чисел и строк и сохраните в переменные, выведите на экран.
"""
import datetime
print("Beer Inspector 1.3")
name = input("Введите ваше имя: ")
year = int(input("Введите год рождения: "))
now = int(datetime.date... |
#Shabri Ash Shiddieqy
#First created 21 January 2021
#Python 3.8
#Create an empty 3x3 array
A = [[0 for i in range (3)] for j in range (3)]
#Filling the array with user input (write 0 for empty cell)
for i in range (3):
X=input("Row " + str(i+1) +" : ")
for j in range (3):
A[i][j]=int(X[j])
'''Create... |
from nanpy import Servo
import time
servo = Servo(7)
while (True):
for move in [0, 90, 180, 90, 0]:
servo.write(move)
time.sleep(1)
|
"""
Manage OS-level configuration.
"""
import logging
from archinfo import ArchARM, ArchMIPS32, ArchMIPS64, ArchX86, ArchAMD64, ArchPPC32, ArchPPC64, ArchAArch64
from simuvex import SimState, SimIRSB, SimStateSystem, SimActionData
from simuvex import s_options as o, s_cc
from simuvex import SimProcedures
from simuvex... |
# The following pseudo code describes how a bookstore computes the price of an order from the total price and the number of books that were ordered (PFE Business P2.32).
#1. Read the total book price and the number of books
price_per_book = int(input("Book Price:"))
number_of_books = int(input("Number of books:"))
tot... |
#!/usr/bin/env python
# coding:utf-8
# http://coding.imooc.com/lesson/62.html#mid=917
# 2-1 如何在列表, 字典, 集合中根据条件筛选数据
# 1 过滤掉列表中的负数 -- 通用方式
data = [1, 5, -3, -2, 6, 0, 9]
L = [3, 7, 9, -1, 20, 30, -2, -7, 18]
res = []
for x in data:
if x >= 0:
res.append(x)
print(res)
resp = []
for i in L:
if i >= 0... |
# -*- coding: utf-8 -*-
import json
import time
from datetime import datetime, date
from pathlib import Path
from pprint import pprint
import pandas as pd
import pytest
from dgp.core.types.reference import Reference
from dgp.core.models.meter import Gravimeter
from dgp.core.models.dataset import DataSet
from dgp.core... |
inventory = {'gold':500, 'pouch' :['flint','twine','gemstone'], 'backpack':['xylophone','dagger','bedroll','bread loaf']}
inventory ['pocket'] = ['seashell','strange berry','lint']
inventory ['backpack'].sort()
inventory ['backpack'].remove('dagger')
inventory ['gold'] += 50
print(inventory['backpack'])
print(inv... |
from django.contrib import admin
from .models import Announcements, ContactForm, ImageService,Achievements
class AnnouncementAdmin(admin.ModelAdmin):
list_display = ('title', 'description', 'completed')
class contactFormAdmin(admin.ModelAdmin):
list_display = ('name', 'phone', 'email','message','completed')
... |
import sys
import numpy as np
from util.sixteenth_array import *
from util.other_util import *
from util.music_theory import *
from c_major_gen_util import *
def randomlyGenerateBars1(n_bars):
melody_arr = [REST] * SIXTEENTH_BAR_LEN * n_bars
for i in range(8 * n_bars):
random_note = np.random.randint... |
import numpy as np
import pandas as pd
import re
import nltk
nltk.download('wordnet')
nltk.download('stopwords')
import pickle
from nltk.corpus import stopwords
from sklearn import svm
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import cross_val_predict
from sklearn.feature_selectio... |
from collections import namedtuple
import os
from contracts.utils import raise_desc
from mcdp import logger, MCDPConstants
from mcdp_utils_misc import memoize_simple
from mcdp_library import Librarian
from mcdp_utils_misc import dir_from_package_name
TestLibrary = namedtuple('TestLibrary', 'bigpath librarian short ... |
#!/usr/bin/env python3
import argparse
import os
import sys
import subprocess
import tensorflow as tf
_DIRNAME = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
def _get_path(basename, trial, version, other_name=None):
path = os.path.join(os.path.join(os.environ.get('DATA_DIR', 'gs://renda'), 'gnmt_... |
import random
from .event import Sender
from .util import Die
from .tiles import Tile, Floor, Wall
from .entities import Entity, Spawner
class World:
def __init__(self, width, height):
self.width = width
self.height = height
self.tiles = []
self.entities = []
self.queued_t... |
#-*-coding:utf8-*-
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
import time
import datetime
import pandas as pd
import re
import telebot
from pyvirtualdisplay import Display
import main
def dex():
df = pd.DataFrame(columns=[
... |
#!/usr/bin/env python
# coding: utf-8
# ## Imports
#
# **TASK: Run the cell below to import the necessary libraries.**
# In[1]:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# ----
#
# **TASK: Run the cell below to read in the data.**
# In[2]:
df = pd.read_csv('... |
print("="*40)
print("Nama : Rohim Kurniawan")
print("Nim : 10200041")
print(" Quis A")
print("="*40)
print("PEMESANAN TIKET KERETA ANTAR KOTA")
print(" OKTOBEER 2020")
print("="*40)
print("Kode Kereta Nama Kereta Haraga")
print("-"*40)
print(" 1 Argo Bromo 150000 ")
print(" ... |
"""book2 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-base... |
path = "./Exercicio1.txt"
sum = 0
with open(path) as file:
for line in file:
sum += int(line)
print(sum) |
#显示波形图等各种图
import matplotlib.pyplot as plt
import librosa as li
import librosa.display as ds
import librosa
from python_speech_features.base import mfcc,logfbank
import scipy.io.wavfile as wav
import numpy as np
import os
indir = r'C:\Users\a7825\Desktop\工作空间\セミナー\语音\wav/C001L_061.wav'
# indir_1 =r'C:\Users... |
from fbprophet import Prophet
from fbprophet.plot import plot_plotly, plot_components_plotly
import pandas_datareader.data as web
def stock_predict(symbol, start, end, period=60):
#grabing and formating the data
df=web.DataReader(symbol,'yahoo', start,end)
df.reset_index(inplace=True)
df = df[['Date', ... |
import time
import paramiko
import getpass
import requests
import yaml
from collections import defaultdict
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#password = getpass.getpass('password: ')
with open('secrets.yaml', 'r') as secrets_file:
secrets = yaml.load(secrets_file)... |
"""Helpers for models."""
from typing import Any
from django.db import models
from django.urls import reverse
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from autoslug import AutoSlugField # type: ignore
from .querysets import NameOrderedQuerySet
from .utils ... |
import ast
import json
import sys
import time
from multiprocessing.pool import ThreadPool
import botocore.config
import botocore.session
session = botocore.session.get_session()
region_name = 'us-east-1'
lambda_function_name = 'client'
cfg = botocore.config.Config(retries={'max_attempts': 0}, connect_timeout=300, rea... |
# Generated by Django 2.1.10 on 2019-10-09 16:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('task', '0002_auto_20191008_1648'),
]
operations = [
migrations.AddField(
model_name='translationtaskitem',
name='_p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 Thomas Reifenberger.
#
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# Thi... |
from iTunesConnector.iTunes import iTunesItem
class WindowInfo(object):
class Bounds(object):
def __get__(self, instance, owner):
return instance.window.bounds()
def __set__(self, instance, value):
instance.window.setBounds_(value)
class Closeable(object):
def __get__(self, instance, owner):
return... |
import os
import psycopg2
def getDatabaseConnection():
docker = "docker"
con = psycopg2.connect(host="db" ,dbname=docker,user=docker,password=os.environ.get("DATABASE_CONNECTION_PASSWORD"))
cur = con.cursor()
return cur, con
def getAllEmails():
"""
Gets all the emails from the database and ... |
for _ in range(int(input())):
n,d = map(int, input().split())
l = list(map(int, input().split()))
l.sort()
boo = False
if n<3:
for i in l:
if i>d:
boo = True
break
else:
i,j = l[:2]
if max(l)>d and i+j>d:
bo... |
class A(object):
def __foo(self, x):
print("executing _foo(%s,%s)" %(self, x))
print('self:', self)
def chen(self):
__foo(5)
@classmethod
def class_foo(cls, x):
print("executing class_foo(%s,%s)" % (cls, x))
print('cls:', cls)
@staticmethod
def static_foo... |
from functools import reduce
from operator import __or__
import torch.nn as nn
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from torch.utils.data.sampler import SubsetRandomSampler
from torchvision import datasets, transforms
from utils import *
class AdversarialDataset(Dataset):
... |
# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""API for calling 'cloudbuildhelper' tool.
See https://chromium.googlesource.com/infra/infra/+/master/build/images/.
"""
from collections import namedtupl... |
# coding: utf-8
# ## Instructions from Soma:
#
# #### Using APIs/Data Structures
# Using the Dark Sky Forecast API at https://developer.forecast.io (Links to an external site.)Links to an external site./, generate a sentence that describes the weather that day.
#
# Right now it is TEMPERATURE degrees out and SUMMARY.... |
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from project_product_category.models import Category
from .models import Product,product_gallery
# Create your views here.
class product_list(ListView):
template_name = 'product_list.html'
paginate_by = 3
def get_q... |
"""guest_registry 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')
Clas... |
#! /usr/bin/env python
# coding: utf-8
#
# Copyright (c) 2019 JR Oakes
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use,... |
import sys
c=str(input('CNP este '))
t=True
if (len(c)==13):
for i in c:
if ((ord(i)<=57) and (ord(i)>=48)):
t=True
else:
t=False
else:
print('introduceti 13 caractere')
sys.exit()
if t==True:
print('CNP corect')
else:
print('CNP incore... |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from wtforms.validators import InputRequired, Length
class AdminForm(FlaskForm):
username = StringField('Username', validators=[InputRequired()])
password = PasswordField('Password', validators=[InputRequired(),
... |
from django.utils.http import urlencode
from django.urls import reverse
def q_reverse(view_name, query=None, **kwargs):
url = reverse(view_name, kwargs=kwargs)
if query:
return '{}?{}'.format(url, urlencode(query))
return url
|
__author__ = 'Swolfod'
# -*- coding: utf-8 -*-
from django.db import models
from .state import State
from .city import City
class Airport(models.Model):
name_en = models.CharField(max_length=128)
name_cn = models.CharField(max_length=64, null=True)
faa = models.CharField()
iata = models.CharField()
... |
from django.shortcuts import render, redirect
from login.models import *
from login.forms import *
import re
from django import forms
def index(request):
pass
return render(request, 'index.html')
def login(request):
if request.method == "POST":
login_form = UserForm(request.POST)
message... |
from __future__ import annotations
import functools
import time
from typing import Callable, Optional
from prometheus_client import Counter, Gauge, Histogram
from workflows.transport.common_transport import MessageCallback, TemporarySubscription
from . import BaseTransportMiddleware, get_callback_source
SUBSCRIPTI... |
# -*- coding: utf-8 -*-
"""The mailtemplates package"""
from tg.configuration import milestones
from tgext.pluggable import plug
from tgext.pluggable import plugged
def plugme(app_config, options):
if not 'default_language' in options:
options['default_language'] = 'EN'
app_config['_mailtemplates'] = ... |
# question: Given a directed graph, design an algorithm to find out whether
# there is a route between two needs.
from collections import deque
from utils import Graph
def bfs(start, end):
if start == end:
return True
visited = set()
q = deque()
q.append(start)
visited.add(start)
while... |
from rest_framework.routers import DefaultRouter
from student.api.views import CourseViewSet
router = DefaultRouter()
router.register(r'course', CourseViewSet)
|
from django.conf.urls import url
from . import views
app_name = 'usuarios'
urlpatterns = [
url(r'^login', views.user_login, name='login'),
url(r'^logout', views.user_logout, name='logout'),
url(r'^new', views.new, name='new'),
url(r'^arearestrita', views.restricted_area, name='restricted_area'),
u... |
from math import sqrt
from random import randrange as rnd, choice
import tkinter as tk
import math
import time
WINDOW_SIZE = (800, 650)
xc = 400
yc = 325
dt = 1
a = 200
R = 300
enemys=[]
enemys2 = []
grenades=[]
balls=[]
boxes = []
medes = []
def pass_event():
pass
class Ball():
def __init__(self, canva... |
import os
import json
import requests
items = None
champions = None
def load_match_data(match_id: int) -> dict:
with open(f'matches/{match_id}.json', 'r') as f:
return json.load(f)
def load_timeline_data(match_id: int) -> dict:
with open(f'timelines/{match_id}.json', 'r') as f:
return json.l... |
# This file is part of the Data Cleaning Library (openclean).
#
# Copyright (C) 2018-2021 New York University.
#
# openclean is released under the Revised BSD License. See file LICENSE for
# full license details.
"""Wrapper to run the HyFD algorithm (A Hybrid Approach to Functional
Dependency Discovery) from the Metan... |
# DO NOT EDIT THIS FILE. This file will be overwritten when re-running go-raml.
from flask import Flask, send_from_directory, send_file
from path_api import path_api
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
app = Flask(__name__)
app.register_blueprint(path_api)
if __name__ == "__main__":
... |
from microbit import *
SECRET_CODE='ABBA'
display.show(Image.CONFUSED)
INPUT_CODE=''
while (len(INPUT_CODE) < 4):
if button_a.is_pressed():
INPUT_CODE = INPUT_CODE + 'A'
sleep(1000)
elif button_b.is_pressed():
INPUT_CODE = INPUT_CODE + 'B'
sleep(1000)
sleep(10)
display.c... |
import time
start_time = time.time()
with open('input.txt') as f:
lines = f.read().splitlines()
relations = {}
planets = []
has_orbits = []
for sequence in lines:
planet_1 = sequence.split(')')[0]
planet_2 = sequence.split(')')[1]
if planet_2 in list(relations.keys()):
print('HEY, ALREADY IN... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat May 6 11:54:29 2017
@author: Work
"""
import pandas as pd
import numpy as np
import pylab as pl
%%sh
tar xvf ~/Users/Work/Documents/DataScience/GA_Jeffrey/week9/lab/beer_reviews.tar.gz
df = pd.read_csv("beer_reviews.csv")
df.head()
beer_1, beer_2 ... |
#----------------------------------------------------------------
#
# TRAFFIC LIGHT
#
# In this exercise you must create a Graphical User
# Interface using Tkinter. The program should create
# a window containing a drawing canvas and three buttons.
# Each time one of the buttons is pressed a red, yellow
# or green cir... |
#!/usr/bin/env python
from LaserSpeed import LaserSpeed
from svgelements import *
CMD_RIGHT = ord(b'B')
CMD_LEFT = ord(b'T')
CMD_TOP = ord(b'L')
CMD_BOTTOM = ord(b'R')
CMD_FINISH = ord(b'F')
CMD_ANGLE = ord(b'M')
CMD_RESET = ord(b'@')
CMD_ON = ord(b'D')
CMD_OFF = ord(b'U')
CMD_P = ord(b'P')
CMD_G = ord(b'G')
CMD_I... |
from rest_framework import serializers
from materia.models import datoshorario, datosmateria, horas
from usuario.models import datosusuario
from semestre.models import semestre, vacaciones
from examen.models import examen, alarmaexamen, repeticionexamen
from tarea.models import tarea, alarmatarea, repeticiontarea
cla... |
q,t = map(int,input().strip().split())
# s = (5*n/2)(1 + n) = (5*(n**2)/2 + 5*n/2 < 240-t
for n in range(q,-1,-1):
if (5*n + 5*(n**2))/2 <= (240-t):
print(n)
break |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 19 21:38:10 2019
@author: ethan
"""
import cv2
import tensorflow as tf
I = cv2.imread('cathon.jpg')
I1 = cv2.imread('new')
# 池化核 5*5
ksize=[1, 5, 5, 1]
# 步長 = 2
strides=[1, 1, 1, 1]
# 輸入影像格式設定
img_shape = [1, I.shape[0], I.shape[1], I.shape[2]]
#im... |
import requests
import pandas as pd
import time
import datetime
import re
def get_search_weather(queries):
"""
Access current weather data for any location.
:param queries: query parameters to https://api.openweathermap.org.
:return: wrapped historical data as type of Pandas DataFrame.
... |
import smtplib,os,sys,socket
import datetime
import mimetypes
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.text import MIMETex... |
import sys
from keras.engine import Layer
from keras import initializations
from keras import backend as K
from keras_extensions import switch
class AttachmentPredictor(Layer):
'''
AttachmentPredictor is a layer that takes an encoded representation of a phrase that ends with a preposition
phrase (preposi... |
#!/usr/bin/env python
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util, template
import os
import sys
# from themoviedb import tmdb
class MainHandler(webapp.RequestHandler):
def get(self):
# m = tmdb.search("8 mile")
# movie = m[0]['name']
... |
from flask import Flask, render_template, flash, redirect, request, json
import os
import urllib.request
from jinja2 import ext
from datetime import datetime
app = Flask(__name__)
def format_time2(gig):
return datetime.strptime(gig, '%Y-%m-%dT%H:%H:%M:%M:%S.%f').strftime('%d. %m. %Y kl. &H %M')
# bensínstöðva... |
#! /usr/bin/env python3
#-*- coding: utf8 -*-
import sys
def happy_pancakes(SS, count_string):
target = "".join(["+" for _ in range(len(SS))])
ii = 0
plus_stack = len(SS) - 1
print(SS, file=sys.stderr)
while (SS != target):
jj = plus_stack
# Find from where the stack must be returne... |
import requests, json, hashlib, time, re
from lxml import etree
from Crawl.tender3.es1 import filter_data, set_data
def md5_jm(v):
md5 = hashlib.md5()
md5.update(v.encode())
md5_v = str(md5.hexdigest())
return md5_v
page_url = 'http://www.sxggzyjy.cn/jydt/001001/001001001/001001001001/subPage_jyxx.h... |
# -*- coding: utf-8 -*-
import os
import unittest
import switch_translate
from flask import json
from lib.translate import translate
class TranslitTestCase(unittest.TestCase):
def setUp(self):
self.text = u'ghjdthrf ищер дфтпгфпуы'
def test_translate(self):
result = translate(self.text)
... |
from __future__ import with_statement
from __future__ import absolute_import
import numpy as np
import pytest
from ruptures.costs import CostAR, CostL1, CostL2, CostLinear, CostNormal, CostRbf, cost_factory
from ruptures.datasets import pw_constant
from ruptures.exceptions import NotEnoughPoints
@pytest.fixture(scop... |
import cv2
import numpy as np
import os
import re
import copy
import shutil
import time
img_width=227
img_heigth=227
def Image_RotateLeftAndRight(image_origin):
if image_origin is None:
print 'Error:func Image_RotateLeftAndRight:please input a valid image!'
return None
image_rotation=np.zeros(... |
n = int(input("enter the number of items in the list"))
lst =[]
for i in range(n):
a = input("enter the element ")
lst.append(a)
print(lst)
|
from torchvision import datasets, transforms
from base import BaseDataLoader
from data_loader.dataset import MidiDataset
class MidiDataLoader(BaseDataLoader):
"""
Midi Dataloader class
"""
def __init__(self, data_path, batch_size, shuffle, validation_split, num_workers, training=True, **kwargs):
... |
# -*- coding: UTF-8 -*-
import sys
from maya import OpenMaya, OpenMayaMPx
om = OpenMaya
omm = OpenMayaMPx
class CreateZipperNode(omm.MPxNode):
kNodeName = "newZipperNode"
kTypeID = om.MTypeId(0x01021)
zip = om.MObject()
zipType = om.MObject()
attenuation = om.MObject()
input = om.MObject()
... |
class MachineOperand(object):
def __init__(self,name):
self.name = name
self.value = None
# FIXME: implement real rendering system
def render(self, context):
"""Return a Render Token for this operand."""
return self.name, 0
class MachineRegisterOperand(MachineOperand):
... |
# -*- coding: utf-8 -*-
# ------ NESNE TABANLI PROGRAMLAMA -----(DEVAMI)---
# ----- Nesneler -----
# sınıflar nesene üretmemizi sağlayan veri tipleridir.
# şimdi ufak bir nesne üretelim.
#class Sınıf():
# pass
#sınıf = Sınıf() # bu komut ile nesne üretmiş ... |
species(
label = '[O]OOC1[CH]C=CCC=C1(1625)',
structure = SMILES('[O]OOC1[CH]C=CCC=C1'),
E0 = (247.172,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2807.14,2864.29,2921.43,2978.57,3035.71,3092.86,3150,900,928.571,957.143,985.714,1014.29,1042.86,1071.43,1100,300,800,800,800,800,800,... |
import pygame
import math
import random
import constants
from img_sound_loader import load_image
from img_sound_loader import resize_image
from img_sound_loader import load_sound
import bullets
def create_enemy(classname,x,y,player):
enemy_dict = {Mushroom.__name__:Mushroom(x,y,player),
... |
# libraries to import
import json
from collections import defaultdict
import requests
from bs4 import BeautifulSoup
# Input stock-list:
stocks_name = input("\nEnter the stock Names separated by a space > ").split()
# stocks_name = ["SBIN", "RELIANCE", "ICICIBANK", "TITAN"]
Stocks = stocks_name
def func(stocks): ... |
import re
from .. utils import TranspileTestCase, BuiltinFunctionTestCase
from .. utils import SAMPLE_SUBSTITUTIONS
class MaxTests(TranspileTestCase):
pass
class BuiltinMaxFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
function = "max"
substitutions = SAMPLE_SUBSTITUTIONS.copy()
substit... |
# for pywinauto
from pywinauto.win32_hooks import *
import time
import threading
class Hooker():
def __init__(self, print_en=True):
self.print_en = print_en
self.search_en = False
self.copy_en = False
self.copy_time = time.time()
self.tk_en = False
self.add_en = Fal... |
import numpy as np
import math
import os
import h5py
class PredictionResult:
def __init__(self, bbox_corners, landmark_sequences, resize_ratios):
self.bbox_corners = bbox_corners
self.landmark_sequences = landmark_sequences
self.resize_ratios = resize_ratios
# revert the p... |
import os
import logging
from datetime import datetime
from tools.exceptions import LoggerException
logger = logging.getLogger(__name__)
def init_logging(file_name, log_path=None, level=logging.INFO):
"""
Init the logging system.
:param file_name: The prefix file name.
:param log_path: Log path if a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.