text stringlengths 8 6.05M |
|---|
# program that reads in a string and outputs how long it is.
inpStr = input('Please enter a string: ')
print ('The length of the string is {} characters'.format(len(inpStr)))
#program creating and out putting a string
string = 'John said\t"hi"\nI said\t\t"bye"'
print (string) |
import sys
import psycopg2
from helper import connect_database, process_file, table_stats
if __name__ == "__main__":
if len(sys.argv) == 8:
# parse command line inputs
dbname, user, pwd, host_ip, port, table, filepath = sys.argv[1:]
# connect to database
cur, conn = connect_databa... |
import requests
url = 'http://192.168.2.133:8000/api/products'
x = requests.get(url).json()
print(x)
def func1(data):
from math import inf
max_price_title = None
min_price_title = None
min_price = inf
max_price = 0
for value in x:
price = value['price']
if price > max_price:
... |
import numpy as np
import pandas as pd
def winsorize(data, **kwargs):
query = ""
for name, value in kwargs.items():
assert (type(value) is tuple and value[1] > value[0]), "winsorization lb and ub should be a tuple (lb,ub)"
lb = np.percentile(data[name], value[0])
ub = np.percentile(dat... |
from selenium import webdriver
import unittest,time
class GetElementTitleByChrome(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
#隐式等待
self.driver.implicitly_wait(10)
def test_getElementTitle(self):
url = "http://www.baidu.com"
self.driver.get(url... |
import cozmo
import cv2
import numpy as np
import logging
import asyncio
import sys
import PIL.ImageTk
import tkinter as tk
from threading import Timer
from scipy.interpolate import UnivariateSpline
from cozmo.util import degrees, distance_mm, speed_mmps
# Logger
log = logging.getLogger('ok.FollowLine... |
#!/usr/bin/python3
import sys
import random
from math import log
import numpy as np
from operator import itemgetter
#Iused this resource to understand the logic: https://en.wikipedia.org/wiki/Viterbi_algorithm
#####################################################
####################################################... |
#!/usr/bin/python
import random
import sys
def main():
# TODO don't remove!
seed = int(sys.argv[1])
random.seed(seed)
# TODO test generation
t = int(sys.argv[2])
n = int(sys.argv[3])
print t
for _ in range(t):
print n
for i in range(n):
print random.randi... |
#!/usr/bin/env python
from decimal import Decimal
from aiokafka import ConsumerRecord
import bz2
import logging
from sqlalchemy.engine import RowProxy
from typing import (
Any,
Optional,
Dict
)
import ujson
from hummingbot.logger import HummingbotLogger
from hummingbot.core.event.events import TradeType
f... |
from tkinter import *
from model.nethandler.battle_net_client import BattleNetClient
from model.nethandler.battle_net_server import BattleNetServer
from views.image_factory import ImageFactory
class GameFrame(Frame):
def __init__(self, master):
Frame.__init__(self, master, bg='darkblue')
# self.m... |
import rlp
from eth2.beacon.sedes import (
uint24,
uint64,
)
from eth2.beacon.typing import (
SlotNumber,
ShardNumber,
ValidatorIndex,
)
class ShardReassignmentRecord(rlp.Serializable):
"""
Note: using RLP until we have standardized serialization format.
"""
fields = [
# W... |
import os
import numpy as np
# collecting all csv files from forwarded directory
def collect_csv_data_collection_from_directory(path):
import pandas as pd
import os
data_collection = []
for csv_name in os.listdir(path):
csv_path = os.path.join(path, csv_name)
data_collection.append(p... |
import pandas as pd
import seaborn as sn
import matplotlib.pyplot as plt
from utils.loader import *
import numpy as np
from sklearn.metrics import confusion_matrix
from sklearn.metrics import f1_score,fbeta_score
# from models import joint_cnn
from utils.transform import test_transform
from models.modules import JLNet
... |
# tuples are immutable lists
t = ("Hello", 4, 4.4)
print(t)
print(t[-1])
|
'''
Created on 8 de dez de 2016
@author: vagnerpraia
'''
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionT... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2020-8-9 23:11:00
# version: 1.0
# __author__: zhilong
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get('http://www.python.org')
assert 'Python' in driver.title
elem = driver.find_element_by_na... |
'''
https://en.wikipedia.org/wiki/Benford's_law
'''
import matplotlib.pyplot as plt
import numpy
def chart_data():
return [(x, numpy.log10((x+1)/x)) for x in range(1,10)]
def main():
for x,y in chart_data():
plt.plot([x,x], [0,y])
plt.ylabel('probability')
plt.xlabel('digit')
plt.show(... |
# !/usr/bin/env python
# -*-coding:utf-8 -*-
# Author: Renkai
import json
import requests
def readJson():
return json.load(open('one.json','r')) # 返回python字典
print(readJson()['item'][0]['request'])
def one_get():
r = requests.request(method='',url='')
return r.json()
|
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as Data
from model_ssd300 import SSD300
from datasets import PascalVOCDataset
def create_label_map():
#lable map
voc_labels = ('aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningta... |
# Generated by Django 2.0.7 on 2018-07-20 23:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('life', '0002_auto_20180718_1558'),
]
operations = [
migrations.CreateModel(
name='Home',
fields=[
('... |
"""
A script to download a cloud directory to a local directory.
"""
import argparse
import os
import logging
import sync_drives.sync as sync
import providers.provider_list as provider_list
from common.basic_utils import check_for_user_quit
def main(args):
logging.basicConfig(level=logging.INFO)
# Init pro... |
# Copyright (c) 2011, James Hanlon, All rights reserved
# This software is freely distributable under a derivative of the
# University of Illinois/NCSA Open Source License posted in
# LICENSE.txt and at <http://github.xcore.com/>
import sys
from util import debug
from ast import NodeVisitor
from builtin import builti... |
# -*- coding:utf-8 -*-
import os
import sys
import numpy as np
from simulater import Simulater
from play_back import PlayBack, PlayBacks
COMMAND = ['UP', 'DOWN', 'LEFT', 'RIGHT']
def get_max_command(target_dict):
return max([(v,k) for k,v in target_dict.items()])[1]
def simplify(command):
return command[... |
import itertools
import matplotlib.pyplot as plt
from util import City, read_cities, write_cities_and_return_them, generate_cities, path_cost
def solve_tsp_dynamic(cities):
distance_matrix = [[x.distance(y) for y in cities] for x in cities]
cities_a = {(frozenset([0, idx + 1]), idx + 1): (dist, [0, idx + 1]) ... |
import datetime
import os
import shutil
import re
#Set a base Dir
basedir = r"\\localhost\d$"
for dirpath, dirnames, filenames in os.walk(basedir):
for d in dirnames:
curpath = os.path.join(dirpath, d)
dir_modified = datetime.datetime.fromtimestamp(os.path.getmtime(curpath))
# Conditional set t... |
# Function to find the minimum number of coins required
# to get total of N from set S
def findMinCoins(S, N):
# T[i] stores minimum number of coins needed to get total of i
T = [0] * (N + 1)
for i in range(1, N + 1):
# initialize minimum number of coins needed to infinity
T[i] = float('in... |
import skimage
import numpy as np
from PIL import Image
from albumentations import Resize
from data.transform import simple_transform
def get_iou(x1, x2):
intersection = np.clip((x1 * x2), 0, 1).sum()
union = np.clip((x1 + x2), 0, 1).sum()
if intersection == 0 and union == 0:
iou = 1.
elif ... |
import inspect
import logging
import shutil
import tempfile
import unittest
import mne
import numpy as np
import moabb.datasets as db
import moabb.datasets.compound_dataset as db_compound
from moabb.datasets import Cattan2019_VR, Shin2017A, Shin2017B
from moabb.datasets.base import BaseDataset, is_abbrev, is_camel_ke... |
count = 0
def isTriplet(word,l):
for i in range(len(word)-2):
(l1,l2,l3) = word[i],word[i+1],word[i+2]
if l1 == l and l2 == l and l3 == l:
return True
return False
originalword = "statisticians"
myword = "statstcians"
def main():
countPerms()
def countPerms():
... |
from pathlib import Path
import os
def convert_super_mario_bros_tile(character):
if character == '-': return '-'
elif character == 'X': return 'b'
elif character == 'x': return 'b'
elif character == 'S': return 'b'
elif character == 'Q': return 'b'
elif character == 'E': return 'A'
elif cha... |
"""
badnwidth portfolio
similar to bandw-2-stackoverfl-almostoriginal.py
"""
## define functions
def setup_df(df, A, B):
"""
asset A and B are strings.
"""
df = df[[A, B]]
df = df.fillna(method='ffill') # maybe remove
A_shares = A + '_shares'
B_shares = B + '_shares'
... |
ls = []
dict = {"name": "小明", "age": 20, "sex": "male"}
# file = open("./Test.txt",'r',encoding='utf-8')
# 只读文件 若文件不存在 则程序会报错
file = open("readfile.txt", 'w', encoding='utf-8')
# 写文件 若文件不存在 则创建一个文件到当前目录下
# file = open("readfile.txt",'r+',encoding='utf-8')
# 读+写文件,在读文件的前提下对于文件进行追加写操作
# 将列表中的元素逐个写入文件中
ls = ['1', '2', '... |
from zz import app
from flask import request,render_template,flash,abort,url_for,redirect,session,Flask,g
from zz.dao import lovemapper
from zz.redissession import redis
from zz.auth import shouquan_required
##desc:
##谈恋爱模块
##desc:
##谈恋爱首页
@app.route("/love/index/<id>")
@app.route("/love/index")
@app.route("/love/ind... |
#! /usr/local/bin/python
import pygame
from pygame.locals import *
import world, gfx
def fade(img, depth):
ret_val = img.copy()
if(depth == 0): return ret_val
for x in xrange(ret_val.get_width()):
for y in xrange(ret_val.get_height()):
(r, g, b, a) = ret_val.get_at((x,y))
ret_val.set_at((x,y), ... |
import copy
import itertools
import json
import logging
import os
import re
import tempfile
import numpy as np
import pandas as pd
import tensorflow as tf
from questions import config
from . import process
from . import symbols
log = logging.getLogger(__name__)
supported_precedence_names = ['predicate', 'function']
... |
import mailbox
import csv
writer = csv.writer(open("output.csv", "wb"))
for message in mailbox.mbox('input.mbox'):
writer.writerow([message['message-id'], message['subject'], message['from']])
print 'Mboxing complete! *high five*'
|
def removeDuplicates(nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
index = 0
for i in range(1, len(nums)):
if nums[index] != nums[i]:
index += 1
nums[index] = nums[i]
return index + 1
nums = [0,0,1,1,1,2,2,3,3,4]
pri... |
from datetime import datetime, timedelta
from tcsocket.app.models import sa_appointments, sa_services
from tcsocket.app.worker import delete_old_appointments, startup
from .conftest import MockEngine, count, create_appointment, create_company, select_set, signed_request
async def create_apt(cli, company, url=None, ... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Customers'
db.create_table(u'erp_app_customers', (
... |
"""functions for controlling mpd/mpx radio via python"""
import subprocess
import requests
baseurl = "http://volumio.local/api/v1/commands/?cmd="
def reboot():
"""reboot pi"""
subprocess.call('mpc stop', shell=True)
subprocess.call('reboot', shell=True)
def poweroff():
"""shutdown pi"""
subproce... |
#!/usr/bin/python
from time import sleep
from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate
import smbus
# initialize the LCD plate
# use busnum = 0 for raspi version 1 (256MB) and busnum = 1 for version 2
lcd = Adafruit_CharLCDPlate(busnum=0)
# clear display
lcd.clear()
# hello!
lcd.message("Adafruit RGB LCD\n... |
# Modulo de conexion con las colas SQS
import boto.sqs
from worker_settings import *
from boto.sqs.message import Message
conn = boto.sqs.connect_to_region(
AWS_REGION,
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
q = conn.get_queue(QUEUE_NAME)
def create_Message(b... |
from sys import argv
script, filename = argv
print(f"We are going to erase", {filename})
print("If you don't want to erase, hit ctr-c (^c)")
print("if you do want to destroy, hit RETURN.")
input("decision...? ")
print("Opening the file...")
target = open(filename, 'w')
print("Truncating the file. See yah!")
target_... |
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
result = 1
if (n < 0):
n = abs(n)
while (n != 0):
result = result * (1 / x)
n = n-1
elif (n > 0):
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-10-04 12:34
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('carto', '0008_auto_20171004_1135'),
]
operations =... |
from __future__ import division
import os
import numpy as np
import OpenEXR
import torch
import torch.utils.data as data
from datasets import pms_transforms
from . import util
np.random.seed(0)
class UpsSynthTestDataset(data.Dataset):
def __init__(self, args, split='train'):
self.root = os.path.join(args... |
# Generated by Django 3.1.3 on 2020-11-25 18:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('test', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ContactInfo',
fields=[
('id',... |
__author__ = 'alexey'
cities = {'red', 'black', 'blue', 'green', 'yellow', 'turquoise', 'orange', 'purple', 'white'}
weighted_subsets = {('red', ('red', 'black', 'blue')): 1.,
('black', ('green', 'black', 'blue', 'green')): 1.,
('blue', ('green', 'black', 'blue', 'green')): 1.,
... |
import matplotlib.pyplot as plt, numpy as np, pandas as pd
def graphs():
df = pd.read_csv('weatherbug_scrape.csv')
data = df.values.tolist()
time = []
temp = []
prec = []
mintemp = 0
maxtemp = 0
for i in range(len(data)):
if i != 0:
present = data[i]
time... |
def my_print():
print("pyhon.py:",__name__)
|
a=int(input('Introduceti 1 numar = '))
b=int(input('Introduceti 2 numar = '))
c=int(input('Introduceti 3 numar = '))
if(a>0 and b>0 and c>0):
if(b>c):
print('b')
if(b<c):
print('c')
if(b==c):
print('c')
if(a<0 and b<0 and c<0):
print(a+b) |
import shlex
import subprocess
from .global_storage import Globals
class UninitializedException(Exception):
def __init__(self, process):
self.commandLine = process.commandLine
def __str__(self):
return "Process is not initialized.\nCommand line for process: {0}".format(self.commandLine)
class TerminatedExcepti... |
from PIL import Image, PngImagePlugin
import os
def save_resized_image(image):
''' Resizes image and saves '''
PngImagePlugin.MAX_TEXT_CHUNK = 100 * (1024**2)
Image.MAX_IMAGE_PIXELS = None
pil_image = Image.open(image)
pil_image = pil_image.convert('RGB')
pil_image.thumbnail((1080, 1080))
... |
import datetime
from sqlalchemy import Column, Integer, ForeignKey, text, TIMESTAMP
from sqlalchemy.dialects.mysql import TEXT
from goldfnd.models import Base
class SurveyAnswerRule(Base):
__tablename__ = 'survey_answer_rule'
id = Column(Integer, primary_key=True, autoincrement=True)
survey_id = Column... |
#implementation of second order RK for second order ODE:
#We will use this to solve the precession of the preohelion of mercury later on
#example:
# The 2nd order ode is : (dy/dx)^2 + dy/dx -6y = 0
# the decoupled equations are:
# dy/dx = z;
# dz/dx = 6y - v;
# start by defining two general first order ODES
... |
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
LINK = "http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/"
def test_add_to_cart_button_is_displayed(browser):
browser.get(LINK)
... |
#! /usr/bin/env python2.7
from scapy.all import *
from netfilterqueue import NetfilterQueue
import os,sys
def usage():
print "[*]Usage: python dnsspoof_with_queue.py [host file] [DNS_SERVER_IP]"
def modify(packet):
print "Got packet"
pkt = IP(packet.get_payload()) #converts the raw packet to a s... |
# System
from datetime import timedelta
# Django
from django.utils import timezone
from django.views.generic import View
from django.shortcuts import render
from django.shortcuts import redirect
from django.urls import reverse
from django.http import Http404
# Open Pipelines
from ..m... |
import sys
from itertools import product
from rosalind_utility import parse_fasta
def multiple_alignment(str_list):
str_list = ["-" + string for string in str_list]
score_mat = {}
backtrack_mat = {}
def add_tuples_elemwise(t1, t2):
return tuple(sum(x) for x in zip(t1, t2))
## all possib... |
# Copyright 2016 Open Source Robotics Foundation, 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... |
# @Title: 打家劫舍 (House Robber)
# @Author: 2464512446@qq.com
# @Date: 2020-11-23 12:10:29
# @Runtime: 32 ms
# @Memory: 13.5 MB
class Solution:
def rob(self, nums: List[int]) -> int:
if not nums:
return 0
size = len(nums)
if size < 2:
return nums[0]
dp = [0] * ... |
import telebot
import config
import random
import numpy
e = 0
bot = telebot.TeleBot(config.TOKEN)
@bot.message_handler(content_types=['text'])
def lalala(message):
t = message.text
arr = []
arr.append(message.text)
if t == "/say":
array = ["Я крутой", "Сбежал из дурки", "Я - ... |
# Anjali Mangla
# 10/08/2018
# This code is the code for a minesweeper game in which participants must flag all of the bombs and not uncover any bombs before they finish the game.
# This is the link on string splitting:
# https://www.geeksforgeeks.org/python-string-split/
# On my honor, I have neither given nor receive... |
# all previous tutorials have been using
# procedure-oriented programming
# in this section, we'll make classes and do OOP stuff
# Objects can store data using ordinary variables that
# belong to the object. Variables that belong to an object
# or class are referred to as fields. Objects can also have
# functionality ... |
from typing import List, Dict, Optional, Union
import numpy as np
from jax import scipy as scipy
from jax import numpy as jnp
from autumn.model_features.outputs import OutputsBuilder
from autumn.model_features.agegroup import convert_param_agegroups
from autumn.models.sm_covid2.parameters import TimeDistribution, Vo... |
from canoser import *
from libra.hasher import gen_hasher
EVENT_KEY_LENGTH = 32
class EventKey(DelegateT):
delegate_type = [Uint8, EVENT_KEY_LENGTH]
class EventHandle(Struct):
_fields = [
('count', Uint64),
('key', EventKey)
]
class ContractEvent(Struct):
_fields... |
from QualiaII.models import tblVenta, tblSurtido, tblProducto
def calculoInversion(listaProductos):
productosCompras = {}
inversionProductos = {}
acumulador = 0
for var2 in listaProductos:
if tblSurtido.objects.filter(producto=var2).exists():
apariciones = tblSurtido.objects.filte... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from .base import FunctionalTest
class NewVisitorTest(FunctionalTest):
def test_can_start_a_list_and_retreive_it_later(self):
# User navigates to the main page of the website.
self.browser.get(self.live_server_url)
... |
#This program calculates Body Mass Index (BMI)
#author: Angelina Belotserkovskaya
# Asks to input height in cm and saves it into variable
# which is converted into int
height = int(input('Please enter your height in centimetres: '))
# Convert cm to m2
height = (height**2) / 10000
# Asks to input weight in kg and s... |
#Escribir un programa que pregunte al usuario por el número de horas trabajadas y el coste por hora. Después debe mostrar por pantalla la paga que le corresponde.
def run(salario,horas):
dinero_ganado = salario * horas
print("Has ganado {} dólares".format(dinero_ganado))
if __name__ == "__main__":
salari... |
# Generated by Django 2.2 on 2020-09-10 10:30
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0004_auto_20200910_1017'),
]
operations = [
migrations.AddField(
model_name='review',
name='re... |
#!/usr/bin/env python
# encoding: utf-8
from collections import namedtuple , deque , defaultdict , OrderedDict , Counter
Ponit = namedtuple('Point',['x','y'])
p = Ponit(1,2)
print (p.x)
print (p.y)
# 索引是自定义的x,y
q = deque(['x','y','z'])
q.append('a')
q.appendleft('b')
print (q)
dd = defaultdict(lambda:'N/A')
dd['key1']... |
# Libraries export
from bs4 import BeautifulSoup
import requests
import pandas as pd
from twilio.rest import Client
# regex module
import re
# lbc search
url = 'https://www.leboncoin.fr/motos/offres/provence_alpes_cote_d_azur/?th=1&q=*vespa%20gt*%20OR%20PX%20OR%20LML%20NOT%20solex%20NOT%20ciao%20NOT%20gts%20NOT%20gt... |
from morepath import redirect
from onegov.core.security import Secret
from onegov.translator_directory import _
from onegov.translator_directory import TranslatorDirectoryApp
from onegov.translator_directory.forms.mutation import ApplyMutationForm
from onegov.translator_directory.layout import ApplyTranslatorChangesLay... |
# -*- coding: cp1252 -*-
import codecs
import simplejson
import requests
#rotten_tomatoes_key = 'mq7dazg2njhpky3u5g5qqy6x'
# http://developer.rottentomatoes.com/docs
# http://www.omdbapi.com/?i=&t=Nina%27s+Heavenly+Delights
# http://www.imdb.com/xml/find?json=1&nr=1&q=Nina's+Heavenly+Delights
themoviedb_key = '8df... |
#queue
class Queue:
def __init__(self):
self.stack = []
def push(self, a):
self.stack.append(a)
def pop(self):
return self.stack.pop(0)
def is_empty(self):
return not self.stack
if __name__ == '__main__':
quantum = 100
tasks = [("p1", 15... |
#!/usr/bin/python
# k - m
# o - q
# e - g
# s - q shift by 2 letters mod 26
stringdata = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
chars = []
for ch in st... |
from collections import namedtuple
from onegov.core.crypto import random_token
from onegov.core.orm import Base
from onegov.core.orm.mixins import TimestampMixin
from onegov.core.orm.types import UTCDateTime
from onegov.file import AssociatedFiles
from onegov.file import File
from onegov.file.utils import as_fileintent... |
INF = 1e9
if __name__ == "__main__":
while True:
n, m, q = map(int, input().split())
if n == 0 and m == 0 and q == 0:
break
dist = [[INF for _ in range(n)] for __ in range(n)]
for i in range(n):
dist[i][i] = 0
for _ in range(m):
u, v, ... |
#!/usr/bin/env python3
import vcf
import pysam
import primer3
import argparse
import sys
def get_ref_dict(reffilename):
reffile = pysam.FastaFile(reffilename)
return {r : reffile.fetch(region=r) for r in reffile.references}
def make_primers_in_vcf(vcfreader, referencedict, exclusions):
print('\t'.join(['... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
DEBUG=False
CSRF_ENABLED = True
SECRET_KEY = 'gO57w=09]SBP:x(<\lP~t>5mD@F;@]8|ZhE<k+B\T|0jD8azhXc.X[GwE}h0x7+0k:G)E^-0drgMw`fi/_Zle^Jp;*~<t?OV0kICBs-}u\<R,\TI<DCdXJg(DGnt,TwDl@*Ebc{~XO>h,XSq]HX}rL<va"r2Z=2edZl[X_P8v=^PKpbG-g2a1yponhRk]n:c7:)kEZF[K{=fZ&a.... |
import json
import boto3
import datetime
import requests
import time
# Change before demo #
es_url = 'https://search-photos-bnrbmus63teifn3tn5obq24pjq.us-east-1.es.amazonaws.com'
s3_url = 'https://hw2-s3-bucket.s3.amazonaws.com/'
def lambda_handler(event, context):
lex = boto3.client('lex-runtime')
respons... |
#!/usr/bin/python3
'''
convert srt to ass with a suitable format
'''
import argparse
from threading import Thread
import pysubs2
BORDER = 'ScaledBorderAndShadow'
FONT = 'DejaVu Sans'
FONT_SIZE = 20
MARGINV = 2
EN_STYLE = r'{\fs14}'
def main(srt_in):
subs = pysubs2.load(srt_in, encoding='UTF-8')
subs.inf... |
from gui.model_view_components.remote_filesystem_model import FileItem
__author__ = 'Галлям'
from PyQt5 import QtWidgets, QtGui, QtCore
from core.core import Core
import gui.model_view_components.local_filesystem_view as local
import gui.model_view_components.remote_filesystem_view as remote
class MainWindow(QtWidg... |
import math, time, matplotlib.pyplot as plt, numpy, functools
# The solution is 75737353,
# and it took 102.2976252 seconds to compute with version 5!
# After improving with version 7,
# it takes only 37.6414667 seconds to compute!
def getFactor(n):
for i in range(2, math.floor(math.sqrt(n))+1):
... |
#!/usr/bin/python3
"""This module performs math on matrices"""
def matrix_divided(matrix, div):
"""This method divides each element in a matrix
Args:
matrix (list or lists): the matrix
div (int): the number to divide each element by
Attributes:
err_1 (str): error message 1
... |
#!/home/myuser/bin/python
not_sent_emails = []
import smtplib as s
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import numpy
import sys; sys.path.append('/home/ec2-user/anaconda3/lib/python3.8/site-packages/mysql')
import mysql.connector
from mysql.connector import erro... |
answers = {'привет':'Привет',
'как дела': 'Хорошо',
'что делаешь': 'Программирую'
}
def get_answer(question, answers):
return answers.get(question)
def ask_user(answers):
while True:
try:
user_say = input('Скажи что-нибудь:')
answer = get_answer(user_say, answers)
if user_say == 'пока':
... |
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import OperationStatusCodes
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials
from ar... |
#!C:\Python27\python.exe
#-*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd
import numpy as np
import cgi
import cgitb
import mpld3 as d3
import sqlalchemy as sql
import sys
reload(sys)
sys.setdefaultencoding('utf8')
cgitb.enable()
#form=cgi.Fie... |
#coding: utf-8
from datetime import date
import boundaries
boundaries.register(u'Pointe-Claire districts',
domain=u'Pointe-Claire, QC',
last_updated=date(2013, 8, 21),
name_func=boundaries.clean_attr('NOM_DISTRI'),
authority=u'Ville de Montréal',
source_url='http://donnees.ville.montreal.qc.ca/fic... |
from __future__ import print_function
import argparse
import random
import re
import subprocess
import sys
import time
import requests
PORTAL_URL = 'https://portal.reivernet.com/'
def set_mac(interface, mac):
"""Set `interface`'s MAC address to `mac`.
Return False if an error occurred (permission denied)... |
número = int(input('Digite um número: '))
calculo = número % 2
print(calculo)
if calculo == 0:
print(f'O número {número} é par')
else:
print(f'O número {número} é ímpar')
|
from sklearn import datasets
import numpy as np
from sklearn.model_selection import train_test_split
iris = datasets.load_iris()
setosa = np.array(iris.data[:50, 2])
versicolor = np.array(iris.data[50:100, 2])
virginica = np.array(iris.data[100:150, 2])
X_train, X_validation, y_train, y_validation = train_test_split(i... |
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
# Examples:
# url(r'^$', 'trains.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
<<<<<<< HEAD
url(r'^contests/', include('contest.urls')),
======... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import twitter
CONSUMER_KEY="Tf0llJkFekN0fQRs3jm8D64BV"
CONSUMER_SECRET="iI909hsiksvYfotc9Ra8EPeA8dpCjShB6E2BlmDK31bu1hfLnd"
ACCESS_TOKEN_KEY="952559428619898881-Cimwl8COh51kdsM04xkxNN3mMV8Oy0n"
ACCESS_TOKEN_SECRET="66wC1hUBRI1kO0S5Wvj7vLYhBoKQCIPHQmx0vFFJwuJgw"
... |
class Stationery:
def __init__(self, title='Stationery'):
self.title = title
def draw(self):
print('Запуск отрисовки')
class Pen(Stationery):
def draw(self):
print(f'Запуск отрисовки объекта {self.title} типа {type(self)}')
class Pencil(Stationery):
def draw(self):
p... |
import random
import math
import numpy as np
def data_pass_generator(n):
output = []
for i in range(n):
center = 0
blink = 0
left = 0
right = 0
for j in range(100):
[ rd ] = random.choices(range(0, 4), weights=[92,4,2,2])
if rd == 0:
center += 1
elif rd == 1:
blink += 1
elif rd == 2:
... |
#Project Euler Problem 67
#Find the maximal sum through the triangle of 100 lines
M=[]
# Open the file import in to python
#f=open('smallTriangle.txt').readlines()
f=open('triangle.txt').readlines()
for line in f:
M.append(line.replace('\n','').split(' '))
print(M)
#Hold an array of sums
sum=[0]*100
sum[0]=int(M[... |
import json
import os.path
import pytest
import sqlalchemy_utils
import sys
from scripts import udf
from scripts import config as tcn
import tests.test_functions as db
from scripts import env_vars as env_vars
#from scripts import config as cn
def readJson(fileLoc):
with open(fileLoc) as f:
data = json.load... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.