text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python
"""Dagor tests 0.2
Usage:
test.py (ha | de) transmission from <angle_0> to <angle_1> speed <S> increment <I>
test.py [-h | --help | help]
test.py --version
Commands:
transmission Test motor pulse to IK220 encoder ratio.
Options:
-h --help Show this screen.
--quiet ... |
from django import forms
from django.conf import settings
from django.contrib.auth import get_user_model, password_validation
from django.contrib.auth.forms import PasswordResetForm, AuthenticationForm
from django.template import loader
from django.utils.translation import ugettext_lazy as _
from core import string_co... |
import logging
import os
from logging.config import fileConfig
from fastapi import Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.utils import get_openapi
from square_auth.auth import Auth
from model_manager.app.core.config import settings
from model_manager.app.core.event_ha... |
import json
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
db = SQLAlchemy()
class BaseModel(object):
def to_json(self):
if not hasattr(self, 'TAG'):
raise NotImplementedError
return json.dumps({self.TAG: ... |
import unittest
from flask import Flask
from flask_testing import TestCase
from app import app, db_session_users
from schemas import base_users
from migrations.setup_api import add_plans
from models import *
from settings import SECRET_JWT
import jwt
import datetime as dt
import json
import os
import time
from random i... |
# Generated by Django 2.1 on 2018-09-17 14:32
from django.db import migrations, models
import django.utils.timezone
import model_utils.fields
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20180904_1503'),
]
operations = [
migrations.CreateModel(
... |
import numpy as np
import tensorflow as tf
import re
import time
# importing the datasets
line=open('movie_lines.txt', encoding='utf-8', errors= 'ignore').read().split('\n')
conversation = open('movie_conversations.txt', encoding='utf-8', errors= 'ignore').read().split('\n')
#mapping of dataset to Dictionary line n... |
# %%
# import libraries
import os
import csv
from pathlib import Path
ROOT_PATH = Path(os.path.dirname(__file__)).parent
# %%
# read mimic data
procedures_data_path = f'{ROOT_PATH}/data/mimic/PROCEDURES_ICD.csv'
admission_data_path = f'{ROOT_PATH}/data/mimic/ADMISSIONS.csv'
procedures_columns = []
procedures = []
wit... |
import os
from google.cloud import pubsub_v1
from jrdb.client import JRDBClient
from jrdb import urlcodec
def main(data, context):
auth = (os.environ['JRDB_ID'], os.environ['JRDB_PW'])
jrdbclient = JRDBClient(auth)
urls = jrdbclient.fetch_latest_urls()
print(f"Extracted urls: {urls}")
compressed_... |
#!/usr/bin/env python
import MySQLdb
# INFORMATION TO YOUR DATABASE MUST BE ENTERED HERE
mydb = MySQLdb.connect(host='localhost',
user='root',
passwd='lobster',
db='mydb')
cursor = mydb.cursor()
try:
cursor.execute("DROP TABLE IF EXISTS m;")
exc... |
from ftw.bumblebee.mimetypes import is_mimetype_supported
from opengever.bumblebee import is_bumblebee_feature_enabled
from opengever.document.behaviors import IBaseDocument
from opengever.document.document import IDocumentSchema
from opengever.document.interfaces import ICheckinCheckoutManager
from opengever.document.... |
from unittest import TestCase
from chat_transformer.commands import Command, InvalidActionError
class CommandTests(TestCase):
def test_str_representation(self):
"""
String representation of an OSCCommand should be its `name`
"""
command = Command(
name='My Command',
... |
# Converts XML back to MKV
# Licence = MIT, 2012, Vitaly "_Vi" Shukela
# the whole parser has been retrieved from: https://github.com/vi/mkvparse
# xml > mkv: cat filename.xml | ./xml2mkv > filename.mkv
# get permission on ubuntu: chmod +x scriptname.extension
import sys
from xml.sax import make_parser, handler
from st... |
import pickle
import torch
data = pickle.load(open('0ae94cff1c998450d76df87ebe81dc91a0da20ae.p', 'rb'))
torch.nn.functional.adaptive_avg_pool2d(**data)
|
#
"""
Python tools for creating the MIRI MRS dither sequences for a given
set of distortion files. These functions will be called from the
associated notebook front-end.
Beta dithers: Ch1 long offset is 5.5 times the Ch1 width because that will be
half-integer for all other channels. Ch 2/3/4 are odd multiples of th... |
#This is a comment
#print writes to console
print('kajfkldj')
## name the variable, set it with =
myName = "ava"
up = 2
low = 2.4
isTrue = True
## if condition
## = means "set this to"
## == means "if these two are equal" or "is equal to"
## one tab to do what you want to do if the condition evaluates true
if myName =... |
from ..models import Snippet, Vote
import tornado.web
from addons import route
from apps.base import BaseHandler
@route('/snippets/vote/(?P<guid>[^/]+)')
class SnippetVoteHandler(BaseHandler):
def get(self, guid=None):
if not self.current_user:
raise tornado.web.HTTPError(404)
vote = s... |
# AUTO GENERATED FILE - DO NOT EDIT
from dash.development.base_component import Component, _explicitize_args
class CrystalToolkitScene(Component):
"""A CrystalToolkitScene component.
Keyword arguments:
- children (optional):
First child will be rendered as the settings panel. Second child
will be rend... |
import i2c_lib
import lcddriver
import sys
def main():
# Main program block
lcd = lcddriver.lcd()
while True:
print("Escribe un texto por líneas de 20 caracteres y pulsa Enter seguido de Ctrl+D")
msg = sys.stdin.readlines()
lcd.lcd_clear()
for x in range(len(msg)):
lcd.lcd_display_string... |
from mnmt.inputter import ModuleArgsFeeder
import torch
from typing import List
class ArgsFeeder:
def __init__(self,
encoder_args_feeder: ModuleArgsFeeder,
decoder_args_feeders: List[ModuleArgsFeeder],
batch_size: int, src_pad_idx: int, trg_pad_idx: in... |
"""Insert default meeting.
Revision ID: 1d70ecd3db0d
Revises: 29ecac35d8b2
Create Date: 2014-12-16 18:24:44.906930
"""
# revision identifiers, used by Alembic.
revision = '1d70ecd3db0d'
down_revision = '29ecac35d8b2'
from alembic import op
from datetime import date
from mrt.models import Meeting, MeetingType, Trans... |
import numpy as np
from scipy.spatial.transform import Rotation
import matplotlib.pyplot as plt
from scipy.spatial import distance_matrix
# coordinates = np.zeros((10,3))
# coordinates[:,:2]= 30*np.random.randn(10,2)
def get_predicted(coordinates, noise=.2):
X = (coordinates - coordinates[0])
x_true, y_tr... |
from make import Clear, getUSTVGO, replaceUStVicons, MakeCS, MakeEng, MakeMain, Git, pushbulletMode, remPYC, RemoveMode2
from Auth.auth import name, Email, gitToken, gitRepo
import time
import os
token = gitToken
repo = gitRepo
email = Email
origin = "sudo git remote set-url origin https://github:" + str(token) + str... |
from Ingresos import Ingresos
from Egresos import Egresos
IngresosObj = Ingresos()
EgresosObj = Egresos()
def Ingreso():
IngresosObj.NuevoIngreso()
def Egreso():
EgresosObj.NuevoEgreso()
def getIngreso():
IngresosObj.getIngreso()
def getEgreso():
EgresosObj.getEgreso()
... |
import os
import multiprocessing
class FileOperator2:
output_dir = os.path.abspath(os.path.join(os.getcwd(), "PageData"))
tar_file_size = 100 * 1024 * 1024
count = 0
def __init__(self, output_dir=output_dir, tar_file_size=tar_file_size, count=count):
self.output_dir = output_dir
self.... |
### Final Project Submission
### Students: Myles Novick & Ariel Camperi
from util import *
class CriminalState(object):
""" Configuration values to describe a criminal agent's state. """
STEAL = 'steal'
ESCAPE = 'escape'
SAFE = 'safe'
CAUGHT = 'caught'
class CriminalAgent(Agent):
"""
This... |
''' mbinary
#########################################################################
# File : permute_back_track.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
# Blog: https://mbinary.xyz
# Github: https://github.com/mbinary
# Created Time: 2018-11-25 12:32
# Description:
###########################################... |
import pymysql
import requests
from bs4 import BeautifulSoup
from abc import *
import crawling
class Yes24BookCrawling(crawling.Crawling, ABC):
def __init__(self, main_url, db_host, db_port, db_user, db_pw, db_name, db_charset):
super().__init__(main_url, db_host, db_port, db_user, db_pw, db_name, db_cha... |
from django.contrib import admin
from .models import Answer
# Register your models here.
admin.site.register(Answer) |
import pandas as pd
from presidio_analyzer import AnalyzerEngine, RecognizerRegistry, PatternRecognizer
from presidio_analyzer.nlp_engine import NlpEngineProvider
from presidio_analyzer.pattern import Pattern
from presidio_anonymizer import AnonymizerEngine
from presidio_anonymizer.entities.engine import RecognizerResu... |
from typing import List
from arg.perspectives.basic_analysis import load_data_point
from arg.perspectives.declaration import PerspectiveCandidate
from arg.perspectives.ranked_list_interface import StaticRankedListInterface
from galagos.query_runs_ids import Q_CONFIG_ID_BM25_10000
def show():
ci = StaticRankedLis... |
# -*- coding: utf-8 -*-
"""
Create a socket file in the Linux system
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2019 by rgb-24bit.
:license: MIT, see LICENSE for more details.
"""
import argparse
import os
import socket
DESCRIPTION = 'Create a socket file in the Linux system'
VERSION ... |
from pygame.surface import Surface
from OpenGL.GL import *
from OpenGL.GLU import *
#-----------------------------------------------------------------------
def init() -> None:
glEnable(GL_DEPTH_TEST)
glClearColor(1., 1., 1., 0.)
glShadeModel(GL_FLAT)
glEnable(GL_COLOR_MATERIAL)
glEnable(GL_LIGHTI... |
'''
Created on Nov 8, 2017
@author: selyunin
'''
import numpy as np
from PIL import Image
import cv2
from sklearn.utils import shuffle
def training_generator(df, batch_size=128):
num_images = df.shape[0]
while 1: # Loop forever so the generator never terminates
for offset in range(0, num_images, batch... |
import sys
#sys.path.append('../vrep_api')
#sys.path.append('../toolkit')
try:
import vrep
except:
print ('--------------------------------------------------------------')
print ('"vrep.py" could not be imported. This means very probably that')
print ('either "vrep.py" or the remoteApi library could not... |
# PF-Prac-15
def check_22(num_list):
str_l1 = [str(i) for i in num_list]
str_l2 = ''.join(str_l1)
#print(str_l2)
sub = '22'
if sub in str_l2:
return True
else:
return False
# start writing your code here
print(check_22([3, 2, 5, 1, 2, 1, 2, 2])) |
import numpy as np
import matplotlib.pyplot as plt
from dnn.deep_convnet import DeepConvNet
from dnn.common.functions import softmax
import math
network = DeepConvNet()
network.load_params("dnn/deep_convnet_params.pkl")
def predict(x):
pre = network.predict(x.reshape(1,1,28,28))
pre_label = int(np.argmax(pr... |
"""
Ask the user to enter their first name by displaying the message:
Please enter your first name:
Display the message:
<FirstName>, please enter a sentence. Enter Stop! to stop running the program:
If the sentence ends with a full stop then count the number of spaces in the sentence and display the appropriate (g... |
# This file makes use of the InferSent, SentEval and CoVe libraries, and may contain adapted code from the repositories
# containing these libraries. Their licenses can be found in <this-repository>/Licenses.
#
# CoVe:
# Copyright (c) 2017, Salesforce.com, Inc. All rights reserved.
# Repository: https://github.com/... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 26 20:13:43 2018
@author: NANCUH
"""
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 26 18:40:41 2018
@author: NANCUH
"""
import numpy as np
from math import sqrt
import pandas as pd
import warnings
import random
from collections import Counter
#... |
"""DabsetScript 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')
Cla... |
import unittest
from process_changes_with_object import get_commits, read_file
from changesvisualise import initialSetup, loadDataFrame, getAuthorInfo, getAuthorLineCount, getAuthorDateLineInfo, getAuthorDateLineCounts, getAuthorSatSunLineCounts, getTimeLineInfo, getTimeLineCounts, getAuthorTimeLineInfo, getAuthorTime... |
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from cms.extensions import PageExtension
from cms.extensions.extension_pool import extension_pool
class ArticlesPlugin(CMSPlugin):
limit = models.PositiveIntegerField(_('Articles per page'))
cl... |
from picamera import PiCamera
import picamera.array
from threading import Thread
import time
from matplotlib import pyplot as plt
import numpy as np
class Stream:
def __init__(self):
self.cam = PiCamera()
self.cam.resolution = (320,240)
self.cam.exposure_mode = "sports"
self.cam.fra... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import time
import json
import requests
import numpy as np
from PIL import Image
from crnn.keys import alphabetChinese
from crnn.util import resizeNormalize, strLabelConver... |
name = "ptex"
version = "2.1.28"
build_requires = [
'gcc-4.8.2+'
]
requires = [
]
variants = [
["platform-linux", "arch-x86_64", "os-CentOS-7"]
]
uuid = "ptex"
def commands():
env.PATH.append("{root}/bin")
if building:
env.PTEX_INCLUDE_DIR = '{root}/include'
env.PTEX_LOCATION = '... |
from math import log2, floor
from torch import nn, cat, add, Tensor
from torch.nn import init, Upsample, Conv2d, ReLU
from torch.nn.functional import interpolate
class Net(nn.Module):
def __init__(self, scale_factor, num_channels=3, base_channels=64, num_residuals=20):
super(Net, self).__init__()
... |
from data.models import ContentType, ReadNum
from django.db.models.fields import exceptions
class ReadNumExtend():
def get_read_num(self):
try:
ct = ContentType.objects.get_for_model(self)
re = ReadNum.objects.get(content_type=ct, object_id=self.pk)
return re.read_num
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 24 15:31:04 2014
@author: gabor
"""
import butools
from butools.mc import CheckProbMatrix
from butools.utils import SumMatrixList
import numpy as np
import scipy.linalg as la
def CheckDMAPRepresentation (D0, D1, prec=None):
"""
Checks if the input matrixes defin... |
import sys
import logging
import os
from splunklib.modularinput import *
import ConfigParser
from SharedAPIs.SharedAPIs import *
def do_work(input_name, ew, symbol):
EventWriter.log(ew, EventWriter.INFO, "JORDI %s" % symbol)
data = symbol
splunk_home = os.getenv("SPLUNK_HOME")
myscript = sys.argv[0]... |
def filtrarPalabras(n, cadena):
palabras = cadena.split()
nueva = ""
for palabra in palabras:
if len(palabra) >= n:
nueva = nueva + palabra + " "
return nueva
# PROGRAMA PRINCIPAL
frase = '''En un lugar de la Mancha de cuyo nombre no quiero acordarme
no ha mucho tiempo que... |
from Interface import *
import pickle
class BankAccount:
"""Creates a bank account with Name on Account and starting value. It will pull
in either data from a file, or from the user if data doesn't exist"""
def __init__(self, startingValue):
self.balance = startingValue
self.categories = []
def categoryExist... |
from rest_framework.response import Response
from rest_framework import serializers, viewsets
from django.shortcuts import get_object_or_404
from health_records.models import HealthProfile, HealthRecord, PhysActivity, EatingInfo
class PhysicalActivitySerializer(serializers.ModelSerializer):
class Meta:
... |
"""
----------------------------------
Minas Katsiokalis
AM: 2011030054
email: minaskatsiokalis@gmail.com
----------------------------------
"""
import crypto_1
import crypto_4
"""
-----------------------------------------
Generation of AES key using SHA-256
--------------------------------... |
from selenium.webdriver.common.by import By
from base.basepage import BasePage
from utilities.custom_logger import customLogger
import logging
import pytest
class LoginPage(BasePage):
log = customLogger(logging.DEBUG)
def __init__(self, driver):
super().__init__(driver)
self.driver = driver
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# First draft of a port of our Django–centric module style fabfile so
# it's suitable for use in deploying Meteor applications.
#
# It looks to a python module (pointed to by HOST_ROLES env. var)
# for roles (groups of hosts) to work on.
#
# Examples:
# `HOST_ROLES=serv... |
# _*_ coding:utf-8 _*_
# @File : passport.py
# @Time : 2020-08-31 8:24
# @Author: zizle
""" 用户登录、注册 """
import re
import time
import base64
from datetime import datetime
from fastapi import APIRouter, Form, File, UploadFile, Depends, Body, Query
from fastapi.encoders import jsonable_encoder
from fastapi.exception_han... |
# -*- coding:utf-8 -*-
from jinja2 import Environment, FileSystemLoader
from fund.smtam import *
import inspect
env = Environment(
loader=FileSystemLoader(
"./templates/",
encoding="utf8",
)
)
def create_report(isin_code: str):
"""
レポート定義ファイルを受け取ってテンプレートに展開する
"""
rep = SmtamTe... |
#coding=utf-8
#!/usr/bin/env python
__author__ = 'XingHua'
import fudge
mock = fudge.Fake('mock')
mock.expects('method')\
.with_arg_count(arg1=1, arg2='2').returns(True)
mock.method(arg1=1, arg2='2')
fudge.verify()
|
#!/usr/bin/env python3
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# =============================================================================
## @file
# Module with some simple but useful utilities fro GSL Error handling
# @author Vanya BELYAEV Ivan.Belyaev@itep.ru
# @date 2013-02-10
# ===========================================... |
#########################################################################################
#
# url_check_hdl_test -
# This is the python script which executes the url_check usecase using python unittest
#
# Revision History
# * 1.0 - 5.28.21 - Karthik Babu Harichandra Babu - Initial version
#
#####################... |
from django.db import models, IntegrityError
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.urls import reverse
from rest_framework_simplejwt.tokens import RefreshToken, AccessToken
from uuid import uuid4
# Create your models here.
class GenerateTokenMi... |
import requests
from django.db import models
class ResultManager(models.Manager):
def from_url(self, url):
result = requests.get(url)
result = self.create(
response_code=result.status_code,
response_text=result.text,
url=url,
)
return result
c... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 2 11:24:10 2020
@author: Georg Maubach
Schreiben Sie eine Funktion isSchaltjahr(), der ein Jahr übergeben wird
und die dann zurückgibt, ob das Jahr ein Schaltjahr ist oder nicht.
Definition Schaltjahr:
- Wenn ein Jahr durch 4 teilbar ist, ist es ein Schaltjahr... |
import unittest
from unittest.mock import Mock
from src.dqn import DQN
from gym import spaces
import numpy as np
import tensorflow as tf
class TestDqn(unittest.TestCase):
def setUp(self):
observation_space = spaces.Box(0, 255, shape=(224, 320, 3), dtype=np.uint8)
environment = Mock(action_space=spa... |
""" lsn14_examples_2ofX.py - example code from lesson 14 """
__author__ = "CS110Z"
# Use a list to store the names of your favorite NFL Quarterbacks
# User must enter each name individually
num_qbs = int(input('How many names do you wish to enter: '))
qb_names = []
for i in range(num_qbs):
qb_names.a... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This is a sample script to demonstrate how to use LNP module in ncupy
@author: juniti-y
"""
######################################################################
###
### Import modules
###
######################################################################
impor... |
#!/usr/bin/env python
# coding: utf-8
# # Titanic - XGBoost
# Este notebook cria um modelo baseado no dataset do Titanic e usando XGBoost.
# Vamos começar importando as bibliotecas básicas que vamos usar.
# In[ ]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
get_ipython().magic(u'matplotl... |
#Hypotheses 3
import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_csv(r'C:\Users\manis\Desktop\unt sundar\5709\project2\final_aqi_df.csv')
dfgroup=df.groupby(['country'])
dfspain=dfgroup.get_group('Spain')
dfitaly=dfgroup.get_group('Italy')
dfindia=dfgroup.get_group('India')
dfgermany=dfgroup.get_g... |
print("Digite 10 numeros. ")
numeros = range(1, 11)
soma = 0
for numero in numeros:
print("Digite um numero: ")
digitado = int(input())
soma += digitado
media = soma / 10
print(media) |
# -*- coding:utf-8 -*-
import datetime
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy_utils import JSONType
__all__ = ["AliEvent", "db"]
db = SQLAlchemy()
class AliEvent(db.Model):
__tablename__ = "ali_event"
#: 事件ID,由 ActionTrail 服务为每个操作事件所产生的一个GUID。
id = db.Column(db.String(64), primary_key... |
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=300)
email = forms.EmailField(required=False, label='Your e-mail addres')
message = forms.CharField(widget=forms.Textarea)
def clean_message(self):
"""
Django form system knows to look for method whose name
starts w... |
# --------------------------------------------------------------------------
# ------------ Metody Systemowe i Decyzyjne w Informatyce ----------------
# --------------------------------------------------------------------------
# Zadanie 4: Zadanie zaliczeniowe
# autorzy: A. Gonczarek, J. Kaczmar, S. Zareba
# 201... |
import os # If you want to run the program on the main Mac terminal
import sys # Same
import time
import spotipy
import Lyrics_Player
import spotipy.util as util
from json.decoder import JSONDecodeError # Convenient to read Spotify's object returns
# Uncomment if you want to run the program from the Mac terminal:
# ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('dancers', '0007_auto_20180119_1522'),
]
operations = [
migrations.AlterField(
model_name='club',
nam... |
#Area of a shape - Algorithm
#1. Great User
#2. Present options
#3. Evaluate options
#4. Collect values based on selected option
#5. Evaluate values
#6. Calculate
#7. Throw result
#1. Great User
print ("Hello, Welcome to our page")
#2. Present options
positive_response=["Y","Yes","yes","y"]
response=input ("Do you wa... |
"""
Defines the blueprint for the users
"""
from flask import Blueprint
from flask_restful import Api
from resources import FilmResource
from resources import FilmsResource
FILM_BLUEPRINT = Blueprint("film", __name__)
Api(FILM_BLUEPRINT).add_resource(
FilmResource, "/film/<string:title>/<string:author>"
)
FILMS... |
"""
Combine multiple saved pickled
Pandas data frames into a single
pickled Pandas data frame.
"""
import pickle
import optparse
import json
import pandas as pd
# Parse the input arguments.
parser = optparse.OptionParser()
parser.add_option('-I', '--input', type='str', dest='input_filename', help='Input file specifyi... |
import glob
import re
import threading
import tensorflow as tf
from tensorflow.contrib import ffmpeg
from wavenet import WaveNet
BATCH_SIZE = 1
CHANNELS = 256
DATA_DIRECTORY='./VCTK-Corpus'
def create_vctk_inputs(directory):
# TODO make sure that text is matched correctly to the samples
# We retrieve each... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 17 20:58:41 2020
@author: sdavis
"""
import h5py
import csv
import numpy as np
import os
import gdal, osr
import matplotlib.pyplot as plt
import sys
from math import floor
import time
import warnings
import pandas as pd
from multiprocessing import Pool
i... |
import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
group = []
years = np.arange(2005,2018,1)
years = years[::-1]
for year in years:
url = "http://www.basketball-reference.com/draft/NBA_{0}.html".format(year)
req = requests.get(url)
soup = BeautifulSoup(req.text, 'html.pa... |
numList = [2000, 2003, 2005, 2006]
stringList = ["Essential", "Python", "Code"]
mixedList = [1, 2, "three", 4]
subList = ["Python", "Phrasebook", ["Copyright", 2006]]
listList = [numList, stringList, mixedList, subList]
#All items
for x in numList:
print x+1
#Specific items
print stringList[0] + ' ' ... |
file = open("P106_Names.txt", "a")
name = input("Enter a name: ").strip()
file.write(name)
file.close() |
import logging
from colorama import Fore
Colors = {
"GREEN": Fore.LIGHTGREEN_EX,
"YELLOW": Fore.LIGHTYELLOW_EX,
"BLUE": Fore.LIGHTBLUE_EX,
"CYAN": Fore.CYAN,
"RED": Fore.LIGHTRED_EX,
"GREY": Fore.LIGHTBLACK_EX,
"DEFAULT": Fore.RESET
}
Levels = {
"WARNING": Colors["YELLOW"],
"INFO"... |
# -*- coding: utf-8 -*-
import os
import pickle
#%%
def read_data_from_1810_09466():
# elements in datalist:
# element[0] = R (kpc)
# element[1] = vc (km/s)
# element[2] = sigma- (km/s)
# element[3] = sigma+ (km/s)
# element[4] = syst (km/s) # saved later
dir_path = os.pa... |
#! /usr/bin/env python
from stdatamodels.jwst import datamodels
from ..stpipe import Step
from . import wfss_contam
__all__ = ["WfssContamStep"]
class WfssContamStep(Step):
"""
This Step performs contamination correction of WFSS spectra.
"""
class_alias = "wfss_contam"
spec = """
save... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 21 14:00:06 2020
@author: whyang
"""
# -*- coding: utf-8 -*-
import os
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import preprocessing, metrics
from sklearn.preprocessing import MinMaxScaler, LabelEncoder
from skl... |
import cv2
import numpy as np
img = cv2.imread('tuoer.jpg',1)
print(img.shape)
# 确定ROI区域 这里是引用
ROI = img[200:399, 480:639]
# 这里是复制 注意引用和复制的区别
ROIR = np.copy(ROI)
# 在引用的ROI矩阵中画红色矩形框
cv2.rectangle(ROI,(0,0),(158,198),(0,0,255))
# 分别显示原图和ROI区域
cv2.namedWindow('SRC')
cv2.namedWindow('ROI')
cv2.imshow('SRC', img)
cv2.imsho... |
import multiprocessing
import time
start = time.perf_counter()
def do_something(seconds):
print(f'Sleeping {seconds} second...')
time.sleep(seconds)
print('Done sleeping')
#
# p1 = multiprocessing.Process(target = do_something)
# p2 = multiprocessing.Process(target = do_something)
#
#
# p1.start()
# p2.s... |
"""
Overview - Data Compression
In general, a data compression algorithm reduces the amount of memory (bits) required to represent a message (data). The compressed data, in turn, helps to reduce the transmission time from a sender to receiver. The sender encodes the data, and the receiver decodes the encoded data. As p... |
#COMMIT DAMN YOU
import pygame, sys, random
from pygame.locals import *
from Tile import *
from Dungeon import *
from Actor import *
from Menu import *
class Menu(pygame.Surface):
def __init__(self, Player,xloc,yloc):
#pygame.init()
self.WHITE = (255, 255, 255)
self.GREE... |
from .device import Device
from .dreamevacuum import DreameVacuum
from .exceptions import DeviceError, DeviceException
from .protocol import Message, Utils
|
mat1 = [[1, 2], [3, 4]]
mat2 = [[1, 2], [3, 4]]
mat3 = [[0, 0], [0, 0]]
for i in range(0, 2):
for j in range(0, 2):
mat3[i][j] = mat1[i][j] + mat2[i][j]
print("Addition of two matrices")
for i in range(0, 2):
for j in range(0, 2):
print(mat3[i][j], end = "")
print()
mat1 = ... |
#!/usr/bin/python -d
# getmailq-by-instance.py - written by Tyzhnenko Dmitry 2013. Steal and share.
# Get postfix instances queue lengths and extend SNMP OID
import sys
import os
import re
from subprocess import call
__version__ = '2.0'
#Place in /usr/local/bin/
#pass .1.3.6.1.4.1.2021.54 postfix-instance-mailq /... |
# https://leetcode.com/problems/degree-of-an-array/
"""
Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.... |
import requests
from bs4 import BeautifulSoup
#brickyard = requests.get('https://www.wunderground.com/weather/us/ca/santa-barbara/93105')
#brickyard_data = (brickyard.text)
#brickyard_soup = BeautifulSoup(brickyard_data, 'html.parser')
#brickyard_high = brickyard_soup.find("span", "_ngcontent-app-root-c5", class_="... |
# -*- encoding: utf-8 -*-
__author__ = 'fredy'
import random
def aleatorio_punto_inicio():
return random.randint(1,3)
def personaje_aleatorio():
return random.randint(1,6)
def BuscaRepetido(lista, elemento):
if len(lista) !=0:
for x in lista:
if x[1]==elemento:
retu... |
import requests
from requests import ConnectTimeout, ReadTimeout
from requests.exceptions import ConnectionError
from Responses.BaseResponse import BaseResponse
from RemitaBillingService.EncryptionConfig import EncryptionConfig
from RemitaBillingService.EnvironmentConfig import EnvironmentConfig
from Responses.SdkResp... |
import re
import os
selection = input('Please choose which file to summarize: [1] or [2]')
if selection == '1':
filename = 'raw_data/paragraph_1.txt'
elif selection == '2':
filename = 'raw_data/paragraph_2.txt'
else:
input(f'try again, select [1] or [2]')
print(f"user selected: {filename}")
file = op... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.