index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
11,400
2d540f18f09bd700504a6873e951c91f9129d064
def dataSegmentation(str): length=len(str) res=list() i=0 while i<length: if str[i]==' ': i+=1 continue elif str[i]>='a' and str[i]<='z': temp=str[i] i+=1 if i<length: while str[i]>='a' and str[i]<='z': ...
11,401
bb9ec5c651023041114877c79d8ce189d3ba4739
tempo = int(input("Tempo: ")) i = (1042000/1500)**(1/tempo) - 1 if (i <= 0.01): print(round(i,5)) print("Real") else: print(round(i,5)) print("Irreal")
11,402
d7ca0f562622d44ca33d08b96289d949c5447f91
import socket import chunkserver import master import client import net import random import log import msg try: import settings # Assumed to be in the same directory. except ImportError: sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. This is required\n" % __file__) sys.e...
11,403
67d063769410fc186f630335bd88aa215ff82a4e
class Device: def __init__(self, d_id=0, d_task_id=0, d_device_type='', d_device_width='', d_device_long='', d_regulation_type='', d_notice=''): self.id = d_id self.task_id = d_task...
11,404
114f0947619ac4bbbc04691fd3766e289d3ae311
from sh import cp, rm, diff, ErrorReturnCode import sh import os SURSA_VERIFICATA = 'conjectura_and.cpp' cp('../' + SURSA_VERIFICATA, '.') os.system('g++ ' + SURSA_VERIFICATA) filename = 'grader_test' for i in range(1, 11): print 'Testul ', i cp(filename + str(i) + '.in', 'conjectura.in') os.system('./a.out') ...
11,405
2dc0606e42fce311a59ee1e6909a2dcaf2b667a4
x = 2 def f(): y = 3 print(x) f() print(x)
11,406
d978abbc0c95b55756f6d64b5ebeaa124b60507d
# -*- coding: utf8 -*- # import Image, ImageDraw, ImageFont import random from cStringIO import StringIO import tornado from Base import BaseHandler class Captcha( BaseHandler ): def create_captcha( self, charNum, fontSize ): alphArr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M...
11,407
cdbe692d6085ae19604db8a65932b8ab93ea9dc8
import numpy as np class Parenthesis(object): def is_valid(self, string): n = len(string) dp = [[False for _ in range(n)] for _ in range(n)] # init for i in range(n): if string[i] == '*': dp[i][i] = True for i in range(n - 1): if strin...
11,408
adbda5b3a5d6649b880ce69c73ae82b64bcec2bb
import sys from operator import itemgetter this = sys.modules[__name__] this.fuel_map = {"gas(euro/MWh)": ["gasfired"], "kerosine(euro/MWh)": ["turbojet"], "wind(%)": ["windturbine"], "co2(euro/ton)": ["gasfired", "turbojet"] } # Due to the multipli...
11,409
e2242209111734d51fa5804bb9c746bbfa58234e
import pymongo class Mongo: def __init__(self): MONGODB_HOST = '127.0.0.1' MONGODB_PORT = '27027' MONGODB_TIMEOUT = 1000 URI_CONNECTION = "mongodb://" + MONGODB_HOST + ":" + MONGODB_PORT + "/" try: self._client = pymongo.MongoClient(URI_CONNECTION) ...
11,410
929d068104901bf257cc7eabd66b9c9dca734fc4
class Config(object): init_scale = 0.04 learning_rate = 0.001 max_grad_norm = 15 num_layers = 3 num_steps = 30 hidden_size = 800 # 隐藏层size last_iteration = 0 # 上次训练的迭代数,从头训练写0,增量写上次的数 iteration = 30 # 这次增加训练的迭代数 save_freq = 1 # 每多少次自动保存 keep_prob = 0.5 batch_size = 128 mo...
11,411
d4777f4746c2aaef7d48ee367e4761ecf328bed5
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, BooleanField, TextAreaField, RadioField,\ SelectField, FloatField, IntegerField from wtforms.validators import DataRequired, Length, Optional, InputRequired, ValidationError, Email, EqualTo from wtforms.fields.html5 i...
11,412
19f2e6424aab75ecfa442bebd67b4708e8129c33
import sys sys.path.insert(0, './') from rlf import BehavioralCloningFromObs from rlf import BasicPolicy from rlf import run_policy from tests.test_run_settings import TestRunSettings from rlf.policies.actor_critic.dist_actor_critic import DistActorCritic from rlf.rl.model import MLPBase class BcoRunSettings(TestRunSe...
11,413
7cd14c01aecb9b0399ad5cc1e05db334abcb93b0
import xml.etree.cElementTree as ET import os class case_info: file_name="" oper_path = "" oper_para = [] def __init__(self, p_file_name, p_oper_path, p_oper_para): self.file_name = p_file_name self.oper_path = p_oper_path self.oper_para = p_oper_name def find_dir(src_pa...
11,414
a553d091917236326dbc2c5a36a95b7f265a82a8
import datetime from functions import * zero_time = datetime.time(hour=0, minute=0, second=0) filename = 'init.xlsx' # filename = 'new-init.xlsx' workbook = op.load_workbook(filename) sheet1 = workbook.active def log_hours(date, time): insert_hours(time[0], time[1], date, sheet1) def show_sheet(): print_sheet(sh...
11,415
624c1c114d37ba5e80a7f218f91c075b4a29b65d
from classes.Helpers import printVerbose def parseGroupsFileToDictOfCounts(groups_file): """Given a .groups file, returns a dictionary mapping each seed to the number of children it represents. :param groups_file: A groups file. :return: A dictionary where each seed name is a key to a count of its childr...
11,416
1c1957a0689086cc4362d806d896561ae1abddf9
import os import torch import pandas as pd from albumentations.pytorch import ToTensorV2 import albumentations as alb from torch.cuda.amp import GradScaler from torch.utils.data import DataLoader from dataloader import ImageDataset from efficient_net import EfficientNetNoisyStudent from train_functions import eval_mo...
11,417
f692a9317e13817b0c0b3a747c7a8f8845f6e595
#program to convert tuple to a string # add items in tuple print('Enter the space seperated value.') dic2 = tuple([int(e) for e in input().strip().split()]) print('Tuple: ', dic2) list1 = list(dic2) value = int(input('Enter the value to add: ').strip()) list1.append(value) print(tuple(list1))
11,418
b81a5f80feb40cf3c3e758f12b1229f82743c210
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def print_list(self): temp = self.head if not temp: print('List is empty') while temp: print(temp.data, en...
11,419
13ffcf3040ca67c623ea322c280fb34c19bfa8dd
#rc.local : screen -dm -t "punch" bash -c "python /home/pi/button_click.py;sleep 10000" import RPi.GPIO as GPIO from time import sleep # this lets us have a time delay (see line 12) import time import os import datetime import httplib GPIO.setmode(GPIO.BCM) # set up BCM GPIO numbering GPIO.setup(25, GPIO...
11,420
310852880c1db27b8335523a7d5841d4706d13a7
''' Created on 2014. 10. 31. @author: biscuit ''' import Orange import networkx as nx def generateTreeLoc(uristr,loc_sq, rcode): if rcode == '404' and uristr != '/favicon.ico': return ['not_found'] if rcode[0] != '2': return [] if uristr.startswith("http") and loc_sq==['/']:...
11,421
ae2031bbfe8e2b7735bfe724b8437e688a95c938
import settings class Camera(object): def __init__(self, renderer): """Constructor.""" self.position = 0, 0 self.lastPosition = 0, 0 self.mode = "follow" self.target = None self.bounds = 0, 0, settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT self.renderer = renderer self.renderer.set_camera_position_an...
11,422
3a73b154b8362236504528731226cd075bd65448
from random import shuffle sentence = 'The world is too big' list_1 = ['Hello', 'my', 'name', 'is', 'Osse'] # print(sentence[0:2:5]) shuffle(list_1) print(list_1) print(ord('e')) print(ord('E')) print('*********************************') password = 'Banana' newPassword = '' #make every character slide 3 Unicode n...
11,423
3da261dca5b77211e983b47b6ec3ef6dd1788c6a
import webbrowser barcode = 123123 url = "https://unexpected-fyp.firebaseapp.com/new-ingredient" + "?id=" + str(barcode) webbrowser.open(url, new=2)
11,424
daa11fe5777a354df05f827198478f28ef35fa68
import copy import subprocess # RDLU DIRECTIONS = [(0, 1), (1, 0), (0, -1), (-1, 0)] def print_tracks(carts, tracks): subprocess.call('clear', shell=True) for i, line in enumerate(tracks): printed_line = '' for j, character in enumerate(line): print_track = True for ...
11,425
65df29097aa7a5f0e4de70b7a811ed898de73f6c
UI_TITLE = "DeviantShow" UI_URL = "URL: " UI_PLAY = "Play" UI_MODE_SEQ = "1 2 3 ..." UI_MODE_REV = "9 8 7 ..." UI_MODE_RND = "4 7 2 ..." UI_TIMER = "⌚" UI_PAUSED = "Slideshow paused" UI_ABOUT = "About" UI_ABOUT_NAME = "DeviantShow v.0.1" UI_ABOUT_AUTHOR = "\nA free open-source tool by:\nEric Pöhlsen" UI_ABOUT_USE = "Sl...
11,426
52e2e683ca2117146b371e82372bd126f598d344
"""Write a program that prompts for two numbers. Add them together and print the result.""" print("Give me two numbers, and I'll add them") print("Enter 'q' to quit") while True: first_number = input("\nFirst Number: ") if first_number == 'q': break second_number = input("Second Number: ") try: answer = in...
11,427
285ee19234d9fa9bc2fcbd742ea8bbed924cc943
import pandas as pd import numpy as np import yfinance_loader as yfl import matplotlib.pyplot as plt import seaborn as sns def get_returns(prices): cleaned = pd.DataFrame(prices).dropna() return cleaned.pct_change(fill_method="ffill").dropna() def get_covar_matrix(returns): return pd.DataFrame(returns)....
11,428
c955e9e1700e024c5416f757e6e70d06bd302c67
from django.conf.urls import patterns, url urlpatterns = patterns('daw.views', url( r'^init_object_approvements/(?P<content_type_id>[$a-zA-Z0-9]+)/(?P<obj_pk>[$a-zA-Z0-9]+)/(?P<state_field>[$a-zA-Z0-9_]+)/(?P<callback_url>[$a-zA-Z0-9%:_.]+)/$', ...
11,429
11a858b60a4d8e2d007c29abee24767251766a0b
import torch.utils.data as data from config.option import args import torch from PIL import Image import numpy as np import matplotlib.pyplot as plt import os import cv2 import utils import utils_align class ZoomDataset(data.Dataset): def __init__(self, args, isTrain, transform=None): self.isTrain = isTra...
11,430
e88067b216f23393ee81be3ec34c34bf0e90837a
#!/usr/bin/python3 import ltr_properties from PyQt5.QtWidgets import QApplication import json import sys from typing import List, Dict, Optional from enum import Enum, auto filename = "data/mainOutput.json" def printLoadedClass(obj): classDesc = type(obj).__name__ + ":" for slot in obj.__slots__: if...
11,431
06408572f715cc243564fe4266165c197a5351ed
def make_brick(small,big,goal): if goal<=small+5*big: if goal%(5) <=small: return True else: return False else: return False def lone_sum(a,b,c): sum=0 if a in (b,c): sum+=0 else: sum+=a if b in (a,c): sum+=0 else: ...
11,432
853065740b916680dea7fee126ca404dea912770
from django.contrib import admin from .models import EmployeeEval, Category, SubCategory, EvaluationCriteria, Evaluation, Comments # Register your models here. class EmployeeEvalView(admin.ModelAdmin): def employee_name(self,obj): return obj.employee.last_name + ', ' + obj.employee.first_name +' (' ...
11,433
ddad0825c3018cce62230115e519fe38f8cd0cb0
default_app_config = 'applications.documentation.apps.DocumentationConfig'
11,434
0c1e588170091322c9f6a0512b4a10f96233d352
for a in range(1,4,2): print(a) else: print("datta") for x in range(2): #hii this datta pass print("its working") def fun(*args): for a in args: print(a) fun("datta","kakkad") def fun4(*kwargs): print(kwargs[0:2]) print(kwargs[1]) fun4("asewe", "faaw") def fun33(s="kkr"): print...
11,435
532db45efdf939e80c07069d912013747bd0e75e
from Node import Node # IDS search algorithm's inner function def depth_limited_search(problem, limit): counter = 0 frontier = [(Node(problem.s_start))] # Stack while frontier: node = frontier.pop() counter += 1 if problem.is_goal(node.state): return node.so...
11,436
9b24063c3001642b42f0dcd9d0d7ac5d05305e66
import numpy as np prediction = # THAT'S YOUR JOB # MAKE SURE THAT YOU HAVE THE RIGHT FORMAT assert prediction.ndim == 1 assert prediction.shape[0] == 2000 # AND SAVE EXACTLY AS SHOWN BELOW np.save('prediction.npy', prediction)
11,437
6628dc248c400c5e21665499677395bec9244388
from django.contrib import admin # Register your models here. # from .models import Customer # from .models import Product # from .models import Order from .models import * # equal to line 5 to 7 admin.site.register(Customer) admin.site.register(Tag) admin.site.register(Product) admin.site.register(Order)
11,438
c0d11507a3616a8feef8b390fee646c56ee4b0e5
import pandas as pd import numpy as np from keras import layers from keras import models import librosa import sys import os import csv import pathlib from sklearn.preprocessing import LabelEncoder, StandardScaler from sklearn.model_selection import train_test_split import keras import warnings warnings.filterwarning...
11,439
07eb83ba2d3680f2470701f7e181fbecb42e949a
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 8 20:37:36 2021 @author: Josey """ [['R' 'B' 'R' 'B' 'R'] ['B' 'R' 'B' 'R' 'B'] ['R' 'B' 'R' 'B' 'R'] ['B' 'R' 'B' 'R' 'B'] ['R' 'B' 'R' 'B' 'R']]
11,440
95c589dea95d20ece298948a7a83da06a07c3b02
import numpy as np import matplotlib.pyplot as plt import keras def evaluate_model(model, split_sets): training_error = model.evaluate(split_sets['X_train'], split_sets['y_train'], verbose=0) print('training error = ' + str(training_error)) testing_error = model.evaluate(split_sets['X_test'], split_sets[...
11,441
38a93c25d601cc9549531354c71a50deddbd6fb0
import time import serial ser= serial.Serial("/dev/ttyACM0", baudrate=9600) try: while True: comando = input("Ingresar comando (on/off): ") comando = comando +"\n" comandoBytes=comando.encode() ser.write(comandoBytes) time.sleep(0.1) read= ser.readline() print(read) except KeyboardInterrupt: pr...
11,442
ce3b6741eb57747c3bf63d0dce60c89b1772a942
from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): """ Custom permission to only allow owners of an object to modify/edit it. Read only is allowed to other users. """ def has_object_permission(self, request, view, obj): # Read permissions are allo...
11,443
aad11e06fce27cdfb29721be3fad4408b852840e
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Michael Pechner <mikey@mikey.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function DOCUMENTATION = r''' --- module: ecs_tag version_added: 1.0.0...
11,444
f176ac000941e0c8c12690a06f6b2801cee33a23
# # SOFTWARE HISTORY # # Date Ticket# Engineer Description # ------------ ---------- ----------- -------------------------- # 08/20/10 njensen Initial Creation. # # __all__ = ['SerializationException'] from . import dstypes, adapters from . impor...
11,445
6c9055797f8147717919e75b673f8134cd4ad8b6
class Solution: def duplicateZeros(self, arr: List[int]) -> None: """ Do not return anything, modify arr in-place instead. """ i = 0 for num in list(arr): if i >= len(arr): break arr[i] = num if not num: i += 1 ...
11,446
b27dae62b516aa24edce37aed85bc001de4f2183
text = list(input("Please enter the text :").lower()) vowels = ["a","e","i","u","o"] result=False if len(text) <= 1: result = False else: for i in range(len(text)-1): if text[i] in vowels and text[i+1] in vowels: result = True break if result: print("positive") else...
11,447
412b59f47030b97f58e666f3d8eb7bfdac001bbc
# Author: kk.Fang(fkfkbill@gmail.com) __all__ = [ "OracleStatsCMDBSQLExecutionCostRank" ] from typing import Generator, Union from mongoengine import StringField, FloatField from models.sqlalchemy import * from .base import * from ..base import * from ...capture import OracleSQLStat @OracleBaseStatistics.need...
11,448
5a983425189fbacd7f171afda865837f8366ca7d
import csv import os from os.path import join import requests import time def fetch_media_for_feed(feed_dict): feed_dir = feed_dict['feed_dir'] media_dir = join(feed_dir, 'media') short_name = feed_dict['short_name'] image_dir = join(media_dir, 'tweet_images') profile_images_dir = join(media_dir,...
11,449
a87503175c808879ce5fc58c6387f6e855dc440a
#!/usr/bin/python import sys prev = "" total = 0 doc_prev = "" for line in sys.stdin: token, docID, count = line.strip().split() count = int(count) if prev == token: if doc_prev == docID: total += count else: print prev, doc_prev, total, " " prev = token ...
11,450
08e3c5ad9f04d3cf610e4c2422e83672eeb35320
#Open the file employees_file = open("employees.txt", "r") #Read values if(employees_file.readable()): for employee in employees_file.readlines(): print(employee) employees_file.close() #Appending to file employees_file = open("employees.txt", "a") employees_file.write("\nLeah - Human Resources") employees...
11,451
a627612570582832ab8c32b0b4af2b3038bbd1c6
from sqlalchemy import create_engine from datetime import datetime from TweetCollector_FullArchiveAPI.Tables import Base, Tweet, Place from sqlalchemy.orm import sessionmaker from contextlib import contextmanager import json """ The TweetLoader class takes care of transforming the fields from the response objects to a...
11,452
655141c4e0dfc8827c457c0f286dc1f6d4d595f9
from pytransform import pyarmor_runtime pyarmor_runtime() __pyarmor__(__name__, __file__, b'\x50\x59\x41\x52\x4d\x4f\x52\x00\x00\x03\x06\x00\x33\x0d\x0d\x0a\x03\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x40\x00\x00\x00\x5e\x15\x00\x00\x00\x00\x00\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x...
11,453
39f492e760c4c82e16a9ebebc18e4432f38d2291
import abc # 抽象观察者类 class Observer(metaclass=abc.ABCMeta): # 更新通知方法 # invoker:通知者 # event:事件 # params:事件参数 @abc.abstractmethod def update(self, invoker, event, params): pass
11,454
86bf7ceb4d664018b498e7c3d3e38b439c30c342
#!/usr/bin/python # vim: set fileencoding=utf-8 # Demonstrační příklady využívající knihovnu Pygame # Příklad číslo 26: použití objektů typu Surface, metoda blit() # a operace pygame.transform.scale(). import pygame, sys, os # Nutno importovat kvůli konstantám QUIT atd. from pygame.locals import ...
11,455
62245bdbee36c8c4292c943b4627c1daa585cb60
import cv2 as cv import numpy as np img = cv.imread('clahe_src.jpg', 0) # 全局直方图均衡 equ = cv.equalizeHist(img) # 自适应直方图均衡 clahe = cv.createCLAHE(clipLimit = 2.0, tileGridSize = (8, 8)) cl1 = clahe.apply(img) # 水平拼接三张图像 result1 = np.hstack((img, equ, cl1)) cv.imwrite('clahe_result.jpg', result1)
11,456
45fd63816fdb037d73ad61b507bab47e61c9fe45
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-10-04 06:21 from __future__ import unicode_literals import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateM...
11,457
368a2592df530520268abd8fff1b55ca842cc1d9
import socket import time # 创建对象 sk = socket.socket() # 绑定IP端口 sk.bind(('127.0.0.1', 8000)) # 监听 sk.listen() def rihan(url): return "欢迎访问 日韩板块{}".format(url) def oumei(url): return "欢迎访问 欧美板块{}".format(url) print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 持续等待链接 while True: conn, addr = s...
11,458
6f5338a99d5e1311f8b1a48679e7a96900aef998
import unittest from backend import utils from backend.messages import ( test_clean_positions, test_all_equals, test_get_segments, ) class UtilsTest(unittest.TestCase): def __init__(self, methodName='runTest'): self.Play = utils super(UtilsTest, self).__init__(methodName=methodName) ...
11,459
7d95b9a59f0158c35bbb99b34dd7307431c85cef
test_input = ''' [1,1,3,1,1] [1,1,5,1,1] [[1],[2,3,4]] [[1],4] [9] [[8,7,6]] [[4,4],4,4] [[4,4],4,4,4] [7,7,7,7] [7,7,7] [] [3] [[[]]] [[]] [1,[2,[3,[4,[5,6,7]]]],8,9] [1,[2,[3,[4,[5,6,0]]]],8,9] ''' def compare_integers(left, right): if left < right: return -1 if left > right: return 1 ...
11,460
1f7d48056abd2e2fd4b987f9973f7e6657d9b3c3
#!/usr/bin/env python3 numbers=0 avg=0 while True: inp=input("please give me a number or the world 'done': ") try: x=float(inp) avg+=x numbers+=1 except ValueError: if inp=="done": break else: print("incorrect value entered. please enter a number or 'done'") try: avg=avg/numbers except ZeroD...
11,461
5e654a76c1e739506d4357c13dd45c43ceaff245
from typing import List ''' 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。 示例: 输入: n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] ''' class Solution: def combine(self, n: int, k: int) -> List[List[int]]: self.result = [] self.tmp = [] self.dfs(1, n, k) pr...
11,462
629e33b9b821ca32db722f92aa1f11d2ef333eff
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: length = 1 node = head while nod...
11,463
2e524ec08d489a932cebdcb044eaa28e6058854b
# -*- coding: utf-8 -*- __author__ = 'admin' import urllib2 from lagou_db import LagouDb import bs4 import requests import re import threading import time import random # url3 = 'http://www.freeproxylists.net/zh/cn.html' def get_cn_proxy(): url = 'http://cn-proxy.com/' proxy = urllib2.ProxyHandler({'http': '...
11,464
046383cedca3283133a4a38dd5dbd677ec65af20
import numpy as np import pandas as pd import matplotlib.pyplot as plt def calci(X1,X2,W,power): #function to find the output for an input ct=0 val=0 for p in range(power+1): tp=p while tp>=0: val=val+W[ct]*(X1**tp)*(X2**(p-tp)) tp=tp-1 ct=ct+1 return val if __name__ == "__main__": #The b...
11,465
682bcbddae6e769505840e96b66ebf1351d80327
from datetime import datetime from pathlib import Path from jinja2 import Template from reconcile.utils.mr.base import MergeRequestBase from reconcile.utils.mr.labels import DO_NOT_MERGE PROJ_ROOT = (Path(__file__) / '..' / '..' / '..').resolve() EMAIL_TEMPLATE = PROJ_ROOT / 'templates' / 'email.yml.j2' class Cre...
11,466
2878a69dbfbb810e2385d867600a6b9e1745d459
import socket import cv2 import numpy import thread import time face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') #Database to identify the faces eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') #Database to identify the eyes def recvall(sock, ...
11,467
89b60790ebbbb7e9300fec7659e183854022eb75
#!/usr/bin/env python3 import fileinput import random def is_tidy(n): for i, c in enumerate(str(n)[:-1]): if c > str(n)[i+1]: return False return True def solve(number): digits = [int(c) for c in str(number)] # find first non-tidy digit for first_invalid, d in enumerate(digi...
11,468
0ba6a3fbac7ed4260848d26e7fb2f83056460a63
''' Call two arms equally strong if the heaviest weights they each are able to lift are equal. Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms. Given your and your friend's arms' lifting capabilities find out...
11,469
f6cb8f33b16f29167c3160883c42581c1dab0534
# Generated by Django 2.0.3 on 2018-11-17 18:58 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Size', fields=[ ('id', models.AutoField(aut...
11,470
53d331b0d1ab767e0c697dd06627598f57e3b71d
# This filter deforms the terrain in the selection box by creating a gash in the surface of the world # # abrightmoore@yahoo.com.au # http://brightmoore.net # from math import sqrt, tan, sin, cos, pi, ceil, floor, acos, atan, asin, degrees, radians, log, atan2 from random import * from numpy import * input...
11,471
03ffe600fecee8f6501d636bf659d32b81ef390c
#!/usr/bin/python3 import argparse getHex = __import__('10').getHex getSparseHash = __import__('10').getSparseHash densifyHash = __import__('10').densifyHash def getArguments(): parser = argparse.ArgumentParser(description='Advent of code') parser.add_argument('input', metavar='file', type=argparse....
11,472
431e9169b03c548e5ce886e9505e2ef446306fbc
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/10/9 下午7:13 # @Author : Hou Rong # @Site : # @File : test_mongo_iter.py # @Software: PyCharm import pymongo import time client = pymongo.MongoClient(host='10.10.231.105') collections = client['Test']['test2'] cursor = collections.find({}) if __na...
11,473
1d04e33209cb8aec365e16ba2f6ad5f3fc9fd94f
"""Command-line tool functionality. Parses arguments and determines which tool should be called. """ import sys import argparse from abc import ABC, abstractmethod from typing import Dict import importlib # New tools should be added to this list. TOOL_NAME_LIST = ['remove-background'] class AbstractCLI(ABC): ...
11,474
b86bec43edbf9ddc9befdab3eab5d46c49f77ddc
# -*- coding: utf-8 -*- ''' Physical Constants =============================================== ''' from sqlalchemy import String, Float, Column from exa.relational.base import Base class Constant(Base): ''' Physical constants and their values in SI units. >>> Eh = Constant['Eh'] >>> Eh.value 4.35...
11,475
b3d418500e70bd41767011a6aa051b8c7b070a66
𛀒𮟯👼䂒𔔻𛊗ﴥ🚼𦯙𠡾𣚏狠웃𘂄焭ѫ諛𧙡섮𒂋ꔌ䭿ᇤ蚢媩ﴭ𘅈𫃨㒰𥴔𫨈𢙚畃ꖉ𪖼𦤍ഁ䫬🖇𝖪𠽺𐼽𭊏𮂎𠒢兆𢡇𤘮倪𤭜𐔥𧯽俙𪝥𦺗⚤𬬺𮑕偧㋑퍨嗂𖢞𦍚𪲄𮗗Ꞽ溹쮍綘𣑺숉𣡉蜴𤵷𡛒㱜お⫸焖𘇜㷮𘪸𩞥𮭞뛒憨𦋝ڑﰥ𦅐ﶙ𘥆䌉𡠵𧑸飩𬅢𣢋ኚ𘇇𢯤𩴵퇽𮬹𝌋𩇵䁦𫙰蚊梪嶘𪘦ᄏ𐌅韬𘍚𭺏궰𞡊窅𨢨𠑝𖥓𦃥𣵹🅞𘚲ꎁ𥇃𢛎𐎑𗏀𧳞𔗀𭦀䈚𣲒𤳨𤌘烶騐𭨜ᰙ⧺𫡭𧥪즺𫤈𧶷𐐣𧭠늇𫺋𣊇𖺆礑ࣹ퇆𗻕𮤴릸Ł𝠿㡐𭪒ꅝ㡂𢐗𫸞𧜓𗦅𮁓𢄞𧡮𬵁筑𧅛𠨏番뫳𪖧鍓𬥸𥏋𐙪次𡝍𠻦𠶡䬿𥇇𦨥⌐갾纬𗜴綐ေ㥯𫆩�...
11,476
424763c41ff0d1ed9c163027113fc346baee34a8
n = int(input()) a = list([input() for i in range(n)]) z = 0 ax = 0 for i in range(n): a[i] = int(a[i]) if a[i] > ax: z = i ax = a[i] print(int(sum(a)-a[z]/2))
11,477
d44f0a64d6365b3225c44a1df7fb4e58b18d6444
from django import forms from django.contrib.auth.models import User from courses.models import CourseFile, CourseInformation class CourseFilesForm(forms.ModelForm): class Meta: model = CourseFile fields = ("cfile", "cfile_class", "cfile_year", "cfile_content") exlcude = ("uploader", "cou...
11,478
9671a62ce9ee1fea1c9e6d3126c976866ca41159
class Solution(object): def findPeakElement(self, nums): if len(nums)==0: return if len(nums)==1: return 0 for i in range(len(nums)): if(i==0 and nums[i]>nums[i+1]): return i elif(i==len(nums)-1 and nums[i]>nums[i-1]): ...
11,479
9a0f65f1c0267f3331a8d583455fc86cf6520a13
import vault_acl_tool.actions.ToolAction import vault_acl_tool.actions.CONNECT_ORDER import vault_acl_tool.config.YamlConfig as YamlConfig class Connect(vault_acl_tool.actions.ToolAction): def __init__(self): super(type(self), self).__init__() self._name = "Connect" self._order = ...
11,480
4c5a8dbbef21d9568a3d353ab5aaef8d35ff715f
# 1st step ##### def display_board(board): print(board[7]+'|'+board[8]+'|'+board[9]) print(board[4]+'|'+board[5]+'|'+board[6]) print(board[1]+'|'+board[2]+'|'+board[3]) # 2nd step ##### def player_input(): ''' :return: (Player 1 marker, Player 2 marker) ''' marker = '' while marker !...
11,481
da667a6a2cc80276438a392aacee0676329e89ba
import os.path from wsgiref.simple_server import make_server from User_Profile_app.handlers import home_handler, profile_handler, update_profile, delete from User_Profile_app.utils import DB_FILE, create_db routes = { '/': home_handler, '/profile': profile_handler, '/update_profile': update_profile, ...
11,482
ffd1eec34ac9d3f13c268e1718fce45fe65d1b84
import tensorflow as tf device_name = tf.test.gpu_device_name() if device_name != '/device:GPU:0': print('GPU device not found') else: print('Found GPU at: {}'.format(device_name)) """Solver for L1-norm""" import sys sys.path.append('') import numpy as np import scipy as sp from scipy.sparse.linalg import LinearO...
11,483
04077e0f6613009b880e2a29e0f43849d306c842
from tkinter import * window=Tk()#创建一个窗口 label=Label(window,text="Welcome to Python")#创建一个标签,小构建类 button=Button(window,text="Click me") label.pack()#把标签放进窗口中 button.pack() window.mainloop()
11,484
ac753a894f99ed9ffb0c962086e3beae1456ec14
import numpy as np import cv2 from PIL import Image import pytesseract #from ocrhelper import preprocess #failed attempt def get_cropped(image, area): (x, y, w, h) = area new_img = image[y: y + h, x: x + w] return new_img def split(image,row,column, area): width = area[2] height = area[3] u...
11,485
326c672fcb8ffdf170d9e272803f1d680408acef
## NASA API Demo ## Once you recieve you API credentials, I recommend storing it as a variable in another file. ## In this example, I created another python file called "NASA_API_Credentials.py" and stored ## it in the same folder as NASA_API_Demo.py. Inside that file, I created a variable api_key ## and set it e...
11,486
5437cf1821104ce416de5a9ac28e98d8e24f25f6
#!/usr/bin/env python from ToolBox import parse_options_and_init_log # have to do this first or ROOT masks the -h messages opts, parser = parse_options_and_init_log() from L1Analysis import L1Ana, L1Ntuple from analysis_tools.plotting import HistManager from analysis_tools.selections import MuonSelections, Matcher imp...
11,487
44322b4122488e0041dad3015c98159b0d3e2852
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Creates the mask of where the Monte Carlo simulation should sample the P-bodies """ import numpy as np import cv2 def extract_sample_area(cell_mask, dapi_image, dapi_threshold = 10, shrink_nucleus = 3): ''' Returns a binary mask of where sampling is possible (i...
11,488
8fc43f3b609d8ed50e790ce2603d2e7fb078a9d1
/home/rajendra/anaconda3/lib/python3.6/encodings/cp424.py
11,489
c245c5dc02e34cd15f508dc591e6cfcd303ed9d1
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.main), url(r'^create$', views.create), url(r'^add/(?P<id>\d+)$', views.add), url(r'^song/(?P<id>\d+)$', views.songUser), url(r'^show/(?P<id>\d+)$', views.showUser), ]
11,490
bdb0a9350470c044b9ced9ed40caca2324fd2227
# 2019 KAKAO BLIND RECRUITMENT 매칭 점수 # https://programmers.co.kr/learn/courses/30/lessons/42893 def solution(word, pages): answer = 0 lenWord = len(word) linkWord = "<a href=" lenLink = len(linkWord) domainWord = '<meta property="og:url" content=' lenDomain = len(domainWord) #기본점수, domain,...
11,491
c60d86980b990ad3ff581d680c85c7a3569baa4b
fp = open("input.dat", "r") line = fp.readline() total = 0 length = len(line) for i in range(length): num = int(line[i]) if (num == int(line[int((i+length/2)%length)])): total += num print (total)
11,492
f15d9c9c9db3b7dc094e13104106baf02fff1ead
import os import struct import shutil from tarfile import TarFile from zipfile import ZipFile import requests import time if os.name == "nt": gd_path = "geckodriver.exe" if os.path.isfile(os.path.join("harquery", gd_path)): print("Harquery dependencies are already installed") exit() if 8 ...
11,493
334dadff97f76924a96a1fe7fd87b9db6eb41acc
from Fs import Fs import os import constants class SuperBlock(Fs): def __init__(self, size=constants.SUPER_BLOCK_SIZE, f_blocks_list=None, ifree_list=None): self.size = size self.f_blocks_list = f_blocks_list self.ifree_list = ifree_list def get_inode_number(self): inode_number = self.ifree_list....
11,494
44b42d2755eecac9153ecc5362f85f18fb7795b3
# -*- coding: utf-8 -*- """ Created on Sat Mar 26 20:15:46 2016 @author: rbanderson """ import numpy as np import scipy.optimize as opt import copy class sm: def __init__(self, blendranges, random_seed = None): self.blendranges = blendranges self.random_seed = random_seed def do_blend(self, p...
11,495
b6e3a62d48c3ae7bea32284ee1fa67da136b16ad
# Nombre: Juan Diego Poccori Escalante # Código: 144884 import math # 1. Escribir un algoritmo que calcule el coseno mediante series de Taylor # definir factorial def factorial(numero): if numero < 0: mensaje = "Error: Debe ser un numero mayor o igual a cero" return print(mensaje) i = 1 factorial = 1 w...
11,496
d071ee971362a9a265a1c7969f9cb781ec7c8ee6
# Generated by Django 3.0.2 on 2020-03-11 17:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pokemon_entities', '0018_auto_20200311_0139'), ] operations = [ migrations.AlterField( model_name='pokemon', name='d...
11,497
9cc71abe8128728634221e3d969adcbdd3273b96
import operator from etc.const import GREATER, GREATER_EQUALS, LESS, LESS_EQUALS, EQUALS, NOT_EQUALS ATTRIBUTES = { 'Character': { 'health': 'hp', 'resource': 'resource', 'is in combat': 'is_in_combat', 'has pet': 'has_pet', 'first class resource': 'first_class_resource', ...
11,498
e0f7c227115f955b3f5e63bc042552f94ff1027f
# -*- coding: utf-8 -*- import os import sys from deconstrst.deconstrst import build, submit from deconstrst.config import Configuration __author__ = 'Ash Wilson' __email__ = 'ash.wilson@rackspace.com' __version__ = '0.1.0' def main(): config = Configuration(os.environ) # Lock source and destination to t...
11,499
398e44942f0f2ec3d7a7c7c8ef8c01df4eff8d26
import csv import re import requests from bs4 import BeautifulSoup from get_all_players import read_all_players_from_csv import pandas as pd BASE_URL = 'https://www.basketball-reference.com' COLUMNS = ['Season', 'Age', 'Tm', 'Lg', 'Pos', 'G', 'GS', 'MP', 'FG', 'FGA', 'FG%', '3P', '3PA', '3P%', '2P', '2PA'...