text stringlengths 8 6.05M |
|---|
# Plural And Single
# Works But not as well...Cactus = Cactuses instead of Cacti
# By Efrain
import inflect
p = inflect.engine()
while True:
plu = input("Enter A Plural Or Singular Word: ")
print("The Plural/Singular Of ", plu, " Is ", p.plural(plu))
"""
print("The singular of ", plu, " is ", p.singula... |
import time
import os.path as osp
import numpy as np
from tqdm import tqdm
import torch
from torch import nn
import torch.nn.functional as F
import torch.nn.init as init
from torch.optim import SGD, Adam
from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts, CosineAnnealingLR, ReduceLROnPlateau
def run_tr... |
from django.shortcuts import render,get_list_or_404,get_object_or_404
from django.contrib.auth import get_user_model
from residents.models import Lot,Community,Area,Street,Resident,ResidentLotThroughModel
from django.utils import timezone
from rest_framework import generics,status,viewsets
from rest_framework.views imp... |
#create species or character class
import json
def create_log(type):
try:
fname=type+".json"
with open(fname) as f:
log=json.load(f)
except:
log={}
query="Enter "+type+" : "
c= input(query)
#tests if type already exists
if c.upper() not in log.keys():
lo... |
from django.urls import path
from .views import *
from . import views
urlpatterns = [
path('', IndexView.as_view(), name='home'),
path('shop/', ShopView.as_view(), name='shop'),
path('book_single/', BookSingleView.as_view(), name='book_single'),
path('create/', BookCreate.as_view(), name='book_crea... |
# dungeon crawler game for me and my friends
from tkinter import *
from weapon import *
from player import *
from goblin import *
from Boss import *
import time as time
class Game():
pass
root = Tk()
root.title('Mictlan')
p = Player(10, "None")
root.geometry('1690x1120')
frame = Frame(root)
frame.pack(side=... |
#Wil Collins
#Part 3
import random
number = int(input("Please enter a number between 10 and 10,000: "))
while number<10 or number > 10000 :
number = int(input("That was an incorrect number please try again. "))
count = 1
wins = 0
percent = wins/count
for number in range(0,number+1,):
person =... |
import enum
import pathlib
from typing import Any, BinaryIO, Dict, List, Optional, Tuple, Union
from torchdata.datapipes.iter import CSVDictParser, Demultiplexer, Filter, IterDataPipe, IterKeyZipper, Mapper
from torchvision.prototype.datasets.utils import Dataset, EncodedImage, HttpResource, OnlineResource
from torchv... |
from array import*
arr=array('i',[])
n=int(input("enter the length"))
for i in range(5):
x= int(input("enter the next value"))
arr.append(x)
print(arr)
print(arr.index(x))
|
"""CLI functions for the db module."""
from flask import Flask, Blueprint, current_app
from flask.cli import with_appcontext
import click
from ..util.logging import get_logger
from .db import DB
# make sure all models are imported for CLI to work properly
from . import models # noqa
DB_CLI_BLP = Blueprint("db_cl... |
'''
最长回文子序列
dp数组的运用:
1) 涉及两个字符串/数组时(比如最长公共子序列),dp 数组的含义如下:
在子数组 arr1[0..i] 和子数组 arr2[0..j] 中,我们要求的子序列(最长公共子序列)长度为 dp[i][j]
2) 只涉及一个字符串/数组时(比如本文要讲的最长回文子序列),dp 数组的含义如下:
在子数组 array[i..j] 中,我们要求的子序列(最长回文子序列)的长度为 dp[i][j]
'''
from collections import defaultdict
import numpy as np
def longestPalindromeSubseq(s):
nu... |
import ConfigParser
from datetime import datetime
import time
import os
from flask import json
import requests
from weasyprint import HTML
file_path = os.path.dirname(os.path.realpath(__file__)) + "/"
REPORT_DURATION = 1.8e+6 # 30 minutes
config = ConfigParser.ConfigParser()
config.read(os.path.dirname(os.path.real... |
f1 = open('text.txt','r')
f2 = open('d:/myimages/mypicture1.jpg','rb')
f1.close()
f2.close()
|
import numpy as np
import random
def sorted_split(x, y, n_shards):
sorted_index = np.argsort(y)
x = x[sorted_index]
y = y[sorted_index]
shard_size = len(x) // n_shards
init_indice = np.arange(0, len(x), shard_size)
print(f"the number of shard : {len(init_indice)}")
x = np.array([x[s:s+shard... |
from taiga.requestmaker import RequestMaker
from taiga.models import Role, Roles
import unittest
from mock import patch
class TestRoles(unittest.TestCase):
@patch('taiga.models.base.ListResource._new_resource')
def test_create_role(self, mock_new_resource):
rm = RequestMaker('/api/v1', 'fakehost', 'f... |
from spack import *
from spack.util.environment import is_system_path
import os,re
class Stitched(CMakePackage):
homepage = "https://github.com/cms-sw/stitched.git"
url = "https://github.com/cms-sw/stitched.git"
version('master', git='https://github.com/cms-sw/Stitched.git',
branch="master")
... |
my_first_name = input("What is your name? ")
neigh_first_name = input("What is your neighbors name? ")
months_coding = input("How many months have you been coding? ")
neigh_months_coding = input("How many months has your neighbor been coding? ")
total_months_coded = int(months_coding) + int(neigh_months_coding)... |
#! /usr/bin/env python
"""
A node in the NLNOG ring.
"""
# ABOUT
# =====
# This file is part of:
#
# ringtools - A generic module for running commands on nodes of the NLNOG
# ring. More information about the ring: U{https://ring.nlnog.net}
#
# source code: U{https://github.com/NLNOG/py-ring}
#
# AUTHOR
# ======
# ... |
EXCHANGE_RATE_POUND_TO_DOLLARS = 1.31
pounds = int(input())
pounds_to_dollars = pounds * EXCHANGE_RATE_POUND_TO_DOLLARS
print("{:.3f}".format(pounds_to_dollars))
|
# Date: 09/09/2020
# Author: rohith mulumudy
# Description: stores san domain data.
import json
class San:
def __init__(self, in_file="certs.json", san_file="sans.txt"):
self.in_file = in_file
self.san_file = san_file
def get_san_lst(self, san):
lst = []
temp = san.split(';')
for i in range(len(temp))... |
from enum import Enum, unique
import random
from statemachine import Machine
from . import messages as m
@unique
class Card(Enum):
"""Bonus Card."""
INFANTRY = 1
CAVALRY = 2
ARTILLERY = 3
class Bonus(Enum):
"""Trade in three cards for bonus troops."""
INFANTRY = ([Card.INFANTRY] * 3, 4)
... |
import pyttsx3
import components.greet as greet
import components.commands as commands
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
if __name__ == "__main__":
greeting = greet.gre... |
s = 'bobobobstqfbobbdobboobobobobbmb'
count = 0
index = int(0)
for char in s:
#print index
if char in ['b']:
index += 1
#print str(index) + ' 1'
for char in s[index]:
if char in ['o']:
index += 1
#print str(index) + ' 2'
... |
def doc(func):
def wrap(request):
print(help(func))
return func(request)
return wrap
@doc
def hello(request):
"""
测试一下
:param request:
:return abc: 321
"""
return '123'
if __name__ == '__main__':
hello('ddd') |
#!/usr/bin/env python
# coding=utf-8
from pymongo import MongoClient
from app import HOST, PORT, DATABASE, USERNAME, PASSWORD
def update_user(user):
client = MongoClient(host=HOST, port=int(PORT))
db = client[DATABASE]
if USERNAME is not None:
db.authenticate(USERNAME, PASSWORD, DATABASE, mechani... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-02-09 18:28
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('qa', '0003_answerrating_questionrating'),
]
operatio... |
t = int(input())
arr = list(map(int,input().split()))
for i in range(t//2):
sum = arr[i]+arr[-i-1]
print(sum//10,sum%10)
|
def discount(price):
return 0.95*price
|
#!/usr/bin/env python
# coding: utf-8
"""
Created on Tue Jun 10 15:56:48 2019
Modified Tue Jun 11 2019
@author: jnsofini
Program to convert the bin files from out phytopet system to castor data format cdf.
The bin file contains a sequence of data in the form [detector coincidence {ABCD}]
: [X_position det1 {ABCD... |
import network
import time
def connect_wifi(essid :str, password : str) -> bool:
connected = False
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('connecting to network...')
sta_if.active(True)
sta_if.connect(essid, password)
for i in reversed(rang... |
dog_age = int(input("How old is your dog? "))
if dog_age > 2:
dog_years = 2 * 10.5
dog_years = dog_years + ((dog_age - 2) * 4)
print("Your dog is", int(dog_years), "in dog years.")
else:
dog_years = dog_age * 10.5
print("Your dog is", int(dog_years), "in dog years.")
|
# Generated by Django 2.2.4 on 2019-09-06 14:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('webapp', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Power',
fields=[
('id', mod... |
#!/usr/bin/env python3
import os.path
import tensorflow as tf
import helper
import warnings
from distutils.version import LooseVersion
import project_tests as tests
KEEP_PROB = 0.7
LEARNING_RATE = 0.0001
correct_label = tf.placeholder(tf.float32)
learning_rate = tf.placeholder(tf.float32)
keep_prob = tf.placeholder(... |
"""dnstools library."""
import ipaddress
from django.utils.translation import gettext as _
from modoboa.admin import lib as admin_lib
from . import constants
def _get_record_type_value(records, rr_type):
if records is None:
return None
for record in records:
# Multiple strings are separate... |
from random import randint
from random import seed
def roll_dice():
""" roll_dice
Generate random string from '一' to '六'
Arguements: None
Returns: a string
"""
chinese_dice_book = {
1:'\
\n\
\n\
\n\
一一一一一一一一\n\
\n\
\n',
2:'\... |
#!/usr/bin/env python2
# -*- coding: UTF-8 -*-
# File: config_example.py
# Date: Fri Feb 21 12:21:57 2014 +0800
# Author: Yuxin Wu <ppwwyyxxc@gmail.com>
from os import path
config = {'onpassword': '/haha',
'offpassword': '/hehe',
'temp_exe_path': path.join(path.dirname(path.abspath(__file__)), 'te... |
from django.test import TestCase
from organisations.tests.factories import (
DivisionGeographyFactory,
OrganisationDivisionFactory,
OrganisationDivisionSetFactory,
OrganisationFactory,
)
class TestElectionIDs(TestCase):
def test_organisation_factory(self):
o = OrganisationFactory()
... |
import numpy
entry = list(map(int,input().split()))
ans = numpy.eye(entry[0],entry[1],k=0)
ans = numpy.array(ans)
print(ans) |
import unittest
import homoglyphs2ascii
class TestHomoglyphs(unittest.TestCase):
cyrillic = 'МАРК8'
latin = 'MAPK8'
def test_latin_and_cyrillic_are_homoglyphs(self):
self.assertNotEqual(self.cyrillic, self.latin)
def test_to_ascii_makes_equal(self):
self.assertEqual(homoglyphs2ascii... |
import copy
import typing
import random
import numpy as np
from pylo import Image
from pylo import CameraInterface
class DummyCamera(CameraInterface):
"""This class represents a dummy camera that records images with random
data.
Attributes
----------
tags : dict
Any values that should be... |
import argparse
def load_arg_parser():
parser = argparse.ArgumentParser()
parser = add_base_args(parser)
parser = add_gnn_args(parser)
args = parser.parse_args()
return args
def add_base_args(parser):
parser.add_argument('--gnn', type=str, default='GCN', choices=['GCN', 'GAT'])
parser.add... |
#CATEGORY DROPTOWN MENU SHORTCUT - for views.py
# def get_context_data(self, *args, **kwargs):
# cat_menu = Categories.objects.all()
# context = super(HomeView, self).get_context_data(*args, **kwargs)
# context['cat_menu'] = cat_menu
# return context |
class Solution:
def minBitFlips(self, start: int, goal: int) -> int:
res = 0
for i in range(31):
if (goal >> i) & 1 != (start >> i) & 1:
res += 1
return res
|
"""
Unit tests. Run with `pytest`.
"""
from lib import *
import pytest, os
def test_settings_paths():
"""
Test whether each of the settings paths resolve to locations that exist.
"""
settings = loadSettings()
for k,v in settings.iteritems():
path, _ = os.path.split(v)
print "Testing... |
# -*- coding: utf-8 -*-
import scrapy
from selenium import webdriver
from scrapy.http import request
from urllib import parse
from spider.cctv.cctv.items import CctvWorldItem
from spider.views import get_md5,clean_tag
import datetime
class NewsWorldSpider(scrapy.Spider):
name = 'news_world'
allowed_domains = [... |
import aiohttp
import asyncio
import pydantic
from typing import Dict, List
class ProxyServer(pydantic.BaseModel):
country: Dict[str, str]
ip: str
anonymity: str
uptime: float
port: int
async def request(url):
async with aiohttp.ClientSession() as session:
async with session.get(url)... |
import unittest
import sys
import os
from abc import ABC, abstractmethod
from drawers.ASCIIDrawer import ASCIIDrawer
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
tc = unittest.TestCase('__init__')
class AbstractBaseGeneratorTest(ABC):
@abstractmethod
def setUp(self):
... |
import lasagne
import numpy as np
from braindecode.analysis.kaggle import (transform_to_time_activations,
transform_to_cnt_activations)
import logging
from braindecode.veganlasagne.layers import create_pred_fn,\
get_input_time_length, get_n_sample_preds, get_all_paths
from braindecode.datahandling.batch_iterati... |
import time
import logging
import sys
from mythril.mythril import Mythril
from web3 import Web3
from karl.exceptions import RPCError
from karl.sandbox.sandbox import Sandbox
from karl.sandbox.exceptions import SandboxBaseException
logging.basicConfig(level=logging.INFO)
class Karl:
"""
Karl main interface c... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Natoms = 2000
Beta = [0,2,4,6,8,10,14,18,22]#26,30,35,40]
#)path = r"C:\\Users\\Daniel White\\Beta_data500000.csv" # 5 0's
L = len(Beta)
def Data(a):
'''[0] is data, [1] is Beta value'''
df = pd.read_excel('AAA_bE_Beta_data{}.xlsx'.form... |
#################################################################################################################
#################################################################################################################
## Made by: Brandon Shaver
##############################################################... |
def reverse(a):
str_a = "".join(a)[::-1]
output = []
iter = 0
for x in a:
l = len(x)
output.append(str_a[iter:iter+l])
iter+=l
return output
'''
Task
Given an array of strings, reverse them and their order in such way that
their length stays the same as the length of the... |
n = int(input('Masukkan tinggi : '))
print(' ')
for i in range (n, 0, -1):
for j in range (0, n-i):
print(" ", end ="")
for j in range (0,i):
print ("* ", end="")
print('')
for i in range (0,n):
for j in range (0,n-i-1):
print (" ", end="")
for j in range (0,i+1)... |
import pandas as pd
import dgl
from time import time
import torch
from sklearn.decomposition import PCA
import numpy as np
from torchlight import set_seed
def load_tissue(params=None):
random_seed = params.random_seed
dense_dim = params.dense_dim
set_seed(random_seed)
# 400 0.7895
# 200 0.5117
... |
# Endi Pythonda arifmetik amallar ya'ni arifmetik operations larni ko'rib chiqamiz
# ' ** ' bu degani soni kvadratga oshirish yoki kubga ....
s=3**2
print(s)
a=544
b=3
c=a//b # bu degani bo'linga sonni butun qismini ol degani bu bo'lgandan keyin sonni yaxlitlash emas
print(c)
d=a%b # bu sonni qoldiqli bo'lib qoldigíni ... |
#!/usr/bin/python3
from ftplib import FTP
'''
ftp=FTP("linux.linuxidc.com")
ftp.login(user='www.linuxidc.com',passwd='www.linuxidc.com')
ftp.cwd('/2017年资料/1月/2日/在Ubuntu 14.04上Sublime Text无法输入中文的解决方法/')
def grabfile():
filename ="sublime-imfix-master.zip"
localfile=open(filename,'wb')
ftp.retrbinary('RETR '+filename... |
# Author: ambiguoustexture
# Date: 2020-03-11
import pickle
from scipy import io
from sklearn.cluster import KMeans
file_t_index_dict = './stuffs_96/t_index_dict_countries'
file_matrix = './stuffs_96/matrix_countries'
with open(file_t_index_dict, 'rb') as t_index_dict:
t_index_dict = pickle.load(t_index_di... |
#!/usr/bin/env python
# http://click.pocoo.org/6/commands/#group-invocation-without-command
import click
@click.group(invoke_without_command=False)
@click.pass_context
def cli(ctx):
if ctx.invoked_subcommand is None:
click.echo('I was invoked without subcommand')
else:
click.echo('I am about t... |
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import functools
import inspect
import re
from abc import ABCMeta
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Iterable, Sequence, TypeVar... |
import random
# 1
for i in range(1,51):
if(i%5 == 0):
print(i)
else :
print(i, end='\t')
# 2
st = "Python basic program language"
st2 = ""
for i in range(0,len(st)):
if st[i] == " ":
continue
else:
st2 += st[i]
print(st2)
# 3
st = ""
for i in range(0,10):
st += chr... |
# This is a hacky way of re-plotting graphs...
from plot import Plot
from bandit_algorithms import IncrementalUniformAlgorithm
from bandit_algorithms import UCBAlgorithm
from bandit_algorithms import EpsilonGreedyAlgorithm
from bandit import SBRDBandit
# load old plot
arm_params = [(1,1)] # dummy params
b = SBRDBandi... |
from __future__ import print_function
import DecisionTree
import csv
import time
main_folder = "/Users/mengqizhou/Desktop/datamining"
folder1 = "/Users/mengqizhou/Desktop/datamining/datasplit_by_3_fold"
folder2 = "/Users/mengqizhou/Desktop/datamining/datasplit_by_5fold"
address = []
address.append(folder1)
address.a... |
from math import *
import hdr_g
import cv2
images = []
for i in range(6):
image_r = "./data/0"+str(i)+".png"
#image_r = "./example/sample2-0"+str(i+1)+".jpg"
image = cv2.imread(image_r,0)
images.append(image)
log_exposure_times = [int(i) for i in [log(1/1000),log(1/500),log(1/250),log(1/125),log(1/64),l... |
import os
import sys
# this is for python 27, in py 3 this changed to tkinter i believe
import Tkinter as tkm
import ttk as ttkm
import tkFileDialog
import os
import threading
import time
from librf import arkivemanager
#--------------------------------------------------------------------------------------------... |
import math
def inicializaMatrizQuadrada(tamanho, matriz):
for i in range(tamanho):
matriz.append([])
for j in range(tamanho):
matriz[i].append(math.inf)
def printMatriz(matriz,tamanho):
for i in range(tamanho):
print(matriz[i])
def custoTotal(matriz,solucao):
custo = ... |
# coding=utf-8
import sys
from ualfred import Workflow3,notify
log = None
def main(wf):
import json
# Get args from Workflow, already in normalized Unicode
args = wf.args
result = json.loads(str(args[0]))
wf.store_data('cy-city', result)
# Add an item to Alfred feedback
log.debug(result[3])
print(result)
... |
from PIL import Image
import numpy
import scipy.signal
import matplotlib.pyplot as plt
def gaussian(dimension=5, sigma=1):
"""
Computes Gaussian kernel
Parameters
----------
dimension : int
The dimension of the computed Gaussian kernel
sigma : int
The standard deviation of th... |
# Copyright 2021 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import tweepy
import csv
consumer_key = ""
consumer_secret = ""
access_key = ""
access_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth,wait_on_rat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from time import sleep
__mtime__ = '2019/5/11'
from page.login_page import LoginPge
from selenium import webdriver
driver = webdriver.Firefox()
a = LoginPge(driver)
a.login()
# 直接打开编辑页面
driver.get("http://127.0.0.1:82/zentao/bug-create-1-0-moduleID=0.html")
# 如果加载慢的时候会出... |
#Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the #array. The array can contain duplicates and negative numbers as well. For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, ... |
import pymysql as db
import numpy as np
import os.path as op
import time
from sklearn.externals import joblib
from numba import jit
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB, MultinomialNB, BernoulliNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.line... |
print("Welcome to the coffee shop. Check out beverages we offer today: ")
menu = {
'espresso':{'price': 3, 'mililiters': 60, 'code':1},
'cappuccino':{'price': 8,'mililiters': 180, 'code':2},
'latte_machiato':{'price': 15, 'mililiters': 200,'code':3},
'tea':{'price': 5, '... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
from .coffee_started import CoffeeStarted
__all__ = [
'CoffeeStarted'
]
|
f = open('exercise\marks.txt',encoding='utf-8')
lines = f.readlines()
f.close()
#个人成绩集合
score_and_name = {}
score_collect = []
item = lines[0].split()
item.append("总分")
item.append("平均分")
#print(item) # 标签列
for line in lines[1:]:
personal_record = line.split()
element = personal_record[1:]
sum = 0
for ... |
# coding=utf-8
"""
题目:
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分
"""
def is_even(number):
if number & 1 == 0:
return True
return False
def record_odd_even(nums, func):
# 如果数组为空
if not nums:
return nums
# 如果数组只有一个数字
if len(nums) == 1:
return nums
be... |
import requests
from bs4 import BeautifulSoup
url = 'https://www.thehindu.com/tag/1142-1138-1073/'
resp = requests.get(url).content
soup = BeautifulSoup(resp, 'html.parser')
e_news = soup.find('span', class_='fts-menu')
print(e_news.text)
link = []
storys = []
story_card = soup.find_all('div', clas... |
import urllib
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import os
import html.parser
def execute_times(times, driver):
for i in range(times):
# 滑动到浏览器底部
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(2) # 等待页面加载
t... |
from __future__ import unicode_literals
import re
from pyaib.plugins import keyword, observe, plugin_class
@plugin_class('karma')
class Karma(object):
def __init__(self, ctx, config):
self._db = ctx.db.get('karma')
self._re = re.compile('^(\w+)(\+{2}|\-{2})$')
@staticmethod
def is_set(val... |
from newsletter.views import SubscribeView
from django.views.generic.base import TemplateView
from django.conf.urls import url
urlpatterns = [
url(r'^$', SubscribeView.as_view(), name='subscribe'),
url(
r'^success/',
TemplateView.as_view(template_name='success.html'),
name='subscribe'
... |
from collections import defaultdict
import pandas as pd
import trueskill as ts
from typing import Iterable, Tuple
DATE_COLUMN = "Date"
def compute_rank(score1: float, score2: float) -> Tuple[float, float]:
# Lower rank is better.
if score1 > score2:
return [0, 1]
if score1 < score2:
re... |
__version__ = "0.1.0"
__author__ = "Sam Ireland"
from .matrix import Matrix
from .functions import create_vertex
|
from xml.etree import ElementTree as ET
def message(**kwargs):
msg = ET.Element("message")
msg.set("xmlns", "jabber:component:accept")
for k, v in kwargs.items():
if k == 'mfrom':
msg.set("from", v)
elif k == 'mto':
msg.set('to', v)
elif k == 'mtype':
... |
import cv2
import os
import imutils
def record(recording):
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
frame = imutils.resize(frame, width=600)
(height, width) = frame.shape[:2]
path = "/Users/yenji/Desktop/Emotion-Detection"
fourcc = cv2.VideoWriter_fourcc("C","J","P","G")
Output = ... |
platform_map = dict(Linux64="Linux")
arch_platform_map = {v: k for k, v in platform_map.items()}
|
#! /Users/jaeseoklee/Documents/Programming/Scraping/scraping/bin/python3
from bs4 import BeautifulSoup
from urllib.request import urlopen
import sys
import re
html = urlopen("https://en.wikipedia.org/wiki/C_(programming_language)")
bsObj = BeautifulSoup(html, "html.parser")
for link in bsObj.find("div", {"id":"bodyCo... |
from django import forms
from .custom_formfields import pdfFileUpload
class FileUploadform(forms.Form):
# file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True,'class': 'browse-ip'}))
file = pdfFileUpload(label="",widget=forms.ClearableFileInput(
attrs={'style':'display: none;'... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 13 12:45:35 2019
@author: Markus.Meister1
"""
def xlsx(fname,sheet, skip=0, header=0):
import zipfile
from xml.etree.ElementTree import iterparse
import re
z = zipfile.ZipFile(fname)
if 'xl/sharedStrings.xml' in z.namelist():
# Ge... |
def no_idea():
n, m = input().split()
array = input().split()
a = set(input().split())
b = set(input().split())
sum = 0
for i in range(int(n)):
if array[i] in a:
sum = sum + 1
elif array[i] in b:
sum = sum - 1
return sum
print(no_idea()) |
'''
Created on Jan 18, 2016
@author: Andrei Padnevici
'''
from builtins import input
name = input('Enter file:')
handle = open(name, 'r')
text = handle.read()
words = text.split()
counts = dict()
for word in words:
counts[word] = counts.get(word, 0) + 1
bigcount = None
bigword = None
for word, count in cou... |
""" Handles all passlib crypto for the project """
from passlib.context import CryptContext
from os import urandom
HASHER = CryptContext(schemes=["argon2"], deprecated="auto")
#hashedPass should be the hasher .hash string output
def verify_password(password : str, hashed_pass : str) -> bool:
return HASHER.verify(... |
from random import shuffle
def rota(rooms):
result = []
for _ in xrange(0, 7, len(rooms)):
shuffle(rooms)
result.extend(rooms)
return result[:7]
|
import itertools
from dataclasses import dataclass
from typing import Union
@dataclass(frozen=True)
class Point:
xpos: int
ypos: int
zpos: int
def __add__(self, rhs: 'Point') -> 'Point':
return Point(self.xpos + rhs.xpos, self.ypos + rhs.ypos, self.zpos + rhs.zpos)
def get_neighbors(self... |
# -*- coding: utf-8 -*-
"""Tests for the API views."""
from django.core.urlresolvers import reverse
from .base import TestCase
class TestViews(TestCase):
def test_home(self):
response = self.client.get('')
self.assertEqual(response.status_code, 200)
def test_view_feature(self):
resp... |
import tensorflow as tf
import argparse
from data import mergeData
from model import multiTaskModel
import logging
import datetime
from sklearn.metrics import classification_report, accuracy_score, confusion_matrix
import os
import time
# configure the logger
logging.basicConfig(level=logging.INFO)
logger ... |
import json
import os
import database
from sqlalchemy import select
from database import Watcher, Price
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.utils import ChromeType
from selenium.webdriver.chrome.options import Options
from selenium.common.except... |
#!/usr/bin/python
"""
Copyright 1999 Illinois Institute of Technology
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, mo... |
from django.urls import path
from playlist.Controllers import Album_controllers, Charts_controllers, Composer_contollers, Genre_controllers, Music_controllers, Radio_contollers,Index_controllers,Charts_controllers,registration_controller
urlpatterns = [
path('', Index_controllers.index, name='index'),
path('c... |
#!/usr/bin/env python3
proto = ["ssh", "http", "https"]
print (proto)
print (proto[1])
proto.extend("dns") ## appends each letter as an element to the list
print(proto)
|
"""GPSTakip URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-base... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.