blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
133
path
stringlengths
2
333
src_encoding
stringclasses
30 values
length_bytes
int64
18
5.47M
score
float64
2.52
5.81
int_score
int64
3
5
detected_licenses
listlengths
0
67
license_type
stringclasses
2 values
text
stringlengths
12
5.47M
download_success
bool
1 class
4a4ca9e89a1eb02fe6a7e435deb88d16d400d6c7
Python
martony38/Catalog-App
/catalog/models.py
UTF-8
2,558
2.75
3
[]
no_license
#!/usr/bin/env python3 '''Catalog app models.''' from hashlib import sha256 from os import urandom from sqlalchemy import (create_engine, Column, ForeignKey, Integer, String, UniqueConstraint, CheckConstraint) from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import re...
true
bf9ff194e4ce3dfd9d0cca6e808c9996edd98651
Python
dayo1/dayo123
/Class Work Wk 7.py
UTF-8
4,680
3.59375
4
[]
no_license
""" fund = 100000.0 level = input (" Please enter S for Senior, or J for Junior, SH for Sophomore or F for Freshmen: ") CGPA = float(input("Enter your grade: ")) if level == 'S': if CGPA >= 3.5: pay = (0.37 * fund)* 0.15 * CGPA print ( "Your scholarship amount is ", pay) elif CGPA > 2.4 and ...
true
97126e0841c1788db56efa4d2db354e710f0d509
Python
wolf-project/py-xls-auto
/pyGeneratorReport.py
UTF-8
436
3.125
3
[ "MIT" ]
permissive
# Generator Script for excel files # Testing ... import pandas as pd import numpy as np #Ferramenta que cria gráficos após tratar os dados em tabela de um arquivo # import matploitlib.pyplot as plt # Definindo a variável com o arquivo Excel a ser utilizado excel_archive_1 = 'data_science.xlsx' # Definindo a leitu...
true
1d89a9345bc81d99d93a02dad803b52810550352
Python
hwanginbeom/TIL
/algorithms/source/54.greedy.py
UTF-8
234
2.796875
3
[]
no_license
N = int(input()) nums = list(map(int, input().split())) result = 0 late = 0 if N == 1: print(nums[0]) else: nums.sort() for i in range(N): result += (nums[i] + late) late += nums[i] print(result)
true
c8e50826f006168a6e8e29737f2ffc599c0c6981
Python
ktrzcin/list-distance
/tests/test_list_distance.py
UTF-8
2,390
2.828125
3
[]
no_license
import pathlib import unittest from contextlib import contextmanager from unittest.mock import patch from list_distance import calculate_distance PATH: str = pathlib.Path(__file__).parent.absolute() / "fixtures/" @contextmanager def patched_stdin(filename: str) -> None: """ Patch stdin to yield values from ...
true
93afba7f0f9860eaa81042b15298be77b41d701f
Python
Sohamtilekar21/PythonCodeyoung
/RockPaper.py
UTF-8
1,383
3.609375
4
[]
no_license
import random counter=0 while counter==0: a=["paper","scissors","rock"] c=random.randint(0,2) b=a[c] print("Rock Paper Scissors Game") print("Rock beats scissors") print("Scisssors cuts paper") print("Paper covers rock") print("Choose 0 for paper , 1 for scissors and 2 for rock...
true
38c6806e8231374a04762cd484f4378d08c0b202
Python
MaxFunProger/sudoku
/solver.py
UTF-8
4,869
2.828125
3
[]
no_license
from random import randint def initiate(): box.append([0, 1, 2, 9, 10, 11, 18, 19, 20]) box.append([3, 4, 5, 12, 13, 14, 21, 22, 23]) box.append([6, 7, 8, 15, 16, 17, 24, 25, 26]) box.append([27, 28, 29, 36, 37, 38, 45, 46, 47]) box.append([30, 31, 32, 39, 40, 41, 48, 49, 50]) box.append([33, ...
true
f3689827e8cd9bf826720d1b5f903ecd12286f27
Python
Slin/ProjectSteve
/Assets/Sprites/Stevelette/genCharackterSheet.py
UTF-8
549
2.578125
3
[ "MIT" ]
permissive
from PIL import Image as img import os import math files = sorted(filter(lambda str: str[-4:] == ".png" , os.listdir('combo'))) z = float(len(files)) y = math.sqrt(z) * 3. / 4. x = y * 16. / 9. x = int(x) y = int(y) out = img.new('RGBA', (x * 128, y * 128 )) for f in range(4): print ('f: ', f) ...
true
099b430a568574beef1d784585033e093f433645
Python
s031199/Backup
/venv/Log_structure.py
UTF-8
1,285
2.59375
3
[]
no_license
import os, shutil from datetime import datetime import traceback def dateTime(): now = datetime.now() current_time = str(now.strftime("%Y-%m-%d %H:%M:%S:%f")) return current_time def logShowDirectory(): logShowDirectory = dateTime() + " " + os.getcwd() + "\n" return logShowDirectory def logCopyFolder(): now = ...
true
ad564ea297688f1f4213c3b6309cbb80f0f6507f
Python
brookscl/aoc-2020
/day14.py
UTF-8
3,655
3.3125
3
[]
no_license
import itertools import re from enum import Enum, auto class Ops(Enum): MASK = auto() MEM = auto() def load_program(file_name): with open(f"inputs/{file_name}") as f: raw_lines = f.read().strip().split("\n") program = [] for line in raw_lines: op = line[:3] if op == 'mas...
true
3ff53a881e0175080f9c2d21f76be34af988ae2d
Python
buyi823/learn_python
/python_exmple/stopwatch_test.py
UTF-8
711
3.671875
4
[]
no_license
#!/usr/bin/python3 # filename: stopwatch import time print('按下回车开始计时,按下 Ctrl + C 停止计时。') while True: try: input() starttime = time.time() # Python time time() 返回当前时间的时间戳(1970纪元后经过的浮点秒数)。 print('START') while True: print('计时: ', round(time.time() - starttime, 0), ...
true
cf283d65f3cc449c412c602c5bbd3817615e498d
Python
mnuhurr/freqresp
/fr_simple.py
UTF-8
3,600
2.984375
3
[]
no_license
''' simple tool to measure frequency response. generates several sinewaves and measures the maximum amplitude of the response. more sophisticated methods to come. ''' import numpy as np import sounddevice as sd from tqdm import tqdm from common import load_config, find_device_id, crop_signal, generate_frequency_ra...
true
224353e0860a45dc71c62f6d500994427edf0dca
Python
KOSASIH/EMAR-Mini
/Devices/1/Classes/Wheels.py
UTF-8
1,511
2.515625
3
[ "MIT" ]
permissive
############################################################################################ # # Project: Peter Moss COVID-19 AI Research Project # Repository: EMAR Mini, Emergency Assistance Robot # # Author: Adam Milton-Barker (AdamMiltonBarker.com) # Contributors: # Title: EMAR Mini Wheels Cl...
true
ee338a4486e3f6c03c040e27b4628f3f225f1361
Python
stantontcady/www
/where/models.py
UTF-8
8,217
2.578125
3
[]
no_license
from collections import deque from csv import reader as csv_reader from datetime import datetime, timedelta from operator import itemgetter from typing import Iterable from dateutil import parser as date_parser from pandas import concat, read_csv, to_datetime from pint import UnitRegistry from pymodm import EmbeddedM...
true
57f0529583e1ce4ba1dcf16a30bcdd21eb2984fd
Python
JoyceYF/medical-kbqa
/ner_model/evaluate.py
UTF-8
5,344
3.140625
3
[ "Apache-2.0" ]
permissive
# 构建函数评估模型的准确率和召回率, F1值 def evaluate(idx_of_tokens, labels, predict_labels, id2char, id2tag): # idx_of_tokens: 代表待评估 的原始样本,shape=[1,seq_len] # labels: 真实的标签序列,shape=[1,seq_len] # predict_labels: 模型预测出来的标签序列,即best_path_list_up,shape=[1,seq_len] # id2char: 代表数字化映射字典 # id2tag: 代表标签的数字换映射字典 # 初始化真实实...
true
c241f4f1cd7519556fc8e2580550d65629242613
Python
Ramesh-kumar-S/Boring_Scripts
/files.py
UTF-8
166
2.90625
3
[]
no_license
with open("/home/ramesh/Motivation.txt") as file: for line in file: print(line.upper()) #print(file.readline()) #print(file.read()) #file.close()
true
a4e9717f4c9fd7be474dd28093428c1b840e56fc
Python
defseg/PyLaut
/pylaut/utils.py
UTF-8
1,959
3.09375
3
[ "MIT" ]
permissive
from collections.abc import Iterable import itertools def breakat(ls, breaks): slices = [] lastbrk = 0 for brk in breaks: slices.append(ls[lastbrk:brk]) lastbrk = brk slices.append(ls[lastbrk:]) return slices def powerset(iterable): s = list(iterable) return itertools.cha...
true
10497040219e9f511f78683c0a7d33dbcc2ce06a
Python
sammiriche/datacode
/.vscode/exercise12.py
UTF-8
482
3.625
4
[]
no_license
# 一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高? # 反弹高度函数 def height(n): if n == 0: m = 100 else: m = height(n-1)*0.5 return m # 第n次运行距离 def long(height,n): t = height(n-1)*1.5 lista.append(t) return t n = 10 lista =[] for i in range(1,n+1): long(height,i) pri...
true
977118780356e16e3d946bfad7964ea31e0d4240
Python
kamilczerwinski22/Advent-of-Code
/main_files/year_2020/day_1/year2020_day1_part1.py
UTF-8
2,253
4.0625
4
[]
no_license
# --- Day 1: Report Repair --- # # After saving Christmas five years in a row, you've decided to take a vacation at a nice resort on a tropical island. Surely, Christmas will go on without you. # # # # The tropical island has its own currency and is entirely cash-only. The gold coins used there have a little picture of...
true
b67343db812582f4c7d87fc8dd93e1c3656b9ee1
Python
EvanHarvill/python
/bincon.py
UTF-8
213
3.03125
3
[]
no_license
# bincon.py cwc n = int(input("Input an integer less than 256 : ")) # d(dividend) q(quotient) r(remainder) d = 128 q = int(n / d) r = n % d n = q print(q,r) # - - - - d = d / 2 q = int(n / d) r = n % d print(q,r)
true
19077cbfa4c407bac5b60e2f7cab004f7a8191ce
Python
yermandy/face-recognition-workflow
/examples/face_alignment.py
UTF-8
2,018
2.71875
3
[]
no_license
import cv2, time from skimage import transform as trans import numpy as np from detection import detection # define a video capture object capture = cv2.VideoCapture(0) capture.set(cv2.CAP_PROP_FRAME_WIDTH, 200) # capture.set(3, 200) capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 200) # capture.set(4, 200) ret, frame = capt...
true
5bac01af15450d22c14fd4e5bf1458d57c0b3a4f
Python
GitH3ll/eyazis
/l2/lab2.py
UTF-8
4,184
3.0625
3
[]
no_license
from bs4 import BeautifulSoup import time from tkinter import filedialog from tkinter import messagebox from tkinter import * def distance(a, b): """Calculates the Levenshtein distance between a and b.""" n, m = len(a), len(b) if n > m: # Make sure n <= m, to use O(min(n, m)) space ...
true
72783e903df80b03de4c2dda0c04edab8130005a
Python
Youssefares/statshousery
/utils/statsbomb/stats.py
UTF-8
6,690
2.53125
3
[ "MIT" ]
permissive
from collections import defaultdict import pandas as pd def player_90s(substitutions, starting_xis, half_ends): player_90s = defaultdict(lambda: 0) for index, starting_xi in starting_xis.iterrows(): for player in starting_xi.lineup: player_name = player['player']['name'] for period in range(1...
true
434968d15bac2089e7a554684839d0dc48bf0a84
Python
DomoKrch/PP2-uni-
/tsis_6/4.py
UTF-8
65
3.15625
3
[]
no_license
s = input() for i in s[::-1]: print(i, end = '') print('')
true
62e5c78f0e57a0a66a46675858dbf3a6cb0b3240
Python
yprodev/python_ads
/recursion/exponential_iter.py
UTF-8
63
3.46875
3
[]
no_license
def exp(x, n): y = 1 for i in range(n): y *= x return y
true
72d6bb8f14513581d4c899594882ccc1bf15173f
Python
FilSta/Tichu
/gym-tichu/gym_tichu/envs/internals/tichu_state.py
UTF-8
46,587
2.65625
3
[ "MIT" ]
permissive
import abc from collections import namedtuple, OrderedDict from typing import Collection, Optional, Union, Iterable, Tuple, Generator, Set, Dict, List, Any, Callable from profilehooks import timecall import logging import itertools import random from .actions import pass_actions, tichu_actions, no_tichu_actions, pl...
true
5bd1ae30a49ec841348248db428b854f5d78c1bb
Python
wuljchange/interesting_python
/part-struct/unpack-value2.py
UTF-8
472
3.375
3
[ "MIT" ]
permissive
records = [('foo', 1, 2), ('bar', 'hello'), ('foo', 3, 4), ] def drop_first_last(grades): _, *middle, _ = grades return middle def do_foo(x, y): print('foo', x, y) def do_bar(s): print('bar', s) if __name__ == "__main__": for tag, *args in records: pr...
true
b78023ddb171cc09e0a42c25d99816a9f7f19981
Python
RiiVa/Harbor_Simulation
/Main.py
UTF-8
7,663
2.734375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sat Mar 23 16:54:00 2019 @author: RiiVa """ from Math import Math from Events import EventManager from Dock import Tug,Ship,Dock_Harbor_Manager events = {} #LLega un barco al puerto events['ARRIVE'] = 1 #Termina de cargar el barco en el muelle events['LOADING'] = 2 ...
true
dbe7d37970a0accc59143c4211b032c97832b635
Python
mrlesmithjr/terraform-to-ansible
/terraform_to_ansible/parser.py
UTF-8
4,593
2.96875
3
[ "MIT" ]
permissive
"""terraform_to_ansible/parser.py""" import json import logging import os import subprocess import sys class Parser: """Main Terraform tfstate parser.""" def __init__(self, args): """Init a thing.""" # Define dictionary to hold all parsed resources self.all_resources = {} #...
true
2bee69a346974b4ee73d8e7cb1c40d82640ce870
Python
yalun-zheng/QM-MM_model
/rfo_cmp.py
UTF-8
2,284
2.921875
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt #define a loss function def loss(x): return (x/2)**-12-2*(x/2)**-6 def gradient(x): return -12*(x/2)**-13*0.5+12*(x/2)**-7*0.5 #RFO def RFOstep(curr_hess = 1, curr_grad = 0, lr=0): #First build augmented Hessian matrix lastrow = np.append(curr_grad, ...
true
5a2ad9a838f3d7c61effb8172a71abc6a76962cd
Python
Aasthaengg/IBMdataset
/Python_codes/p03779/s457719314.py
UTF-8
76
2.84375
3
[]
no_license
from math import ceil, sqrt X = int(input()) print(ceil((-1+sqrt(1+8*X))/2))
true
347c4e4e97af3a9abc0fa17cff7d6da2b435cb4f
Python
ashiksmd/scripts
/rulesTokenizer.py
UTF-8
1,802
3.234375
3
[]
no_license
import re; scanner = re.Scanner([ (r"\$[A-Za-z_]\w*", lambda scanner, token: ("VARIABLE", token[1:])), (r"\(", lambda scanner, token: ("GROUP_OPEN", token)), (r"\)", lambda scanner, token: ("GROUP_CLOSE", token)), (r"\[", lambda scanner, token: ("SQ_GROUP_OPEN", token)), (r"\]", lambda scanner, tok...
true
8e165091e3907f0e4dc4b8b9396b0f57a7d5bc6c
Python
Nick-Zhang1996/spinvtol
/dummyController.py
UTF-8
506
2.640625
3
[]
no_license
# sample controller # vicon_list: list of 5 previous vicon states (3 element tuple) # [(x,y,z,rx,ry,rz),(x,y,z ....] # Return: # thrust_N, flap_rad def expControl(vicon_list): state1 = vicon_list[0] return (3000,0.1) def cvt2pwm(thrust_N,flap_rad,voltage): # from fittravel.py flapP...
true
1628a8b1a4f5206a528c10f236419d13f1e8493c
Python
naomijub/progressoes-python
/aritimetica.py
UTF-8
225
3.5
4
[]
no_license
#!/usr/bin/python3 def sum(a1, step, n): sum = 0 for i in range(n): sum += a1 + (step * i) return sum def nvalue(a1, step, n): return a1 + ((n - 1) * step) print(nvalue(1,1,10)) print(sum(1,1,10))
true
828573824a537aed722072362e950ffea2a64752
Python
banya100/temp_project
/temp.py
UTF-8
558
3.484375
3
[]
no_license
# -*- coding: utf-8 -*- from time import sleep print("프로젝트 파일 작성의 모범 답안입니다.") def process_data(data): print("1단계: 데이터 전처리 함수를 실행합니다. ") modified_data = "3단계: " + data + "가 수정 완료 되었습니다." sleep(3) print("2단계: 데이터 전처리가 끝났습니다.") return modified_data def main(): data = "빅쿼리에서 온 데이터" print(data...
true
fa0de0a3c76df941e74965c27af1f5f759fb4ec0
Python
Chege-Simon/learning-python
/displayInventory.py
UTF-8
337
3.46875
3
[]
no_license
stuff = {'arrow' : 12, 'rope' : 1, 'gold coin' : 42, 'torch' : 6, 'dagger' : 1} def display(inventory): print("Inventory: ") item_total = 0 for k, v in inventory.items(): item_total += v print(str(v) + " " + k) print("Total number of items is: " + str(item_total))...
true
3a2fa7f3600f285bf67841efce6d3482c9c7ba78
Python
uycuhnt2467/Leetcode
/array/795.py
UTF-8
1,861
3.296875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Feb 5 00:04:10 2021 @author: a8520 """ class Solution: def numSubarrayBoundedMax(self, arr, l, r): if not arr: return -1 i = 0 cum_r = 0 cur_total = 0 while i < len(arr) + 1: if i == len(...
true
ee549c3db7b852f70a02204da492ae4c443c2a42
Python
muzhen321/FPIR17
/pir_h2.py
UTF-8
3,573
3.640625
4
[]
no_license
#! /usr/bin/python # -*- coding: utf-8 -*- """MLE for the multinomial distribution.""" import heapq from argparse import ArgumentParser from collections import Counter def get_words(file_path): """Return a list of words from a file, converted to lower case.""" with open(file_path, encoding='ut...
true
69ae948b8dd4d582c723abc89af601002a73de7f
Python
rootcoma/imageglitch
/shader_filters/filter_scanlines.py
UTF-8
2,648
2.640625
3
[ "MIT" ]
permissive
from shader_filter import ShaderFilter VERT_SOURCE = """ #version 330 uniform float rand; uniform int frame; in vec2 vert_coord; in vec2 vert_tex_coord; out vec2 frag_tex_coord; void main() { frag_tex_coord = vert_tex_coord; gl_Position = vec4(vert_coord, 0.0, 1.0); }""" FRAG_SOURCE = """ #ver...
true
76975f3518c15d894cd45036408d4f517e42fdd2
Python
Ivan270991/homework2
/spisok.py
UTF-8
190
3.109375
3
[]
no_license
s = [16, -17, 2, 78.7, False, False, {"True": True}, 555, 12, 23, 42, "DD"] def spisok(x): return type(x) is int or type(x) is float s=sorted(list(filter(spisok,s))) print(s)
true
8020173d27c947ab24fae291f4c3c22747681fd6
Python
pedrocarvalhoaguiar/SinglyLinkedList
/list.py
UTF-8
3,630
3.515625
4
[ "MIT" ]
permissive
from node import Node # create list class class LinkedList(): def __init__(self): self.head = None self.__size = 0 def append(self, value): pointer = self.head if not pointer: self.head = Node(value) else: while pointer.next: p...
true
3e0d3b2d19fb917ff9d8df482ebeff14d8156dcf
Python
skidne/labs_MS
/lab1/problem5/collision.py
UTF-8
1,308
3.21875
3
[]
no_license
################################################################################ #---------------- ####### ---- ## ---- ####### --------------------------------# #---------------- ## ------- ##--## ------- ## ---------------| FAF-161 |--# #---------------- ##### --- ######## --- ##### ---------------| Gore-Polina |...
true
491c38a8b09bfccb81b4310a0897cb539e636a7e
Python
SabrinaAzar97/ImageProject
/python GUI/steganographyGUI.py
UTF-8
3,886
2.609375
3
[]
no_license
import Tkinter as Tkr from tkFileDialog import askopenfilename as OpenFile from Tkinter import Tk from PIL import ImageTk, Image import sys as System class OmarsButtons: def __init__(self, master): frame = Tkr.Frame(master, bg="#4682B4") frame.pack() frame.pack_propagate(0) frame.p...
true
ee424281bc237291b22620de0bb471b7ffa4a133
Python
xinzzzhou/crispr_bedict_reproduce
/train/demonstration.py
UTF-8
1,953
2.546875
3
[ "MIT" ]
permissive
''' Process more data Author: Xin Zhou Date: 17 Sep, 2021 ''' import argparse from criscas.utilities import create_directory, get_device, report_available_cuda_devices from criscas.predict_model_training import * def parse_args(): parser = argparse.ArgumentParser(description="Train crispr.") parser.add_argumen...
true
56a1e7b5f4585c77762ce707d05db3d8e7a63585
Python
DikranHachikyan/python-20201012
/ex49.py
UTF-8
449
3.78125
4
[]
no_license
def suma(a, b): return a + b if __name__ == '__main__': actions = { '+': suma } try: a = int(input('value of a(int):')) op = input('Enter +, -, *, /:') b = int(input('value of b(int):')) print(f'{a} {op} {b} = {actions[op](a,b)}') except ValueError: ...
true
4a49f192bf8ec44fc1b604ee77036d1b8dae8dcf
Python
nulijiushimeili/python_training
/training/单继承.py
UTF-8
1,036
4.15625
4
[]
no_license
class Cat: name = "cat" def __init__(self, name, color="white"): self.name = name self.color = color # 定义类方法 @classmethod def jump(cls): print("{} jump".format(cls.name)) print("The cat jume to the wall") def run(self): print("{} is runing ...".format(s...
true
7c62233ae39aa34537ea32fa6a2899ad683a35e1
Python
sampittko/tuke-beautofuel
/src/updater/app/lib/packages/vehicle_eco_balance/consumption.py
UTF-8
9,403
3.140625
3
[ "MIT" ]
permissive
import numpy as np from .utils import calc_efficiency class ConsumptionPhys: """ Physical (load-based) consumption model. It is based on "Stefan Pischinger und Ulrich Seiffert. Vieweg Handbuch Kraftfahrzeugtechnik. Springer, 2016." (page 62) Parameters ---------- consumption_type: str 'en...
true
5c061e4ba75d073a39232b0256c69ecad67e4168
Python
crsanderford/Intro-Python-II
/src/player.py
UTF-8
1,442
3.921875
4
[]
no_license
# Write a class to hold player information, e.g. what room they are in # currently. class Player: def __init__(self, name, current_room, inventory=[]): self.name = name self.current_room = current_room self.inventory = inventory def move(self, string): control_mapping = { ...
true
9f8e5ccb7aab704e96f9ba35ae7517fa23942078
Python
SaiSujithReddy/CodePython
/FindPalindrome_v1.py
UTF-8
326
3.75
4
[]
no_license
def find_palindrome(string): print("String is ", string) if string == "": return True if len(string) == 1: return True else : if string[0] == string[len(string)-1]: return find_palindrome(string[1:len(string)-1]) return False print(find_palindrome("ABCDEFDCB...
true
475241e419acb0bd9b4859dbb6f513657cbaa7a1
Python
tranphibaochau/LeetCodeProgramming
/Medium/house_robber.py
UTF-8
600
2.96875
3
[]
no_license
from collections import namedtuple Task = namedtuple('Task', ['summary', 'owner', 'done', 'id']) Task.__new__.__defaults__= (None, None, False, None) def test_func(): t1 = Task() t2 = Task(None, None, False, None) assert t1 == t2 def test_member_access(): t = Task('buy milk', 'brian') assert t.sum...
true
d55e62c5637f2ff942a2ef474c72803fde05dc67
Python
ZodiacSyndicate/leet-code-solutions
/easy/20.有效的括号/20.有效的括号.py
UTF-8
1,263
3.40625
3
[]
no_license
# # @lc app=leetcode.cn id=20 lang=python3 # # [20] 有效的括号 # # https://leetcode-cn.com/problems/valid-parentheses/description/ # # algorithms # Easy (36.24%) # Total Accepted: 44.5K # Total Submissions: 122.7K # Testcase Example: '"()"' # # 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 # # 有效字符串需满足: # # # 左括号必须用相同...
true
f85154bbe9b465002bcfbf340f0788fae35e77a1
Python
MeLight/tiny-server
/http_server.py
UTF-8
2,667
2.6875
3
[]
no_license
import socket import time import urllib import re import os LISTEN_SOCKET = 20959 WWW_DIR = 'www' def headers2json(str): req_decoded = urllib.unquote(request).decode('utf8') arr = req_decoded.split('\r\n') request_line = arr.pop(0) #print(arr) return (request_line, arr,) def getTemplateString(filename): with o...
true
48b73900d1c0aa13a059ab1a01175a3a164dae94
Python
TyroneWilkinson/Python_Practice
/dayOfProgrammer.py
UTF-8
1,451
4.625
5
[]
no_license
def dayOfProgrammer(year): """ Given a year, determines the date of the 256th day of the year, the "Day of the programmer," according to the Russian calendar. Note: From 1700 to 1917 Russia's calendar was the Julian calendar. -The leap year was a year divisible by four. After 1918 Russi...
true
e82f21d28d82105a9d75249c1b05f3abba80f459
Python
Zhuo-Ren/event_entity_coref_ecb_plus
/src/features/create_elmo_embeddings.py
UTF-8
1,037
3
3
[]
no_license
import logging import numpy as np from allennlp.commands.elmo import ElmoEmbedder logger = logging.getLogger(__name__) class ElmoEmbedding(object): ''' A wrapper class for the ElmoEmbedder of Allen NLP ''' def __init__(self, options_file, weight_file): logger.info('Loading Elmo ...
true
a4bdbbc2fa8288cf0115481566c00d3572b11764
Python
aaron-parsons/nexusformat
/src/nexusformat/nexus/plot.py
UTF-8
6,657
2.671875
3
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/env python # -*- coding: utf-8 -*- #----------------------------------------------------------------------------- # Copyright (c) 2013, NeXpy Development Team. # # Author: Paul Kienzle, Ray Osborn # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING, dist...
true
adb620989b4cf9c8b0e364c74d370483ac9150ba
Python
radhac88/SMNS
/shiva/python exercises/exercise2.py
UTF-8
290
4.03125
4
[]
no_license
print("enter two numbers ") a = int(input("enter value of a:")) b = int(input("enter value of b:")) print("if both values are equal it will returns sum else it will return's double their sum ") def sum_double(a,b): if(a==b): print(2*a + 2*b); elif(a!=b): print(a+b); sum_double(a,b)
true
3a19c3ba6208408026c99d64965dcb7983625946
Python
nainy05/NLP-Basics
/tfidf_model.py
UTF-8
3,682
3.140625
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 18 17:24:07 2020 @author: naijain """ import heapq import re import nltk import numpy as np paragraph = """Thank you all so very much. Thank you to the Academy. Thank you to all of you in this room. I have to congratulate ...
true
2fd34a2846d996fec927700dc5964f02fa688a67
Python
mirca/gammapy
/docs/tutorials/crab_mwl_sed/crab_mwl_sed.py
UTF-8
1,120
2.921875
3
[ "BSD-3-Clause" ]
permissive
"""Plot Crab pulsar and nebula spectral energy distribution (SED).""" import numpy as np import matplotlib.pyplot as plt import astropy.units as u from gammapy.datasets import load_crab_flux_points from gammapy.spectrum import CrabSpectrum # Plot flux points for component in ['pulsar', 'nebula']: table = load_crab...
true
7666114803ef74ab400b7ee27bb9a0b92a88d971
Python
andrelima19/Projetos_Python
/Developer/Python_Definitivo/Exercícios/Listas/84b.py
UTF-8
1,171
4.28125
4
[]
no_license
#Exercício Python 084: Faça um programa que leia nome e peso de várias pessoas, # guardando tudo em uma lista. No final, mostre: # A) Quantas pessoas foram cadastradas. # B) Uma listagem com as pessoas mais pesadas. # C) Uma listagem com as pessoas mais leves. grupo_pessoas = [] pessoas = [] mais_pesados = [] mais_...
true
c8d43294fce64931a25e3882cc9ef97f8e0b3bea
Python
daniel-reich/ubiquitous-fiesta
/2NPjN7DDvyi6f5CHF_24.py
UTF-8
131
3.515625
4
[]
no_license
def age_difference(f_age, s_age): i=0 while 2*(s_age+i)!=(f_age+i) and 2*(s_age-i)!=(f_age-i): i+=1 return i
true
0ca9b94d0b98e50eb4a6cc297a1cc39265c8ce8c
Python
cgrambow/parsePrIMe
/classes.py
UTF-8
8,706
2.953125
3
[ "MIT" ]
permissive
#!/usr/bin/env python # -*- coding:utf-8 -*- import cirpy from rmgpy.molecule import Molecule from rmgpy.species import Species from rmgpy.reaction import Reaction class ConversionError(Exception): """ An exception class for errors during name to structure conversion. """ pass class StoichiometryE...
true
cd3372acfb3993c9660ea967347706951257ca00
Python
0tushar0/tictactoe
/model.py
UTF-8
2,148
4.125
4
[]
no_license
# model stores board position and checks win condition import numpy as np class Model(): def __init__(self): self.__board = np.array([['1','2','3'],['4','5','6'],['7','8','9']]) def update(self, row, col, pos): if self.__board[row][col] != 'x' and \ self.__board[row][col] != '...
true
e52efe3d7cb07e4bc60c3bd5bdeeb8297fb70c7d
Python
JanaSabuj/Coursera-Getting-started-with-python-Dr-Chuck-Michigan
/Michigan-Python/ex5.py
UTF-8
324
3.296875
3
[]
no_license
fname = input('Enter the file name') fhandle = open(fname) cnt = 0 for line in fhandle: if not line.startswith('From '): continue line = line.rstrip() words = line.split() email = words[1] print(email) cnt = cnt + 1 print('There were {} lines in the file with From as the first word'.format(cnt...
true
77f5936f0c190194314014df0b2b3b0319ed6176
Python
INM-6/Python-Module-of-the-Week
/session28_ModernPython/GeneratorExpression.py
UTF-8
135
3.09375
3
[ "MIT" ]
permissive
s = sum([i**2 for i in range(3)]) print(s) s = sum(i**2 for i in range(3)) print(s) d = dict((i, i % 7) for i in range(12)) print(d)
true
5b8d28a2f163be99bd378dae0d75b030bb9bf48a
Python
byee4/rbp-maps
/maps/density/matrix.py
UTF-8
22,973
2.84375
3
[]
no_license
#!/bin/env python """ Created on Jun 18, 2016 This module contains functions for creating a dataframe from a list of event features. Each function will require: 1) an annotation file to generate an event-specific Feature, 2) a ReadDensity object containing RPM-normalized read densities for a particular RBP, and call ...
true
8df2108b0c818eca52affb000302c745812ae9d4
Python
soundaraj/practicepython.org
/file overlap.py
UTF-8
338
3.21875
3
[]
no_license
file1 = open("happynumbers.txt",'r') file2 = open("primenumbers.txt",'r') a = [] b = [] c = [] f1 = file1.readline() f2 = file2.readline() while f1: a.append(int(f1)) f1 = file1.readline() while f2: b.append(int(f2)) f2 = file2.readline() for i in a: if i in b: c.append(i) pr...
true
9f118af1018772c62cd720e2742edb7890a3a83d
Python
vincenttuan/Python20210713
/day08/LambdaDemo1.py
UTF-8
792
3.859375
4
[]
no_license
def check_score(score): if score >= 60: return "Pass" else: return "Fail" if __name__ == '__main__': score = 80 result = check_score(score) # result 就僅僅只是一個結果 print(score, result) #----------------------------------------------- score = 80 result = "Pass" if score >=...
true
652b069606f3b75484871594dcb4c9fe860b000a
Python
thiagomanel/intrusiveness-meter
/IntrusivenessMeter/data_processor/to_pure_data.py
UTF-8
505
2.578125
3
[]
no_license
# # Federal University of Campina Grande # Distributed Systems Laboratory # # Author: Armstrong Mardilson da Silva Goes # Contact: armstrongmsg@lsd.ufcg.edu.br # # # This program removes the header and tail of the result files # generated by the scripts of data_collector, so the data can be # used as input for progra...
true
6280ceb9b21ca0af76292ed495156f73e3ab2511
Python
yuchun921/CodeWars_python
/8kyu/Lario_and_muigi_pipe_problem.py
UTF-8
120
2.65625
3
[]
no_license
def pipe_fix(nums): arr = [] for i in range(nums[0], nums[len(nums)-1]+1): arr.append(i) return arr
true
0c1fe610910ded5665a0521669a539e20260e75e
Python
Clebom/exercicios-livro-introd-prog-python-3ed
/capitulo-04/ex09.py
UTF-8
994
4.40625
4
[ "MIT" ]
permissive
# Escreva um programa para aprovar um empréstimo bancário para compra de uma casa # O programa deve perguntar o valor da casa a comprar, o salário e a quantidade de anos a pagar # O valor da prestação mensal não pode ser superior a 30% do salário # Calcule o valor da prestação como sendo o valor da casa a comprar divid...
true
a99617379f7bcad7543f3e3ac66dbad3327df150
Python
xenten9/game-x
/main/manual tests/tester.py
UTF-8
4,277
2.703125
3
[ "Unlicense" ]
permissive
"""Game-X Level testing tool.""" printer = ["\033[36m# Game-X tester.py"] import sys from os import getcwd, path # Add root of executable if getattr(sys, "frozen", False): root = path.dirname(sys.executable) if root not in sys.path: printer.append(f"adding path: {root}") sys.path.insert(0, roo...
true
8273400ff6e660ce9c7be34da48e8b57829acb76
Python
ebilionis/principal-agent-systems-engineering
/sepdesign/_individual_rationality.py
UTF-8
7,115
2.78125
3
[ "MIT" ]
permissive
""" Everything related to the individual rationality constraints. """ __all__ = ['IndividualRationality'] import theano import theano.tensor as T import scipy.optimize as opt import numpy as np from sepdesign._types import AgentType from sepdesign._transfer_functions import TransferFunction class IndividualRatio...
true
cdbfb92e4e656fa30431141d77d6a9e81bdd95bf
Python
QianErGe/hello
/time_zone.py
UTF-8
717
2.796875
3
[]
no_license
#!/usr/bin/python # -*- coding=utf-8 -*- from datetime import timedelta from pytz import timezone import pytz import time import datetime import sys # 根据时间戳与时区值 返回此时间戳在此时区下的时间 def get_time( ts, time_zone ): print("current ts:", ts) str_tz = 'Etc/GMT' + time_zone dd = dt.fromtimestamp(ts, pytz.timezone('Etc/...
true
b2ddaae303d072eb9cd8c0ee8a6302117092a42e
Python
terratenney/BigDataAlgorithm
/hw5/HW5code/ItemBased.py
UTF-8
8,259
2.953125
3
[]
no_license
from __future__ import print_function import sys from pyspark import SparkContext from itertools import combinations import numpy as np import time import math def get_ratings_tuple(entry): """ Parse a line in the ratings dataset Args: entry (str): a line in the ratings dataset in the form of UserID::M...
true
3167ca0dac521f5ecdd0dc17836422ba4cf40307
Python
NerdvanaNC/D-DGame
/Engine.py
UTF-8
516
2.828125
3
[]
no_license
import Map class Engine(object): def start_game(self, opening_scene): game_map = Map.Map() next_scene = game_map.return_scene_obj(opening_scene) current_scene = game_map.return_scene_obj(opening_scene) next_scene = next_scene.enter() hero = current_scene.return_hero_obj() while True: i...
true
4940d9fd15c47fb5b767e7f085167807722f1862
Python
gnat79/char2
/char2.py
UTF-8
5,728
3.21875
3
[]
no_license
# This file is part of char2. # char2 is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # char2 is distributed in the hope that it wil...
true
e3a25e330a5b7e487e6230b846b687f88a7aed59
Python
engeir/BM_rocket_sim
/plotter.py
UTF-8
13,558
2.75
3
[]
no_license
"""Script that makes plot of the historical data obtained through all runs. """ import os import glob import ast import matplotlib.pyplot as plt import numpy as np import config as cf from main import FindFiles class ProbeDesign(FindFiles): """Find the design of the Hedin detector design. Arguments: ...
true
3273701707497d954cf2d68ffba69ae0a5967ed4
Python
Moguf/cluster_pscripts
/calc_dist_dcd.py
UTF-8
2,444
2.765625
3
[]
no_license
#!/usr/bin/env python import argparse import json import sys import numpy as np from dcdfile import DcdFile class CalcDist: def __init__(self): self.inputfile='' self.atom1=0 self.atom2=0 self.natoms=0 self.stepsize=1 self.deltalist=[] self.result={} ...
true
80ca24693e8b20fd85fb81a16cd1c651b0d4c29c
Python
yamadayoshi/deep_learning
/games/games_regressao.py
UTF-8
1,941
2.84375
3
[]
no_license
import pandas as pd import numpy as np from keras.layers import Dense, Dropout, Activation, Input from keras.models import Model from sklearn.preprocessing import LabelEncoder, OneHotEncoder dataset = pd.read_csv('games.csv') dataset = dataset.drop('Other_Sales', axis= 1) dataset = dataset.drop('Global_Sales', axis= ...
true
61a226499148e56f288f7f9901df2aa1b68df966
Python
YellowruiAccount/Arctic_codes
/equation_test_area.py
UTF-8
5,327
2.8125
3
[]
no_license
#!/usr/bin/env python """ """ import sys import matplotlib.pyplot as plt import numpy as np # Clear-sky summer values from net flux figure dflux_darea = -0.039128 # Use the value for ice area change here. To find with # respect to water area, take the negative of this ...
true
1d0871930e83dcfcf7b7c8fad64d808594e125b2
Python
Phantomb/malmo_rl
/utilities/replay_memory.py
UTF-8
11,701
2.90625
3
[ "MIT" ]
permissive
import argparse import copy from collections import namedtuple from typing import List import numpy as np from utilities.segment_tree import SumSegmentTree # Definition of observation: # state: s_t # action: a_t # reward: r_(t+1) (reward received due to being at state s_t and performing action a_t which...
true
dd6fbf8e0e16b1477261f91dee92e4f8be6e4ab6
Python
jimfred/python
/set-file-time.py
UTF-8
490
3.46875
3
[]
no_license
''' Example to change a file's time. ''' import os import datetime def set_mod_time(file_str: str, iso_date_time_str: str): # date = datetime.datetime.now() date = datetime.datetime.strptime(iso_date_time_str, "%Y-%m-%d %H:%M:%S") timestamp = date.timestamp() # seconds passed since epoch in local time. ...
true
2c392ffedc224bddbbabc5738169bedbc4743a9e
Python
ycu-engine/kaggle
/typings/sklearn/ensemble/_stacking.pyi
UTF-8
17,468
2.875
3
[]
no_license
""" This type stub file was generated by pyright. """ from abc import ABCMeta, abstractmethod from ..base import ClassifierMixin, RegressorMixin, TransformerMixin from ._base import _BaseHeterogeneousEnsemble from ..utils.metaestimators import if_delegate_has_method from ..utils.validation import _deprecate_positional...
true
27fccff6186e761d375c0a588b6b4d4ac3acd4f3
Python
sarahghanei/Euler-Project-Programming
/Problem3.py
UTF-8
606
3.734375
4
[]
no_license
# # Euler project Problem 3 # def is_prime(n): # res = True # for i in range(2, int(n ** 0.5) + 1): # if n % i == 0: # res = False # return res # # # def max_prime_factor(n): # max_prime = 0 # while n % 2 == 0: # max_prime = 2 # n /= 2 # for i in range(3, int(...
true
ffdf7b6a0f976c9f24acebf263bab25272c4ce71
Python
suppoor/pml-git
/python/plotting_test.py
UTF-8
527
3.5
4
[]
no_license
#!/usr/bin/env python import matplotlib.pyplot as plt import numpy as np # Fiddling around with matplotlib plt.plot([0,1,2,3], [10,20,30,40]) plt.plot([0,1,2,3], [10,20,30,40], 'ro') plt.ylabel('Some variables') plt.xlabel('Some constants') plt.axis('equal') plt.axis('tight') plt.show() # Do some more interesting l...
true
76804905395dff835bd61908a037401fdc2da1af
Python
dastier/top3distance
/top3distances/dbutils.py
UTF-8
3,008
2.5625
3
[]
no_license
import logging import os import time import psycopg2 logger = logging.getLogger(__name__) LIMIT_RETRIES = 5 class Database(): def __init__(self): self.host = os.getenv('POSTGRES_HOST') self.port = os.getenv('POSTGRES_PORT') self.user = os.getenv('POSTGRES_USER') self.password = ...
true
9d055c46bd937129b16a3d67db50d29f0f0e82c8
Python
PaulCotney/tfpipe
/tfpipe/pipeline/engine.py
UTF-8
6,311
2.5625
3
[]
no_license
"""Defines functionality for pipeline. """ from re import findall from os import system from sys import exit from datetime import datetime from tfpipe.utils import logger, DuplicateJobNames class WorkFlow(object): """WorkFlow creates and executes job submission statements. """ def __init__(self, job_list...
true
620cbdff444f45dff7a6c1ba60c256ea60266d9b
Python
xshirl/ctci
/chapter2/2.3.deleteMiddleNode.py
UTF-8
252
2.796875
3
[]
no_license
import Node class Solution: def deleteMiddle(self, node: Node) -> bool: if node is None or node.next is None: return False next = node.next node.val = next.val node.next = next.next return True
true
af683a8fa5677e6b1c65c4c8757630cc04d4496f
Python
bmsr56/cs4096
/py_code/pump.py
UTF-8
585
3.171875
3
[]
no_license
import RPi.GPIO as gpio import time # gpio general settings gpio.setmode(gpio.BCM) gpio.setwarnings(False) def assignPumps(*args): """Assign the pumps to gpio pins Args: args (ints): 6 BCM pin numbers in order of how you want them assigned to the pumps. Returns: pump (dict)...
true
8bf9f729711b9f646023fe57f6ef15cc6a5f4297
Python
shwetachauras/Final-Project-on-OECD-Road-Accidents
/Functions_RD.py
UTF-8
9,659
4.1875
4
[]
no_license
def csvToList(csv_file): """ This functions reads data from a csv file Accepts a csv file as paramter Returns a list of lists, with data of only 0, 5 and 6 columns (i.e. country name, year and number of road deaths) of csv file. Header of the file is ignored. """ with open (csv_file) as...
true
aed762af1bfbc32e9fd321733417361ada0786fc
Python
GoldxKey/putianHospitalMap
/spider.py
UTF-8
1,053
2.6875
3
[]
no_license
# -*- coding: UTF-8 -*- import urllib2 def downTheHTML(url): req_header = { 'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', 'Accept':'text/html;q=0.9,*/*;q=0.8', 'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Connecti...
true
6dd59c5439d851ad8bae280f662fff150e4ae36c
Python
derektolliver/spectral-jellyfish
/Competitive Programming/9:23/invalid.py
UTF-8
422
2.875
3
[]
no_license
def invalid(): num_tests = int(input()) for i in range(num_tests): invalid_num = 0 num_friends = int(input()) for f in range(num_friends): info = [int(elem) for elem in input().split()] if info[0] < 6 or info[0] > 21 or info[1] < 0 or info[1] > 1024: ...
true
5d0992b4ae8e014a28cd04cc1d5788e35440ffc5
Python
nickmcblain/HackKingsWorkshop-React
/Resources/bankingLambda.py
UTF-8
7,970
3.03125
3
[]
no_license
""" This sample demonstrates a simple skill built with the Amazon Alexa Skills Kit. The Intent Schema, Custom Slots, and Sample Utterances for this skill, as well as testing instructions are located at http://amzn.to/1LzFrj6 For additional samples, visit the Alexa Skills Kit Getting Started guide at http://amzn.to/1LG...
true
3c9717ebe887bebd5db3477cd7b56faeff52bfa5
Python
yogalin910731/studytest
/twokindstrees/treesonpoint.py
UTF-8
2,059
3.328125
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/7/23 10:35 # @Author : fangbo class treenode: def __init__(self,val): self.val = val self.lchild = None self.rchild = None def iseuqual(root1,root2): # 如果B树为空,那么可以算B是A的子结构 # 如果A树空,而B树不空,那么B不是A的子结构 # ...
true
f17a571f68690728ad52f21037dadbb493a1ef5f
Python
rickhanlonii/slacksocket
/slacksocket/client.py
UTF-8
12,724
2.546875
3
[ "MIT" ]
permissive
import json import logging import websocket import requests import time from threading import Thread, Lock import slacksocket.errors as errors from .config import slackurl, event_types from .models import SlackEvent, SlackMsg log = logging.getLogger('slacksocket') class SlackClient(requests.Session): """ A ...
true
c0bff73bba3aaf951dc67c86654700fc0de3b97c
Python
MiyuruThathsara/Dynamic-Channel-Pruning-
/Feature Map Prominance/Scripts/Custom Net/Custom_Net_Train.py
UTF-8
1,703
2.5625
3
[]
no_license
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision import torchvision.transforms as transforms from Custom_Net import Custom_Net as Net device = torch.device( 'cuda:0' if torch.cuda.is_available() else 'cpu' ) print( "Device : ", device ) transform = t...
true
713148d60d573ba99547839251ad1b7debc6ebe3
Python
ShabbirHasan1/MarketMatrix
/strategys/Rsi.py
UTF-8
970
2.515625
3
[]
no_license
import pandas as pd import random from datetime import datetime, timedelta import ta from market import strategy sma = [] class Rsi(strategy.Strategy): def initialize(self): self.sym = "ETH-USD" self.tickers = [self.sym] self.entry_rsi = 25 self.exit_rsi = 80 self.rsi_wi...
true
4d0076d559137382f5ffda40164536fda87baca7
Python
yupm/Computer-Vision-with-3DoF-estimation
/computervision.py
UTF-8
6,866
2.625
3
[]
no_license
import numpy as np import cv2 as cv from matplotlib import pyplot as plt import imagecapture import cameracalibration from collections import deque import re # for smoothing values rowq = deque(maxlen=10) pitchq = deque(maxlen=10) yawq = deque(maxlen=10) #convert rotation vector to roll pitch yaw def rot_params_rv(r...
true
d582b9d5ed2b849e8b6e2fee204d3d746f1a2118
Python
hrit1995/Sorting-Analysis-Queue-BST
/test_tree_sort.py
UTF-8
922
3.140625
3
[]
no_license
import unittest from tree_sort import sortTree from timeit import default_timer as timer import random class TreeSortTest(unittest.TestCase): def setUp(self): self.tree = [random.randint(1, 4000) for _ in range(1, 979)] def test_tree_already_sorted(self): copy_tree = self.tree ...
true
37d4f20934b5b7d32319defa8d3b7058f72236b8
Python
undisbeliever/first-person-tetromones
/tables/level-colors.py
UTF-8
1,657
3.015625
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # vim: set fenc=utf-8 ai ts=4 sw=4 sts=4 et: from colorsys import hsv_to_rgb SAT_VAL_PER_TILE_COLOR = ( (1.00, 1.00), (0.71, 1.00), (1.00, 0.65), (1.00, 0.78), (1.00, 0.89) ) HUES_PER_LEVEL = ( ( 48, 88, 208, 8, 328), # 1 (220, 33, 153, ...
true