index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
15,000 | cd2557bde0664237e44b4e93354d177ef548a497 | # coding=utf-8
import pymysql
import logging
from offer.projects.Automation.excel_util import excelutil
from offer.projects.Automation.file_util import fileutil
'''
构建util
util=mysql_util({'host':'127.0.0.1', 'user':'', 'passwd':'', 'db':''})
执行sql,仅查看
util.getData("sql")
util.copy_... |
15,001 | 6246c1ed62d36c131c195f697272b171bba223e0 | #!/usr/bin/python
from fann2 import libfann
connection_rate = 1
learning_rate = 0.07
num_input = 64
num_hidden_1 = 20
num_output = 10
desired_error = 0.0001
max_iterations = 100000
iterations_between_reports = 100
ann = libfann.neural_net()
ann.create_sparse_array(connection_rate, (num_input, num_hidden_1, num_outp... |
15,002 | 044778968e3af8d3cbb7f665a4eac2278ab8ad4c | # -*- coding:utf-8 -*-
import scipy.misc
import numpy as np
import os
from glob import glob
import cv2
import tensorflow as tf
import tensorflow.contrib.slim as slim
#from keras.datasets import cifar10, mnist
from tensorflow.contrib.framework import arg_scope, add_arg_scope
from tensorflow.contrib.layers import batch_n... |
15,003 | d50d4107406ef8b71c276c0a209b92a8e32278ee | import random
# 20 numbers between 0 and 49 inclusive
ints = [random.randrange(50) for i in range(20)]
print ints
squares = map(lambda x: x**2, ints)
print squares |
15,004 | e4ee4c29400e94a654a85ac57ad419eba9856e96 | import asyncio
import discord
from discord.ext import commands
import base64
import binascii
import re
from Cogs import Nullify
def setup(bot):
# Add the bot and deps
settings = bot.get_cog("Settings")
bot.add_cog(Encode(bot, settings))
class Encode:
# Init with the bot reference
def __init__... |
15,005 | 9707000f1245d9e24a5314f1def23eaa87fea667 | import sys
from PyQt5 import QtWidgets
import windows.menu_window as menu
from ui.login import Ui_Login
class Login(QtWidgets.QMainWindow):
def __init__(self):
super(Login, self).__init__()
self.ui = Ui_Login()
self.ui.setupUi(self)
self.ui.pushButton_menu.setDisabled(Tr... |
15,006 | 16276f6abdfeefc4dadb670a57bb58bc07a78853 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... |
15,007 | 140e730e34d811c1bd3a99c3d66e2dd0b3da65de | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 12 04:09:01 2021
@author: ilkin
"""
def choices():
print("Please choose what you would like to do.")
choice = int(input("For Sigining Up Type 1 and For Signing in Type 2: "))
if choice == 1:
return getdetails()
elif choice == 2:
return check... |
15,008 | 9f3dcc05db2d191ccf67ea3479d8bd52048f6d27 | from termcolor import colored
logFile = None
def open_log(path):
global logFile
logFile = open(path+"/log.txt","a")
def info(*msg):
global logFile
s = "[I] " + " ".join(list(map(str, msg)))
print(colored(s, "green"))
logFile.write(s+"\n")
def debug(*msg):
global logFile
s = "[D] " ... |
15,009 | 4b0b9c54cf213cf4fc1e01402442b492ba5b6f5a | from datetime import datetime
import os
import math
import tensorflow as tf
import dataset
from utils import add_summaries
from utils import align_image
from utils import convert_rgb_to_y
from utils import convert_rgb_to_ycbcr
from utils import convert_y_and_cbcr_to_rgb
from utils import resize_image
from utils impor... |
15,010 | 0285dba2fc481a158794acbd29e6c3d9a8b5bc61 | '''
Created on Sep 6, 2013
https://projecteuler.net/problem=40
An irrational decimal fraction is created by concatenating
the positive integers:
0.12345678910
!!!1!!!
112131415161718192021...
It can be seen that the 12th digit of the fractional part
is 1.
If dn represents the nth digit of the fractional part, fi... |
15,011 | 633c895d8cffbf6673f5e3533ebb049c129849f4 | from django.urls import include, path, re_path
from django.contrib import admin
from rest_framework import routers
from api import views
router = routers.DefaultRouter()
router.register(r'users', views.UserApiViewSet)
router.register(r'agents', views.AgentApiViewSet)
router.register(r'events', views.EventApiViewSet)
... |
15,012 | 4ac877966812cb5454660e3d652f396209578b5a | from . import teachers
|
15,013 | 2013747af44d8fd3a55fac7f3d77c46fd48163c0 | # Generated by Django 3.2 on 2021-07-15 20:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pages', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Contact',
fields=[
('id', mode... |
15,014 | 469f19e83bdccb194d0e9f2b42cd5f5ffa060d9a |
from sql2doc.db import DB
import numpy as np
from sql2doc.pen import MyPen
from configparser import ConfigParser
cf = ConfigParser()
cf.read('conf/conf.ini')
def getTablesNameComment(db_obj,schema_name):
"""
获取库中所有表名和表注释
:@param db_obj:数据库连接对象
:@param shcama_name:数据库名称
:return: ([name1,name2,],... |
15,015 | 7316dfc1f296b285583896250afed048c61e633c | import pytest
from brain_brew.build_tasks.build_task_generic import BuildTaskGeneric
from tests.representation.configuration.test_global_config import global_config
class TestSplitTags:
@pytest.mark.parametrize("str_to_split, expected_result", [
("tags1, tags2", ["tags1", "tags2"]),
("tags1 tags2... |
15,016 | eac688240d68853292a227265bcb968585e56890 | # https://en.wikipedia.org/wiki/Martingale_(betting_system)
import random
import time
def bet_to_win():
count = 1
while random.choice(['win', 'lose']) == 'lose':
count += 1
return count
def main():
max_count = 0
earning = 0
while True:
count = bet_to_win()
if max_cou... |
15,017 | 9a2bec767d6c1bd44391a440f8b209c8a1598f19 | from setuptools import setup, find_packages
setup(
name="gitconfigs",
version="0.1",
packages=find_packages(),
scripts=[],
install_requires=[
'click>=7.0'
],
author="Emmanuel Bavoux",
author_email="emmanuel.bavoux@gmail.com",
description="Some description")
|
15,018 | dc60ba9575b9fa68fef5442bee8656e3b95e94a4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# code by Mr_Java
# email:***@qianxin.com
import re
import time
import os
import json
import threading
import time
import sys
if sys.getdefaultencoding() != 'utf-8':
reload(sys)
sys.setdefaultencoding('utf-8')
path = 'D:\\csv-to-json\\'
all = []
for fpathe, dirs, f... |
15,019 | 17ac627c2850e2bc357efae6c486da9ebe6dde3c | incio = None
final = None
lista = None
def read_line():
try:
# read for Python 2.x
return raw_input()
except NameError:
# read for Python 3.x
return input()
lista = read_line().split(" ")
inicio = int(lista[0])
final = int(lista[1])
if inicio >= 0 and final <= 2:
print("nova")
elif final > in... |
15,020 | 80633fe01d7b9cee9659dfb98c1c1315d4af9743 | # Smash script
import code # code.interact(local=locals())
from sklearn.datasets import load_iris
iris = load_iris()
from sklearn import neighbors
X, y = iris.data, iris.target
code.interact(local=locals())
# classify as whichever one it is closest to
knn = neighbors.KNeighborsClassifier(n_neighbors=1)
knn.fit(X, ... |
15,021 | 2cd4a29bca0b07d87f6b79a99ad68ed85201f900 | def isAlienSorted(words, order):
"""
:type words: List[str]
:type order: str
:rtype: bool
"""
d = {}
for i,c in enumerate(order):
d[c] = i
for i in range(0, len(words)-1):
j = i+1
x = words[i]
... |
15,022 | f7a5f42daf97bb94e4f04c65b27cfab3c7a8997d | # -*- coding:utf-8 -*-
def f1(a,b,c=0,*args,**kw):
print('a=',a,'b=',b,'c=',c,'args=',args,'kw=',kw)
f1(1,2,3,4,5)
|
15,023 | 34d10bfad3e99ffee070b74206aae2f7eca106f8 | # viết hoa chữ cái đầu chuỗi
user_str = 'trần tấn Dũng'
cap = user_str.capitalize() # chỉ có chữ Tran viết hoa, các chữ cái còn lại không viết hoa
print('cap: ',cap)
# viết hoa tất cả các chữ
up = user_str.upper()
print('upper: ', up)
# viết thường tất cả chuỗi
low = user_str.lower()
print('lower: ', low)
# hoán đổ... |
15,024 | 5ba5c9796e3ed80722fd0f219a4beace6e9941b0 | from flask import Flask, request
import requests
import ujson
import os.path
import urllib
app = Flask(__name__)
@app.route('/')
def index():
return "Admin API"
@app.route('/admin')
def admin():
username = request.cookies.get("username")
if not username:
return {"Error": "Specify username in C... |
15,025 | 6981c21421dcb278d77298202f804634ffd42555 | import base58
import calendar
from datetime import datetime
def tb(l):
return b''.join(map(lambda x: x.to_bytes(1, 'big'), l))
base58_encodings = [
# Encoded | Decoded |
# prefix | len | prefix | len | Data type
(b"B", 51, tb([1, 52]), ... |
15,026 | 4cba6e32808fcd54911d75d7a1bd949bb0cce654 | #Change the color of the points to 'red'.
# Change the marker color to red
plt.scatter(cellphone.x, cellphone.y,
color='red')
# Add labels
plt.ylabel('Latitude')
plt.xlabel('Longitude')
# Display the plot
plt.show()
#Change the marker shape to square.
# Change the marker shape to square
plt.scatter(cell... |
15,027 | d9f8eefdf0141b6a2b10180fc41f897257cdc2e5 | import datetime
now = datetime.datetime.now()
ano = int(input('Informe o ano do atleta: '))
idade = now.year - ano
if idade < 9:
print('Idade do atleta: {}\nCategoria Mirim'.format(idade))
elif idade <= 14:
print('Idade do atleta: {}\nCategoria Infantil'.format(idade))
elif idade <= 19:
print('Idade do atle... |
15,028 | 40c52079cffd29b3e5ad5dee782db361623fa023 | import requests
def singleton(cls):
instance = {}
def singleton_inner(*args, **kwargs):
if cls not in instance:
instance[cls] = cls(*args, **kwargs)
return instance[cls]
return singleton_inner
@singleton
class VaultSession:
def __init__(self):
self.session = req... |
15,029 | 5a5b14bfd874a8b9acb831075195cbaaeebed5d8 | import math, collections
import wikipedia
from util import getWordCountWiki, dot
# Given two article, return a word spectrum. Input must be a Counter.
def getPairUniqueness(article1, article2, smooth=1, returntype=collections.Counter):
result = returntype()
if article1==article2:
return result
for ... |
15,030 | f103273dbd355e1fa7c0e5ffa138f951592cb391 | class Solution:
def isPalindrome(self, s: str) -> bool:
lst = [i.lower() for i in s if i.isalnum() == True]
new = lst.copy()
midpoint = int(len(lst)/2)
for i in range(midpoint):
temp = new[i]
new[i] = new[-i-1]
new[-i-1] = temp
... |
15,031 | 193939b7f064b8d304653a91af006930a2cddfe0 | import subprocess
import glob
import pandas as pd
import regex
from sklearn.model_selection import train_test_split
# import TensorFlow as tf
import spacy
import pickle
nlp = spacy.load('ja_ginza')
doc = nlp('銀座でランチをご一緒しましょう。')
for sent in doc.sents:
for token in sent:
print(token.i, token.orth_, token.lem... |
15,032 | 5eb50c15b17d266d85e3ef5d840c8b60a511eef9 | import math
def verif_triangle(a,b,c):
if a + b < c:
print ('No')
elif a + c < b:
print ('No')
elif b + c < a:
print ('No')
else:
print ('Yes')
def input_triangle():
a = input('Informe o tamanho do 1º graveto:\n')
b = input('Informe o tamanho do 2º grav... |
15,033 | 40c359ef13e40cc777e014cb3fd40a7b005fa4b6 | from abc import ABCMeta, abstractmethod
class IModel:
__metaclass__=ABCMeta
def fetchall(self, databaseName):
"""
Gets all Moviereview datastore entries along with the sentiment analysis performed on the comments
"""
pass
def addreview(self, name, year, genre, ... |
15,034 | c59955f286d7d5ccbecfc6d3dcb08ecffeef565c | # Detection and Recognition using ZED Camera
import cv2, sys, os, math
import numpy as np
import pyzed.sl as sl
camera_settings = sl.CAMERA_SETTINGS.CAMERA_SETTINGS_BRIGHTNESS
str_camera_settings = "BRIGHTNESS"
step_camera_settings = 1
# Create a Camera object
zed = sl.Camera()
# Create a InitParameters ... |
15,035 | e8eb8dac73f62516c25b5381258abbc9102d3dda | # -*- coding: utf-8 -*-
n = int(raw_input())
p = set(filter(lambda x: x, map(int, raw_input().split(' '))[1:]))
q = set(filter(lambda x: x, map(int, raw_input().split(' '))[1:]))
if len(p | q) >= n:
print('I become the guy.')
else:
print('Oh, my keyboard!')
|
15,036 | 41e810a2e103a6372aa0c10bddab5de3f97815d5 | # SMART MICROWAVE PYTHON CODE __VERSION__2.0.0 Date-07/07/2020 Owner - Udyogyantra Tecchnologies
# #======================================================================================================================================
import time
import redis
import json
import oven
import led
from threading ... |
15,037 | ff1d06e3090807133476603013a39a4f5cbcd0d7 | # -*- coding: utf-8 -*-
# !/usr/bin/env
# !/Library/Frameworks/Python.framework/Versions/3.8/bin/python3
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
def createlollipopgraph(d):
# Create a dataframe
# random create a dataframe
df = pd.DataFrame({
'g... |
15,038 | fb5d17fdf1810c266320797c563d187127c075f8 | import math
## Solution
# 做法,把這個數字除以第一個 `prime number`, 一直到無法整除,接下來除以第二個 `prime number...` 一次類推,一直到最後剩下的數字也是 `prime number` 爲止, 要考慮到不要一直重複的檢查某個數字是否爲prime, 只要有檢查過,就記下來。這樣之後再使用就可用O(1) 的時間來判斷是否是 `prime`
prime_list = {}
def is_prime(n):
primes = [2, 3, 5, 7]
if n in prime_list:
return True
for p i... |
15,039 | 49d94c18b11172eaa3d44547ef00a48c07acd274 | #Autor: Javier Urrutia
#Email: javier.urrutia.r@ug.uchile.cl
#Excepcion de archivo modificado
class ArchivoModificado(Exception):
pass
# Clase para manejar archivo con movimientos
class Movimientos:
# Crea un objeto Movimientos con el archivo
def __init__(self, archivo):
assert type(archivo) == st... |
15,040 | 91a87294d8d47857be2648b14f46097aecc5037c | import csv
filename = raw_input("Please enter the csv file you'd like to use (i.e. names.csv)>>")
names = []
while filename != "END":
with open(filename, 'rb') as f:
reader = csv.reader(f)
for row in reader:
if row[0] not in names:
names.append(row[0])
filename = raw_... |
15,041 | 60445717b81d3974c750ab4df5100785ab06d1f6 | version https://git-lfs.github.com/spec/v1
oid sha256:55a046e8eea9526243fe920528bbf26ddc331203ef81d022026b0b156a5433df
size 40004
|
15,042 | 9192924e84cf553079634d4c651bb29d1d76f60e | """
CP1404/CP5632 Practical - Suggested Solution
A program that allows user to look up hexadecimal colour codes like those at http://www.color-hex.com/color-names.html
"""
NAME_TO_CODE = {"ALICEBlUE": "#f0f8ff",
"ANTIQUEWHITE": "#faebd7",
"BEIGE": "#f5f5dc",
"BLACK": "#0... |
15,043 | b7e44e22d89d25460a3e4e7b52f33e8c05af1013 | # Generated by Django 3.2.4 on 2021-06-15 18:48
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('tweets', '0008_auto_2021... |
15,044 | f7222ed495c7432dc89e50448708fcf974766b63 | # Generated by Django 2.0.4 on 2018-07-22 09:04
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('compounds', '0016_auto_20180722_1053'),
]
operations = [
migrations.RenameField(
model_name='userodorantsource',
old_name='c... |
15,045 | 02cb55916ac5d0ef94b8ee1a544658b831f1254b | import json
"""crear json con listas"""
ls=[1,2,3]
ls2=[[1,2],[3,4],[4,5]]
"""escribir archivo json"""
with open("test3.json", "w") as fl:
json.dump(ls2, fl,indent=4)
"""leer un json"""
with open("test3.json", "r") as fl:
ls=json.load(fl) ##convierte el json a un diccionario
print(ls)
print(type(ls))
for... |
15,046 | 598525118fdfe5db05660e29f3817d4d3773863e | import facebook
import pprint
graph = facebook.GraphAPI('AAACEdEose0cBAJoNl0ruByNwBIAHxUNCZB01eKCkAb6jco8WSQJxfkyXWMYGTkDYrg4yIKK75VPqlEXeU7Ywbmk15Fdce1t3oRjSkAiba9o29MxRe')
friends = [item['uid2'] for item in graph.fql('SELECT uid2 FROM friend WHERE uid1 = me()')['data']]
for friend in friends:
try:
print... |
15,047 | 3b2cee38802147e940a8ac9cb990434ad7e82d57 | import numpy as np
class periodicmap_spliter:
def __init__(self):
pass
@staticmethod
def get_slices_chk_N(N, LD_res, HD_res, buffers, inverse=False):
"""
This lengthy, irritating piece of code returns the slice idcs for subcube (i,j)
in a decomposition of an original map ... |
15,048 | cf38d7116e187b2dffd3801e7b122ca575f569da | # Setup file for package urlencode
from setuptools import setup
setup(name="urlencode",
version="0.0.1",
install_requires=["quark==0.0.1"],
py_modules=['urlencode'],
packages=['urlencode', 'urlencode_md'])
|
15,049 | f6f625c22005e5e4c56d7ed3e464985308a9d074 | from django.db import models
class Todo(models.Model):
text = models.CharField(max_length=255, null=None)
is_done = models.BooleanField(default=False, null=None)
created_at = models.DateTimeField(auto_now_add=True)
@classmethod
def create(cls, **params):
return cls.objects.create(**params... |
15,050 | bab1597162db15947ee6b3b3fe18da75476a7665 | from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("http://www.practiceselenium.com/")
elem = driver.find_... |
15,051 | e053c75ece06f3405196612cbff62fd340f11416 | #!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Top Composer: Top storage client
Stores the distributions computed by the Top Composer and assigns them an UUID
:author: Thomas Calmant
:license: Apache Software License 2.0
:version: 3.0.0
..
Copyright 2014 isandlaTech
Licensed under the Apache Lic... |
15,052 | c764cb5ef114bd5b3e3a4a76689c119fea30bedd | # Vishok Srikanth
# early version testing how to download NSF search results
import os
import bs4
import sqlite3
# How to Set Up Linux Prerequisites:
# install selenium, pyvirtualdisplay
# sudo pip3 install selenium pyvirtualdisplay
# install xvfb and chromium
# sudo apt-get updtae
# s... |
15,053 | 3f7b7bfcd683cb7007c82d56117c21bbb2b44578 | from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Category, Item, User
engine = create_engine('sqlite:///catalog.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
def getCategories():
"""
Loads category n... |
15,054 | ae188a599f9d27fc15b6f7f86c18e2e640a068ef | #!/usr/bin/python
#coding=utf-8
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
import sys, re
from simplified_scrapy.core.utils import printInfo
from simplified_scrapy.core.dictex import Dict
class XmlDictConfig(Dict):
def __init__(self, parent_element):
... |
15,055 | eee5aef969da745d00423d0c002e359bdcdfc182 | """
Routes Configuration File
"""
from system.core.router import routes
#=============
#Default Route
#=============
routes['default_controller'] = 'Pages'
#=============
#Access Routes
#=============
routes['GET']['/login'] = 'Pages#login'
routes['GET']['/logout'] = 'Auths#reset'
routes['POST']['/processreg'] = ... |
15,056 | ff7715d93b61518a74454d89bdcb288deb89f8ff | # -*- coding: utf-8 -*-
# ==============================================================================
# MIT License
#
# Copyright (c) 2019 Albert Moky
#
# 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 ... |
15,057 | d38e64f5a85de753accb854ebdc3e32bb9c41bc9 | #############################################
# #
# Code for various different classification #
# algorithms to be used in conjunction #
# with the wavelength selection algorithms. #
# #
############################################... |
15,058 | 0911dcd6ceeaaa3ea94a626d40cbd98b46bed210 | from graphene_sqlalchemy import SQLAlchemyObjectType
from models import ModelTeacher, ModelStudent
import graphene
class TeacherAttribute:
# id = graphene.ID(description="row ID")
name = graphene.String(description="Name of the Teacher")
password = graphene.String(description="Password for Login")
class... |
15,059 | 238ae47cb3201b1be7a77c1825924af0c7bb4c38 | from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.tree import DecisionTree
from pyspark.mllib.linalg import Vectors
from pyspark import SparkContext
sc = SparkContext('local')
denseVec1 = LabeledPoint(1.0, Vectors.dense([3.0,5.0,1.0]))
denseVec2 = LabeledPoint(0.0, Vectors.dense([2.0, 0.0, 1.0]))
ve... |
15,060 | 12cbf77718427166a1252b5264f40f935557be97 | from django.core.exceptions import ImproperlyConfigured
settings = {
'ACTIVATION_URL': 'activate/{uid}/{token}',
'SEND_ACTIVATION_EMAIL': True,
'SEND_CONFIRMATION_EMAIL': True,
'SET_PASSWORD_RETYPE': False,
'SET_USERNAME_RETYPE': False,
'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{ui... |
15,061 | 2784588463e4fcfe4da10617f2c7c45a37ebb27b | from Person.Person import Person
def main():
bob = Person('bob')
bob.eat()
dob = Student('dob','ubb')
dob.eat()
dob.sleep()
main() |
15,062 | 1ba5e521d88d6464490a596a24713f1c692a798c | # -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
#! /usr/bin/env python
#
# Example script that shows how to perform the registration
from __future__ import print_function, absolute_import
import elastix
import matplotlib.pyplot as plt
import numpy as np
import imageio
import os
import SimpleITK... |
15,063 | 7003d016330aa142444c972371336d485304c602 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 14 08:27:28 2020
@author: Ken
"""
data_in = [1989, 31, 0, 0, 0, 0, 0, 0, 0, 2021, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,... |
15,064 | 624974edf011ef4c36c32d7886add23c2953f9ab | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import math
import sys
n=int(input())
# n,t=list(map(int,input().split()))
# serial=input().split()
# a=list(map(int,input().split()))
for i in range(n):
num=int(input())
a=list(map(int,input().split()))
a_u=list(set(a))
count=[]
for n in a_u:
co... |
15,065 | 1fd79f2b1ccd83ba2bfe82558699b7e33eee034f | import requests
from bs4 import BeautifulSoup
from settings import COOKIE
import pickle
def bs_css_parse_movies(html, j):
res_list = []
soup = BeautifulSoup(html, "lxml")
div_list = soup.select("tbody > tr > th > a")
time_list = soup.select("tbody > tr > td.by > em")
page_list = soup.select("tbody... |
15,066 | 5716d2c60efea6f9ede60c07870844edd25ec134 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
from flask import Flask
from flask import Markup
from flask import g, render_template, url_for, redirect, abort, request
from datetime import date, datetime
app = Flask(__name__)
app.debug = True
page = {
'title': 'Five years later, how does Hur... |
15,067 | 921e9b21773e7ab8ae3dc9698fdf9b4c1fa51931 | from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta
# construct a basic timedelta and print
print(timedelta(days=365, hours=5, minutes=1))
# print today's date
now = datetime.now()
print("Today is: ", str(now))
# print today's date one year from now
print(... |
15,068 | e77ca30c538d3001723dbfebdbed8936561a2601 | from django.shortcuts import render
from django.http import HttpResponse
from .forms import UserRegisterForm
from django.shortcuts import redirect
# Create your views here.
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
def team(request):
return render(request, 'player/... |
15,069 | c8464abd6ed18f88b13c1d6635e732ff477d3949 | # Generated by Django 3.2.4 on 2021-06-30 11:38
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('apply', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='project',
na... |
15,070 | 7dfdec41fc858f88c14c4b7c9a29f8f4e9cff4f5 | class Solution:
def dailyTemperatures(self, temperatures):
n = len(temperatures)
stack = []
res = [0] * n
for i in range(n):
while stack and temperatures[i] > temperatures[stack[-1]]:
idx = stack.pop()
res[idx] = i - idx
stack.... |
15,071 | 6b82f87651515457f8f2d0edf702fe34772cccc7 | import RPi.GPIO as GPIO
import time
import random
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(17,GPIO.OUT)
GPIO.setup(27,GPIO.OUT)
GPIO.setup(22,GPIO.OUT)
GPIO.setup(26, GPIO.OUT)
GPIO.output([17, 27, 22, 26], GPIO.HIGH)
time.sleep(1)
GPIO.output([17, 27, 22, 26], GPIO.LOW)
for i in range(0,20):
r =... |
15,072 | 1c66747cbfc80206c95d30deaac85c7fca63204c | #!/usr/bin/env python
# coding: utf-8
# # House Price
# ## Import Libraries
# In[1]:
import pandas as pd
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model impo... |
15,073 | 33efa1d5dafcb0e7064a019265130fb92ebc1bb0 | #!/bin/env python27
from getwiki import GlycoMotifWiki, GlyTouCanMotif
w = GlycoMotifWiki()
|
15,074 | 8ef489d3e84864bbed3be6f88fbe65342afd1637 | #! /usr/bin/env python
# CLI structure
import argparse
import webbrowser
import subprocess
import sys
parser = argparse.ArgumentParser(description='Global CLI for multiple usage', prog='bipbop', usage='%(prog)s [argument]', formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-t','--tool', metavar=... |
15,075 | 50eb3b794a4e908d5a3e0195b452a249cf89f6de | def isPalin(n,rev=0):
if n==0:
return rev
rev =rev*10+(n%10)
rev= reverse(n//10,rev)
return rev
def isPalin(num):
if num==reverse(num):
return 1
else:
return 0
n=101
print(reverse(n))
print(isPalin(n)) |
15,076 | de5f5e9eaea91f764e03242f66385e9b955fe4ef | import praw
import prawcore
import os
def reddit_login():
'''logs in the user using OAuth 2.0 and returns a redditor object for use'''
user_agent = 'PC:redditFavoriteGrab:v0.1 (by /u/Scien)'
r = praw.Reddit('mysettings', user_agent=user_agent)
try:
return r.user.me()
except prawcore.excepti... |
15,077 | 8539ef6278f56c1b1edcb288328ab1f25df4d369 | # message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
# count = {}
# for character in message:
# count.setdefault(character, 0)
# count[character] = count[character] + 1
# print(count)
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
'mid-L': ' '... |
15,078 | b31c04ca2c5b994c3fe69358df8bb967ac8cc0dd | import discord
from discord.ext import commands
import datetime
import itertools
from utils import get_member, log, error, success, EmbedColor, read_logs, is_admin
class User(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="commands")
async def _commands(self, ctx)... |
15,079 | e5a04820f82c33ae59dc7d07469c5f839d2772e5 | import pyttsx3
import datetime
import speech_recognition as sr
import smtplib
import wikipedia
import webbrowser
import os
engine = pyttsx3.init('sapi5')
newVoiceRate = 135
engine.setProperty('rate',newVoiceRate)
voices= engine.getProperty('voices') #getting details of current voice
print(voices)
engine.s... |
15,080 | 99c8787895003c8b76f0f603d099d4ce008bda17 | zbior = set()
dodatnie = set()
y = 0
for y in dodatnie:
y += 2
if y == 100:
break
x = (input("Podaj liczbę (wpisz <stop> jeżeli chcesz skończyć): "))
while x != "stop":
x = int(x)
zbior.add(x)
if x == "stop":
break
|
15,081 | 19d64dc3d2bc2d7854dcc617d5c5402fbf7856e3 | import os
import subprocess
import sys
"""
This script speeds up the computation of the topology based attack.
Specifically it creates multiple subprocesses and assigns to it a subset of the attack data to conceal.
"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--data', narg... |
15,082 | b129f2fc0597d8c158d4316d8450d9dc32661ae7 | import os
import csv
csvpath = os.path.join("Resources", "election_data.csv")
out_path = os.path.join("analysis","analysis.txt")
total_votes = 0
with open(csvpath) as election_file:
election_reader = csv.reader(election_file, delimiter = ",")
header = next(election_reader)
candidates = []
Votes = []
... |
15,083 | 72fbd5ce65daad47224817fae613733d49efd7eb | # encoding: utf-8
'''
Scenariusz testowy:
Rejestracja na stronie https://www.vinted.pl/
Warunki wstepne:
Przeglądarka otwarta na stronie https://www.vinted.pl/
Przypadek testowy:
Błędne imię (obecność znaku '@')
Kroki:
1. Zaakceptuj zgodę cookies.
2. Kliknij "Zarejestruj się".
3. Kliknij "Zarejestruj się" w nowym o... |
15,084 | 61fc2cb006e723f0ece42ec3a0db43cc24361be0 | import math
import matplotlib.pyplot as plt
yita_opt=0.970
fai0=1.00e17
arfa=5.00e3
n0=1.00e16
d=10.0e-4
M=4.5
tao=10e-3
D=5.00e-4
q=1.6e-19
k_B=1.38e-23
T_ref=T_a=300
G=100e-3
A_D=100
l=math.sqrt(D*tao)
print (l)
#D is the electron diffusion parameter,tao is the electron lifetime,fai0 is the optical efficiency of the ... |
15,085 | 2e7be51cd7da903dda9930f7830ab407500cdb30 | #!/usr/bin/env python
import os
import errno
import time
import rospy
from uuv_world_ros_plugins_msgs.srv import SetCurrentVelocity
# Because of transformations
# import tf_conversions
# import tf2_ros
# from sensor_msgs.msg import JointState
from std_msgs.msg import Header
from nav_msgs.msg import Odometry
from s... |
15,086 | dbab306a3d2fb5ced0ab946636628c5c18530db2 | import psycopg2
DB_NAME = "esxbzxjm"
DB_USER = "esxbzxjm"
DB_PASS = "xcokxIYMBjRCnQpVJBTSCSMBGvdCEzh-"
DB_HOST = "ziggy.db.elephantsql.com"
DB_PORT = "5432"
conn = psycopg2.connect(database = DB_NAME, user = DB_USER, password = DB_PASS, host = DB_HOST, port = DB_PORT)
print("Database connected successfully")
cur = c... |
15,087 | ddb0829a3ee5c0b8b0a9d55ed14e6f273cf93df0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-11 04:14
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app', '0015_auto_20170210_1108'),
]
operations = [
migrations.RemoveField(
... |
15,088 | c8d0f9430cfc28968764ddb12cd1ab7c8f89674c | import numpy as np
import cv2
import time
help_message = '''
USAGE: peopledetect.py <video_name> ...
Press any key to continue, ESC to stop.
'''
def inside(r, q):
rx, ry, rw, rh = r
qx, qy, qw, qh = q
return rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh
def draw_detections... |
15,089 | d916a86ed589f4e46a0c01847c13bb7c12ae354d |
import unittest
import mock
from datetime import datetime
class TestNumberEncoding(unittest.TestCase):
def test_encoder(self):
"""Ensure encoder produces expected encoded output."""
from sosbeacon.utils import number_encode
number = 123
encoded = number_encode(number)
s... |
15,090 | ed7ca0119417dd91622a6a17f7582999cd630376 | """
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。
如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
二叉搜索树
如果节点的左子树不空,则左子树上所有结点的值均小于等于它的根结点的值;
如果节点的右子树不空,则右子树上所有结点的值均大于等于它的根结点的值;
任意节点的左、右子树也分别为二叉查找树
"""
# -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
if sequence==None or len(s... |
15,091 | 0d83854b0f2fba83f5698fe212ab45a2cf658a27 | import pytest
from sentinel_common.all_keywords_matcher import AllKeywordsMatcher
@pytest.mark.parametrize(
"keywords , text, expected",
[
(["Paris", "life"], "There is no life in Paris", ["life", "Paris"]),
(["Paris", "life"], "There is no -life- in ,Paris.",
["life", "Paris"]),
... |
15,092 | 103a68ca9986393c6148fec53b28592f7fbe6f7d | text = 'stressed'
print(text[::-1])
|
15,093 | cf28c13ddd9c3e20339c530ee3a70ae305060e62 | from unittest import TestCase
from unittest.mock import patch
import app
class AppTest(TestCase):
def test_print_header(self):
expected_header_text = '-----------\n Mad Libs \n-----------\n'
with patch('builtins.print') as mocked_print:
app.print_header()
mocked_print.asser... |
15,094 | 94c32e59847e0a223a343c15424ba07c6d154dbf |
# coding: utf-8
# In[1]:
import numpy as np
from numpy import linalg as LA
import tensorflow as tf
import matplotlib.pyplot as plt
# fix random seed for reproducibility
np.random.seed()
m = 1 # dimension
k_squared = 0.04
m_inv = 1.0
learning_rate = 1e-5
# epochs = 20000
epochs = 10000
batch_size = 1000000
x_stddev ... |
15,095 | e05911eaf1f6275c7f10327f38359514c50f8e15 | """V2 backend for `asr_recog.py` using py:class:`espnet.nets.beam_search.BeamSearch`."""
import json
import logging
import pickle
import numpy as np
import os
import torch
from collections import OrderedDict
import random
from espnet.asr.asr_utils import add_results_to_json
from espnet.asr.asr_utils import get_model_... |
15,096 | b0bde4ff166ad61681624859b81ebc32d2609bbb | # Generated by Django 2.0.7 on 2018-10-09 00:59
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('course', '0013_auto_20181009_0053'),
]
operations = [
migrations.RemoveField(
model_name='fill',
name='fill_answer',
... |
15,097 | 6c791f333ff2efe0084b5b407ac50e3df55f9262 | #printing condition 3
a=int(input("enter the value of a :"))
#checking the condition
if(a>=80):
print("A grade")
elif(a>70):
print("B grade")
elif(a>=60):
print("C grade")
elif(a>=50):
print("D grade")
elif(a<35):
print("better luck next time") |
15,098 | e585970c4adc62545787b5ce049b683c477f5c2a | from django import template
register = template.Library()
@register.simple_tag(name='GET_string',takes_context=True)
def GET_string(context):
return context['request'].GET.urlencode() |
15,099 | bd154d9d84726e00c63aaf98fa65df20660c3999 | #!/usr/bin/python3
# HISTORY
# 0.2 added correct exiting
# 0.1 initial version
# TODO
#Commands are: HELO, INIT, SET (pin,value), SETALL (values), EXIT
import socket
import time
import sys
import pickle
from _thread import *
BUFSIZ = 1024
class PWM:
def __init__( self, pin ):
self.pin = pin
def s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.