blob_id large_string | repo_name large_string | path large_string | src_encoding large_string | length_bytes int64 | score float64 | int_score int64 | detected_licenses large list | license_type large_string | text string | download_success bool |
|---|---|---|---|---|---|---|---|---|---|---|
e03cb1307d237ba3822034fe95ea3aaf316c6cad | Arx247/Arnas-2332-oop-labs | /Lab 6/problem2.py | UTF-8 | 177 | 3.125 | 3 | [] | no_license | # Arnas Oonsadao, 633040233-2
"""
Lab 6 Input and Output: Problem 2
"""
file_name = input("Enter a file name: ")
with open(f'{file_name}') as f:
print(f.read())
#print(contents) | true |
921a431ab9aae079f80e09b59bfe47eed3bb83e9 | eliben/code-for-blog | /2008/google_api_search.py | UTF-8 | 2,792 | 2.859375 | 3 | [
"LicenseRef-scancode-public-domain",
"Unlicense"
] | permissive | # GoogleApiSearch
#
# A very simple interface to the Google AJAX Search API.
#
# Depends on the following modules:
# - demjson:
# For parsing the JSON results returned by the Google API
#
# Eli Bendersky (http://eli.thegreenplace.net)
# This code is in the public domain
#
import logging
import pprint
import ur... | true |
e0bbdc8107942f05ec5c38bf89dafae83c92a2a2 | lowellw6/hpl-gan | /hpl_gan/mnist/util.py | UTF-8 | 1,703 | 2.65625 | 3 | [] | no_license | import torch
import torch.optim as optim
import torch.nn.functional as F
import os
from tqdm import tqdm
import cv2
def save_reconstructions(name, image_tensors, reconstructions):
reconstructions_shaped = reconstructions.view(-1, 1, 28, 28).to("cpu")
results = create_compare_grid(image_tensors, reconstr... | true |
b01e724c65b6b66f5e7e97d7b80ebf33a9c0ea66 | 42madrid/remote-challs | /chall10/estina.py | UTF-8 | 2,330 | 3.3125 | 3 | [] | no_license | #!/usr/bin/env python3
import sys
ROWS = 6
COLS = 7
def check_line(line, colors, split_line):
if len(split_line[0]) != 1:
exit("Invalid input.")
if not len(colors) or (len(colors) != 2 and colors[0] != split_line[1]):
colors.append(split_line[1])
elif colors[0] != split_line[1] and colors[1] != split_line[1]:... | true |
fb1e444b25b0e861ef7255420bee5ed79408c4b5 | tilakgajjar/MapReduce | /Server Log Data Problems/reducer5.py | UTF-8 | 391 | 3.078125 | 3 | [] | no_license | #!/usr/bin/python
import sys
currentPath = None
requestedCount = 0
for line in sys.stdin:
newPath = line.strip().split()
if len(newPath) != 1:
continue
if currentPath and currentPath != newPath:
print currentPath,"\t", requestedCount
requestedCount = 0
currentPath = newPath
requestedCount += ... | true |
c309f3e6e90647792e7ed3716ae959446928486e | loganhue52/Personal-Portfolio | /Python/Password Manager/Checker.py | UTF-8 | 917 | 3.03125 | 3 | [] | no_license | class Checker:
def __init__(self,password):
self.cL=[False,False,False,False,False]
self.password=password
def check(self):
#mostly pieces from the original strength checker assignment
for i in self.password:
if ord(i) in range(97,123):
self.cL[0] = T... | true |
8b207f92947662dbb04883e9df657f8fce6e0921 | WolfElkan/hst3 | /Utils/data.py | UTF-8 | 4,407 | 2.625 | 3 | [] | no_license | from django.db.models.query import QuerySet
from inspect import getargspec # Update getargspec -> signature in Python3
def allify(obj):
if hasattr(obj,'all'):
return obj.all()
else:
return obj
def collect(thing, lam):
if type(thing) in [list, tuple, QuerySet]:
new = []
nargs = len(getargspec(lam).args)
i... | true |
782e74c57a3d05bbf0660b6d4fce960a3bade3d0 | aniGevorgyan/python | /registration.py | UTF-8 | 1,229 | 3.578125 | 4 | [] | no_license | #!/usr/bin/python
# Registration form
"""
:input username, password, confirm password
:output: success or error on registration process
"""
def registration():
f = open("credentials.txt", "r")
creds = f.read().splitlines()
f.close()
data = {}
for i in creds:
up = i.split(": ")
data[up[0]] = up[1]... | true |
3b45080a774b3d541f8a463e064b850c5841e8e9 | Bystrykha/arithmetic-encoding | /a_coder.py | UTF-8 | 5,096 | 3.046875 | 3 | [] | no_license | import struct
from decimal import Decimal
class interval(object): # для словаря
def __init__(self, left, right):
self.left = left
self.right = right
class dictionary_el(object): # для словаря
def __init__(self, el_freq, all_let):
self.el_freq = el_freq
self.all_let = all_le... | true |
1e004d8dd8491821def851b97ec3aad70606d8e4 | jugba/solved | /october/28.py | UTF-8 | 945 | 4.0625 | 4 | [] | no_license | """Hi, here's your problem today. This problem was recently asked by Twitter:
Given an array of characters with repeats, compress it in place. The length after compression should be less than or equal to the original array.
Example:
Input: ['a', 'a', 'b', 'c', 'c', 'c']
Output: ['a', '2', 'b', 'c', '3']
Here's a star... | true |
29a80e55ffc8a9b9f1157cfe4c4f0e413d5c96ef | kangwubin/xatu_python | /LS14_number_test.py | UTF-8 | 1,174 | 3.40625 | 3 | [] | no_license | # coding:utf-8
title = '康康学校的春游'
class_count = 55
boys = 28
girls = 23
every_body_pay = 35.5
start_time = 8.00
bus_count = 2
site_every_bus = 30
come_park_time = 10.30
lunch_time = 12.00
lunch_pay = 25.5
leave_park_time = 3.05
bus_pay = 5
come_back_school_time = 5.00
back_pay = 5
if __name__ == '__main__':
... | true |
473fa1a34c79ee32d0d10872a3d1ca8baf70adee | kaifsadri/Advent-of-Code-2017 | /16.py | UTF-8 | 1,175 | 3.015625 | 3 | [] | no_license | Dance = open("16.txt").readline().strip().split(",")
P = "abcdefghijklmnop"
for step in Dance:
if step[0] == "s":
n = int(step[1:])
P = P[16 - n :] + P[: 16 - n]
elif step[0] == "x":
c = step[1:].split("/")
a, b = P[int(c[0])], P[int(c[1])]
P = P.replace(b, "z").replace(a... | true |
2201b6241c99b71d01999044bb7c067327bd7874 | pedroceciliocn/programa-o-1 | /funções/exercício_3_palíndromos.py | UTF-8 | 1,935 | 4.46875 | 4 | [] | no_license | """
Fazer um programa para achar todos os números
palíndromos entre 100 e 5000.
– Um número é palíndromo se ele tiver o mesmo valor
quando escrito da direita para a esquerda. Ex: 17371.
– Escreva e utilize uma subrotina cujo resultado é o valor
recebido no parâmetro (int) escrito ao contrário.
•... | true |
02aefe5477465afe32bbde207c6527fc221e2843 | akiljames83/enghack2018 | /sentiment.py | UTF-8 | 504 | 3.0625 | 3 | [] | no_license | #a70776a16ea44fe661bbb0e2aaec1e12
import indicoio
indicoio.config.api_key = ''
# single example
print(indicoio.sentiment("I love writing code!"))
# batch example
indicoio.sentiment([
"I love writing code!",
"Alexander and the Terrible, Horrible, No Good, Very Bad Day"
])
something = 'something... | true |
f6d72ea1253e998e6d23f1c5e3d757fec42f373e | rubenhortas/python_examples | /performance/string_concatenation_performance.py | UTF-8 | 3,855 | 3.640625 | 4 | [
"MIT"
] | permissive | #!/usr/bin/env python3
import time
from array import array
from functools import wraps
from io import StringIO
LIST_LENGTH = 10000
ITERATIONS = 1000
def timeit(func):
@wraps(func)
def timeit_wrapper(*args, **kwargs):
start_time = time.perf_counter()
for i in range(1, ITERATIONS):
... | true |
abc6d6c5fa3cdf223475717278f7d48056119f66 | bleist88/System | /Vault/plot_sed | UTF-8 | 3,363 | 2.609375 | 3 | [] | no_license | #!/usr/local/bin/python3
"""
This script is used to plot a set of spectrums in a SpectrumPlot from a
configurations file.
"""
from AstroLib import *
################################################################################
## Default Configurations.
title = None
figsize = 14, 6
xlabel = "Wav... | true |
cfa2c0e16fb689019ffdc74a15ce4ab1264536df | MatejMecka/SubtitleExtractor | /netflix.py | UTF-8 | 8,653 | 2.5625 | 3 | [] | no_license | import os
import re
import requests
from bs4 import BeautifulSoup
import json
from configparser import ConfigParser
from selenium import webdriver
import time
import codecs
import math
import Netflix_XmlToSrt
class netflixExtractor(object):
"""docstring for netflixExtractor"""
def __init__(self, url, testMo... | true |
7b989c323035c0effcc94fcac0ecc80139917e29 | YUKAI/konashi-android-sdk | /.wercker/report.py | UTF-8 | 1,374 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | import sys
import os
import StringIO
import xml.etree.ElementTree as ET
def main():
assert 1 < len(sys.argv)
path = sys.argv[1]
tree = None
with open(path) as f:
source = ''.join(f.readlines()[1:]) + '</html>'
print source
html = StringIO.StringIO(source)
tree = ET.parse... | true |
7dbdaee99c105669047faee4cc9422a0e8112f00 | imacube/thermostat-pi | /tests/test_get_remote_state.py | UTF-8 | 2,172 | 2.515625 | 3 | [
"MIT"
] | permissive | """Tests for Thermostat class which talks to the thermostat via the XBee radios."""
from unittest.mock import patch, MagicMock
import pytest
from digi.xbee.exception import TimeoutException
from thermopi.exceptions import CrcVerificationFailure, FailedToGetState
from thermopi.thermostat import Thermostat
@patch('d... | true |
8ff1295426b0fee7883479dc27519650b094081f | Josasalencar/PO | /Melhor_Pior__aleatorio.py | UTF-8 | 1,614 | 3.640625 | 4 | [] | no_license | import timeit
from random import randint
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
def desenhaGrafico(x, y, xl="Entradas", yl="Saídas"):
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111)
ax.plot(x, y, label="Melhor Tempo")
ax.legend(bbox_to_anchor=(1, 1), bbox_... | true |
1613e3df5f987e201bed24c8cdde6fec528d935c | MrHamdulay/csc3-capstone | /examples/data/Assignment_3/rhsphi001/question3.py | UTF-8 | 616 | 3.359375 | 3 | [] | no_license | message=input('Enter the message:\n')
repeat=eval(input('Enter the message repeat count:\n'))
thick=eval(input('Enter the frame thickness:\n'))
a=len(message)+2
b=a+2*thick
gap=0
for i in range(b,a,-2):
print('|'*gap,end='')
print('+',end='')
print('-'*(i-2),end='')
print('+',end='')
prin... | true |
2e4815cf6e57d32f2b5500e26ac60123b0408961 | antvis/AVAPy | /AVAPy/chart_advisor/aux/scatterplot.py | UTF-8 | 4,343 | 2.96875 | 3 | [
"MIT"
] | permissive | """
The functions tend to configure auxiliaries
on plotting single-class scatterplots
as vega specifications.
Data format:
1. x = [], y = []
2. json {x:..., y:...}
*x.dtype == Number or String
*y.dtype == Number
"""
import numpy as np
import pandas as pd
import altair as alt
from . import auxiliary a... | true |
0db6a8dc706645fc23c1e56ede70e148e3d06394 | tsaoalbert/test.tensor.flow | /others/my.555/Notes-Feb-15-16/network/ftpserver.py | UTF-8 | 4,074 | 3.0625 | 3 | [] | no_license | import socket
import os
from threading import Thread
listen_port = 21
class ClientThread(Thread):
def __init__(self, ip, sock):
Thread.__init__(self)
self.client_ip = ip
self.controlsock = sock
self.dataport = 12346
self.datasock = None
print( " N... | true |
dfae3eab64588829da9fd02b55597a28dfcb7a6a | torayeff/simple-logger | /main.py | UTF-8 | 854 | 2.921875 | 3 | [] | no_license | from Logger import Logger
if __name__ == "__main__":
weightLogger = Logger(id="some_id_1", category="Health")
weightLogger.log({
"weight": 75.30
})
weightLogger.log({
"weight": 75.10
})
weightLogger.log({
"weight": 75.00
})
weightLogger.log({
"we... | true |
5751809f0ef1a057e96b522431f9e66e1b04e0bd | fleitner/XenaPythonLib | /xenalib/XenaManager.py | UTF-8 | 2,803 | 2.53125 | 3 | [] | no_license | import sys
import time
import logging
from . import KeepAliveThread
from . import XenaPort
logger = logging.getLogger(__name__)
class XenaManager:
def __init__(self, xsocket, owner, password='xena'):
self.xsocket = xsocket
self.ports = {}
self.keep_alive_thread = None
# FIXME: Th... | true |
6bd2d748cddd5cdcb49862cd70299177dec6426a | eterinfi/python | /weatherH.py | UTF-8 | 1,558 | 2.65625 | 3 | [] | no_license | # Filename: weatherH.py
# -*- coding: utf-8 -*-
import urllib2
from time import time, localtime, strftime
from HTMLParser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
pass
def handle_endtag(self, tag):
pass
def handle_startendtag(self, tag, att... | true |
f2048a394d49306cd166f2acbbe62b53ab491941 | Husseinbeygi/My-Research-on-Opencv-With-Python | /Object Detection/FLANN MATCHING.py | UTF-8 | 1,690 | 2.6875 | 3 | [] | no_license | ### Imports
import cv2
import matplotlib.pyplot as plt
import numpy as np
### load Images
Original = cv2.imread('DATA/socket.png')
Target = cv2.imread('DATA/socket2.jpg')
Original = cv2.cvtColor(Original,cv2.COLOR_BGR2GRAY)
Target = cv2.cvtColor(Target,cv2.COLOR_BGR2GRAY)
# ret,thresh = cv2.threshold(frame,(frame.max... | true |
f7525253946001a619006b6150587de600f52f5d | TeoRojas/Curso_Aprende_Python_con_DBZ | /Colecciones_de_datos/COL_diccionarios_04.py | UTF-8 | 388 | 3.484375 | 3 | [] | no_license | # Declaración de diccionario más completo y complejo de guerreros saiyajins
dic_de_saiyajins_completo = {
'Broly' : 'El legendario',
'Vegeta' : 'El orgulloso',
'Kakarotto' : 'El ingenuo'
}
for clave, valor in dic_de_saiyajins_completo.items():
print(
'El Saiyajin',
clave,
... | true |
6eeed318b73369f24ab1058e957b2f36cc5010b7 | kamyu104/LeetCode-Solutions | /Python/count-number-of-maximum-bitwise-or-subsets.py | UTF-8 | 418 | 3.3125 | 3 | [
"MIT"
] | permissive | # Time: O(min(2^n, m * n)), m is the 'bitwise or' of nums
# Space: O(min(2^n, m))
import collections
class Solution(object):
def countMaxOrSubsets(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = collections.Counter([0])
for x in nums:
for k... | true |
66f540e3a2d73b6171bdc63df5d570e1a9b0b098 | Wdiii/LeetCode-exercise-start-from-easy | /Math/medium-Reach a Number.py | UTF-8 | 430 | 2.96875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
class Solution:
def reachNumber(self, target: int) -> int:
t=abs(target)
k=0
s=0
while s<t:
k+=1
s+=k
dt=s-t
if dt%2==0:
return k
... | true |
ce4c1157007406cf548c019bd2bd09ddbe026478 | sdierauf/uw-cse | /143/PyHelloWorld/moar.py | UTF-8 | 702 | 3.953125 | 4 | [] | no_license | '''
Created on Feb 28, 2013
@author: Stefan
'''
colors = ['red', 'blue', 'green']
print(colors)
sum = 0
for i in range(100):
sum += i
print(sum)
sum = 0
numbers = [1, 3, 5, 6, 7, 5, 6, 7, 9, 0, 1, 2, 6, 7, 4]
for i in numbers:
print(i)
sum += i
print('sum is: ' + str(sum))... | true |
f4f795e77e4befc0b4ca0e19f51dc32420dacf75 | ladorabl/shuffleMasterAssignment | /shuffleAssignment.py | UTF-8 | 5,494 | 3.875 | 4 | [] | no_license | #!/usr/bin/python
import copy, random, time
#1. A standard deck of 52 cards is represented in an array. Each card is represented as an integer. Write a method to shuffle the cards.
'''
This problem was solved through the function shuffleList(a_list)
I used the Fisher-Yates shuffle algorithm in order to shuffle the dec... | true |
8d1f53818a80901731a28466b714ce1a5141d2d9 | bbalin12/DAT5_BOS_students | /haruom/class8/class8_homework.py | UTF-8 | 7,870 | 2.921875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 16 17:25:41 2015
@author: Haruo M
"""
import numpy
import pandas
import sqlite3
from sklearn.neighbors import KNeighborsClassifier
con = sqlite3.connect('C:\Users\mizutani\Documents\SQLite\lahman2013.sqlite')
sql = """SELECT h.playerID, h.inducted, SUM(b.G_batting) AS t... | true |
38575d1a447060788e13f72f989e7dbffbbc776b | adam2392/blackjack_kpcb | /blackjack/teacher/base.py | UTF-8 | 1,187 | 3.40625 | 3 | [] | no_license | from abc import ABC, abstractmethod
from blackjack.utility.strategy import BasicStrategy
class BaseTeacher(ABC):
@abstractmethod
def suggest_action(self):
"""
Function that suggests an action based on the
current state of the cards.
Most learners will have the ability to proc... | true |
8e433236f2a673f98d4c2aba7843e76ca7ddc936 | alPreuhs/MotionCreator | /include/readWriteRaw.py | UTF-8 | 1,589 | 3.078125 | 3 | [] | no_license | import numpy as np
def read(filename):
"""
:param filename: name of raw data file that is ordered as follows:
3 number in int16 format (2bytes each number -> 6byte header) encoding the height,width and number of matrices,
followed by the matrix indices in float64 (6 byte) format.
:return:
List ... | true |
3c6b0f044555e46f681407d93d0a408022ca8149 | Bihanojko/DatasetConsumption | /tests.py | UTF-8 | 3,364 | 2.875 | 3 | [] | no_license | ###############################################################################
# Assignment: The dataset consumption
# tests.py
# Unit tests testing inidivdual functions
# Date: 4. 5. 2020
# Author: Nikola Valesova
###############################################################################
import unittest
import ... | true |
6239522da8b4b8c01f2de6c0db56ac68ca8586a4 | SylwekSzewczyk/NN-for-NBA-data-WS-analysis- | /main/regressors.py | UTF-8 | 2,276 | 2.9375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 23 22:13:55 2019
@author: Sylwek Szewczyk
"""
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from yellowbrick.regressor import PredictionError, ResidualsPlot
from d... | true |
efb3095ca8200ce4b33278672795a2c76796f9b3 | JonhLucas/Projeto-redes | /Room.py | UTF-8 | 7,236 | 2.90625 | 3 | [] | no_license | import socket
import threading
import time
import random
from unicodedata import normalize
class Room:
def __init__(self, port):
self.port = port
self.ip = "localhost"
self.first_iteration = True
self.winner = 0
self.cont_plays = 0
self.cont_categories = 1
... | true |
b885ed8f0d9bf0cb91e5cdb0cadc70e7c8f0e470 | ParitoshBarman/Machine-Learning-Practices | /ML Harry/14_classify.py | UTF-8 | 432 | 3.03125 | 3 | [] | no_license | # Loading requred modules
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
iris = datasets.load_iris()
# Loading dataset
# Printing description and features
# print(iris.DESCR)
features = iris.data
labels = iris.target
print(features[0], labels[0])
# Traning the classifier
c... | true |
eddac6fb5c2401b387e8ad0c752a1cd2879c8031 | rjOwl/Python-file-transfer | /clientFtp.py | UTF-8 | 2,739 | 2.90625 | 3 | [] | no_license | #!/usr/bin/python
# This is client file
"""
Reference:
http://eli.thegreenplace.net/2011/05/18/code-sample-socket-client-thread-in-python
https://docs.python.org/2/library/threading.html
"""
import socket, threading
from time import sleep
from ftp_parent import MAIN
from os.path import exists
from os import system
f... | true |
0af8a6238a6612939833739da14e3f65714e07cf | scrakes/pg_sc | /Subjects_SC.py | UTF-8 | 776 | 4.09375 | 4 | [] | no_license | name = "Scarlett"
subjects = ["English","Math","Science","History","Chinese"]
print("Hello " + name)
for i in subjects:
print("One of your subjects is " + i)
desserts = ["Cake","Ice Cream","Cupcakes","Tarts","Pie","Vegetables","Tiramisu","Cookies","Brownies"]
for i in desserts:
if i == ... | true |
747cfd37eaf8f151beeece854b720ce5378696dd | zhiwei53010/Unet_pytorch | /unet/util.py | UTF-8 | 415 | 2.59375 | 3 | [] | no_license | import numpy as np
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
def doubleCrop(img, label, size):
i, j, h, w = transforms.RandomCrop.get_params(img, size)
img = transforms.functional.crop(img, i, j, h, w)
label = transforms.functional.crop(label, i, j, h, w)
return img, l... | true |
df7e8aff72b23548d61de8f3f474f01d5da061af | DaanMoll/SWT | /heartmonitor/main_old.py | UTF-8 | 9,473 | 3.890625 | 4 | [] | no_license | # This program simulates the controller of a heart monitoring device.
# It reads the pulse, the oxygen level as well as the blood pressure.
# Its main purpose is to raise alarms if there is something seriously wrong.
def heart(number):
# normal heart rate
if (number >= 60 and number <= 100):
print("He... | true |
85067f2ff797c6bc32d68ed9f418a2314543d777 | mahesanmidhun/ridley | /ridley.py | UTF-8 | 2,262 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | import wx
import time
import wikipedia
import wolframalpha
import winspeech
import wolframalpha
from PIL import Image
from speech import speechutils
from utils.configreader import get_preferences, get_phrases
app_id = "RT2P2A-TKVHWP2EVY"
client = wolframalpha.Client(app_id)
hour = time.localtime().tm_hour
preference... | true |
55d7d5f0cc532432e5327d88f490dff5fc2913c9 | NJMES/HackerRank | /30DaysChallenge/Day8DictionariesandMaps_complete.py | UTF-8 | 991 | 3.703125 | 4 | [] | no_license | # link https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem
# Day 8: Dictionaries and Maps
''' My solution but can't pass one of the test.
n = input()
phonebook={}
for i in range(int(n)):
nmph = input().split()
nm,ph = nmph[0],nmph[1]
phonebook[nm]=ph
for i in range(int(n)): #problem... | true |
5058a4183cef5c2cbbcabccc5254bb5a286ebf98 | zhihuazhanggdut/BPDemo | /train.py | UTF-8 | 5,672 | 2.90625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 10 16:21:46 2017
@author: zhihuazhang
"""
#本程序由UESTC的BigMoyan完成,并供所有人免费参考学习,但任何对本程序的使用必须包含这条声明
from input_data import input_data
import numpy as np
import math
########################
#读入数据
########################
sample, label, test_s, test_l = input_data() #灰度值
sample... | true |
a03a40b229f8697bee9bb340e14401aef1f5420c | lexxxv/stepik_final_test | /pages/login_page.py | UTF-8 | 1,523 | 2.578125 | 3 | [] | no_license | import pytest
from .base_page import BasePage
from .locators import LoginPageLocators
class LoginPage(BasePage):
def should_be_login_page(self):
self.should_be_login_url()
self.should_be_login_form()
self.should_be_register_form()
def should_be_login_url(self):
# реализуйте п... | true |
faeca77780ab4d3653a11a029ce28d7bd58b43bc | ZhongXiLu/compilers | /src/AST/Expression.py | UTF-8 | 3,404 | 3.203125 | 3 | [] | no_license |
from AST.ASTNode import ASTNode
from enum import Enum
class BinOpTokens(Enum):
AND = "&&"
OR = "||"
LT = "<"
GT = ">"
LTE = "<="
GTE = ">="
EQ = "=="
NEQ = "!="
PLUS = "+"
MIN = "-"
MULT = "*"
DIV = "/"
class UnaryOpTokens(Enum):
NEG = "!"
MIN = "-"
class A... | true |
553eec12f84767ee7e57037f99326d2243067d62 | JasonFaas/pythonhelloworld2 | /src/opencv/processing/image_segementation_watershed.py | UTF-8 | 3,132 | 2.59375 | 3 | [] | no_license | import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('../resources/320x480-Wallpaper-110.jpg')
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
hue, sat, val = cv.split(hsv)
_, t1 = cv.threshold(sat, 30, 255, cv.THRESH_BINARY+cv.THRESH_OTSU)
_, t2 ... | true |
64b3457d715336b37b625234d806bdbc54407662 | SyedTanzimAlam/Natural_Language_Processing | /face_detect.py | UTF-8 | 4,516 | 2.625 | 3 | [] | no_license | import cv2
import sys
import fitz
doc = fitz.open(r'C:\Users\tehzeeb\Downloads\FaceDetect-master\FaceDetect-master\Doc3.pdf')
for i in range(len(doc)):
for img in doc.getPageImageList(i):
xref = img[0]
pix = fitz.Pixmap(doc, xref)
if pix.n < 5: # this is GRAY or RGB
pix.wri... | true |
9652c53078c81475d15c459cbbd00a1642adb382 | jonhue/propose | /test/test_builder.py | UTF-8 | 1,828 | 2.828125 | 3 | [
"MIT"
] | permissive | from textwrap import dedent
from propose.builder import build
from propose.lexer import lex
from propose.parser import State, parse
def _build(input):
tokens = lex(input)
state = State()
ast = parse(input, tokens, state)
return build(state, ast, highlight=False)
def _match_output(expected, actual, m... | true |
94393d39fd7d0f53f097b51fb9a81bfd0728bd7f | delekta/agh-asd | /2.3graphs/paths/DAG_shortest_path.py | UTF-8 | 496 | 3.453125 | 3 | [] | no_license | # Jak znaleźć najkrótsze ścieżki z wierzchołka s do wszystkich innych w
# acyklicznym grafie skierowanym? (Krawędzie są ważone.)
# Topological sort time complexity: O(V + E)
"""
1. Topological Sort na Grafie
2. Jak mamy posortowane topologicznie, to wystarczy raz przejsc po krawędziach bellman-fordem, bo ... | true |
aedce81b9fb68337063747292c0f9c7feb492c47 | CowsSayOink/Euler | /euler91.py | UTF-8 | 184 | 2.84375 | 3 | [] | no_license | total=0
n=2
print(n+2*total)# 2 for symmetry and the n is for the ones that only occure once
| true |
b9e46cb59f9c044af8bd808e6abb0d096dbff139 | Aasthaengg/IBMdataset | /Python_codes/p02623/s816025370.py | UTF-8 | 395 | 2.6875 | 3 | [] | no_license | import numpy as np
from bisect import bisect_right
n, m, k = map(int, input().split())
a = [0] + list(map(int, input().split()))
b = [0] + list(map(int, input().split()))
a = np.cumsum(a)
b = np.cumsum(b)
ans = 0
for a_num, time in enumerate(a):
if time > k:
continue
b_num = bisect_right(b, k - time)
... | true |
d222a0f2be758aef2eb01357f1924447e1a17e0a | monetree/core-python | /py26/py2.py | UTF-8 | 340 | 3.453125 | 3 | [] | no_license | #Random Accessing
with open('line.txt','w+b') as f:
f.write(b'Python is Amazing')
n = f.tell()
print(n)
f.seek(0,0)
print(f.read(5))
f.seek(-5,2)
print(f.tell())
print(f.read(5))
print(f.tell())
'''
a m a z i n g p y t h o n
1 2 3 4 5 6 7 8 9 10 11 12 13 14
14131211109 8 7 6 5... | true |
08dd85b38d39b8a1317880d3d3ba9d7ea0c0bfab | tkliuxing/iBlogsite-django | /createdb.py | UTF-8 | 1,284 | 2.53125 | 3 | [] | no_license | import psycopg2
import os
from wsgi import application
application = application
def create_dbs():
print("create_dbs: let's go.")
django_settings = __import__(os.environ['DJANGO_SETTINGS_MODULE'], fromlist='DATABASES')
print("create_dbs: got settings.")
databases = django_settings.DATABASES
for na... | true |
4221e0f1bf2691e002a50f8c18fedd867138c506 | bombrun/GaiaLQSO | /lens/sis/inferencePM.py | UTF-8 | 2,504 | 2.96875 | 3 | [
"CC-BY-4.0",
"LicenseRef-scancode-other-permissive",
"MIT"
] | permissive | """
QSO position, magnitude and proper motion inference and SIS lens inference
from LQSO images position, magnitude and proper motion
model : xS,yS,dxS,dyS,gS,bL,xL,yL
"""
from lens.sis.inference import *
def pmPrior(x):
"""SIS L-S proper motion prior"""
return norm.pdf(x,0,0.5)
def log_prior_pm(model):... | true |
e069da7845cb4dea74163d0fe9425e1cc88e7f5e | richardqiao2000/quant-practice | /yahoo/data_update/4.store_ticker_data_daily.py | UTF-8 | 4,667 | 2.703125 | 3 | [] | no_license | import urllib.request
import ssl
import requests
import time
from datetime import datetime
import psycopg2
import pandas as pd
import sqlalchemy
# Set start/end day to update data
day_start = "2021-02-22"
day_end = "2021-02-23"
last_ticker = None # to continue from last job executed ticker
# get all ticker name and ... | true |
f99e315e1abc72a8668ed6e7e0904e292c3aeb65 | neinkopp/screenmanager-setup | /files/tools/colorify.py | UTF-8 | 455 | 2.9375 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
def colorify(color, escape, text):
colors = {
"blue": "\033[34m",
"blue_bold": "\033[1;34m",
"cyan": "\033[1;36m",
"green": "\033[32m",
"green_bold": "\033[1;32m",
"red_bold": "\033[1;91m",
"magenta": "\033[35m",
"magenta_bold": "\033[1;35m",
"escape": "\... | true |
34e8991bc1cc0680f0eb2f41528110ab94c82fa1 | matteogabburo/python-ast-utils | /tests/resources/accepted/res_19_minpyversion_3_0.py | UTF-8 | 6,899 | 2.515625 | 3 | [
"MIT"
] | permissive | from torch import nn
import torch
# import torch_scatter
import torch.autograd.profiler as profiler
import util
# Resnet Blocks
class ResnetBlockFC(nn.Module):
"""
Fully connected ResNet Block class.
Taken from DVR code.
:param size_in (int): input dimension
:param size_out (int): output dimensi... | true |
fe55bebff598512e1fee5bd54e460f8e1001f464 | cRYP70n-13/Algorithms | /interviews/Array/FindAllNumbersDisappearedInAnArray.py | UTF-8 | 403 | 3.734375 | 4 | [] | no_license | def findAllTheDisappearedElementsInArray(nums):
hash_table = {}
res = []
for num in nums:
hash_table[num] = 1
for num in range(1, len(nums) + 1):
if num not in hash_table:
res.append(num)
return res
# We can also use a Set here but I prefer the hash_table data... | true |
26b399efa7b5a9faab75d00cd7ae522ecf83b86f | romanzes637/colormap_writer | /colormap_writer.py | UTF-8 | 853 | 2.90625 | 3 | [] | no_license | import seaborn as sns
import json
print("Reading names")
names = []
with open("names") as f:
data = f.readlines()
for line in data:
names.extend(line.split())
print(names)
print("Importing colormaps")
n_colors = []
colors = []
n_components = []
for name in names:
palette = sns.... | true |
f8fac93129a2455266b4e285cd702ec7fd07e22c | aarondemolder/inMotion | /inMotion-maya-script/inmotion-maya.py | UTF-8 | 3,028 | 2.5625 | 3 | [] | no_license | import maya.cmds as cmds
def createUI():
#creates window
cmds.window("inMotion")
cmds.columnLayout( adjustableColumn=True)
cmds.frameLayout( label='Locator Creation')
cmds.text( label='Remember to set your project framerate before importing motion data.', align='left' )
cmds.button(label = "Add Locator", comm... | true |
81a2f62b12efd214a02b4f48710a9e34f19366d8 | rashimjain/python-challenge | /PyPoll/main.py | UTF-8 | 3,173 | 3.21875 | 3 | [] | no_license | # First we'll import the os module
# This will allow us to create file paths across operating systems
import os
# Module for reading CSV's
import csv
csvpath = os.path.join('raw_data','election_data_1.csv')
# Part 1 - Calculate total number of votes
with open(csvpath, newline='') as csvfile:
# CSV reader sp... | true |
642d9557d24179762936bb6258a7bb9b294dcf53 | duk1edev/tceh | /tceh5_opp/self_work/task2.py | UTF-8 | 962 | 3.96875 | 4 | [] | no_license | # Пользователь вводит список чисел через пробелб если ввел
# 1 число строим квадрат
# 2 числа строим прямоугольник
# 3 числа строим трехугольник
# 4 строим многоугольник
#
# Вычисляем площадь, перимет и выводим в консль
# провеки на воозможность пострить фигуру с данными сторонами
class Figure(object):
def _... | true |
745bb56c561c4372e7518c521ca54c534fb5268d | nilsonsales/PAA | /count_sort.py | UTF-8 | 463 | 3.734375 | 4 | [] | no_license | """
Problem: Count Sort
Author: nilsonsales
"""
my_list = []
my_list = input().split(" ")
count = 0
for i in range(len(my_list)):
my_list[i] = int(my_list[i])
#my_list.sort()
for i in range(len(my_list)-1):
for j in range(i+1, len(my_list)):
count += 1
if my_list[i] > my_list[j]:
... | true |
11a8f7388788a7057e89cba5ace363e1d4852ddb | geewynn/MickysBite | /mickys/models.py | UTF-8 | 612 | 2.53125 | 3 | [] | no_license | from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
mobile_number = models.IntegerField()
def __str__(self):
return self.user.username
class Product(mod... | true |
a82093d2eca5c9dba7920bab0d620f3afda7e263 | eduardosoaresdutra/tictactoe_game | /tictactoe.py | UTF-8 | 3,738 | 4.03125 | 4 | [] | no_license | from IPython.display import clear_output
import random
def board_display(board):
''' Print the board. '''
clear_output(wait=True)
print(' | |')
print(' '+ board[7] + ' | ' + board[8] + ' | ' + board[9])
print('-----------')
print(' '+ board[4] + ' | ' + board[5] + ' | ' + board[6])
print('------... | true |
06ce868217010d04702ce28b23438d2c52433363 | itsparth20/Data-structure-and-Algorithms | /hackerrank/LCATree/lca.py | UTF-8 | 903 | 3.8125 | 4 | [] | no_license | """
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node)
self.data (the value of the node)
"""
def lca(root , v1 , v2):
#Enter your code here
r1,r2=root,root
vl1,vl2=[],[]
while(r1):
if v1>r1.data:
vl1.append(r1)
r1=r1.righ... | true |
fff4a5aae56926dbcf1f4135703e43018cd30b98 | RianMarlon/Python-Geek-University | /secao12_modulos_e_pacotes/modulo_random.py | UTF-8 | 2,098 | 4.28125 | 4 | [] | no_license | """
Módulo Random e o que são módulos?
- Em Python, módulos nada mais são do que outros arquivos Python.
Módulo Random -> Possui várias funções para geração de números pseudo-aleatório.
# OBS: Existem duas formas de se utilizar um módulo ou função deste
# Forma 1 - Importando todo o módulo (Não recomendado).
impo... | true |
fde020d803e8072a60f6a4300f831dd331971d70 | andrewRv/CRUD-app | /run.py | UTF-8 | 272 | 2.75 | 3 | [] | no_license | from user import User
user = {"name": "John Dou", "age": 30, "address": "New York"}
john_dou = User(user)
john_dou.save()
john_dou.update({"name": "John Dou", "age": 30, "address": "L A"})
uncle_sam = User(input())
uncle_sam.save()
john_dou.db.close()
uncle_sam.db.close()
| true |
20a78167809e12c8ea0c3354bedba4ab64e2bdd8 | AChen24562/Python-QCC | /Week-1/VariableExamples_I/Ex7d_numbers_representation.py | UTF-8 | 223 | 3.421875 | 3 | [] | no_license | # S. Trowbridge 2020
# underscore can be used to simplify the visualization of a big_number
big_number = 15_000_000
print(big_number)
# to the interpreter, the underscores do not exist
big_number = 150_00_0_00
print(big_number)
| true |
2f167e567a291b4b60082fbd5b280912f9514248 | kh0p/glblox | /controller.py | UTF-8 | 3,594 | 2.6875 | 3 | [] | no_license |
""" Keyboard manager """
__author__ = "Peter Bennett"
__copyright__ = "Copyright 2012, Peter A Bennett"
__license__ = "LGPL"
__version__ = "0.1"
__maintainer__ = "Peter Bennett"
__email__ = "pab850@googlemail.com"
__contact__ = "www.bytebash.com"
from pyglet.window import key, mouse
from pyglet import clock
""" St... | true |
f6c9e7ef88d1f6bef3e1bb2e505392cf1cb58b8d | choogiesaur/codebits | /challenges/python/unique-emails.py | UTF-8 | 735 | 2.96875 | 3 | [
"MIT"
] | permissive | # Input: emails = ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]
# Output: 2
# Explanation: "testemail@leetcode.com" and "testemail@lee.tcode.com" actually receive mails.
class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
uniques = {}... | true |
7629961e1429c3d763519997a2c9a47bcfb542c2 | passionCodingTest/bommi | /bf/9095.py | UTF-8 | 303 | 3.328125 | 3 | [] | no_license | T=int(input())
#숫자 4부터 이전 3개의 개수를 모두 더한 수가 총 개수가 되는 것
input_list=[]
for _ in range(T):
input_list.append(int(input()))
dp=[1,2,4]
for i in range(3,max(input_list)):
dp.append(dp[i-1]+dp[i-2]+dp[i-3])
for i in input_list:
print(dp[i-1]) | true |
0cdbb29e2456ae45e38d12267e018c31863ff423 | xueshengke/WRANSR-keras | /utils.py | UTF-8 | 3,300 | 2.5625 | 3 | [] | no_license | from __future__ import print_function
import tensorflow as tf
import keras
from keras import backend as K
import numpy as np
import os
import keras.backend.tensorflow_backend as KTF
def useGPU(gpu_id):
if not gpu_id:
print('Use CPU')
else:
print('Use GPU')
# only use limited GPU memory
... | true |
4194a6498288a11986cc32ab8f8eb4a45899130e | RickXie747/UNSW-18S1-COMP9021- | /Lab3/Q4.py | UTF-8 | 1,005 | 2.75 | 3 | [] | no_license | a = '0123456789'
def f(n, sum, sign, n2, path):
if n < 9:
f(n + 1, sum + int(a[n + 1]), ' + ', str(n + 1), path + sign + n2)
f(n + 1, sum - int(a[n + 1]), ' - ', str(n + 1), path + sign + n2)
if n < 7:
f(n + 3, sum + 100 * int(a[n + 1]) + 10 * int(a[n + 2]) + int(a[n + 3]), ' + ... | true |
5542afd14f3e7dc8a08e9678eaab5d5529926842 | l-mizrahi/Practical-Python-Exercises | /tests/test_tableformat.py | UTF-8 | 2,856 | 3.125 | 3 | [] | no_license | from src.tableformat import TextTableFormatter, CSVTableFormatter, is_formatter
import pytest
@pytest.fixture
def data():
headers = ("Name", "Shares", "Price", "Change")
rows = [
("AA", 100, 9.22, -22.98),
("IBM", 50, 106.28, 15.18),
("CAT", 150, 35.46, -47.98),
("MSFT", 200, 2... | true |
74ddbeb64cbafcde1cb3c1b71720af8be3deb240 | joao-conde/competitive-programming | /online-judges/codeforces/e.py | UTF-8 | 355 | 2.859375 | 3 | [] | no_license | s = input()
modulo = 10**9 + 7
dp = [1] * len(s)
for i in range(1, len(s)):
if s[i] == "m" or s[i] == "w":
dp[-1] = 0
break
if s[i] == "u" and s[i - 1] == "u":
dp[i] = dp[i - 2] + dp[i - 1]
elif s[i] == "n" and s[i - 1] == "n":
dp[i] = dp[i - 2] + dp[i - 1]
else:
... | true |
606c8740467be7da1071be6991e463dfe02d4c2d | SimoneLazzaris/usermgt-py | /usermgt.py | UTF-8 | 4,002 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env python3
# must user varchar[256] for primary key, since straight varchar is not working
# missing documentation for creating a primary key spanning multiple columns
# ERROR: rpc error: code = Unknown desc = max key length exceeded if using varchar[256] for primary key
# missing UNION in select
from imm... | true |
27770ad1108a951131086d24dda4046c3b7eca18 | Rajtek/PSZT-cards-divider | /src/wykres.py | UTF-8 | 1,163 | 3.03125 | 3 | [] | no_license | import sys
import matplotlib
import pylab
"""
def main(argv):
plik = open("result_2.txt", "r")
liczby = []
srednia = []
a = 0
for val in plik.read().split():
if a%2 == 0:
liczby.append(int(val))
else:
srednia.append(float(val))
a += 1
plik.close()
x = range(0, len(liczby) )
m = max(srednia)
py... | true |
304f2debfdcf810288c6ec799c8856a9f57e1ab7 | syurskyi/Algorithms_and_Data_Structure | /Data Structures & Algorithms - Python/Section 5 Data Structures Doubly Linked Lists/src/40.EXERCISE-DLL-Insert.py | UTF-8 | 3,337 | 4.09375 | 4 | [] | no_license | class Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self, value):
new_node = Node(value)
self.head = new_node
self.tail = new_node
self.length = 1
def print_list(se... | true |
4c3371cf9e9e1c71961b7a12566b2778831defae | yweweler/pysrec | /zwuenf/pysrec/SRecord.py | UTF-8 | 4,832 | 2.921875 | 3 | [
"MIT"
] | permissive | import struct
import binascii
__all__ = ('SRecordType', 'SRecord')
from enum import Enum
from colored import fore, style
from zwuenf.pysrec import SRecordParsingError
class SRecordType(Enum):
HEADER = 0
DATA = 1
COUNT = 2
TERMINATION = 3
UNKNOWN = 4
class SRecord:
"""Data structure fot hol... | true |
4aff07e8ca7f50781c0183a713d18b76b24788ba | rileyrohloff/pythontheHardWay | /Python Projects/ex7.py | UTF-8 | 614 | 4 | 4 | [] | no_license | formatter = "{} {} {} {}"
#using our 'formatter' variable to write different strings
print(formatter.format(1, 2, 3, 4)) #each value input for the space brackets are input
print(formatter.format("one", "two", "three", "four"))
print(formatter.format(True, False, False, True))
print(formatter.format(formatter, format... | true |
2d915fbc02cef5aa7250d9e271b373e3fdc758a7 | cosmozhang/ml_final_project_yelp | /nbc/classifier_1.py | UTF-8 | 5,148 | 2.71875 | 3 | [] | no_license | # -*- coding: iso-8859-1 -*-
import time
import csv
import sys
import random
import math
classIdx = 0
num_feature = 5000
attrIdxs = range(1,num_feature+1)
smoothing = True
squaredloss = False
verbose = False
for arg in sys.argv[1:]:
if arg == '--nosmoothing' or arg == '-nosmoothing' or arg == '-n':
smoothing = Fa... | true |
e2c5bdb58ac9e3f83a1603a7ee9bae22b8302516 | JMtifr/Comp-Assignment-2 | /A2_3.py | UTF-8 | 1,037 | 3.3125 | 3 | [] | no_license | # Assignment 2
# Problem 3
# y"-2y'+y=xexp(x)-x
# Let p=y' => p'-2p+y=xexp(x)-x
# r=[p,y]
# f=[p',p]
# k1=hf(r,x)
# k2=hf(r+k1/2,x+h/2)
# k3=hf(r+k2/2,x+h/2)
# k4=hf(r+k3,x+h)
# r(i+1)=r(i)+(k1+2k2+2k3+k4)/6
import numpy as np
import matplotlib.pyplot as pt
def dp(x,y,p): # y"=p'=(2p-y+xexp(x)-x)
return(2*p-y+x*np.e... | true |
8b21afd94a1129a36676c8f31dafafc2a689a811 | ananyacleetus/15-112 | /decorators.py | UTF-8 | 922 | 3.921875 | 4 | [
"MIT"
] | permissive | #!/usr/bin/python
#acleetus
class LessThanZero(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
def nonNegative(function):
#this is just like the example one
def checkZero(*numbers):
for x in numbers:
if x < 0:
raise LessThanZero("ERROR! This is ... | true |
9f1e2147eb19aa56f62ed448cc01a4b63dbd41d7 | FelipeTellini/Python | /1-PrimeirosPasso/des04.py | UTF-8 | 525 | 3.84375 | 4 | [
"MIT"
] | permissive | digita = (input('Digita algo: '))
print(f'O tipo primitivo desse valor é: {digita} ', type(digita))
print('Sua palavra ou número só tem espaço ? ',digita.isspace())
print('É um número ? ', digita.isnumeric())
print('É alfabetico ? ', digita.isalpha())
print('É alfanumerico ?', digita.isalnum())
print('Está tudo em maiu... | true |
d35a7e4c1282a262479363b721c3c5115389c6dd | Phinease/Fluent_Python_Learning_Code | /example-code-master/07-closure-deco/test_closure.py | UTF-8 | 313 | 3.328125 | 3 | [
"MIT"
] | permissive | def make_averager():
series = []
def averager(new_value):
series.append(new_value)
total = sum(series)
return total/len(series)
return averager
a = make_averager()
a(10)
a(11)
a(12)
print(a.__closure__)
print(a.__closure__[0].cell_contents)
print(a.__closure__[0].__doc__)
| true |
64e2f22398802427b19b287612b25ca2b483187c | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_201/1544.py | UTF-8 | 1,555 | 3.484375 | 3 | [] | no_license | def cal(S, K):
max = 0
min = 0
if S >= K:
if (K != 0 and ((K & (K - 1)) == 0)):
factor = K
repeat = 0
for i in range(K, S+1):
if repeat < factor:
repeat += 1
else:
repeat = 1
... | true |
34963da9892fc551384642c9ac49d6980e310031 | akapitonov/test_new_worker_plugin | /tfw_myworker/myworker.py | UTF-8 | 3,913 | 2.65625 | 3 | [] | no_license | """
Module Introduction.
Any module level documentation comes here.
"""
import re
import logging
from tf_workers import ( # pylint: disable=E0611
Worker, SettingProperty, WorkerResponse, ResponseCodes as RC
)
from tf_workers.config import ApplicationConfig # pylint: disable=E
from tfw_myworker.parsers import G... | true |
b2c013fe432af3b4d1d6a3d6cb49683148b4b1c3 | gangmiss/my_python | /_02python_basicknowledge/_17异常处理.py | UTF-8 | 2,360 | 3.328125 | 3 | [] | no_license | try :
open("xxx.txt","r")
print("111111111111111")
except (NameError,IOError,FileNotFoundError):
print("捕获到异常后的处理...")
except Exception as result:#result为异常对象的引用
print(result)
print("如果上面没有查到相应的异常类型,则我会调用")
else :
print("如果上面没有异常出现,则我会调用,如果上面有异常,我不会调用")
finally:
print("一定会执行")
print("2222222... | true |
b87d3c9bf96ae213a2ae433d57e21f1b0d497963 | brabadu/test_42cc | /model_list/management/commands/modellist.py | UTF-8 | 745 | 2.546875 | 3 | [] | no_license | import sys
from django.core.management.base import NoArgsCommand
from django.db import models
class Command(NoArgsCommand):
help = 'List all models in project and count object in them'
def handle_noargs(self, **options):
output = "\n".join(["%s: %d" % (model_name, count)
... | true |
9d9736efe41c340bb305fa4ad2da216fa5d3b991 | Lmyxxn/JZoffer | /code/分割回文串.py | UTF-8 | 471 | 3.828125 | 4 | [] | no_license | class Solution:
def partition(self, s: str) -> List[List[str]]:
self.res = []
self.backtrack([], s)
return self.res
def backtrack(self, sol, s):
if not s:
self.res.append(sol)
return
for i in range(1, len(s) + 1):
if s[:i] != s[:i][::-... | true |
1b3833dd150c96a162a868768c3e3f8412504132 | xrustle/GB_Algorithms | /01_Algorithms/Lesson5/task_2.py | UTF-8 | 484 | 3.546875 | 4 | [] | no_license | from collections import deque
a = deque()
b = deque('abrakadabra')
c = deque([1, 2, 3, 4, 5])
print(a, b, c, sep='\n')
b = deque('abrakadabra', maxlen=7)
c = deque([1, 2, 3, 4, 5], maxlen=7)
print(b, c, sep='\n')
print('*' * 50)
d = deque([i for i in range(5)])
print(d)
d.append(5)
print(d)
d.appendleft(6)
print(d)
... | true |
b916f145fea7db57522e0fbf8df86dd51440de70 | jiewu-stanford/leetcode | /165. Compare Version Numbers.py | UTF-8 | 1,200 | 3.640625 | 4 | [] | no_license | '''
Title : 165. Compare Version Numbers
Problem : https://leetcode.com/problems/compare-version-numbers/
'''
'''
iterative solution
Reference: https://leetcode.com/problems/compare-version-numbers/discuss/50952/Python-10-lines-solution
'''
class Solution:
def compareVersion(self, version1: str, version2: str... | true |
5df6a5b64274d6de3539d60080c9bc78aa95e999 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_16/21.py | UTF-8 | 2,175 | 2.703125 | 3 | [] | no_license | #!/usr/bin/python
import sys
import copy
szfile = './D-small-attempt0.in.txt'
szfile_output = './D-small.output.txt'
##szfile = './D-large.in.txt'
##szfile_output = './D-large.output.txt'
##szfile = './B-small.in.txt'
##szfile_output = './B-small.output.txt'
class PRLE:
def __init__(self):
... | true |
43b5cdddf30fa81a35ba404463ce9dcdcd28cb20 | k0gane/ShinyBrowser | /mainwindow.py | UTF-8 | 2,742 | 2.921875 | 3 | [] | no_license | """
ZetCode PyQt5 tutorial
This program creates a skeleton of
a classic GUI application with a menubar,
toolbar, statusbar, and a central widget.
Author: Jan Bodnar
Website: zetcode.com
Last edited: August 2017
"""
import sys
from PyQt5.QtWidgets import QMainWindow, QTextEdit, QAction, QApplication, QWidget, QLab... | true |
11b9b538d6a817fdd78c18decaeabd289db51460 | b1naryth1ef/BroCraft | /src/inventory/block.py | UTF-8 | 169 | 2.71875 | 3 | [] | no_license |
class Block(object): # Inheirt this for stuff that is "special"
def __init__(self, id, loc):
self.id = id
self.loc = loc
def update(self): pass | true |
c077e6cb5404cea7391944a7db60f7abdfaa5e0d | freedream520/python_notes | /examples/builtin/type.py | UTF-8 | 196 | 2.5625 | 3 | [] | no_license | '''
Created on 2013-9-1
@author: Administrator
'''
def load(file):
if isinstance(file, type("")):
file = open(file, "rb")
return file.read()
print len(load("data.txt"))
| true |