text stringlengths 8 6.05M |
|---|
import cs50
def caesar():
print("Ciphertext: ", end="")
for char in zdanie:
if char.isupper():
ascii = ord(char) + przesun
if ascii > 90:
ascii = ascii - 26
char = chr(ascii)
elif char.isalpha():
ascii = ord(char) + przesun
... |
str1 = "suriya"
str2 = "ganesh"
print(str1+str2)
print(str1+" "+str2)
print(str1*3)
print(str1+"\n"+str2)
print(str1+"\t"+str2)
print(str1[0])
print(str1.find('u')) # in place of a char or string u can also pass a string variable
print(str1.replace('ri','r'))
print(str1.count('s'))
print(str1.capitalize())
print(r"\n... |
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views.generic import DetailView, ListView, UpdateView
from django.views.generic.edit import CreateView
from .models import RestaurantReview, Restaurant #, Dish
from .forms impo... |
import couchdb
import config
import os
import thread
import csv
class CouchConnection:
def __init__(self, address=config.couch_address, dbName=config.dbName):
self.rootPath = config.rootPath
try:
self.server = couchdb.Server(address)
if dbName in self.server:
... |
"""Script for launch brain even game."""
from brain_games.flow.game import play
from brain_games.games import calc
def main():
"""Entry point to brain even game."""
play(calc)
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('finanzas', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='cliente',
name='IDB... |
import unittest
from .scanner import TestScanner
from .parser import TestParser
def test_suite():
scanner_suite = unittest.makeSuite(TestScanner)
parser_suite = unittest.makeSuite(TestParser)
return unittest.TestSuite([scanner_suite, parser_suite])
if __name__ == "__main__":
suite = test_suite()
... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sklearn
from imutils import contours
import cv2
from PIL import Image,ImageGrab
import kociemba
import keyboard
vid = cv2.VideoCapture(0)
p=[(0,0,0)]*96
p1=[(0,0,0)]*96
p0=['O']*96
pf=['O']*54
z=90
z1=180
n=0
m='ru'
def so... |
# Generated by Django 2.2.2 on 2019-09-17 03:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('teachingtask', '0008_teachingtask_is_changed'),
('teacher', '0006_teacher_photo'),
('headteacher', '0001_ini... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^imagecodes/(?P<image_code_id>.+)/$', views.RegisterImageCodeAPI.as_view()),
url(r'^smscodes/(?P<mobile>1[3456789]\d{9})/$', views.RegisterSmsCodeAPI.as_view()),
url(r'^image_codes/(?P<image_code_id>.+)/$',views.RegisterImageCodeAP... |
from django.shortcuts import render
from rest_framework import generics
from rest_framework.response import Response
from data.data_controller import *
def index(request):
return render(request, 'index.html')
def line(request):
return render(request, 'line.html')
def pie(request):
return render(reque... |
from app import app, db
from app.models import User, Autobase
import unittest
class UserModelCase(unittest.TestCase):
def setUp(self) -> None:
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
db.create_all()
def tearDown(self) -> None:
db.session.remove()
db.drop_all()
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 12 17:17:17 2020
@author: isaac
"""
#Importar as bibliotecas para tratamento matemático, pré-processamento, gráficos e aplicação de modelos
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#%matplotlib inline
from sklearn.model... |
# De 7, Quantos atingiram a maioridade e quantos não
from datetime import date
anoAtual = date.today().year
maiores = 0
menores = 0
for i in range(0, 7):
ano = int(input('Digite o ano de nasc. da {}ª pessoa: '.format(i + 1)))
if (anoAtual - ano) >= 18:
maiores += 1
else:
menores += 1
pri... |
from __future__ import unicode_literals
from django import forms
from django.core.validators import validate_ipv46_address
from .validators import validate_domain
class HeadersForm(forms.Form):
headers = forms.CharField(widget=forms.Textarea())
class DomainForm(forms.Form):
domain = forms.URLField(help_te... |
import googleplaces
print (googleplaces.__version__)
try:
a = googleplaces.getAllPlaces(
key = 'xxxxxxxxxxxxxxxxxxxx',
latitude = 41.146057,
longitude = -8.605268,
radius = 500,
type='restaurant',
keywords=['sushi','tasca'],
total = 5)
for i in a:
print (i)
print ("\n\n")
print (l... |
###########
## Notes ##
###########
'''
Here is the Python grammar for writing a procedure:
def <name>(<params>):
<block>
'''
'''
Quiz: Find Second
'''
def find_second(search, target):
first = search.find(target)
return search.find(target, first + 1)
'''
Quiz: Is Friend & More Friends
<expression> or <exp... |
from django.shortcuts import render_to_response
from django.template import RequestContext
def index(request, day=None, month=None, year=None):
# some code to get posts/articles/etc by
# passed day, month or year
return render_to_response("archive/index.html", {}, context_instance=RequestContext(request))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = ['Nico Curti', "Daniele Dall'Olio"]
__email__ = ['nico.curti2@unibo.it', 'daniele.dallolio@studio.unibo.it']
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 9 14:38:54 2020
@author: TakahiroKurokawa
"""
items=['note','notebook','sketchbook']
print(1,type(items))
print(2,items)
print(3,list('book'))
items.append('paperbook')
print(4,items)
items=['book']+items
print(5,items)
print(6,items.pop(0))
pri... |
"""
Unit tests for the parser.
"""
import unittest
class TestParser(unittest.TestCase):
def setUp(self):
self._parser_module = None
def getParserModule(self):
if self._parser_module is None:
from bigrig import parser
self._parser_module = parser
return self._par... |
import math
import datetime
class Solution:
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
# com = [False] * (n+1) # assume all are primes
# prime = []
# primes = 0
# i = 2
# while i < n:
# if com[i] == False:
#... |
"""XKNX version."""
__version__ = "0.18.12"
|
import os
import shutil
from django.conf import settings
import requests
import time
_base_link = 'https://m.rebrickable.com/media/downloads/'
_tmp_dir = settings.API_UPDATE_TEMP_DIR
_api_key = '7a63f7230da51d57ede0d83357d160d9'
_delay_in_seconds = 0.75
def download_packages(packages, msg_writer):
make_temp_dir... |
# -*- coding: utf-8 -*-
"""
@author: Duy Anh Philippe Pham
@date: 21/07/21
@version: 1.00
@Recommandation: Python 3.7
@But : DBSCAN discret
"""
import numpy as np
import sys
sys.path.insert(1,'../../libs')
from sklearn.cluster import DBSCAN
from sklearn import metrics
import matplotlib.pylab as plt
import tools, di... |
import os
import sys
import time
import random
import termcolor
def init_array(width, height):
return [[0 for j in range(width)] for i in range(height)]
def random_init_array(width, height):
return [[random.randint(0, 1) for j in range(width)] for i in range(height)]
def count_c(array, row, col):
cr = l... |
from __future__ import annotations
import datetime
from main.core.model.exceptions.internal.SingletonClassException import SingletonClassException
from main.core.model.exceptions.request.NoSuchElementException import NoSuchElementException
from main.core.model.simulation.SimulationReport import SimulationReport
from ... |
import sys
import re
import roman
import enchant
def get_professor_course_mapping(dirty_professor_course_data):
clean_professor_course_data = {}
for row in dirty_professor_course_data:
professor_full_name, courses = row.split(' - ')
professor_full_name = professor_full_name.strip()
cou... |
import sys
sys.stdin=open("input.txt", "r")
# 기타 레슨
# 파라메트릭 서치
N, M = map(int, input().split())
lectures = list(map(int, input().split()))
s = max(lectures)
e = sum(lectures)
ans = 100000
while s <= e:
mid = (s + e) // 2
length = 0
numOfBlue = 1
for lecture in lectures:
if length + lecture <... |
from rest_framework import serializers
from authentication.models import User
import uuid
from .models import UserProject,UserEducation,UserExperience
class UserProjectSerializer(serializers.ModelSerializer):
class Meta:
model= UserProject
fields=['title','description','start_date','end_date','u... |
import random
number = random.randint(0,3)
words = ["cat","shoe","pizza","dragon"]
hint1 = ["chases mice","tastes great","laces","breathes fire"]
hint2 = ["meow","cheese and sauce","soles","flies"]
secretword = words[number]
guess = ""
counter = 1
while True:
print("Guess a word")
print("Type ... |
from app.models.kuotaModel import db, Quota
from app import app
from flask import render_template,request,redirect
@app.route('/kuotadata', methods=['GET','POST'])
def choose():
if request.method == 'POST':
nama = request.form['nama']
sekolah = request.form['sekolah']
email = request.form... |
a=int(input("enter height in feet: "))
x=a*12
print("no. of inches: ",x) |
from unittest import TestCase, main
from ... import UndirectedGraph
class TestFormulateMaxStableSet(TestCase):
def test_formulate_max_stable_set(self) -> None:
pass # TODO
if __name__ == "__main__":
g = UndirectedGraph(
edges={("a", "b"): 1, ("a", "c"): 0, ("a", "d"): 2}, vertices={"a": 10... |
# merge sort
import random
def mergeSort(data, start, end):
if end - start == 0: # if length of data is 1
# print(f"start : {data[start]}, end : {data[end]}")
return
mid = (start + end) // 2
mergeSort(data, start, mid) # from start to middle
mergeSort(data, mid + 1, end) # from mid... |
import day6
import unittest
class Day2Tests(unittest.TestCase):
def test_True(self):
self.assertTrue(True)
def test_Day6_Example(self):
data = '''eedadn
drvtee
eandsr
raavrd
atevrs
tsrnev
sdttsa
rasrtv
nssdts
ntnada
... |
# matrix_utils.py
#
# A matrix is a list of it's rows.
# This is a 1x4 matrix [[0, 1, 2, 3, 4]]
# and this is a 4x1 matrix [[0], [1], [2], [3], [4]]
#__all__ =['multiply', 'transpose', 'add', 'id', 'zero', 'dimension']
"""
>>> 1 + 2
3
"""
def multiply(m1, m2):
assert num_cols(m1) == num_rows(m2)
return [combi... |
import scraperwiki
import requests
import lxml.html
import mechanize
countryList = []
linkList = []
#FUNCTION TO GET A HREF OF CRIMINALS
def getLinks(url):
html = requests.get(url).text
br = mechanize.Browser()
br.set_handle_robots(False)
root = lxml.html.fromstring(html)
for el in root.cssselect... |
#!/usr/local/bin/python
import sys
import random
import operator
def aat_recursive ( v ) :
global fanin, MIN, dly
fanin_of_v = fanin[v]
tmp = MIN
if ( len(fanin_of_v) > 0 ) :
for u in fanin_of_v :
if ( tmp < aat_recursive( u ) + dly[ v ] ) :
tmp = aat_recursive( u ) + dly[ v ]
... |
# Sample list
# lst = [(' ', 'Mean', 'Standard deviation', 'Min', 'Max'),
# (1, 444, 'Pune', 18),
# (2, 'Vaishnavi', 'Mumbai', 20),
# (3, 'Rachna', 'Mumbai', 21),
# (4, 'Shubham', 'Delhi', 21)]
import numpy as np
def geneTable(numFI, csvPath):
y = np.loadtxt(csvPath, delimiter='\n', unpack=True)
... |
from jBird.utils.Constants import Positions
class Chicken:
"""Class containing methods and attributes referring to chicken moving on the board."""
def __init__(self):
""""Initialization of chicken."""
self.position = list(Positions.CHICKEN_INIT_POSITION.value)
self.level = -1
... |
import random
import time
from init import Config
config = Config()
def generate_range():
return random.randint(config.min_val, config.max_val), random.randint(config.min_val, config.max_val)
def question(operator, operand_a, operand_b):
"""Build the question string"""
return 'What is ' + str(operand_... |
import yaml
from aws_cdk import (
core,
aws_ecs as ecs,
aws_iam as iam,
aws_secretsmanager as secrets,
aws_codebuild as codebuild,
aws_codepipeline as codepipeline,
aws_codepipeline_actions as actions,
aws_chatbot as chatbot
)
from .common_resources import CommonResourceStack
class Ap... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2018-07-09 18:06
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wagtail.wagtailcore.blocks
import wagtail.wagtailcore.fields
class Migration(migrations.Migration):
dependencies = [
... |
# Import libraries
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
# Import dataset
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:,:-1].values #independent variable
Y = dataset.iloc[:,1].values #dependent variable
#splitting the training and test data
from sklearn.mode... |
#-*- coding:utf-8 -*-
'''
描述:
蒙特卡罗方法,或称计算机随机模拟方法,是一种基于随机数的计算方法,在金融工程学,宏观经济学,计算物理学等领域应用广泛。
试编写函数solve(a,b),利用蒙特卡罗方法计算函数f(x)=(e^(-x²/2))/√2√π在区间[a,b]上的定积分并返回,其中b>a>0。
输入:a,b分别为正浮点数
输出:m: 定积分值
注意:
(1)为保证精确性,蒙特卡罗模拟次数至少为100000
(2)不能使用scipy.integrate库
'''
'''
要点:
'''
import random
import math
class Solution:
... |
from common import *
from net.loss import *
import net.lovasz_losses as L
from net.sync_batchnorm.batchnorm import *
from model.senet import SEResNeXtBottleneck, SENet
#########################################################################################
class ConvBn2d(nn.Module):
def __init__(self, in_... |
# Generated by Django 3.0.6 on 2020-06-12 10:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Home', '0016_auto_20200612_1447'),
]
operations = [
migrations.AddField(
model_name='item',
name='medium',
... |
import re
from functools import partial
def sample_partial_sub():
""" Sample of sub with partial
>>> sample_partial_sub()
'This is a .'
"""
erase_hoge = partial(re.compile(r'hoge').sub, '')
return erase_hoge('This is a hoge.')
if __name__ == '__main__':
import doctest
doctest.test... |
import numpy as np
from .data_structure import Config, Rule
def stableMajority(array: np.ndarray, config: Config, index):
even = 1 if config.nodes[index].degree % 2 == 0 else 0
state = 1 if config.prod(array, index) + even*array[index] > 0 else -1
return state
def unstableMajority(array, config: Config,... |
from flask import Flask, render_template
from api import api_bp
import argparse
import os
app = Flask(__name__)
app.config.from_pyfile('config.py')
app.register_blueprint(api_bp)
@app.route('/')
def index():
return render_template('index.html')
|
import eqparser
import copyTree
def comm(root):
if root == None:
return root;
if root.leaf == '=':
return 0
if root.leaf == '+' or root.leaf == '*':
newRoot = copyTree.createTreeCopy(root)
tmp = newRoot.children[0]
newRoot.children[0] = newRoot.children[1]
newRoot.children[1] = tmp
return newRoot
ret... |
import unittest
from gpiozero.pins.mock import MockFactory, MockTriggerPin
from gpiozero import Device
from hardware.trash_detector import TrashDetector, PIN_TRIGGER, PIN_ECHO
factory = MockFactory()
Device.pin_factory = factory
class ProximityTest(unittest.TestCase):
def test_if_object_was_detected(self):
... |
#!/usr/bin/env python
# Copyright 2013, Big Switch Networks, Inc.
#
# LoxiGen is licensed under the Eclipse Public License, version 1.0 (EPL), with
# the following special exception:
#
# LOXI Exception
#
# As a special exception to the terms of the EPL, you may distribute libraries
# generated by LoxiGen (LoxiGen Libra... |
#!/usr/bin/python
'''
Find the Shortest path from a single source to all its vertices
Dijkstra Algorithm using HEAP
Important point is the way in which the next vertex to process is chosen. It is a Greedy algorithm.
Priority Q or Min Heap is used for chosing the next closest vertex
'''
import math
from heapq impor... |
import glob
import os.path
import pathlib
import sqlite3
__all__ = ["get_backup"]
MANIFESTS = "~/Library/Application Support/MobileSync/Backup/*/Manifest.db"
PLIST_PATH = "Library/Preferences/com.duosecurity.DuoMobile.plist"
def file_stats(path):
p = pathlib.Path(path)
return (path, p.stat().st_mtime)
def... |
#!/bin/python
import sys
infile = open(sys.argv[1], "r")
input = []
lineNo = 1
for line in infile:
line = line.rstrip()
input.append(int(line))
input.sort()
input.append(input[-1] + 3)
oneJolt = 0
twoJolt = 0
threeJolt = 0
#print input
prev = 0
for a in input:
#print prev, a
if a - prev == 1:
... |
# This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... |
import socket
import time
import json
import os
import Cryptodome
from Cryptodome.PublicKey import ECC
from Cryptodome.Hash import SHA256
from Cryptodome.Signature import DSS
def DummyClient():
"""Starts a TCP client
Connects to server
Pings some data off of the server
"""
host = "127.0.0.1" #loopb... |
#-- GAUDI jobOptions generated on Tue Nov 11 13:42:14 2014
#-- Contains event types :
#-- 25103010 - 33 files - 523499 events - 111.88 GBytes
#-- Extra information about the data processing phases:
#-- Processing Pass Step-124834
#-- StepId : 124834
#-- StepName : Reco14a for MC
#-- ApplicationName : Br... |
import numpy as np
np.set_printoptions(precision=4)
import time
from scipy import spatial
def xy2theta(x, y):
if (x >= 0 and y >= 0):
theta = 180/np.pi * np.arctan(y/x);
if (x < 0 and y >= 0):
theta = 180 - ((180/np.pi) * np.arctan(y/(-x)));
if (x < 0 and y < 0):
the... |
from sense_hat import SenseHat
from random import randint
from time import sleep
sense = SenseHat()
while 1:
def pick_color():
r = randint(0,255)
g = randint(0,255)
b = randint(0,255)
return(r,g,b)
sense.show_letter("N", pick_color())
sleep(1)
sense.show_lett... |
#!/usr/bin/env python
import os
import sys
import subprocess
print('Start SERVE')
########## 1 ########## # some printing abt the sys
if os.environ.get('PRINT_SYS'):
print(os.environ)
print('pip freeze')
subprocess.call('pip freeze', shell=True)
print('df -h')
subprocess.call('df -h', she... |
from browser import document
import brythonserver.turtle as turtle
t = turtle.Turtle()
t.width(5)
for c in ['red', '#00ff00', '#fa0', 'rgb(0,0,200)']:
t.color(c)
t.forward(100)
t.left(90)
# dot() and write() do not require the pen to be down
t.penup()
t.goto(-30, -100)
t.dot(40, 'rgba(255, 0, 0, 0.5')
t.... |
from transformers import MBartForConditionalGeneration, MBart50Tokenizer
from .base_multilingual_model import MultilingualSummModel
class MBartModel(MultilingualSummModel):
# static variables
model_name = "mBART"
is_extractive = False
is_neural = True
is_multilingual = True
lang_tag_dict = {
... |
a=int(input())
b=input()
c=''
for i in range(-1,-a-1,-1):
if b[i].lower() not in "aeiou":
c+=b[i]
print(c)
|
"""
PCPP-32-101 1.3 Understand and use the concepts of inheritance,
polymorphism, and composition
- inheritance vs. composition
- modelling real-life problems using the "is a" and "has a" relations
Inheritance models what is called an is a relationship. This means that when you have a Derived class that inherits
fro... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-08-28 21:01
from __future__ import unicode_literals
import autoslug.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('thoughts', '0004_auto_20170828_1619'),
]
operations = [
migr... |
from os import environ
from flask import Flask, jsonify, request, make_response
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import func
from flask_migrate import Migrate
from flask_cors import CORS
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = environ.get("dbURL")
app.config["SQLALCHEM... |
import numpy as np
import matplotlib.pylab as plt
import scipy.sparse
from .basewidget import BaseWidget
class DriftOverTimeWidget(BaseWidget):
"""
Plot "y" (=depth) (or "x") drift over time.
The use peak detection on channel and make histogram
of peak activity over time bins.
Parameters
--... |
import cv2
import numpy as np
import os
from PIL import Image, ImageTk
import tkinter
import PySimpleGUI as sg
import numpy as np
import PySimpleGUI as sg
from PySimpleGUI.PySimpleGUI import WINDOW_CLOSED
layout = [[sg.Text("SISTEMA IDENTIFICAÇÃO DE IMPRESSÕES DIGITAIS")],
[sg.Text("ATENÇÃO: ADI... |
"""=
Define all routes here
"""
from config import Config
from flask import Blueprint
from flask import request, make_response, render_template
from models import db, User, Stats
handler = Blueprint('router', __name__)
@handler.route("/")
@handler.route("/home")
def home_feed():
return render_template('index.html')
... |
from bs4 import BeautifulSoup,Comment
import requests
from requests.adapters import HTTPAdapter
from time import sleep
import json
import urllib
import re
import nltk
from nltk.tokenize import RegexpTokenizer
from nltk.tag import pos_tag
from unidecode import unidecode
import os
tokenizer = RegexpTokenizer(r'\w+... |
#!/bin/python3
def equalize_the_array():
n = int(input())
counts = {}
current_max = 0
for x in input().strip().split(' '):
if x in counts:
counts[x] += 1
else:
counts[x] = 1
current_max = max(current_max, counts[x])
return n - current_max
print(equal... |
# -*- coding: UTF-8 -*-
#
# Base class of all experiments.
#
# Copyright (C) 2010-2011 Huang Xin
#
# See LICENSE.TXT that came with this file.
import os
import re
import time
import logging
from StimControl.ControlCmd import StimCommand
class ExperimentConfig(object):
""" Define essential parameters before runnin... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-08-17 03:03
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nova', '0007_auto_20170817_1102'),
]
operations = [
migrations.AddField(
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# cy
from appium import webdriver
class TestSetting:
def test_set(self):
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '5.1'
desired_caps['deviceName'] = '192.168.56.101:5555'
des... |
import mysql.connector
cnx = mysql.connector.connect(user='root', password='toor',
host='127.0.0.1',
database='sakila_dwh')
cursor = cnx.cursor()
for x in range(1000):
cursor.execute("UPDATE `sakila_dwh`.`dim_film` SET `film_key` = '%d' WHERE ... |
from pwn import *
import sys
#import kmpwn
sys.path.append('/home/vagrant/kmpwn')
from kmpwn import *
#fsb(width, offset, data, padding, roop)
#config
context(os='linux', arch='i386')
context.log_level = 'debug'
FILE_NAME = "./give_away_2"
HOST = "sharkyctf.xyz"
PORT = 20335
if len(sys.argv) > 1 and sys.argv[1] == ... |
# Intro to Market Basket Analysis
# Cross-selling products
# Count the number of transactions with coffee and gum
coffee = transactions.count(['coffee', 'gum'])
# Count the number of transactions with cereal and gum
cereal = transactions.count(['cereal', 'gum'])
# Count the number of transactions with bread and gum
b... |
import gensim
from gensim.utils import simple_preprocess
from gensim.parsing.preprocessing import STOPWORDS
from nltk.stem import WordNetLemmatizer, SnowballStemmer
from gensim import corpora, models
from nltk.stem import WordNetLemmatizer, SnowballStemmer
from nltk.stem.porter import *
# load model, load n_topics,
# ... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
bicycles = ['hero','ranger','bmx','redline']
print (bicycles)
print(bicycles[1])
print(bicycles[3])
# In[2]:
bicycles = ['hero','ranger','bmx','redline']
print (bicycles[0].title())
print(bicycles[1].upper())
# In[4]:
bicycles = ['hero','ranger','bmx','redline']... |
#coding:utf-8
from . import api
from .. import db
from ..models import Project, Applicant
from flask import jsonify, request
@api.route('/project/posting/cache/unit/', methods = ['GET'])
@Applicant.check
def get_information(aid):
if request.method == 'GET':
applicant = Applicant.query.filter_by(id=aid).f... |
import pandas as pd
import numpy as np
from datetime import timedelta
import sys
from pandas.plotting import register_matplotlib_converters
import matplotlib.pyplot as plt
register_matplotlib_converters()
def create_csv():
xls = './Netzfrequenz_Sekundenwerte_2012_KW37.xlsx'
tab_with_data = 'Netzfreque... |
letters = ['a', 'b', 'c', 'd']
numbers = [1,2,34,5,6,6]
zipped_object = zip(letters, numbers)
# print(list(zipped_object))
for pair in zipped_object:
print(pair)
|
# coding = UTF-8
import ephem
import datetime
import logging
def get_eng_planet_name(planet_name):
#print('start get_eng_planet_name with planet_name = {planet_name}'.format(planet_name=planet_name))
err = ''
planet_name_eng = ''
if planet_name.lower() == 'меркурий' or planet_name.lower()=='mercury':
... |
from flask import render_template, flash, redirect, url_for, g, request
from app.forms import SearchForm
import bleach
from app.models import AlternateNames
import app.nameTools as nt
from sqlalchemy.sql.functions import Function
from sqlalchemy.sql.expression import select, desc
from app import app
from app import d... |
from .form import RegisterationForm
from .form import LoginForm
from django.test import TestCase
from django.core.urlresolvers import reverse
import sys
#---------------Testing Forms----------------------
|
import n2
from sknetwork.hierarchy import Paris
from sknetwork.hierarchy import cut_balanced, cut_straight
##paris clustering. The alternative would be MiniBatchKMeans (below),
##which to be honest is muc... |
import sys
import csv
from bs4 import BeautifulSoup
def generate_soup(html_file_name):
with open(html_file_name) as html_file:
soup = BeautifulSoup(html_file.read(), 'html.parser')
return soup
def get_game_number(table_row):
table_cell = table_row.find_all('td')[0]
game_number = table_cell.fi... |
import unittest
from Learn_python3.Home_Work_5.H_W5_P1_3 import ITEmployee
class TestItEmployee(unittest.TestCase):
def setUp(self):
self.test = ITEmployee("Eugene Storchak", 1987, "Qa Engineer", 5, 1850)
def test_name(self):
a = self.test.get_name()
self.assertEqual(a, "Eugene")
... |
# Generated by Django 2.2.1 on 2019-07-21 21:37
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
... |
import pydantic
from typing import Any, Optional
from models.game.unit import BaseGameUnit, Worker, Warrior
import constants
class NotHaveMoney(Exception):
pass
class Player(pydantic.BaseModel):
"""Идентификатор игрока.
"""
id: int
"""Готов к игре.
"""
is_started: bool = False
"""И... |
import os
from music21 import scale
def get_no_flat_equivalent(self):
tonic = self.getTonic()
if tonic.accidental and tonic.accidental.name == 'flat':
return self.__class__(tonic.getEnharmonic())
else:
return self
def to_string(self):
tonic = self.getTonic()
return '{mode}{tonic}{... |
from game.items.item import Pickaxe
from game.skills import SkillTypes
class IronPickaxe(Pickaxe):
name = 'Iron Pickaxe'
value = 140
skill_requirement = {SkillTypes.mining: 1}
equip_requirement = {SkillTypes.attack: 10}
damage = 74
accuracy = 202 |
from django.shortcuts import render, redirect, get_object_or_404
from django.core.exceptions import PermissionDenied
from django.db.models import Q
from django.http import JsonResponse
from django.utils import timezone
from .models import Events, Types
from .forms import EventForm
def add(request):
if request.us... |
#easy dropout
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as Data
from torch.nn import init
import torch.optim as optim
from collections import OrderedDict
import torchvision as tv
import torchvision.transforms as transforms
import numpy as np
import matplotlib.pyplot as p... |
#!/usr/bin/env python
#python count_heterozygotes.py filein filetype
"""
Deprecated
"""
import sys
import diploidify
from Bio import AlignIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import IUPAC
from Bio.Align import MultipleSeqAlignment
iupac = {
'A' : 'AA',
'C' : 'CC',
'T' : ... |
class LinkedListUnderFLow(ValueError):
pass
class LinkedListOverFLow(Exception):
pass
class LNode:
"""
Linked List Node class. This class is used to represent each node in Linked List.
"""
def __init__(self, elem, _next=None):
self.elem = elem
self.next = _next
class LList:... |
#!/usr/bin/python3
# coding: utf8
from google.cloud import texttospeech_v1beta1 as texttospeech
import os
from sys import argv, exit
from subprocess import call
import hashlib
import locale
import requests
import pytoml
# have to set google_creds in snips.toml
# https://console.cloud.google.com/apis/credentials/servi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.