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
fc7b58e6e12cdf09ed67b51185449748dffbaf57
JosiahDub/laser_game
/tests/pro_tryout.py
UTF-8
864
2.90625
3
[]
no_license
import time from src import ProController c = ProController() while True: if c.button_a(): print('a') if c.button_b(): print('b') if c.button_x(): print('x') if c.button_y(): print('y') if c.button_up(): print('up') if c.button_down(): print('down...
true
4f04c91d0df3cb19a9281a06d524eecf4b66ad3d
rosalieper/python_code
/opening_files.py
UTF-8
213
3.21875
3
[]
no_license
#!/usr/bin/python # Open a file fo = open("foo.txt", "wb") print ("Name of the file: ", fo.name) print ("Closed or not : ", fo.closed) print ("Opening mode : ", fo.mode) print ("Softspace flag : ", fo.softspace)
true
45cf820741151db10284b40e8e77454fa31927d1
tkqlzz/dirAuto
/main.py
UTF-8
168
2.859375
3
[]
no_license
import os arr = os.listdir() res = "" for str in arr: if str.find(".zip") > -1: res += str[:-4] + "\n" f = open("zip_list.txt", "w") f.write(res) f.close()
true
a3394de5010081cfb5ce20e5f945125139161727
nimay-gupta/CS251-Project
/Django/mysite/freq.py
UTF-8
627
2.53125
3
[]
no_license
import sys import requests import urllib # q = "https://api.datamuse.com/words?md=f&sp="+sys.argv[2] # q = q + '&lc=' + sys.argv[1] # q = q + '&rc=' + sys.argv[3] # response = requests.get(q) def phraseScore(phrase): encoded_query = urllib.parse.quote(phrase) params = {'corpus': 'eng-gb', 'query': encoded_query} ...
true
642b672b96afa140f66adb1c1424f2795d1c3e94
s-heiden/LSSTM
/crop_data_stm.py
UTF-8
687
3.015625
3
[ "MIT" ]
permissive
import pickle from typing import Dict dct: Dict = pickle.load(open("./finance_data/data_stm_2004_to_2017.pkl", "rb")) new_dct: Dict = dict() print("len keys", len(dct.keys())) # This dict has two Keys, "Volume" and "Price" # "Volume" contains a pd.DataFrame with a DatetimeIndex and the Cols: VIX Price Gold Price...
true
c99e1ab4b0fd2539b50dbe96523b39b3f2265ca3
HaroldCCS/python
/python/platzi/1_Basico/bucles.py
UTF-8
668
3.8125
4
[]
no_license
def run(): # limite = 1000 # contador = 0 # potencia_2 = 2**contador # while potencia_2 < limite: # print ('2 elevado a ' + str(contador) + ' es igual a ' + str(potencia_2)) # contador += 1 # potencia_2 = 2**contador # for contador in range(1001): # print(contador) #...
true
de047b9e9fd297f42e531c342b1496f914f86cdc
PolinaVin/OADFE
/opt.py
UTF-8
1,190
3.15625
3
[]
no_license
# coding: utf-8 # In[1]: #!/usr/bin/env python3 from collections import namedtuple Result = namedtuple('Result', ('nfev', 'cost', 'gradnorm', 'x')) Result.__doc__ = """Результаты оптимизации Attributes ---------- nfev : int Полное число вызовов модельной функции cost : 1-d array Значения фу...
true
c86f01a2d5df53f5229874ea836236bdc5451bed
CUCyber/scoreboard
/scoreboard/smtp.py
UTF-8
1,176
2.515625
3
[ "MIT" ]
permissive
import logging import random import smtplib import ssl import string log = logging.getLogger('scoreboard:poll') def check(addr, port, cert=None, username=None, password=None, from_=None, to=None, timeout=1, **kwargs): log.info(('SMTP: trying {addr}:{port}' + (' with {username}' if username else '') + (' for {fr...
true
016f6479eeb5bb2750fab0a9b0991ce862e5c98b
sw0rdsm1th/natural-language-processing
/web-parser/soup.py
UTF-8
504
3.34375
3
[]
no_license
import urllib.request from bs4 import beautifulsoup #Wanted to read from Hacker News html = urllib.request.urlopen('https://news.ycombinator.com/').read() soup = BeautifulSoup(html, 'html.parser') texts = soup.findAll(text=True) # Looping through proper tags to print the links for articles, but I got more than I barg...
true
e2e73d9258bf6cee82b104e30c1322735500296b
ashwinbaweja/fun
/project-euler/21-30/30.py
UTF-8
357
3.78125
4
[]
no_license
fifth_powers = {} for i in range(10): fifth_powers[str(i)] = i**5 # 9**5 * 6 < 999999 # thus, all numbers > 999999 cannot be written as sum of 5th powers of their digits total = 0 for i in range(2, 9**5 * 6): digit_sum = 0 for digit in str(i): digit_sum += fifth_powers[digit] if digit_sum ==...
true
0b409a8e425c030311a73bcd09fe5b6a1e18fca4
frnkvsk/Warbler
/forms.py
UTF-8
1,683
2.5625
3
[]
no_license
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, TextAreaField from wtforms.validators import InputRequired, DataRequired, Email, Length, EqualTo, ValidationError class MessageForm(FlaskForm): """Form for adding/editing messages.""" text = TextAreaField('text', validators=[Data...
true
42a462ec42d8c9bd5bfbe86a9204b751266aa323
Liyubov/ojo_daps_mirror
/ojd_daps/flows/extract/tests/test_indeed_extract.py
UTF-8
1,263
2.515625
3
[ "MIT" ]
permissive
import pytest from bs4 import BeautifulSoup from datetime import datetime from pathlib import Path from ojd_daps.flows.extract.indeed import get_indeed_details, indeed_detail_parser,\ regex_search PATH = Path(__file__).parent EXAMPLE_QUERY = PATH / "resources" / "example_indeed_ad.html" AD_CONTENT = open(EXAMPL...
true
63edcaaec3f028698bccdd77189a91c3d1f1a4b3
Gauravcg492/ProblemSolving
/HackerRank/Interview_Prep/Warm-up/Repeated_String/solution.py
UTF-8
236
2.65625
3
[]
no_license
#!/bin/python3 import math import os import random import re import sys import math # Complete the repeatedString function below. def repeatedString(s, n): s_len = len(s) return s.count("a")*(n//s_len) + s[:n%s_len].count('a')
true
da685bf8bcfb852e7bf9ecd9ff9722456f69d679
Shopyangu-engineering/Shopyangu-Payments
/payments/processors/mpesa/base.py
UTF-8
1,892
2.859375
3
[ "BSD-2-Clause" ]
permissive
import datetime class MpesaBase: def __init__(self, is_sandbox_env=True, **kwargs): self.is_sandbox_env = is_sandbox_env self.base_safaricom_url = self.get_base_safaricom_url() self.authentication_token = None self.generate_token_url = "{base_url}{authenticate_uri}".format( ...
true
91bc5da7c88497dcfd5188817223cf62e641fc25
YuyaoZhang17/Community-Recommendation
/Code/Part 3.py
UTF-8
8,527
2.640625
3
[]
no_license
# %% import pandas as pd import numpy as np from Ranking import ranking from DistanceRanking import DistRank, DistRank_F # %% df = pd.read_csv("data.csv", dtype={"Zip Code": str}) def safety_consideration(safety, data): safety_list = ["Property | Theft", "Violent | Sex Abuse", "Violent | Homicide", "Property |...
true
6bca4175b7170a886c81de870d444b8c9f238444
Krutix/DandyBot
/plitk.py
UTF-8
1,796
3.078125
3
[ "MIT" ]
permissive
import json from pathlib import Path import tkinter as tk def load_tileset(filename): tileset = json.loads(Path(filename).read_text()) tileset["data"] = Path(tileset["file"]).read_bytes() return tileset def get_tile_ppm(tileset, index): x = tileset["tile_width"] * (index % tileset["columns"]) y...
true
ccb949c86d00e0ca97c02b49e25b29f2a932b94d
seilaman/python
/hangman.py
UTF-8
1,278
3.609375
4
[]
no_license
import random NewGame = input("Do you want to play? (Y/N)") retry=0 wordlist=["PIKACHU", "SEILA", "KEYBOARD","WORK","WALK","PROJECT","FIND","SUBLIME"] Wordtofind=wordlist[random.randrange(0, len(wordlist))] letters=[] WordSplit = list(Wordtofind) global Lettersfoundsofar Lettersfoundsofar = ["_" for i in Wordtofind ]...
true
1120c93445c4195852a27e06890692b5c1cd69ec
TheStoneMX/Udacity
/AI with Python/predict.py
UTF-8
5,071
2.609375
3
[ "MIT" ]
permissive
# PROGRAMMER: Oscar A. Rangel # DATE CREATED: Nov 25 2018 # REVISED DATE: Dec 1 2018 # PURPOSE: It will train a new network on a dataset and save the model as a checkpoint ## # Imports python modules import argparse from time import time import json import torch import...
true
0ea84cab92ea17b13d2a63aab2387303d80df8f6
Kirimson/Mars-py
/mars/model/Field.py
UTF-8
4,538
3.03125
3
[]
no_license
from mars.model.Constants import ModelConstants from mars.model.Entities import Entity, Location class Field: def __init__(self): self.width = ModelConstants.width self.depth = ModelConstants.depth # Set map up, including crumbs and signal self.crumbs = [[0 for x in range(self.widt...
true
8285e499b2484201e8371f1b1af40eb91cd0f8f6
lkloh/kalman_filter_phil_kim
/extended_kalman_filter/radar_tracking/radar_ekf.py
UTF-8
1,883
3.140625
3
[]
no_license
#!/usr/bin/env python3 import numpy as np import math from numpy.linalg import inv class StateVariables: def __init__(self, x_position, velocity, altitude): self.x_position = x_position self.velocity = velocity self.altitude = altitude class RadarEKF: def __init__(self, A, Q, R): ...
true
3677c7f86233b5cc1cbd71565f8005732e37cf36
Cibirsk/Think_Python
/letters_cartalk_challenge.py
UTF-8
3,205
4.5625
5
[]
no_license
#find words with three consecutive double letters def cartalk1(): fin = open('words2.txt') #open the file for word in fin: i=0 while i < len(word)-1: if word[i]==word[i+1] and word[i+2]==word[i+3] and word[i+4]==word[i+5]: print(word) break ...
true
0b0e2d379c95230c164c3707bcb5f2db2caeb0e9
YuanXianguo/Python-IT-Heima
/数据库/Sqlite/python_sqlite应用.py
UTF-8
1,004
2.828125
3
[]
no_license
from python_sqlite import MySqlite if __name__ == '__main__': db = "E:/Sqlite/test1.db" sqlite = MySqlite(db) sqlite.drop_table("student") sqlite.create_table("create table student(" "id INTEGER PRIMARY KEY AUTOINCREMENT, " "name varchar(20) not null,...
true
40e50d8e18d769fe166012c5fee7542b8b8fb1ce
camerongridley/TherapistRecommender
/src/scraping/scrapy - ignore/goodtherapy_scrapy/pipelines.py
UTF-8
1,726
2.578125
3
[]
no_license
import psycopg2 from sql_queries import SqlQueries # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html class GoodtherapyScrapyPipeline: def __init__(self): self.cr...
true
4adeb5014e931c212bda8030ab8c38362548084a
CCordova88/Python-Projects
/Assignments/encapsulation_assignment.py
UTF-8
330
3.328125
3
[]
no_license
class Protected: def __init__(self): self._protectedVar = 6 self.__privateVar = 13 def getSum(self): obj1 = Protected()._protectedVar obj2 = Protected().__privateVar varSum = obj1 + obj2 print("{} + {} = {}".format(obj1,obj2,varSum)) Protected().getSum() ...
true
f8291ceb749801197eeb734c97b0afb4d9eecd39
AKZMH/Python_Algos
/Урок 2. Практическое задание/task_6/task_6_1.py
UTF-8
1,308
4.28125
4
[]
no_license
""" 6. В программе генерируется случайное целое число от 0 до 100. Пользователь должен его отгадать не более чем за 10 попыток. После каждой неудачной попытки должно сообщаться больше или меньше введенное пользователем число, чем то, что загадано. Если за 10 попыток число не отгадано, то вывести загаданное число. ЗДЕС...
true
2a4e458a13129dc91f4bb15e8a9c3060f097bb35
BinitaPathak/Python_Bootcamp
/hangmanlive.py
UTF-8
4,747
4.03125
4
[]
no_license
# ==================================================================================================================== # -------------------------------------------- Project Assignment-2--------------------------------------------------- # ================================================================================...
true
b0e6a61c530f8401f1b415dddaada06ddd0f6aaa
rvpatel92/Parser-Project
/PythonParser/LexicalAnalyzer2.py
UTF-8
4,391
3.53125
4
[]
no_license
__author__ = 'ravipatel' from LexicalException import LexicalException from TokenType import TokenType from Token import Token class LexicalAnalyzer2(object): tokenList = [] def __init__(self, filename): if filename is None: raise LexicalException("file is invalid") file = open(...
true
db399f0a6f86846aac9452c845161dd9e3d21203
sppliyong/day01
/day02/mysuiji.py
UTF-8
317
2.859375
3
[]
no_license
import random if __name__ == '__main__': # mlist =[random.randint(1,100) for i in range(0,10)] # # # print(mlist) #列表的复制 nlist=[1,2,3] mlist=nlist[:] nlist[0]=3 print("nlist={0}".format(nlist)) print("mlist={0}".format(mlist)) #赋值是传指的过程 #复制数是传值的过程
true
1ae3f5ee809c0ee1af53e8991e599a39e80e16e5
alyssadev/precisionapi
/precisionapi/models/arena.py
UTF-8
523
2.59375
3
[]
no_license
import attr from .enums import Realm from .precision import PrecisionRealmObject @attr.s class ArenaTeam(PrecisionRealmObject): type: int = attr.ib() name: str = attr.ib() def __repr__(self): return "ArenaTeam(type={0}x{0}, name={1}".format(self.type, self.name) @staticmethod def from_se...
true
283195210f3978350d437e68b959ed87c0da02a8
YMSPython/Degiskenler
/Lesson3/Ornek5.py
UTF-8
391
2.78125
3
[]
no_license
username = input("Kullanıcı Adınızı Giriniz : ") password = input("Şifrenizi Giriniz : ") if (username == "admin" or username == "admin@admin.com") and (password == "123" or password == "1234"): print("Giriş yaptınız!") else: print("Kullanıcı bilgilerinizi kontrol ediniz!") if(username == "{}.{}".format("mura...
true
83fd3883a4bcd8fb56d7f848aef9183e4ce20f67
CUL-DigitalServices/timetable-3
/app/scripts/stats/userstats/utils.py
UTF-8
929
3.75
4
[]
no_license
import itertools import operator def ilen(seq): """ Return the number of items in an iterator or iterable. """ if hasattr(seq, "__len__"): return len(seq) try: return max(i for i, _ in enumerate(seq)) + 1 except ValueError: return 0 def window(seq, n=2): iters = [ ...
true
14d8ceeef4c6c507d7b33d8bf5dfbb54379a7d68
amcmorl/motorlab
/tuning/display/position_plot.py
UTF-8
5,472
2.75
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Mar 25 12:57:44 2011 @author: amcmorl """ import numpy as np import matplotlib.pyplot as plt #from matplotlib.gridspec import GridSpec, GridSpecFromSubplotSpec from warnings import warn import plot_tools as ptl def minmax(arr, axis=0): return np.concatenate([np.min(arr, ...
true
a8e71720a7125a6edeca2ef61c838c3fc96706bb
noeoeh/AI4
/AI4_cnn_image_classification.py
UTF-8
10,147
2.75
3
[]
no_license
import os import sys import numpy as np from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Dense, Flatten, Conv2D, Dropout, MaxPooling2D, ZeroPadding2D from keras import optimizers import tensorflow as tf import matplotlib.pyplot as plt from matplotli...
true
c73f39863db772bcce430fc9974a2d272c30a8aa
chris-miklas/Python
/Lab02/parser.py
UTF-8
345
3.28125
3
[]
no_license
#! /usr/bin/env python3 """ URL parser """ import sys def parse(path): tokens = path.split("/") suffixes = tokens[-1].split(".") for token in tokens[:-1]: print(token) for suff in suffixes: print(suff) if __name__ == "__main__": if len(sys.argv) == 2: parse(sys.argv[1]) ...
true
0de6327340bf4c0ebc0c6f235f8eae722079855b
Akramium/quizGame
/main.py
UTF-8
521
3.25
3
[]
no_license
from data import question_data from question_model import Question from quiz_brain import QuizzBrain question_bank = [] for question in question_data: q_text = question["question"] q_answer = question["correct_answer"] new_question = Question(q_text=q_text, q_answer=q_answer) question_bank.append(new_q...
true
fe96730554042485f8fdff08255009fc99b7bee1
ejsuarez793/food-api
/app/dao/recipes_dao.py
UTF-8
1,176
2.546875
3
[]
no_license
import logging from app import db log = logging.getLogger(__name__) COLUMNS = ['id', 'name', 'veggie_friendly', 'meal_type', 'cook_time', 'wash_time', 'cook_technique', 'info', 'steps'] QUERY = "SELECT {columns} FROM recipe WHERE id in(SELECT id FROM unnest(meal_type) mt WHERE mt in ({meals_type}))"; QUERY_VEGGIE_ONL...
true
011f78d6f2017682ef72343797dacb90840ee19e
Aasthaengg/IBMdataset
/Python_codes/p02314/s967652203.py
UTF-8
270
2.640625
3
[]
no_license
n, m = map(int, raw_input().split()) c = map(int, raw_input().split()) t = [float('inf') for i in range(n+1)] t[0] = 0 for i in range(m): if c[i] > n: break else: for j in range(c[i], n+1): t[j] = min([t[j], t[j-c[i]]+1]) print t[n]
true
d9eb42769be7a97016405a673664510d4e243a11
AdamZhouSE/pythonHomework
/Code/CodeRecords/2211/60782/311233.py
UTF-8
606
2.734375
3
[]
no_license
line1 = list(map(int, input().split(" "))) s = "" for i in range(line1[0] + line1[1]): s += input() if s == 'S 0Y 1R 2E 3N 4E 5A 6D 7Y 7R 9RYENSAY': print(2) print(2) print(1) print(1) print(0) exit() if s == 'E 0E 1E 2E 3E 4E 5EEEEEEE': print(0) exit() if s == 'K 0K': print(1) ...
true
7f814d16f562ea9eb6a2c1abd79f36b20050612c
andrewgait/advent_of_code
/adventofcode2020/advent6/advent6.py
UTF-8
1,949
3.859375
4
[]
no_license
# Advent of code, day 6 from collections import OrderedDict # open file input = open("advent6_input.txt", "r") # input = open("advent6_test_input.txt", "r") input_array = [] # read string into array for line in input: input_array.append(line) def create_array(input_array): # full array of all answers an...
true
7501cfcc4e26f1e7902333b615fb066020dbeb6b
daiit0578/Hello-Python
/python-basic/OOP-Python.py
UTF-8
404
3.046875
3
[]
no_license
class Superman: strength = 50 def __init__(self, name,weapon,clothes): self.name = name self.weapon = weapon self.clothes = clothes def __str__(self): return 'day la {} su dung {}'.format(self.name,self.clothes) def __repr__(self): return 'hello superman' superman...
true
ada878561ff31d48240b607d06c656a78e9deaa3
REXJJ/useful-codes
/Wrinkle_Detection/test_sub.py
UTF-8
1,554
2.828125
3
[]
no_license
import cv2 import numpy as np img = cv2.imread('/home/rex/Desktop/Images/base.png') img_ref = cv2.imread('/home/rex/Desktop/Images/wrinkled.png') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray_ref = cv2.cvtColor(img_ref, cv2.COLOR_BGR2GRAY) kernel = np.ones((2,2),np.uint8) #prewitt kernelx = np.array([[1,1,1],[0,...
true
59b0f74f0c618b79d1f88d224cbd77596cecc0f6
steph-meyering/DSandAlgorithms
/leetcode/1769.py
UTF-8
325
2.859375
3
[]
no_license
class Solution: def minOperations(self, boxes: str) -> List[int]: res = [0 for _ in range(len(boxes))] ball_indices = [i for i, char in enumerate(boxes) if char == "1"] for i in range(len(boxes)): for ball_i in ball_indices: res[i] += abs(ball_i - i) retur...
true
6e493662a5a2b6e9e947ead9ba5616dec598bbdc
yoraish/meme_net_titles_scrape
/xy_train_test.py
UTF-8
2,180
3.125
3
[]
no_license
# this script is used to convert the json object all_scrape_data.json to x_train x_test, y_train... etc # computing correct classes scores and dividing data to two groups import json from math import log import matplotlib.pyplot as plt import numpy as np import os def vis(dict, heading): plt.figure(0) lst = s...
true
3b1cbf70cf70f93bb270294793a7ba5b0d13930c
Torath/qrscanner_api
/api.py
UTF-8
1,222
2.515625
3
[]
no_license
# -*- coding: utf-8 -*- import cv2 from pyzbar.pyzbar import decode from flask import Flask from flask import request from flask_cors import CORS from flask_restful import Resource, Api, reqparse from werkzeug.exceptions import BadRequest import numpy as np app = Flask(__name__) api = Api(app) CORS(app) parser = reqpa...
true
a38ae7fbcf62b7a7e918ed0d5a0d6b245e287ce5
webclinic017/UsefulExamples
/words_in_grid.py
UTF-8
866
2.828125
3
[]
no_license
words = {'hook', 'hope', 'shoe', 'hoe', 'hop'} grid = ['hop', 'hoe', 'skx'] def check_if_word(so_far): if so_far in words: print(so_far, ' word found') def find(idx1, idx2, so_far, visited_idxs): if (idx1, idx2) in visited_idxs: return visited_idxs.add((idx1,idx2)) so_far = so_far + g...
true
774768953529e0cb041a7009667f6230ff4fad00
gouarin/formation_python2017
/nbody/python/nbody/barnes_hut_array/quadTree.py
UTF-8
6,349
2.671875
3
[]
no_license
import numpy as np from ..forces import force class quadArray: def __init__(self, bmin, bmax, size): self.nbodies = size self.child = -np.ones(4*(2*size+1), dtype=np.int32) self.bmin = np.asarray(bmin) self.bmax = np.asarray(bmax) self.center = .5*(self.bmin + self.bmax) ...
true
5c1f47c22fda4516b79ba8022460563fe986c836
xkortex/pstruct
/pstruct/core.py
UTF-8
2,604
3.28125
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env python # -*- coding: utf-8 -*- from collections import Mapping from pstruct.validity import is_invalid_key, InvalidKeyName class Pstruct(dict): """ A dict-compatible data structure with attributes defined by slots. """ __slots__ = ["_pstruct"] def __init__(self, *args, **kwargs): ...
true
97af3dc6a8909a6118174e93c6a15331b53111a6
zc-cris/python_demo01
/进阶02_函数进阶/demo02_函数嵌套.py
UTF-8
1,257
4.125
4
[]
no_license
# _Author: zc-cris # 函数的嵌套调用 def max_two_number(a, b): return a if a > b else b print(max_two_number(1, 4)) def max_three_number(a, b, c): d = max_two_number(a, b) return max_two_number(d, c) print(max_three_number(3, 1, 9)) a = 1 def outer(): a = 2 def inner(): # def 只定义函数,不执行 a...
true
c31b3cbc178dadc1039dba45c844687824a03327
wentilin/algorithms-study
/python/jianzhi/矩形覆盖.py
UTF-8
957
3.84375
4
[]
no_license
""" 题目描述 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法? 比如n=3时,2*3的矩形块有3种覆盖方法: https://www.nowcoder.com/practice/72a5a919508a4251859fb2cfb987a0e6?tpId=13&&tqId=11163&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking """ # -*- coding:utf-8 -*- class Solution: # 方法: 记忆性递归 f...
true
5866dc763b272709626d5c16c975d15aca4d4eba
albertkklam/simpleinterpreter
/postfix_translator.py
UTF-8
1,295
2.984375
3
[]
no_license
from spi import Lexer, Parser, NodeVisitor INTEGER, PLUS, MINUS, MULTIPLY, DIVIDE, LPAREN, RPAREN, EOF = \ "INTEGER", "PLUS", "MINUS", "MULTIPLY", "DIVIDE", "LPAREN", "RPAREN", "EOF" class Interpreter(NodeVisitor): def __init__(self, parser): self.parser = parser def visit_BinOp(self, node): ...
true
da8e930818ed3fd0db7b83bd0fb76f3dc1f4b31b
priyanshbalyan/wallbreakers-challenges
/week-5/is-graph-bipartite/is-graph-bipartite.py
UTF-8
596
3.125
3
[]
no_license
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: colors = [0 for i in graph] for i in range(len(graph)): if colors[i] == 0 and not self.dfs(i, graph, colors, 1): return False return True def dfs(self, i, graph, colors, c...
true
5151edf8faf1f180b89171aefefa0b11fc46de70
blacktiger141/game.py
/main.py
UTF-8
608
4.21875
4
[]
no_license
# You can edit this code and run it right here in the browser! # First we'll import some turtles and shapes: from turtle import * from shapes import * # Create a turtle named Tommy: tommy = Turtle() tommy.shape("turtle") tommy.speed(7) # Draw three circles: draw_circle(tommy, "black", 50, 25, 0) draw_circle(tommy, "...
true
1688fdf5ec8e90f6f1ee0c6971691c1872b23e79
GunnerLab/Stable-MCCE
/bin/getpdb
UTF-8
1,130
2.59375
3
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
#!/usr/bin/env python ######################################################################## # getpdb # # Junjun Mao, July 27, 2020 # # # #####...
true
aa67b6e4bd6e345cb168bdbadba8bcc80f44c3aa
alainGonzalez-11/ADCS
/Python/Attitude_representation/MRP.py
UTF-8
3,501
2.875
3
[]
no_license
import numpy as np from math import sqrt, pi, tan, sin, cos import basic_operators as bo import Quaternions def get_dcm(sigmas): if not (sigmas.shape == (3, 1)): print("Error. Modified Rodrigues Parameters' vector must be of shape (3, 1)") return -1 st = bo.tilde(sigmas) c = np.identity(3)...
true
2d5328f2cb022e94462b8915b082af26c53611ec
milllee/others_spider
/program_test2.py
UTF-8
777
3.265625
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Filename: program_test2.py # Create Time: 2017年04月13日 星期四 18时12分43秒 # Author: Miller Lee # Email: 252343465@qq.com # ############################################## import threading, time def get_page(): print('thread {} is running...'.format(threading.current_threa...
true
6b1498871dd0fe395bf32550cb1e37f8893eb8a9
rdguerrerom/DFTBaby
/DFTB/optimize_neb_g09.py
UTF-8
20,392
2.671875
3
[]
no_license
#!/usr/bin/env python """ Optimize a reaction path using the nudged elastic band algorithm. An electronic structure method implemented in Gaussian 09 is used to drive the calculation. Nudged elastic band (NEB) method for finding minimum energy paths (MEP) and saddle points. Implementation based on "Improved tang...
true
ae8f8a07a9f519a563618bf966778da61621f5e0
lekshmi12340/python-programs
/area of a square using class.py
UTF-8
241
3.765625
4
[]
no_license
class square: def __init__(self,side): self.side = side def areasq(self): return self.side ** 2 a=int(input("Enter the length of the side of square")) obj=square(a) print("The area of the square is",obj.areasq())
true
8d5c6964f92a3541f5eaf6d1f49bf8e9fb4c20ed
cnoott/getemails
/getemails/spiders/sorting/houzz_sorter.py
UTF-8
927
2.71875
3
[]
no_license
import csv mainfile = open('main_houzz.csv','r') emailfile = open('output_emails1.csv','r') output_file = open('sorted_output.csv','w') mainreader = csv.reader(mainfile) emailreader = csv.reader(emailfile) ''' for row0 in emailreader: email_domain = row0[1].split(';') for email in email_domain: if em...
true
1b89f08bf77b8c5ff6ed651296e408aeede62e61
MarioMarinDev/PythonCourse
/testing/rpg/database_manager.py
UTF-8
915
3.328125
3
[]
no_license
import json import os from rpg.character import Character class DatabaseManager: def __init__(self): self.party = self.load_party() def load_party(self): party = [] members_data = self.load_file("party.json") for member in members_data: party.append(Character(memb...
true
57746d567ec1f731c7e1fb4c6140859e5b1f4def
rahulkaplesh/PenetrationTestingScripts
/scripts/passwdCracking/hasher.py
UTF-8
918
3.390625
3
[]
no_license
#!/usr/bin/python3 import hashlib from termcolor import colored def main(): hashValue = input(colored('[*] Enter a string to hash : ', 'yellow')) hashObj1 = hashlib.md5() hashObj1.update(hashValue.encode()) print(colored('MD5 Hash value is : ' + hashObj1.hexdigest(), 'green')) hashObj2 = hashlib.sha...
true
2353133141027af6d8b04fd5d4b033ec7d26eadf
CharlesJ10/Virtual-Assistant
/virtual_assistant.py
UTF-8
8,875
3.265625
3
[]
no_license
# Description: This is a virtual assistant program that will greet you with a random greeting, get the date, # time, retrieve information from wikipedia, open videos on Youtube and read the latest news. # Import the libraries import speech_recognition as sr import os from gtts import gTTS from selenium impo...
true
d20e6c4135306b1a01fdea0bbb7a633f145c162d
YPatschke/MachineLearning
/Final/Codes/RandomGenerator.py
UTF-8
2,172
2.609375
3
[]
no_license
from __future__ import print_function import random import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import loadData as ld import split as sp import data_iterator as di # Random Generator def runRandomGenerator(model, stepToGenerate, user_to_test, input, output, train_size, timestep, path)...
true
c9ef142703516cd6833cf575c6d40930e810c53c
sand9888/logging
/basic_config.py
UTF-8
478
2.78125
3
[]
no_license
import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(levelname)s:%(name)s:%(message)s') file_handler = logging.FileHandler('logs/cff.log') file_handler.setFormatter(formatter) logger.addHandler(file_handler) # code here def divide(x, y): """Divide ...
true
f5cfdf2193bd06fa5c4ff95a486d32df2708fbe7
kiudee/cs-ranking
/csrank/objectranking/object_ranker.py
UTF-8
2,677
2.921875
3
[ "Apache-2.0" ]
permissive
from abc import ABCMeta from csrank.constants import OBJECT_RANKING from csrank.learner import SkorchInstanceEstimator from csrank.numpy_util import scores_to_rankings from csrank.rank_losses import HingedRankLoss __all__ = ["ObjectRanker", "SkorchObjectRanker"] class ObjectRanker(metaclass=ABCMeta): @property ...
true
48810cc2796a510da69b534e15d1f4f1470a8397
mycomath/First-Code-Upload
/Menu.py
UTF-8
1,291
4
4
[]
no_license
print "\nWelcome to Old-Mart. We have a fine selection of video games." ans = True while ans: print (""" 1. Zelda - 10.00$ 2. Sonic - 8.99$ 3. Mario - 15.00$ 4. Asteroids - 2.00$ 5. Exit Menu """) ans = raw_input("Which game would you like to purchase? ") if ans == "1": print "You are purchasing ...
true
bb3474ce59b719f1cf71927dc6c86926e3f9b09a
aes/python-poke
/poke_test.py
UTF-8
456
2.671875
3
[ "Artistic-1.0", "Artistic-1.0-Perl" ]
permissive
import unittest import poke class TestPoke(unittest.TestCase): def test_string_peek(self): s = 'rather_unlikely' q = poke.peek(id(s), 128) assert s in q def test_string(self): s = 'rather_unlikely' q = poke.peek(id(s), 128) i = q.find(s) assert i >= 0 ...
true
1f67204cab113f2dfcf3354dc412065cb7e7c73a
Jananisathya/jananisathya
/janu6.py
UTF-8
270
3.046875
3
[]
no_license
#j list11=['I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII','XIII','XIV','XV','XVI','XVII','XVIII','XIX','XX'] list21=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] w=str(input()) for i in range(20): if(w==list11[i]): print(list21[i]) break
true
a937ed8f58ca5a80511ace8a9d2476071e8330f5
NiharikaRajaram/Batch_24
/google_image_download.py
UTF-8
393
2.78125
3
[]
no_license
from google_images_download import google_images_download #importing the library response = google_images_download.googleimagesdownload() #class instantiation for i in range(len(topics)): arguments = {"keywords":"topics[i]","limit":20,"print_urls":True} #creating list of arguments paths = response.downl...
true
0ebe28e7a8f828a6aad8705e107785ec8fbcb803
Kalpavrikshika/python_modules
/numpy_swap.py
UTF-8
195
3.546875
4
[ "Apache-2.0" ]
permissive
import numpy as numpy a = numpy.arange(8).reshape(2,2,2) print ('The original array:') print(a) print('\n') print('The array after applying the swapaxes function:') print(numpy.swapaxes(a,2,0))
true
6f80cd1ea21778ba29e707603a597bafb4ce2568
capac/python-exercises
/various/cricket.py
UTF-8
667
3.65625
4
[ "MIT" ]
permissive
from random import choice from sys import exit options = ["It's a four!!!'", "What a corker!", "OUT!!!", "You are at silly mid off!", "My dear old thing, it's the end of the Over!'", "You could have hit that with a rhubarb stick!!"] def playing_the_ashes(): counter = 1 print("""You are at Lord's, choose a num...
true
31bdbd7a83fd093e67b739763defc83f1d614a13
kaphc/CS5540_Principles_Of_Big_Data
/Phase2/Logger.py
UTF-8
625
2.71875
3
[]
no_license
import logging class LoggerFile: @staticmethod def set_logger_file(log_name, log_file_name): logger = logging.getLogger(log_name) logging.getLogger().setLevel(logging.INFO) file_log_handler = logging.FileHandler(log_file_name) logger.addHandler(file_log_handler) stder...
true
7bde4a1e068ffba3496674efa42f6328c9e5ec08
MadsArnlov/P3_Dynamic_Systems
/eigenvalue_experiments.py
UTF-8
5,000
3.125
3
[]
no_license
""" Created for P3-Project -- Aalborg University Authors: MATTEK 4.211 """ import numpy as np from scipy import signal from matplotlib import pyplot as plt # ============================================================================= # Constants # ==================================================================...
true
f020826c02439274c1cfcbb0c6419d85241d8120
shyamrayaprolu/pypette
/pypette/jobs.py
UTF-8
2,793
3.53125
4
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- """ jobs.api ~~~~~~~~ Class definitions to describe python method calls in a deterministic way. Description: Method outputs are determined by the inputs provided to it, hence to describe all aspects of the method call we need to know what method is being called and what arguments it is called ...
true
835bb9fcab68ded3932fc02c42b1f9c2c0d6ac01
lorosanu/ccquery
/ccquery/spelling/eval.py
UTF-8
3,778
2.5625
3
[ "MIT" ]
permissive
import logging from ccquery.error import DataError from ccquery.utils import io_utils from ccquery.data import json_controller class Evaluation: """ Evaluate the performance of the automatic spelling correction Consider the case of - |Q| input queries - each query q has multiple candidate correcti...
true
cb073cedc22bd196547742baa21c890252348375
abakan-zz/napi
/napi/magics.py
UTF-8
3,653
2.625
3
[ "MIT" ]
permissive
from IPython.core.magic import Magics, magics_class, line_magic from IPython import get_ipython from .transformers import LazyTransformer __all__ = ['NapiMagics'] STATES = {'off': False, '0': False, 'false': False, 'on': True, '1': True, 'true': True} @magics_class class NapiMagics(Magics): """Magic ...
true
26ca79cf7a01b5c2141e368797680cde9ae3ef42
jerryneal/TradeChart
/test3.py
UTF-8
115
2.53125
3
[]
no_license
def classic(): val = 1 em = 2 return val, em if __name__ == '__main__': print classic()[0]
true
25a60a3ef637a76d16b087d0ec112dd839a85ced
AreteMed/meditrina_challenges
/scheduling_automation/morvarid.py
UTF-8
1,670
3.03125
3
[]
no_license
# -*- coding: utf-8 -*- from __future__ import division from datetime import datetime, timedelta class PrescriptionScheule(object): """ Your defined schedule for a prescription """ name = "" daily = None weekly = None monthly = None def get_schedule_suggestions(prescription_schedule, las...
true
899ac37f1b36bf04c027eaf8d66f921dca75dcba
6gav/FinalProject
/client/tests/Tools/Bots.py
UTF-8
843
3
3
[]
no_license
from selenium import webdriver from selenium.webdriver.common.keys import Keys from os import path import time class Navigator: def __init__(self): print("Navigator") self.browser = webdriver.Chrome(executable_path=path.dirname(__file__)+'./chromedriver.exe') print("Ready.") def loadPa...
true
09fe7bb532df31bd5e86da224d016357fc58b8db
quanpower/xielaoban-server
/app/models/inventory/tag.py
UTF-8
980
2.53125
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- from application.extensions import db from configs.enum import TAG_TYPES __all__ = ['Tag'] class Tag(db.Document): meta = { 'db_alias': 'inventory_db', 'indexes': ['en'] } en = db.StringField(required=True, unique=True) cn = db.StringField() kind = db.Stri...
true
53dfbbeb278fafde5c56ed1ad0a4dae99fd2d2e3
ysnodbs/playground
/lab01/lab1.py
UTF-8
203
3.375
3
[]
no_license
def square(x): return x*x def fibs(x): a,b =0,1 for i in range(x): print("fib(", i,")=",a) a,b=b,a+b print("test branch to see difference")
true
a343e62df1eee5fdfae02e321d0da3bf1b0672e3
fatima72/raniai
/09-07/detectfloat.py
UTF-8
465
4.09375
4
[]
no_license
""" Validate float Conditions: Number can start with +, - or . symbol. Number must contain at least 1 decimal value. Number must have exactly one . symbol. No exception while using float(N) on it """ import re def validate(s): pattern = re.compile(r'^[+-.]?(\d)(\.\d)?$') matches = pattern.match(s) if (m...
true
ef0f1729949118088a10d8ab40a0645713514696
giannisdaras/codejam2018
/qualification/attempts/gopher.py
UTF-8
2,075
2.84375
3
[]
no_license
import sys T=int(input()) for i in range(T): A=int(input()) grid = [[0 for i in range(1002)] for j in range(1002)] grid[0]=[-1 for i in range(1002)] grid[1001]=[-1 for i in range(1002)] flag=True; sys.stdout.flush() print("{} {}".format(500,500)) sys.stdout.flush() last_cell=[500,500] def find_common_neighbo...
true
648c9c4d178c7516ed960af516adb2adc5f9f7a6
kwan2004/pointcloud-benchmark
/python/pointcloud/run/queries/generate_queries_xml.py
UTF-8
2,149
2.609375
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env python ################################################################################ # Created by Oscar Martinez # # o.rubi@esciencecenter.nl # #######################################################...
true
d057f3ac37e06a7e2dbb07f5eb689930d50864ef
Engineer1999/Double-Deep-Q-Learning-for-Resource-Allocation
/Environment.py
UTF-8
43,462
2.515625
3
[]
no_license
from __future__ import division import numpy as np import time import random import math # This file is revised for more precise and concise expression. class V2Vchannels: # Simulator of the V2V Channels def __init__(self, n_Veh, n_RB): self.t = 0 self.h_bs = 1.5 self.h_ms ...
true
916d423ea015b03b28617a5196cca3dab5bcc388
pharmbio/big-data_deeplearning
/Labs/cnn_helper.py
UTF-8
2,991
2.84375
3
[]
no_license
import numpy as np from collections import Counter def getClassSizes(generator): counter = Counter(generator.classes) max_val = float(max(counter.values())) class_sizes = {class_id: num_images for class_id, num_images in counter.items()} return class_sizes def getClassWeights(generator): counter =...
true
e9e70ea2e1b133ae75f14f94d98a46c9eeef1c47
alexander-turner/PyPlan
/agents/bandits/uniform_bandit.py
UTF-8
361
2.734375
3
[]
no_license
from abstract import abstract_bandit class UniformBandit(abstract_bandit.AbstractBandit): """Pulls each arm an approximately equal number of times (difference is at most 1).""" name = "Uniform Bandit" def select_pull_arm(self): """Returns the arm that has been pulled the fewest number of times.""...
true
b1d8a442777914353e6e43d83980d40b7e60be23
jadelyn/cs168-proj1
/project1/dv_router.py
UTF-8
6,441
2.78125
3
[]
no_license
from sim.api import * from sim.basics import * ''' Create your distance vector router in this file. ''' class DVRouter (Entity): def __init__(self): self.routing_table = {} # self or neighbor to distance vector (destination to distance) self.routing_table[self] = {self:0} self.neighbor_port...
true
e905eef42b3197eb100e3916d2883f863256233d
cnlinxi/deep_learning_practice
/practise_of_google_tensorflow/word2vec/word2vec.py
UTF-8
7,572
2.578125
3
[]
no_license
# -*- coding: utf-8 -*- # @Time : 2018/10/21 19:30 # @Author : MengnanChen # @FileName: word2vec.py # @Software: PyCharm import os import collections import math import zipfile import random import urllib import numpy as np from sklearn.manifold import TSNE import matplotlib.pyplot as plt import tensorflow as tf ...
true
6b7d804ef7130681a88ba80a864d54b27fd4859c
charlie-boy/python
/pygame/test.py
UTF-8
706
2.953125
3
[]
no_license
import pygame pygame.init() screen = pygame.display.set_mode((400,300)) done = False is_blue = True x = 30 y = 30 clock = pygame.time.Clock() while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.KEYDOWN and event.key ==pygame.K_SPACE: is_blue ...
true
8e6b68650fb001fb8c8d5ad38766e0e078d1c903
ptqatester1/ptqa
/trunk/workspace/Squish/src/API/MenuBar/Extensions/Environment/Environment.py
UTF-8
9,480
2.640625
3
[]
no_license
#************************************************************************** #@author: Chris Allen #@summary: Holds methods related to the environment manager #************************************************************************** from API.MenuBar.Extensions.Environment.EnvironmentConst import EnvironmentConst from...
true
0e72182c2fba05394ffd0810ea30927bf0f06608
JulyKikuAkita/PythonPrac
/cs15211/FlipEquivalentBinaryTrees.py
UTF-8
3,831
4.125
4
[ "Apache-2.0" ]
permissive
__source__ = 'https://leetcode.com/problems/flip-equivalent-binary-trees/' # Time: O(N1 + N2) where N1, N2 are the lengths of root1 and root2. # Space: O(N1 + N2) # # Description: Leetcode # 951. Flip Equivalent Binary Trees # # For a binary tree T, we can define a flip operation as follows: # choose any node, and swa...
true
5c59017d2e9f6c3826b40fcf47f3afede30cd8b0
Emna491/Deploying-a-ML-Model-on-Heroku-with-FastAPI
/src/app/api.py
UTF-8
1,592
2.546875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
""" Author: Ibrahim Sherif Date: October, 2021 This script holds the fastapi and routing functions """ import os import yaml import joblib import numpy as np import pandas as pd from fastapi import FastAPI, Body from config import MODEL_DIR, EXAMPLES_DIR from app.schemas import Person, FeatureInfo if...
true
2bb37e9c29886286a1a238244cb0a82e309159b0
571730/MAT102
/Regression/regression.py
UTF-8
2,134
3.6875
4
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Sep 30 11:02:27 2016 @author: jev """ from __future__ import division import numpy as np import scipy.linalg as sl # [a,b] = linearRegression(x,y) computes a and b such that y = ax+b is the least squares # approximation line to the points (x(i),y(i)). # x and y must be tabl...
true
2424e5bae9bc55013cab2f3f2b07cdb0c42e2431
Kvikikpt/pepeo_telegram_bot
/final.py
UTF-8
907
2.765625
3
[]
no_license
from PIL import Image import random def photo_select(): i = random.randint(1, 15) b = random.randint(16, 22) im1 = Image.open(f'cuted/firstpart/{i}.jpg') im2 = Image.open(f'cuted/secondpart/{b}.jpg') width = im2.width + im1.width final = Image.new(mode = "RGB", size = (width, 150), color = (255...
true
fc2da5dee4db5d4671128b4bf91a38820481f783
b0nedev/sns-crawler
/model/scraphistory.py
UTF-8
2,956
2.921875
3
[]
no_license
""" - ScrapHistory class - scrap_data model class - id: ordering - scrap_id: scrap_data number - key_id: keyword id - crw_id: crawler id - created_at: crawler created date """ from datetime import datetime from pymongo import MongoClient from lib.debug import print_exception_info class ScrapHistory(object): ...
true
c22bf9ce46dc65483354ec9d0fa2308d9e94590f
0ffkilter/JerryBot
/modules/dunce.py
UTF-8
1,268
2.65625
3
[]
no_license
from modules.permissions import * from time import sleep def duncecap(args, perms={}): # Get name and uid of person name = " ".join(args) uid = perms[FN_GET_UID](name) # Get all nicknames in thread nicknames = perms[THREAD_NICKNAMES](perms[MESSAGE_THREADID]) # Check that no one is currently...
true
2282cc186a45ab783b47bacce20ef47c529745a8
bkbhanu/mytrypy2
/PythonApplication1.py
UTF-8
697
3.21875
3
[]
no_license
## --- internet access import os import urllib #from urllib.request import urlopen url="http://www."+ input("Enter the URL you need the Title for: ") tagtype=input("What Tag do you want to search for:") tagS= "<"+tagtype tagF= "</"+tagtype btagS=tagS.encode('utf-8') btagF=tagF.encode('utf-8') Resp = urlo...
true
682a1f8533a8e606903946a39260f24f5b8fa259
kkthecompguy/30DaysOfPython
/themoviedb/connect.py
UTF-8
1,706
2.75
3
[]
no_license
import os import requests import pandas as pd api_key_v3 = '32dfea6359b57a648549c4baad6707cf' api_key_v4 ='eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIzMmRmZWE2MzU5YjU3YTY0ODU0OWM0YmFhZDY3MDdjZiIsInN1YiI6IjVlYTAyMjM5MDdmYWEyMDAxYWZhNGFlMSIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.hT89VlsArMNEKYrBJxr7o2tcD-SA-dXgpNHtJk50m1w...
true
5774aec093a4647d7b6cdb6c012de89ccba58246
vincenttuan/yzu_python_20210414
/day07/ReadFile_Salary2.py
UTF-8
827
4.3125
4
[]
no_license
file = open('salary.txt', 'r', encoding='UTF-8') rows = file.readlines() # 進行資料結構化的整理 #[ {'name': John, 'salary':45000}, {'name': Mary, 'salary':55000} ... ] employees = [] for row in rows: data = row.split(',') name = data[0] # 員工姓名 salary = int(data[1].strip('\n')) # 員工薪資 employee = {'name': name, 'sa...
true
8b8ed6f6a48231bf5802f1972904c4478c04d896
pombreda/pyamg
/Examples/VisualizingAggregation/demo1.py
UTF-8
1,224
2.546875
3
[ "BSD-3-Clause" ]
permissive
# 2D example of viewing aggregates from SA using VTK from pyamg.aggregation import standard_aggregation from pyamg.vis import vis_coarse, vtk_writer from pyamg.gallery import load_example # retrieve the problem data = load_example('unit_square') A = data['A'].tocsr() V = data['vertices'] E2V = data['elements'] # perf...
true