text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python3
from vosk import Model, KaldiRecognizer
import os
import pyaudio
import pyttsx3
import json
import core
from nlu.classifier import classify
# Síntese de fala
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[-2].id)
def speak(text):
engine.say... |
class Solution(object):
def characterReplacement(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
result = 0
counts = [0] * 128
left_index = 0
current_max = 0
for right_index, letter in enumerate(s):
counts[ord(let... |
import random
class BaseUI:
def __init__(self, element, type, id=None, draggable=False):
self._element=element
if id is None:
self._element.setAttribute('id','%s_%s' % (type, int(100000*random.random())))
else:
self._element.setAttribute('id',id)
if draggable:
sel... |
# encoding: utf-8
"""
@author: forencen
@time: 2020/11/26 5:57 下午
@desc:
"""
CONFIG = {
"KAFKA": {
"KAFKA_REDIS_URL": "redis://:test@127.0.0.1/6", # your server
"PRODUCER_COUNT": 1,
"WAITING_PUBLISH_MESSAGE_QUEUE": "kafka_waiting_publish_message",
"bootstrap.servers": ".....", # y... |
# -*- coding=UTF-8 -*-
import datetime
import dateutil
import os
import pyExcelerator
import re
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.db import connection
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
... |
from django.db import models
# Create your models here.
class Img(models.Model):
title = models.CharField(max_length=20)
img=models.CharField(max_length=255)
objects=models.Manager() |
#!/usr/bin/env/python
# File name : server.py
# Production : GWR
# Website : www.gewbot.com
# E-mail : gewubot@163.com
# Author : William
# Date : 2019/07/24
import socket
import time
import threading
import info
def info_send_client():
SERVER_IP = addr[0]
SERVER_PORT = 2256 #Define ... |
from turtle import *
from random import randint
def Create_Path():
for row in range(15):
#t.speed(2)
t.write(row,align='center')
t.right(90)
for coln in range(10):
t.penup()
t.forward(10)
t.pendown()
t.forward(10)
t.speed(0)
t.pe... |
# Generated by Django 2.2 on 2020-05-27 14:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('secondapp', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Statement',
fields=[
('id'... |
from dynamodb_encryption_sdk.encrypted import CryptoConfig
from dynamodb_encryption_sdk.encrypted.item import (
decrypt_dynamodb_item as aws_decrypt_dynamodb_item,
encrypt_dynamodb_item as aws_encrypt_dynamodb_item,
)
from dynamodb_encryption_sdk.transform import ddb_to_dict, dict_to_ddb
from dynamodb_encryptio... |
#! python3
import sys
from vininfo import Vin
from pprint import pprint
try:
vin = Vin(sys.argv[1])
pprint(vin.annotate())
except Exception as e:
print('Error: %s' % e)
sys.exit(1)
|
class Article:
def __init__(self,id_num, title, link, pubDate, description):
self.id_num = id_num
self.title = title
self.link = link
self.pubDate = pubDate
self.description = description
self.vector = []
self.score = 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 11 17:50:04 2019
@author: guisier
"""
import numpy as np
import scipy.stats as st
from statistics import stdev
# use ARMA(s,m)-GARCH(1,1) validate (figure 4.3)
validate=[]
validate[0:728]=excess_ret[728:1456]
s=0
m=4
# model the conditional me... |
import socket
import sys
from escape_room import EscapeRoom
import _thread
if len(sys.argv) > 1:
port = int(sys.argv[1])
# print("port: ", port)
else:
port = 9999
host = ""
s = socket.socket()
# binding socket
try:
# print("Binding the port " + str(port))
s.bind((host, port... |
# hash table
class MyHashMap(object):
def __init__(self, size=1024):
self.size = size
self.hash = [[] for _ in range(self.size)]
def put(self, key: int, value: int) -> None:
for item in self.hash[key]:
if item[0] == key:
item[1] = value
... |
# 实现不同页面使用不同登录方式
import time
user,passwd='jfsu','abc'
def auth(auth_type):
print('the func is %s'% auth_type)
def outer_wrapper(func):
def wrapper(*args,**kwargs):
print('the wrapper is:',*args,**kwargs)
if auth_type == 'local':
username = input('Username:').stri... |
#!/usr/bin/env python3
import requests
matchID="5280316503"
key="KEY GOES HERE"
baseURL= "http://api.steampowered.com/IEconDOTA2_570/GetHeroes/v1/"
response = requests.get(baseURL + "?key=" + key)
print(response.status_code)
print(response.json())
|
from django.db import models
# Create your models here
class HotPoint(models.Model):
title = models.CharField(max_length=50)
number = models.IntegerField()
charts = models.JSONField(null = True)
class User(models.Model):
name = models.CharField(max_length=10)
password = models.CharField(max_length=20)
history ... |
import re
__author__ = 'Переверза Дмитрий Витальевич'
# Задание-1: уравнение прямой вида y = kx + b задано в виде строки.
# Определить координату y точки с заданной координатой x.
equation = input("Введите уравнение вида y = kx + b:\n")
x = input('X = ')
if not x.isnumeric():
raise AttributeError('Вывведи не чис... |
#import celerite
import numpy as np
import h5py #Maybe separate this, as a lot of utils can work without ever using h5py or local files
import matplotlib
import matplotlib.pyplot as plt
from tqdm import tqdm
#from celerite import terms
from scipy.optimize import minimize
from scipy.signal import medfilt
from astropy.io... |
import scrapy
from land_register import db_handler
def generate_scraping_objects(ids):
"""Get next url."""
db = db_handler.get_dataset()
table = db['stavebni_objekt_ref'].table
statement = table.select(table.c.id.in_(tuple(ids)))
results = db.query(statement)
for obj in results:
yield... |
from train import emotion_analysis, reshape_dataset
import matplotlib.pyplot as plt
import numpy as np
from keras.preprocessing import image
from model import build_model
if __name__ == '__main__':
num_classes = 7
# x_train, y_train, x_test, y_test = reshape_dataset(path, num_classes)
model = build_model... |
from django.db import models
class Course(models.Model):
name = models.SlugField()
descr = models.CharField(max_length=200)
def __str__(self):
return self.name
class Meta:
ordering = ('name',)
|
#coding=utf-8
'''
unittes使用
'''
import sys
sys.path.append("E:\\AppiumProjectAndroid")
import unittest
import HTMLTestReportCN
import threading
import multiprocessing
from util.server import Server
import time
from util.write_user_command import WriteUserCommand
# from appium import webdriver
from business.login_busin... |
lista_nomes = ['Ana', 'Ana Maria', 'Pedro', 'Elena', 'Helena', 'Elen']
for nome in lista_nomes:
print(nome.replace("", " | "))
|
"""
module: __init__.py
------------------------------------------------------------------------
Author: David J. Sanders
Student No: H00035340
Last Update: 15 December 2015
Update: Revise documentation
------------------------------------------------------------------------
O... |
from src.constant import market_constants
class Company:
def __init__(self, index):
self.index = index
# self.value = np.random.randint(low=10, high=100)
self.value = 100
self.margin_coefficient = market_constants.market_margin_coefficient[index]
# self.p_margin = 0.01
... |
from string import join
import os
from settings import MEDIA_ROOT
from photos.models import models
from django.contrib import admin
# Esto nos permite manipular el listado a mostrar para los admins
class ImageAdmin(admin.ModelAdmin):
list_display = ["titulo", "usuario", "descripcion", "imagen"]
list_filter = ... |
import torch
from torch.utils.data import DataLoader
import numpy as np
import cv2
import argparse
import os
import random
import time
import datetime
import pickle as pkl
from utils.util import *
from utils.datasets import *
from models import *
import matplotlib.pyplot as plt
def arg_parse():
parser = argpar... |
import matplotlib.pyplot as plt
import fact.plotting
import numpy as np
plt.ion()
data = np.random.normal(loc=5, scale=1, size=1440)
bad_pixels = [863, 868, 297, 927, 80, 873, 1093, 1094, 527, 528, 721, 722]
f, axes = plt.subplots(2,2)
axes[0,0].plot(data, ".")
axes[0,0].set_title("Data vs pixel Id")
axes[0,1].hist... |
#!/usr/bin/env python3
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "... |
for i in range (100):
count = i + 1
print(count)
for i in range (100):
count= i +1
if count% 3==0:
print("fizz")
else:
print(count)
for i in range (101):
count=i+1
if count%3==0:
print("fizz")
if count % 5== 0:
print("buzz")
elif count % 3 == 0 and count %... |
#!/usr/bin/python3
from sys import argv
def main():
argc = len(argv)
total = 0
for i in range(1, argc):
total += int(argv[i])
print(total)
if __name__ == "__main__":
main()
|
"""
python2to3.py
By Paul Malmsten, 2011
Helper functions for handling Python 2 and Python 3 datatype shenanigans.
"""
import sys
def byteToInt(byte):
"""
byte -> int
Determines whether to use ord() or not to get a byte's value.
"""
if hasattr(byte, 'bit_length'):
# This is already an in... |
import rospy
import numpy
import random
from gym import spaces
from openai_ros.robot_envs import turtlebot2_joy_env
from gym.envs.registration import register
from geometry_msgs.msg import Point
from openai_ros.task_envs.task_commons import LoadYamlFileParamsTest
from openai_ros.openai_ros_common import ROSLauncher
fro... |
#!/usr/bin/python -Wall
# ================================================================
# Please see LICENSE.txt in the same directory as this file.
# John Kerl
# kerl.john.r@gmail.com
# 2007-05-31
# ================================================================
import re
import copy
class coset:
slots = []... |
##! /usr/bin/python
import os
# recursive dir structuresa
import glob
#glob.glob(pattern, exclude); # wildcard processsing like "*.txt"
#pickle modules: dump and load
#a = ['wre',2431,'test',23.324]
#import pickle
#f = open('c:/files/pick.txt','wb')
#pickle.dump(a,f)
#f.close()
#f2 = open('c:/files/pic.txt','r')
#a =... |
#7
def string_to_int (list:[str]):
intList : [int] = []
for i in list:
intList.append(len(i))
return intList
print(string_to_int(["aaa", "ccc"])) |
from collections import deque
unks = deque() # queue, left in & right out
cands = []
docs = [] # list of doc. doc is a dictionary of word vector
results = {} # dict key:unk , value:cands list
trainvectors = {}
trainwords = set(trainvectors.keys())
def update_doc(doc, unk, cand):
if cand == '':
return doc
upd... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
import numpy as np
import pandas as pd
import pylab
import seaborn as sns
import matplotlib.pyplot as plt
import scipy.stats as sci
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bakeMass预测.sett... |
from kodijson import Kodi
import time
current_milli_time = lambda: int(round(time.time() * 1000))
class ibusKodi(Kodi):
kodi = Kodi("http://192.168.10.1:8080/jsonrpc", "kodi", "kodi")
cdNumber = 1
trackNumber = 1
kodiTrNumbers = 60 #dummy value
preDefPlaylist=["/media/pi/Adus/DiscoPolo", "/media/pi/... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 18 15:36:34 2018
@author: Sumudu Tennakoon
"""
import re
EMAIL_FORMAT = re.compile(r'([\w\.-]+@[\w\.-]+\.\w+)')
DOMAIN_FORMAT = re.compile(r'@([\w\.-]+)')
PHONENUM_FORMAT = re.compile(r'(\d{3})\D*(\d{3})\D*(\d{4})\D*(\d*)$')
MESSAGID_FORMAT = re.compile(r'<(.*?)>')
def... |
import boto3, time, os
from botocore.exceptions import ClientError
s3_resource = boto3.resource('s3')
s3_client = boto3.client('s3')
buckets = {
'cis3110-ccorneli': ['3110Assignment1.pdf', '3110Lecture1.pdf', '3110Lecture2.pdf', '3110Lecture3.pdf'],
'cis1300-ccorneli': ['1300Assignment1.pdf', '1300Assi... |
import argparse
import gzip
import pandas as pd
import math
import subprocess
def parse_specific_peaks(file_object):
columns = ['chr', 'start', 'stop']
specific_peaks = []
for line in file_object:
entries = line.strip().split('\t')
entry_dict = dict(zip(columns, entries))
specific... |
from redis import Redis
from tc2.env.EnvType import EnvType
from tc2.log.LogFeed import LogFeed
from tc2.log.Loggable import Loggable
class AbstractRedisWorker(Loggable):
"""A class equipped with a redis client; used to perform a group of specific tasks."""
client: Redis
env_type: EnvType
def __ini... |
import sys
sys.path.append('../production')
import logging
log = logging.getLogger(__name__)
from pprint import pprint
from gcc_utils import cons_to_list
import dis
def to_int32(x):
return (x & 0xFFFFFFFF) - ((x & 0x80000000) << 1)
def do_stuff():
code, field = (999888777, (((0, 0), ((0, 0), ((0, 0), ((0,... |
__all__ = ['send_command']
import logging
import my_fastnetmon.config as config
logger = logging.getLogger("log")
def send_command(rule):
try:
f = open(config.get('EXABGP_PIPE'),"w")
f.write(rule+"\n")
f.close()
return 0
except (OSError, IOError) as err:
logging.error(... |
l=list(map(int,input().split()))
m=list(map(int,input().split()))
flag=1
for i in l:
if i in m:
flag=0
break
if(flag==0):
print("not unique" )
else:
print("unique")
|
# this program implements a bubblesort algorithm
# in bubblesort, each pair of adjacent elements is compared and the elements are swapped if they are not in the correct order. this continues until everything is properly ordered
def bubble_sort(list):
for pair in range(len(list)-1, 0, -1): #iterate over each pair i... |
# -*- coding: utf-8 -*-
"""
Created on 2020/1/31 9:43
@author: dct
"""
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
if __name__ == '__main__':
process = CrawlerProcess(get_project_settings())
process.crawl('DoubanSpider') # 你需要将此处的spider_name替换为你自己的爬虫名称
... |
class Header:
Account = 0
Flag = 1
CheckNumber = 2
Date = 3
Payee = 4
Category = 5
MasterCategory = 6
SubCategory = 7
Memo = 8
Outflow = 9
Inflow = 10
Cleared = 11
RunningBalance = 12 |
import RPi.GPIO as GPIO
class Config():
MEDIA_NAME = "./video/sawmill.mov" # ./ is relative to PiMediaSync repo
DMX_DEVICE = "/dev/ttyUSB0"
GPIO_VALUES = {
'pin': 10,
'pull_up_down': GPIO.PUD_OFF,
}
AUTOREPEAT=False # causes automatic start and repeat of media sequence
DE... |
# Generated by Django 2.0.1 on 2018-03-31 17:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ActivityLog', '0005_auto_20180401_0149'),
]
operations = [
migrations.RemoveField(
model_name='activitylog',
name='img_url',... |
# -*- coding: utf-8 -*-
###################################################################################
# scrapy configurations
BOT_NAME = 'oldHouse'
SPIDER_MODULES = ['oldHouse.spiders']
NEWSPIDER_MODULE = 'oldHouse.spiders'
ROBOTSTXT_OBEY = False
RETRY_TIMES = 8
SCHEDULER_PERSIST = True
SCHEDULER_FLUSH_ON_START ... |
#
# Copyright (c) 2010-2014, MIT Probabilistic Computing Project
#
# Lead Developers: Jay Baxter and Dan Lovell
# Authors: Jay Baxter, Dan Lovell, Baxter Eaves, Vikash Mansinghka
# Research Leads: Vikash Mansinghka, Patrick Shafto
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may... |
from django.conf.urls import url
from django.urls import include, path
from .views import PostAPIView, PostRudView
urlpatterns = [
path('post/', PostAPIView.as_view(), name='post-article-create'),
path('post/<int:pk>/', PostRudView.as_view(), name='post-article-rud'),
]
|
import urllib.request, json
from .models import Article, Quote
def configure_request(app):
global quotes_url, pixelbay_api_key, pixelbay_api_url
quotes_url = app.config['QUOTES_URL']
pixelbay_api_key = app.config['PIXELBAY_API_KEY']
pixelbay_api_url = app.config['PIXELBAY_API_URL']
def get_... |
#!/usr/bin/env python
# coding=utf-8
import re
from pymongo import MongoClient
from basic import BaseHandler
class HomeHandler(BaseHandler):
def get(self):
self.render('home.html',title='HomePage')
|
from fht.reader.ht_reader import *
from fht.helpers.fht import *
from fht.helpers.compare import *
from fht.helpers.average import *
class Signature:
def __init__(self, file, offset, extension):
self.file = file
self.offset = offset
self.file_extension = extension
self.signature =... |
from typing import List
class Solution:
# 2
def twoSum(self, nums: List[int], target: int) -> List[int]:
j = 0
for i in range(len(nums)):
num = target - nums[i]
if num in nums[i+1:]:
j = nums[i+1:].index(num) + i + 1
break
return [i, j]
# 3
def twoSum(self, nums:... |
from __future__ import print_function, division
import numpy as np
N = 2001
eps = 0.1
rc = 2.**(1./6.)
r = np.linspace(0, 2*rc, N+2)[1:-1]
support = (r>=rc)
def LJ(r):
rm6 = r**(-6)
return 4*rm6*(rm6-1)+1
def F_LJ(r):
return 24*(2*r**(-13)-r**(-7))
def FPRIME_LJ(r):
return -24*(26*r**(-14)-7*r**(... |
from django.db import models
from django.urls import reverse
# Create your models here.
class faculty(models.Model):
#описание факультета
name = models.CharField(max_length=200, help_text="Введите наименование факультета")
def __str__(self):
return self.name
class course(models.Model):
#описани... |
import enum
import typing
from pathlib import Path
import rivals_workshop_assistant.info_files as info_files
from rivals_workshop_assistant.paths import ASSISTANT_FOLDER
if typing.TYPE_CHECKING:
from rivals_workshop_assistant.aseprite_handling import TagColor
FILENAME = "assistant_config.yaml"
PATH = ASSISTANT_F... |
import sys
f = open(sys.argv[1],"r") #Read in the file given as the first command line argument
contents = f.read() #Read the file contents into a variable
length = len(contents) #Find the length of the cipher text block
maxFreq = 0 #What is the greatest number of occurances
keyLengthFreq = [0]*length #Array to hold t... |
import sys
import importlib
class _ObjInfoParents:
def spawn_parents(self):
""" Attempt to generate parents after creation if missing.
:param generallibrary.ObjInfo self: """
if self.get_parent(spawn=False) is None:
module_name = getattr(self.origin, "__module__", None)
... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
msg = "glhf"
s = pd.Series([1,3,5,np.nan,6,8])
print(msg)
print(s)
# msg.capitalize |
from django.contrib import admin
from .models import accident
from .models import acmodels
# decorator
@admin.register(accident)
class accident_Admin(admin.ModelAdmin):
list_display = ('title','date','content','acmodels')
list_filter = ('date','acmodels')
search_fields = ('title','content')
d... |
# coding: utf-8
import json
from decimal import Decimal
import requests
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required, permission_required
from django.shortcuts import render_to_response
from math import ceil
from common.views import add_common_var
from common.views im... |
# -*- encoding=UTF-8 -*-
from skimage import util
import cv2
import numpy as np
import random
def skimage_function():
img_original = cv2.imread("images/lenna.png")
cv2.imshow("img_original1",img_original)
img_gauss = util.random_noise(img_original,mode='gaussian')
cv2.imshow("img_gauss1",img_gauss)
s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : udp_receive.py
# @Author: ly
# @Date : 2018/12/2
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : udp.py
# @Author: ly
# @Date : 2018/12/2
import socket
'''
create socket
'''
upd_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
upd_so... |
from pyspark.sql import SparkSession
from pyspark.sql import SQLContext
#Build and initiate the spark session for leveraging spark
if __name__ == '__main__':
spark = SparkSession \
.builder \
.appName("csv_processing") \
.getOrCreate()
#Building the spark context
sc=spark.sparkC... |
numX = 20
stringX = str(20)
result1 = numX * 10
result2 = stringX * 10
print("Result 1 = ", result1)
print("Result 2 = ", result2)
|
from vc_wrap import SvetObject
from combine_runs import ConstraintObject
iso_name = "PJM"
Scenario_time_series_filename = "/Users/zhenhua/Desktop/price_data/hourly_timeseries_pjm_2019_200x.csv"
# Scenario_time_series_filename = "/Users/zhenhua/Desktop/price_data/hourly_timeseries_2019_200x.csv"
Finance_customer_tariff... |
# -*- coding: utf-8 -*-
# QT IVVI DAC controller
# Version 1.1 (2020-02-07)
# Daan Wielens (ICE/QTM)
# PUT YOUR COM PORT HERE:
COMport = 1
import sys
from datetime import datetime
try:
# These modules will import succesfully for Python 2.x
import Tkinter
import ttk
import tkMessageBox as messagebox
... |
import asyncio
import logging
from typing import Any, Dict, List, Optional, TYPE_CHECKING, Tuple, Union
import aiohttp
from .canvas import Canvas
from .color import Color
from .exceptions import Cooldown, HttpException, Ratelimit
from .ratelimits import Ratelimits
if TYPE_CHECKING:
from .source import Source
lo... |
# Importing modules
import json
import dash_cytoscape as cyto
from dash import dcc
from dash import html
from dash import dash_table
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_obj... |
import random
def do_weighted_draw(weights):
total = 0;
current_total = 0;
bucket = 0;
for weight in weights:
total += weight
rand = random.random() * total
for weight in weights:
current_total += weight
if rand > current_total:
bucket += 1
else:
... |
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.contrib import admin
from settings import DEBUG
admin.autodiscover()
urlpatterns = patterns(
'',
#url(r'^$', index, name='index'),
url(r'^admin_tools/', include('admin_tools.urls')),
url(r'^admin/', include(admin... |
def sumOfTwo(l,n):
count=0
for i in range(len(l)):
for j in range(i+1,len(l)):
if l[i]+l[j]== n:
count+=1
return count
print sumOfTwo([1,2,3,4,5,6,7,8,9],10)
|
#!/usr/bin/env python3.7.0
# -*- coding: utf-8 -*-
# @Time : 2020/4/8 14:01
# @Author : XiaShengSheng
# @FileName: make_wordcloud.py
# @Software: PyCharm
from collections import Counter
import jieba
record = open("data/neg.txt", 'r', encoding='utf-8')
#print(record)
#%%
#读取文档,分词,并将分词后的单词用空格连接,形成字符串。
cut_words = '... |
#!/usr/bin/python
import time
w, h = 1024, 1024;
Matrix = [[0 for x in range(w)] for y in range(h)] ;
startTime = time.time()
for i in range(0, 1024):
for j in range(0, 1024):
Matrix[i][j] = 1;
endTime = time.time()
total = endTime - startTime
print total
|
import os
import json
import random
from src import Google_API, Google_datastore
class Question:
def __init__(self, path):
self.path = path
def get_questions(self):
# with open(self.path) as f:
# questions_json = json.load(f)
# return questions_json['questions']
d... |
from _Lib_.Lib import *
def SetUpDriver(HeadLess=True):
options = webdriver.ChromeOptions()
if HeadLess:
options.add_argument('headless')
options.add_argument('--no-sandbox')
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-... |
import seaborn as sns
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score,recall_score,precision_score,roc_auc_score,f1_score
from sklearn.metrics import roc_curve
pbl_data = pd.read_cs... |
import logging
import os
from argparse import ArgumentParser
import numpy as np
import pandas as pd
import torch
from sklearn.metrics import (
accuracy_score, precision_recall_fscore_support
)
from transformers import (
T5Tokenizer, T5ForConditionalGeneration,
Trainer, TrainingArguments,
)
from dataset im... |
# Make Server
# Functionality Wish list:
# allow users to send and receive messages
# Connect to server from anywhere/ maybe end up federating users/
# serverless? prebaked ami?
# end to end encryption
# option for message to self delete on read
# Bonus objective: integrate media project
|
# pylint: disable=too-many-instance-attributes, too-few-public-methods
""" Duckdown configuration """
import os
import time
import logging
from pkg_resources import resource_filename
LOGGER = logging.getLogger(__name__)
class Config:
""" holding all the variables """
# constants
PAGE_PATH = "pages/"
... |
# Use this formula for the distance that a car travels down the interstate:
# Distance = Speed * Time
# The car is traveling 82 miles per hour. Write a program that displays the following:
# 1. The distance the car will travel in 6 hours
# 2. The distance the car will travel in 10 hours
# 3. The distance the car... |
# Copyright (c) 2015
#
# All rights reserved.
#
# This file is distributed under the Clear BSD license.
# The full text can be found in LICENSE in the root directory.
import rootfs_boot
import time
from devices import board, wan, lan, wlan, prompt
class Connection_Stress(rootfs_boot.RootFSBootTest):
'''Measured C... |
## Leira Salene 1785752
print("Davy's auto shop services")
print("Oil change -- $35")
print("Tire rotation -- $19")
print("Car wash -- $7")
print("Car wax -- $12\n")
def getCost(s):
if s == 'Oil change':
return 35
if s == 'Tire rotation':
return 19
if s == 'Car wash':
r... |
# -*- coding: utf-8 -*-
import tushare as ts
import pandas as pd
from dataget.helper import *
import dataget.info as info
import os
import time
from datetime import datetime
from datetime import timedelta
#def write_db_all_stock_1day(start_symbol = '', end = ''):
# symbols = ts.get_stock_basics()
# o... |
## 135. Candy
#
# There are N children standing in a line. Each child is assigned a rating value.
#
# You are giving candies to these children subjected to the following requirements:
#
# Each child must have at least one candy.
# Children with a higher rating get more candies than their neighbors.
# What is the minimu... |
from __future__ import print_function
import time
import os
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import scipy.ndimage
# from Net import Generator, WeightNet
from scipy.misc import imread, imsave
from skimage import transform, data
from glob import glob
from model imp... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2020-03-27 13:07
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exhibition', '0001_initial'),
]
operations = [
migrations.AddField(
... |
import time
import numpy as np
from dolo.algos.dtcscc.perturbations import approximate_controls
from dolo.numeric.optimize.ncpsolve import ncpsolve
from dolo.numeric.optimize.newton import (SerialDifferentiableFunction,
serial_newton)
from dolo.numeric.interpolation import crea... |
from __future__ import print_function, division, absolute_import
import os
from jinja2 import Template
cur_dir = os.path.abspath(os.path.dirname(__file__))
def create_docker_compose_template(IMAGE_NAME="k2d_example", IMAGE_VERSION="v1",
SERVICE_NAME="k2d_example", CONTAINER_NAME="k2d_example",
... |
from Aircraft_winglets import Aircraft, Wing, Fuselage, ACSolidWing, ACRibWing
from Aerothon.DefaultMaterialsLibrary import Monokote, PinkFoam, Basswood, Steel, Balsa, Aluminum, Ultracote
from scalar.units import ARCDEG, FT, SEC, LBF, IN
from scalar.units import AsUnit
import pylab as pyl
import numpy as npy
from scala... |
def itsMovieTime(d):
movie_duration=[90, 85, 75, 60, 120, 150, 125]
for i,x in enumerate(movie_duration):
for z,y in enumerate(movie_duration):
# print(x+y)
if ((x+y)>=d):
print( x,y,i,z )
print(itsMovieTime(250))
|
"""
Copy Target functions
"""
from ..utils import Dispatch, exceptions
Copy = Dispatch("copy")
@Copy.register
def default(*extra_args, **extra_kwargs):
return exceptions.target_not_implemented()
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-09 21:21
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('events', '0021_auto_20170709_1951'),
]
operations = [
migrations.AlterField... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.